Search is not available for this dataset
repo
stringlengths 2
152
⌀ | file
stringlengths 15
239
| code
stringlengths 0
58.4M
| file_length
int64 0
58.4M
| avg_line_length
float64 0
1.81M
| max_line_length
int64 0
12.7M
| extension_type
stringclasses 364
values |
---|---|---|---|---|---|---|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpl_toolkits/axes_grid/axes_size.py
|
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from mpl_toolkits.axes_grid1.axes_size import *
| 158 | 30.8 | 66 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpl_toolkits/axes_grid/angle_helper.py
|
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from mpl_toolkits.axisartist.angle_helper import *
| 161 | 31.4 | 66 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpl_toolkits/axes_grid/parasite_axes.py
|
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from mpl_toolkits.axes_grid1.parasite_axes import (
host_axes_class_factory, parasite_axes_class_factory,
parasite_axes_auxtrans_class_factory, subplot_class_factory)
from .axislines import Axes
ParasiteAxes = parasite_axes_class_factory(Axes)
ParasiteAxesAuxTrans = \
parasite_axes_auxtrans_class_factory(axes_class=ParasiteAxes)
HostAxes = host_axes_class_factory(axes_class=Axes)
SubplotHost = subplot_class_factory(HostAxes)
| 557 | 28.368421 | 66 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpl_toolkits/axes_grid/axislines.py
|
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from mpl_toolkits.axisartist.axislines import *
| 158 | 30.8 | 66 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpl_toolkits/axes_grid/axis_artist.py
|
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from mpl_toolkits.axisartist.axis_artist import *
| 160 | 31.2 | 66 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpl_toolkits/axes_grid/colorbar.py
|
from mpl_toolkits.axes_grid1.colorbar import (
make_axes_kw_doc, colormap_kw_doc, colorbar_doc,
CbarAxesLocator, ColorbarBase, Colorbar,
make_axes, colorbar
)
| 171 | 27.666667 | 52 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpl_toolkits/axes_grid/inset_locator.py
|
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from mpl_toolkits.axes_grid1.inset_locator import InsetPosition, \
AnchoredSizeLocator, \
AnchoredZoomLocator, BboxPatch, BboxConnector, BboxConnectorPatch, \
inset_axes, zoomed_inset_axes, mark_inset
| 326 | 39.875 | 73 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpl_toolkits/axes_grid/clip_path.py
|
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from mpl_toolkits.axisartist.clip_path import *
| 158 | 30.8 | 66 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpl_toolkits/axes_grid/floating_axes.py
|
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from mpl_toolkits.axisartist.floating_axes import *
| 162 | 31.6 | 66 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpl_toolkits/axes_grid/__init__.py
|
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from . import axes_size as Size
from .axes_divider import Divider, SubplotDivider, LocatableAxes, \
make_axes_locatable
from .axes_grid import Grid, ImageGrid, AxesGrid
#from axes_divider import make_axes_locatable
from matplotlib.cbook import warn_deprecated
warn_deprecated(since='2.1',
name='mpl_toolkits.axes_grid',
alternative='mpl_toolkits.axes_grid1 and'
' mpl_toolkits.axisartist provies the same'
' functionality',
obj_type='module')
| 662 | 40.4375 | 71 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpl_toolkits/axes_grid/axes_divider.py
|
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from mpl_toolkits.axes_grid1.axes_divider import Divider, AxesLocator, SubplotDivider, \
AxesDivider, locatable_axes_factory, make_axes_locatable
from mpl_toolkits.axes_grid.axislines import Axes
LocatableAxes = locatable_axes_factory(Axes)
| 357 | 38.777778 | 88 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpl_toolkits/axes_grid/axes_rgb.py
|
from __future__ import (absolute_import, division, print_function,
unicode_literals)
#from mpl_toolkits.axes_grid1.axes_rgb import *
from mpl_toolkits.axes_grid1.axes_rgb import make_rgb_axes, imshow_rgb, RGBAxesBase
#import mpl_toolkits.axes_grid1.axes_rgb as axes_rgb_orig
from .axislines import Axes
class RGBAxes(RGBAxesBase):
_defaultAxesClass = Axes
| 387 | 31.333333 | 83 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpl_toolkits/axes_grid/grid_finder.py
|
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from mpl_toolkits.axisartist.grid_finder import *
| 160 | 31.2 | 66 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpl_toolkits/axes_grid/axisline_style.py
|
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from mpl_toolkits.axisartist.axisline_style import *
| 163 | 31.8 | 66 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpl_toolkits/axisartist/axes_grid.py
|
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import mpl_toolkits.axes_grid1.axes_grid as axes_grid_orig
from .axes_divider import LocatableAxes
class CbarAxes(axes_grid_orig.CbarAxesBase, LocatableAxes):
def __init__(self, *kl, **kwargs):
orientation=kwargs.pop("orientation", None)
if orientation is None:
raise ValueError("orientation must be specified")
self.orientation = orientation
self._default_label_on = False
self.locator = None
super(LocatableAxes, self).__init__(*kl, **kwargs)
def cla(self):
super(LocatableAxes, self).cla()
self._config_axes()
class Grid(axes_grid_orig.Grid):
_defaultLocatableAxesClass = LocatableAxes
class ImageGrid(axes_grid_orig.ImageGrid):
_defaultLocatableAxesClass = LocatableAxes
_defaultCbarAxesClass = CbarAxes
AxesGrid = ImageGrid
| 942 | 29.419355 | 66 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpl_toolkits/axisartist/grid_helper_curvelinear.py
|
"""
An experimental support for curvilinear grid.
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import six
from six.moves import zip
from itertools import chain
from .grid_finder import GridFinder
from .axislines import AxisArtistHelper, GridHelperBase
from .axis_artist import AxisArtist
from matplotlib.transforms import Affine2D, IdentityTransform
import numpy as np
from matplotlib.path import Path
class FixedAxisArtistHelper(AxisArtistHelper.Fixed):
"""
Helper class for a fixed axis.
"""
def __init__(self, grid_helper, side, nth_coord_ticks=None):
"""
nth_coord = along which coordinate value varies.
nth_coord = 0 -> x axis, nth_coord = 1 -> y axis
"""
super(FixedAxisArtistHelper, self).__init__(loc=side)
self.grid_helper = grid_helper
if nth_coord_ticks is None:
nth_coord_ticks = self.nth_coord
self.nth_coord_ticks = nth_coord_ticks
self.side = side
self._limits_inverted = False
def update_lim(self, axes):
self.grid_helper.update_lim(axes)
if self.nth_coord == 0:
xy1, xy2 = axes.get_ylim()
else:
xy1, xy2 = axes.get_xlim()
if xy1 > xy2:
self._limits_inverted = True
else:
self._limits_inverted = False
def change_tick_coord(self, coord_number=None):
if coord_number is None:
self.nth_coord_ticks = 1 - self.nth_coord_ticks
elif coord_number in [0, 1]:
self.nth_coord_ticks = coord_number
else:
raise Exception("wrong coord number")
def get_tick_transform(self, axes):
return axes.transData
def get_tick_iterators(self, axes):
"""tick_loc, tick_angle, tick_label"""
g = self.grid_helper
if self._limits_inverted:
side = {"left":"right","right":"left",
"top":"bottom", "bottom":"top"}[self.side]
else:
side = self.side
ti1 = g.get_tick_iterator(self.nth_coord_ticks, side)
ti2 = g.get_tick_iterator(1-self.nth_coord_ticks, side, minor=True)
#ti2 = g.get_tick_iterator(1-self.nth_coord_ticks, self.side, minor=True)
return chain(ti1, ti2), iter([])
class FloatingAxisArtistHelper(AxisArtistHelper.Floating):
def __init__(self, grid_helper, nth_coord, value, axis_direction=None):
"""
nth_coord = along which coordinate value varies.
nth_coord = 0 -> x axis, nth_coord = 1 -> y axis
"""
super(FloatingAxisArtistHelper, self).__init__(nth_coord,
value,
)
self.value = value
self.grid_helper = grid_helper
self._extremes = None, None
self._get_line_path = None # a method that returns a Path.
self._line_num_points = 100 # number of points to create a line
def set_extremes(self, e1, e2):
self._extremes = e1, e2
def update_lim(self, axes):
self.grid_helper.update_lim(axes)
x1, x2 = axes.get_xlim()
y1, y2 = axes.get_ylim()
grid_finder = self.grid_helper.grid_finder
extremes = grid_finder.extreme_finder(grid_finder.inv_transform_xy,
x1, y1, x2, y2)
extremes = list(extremes)
e1, e2 = self._extremes # ranges of other coordinates
if self.nth_coord == 0:
if e1 is not None:
extremes[2] = max(e1, extremes[2])
if e2 is not None:
extremes[3] = min(e2, extremes[3])
elif self.nth_coord == 1:
if e1 is not None:
extremes[0] = max(e1, extremes[0])
if e2 is not None:
extremes[1] = min(e2, extremes[1])
grid_info = dict()
lon_min, lon_max, lat_min, lat_max = extremes
lon_levs, lon_n, lon_factor = \
grid_finder.grid_locator1(lon_min, lon_max)
lat_levs, lat_n, lat_factor = \
grid_finder.grid_locator2(lat_min, lat_max)
grid_info["extremes"] = extremes
grid_info["lon_info"] = lon_levs, lon_n, lon_factor
grid_info["lat_info"] = lat_levs, lat_n, lat_factor
grid_info["lon_labels"] = grid_finder.tick_formatter1("bottom",
lon_factor,
lon_levs)
grid_info["lat_labels"] = grid_finder.tick_formatter2("bottom",
lat_factor,
lat_levs)
grid_finder = self.grid_helper.grid_finder
#e1, e2 = self._extremes # ranges of other coordinates
if self.nth_coord == 0:
xx0 = np.linspace(self.value, self.value, self._line_num_points)
yy0 = np.linspace(extremes[2], extremes[3], self._line_num_points)
xx, yy = grid_finder.transform_xy(xx0, yy0)
elif self.nth_coord == 1:
xx0 = np.linspace(extremes[0], extremes[1], self._line_num_points)
yy0 = np.linspace(self.value, self.value, self._line_num_points)
xx, yy = grid_finder.transform_xy(xx0, yy0)
grid_info["line_xy"] = xx, yy
self.grid_info = grid_info
def get_axislabel_transform(self, axes):
return Affine2D() #axes.transData
def get_axislabel_pos_angle(self, axes):
extremes = self.grid_info["extremes"]
if self.nth_coord == 0:
xx0 = self.value
yy0 = (extremes[2]+extremes[3])/2.
dxx, dyy = 0., abs(extremes[2]-extremes[3])/1000.
elif self.nth_coord == 1:
xx0 = (extremes[0]+extremes[1])/2.
yy0 = self.value
dxx, dyy = abs(extremes[0]-extremes[1])/1000., 0.
grid_finder = self.grid_helper.grid_finder
xx1, yy1 = grid_finder.transform_xy([xx0], [yy0])
trans_passingthrough_point = axes.transData + axes.transAxes.inverted()
p = trans_passingthrough_point.transform_point([xx1[0], yy1[0]])
if (0. <= p[0] <= 1.) and (0. <= p[1] <= 1.):
xx1c, yy1c = axes.transData.transform_point([xx1[0], yy1[0]])
xx2, yy2 = grid_finder.transform_xy([xx0+dxx], [yy0+dyy])
xx2c, yy2c = axes.transData.transform_point([xx2[0], yy2[0]])
return (xx1c, yy1c), np.arctan2(yy2c-yy1c, xx2c-xx1c)/np.pi*180.
else:
return None, None
def get_tick_transform(self, axes):
return IdentityTransform() #axes.transData
def get_tick_iterators(self, axes):
"""tick_loc, tick_angle, tick_label, (optionally) tick_label"""
grid_finder = self.grid_helper.grid_finder
lat_levs, lat_n, lat_factor = self.grid_info["lat_info"]
lat_levs = np.asarray(lat_levs)
if lat_factor is not None:
yy0 = lat_levs / lat_factor
dy = 0.01 / lat_factor
else:
yy0 = lat_levs
dy = 0.01
lon_levs, lon_n, lon_factor = self.grid_info["lon_info"]
lon_levs = np.asarray(lon_levs)
if lon_factor is not None:
xx0 = lon_levs / lon_factor
dx = 0.01 / lon_factor
else:
xx0 = lon_levs
dx = 0.01
if None in self._extremes:
e0, e1 = self._extremes
else:
e0, e1 = sorted(self._extremes)
if e0 is None:
e0 = -np.inf
if e1 is None:
e1 = np.inf
if self.nth_coord == 0:
mask = (e0 <= yy0) & (yy0 <= e1)
#xx0, yy0 = xx0[mask], yy0[mask]
yy0 = yy0[mask]
elif self.nth_coord == 1:
mask = (e0 <= xx0) & (xx0 <= e1)
#xx0, yy0 = xx0[mask], yy0[mask]
xx0 = xx0[mask]
def transform_xy(x, y):
x1, y1 = grid_finder.transform_xy(x, y)
x2y2 = axes.transData.transform(np.array([x1, y1]).transpose())
x2, y2 = x2y2.transpose()
return x2, y2
# find angles
if self.nth_coord == 0:
xx0 = np.empty_like(yy0)
xx0.fill(self.value)
xx1, yy1 = transform_xy(xx0, yy0)
xx00 = xx0.copy()
xx00[xx0+dx>e1] -= dx
xx1a, yy1a = transform_xy(xx00, yy0)
xx1b, yy1b = transform_xy(xx00+dx, yy0)
xx2a, yy2a = transform_xy(xx0, yy0)
xx2b, yy2b = transform_xy(xx0, yy0+dy)
labels = self.grid_info["lat_labels"]
labels = [l for l, m in zip(labels, mask) if m]
elif self.nth_coord == 1:
yy0 = np.empty_like(xx0)
yy0.fill(self.value)
xx1, yy1 = transform_xy(xx0, yy0)
xx1a, yy1a = transform_xy(xx0, yy0)
xx1b, yy1b = transform_xy(xx0, yy0+dy)
xx00 = xx0.copy()
xx00[xx0+dx>e1] -= dx
xx2a, yy2a = transform_xy(xx00, yy0)
xx2b, yy2b = transform_xy(xx00+dx, yy0)
labels = self.grid_info["lon_labels"]
labels = [l for l, m in zip(labels, mask) if m]
def f1():
dd = np.arctan2(yy1b-yy1a, xx1b-xx1a) # angle normal
dd2 = np.arctan2(yy2b-yy2a, xx2b-xx2a) # angle tangent
mm = ((yy1b-yy1a)==0.) & ((xx1b-xx1a)==0.) # mask where dd1 is not defined
dd[mm] = dd2[mm] + np.pi / 2
#dd = np.arctan2(yy2-yy1, xx2-xx1) # angle normal
#dd2 = np.arctan2(yy3-yy1, xx3-xx1) # angle tangent
#mm = ((yy2-yy1)==0.) & ((xx2-xx1)==0.) # mask where dd1 is not defined
#dd[mm] = dd2[mm] + np.pi / 2
#dd += np.pi
#dd = np.arctan2(xx2-xx1, angle_tangent-yy1)
trans_tick = self.get_tick_transform(axes)
tr2ax = trans_tick + axes.transAxes.inverted()
for x, y, d, d2, lab in zip(xx1, yy1, dd, dd2, labels):
c2 = tr2ax.transform_point((x, y))
delta=0.00001
if (0. -delta<= c2[0] <= 1.+delta) and \
(0. -delta<= c2[1] <= 1.+delta):
d1 = d/3.14159*180.
d2 = d2/3.14159*180.
yield [x, y], d1, d2, lab
return f1(), iter([])
def get_line_transform(self, axes):
return axes.transData
def get_line(self, axes):
self.update_lim(axes)
x, y = self.grid_info["line_xy"]
if self._get_line_path is None:
return Path(np.column_stack([x, y]))
else:
return self._get_line_path(axes, x, y)
class GridHelperCurveLinear(GridHelperBase):
def __init__(self, aux_trans,
extreme_finder=None,
grid_locator1=None,
grid_locator2=None,
tick_formatter1=None,
tick_formatter2=None):
"""
aux_trans : a transform from the source (curved) coordinate to
target (rectilinear) coordinate. An instance of MPL's Transform
(inverse transform should be defined) or a tuple of two callable
objects which defines the transform and its inverse. The callables
need take two arguments of array of source coordinates and
should return two target coordinates.
e.g., ``x2, y2 = trans(x1, y1)``
"""
super(GridHelperCurveLinear, self).__init__()
self.grid_info = None
self._old_values = None
#self._grid_params = dict()
self._aux_trans = aux_trans
self.grid_finder = GridFinder(aux_trans,
extreme_finder,
grid_locator1,
grid_locator2,
tick_formatter1,
tick_formatter2)
def update_grid_finder(self, aux_trans=None, **kw):
if aux_trans is not None:
self.grid_finder.update_transform(aux_trans)
self.grid_finder.update(**kw)
self.invalidate()
def _update(self, x1, x2, y1, y2):
"bbox in 0-based image coordinates"
# update wcsgrid
if self.valid() and self._old_values == (x1, x2, y1, y2):
return
self._update_grid(x1, y1, x2, y2)
self._old_values = (x1, x2, y1, y2)
self._force_update = False
def new_fixed_axis(self, loc,
nth_coord=None,
axis_direction=None,
offset=None,
axes=None):
if axes is None:
axes = self.axes
if axis_direction is None:
axis_direction = loc
_helper = FixedAxisArtistHelper(self, loc,
#nth_coord,
nth_coord_ticks=nth_coord,
)
axisline = AxisArtist(axes, _helper, axis_direction=axis_direction)
return axisline
def new_floating_axis(self, nth_coord,
value,
axes=None,
axis_direction="bottom"
):
if axes is None:
axes = self.axes
_helper = FloatingAxisArtistHelper(
self, nth_coord, value, axis_direction)
axisline = AxisArtist(axes, _helper)
#_helper = FloatingAxisArtistHelper(self, nth_coord,
# value,
# label_direction=label_direction,
# )
#axisline = AxisArtistFloating(axes, _helper,
# axis_direction=axis_direction)
axisline.line.set_clip_on(True)
axisline.line.set_clip_box(axisline.axes.bbox)
#axisline.major_ticklabels.set_visible(True)
#axisline.minor_ticklabels.set_visible(False)
#axisline.major_ticklabels.set_rotate_along_line(True)
#axisline.set_rotate_label_along_line(True)
return axisline
def _update_grid(self, x1, y1, x2, y2):
self.grid_info = self.grid_finder.get_grid_info(x1, y1, x2, y2)
def get_gridlines(self, which="major", axis="both"):
grid_lines = []
if axis in ["both", "x"]:
for gl in self.grid_info["lon"]["lines"]:
grid_lines.extend(gl)
if axis in ["both", "y"]:
for gl in self.grid_info["lat"]["lines"]:
grid_lines.extend(gl)
return grid_lines
def get_tick_iterator(self, nth_coord, axis_side, minor=False):
#axisnr = dict(left=0, bottom=1, right=2, top=3)[axis_side]
angle_tangent = dict(left=90, right=90, bottom=0, top=0)[axis_side]
#angle = [0, 90, 180, 270][axisnr]
lon_or_lat = ["lon", "lat"][nth_coord]
if not minor: # major ticks
def f():
for (xy, a), l in zip(self.grid_info[lon_or_lat]["tick_locs"][axis_side],
self.grid_info[lon_or_lat]["tick_labels"][axis_side]):
angle_normal = a
yield xy, angle_normal, angle_tangent, l
else:
def f():
for (xy, a), l in zip(self.grid_info[lon_or_lat]["tick_locs"][axis_side],
self.grid_info[lon_or_lat]["tick_labels"][axis_side]):
angle_normal = a
yield xy, angle_normal, angle_tangent, ""
#for xy, a, l in self.grid_info[lon_or_lat]["ticks"][axis_side]:
# yield xy, a, ""
return f()
| 15,909 | 32.42437 | 90 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpl_toolkits/axisartist/angle_helper.py
|
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import six
import numpy as np
import math
from mpl_toolkits.axisartist.grid_finder import ExtremeFinderSimple
def select_step_degree(dv):
degree_limits_ = [1.5, 3, 7, 13, 20, 40, 70, 120, 270, 520]
degree_steps_ = [ 1, 2, 5, 10, 15, 30, 45, 90, 180, 360]
degree_factors = [1.] * len(degree_steps_)
minsec_limits_ = [1.5, 2.5, 3.5, 8, 11, 18, 25, 45]
minsec_steps_ = [1, 2, 3, 5, 10, 15, 20, 30]
minute_limits_ = np.array(minsec_limits_) / 60
minute_factors = [60.] * len(minute_limits_)
second_limits_ = np.array(minsec_limits_) / 3600
second_factors = [3600.] * len(second_limits_)
degree_limits = np.concatenate([second_limits_,
minute_limits_,
degree_limits_])
degree_steps = np.concatenate([minsec_steps_,
minsec_steps_,
degree_steps_])
degree_factors = np.concatenate([second_factors,
minute_factors,
degree_factors])
n = degree_limits.searchsorted(dv)
step = degree_steps[n]
factor = degree_factors[n]
return step, factor
def select_step_hour(dv):
hour_limits_ = [1.5, 2.5, 3.5, 5, 7, 10, 15, 21, 36]
hour_steps_ = [1, 2 , 3, 4, 6, 8, 12, 18, 24]
hour_factors = [1.] * len(hour_steps_)
minsec_limits_ = [1.5, 2.5, 3.5, 4.5, 5.5, 8, 11, 14, 18, 25, 45]
minsec_steps_ = [1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30]
minute_limits_ = np.array(minsec_limits_) / 60
minute_factors = [60.] * len(minute_limits_)
second_limits_ = np.array(minsec_limits_) / 3600
second_factors = [3600.] * len(second_limits_)
hour_limits = np.concatenate([second_limits_,
minute_limits_,
hour_limits_])
hour_steps = np.concatenate([minsec_steps_,
minsec_steps_,
hour_steps_])
hour_factors = np.concatenate([second_factors,
minute_factors,
hour_factors])
n = hour_limits.searchsorted(dv)
step = hour_steps[n]
factor = hour_factors[n]
return step, factor
def select_step_sub(dv):
# subarcsec or degree
tmp = 10.**(int(math.log10(dv))-1.)
factor = 1./tmp
if 1.5*tmp >= dv:
step = 1
elif 3.*tmp >= dv:
step = 2
elif 7.*tmp >= dv:
step = 5
else:
step = 1
factor = 0.1*factor
return step, factor
def select_step(v1, v2, nv, hour=False, include_last=True,
threshold_factor=3600.):
if v1 > v2:
v1, v2 = v2, v1
dv = (v2 - v1) / nv
if hour:
_select_step = select_step_hour
cycle = 24.
else:
_select_step = select_step_degree
cycle = 360.
# for degree
if dv > 1./threshold_factor:
step, factor = _select_step(dv)
else:
step, factor = select_step_sub(dv*threshold_factor)
factor = factor * threshold_factor
f1, f2, fstep = v1*factor, v2*factor, step/factor
levs = np.arange(np.floor(f1/step), np.ceil(f2/step)+0.5, dtype=int) * step
# n : number of valid levels. If there is a cycle, e.g., [0, 90, 180,
# 270, 360], the grid line needs to be extended from 0 to 360, so
# we need to return the whole array. However, the last level (360)
# needs to be ignored often. In this case, so we return n=4.
n = len(levs)
# we need to check the range of values
# for example, -90 to 90, 0 to 360,
if factor == 1. and (levs[-1] >= levs[0]+cycle): # check for cycle
nv = int(cycle / step)
if include_last:
levs = levs[0] + np.arange(0, nv+1, 1) * step
else:
levs = levs[0] + np.arange(0, nv, 1) * step
n = len(levs)
return np.array(levs), n, factor
def select_step24(v1, v2, nv, include_last=True, threshold_factor=3600):
v1, v2 = v1/15., v2/15.
levs, n, factor = select_step(v1, v2, nv, hour=True,
include_last=include_last,
threshold_factor=threshold_factor)
return levs*15., n, factor
def select_step360(v1, v2, nv, include_last=True, threshold_factor=3600):
return select_step(v1, v2, nv, hour=False,
include_last=include_last,
threshold_factor=threshold_factor)
class LocatorBase(object):
def __init__(self, den, include_last=True):
self.den = den
self._include_last = include_last
@property
def nbins(self):
return self.den
@nbins.setter
def nbins(self, v):
self.den = v
def set_params(self, nbins=None):
if nbins is not None:
self.den = int(nbins)
class LocatorHMS(LocatorBase):
def __call__(self, v1, v2):
return select_step24(v1, v2, self.den, self._include_last)
class LocatorHM(LocatorBase):
def __call__(self, v1, v2):
return select_step24(v1, v2, self.den, self._include_last,
threshold_factor=60)
class LocatorH(LocatorBase):
def __call__(self, v1, v2):
return select_step24(v1, v2, self.den, self._include_last,
threshold_factor=1)
class LocatorDMS(LocatorBase):
def __call__(self, v1, v2):
return select_step360(v1, v2, self.den, self._include_last)
class LocatorDM(LocatorBase):
def __call__(self, v1, v2):
return select_step360(v1, v2, self.den, self._include_last,
threshold_factor=60)
class LocatorD(LocatorBase):
def __call__(self, v1, v2):
return select_step360(v1, v2, self.den, self._include_last,
threshold_factor=1)
class FormatterDMS(object):
deg_mark = "^{\circ}"
min_mark = "^{\prime}"
sec_mark = "^{\prime\prime}"
fmt_d = "$%d" + deg_mark + "$"
fmt_ds = r"$%d.%s" + deg_mark + "$"
# %s for sign
fmt_d_m = r"$%s%d" + deg_mark + "\,%02d" + min_mark + "$"
fmt_d_ms = r"$%s%d" + deg_mark + "\,%02d.%s" + min_mark + "$"
fmt_d_m_partial = "$%s%d" + deg_mark + "\,%02d" + min_mark + "\,"
fmt_s_partial = "%02d" + sec_mark + "$"
fmt_ss_partial = "%02d.%s" + sec_mark + "$"
def _get_number_fraction(self, factor):
## check for fractional numbers
number_fraction = None
# check for 60
for threshold in [1, 60, 3600]:
if factor <= threshold:
break
d = factor // threshold
int_log_d = int(np.floor(np.log10(d)))
if 10**int_log_d == d and d != 1:
number_fraction = int_log_d
factor = factor // 10**int_log_d
return factor, number_fraction
return factor, number_fraction
def __call__(self, direction, factor, values):
if len(values) == 0:
return []
#ss = [[-1, 1][v>0] for v in values] #not py24 compliant
values = np.asarray(values)
ss = np.where(values>0, 1, -1)
sign_map = {(-1, True):"-"}
signs = [sign_map.get((s, v!=0), "") for s, v in zip(ss, values)]
factor, number_fraction = self._get_number_fraction(factor)
values = np.abs(values)
if number_fraction is not None:
values, frac_part = divmod(values, 10**number_fraction)
frac_fmt = "%%0%dd" % (number_fraction,)
frac_str = [frac_fmt % (f1,) for f1 in frac_part]
if factor == 1:
if number_fraction is None:
return [self.fmt_d % (s*int(v),) for (s, v) in zip(ss, values)]
else:
return [self.fmt_ds % (s*int(v), f1)
for (s, v, f1) in zip(ss, values, frac_str)]
elif factor == 60:
deg_part, min_part = divmod(values, 60)
if number_fraction is None:
return [self.fmt_d_m % (s1, d1, m1)
for s1, d1, m1 in zip(signs, deg_part, min_part)]
else:
return [self.fmt_d_ms % (s, d1, m1, f1)
for s, d1, m1, f1 in zip(signs, deg_part, min_part, frac_str)]
elif factor == 3600:
if ss[-1] == -1:
inverse_order = True
values = values[::-1]
signs = signs[::-1]
else:
inverse_order = False
l_hm_old = ""
r = []
deg_part, min_part_ = divmod(values, 3600)
min_part, sec_part = divmod(min_part_, 60)
if number_fraction is None:
sec_str = [self.fmt_s_partial % (s1,) for s1 in sec_part]
else:
sec_str = [self.fmt_ss_partial % (s1, f1) for s1, f1 in zip(sec_part, frac_str)]
for s, d1, m1, s1 in zip(signs, deg_part, min_part, sec_str):
l_hm = self.fmt_d_m_partial % (s, d1, m1)
if l_hm != l_hm_old:
l_hm_old = l_hm
l = l_hm + s1 #l_s
else:
l = "$" + s + s1
r.append(l)
if inverse_order:
return r[::-1]
else:
return r
else: # factor > 3600.
return [r"$%s^{\circ}$" % (str(v),) for v in ss*values]
class FormatterHMS(FormatterDMS):
deg_mark = "^\mathrm{h}"
min_mark = "^\mathrm{m}"
sec_mark = "^\mathrm{s}"
fmt_d = "$%d" + deg_mark + "$"
fmt_ds = r"$%d.%s" + deg_mark + "$"
# %s for sign
fmt_d_m = r"$%s%d" + deg_mark + "\,%02d" + min_mark+"$"
fmt_d_ms = r"$%s%d" + deg_mark + "\,%02d.%s" + min_mark+"$"
fmt_d_m_partial = "$%s%d" + deg_mark + "\,%02d" + min_mark + "\,"
fmt_s_partial = "%02d" + sec_mark + "$"
fmt_ss_partial = "%02d.%s" + sec_mark + "$"
def __call__(self, direction, factor, values): # hour
return FormatterDMS.__call__(self, direction, factor, np.asarray(values)/15.)
class ExtremeFinderCycle(ExtremeFinderSimple):
"""
When there is a cycle, e.g., longitude goes from 0-360.
"""
def __init__(self,
nx, ny,
lon_cycle = 360.,
lat_cycle = None,
lon_minmax = None,
lat_minmax = (-90, 90)
):
#self.transfrom_xy = transform_xy
#self.inv_transfrom_xy = inv_transform_xy
self.nx, self.ny = nx, ny
self.lon_cycle, self.lat_cycle = lon_cycle, lat_cycle
self.lon_minmax = lon_minmax
self.lat_minmax = lat_minmax
def __call__(self, transform_xy, x1, y1, x2, y2):
"""
get extreme values.
x1, y1, x2, y2 in image coordinates (0-based)
nx, ny : number of divisions in each axis
"""
x_, y_ = np.linspace(x1, x2, self.nx), np.linspace(y1, y2, self.ny)
x, y = np.meshgrid(x_, y_)
lon, lat = transform_xy(np.ravel(x), np.ravel(y))
# iron out jumps, but algorithm should be improved.
# This is just naive way of doing and my fail for some cases.
# Consider replacing this with numpy.unwrap
# We are ignoring invalid warnings. They are triggered when
# comparing arrays with NaNs using > We are already handling
# that correctly using np.nanmin and np.nanmax
with np.errstate(invalid='ignore'):
if self.lon_cycle is not None:
lon0 = np.nanmin(lon)
lon -= 360. * ((lon - lon0) > 180.)
if self.lat_cycle is not None:
lat0 = np.nanmin(lat)
lat -= 360. * ((lat - lat0) > 180.)
lon_min, lon_max = np.nanmin(lon), np.nanmax(lon)
lat_min, lat_max = np.nanmin(lat), np.nanmax(lat)
lon_min, lon_max, lat_min, lat_max = \
self._adjust_extremes(lon_min, lon_max, lat_min, lat_max)
return lon_min, lon_max, lat_min, lat_max
def _adjust_extremes(self, lon_min, lon_max, lat_min, lat_max):
lon_min, lon_max, lat_min, lat_max = \
self._add_pad(lon_min, lon_max, lat_min, lat_max)
# check cycle
if self.lon_cycle:
lon_max = min(lon_max, lon_min + self.lon_cycle)
if self.lat_cycle:
lat_max = min(lat_max, lat_min + self.lat_cycle)
if self.lon_minmax is not None:
min0 = self.lon_minmax[0]
lon_min = max(min0, lon_min)
max0 = self.lon_minmax[1]
lon_max = min(max0, lon_max)
if self.lat_minmax is not None:
min0 = self.lat_minmax[0]
lat_min = max(min0, lat_min)
max0 = self.lat_minmax[1]
lat_max = min(max0, lat_max)
return lon_min, lon_max, lat_min, lat_max
| 13,040 | 30.273381 | 96 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpl_toolkits/axisartist/parasite_axes.py
|
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from mpl_toolkits.axes_grid1.parasite_axes import (
host_axes_class_factory, parasite_axes_class_factory,
parasite_axes_auxtrans_class_factory, subplot_class_factory)
from .axislines import Axes
ParasiteAxes = parasite_axes_class_factory(Axes)
ParasiteAxesAuxTrans = \
parasite_axes_auxtrans_class_factory(axes_class=ParasiteAxes)
HostAxes = host_axes_class_factory(axes_class=Axes)
SubplotHost = subplot_class_factory(HostAxes)
| 557 | 28.368421 | 66 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpl_toolkits/axisartist/axislines.py
|
"""
Axislines includes modified implementation of the Axes class. The
biggest difference is that the artists responsible for drawing the axis spine,
ticks, ticklabels and axis labels are separated out from mpl's Axis
class. Originally, this change was motivated to support curvilinear
grid. Here are a few reasons that I came up with a new axes class:
* "top" and "bottom" x-axis (or "left" and "right" y-axis) can have
different ticks (tick locations and labels). This is not possible
with the current mpl, although some twin axes trick can help.
* Curvilinear grid.
* angled ticks.
In the new axes class, xaxis and yaxis is set to not visible by
default, and new set of artist (AxisArtist) are defined to draw axis
line, ticks, ticklabels and axis label. Axes.axis attribute serves as
a dictionary of these artists, i.e., ax.axis["left"] is a AxisArtist
instance responsible to draw left y-axis. The default Axes.axis contains
"bottom", "left", "top" and "right".
AxisArtist can be considered as a container artist and
has following children artists which will draw ticks, labels, etc.
* line
* major_ticks, major_ticklabels
* minor_ticks, minor_ticklabels
* offsetText
* label
Note that these are separate artists from Axis class of the
original mpl, thus most of tick-related command in the original mpl
won't work, although some effort has made to work with. For example,
color and markerwidth of the ax.axis["bottom"].major_ticks will follow
those of Axes.xaxis unless explicitly specified.
In addition to AxisArtist, the Axes will have *gridlines* attribute,
which obviously draws grid lines. The gridlines needs to be separated
from the axis as some gridlines can never pass any axis.
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import six
import warnings
import numpy as np
from matplotlib import rcParams
import matplotlib.artist as martist
import matplotlib.axes as maxes
from matplotlib.path import Path
from matplotlib.transforms import Bbox
from .axisline_style import AxislineStyle
from .axis_artist import AxisArtist, GridlinesCollection
class AxisArtistHelper(object):
"""
AxisArtistHelper should define
following method with given APIs. Note that the first axes argument
will be axes attribute of the caller artist.::
# LINE (spinal line?)
def get_line(self, axes):
# path : Path
return path
def get_line_transform(self, axes):
# ...
# trans : transform
return trans
# LABEL
def get_label_pos(self, axes):
# x, y : position
return (x, y), trans
def get_label_offset_transform(self, \
axes,
pad_points, fontprops, renderer,
bboxes,
):
# va : vertical alignment
# ha : horizontal alignment
# a : angle
return trans, va, ha, a
# TICK
def get_tick_transform(self, axes):
return trans
def get_tick_iterators(self, axes):
# iter : iterable object that yields (c, angle, l) where
# c, angle, l is position, tick angle, and label
return iter_major, iter_minor
"""
class _Base(object):
"""
Base class for axis helper.
"""
def __init__(self):
"""
"""
self.delta1, self.delta2 = 0.00001, 0.00001
def update_lim(self, axes):
pass
class Fixed(_Base):
"""
Helper class for a fixed (in the axes coordinate) axis.
"""
_default_passthru_pt = dict(left=(0, 0),
right=(1, 0),
bottom=(0, 0),
top=(0, 1))
def __init__(self,
loc, nth_coord=None,
):
"""
nth_coord = along which coordinate value varies
in 2d, nth_coord = 0 -> x axis, nth_coord = 1 -> y axis
"""
self._loc = loc
if loc not in ["left", "right", "bottom", "top"]:
raise ValueError("%s" % loc)
if nth_coord is None:
if loc in ["left", "right"]:
nth_coord = 1
elif loc in ["bottom", "top"]:
nth_coord = 0
self.nth_coord = nth_coord
super(AxisArtistHelper.Fixed, self).__init__()
self.passthru_pt = self._default_passthru_pt[loc]
_verts = np.array([[0., 0.],
[1., 1.]])
fixed_coord = 1-nth_coord
_verts[:,fixed_coord] = self.passthru_pt[fixed_coord]
# axis line in transAxes
self._path = Path(_verts)
def get_nth_coord(self):
return self.nth_coord
# LINE
def get_line(self, axes):
return self._path
def get_line_transform(self, axes):
return axes.transAxes
# LABEL
def get_axislabel_transform(self, axes):
return axes.transAxes
def get_axislabel_pos_angle(self, axes):
"""
label reference position in transAxes.
get_label_transform() returns a transform of (transAxes+offset)
"""
loc = self._loc
pos, angle_tangent = dict(left=((0., 0.5), 90),
right=((1., 0.5), 90),
bottom=((0.5, 0.), 0),
top=((0.5, 1.), 0))[loc]
return pos, angle_tangent
# TICK
def get_tick_transform(self, axes):
trans_tick = [axes.get_xaxis_transform(),
axes.get_yaxis_transform()][self.nth_coord]
return trans_tick
class Floating(_Base):
def __init__(self, nth_coord,
value):
self.nth_coord = nth_coord
self._value = value
super(AxisArtistHelper.Floating,
self).__init__()
def get_nth_coord(self):
return self.nth_coord
def get_line(self, axes):
raise RuntimeError("get_line method should be defined by the derived class")
class AxisArtistHelperRectlinear(object):
class Fixed(AxisArtistHelper.Fixed):
def __init__(self, axes, loc, nth_coord=None):
"""
nth_coord = along which coordinate value varies
in 2d, nth_coord = 0 -> x axis, nth_coord = 1 -> y axis
"""
super(AxisArtistHelperRectlinear.Fixed, self).__init__(
loc, nth_coord)
self.axis = [axes.xaxis, axes.yaxis][self.nth_coord]
# TICK
def get_tick_iterators(self, axes):
"""tick_loc, tick_angle, tick_label"""
loc = self._loc
if loc in ["bottom", "top"]:
angle_normal, angle_tangent = 90, 0
else:
angle_normal, angle_tangent = 0, 90
major = self.axis.major
majorLocs = major.locator()
major.formatter.set_locs(majorLocs)
majorLabels = [major.formatter(val, i) for i, val in enumerate(majorLocs)]
minor = self.axis.minor
minorLocs = minor.locator()
minor.formatter.set_locs(minorLocs)
minorLabels = [minor.formatter(val, i) for i, val in enumerate(minorLocs)]
trans_tick = self.get_tick_transform(axes)
tr2ax = trans_tick + axes.transAxes.inverted()
def _f(locs, labels):
for x, l in zip(locs, labels):
c = list(self.passthru_pt) # copy
c[self.nth_coord] = x
# check if the tick point is inside axes
c2 = tr2ax.transform_point(c)
#delta=0.00001
if 0. -self.delta1<= c2[self.nth_coord] <= 1.+self.delta2:
yield c, angle_normal, angle_tangent, l
return _f(majorLocs, majorLabels), _f(minorLocs, minorLabels)
class Floating(AxisArtistHelper.Floating):
def __init__(self, axes, nth_coord,
passingthrough_point, axis_direction="bottom"):
super(AxisArtistHelperRectlinear.Floating, self).__init__(
nth_coord, passingthrough_point)
self._axis_direction = axis_direction
self.axis = [axes.xaxis, axes.yaxis][self.nth_coord]
def get_line(self, axes):
_verts = np.array([[0., 0.],
[1., 1.]])
fixed_coord = 1-self.nth_coord
trans_passingthrough_point = axes.transData + axes.transAxes.inverted()
p = trans_passingthrough_point.transform_point([self._value,
self._value])
_verts[:,fixed_coord] = p[fixed_coord]
return Path(_verts)
def get_line_transform(self, axes):
return axes.transAxes
def get_axislabel_transform(self, axes):
return axes.transAxes
def get_axislabel_pos_angle(self, axes):
"""
label reference position in transAxes.
get_label_transform() returns a transform of (transAxes+offset)
"""
loc = self._axis_direction
#angle = dict(left=0,
# right=0,
# bottom=.5*np.pi,
# top=.5*np.pi)[loc]
if self.nth_coord == 0:
angle = 0
else:
angle = 90
_verts = [0.5, 0.5]
fixed_coord = 1-self.nth_coord
trans_passingthrough_point = axes.transData + axes.transAxes.inverted()
p = trans_passingthrough_point.transform_point([self._value,
self._value])
_verts[fixed_coord] = p[fixed_coord]
if not (0. <= _verts[fixed_coord] <= 1.):
return None, None
else:
return _verts, angle
def get_tick_transform(self, axes):
return axes.transData
def get_tick_iterators(self, axes):
"""tick_loc, tick_angle, tick_label"""
loc = self._axis_direction
if loc in ["bottom", "top"]:
angle_normal, angle_tangent = 90, 0
else:
angle_normal, angle_tangent = 0, 90
if self.nth_coord == 0:
angle_normal, angle_tangent = 90, 0
else:
angle_normal, angle_tangent = 0, 90
#angle = 90 - 90 * self.nth_coord
major = self.axis.major
majorLocs = major.locator()
major.formatter.set_locs(majorLocs)
majorLabels = [major.formatter(val, i) for i, val in enumerate(majorLocs)]
minor = self.axis.minor
minorLocs = minor.locator()
minor.formatter.set_locs(minorLocs)
minorLabels = [minor.formatter(val, i) for i, val in enumerate(minorLocs)]
tr2ax = axes.transData + axes.transAxes.inverted()
def _f(locs, labels):
for x, l in zip(locs, labels):
c = [self._value, self._value]
c[self.nth_coord] = x
c1, c2 = tr2ax.transform_point(c)
if 0. <= c1 <= 1. and 0. <= c2 <= 1.:
if 0. - self.delta1 <= [c1, c2][self.nth_coord] <= 1. + self.delta2:
yield c, angle_normal, angle_tangent, l
return _f(majorLocs, majorLabels), _f(minorLocs, minorLabels)
class GridHelperBase(object):
def __init__(self):
self._force_update = True
self._old_limits = None
super(GridHelperBase, self).__init__()
def update_lim(self, axes):
x1, x2 = axes.get_xlim()
y1, y2 = axes.get_ylim()
if self._force_update or self._old_limits != (x1, x2, y1, y2):
self._update(x1, x2, y1, y2)
self._force_update = False
self._old_limits = (x1, x2, y1, y2)
def _update(self, x1, x2, y1, y2):
pass
def invalidate(self):
self._force_update = True
def valid(self):
return not self._force_update
def get_gridlines(self, which, axis):
"""
Return list of grid lines as a list of paths (list of points).
*which* : "major" or "minor"
*axis* : "both", "x" or "y"
"""
return []
def new_gridlines(self, ax):
"""
Create and return a new GridlineCollection instance.
*which* : "major" or "minor"
*axis* : "both", "x" or "y"
"""
gridlines = GridlinesCollection(None, transform=ax.transData,
colors=rcParams['grid.color'],
linestyles=rcParams['grid.linestyle'],
linewidths=rcParams['grid.linewidth'])
ax._set_artist_props(gridlines)
gridlines.set_grid_helper(self)
ax.axes._set_artist_props(gridlines)
# gridlines.set_clip_path(self.axes.patch)
# set_clip_path need to be deferred after Axes.cla is completed.
# It is done inside the cla.
return gridlines
class GridHelperRectlinear(GridHelperBase):
def __init__(self, axes):
super(GridHelperRectlinear, self).__init__()
self.axes = axes
def new_fixed_axis(self, loc,
nth_coord=None,
axis_direction=None,
offset=None,
axes=None,
):
if axes is None:
warnings.warn("'new_fixed_axis' explicitly requires the axes keyword.")
axes = self.axes
_helper = AxisArtistHelperRectlinear.Fixed(axes, loc, nth_coord)
if axis_direction is None:
axis_direction = loc
axisline = AxisArtist(axes, _helper, offset=offset,
axis_direction=axis_direction,
)
return axisline
def new_floating_axis(self, nth_coord, value,
axis_direction="bottom",
axes=None,
):
if axes is None:
warnings.warn(
"'new_floating_axis' explicitly requires the axes keyword.")
axes = self.axes
passthrough_point = (value, value)
transform = axes.transData
_helper = AxisArtistHelperRectlinear.Floating(
axes, nth_coord, value, axis_direction)
axisline = AxisArtist(axes, _helper)
axisline.line.set_clip_on(True)
axisline.line.set_clip_box(axisline.axes.bbox)
return axisline
def get_gridlines(self, which="major", axis="both"):
"""
return list of gridline coordinates in data coordinates.
*which* : "major" or "minor"
*axis* : "both", "x" or "y"
"""
gridlines = []
if axis in ["both", "x"]:
locs = []
y1, y2 = self.axes.get_ylim()
#if self.axes.xaxis._gridOnMajor:
if which in ["both", "major"]:
locs.extend(self.axes.xaxis.major.locator())
#if self.axes.xaxis._gridOnMinor:
if which in ["both", "minor"]:
locs.extend(self.axes.xaxis.minor.locator())
for x in locs:
gridlines.append([[x, x], [y1, y2]])
if axis in ["both", "y"]:
x1, x2 = self.axes.get_xlim()
locs = []
if self.axes.yaxis._gridOnMajor:
#if which in ["both", "major"]:
locs.extend(self.axes.yaxis.major.locator())
if self.axes.yaxis._gridOnMinor:
#if which in ["both", "minor"]:
locs.extend(self.axes.yaxis.minor.locator())
for y in locs:
gridlines.append([[x1, x2], [y, y]])
return gridlines
class SimpleChainedObjects(object):
def __init__(self, objects):
self._objects = objects
def __getattr__(self, k):
_a = SimpleChainedObjects([getattr(a, k) for a in self._objects])
return _a
def __call__(self, *kl, **kwargs):
for m in self._objects:
m(*kl, **kwargs)
class Axes(maxes.Axes):
class AxisDict(dict):
def __init__(self, axes):
self.axes = axes
super(Axes.AxisDict, self).__init__()
def __getitem__(self, k):
if isinstance(k, tuple):
r = SimpleChainedObjects([dict.__getitem__(self, k1) for k1 in k])
return r
elif isinstance(k, slice):
if k.start == None and k.stop == None and k.step == None:
r = SimpleChainedObjects(list(six.itervalues(self)))
return r
else:
raise ValueError("Unsupported slice")
else:
return dict.__getitem__(self, k)
def __call__(self, *v, **kwargs):
return maxes.Axes.axis(self.axes, *v, **kwargs)
def __init__(self, *kl, **kw):
helper = kw.pop("grid_helper", None)
self._axisline_on = True
if helper:
self._grid_helper = helper
else:
self._grid_helper = GridHelperRectlinear(self)
super(Axes, self).__init__(*kl, **kw)
self.toggle_axisline(True)
def toggle_axisline(self, b=None):
if b is None:
b = not self._axisline_on
if b:
self._axisline_on = True
for s in self.spines.values():
s.set_visible(False)
self.xaxis.set_visible(False)
self.yaxis.set_visible(False)
else:
self._axisline_on = False
for s in self.spines.values():
s.set_visible(True)
self.xaxis.set_visible(True)
self.yaxis.set_visible(True)
def _init_axis(self):
super(Axes, self)._init_axis()
def _init_axis_artists(self, axes=None):
if axes is None:
axes = self
self._axislines = self.AxisDict(self)
new_fixed_axis = self.get_grid_helper().new_fixed_axis
for loc in ["bottom", "top", "left", "right"]:
self._axislines[loc] = new_fixed_axis(loc=loc, axes=axes,
axis_direction=loc)
for axisline in [self._axislines["top"], self._axislines["right"]]:
axisline.label.set_visible(False)
axisline.major_ticklabels.set_visible(False)
axisline.minor_ticklabels.set_visible(False)
@property
def axis(self):
return self._axislines
def new_gridlines(self, grid_helper=None):
"""
Create and return a new GridlineCollection instance.
*which* : "major" or "minor"
*axis* : "both", "x" or "y"
"""
if grid_helper is None:
grid_helper = self.get_grid_helper()
gridlines = grid_helper.new_gridlines(self)
return gridlines
def _init_gridlines(self, grid_helper=None):
# It is done inside the cla.
gridlines = self.new_gridlines(grid_helper)
self.gridlines = gridlines
def cla(self):
# gridlines need to b created before cla() since cla calls grid()
self._init_gridlines()
super(Axes, self).cla()
# the clip_path should be set after Axes.cla() since that's
# when a patch is created.
self.gridlines.set_clip_path(self.axes.patch)
self._init_axis_artists()
def get_grid_helper(self):
return self._grid_helper
def grid(self, b=None, which='major', axis="both", **kwargs):
"""
Toggle the gridlines, and optionally set the properties of the lines.
"""
# their are some discrepancy between the behavior of grid in
# axes_grid and the original mpl's grid, because axes_grid
# explicitly set the visibility of the gridlines.
super(Axes, self).grid(b, which=which, axis=axis, **kwargs)
if not self._axisline_on:
return
if b is None:
if self.axes.xaxis._gridOnMinor or self.axes.xaxis._gridOnMajor or \
self.axes.yaxis._gridOnMinor or self.axes.yaxis._gridOnMajor:
b=True
else:
b=False
self.gridlines.set_which(which)
self.gridlines.set_axis(axis)
self.gridlines.set_visible(b)
if len(kwargs):
martist.setp(self.gridlines, **kwargs)
def get_children(self):
if self._axisline_on:
children = list(six.itervalues(self._axislines)) + [self.gridlines]
else:
children = []
children.extend(super(Axes, self).get_children())
return children
def invalidate_grid_helper(self):
self._grid_helper.invalidate()
def new_fixed_axis(self, loc, offset=None):
gh = self.get_grid_helper()
axis = gh.new_fixed_axis(loc,
nth_coord=None,
axis_direction=None,
offset=offset,
axes=self,
)
return axis
def new_floating_axis(self, nth_coord, value,
axis_direction="bottom",
):
gh = self.get_grid_helper()
axis = gh.new_floating_axis(nth_coord, value,
axis_direction=axis_direction,
axes=self)
return axis
def draw(self, renderer, inframe=False):
if not self._axisline_on:
super(Axes, self).draw(renderer, inframe)
return
orig_artists = self.artists
self.artists = self.artists + list(self._axislines.values()) + [self.gridlines]
super(Axes, self).draw(renderer, inframe)
self.artists = orig_artists
def get_tightbbox(self, renderer, call_axes_locator=True):
bb0 = super(Axes, self).get_tightbbox(renderer, call_axes_locator)
if not self._axisline_on:
return bb0
bb = [bb0]
for axisline in list(six.itervalues(self._axislines)):
if not axisline.get_visible():
continue
bb.append(axisline.get_tightbbox(renderer))
# if axisline.label.get_visible():
# bb.append(axisline.label.get_window_extent(renderer))
# if axisline.major_ticklabels.get_visible():
# bb.extend(axisline.major_ticklabels.get_window_extents(renderer))
# if axisline.minor_ticklabels.get_visible():
# bb.extend(axisline.minor_ticklabels.get_window_extents(renderer))
# if axisline.major_ticklabels.get_visible() or \
# axisline.minor_ticklabels.get_visible():
# bb.append(axisline.offsetText.get_window_extent(renderer))
#bb.extend([c.get_window_extent(renderer) for c in artists \
# if c.get_visible()])
_bbox = Bbox.union([b for b in bb if b and (b.width!=0 or b.height!=0)])
return _bbox
Subplot = maxes.subplot_class_factory(Axes)
class AxesZero(Axes):
def __init__(self, *kl, **kw):
super(AxesZero, self).__init__(*kl, **kw)
def _init_axis_artists(self):
super(AxesZero, self)._init_axis_artists()
new_floating_axis = self._grid_helper.new_floating_axis
xaxis_zero = new_floating_axis(nth_coord=0,
value=0.,
axis_direction="bottom",
axes=self)
xaxis_zero.line.set_clip_path(self.patch)
xaxis_zero.set_visible(False)
self._axislines["xzero"] = xaxis_zero
yaxis_zero = new_floating_axis(nth_coord=1,
value=0.,
axis_direction="left",
axes=self)
yaxis_zero.line.set_clip_path(self.patch)
yaxis_zero.set_visible(False)
self._axislines["yzero"] = yaxis_zero
SubplotZero = maxes.subplot_class_factory(AxesZero)
| 24,756 | 28.863691 | 92 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpl_toolkits/axisartist/axis_artist.py
|
"""
axis_artist.py module provides axis-related artists. They are
* axis line
* tick lines
* tick labels
* axis label
* grid lines
The main artist class is a AxisArtist and a GridlinesCollection. The
GridlinesCollection is responsible for drawing grid lines and the
AxisArtist is responsible for all other artists. The AxisArtist class
has attributes that are associated with each type of artists.
* line : axis line
* major_ticks : major tick lines
* major_ticklabels : major tick labels
* minor_ticks : minor tick lines
* minor_ticklabels : minor tick labels
* label : axis label
Typically, the AxisArtist associated with a axes will be accessed with
the *axis* dictionary of the axes, i.e., the AxisArtist for the bottom
axis is
ax.axis["bottom"]
where *ax* is an instance of axes (mpl_toolkits.axislines.Axes). Thus,
ax.axis["bottom"].line is an artist associated with the axis line, and
ax.axis["bottom"].major_ticks is an artist associated with the major tick
lines.
You can change the colors, fonts, line widths, etc. of these artists
by calling suitable set method. For example, to change the color of the major
ticks of the bottom axis to red,
ax.axis["bottom"].major_ticks.set_color("r")
However, things like the locations of ticks, and their ticklabels need
to be changed from the side of the grid_helper.
axis_direction
--------------
AxisArtist, AxisLabel, TickLabels have *axis_direction* attribute,
which adjusts the location, angle, etc.,. The *axis_direction* must be
one of [left, right, bottom, top] and they follow the matplotlib
convention for the rectangle axis.
For example, for the *bottom* axis (the left and right is relative to
the direction of the increasing coordinate),
* ticklabels and axislabel are on the right
* ticklabels and axislabel have text angle of 0
* ticklabels are baseline, center-aligned
* axislabel is top, center-aligned
The text angles are actually relative to (90 + angle of the direction
to the ticklabel), which gives 0 for bottom axis.
left bottom right top
ticklabels location left right right left
axislabel location left right right left
ticklabels angle 90 0 -90 180
axislabel angle 180 0 0 180
ticklabel va center baseline center baseline
axislabel va center top center bottom
ticklabel ha right center right center
axislabel ha right center right center
Ticks are by default direct opposite side of the ticklabels. To make
ticks to the same side of the ticklabels,
ax.axis["bottom"].major_ticks.set_ticks_out(True)
Following attributes can be customized (use set_xxx method)
* Ticks : ticksize, tick_out
* TickLabels : pad
* AxisLabel : pad
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import six
# FIXME :
# angles are given in data coordinate - need to convert it to canvas coordinate
import matplotlib.artist as martist
import matplotlib.text as mtext
import matplotlib.font_manager as font_manager
from matplotlib.path import Path
from matplotlib.transforms import (
Affine2D, Bbox, IdentityTransform, ScaledTranslation, TransformedPath)
from matplotlib.collections import LineCollection
from matplotlib import rcParams
from matplotlib.artist import allow_rasterization
import warnings
import numpy as np
import matplotlib.lines as mlines
from .axisline_style import AxislineStyle
class BezierPath(mlines.Line2D):
def __init__(self, path, *kl, **kw):
mlines.Line2D.__init__(self, [], [], *kl, **kw)
self._path = path
self._invalid = False
def recache(self):
self._transformed_path = TransformedPath(self._path, self.get_transform())
self._invalid = False
def set_path(self, path):
self._path = path
self._invalid = True
def draw(self, renderer):
if self._invalid:
self.recache()
if not self._visible: return
renderer.open_group('line2d')
gc = renderer.new_gc()
self._set_gc_clip(gc)
gc.set_foreground(self._color)
gc.set_antialiased(self._antialiased)
gc.set_linewidth(self._linewidth)
gc.set_alpha(self._alpha)
if self.is_dashed():
cap = self._dashcapstyle
join = self._dashjoinstyle
else:
cap = self._solidcapstyle
join = self._solidjoinstyle
gc.set_joinstyle(join)
gc.set_capstyle(cap)
gc.set_dashes(self._dashOffset, self._dashSeq)
if self._lineStyles[self._linestyle] != '_draw_nothing':
tpath, affine = (
self._transformed_path.get_transformed_path_and_affine())
renderer.draw_path(gc, tpath, affine.frozen())
gc.restore()
renderer.close_group('line2d')
class UnimplementedException(Exception):
pass
from matplotlib.artist import Artist
class AttributeCopier(object):
def __init__(self, ref_artist, klass=Artist):
self._klass = klass
self._ref_artist = ref_artist
super(AttributeCopier, self).__init__()
def set_ref_artist(self, artist):
self._ref_artist = artist
def get_ref_artist(self):
raise RuntimeError("get_ref_artist must overridden")
#return self._ref_artist
def get_attribute_from_ref_artist(self, attr_name, default_value):
get_attr_method_name = "get_"+attr_name
c = getattr(self._klass, get_attr_method_name)(self)
if c == 'auto':
ref_artist = self.get_ref_artist()
if ref_artist:
attr = getattr(ref_artist,
get_attr_method_name)()
return attr
else:
return default_value
return c
from matplotlib.lines import Line2D
class Ticks(Line2D, AttributeCopier):
"""
Ticks are derived from Line2D, and note that ticks themselves
are markers. Thus, you should use set_mec, set_mew, etc.
To change the tick size (length), you need to use
set_ticksize. To change the direction of the ticks (ticks are
in opposite direction of ticklabels by default), use
set_tick_out(False).
"""
def __init__(self, ticksize, tick_out=False, **kwargs):
self._ticksize = ticksize
self.locs_angles_labels = []
self.set_tick_out(tick_out)
self._axis = kwargs.pop("axis", None)
if self._axis is not None:
if "color" not in kwargs:
kwargs["color"] = "auto"
if ("mew" not in kwargs) and ("markeredgewidth" not in kwargs):
kwargs["markeredgewidth"] = "auto"
Line2D.__init__(self, [0.], [0.], **kwargs)
AttributeCopier.__init__(self, self._axis, klass=Line2D)
self.set_snap(True)
def get_ref_artist(self):
#return self._ref_artist.get_ticklines()[0]
return self._ref_artist.majorTicks[0].tick1line
def get_color(self):
return self.get_attribute_from_ref_artist("color", "k")
def get_markeredgecolor(self):
if self._markeredgecolor == 'auto':
return self.get_color()
else:
return self._markeredgecolor
def get_markeredgewidth(self):
return self.get_attribute_from_ref_artist("markeredgewidth", .5)
def set_tick_out(self, b):
"""
set True if tick need to be rotated by 180 degree.
"""
self._tick_out = b
def get_tick_out(self):
"""
Return True if the tick will be rotated by 180 degree.
"""
return self._tick_out
def set_ticksize(self, ticksize):
"""
set length of the ticks in points.
"""
self._ticksize = ticksize
def get_ticksize(self):
"""
Return length of the ticks in points.
"""
return self._ticksize
def set_locs_angles(self, locs_angles):
self.locs_angles = locs_angles
def _update(self, renderer):
pass
_tickvert_path = Path([[0., 0.], [1., 0.]])
def draw(self, renderer):
if not self.get_visible():
return
self._update(renderer) # update the tick
size = self._ticksize
path_trans = self.get_transform()
# set gc : copied from lines.py
# gc = renderer.new_gc()
# self._set_gc_clip(gc)
# gc.set_foreground(self.get_color())
# gc.set_antialiased(self._antialiased)
# gc.set_linewidth(self._linewidth)
# gc.set_alpha(self._alpha)
# if self.is_dashed():
# cap = self._dashcapstyle
# join = self._dashjoinstyle
# else:
# cap = self._solidcapstyle
# join = self._solidjoinstyle
# gc.set_joinstyle(join)
# gc.set_capstyle(cap)
# gc.set_snap(self.get_snap())
gc = renderer.new_gc()
gc.set_foreground(self.get_markeredgecolor())
gc.set_linewidth(self.get_markeredgewidth())
gc.set_alpha(self._alpha)
offset = renderer.points_to_pixels(size)
marker_scale = Affine2D().scale(offset, offset)
if self.get_tick_out():
add_angle = 180
else:
add_angle = 0
marker_rotation = Affine2D()
marker_transform = marker_scale + marker_rotation
for loc, angle in self.locs_angles:
marker_rotation.clear().rotate_deg(angle+add_angle)
locs = path_trans.transform_non_affine([loc])
if (self.axes and
not self.axes.viewLim.contains(locs[0][0], locs[0][1])):
continue
renderer.draw_markers(gc, self._tickvert_path, marker_transform,
Path(locs), path_trans.get_affine())
gc.restore()
class LabelBase(mtext.Text):
"""
A base class for AxisLabel and TickLabels. The position and angle
of the text are calculated by to offset_ref_angle,
text_ref_angle, and offset_radius attributes.
"""
def __init__(self, *kl, **kwargs):
self.locs_angles_labels = []
self._ref_angle = 0
self._offset_radius = 0.
super(LabelBase, self).__init__(*kl,
**kwargs)
self.set_rotation_mode("anchor")
self._text_follow_ref_angle = True
#self._offset_ref_angle = 0
def _set_ref_angle(self, a):
self._ref_angle = a
def _get_ref_angle(self):
return self._ref_angle
def _get_text_ref_angle(self):
if self._text_follow_ref_angle:
return self._get_ref_angle()+90
else:
return 0 #self.get_ref_angle()
def _get_offset_ref_angle(self):
return self._get_ref_angle()
def _set_offset_radius(self, offset_radius):
self._offset_radius = offset_radius
def _get_offset_radius(self):
return self._offset_radius
_get_opposite_direction = {"left":"right",
"right":"left",
"top":"bottom",
"bottom":"top"}.__getitem__
def _update(self, renderer):
pass
def draw(self, renderer):
if not self.get_visible(): return
self._update(renderer)
# save original and adjust some properties
tr = self.get_transform()
angle_orig = self.get_rotation()
offset_tr = Affine2D()
self.set_transform(tr+offset_tr)
text_ref_angle = self._get_text_ref_angle()
offset_ref_angle = self._get_offset_ref_angle()
theta = (offset_ref_angle)/180.*np.pi
dd = self._get_offset_radius()
dx, dy = dd * np.cos(theta), dd * np.sin(theta)
offset_tr.translate(dx, dy)
self.set_rotation(text_ref_angle+angle_orig)
super(LabelBase, self).draw(renderer)
offset_tr.clear()
# restore original properties
self.set_transform(tr)
self.set_rotation(angle_orig)
def get_window_extent(self, renderer):
self._update(renderer)
# save original and adjust some properties
tr = self.get_transform()
angle_orig = self.get_rotation()
offset_tr = Affine2D()
self.set_transform(tr+offset_tr)
text_ref_angle = self._get_text_ref_angle()
offset_ref_angle = self._get_offset_ref_angle()
theta = (offset_ref_angle)/180.*np.pi
dd = self._get_offset_radius()
dx, dy = dd * np.cos(theta), dd * np.sin(theta)
offset_tr.translate(dx, dy)
self.set_rotation(text_ref_angle+angle_orig)
bbox = super(LabelBase, self).get_window_extent(renderer).frozen()
offset_tr.clear()
# restore original properties
self.set_transform(tr)
self.set_rotation(angle_orig)
return bbox
class AxisLabel(LabelBase, AttributeCopier):
"""
Axis Label. Derived from Text. The position of the text is updated
in the fly, so changing text position has no effect. Otherwise, the
properties can be changed as a normal Text.
To change the pad between ticklabels and axis label, use set_pad.
"""
def __init__(self, *kl, **kwargs):
axis_direction = kwargs.pop("axis_direction", "bottom")
self._axis = kwargs.pop("axis", None)
#super(AxisLabel, self).__init__(*kl, **kwargs)
LabelBase.__init__(self, *kl, **kwargs)
AttributeCopier.__init__(self, self._axis, klass=LabelBase)
self.set_axis_direction(axis_direction)
self._pad = 5
self._extra_pad = 0
def set_pad(self, pad):
"""
Set the pad in points. Note that the actual pad will be the
sum of the internal pad and the external pad (that are set
automatically by the AxisArtist), and it only set the internal
pad
"""
self._pad = pad
def get_pad(self):
"""
return pad in points. See set_pad for more details.
"""
return self._pad
def _set_external_pad(self, p):
"""
Set external pad IN PIXELS. This is intended to be set by the
AxisArtist, bot by user..
"""
self._extra_pad = p
def _get_external_pad(self):
"""
Get external pad.
"""
return self._extra_pad
def get_ref_artist(self):
return self._axis.get_label()
def get_text(self):
t = super(AxisLabel, self).get_text()
if t == "__from_axes__":
return self._axis.get_label().get_text()
return self._text
_default_alignments = dict(left=("bottom", "center"),
right=("top", "center"),
bottom=("top", "center"),
top=("bottom", "center"))
def set_default_alignment(self, d):
if d not in ["left", "right", "top", "bottom"]:
raise ValueError('direction must be on of "left", "right", "top", "bottom"')
va, ha = self._default_alignments[d]
self.set_va(va)
self.set_ha(ha)
_default_angles = dict(left=180,
right=0,
bottom=0,
top=180)
def set_default_angle(self, d):
if d not in ["left", "right", "top", "bottom"]:
raise ValueError('direction must be on of "left", "right", "top", "bottom"')
self.set_rotation(self._default_angles[d])
def set_axis_direction(self, d):
"""
Adjust the text angle and text alignment of axis label
according to the matplotlib convention.
===================== ========== ========= ========== ==========
property left bottom right top
===================== ========== ========= ========== ==========
axislabel angle 180 0 0 180
axislabel va center top center bottom
axislabel ha right center right center
===================== ========== ========= ========== ==========
Note that the text angles are actually relative to (90 + angle
of the direction to the ticklabel), which gives 0 for bottom
axis.
"""
if d not in ["left", "right", "top", "bottom"]:
raise ValueError('direction must be on of "left", "right", "top", "bottom"')
self.set_default_alignment(d)
self.set_default_angle(d)
def get_color(self):
return self.get_attribute_from_ref_artist("color", "k")
def draw(self, renderer):
if not self.get_visible():
return
pad = renderer.points_to_pixels(self.get_pad())
r = self._get_external_pad() + pad
self._set_offset_radius(r)
super(AxisLabel, self).draw(renderer)
def get_window_extent(self, renderer):
if not self.get_visible():
return
pad = renderer.points_to_pixels(self.get_pad())
r = self._get_external_pad() + pad
self._set_offset_radius(r)
bb = super(AxisLabel, self).get_window_extent(renderer)
return bb
class TickLabels(AxisLabel, AttributeCopier): # mtext.Text
"""
Tick Labels. While derived from Text, this single artist draws all
ticklabels. As in AxisLabel, the position of the text is updated
in the fly, so changing text position has no effect. Otherwise,
the properties can be changed as a normal Text. Unlike the
ticklabels of the mainline matplotlib, properties of single
ticklabel alone cannot modified.
To change the pad between ticks and ticklabels, use set_pad.
"""
def __init__(self, **kwargs):
axis_direction = kwargs.pop("axis_direction", "bottom")
AxisLabel.__init__(self, **kwargs)
self.set_axis_direction(axis_direction)
#self._axis_direction = axis_direction
self._axislabel_pad = 0
#self._extra_pad = 0
# attribute copier
def get_ref_artist(self):
return self._axis.get_ticklabels()[0]
def set_axis_direction(self, label_direction):
"""
Adjust the text angle and text alignment of ticklabels
according to the matplotlib convention.
The *label_direction* must be one of [left, right, bottom,
top].
===================== ========== ========= ========== ==========
property left bottom right top
===================== ========== ========= ========== ==========
ticklabels angle 90 0 -90 180
ticklabel va center baseline center baseline
ticklabel ha right center right center
===================== ========== ========= ========== ==========
Note that the text angles are actually relative to (90 + angle
of the direction to the ticklabel), which gives 0 for bottom
axis.
"""
if label_direction not in ["left", "right", "top", "bottom"]:
raise ValueError('direction must be one of "left", "right", "top", "bottom"')
self._axis_direction = label_direction
self.set_default_alignment(label_direction)
self.set_default_angle(label_direction)
def invert_axis_direction(self):
label_direction = self._get_opposite_direction(self._axis_direction)
self.set_axis_direction(label_direction)
def _get_ticklabels_offsets(self, renderer, label_direction):
"""
Calculates the offsets of the ticklabels from the tick and
their total heights. The offset only takes account the offset
due to the vertical alignment of the ticklabels, i.e.,if axis
direction is bottom and va is ;top', it will return 0. if va
is 'baseline', it will return (height-descent).
"""
whd_list = self.get_texts_widths_heights_descents(renderer)
if not whd_list:
return 0, 0
r = 0
va, ha = self.get_va(), self.get_ha()
if label_direction == "left":
pad = max(w for w, h, d in whd_list)
if ha == "left":
r = pad
elif ha == "center":
r = .5 * pad
elif label_direction == "right":
pad = max(w for w, h, d in whd_list)
if ha == "right":
r = pad
elif ha == "center":
r = .5 * pad
elif label_direction == "bottom":
pad = max(h for w, h, d in whd_list)
if va == "bottom":
r = pad
elif va == "center":
r =.5 * pad
elif va == "baseline":
max_ascent = max(h - d for w, h, d in whd_list)
max_descent = max(d for w, h, d in whd_list)
r = max_ascent
pad = max_ascent + max_descent
elif label_direction == "top":
pad = max(h for w, h, d in whd_list)
if va == "top":
r = pad
elif va == "center":
r =.5 * pad
elif va == "baseline":
max_ascent = max(h - d for w, h, d in whd_list)
max_descent = max(d for w, h, d in whd_list)
r = max_descent
pad = max_ascent + max_descent
#tick_pad = renderer.points_to_pixels(self.get_pad())
# r : offset
# pad : total height of the ticklabels. This will be used to
# calculate the pad for the axislabel.
return r, pad
_default_alignments = dict(left=("center", "right"),
right=("center", "left"),
bottom=("baseline", "center"),
top=("baseline", "center"))
# set_default_alignments(self, d)
_default_angles = dict(left=90,
right=-90,
bottom=0,
top=180)
def draw(self, renderer):
if not self.get_visible():
self._axislabel_pad = self._get_external_pad()
return
r, total_width = self._get_ticklabels_offsets(renderer,
self._axis_direction)
#self._set_external_pad(r+self._get_external_pad())
pad = self._get_external_pad() + \
renderer.points_to_pixels(self.get_pad())
self._set_offset_radius(r+pad)
#self._set_offset_radius(r)
for (x, y), a, l in self._locs_angles_labels:
if not l.strip(): continue
self._set_ref_angle(a) #+ add_angle
self.set_x(x)
self.set_y(y)
self.set_text(l)
LabelBase.draw(self, renderer)
self._axislabel_pad = total_width \
+ pad # the value saved will be used to draw axislabel.
def set_locs_angles_labels(self, locs_angles_labels):
self._locs_angles_labels = locs_angles_labels
def get_window_extents(self, renderer):
if not self.get_visible():
self._axislabel_pad = self._get_external_pad()
return []
bboxes = []
r, total_width = self._get_ticklabels_offsets(renderer,
self._axis_direction)
pad = self._get_external_pad() + \
renderer.points_to_pixels(self.get_pad())
self._set_offset_radius(r+pad)
for (x, y), a, l in self._locs_angles_labels:
self._set_ref_angle(a) #+ add_angle
self.set_x(x)
self.set_y(y)
self.set_text(l)
bb = LabelBase.get_window_extent(self, renderer)
bboxes.append(bb)
self._axislabel_pad = total_width \
+ pad # the value saved will be used to draw axislabel.
return bboxes
def get_texts_widths_heights_descents(self, renderer):
"""
return a list of width, height, descent for ticklabels.
"""
whd_list = []
for (x, y), a, l in self._locs_angles_labels:
if not l.strip(): continue
clean_line, ismath = self.is_math_text(l)
whd = renderer.get_text_width_height_descent(
clean_line, self._fontproperties, ismath=ismath)
whd_list.append(whd)
return whd_list
class GridlinesCollection(LineCollection):
def __init__(self, *kl, **kwargs):
"""
*which* : "major" or "minor"
*axis* : "both", "x" or "y"
"""
self._which = kwargs.pop("which", "major")
self._axis = kwargs.pop("axis", "both")
super(GridlinesCollection, self).__init__(*kl, **kwargs)
self.set_grid_helper(None)
def set_which(self, which):
self._which = which
def set_axis(self, axis):
self._axis = axis
def set_grid_helper(self, grid_helper):
self._grid_helper = grid_helper
def draw(self, renderer):
if self._grid_helper is not None:
self._grid_helper.update_lim(self.axes)
gl = self._grid_helper.get_gridlines(self._which, self._axis)
if gl:
self.set_segments([np.transpose(l) for l in gl])
else:
self.set_segments([])
super(GridlinesCollection, self).draw(renderer)
class AxisArtist(martist.Artist):
"""
An artist which draws axis (a line along which the n-th axes coord
is constant) line, ticks, ticklabels, and axis label.
"""
ZORDER=2.5
@property
def LABELPAD(self):
return self.label.get_pad()
@LABELPAD.setter
def LABELPAD(self, v):
return self.label.set_pad(v)
def __init__(self, axes,
helper,
offset=None,
axis_direction="bottom",
**kw):
"""
*axes* : axes
*helper* : an AxisArtistHelper instance.
"""
#axes is also used to follow the axis attribute (tick color, etc).
super(AxisArtist, self).__init__(**kw)
self.axes = axes
self._axis_artist_helper = helper
if offset is None:
offset = (0, 0)
self.dpi_transform = Affine2D()
self.offset_transform = ScaledTranslation(offset[0], offset[1],
self.dpi_transform)
self._label_visible = True
self._majortick_visible = True
self._majorticklabel_visible = True
self._minortick_visible = True
self._minorticklabel_visible = True
#if self._axis_artist_helper._loc in ["left", "right"]:
if axis_direction in ["left", "right"]:
axis_name = "ytick"
self.axis = axes.yaxis
else:
axis_name = "xtick"
self.axis = axes.xaxis
self._axisline_style = None
self._axis_direction = axis_direction
self._init_line()
self._init_ticks(axis_name, **kw)
self._init_offsetText(axis_direction)
self._init_label()
self.set_zorder(self.ZORDER)
self._rotate_label_along_line = False
# axis direction
self._tick_add_angle = 180.
self._ticklabel_add_angle = 0.
self._axislabel_add_angle = 0.
self.set_axis_direction(axis_direction)
# axis direction
def set_axis_direction(self, axis_direction):
"""
Adjust the direction, text angle, text alignment of
ticklabels, labels following the matplotlib convention for
the rectangle axes.
The *axis_direction* must be one of [left, right, bottom,
top].
===================== ========== ========= ========== ==========
property left bottom right top
===================== ========== ========= ========== ==========
ticklabels location "-" "+" "+" "-"
axislabel location "-" "+" "+" "-"
ticklabels angle 90 0 -90 180
ticklabel va center baseline center baseline
ticklabel ha right center right center
axislabel angle 180 0 0 180
axislabel va center top center bottom
axislabel ha right center right center
===================== ========== ========= ========== ==========
Note that the direction "+" and "-" are relative to the direction of
the increasing coordinate. Also, the text angles are actually
relative to (90 + angle of the direction to the ticklabel),
which gives 0 for bottom axis.
"""
if axis_direction not in ["left", "right", "top", "bottom"]:
raise ValueError('direction must be on of "left", "right", "top", "bottom"')
self._axis_direction = axis_direction
if axis_direction in ["left", "top"]:
#self._set_tick_direction("+")
self.set_ticklabel_direction("-")
self.set_axislabel_direction("-")
else:
#self._set_tick_direction("-")
self.set_ticklabel_direction("+")
self.set_axislabel_direction("+")
self.major_ticklabels.set_axis_direction(axis_direction)
self.label.set_axis_direction(axis_direction)
# def _set_tick_direction(self, d):
# if d not in ["+", "-"]:
# raise ValueError('direction must be on of "in", "out"')
# if d == "+":
# self._tick_add_angle = 0 #get_helper()._extremes=0, 10
# else:
# self._tick_add_angle = 180 #get_helper()._extremes=0, 10
def set_ticklabel_direction(self, tick_direction):
"""
Adjust the direction of the ticklabel.
ACCEPTS: [ "+" | "-" ]
Note that the label_direction '+' and '-' are relative to the
direction of the increasing coordinate.
"""
if tick_direction not in ["+", "-"]:
raise ValueError('direction must be one of "+", "-"')
if tick_direction == "-":
self._ticklabel_add_angle = 180
else:
self._ticklabel_add_angle = 0
def invert_ticklabel_direction(self):
self._ticklabel_add_angle = (self._ticklabel_add_angle + 180) % 360
self.major_ticklabels.invert_axis_direction()
self.minor_ticklabels.invert_axis_direction()
# def invert_ticks_direction(self):
# self.major_ticks.set_tick_out(not self.major_ticks.get_tick_out())
# self.minor_ticks.set_tick_out(not self.minor_ticks.get_tick_out())
def set_axislabel_direction(self, label_direction):
"""
Adjust the direction of the axislabel.
ACCEPTS: [ "+" | "-" ]
Note that the label_direction '+' and '-' are relative to the
direction of the increasing coordinate.
"""
if label_direction not in ["+", "-"]:
raise ValueError('direction must be one of "+", "-"')
if label_direction == "-":
self._axislabel_add_angle = 180
else:
self._axislabel_add_angle = 0
def get_transform(self):
return self.axes.transAxes + self.offset_transform
def get_helper(self):
"""
Return axis artist helper instance.
"""
return self._axis_artist_helper
def set_axisline_style(self, axisline_style=None, **kw):
"""
Set the axisline style.
*axisline_style* can be a string with axisline style name with optional
comma-separated attributes. Alternatively, the attrs can
be provided as keywords.
set_arrowstyle("->,size=1.5")
set_arrowstyle("->", size=1.5)
Old attrs simply are forgotten.
Without argument (or with arrowstyle=None), return
available styles as a list of strings.
"""
if axisline_style==None:
return AxislineStyle.pprint_styles()
if isinstance(axisline_style, AxislineStyle._Base):
self._axisline_style = axisline_style
else:
self._axisline_style = AxislineStyle(axisline_style, **kw)
self._init_line()
def get_axisline_style(self):
"""
return the current axisline style.
"""
return self._axisline_style
def _init_line(self):
"""
Initialize the *line* artist that is responsible to draw the axis line.
"""
tran = self._axis_artist_helper.get_line_transform(self.axes) \
+ self.offset_transform
axisline_style = self.get_axisline_style()
if axisline_style is None:
self.line = BezierPath(self._axis_artist_helper.get_line(self.axes),
color=rcParams['axes.edgecolor'],
linewidth=rcParams['axes.linewidth'],
transform=tran)
else:
self.line = axisline_style(self, transform=tran)
def _draw_line(self, renderer):
self.line.set_path(self._axis_artist_helper.get_line(self.axes))
if self.get_axisline_style() is not None:
self.line.set_line_mutation_scale(self.major_ticklabels.get_size())
self.line.draw(renderer)
def _init_ticks(self, axis_name, **kw):
trans=self._axis_artist_helper.get_tick_transform(self.axes) \
+ self.offset_transform
major_tick_size = kw.get("major_tick_size",
rcParams['%s.major.size'%axis_name])
major_tick_pad = kw.get("major_tick_pad",
rcParams['%s.major.pad'%axis_name])
minor_tick_size = kw.get("minor_tick_size",
rcParams['%s.minor.size'%axis_name])
minor_tick_pad = kw.get("minor_tick_pad",
rcParams['%s.minor.pad'%axis_name])
self.major_ticks = Ticks(major_tick_size,
axis=self.axis,
transform=trans)
self.minor_ticks = Ticks(minor_tick_size,
axis=self.axis,
transform=trans)
if axis_name == "xaxis":
size = rcParams['xtick.labelsize']
else:
size = rcParams['ytick.labelsize']
fontprops = font_manager.FontProperties(size=size)
self.major_ticklabels = TickLabels(size=size, axis=self.axis,
axis_direction=self._axis_direction)
self.minor_ticklabels = TickLabels(size=size, axis=self.axis,
axis_direction=self._axis_direction)
self.major_ticklabels.set(figure = self.axes.figure,
transform=trans,
fontproperties=fontprops)
self.major_ticklabels.set_pad(major_tick_pad)
self.minor_ticklabels.set(figure = self.axes.figure,
transform=trans,
fontproperties=fontprops)
self.minor_ticklabels.set_pad(minor_tick_pad)
def _get_tick_info(self, tick_iter):
"""
return ticks_loc_angle, ticklabels_loc_angle_label
ticks_loc_angle : list of locs and angles for ticks
ticklabels_loc_angle_label : list of locs, angles and labels for tickslabels
"""
ticks_loc_angle = []
ticklabels_loc_angle_label = []
tick_add_angle = self._tick_add_angle
ticklabel_add_angle = self._ticklabel_add_angle
for loc, angle_normal, angle_tangent, label in tick_iter:
angle_label = angle_tangent - 90
angle_label += ticklabel_add_angle
if np.cos((angle_label - angle_normal)/180.*np.pi) < 0.:
angle_tick = angle_normal
else:
angle_tick = angle_normal + 180
ticks_loc_angle.append([loc, angle_tick])
ticklabels_loc_angle_label.append([loc, angle_label, label])
return ticks_loc_angle, ticklabels_loc_angle_label
def _update_ticks(self, renderer):
# set extra pad for major and minor ticklabels:
# use ticksize of majorticks even for minor ticks. not clear what is best.
dpi_cor = renderer.points_to_pixels(1.)
if self.major_ticks.get_visible() and self.major_ticks.get_tick_out():
self.major_ticklabels._set_external_pad(self.major_ticks._ticksize*dpi_cor)
self.minor_ticklabels._set_external_pad(self.major_ticks._ticksize*dpi_cor)
else:
self.major_ticklabels._set_external_pad(0)
self.minor_ticklabels._set_external_pad(0)
majortick_iter, minortick_iter = \
self._axis_artist_helper.get_tick_iterators(self.axes)
tick_loc_angle, ticklabel_loc_angle_label \
= self._get_tick_info(majortick_iter)
self.major_ticks.set_locs_angles(tick_loc_angle)
self.major_ticklabels.set_locs_angles_labels(ticklabel_loc_angle_label)
#self.major_ticks.draw(renderer)
#self.major_ticklabels.draw(renderer)
# minor ticks
tick_loc_angle, ticklabel_loc_angle_label \
= self._get_tick_info(minortick_iter)
self.minor_ticks.set_locs_angles(tick_loc_angle)
self.minor_ticklabels.set_locs_angles_labels(ticklabel_loc_angle_label)
#self.minor_ticks.draw(renderer)
#self.minor_ticklabels.draw(renderer)
#if (self.major_ticklabels.get_visible() or self.minor_ticklabels.get_visible()):
# self._draw_offsetText(renderer)
return self.major_ticklabels.get_window_extents(renderer)
def _draw_ticks(self, renderer):
extents = self._update_ticks(renderer)
self.major_ticks.draw(renderer)
self.major_ticklabels.draw(renderer)
self.minor_ticks.draw(renderer)
self.minor_ticklabels.draw(renderer)
if (self.major_ticklabels.get_visible() or self.minor_ticklabels.get_visible()):
self._draw_offsetText(renderer)
return extents
def _draw_ticks2(self, renderer):
# set extra pad for major and minor ticklabels:
# use ticksize of majorticks even for minor ticks. not clear what is best.
dpi_cor = renderer.points_to_pixels(1.)
if self.major_ticks.get_visible() and self.major_ticks.get_tick_out():
self.major_ticklabels._set_external_pad(self.major_ticks._ticksize*dpi_cor)
self.minor_ticklabels._set_external_pad(self.major_ticks._ticksize*dpi_cor)
else:
self.major_ticklabels._set_external_pad(0)
self.minor_ticklabels._set_external_pad(0)
majortick_iter, minortick_iter = \
self._axis_artist_helper.get_tick_iterators(self.axes)
tick_loc_angle, ticklabel_loc_angle_label \
= self._get_tick_info(majortick_iter)
self.major_ticks.set_locs_angles(tick_loc_angle)
self.major_ticklabels.set_locs_angles_labels(ticklabel_loc_angle_label)
self.major_ticks.draw(renderer)
self.major_ticklabels.draw(renderer)
# minor ticks
tick_loc_angle, ticklabel_loc_angle_label \
= self._get_tick_info(minortick_iter)
self.minor_ticks.set_locs_angles(tick_loc_angle)
self.minor_ticklabels.set_locs_angles_labels(ticklabel_loc_angle_label)
self.minor_ticks.draw(renderer)
self.minor_ticklabels.draw(renderer)
if (self.major_ticklabels.get_visible() or self.minor_ticklabels.get_visible()):
self._draw_offsetText(renderer)
return self.major_ticklabels.get_window_extents(renderer)
_offsetText_pos = dict(left=(0, 1, "bottom", "right"),
right=(1, 1, "bottom", "left"),
bottom=(1, 0, "top", "right"),
top=(1, 1, "bottom", "right"))
def _init_offsetText(self, direction):
x,y,va,ha = self._offsetText_pos[direction]
self.offsetText = mtext.Annotation("",
xy=(x,y), xycoords="axes fraction",
xytext=(0,0), textcoords="offset points",
#fontproperties = fp,
color = rcParams['xtick.color'],
verticalalignment=va,
horizontalalignment=ha,
)
self.offsetText.set_transform(IdentityTransform())
self.axes._set_artist_props(self.offsetText)
def _update_offsetText(self):
self.offsetText.set_text( self.axis.major.formatter.get_offset() )
self.offsetText.set_size(self.major_ticklabels.get_size())
offset = self.major_ticklabels.get_pad() + self.major_ticklabels.get_size() + 2.
self.offsetText.xyann= (0, offset)
def _draw_offsetText(self, renderer):
self._update_offsetText()
self.offsetText.draw(renderer)
def _init_label(self, **kw):
# x in axes coords, y in display coords (to be updated at draw
# time by _update_label_positions)
labelsize = kw.get("labelsize",
rcParams['axes.labelsize'])
#labelcolor = kw.get("labelcolor",
# rcParams['axes.labelcolor'])
fontprops = font_manager.FontProperties(
size=labelsize,
weight=rcParams['axes.labelweight'])
textprops = dict(fontproperties = fontprops)
#color = labelcolor)
tr = self._axis_artist_helper.get_axislabel_transform(self.axes) \
+ self.offset_transform
self.label = AxisLabel(0, 0, "__from_axes__",
color = "auto", #rcParams['axes.labelcolor'],
fontproperties=fontprops,
axis=self.axis,
transform=tr,
axis_direction=self._axis_direction,
)
self.label.set_figure(self.axes.figure)
labelpad = kw.get("labelpad", 5)
self.label.set_pad(labelpad)
def _update_label(self, renderer):
if not self.label.get_visible():
return
fontprops = font_manager.FontProperties(
size=rcParams['axes.labelsize'],
weight=rcParams['axes.labelweight'])
#pad_points = self.major_tick_pad
#if abs(self._ticklabel_add_angle - self._axislabel_add_angle)%360 > 90:
if self._ticklabel_add_angle != self._axislabel_add_angle:
if (self.major_ticks.get_visible() and not self.major_ticks.get_tick_out()) \
or \
(self.minor_ticks.get_visible() and not self.major_ticks.get_tick_out()):
axislabel_pad = self.major_ticks._ticksize
else:
axislabel_pad = 0
else:
axislabel_pad = max(self.major_ticklabels._axislabel_pad,
self.minor_ticklabels._axislabel_pad)
#label_offset = axislabel_pad + self.LABELPAD
#self.label._set_offset_radius(label_offset)
self.label._set_external_pad(axislabel_pad)
xy, angle_tangent = self._axis_artist_helper.get_axislabel_pos_angle(self.axes)
if xy is None: return
angle_label = angle_tangent - 90
x, y = xy
self.label._set_ref_angle(angle_label+self._axislabel_add_angle)
self.label.set(x=x, y=y)
def _draw_label(self, renderer):
self._update_label(renderer)
self.label.draw(renderer)
def _draw_label2(self, renderer):
if not self.label.get_visible():
return
fontprops = font_manager.FontProperties(
size=rcParams['axes.labelsize'],
weight=rcParams['axes.labelweight'])
#pad_points = self.major_tick_pad
#if abs(self._ticklabel_add_angle - self._axislabel_add_angle)%360 > 90:
if self._ticklabel_add_angle != self._axislabel_add_angle:
if (self.major_ticks.get_visible() and not self.major_ticks.get_tick_out()) \
or \
(self.minor_ticks.get_visible() and not self.major_ticks.get_tick_out()):
axislabel_pad = self.major_ticks._ticksize
else:
axislabel_pad = 0
else:
axislabel_pad = max(self.major_ticklabels._axislabel_pad,
self.minor_ticklabels._axislabel_pad)
#label_offset = axislabel_pad + self.LABELPAD
#self.label._set_offset_radius(label_offset)
self.label._set_external_pad(axislabel_pad)
xy, angle_tangent = self._axis_artist_helper.get_axislabel_pos_angle(self.axes)
if xy is None: return
angle_label = angle_tangent - 90
x, y = xy
self.label._set_ref_angle(angle_label+self._axislabel_add_angle)
self.label.set(x=x, y=y)
self.label.draw(renderer)
def set_label(self, s):
self.label.set_text(s)
def get_tightbbox(self, renderer):
if not self.get_visible(): return
self._axis_artist_helper.update_lim(self.axes)
dpi_cor = renderer.points_to_pixels(1.)
self.dpi_transform.clear().scale(dpi_cor, dpi_cor)
bb = []
self._update_ticks(renderer)
#if self.major_ticklabels.get_visible():
bb.extend(self.major_ticklabels.get_window_extents(renderer))
#if self.minor_ticklabels.get_visible():
bb.extend(self.minor_ticklabels.get_window_extents(renderer))
self._update_label(renderer)
#if self.label.get_visible():
bb.append(self.label.get_window_extent(renderer))
bb.append(self.offsetText.get_window_extent(renderer))
bb = [b for b in bb if b and (b.width!=0 or b.height!=0)]
if bb:
_bbox = Bbox.union(bb)
return _bbox
else:
return None
#self._draw_line(renderer)
#self._draw_ticks(renderer)
#self._draw_offsetText(renderer)
#self._draw_label(renderer)
@allow_rasterization
def draw(self, renderer):
'Draw the axis lines, tick lines and labels'
if not self.get_visible(): return
renderer.open_group(__name__)
self._axis_artist_helper.update_lim(self.axes)
dpi_cor = renderer.points_to_pixels(1.)
self.dpi_transform.clear().scale(dpi_cor, dpi_cor)
self._draw_ticks(renderer)
self._draw_line(renderer)
#self._draw_offsetText(renderer)
self._draw_label(renderer)
renderer.close_group(__name__)
#def get_ticklabel_extents(self, renderer):
# pass
def toggle(self, all=None, ticks=None, ticklabels=None, label=None):
"""
Toggle visibility of ticks, ticklabels, and (axis) label.
To turn all off, ::
axis.toggle(all=False)
To turn all off but ticks on ::
axis.toggle(all=False, ticks=True)
To turn all on but (axis) label off ::
axis.toggle(all=True, label=False))
"""
if all:
_ticks, _ticklabels, _label = True, True, True
elif all is not None:
_ticks, _ticklabels, _label = False, False, False
else:
_ticks, _ticklabels, _label = None, None, None
if ticks is not None:
_ticks = ticks
if ticklabels is not None:
_ticklabels = ticklabels
if label is not None:
_label = label
if _ticks is not None:
self.major_ticks.set_visible(_ticks)
self.minor_ticks.set_visible(_ticks)
if _ticklabels is not None:
self.major_ticklabels.set_visible(_ticklabels)
self.minor_ticklabels.set_visible(_ticklabels)
if _label is not None:
self.label.set_visible(_label)
| 48,594 | 30.782211 | 89 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpl_toolkits/axisartist/clip_path.py
|
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import six
from six.moves import zip
import numpy as np
from math import degrees
import math
import warnings
def atan2(dy, dx):
if dx == 0 and dy == 0:
warnings.warn("dx and dy is 0")
return 0
else:
return math.atan2(dy, dx)
# FIXME : The current algorithm seems to return incorrect angle when the line
# ends at the boundary.
def clip(xlines, ylines, x0, clip="right", xdir=True, ydir=True):
clipped_xlines = []
clipped_ylines = []
_pos_angles = []
if xdir:
xsign = 1
else:
xsign = -1
if ydir:
ysign = 1
else:
ysign = -1
for x, y in zip(xlines, ylines):
if clip in ["up", "right"]:
b = (x < x0).astype("i")
db = b[1:] - b[:-1]
else:
b = (x > x0).astype("i")
db = b[1:] - b[:-1]
if b[0]:
ns = 0
else:
ns = -1
segx, segy = [], []
for (i,) in np.argwhere(db!=0):
c = db[i]
if c == -1:
dx = (x0 - x[i])
dy = (y[i+1] - y[i]) * (dx/ (x[i+1] - x[i]))
y0 = y[i] + dy
clipped_xlines.append(np.concatenate([segx, x[ns:i+1], [x0]]))
clipped_ylines.append(np.concatenate([segy, y[ns:i+1], [y0]]))
ns = -1
segx, segy = [], []
if dx == 0. and dy == 0:
dx = x[i+1] - x[i]
dy = y[i+1] - y[i]
a = degrees(atan2(ysign*dy, xsign*dx))
_pos_angles.append((x0, y0, a))
elif c == 1:
dx = (x0 - x[i])
dy = (y[i+1] - y[i]) * (dx / (x[i+1] - x[i]))
y0 = y[i] + dy
segx, segy = [x0], [y0]
ns = i+1
if dx == 0. and dy == 0:
dx = x[i+1] - x[i]
dy = y[i+1] - y[i]
a = degrees(atan2(ysign*dy, xsign*dx))
_pos_angles.append((x0, y0, a))
if ns != -1:
clipped_xlines.append(np.concatenate([segx, x[ns:]]))
clipped_ylines.append(np.concatenate([segy, y[ns:]]))
#clipped_pos_angles.append(_pos_angles)
return clipped_xlines, clipped_ylines, _pos_angles
def clip_line_to_rect(xline, yline, bbox):
x0, y0, x1, y1 = bbox.extents
xdir = x1 > x0
ydir = y1 > y0
if x1 > x0:
lx1, ly1, c_right_ = clip([xline], [yline], x1, clip="right", xdir=xdir, ydir=ydir)
lx2, ly2, c_left_ = clip(lx1, ly1, x0, clip="left", xdir=xdir, ydir=ydir)
else:
lx1, ly1, c_right_ = clip([xline], [yline], x0, clip="right", xdir=xdir, ydir=ydir)
lx2, ly2, c_left_ = clip(lx1, ly1, x1, clip="left", xdir=xdir, ydir=ydir)
if y1 > y0:
ly3, lx3, c_top_ = clip(ly2, lx2, y1, clip="right", xdir=ydir, ydir=xdir)
ly4, lx4, c_bottom_ = clip(ly3, lx3, y0, clip="left", xdir=ydir, ydir=xdir)
else:
ly3, lx3, c_top_ = clip(ly2, lx2, y0, clip="right", xdir=ydir, ydir=xdir)
ly4, lx4, c_bottom_ = clip(ly3, lx3, y1, clip="left", xdir=ydir, ydir=xdir)
# lx1, ly1, c_right_ = clip([xline], [yline], x1, clip="right")
# lx2, ly2, c_left_ = clip(lx1, ly1, x0, clip="left")
# ly3, lx3, c_top_ = clip(ly2, lx2, y1, clip="right")
# ly4, lx4, c_bottom_ = clip(ly3, lx3, y0, clip="left")
#c_left = [((x, y), (a+90)%180-180) for (x, y, a) in c_left_ \
# if bbox.containsy(y)]
c_left = [((x, y), (a+90)%180-90) for (x, y, a) in c_left_
if bbox.containsy(y)]
c_bottom = [((x, y), (90 - a)%180) for (y, x, a) in c_bottom_
if bbox.containsx(x)]
c_right = [((x, y), (a+90)%180+90) for (x, y, a) in c_right_
if bbox.containsy(y)]
c_top = [((x, y), (90 - a)%180+180) for (y, x, a) in c_top_
if bbox.containsx(x)]
return list(zip(lx4, ly4)), [c_left, c_bottom, c_right, c_top]
| 4,090 | 29.080882 | 91 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpl_toolkits/axisartist/floating_axes.py
|
"""
An experimental support for curvilinear grid.
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import six
from six.moves import zip
# TODO :
# see if tick_iterator method can be simplified by reusing the parent method.
import numpy as np
from matplotlib.transforms import Affine2D, IdentityTransform
from . import grid_helper_curvelinear
from .axislines import AxisArtistHelper, GridHelperBase
from .axis_artist import AxisArtist
from .grid_finder import GridFinder
class FloatingAxisArtistHelper(grid_helper_curvelinear.FloatingAxisArtistHelper):
pass
class FixedAxisArtistHelper(grid_helper_curvelinear.FloatingAxisArtistHelper):
def __init__(self, grid_helper, side, nth_coord_ticks=None):
"""
nth_coord = along which coordinate value varies.
nth_coord = 0 -> x axis, nth_coord = 1 -> y axis
"""
value, nth_coord = grid_helper.get_data_boundary(side) # return v= 0 , nth=1, extremes of the other coordinate.
super(FixedAxisArtistHelper, self).__init__(grid_helper,
nth_coord,
value,
axis_direction=side,
)
#self.grid_helper = grid_helper
if nth_coord_ticks is None:
nth_coord_ticks = nth_coord
self.nth_coord_ticks = nth_coord_ticks
self.value = value
self.grid_helper = grid_helper
self._side = side
def update_lim(self, axes):
self.grid_helper.update_lim(axes)
self.grid_info = self.grid_helper.grid_info
def get_axislabel_pos_angle(self, axes):
extremes = self.grid_info["extremes"]
if self.nth_coord == 0:
xx0 = self.value
yy0 = (extremes[2]+extremes[3])/2.
dxx, dyy = 0., abs(extremes[2]-extremes[3])/1000.
elif self.nth_coord == 1:
xx0 = (extremes[0]+extremes[1])/2.
yy0 = self.value
dxx, dyy = abs(extremes[0]-extremes[1])/1000., 0.
grid_finder = self.grid_helper.grid_finder
xx1, yy1 = grid_finder.transform_xy([xx0], [yy0])
trans_passingthrough_point = axes.transData + axes.transAxes.inverted()
p = trans_passingthrough_point.transform_point([xx1[0], yy1[0]])
if (0. <= p[0] <= 1.) and (0. <= p[1] <= 1.):
xx1c, yy1c = axes.transData.transform_point([xx1[0], yy1[0]])
xx2, yy2 = grid_finder.transform_xy([xx0+dxx], [yy0+dyy])
xx2c, yy2c = axes.transData.transform_point([xx2[0], yy2[0]])
return (xx1c, yy1c), np.arctan2(yy2c-yy1c, xx2c-xx1c)/np.pi*180.
else:
return None, None
def get_tick_transform(self, axes):
return IdentityTransform() #axes.transData
def get_tick_iterators(self, axes):
"""tick_loc, tick_angle, tick_label, (optionally) tick_label"""
grid_finder = self.grid_helper.grid_finder
lat_levs, lat_n, lat_factor = self.grid_info["lat_info"]
lon_levs, lon_n, lon_factor = self.grid_info["lon_info"]
lon_levs, lat_levs = np.asarray(lon_levs), np.asarray(lat_levs)
if lat_factor is not None:
yy0 = lat_levs / lat_factor
dy = 0.001 / lat_factor
else:
yy0 = lat_levs
dy = 0.001
if lon_factor is not None:
xx0 = lon_levs / lon_factor
dx = 0.001 / lon_factor
else:
xx0 = lon_levs
dx = 0.001
_extremes = self.grid_helper._extremes
xmin, xmax = sorted(_extremes[:2])
ymin, ymax = sorted(_extremes[2:])
if self.nth_coord == 0:
mask = (ymin <= yy0) & (yy0 <= ymax)
yy0 = yy0[mask]
elif self.nth_coord == 1:
mask = (xmin <= xx0) & (xx0 <= xmax)
xx0 = xx0[mask]
def transform_xy(x, y):
x1, y1 = grid_finder.transform_xy(x, y)
x2y2 = axes.transData.transform(np.array([x1, y1]).transpose())
x2, y2 = x2y2.transpose()
return x2, y2
# find angles
if self.nth_coord == 0:
xx0 = np.empty_like(yy0)
xx0.fill(self.value)
#yy0_ = yy0.copy()
xx1, yy1 = transform_xy(xx0, yy0)
xx00 = xx0.astype(float, copy=True)
xx00[xx0+dx>xmax] -= dx
xx1a, yy1a = transform_xy(xx00, yy0)
xx1b, yy1b = transform_xy(xx00+dx, yy0)
yy00 = yy0.astype(float, copy=True)
yy00[yy0+dy>ymax] -= dy
xx2a, yy2a = transform_xy(xx0, yy00)
xx2b, yy2b = transform_xy(xx0, yy00+dy)
labels = self.grid_info["lat_labels"]
labels = [l for l, m in zip(labels, mask) if m]
elif self.nth_coord == 1:
yy0 = np.empty_like(xx0)
yy0.fill(self.value)
#xx0_ = xx0.copy()
xx1, yy1 = transform_xy(xx0, yy0)
yy00 = yy0.astype(float, copy=True)
yy00[yy0+dy>ymax] -= dy
xx1a, yy1a = transform_xy(xx0, yy00)
xx1b, yy1b = transform_xy(xx0, yy00+dy)
xx00 = xx0.astype(float, copy=True)
xx00[xx0+dx>xmax] -= dx
xx2a, yy2a = transform_xy(xx00, yy0)
xx2b, yy2b = transform_xy(xx00+dx, yy0)
labels = self.grid_info["lon_labels"]
labels = [l for l, m in zip(labels, mask) if m]
def f1():
dd = np.arctan2(yy1b-yy1a, xx1b-xx1a) # angle normal
dd2 = np.arctan2(yy2b-yy2a, xx2b-xx2a) # angle tangent
mm = ((yy1b-yy1a)==0.) & ((xx1b-xx1a)==0.) # mask where dd1 is not defined
dd[mm] = dd2[mm] + np.pi / 2
#dd += np.pi
#dd = np.arctan2(xx2-xx1, angle_tangent-yy1)
trans_tick = self.get_tick_transform(axes)
tr2ax = trans_tick + axes.transAxes.inverted()
for x, y, d, d2, lab in zip(xx1, yy1, dd, dd2, labels):
c2 = tr2ax.transform_point((x, y))
delta=0.00001
if (0. -delta<= c2[0] <= 1.+delta) and \
(0. -delta<= c2[1] <= 1.+delta):
d1 = d/3.14159*180.
d2 = d2/3.14159*180.
#_mod = (d2-d1+180)%360
#if _mod < 180:
# d1 += 180
##_div, _mod = divmod(d2-d1, 360)
yield [x, y], d1, d2, lab
#, d2/3.14159*180.+da)
return f1(), iter([])
def get_line_transform(self, axes):
return axes.transData
def get_line(self, axes):
self.update_lim(axes)
from matplotlib.path import Path
k, v = dict(left=("lon_lines0", 0),
right=("lon_lines0", 1),
bottom=("lat_lines0", 0),
top=("lat_lines0", 1))[self._side]
xx, yy = self.grid_info[k][v]
return Path(np.column_stack([xx, yy]))
from .grid_finder import ExtremeFinderSimple
class ExtremeFinderFixed(ExtremeFinderSimple):
def __init__(self, extremes):
self._extremes = extremes
def __call__(self, transform_xy, x1, y1, x2, y2):
"""
get extreme values.
x1, y1, x2, y2 in image coordinates (0-based)
nx, ny : number of division in each axis
"""
#lon_min, lon_max, lat_min, lat_max = self._extremes
return self._extremes
class GridHelperCurveLinear(grid_helper_curvelinear.GridHelperCurveLinear):
def __init__(self, aux_trans, extremes,
grid_locator1=None,
grid_locator2=None,
tick_formatter1=None,
tick_formatter2=None):
"""
aux_trans : a transform from the source (curved) coordinate to
target (rectilinear) coordinate. An instance of MPL's Transform
(inverse transform should be defined) or a tuple of two callable
objects which defines the transform and its inverse. The callables
need take two arguments of array of source coordinates and
should return two target coordinates:
e.g., x2, y2 = trans(x1, y1)
"""
self._old_values = None
self._extremes = extremes
extreme_finder = ExtremeFinderFixed(extremes)
super(GridHelperCurveLinear, self).__init__(aux_trans,
extreme_finder,
grid_locator1=grid_locator1,
grid_locator2=grid_locator2,
tick_formatter1=tick_formatter1,
tick_formatter2=tick_formatter2)
# def update_grid_finder(self, aux_trans=None, **kw):
# if aux_trans is not None:
# self.grid_finder.update_transform(aux_trans)
# self.grid_finder.update(**kw)
# self.invalidate()
# def _update(self, x1, x2, y1, y2):
# "bbox in 0-based image coordinates"
# # update wcsgrid
# if self.valid() and self._old_values == (x1, x2, y1, y2):
# return
# self._update_grid(x1, y1, x2, y2)
# self._old_values = (x1, x2, y1, y2)
# self._force_update = False
def get_data_boundary(self, side):
"""
return v= 0 , nth=1
"""
lon1, lon2, lat1, lat2 = self._extremes
return dict(left=(lon1, 0),
right=(lon2, 0),
bottom=(lat1, 1),
top=(lat2, 1))[side]
def new_fixed_axis(self, loc,
nth_coord=None,
axis_direction=None,
offset=None,
axes=None):
if axes is None:
axes = self.axes
if axis_direction is None:
axis_direction = loc
_helper = FixedAxisArtistHelper(self, loc,
nth_coord_ticks=nth_coord)
axisline = AxisArtist(axes, _helper, axis_direction=axis_direction)
axisline.line.set_clip_on(True)
axisline.line.set_clip_box(axisline.axes.bbox)
return axisline
# new_floating_axis will inherit the grid_helper's extremes.
# def new_floating_axis(self, nth_coord,
# value,
# axes=None,
# axis_direction="bottom"
# ):
# axis = super(GridHelperCurveLinear,
# self).new_floating_axis(nth_coord,
# value, axes=axes,
# axis_direction=axis_direction)
# # set extreme values of the axis helper
# if nth_coord == 1:
# axis.get_helper().set_extremes(*self._extremes[:2])
# elif nth_coord == 0:
# axis.get_helper().set_extremes(*self._extremes[2:])
# return axis
def _update_grid(self, x1, y1, x2, y2):
#self.grid_info = self.grid_finder.get_grid_info(x1, y1, x2, y2)
if self.grid_info is None:
self.grid_info = dict()
grid_info = self.grid_info
grid_finder = self.grid_finder
extremes = grid_finder.extreme_finder(grid_finder.inv_transform_xy,
x1, y1, x2, y2)
lon_min, lon_max = sorted(extremes[:2])
lat_min, lat_max = sorted(extremes[2:])
lon_levs, lon_n, lon_factor = \
grid_finder.grid_locator1(lon_min, lon_max)
lat_levs, lat_n, lat_factor = \
grid_finder.grid_locator2(lat_min, lat_max)
grid_info["extremes"] = lon_min, lon_max, lat_min, lat_max #extremes
grid_info["lon_info"] = lon_levs, lon_n, lon_factor
grid_info["lat_info"] = lat_levs, lat_n, lat_factor
grid_info["lon_labels"] = grid_finder.tick_formatter1("bottom",
lon_factor,
lon_levs)
grid_info["lat_labels"] = grid_finder.tick_formatter2("bottom",
lat_factor,
lat_levs)
if lon_factor is None:
lon_values = np.asarray(lon_levs[:lon_n])
else:
lon_values = np.asarray(lon_levs[:lon_n]/lon_factor)
if lat_factor is None:
lat_values = np.asarray(lat_levs[:lat_n])
else:
lat_values = np.asarray(lat_levs[:lat_n]/lat_factor)
lon_values0 = lon_values[(lon_min<lon_values) & (lon_values<lon_max)]
lat_values0 = lat_values[(lat_min<lat_values) & (lat_values<lat_max)]
lon_lines, lat_lines = grid_finder._get_raw_grid_lines(lon_values0,
lat_values0,
lon_min, lon_max,
lat_min, lat_max)
grid_info["lon_lines"] = lon_lines
grid_info["lat_lines"] = lat_lines
lon_lines, lat_lines = grid_finder._get_raw_grid_lines(extremes[:2],
extremes[2:],
*extremes)
#lon_min, lon_max,
# lat_min, lat_max)
grid_info["lon_lines0"] = lon_lines
grid_info["lat_lines0"] = lat_lines
def get_gridlines(self, which="major", axis="both"):
grid_lines = []
if axis in ["both", "x"]:
for gl in self.grid_info["lon_lines"]:
grid_lines.extend([gl])
if axis in ["both", "y"]:
for gl in self.grid_info["lat_lines"]:
grid_lines.extend([gl])
return grid_lines
def get_boundary(self):
"""
return Nx2 array of x,y coordinate of the boundary
"""
x0, x1, y0, y1 = self._extremes
tr = self._aux_trans
xx = np.linspace(x0, x1, 100)
yy0, yy1 = np.empty_like(xx), np.empty_like(xx)
yy0.fill(y0)
yy1.fill(y1)
yy = np.linspace(y0, y1, 100)
xx0, xx1 = np.empty_like(yy), np.empty_like(yy)
xx0.fill(x0)
xx1.fill(x1)
xxx = np.concatenate([xx[:-1], xx1[:-1], xx[-1:0:-1], xx0])
yyy = np.concatenate([yy0[:-1], yy[:-1], yy1[:-1], yy[::-1]])
t = tr.transform(np.array([xxx, yyy]).transpose())
return t
class FloatingAxesBase(object):
def __init__(self, *kl, **kwargs):
grid_helper = kwargs.get("grid_helper", None)
if grid_helper is None:
raise ValueError("FloatingAxes requires grid_helper argument")
if not hasattr(grid_helper, "get_boundary"):
raise ValueError("grid_helper must implement get_boundary method")
self._axes_class_floating.__init__(self, *kl, **kwargs)
self.set_aspect(1.)
self.adjust_axes_lim()
def _gen_axes_patch(self):
"""
Returns the patch used to draw the background of the axes. It
is also used as the clipping path for any data elements on the
axes.
In the standard axes, this is a rectangle, but in other
projections it may not be.
.. note::
Intended to be overridden by new projection types.
"""
import matplotlib.patches as mpatches
grid_helper = self.get_grid_helper()
t = grid_helper.get_boundary()
return mpatches.Polygon(t)
def cla(self):
self._axes_class_floating.cla(self)
#HostAxes.cla(self)
self.patch.set_transform(self.transData)
patch = self._axes_class_floating._gen_axes_patch(self)
patch.set_figure(self.figure)
patch.set_visible(False)
patch.set_transform(self.transAxes)
self.patch.set_clip_path(patch)
self.gridlines.set_clip_path(patch)
self._original_patch = patch
def adjust_axes_lim(self):
#t = self.get_boundary()
grid_helper = self.get_grid_helper()
t = grid_helper.get_boundary()
x, y = t[:,0], t[:,1]
xmin, xmax = min(x), max(x)
ymin, ymax = min(y), max(y)
dx = (xmax-xmin)/100.
dy = (ymax-ymin)/100.
self.set_xlim(xmin-dx, xmax+dx)
self.set_ylim(ymin-dy, ymax+dy)
_floatingaxes_classes = {}
def floatingaxes_class_factory(axes_class):
new_class = _floatingaxes_classes.get(axes_class)
if new_class is None:
new_class = type(str("Floating %s" % (axes_class.__name__)),
(FloatingAxesBase, axes_class),
{'_axes_class_floating': axes_class})
_floatingaxes_classes[axes_class] = new_class
return new_class
from .axislines import Axes
from mpl_toolkits.axes_grid1.parasite_axes import host_axes_class_factory
FloatingAxes = floatingaxes_class_factory(host_axes_class_factory(Axes))
import matplotlib.axes as maxes
FloatingSubplot = maxes.subplot_class_factory(FloatingAxes)
| 17,497 | 31.106422 | 119 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpl_toolkits/axisartist/__init__.py
|
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import six
from .axislines import (
Axes, AxesZero, AxisArtistHelper, AxisArtistHelperRectlinear,
GridHelperBase, GridHelperRectlinear, Subplot, SubplotZero)
from .axis_artist import AxisArtist, GridlinesCollection
from .grid_helper_curvelinear import GridHelperCurveLinear
from .floating_axes import FloatingAxes, FloatingSubplot
from mpl_toolkits.axes_grid1.parasite_axes import (
host_axes_class_factory, parasite_axes_class_factory,
parasite_axes_auxtrans_class_factory, subplot_class_factory)
ParasiteAxes = parasite_axes_class_factory(Axes)
ParasiteAxesAuxTrans = \
parasite_axes_auxtrans_class_factory(axes_class=ParasiteAxes)
HostAxes = host_axes_class_factory(axes_class=Axes)
SubplotHost = subplot_class_factory(HostAxes)
| 870 | 31.259259 | 66 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpl_toolkits/axisartist/axes_divider.py
|
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from mpl_toolkits.axes_grid1.axes_divider import (
Divider, AxesLocator, SubplotDivider, AxesDivider, locatable_axes_factory,
make_axes_locatable)
from mpl_toolkits.axes_grid.axislines import Axes
LocatableAxes = locatable_axes_factory(Axes)
| 361 | 35.2 | 78 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpl_toolkits/axisartist/axes_rgb.py
|
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from mpl_toolkits.axes_grid1.axes_rgb import (
make_rgb_axes, imshow_rgb, RGBAxesBase)
from .axislines import Axes
class RGBAxes(RGBAxesBase):
_defaultAxesClass = Axes
| 289 | 23.166667 | 66 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpl_toolkits/axisartist/grid_finder.py
|
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import six
import numpy as np
from matplotlib.transforms import Bbox
from . import clip_path
clip_line_to_rect = clip_path.clip_line_to_rect
import matplotlib.ticker as mticker
from matplotlib.transforms import Transform
# extremes finder
class ExtremeFinderSimple(object):
def __init__(self, nx, ny):
self.nx, self.ny = nx, ny
def __call__(self, transform_xy, x1, y1, x2, y2):
"""
get extreme values.
x1, y1, x2, y2 in image coordinates (0-based)
nx, ny : number of division in each axis
"""
x_, y_ = np.linspace(x1, x2, self.nx), np.linspace(y1, y2, self.ny)
x, y = np.meshgrid(x_, y_)
lon, lat = transform_xy(np.ravel(x), np.ravel(y))
lon_min, lon_max = lon.min(), lon.max()
lat_min, lat_max = lat.min(), lat.max()
return self._add_pad(lon_min, lon_max, lat_min, lat_max)
def _add_pad(self, lon_min, lon_max, lat_min, lat_max):
""" a small amount of padding is added because the current
clipping algorithms seems to fail when the gridline ends at
the bbox boundary.
"""
dlon = (lon_max - lon_min) / self.nx
dlat = (lat_max - lat_min) / self.ny
lon_min, lon_max = lon_min - dlon, lon_max + dlon
lat_min, lat_max = lat_min - dlat, lat_max + dlat
return lon_min, lon_max, lat_min, lat_max
class GridFinderBase(object):
def __init__(self,
extreme_finder,
grid_locator1,
grid_locator2,
tick_formatter1=None,
tick_formatter2=None):
"""
the transData of the axes to the world coordinate.
locator1, locator2 : grid locator for 1st and 2nd axis.
Derived must define "transform_xy, inv_transform_xy"
(may use update_transform)
"""
super(GridFinderBase, self).__init__()
self.extreme_finder = extreme_finder
self.grid_locator1 = grid_locator1
self.grid_locator2 = grid_locator2
self.tick_formatter1 = tick_formatter1
self.tick_formatter2 = tick_formatter2
def get_grid_info(self,
x1, y1, x2, y2):
"""
lon_values, lat_values : list of grid values. if integer is given,
rough number of grids in each direction.
"""
extremes = self.extreme_finder(self.inv_transform_xy, x1, y1, x2, y2)
# min & max rage of lat (or lon) for each grid line will be drawn.
# i.e., gridline of lon=0 will be drawn from lat_min to lat_max.
lon_min, lon_max, lat_min, lat_max = extremes
lon_levs, lon_n, lon_factor = \
self.grid_locator1(lon_min, lon_max)
lat_levs, lat_n, lat_factor = \
self.grid_locator2(lat_min, lat_max)
if lon_factor is None:
lon_values = np.asarray(lon_levs[:lon_n])
else:
lon_values = np.asarray(lon_levs[:lon_n]/lon_factor)
if lat_factor is None:
lat_values = np.asarray(lat_levs[:lat_n])
else:
lat_values = np.asarray(lat_levs[:lat_n]/lat_factor)
lon_lines, lat_lines = self._get_raw_grid_lines(lon_values,
lat_values,
lon_min, lon_max,
lat_min, lat_max)
ddx = (x2-x1)*1.e-10
ddy = (y2-y1)*1.e-10
bb = Bbox.from_extents(x1-ddx, y1-ddy, x2+ddx, y2+ddy)
grid_info = {}
grid_info["extremes"] = extremes
grid_info["lon_lines"] = lon_lines
grid_info["lat_lines"] = lat_lines
grid_info["lon"] = self._clip_grid_lines_and_find_ticks(lon_lines,
lon_values,
lon_levs,
bb)
grid_info["lat"] = self._clip_grid_lines_and_find_ticks(lat_lines,
lat_values,
lat_levs,
bb)
tck_labels = grid_info["lon"]["tick_labels"] = dict()
for direction in ["left", "bottom", "right", "top"]:
levs = grid_info["lon"]["tick_levels"][direction]
tck_labels[direction] = self.tick_formatter1(direction,
lon_factor, levs)
tck_labels = grid_info["lat"]["tick_labels"] = dict()
for direction in ["left", "bottom", "right", "top"]:
levs = grid_info["lat"]["tick_levels"][direction]
tck_labels[direction] = self.tick_formatter2(direction,
lat_factor, levs)
return grid_info
def _get_raw_grid_lines(self,
lon_values, lat_values,
lon_min, lon_max, lat_min, lat_max):
lons_i = np.linspace(lon_min, lon_max, 100) # for interpolation
lats_i = np.linspace(lat_min, lat_max, 100)
lon_lines = [self.transform_xy(np.zeros_like(lats_i) + lon, lats_i)
for lon in lon_values]
lat_lines = [self.transform_xy(lons_i, np.zeros_like(lons_i) + lat)
for lat in lat_values]
return lon_lines, lat_lines
def _clip_grid_lines_and_find_ticks(self, lines, values, levs, bb):
gi = dict()
gi["values"] = []
gi["levels"] = []
gi["tick_levels"] = dict(left=[], bottom=[], right=[], top=[])
gi["tick_locs"] = dict(left=[], bottom=[], right=[], top=[])
gi["lines"] = []
tck_levels = gi["tick_levels"]
tck_locs = gi["tick_locs"]
for (lx, ly), v, lev in zip(lines, values, levs):
xy, tcks = clip_line_to_rect(lx, ly, bb)
if not xy:
continue
gi["levels"].append(v)
gi["lines"].append(xy)
for tck, direction in zip(tcks,
["left", "bottom", "right", "top"]):
for t in tck:
tck_levels[direction].append(lev)
tck_locs[direction].append(t)
return gi
def update_transform(self, aux_trans):
if isinstance(aux_trans, Transform):
def transform_xy(x, y):
x, y = np.asarray(x), np.asarray(y)
ll1 = np.concatenate((x[:,np.newaxis], y[:,np.newaxis]), 1)
ll2 = aux_trans.transform(ll1)
lon, lat = ll2[:,0], ll2[:,1]
return lon, lat
def inv_transform_xy(x, y):
x, y = np.asarray(x), np.asarray(y)
ll1 = np.concatenate((x[:,np.newaxis], y[:,np.newaxis]), 1)
ll2 = aux_trans.inverted().transform(ll1)
lon, lat = ll2[:,0], ll2[:,1]
return lon, lat
else:
transform_xy, inv_transform_xy = aux_trans
self.transform_xy = transform_xy
self.inv_transform_xy = inv_transform_xy
def update(self, **kw):
for k in kw:
if k in ["extreme_finder",
"grid_locator1",
"grid_locator2",
"tick_formatter1",
"tick_formatter2"]:
setattr(self, k, kw[k])
else:
raise ValueError("unknown update property '%s'" % k)
class GridFinder(GridFinderBase):
def __init__(self,
transform,
extreme_finder=None,
grid_locator1=None,
grid_locator2=None,
tick_formatter1=None,
tick_formatter2=None):
"""
transform : transform from the image coordinate (which will be
the transData of the axes to the world coordinate.
or transform = (transform_xy, inv_transform_xy)
locator1, locator2 : grid locator for 1st and 2nd axis.
"""
if extreme_finder is None:
extreme_finder = ExtremeFinderSimple(20, 20)
if grid_locator1 is None:
grid_locator1 = MaxNLocator()
if grid_locator2 is None:
grid_locator2 = MaxNLocator()
if tick_formatter1 is None:
tick_formatter1 = FormatterPrettyPrint()
if tick_formatter2 is None:
tick_formatter2 = FormatterPrettyPrint()
super(GridFinder, self).__init__(
extreme_finder,
grid_locator1,
grid_locator2,
tick_formatter1,
tick_formatter2)
self.update_transform(transform)
class MaxNLocator(mticker.MaxNLocator):
def __init__(self, nbins=10, steps=None,
trim=True,
integer=False,
symmetric=False,
prune=None):
# trim argument has no effect. It has been left for API compatibility
mticker.MaxNLocator.__init__(self, nbins, steps=steps,
integer=integer,
symmetric=symmetric, prune=prune)
self.create_dummy_axis()
self._factor = None
def __call__(self, v1, v2):
if self._factor is not None:
self.set_bounds(v1*self._factor, v2*self._factor)
locs = mticker.MaxNLocator.__call__(self)
return np.array(locs), len(locs), self._factor
else:
self.set_bounds(v1, v2)
locs = mticker.MaxNLocator.__call__(self)
return np.array(locs), len(locs), None
def set_factor(self, f):
self._factor = f
class FixedLocator(object):
def __init__(self, locs):
self._locs = locs
self._factor = None
def __call__(self, v1, v2):
if self._factor is None:
v1, v2 = sorted([v1, v2])
else:
v1, v2 = sorted([v1*self._factor, v2*self._factor])
locs = np.array([l for l in self._locs if ((v1 <= l) and (l <= v2))])
return locs, len(locs), self._factor
def set_factor(self, f):
self._factor = f
# Tick Formatter
class FormatterPrettyPrint(object):
def __init__(self, useMathText=True):
self._fmt = mticker.ScalarFormatter(
useMathText=useMathText, useOffset=False)
self._fmt.create_dummy_axis()
self._ignore_factor = True
def __call__(self, direction, factor, values):
if not self._ignore_factor:
if factor is None:
factor = 1.
values = [v/factor for v in values]
#values = [v for v in values]
self._fmt.set_locs(values)
return [self._fmt(v) for v in values]
class DictFormatter(object):
def __init__(self, format_dict, formatter=None):
"""
format_dict : dictionary for format strings to be used.
formatter : fall-back formatter
"""
super(DictFormatter, self).__init__()
self._format_dict = format_dict
self._fallback_formatter = formatter
def __call__(self, direction, factor, values):
"""
factor is ignored if value is found in the dictionary
"""
if self._fallback_formatter:
fallback_strings = self._fallback_formatter(
direction, factor, values)
else:
fallback_strings = [""]*len(values)
r = [self._format_dict.get(k, v) for k, v in zip(values,
fallback_strings)]
return r
| 11,863 | 33.791789 | 77 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpl_toolkits/axisartist/axisline_style.py
|
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import six
from matplotlib.patches import _Style, FancyArrowPatch
from matplotlib.transforms import IdentityTransform
from matplotlib.path import Path
import numpy as np
class _FancyAxislineStyle(object):
class SimpleArrow(FancyArrowPatch):
"""
The artist class that will be returned for SimpleArrow style.
"""
_ARROW_STYLE = "->"
def __init__(self, axis_artist, line_path, transform,
line_mutation_scale):
self._axis_artist = axis_artist
self._line_transform = transform
self._line_path = line_path
self._line_mutation_scale = line_mutation_scale
FancyArrowPatch.__init__(self,
path=self._line_path,
arrowstyle=self._ARROW_STYLE,
arrow_transmuter=None,
patchA=None,
patchB=None,
shrinkA=0.,
shrinkB=0.,
mutation_scale=line_mutation_scale,
mutation_aspect=None,
transform=IdentityTransform(),
)
def set_line_mutation_scale(self, scale):
self.set_mutation_scale(scale*self._line_mutation_scale)
def _extend_path(self, path, mutation_size=10):
"""
Extend the path to make a room for drawing arrow.
"""
from matplotlib.bezier import get_cos_sin
x0, y0 = path.vertices[-2]
x1, y1 = path.vertices[-1]
cost, sint = get_cos_sin(x0, y0, x1, y1)
d = mutation_size * 1.
x2, y2 = x1 + cost*d, y1+sint*d
if path.codes is None:
_path = Path(np.concatenate([path.vertices, [[x2, y2]]]))
else:
_path = Path(np.concatenate([path.vertices, [[x2, y2]]]),
np.concatenate([path.codes, [Path.LINETO]]))
return _path
def set_path(self, path):
self._line_path = path
def draw(self, renderer):
"""
Draw the axis line.
1) transform the path to the display coordinate.
2) extend the path to make a room for arrow
3) update the path of the FancyArrowPatch.
4) draw
"""
path_in_disp = self._line_transform.transform_path(self._line_path)
mutation_size = self.get_mutation_scale() #line_mutation_scale()
extented_path = self._extend_path(path_in_disp,
mutation_size=mutation_size)
self._path_original = extented_path
FancyArrowPatch.draw(self, renderer)
class FilledArrow(SimpleArrow):
"""
The artist class that will be returned for SimpleArrow style.
"""
_ARROW_STYLE = "-|>"
class AxislineStyle(_Style):
"""
:class:`AxislineStyle` is a container class which defines style classes
for AxisArtists.
An instance of any axisline style class is an callable object,
whose call signature is ::
__call__(self, axis_artist, path, transform)
When called, this should return a mpl artist with following
methods implemented. ::
def set_path(self, path):
# set the path for axisline.
def set_line_mutation_scale(self, scale):
# set the scale
def draw(self, renderer):
# draw
"""
_style_list = {}
class _Base(object):
# The derived classes are required to be able to be initialized
# w/o arguments, i.e., all its argument (except self) must have
# the default values.
def __init__(self):
"""
initialization.
"""
super(AxislineStyle._Base, self).__init__()
def __call__(self, axis_artist, transform):
"""
Given the AxisArtist instance, and transform for the path
(set_path method), return the mpl artist for drawing the axis line.
"""
return self.new_line(axis_artist, transform)
class SimpleArrow(_Base):
"""
A simple arrow.
"""
ArrowAxisClass = _FancyAxislineStyle.SimpleArrow
def __init__(self, size=1):
"""
*size*
size of the arrow as a fraction of the ticklabel size.
"""
self.size = size
super(AxislineStyle.SimpleArrow, self).__init__()
def new_line(self, axis_artist, transform):
linepath = Path([(0,0), (0, 1)])
axisline = self.ArrowAxisClass(axis_artist, linepath, transform,
line_mutation_scale=self.size)
return axisline
_style_list["->"] = SimpleArrow
class FilledArrow(SimpleArrow):
ArrowAxisClass = _FancyAxislineStyle.FilledArrow
_style_list["-|>"] = FilledArrow
| 5,285 | 30.278107 | 79 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpl_toolkits/mplot3d/art3d.py
|
# art3d.py, original mplot3d version by John Porter
# Parts rewritten by Reinier Heeres <reinier@heeres.eu>
# Minor additions by Ben Axelrod <baxelrod@coroware.com>
'''
Module containing 3D artist code and functions to convert 2D
artists into 3D versions which can be added to an Axes3D.
'''
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import six
from six.moves import zip
import math
import numpy as np
from matplotlib import (
artist, cbook, colors as mcolors, lines, text as mtext, path as mpath)
from matplotlib.cbook import _backports
from matplotlib.collections import (
Collection, LineCollection, PolyCollection, PatchCollection,
PathCollection)
from matplotlib.colors import Normalize
from matplotlib.patches import Patch
from . import proj3d
def norm_angle(a):
"""Return angle between -180 and +180"""
a = (a + 360) % 360
if a > 180:
a = a - 360
return a
def norm_text_angle(a):
"""Return angle between -90 and +90"""
a = (a + 180) % 180
if a > 90:
a = a - 180
return a
def get_dir_vector(zdir):
if zdir == 'x':
return np.array((1, 0, 0))
elif zdir == 'y':
return np.array((0, 1, 0))
elif zdir == 'z':
return np.array((0, 0, 1))
elif zdir is None:
return np.array((0, 0, 0))
elif cbook.iterable(zdir) and len(zdir) == 3:
return zdir
else:
raise ValueError("'x', 'y', 'z', None or vector of length 3 expected")
class Text3D(mtext.Text):
'''
Text object with 3D position and (in the future) direction.
'''
def __init__(self, x=0, y=0, z=0, text='', zdir='z', **kwargs):
'''
*x*, *y*, *z* Position of text
*text* Text string to display
*zdir* Direction of text
Keyword arguments are passed onto :func:`~matplotlib.text.Text`.
'''
mtext.Text.__init__(self, x, y, text, **kwargs)
self.set_3d_properties(z, zdir)
def set_3d_properties(self, z=0, zdir='z'):
x, y = self.get_position()
self._position3d = np.array((x, y, z))
self._dir_vec = get_dir_vector(zdir)
self.stale = True
def draw(self, renderer):
proj = proj3d.proj_trans_points(
[self._position3d, self._position3d + self._dir_vec], renderer.M)
dx = proj[0][1] - proj[0][0]
dy = proj[1][1] - proj[1][0]
if dx==0. and dy==0.:
# atan2 raises ValueError: math domain error on 0,0
angle = 0.
else:
angle = math.degrees(math.atan2(dy, dx))
self.set_position((proj[0][0], proj[1][0]))
self.set_rotation(norm_text_angle(angle))
mtext.Text.draw(self, renderer)
self.stale = False
def text_2d_to_3d(obj, z=0, zdir='z'):
"""Convert a Text to a Text3D object."""
obj.__class__ = Text3D
obj.set_3d_properties(z, zdir)
class Line3D(lines.Line2D):
'''
3D line object.
'''
def __init__(self, xs, ys, zs, *args, **kwargs):
'''
Keyword arguments are passed onto :func:`~matplotlib.lines.Line2D`.
'''
lines.Line2D.__init__(self, [], [], *args, **kwargs)
self._verts3d = xs, ys, zs
def set_3d_properties(self, zs=0, zdir='z'):
xs = self.get_xdata()
ys = self.get_ydata()
try:
# If *zs* is a list or array, then this will fail and
# just proceed to juggle_axes().
zs = float(zs)
zs = [zs for x in xs]
except TypeError:
pass
self._verts3d = juggle_axes(xs, ys, zs, zdir)
self.stale = True
def draw(self, renderer):
xs3d, ys3d, zs3d = self._verts3d
xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)
self.set_data(xs, ys)
lines.Line2D.draw(self, renderer)
self.stale = False
def line_2d_to_3d(line, zs=0, zdir='z'):
'''
Convert a 2D line to 3D.
'''
line.__class__ = Line3D
line.set_3d_properties(zs, zdir)
def path_to_3d_segment(path, zs=0, zdir='z'):
'''Convert a path to a 3D segment.'''
zs = _backports.broadcast_to(zs, len(path))
pathsegs = path.iter_segments(simplify=False, curves=False)
seg = [(x, y, z) for (((x, y), code), z) in zip(pathsegs, zs)]
seg3d = [juggle_axes(x, y, z, zdir) for (x, y, z) in seg]
return seg3d
def paths_to_3d_segments(paths, zs=0, zdir='z'):
'''
Convert paths from a collection object to 3D segments.
'''
zs = _backports.broadcast_to(zs, len(paths))
segs = [path_to_3d_segment(path, pathz, zdir)
for path, pathz in zip(paths, zs)]
return segs
def path_to_3d_segment_with_codes(path, zs=0, zdir='z'):
'''Convert a path to a 3D segment with path codes.'''
zs = _backports.broadcast_to(zs, len(path))
seg = []
codes = []
pathsegs = path.iter_segments(simplify=False, curves=False)
for (((x, y), code), z) in zip(pathsegs, zs):
seg.append((x, y, z))
codes.append(code)
seg3d = [juggle_axes(x, y, z, zdir) for (x, y, z) in seg]
return seg3d, codes
def paths_to_3d_segments_with_codes(paths, zs=0, zdir='z'):
'''
Convert paths from a collection object to 3D segments with path codes.
'''
zs = _backports.broadcast_to(zs, len(paths))
segments = []
codes_list = []
for path, pathz in zip(paths, zs):
segs, codes = path_to_3d_segment_with_codes(path, pathz, zdir)
segments.append(segs)
codes_list.append(codes)
return segments, codes_list
class Line3DCollection(LineCollection):
'''
A collection of 3D lines.
'''
def __init__(self, segments, *args, **kwargs):
'''
Keyword arguments are passed onto :func:`~matplotlib.collections.LineCollection`.
'''
LineCollection.__init__(self, segments, *args, **kwargs)
def set_sort_zpos(self, val):
'''Set the position to use for z-sorting.'''
self._sort_zpos = val
self.stale = True
def set_segments(self, segments):
'''
Set 3D segments
'''
self._segments3d = np.asanyarray(segments)
LineCollection.set_segments(self, [])
def do_3d_projection(self, renderer):
'''
Project the points according to renderer matrix.
'''
xyslist = [
proj3d.proj_trans_points(points, renderer.M) for points in
self._segments3d]
segments_2d = [np.column_stack([xs, ys]) for xs, ys, zs in xyslist]
LineCollection.set_segments(self, segments_2d)
# FIXME
minz = 1e9
for xs, ys, zs in xyslist:
minz = min(minz, min(zs))
return minz
def draw(self, renderer, project=False):
if project:
self.do_3d_projection(renderer)
LineCollection.draw(self, renderer)
def line_collection_2d_to_3d(col, zs=0, zdir='z'):
"""Convert a LineCollection to a Line3DCollection object."""
segments3d = paths_to_3d_segments(col.get_paths(), zs, zdir)
col.__class__ = Line3DCollection
col.set_segments(segments3d)
class Patch3D(Patch):
'''
3D patch object.
'''
def __init__(self, *args, **kwargs):
zs = kwargs.pop('zs', [])
zdir = kwargs.pop('zdir', 'z')
Patch.__init__(self, *args, **kwargs)
self.set_3d_properties(zs, zdir)
def set_3d_properties(self, verts, zs=0, zdir='z'):
zs = _backports.broadcast_to(zs, len(verts))
self._segment3d = [juggle_axes(x, y, z, zdir)
for ((x, y), z) in zip(verts, zs)]
self._facecolor3d = Patch.get_facecolor(self)
def get_path(self):
return self._path2d
def get_facecolor(self):
return self._facecolor2d
def do_3d_projection(self, renderer):
s = self._segment3d
xs, ys, zs = zip(*s)
vxs, vys, vzs, vis = proj3d.proj_transform_clip(xs, ys, zs, renderer.M)
self._path2d = mpath.Path(np.column_stack([vxs, vys]))
# FIXME: coloring
self._facecolor2d = self._facecolor3d
return min(vzs)
def draw(self, renderer):
Patch.draw(self, renderer)
class PathPatch3D(Patch3D):
'''
3D PathPatch object.
'''
def __init__(self, path, **kwargs):
zs = kwargs.pop('zs', [])
zdir = kwargs.pop('zdir', 'z')
Patch.__init__(self, **kwargs)
self.set_3d_properties(path, zs, zdir)
def set_3d_properties(self, path, zs=0, zdir='z'):
Patch3D.set_3d_properties(self, path.vertices, zs=zs, zdir=zdir)
self._code3d = path.codes
def do_3d_projection(self, renderer):
s = self._segment3d
xs, ys, zs = zip(*s)
vxs, vys, vzs, vis = proj3d.proj_transform_clip(xs, ys, zs, renderer.M)
self._path2d = mpath.Path(np.column_stack([vxs, vys]), self._code3d)
# FIXME: coloring
self._facecolor2d = self._facecolor3d
return min(vzs)
def get_patch_verts(patch):
"""Return a list of vertices for the path of a patch."""
trans = patch.get_patch_transform()
path = patch.get_path()
polygons = path.to_polygons(trans)
if len(polygons):
return polygons[0]
else:
return []
def patch_2d_to_3d(patch, z=0, zdir='z'):
"""Convert a Patch to a Patch3D object."""
verts = get_patch_verts(patch)
patch.__class__ = Patch3D
patch.set_3d_properties(verts, z, zdir)
def pathpatch_2d_to_3d(pathpatch, z=0, zdir='z'):
"""Convert a PathPatch to a PathPatch3D object."""
path = pathpatch.get_path()
trans = pathpatch.get_patch_transform()
mpath = trans.transform_path(path)
pathpatch.__class__ = PathPatch3D
pathpatch.set_3d_properties(mpath, z, zdir)
class Patch3DCollection(PatchCollection):
'''
A collection of 3D patches.
'''
def __init__(self, *args, **kwargs):
"""
Create a collection of flat 3D patches with its normal vector
pointed in *zdir* direction, and located at *zs* on the *zdir*
axis. 'zs' can be a scalar or an array-like of the same length as
the number of patches in the collection.
Constructor arguments are the same as for
:class:`~matplotlib.collections.PatchCollection`. In addition,
keywords *zs=0* and *zdir='z'* are available.
Also, the keyword argument "depthshade" is available to
indicate whether or not to shade the patches in order to
give the appearance of depth (default is *True*).
This is typically desired in scatter plots.
"""
zs = kwargs.pop('zs', 0)
zdir = kwargs.pop('zdir', 'z')
self._depthshade = kwargs.pop('depthshade', True)
PatchCollection.__init__(self, *args, **kwargs)
self.set_3d_properties(zs, zdir)
def set_sort_zpos(self, val):
'''Set the position to use for z-sorting.'''
self._sort_zpos = val
self.stale = True
def set_3d_properties(self, zs, zdir):
# Force the collection to initialize the face and edgecolors
# just in case it is a scalarmappable with a colormap.
self.update_scalarmappable()
offsets = self.get_offsets()
if len(offsets) > 0:
xs, ys = zip(*offsets)
else:
xs = []
ys = []
self._offsets3d = juggle_axes(xs, ys, np.atleast_1d(zs), zdir)
self._facecolor3d = self.get_facecolor()
self._edgecolor3d = self.get_edgecolor()
self.stale = True
def do_3d_projection(self, renderer):
xs, ys, zs = self._offsets3d
vxs, vys, vzs, vis = proj3d.proj_transform_clip(xs, ys, zs, renderer.M)
fcs = (zalpha(self._facecolor3d, vzs) if self._depthshade else
self._facecolor3d)
fcs = mcolors.to_rgba_array(fcs, self._alpha)
self.set_facecolors(fcs)
ecs = (zalpha(self._edgecolor3d, vzs) if self._depthshade else
self._edgecolor3d)
ecs = mcolors.to_rgba_array(ecs, self._alpha)
self.set_edgecolors(ecs)
PatchCollection.set_offsets(self, np.column_stack([vxs, vys]))
if vzs.size > 0:
return min(vzs)
else:
return np.nan
class Path3DCollection(PathCollection):
'''
A collection of 3D paths.
'''
def __init__(self, *args, **kwargs):
"""
Create a collection of flat 3D paths with its normal vector
pointed in *zdir* direction, and located at *zs* on the *zdir*
axis. 'zs' can be a scalar or an array-like of the same length as
the number of paths in the collection.
Constructor arguments are the same as for
:class:`~matplotlib.collections.PathCollection`. In addition,
keywords *zs=0* and *zdir='z'* are available.
Also, the keyword argument "depthshade" is available to
indicate whether or not to shade the patches in order to
give the appearance of depth (default is *True*).
This is typically desired in scatter plots.
"""
zs = kwargs.pop('zs', 0)
zdir = kwargs.pop('zdir', 'z')
self._depthshade = kwargs.pop('depthshade', True)
PathCollection.__init__(self, *args, **kwargs)
self.set_3d_properties(zs, zdir)
def set_sort_zpos(self, val):
'''Set the position to use for z-sorting.'''
self._sort_zpos = val
self.stale = True
def set_3d_properties(self, zs, zdir):
# Force the collection to initialize the face and edgecolors
# just in case it is a scalarmappable with a colormap.
self.update_scalarmappable()
offsets = self.get_offsets()
if len(offsets) > 0:
xs, ys = zip(*offsets)
else:
xs = []
ys = []
self._offsets3d = juggle_axes(xs, ys, np.atleast_1d(zs), zdir)
self._facecolor3d = self.get_facecolor()
self._edgecolor3d = self.get_edgecolor()
self.stale = True
def do_3d_projection(self, renderer):
xs, ys, zs = self._offsets3d
vxs, vys, vzs, vis = proj3d.proj_transform_clip(xs, ys, zs, renderer.M)
fcs = (zalpha(self._facecolor3d, vzs) if self._depthshade else
self._facecolor3d)
fcs = mcolors.to_rgba_array(fcs, self._alpha)
self.set_facecolors(fcs)
ecs = (zalpha(self._edgecolor3d, vzs) if self._depthshade else
self._edgecolor3d)
ecs = mcolors.to_rgba_array(ecs, self._alpha)
self.set_edgecolors(ecs)
PathCollection.set_offsets(self, np.column_stack([vxs, vys]))
if vzs.size > 0 :
return min(vzs)
else :
return np.nan
def patch_collection_2d_to_3d(col, zs=0, zdir='z', depthshade=True):
"""
Convert a :class:`~matplotlib.collections.PatchCollection` into a
:class:`Patch3DCollection` object
(or a :class:`~matplotlib.collections.PathCollection` into a
:class:`Path3DCollection` object).
Keywords:
*za* The location or locations to place the patches in the
collection along the *zdir* axis. Defaults to 0.
*zdir* The axis in which to place the patches. Default is "z".
*depthshade* Whether to shade the patches to give a sense of depth.
Defaults to *True*.
"""
if isinstance(col, PathCollection):
col.__class__ = Path3DCollection
elif isinstance(col, PatchCollection):
col.__class__ = Patch3DCollection
col._depthshade = depthshade
col.set_3d_properties(zs, zdir)
class Poly3DCollection(PolyCollection):
'''
A collection of 3D polygons.
'''
def __init__(self, verts, *args, **kwargs):
'''
Create a Poly3DCollection.
*verts* should contain 3D coordinates.
Keyword arguments:
zsort, see set_zsort for options.
Note that this class does a bit of magic with the _facecolors
and _edgecolors properties.
'''
zsort = kwargs.pop('zsort', True)
PolyCollection.__init__(self, verts, *args, **kwargs)
self.set_zsort(zsort)
self._codes3d = None
_zsort_functions = {
'average': np.average,
'min': np.min,
'max': np.max,
}
def set_zsort(self, zsort):
'''
Set z-sorting behaviour:
boolean: if True use default 'average'
string: 'average', 'min' or 'max'
'''
if zsort is True:
zsort = 'average'
if zsort is not False:
if zsort in self._zsort_functions:
zsortfunc = self._zsort_functions[zsort]
else:
return False
else:
zsortfunc = None
self._zsort = zsort
self._sort_zpos = None
self._zsortfunc = zsortfunc
self.stale = True
def get_vector(self, segments3d):
"""Optimize points for projection"""
si = 0
ei = 0
segis = []
points = []
for p in segments3d:
points.extend(p)
ei = si + len(p)
segis.append((si, ei))
si = ei
if len(segments3d):
xs, ys, zs = zip(*points)
else :
# We need this so that we can skip the bad unpacking from zip()
xs, ys, zs = [], [], []
ones = np.ones(len(xs))
self._vec = np.array([xs, ys, zs, ones])
self._segis = segis
def set_verts(self, verts, closed=True):
'''Set 3D vertices.'''
self.get_vector(verts)
# 2D verts will be updated at draw time
PolyCollection.set_verts(self, [], False)
self._closed = closed
def set_verts_and_codes(self, verts, codes):
'''Sets 3D vertices with path codes'''
# set vertices with closed=False to prevent PolyCollection from
# setting path codes
self.set_verts(verts, closed=False)
# and set our own codes instead.
self._codes3d = codes
def set_3d_properties(self):
# Force the collection to initialize the face and edgecolors
# just in case it is a scalarmappable with a colormap.
self.update_scalarmappable()
self._sort_zpos = None
self.set_zsort(True)
self._facecolors3d = PolyCollection.get_facecolors(self)
self._edgecolors3d = PolyCollection.get_edgecolors(self)
self._alpha3d = PolyCollection.get_alpha(self)
self.stale = True
def set_sort_zpos(self,val):
'''Set the position to use for z-sorting.'''
self._sort_zpos = val
self.stale = True
def do_3d_projection(self, renderer):
'''
Perform the 3D projection for this object.
'''
# FIXME: This may no longer be needed?
if self._A is not None:
self.update_scalarmappable()
self._facecolors3d = self._facecolors
txs, tys, tzs = proj3d.proj_transform_vec(self._vec, renderer.M)
xyzlist = [(txs[si:ei], tys[si:ei], tzs[si:ei])
for si, ei in self._segis]
# This extra fuss is to re-order face / edge colors
cface = self._facecolors3d
cedge = self._edgecolors3d
if len(cface) != len(xyzlist):
cface = cface.repeat(len(xyzlist), axis=0)
if len(cedge) != len(xyzlist):
if len(cedge) == 0:
cedge = cface
else:
cedge = cedge.repeat(len(xyzlist), axis=0)
# if required sort by depth (furthest drawn first)
if self._zsort:
z_segments_2d = sorted(
((self._zsortfunc(zs), np.column_stack([xs, ys]), fc, ec, idx)
for idx, ((xs, ys, zs), fc, ec)
in enumerate(zip(xyzlist, cface, cedge))),
key=lambda x: x[0], reverse=True)
else:
raise ValueError("whoops")
segments_2d = [s for z, s, fc, ec, idx in z_segments_2d]
if self._codes3d is not None:
codes = [self._codes3d[idx] for z, s, fc, ec, idx in z_segments_2d]
PolyCollection.set_verts_and_codes(self, segments_2d, codes)
else:
PolyCollection.set_verts(self, segments_2d, self._closed)
self._facecolors2d = [fc for z, s, fc, ec, idx in z_segments_2d]
if len(self._edgecolors3d) == len(cface):
self._edgecolors2d = [ec for z, s, fc, ec, idx in z_segments_2d]
else:
self._edgecolors2d = self._edgecolors3d
# Return zorder value
if self._sort_zpos is not None:
zvec = np.array([[0], [0], [self._sort_zpos], [1]])
ztrans = proj3d.proj_transform_vec(zvec, renderer.M)
return ztrans[2][0]
elif tzs.size > 0 :
# FIXME: Some results still don't look quite right.
# In particular, examine contourf3d_demo2.py
# with az = -54 and elev = -45.
return np.min(tzs)
else :
return np.nan
def set_facecolor(self, colors):
PolyCollection.set_facecolor(self, colors)
self._facecolors3d = PolyCollection.get_facecolor(self)
set_facecolors = set_facecolor
def set_edgecolor(self, colors):
PolyCollection.set_edgecolor(self, colors)
self._edgecolors3d = PolyCollection.get_edgecolor(self)
set_edgecolors = set_edgecolor
def set_alpha(self, alpha):
"""
Set the alpha tranparencies of the collection. *alpha* must be
a float or *None*.
ACCEPTS: float or None
"""
if alpha is not None:
try:
float(alpha)
except TypeError:
raise TypeError('alpha must be a float or None')
artist.Artist.set_alpha(self, alpha)
try:
self._facecolors = mcolors.to_rgba_array(
self._facecolors3d, self._alpha)
except (AttributeError, TypeError, IndexError):
pass
try:
self._edgecolors = mcolors.to_rgba_array(
self._edgecolors3d, self._alpha)
except (AttributeError, TypeError, IndexError):
pass
self.stale = True
def get_facecolors(self):
return self._facecolors2d
get_facecolor = get_facecolors
def get_edgecolors(self):
return self._edgecolors2d
get_edgecolor = get_edgecolors
def draw(self, renderer):
return Collection.draw(self, renderer)
def poly_collection_2d_to_3d(col, zs=0, zdir='z'):
"""Convert a PolyCollection to a Poly3DCollection object."""
segments_3d, codes = paths_to_3d_segments_with_codes(col.get_paths(),
zs, zdir)
col.__class__ = Poly3DCollection
col.set_verts_and_codes(segments_3d, codes)
col.set_3d_properties()
def juggle_axes(xs, ys, zs, zdir):
"""
Reorder coordinates so that 2D xs, ys can be plotted in the plane
orthogonal to zdir. zdir is normally x, y or z. However, if zdir
starts with a '-' it is interpreted as a compensation for rotate_axes.
"""
if zdir == 'x':
return zs, xs, ys
elif zdir == 'y':
return xs, zs, ys
elif zdir[0] == '-':
return rotate_axes(xs, ys, zs, zdir)
else:
return xs, ys, zs
def rotate_axes(xs, ys, zs, zdir):
"""
Reorder coordinates so that the axes are rotated with zdir along
the original z axis. Prepending the axis with a '-' does the
inverse transform, so zdir can be x, -x, y, -y, z or -z
"""
if zdir == 'x':
return ys, zs, xs
elif zdir == '-x':
return zs, xs, ys
elif zdir == 'y':
return zs, xs, ys
elif zdir == '-y':
return ys, zs, xs
else:
return xs, ys, zs
def get_colors(c, num):
"""Stretch the color argument to provide the required number num"""
return _backports.broadcast_to(
mcolors.to_rgba_array(c) if len(c) else [0, 0, 0, 0],
(num, 4))
def zalpha(colors, zs):
"""Modify the alphas of the color list according to depth"""
# FIXME: This only works well if the points for *zs* are well-spaced
# in all three dimensions. Otherwise, at certain orientations,
# the min and max zs are very close together.
# Should really normalize against the viewing depth.
colors = get_colors(colors, len(zs))
if len(zs):
norm = Normalize(min(zs), max(zs))
sats = 1 - norm(zs) * 0.7
colors = [(c[0], c[1], c[2], c[3] * s) for c, s in zip(colors, sats)]
return colors
| 24,694 | 30.864516 | 89 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpl_toolkits/mplot3d/proj3d.py
|
# 3dproj.py
#
"""
Various transforms used for by the 3D code
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import six
from six.moves import zip
import numpy as np
import numpy.linalg as linalg
def line2d(p0, p1):
"""
Return 2D equation of line in the form ax+by+c = 0
"""
# x + x1 = 0
x0, y0 = p0[:2]
x1, y1 = p1[:2]
#
if x0 == x1:
a = -1
b = 0
c = x1
elif y0 == y1:
a = 0
b = 1
c = -y1
else:
a = (y0-y1)
b = (x0-x1)
c = (x0*y1 - x1*y0)
return a, b, c
def line2d_dist(l, p):
"""
Distance from line to point
line is a tuple of coefficients a,b,c
"""
a, b, c = l
x0, y0 = p
return abs((a*x0 + b*y0 + c)/np.sqrt(a**2+b**2))
def line2d_seg_dist(p1, p2, p0):
"""distance(s) from line defined by p1 - p2 to point(s) p0
p0[0] = x(s)
p0[1] = y(s)
intersection point p = p1 + u*(p2-p1)
and intersection point lies within segment if u is between 0 and 1
"""
x21 = p2[0] - p1[0]
y21 = p2[1] - p1[1]
x01 = np.asarray(p0[0]) - p1[0]
y01 = np.asarray(p0[1]) - p1[1]
u = (x01*x21 + y01*y21) / (x21**2 + y21**2)
u = np.clip(u, 0, 1)
d = np.sqrt((x01 - u*x21)**2 + (y01 - u*y21)**2)
return d
def mod(v):
"""3d vector length"""
return np.sqrt(v[0]**2+v[1]**2+v[2]**2)
def world_transformation(xmin, xmax,
ymin, ymax,
zmin, zmax):
dx, dy, dz = (xmax-xmin), (ymax-ymin), (zmax-zmin)
return np.array([
[1.0/dx,0,0,-xmin/dx],
[0,1.0/dy,0,-ymin/dy],
[0,0,1.0/dz,-zmin/dz],
[0,0,0,1.0]])
def view_transformation(E, R, V):
n = (E - R)
## new
# n /= mod(n)
# u = np.cross(V,n)
# u /= mod(u)
# v = np.cross(n,u)
# Mr = np.diag([1.]*4)
# Mt = np.diag([1.]*4)
# Mr[:3,:3] = u,v,n
# Mt[:3,-1] = -E
## end new
## old
n = n / mod(n)
u = np.cross(V, n)
u = u / mod(u)
v = np.cross(n, u)
Mr = [[u[0],u[1],u[2],0],
[v[0],v[1],v[2],0],
[n[0],n[1],n[2],0],
[0, 0, 0, 1],
]
#
Mt = [[1, 0, 0, -E[0]],
[0, 1, 0, -E[1]],
[0, 0, 1, -E[2]],
[0, 0, 0, 1]]
## end old
return np.dot(Mr, Mt)
def persp_transformation(zfront, zback):
a = (zfront+zback)/(zfront-zback)
b = -2*(zfront*zback)/(zfront-zback)
return np.array([[1,0,0,0],
[0,1,0,0],
[0,0,a,b],
[0,0,-1,0]
])
def ortho_transformation(zfront, zback):
# note: w component in the resulting vector will be (zback-zfront), not 1
a = -(zfront + zback)
b = -(zfront - zback)
return np.array([[2,0,0,0],
[0,2,0,0],
[0,0,-2,0],
[0,0,a,b]
])
def proj_transform_vec(vec, M):
vecw = np.dot(M, vec)
w = vecw[3]
# clip here..
txs, tys, tzs = vecw[0]/w, vecw[1]/w, vecw[2]/w
return txs, tys, tzs
def proj_transform_vec_clip(vec, M):
vecw = np.dot(M, vec)
w = vecw[3]
# clip here.
txs, tys, tzs = vecw[0] / w, vecw[1] / w, vecw[2] / w
tis = (0 <= vecw[0]) & (vecw[0] <= 1) & (0 <= vecw[1]) & (vecw[1] <= 1)
if np.any(tis):
tis = vecw[1] < 1
return txs, tys, tzs, tis
def inv_transform(xs, ys, zs, M):
iM = linalg.inv(M)
vec = vec_pad_ones(xs, ys, zs)
vecr = np.dot(iM, vec)
try:
vecr = vecr/vecr[3]
except OverflowError:
pass
return vecr[0], vecr[1], vecr[2]
def vec_pad_ones(xs, ys, zs):
return np.array([xs, ys, zs, np.ones_like(xs)])
def proj_transform(xs, ys, zs, M):
"""
Transform the points by the projection matrix
"""
vec = vec_pad_ones(xs, ys, zs)
return proj_transform_vec(vec, M)
def proj_transform_clip(xs, ys, zs, M):
"""
Transform the points by the projection matrix
and return the clipping result
returns txs,tys,tzs,tis
"""
vec = vec_pad_ones(xs, ys, zs)
return proj_transform_vec_clip(vec, M)
transform = proj_transform
def proj_points(points, M):
return np.column_stack(proj_trans_points(points, M))
def proj_trans_points(points, M):
xs, ys, zs = zip(*points)
return proj_transform(xs, ys, zs, M)
def proj_trans_clip_points(points, M):
xs, ys, zs = zip(*points)
return proj_transform_clip(xs, ys, zs, M)
def rot_x(V, alpha):
cosa, sina = np.cos(alpha), np.sin(alpha)
M1 = np.array([[1,0,0,0],
[0,cosa,-sina,0],
[0,sina,cosa,0],
[0,0,0,1]])
return np.dot(M1, V)
| 4,760 | 22.338235 | 77 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpl_toolkits/mplot3d/axes3d.py
|
"""
axes3d.py, original mplot3d version by John Porter
Created: 23 Sep 2005
Parts fixed by Reinier Heeres <reinier@heeres.eu>
Minor additions by Ben Axelrod <baxelrod@coroware.com>
Significant updates and revisions by Ben Root <ben.v.root@gmail.com>
Module containing Axes3D, an object which can plot 3D objects on a
2D matplotlib figure.
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import six
from six.moves import map, xrange, zip, reduce
import math
import warnings
from collections import defaultdict
import numpy as np
import matplotlib.axes as maxes
import matplotlib.cbook as cbook
import matplotlib.collections as mcoll
import matplotlib.colors as mcolors
import matplotlib.docstring as docstring
import matplotlib.scale as mscale
import matplotlib.transforms as mtransforms
from matplotlib.axes import Axes, rcParams
from matplotlib.cbook import _backports
from matplotlib.colors import Normalize, LightSource
from matplotlib.transforms import Bbox
from matplotlib.tri.triangulation import Triangulation
from . import art3d
from . import proj3d
from . import axis3d
def unit_bbox():
box = Bbox(np.array([[0, 0], [1, 1]]))
return box
class Axes3D(Axes):
"""
3D axes object.
"""
name = '3d'
_shared_z_axes = cbook.Grouper()
def __init__(self, fig, rect=None, *args, **kwargs):
'''
Build an :class:`Axes3D` instance in
:class:`~matplotlib.figure.Figure` *fig* with
*rect=[left, bottom, width, height]* in
:class:`~matplotlib.figure.Figure` coordinates
Optional keyword arguments:
================ =========================================
Keyword Description
================ =========================================
*azim* Azimuthal viewing angle (default -60)
*elev* Elevation viewing angle (default 30)
*zscale* [%(scale)s]
*sharez* Other axes to share z-limits with
*proj_type* 'persp' or 'ortho' (default 'persp')
================ =========================================
.. versionadded :: 1.2.1
*sharez*
''' % {'scale': ' | '.join([repr(x) for x in mscale.get_scale_names()])}
if rect is None:
rect = [0.0, 0.0, 1.0, 1.0]
self._cids = []
self.initial_azim = kwargs.pop('azim', -60)
self.initial_elev = kwargs.pop('elev', 30)
zscale = kwargs.pop('zscale', None)
sharez = kwargs.pop('sharez', None)
self.set_proj_type(kwargs.pop('proj_type', 'persp'))
self.xy_viewLim = unit_bbox()
self.zz_viewLim = unit_bbox()
self.xy_dataLim = unit_bbox()
self.zz_dataLim = unit_bbox()
# inihibit autoscale_view until the axes are defined
# they can't be defined until Axes.__init__ has been called
self.view_init(self.initial_elev, self.initial_azim)
self._ready = 0
self._sharez = sharez
if sharez is not None:
self._shared_z_axes.join(self, sharez)
self._adjustable = 'datalim'
super(Axes3D, self).__init__(fig, rect,
frameon=True,
*args, **kwargs)
# Disable drawing of axes by base class
super(Axes3D, self).set_axis_off()
# Enable drawing of axes by Axes3D class
self.set_axis_on()
self.M = None
# func used to format z -- fall back on major formatters
self.fmt_zdata = None
if zscale is not None:
self.set_zscale(zscale)
if self.zaxis is not None:
self._zcid = self.zaxis.callbacks.connect(
'units finalize', lambda: self._on_units_changed(scalez=True))
else:
self._zcid = None
self._ready = 1
self.mouse_init()
self.set_top_view()
self.patch.set_linewidth(0)
# Calculate the pseudo-data width and height
pseudo_bbox = self.transLimits.inverted().transform([(0, 0), (1, 1)])
self._pseudo_w, self._pseudo_h = pseudo_bbox[1] - pseudo_bbox[0]
self.figure.add_axes(self)
def set_axis_off(self):
self._axis3don = False
self.stale = True
def set_axis_on(self):
self._axis3don = True
self.stale = True
def have_units(self):
"""
Return *True* if units are set on the *x*, *y*, or *z* axes
"""
return (self.xaxis.have_units() or self.yaxis.have_units() or
self.zaxis.have_units())
def convert_zunits(self, z):
"""
For artists in an axes, if the zaxis has units support,
convert *z* using zaxis unit type
.. versionadded :: 1.2.1
"""
return self.zaxis.convert_units(z)
def _process_unit_info(self, xdata=None, ydata=None, zdata=None,
kwargs=None):
"""
Look for unit *kwargs* and update the axis instances as necessary
"""
super(Axes3D, self)._process_unit_info(xdata=xdata, ydata=ydata,
kwargs=kwargs)
if self.xaxis is None or self.yaxis is None or self.zaxis is None:
return
if zdata is not None:
# we only need to update if there is nothing set yet.
if not self.zaxis.have_units():
self.zaxis.update_units(xdata)
# process kwargs 2nd since these will override default units
if kwargs is not None:
zunits = kwargs.pop('zunits', self.zaxis.units)
if zunits != self.zaxis.units:
self.zaxis.set_units(zunits)
# If the units being set imply a different converter,
# we need to update.
if zdata is not None:
self.zaxis.update_units(zdata)
def set_top_view(self):
# this happens to be the right view for the viewing coordinates
# moved up and to the left slightly to fit labels and axes
xdwl = (0.95/self.dist)
xdw = (0.9/self.dist)
ydwl = (0.95/self.dist)
ydw = (0.9/self.dist)
# This is purposely using the 2D Axes's set_xlim and set_ylim,
# because we are trying to place our viewing pane.
super(Axes3D, self).set_xlim(-xdwl, xdw, auto=None)
super(Axes3D, self).set_ylim(-ydwl, ydw, auto=None)
def _init_axis(self):
'''Init 3D axes; overrides creation of regular X/Y axes'''
self.w_xaxis = axis3d.XAxis('x', self.xy_viewLim.intervalx,
self.xy_dataLim.intervalx, self)
self.xaxis = self.w_xaxis
self.w_yaxis = axis3d.YAxis('y', self.xy_viewLim.intervaly,
self.xy_dataLim.intervaly, self)
self.yaxis = self.w_yaxis
self.w_zaxis = axis3d.ZAxis('z', self.zz_viewLim.intervalx,
self.zz_dataLim.intervalx, self)
self.zaxis = self.w_zaxis
for ax in self.xaxis, self.yaxis, self.zaxis:
ax.init3d()
def get_children(self):
return [self.zaxis, ] + super(Axes3D, self).get_children()
def _get_axis_list(self):
return super(Axes3D, self)._get_axis_list() + (self.zaxis, )
def unit_cube(self, vals=None):
minx, maxx, miny, maxy, minz, maxz = vals or self.get_w_lims()
xs, ys, zs = ([minx, maxx, maxx, minx, minx, maxx, maxx, minx],
[miny, miny, maxy, maxy, miny, miny, maxy, maxy],
[minz, minz, minz, minz, maxz, maxz, maxz, maxz])
return list(zip(xs, ys, zs))
def tunit_cube(self, vals=None, M=None):
if M is None:
M = self.M
xyzs = self.unit_cube(vals)
tcube = proj3d.proj_points(xyzs, M)
return tcube
def tunit_edges(self, vals=None, M=None):
tc = self.tunit_cube(vals, M)
edges = [(tc[0], tc[1]),
(tc[1], tc[2]),
(tc[2], tc[3]),
(tc[3], tc[0]),
(tc[0], tc[4]),
(tc[1], tc[5]),
(tc[2], tc[6]),
(tc[3], tc[7]),
(tc[4], tc[5]),
(tc[5], tc[6]),
(tc[6], tc[7]),
(tc[7], tc[4])]
return edges
def draw(self, renderer):
# draw the background patch
self.patch.draw(renderer)
self._frameon = False
# first, set the aspect
# this is duplicated from `axes._base._AxesBase.draw`
# but must be called before any of the artist are drawn as
# it adjusts the view limits and the size of the bounding box
# of the axes
locator = self.get_axes_locator()
if locator:
pos = locator(self, renderer)
self.apply_aspect(pos)
else:
self.apply_aspect()
# add the projection matrix to the renderer
self.M = self.get_proj()
renderer.M = self.M
renderer.vvec = self.vvec
renderer.eye = self.eye
renderer.get_axis_position = self.get_axis_position
# Calculate projection of collections and zorder them
for i, col in enumerate(
sorted(self.collections,
key=lambda col: col.do_3d_projection(renderer),
reverse=True)):
col.zorder = i
# Calculate projection of patches and zorder them
for i, patch in enumerate(
sorted(self.patches,
key=lambda patch: patch.do_3d_projection(renderer),
reverse=True)):
patch.zorder = i
if self._axis3don:
axes = (self.xaxis, self.yaxis, self.zaxis)
# Draw panes first
for ax in axes:
ax.draw_pane(renderer)
# Then axes
for ax in axes:
ax.draw(renderer)
# Then rest
super(Axes3D, self).draw(renderer)
def get_axis_position(self):
vals = self.get_w_lims()
tc = self.tunit_cube(vals, self.M)
xhigh = tc[1][2] > tc[2][2]
yhigh = tc[3][2] > tc[2][2]
zhigh = tc[0][2] > tc[2][2]
return xhigh, yhigh, zhigh
def _on_units_changed(self, scalex=False, scaley=False, scalez=False):
"""
Callback for processing changes to axis units.
Currently forces updates of data limits and view limits.
"""
self.relim()
self.autoscale_view(scalex=scalex, scaley=scaley, scalez=scalez)
def update_datalim(self, xys, **kwargs):
pass
def get_autoscale_on(self):
"""
Get whether autoscaling is applied for all axes on plot commands
.. versionadded :: 1.1.0
This function was added, but not tested. Please report any bugs.
"""
return super(Axes3D, self).get_autoscale_on() and self.get_autoscalez_on()
def get_autoscalez_on(self):
"""
Get whether autoscaling for the z-axis is applied on plot commands
.. versionadded :: 1.1.0
This function was added, but not tested. Please report any bugs.
"""
return self._autoscaleZon
def set_autoscale_on(self, b):
"""
Set whether autoscaling is applied on plot commands
.. versionadded :: 1.1.0
This function was added, but not tested. Please report any bugs.
Parameters
----------
b : bool
.. ACCEPTS: bool
"""
super(Axes3D, self).set_autoscale_on(b)
self.set_autoscalez_on(b)
def set_autoscalez_on(self, b):
"""
Set whether autoscaling for the z-axis is applied on plot commands
.. versionadded :: 1.1.0
This function was added, but not tested. Please report any bugs.
Parameters
----------
b : bool
.. ACCEPTS: bool
"""
self._autoscaleZon = b
def set_zmargin(self, m):
"""
Set padding of Z data limits prior to autoscaling.
*m* times the data interval will be added to each
end of that interval before it is used in autoscaling.
accepts: float in range 0 to 1
.. versionadded :: 1.1.0
This function was added, but not tested. Please report any bugs.
"""
if m < 0 or m > 1 :
raise ValueError("margin must be in range 0 to 1")
self._zmargin = m
self.stale = True
def margins(self, *args, **kw):
"""
Convenience method to set or retrieve autoscaling margins.
signatures::
margins()
returns xmargin, ymargin, zmargin
::
margins(margin)
margins(xmargin, ymargin, zmargin)
margins(x=xmargin, y=ymargin, z=zmargin)
margins(..., tight=False)
All forms above set the xmargin, ymargin and zmargin
parameters. All keyword parameters are optional. A single argument
specifies xmargin, ymargin and zmargin. The *tight* parameter
is passed to :meth:`autoscale_view`, which is executed after
a margin is changed; the default here is *True*, on the
assumption that when margins are specified, no additional
padding to match tick marks is usually desired. Setting
*tight* to *None* will preserve the previous setting.
Specifying any margin changes only the autoscaling; for example,
if *xmargin* is not None, then *xmargin* times the X data
interval will be added to each end of that interval before
it is used in autoscaling.
.. versionadded :: 1.1.0
This function was added, but not tested. Please report any bugs.
"""
if not args and not kw:
return self._xmargin, self._ymargin, self._zmargin
tight = kw.pop('tight', True)
mx = kw.pop('x', None)
my = kw.pop('y', None)
mz = kw.pop('z', None)
if not args:
pass
elif len(args) == 1:
mx = my = mz = args[0]
elif len(args) == 2:
warnings.warn(
"Passing exactly two positional arguments to Axes3D.margins "
"is deprecated. If needed, pass them as keyword arguments "
"instead", cbook.mplDeprecation)
mx, my = args
elif len(args) == 3:
mx, my, mz = args
else:
raise ValueError(
"Axes3D.margins takes at most three positional arguments")
if mx is not None:
self.set_xmargin(mx)
if my is not None:
self.set_ymargin(my)
if mz is not None:
self.set_zmargin(mz)
scalex = mx is not None
scaley = my is not None
scalez = mz is not None
self.autoscale_view(tight=tight, scalex=scalex, scaley=scaley,
scalez=scalez)
def autoscale(self, enable=True, axis='both', tight=None):
"""
Convenience method for simple axis view autoscaling.
See :meth:`matplotlib.axes.Axes.autoscale` for full explanation.
Note that this function behaves the same, but for all
three axes. Therefore, 'z' can be passed for *axis*,
and 'both' applies to all three axes.
.. versionadded :: 1.1.0
This function was added, but not tested. Please report any bugs.
"""
if enable is None:
scalex = True
scaley = True
scalez = True
else:
if axis in ['x', 'both']:
self._autoscaleXon = scalex = bool(enable)
else:
scalex = False
if axis in ['y', 'both']:
self._autoscaleYon = scaley = bool(enable)
else:
scaley = False
if axis in ['z', 'both']:
self._autoscaleZon = scalez = bool(enable)
else:
scalez = False
self.autoscale_view(tight=tight, scalex=scalex, scaley=scaley,
scalez=scalez)
def auto_scale_xyz(self, X, Y, Z=None, had_data=None):
x, y, z = map(np.asarray, (X, Y, Z))
try:
x, y = x.flatten(), y.flatten()
if Z is not None:
z = z.flatten()
except AttributeError:
raise
# This updates the bounding boxes as to keep a record as
# to what the minimum sized rectangular volume holds the
# data.
self.xy_dataLim.update_from_data_xy(np.array([x, y]).T, not had_data)
if z is not None:
self.zz_dataLim.update_from_data_xy(np.array([z, z]).T, not had_data)
# Let autoscale_view figure out how to use this data.
self.autoscale_view()
def autoscale_view(self, tight=None, scalex=True, scaley=True,
scalez=True):
"""
Autoscale the view limits using the data limits.
See :meth:`matplotlib.axes.Axes.autoscale_view` for documentation.
Note that this function applies to the 3D axes, and as such
adds the *scalez* to the function arguments.
.. versionchanged :: 1.1.0
Function signature was changed to better match the 2D version.
*tight* is now explicitly a kwarg and placed first.
.. versionchanged :: 1.2.1
This is now fully functional.
"""
if not self._ready:
return
# This method looks at the rectangular volume (see above)
# of data and decides how to scale the view portal to fit it.
if tight is None:
# if image data only just use the datalim
_tight = self._tight or (len(self.images)>0 and
len(self.lines)==0 and
len(self.patches)==0)
else:
_tight = self._tight = bool(tight)
if scalex and self._autoscaleXon:
xshared = self._shared_x_axes.get_siblings(self)
dl = [ax.dataLim for ax in xshared]
bb = mtransforms.BboxBase.union(dl)
x0, x1 = self.xy_dataLim.intervalx
xlocator = self.xaxis.get_major_locator()
try:
x0, x1 = xlocator.nonsingular(x0, x1)
except AttributeError:
x0, x1 = mtransforms.nonsingular(x0, x1, increasing=False,
expander=0.05)
if self._xmargin > 0:
delta = (x1 - x0) * self._xmargin
x0 -= delta
x1 += delta
if not _tight:
x0, x1 = xlocator.view_limits(x0, x1)
self.set_xbound(x0, x1)
if scaley and self._autoscaleYon:
yshared = self._shared_y_axes.get_siblings(self)
dl = [ax.dataLim for ax in yshared]
bb = mtransforms.BboxBase.union(dl)
y0, y1 = self.xy_dataLim.intervaly
ylocator = self.yaxis.get_major_locator()
try:
y0, y1 = ylocator.nonsingular(y0, y1)
except AttributeError:
y0, y1 = mtransforms.nonsingular(y0, y1, increasing=False,
expander=0.05)
if self._ymargin > 0:
delta = (y1 - y0) * self._ymargin
y0 -= delta
y1 += delta
if not _tight:
y0, y1 = ylocator.view_limits(y0, y1)
self.set_ybound(y0, y1)
if scalez and self._autoscaleZon:
zshared = self._shared_z_axes.get_siblings(self)
dl = [ax.dataLim for ax in zshared]
bb = mtransforms.BboxBase.union(dl)
z0, z1 = self.zz_dataLim.intervalx
zlocator = self.zaxis.get_major_locator()
try:
z0, z1 = zlocator.nonsingular(z0, z1)
except AttributeError:
z0, z1 = mtransforms.nonsingular(z0, z1, increasing=False,
expander=0.05)
if self._zmargin > 0:
delta = (z1 - z0) * self._zmargin
z0 -= delta
z1 += delta
if not _tight:
z0, z1 = zlocator.view_limits(z0, z1)
self.set_zbound(z0, z1)
def get_w_lims(self):
'''Get 3D world limits.'''
minx, maxx = self.get_xlim3d()
miny, maxy = self.get_ylim3d()
minz, maxz = self.get_zlim3d()
return minx, maxx, miny, maxy, minz, maxz
def _determine_lims(self, xmin=None, xmax=None, *args, **kwargs):
if xmax is None and cbook.iterable(xmin):
xmin, xmax = xmin
if xmin == xmax:
xmin -= 0.05
xmax += 0.05
return (xmin, xmax)
def set_xlim3d(self, left=None, right=None, emit=True, auto=False, **kw):
"""
Set 3D x limits.
See :meth:`matplotlib.axes.Axes.set_xlim` for full documentation.
"""
if 'xmin' in kw:
left = kw.pop('xmin')
if 'xmax' in kw:
right = kw.pop('xmax')
if kw:
raise ValueError("unrecognized kwargs: %s" % list(kw))
if right is None and cbook.iterable(left):
left, right = left
self._process_unit_info(xdata=(left, right))
left = self._validate_converted_limits(left, self.convert_xunits)
right = self._validate_converted_limits(right, self.convert_xunits)
old_left, old_right = self.get_xlim()
if left is None:
left = old_left
if right is None:
right = old_right
if left == right:
warnings.warn(('Attempting to set identical left==right results\n'
'in singular transformations; automatically expanding.\n'
'left=%s, right=%s') % (left, right))
left, right = mtransforms.nonsingular(left, right, increasing=False)
left, right = self.xaxis.limit_range_for_scale(left, right)
self.xy_viewLim.intervalx = (left, right)
if auto is not None:
self._autoscaleXon = bool(auto)
if emit:
self.callbacks.process('xlim_changed', self)
# Call all of the other x-axes that are shared with this one
for other in self._shared_x_axes.get_siblings(self):
if other is not self:
other.set_xlim(self.xy_viewLim.intervalx,
emit=False, auto=auto)
if (other.figure != self.figure and
other.figure.canvas is not None):
other.figure.canvas.draw_idle()
self.stale = True
return left, right
set_xlim = set_xlim3d
def set_ylim3d(self, bottom=None, top=None, emit=True, auto=False, **kw):
"""
Set 3D y limits.
See :meth:`matplotlib.axes.Axes.set_ylim` for full documentation.
"""
if 'ymin' in kw:
bottom = kw.pop('ymin')
if 'ymax' in kw:
top = kw.pop('ymax')
if kw:
raise ValueError("unrecognized kwargs: %s" % list(kw))
if top is None and cbook.iterable(bottom):
bottom, top = bottom
self._process_unit_info(ydata=(bottom, top))
bottom = self._validate_converted_limits(bottom, self.convert_yunits)
top = self._validate_converted_limits(top, self.convert_yunits)
old_bottom, old_top = self.get_ylim()
if bottom is None:
bottom = old_bottom
if top is None:
top = old_top
if top == bottom:
warnings.warn(('Attempting to set identical bottom==top results\n'
'in singular transformations; automatically expanding.\n'
'bottom=%s, top=%s') % (bottom, top))
bottom, top = mtransforms.nonsingular(bottom, top, increasing=False)
bottom, top = self.yaxis.limit_range_for_scale(bottom, top)
self.xy_viewLim.intervaly = (bottom, top)
if auto is not None:
self._autoscaleYon = bool(auto)
if emit:
self.callbacks.process('ylim_changed', self)
# Call all of the other y-axes that are shared with this one
for other in self._shared_y_axes.get_siblings(self):
if other is not self:
other.set_ylim(self.xy_viewLim.intervaly,
emit=False, auto=auto)
if (other.figure != self.figure and
other.figure.canvas is not None):
other.figure.canvas.draw_idle()
self.stale = True
return bottom, top
set_ylim = set_ylim3d
def set_zlim3d(self, bottom=None, top=None, emit=True, auto=False, **kw):
"""
Set 3D z limits.
See :meth:`matplotlib.axes.Axes.set_ylim` for full documentation
"""
if 'zmin' in kw:
bottom = kw.pop('zmin')
if 'zmax' in kw:
top = kw.pop('zmax')
if kw:
raise ValueError("unrecognized kwargs: %s" % list(kw))
if top is None and cbook.iterable(bottom):
bottom, top = bottom
self._process_unit_info(zdata=(bottom, top))
bottom = self._validate_converted_limits(bottom, self.convert_zunits)
top = self._validate_converted_limits(top, self.convert_zunits)
old_bottom, old_top = self.get_zlim()
if bottom is None:
bottom = old_bottom
if top is None:
top = old_top
if top == bottom:
warnings.warn(('Attempting to set identical bottom==top results\n'
'in singular transformations; automatically expanding.\n'
'bottom=%s, top=%s') % (bottom, top))
bottom, top = mtransforms.nonsingular(bottom, top, increasing=False)
bottom, top = self.zaxis.limit_range_for_scale(bottom, top)
self.zz_viewLim.intervalx = (bottom, top)
if auto is not None:
self._autoscaleZon = bool(auto)
if emit:
self.callbacks.process('zlim_changed', self)
# Call all of the other y-axes that are shared with this one
for other in self._shared_z_axes.get_siblings(self):
if other is not self:
other.set_zlim(self.zz_viewLim.intervalx,
emit=False, auto=auto)
if (other.figure != self.figure and
other.figure.canvas is not None):
other.figure.canvas.draw_idle()
self.stale = True
return bottom, top
set_zlim = set_zlim3d
def get_xlim3d(self):
return tuple(self.xy_viewLim.intervalx)
get_xlim3d.__doc__ = maxes.Axes.get_xlim.__doc__
get_xlim = get_xlim3d
if get_xlim.__doc__ is not None:
get_xlim.__doc__ += """
.. versionchanged :: 1.1.0
This function now correctly refers to the 3D x-limits
"""
def get_ylim3d(self):
return tuple(self.xy_viewLim.intervaly)
get_ylim3d.__doc__ = maxes.Axes.get_ylim.__doc__
get_ylim = get_ylim3d
if get_ylim.__doc__ is not None:
get_ylim.__doc__ += """
.. versionchanged :: 1.1.0
This function now correctly refers to the 3D y-limits.
"""
def get_zlim3d(self):
'''Get 3D z limits.'''
return tuple(self.zz_viewLim.intervalx)
get_zlim = get_zlim3d
def get_zscale(self):
"""
Return the zaxis scale string %s
.. versionadded :: 1.1.0
This function was added, but not tested. Please report any bugs.
""" % (", ".join(mscale.get_scale_names()))
return self.zaxis.get_scale()
# We need to slightly redefine these to pass scalez=False
# to their calls of autoscale_view.
def set_xscale(self, value, **kwargs):
self.xaxis._set_scale(value, **kwargs)
self.autoscale_view(scaley=False, scalez=False)
self._update_transScale()
if maxes.Axes.set_xscale.__doc__ is not None:
set_xscale.__doc__ = maxes.Axes.set_xscale.__doc__ + """
.. versionadded :: 1.1.0
This function was added, but not tested. Please report any bugs.
"""
def set_yscale(self, value, **kwargs):
self.yaxis._set_scale(value, **kwargs)
self.autoscale_view(scalex=False, scalez=False)
self._update_transScale()
self.stale = True
if maxes.Axes.set_yscale.__doc__ is not None:
set_yscale.__doc__ = maxes.Axes.set_yscale.__doc__ + """
.. versionadded :: 1.1.0
This function was added, but not tested. Please report any bugs.
"""
@docstring.dedent_interpd
def set_zscale(self, value, **kwargs):
"""
Set the scaling of the z-axis: %(scale)s
ACCEPTS: [%(scale)s]
Different kwargs are accepted, depending on the scale:
%(scale_docs)s
.. note ::
Currently, Axes3D objects only supports linear scales.
Other scales may or may not work, and support for these
is improving with each release.
.. versionadded :: 1.1.0
This function was added, but not tested. Please report any bugs.
"""
self.zaxis._set_scale(value, **kwargs)
self.autoscale_view(scalex=False, scaley=False)
self._update_transScale()
self.stale = True
def set_zticks(self, *args, **kwargs):
"""
Set z-axis tick locations.
See :meth:`matplotlib.axes.Axes.set_yticks` for more details.
.. note::
Minor ticks are not supported.
.. versionadded:: 1.1.0
"""
return self.zaxis.set_ticks(*args, **kwargs)
def get_zticks(self, minor=False):
"""
Return the z ticks as a list of locations
See :meth:`matplotlib.axes.Axes.get_yticks` for more details.
.. note::
Minor ticks are not supported.
.. versionadded:: 1.1.0
"""
return self.zaxis.get_ticklocs(minor=minor)
def get_zmajorticklabels(self):
"""
Get the ztick labels as a list of Text instances
.. versionadded :: 1.1.0
"""
return cbook.silent_list('Text zticklabel',
self.zaxis.get_majorticklabels())
def get_zminorticklabels(self):
"""
Get the ztick labels as a list of Text instances
.. note::
Minor ticks are not supported. This function was added
only for completeness.
.. versionadded :: 1.1.0
"""
return cbook.silent_list('Text zticklabel',
self.zaxis.get_minorticklabels())
def set_zticklabels(self, *args, **kwargs):
"""
Set z-axis tick labels.
See :meth:`matplotlib.axes.Axes.set_yticklabels` for more details.
.. note::
Minor ticks are not supported by Axes3D objects.
.. versionadded:: 1.1.0
"""
return self.zaxis.set_ticklabels(*args, **kwargs)
def get_zticklabels(self, minor=False):
"""
Get ztick labels as a list of Text instances.
See :meth:`matplotlib.axes.Axes.get_yticklabels` for more details.
.. note::
Minor ticks are not supported.
.. versionadded:: 1.1.0
"""
return cbook.silent_list('Text zticklabel',
self.zaxis.get_ticklabels(minor=minor))
def zaxis_date(self, tz=None):
"""
Sets up z-axis ticks and labels that treat the z data as dates.
*tz* is a timezone string or :class:`tzinfo` instance.
Defaults to rc value.
.. note::
This function is merely provided for completeness.
Axes3D objects do not officially support dates for ticks,
and so this may or may not work as expected.
.. versionadded :: 1.1.0
This function was added, but not tested. Please report any bugs.
"""
self.zaxis.axis_date(tz)
def get_zticklines(self):
"""
Get ztick lines as a list of Line2D instances.
Note that this function is provided merely for completeness.
These lines are re-calculated as the display changes.
.. versionadded:: 1.1.0
"""
return self.zaxis.get_ticklines()
def clabel(self, *args, **kwargs):
"""
This function is currently not implemented for 3D axes.
Returns *None*.
"""
return None
def view_init(self, elev=None, azim=None):
"""
Set the elevation and azimuth of the axes.
This can be used to rotate the axes programmatically.
'elev' stores the elevation angle in the z plane.
'azim' stores the azimuth angle in the x,y plane.
if elev or azim are None (default), then the initial value
is used which was specified in the :class:`Axes3D` constructor.
"""
self.dist = 10
if elev is None:
self.elev = self.initial_elev
else:
self.elev = elev
if azim is None:
self.azim = self.initial_azim
else:
self.azim = azim
def set_proj_type(self, proj_type):
"""
Set the projection type.
Parameters
----------
proj_type : str
Type of projection, accepts 'persp' and 'ortho'.
"""
if proj_type == 'persp':
self._projection = proj3d.persp_transformation
elif proj_type == 'ortho':
self._projection = proj3d.ortho_transformation
else:
raise ValueError("unrecognized projection: %s" % proj_type)
def get_proj(self):
"""
Create the projection matrix from the current viewing position.
elev stores the elevation angle in the z plane
azim stores the azimuth angle in the x,y plane
dist is the distance of the eye viewing point from the object
point.
"""
relev, razim = np.pi * self.elev/180, np.pi * self.azim/180
xmin, xmax = self.get_xlim3d()
ymin, ymax = self.get_ylim3d()
zmin, zmax = self.get_zlim3d()
# transform to uniform world coordinates 0-1.0,0-1.0,0-1.0
worldM = proj3d.world_transformation(xmin, xmax,
ymin, ymax,
zmin, zmax)
# look into the middle of the new coordinates
R = np.array([0.5, 0.5, 0.5])
xp = R[0] + np.cos(razim) * np.cos(relev) * self.dist
yp = R[1] + np.sin(razim) * np.cos(relev) * self.dist
zp = R[2] + np.sin(relev) * self.dist
E = np.array((xp, yp, zp))
self.eye = E
self.vvec = R - E
self.vvec = self.vvec / proj3d.mod(self.vvec)
if abs(relev) > np.pi/2:
# upside down
V = np.array((0, 0, -1))
else:
V = np.array((0, 0, 1))
zfront, zback = -self.dist, self.dist
viewM = proj3d.view_transformation(E, R, V)
projM = self._projection(zfront, zback)
M0 = np.dot(viewM, worldM)
M = np.dot(projM, M0)
return M
def mouse_init(self, rotate_btn=1, zoom_btn=3):
"""Initializes mouse button callbacks to enable 3D rotation of
the axes. Also optionally sets the mouse buttons for 3D rotation
and zooming.
============ =======================================================
Argument Description
============ =======================================================
*rotate_btn* The integer or list of integers specifying which mouse
button or buttons to use for 3D rotation of the axes.
Default = 1.
*zoom_btn* The integer or list of integers specifying which mouse
button or buttons to use to zoom the 3D axes.
Default = 3.
============ =======================================================
"""
self.button_pressed = None
canv = self.figure.canvas
if canv is not None:
c1 = canv.mpl_connect('motion_notify_event', self._on_move)
c2 = canv.mpl_connect('button_press_event', self._button_press)
c3 = canv.mpl_connect('button_release_event', self._button_release)
self._cids = [c1, c2, c3]
else:
warnings.warn(
"Axes3D.figure.canvas is 'None', mouse rotation disabled. "
"Set canvas then call Axes3D.mouse_init().")
# coerce scalars into array-like, then convert into
# a regular list to avoid comparisons against None
# which breaks in recent versions of numpy.
self._rotate_btn = np.atleast_1d(rotate_btn).tolist()
self._zoom_btn = np.atleast_1d(zoom_btn).tolist()
def can_zoom(self):
"""
Return *True* if this axes supports the zoom box button functionality.
3D axes objects do not use the zoom box button.
"""
return False
def can_pan(self):
"""
Return *True* if this axes supports the pan/zoom button functionality.
3D axes objects do not use the pan/zoom button.
"""
return False
def cla(self):
"""
Clear axes
"""
# Disabling mouse interaction might have been needed a long
# time ago, but I can't find a reason for it now - BVR (2012-03)
#self.disable_mouse_rotation()
super(Axes3D, self).cla()
self.zaxis.cla()
if self._sharez is not None:
self.zaxis.major = self._sharez.zaxis.major
self.zaxis.minor = self._sharez.zaxis.minor
z0, z1 = self._sharez.get_zlim()
self.set_zlim(z0, z1, emit=False, auto=None)
self.zaxis._set_scale(self._sharez.zaxis.get_scale())
else:
self.zaxis._set_scale('linear')
try:
self.set_zlim(0, 1)
except TypeError:
pass
self._autoscaleZon = True
self._zmargin = 0
self.grid(rcParams['axes3d.grid'])
def disable_mouse_rotation(self):
"""Disable mouse button callbacks.
"""
# Disconnect the various events we set.
for cid in self._cids:
self.figure.canvas.mpl_disconnect(cid)
self._cids = []
def _button_press(self, event):
if event.inaxes == self:
self.button_pressed = event.button
self.sx, self.sy = event.xdata, event.ydata
def _button_release(self, event):
self.button_pressed = None
def format_zdata(self, z):
"""
Return *z* string formatted. This function will use the
:attr:`fmt_zdata` attribute if it is callable, else will fall
back on the zaxis major formatter
"""
try: return self.fmt_zdata(z)
except (AttributeError, TypeError):
func = self.zaxis.get_major_formatter().format_data_short
val = func(z)
return val
def format_coord(self, xd, yd):
"""
Given the 2D view coordinates attempt to guess a 3D coordinate.
Looks for the nearest edge to the point and then assumes that
the point is at the same z location as the nearest point on the edge.
"""
if self.M is None:
return ''
if self.button_pressed in self._rotate_btn:
return 'azimuth=%d deg, elevation=%d deg ' % (self.azim, self.elev)
# ignore xd and yd and display angles instead
# nearest edge
p0, p1 = min(self.tunit_edges(),
key=lambda edge: proj3d.line2d_seg_dist(
edge[0], edge[1], (xd, yd)))
# scale the z value to match
x0, y0, z0 = p0
x1, y1, z1 = p1
d0 = np.hypot(x0-xd, y0-yd)
d1 = np.hypot(x1-xd, y1-yd)
dt = d0+d1
z = d1/dt * z0 + d0/dt * z1
x, y, z = proj3d.inv_transform(xd, yd, z, self.M)
xs = self.format_xdata(x)
ys = self.format_ydata(y)
zs = self.format_zdata(z)
return 'x=%s, y=%s, z=%s' % (xs, ys, zs)
def _on_move(self, event):
"""Mouse moving
button-1 rotates by default. Can be set explicitly in mouse_init().
button-3 zooms by default. Can be set explicitly in mouse_init().
"""
if not self.button_pressed:
return
if self.M is None:
return
x, y = event.xdata, event.ydata
# In case the mouse is out of bounds.
if x is None:
return
dx, dy = x - self.sx, y - self.sy
w = self._pseudo_w
h = self._pseudo_h
self.sx, self.sy = x, y
# Rotation
if self.button_pressed in self._rotate_btn:
# rotate viewing point
# get the x and y pixel coords
if dx == 0 and dy == 0:
return
self.elev = art3d.norm_angle(self.elev - (dy/h)*180)
self.azim = art3d.norm_angle(self.azim - (dx/w)*180)
self.get_proj()
self.stale = True
self.figure.canvas.draw_idle()
# elif self.button_pressed == 2:
# pan view
# project xv,yv,zv -> xw,yw,zw
# pan
# pass
# Zoom
elif self.button_pressed in self._zoom_btn:
# zoom view
# hmmm..this needs some help from clipping....
minx, maxx, miny, maxy, minz, maxz = self.get_w_lims()
df = 1-((h - dy)/h)
dx = (maxx-minx)*df
dy = (maxy-miny)*df
dz = (maxz-minz)*df
self.set_xlim3d(minx - dx, maxx + dx)
self.set_ylim3d(miny - dy, maxy + dy)
self.set_zlim3d(minz - dz, maxz + dz)
self.get_proj()
self.figure.canvas.draw_idle()
def set_zlabel(self, zlabel, fontdict=None, labelpad=None, **kwargs):
'''
Set zlabel. See doc for :meth:`set_ylabel` for description.
'''
if labelpad is not None : self.zaxis.labelpad = labelpad
return self.zaxis.set_label_text(zlabel, fontdict, **kwargs)
def get_zlabel(self):
"""
Get the z-label text string.
.. versionadded :: 1.1.0
This function was added, but not tested. Please report any bugs.
"""
label = self.zaxis.get_label()
return label.get_text()
#### Axes rectangle characteristics
def get_frame_on(self):
"""
Get whether the 3D axes panels are drawn.
.. versionadded :: 1.1.0
"""
return self._frameon
def set_frame_on(self, b):
"""
Set whether the 3D axes panels are drawn.
.. versionadded :: 1.1.0
Parameters
----------
b : bool
.. ACCEPTS: bool
"""
self._frameon = bool(b)
self.stale = True
def get_axisbelow(self):
"""
Get whether axis below is true or not.
For axes3d objects, this will always be *True*
.. versionadded :: 1.1.0
This function was added for completeness.
"""
return True
def set_axisbelow(self, b):
"""
Set whether axis ticks and gridlines are above or below most artists.
For axes3d objects, this will ignore any settings and just use *True*
.. versionadded :: 1.1.0
This function was added for completeness.
Parameters
----------
b : bool
.. ACCEPTS: bool
"""
self._axisbelow = True
self.stale = True
def grid(self, b=True, **kwargs):
'''
Set / unset 3D grid.
.. note::
Currently, this function does not behave the same as
:meth:`matplotlib.axes.Axes.grid`, but it is intended to
eventually support that behavior.
.. versionchanged :: 1.1.0
This function was changed, but not tested. Please report any bugs.
'''
# TODO: Operate on each axes separately
if len(kwargs):
b = True
self._draw_grid = cbook._string_to_bool(b)
self.stale = True
def ticklabel_format(self, **kwargs):
"""
Convenience method for manipulating the ScalarFormatter
used by default for linear axes in Axed3D objects.
See :meth:`matplotlib.axes.Axes.ticklabel_format` for full
documentation. Note that this version applies to all three
axes of the Axes3D object. Therefore, the *axis* argument
will also accept a value of 'z' and the value of 'both' will
apply to all three axes.
.. versionadded :: 1.1.0
This function was added, but not tested. Please report any bugs.
"""
style = kwargs.pop('style', '').lower()
scilimits = kwargs.pop('scilimits', None)
useOffset = kwargs.pop('useOffset', None)
axis = kwargs.pop('axis', 'both').lower()
if scilimits is not None:
try:
m, n = scilimits
m+n+1 # check that both are numbers
except (ValueError, TypeError):
raise ValueError("scilimits must be a sequence of 2 integers")
if style[:3] == 'sci':
sb = True
elif style in ['plain', 'comma']:
sb = False
if style == 'plain':
cb = False
else:
cb = True
raise NotImplementedError("comma style remains to be added")
elif style == '':
sb = None
else:
raise ValueError("%s is not a valid style value")
try:
if sb is not None:
if axis in ['both', 'z']:
self.xaxis.major.formatter.set_scientific(sb)
if axis in ['both', 'y']:
self.yaxis.major.formatter.set_scientific(sb)
if axis in ['both', 'z'] :
self.zaxis.major.formatter.set_scientific(sb)
if scilimits is not None:
if axis in ['both', 'x']:
self.xaxis.major.formatter.set_powerlimits(scilimits)
if axis in ['both', 'y']:
self.yaxis.major.formatter.set_powerlimits(scilimits)
if axis in ['both', 'z']:
self.zaxis.major.formatter.set_powerlimits(scilimits)
if useOffset is not None:
if axis in ['both', 'x']:
self.xaxis.major.formatter.set_useOffset(useOffset)
if axis in ['both', 'y']:
self.yaxis.major.formatter.set_useOffset(useOffset)
if axis in ['both', 'z']:
self.zaxis.major.formatter.set_useOffset(useOffset)
except AttributeError:
raise AttributeError(
"This method only works with the ScalarFormatter.")
def locator_params(self, axis='both', tight=None, **kwargs):
"""
Convenience method for controlling tick locators.
See :meth:`matplotlib.axes.Axes.locator_params` for full
documentation Note that this is for Axes3D objects,
therefore, setting *axis* to 'both' will result in the
parameters being set for all three axes. Also, *axis*
can also take a value of 'z' to apply parameters to the
z axis.
.. versionadded :: 1.1.0
This function was added, but not tested. Please report any bugs.
"""
_x = axis in ['x', 'both']
_y = axis in ['y', 'both']
_z = axis in ['z', 'both']
if _x:
self.xaxis.get_major_locator().set_params(**kwargs)
if _y:
self.yaxis.get_major_locator().set_params(**kwargs)
if _z:
self.zaxis.get_major_locator().set_params(**kwargs)
self.autoscale_view(tight=tight, scalex=_x, scaley=_y, scalez=_z)
def tick_params(self, axis='both', **kwargs):
"""
Convenience method for changing the appearance of ticks and
tick labels.
See :meth:`matplotlib.axes.Axes.tick_params` for more complete
documentation.
The only difference is that setting *axis* to 'both' will
mean that the settings are applied to all three axes. Also,
the *axis* parameter also accepts a value of 'z', which
would mean to apply to only the z-axis.
Also, because of how Axes3D objects are drawn very differently
from regular 2D axes, some of these settings may have
ambiguous meaning. For simplicity, the 'z' axis will
accept settings as if it was like the 'y' axis.
.. note::
While this function is currently implemented, the core part
of the Axes3D object may ignore some of these settings.
Future releases will fix this. Priority will be given to
those who file bugs.
.. versionadded :: 1.1.0
This function was added, but not tested. Please report any bugs.
"""
super(Axes3D, self).tick_params(axis, **kwargs)
if axis in ['z', 'both'] :
zkw = dict(kwargs)
zkw.pop('top', None)
zkw.pop('bottom', None)
zkw.pop('labeltop', None)
zkw.pop('labelbottom', None)
self.zaxis.set_tick_params(**zkw)
### data limits, ticks, tick labels, and formatting
def invert_zaxis(self):
"""
Invert the z-axis.
.. versionadded :: 1.1.0
This function was added, but not tested. Please report any bugs.
"""
bottom, top = self.get_zlim()
self.set_zlim(top, bottom, auto=None)
def zaxis_inverted(self):
'''
Returns True if the z-axis is inverted.
.. versionadded :: 1.1.0
This function was added, but not tested. Please report any bugs.
'''
bottom, top = self.get_zlim()
return top < bottom
def get_zbound(self):
"""
Returns the z-axis numerical bounds where::
lowerBound < upperBound
.. versionadded :: 1.1.0
This function was added, but not tested. Please report any bugs.
"""
bottom, top = self.get_zlim()
if bottom < top:
return bottom, top
else:
return top, bottom
def set_zbound(self, lower=None, upper=None):
"""
Set the lower and upper numerical bounds of the z-axis.
This method will honor axes inversion regardless of parameter order.
It will not change the :attr:`_autoscaleZon` attribute.
.. versionadded :: 1.1.0
This function was added, but not tested. Please report any bugs.
"""
if upper is None and cbook.iterable(lower):
lower,upper = lower
old_lower,old_upper = self.get_zbound()
if lower is None: lower = old_lower
if upper is None: upper = old_upper
if self.zaxis_inverted():
if lower < upper:
self.set_zlim(upper, lower, auto=None)
else:
self.set_zlim(lower, upper, auto=None)
else :
if lower < upper:
self.set_zlim(lower, upper, auto=None)
else :
self.set_zlim(upper, lower, auto=None)
def text(self, x, y, z, s, zdir=None, **kwargs):
'''
Add text to the plot. kwargs will be passed on to Axes.text,
except for the `zdir` keyword, which sets the direction to be
used as the z direction.
'''
text = super(Axes3D, self).text(x, y, s, **kwargs)
art3d.text_2d_to_3d(text, z, zdir)
return text
text3D = text
text2D = Axes.text
def plot(self, xs, ys, *args, **kwargs):
'''
Plot 2D or 3D data.
========== ================================================
Argument Description
========== ================================================
*xs*, *ys* x, y coordinates of vertices
*zs* z value(s), either one for all points or one for
each point.
*zdir* Which direction to use as z ('x', 'y' or 'z')
when plotting a 2D set.
========== ================================================
Other arguments are passed on to
:func:`~matplotlib.axes.Axes.plot`
'''
had_data = self.has_data()
# `zs` can be passed positionally or as keyword; checking whether
# args[0] is a string matches the behavior of 2D `plot` (via
# `_process_plot_var_args`).
if args and not isinstance(args[0], six.string_types):
zs = args[0]
args = args[1:]
if 'zs' in kwargs:
raise TypeError("plot() for multiple values for argument 'z'")
else:
zs = kwargs.pop('zs', 0)
zdir = kwargs.pop('zdir', 'z')
# Match length
zs = _backports.broadcast_to(zs, len(xs))
lines = super(Axes3D, self).plot(xs, ys, *args, **kwargs)
for line in lines:
art3d.line_2d_to_3d(line, zs=zs, zdir=zdir)
xs, ys, zs = art3d.juggle_axes(xs, ys, zs, zdir)
self.auto_scale_xyz(xs, ys, zs, had_data)
return lines
plot3D = plot
def plot_surface(self, X, Y, Z, *args, **kwargs):
"""
Create a surface plot.
By default it will be colored in shades of a solid color, but it also
supports color mapping by supplying the *cmap* argument.
.. note::
The *rcount* and *ccount* kwargs, which both default to 50,
determine the maximum number of samples used in each direction. If
the input data is larger, it will be downsampled (by slicing) to
these numbers of points.
Parameters
----------
X, Y, Z : 2d arrays
Data values.
rcount, ccount : int
Maximum number of samples used in each direction. If the input
data is larger, it will be downsampled (by slicing) to these
numbers of points. Defaults to 50.
.. versionadded:: 2.0
rstride, cstride : int
Downsampling stride in each direction. These arguments are
mutually exclusive with *rcount* and *ccount*. If only one of
*rstride* or *cstride* is set, the other defaults to 10.
'classic' mode uses a default of ``rstride = cstride = 10`` instead
of the new default of ``rcount = ccount = 50``.
color : color-like
Color of the surface patches.
cmap : Colormap
Colormap of the surface patches.
facecolors : array-like of colors.
Colors of each individual patch.
norm : Normalize
Normalization for the colormap.
vmin, vmax : float
Bounds for the normalization.
shade : bool
Whether to shade the face colors.
**kwargs :
Other arguments are forwarded to `.Poly3DCollection`.
"""
had_data = self.has_data()
if Z.ndim != 2:
raise ValueError("Argument Z must be 2-dimensional.")
# TODO: Support masked arrays
X, Y, Z = np.broadcast_arrays(X, Y, Z)
rows, cols = Z.shape
has_stride = 'rstride' in kwargs or 'cstride' in kwargs
has_count = 'rcount' in kwargs or 'ccount' in kwargs
if has_stride and has_count:
raise ValueError("Cannot specify both stride and count arguments")
rstride = kwargs.pop('rstride', 10)
cstride = kwargs.pop('cstride', 10)
rcount = kwargs.pop('rcount', 50)
ccount = kwargs.pop('ccount', 50)
if rcParams['_internal.classic_mode']:
# Strides have priority over counts in classic mode.
# So, only compute strides from counts
# if counts were explicitly given
if has_count:
rstride = int(max(np.ceil(rows / rcount), 1))
cstride = int(max(np.ceil(cols / ccount), 1))
else:
# If the strides are provided then it has priority.
# Otherwise, compute the strides from the counts.
if not has_stride:
rstride = int(max(np.ceil(rows / rcount), 1))
cstride = int(max(np.ceil(cols / ccount), 1))
if 'facecolors' in kwargs:
fcolors = kwargs.pop('facecolors')
else:
color = kwargs.pop('color', None)
if color is None:
color = self._get_lines.get_next_color()
color = np.array(mcolors.to_rgba(color))
fcolors = None
cmap = kwargs.get('cmap', None)
norm = kwargs.pop('norm', None)
vmin = kwargs.pop('vmin', None)
vmax = kwargs.pop('vmax', None)
linewidth = kwargs.get('linewidth', None)
shade = kwargs.pop('shade', cmap is None)
lightsource = kwargs.pop('lightsource', None)
# Shade the data
if shade and cmap is not None and fcolors is not None:
fcolors = self._shade_colors_lightsource(Z, cmap, lightsource)
polys = []
# Only need these vectors to shade if there is no cmap
if cmap is None and shade :
totpts = int(np.ceil((rows - 1) / rstride) *
np.ceil((cols - 1) / cstride))
v1 = np.empty((totpts, 3))
v2 = np.empty((totpts, 3))
# This indexes the vertex points
which_pt = 0
#colset contains the data for coloring: either average z or the facecolor
colset = []
for rs in xrange(0, rows-1, rstride):
for cs in xrange(0, cols-1, cstride):
ps = []
for a in (X, Y, Z):
ztop = a[rs,cs:min(cols, cs+cstride+1)]
zleft = a[rs+1:min(rows, rs+rstride+1),
min(cols-1, cs+cstride)]
zbase = a[min(rows-1, rs+rstride), cs:min(cols, cs+cstride+1):][::-1]
zright = a[rs:min(rows-1, rs+rstride):, cs][::-1]
z = np.concatenate((ztop, zleft, zbase, zright))
ps.append(z)
# The construction leaves the array with duplicate points, which
# are removed here.
ps = list(zip(*ps))
lastp = np.array([])
ps2 = [ps[0]] + [ps[i] for i in xrange(1, len(ps)) if ps[i] != ps[i-1]]
avgzsum = sum(p[2] for p in ps2)
polys.append(ps2)
if fcolors is not None:
colset.append(fcolors[rs][cs])
else:
colset.append(avgzsum / len(ps2))
# Only need vectors to shade if no cmap
if cmap is None and shade:
i1, i2, i3 = 0, int(len(ps2)/3), int(2*len(ps2)/3)
v1[which_pt] = np.array(ps2[i1]) - np.array(ps2[i2])
v2[which_pt] = np.array(ps2[i2]) - np.array(ps2[i3])
which_pt += 1
if cmap is None and shade:
normals = np.cross(v1, v2)
else :
normals = []
polyc = art3d.Poly3DCollection(polys, *args, **kwargs)
if fcolors is not None:
if shade:
colset = self._shade_colors(colset, normals)
polyc.set_facecolors(colset)
polyc.set_edgecolors(colset)
elif cmap:
colset = np.array(colset)
polyc.set_array(colset)
if vmin is not None or vmax is not None:
polyc.set_clim(vmin, vmax)
if norm is not None:
polyc.set_norm(norm)
else:
if shade:
colset = self._shade_colors(color, normals)
else:
colset = color
polyc.set_facecolors(colset)
self.add_collection(polyc)
self.auto_scale_xyz(X, Y, Z, had_data)
return polyc
def _generate_normals(self, polygons):
'''
Generate normals for polygons by using the first three points.
This normal of course might not make sense for polygons with
more than three points not lying in a plane.
'''
normals = []
for verts in polygons:
v1 = np.array(verts[0]) - np.array(verts[1])
v2 = np.array(verts[2]) - np.array(verts[0])
normals.append(np.cross(v1, v2))
return normals
def _shade_colors(self, color, normals):
'''
Shade *color* using normal vectors given by *normals*.
*color* can also be an array of the same length as *normals*.
'''
shade = np.array([np.dot(n / proj3d.mod(n), [-1, -1, 0.5])
if proj3d.mod(n) else np.nan
for n in normals])
mask = ~np.isnan(shade)
if len(shade[mask]) > 0:
norm = Normalize(min(shade[mask]), max(shade[mask]))
shade[~mask] = min(shade[mask])
color = mcolors.to_rgba_array(color)
# shape of color should be (M, 4) (where M is number of faces)
# shape of shade should be (M,)
# colors should have final shape of (M, 4)
alpha = color[:, 3]
colors = (0.5 + norm(shade)[:, np.newaxis] * 0.5) * color
colors[:, 3] = alpha
else:
colors = np.asanyarray(color).copy()
return colors
def _shade_colors_lightsource(self, data, cmap, lightsource):
if lightsource is None:
lightsource = LightSource(azdeg=135, altdeg=55)
return lightsource.shade(data, cmap)
def plot_wireframe(self, X, Y, Z, *args, **kwargs):
"""
Plot a 3D wireframe.
.. note::
The *rcount* and *ccount* kwargs, which both default to 50,
determine the maximum number of samples used in each direction. If
the input data is larger, it will be downsampled (by slicing) to
these numbers of points.
Parameters
----------
X, Y, Z : 2d arrays
Data values.
rcount, ccount : int
Maximum number of samples used in each direction. If the input
data is larger, it will be downsampled (by slicing) to these
numbers of points. Setting a count to zero causes the data to be
not sampled in the corresponding direction, producing a 3D line
plot rather than a wireframe plot. Defaults to 50.
.. versionadded:: 2.0
rstride, cstride : int
Downsampling stride in each direction. These arguments are
mutually exclusive with *rcount* and *ccount*. If only one of
*rstride* or *cstride* is set, the other defaults to 1. Setting a
stride to zero causes the data to be not sampled in the
corresponding direction, producing a 3D line plot rather than a
wireframe plot.
'classic' mode uses a default of ``rstride = cstride = 1`` instead
of the new default of ``rcount = ccount = 50``.
**kwargs :
Other arguments are forwarded to `.Line3DCollection`.
"""
had_data = self.has_data()
if Z.ndim != 2:
raise ValueError("Argument Z must be 2-dimensional.")
# FIXME: Support masked arrays
X, Y, Z = np.broadcast_arrays(X, Y, Z)
rows, cols = Z.shape
has_stride = 'rstride' in kwargs or 'cstride' in kwargs
has_count = 'rcount' in kwargs or 'ccount' in kwargs
if has_stride and has_count:
raise ValueError("Cannot specify both stride and count arguments")
rstride = kwargs.pop('rstride', 1)
cstride = kwargs.pop('cstride', 1)
rcount = kwargs.pop('rcount', 50)
ccount = kwargs.pop('ccount', 50)
if rcParams['_internal.classic_mode']:
# Strides have priority over counts in classic mode.
# So, only compute strides from counts
# if counts were explicitly given
if has_count:
rstride = int(max(np.ceil(rows / rcount), 1)) if rcount else 0
cstride = int(max(np.ceil(cols / ccount), 1)) if ccount else 0
else:
# If the strides are provided then it has priority.
# Otherwise, compute the strides from the counts.
if not has_stride:
rstride = int(max(np.ceil(rows / rcount), 1)) if rcount else 0
cstride = int(max(np.ceil(cols / ccount), 1)) if ccount else 0
# We want two sets of lines, one running along the "rows" of
# Z and another set of lines running along the "columns" of Z.
# This transpose will make it easy to obtain the columns.
tX, tY, tZ = np.transpose(X), np.transpose(Y), np.transpose(Z)
if rstride:
rii = list(xrange(0, rows, rstride))
# Add the last index only if needed
if rows > 0 and rii[-1] != (rows - 1):
rii += [rows-1]
else:
rii = []
if cstride:
cii = list(xrange(0, cols, cstride))
# Add the last index only if needed
if cols > 0 and cii[-1] != (cols - 1):
cii += [cols-1]
else:
cii = []
if rstride == 0 and cstride == 0:
raise ValueError("Either rstride or cstride must be non zero")
# If the inputs were empty, then just
# reset everything.
if Z.size == 0:
rii = []
cii = []
xlines = [X[i] for i in rii]
ylines = [Y[i] for i in rii]
zlines = [Z[i] for i in rii]
txlines = [tX[i] for i in cii]
tylines = [tY[i] for i in cii]
tzlines = [tZ[i] for i in cii]
lines = ([list(zip(xl, yl, zl))
for xl, yl, zl in zip(xlines, ylines, zlines)]
+ [list(zip(xl, yl, zl))
for xl, yl, zl in zip(txlines, tylines, tzlines)])
linec = art3d.Line3DCollection(lines, *args, **kwargs)
self.add_collection(linec)
self.auto_scale_xyz(X, Y, Z, had_data)
return linec
def plot_trisurf(self, *args, **kwargs):
"""
============= ================================================
Argument Description
============= ================================================
*X*, *Y*, *Z* Data values as 1D arrays
*color* Color of the surface patches
*cmap* A colormap for the surface patches.
*norm* An instance of Normalize to map values to colors
*vmin* Minimum value to map
*vmax* Maximum value to map
*shade* Whether to shade the facecolors
============= ================================================
The (optional) triangulation can be specified in one of two ways;
either::
plot_trisurf(triangulation, ...)
where triangulation is a :class:`~matplotlib.tri.Triangulation`
object, or::
plot_trisurf(X, Y, ...)
plot_trisurf(X, Y, triangles, ...)
plot_trisurf(X, Y, triangles=triangles, ...)
in which case a Triangulation object will be created. See
:class:`~matplotlib.tri.Triangulation` for a explanation of
these possibilities.
The remaining arguments are::
plot_trisurf(..., Z)
where *Z* is the array of values to contour, one per point
in the triangulation.
Other arguments are passed on to
:class:`~mpl_toolkits.mplot3d.art3d.Poly3DCollection`
**Examples:**
.. plot:: gallery/mplot3d/trisurf3d.py
.. plot:: gallery/mplot3d/trisurf3d_2.py
.. versionadded:: 1.2.0
This plotting function was added for the v1.2.0 release.
"""
had_data = self.has_data()
# TODO: Support custom face colours
color = kwargs.pop('color', None)
if color is None:
color = self._get_lines.get_next_color()
color = np.array(mcolors.to_rgba(color))
cmap = kwargs.get('cmap', None)
norm = kwargs.pop('norm', None)
vmin = kwargs.pop('vmin', None)
vmax = kwargs.pop('vmax', None)
linewidth = kwargs.get('linewidth', None)
shade = kwargs.pop('shade', cmap is None)
lightsource = kwargs.pop('lightsource', None)
tri, args, kwargs = Triangulation.get_from_args_and_kwargs(*args, **kwargs)
if 'Z' in kwargs:
z = np.asarray(kwargs.pop('Z'))
else:
z = np.asarray(args[0])
# We do this so Z doesn't get passed as an arg to PolyCollection
args = args[1:]
triangles = tri.get_masked_triangles()
xt = tri.x[triangles]
yt = tri.y[triangles]
zt = z[triangles]
# verts = np.stack((xt, yt, zt), axis=-1)
verts = np.concatenate((
xt[..., np.newaxis], yt[..., np.newaxis], zt[..., np.newaxis]
), axis=-1)
polyc = art3d.Poly3DCollection(verts, *args, **kwargs)
if cmap:
# average over the three points of each triangle
avg_z = verts[:, :, 2].mean(axis=1)
polyc.set_array(avg_z)
if vmin is not None or vmax is not None:
polyc.set_clim(vmin, vmax)
if norm is not None:
polyc.set_norm(norm)
else:
if shade:
v1 = verts[:, 0, :] - verts[:, 1, :]
v2 = verts[:, 1, :] - verts[:, 2, :]
normals = np.cross(v1, v2)
colset = self._shade_colors(color, normals)
else:
colset = color
polyc.set_facecolors(colset)
self.add_collection(polyc)
self.auto_scale_xyz(tri.x, tri.y, z, had_data)
return polyc
def _3d_extend_contour(self, cset, stride=5):
'''
Extend a contour in 3D by creating
'''
levels = cset.levels
colls = cset.collections
dz = (levels[1] - levels[0]) / 2
for z, linec in zip(levels, colls):
topverts = art3d.paths_to_3d_segments(linec.get_paths(), z - dz)
botverts = art3d.paths_to_3d_segments(linec.get_paths(), z + dz)
color = linec.get_color()[0]
polyverts = []
normals = []
nsteps = np.round(len(topverts[0]) / stride)
if nsteps <= 1:
if len(topverts[0]) > 1:
nsteps = 2
else:
continue
stepsize = (len(topverts[0]) - 1) / (nsteps - 1)
for i in range(int(np.round(nsteps)) - 1):
i1 = int(np.round(i * stepsize))
i2 = int(np.round((i + 1) * stepsize))
polyverts.append([topverts[0][i1],
topverts[0][i2],
botverts[0][i2],
botverts[0][i1]])
v1 = np.array(topverts[0][i1]) - np.array(topverts[0][i2])
v2 = np.array(topverts[0][i1]) - np.array(botverts[0][i1])
normals.append(np.cross(v1, v2))
colors = self._shade_colors(color, normals)
colors2 = self._shade_colors(color, normals)
polycol = art3d.Poly3DCollection(polyverts,
facecolors=colors,
edgecolors=colors2)
polycol.set_sort_zpos(z)
self.add_collection3d(polycol)
for col in colls:
self.collections.remove(col)
def add_contour_set(self, cset, extend3d=False, stride=5, zdir='z', offset=None):
zdir = '-' + zdir
if extend3d:
self._3d_extend_contour(cset, stride)
else:
for z, linec in zip(cset.levels, cset.collections):
if offset is not None:
z = offset
art3d.line_collection_2d_to_3d(linec, z, zdir=zdir)
def add_contourf_set(self, cset, zdir='z', offset=None):
zdir = '-' + zdir
for z, linec in zip(cset.levels, cset.collections):
if offset is not None :
z = offset
art3d.poly_collection_2d_to_3d(linec, z, zdir=zdir)
linec.set_sort_zpos(z)
def contour(self, X, Y, Z, *args, **kwargs):
'''
Create a 3D contour plot.
========== ================================================
Argument Description
========== ================================================
*X*, *Y*, Data values as numpy.arrays
*Z*
*extend3d* Whether to extend contour in 3D (default: False)
*stride* Stride (step size) for extending contour
*zdir* The direction to use: x, y or z (default)
*offset* If specified plot a projection of the contour
lines on this position in plane normal to zdir
========== ================================================
The positional and other keyword arguments are passed on to
:func:`~matplotlib.axes.Axes.contour`
Returns a :class:`~matplotlib.axes.Axes.contour`
'''
extend3d = kwargs.pop('extend3d', False)
stride = kwargs.pop('stride', 5)
zdir = kwargs.pop('zdir', 'z')
offset = kwargs.pop('offset', None)
had_data = self.has_data()
jX, jY, jZ = art3d.rotate_axes(X, Y, Z, zdir)
cset = super(Axes3D, self).contour(jX, jY, jZ, *args, **kwargs)
self.add_contour_set(cset, extend3d, stride, zdir, offset)
self.auto_scale_xyz(X, Y, Z, had_data)
return cset
contour3D = contour
def tricontour(self, *args, **kwargs):
"""
Create a 3D contour plot.
========== ================================================
Argument Description
========== ================================================
*X*, *Y*, Data values as numpy.arrays
*Z*
*extend3d* Whether to extend contour in 3D (default: False)
*stride* Stride (step size) for extending contour
*zdir* The direction to use: x, y or z (default)
*offset* If specified plot a projection of the contour
lines on this position in plane normal to zdir
========== ================================================
Other keyword arguments are passed on to
:func:`~matplotlib.axes.Axes.tricontour`
Returns a :class:`~matplotlib.axes.Axes.contour`
.. versionchanged:: 1.3.0
Added support for custom triangulations
EXPERIMENTAL: This method currently produces incorrect output due to a
longstanding bug in 3D PolyCollection rendering.
"""
extend3d = kwargs.pop('extend3d', False)
stride = kwargs.pop('stride', 5)
zdir = kwargs.pop('zdir', 'z')
offset = kwargs.pop('offset', None)
had_data = self.has_data()
tri, args, kwargs = Triangulation.get_from_args_and_kwargs(
*args, **kwargs)
X = tri.x
Y = tri.y
if 'Z' in kwargs:
Z = kwargs.pop('Z')
else:
Z = args[0]
# We do this so Z doesn't get passed as an arg to Axes.tricontour
args = args[1:]
jX, jY, jZ = art3d.rotate_axes(X, Y, Z, zdir)
tri = Triangulation(jX, jY, tri.triangles, tri.mask)
cset = super(Axes3D, self).tricontour(tri, jZ, *args, **kwargs)
self.add_contour_set(cset, extend3d, stride, zdir, offset)
self.auto_scale_xyz(X, Y, Z, had_data)
return cset
def contourf(self, X, Y, Z, *args, **kwargs):
'''
Create a 3D contourf plot.
========== ================================================
Argument Description
========== ================================================
*X*, *Y*, Data values as numpy.arrays
*Z*
*zdir* The direction to use: x, y or z (default)
*offset* If specified plot a projection of the filled contour
on this position in plane normal to zdir
========== ================================================
The positional and keyword arguments are passed on to
:func:`~matplotlib.axes.Axes.contourf`
Returns a :class:`~matplotlib.axes.Axes.contourf`
.. versionchanged :: 1.1.0
The *zdir* and *offset* kwargs were added.
'''
zdir = kwargs.pop('zdir', 'z')
offset = kwargs.pop('offset', None)
had_data = self.has_data()
jX, jY, jZ = art3d.rotate_axes(X, Y, Z, zdir)
cset = super(Axes3D, self).contourf(jX, jY, jZ, *args, **kwargs)
self.add_contourf_set(cset, zdir, offset)
self.auto_scale_xyz(X, Y, Z, had_data)
return cset
contourf3D = contourf
def tricontourf(self, *args, **kwargs):
"""
Create a 3D contourf plot.
========== ================================================
Argument Description
========== ================================================
*X*, *Y*, Data values as numpy.arrays
*Z*
*zdir* The direction to use: x, y or z (default)
*offset* If specified plot a projection of the contour
lines on this position in plane normal to zdir
========== ================================================
Other keyword arguments are passed on to
:func:`~matplotlib.axes.Axes.tricontour`
Returns a :class:`~matplotlib.axes.Axes.contour`
.. versionchanged :: 1.3.0
Added support for custom triangulations
EXPERIMENTAL: This method currently produces incorrect output due to a
longstanding bug in 3D PolyCollection rendering.
"""
zdir = kwargs.pop('zdir', 'z')
offset = kwargs.pop('offset', None)
had_data = self.has_data()
tri, args, kwargs = Triangulation.get_from_args_and_kwargs(
*args, **kwargs)
X = tri.x
Y = tri.y
if 'Z' in kwargs:
Z = kwargs.pop('Z')
else:
Z = args[0]
# We do this so Z doesn't get passed as an arg to Axes.tricontourf
args = args[1:]
jX, jY, jZ = art3d.rotate_axes(X, Y, Z, zdir)
tri = Triangulation(jX, jY, tri.triangles, tri.mask)
cset = super(Axes3D, self).tricontourf(tri, jZ, *args, **kwargs)
self.add_contourf_set(cset, zdir, offset)
self.auto_scale_xyz(X, Y, Z, had_data)
return cset
def add_collection3d(self, col, zs=0, zdir='z'):
'''
Add a 3D collection object to the plot.
2D collection types are converted to a 3D version by
modifying the object and adding z coordinate information.
Supported are:
- PolyCollection
- LineCollection
- PatchCollection
'''
zvals = np.atleast_1d(zs)
if len(zvals) > 0 :
zsortval = min(zvals)
else :
zsortval = 0 # FIXME: Fairly arbitrary. Is there a better value?
# FIXME: use issubclass() (although, then a 3D collection
# object would also pass.) Maybe have a collection3d
# abstract class to test for and exclude?
if type(col) is mcoll.PolyCollection:
art3d.poly_collection_2d_to_3d(col, zs=zs, zdir=zdir)
col.set_sort_zpos(zsortval)
elif type(col) is mcoll.LineCollection:
art3d.line_collection_2d_to_3d(col, zs=zs, zdir=zdir)
col.set_sort_zpos(zsortval)
elif type(col) is mcoll.PatchCollection:
art3d.patch_collection_2d_to_3d(col, zs=zs, zdir=zdir)
col.set_sort_zpos(zsortval)
super(Axes3D, self).add_collection(col)
def scatter(self, xs, ys, zs=0, zdir='z', s=20, c=None, depthshade=True,
*args, **kwargs):
'''
Create a scatter plot.
============ ========================================================
Argument Description
============ ========================================================
*xs*, *ys* Positions of data points.
*zs* Either an array of the same length as *xs* and
*ys* or a single value to place all points in
the same plane. Default is 0.
*zdir* Which direction to use as z ('x', 'y' or 'z')
when plotting a 2D set.
*s* Size in points^2. It is a scalar or an array of the
same length as *x* and *y*.
*c* A color. *c* can be a single color format string, or a
sequence of color specifications of length *N*, or a
sequence of *N* numbers to be mapped to colors using the
*cmap* and *norm* specified via kwargs (see below). Note
that *c* should not be a single numeric RGB or RGBA
sequence because that is indistinguishable from an array
of values to be colormapped. *c* can be a 2-D array in
which the rows are RGB or RGBA, however, including the
case of a single row to specify the same color for
all points.
*depthshade*
Whether or not to shade the scatter markers to give
the appearance of depth. Default is *True*.
============ ========================================================
Keyword arguments are passed on to
:func:`~matplotlib.axes.Axes.scatter`.
Returns a :class:`~mpl_toolkits.mplot3d.art3d.Patch3DCollection`
'''
had_data = self.has_data()
xs, ys, zs = np.broadcast_arrays(
*[np.ravel(np.ma.filled(t, np.nan)) for t in [xs, ys, zs]])
s = np.ma.ravel(s) # This doesn't have to match x, y in size.
xs, ys, zs, s, c = cbook.delete_masked_points(xs, ys, zs, s, c)
patches = super(Axes3D, self).scatter(
xs, ys, s=s, c=c, *args, **kwargs)
is_2d = not cbook.iterable(zs)
zs = _backports.broadcast_to(zs, len(xs))
art3d.patch_collection_2d_to_3d(patches, zs=zs, zdir=zdir,
depthshade=depthshade)
if self._zmargin < 0.05 and xs.size > 0:
self.set_zmargin(0.05)
#FIXME: why is this necessary?
if not is_2d:
self.auto_scale_xyz(xs, ys, zs, had_data)
return patches
scatter3D = scatter
def bar(self, left, height, zs=0, zdir='z', *args, **kwargs):
'''
Add 2D bar(s).
========== ================================================
Argument Description
========== ================================================
*left* The x coordinates of the left sides of the bars.
*height* The height of the bars.
*zs* Z coordinate of bars, if one value is specified
they will all be placed at the same z.
*zdir* Which direction to use as z ('x', 'y' or 'z')
when plotting a 2D set.
========== ================================================
Keyword arguments are passed onto :func:`~matplotlib.axes.Axes.bar`.
Returns a :class:`~mpl_toolkits.mplot3d.art3d.Patch3DCollection`
'''
had_data = self.has_data()
patches = super(Axes3D, self).bar(left, height, *args, **kwargs)
zs = _backports.broadcast_to(zs, len(left))
verts = []
verts_zs = []
for p, z in zip(patches, zs):
vs = art3d.get_patch_verts(p)
verts += vs.tolist()
verts_zs += [z] * len(vs)
art3d.patch_2d_to_3d(p, z, zdir)
if 'alpha' in kwargs:
p.set_alpha(kwargs['alpha'])
if len(verts) > 0 :
# the following has to be skipped if verts is empty
# NOTE: Bugs could still occur if len(verts) > 0,
# but the "2nd dimension" is empty.
xs, ys = list(zip(*verts))
else :
xs, ys = [], []
xs, ys, verts_zs = art3d.juggle_axes(xs, ys, verts_zs, zdir)
self.auto_scale_xyz(xs, ys, verts_zs, had_data)
return patches
def bar3d(self, x, y, z, dx, dy, dz, color=None,
zsort='average', shade=True, *args, **kwargs):
"""Generate a 3D barplot.
This method creates three dimensional barplot where the width,
depth, height, and color of the bars can all be uniquely set.
Parameters
----------
x, y, z : array-like
The coordinates of the anchor point of the bars.
dx, dy, dz : scalar or array-like
The width, depth, and height of the bars, respectively.
color : sequence of valid color specifications, optional
The color of the bars can be specified globally or
individually. This parameter can be:
- A single color value, to color all bars the same color.
- An array of colors of length N bars, to color each bar
independently.
- An array of colors of length 6, to color the faces of the
bars similarly.
- An array of colors of length 6 * N bars, to color each face
independently.
When coloring the faces of the boxes specifically, this is
the order of the coloring:
1. -Z (bottom of box)
2. +Z (top of box)
3. -Y
4. +Y
5. -X
6. +X
zsort : str, optional
The z-axis sorting scheme passed onto
:func:`~mpl_toolkits.mplot3d.art3d.Poly3DCollection`
shade : bool, optional (default = True)
When true, this shades the dark sides of the bars (relative
to the plot's source of light).
Any additional keyword arguments are passed onto
:func:`~mpl_toolkits.mplot3d.art3d.Poly3DCollection`
Returns
-------
collection : Poly3DCollection
A collection of three dimensional polygons representing
the bars.
"""
had_data = self.has_data()
x, y, z, dx, dy, dz = np.broadcast_arrays(
np.atleast_1d(x), y, z, dx, dy, dz)
minx = np.min(x)
maxx = np.max(x + dx)
miny = np.min(y)
maxy = np.max(y + dy)
minz = np.min(z)
maxz = np.max(z + dz)
polys = []
for xi, yi, zi, dxi, dyi, dzi in zip(x, y, z, dx, dy, dz):
polys.extend([
((xi, yi, zi), (xi + dxi, yi, zi),
(xi + dxi, yi + dyi, zi), (xi, yi + dyi, zi)),
((xi, yi, zi + dzi), (xi + dxi, yi, zi + dzi),
(xi + dxi, yi + dyi, zi + dzi), (xi, yi + dyi, zi + dzi)),
((xi, yi, zi), (xi + dxi, yi, zi),
(xi + dxi, yi, zi + dzi), (xi, yi, zi + dzi)),
((xi, yi + dyi, zi), (xi + dxi, yi + dyi, zi),
(xi + dxi, yi + dyi, zi + dzi), (xi, yi + dyi, zi + dzi)),
((xi, yi, zi), (xi, yi + dyi, zi),
(xi, yi + dyi, zi + dzi), (xi, yi, zi + dzi)),
((xi + dxi, yi, zi), (xi + dxi, yi + dyi, zi),
(xi + dxi, yi + dyi, zi + dzi), (xi + dxi, yi, zi + dzi)),
])
facecolors = []
if color is None:
color = [self._get_patches_for_fill.get_next_color()]
if len(color) == len(x):
# bar colors specified, need to expand to number of faces
for c in color:
facecolors.extend([c] * 6)
else:
# a single color specified, or face colors specified explicitly
facecolors = list(mcolors.to_rgba_array(color))
if len(facecolors) < len(x):
facecolors *= (6 * len(x))
if shade:
normals = self._generate_normals(polys)
sfacecolors = self._shade_colors(facecolors, normals)
else:
sfacecolors = facecolors
col = art3d.Poly3DCollection(polys,
zsort=zsort,
facecolor=sfacecolors,
*args, **kwargs)
self.add_collection(col)
self.auto_scale_xyz((minx, maxx), (miny, maxy), (minz, maxz), had_data)
return col
def set_title(self, label, fontdict=None, loc='center', **kwargs):
ret = super(Axes3D, self).set_title(label, fontdict=fontdict, loc=loc,
**kwargs)
(x, y) = self.title.get_position()
self.title.set_y(0.92 * y)
return ret
set_title.__doc__ = maxes.Axes.set_title.__doc__
def quiver(self, *args, **kwargs):
"""
Plot a 3D field of arrows.
call signatures::
quiver(X, Y, Z, U, V, W, **kwargs)
Arguments:
*X*, *Y*, *Z*:
The x, y and z coordinates of the arrow locations (default is
tail of arrow; see *pivot* kwarg)
*U*, *V*, *W*:
The x, y and z components of the arrow vectors
The arguments could be array-like or scalars, so long as they
they can be broadcast together. The arguments can also be
masked arrays. If an element in any of argument is masked, then
that corresponding quiver element will not be plotted.
Keyword arguments:
*length*: [1.0 | float]
The length of each quiver, default to 1.0, the unit is
the same with the axes
*arrow_length_ratio*: [0.3 | float]
The ratio of the arrow head with respect to the quiver,
default to 0.3
*pivot*: [ 'tail' | 'middle' | 'tip' ]
The part of the arrow that is at the grid point; the arrow
rotates about this point, hence the name *pivot*.
Default is 'tail'
*normalize*: bool
When True, all of the arrows will be the same length. This
defaults to False, where the arrows will be different lengths
depending on the values of u,v,w.
Any additional keyword arguments are delegated to
:class:`~matplotlib.collections.LineCollection`
"""
def calc_arrow(uvw, angle=15):
"""
To calculate the arrow head. uvw should be a unit vector.
We normalize it here:
"""
# get unit direction vector perpendicular to (u,v,w)
norm = np.linalg.norm(uvw[:2])
if norm > 0:
x = uvw[1] / norm
y = -uvw[0] / norm
else:
x, y = 0, 1
# compute the two arrowhead direction unit vectors
ra = math.radians(angle)
c = math.cos(ra)
s = math.sin(ra)
# construct the rotation matrices
Rpos = np.array([[c+(x**2)*(1-c), x*y*(1-c), y*s],
[y*x*(1-c), c+(y**2)*(1-c), -x*s],
[-y*s, x*s, c]])
# opposite rotation negates all the sin terms
Rneg = Rpos.copy()
Rneg[[0,1,2,2],[2,2,0,1]] = -Rneg[[0,1,2,2],[2,2,0,1]]
# multiply them to get the rotated vector
return Rpos.dot(uvw), Rneg.dot(uvw)
had_data = self.has_data()
# handle kwargs
# shaft length
length = kwargs.pop('length', 1)
# arrow length ratio to the shaft length
arrow_length_ratio = kwargs.pop('arrow_length_ratio', 0.3)
# pivot point
pivot = kwargs.pop('pivot', 'tail')
# normalize
normalize = kwargs.pop('normalize', False)
# handle args
argi = 6
if len(args) < argi:
raise ValueError('Wrong number of arguments. Expected %d got %d' %
(argi, len(args)))
# first 6 arguments are X, Y, Z, U, V, W
input_args = args[:argi]
# if any of the args are scalar, convert into list
input_args = [[k] if isinstance(k, (int, float)) else k
for k in input_args]
# extract the masks, if any
masks = [k.mask for k in input_args if isinstance(k, np.ma.MaskedArray)]
# broadcast to match the shape
bcast = np.broadcast_arrays(*(input_args + masks))
input_args = bcast[:argi]
masks = bcast[argi:]
if masks:
# combine the masks into one
mask = reduce(np.logical_or, masks)
# put mask on and compress
input_args = [np.ma.array(k, mask=mask).compressed()
for k in input_args]
else:
input_args = [k.flatten() for k in input_args]
if any(len(v) == 0 for v in input_args):
# No quivers, so just make an empty collection and return early
linec = art3d.Line3DCollection([], *args[argi:], **kwargs)
self.add_collection(linec)
return linec
# Following assertions must be true before proceeding
# must all be ndarray
assert all(isinstance(k, np.ndarray) for k in input_args)
# must all in same shape
assert len({k.shape for k in input_args}) == 1
shaft_dt = np.linspace(0, length, num=2)
arrow_dt = shaft_dt * arrow_length_ratio
if pivot == 'tail':
shaft_dt -= length
elif pivot == 'middle':
shaft_dt -= length/2.
elif pivot != 'tip':
raise ValueError('Invalid pivot argument: ' + str(pivot))
XYZ = np.column_stack(input_args[:3])
UVW = np.column_stack(input_args[3:argi]).astype(float)
# Normalize rows of UVW
# Note: with numpy 1.9+, could use np.linalg.norm(UVW, axis=1)
norm = np.sqrt(np.sum(UVW**2, axis=1))
# If any row of UVW is all zeros, don't make a quiver for it
mask = norm > 0
XYZ = XYZ[mask]
if normalize:
UVW = UVW[mask] / norm[mask].reshape((-1, 1))
else:
UVW = UVW[mask]
if len(XYZ) > 0:
# compute the shaft lines all at once with an outer product
shafts = (XYZ - np.multiply.outer(shaft_dt, UVW)).swapaxes(0, 1)
# compute head direction vectors, n heads by 2 sides by 3 dimensions
head_dirs = np.array([calc_arrow(d) for d in UVW])
# compute all head lines at once, starting from where the shaft ends
heads = shafts[:, :1] - np.multiply.outer(arrow_dt, head_dirs)
# stack left and right head lines together
heads.shape = (len(arrow_dt), -1, 3)
# transpose to get a list of lines
heads = heads.swapaxes(0, 1)
lines = list(shafts) + list(heads)
else:
lines = []
linec = art3d.Line3DCollection(lines, *args[argi:], **kwargs)
self.add_collection(linec)
self.auto_scale_xyz(XYZ[:, 0], XYZ[:, 1], XYZ[:, 2], had_data)
return linec
quiver3D = quiver
def voxels(self, *args, **kwargs):
"""
ax.voxels([x, y, z,] /, filled, **kwargs)
Plot a set of filled voxels
All voxels are plotted as 1x1x1 cubes on the axis, with filled[0,0,0]
placed with its lower corner at the origin. Occluded faces are not
plotted.
Call signatures::
voxels(filled, facecolors=fc, edgecolors=ec, **kwargs)
voxels(x, y, z, filled, facecolors=fc, edgecolors=ec, **kwargs)
.. versionadded:: 2.1
Parameters
----------
filled : 3D np.array of bool
A 3d array of values, with truthy values indicating which voxels
to fill
x, y, z : 3D np.array, optional
The coordinates of the corners of the voxels. This should broadcast
to a shape one larger in every dimension than the shape of `filled`.
These can be used to plot non-cubic voxels.
If not specified, defaults to increasing integers along each axis,
like those returned by :func:`~numpy.indices`.
As indicated by the ``/`` in the function signature, these arguments
can only be passed positionally.
facecolors, edgecolors : array_like, optional
The color to draw the faces and edges of the voxels. Can only be
passed as keyword arguments.
This parameter can be:
- A single color value, to color all voxels the same color. This
can be either a string, or a 1D rgb/rgba array
- ``None``, the default, to use a single color for the faces, and
the style default for the edges.
- A 3D ndarray of color names, with each item the color for the
corresponding voxel. The size must match the voxels.
- A 4D ndarray of rgb/rgba data, with the components along the
last axis.
**kwargs
Additional keyword arguments to pass onto
:func:`~mpl_toolkits.mplot3d.art3d.Poly3DCollection`
Returns
-------
faces : dict
A dictionary indexed by coordinate, where ``faces[i,j,k]`` is a
`Poly3DCollection` of the faces drawn for the voxel
``filled[i,j,k]``. If no faces were drawn for a given voxel, either
because it was not asked to be drawn, or it is fully occluded, then
``(i,j,k) not in faces``.
Examples
--------
.. plot:: gallery/mplot3d/voxels.py
.. plot:: gallery/mplot3d/voxels_rgb.py
.. plot:: gallery/mplot3d/voxels_torus.py
.. plot:: gallery/mplot3d/voxels_numpy_logo.py
"""
# work out which signature we should be using, and use it to parse
# the arguments. Name must be voxels for the correct error message
if len(args) >= 3:
# underscores indicate position only
def voxels(__x, __y, __z, filled, **kwargs):
return (__x, __y, __z), filled, kwargs
else:
def voxels(filled, **kwargs):
return None, filled, kwargs
xyz, filled, kwargs = voxels(*args, **kwargs)
# check dimensions
if filled.ndim != 3:
raise ValueError("Argument filled must be 3-dimensional")
size = np.array(filled.shape, dtype=np.intp)
# check xyz coordinates, which are one larger than the filled shape
coord_shape = tuple(size + 1)
if xyz is None:
x, y, z = np.indices(coord_shape)
else:
x, y, z = (_backports.broadcast_to(c, coord_shape) for c in xyz)
def _broadcast_color_arg(color, name):
if np.ndim(color) in (0, 1):
# single color, like "red" or [1, 0, 0]
return _backports.broadcast_to(
color, filled.shape + np.shape(color))
elif np.ndim(color) in (3, 4):
# 3D array of strings, or 4D array with last axis rgb
if np.shape(color)[:3] != filled.shape:
raise ValueError(
"When multidimensional, {} must match the shape of "
"filled".format(name))
return color
else:
raise ValueError("Invalid {} argument".format(name))
# intercept the facecolors, handling defaults and broacasting
facecolors = kwargs.pop('facecolors', None)
if facecolors is None:
facecolors = self._get_patches_for_fill.get_next_color()
facecolors = _broadcast_color_arg(facecolors, 'facecolors')
# broadcast but no default on edgecolors
edgecolors = kwargs.pop('edgecolors', None)
edgecolors = _broadcast_color_arg(edgecolors, 'edgecolors')
# always scale to the full array, even if the data is only in the center
self.auto_scale_xyz(x, y, z)
# points lying on corners of a square
square = np.array([
[0, 0, 0],
[0, 1, 0],
[1, 1, 0],
[1, 0, 0]
], dtype=np.intp)
voxel_faces = defaultdict(list)
def permutation_matrices(n):
""" Generator of cyclic permutation matices """
mat = np.eye(n, dtype=np.intp)
for i in range(n):
yield mat
mat = np.roll(mat, 1, axis=0)
# iterate over each of the YZ, ZX, and XY orientations, finding faces to
# render
for permute in permutation_matrices(3):
# find the set of ranges to iterate over
pc, qc, rc = permute.T.dot(size)
pinds = np.arange(pc)
qinds = np.arange(qc)
rinds = np.arange(rc)
square_rot = square.dot(permute.T)
# iterate within the current plane
for p in pinds:
for q in qinds:
# iterate perpendicularly to the current plane, handling
# boundaries. We only draw faces between a voxel and an
# empty space, to avoid drawing internal faces.
# draw lower faces
p0 = permute.dot([p, q, 0])
i0 = tuple(p0)
if filled[i0]:
voxel_faces[i0].append(p0 + square_rot)
# draw middle faces
for r1, r2 in zip(rinds[:-1], rinds[1:]):
p1 = permute.dot([p, q, r1])
p2 = permute.dot([p, q, r2])
i1 = tuple(p1)
i2 = tuple(p2)
if filled[i1] and not filled[i2]:
voxel_faces[i1].append(p2 + square_rot)
elif not filled[i1] and filled[i2]:
voxel_faces[i2].append(p2 + square_rot)
# draw upper faces
pk = permute.dot([p, q, rc-1])
pk2 = permute.dot([p, q, rc])
ik = tuple(pk)
if filled[ik]:
voxel_faces[ik].append(pk2 + square_rot)
# iterate over the faces, and generate a Poly3DCollection for each voxel
polygons = {}
for coord, faces_inds in voxel_faces.items():
# convert indices into 3D positions
if xyz is None:
faces = faces_inds
else:
faces = []
for face_inds in faces_inds:
ind = face_inds[:, 0], face_inds[:, 1], face_inds[:, 2]
face = np.empty(face_inds.shape)
face[:, 0] = x[ind]
face[:, 1] = y[ind]
face[:, 2] = z[ind]
faces.append(face)
poly = art3d.Poly3DCollection(faces,
facecolors=facecolors[coord],
edgecolors=edgecolors[coord],
**kwargs
)
self.add_collection3d(poly)
polygons[coord] = poly
return polygons
def get_test_data(delta=0.05):
'''
Return a tuple X, Y, Z with a test data set.
'''
x = y = np.arange(-3.0, 3.0, delta)
X, Y = np.meshgrid(x, y)
Z1 = np.exp(-(X**2 + Y**2) / 2) / (2 * np.pi)
Z2 = (np.exp(-(((X - 1) / 1.5)**2 + ((Y - 1) / 0.5)**2) / 2) /
(2 * np.pi * 0.5 * 1.5))
Z = Z2 - Z1
X = X * 10
Y = Y * 10
Z = Z * 500
return X, Y, Z
########################################################
# Register Axes3D as a 'projection' object available
# for use just like any other axes
########################################################
import matplotlib.projections as proj
proj.projection_registry.register(Axes3D)
| 105,431 | 34.630956 | 89 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpl_toolkits/mplot3d/__init__.py
|
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import six
from .axes3d import Axes3D
| 149 | 20.428571 | 66 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/mpl_toolkits/mplot3d/axis3d.py
|
# axis3d.py, original mplot3d version by John Porter
# Created: 23 Sep 2005
# Parts rewritten by Reinier Heeres <reinier@heeres.eu>
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import six
import math
import copy
from matplotlib import lines as mlines, axis as maxis, patches as mpatches
from matplotlib import rcParams
from . import art3d
from . import proj3d
import numpy as np
def get_flip_min_max(coord, index, mins, maxs):
if coord[index] == mins[index]:
return maxs[index]
else:
return mins[index]
def move_from_center(coord, centers, deltas, axmask=(True, True, True)):
'''Return a coordinate that is moved by "deltas" away from the center.'''
coord = copy.copy(coord)
for i in range(3):
if not axmask[i]:
continue
if coord[i] < centers[i]:
coord[i] -= deltas[i]
else:
coord[i] += deltas[i]
return coord
def tick_update_position(tick, tickxs, tickys, labelpos):
'''Update tick line and label position and style.'''
for (label, on) in [(tick.label1, tick.label1On),
(tick.label2, tick.label2On)]:
if on:
label.set_position(labelpos)
tick.tick1On, tick.tick2On = True, False
tick.tick1line.set_linestyle('-')
tick.tick1line.set_marker('')
tick.tick1line.set_data(tickxs, tickys)
tick.gridline.set_data(0, 0)
class Axis(maxis.XAxis):
# These points from the unit cube make up the x, y and z-planes
_PLANES = (
(0, 3, 7, 4), (1, 2, 6, 5), # yz planes
(0, 1, 5, 4), (3, 2, 6, 7), # xz planes
(0, 1, 2, 3), (4, 5, 6, 7), # xy planes
)
# Some properties for the axes
_AXINFO = {
'x': {'i': 0, 'tickdir': 1, 'juggled': (1, 0, 2),
'color': (0.95, 0.95, 0.95, 0.5)},
'y': {'i': 1, 'tickdir': 0, 'juggled': (0, 1, 2),
'color': (0.90, 0.90, 0.90, 0.5)},
'z': {'i': 2, 'tickdir': 0, 'juggled': (0, 2, 1),
'color': (0.925, 0.925, 0.925, 0.5)},
}
def __init__(self, adir, v_intervalx, d_intervalx, axes, *args, **kwargs):
# adir identifies which axes this is
self.adir = adir
# data and viewing intervals for this direction
self.d_interval = d_intervalx
self.v_interval = v_intervalx
# This is a temporary member variable.
# Do not depend on this existing in future releases!
self._axinfo = self._AXINFO[adir].copy()
if rcParams['_internal.classic_mode']:
self._axinfo.update(
{'label': {'va': 'center',
'ha': 'center'},
'tick': {'inward_factor': 0.2,
'outward_factor': 0.1,
'linewidth': rcParams['lines.linewidth'],
'color': 'k'},
'axisline': {'linewidth': 0.75,
'color': (0, 0, 0, 1)},
'grid': {'color': (0.9, 0.9, 0.9, 1),
'linewidth': 1.0,
'linestyle': '-'},
})
else:
self._axinfo.update(
{'label': {'va': 'center',
'ha': 'center'},
'tick': {'inward_factor': 0.2,
'outward_factor': 0.1,
'linewidth': rcParams.get(
adir + 'tick.major.width',
rcParams['xtick.major.width']),
'color': rcParams.get(
adir + 'tick.color',
rcParams['xtick.color'])},
'axisline': {'linewidth': rcParams['axes.linewidth'],
'color': rcParams['axes.edgecolor']},
'grid': {'color': rcParams['grid.color'],
'linewidth': rcParams['grid.linewidth'],
'linestyle': rcParams['grid.linestyle']},
})
maxis.XAxis.__init__(self, axes, *args, **kwargs)
self.set_rotate_label(kwargs.get('rotate_label', None))
def init3d(self):
self.line = mlines.Line2D(
xdata=(0, 0), ydata=(0, 0),
linewidth=self._axinfo['axisline']['linewidth'],
color=self._axinfo['axisline']['color'],
antialiased=True)
# Store dummy data in Polygon object
self.pane = mpatches.Polygon(
np.array([[0, 0], [0, 1], [1, 0], [0, 0]]),
closed=False, alpha=0.8, facecolor='k', edgecolor='k')
self.set_pane_color(self._axinfo['color'])
self.axes._set_artist_props(self.line)
self.axes._set_artist_props(self.pane)
self.gridlines = art3d.Line3DCollection([])
self.axes._set_artist_props(self.gridlines)
self.axes._set_artist_props(self.label)
self.axes._set_artist_props(self.offsetText)
# Need to be able to place the label at the correct location
self.label._transform = self.axes.transData
self.offsetText._transform = self.axes.transData
def get_tick_positions(self):
majorLocs = self.major.locator()
self.major.formatter.set_locs(majorLocs)
majorLabels = [self.major.formatter(val, i)
for i, val in enumerate(majorLocs)]
return majorLabels, majorLocs
def get_major_ticks(self, numticks=None):
ticks = maxis.XAxis.get_major_ticks(self, numticks)
for t in ticks:
t.tick1line.set_transform(self.axes.transData)
t.tick2line.set_transform(self.axes.transData)
t.gridline.set_transform(self.axes.transData)
t.label1.set_transform(self.axes.transData)
t.label2.set_transform(self.axes.transData)
return ticks
def set_pane_pos(self, xys):
xys = np.asarray(xys)
xys = xys[:,:2]
self.pane.xy = xys
self.stale = True
def set_pane_color(self, color):
'''Set pane color to a RGBA tuple.'''
self._axinfo['color'] = color
self.pane.set_edgecolor(color)
self.pane.set_facecolor(color)
self.pane.set_alpha(color[-1])
self.stale = True
def set_rotate_label(self, val):
'''
Whether to rotate the axis label: True, False or None.
If set to None the label will be rotated if longer than 4 chars.
'''
self._rotate_label = val
self.stale = True
def get_rotate_label(self, text):
if self._rotate_label is not None:
return self._rotate_label
else:
return len(text) > 4
def _get_coord_info(self, renderer):
minx, maxx, miny, maxy, minz, maxz = self.axes.get_w_lims()
if minx > maxx:
minx, maxx = maxx, minx
if miny > maxy:
miny, maxy = maxy, miny
if minz > maxz:
minz, maxz = maxz, minz
mins = np.array((minx, miny, minz))
maxs = np.array((maxx, maxy, maxz))
centers = (maxs + mins) / 2.
deltas = (maxs - mins) / 12.
mins = mins - deltas / 4.
maxs = maxs + deltas / 4.
vals = mins[0], maxs[0], mins[1], maxs[1], mins[2], maxs[2]
tc = self.axes.tunit_cube(vals, renderer.M)
avgz = [tc[p1][2] + tc[p2][2] + tc[p3][2] + tc[p4][2]
for p1, p2, p3, p4 in self._PLANES]
highs = np.array([avgz[2*i] < avgz[2*i+1] for i in range(3)])
return mins, maxs, centers, deltas, tc, highs
def draw_pane(self, renderer):
renderer.open_group('pane3d')
mins, maxs, centers, deltas, tc, highs = self._get_coord_info(renderer)
info = self._axinfo
index = info['i']
if not highs[index]:
plane = self._PLANES[2 * index]
else:
plane = self._PLANES[2 * index + 1]
xys = [tc[p] for p in plane]
self.set_pane_pos(xys)
self.pane.draw(renderer)
renderer.close_group('pane3d')
def draw(self, renderer):
self.label._transform = self.axes.transData
renderer.open_group('axis3d')
# code from XAxis
majorTicks = self.get_major_ticks()
majorLocs = self.major.locator()
info = self._axinfo
index = info['i']
# filter locations here so that no extra grid lines are drawn
locmin, locmax = self.get_view_interval()
if locmin > locmax:
locmin, locmax = locmax, locmin
# Rudimentary clipping
majorLocs = [loc for loc in majorLocs if
locmin <= loc <= locmax]
self.major.formatter.set_locs(majorLocs)
majorLabels = [self.major.formatter(val, i)
for i, val in enumerate(majorLocs)]
mins, maxs, centers, deltas, tc, highs = self._get_coord_info(renderer)
# Determine grid lines
minmax = np.where(highs, maxs, mins)
# Draw main axis line
juggled = info['juggled']
edgep1 = minmax.copy()
edgep1[juggled[0]] = get_flip_min_max(edgep1, juggled[0], mins, maxs)
edgep2 = edgep1.copy()
edgep2[juggled[1]] = get_flip_min_max(edgep2, juggled[1], mins, maxs)
pep = proj3d.proj_trans_points([edgep1, edgep2], renderer.M)
centpt = proj3d.proj_transform(
centers[0], centers[1], centers[2], renderer.M)
self.line.set_data((pep[0][0], pep[0][1]), (pep[1][0], pep[1][1]))
self.line.draw(renderer)
# Grid points where the planes meet
xyz0 = []
for val in majorLocs:
coord = minmax.copy()
coord[index] = val
xyz0.append(coord)
# Draw labels
peparray = np.asanyarray(pep)
# The transAxes transform is used because the Text object
# rotates the text relative to the display coordinate system.
# Therefore, if we want the labels to remain parallel to the
# axis regardless of the aspect ratio, we need to convert the
# edge points of the plane to display coordinates and calculate
# an angle from that.
# TODO: Maybe Text objects should handle this themselves?
dx, dy = (self.axes.transAxes.transform([peparray[0:2, 1]]) -
self.axes.transAxes.transform([peparray[0:2, 0]]))[0]
lxyz = 0.5*(edgep1 + edgep2)
# A rough estimate; points are ambiguous since 3D plots rotate
ax_scale = self.axes.bbox.size / self.figure.bbox.size
ax_inches = np.multiply(ax_scale, self.figure.get_size_inches())
ax_points_estimate = sum(72. * ax_inches)
deltas_per_point = 48. / ax_points_estimate
default_offset = 21.
labeldeltas = (
(self.labelpad + default_offset) * deltas_per_point * deltas)
axmask = [True, True, True]
axmask[index] = False
lxyz = move_from_center(lxyz, centers, labeldeltas, axmask)
tlx, tly, tlz = proj3d.proj_transform(lxyz[0], lxyz[1], lxyz[2],
renderer.M)
self.label.set_position((tlx, tly))
if self.get_rotate_label(self.label.get_text()):
angle = art3d.norm_text_angle(math.degrees(math.atan2(dy, dx)))
self.label.set_rotation(angle)
self.label.set_va(info['label']['va'])
self.label.set_ha(info['label']['ha'])
self.label.draw(renderer)
# Draw Offset text
# Which of the two edge points do we want to
# use for locating the offset text?
if juggled[2] == 2 :
outeredgep = edgep1
outerindex = 0
else :
outeredgep = edgep2
outerindex = 1
pos = copy.copy(outeredgep)
pos = move_from_center(pos, centers, labeldeltas, axmask)
olx, oly, olz = proj3d.proj_transform(
pos[0], pos[1], pos[2], renderer.M)
self.offsetText.set_text( self.major.formatter.get_offset() )
self.offsetText.set_position( (olx, oly) )
angle = art3d.norm_text_angle(math.degrees(math.atan2(dy, dx)))
self.offsetText.set_rotation(angle)
# Must set rotation mode to "anchor" so that
# the alignment point is used as the "fulcrum" for rotation.
self.offsetText.set_rotation_mode('anchor')
#----------------------------------------------------------------------
# Note: the following statement for determining the proper alignment of
# the offset text. This was determined entirely by trial-and-error
# and should not be in any way considered as "the way". There are
# still some edge cases where alignment is not quite right, but this
# seems to be more of a geometry issue (in other words, I might be
# using the wrong reference points).
#
# (TT, FF, TF, FT) are the shorthand for the tuple of
# (centpt[info['tickdir']] <= peparray[info['tickdir'], outerindex],
# centpt[index] <= peparray[index, outerindex])
#
# Three-letters (e.g., TFT, FTT) are short-hand for the array of bools
# from the variable 'highs'.
# ---------------------------------------------------------------------
if centpt[info['tickdir']] > peparray[info['tickdir'], outerindex] :
# if FT and if highs has an even number of Trues
if (centpt[index] <= peparray[index, outerindex]
and ((len(highs.nonzero()[0]) % 2) == 0)) :
# Usually, this means align right, except for the FTT case,
# in which offset for axis 1 and 2 are aligned left.
if highs.tolist() == [False, True, True] and index in (1, 2) :
align = 'left'
else :
align = 'right'
else :
# The FF case
align = 'left'
else :
# if TF and if highs has an even number of Trues
if (centpt[index] > peparray[index, outerindex]
and ((len(highs.nonzero()[0]) % 2) == 0)) :
# Usually mean align left, except if it is axis 2
if index == 2 :
align = 'right'
else :
align = 'left'
else :
# The TT case
align = 'right'
self.offsetText.set_va('center')
self.offsetText.set_ha(align)
self.offsetText.draw(renderer)
# Draw grid lines
if len(xyz0) > 0:
# Grid points at end of one plane
xyz1 = copy.deepcopy(xyz0)
newindex = (index + 1) % 3
newval = get_flip_min_max(xyz1[0], newindex, mins, maxs)
for i in range(len(majorLocs)):
xyz1[i][newindex] = newval
# Grid points at end of the other plane
xyz2 = copy.deepcopy(xyz0)
newindex = (index + 2) % 3
newval = get_flip_min_max(xyz2[0], newindex, mins, maxs)
for i in range(len(majorLocs)):
xyz2[i][newindex] = newval
lines = list(zip(xyz1, xyz0, xyz2))
if self.axes._draw_grid:
self.gridlines.set_segments(lines)
self.gridlines.set_color([info['grid']['color']] * len(lines))
self.gridlines.set_linewidth(
[info['grid']['linewidth']] * len(lines))
self.gridlines.set_linestyle(
[info['grid']['linestyle']] * len(lines))
self.gridlines.draw(renderer, project=True)
# Draw ticks
tickdir = info['tickdir']
tickdelta = deltas[tickdir]
if highs[tickdir]:
ticksign = 1
else:
ticksign = -1
for tick, loc, label in zip(majorTicks, majorLocs, majorLabels):
if tick is None:
continue
# Get tick line positions
pos = copy.copy(edgep1)
pos[index] = loc
pos[tickdir] = (
edgep1[tickdir]
+ info['tick']['outward_factor'] * ticksign * tickdelta)
x1, y1, z1 = proj3d.proj_transform(pos[0], pos[1], pos[2],
renderer.M)
pos[tickdir] = (
edgep1[tickdir]
- info['tick']['inward_factor'] * ticksign * tickdelta)
x2, y2, z2 = proj3d.proj_transform(pos[0], pos[1], pos[2],
renderer.M)
# Get position of label
default_offset = 8. # A rough estimate
labeldeltas = (
(tick.get_pad() + default_offset) * deltas_per_point * deltas)
axmask = [True, True, True]
axmask[index] = False
pos[tickdir] = edgep1[tickdir]
pos = move_from_center(pos, centers, labeldeltas, axmask)
lx, ly, lz = proj3d.proj_transform(pos[0], pos[1], pos[2],
renderer.M)
tick_update_position(tick, (x1, x2), (y1, y2), (lx, ly))
tick.tick1line.set_linewidth(info['tick']['linewidth'])
tick.tick1line.set_color(info['tick']['color'])
tick.set_label1(label)
tick.set_label2(label)
tick.draw(renderer)
renderer.close_group('axis3d')
self.stale = False
def get_view_interval(self):
"""return the Interval instance for this 3d axis view limits"""
return self.v_interval
def set_view_interval(self, vmin, vmax, ignore=False):
if ignore:
self.v_interval = vmin, vmax
else:
Vmin, Vmax = self.get_view_interval()
self.v_interval = min(vmin, Vmin), max(vmax, Vmax)
# TODO: Get this to work properly when mplot3d supports
# the transforms framework.
def get_tightbbox(self, renderer) :
# Currently returns None so that Axis.get_tightbbox
# doesn't return junk info.
return None
# Use classes to look at different data limits
class XAxis(Axis):
def get_data_interval(self):
'return the Interval instance for this axis data limits'
return self.axes.xy_dataLim.intervalx
class YAxis(Axis):
def get_data_interval(self):
'return the Interval instance for this axis data limits'
return self.axes.xy_dataLim.intervaly
class ZAxis(Axis):
def get_data_interval(self):
'return the Interval instance for this axis data limits'
return self.axes.zz_dataLim.intervalx
| 18,704 | 37.56701 | 79 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/pyglet/clock.py
|
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
"""Precise framerate calculation, scheduling and framerate limiting.
Measuring time
==============
The `tick` and `get_fps` functions can be used in conjunction to fulfil most
games' basic requirements::
from pyglet import clock
while True:
dt = clock.tick()
# ... update and render ...
print 'FPS is %f' % clock.get_fps()
The ``dt`` value returned gives the number of seconds (as a float) since the
last "tick".
The `get_fps` function averages the framerate over a sliding window of
approximately 1 second. (You can calculate the instantaneous framerate by
taking the reciprocal of ``dt``).
Always remember to `tick` the clock!
Limiting frame-rate
===================
The framerate can be limited::
clock.set_fps_limit(60)
This causes :py:class:`~pyglet.clock.Clock` to sleep during each `tick` in an
attempt to keep the number of ticks (frames) per second below 60.
The implementation uses platform-dependent high-resolution sleep functions
to achieve better accuracy with busy-waiting than would be possible using
just the `time` module.
Scheduling
==========
You can schedule a function to be called every time the clock is ticked::
def callback(dt):
print '%f seconds since last callback' % dt
clock.schedule(callback)
The `schedule_interval` method causes a function to be called every "n"
seconds::
clock.schedule_interval(callback, .5) # called twice a second
The `schedule_once` method causes a function to be called once "n" seconds
in the future::
clock.schedule_once(callback, 5) # called in 5 seconds
All of the `schedule` methods will pass on any additional args or keyword args
you specify to the callback function::
def animate(dt, velocity, sprite):
sprite.position += dt * velocity
clock.schedule(animate, velocity=5.0, sprite=alien)
You can cancel a function scheduled with any of these methods using
`unschedule`::
clock.unschedule(animate)
Displaying FPS
==============
The ClockDisplay class provides a simple FPS counter. You should create
an instance of ClockDisplay once during the application's start up::
fps_display = clock.ClockDisplay()
Call draw on the ClockDisplay object for each frame::
fps_display.draw()
There are several options to change the font, color and text displayed
within the __init__ method.
Using multiple clocks
=====================
The clock functions are all relayed to an instance of
:py:class:`~pyglet.clock.Clock` which is initialised with the module. You can
get this instance to use directly::
clk = clock.get_default()
You can also replace the default clock with your own:
myclk = clock.Clock()
clock.set_default(myclk)
Each clock maintains its own set of scheduled functions and FPS
limiting/measurement. Each clock must be "ticked" separately.
Multiple and derived clocks potentially allow you to separate "game-time" and
"wall-time", or to synchronise your clock to an audio or video stream instead
of the system clock.
"""
from __future__ import print_function
from __future__ import division
from builtins import range
from builtins import object
import time
import ctypes
from operator import attrgetter
from heapq import heappush, heappop, heappushpop
from collections import deque
import pyglet.lib
from pyglet import compat_platform
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
if compat_platform in ('win32', 'cygwin'):
class _ClockBase(object):
def sleep(self, microseconds):
time.sleep(microseconds * 1e-6)
_default_time_function = time.clock
else:
_c = pyglet.lib.load_library('c')
_c.usleep.argtypes = [ctypes.c_ulong]
class _ClockBase(object):
def sleep(self, microseconds):
_c.usleep(int(microseconds))
_default_time_function = time.time
class _ScheduledItem(object):
__slots__ = ['func', 'args', 'kwargs']
def __init__(self, func, args, kwargs):
self.func = func
self.args = args
self.kwargs = kwargs
class _ScheduledIntervalItem(object):
__slots__ = ['func', 'interval', 'last_ts', 'next_ts',
'args', 'kwargs']
def __init__(self, func, interval, last_ts, next_ts, args, kwargs):
self.func = func
self.interval = interval
self.last_ts = last_ts
self.next_ts = next_ts
self.args = args
self.kwargs = kwargs
def __lt__(self, other):
try:
return self.next_ts < other.next_ts
except AttributeError:
return self.next_ts < other
class Clock(_ClockBase):
"""Class for calculating and limiting framerate.
It is also used for calling scheduled functions.
"""
#: The minimum amount of time in seconds this clock will attempt to sleep
#: for when framerate limiting. Higher values will increase the
#: accuracy of the limiting but also increase CPU usage while
#: busy-waiting. Lower values mean the process sleeps more often, but is
#: prone to over-sleep and run at a potentially lower or uneven framerate
#: than desired.
#: On Windows, MIN_SLEEP is larger because the default timer resolution
#: is set by default to 15 .6 ms.
MIN_SLEEP = 0.008 if compat_platform in ('win32', 'cygwin') else 0.005
#: The amount of time in seconds this clock subtracts from sleep values
#: to compensate for lazy operating systems.
SLEEP_UNDERSHOOT = MIN_SLEEP - 0.001
# List of functions to call every tick.
_schedule_items = None
# List of schedule interval items kept in sort order.
_schedule_interval_items = None
# If True, a sleep(0) is inserted on every tick.
_force_sleep = False
def __init__(self, fps_limit=None, time_function=_default_time_function):
"""Initialise a Clock, with optional framerate limit and custom time function.
:Parameters:
`fps_limit` : float
If not None, the maximum allowable framerate. Defaults
to None. Deprecated in pyglet 1.2.
`time_function` : function
Function to return the elapsed time of the application,
in seconds. Defaults to time.time, but can be replaced
to allow for easy time dilation effects or game pausing.
"""
super(Clock, self).__init__()
self.time = time_function
self.next_ts = self.time()
self.last_ts = None
self.times = deque()
self.set_fps_limit(fps_limit)
self.cumulative_time = 0
self._schedule_items = []
self._schedule_interval_items = []
self._current_interval_item = None
def update_time(self):
"""Get the elapsed time since the last call to `update_time`.
This updates the clock's internal measure of time and returns
the difference since the last update (or since the clock was created).
.. versionadded:: 1.2
:rtype: float
:return: The number of seconds since the last `update_time`, or 0
if this was the first time it was called.
"""
ts = self.time()
if self.last_ts is None:
delta_t = 0
else:
delta_t = ts - self.last_ts
self.times.appendleft(delta_t)
if len(self.times) > self.window_size:
self.cumulative_time -= self.times.pop()
self.cumulative_time += delta_t
self.last_ts = ts
return delta_t
def call_scheduled_functions(self, dt):
"""Call scheduled functions that elapsed on the last `update_time`.
.. versionadded:: 1.2
:Parameters:
dt : float
The elapsed time since the last update to pass to each
scheduled function. This is *not* used to calculate which
functions have elapsed.
:rtype: bool
:return: True if any functions were called, otherwise False.
"""
now = self.last_ts
result = False # flag indicates if any function was called
# handle items scheduled for every tick
if self._schedule_items:
result = True
# duplicate list in case event unschedules itself
for item in list(self._schedule_items):
item.func(dt, *item.args, **item.kwargs)
# check the next scheduled item that is not called each tick
# if it is scheduled in the future, then exit
interval_items = self._schedule_interval_items
try:
if interval_items[0].next_ts > now:
return result
# raised when the interval_items list is empty
except IndexError:
return result
# NOTE: there is no special handling required to manage things
# that are scheduled during this loop, due to the heap
self._current_interval_item = item = None
get_soft_next_ts = self._get_soft_next_ts
while interval_items:
# the scheduler will hold onto a reference to an item in
# case it needs to be rescheduled. it is more efficient
# to push and pop the heap at once rather than two operations
if item is None:
item = heappop(interval_items)
else:
item = heappushpop(interval_items, item)
# a scheduled function may try and unschedule itself
# so we need to keep a reference to the current
# item no longer on heap to be able to check
self._current_interval_item = item
# if next item is scheduled in the future then break
if item.next_ts > now:
break
# execute the callback
item.func(now - item.last_ts, *item.args, **item.kwargs)
if item.interval:
# Try to keep timing regular, even if overslept this time;
# but don't schedule in the past (which could lead to
# infinitely-worsening error).
item.next_ts = item.last_ts + item.interval
item.last_ts = now
# test the schedule for the next execution
if item.next_ts <= now:
# the scheduled time of this item has already passed
# so it must be rescheduled
if now - item.next_ts < 0.05:
# missed execution time by 'reasonable' amount, so
# reschedule at normal interval
item.next_ts = now + item.interval
else:
# missed by significant amount, now many events have
# likely missed execution. do a soft reschedule to
# avoid lumping many events together.
# in this case, the next dt will not be accurate
item.next_ts = get_soft_next_ts(now, item.interval)
item.last_ts = item.next_ts - item.interval
else:
# not an interval, so this item will not be rescheduled
self._current_interval_item = item = None
if item is not None:
heappush(interval_items, item)
return True
def tick(self, poll=False):
"""Signify that one frame has passed.
This will call any scheduled functions that have elapsed.
:Parameters:
`poll` : bool
If True, the function will call any scheduled functions
but will not sleep or busy-wait for any reason. Recommended
for advanced applications managing their own sleep timers
only.
Since pyglet 1.1.
:rtype: float
:return: The number of seconds since the last "tick", or 0 if this was
the first frame.
"""
if poll:
if self.period_limit:
self.next_ts += self.period_limit
else:
if self.period_limit:
self._limit()
if self._force_sleep:
self.sleep(0)
delta_t = self.update_time()
self.call_scheduled_functions(delta_t)
return delta_t
def _limit(self):
"""Sleep until the next frame is due.
Called automatically by :meth:`.tick` if a framerate limit has been
set.
This method uses several heuristics to determine whether to
sleep or busy-wait (or both).
"""
ts = self.time()
# Sleep to just before the desired time
sleeptime = self.get_sleep_time(False)
while sleeptime - self.SLEEP_UNDERSHOOT > self.MIN_SLEEP:
self.sleep(1000000 * (sleeptime - self.SLEEP_UNDERSHOOT))
sleeptime = self.get_sleep_time(False)
# Busy-loop CPU to get closest to the mark
sleeptime = self.next_ts - self.time()
while sleeptime > 0:
sleeptime = self.next_ts - self.time()
if sleeptime < -2 * self.period_limit:
# Missed the time by a long shot, let's reset the clock
# print >> sys.stderr, 'Step %f' % -sleeptime
self.next_ts = ts + 2 * self.period_limit
else:
# Otherwise keep the clock steady
self.next_ts += self.period_limit
def get_sleep_time(self, sleep_idle):
"""Get the time until the next item is scheduled.
This method considers all scheduled items and the current
``fps_limit``, if any.
Applications can choose to continue receiving updates at the
maximum framerate during idle time (when no functions are scheduled),
or they can sleep through their idle time and allow the CPU to
switch to other processes or run in low-power mode.
If `sleep_idle` is ``True`` the latter behaviour is selected, and
``None`` will be returned if there are no scheduled items.
Otherwise, if `sleep_idle` is ``False``, a sleep time allowing
the maximum possible framerate (considering ``fps_limit``) will
be returned; or an earlier time if a scheduled function is ready.
:Parameters:
`sleep_idle` : bool
If True, the application intends to sleep through its idle
time; otherwise it will continue ticking at the maximum
frame rate allowed.
:rtype: float
:return: Time until the next scheduled event in seconds, or ``None``
if there is no event scheduled.
.. versionadded:: 1.1
"""
if self._schedule_items or not sleep_idle:
if not self.period_limit:
return 0.
else:
wake_time = self.next_ts
if self._schedule_interval_items:
wake_time = min(wake_time,
self._schedule_interval_items[0].next_ts)
return max(wake_time - self.time(), 0.)
if self._schedule_interval_items:
return max(self._schedule_interval_items[0].next_ts - self.time(),
0)
return None
def set_fps_limit(self, fps_limit):
"""Set the framerate limit.
The framerate limit applies only when a function is scheduled
for every frame. That is, the framerate limit can be exceeded by
scheduling a function for a very small period of time.
:Parameters:
`fps_limit` : float
Maximum frames per second allowed, or None to disable
limiting.
:deprecated: Use `pyglet.app.run` and `schedule_interval` instead.
"""
if not fps_limit:
self.period_limit = None
else:
self.period_limit = 1. / fps_limit
self.window_size = fps_limit or 60
def get_fps_limit(self):
"""Get the framerate limit.
:rtype: float
:return: The framerate limit previously set in the constructor or
`set_fps_limit`, or None if no limit was set.
"""
if self.period_limit:
return 1. / self.period_limit
else:
return 0
def get_fps(self):
"""Get the average FPS of recent history.
The result is the average of a sliding window of the last "n" frames,
where "n" is some number designed to cover approximately 1 second.
:rtype: float
:return: The measured frames per second.
"""
if not self.cumulative_time:
return 0
return len(self.times) / self.cumulative_time
def _get_nearest_ts(self):
"""Get the nearest timestamp.
Schedule from now, unless now is sufficiently close to last_ts, in
which case use last_ts. This clusters together scheduled items that
probably want to be scheduled together. The old (pre 1.1.1)
behaviour was to always use self.last_ts, and not look at ts. The
new behaviour is needed because clock ticks can now be quite
irregular, and span several seconds.
"""
last_ts = self.last_ts or self.next_ts
ts = self.time()
if ts - last_ts > 0.2:
return ts
return last_ts
def _get_soft_next_ts(self, last_ts, interval):
def taken(ts, e):
"""Check if `ts` has already got an item scheduled nearby."""
# TODO this function is slow and called very often.
# Optimise it, maybe?
for item in self._schedule_interval_items:
if abs(item.next_ts - ts) <= e:
return True
elif item.next_ts > ts + e:
return False
return False
# sorted list is required required to produce expected results
# taken() will iterate through the heap, expecting it to be sorted
# and will not always catch smallest value, so sort here.
# do not remove the sort key...it is faster than relaying comparisons
# NOTE: do not rewrite as popping from heap, as that is super slow!
self._schedule_interval_items.sort(key=attrgetter('next_ts'))
# Binary division over interval:
#
# 0 interval
# |--------------------------|
# 5 3 6 2 7 4 8 1 Order of search
#
# i.e., first scheduled at interval,
# then at interval/2
# then at interval/4
# then at interval*3/4
# then at ...
#
# Schedule is hopefully then evenly distributed for any interval,
# and any number of scheduled functions.
next_ts = last_ts + interval
if not taken(next_ts, interval / 4):
return next_ts
dt = interval
divs = 1
while True:
next_ts = last_ts
for i in range(divs - 1):
next_ts += dt
if not taken(next_ts, dt / 4):
return next_ts
dt /= 2
divs *= 2
# Avoid infinite loop in pathological case
if divs > 16:
return next_ts
def schedule(self, func, *args, **kwargs):
"""Schedule a function to be called every frame.
The function should have a prototype that includes ``dt`` as the
first argument, which gives the elapsed time, in seconds, since the
last clock tick. Any additional arguments given to this function
are passed on to the callback::
def callback(dt, *args, **kwargs):
pass
:Parameters:
`func` : callable
The function to call each frame.
"""
item = _ScheduledItem(func, args, kwargs)
self._schedule_items.append(item)
def schedule_once(self, func, delay, *args, **kwargs):
"""Schedule a function to be called once after `delay` seconds.
The callback function prototype is the same as for `schedule`.
:Parameters:
`func` : callable
The function to call when the timer lapses.
`delay` : float
The number of seconds to wait before the timer lapses.
"""
last_ts = self._get_nearest_ts()
next_ts = last_ts + delay
item = _ScheduledIntervalItem(func, 0, last_ts, next_ts, args, kwargs)
heappush(self._schedule_interval_items, item)
def schedule_interval(self, func, interval, *args, **kwargs):
"""Schedule a function to be called every `interval` seconds.
Specifying an interval of 0 prevents the function from being
called again (see `schedule` to call a function as often as possible).
The callback function prototype is the same as for `schedule`.
:Parameters:
`func` : callable
The function to call when the timer lapses.
`interval` : float
The number of seconds to wait between each call.
"""
last_ts = self._get_nearest_ts()
next_ts = last_ts + interval
item = _ScheduledIntervalItem(func, interval, last_ts,
next_ts, args, kwargs)
heappush(self._schedule_interval_items, item)
def schedule_interval_soft(self, func, interval, *args, **kwargs):
"""Schedule a function to be called every ``interval`` seconds.
This method is similar to `schedule_interval`, except that the
clock will move the interval out of phase with other scheduled
functions so as to distribute CPU more load evenly over time.
This is useful for functions that need to be called regularly,
but not relative to the initial start time. :py:mod:`pyglet.media`
does this for scheduling audio buffer updates, which need to occur
regularly -- if all audio updates are scheduled at the same time
(for example, mixing several tracks of a music score, or playing
multiple videos back simultaneously), the resulting load on the
CPU is excessive for those intervals but idle outside. Using
the soft interval scheduling, the load is more evenly distributed.
Soft interval scheduling can also be used as an easy way to schedule
graphics animations out of phase; for example, multiple flags
waving in the wind.
.. versionadded:: 1.1
:Parameters:
`func` : callable
The function to call when the timer lapses.
`interval` : float
The number of seconds to wait between each call.
"""
next_ts = self._get_soft_next_ts(self._get_nearest_ts(), interval)
last_ts = next_ts - interval
item = _ScheduledIntervalItem(func, interval, last_ts,
next_ts, args, kwargs)
heappush(self._schedule_interval_items, item)
def unschedule(self, func):
"""Remove a function from the schedule.
If the function appears in the schedule more than once, all occurrences
are removed. If the function was not scheduled, no error is raised.
:Parameters:
`func` : callable
The function to remove from the schedule.
"""
# clever remove item without disturbing the heap:
# 1. set function to an empty lambda -- original function is not called
# 2. set interval to 0 -- item will be removed from heap
# eventually
valid_items = set(item
for item in self._schedule_interval_items
if item.func == func)
if self._current_interval_item:
if self._current_interval_item.func == func:
valid_items.add(self._current_interval_item)
for item in valid_items:
item.interval = 0
item.func = lambda x, *args, **kwargs: x
self._schedule_items = [i for i in self._schedule_items
if i.func != func]
# Default clock.
_default = Clock()
def set_default(default):
"""Set the default clock to use for all module-level functions.
By default an instance of :py:class:`~pyglet.clock.Clock` is used.
:Parameters:
`default` : `Clock`
The default clock to use.
"""
global _default
_default = default
def get_default():
"""Get the pyglet default Clock.
Return the :py:class:`~pyglet.clock.Clock` instance that is used by all
module-level clock functions.
:rtype: `Clock`
:return: The default clock.
"""
return _default
def tick(poll=False):
"""Signify that one frame has passed on the default clock.
This will call any scheduled functions that have elapsed.
:Parameters:
`poll` : bool
If True, the function will call any scheduled functions
but will not sleep or busy-wait for any reason. Recommended
for advanced applications managing their own sleep timers
only.
Since pyglet 1.1.
:rtype: float
:return: The number of seconds since the last "tick", or 0 if this was the
first frame.
"""
return _default.tick(poll)
def get_sleep_time(sleep_idle):
"""Get the time until the next item is scheduled on the default clock.
See `Clock.get_sleep_time` for details.
:Parameters:
`sleep_idle` : bool
If True, the application intends to sleep through its idle
time; otherwise it will continue ticking at the maximum
frame rate allowed.
:rtype: float
:return: Time until the next scheduled event in seconds, or ``None``
if there is no event scheduled.
.. versionadded:: 1.1
"""
return _default.get_sleep_time(sleep_idle)
def get_fps():
"""Return the current measured FPS of the default clock.
:rtype: float
"""
return _default.get_fps()
def set_fps_limit(fps_limit):
"""Set the framerate limit for the default clock.
:Parameters:
`fps_limit` : float
Maximum frames per second allowed, or None to disable
limiting.
:deprecated: Use `pyglet.app.run` and `schedule_interval` instead.
"""
_default.set_fps_limit(fps_limit)
def get_fps_limit():
"""Get the framerate limit for the default clock.
:return: The framerate limit previously set by `set_fps_limit`, or None if
no limit was set.
"""
return _default.get_fps_limit()
def schedule(func, *args, **kwargs):
"""Schedule 'func' to be called every frame on the default clock.
The arguments passed to func are ``dt``, followed by any ``*args`` and
``**kwargs`` given here.
:Parameters:
`func` : callable
The function to call each frame.
"""
_default.schedule(func, *args, **kwargs)
def schedule_interval(func, interval, *args, **kwargs):
"""Schedule ``func`` on the default clock every interval seconds.
The arguments passed to ``func`` are ``dt`` (time since last function
call), followed by any ``*args`` and ``**kwargs`` given here.
:Parameters:
`func` : callable
The function to call when the timer lapses.
`interval` : float
The number of seconds to wait between each call.
"""
_default.schedule_interval(func, interval, *args, **kwargs)
def schedule_interval_soft(func, interval, *args, **kwargs):
"""Schedule ``func`` on the default clock every interval seconds.
The clock will move the interval out of phase with other scheduled
functions so as to distribute CPU more load evenly over time.
The arguments passed to ``func`` are ``dt`` (time since last function
call), followed by any ``*args`` and ``**kwargs`` given here.
:see: `Clock.schedule_interval_soft`
.. versionadded:: 1.1
:Parameters:
`func` : callable
The function to call when the timer lapses.
`interval` : float
The number of seconds to wait between each call.
"""
_default.schedule_interval_soft(func, interval, *args, **kwargs)
def schedule_once(func, delay, *args, **kwargs):
"""Schedule ``func`` to be called once after ``delay`` seconds.
This function uses the fefault clock. ``delay`` can be a float. The
arguments passed to ``func`` are ``dt`` (time since last function call),
followed by any ``*args`` and ``**kwargs`` given here.
If no default clock is set, the func is queued and will be scheduled
on the default clock as soon as it is created.
:Parameters:
`func` : callable
The function to call when the timer lapses.
`delay` : float
The number of seconds to wait before the timer lapses.
"""
_default.schedule_once(func, delay, *args, **kwargs)
def unschedule(func):
"""Remove ``func`` from the default clock's schedule.
No error is raised if the ``func`` was never scheduled.
:Parameters:
`func` : callable
The function to remove from the schedule.
"""
_default.unschedule(func)
class ClockDisplay(object):
"""Display current clock values, such as FPS.
This is a convenience class for displaying diagnostics such as the
framerate. See the module documentation for example usage.
:Ivariables:
`label` : `pyglet.font.Text`
The label which is displayed.
:deprecated: This class presents values that are often misleading, as
they reflect the rate of clock ticks, not displayed framerate. Use
pyglet.window.FPSDisplay instead.
"""
def __init__(self,
font=None,
interval=0.25,
format='%(fps).2f',
color=(.5, .5, .5, .5),
clock=None):
"""Create a ClockDisplay.
All parameters are optional. By default, a large translucent
font will be used to display the FPS to two decimal places.
:Parameters:
`font` : `pyglet.font.Font`
The font to format text in.
`interval` : float
The number of seconds between updating the display.
`format` : str
A format string describing the format of the text. This
string is modulated with the dict ``{'fps' : fps}``.
`color` : 4-tuple of float
The color, including alpha, passed to ``glColor4f``.
`clock` : `Clock`
The clock which determines the time. If None, the default
clock is used.
"""
if clock is None:
clock = _default
self.clock = clock
self.clock.schedule_interval(self.update_text, interval)
if not font:
from pyglet.font import load as load_font
font = load_font('', 36, bold=True)
import pyglet.font
self.label = pyglet.font.Text(font, '', color=color, x=10, y=10)
self.format = format
def unschedule(self):
"""Remove the display from its clock's schedule.
:class:`~pyglet.clock.ClockDisplay` uses
:class:`~pyglet.clocl.Clock.schedule_interval` to periodically update
its display label. Even if the ClockDisplay is not being used any
more, its update method will still be scheduled, which can be a
resource drain. Call this method to unschedule the update method
and allow the ClockDisplay to be garbage collected.
.. versionadded:: 1.1
"""
self.clock.unschedule(self.update_text)
def update_text(self, dt=0):
"""Scheduled method to update the label text."""
fps = self.clock.get_fps()
self.label.text = self.format % {'fps': fps}
def draw(self):
"""Method called each frame to render the label."""
self.label.draw()
def test_clock():
"""Test clock implementation."""
import getopt
import sys
test_seconds = 1
test_fps = 60
show_fps = False
options, args = getopt.getopt(sys.argv[1:], 'vht:f:',
['time=', 'fps=', 'help'])
for key, value in options:
if key in ('-t', '--time'):
test_seconds = float(value)
elif key in ('-f', '--fps'):
test_fps = float(value)
elif key in ('-v', ):
show_fps = True
elif key in ('-h', '--help'):
print('Usage: clock.py <options>\n'
'\n'
'Options:\n'
' -t --time Number of seconds to run for.\n'
' -f --fps Target FPS.\n'
'\n'
'Tests the clock module by measuring how close we can\n'
'get to the desired FPS by sleeping and busy-waiting.')
sys.exit(0)
set_fps_limit(test_fps)
start = time.time()
# Add one because first frame has no update interval.
n_frames = int(test_seconds * test_fps + 1)
print('Testing %f FPS for %f seconds...' % (test_fps, test_seconds))
for i in range(n_frames):
tick()
if show_fps:
print(get_fps())
total_time = time.time() - start
total_error = total_time - test_seconds
print('Total clock error: %f secs' % total_error)
print('Total clock error / secs: %f secs/secs' %
(total_error / test_seconds))
# Not fair to add the extra frame in this calc, since no-one's interested
# in the startup situation.
print('Average FPS: %f' % ((n_frames - 1) / total_time))
if __name__ == '__main__':
test_clock()
| 35,638 | 33.367406 | 86 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/pyglet/resource.py
|
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
"""Load application resources from a known path.
Loading resources by specifying relative paths to filenames is often
problematic in Python, as the working directory is not necessarily the same
directory as the application's script files.
This module allows applications to specify a search path for resources.
Relative paths are taken to be relative to the application's ``__main__``
module. ZIP files can appear on the path; they will be searched inside. The
resource module also behaves as expected when applications are bundled using py2exe or py2app.
As well as providing file references (with the :py:func:`file` function), the
resource module also contains convenience functions for loading images,
textures, fonts, media and documents.
3rd party modules or packages not bound to a specific application should
construct their own :py:class:`Loader` instance and override the path to use the
resources in the module's directory.
Path format
^^^^^^^^^^^
The resource path :py:attr:`path` (see also :py:meth:`Loader.__init__` and
:py:meth:`Loader.path`)
is a list of locations to search for resources. Locations are searched in the
order given in the path. If a location is not valid (for example, if the
directory does not exist), it is skipped.
Locations in the path beginning with an ampersand (''@'' symbol) specify
Python packages. Other locations specify a ZIP archive or directory on the
filesystem. Locations that are not absolute are assumed to be relative to the
script home. Some examples::
# Search just the `res` directory, assumed to be located alongside the
# main script file.
path = ['res']
# Search the directory containing the module `levels.level1`, followed
# by the `res/images` directory.
path = ['@levels.level1', 'res/images']
Paths are always case-sensitive and forward slashes are always used as path
separators, even in cases when the filesystem or platform does not do this.
This avoids a common programmer error when porting applications between
platforms.
The default path is ``['.']``. If you modify the path, you must call
:py:func:`reindex`.
.. versionadded:: 1.1
"""
from future import standard_library
standard_library.install_aliases()
from builtins import object
from past.builtins import basestring
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import os
import weakref
import sys
import zipfile
import pyglet
from pyglet.compat import BytesIO
class ResourceNotFoundException(Exception):
"""The named resource was not found on the search path."""
def __init__(self, name):
message = ('Resource "%s" was not found on the path. '
'Ensure that the filename has the correct captialisation.') % name
Exception.__init__(self, message)
def get_script_home():
"""Get the directory containing the program entry module.
For ordinary Python scripts, this is the directory containing the
``__main__`` module. For executables created with py2exe the result is
the directory containing the running executable file. For OS X bundles
created using Py2App the result is the Resources directory within the
running bundle.
If none of the above cases apply and the file for ``__main__`` cannot
be determined the working directory is returned.
When the script is being run by a Python profiler, this function
may return the directory where the profiler is running instead of
the directory of the real script. To workaround this behaviour the
full path to the real script can be specified in :py:attr:`pyglet.resource.path`.
:rtype: str
"""
frozen = getattr(sys, 'frozen', None)
meipass = getattr(sys, '_MEIPASS', None)
if meipass:
# PyInstaller
return meipass
elif frozen in ('windows_exe', 'console_exe'):
return os.path.dirname(sys.executable)
elif frozen == 'macosx_app':
# py2app
return os.environ['RESOURCEPATH']
else:
main = sys.modules['__main__']
if hasattr(main, '__file__'):
return os.path.dirname(os.path.abspath(main.__file__))
else:
if 'python' in os.path.basename(sys.executable):
# interactive
return os.getcwd()
else:
# cx_Freeze
return os.path.dirname(sys.executable)
def get_settings_path(name):
"""Get a directory to save user preferences.
Different platforms have different conventions for where to save user
preferences, saved games, and settings. This function implements those
conventions. Note that the returned path may not exist: applications
should use ``os.makedirs`` to construct it if desired.
On Linux, a directory `name` in the user's configuration directory is
returned (usually under ``~/.config``).
On Windows (including under Cygwin) the `name` directory in the user's
``Application Settings`` directory is returned.
On Mac OS X the `name` directory under ``~/Library/Application Support``
is returned.
:Parameters:
`name` : str
The name of the application.
:rtype: str
"""
if pyglet.compat_platform in ('cygwin', 'win32'):
if 'APPDATA' in os.environ:
return os.path.join(os.environ['APPDATA'], name)
else:
return os.path.expanduser('~/%s' % name)
elif pyglet.compat_platform == 'darwin':
return os.path.expanduser('~/Library/Application Support/%s' % name)
elif pyglet.compat_platform.startswith('linux'):
if 'XDG_CONFIG_HOME' in os.environ:
return os.path.join(os.environ['XDG_CONFIG_HOME'], name)
else:
return os.path.expanduser('~/.config/%s' % name)
else:
return os.path.expanduser('~/.%s' % name)
class Location(object):
"""Abstract resource location.
Given a location, a file can be loaded from that location with the `open`
method. This provides a convenient way to specify a path to load files
from, and not necessarily have that path reside on the filesystem.
"""
def open(self, filename, mode='rb'):
"""Open a file at this location.
:Parameters:
`filename` : str
The filename to open. Absolute paths are not supported.
Relative paths are not supported by most locations (you
should specify only a filename with no path component).
`mode` : str
The file mode to open with. Only files opened on the
filesystem make use of this parameter; others ignore it.
:rtype: file object
"""
raise NotImplementedError('abstract')
class FileLocation(Location):
"""Location on the filesystem.
"""
def __init__(self, path):
"""Create a location given a relative or absolute path.
:Parameters:
`path` : str
Path on the filesystem.
"""
self.path = path
def open(self, filename, mode='rb'):
return open(os.path.join(self.path, filename), mode)
class ZIPLocation(Location):
"""Location within a ZIP file.
"""
def __init__(self, zip, dir):
"""Create a location given an open ZIP file and a path within that
file.
:Parameters:
`zip` : ``zipfile.ZipFile``
An open ZIP file from the ``zipfile`` module.
`dir` : str
A path within that ZIP file. Can be empty to specify files at
the top level of the ZIP file.
"""
self.zip = zip
self.dir = dir
def open(self, filename, mode='rb'):
if self.dir:
path = self.dir + '/' + filename
else:
path = filename
text = self.zip.read(path)
return BytesIO(text)
class URLLocation(Location):
"""Location on the network.
This class uses the ``urlparse`` and ``urllib2`` modules to open files on
the network given a URL.
"""
def __init__(self, base_url):
"""Create a location given a base URL.
:Parameters:
`base_url` : str
URL string to prepend to filenames.
"""
self.base = base_url
def open(self, filename, mode='rb'):
import urllib.request, urllib.error, urllib.parse
url = urllib.parse.urljoin(self.base, filename)
return urllib.request.urlopen(url)
class Loader(object):
"""Load program resource files from disk.
The loader contains a search path which can include filesystem
directories, ZIP archives and Python packages.
:Ivariables:
`path` : list of str
List of search locations. After modifying the path you must
call the `reindex` method.
`script_home` : str
Base resource location, defaulting to the location of the
application script.
"""
def __init__(self, path=None, script_home=None):
"""Create a loader for the given path.
If no path is specified it defaults to ``['.']``; that is, just the
program directory.
See the module documentation for details on the path format.
:Parameters:
`path` : list of str
List of locations to search for resources.
`script_home` : str
Base location of relative files. Defaults to the result of
`get_script_home`.
"""
if path is None:
path = ['.']
if isinstance(path, basestring):
path = [path]
self.path = list(path)
if script_home is None:
script_home = get_script_home()
self._script_home = script_home
self._index = None
# Map bin size to list of atlases
self._texture_atlas_bins = {}
def _require_index(self):
if self._index is None:
self.reindex()
def reindex(self):
"""Refresh the file index.
You must call this method if `path` is changed or the filesystem
layout changes.
"""
# map name to image etc.
self._cached_textures = weakref.WeakValueDictionary()
self._cached_images = weakref.WeakValueDictionary()
self._cached_animations = weakref.WeakValueDictionary()
self._index = {}
for path in self.path:
if path.startswith('@'):
# Module
name = path[1:]
try:
module = __import__(name)
except:
continue
for component in name.split('.')[1:]:
module = getattr(module, component)
if hasattr(module, '__file__'):
path = os.path.dirname(module.__file__)
else:
path = '' # interactive
elif not os.path.isabs(path):
# Add script base unless absolute
assert '\\' not in path, \
'Backslashes not permitted in relative path'
path = os.path.join(self._script_home, path)
if os.path.isdir(path):
# Filesystem directory
path = path.rstrip(os.path.sep)
location = FileLocation(path)
for dirpath, dirnames, filenames in os.walk(path):
dirpath = dirpath[len(path) + 1:]
# Force forward slashes for index
if dirpath:
parts = [part
for part
in dirpath.split(os.sep)
if part is not None]
dirpath = '/'.join(parts)
for filename in filenames:
if dirpath:
index_name = dirpath + '/' + filename
else:
index_name = filename
self._index_file(index_name, location)
else:
# Find path component that is the ZIP file.
dir = ''
old_path = None
while path and not os.path.isfile(path):
old_path = path
path, tail_dir = os.path.split(path)
if path == old_path:
break
dir = '/'.join((tail_dir, dir))
if path == old_path:
continue
dir = dir.rstrip('/')
# path is a ZIP file, dir resides within ZIP
if path and zipfile.is_zipfile(path):
zip = zipfile.ZipFile(path, 'r')
location = ZIPLocation(zip, dir)
for zip_name in zip.namelist():
# zip_name_dir, zip_name = os.path.split(zip_name)
# assert '\\' not in name_dir
# assert not name_dir.endswith('/')
if zip_name.startswith(dir):
if dir:
zip_name = zip_name[len(dir) + 1:]
self._index_file(zip_name, location)
def _index_file(self, name, location):
if name not in self._index:
self._index[name] = location
def file(self, name, mode='rb'):
"""Load a resource.
:Parameters:
`name` : str
Filename of the resource to load.
`mode` : str
Combination of ``r``, ``w``, ``a``, ``b`` and ``t`` characters
with the meaning as for the builtin ``open`` function.
:rtype: file object
"""
self._require_index()
try:
location = self._index[name]
return location.open(name, mode)
except KeyError:
raise ResourceNotFoundException(name)
def location(self, name):
"""Get the location of a resource.
This method is useful for opening files referenced from a resource.
For example, an HTML file loaded as a resource might reference some
images. These images should be located relative to the HTML file, not
looked up individually in the loader's path.
:Parameters:
`name` : str
Filename of the resource to locate.
:rtype: `Location`
"""
self._require_index()
try:
return self._index[name]
except KeyError:
raise ResourceNotFoundException(name)
def add_font(self, name):
"""Add a font resource to the application.
Fonts not installed on the system must be added to pyglet before they
can be used with `font.load`. Although the font is added with
its filename using this function, it is loaded by specifying its
family name. For example::
resource.add_font('action_man.ttf')
action_man = font.load('Action Man')
:Parameters:
`name` : str
Filename of the font resource to add.
"""
self._require_index()
from pyglet import font
file = self.file(name)
font.add_file(file)
def _alloc_image(self, name, atlas=True):
file = self.file(name)
try:
img = pyglet.image.load(name, file=file)
finally:
file.close()
if not atlas:
return img.get_texture(True)
# find an atlas suitable for the image
bin = self._get_texture_atlas_bin(img.width, img.height)
if bin is None:
return img.get_texture(True)
return bin.add(img)
def _get_texture_atlas_bin(self, width, height):
"""A heuristic for determining the atlas bin to use for a given image
size. Returns None if the image should not be placed in an atlas (too
big), otherwise the bin (a list of TextureAtlas).
"""
# Large images are not placed in an atlas
max_texture_size = pyglet.image.atlas.get_max_texture_size()
max_size = min(1024, max_texture_size / 2)
if width > max_size or height > max_size:
return None
# Group images with small height separately to larger height
# (as the allocator can't stack within a single row).
bin_size = 1
if height > max_size / 4:
bin_size = 2
try:
texture_bin = self._texture_atlas_bins[bin_size]
except KeyError:
texture_bin = self._texture_atlas_bins[bin_size] =\
pyglet.image.atlas.TextureBin()
return texture_bin
def image(self, name, flip_x=False, flip_y=False, rotate=0, atlas=True):
"""Load an image with optional transformation.
This is similar to `texture`, except the resulting image will be
packed into a :py:class:`~pyglet.image.atlas.TextureBin` if it is an appropriate size for packing.
This is more efficient than loading images into separate textures.
:Parameters:
`name` : str
Filename of the image source to load.
`flip_x` : bool
If True, the returned image will be flipped horizontally.
`flip_y` : bool
If True, the returned image will be flipped vertically.
`rotate` : int
The returned image will be rotated clockwise by the given
number of degrees (a multiple of 90).
`atlas` : bool
If True, the image will be loaded into an atlas managed by
pyglet. If atlas loading is not appropriate for specific
texturing reasons (e.g. border control is required) then set
this argument to False.
:rtype: `Texture`
:return: A complete texture if the image is large or not in an atlas,
otherwise a :py:class:`~pyglet.image.TextureRegion` of a texture atlas.
"""
self._require_index()
if name in self._cached_images:
identity = self._cached_images[name]
else:
identity = self._cached_images[name] = self._alloc_image(name,
atlas=atlas)
if not rotate and not flip_x and not flip_y:
return identity
return identity.get_transform(flip_x, flip_y, rotate)
def animation(self, name, flip_x=False, flip_y=False, rotate=0):
"""Load an animation with optional transformation.
Animations loaded from the same source but with different
transformations will use the same textures.
:Parameters:
`name` : str
Filename of the animation source to load.
`flip_x` : bool
If True, the returned image will be flipped horizontally.
`flip_y` : bool
If True, the returned image will be flipped vertically.
`rotate` : int
The returned image will be rotated clockwise by the given
number of degrees (a multiple of 90).
:rtype: :py:class:`~pyglet.image.Animation`
"""
self._require_index()
try:
identity = self._cached_animations[name]
except KeyError:
animation = pyglet.image.load_animation(name, self.file(name))
bin = self._get_texture_atlas_bin(animation.get_max_width(),
animation.get_max_height())
if bin:
animation.add_to_texture_bin(bin)
identity = self._cached_animations[name] = animation
if not rotate and not flip_x and not flip_y:
return identity
return identity.get_transform(flip_x, flip_y, rotate)
def get_cached_image_names(self):
"""Get a list of image filenames that have been cached.
This is useful for debugging and profiling only.
:rtype: list
:return: List of str
"""
self._require_index()
return list(self._cached_images.keys())
def get_cached_animation_names(self):
"""Get a list of animation filenames that have been cached.
This is useful for debugging and profiling only.
:rtype: list
:return: List of str
"""
self._require_index()
return list(self._cached_animations.keys())
def get_texture_bins(self):
"""Get a list of texture bins in use.
This is useful for debugging and profiling only.
:rtype: list
:return: List of :py:class:`~pyglet.image.atlas.TextureBin`
"""
self._require_index()
return list(self._texture_atlas_bins.values())
def media(self, name, streaming=True):
"""Load a sound or video resource.
The meaning of `streaming` is as for `media.load`. Compressed
sources cannot be streamed (that is, video and compressed audio
cannot be streamed from a ZIP archive).
:Parameters:
`name` : str
Filename of the media source to load.
`streaming` : bool
True if the source should be streamed from disk, False if
it should be entirely decoded into memory immediately.
:rtype: `media.Source`
"""
self._require_index()
from pyglet import media
try:
location = self._index[name]
if isinstance(location, FileLocation):
# Don't open the file if it's streamed from disk -- AVbin
# needs to do it.
path = os.path.join(location.path, name)
return media.load(path, streaming=streaming)
else:
file = location.open(name)
return media.load(name, file=file, streaming=streaming)
except KeyError:
raise ResourceNotFoundException(name)
def texture(self, name):
"""Load a texture.
The named image will be loaded as a single OpenGL texture. If the
dimensions of the image are not powers of 2 a :py:class:`~pyglet.image.TextureRegion` will
be returned.
:Parameters:
`name` : str
Filename of the image resource to load.
:rtype: `Texture`
"""
self._require_index()
if name in self._cached_textures:
return self._cached_textures[name]
file = self.file(name)
texture = pyglet.image.load(name, file=file).get_texture()
self._cached_textures[name] = texture
return texture
def html(self, name):
"""Load an HTML document.
:Parameters:
`name` : str
Filename of the HTML resource to load.
:rtype: `FormattedDocument`
"""
self._require_index()
file = self.file(name)
return pyglet.text.load(name, file, 'text/html')
def attributed(self, name):
"""Load an attributed text document.
See `pyglet.text.formats.attributed` for details on this format.
:Parameters:
`name` : str
Filename of the attribute text resource to load.
:rtype: `FormattedDocument`
"""
self._require_index()
file = self.file(name)
return pyglet.text.load(name, file, 'text/vnd.pyglet-attributed')
def text(self, name):
"""Load a plain text document.
:Parameters:
`name` : str
Filename of the plain text resource to load.
:rtype: `UnformattedDocument`
"""
self._require_index()
file = self.file(name)
return pyglet.text.load(name, file, 'text/plain')
def get_cached_texture_names(self):
"""Get the names of textures currently cached.
:rtype: list of str
"""
self._require_index()
return list(self._cached_textures.keys())
#: Default resource search path.
#:
#: Locations in the search path are searched in order and are always
#: case-sensitive. After changing the path you must call `reindex`.
#:
#: See the module documentation for details on the path format.
#:
#: :type: list of str
path = []
class _DefaultLoader(Loader):
@property
def path(self):
return path
@path.setter
def path(self, value):
global path
path = value
_default_loader = _DefaultLoader()
reindex = _default_loader.reindex
file = _default_loader.file
location = _default_loader.location
add_font = _default_loader.add_font
image = _default_loader.image
animation = _default_loader.animation
get_cached_image_names = _default_loader.get_cached_image_names
get_cached_animation_names = _default_loader.get_cached_animation_names
get_texture_bins = _default_loader.get_texture_bins
media = _default_loader.media
texture = _default_loader.texture
html = _default_loader.html
attributed = _default_loader.attributed
text = _default_loader.text
get_cached_texture_names = _default_loader.get_cached_texture_names
| 26,898 | 33.798189 | 106 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/pyglet/com.py
|
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
'''Minimal Windows COM interface.
Allows pyglet to use COM interfaces on Windows without comtypes. Unlike
comtypes, this module does not provide property interfaces, read typelibs,
nice-ify return values or permit Python implementations of COM interfaces. We
don't need anything that sophisticated to work with DirectX.
All interfaces should derive from IUnknown (defined in this module). The
Python COM interfaces are actually pointers to the implementation (take note
when translating methods that take an interface as argument).
Interfaces can define methods::
class IDirectSound8(com.IUnknown):
_methods_ = [
('CreateSoundBuffer', com.STDMETHOD()),
('GetCaps', com.STDMETHOD(LPDSCAPS)),
...
]
Only use STDMETHOD or METHOD for the method types (not ordinary ctypes
function types). The 'this' pointer is bound automatically... e.g., call::
device = IDirectSound8()
DirectSoundCreate8(None, ctypes.byref(device), None)
caps = DSCAPS()
device.GetCaps(caps)
Because STDMETHODs use HRESULT as the return type, there is no need to check
the return value.
Don't forget to manually manage memory... call Release() when you're done with
an interface.
'''
from builtins import object
import ctypes
import sys
from pyglet.debug import debug_print
_debug_com = debug_print('debug_com')
if sys.platform != 'win32':
raise ImportError('pyglet.com requires a Windows build of Python')
class GUID(ctypes.Structure):
_fields_ = [
('Data1', ctypes.c_ulong),
('Data2', ctypes.c_ushort),
('Data3', ctypes.c_ushort),
('Data4', ctypes.c_ubyte * 8)
]
def __init__(self, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8):
self.Data1 = l
self.Data2 = w1
self.Data3 = w2
self.Data4[:] = (b1, b2, b3, b4, b5, b6, b7, b8)
def __repr__(self):
b1, b2, b3, b4, b5, b6, b7, b8 = self.Data4
return 'GUID(%x, %x, %x, %x, %x, %x, %x, %x, %x, %x, %x)' % (
self.Data1, self.Data2, self.Data3, b1, b2, b3, b4, b5, b6, b7, b8)
LPGUID = ctypes.POINTER(GUID)
IID = GUID
REFIID = ctypes.POINTER(IID)
class METHOD(object):
'''COM method.'''
def __init__(self, restype, *args):
self.restype = restype
self.argtypes = args
def get_field(self):
return ctypes.WINFUNCTYPE(self.restype, *self.argtypes)
class STDMETHOD(METHOD):
'''COM method with HRESULT return value.'''
def __init__(self, *args):
super(STDMETHOD, self).__init__(ctypes.HRESULT, *args)
class COMMethodInstance(object):
'''Binds a COM interface method.'''
def __init__(self, name, i, method):
self.name = name
self.i = i
self.method = method
def __get__(self, obj, tp):
if obj is not None:
def _call(*args):
assert _debug_com('COM: IN {}({}, {})'.format(self.name, obj.__class__.__name__, args))
ret = self.method.get_field()(self.i, self.name)(obj, *args)
assert _debug_com('COM: OUT {}({}, {})'.format(self.name, obj.__class__.__name__, args))
assert _debug_com('COM: RETURN {}'.format(ret))
return ret
return _call
raise AttributeError()
class COMInterface(ctypes.Structure):
'''Dummy struct to serve as the type of all COM pointers.'''
_fields_ = [
('lpVtbl', ctypes.c_void_p),
]
class InterfaceMetaclass(type(ctypes.POINTER(COMInterface))):
'''Creates COM interface pointers.'''
def __new__(cls, name, bases, dct):
methods = []
for base in bases[::-1]:
methods.extend(base.__dict__.get('_methods_', ()))
methods.extend(dct.get('_methods_', ()))
for i, (n, method) in enumerate(methods):
dct[n] = COMMethodInstance(n, i, method)
dct['_type_'] = COMInterface
return super(InterfaceMetaclass, cls).__new__(cls, name, bases, dct)
# future.utils.with_metaclass does not work here, as the base class is from _ctypes.lib
# See https://wiki.python.org/moin/PortingToPy3k/BilingualQuickRef
Interface = InterfaceMetaclass(str('Interface'), (ctypes.POINTER(COMInterface),), {
'__doc__': 'Base COM interface pointer.',
})
class IUnknown(Interface):
_methods_ = [
('QueryInterface', STDMETHOD(REFIID, ctypes.c_void_p)),
('AddRef', METHOD(ctypes.c_int)),
('Release', METHOD(ctypes.c_int))
]
| 6,183 | 34.953488 | 104 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/pyglet/event.py
|
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
'''Event dispatch framework.
All objects that produce events in pyglet implement :py:class:`~pyglet.event.EventDispatcher`,
providing a consistent interface for registering and manipulating event
handlers. A commonly used event dispatcher is `pyglet.window.Window`.
Event types
===========
For each event dispatcher there is a set of events that it dispatches; these
correspond with the type of event handlers you can attach. Event types are
identified by their name, for example, ''on_resize''. If you are creating a
new class which implements :py:class:`~pyglet.event.EventDispatcher`, you must call
`EventDispatcher.register_event_type` for each event type.
Attaching event handlers
========================
An event handler is simply a function or method. You can attach an event
handler by setting the appropriate function on the instance::
def on_resize(width, height):
# ...
dispatcher.on_resize = on_resize
There is also a convenience decorator that reduces typing::
@dispatcher.event
def on_resize(width, height):
# ...
You may prefer to subclass and override the event handlers instead::
class MyDispatcher(DispatcherClass):
def on_resize(self, width, height):
# ...
Event handler stack
===================
When attaching an event handler to a dispatcher using the above methods, it
replaces any existing handler (causing the original handler to no longer be
called). Each dispatcher maintains a stack of event handlers, allowing you to
insert an event handler "above" the existing one rather than replacing it.
There are two main use cases for "pushing" event handlers:
* Temporarily intercepting the events coming from the dispatcher by pushing a
custom set of handlers onto the dispatcher, then later "popping" them all
off at once.
* Creating "chains" of event handlers, where the event propagates from the
top-most (most recently added) handler to the bottom, until a handler
takes care of it.
Use `EventDispatcher.push_handlers` to create a new level in the stack and
attach handlers to it. You can push several handlers at once::
dispatcher.push_handlers(on_resize, on_key_press)
If your function handlers have different names to the events they handle, use
keyword arguments::
dispatcher.push_handlers(on_resize=my_resize,
on_key_press=my_key_press)
After an event handler has processed an event, it is passed on to the
next-lowest event handler, unless the handler returns `EVENT_HANDLED`, which
prevents further propagation.
To remove all handlers on the top stack level, use
`EventDispatcher.pop_handlers`.
Note that any handlers pushed onto the stack have precedence over the
handlers set directly on the instance (for example, using the methods
described in the previous section), regardless of when they were set.
For example, handler ``foo`` is called before handler ``bar`` in the following
example::
dispatcher.push_handlers(on_resize=foo)
dispatcher.on_resize = bar
Dispatching events
==================
pyglet uses a single-threaded model for all application code. Event
handlers are only ever invoked as a result of calling
EventDispatcher.dispatch_events`.
It is up to the specific event dispatcher to queue relevant events until they
can be dispatched, at which point the handlers are called in the order the
events were originally generated.
This implies that your application runs with a main loop that continuously
updates the application state and checks for new events::
while True:
dispatcher.dispatch_events()
# ... additional per-frame processing
Not all event dispatchers require the call to ``dispatch_events``; check with
the particular class documentation.
'''
from builtins import object
from past.builtins import basestring
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import inspect
EVENT_HANDLED = True
EVENT_UNHANDLED = None
class EventException(Exception):
'''An exception raised when an event handler could not be attached.
'''
pass
class EventDispatcher(object):
'''Generic event dispatcher interface.
See the module docstring for usage.
'''
# Placeholder empty stack; real stack is created only if needed
_event_stack = ()
@classmethod
def register_event_type(cls, name):
'''Register an event type with the dispatcher.
Registering event types allows the dispatcher to validate event
handler names as they are attached, and to search attached objects for
suitable handlers.
:Parameters:
`name` : str
Name of the event to register.
'''
if not hasattr(cls, 'event_types'):
cls.event_types = []
cls.event_types.append(name)
return name
def push_handlers(self, *args, **kwargs):
'''Push a level onto the top of the handler stack, then attach zero or
more event handlers.
If keyword arguments are given, they name the event type to attach.
Otherwise, a callable's `__name__` attribute will be used. Any other
object may also be specified, in which case it will be searched for
callables with event names.
'''
# Create event stack if necessary
if type(self._event_stack) is tuple:
self._event_stack = []
# Place dict full of new handlers at beginning of stack
self._event_stack.insert(0, {})
self.set_handlers(*args, **kwargs)
def _get_handlers(self, args, kwargs):
'''Implement handler matching on arguments for set_handlers and
remove_handlers.
'''
for object in args:
if inspect.isroutine(object):
# Single magically named function
name = object.__name__
if name not in self.event_types:
raise EventException('Unknown event "%s"' % name)
yield name, object
else:
# Single instance with magically named methods
for name in dir(object):
if name in self.event_types:
yield name, getattr(object, name)
for name, handler in kwargs.items():
# Function for handling given event (no magic)
if name not in self.event_types:
raise EventException('Unknown event "%s"' % name)
yield name, handler
def set_handlers(self, *args, **kwargs):
'''Attach one or more event handlers to the top level of the handler
stack.
See :py:meth:`~pyglet.event.EventDispatcher.push_handlers` for the accepted argument types.
'''
# Create event stack if necessary
if type(self._event_stack) is tuple:
self._event_stack = [{}]
for name, handler in self._get_handlers(args, kwargs):
self.set_handler(name, handler)
def set_handler(self, name, handler):
'''Attach a single event handler.
:Parameters:
`name` : str
Name of the event type to attach to.
`handler` : callable
Event handler to attach.
'''
# Create event stack if necessary
if type(self._event_stack) is tuple:
self._event_stack = [{}]
self._event_stack[0][name] = handler
def pop_handlers(self):
'''Pop the top level of event handlers off the stack.
'''
assert self._event_stack and 'No handlers pushed'
del self._event_stack[0]
def remove_handlers(self, *args, **kwargs):
'''Remove event handlers from the event stack.
See :py:meth:`~pyglet.event.EventDispatcher.push_handlers` for the accepted argument types. All handlers
are removed from the first stack frame that contains any of the given
handlers. No error is raised if any handler does not appear in that
frame, or if no stack frame contains any of the given handlers.
If the stack frame is empty after removing the handlers, it is
removed from the stack. Note that this interferes with the expected
symmetry of :py:meth:`~pyglet.event.EventDispatcher.push_handlers` and :py:meth:`~pyglet.event.EventDispatcher.pop_handlers`.
'''
handlers = list(self._get_handlers(args, kwargs))
# Find the first stack frame containing any of the handlers
def find_frame():
for frame in self._event_stack:
for name, handler in handlers:
try:
if frame[name] == handler:
return frame
except KeyError:
pass
frame = find_frame()
# No frame matched; no error.
if not frame:
return
# Remove each handler from the frame.
for name, handler in handlers:
try:
if frame[name] == handler:
del frame[name]
except KeyError:
pass
# Remove the frame if it's empty.
if not frame:
self._event_stack.remove(frame)
def remove_handler(self, name, handler):
'''Remove a single event handler.
The given event handler is removed from the first handler stack frame
it appears in. The handler must be the exact same callable as passed
to `set_handler`, `set_handlers` or :py:meth:`~pyglet.event.EventDispatcher.push_handlers`; and the name
must match the event type it is bound to.
No error is raised if the event handler is not set.
:Parameters:
`name` : str
Name of the event type to remove.
`handler` : callable
Event handler to remove.
'''
for frame in self._event_stack:
try:
if frame[name] == handler:
del frame[name]
break
except KeyError:
pass
def dispatch_event(self, event_type, *args):
'''Dispatch a single event to the attached handlers.
The event is propagated to all handlers from from the top of the stack
until one returns `EVENT_HANDLED`. This method should be used only by
:py:class:`~pyglet.event.EventDispatcher` implementors; applications should call
the ``dispatch_events`` method.
Since pyglet 1.2, the method returns `EVENT_HANDLED` if an event
handler returned `EVENT_HANDLED` or `EVENT_UNHANDLED` if all events
returned `EVENT_UNHANDLED`. If no matching event handlers are in the
stack, ``False`` is returned.
:Parameters:
`event_type` : str
Name of the event.
`args` : sequence
Arguments to pass to the event handler.
:rtype: bool or None
:return: (Since pyglet 1.2) `EVENT_HANDLED` if an event handler
returned `EVENT_HANDLED`; `EVENT_UNHANDLED` if one or more event
handlers were invoked but returned only `EVENT_UNHANDLED`;
otherwise ``False``. In pyglet 1.1 and earler, the return value
is always ``None``.
'''
assert event_type in self.event_types, "%r not found in %r.event_types == %r" % (event_type, self, self.event_types)
invoked = False
# Search handler stack for matching event handlers
for frame in list(self._event_stack):
handler = frame.get(event_type, None)
if handler:
try:
invoked = True
if handler(*args):
return EVENT_HANDLED
except TypeError:
self._raise_dispatch_exception(event_type, args, handler)
# Check instance for an event handler
if hasattr(self, event_type):
try:
invoked = True
if getattr(self, event_type)(*args):
return EVENT_HANDLED
except TypeError:
self._raise_dispatch_exception(
event_type, args, getattr(self, event_type))
if invoked:
return EVENT_UNHANDLED
return False
def _raise_dispatch_exception(self, event_type, args, handler):
# A common problem in applications is having the wrong number of
# arguments in an event handler. This is caught as a TypeError in
# dispatch_event but the error message is obfuscated.
#
# Here we check if there is indeed a mismatch in argument count,
# and construct a more useful exception message if so. If this method
# doesn't find a problem with the number of arguments, the error
# is re-raised as if we weren't here.
n_args = len(args)
# Inspect the handler
handler_args, handler_varargs, _, handler_defaults = \
inspect.getargspec(handler)
n_handler_args = len(handler_args)
# Remove "self" arg from handler if it's a bound method
if inspect.ismethod(handler) and handler.__self__:
n_handler_args -= 1
# Allow *args varargs to overspecify arguments
if handler_varargs:
n_handler_args = max(n_handler_args, n_args)
# Allow default values to overspecify arguments
if (n_handler_args > n_args and
handler_defaults and
n_handler_args - len(handler_defaults) <= n_args):
n_handler_args = n_args
if n_handler_args != n_args:
if inspect.isfunction(handler) or inspect.ismethod(handler):
descr = '%s at %s:%d' % (
handler.__name__,
handler.__code__.co_filename,
handler.__code__.co_firstlineno)
else:
descr = repr(handler)
raise TypeError(
'%s event was dispatched with %d arguments, but '
'handler %s has an incompatible function signature' %
(event_type, len(args), descr))
else:
raise
def event(self, *args):
'''Function decorator for an event handler.
Usage::
win = window.Window()
@win.event
def on_resize(self, width, height):
# ...
or::
@win.event('on_resize')
def foo(self, width, height):
# ...
'''
if len(args) == 0: # @window.event()
def decorator(func):
name = func.__name__
self.set_handler(name, func)
return func
return decorator
elif inspect.isroutine(args[0]): # @window.event
func = args[0]
name = func.__name__
self.set_handler(name, func)
return args[0]
elif isinstance(args[0], basestring): # @window.event('on_resize')
name = args[0]
def decorator(func):
self.set_handler(name, func)
return func
return decorator
| 16,987 | 35.930435 | 133 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/pyglet/lib.py
|
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
'''Functions for loading dynamic libraries.
These extend and correct ctypes functions.
'''
from __future__ import print_function
from builtins import str
from builtins import object
from past.builtins import basestring
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import os
import re
import sys
import ctypes
import ctypes.util
import pyglet
_debug_lib = pyglet.options['debug_lib']
_debug_trace = pyglet.options['debug_trace']
_is_pyglet_docgen = hasattr(sys, 'is_pyglet_docgen') and sys.is_pyglet_docgen
if pyglet.options['search_local_libs']:
script_path = pyglet.resource.get_script_home()
_local_lib_paths = [script_path, os.path.join(script_path, 'lib'),]
else:
_local_lib_paths = None
class _TraceFunction(object):
def __init__(self, func):
self.__dict__['_func'] = func
def __str__(self):
return self._func.__name__
def __call__(self, *args, **kwargs):
return self._func(*args, **kwargs)
def __getattr__(self, name):
return getattr(self._func, name)
def __setattr__(self, name, value):
setattr(self._func, name, value)
class _TraceLibrary(object):
def __init__(self, library):
self._library = library
print(library)
def __getattr__(self, name):
func = getattr(self._library, name)
f = _TraceFunction(func)
return f
if _is_pyglet_docgen:
class LibraryMock(object):
"""Mock library used when generating documentation."""
def __getattr__(self, name):
return LibraryMock()
def __setattr__(self, name, value):
pass
def __call__(self, *args, **kwargs):
return LibraryMock()
class LibraryLoader(object):
def load_library(self, *names, **kwargs):
'''Find and load a library.
More than one name can be specified, they will be tried in order.
Platform-specific library names (given as kwargs) are tried first.
Raises ImportError if library is not found.
'''
if _is_pyglet_docgen:
return LibraryMock()
if 'framework' in kwargs and self.platform == 'darwin':
return self.load_framework(kwargs['framework'])
if not names:
raise ImportError("No library name specified")
platform_names = kwargs.get(self.platform, [])
if isinstance(platform_names, basestring):
platform_names = [platform_names]
elif type(platform_names) is tuple:
platform_names = list(platform_names)
if self.platform.startswith('linux'):
for name in names:
libname = self.find_library(name)
platform_names.append(libname or 'lib%s.so' % name)
platform_names.extend(names)
for name in platform_names:
try:
lib = ctypes.cdll.LoadLibrary(name)
if _debug_lib:
print(name)
if _debug_trace:
lib = _TraceLibrary(lib)
return lib
except OSError as o:
if self.platform == "win32" and o.winerror != 126:
print("Unexpected error loading library %s: %s" % (name, str(o)))
raise
path = self.find_library(name)
if path:
try:
lib = ctypes.cdll.LoadLibrary(path)
if _debug_lib:
print(path)
if _debug_trace:
lib = _TraceLibrary(lib)
return lib
except OSError:
pass
raise ImportError('Library "%s" not found.' % names[0])
find_library = lambda self, name: ctypes.util.find_library(name)
platform = pyglet.compat_platform
# this is only for library loading, don't include it in pyglet.platform
if platform == 'cygwin':
platform = 'win32'
def load_framework(self, path):
raise RuntimeError("Can't load framework on this platform.")
class MachOLibraryLoader(LibraryLoader):
def __init__(self):
if 'LD_LIBRARY_PATH' in os.environ:
self.ld_library_path = os.environ['LD_LIBRARY_PATH'].split(':')
else:
self.ld_library_path = []
if _local_lib_paths:
# search first for local libs
self.ld_library_path = _local_lib_paths + self.ld_library_path
os.environ['LD_LIBRARY_PATH'] = ':'.join(self.ld_library_path)
if 'DYLD_LIBRARY_PATH' in os.environ:
self.dyld_library_path = os.environ['DYLD_LIBRARY_PATH'].split(':')
else:
self.dyld_library_path = []
if 'DYLD_FALLBACK_LIBRARY_PATH' in os.environ:
self.dyld_fallback_library_path = \
os.environ['DYLD_FALLBACK_LIBRARY_PATH'].split(':')
else:
self.dyld_fallback_library_path = [
os.path.expanduser('~/lib'),
'/usr/local/lib',
'/usr/lib']
def find_library(self, path):
'''Implements the dylib search as specified in Apple documentation:
http://developer.apple.com/documentation/DeveloperTools/Conceptual/DynamicLibraries/100-Articles/DynamicLibraryUsageGuidelines.html
Before commencing the standard search, the method first checks
the bundle's ``Frameworks`` directory if the application is running
within a bundle (OS X .app).
'''
libname = os.path.basename(path)
search_path = []
if '.' not in libname:
libname = 'lib' + libname + '.dylib'
# py2app support
if (hasattr(sys, 'frozen') and sys.frozen == 'macosx_app' and
'RESOURCEPATH' in os.environ):
search_path.append(os.path.join(
os.environ['RESOURCEPATH'],
'..',
'Frameworks',
libname))
# pyinstaller.py sets sys.frozen to True, and puts dylibs in
# Contents/MacOS, which path pyinstaller puts in sys._MEIPASS
if (hasattr(sys, 'frozen') and hasattr(sys, '_MEIPASS') and
sys.frozen == True and pyglet.compat_platform == 'darwin'):
search_path.append(os.path.join(sys._MEIPASS, libname))
if '/' in path:
search_path.extend(
[os.path.join(p, libname) \
for p in self.dyld_library_path])
search_path.append(path)
search_path.extend(
[os.path.join(p, libname) \
for p in self.dyld_fallback_library_path])
else:
search_path.extend(
[os.path.join(p, libname) \
for p in self.ld_library_path])
search_path.extend(
[os.path.join(p, libname) \
for p in self.dyld_library_path])
search_path.append(path)
search_path.extend(
[os.path.join(p, libname) \
for p in self.dyld_fallback_library_path])
for path in search_path:
if os.path.exists(path):
return path
return None
def find_framework(self, path):
'''Implement runtime framework search as described by:
http://developer.apple.com/documentation/MacOSX/Conceptual/BPFrameworks/Concepts/FrameworkBinding.html
'''
# e.g. path == '/System/Library/Frameworks/OpenGL.framework'
# name == 'OpenGL'
# return '/System/Library/Frameworks/OpenGL.framework/OpenGL'
name = os.path.splitext(os.path.split(path)[1])[0]
realpath = os.path.join(path, name)
if os.path.exists(realpath):
return realpath
for dir in ('/Library/Frameworks',
'/System/Library/Frameworks'):
realpath = os.path.join(dir, '%s.framework' % name, name)
if os.path.exists(realpath):
return realpath
return None
def load_framework(self, path):
realpath = self.find_framework(path)
if realpath:
lib = ctypes.cdll.LoadLibrary(realpath)
if _debug_lib:
print(realpath)
if _debug_trace:
lib = _TraceLibrary(lib)
return lib
raise ImportError("Can't find framework %s." % path)
class LinuxLibraryLoader(LibraryLoader):
_ld_so_cache = None
_local_libs_cache = None
def _find_libs(self, directories):
cache = {}
lib_re = re.compile('lib(.*)\.so(?:$|\.)')
for dir in directories:
try:
for file in os.listdir(dir):
match = lib_re.match(file)
if match:
# Index by filename
path = os.path.join(dir, file)
if file not in cache:
cache[file] = path
# Index by library name
library = match.group(1)
if library not in cache:
cache[library] = path
except OSError:
pass
return cache
def _create_ld_so_cache(self):
# Recreate search path followed by ld.so. This is going to be
# slow to build, and incorrect (ld.so uses ld.so.cache, which may
# not be up-to-date). Used only as fallback for distros without
# /sbin/ldconfig.
#
# We assume the DT_RPATH and DT_RUNPATH binary sections are omitted.
directories = []
try:
directories.extend(os.environ['LD_LIBRARY_PATH'].split(':'))
except KeyError:
pass
try:
with open('/etc/ld.so.conf') as fid:
directories.extend([dir.strip() for dir in fid])
except IOError:
pass
directories.extend(['/lib', '/usr/lib'])
self._ld_so_cache = self._find_libs(directories)
def find_library(self, path):
# search first for local libs
if _local_lib_paths:
if not self._local_libs_cache:
self._local_libs_cache = self._find_libs(_local_lib_paths)
if path in self._local_libs_cache:
return self._local_libs_cache[path]
# ctypes tries ldconfig, gcc and objdump. If none of these are
# present, we implement the ld-linux.so search path as described in
# the man page.
result = ctypes.util.find_library(path)
if result:
return result
if self._ld_so_cache is None:
self._create_ld_so_cache()
return self._ld_so_cache.get(path)
if pyglet.compat_platform == 'darwin':
loader = MachOLibraryLoader()
elif pyglet.compat_platform.startswith('linux'):
loader = LinuxLibraryLoader()
else:
loader = LibraryLoader()
load_library = loader.load_library
| 12,743 | 33.915068 | 139 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/pyglet/info.py
|
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
'''Get environment information useful for debugging.
Intended usage is to create a file for bug reports, e.g.::
python -m pyglet.info > info.txt
'''
from __future__ import print_function
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
_first_heading = True
def _heading(heading):
global _first_heading
if not _first_heading:
print()
else:
_first_heading = False
print(heading)
print('-' * 78)
def dump_python():
'''Dump Python version and environment to stdout.'''
import os
import sys
print('sys.version:', sys.version)
print('sys.platform:', sys.platform)
print('sys.maxint:', sys.maxsize)
if sys.platform == 'darwin':
try:
from objc import __version__ as pyobjc_version
print('objc.__version__:', pyobjc_version)
except:
print('PyObjC not available')
print('os.getcwd():', os.getcwd())
for key, value in os.environ.items():
if key.startswith('PYGLET_'):
print("os.environ['%s']: %s" % (key, value))
def dump_pyglet():
'''Dump pyglet version and options.'''
import pyglet
print('pyglet.version:', pyglet.version)
print('pyglet.compat_platform:', pyglet.compat_platform)
print('pyglet.__file__:', pyglet.__file__)
for key, value in pyglet.options.items():
print("pyglet.options['%s'] = %r" % (key, value))
def dump_window():
'''Dump display, window, screen and default config info.'''
import pyglet.window
platform = pyglet.window.get_platform()
print('platform:', repr(platform))
display = platform.get_default_display()
print('display:', repr(display))
screens = display.get_screens()
for i, screen in enumerate(screens):
print('screens[%d]: %r' % (i, screen))
window = pyglet.window.Window(visible=False)
for key, value in window.config.get_gl_attributes():
print("config['%s'] = %r" % (key, value))
print('context:', repr(window.context))
_heading('window.context._info')
dump_gl(window.context)
window.close()
def dump_gl(context=None):
'''Dump GL info.'''
if context is not None:
info = context.get_info()
else:
from pyglet.gl import gl_info as info
print('gl_info.get_version():', info.get_version())
print('gl_info.get_vendor():', info.get_vendor())
print('gl_info.get_renderer():', info.get_renderer())
print('gl_info.get_extensions():')
extensions = list(info.get_extensions())
extensions.sort()
for name in extensions:
print(' ', name)
def dump_glu():
'''Dump GLU info.'''
from pyglet.gl import glu_info
print('glu_info.get_version():', glu_info.get_version())
print('glu_info.get_extensions():')
extensions = list(glu_info.get_extensions())
extensions.sort()
for name in extensions:
print(' ', name)
def dump_glx():
'''Dump GLX info.'''
try:
from pyglet.gl import glx_info
except:
print('GLX not available.')
return
import pyglet
window = pyglet.window.Window(visible=False)
print('context.is_direct():', window.context.is_direct())
window.close()
if not glx_info.have_version(1, 1):
print('Version: < 1.1')
else:
print('glx_info.get_server_vendor():', glx_info.get_server_vendor())
print('glx_info.get_server_version():', glx_info.get_server_version())
print('glx_info.get_server_extensions():')
for name in glx_info.get_server_extensions():
print(' ', name)
print('glx_info.get_client_vendor():', glx_info.get_client_vendor())
print('glx_info.get_client_version():', glx_info.get_client_version())
print('glx_info.get_client_extensions():')
for name in glx_info.get_client_extensions():
print(' ', name)
print('glx_info.get_extensions():')
for name in glx_info.get_extensions():
print(' ', name)
def dump_media():
'''Dump pyglet.media info.'''
import pyglet.media
print('audio driver:', pyglet.media.get_audio_driver())
def dump_avbin():
'''Dump AVbin info.'''
try:
import pyglet.media.avbin
print('Library:', pyglet.media.avbin.av)
print('AVbin version:', pyglet.media.avbin.av.avbin_get_version())
print('FFmpeg revision:', \
pyglet.media.avbin.av.avbin_get_ffmpeg_revision())
except:
print('AVbin not available.')
def dump_al():
'''Dump OpenAL info.'''
try:
from pyglet.media.drivers import openal
except:
print('OpenAL not available.')
return
print('Library:', openal.lib_openal._lib)
driver = openal.create_audio_driver()
print('Version: {}.{}'.format(*driver.get_version()))
print('Extensions:')
for extension in driver.get_extensions():
print(' ', extension)
def dump_wintab():
'''Dump WinTab info.'''
try:
from pyglet.input import wintab
except:
print('WinTab not available.')
return
interface_name = wintab.get_interface_name()
impl_version = wintab.get_implementation_version()
spec_version = wintab.get_spec_version()
print('WinTab: %s %d.%d (Spec %d.%d)' % (interface_name,
impl_version >> 8, impl_version & 0xff,
spec_version >> 8, spec_version & 0xff))
def _try_dump(heading, func):
_heading(heading)
try:
func()
except:
import traceback
traceback.print_exc()
def dump():
'''Dump all information to stdout.'''
_try_dump('Python', dump_python)
_try_dump('pyglet', dump_pyglet)
_try_dump('pyglet.window', dump_window)
_try_dump('pyglet.gl.glu_info', dump_glu)
_try_dump('pyglet.gl.glx_info', dump_glx)
_try_dump('pyglet.media', dump_media)
_try_dump('pyglet.media.avbin', dump_avbin)
_try_dump('pyglet.media.drivers.openal', dump_al)
_try_dump('pyglet.input.wintab', dump_wintab)
if __name__ == '__main__':
dump()
| 7,728 | 33.199115 | 78 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/pyglet/sprite.py
|
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
"""Display positioned, scaled and rotated images.
A sprite is an instance of an image displayed on-screen. Multiple sprites can
display the same image at different positions on the screen. Sprites can also
be scaled larger or smaller, rotated at any angle and drawn at a fractional
opacity.
The following complete example loads a ``"ball.png"`` image and creates a
sprite for that image. The sprite is then drawn in the window's
draw event handler::
import pyglet
ball_image = pyglet.image.load('ball.png')
ball = pyglet.sprite.Sprite(ball_image, x=50, y=50)
window = pyglet.window.Window()
@window.event
def on_draw():
ball.draw()
pyglet.app.run()
The sprite can be moved by modifying the :py:attr:`~pyglet.sprite.Sprite.x` and
:py:attr:`~pyglet.sprite.Sprite.y` properties. Other
properties determine the sprite's :py:attr:`~pyglet.sprite.Sprite.rotation`,
:py:attr:`~pyglet.sprite.Sprite.scale` and
:py:attr:`~pyglet.sprite.Sprite.opacity`.
By default sprite coordinates are restricted to integer values to avoid
sub-pixel artifacts. If you require to use floats, for example for smoother
animations, you can set the ``subpixel`` parameter to ``True`` when creating
the sprite (:since: pyglet 1.2).
The sprite's positioning, rotation and scaling all honor the original
image's anchor (:py:attr:`~pyglet.image.AbstractImage.anchor_x`,
:py:attr:`~pyglet.image.AbstractImage.anchor_y`).
Drawing multiple sprites
========================
Sprites can be "batched" together and drawn at once more quickly than if each
of their ``draw`` methods were called individually. The following example
creates one hundred ball sprites and adds each of them to a :py:class:`~pyglet.graphics.Batch`. The
entire batch of sprites is then drawn in one call::
batch = pyglet.graphics.Batch()
ball_sprites = []
for i in range(100):
x, y = i * 10, 50
ball_sprites.append(pyglet.sprite.Sprite(ball_image, x, y, batch=batch))
@window.event
def on_draw():
batch.draw()
Sprites can be freely modified in any way even after being added to a batch,
however a sprite can belong to at most one batch. See the documentation for
:py:mod:`pyglet.graphics` for more details on batched rendering, and grouping of
sprites within batches.
.. versionadded:: 1.1
"""
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import math
import sys
import warnings
from pyglet.gl import *
from pyglet import clock
from pyglet import event
from pyglet import graphics
from pyglet import image
_is_pyglet_docgen = hasattr(sys, 'is_pyglet_docgen') and sys.is_pyglet_docgen
class SpriteGroup(graphics.Group):
"""Shared sprite rendering group.
The group is automatically coalesced with other sprite groups sharing the
same parent group, texture and blend parameters.
"""
def __init__(self, texture, blend_src, blend_dest, parent=None):
"""Create a sprite group.
The group is created internally within :py:class:`~pyglet.sprite.Sprite`; applications usually
do not need to explicitly create it.
:Parameters:
`texture` : `~pyglet.image.Texture`
The (top-level) texture containing the sprite image.
`blend_src` : int
OpenGL blend source mode; for example,
``GL_SRC_ALPHA``.
`blend_dest` : int
OpenGL blend destination mode; for example,
``GL_ONE_MINUS_SRC_ALPHA``.
`parent` : `~pyglet.graphics.Group`
Optional parent group.
"""
super(SpriteGroup, self).__init__(parent)
self.texture = texture
self.blend_src = blend_src
self.blend_dest = blend_dest
def set_state(self):
glEnable(self.texture.target)
glBindTexture(self.texture.target, self.texture.id)
glPushAttrib(GL_COLOR_BUFFER_BIT)
glEnable(GL_BLEND)
glBlendFunc(self.blend_src, self.blend_dest)
def unset_state(self):
glPopAttrib()
glDisable(self.texture.target)
def __repr__(self):
return '%s(%r)' % (self.__class__.__name__, self.texture)
def __eq__(self, other):
return (other.__class__ is self.__class__ and
self.parent is other.parent and
self.texture.target == other.texture.target and
self.texture.id == other.texture.id and
self.blend_src == other.blend_src and
self.blend_dest == other.blend_dest)
def __hash__(self):
return hash((id(self.parent),
self.texture.id, self.texture.target,
self.blend_src, self.blend_dest))
class Sprite(event.EventDispatcher):
"""Instance of an on-screen image.
See the module documentation for usage.
"""
_batch = None
_animation = None
_rotation = 0
_opacity = 255
_rgb = (255, 255, 255)
_scale = 1.0
_scale_x = 1.0
_scale_y = 1.0
_visible = True
_vertex_list = None
def __init__(self,
img, x=0, y=0,
blend_src=GL_SRC_ALPHA,
blend_dest=GL_ONE_MINUS_SRC_ALPHA,
batch=None,
group=None,
usage='dynamic',
subpixel=False):
"""Create a sprite.
:Parameters:
`img` : `~pyglet.image.AbstractImage` or `~pyglet.image.Animation`
Image or animation to display.
`x` : int
X coordinate of the sprite.
`y` : int
Y coordinate of the sprite.
`blend_src` : int
OpenGL blend source mode. The default is suitable for
compositing sprites drawn from back-to-front.
`blend_dest` : int
OpenGL blend destination mode. The default is suitable for
compositing sprites drawn from back-to-front.
`batch` : `~pyglet.graphics.Batch`
Optional batch to add the sprite to.
`group` : `~pyglet.graphics.Group`
Optional parent group of the sprite.
`usage` : str
Vertex buffer object usage hint, one of ``"none"``,
``"stream"``, ``"dynamic"`` (default) or ``"static"``. Applies
only to vertex data.
`subpixel` : bool
Allow floating-point coordinates for the sprite. By default,
coordinates are restricted to integer values.
"""
if batch is not None:
self._batch = batch
self._x = x
self._y = y
if isinstance(img, image.Animation):
self._animation = img
self._frame_index = 0
self._texture = img.frames[0].image.get_texture()
self._next_dt = img.frames[0].duration
if self._next_dt:
clock.schedule_once(self._animate, self._next_dt)
else:
self._texture = img.get_texture()
self._group = SpriteGroup(self._texture, blend_src, blend_dest, group)
self._usage = usage
self._subpixel = subpixel
self._create_vertex_list()
def __del__(self):
try:
if self._vertex_list is not None:
self._vertex_list.delete()
except:
pass
def delete(self):
"""Force immediate removal of the sprite from video memory.
This is often necessary when using batches, as the Python garbage
collector will not necessarily call the finalizer as soon as the
sprite is garbage.
"""
if self._animation:
clock.unschedule(self._animate)
self._vertex_list.delete()
self._vertex_list = None
self._texture = None
# Easy way to break circular reference, speeds up GC
self._group = None
def _animate(self, dt):
self._frame_index += 1
if self._frame_index >= len(self._animation.frames):
self._frame_index = 0
self.dispatch_event('on_animation_end')
if self._vertex_list is None:
return # Deleted in event handler.
frame = self._animation.frames[self._frame_index]
self._set_texture(frame.image.get_texture())
if frame.duration is not None:
duration = frame.duration - (self._next_dt - dt)
duration = min(max(0, duration), frame.duration)
clock.schedule_once(self._animate, duration)
self._next_dt = duration
else:
self.dispatch_event('on_animation_end')
@property
def batch(self):
"""Graphics batch.
The sprite can be migrated from one batch to another, or removed from
its batch (for individual drawing). Note that this can be an expensive
operation.
:type: :py:class:`pyglet.graphics.Batch`
"""
return self._batch
@batch.setter
def batch(self, batch):
if self._batch == batch:
return
if batch is not None and self._batch is not None:
self._batch.migrate(self._vertex_list, GL_QUADS, self._group, batch)
self._batch = batch
else:
self._vertex_list.delete()
self._batch = batch
self._create_vertex_list()
@property
def group(self):
"""Parent graphics group.
The sprite can change its rendering group, however this can be an
expensive operation.
:type: :py:class:`pyglet.graphics.Group`
"""
return self._group.parent
@group.setter
def group(self, group):
if self._group.parent == group:
return
self._group = SpriteGroup(self._texture,
self._group.blend_src,
self._group.blend_dest,
group)
if self._batch is not None:
self._batch.migrate(self._vertex_list, GL_QUADS, self._group,
self._batch)
@property
def image(self):
"""Image or animation to display.
:type: :py:class:`~pyglet.image.AbstractImage` or
:py:class:`~pyglet.image.Animation`
"""
if self._animation:
return self._animation
return self._texture
@image.setter
def image(self, img):
if self._animation is not None:
clock.unschedule(self._animate)
self._animation = None
if isinstance(img, image.Animation):
self._animation = img
self._frame_index = 0
self._set_texture(img.frames[0].image.get_texture())
self._next_dt = img.frames[0].duration
if self._next_dt:
clock.schedule_once(self._animate, self._next_dt)
else:
self._set_texture(img.get_texture())
self._update_position()
def _set_texture(self, texture):
if texture.id is not self._texture.id:
self._group = SpriteGroup(texture,
self._group.blend_src,
self._group.blend_dest,
self._group.parent)
if self._batch is None:
self._vertex_list.tex_coords[:] = texture.tex_coords
else:
self._vertex_list.delete()
self._texture = texture
self._create_vertex_list()
else:
self._vertex_list.tex_coords[:] = texture.tex_coords
self._texture = texture
def _create_vertex_list(self):
if self._subpixel:
vertex_format = 'v2f/%s' % self._usage
else:
vertex_format = 'v2i/%s' % self._usage
if self._batch is None:
self._vertex_list = graphics.vertex_list(4, vertex_format,
'c4B', ('t3f', self._texture.tex_coords))
else:
self._vertex_list = self._batch.add(4, GL_QUADS, self._group,
vertex_format, 'c4B', ('t3f', self._texture.tex_coords))
self._update_position()
self._update_color()
def _update_position(self):
img = self._texture
scale_x = self._scale * self.scale_x
scale_y = self._scale * self.scale_y
if not self._visible:
vertices = (0, 0, 0, 0, 0, 0, 0, 0)
elif self._rotation:
x1 = -img.anchor_x * scale_x
y1 = -img.anchor_y * scale_y
x2 = x1 + img.width * scale_x
y2 = y1 + img.height * scale_y
x = self._x
y = self._y
r = -math.radians(self._rotation)
cr = math.cos(r)
sr = math.sin(r)
ax = x1 * cr - y1 * sr + x
ay = x1 * sr + y1 * cr + y
bx = x2 * cr - y1 * sr + x
by = x2 * sr + y1 * cr + y
cx = x2 * cr - y2 * sr + x
cy = x2 * sr + y2 * cr + y
dx = x1 * cr - y2 * sr + x
dy = x1 * sr + y2 * cr + y
vertices = (ax, ay, bx, by, cx, cy, dx, dy)
elif scale_x != 1.0 or scale_y != 1.0:
x1 = self._x - img.anchor_x * scale_x
y1 = self._y - img.anchor_y * scale_y
x2 = x1 + img.width * scale_x
y2 = y1 + img.height * scale_y
vertices = (x1, y1, x2, y1, x2, y2, x1, y2)
else:
x1 = self._x - img.anchor_x
y1 = self._y - img.anchor_y
x2 = x1 + img.width
y2 = y1 + img.height
vertices = (x1, y1, x2, y1, x2, y2, x1, y2)
if not self._subpixel:
vertices = (int(vertices[0]), int(vertices[1]),
int(vertices[2]), int(vertices[3]),
int(vertices[4]), int(vertices[5]),
int(vertices[6]), int(vertices[7]))
self._vertex_list.vertices[:] = vertices
def _update_color(self):
r, g, b = self._rgb
self._vertex_list.colors[:] = [r, g, b, int(self._opacity)] * 4
@property
def position(self):
"""The (x, y) coordinates of the sprite, as a tuple.
:Parameters:
`x` : int
X coordinate of the sprite.
`y` : int
Y coordinate of the sprite.
"""
return self._x, self._y
@position.setter
def position(self, pos):
self._x, self._y = pos
self._update_position()
def set_position(self, x, y):
"""Set the X and Y coordinates of the sprite simultaneously.
:Parameters:
`x` : int
X coordinate of the sprite.
`y` : int
Y coordinate of the sprite.
:deprecated: Set the X, Y coordinates via sprite.position instead.
"""
self._x = x
self._y = y
self._update_position()
warnings.warn("Use position property instead.", DeprecationWarning)
@property
def x(self):
"""X coordinate of the sprite.
:type: int
"""
return self._x
@x.setter
def x(self, x):
self._x = x
self._update_position()
@property
def y(self):
"""Y coordinate of the sprite.
:type: int
"""
return self._y
@y.setter
def y(self, y):
self._y = y
self._update_position()
@property
def rotation(self):
"""Clockwise rotation of the sprite, in degrees.
The sprite image will be rotated about its image's (anchor_x, anchor_y)
position.
:type: float
"""
return self._rotation
@rotation.setter
def rotation(self, rotation):
self._rotation = rotation
self._update_position()
@property
def scale(self):
"""Base Scaling factor.
A scaling factor of 1 (the default) has no effect. A scale of 2 will
draw the sprite at twice the native size of its image.
:type: float
"""
return self._scale
@scale.setter
def scale(self, scale):
self._scale = scale
self._update_position()
@property
def scale_x(self):
"""Horizontal scaling factor.
A scaling factor of 1 (the default) has no effect. A scale of 2 will
draw the sprite at twice the native width of its image.
:type: float
"""
return self._scale_x
@scale_x.setter
def scale_x(self, scale_x):
self._scale_x = scale_x
self._update_position()
@property
def scale_y(self):
"""Vertical scaling factor.
A scaling factor of 1 (the default) has no effect. A scale of 2 will
draw the sprite at twice the native height of its image.
:type: float
"""
return self._scale_y
@scale_y.setter
def scale_y(self, scale_y):
self._scale_y = scale_y
self._update_position()
def update(self, x=None, y=None, rotation=None, scale=None, scale_x=None, scale_y=None):
"""Simultaneously change the position, rotation or scale.
This method is provided for performance. In cases where
multiple Sprite attributes need to be updated at the same
time, it is more efficent to update them together using
the update method, rather than modifying them one by one.
:Parameters:
`x` : int
X coordinate of the sprite.
`y` : int
Y coordinate of the sprite.
`rotation` : float
Clockwise rotation of the sprite, in degrees.
`scale` : float
Scaling factor.
`scale_x` : float
Horizontal scaling factor.
`scale_y` : float
Vertical scaling factor.
"""
if x is not None:
self._x = x
if y is not None:
self._y = y
if rotation is not None:
self._rotation = rotation
if scale is not None:
self._scale = scale
if scale_x is not None:
self._scale_x = scale_x
if scale_y is not None:
self._scale_y = scale_y
self._update_position()
@property
def width(self):
"""Scaled width of the sprite.
Read-only. Invariant under rotation.
:type: int
"""
if self._subpixel:
return self._texture.width * abs(self._scale_x) * abs(self._scale)
else:
return int(self._texture.width * abs(self._scale_x) * abs(self._scale))
@property
def height(self):
"""Scaled height of the sprite.
Read-only. Invariant under rotation.
:type: int
"""
if self._subpixel:
return self._texture.height * abs(self._scale_y) * abs(self._scale)
else:
return int(self._texture.height * abs(self._scale_y) * abs(self._scale))
@property
def opacity(self):
"""Blend opacity.
This property sets the alpha component of the colour of the sprite's
vertices. With the default blend mode (see the constructor), this
allows the sprite to be drawn with fractional opacity, blending with the
background.
An opacity of 255 (the default) has no effect. An opacity of 128 will
make the sprite appear translucent.
:type: int
"""
return self._opacity
@opacity.setter
def opacity(self, opacity):
self._opacity = opacity
self._update_color()
@property
def color(self):
"""Blend color.
This property sets the color of the sprite's vertices. This allows the
sprite to be drawn with a color tint.
The color is specified as an RGB tuple of integers '(red, green, blue)'.
Each color component must be in the range 0 (dark) to 255 (saturated).
:type: (int, int, int)
"""
return self._rgb
@color.setter
def color(self, rgb):
self._rgb = list(map(int, rgb))
self._update_color()
@property
def visible(self):
"""True if the sprite will be drawn.
:type: bool
"""
return self._visible
@visible.setter
def visible(self, visible):
self._visible = visible
self._update_position()
def draw(self):
"""Draw the sprite at its current position.
See the module documentation for hints on drawing multiple sprites
efficiently.
"""
self._group.set_state_recursive()
self._vertex_list.draw(GL_QUADS)
self._group.unset_state_recursive()
if _is_pyglet_docgen:
def on_animation_end(self):
"""The sprite animation reached the final frame.
The event is triggered only if the sprite has an animation, not an
image. For looping animations, the event is triggered each time
the animation loops.
:event:
"""
Sprite.register_event_type('on_animation_end')
| 22,869 | 31.347949 | 102 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/pyglet/__init__.py
|
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
"""pyglet is a cross-platform games and multimedia package.
Detailed documentation is available at http://www.pyglet.org
"""
from __future__ import print_function
from __future__ import absolute_import
# Check if future is installed, if not use included batteries
try:
import future
except ImportError:
import os.path as op
import sys
future_base = op.abspath(op.join(op.dirname(__file__), 'extlibs', 'future'))
sys.path.insert(0, op.join(future_base, 'py2_3'))
if sys.version_info[:2] < (3, 0):
sys.path.insert(0, op.join(future_base, 'py2'))
del future_base
del sys
del op
try:
import future
except ImportError:
print('Failed to get python-future')
raise
from builtins import range
from builtins import object
import os
import sys
import warnings
if 'sphinx' in sys.modules:
setattr(sys, 'is_pyglet_docgen', True)
_is_pyglet_docgen = hasattr(sys, 'is_pyglet_docgen') and sys.is_pyglet_docgen
#: The release version of this pyglet installation.
#:
#: Valid only if pyglet was installed from a source or binary distribution
#: (i.e. not in a checked-out copy from SVN).
#:
#: Use setuptools if you need to check for a specific release version, e.g.::
#:
#: >>> import pyglet
#: >>> from pkg_resources import parse_version
#: >>> parse_version(pyglet.version) >= parse_version('1.1')
#: True
#:
version = '1.3.2'
# Pyglet platform treats *BSD systems as Linux
compat_platform = sys.platform
if "bsd" in compat_platform:
compat_platform = "linux-compat"
_enable_optimisations = not __debug__
if getattr(sys, 'frozen', None):
_enable_optimisations = True
#: Global dict of pyglet options. To change an option from its default, you
#: must import ``pyglet`` before any sub-packages. For example::
#:
#: import pyglet
#: pyglet.options['debug_gl'] = False
#:
#: The default options can be overridden from the OS environment. The
#: corresponding environment variable for each option key is prefaced by
#: ``PYGLET_``. For example, in Bash you can set the ``debug_gl`` option with::
#:
#: PYGLET_DEBUG_GL=True; export PYGLET_DEBUG_GL
#:
#: For options requiring a tuple of values, separate each value with a comma.
#:
#: The non-development options are:
#:
#: audio
#: A sequence of the names of audio modules to attempt to load, in
#: order of preference. Valid driver names are:
#:
#: * directsound, the Windows DirectSound audio module (Windows only)
#: * pulse, the PulseAudio module (Linux only)
#: * openal, the OpenAL audio module
#: * silent, no audio
#: debug_lib
#: If True, prints the path of each dynamic library loaded.
#: debug_gl
#: If True, all calls to OpenGL functions are checked afterwards for
#: errors using ``glGetError``. This will severely impact performance,
#: but provides useful exceptions at the point of failure. By default,
#: this option is enabled if ``__debug__`` is (i.e., if Python was not run
#: with the -O option). It is disabled by default when pyglet is "frozen"
#: within a py2exe or py2app library archive.
#: shadow_window
#: By default, pyglet creates a hidden window with a GL context when
#: pyglet.gl is imported. This allows resources to be loaded before
#: the application window is created, and permits GL objects to be
#: shared between windows even after they've been closed. You can
#: disable the creation of the shadow window by setting this option to
#: False.
#:
#: Some OpenGL driver implementations may not support shared OpenGL
#: contexts and may require disabling the shadow window (and all resources
#: must be loaded after the window using them was created). Recommended
#: for advanced developers only.
#:
#: .. versionadded:: 1.1
#: vsync
#: If set, the `pyglet.window.Window.vsync` property is ignored, and
#: this option overrides it (to either force vsync on or off). If unset,
#: or set to None, the `pyglet.window.Window.vsync` property behaves
#: as documented.
#: xsync
#: If set (the default), pyglet will attempt to synchronise the drawing of
#: double-buffered windows to the border updates of the X11 window
#: manager. This improves the appearance of the window during resize
#: operations. This option only affects double-buffered windows on
#: X11 servers supporting the Xsync extension with a window manager
#: that implements the _NET_WM_SYNC_REQUEST protocol.
#:
#: .. versionadded:: 1.1
#: darwin_cocoa
#: If True, the Cocoa-based pyglet implementation is used as opposed to
#: the 32-bit Carbon implementation. When python is running in 64-bit mode
#: on Mac OS X 10.6 or later, this option is set to True by default.
#: Otherwise the Carbon implementation is preferred.
#:
#: .. versionadded:: 1.2
#:
#: search_local_libs
#: If False, pyglet won't try to search for libraries in the script
#: directory and its `lib` subdirectory. This is useful to load a local
#: library instead of the system installed version. This option is set
#: to True by default.
#:
#: .. versionadded:: 1.2
#:
options = {
'audio': ('directsound', 'pulse', 'openal', 'silent'),
'font': ('gdiplus', 'win32'), # ignored outside win32; win32 is deprecated
'debug_font': False,
'debug_gl': not _enable_optimisations,
'debug_gl_trace': False,
'debug_gl_trace_args': False,
'debug_graphics_batch': False,
'debug_lib': False,
'debug_media': False,
'debug_texture': False,
'debug_trace': False,
'debug_trace_args': False,
'debug_trace_depth': 1,
'debug_trace_flush': True,
'debug_win32': False,
'debug_x11': False,
'graphics_vbo': True,
'shadow_window': True,
'vsync': None,
'xsync': True,
'xlib_fullscreen_override_redirect': False,
'darwin_cocoa': False,
'search_local_libs': True,
}
_option_types = {
'audio': tuple,
'font': tuple,
'debug_font': bool,
'debug_gl': bool,
'debug_gl_trace': bool,
'debug_gl_trace_args': bool,
'debug_graphics_batch': bool,
'debug_lib': bool,
'debug_media': bool,
'debug_texture': bool,
'debug_trace': bool,
'debug_trace_args': bool,
'debug_trace_depth': int,
'debug_trace_flush': bool,
'debug_win32': bool,
'debug_x11': bool,
'graphics_vbo': bool,
'shadow_window': bool,
'vsync': bool,
'xsync': bool,
'xlib_fullscreen_override_redirect': bool,
'darwin_cocoa': bool,
}
def _choose_darwin_platform():
"""Choose between Darwin's Carbon and Cocoa implementations."""
if compat_platform != 'darwin':
return
import struct
numbits = 8*struct.calcsize("P")
if numbits == 64:
import platform
osx_version = platform.mac_ver()[0].split(".")
if int(osx_version[0]) == 10 and int(osx_version[1]) < 6:
raise Exception('pyglet is not compatible with 64-bit Python '
'for versions of Mac OS X prior to 10.6.')
options['darwin_cocoa'] = True
else:
options['darwin_cocoa'] = False
_choose_darwin_platform() # can be overridden by an environment variable below
def _read_environment():
"""Read defaults for options from environment"""
for key in options:
env = 'PYGLET_%s' % key.upper()
try:
value = os.environ[env]
if _option_types[key] is tuple:
options[key] = value.split(',')
elif _option_types[key] is bool:
options[key] = value in ('true', 'TRUE', 'True', '1')
elif _option_types[key] is int:
options[key] = int(value)
except KeyError:
pass
_read_environment()
if compat_platform == 'cygwin':
# This hack pretends that the posix-like ctypes provides windows
# functionality. COM does not work with this hack, so there is no
# DirectSound support.
import ctypes
ctypes.windll = ctypes.cdll
ctypes.oledll = ctypes.cdll
ctypes.WINFUNCTYPE = ctypes.CFUNCTYPE
ctypes.HRESULT = ctypes.c_long
if compat_platform == 'darwin' and not options['darwin_cocoa']:
warnings.warn('Carbon support is to be deprecated in Pyglet 1.4', PendingDeprecationWarning)
# Call tracing
# ------------
_trace_filename_abbreviations = {}
def _trace_repr(value, size=40):
value = repr(value)
if len(value) > size:
value = value[:size//2-2] + '...' + value[-size//2-1:]
return value
def _trace_frame(thread, frame, indent):
from pyglet import lib
if frame.f_code is lib._TraceFunction.__call__.__code__:
is_ctypes = True
func = frame.f_locals['self']._func
name = func.__name__
location = '[ctypes]'
else:
is_ctypes = False
code = frame.f_code
name = code.co_name
path = code.co_filename
line = code.co_firstlineno
try:
filename = _trace_filename_abbreviations[path]
except KeyError:
# Trim path down
dir = ''
path, filename = os.path.split(path)
while len(dir + filename) < 30:
filename = os.path.join(dir, filename)
path, dir = os.path.split(path)
if not dir:
filename = os.path.join('', filename)
break
else:
filename = os.path.join('...', filename)
_trace_filename_abbreviations[path] = filename
location = '(%s:%d)' % (filename, line)
if indent:
name = 'Called from %s' % name
print('[%d] %s%s %s' % (thread, indent, name, location))
if _trace_args:
if is_ctypes:
args = [_trace_repr(arg) for arg in frame.f_locals['args']]
print(' %sargs=(%s)' % (indent, ', '.join(args)))
else:
for argname in code.co_varnames[:code.co_argcount]:
try:
argvalue = _trace_repr(frame.f_locals[argname])
print(' %s%s=%s' % (indent, argname, argvalue))
except:
pass
if _trace_flush:
sys.stdout.flush()
def _thread_trace_func(thread):
def _trace_func(frame, event, arg):
if event == 'call':
indent = ''
for i in range(_trace_depth):
_trace_frame(thread, frame, indent)
indent += ' '
frame = frame.f_back
if not frame:
break
elif event == 'exception':
(exception, value, traceback) = arg
print('First chance exception raised:', repr(exception))
return _trace_func
def _install_trace():
global _trace_thread_count
sys.setprofile(_thread_trace_func(_trace_thread_count))
_trace_thread_count += 1
_trace_thread_count = 0
_trace_args = options['debug_trace_args']
_trace_depth = options['debug_trace_depth']
_trace_flush = options['debug_trace_flush']
if options['debug_trace']:
_install_trace()
# Lazy loading
# ------------
class _ModuleProxy(object):
_module = None
def __init__(self, name):
self.__dict__['_module_name'] = name
def __getattr__(self, name):
try:
return getattr(self._module, name)
except AttributeError:
if self._module is not None:
raise
import_name = 'pyglet.%s' % self._module_name
__import__(import_name)
module = sys.modules[import_name]
object.__setattr__(self, '_module', module)
globals()[self._module_name] = module
return getattr(module, name)
def __setattr__(self, name, value):
try:
setattr(self._module, name, value)
except AttributeError:
if self._module is not None:
raise
import_name = 'pyglet.%s' % self._module_name
__import__(import_name)
module = sys.modules[import_name]
object.__setattr__(self, '_module', module)
globals()[self._module_name] = module
setattr(module, name, value)
if True:
app = _ModuleProxy('app')
canvas = _ModuleProxy('canvas')
clock = _ModuleProxy('clock')
com = _ModuleProxy('com')
event = _ModuleProxy('event')
font = _ModuleProxy('font')
gl = _ModuleProxy('gl')
graphics = _ModuleProxy('graphics')
image = _ModuleProxy('image')
input = _ModuleProxy('input')
lib = _ModuleProxy('lib')
media = _ModuleProxy('media')
resource = _ModuleProxy('resource')
sprite = _ModuleProxy('sprite')
text = _ModuleProxy('text')
window = _ModuleProxy('window')
# Fool py2exe, py2app into including all top-level modules (doesn't understand
# lazy loading)
if False:
from . import app
from . import canvas
from . import clock
from . import com
from . import event
from . import font
from . import gl
from . import graphics
from . import input
from . import image
from . import lib
from . import media
from . import resource
from . import sprite
from . import text
from . import window
# Hack around some epydoc bug that causes it to think pyglet.window is None.
if False:
from . import window
| 15,079 | 32.88764 | 96 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/pyglet/compat.py
|
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
'''Compatibility tools
Various tools for simultaneous Python 2.x and Python 3.x support
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import sys
import itertools
if sys.version_info[0] == 2:
if sys.version_info[1] < 6:
#Pure Python implementation from
#http://docs.python.org/library/itertools.html#itertools.izip_longest
def izip_longest(*args, **kwds):
# izip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D-
fillvalue = kwds.get('fillvalue')
def sentinel(counter = ([fillvalue]*(len(args)-1)).pop):
yield counter() # yields the fillvalue, or raises IndexError
fillers = itertools.repeat(fillvalue)
iters = [itertools.chain(it, sentinel(), fillers) for it in args]
try:
for tup in itertools.izip(*iters):
yield tup
except IndexError:
pass
else:
izip_longest = itertools.izip_longest
else:
izip_longest = itertools.zip_longest
if sys.version_info[0] >= 3:
import io
def asbytes(s):
if isinstance(s, bytes):
return s
elif isinstance(s, str):
return bytes(ord(c) for c in s)
else:
return bytes(s)
def asbytes_filename(s):
if isinstance(s, bytes):
return s
elif isinstance(s, str):
return s.encode(encoding=sys.getfilesystemencoding())
def asstr(s):
if s is None:
return ''
if isinstance(s, str):
return s
return s.decode("utf-8")
bytes_type = bytes
BytesIO = io.BytesIO
else:
import StringIO
asbytes = str
asbytes_filename = str
asstr = str
bytes_type = str
BytesIO = StringIO.StringIO
| 3,545 | 33.764706 | 80 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/pyglet/debug.py
|
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
from __future__ import print_function
import pyglet
def debug_print(enabled_or_option='debug'):
"""Get a debug printer that is enabled based on a boolean input or a pyglet option.
The debug print function returned should be used in an assert. This way it can be
optimized out when running python with the -O flag.
Usage example::
from pyglet.debug import debug_print
_debug_media = debug_print('debug_media')
def some_func():
assert _debug_media('My debug statement')
:parameters:
`enabled_or_options` : bool or str
If a bool is passed, debug printing is enabled if it is True. If str is passed
debug printing is enabled if the pyglet option with that name is True.
:returns: Function for debug printing.
"""
if isinstance(enabled_or_option, bool):
enabled = enabled_or_option
else:
enabled = pyglet.options.get(enabled_or_option, False)
if enabled:
def _debug_print(*args, **kwargs):
print(*args, **kwargs)
return True
else:
def _debug_print(*args, **kwargs):
return True
return _debug_print
| 2,904 | 37.733333 | 90 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/pyglet/image/__init__.py
|
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
"""Image load, capture and high-level texture functions.
Only basic functionality is described here; for full reference see the
accompanying documentation.
To load an image::
from pyglet import image
pic = image.load('picture.png')
The supported image file types include PNG, BMP, GIF, JPG, and many more,
somewhat depending on the operating system. To load an image from a file-like
object instead of a filename::
pic = image.load('hint.jpg', file=fileobj)
The hint helps the module locate an appropriate decoder to use based on the
file extension. It is optional.
Once loaded, images can be used directly by most other modules of pyglet. All
images have a width and height you can access::
width, height = pic.width, pic.height
You can extract a region of an image (this keeps the original image intact;
the memory is shared efficiently)::
subimage = pic.get_region(x, y, width, height)
Remember that y-coordinates are always increasing upwards.
Drawing images
--------------
To draw an image at some point on the screen::
pic.blit(x, y, z)
This assumes an appropriate view transform and projection have been applied.
Some images have an intrinsic "anchor point": this is the point which will be
aligned to the ``x`` and ``y`` coordinates when the image is drawn. By
default the anchor point is the lower-left corner of the image. You can use
the anchor point to center an image at a given point, for example::
pic.anchor_x = pic.width // 2
pic.anchor_y = pic.height // 2
pic.blit(x, y, z)
Texture access
--------------
If you are using OpenGL directly, you can access the image as a texture::
texture = pic.get_texture()
(This is the most efficient way to obtain a texture; some images are
immediately loaded as textures, whereas others go through an intermediate
form). To use a texture with pyglet.gl::
from pyglet.gl import *
glEnable(texture.target) # typically target is GL_TEXTURE_2D
glBindTexture(texture.target, texture.id)
# ... draw with the texture
Pixel access
------------
To access raw pixel data of an image::
rawimage = pic.get_image_data()
(If the image has just been loaded this will be a very quick operation;
however if the image is a texture a relatively expensive readback operation
will occur). The pixels can be accessed as a string::
format = 'RGBA'
pitch = rawimage.width * len(format)
pixels = rawimage.get_data(format, pitch)
"format" strings consist of characters that give the byte order of each color
component. For example, if rawimage.format is 'RGBA', there are four color
components: red, green, blue and alpha, in that order. Other common format
strings are 'RGB', 'LA' (luminance, alpha) and 'I' (intensity).
The "pitch" of an image is the number of bytes in a row (this may validly be
more than the number required to make up the width of the image, it is common
to see this for word alignment). If "pitch" is negative the rows of the image
are ordered from top to bottom, otherwise they are ordered from bottom to top.
Retrieving data with the format and pitch given in `ImageData.format` and
`ImageData.pitch` avoids the need for data conversion (assuming you can make
use of the data in this arbitrary format).
"""
from __future__ import division
from builtins import bytes
from builtins import zip
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
from io import open
import re
import warnings
import weakref
from ctypes import *
from pyglet.gl import *
from pyglet.gl import gl_info
from pyglet.window import *
from pyglet.image import atlas
from pyglet.image import codecs as _codecs
from pyglet.compat import asbytes, bytes_type, BytesIO
class ImageException(Exception):
pass
def load(filename, file=None, decoder=None):
"""Load an image from a file.
:note: You can make no assumptions about the return type; usually it will
be ImageData or CompressedImageData, but decoders are free to return
any subclass of AbstractImage.
:Parameters:
`filename` : str
Used to guess the image format, and to load the file if `file` is
unspecified.
`file` : file-like object or None
Source of image data in any supported format.
`decoder` : ImageDecoder or None
If unspecified, all decoders that are registered for the filename
extension are tried. If none succeed, the exception from the
first decoder is raised.
:rtype: AbstractImage
"""
if not file:
file = open(filename, 'rb')
opened_file = file
else:
opened_file = None
if not hasattr(file, 'seek'):
file = BytesIO(file.read())
try:
if decoder:
return decoder.decode(file, filename)
else:
first_exception = None
for decoder in _codecs.get_decoders(filename):
try:
image = decoder.decode(file, filename)
return image
except _codecs.ImageDecodeException as e:
if (not first_exception or
first_exception.exception_priority < e.exception_priority):
first_exception = e
file.seek(0)
if not first_exception:
raise _codecs.ImageDecodeException('No image decoders are available')
raise first_exception
finally:
if opened_file:
opened_file.close()
def create(width, height, pattern=None):
"""Create an image optionally filled with the given pattern.
:note: You can make no assumptions about the return type; usually it will
be ImageData or CompressedImageData, but patterns are free to return
any subclass of AbstractImage.
:Parameters:
`width` : int
Width of image to create
`height` : int
Height of image to create
`pattern` : ImagePattern or None
Pattern to fill image with. If unspecified, the image will
initially be transparent.
:rtype: AbstractImage
"""
if not pattern:
pattern = SolidColorImagePattern()
return pattern.create_image(width, height)
def color_as_bytes(color):
if sys.version.startswith('2'):
return '%c%c%c%c' % color
else:
if len(color) != 4:
raise TypeError("color is expected to have 4 components")
return bytes(color)
class ImagePattern(object):
"""Abstract image creation class."""
def create_image(self, width, height):
"""Create an image of the given size.
:Parameters:
`width` : int
Width of image to create
`height` : int
Height of image to create
:rtype: AbstractImage
"""
raise NotImplementedError('abstract')
class SolidColorImagePattern(ImagePattern):
"""Creates an image filled with a solid color."""
def __init__(self, color=(0, 0, 0, 0)):
"""Create a solid image pattern with the given color.
:Parameters:
`color` : (int, int, int, int)
4-tuple of ints in range [0,255] giving RGBA components of
color to fill with.
"""
self.color = color_as_bytes(color)
def create_image(self, width, height):
data = self.color * width * height
return ImageData(width, height, 'RGBA', data)
class CheckerImagePattern(ImagePattern):
"""Create an image with a tileable checker image.
"""
def __init__(self, color1=(150, 150, 150, 255), color2=(200, 200, 200, 255)):
"""Initialise with the given colors.
:Parameters:
`color1` : (int, int, int, int)
4-tuple of ints in range [0,255] giving RGBA components of
color to fill with. This color appears in the top-left and
bottom-right corners of the image.
`color2` : (int, int, int, int)
4-tuple of ints in range [0,255] giving RGBA components of
color to fill with. This color appears in the top-right and
bottom-left corners of the image.
"""
self.color1 = color_as_bytes(color1)
self.color2 = color_as_bytes(color2)
def create_image(self, width, height):
hw = width // 2
hh = height // 2
row1 = self.color1 * hw + self.color2 * hw
row2 = self.color2 * hw + self.color1 * hw
data = row1 * hh + row2 * hh
return ImageData(width, height, 'RGBA', data)
class AbstractImage(object):
"""Abstract class representing an image.
:Ivariables:
`width` : int
Width of image
`height` : int
Height of image
`anchor_x` : int
X coordinate of anchor, relative to left edge of image data
`anchor_y` : int
Y coordinate of anchor, relative to bottom edge of image data
"""
anchor_x = 0
anchor_y = 0
_is_rectangle = False
def __init__(self, width, height):
self.width = width
self.height = height
def __repr__(self):
return '<%s %dx%d>' % (self.__class__.__name__, self.width, self.height)
def get_image_data(self):
"""Get an ImageData view of this image.
Changes to the returned instance may or may not be reflected in this
image.
:rtype: :py:class:`~pyglet.image.ImageData`
.. versionadded:: 1.1
"""
raise ImageException('Cannot retrieve image data for %r' % self)
@property
def image_data(self):
"""An :py:class:`~pyglet.image.ImageData` view of this image.
Changes to the returned instance may or may not be reflected in this
image. Read-only.
:deprecated: Use :py:meth:`~pyglet.image.ImageData.get_image_data`.
:type: :py:class:`~pyglet.image.ImageData`
"""
return self.get_image_data()
def get_texture(self, rectangle=False, force_rectangle=False):
"""A :py:class:`~pyglet.image.Texture` view of this image.
By default, textures are created with dimensions that are powers of
two. Smaller images will return a :py:class:`~pyglet.image.TextureRegion` that covers just
the image portion of the larger texture. This restriction is required
on older video cards, and for compressed textures, or where texture
repeat modes will be used, or where mipmapping is desired.
If the `rectangle` parameter is ``True``, this restriction is ignored
and a texture the size of the image may be created if the driver
supports the ``GL_ARB_texture_rectangle`` or
``GL_NV_texture_rectangle`` extensions. If the extensions are not
present, the image already is a texture, or the image has power 2
dimensions, the `rectangle` parameter is ignored.
Examine `Texture.target` to determine if the returned texture is a
rectangle (``GL_TEXTURE_RECTANGLE_ARB`` or
``GL_TEXTURE_RECTANGLE_NV``) or not (``GL_TEXTURE_2D``).
If the `force_rectangle` parameter is ``True``, one of these
extensions must be present, and the returned texture always
has target ``GL_TEXTURE_RECTANGLE_ARB`` or ``GL_TEXTURE_RECTANGLE_NV``.
Changes to the returned instance may or may not be reflected in this
image.
:Parameters:
`rectangle` : bool
True if the texture can be created as a rectangle.
`force_rectangle` : bool
True if the texture must be created as a rectangle.
.. versionadded:: 1.1.4.
:rtype: :py:class:`~pyglet.image.Texture`
.. versionadded:: 1.1
"""
raise ImageException('Cannot retrieve texture for %r' % self)
@property
def texture(self):
"""Get a :py:class:`~pyglet.image.Texture` view of this image.
Changes to the returned instance may or may not be reflected in this
image.
:deprecated: Use :py:meth:`~pyglet.image.AbstractImage.get_texture`.
:type: :py:class:`~pyglet.image.Texture`
"""
return self.get_texture()
def get_mipmapped_texture(self):
"""Retrieve a :py:class:`~pyglet.image.Texture` instance with all mipmap levels filled in.
Requires that image dimensions be powers of 2.
:rtype: :py:class:`~pyglet.image.Texture`
.. versionadded:: 1.1
"""
raise ImageException('Cannot retrieve mipmapped texture for %r' % self)
@property
def mipmapped_texture(self):
"""A Texture view of this image.
The returned Texture will have mipmaps filled in for all levels.
Requires that image dimensions be powers of 2. Read-only.
:deprecated: Use `get_mipmapped_texture`.
:type: :py:class:`~pyglet.image.Texture`
"""
return self.get_mipmapped_texture()
def get_region(self, x, y, width, height):
"""Retrieve a rectangular region of this image.
:Parameters:
`x` : int
Left edge of region.
`y` : int
Bottom edge of region.
`width` : int
Width of region.
`height` : int
Height of region.
:rtype: AbstractImage
"""
raise ImageException('Cannot get region for %r' % self)
def save(self, filename=None, file=None, encoder=None):
"""Save this image to a file.
:Parameters:
`filename` : str
Used to set the image file format, and to open the output file
if `file` is unspecified.
`file` : file-like object or None
File to write image data to.
`encoder` : ImageEncoder or None
If unspecified, all encoders matching the filename extension
are tried. If all fail, the exception from the first one
attempted is raised.
"""
if not file:
file = open(filename, 'wb')
if encoder:
encoder.encode(self, file, filename)
else:
first_exception = None
for encoder in _codecs.get_encoders(filename):
try:
encoder.encode(self, file, filename)
return
except _codecs.ImageEncodeException as e:
first_exception = first_exception or e
file.seek(0)
if not first_exception:
raise _codecs.ImageEncodeException(
'No image encoders are available')
raise first_exception
def blit(self, x, y, z=0):
"""Draw this image to the active framebuffers.
The image will be drawn with the lower-left corner at
(``x -`` `anchor_x`, ``y -`` `anchor_y`, ``z``).
"""
raise ImageException('Cannot blit %r.' % self)
def blit_into(self, source, x, y, z):
"""Draw `source` on this image.
`source` will be copied into this image such that its anchor point
is aligned with the `x` and `y` parameters. If this image is a 3D
texture, the `z` coordinate gives the image slice to copy into.
Note that if `source` is larger than this image (or the positioning
would cause the copy to go out of bounds) then you must pass a
region of `source` to this method, typically using get_region().
"""
raise ImageException('Cannot blit images onto %r.' % self)
def blit_to_texture(self, target, level, x, y, z=0):
"""Draw this image on the currently bound texture at `target`.
This image is copied into the texture such that this image's anchor
point is aligned with the given `x` and `y` coordinates of the
destination texture. If the currently bound texture is a 3D texture,
the `z` coordinate gives the image slice to blit into.
"""
raise ImageException('Cannot blit %r to a texture.' % self)
class AbstractImageSequence(object):
"""Abstract sequence of images.
The sequence is useful for storing image animations or slices of a volume.
For efficient access, use the `texture_sequence` member. The class
also implements the sequence interface (`__len__`, `__getitem__`,
`__setitem__`).
"""
def get_texture_sequence(self):
"""Get a TextureSequence.
:rtype: `TextureSequence`
.. versionadded:: 1.1
"""
raise NotImplementedError('abstract')
@property
def texture_sequence(self):
"""Access this image sequence as a texture sequence.
:deprecated: Use `get_texture_sequence`
:type: `TextureSequence`
"""
return self.get_texture_sequence()
def get_animation(self, period, loop=True):
"""Create an animation over this image sequence for the given constant
framerate.
:Parameters
`period` : float
Number of seconds to display each frame.
`loop` : bool
If True, the animation will loop continuously.
:rtype: :py:class:`~pyglet.image.Animation`
.. versionadded:: 1.1
"""
return Animation.from_image_sequence(self, period, loop)
def __getitem__(self, slice):
"""Retrieve a (list of) image.
:rtype: AbstractImage
"""
raise NotImplementedError('abstract')
def __setitem__(self, slice, image):
"""Replace one or more images in the sequence.
:Parameters:
`image` : `~pyglet.image.AbstractImage`
The replacement image. The actual instance may not be used,
depending on this implementation.
"""
raise NotImplementedError('abstract')
def __len__(self):
raise NotImplementedError('abstract')
def __iter__(self):
"""Iterate over the images in sequence.
:rtype: Iterator
.. versionadded:: 1.1
"""
raise NotImplementedError('abstract')
class TextureSequence(AbstractImageSequence):
"""Interface for a sequence of textures.
Typical implementations store multiple :py:class:`~pyglet.image.TextureRegion` s within one
:py:class:`~pyglet.image.Texture` so as to minimise state changes.
"""
def get_texture_sequence(self):
return self
class UniformTextureSequence(TextureSequence):
"""Interface for a sequence of textures, each with the same dimensions.
:Ivariables:
`item_width` : int
Width of each texture in the sequence.
`item_height` : int
Height of each texture in the sequence.
"""
def _get_item_width(self):
raise NotImplementedError('abstract')
def _get_item_height(self):
raise NotImplementedError('abstract')
@property
def item_width(self):
return self._get_item_width()
@property
def item_height(self):
return self._get_item_height()
class ImageData(AbstractImage):
"""An image represented as a string of unsigned bytes.
:Ivariables:
`data` : str
Pixel data, encoded according to `format` and `pitch`.
`format` : str
The format string to use when reading or writing `data`.
`pitch` : int
Number of bytes per row. Negative values indicate a top-to-bottom
arrangement.
Setting the `format` and `pitch` instance variables and reading `data` is
deprecated; use `get_data` and `set_data` in new applications. (Reading
`format` and `pitch` to obtain the current encoding is not deprecated).
"""
_swap1_pattern = re.compile(asbytes('(.)'), re.DOTALL)
_swap2_pattern = re.compile(asbytes('(.)(.)'), re.DOTALL)
_swap3_pattern = re.compile(asbytes('(.)(.)(.)'), re.DOTALL)
_swap4_pattern = re.compile(asbytes('(.)(.)(.)(.)'), re.DOTALL)
_current_texture = None
_current_mipmap_texture = None
def __init__(self, width, height, format, data, pitch=None):
"""Initialise image data.
:Parameters:
`width` : int
Width of image data
`height` : int
Height of image data
`format` : str
A valid format string, such as 'RGB', 'RGBA', 'ARGB', etc.
`data` : sequence
String or array/list of bytes giving the decoded data.
`pitch` : int or None
If specified, the number of bytes per row. Negative values
indicate a top-to-bottom arrangement. Defaults to
``width * len(format)``.
"""
super(ImageData, self).__init__(width, height)
self._current_format = self._desired_format = format.upper()
self._current_data = data
if not pitch:
pitch = width * len(format)
self._current_pitch = self.pitch = pitch
self.mipmap_images = []
def __getstate__(self):
return {
'width': self.width,
'height': self.height,
'_current_data': self.get_data(self._current_format, self._current_pitch),
'_current_format': self._current_format,
'_desired_format': self._desired_format,
'_current_pitch': self._current_pitch,
'pitch': self.pitch,
'mipmap_images': self.mipmap_images
}
def get_image_data(self):
return self
def _set_format(self, fmt):
self._desired_format = fmt.upper()
self._current_texture = None
@property
def format(self):
"""Format string of the data. Read-write.
:type: str
"""
return self._desired_format
@format.setter
def format(self, fmt):
self._set_format(fmt)
def _get_data(self):
if self._current_pitch != self.pitch or \
self._current_format != self.format:
self._current_data = self._convert(self.format, self.pitch)
self._current_format = self.format
self._current_pitch = self.pitch
self._ensure_string_data()
return self._current_data
def _set_data(self, data):
self._current_data = data
self._current_format = self.format
self._current_pitch = self.pitch
self._current_texture = None
self._current_mipmapped_texture = None
@property
def data(self):
"""The byte data of the image. Read-write.
:deprecated: Use `get_data` and `set_data`.
:type: sequence of bytes, or str
"""
return self._get_data()
@data.setter
def data(self, data):
self._set_data(data)
def get_data(self, format, pitch):
"""Get the byte data of the image.
:Parameters:
`format` : str
Format string of the return data.
`pitch` : int
Number of bytes per row. Negative values indicate a
top-to-bottom arrangement.
.. versionadded:: 1.1
:rtype: sequence of bytes, or str
"""
if format == self._current_format and pitch == self._current_pitch:
return self._current_data
return self._convert(format, pitch)
def set_data(self, format, pitch, data):
"""Set the byte data of the image.
:Parameters:
`format` : str
Format string of the return data.
`pitch` : int
Number of bytes per row. Negative values indicate a
top-to-bottom arrangement.
`data` : str or sequence of bytes
Image data.
.. versionadded:: 1.1
"""
self._current_format = format
self._current_pitch = pitch
self._current_data = data
self._current_texture = None
self._current_mipmapped_texture = None
def set_mipmap_image(self, level, image):
"""Set a mipmap image for a particular level.
The mipmap image will be applied to textures obtained via
`get_mipmapped_texture`.
:Parameters:
`level` : int
Mipmap level to set image at, must be >= 1.
`image` : AbstractImage
Image to set. Must have correct dimensions for that mipmap
level (i.e., width >> level, height >> level)
"""
if level == 0:
raise ImageException(
'Cannot set mipmap image at level 0 (it is this image)')
if not _is_pow2(self.width) or not _is_pow2(self.height):
raise ImageException(
'Image dimensions must be powers of 2 to use mipmaps.')
# Check dimensions of mipmap
width, height = self.width, self.height
for i in range(level):
width >>= 1
height >>= 1
if width != image.width or height != image.height:
raise ImageException(
'Mipmap image has wrong dimensions for level %d' % level)
# Extend mipmap_images list to required level
self.mipmap_images += [None] * (level - len(self.mipmap_images))
self.mipmap_images[level - 1] = image
def create_texture(self, cls, rectangle=False, force_rectangle=False):
"""Create a texture containing this image.
If the image's dimensions are not powers of 2, a TextureRegion of
a larger Texture will be returned that matches the dimensions of this
image.
:Parameters:
`cls` : class (subclass of Texture)
Class to construct.
`rectangle` : bool
``True`` if a rectangle can be created; see
`AbstractImage.get_texture`.
.. versionadded:: 1.1
`force_rectangle` : bool
``True`` if a rectangle must be created; see
`AbstractImage.get_texture`.
.. versionadded:: 1.1.4
:rtype: cls or cls.region_class
"""
internalformat = self._get_internalformat(self.format)
texture = cls.create(self.width, self.height, internalformat,
rectangle, force_rectangle)
if self.anchor_x or self.anchor_y:
texture.anchor_x = self.anchor_x
texture.anchor_y = self.anchor_y
self.blit_to_texture(texture.target, texture.level,
self.anchor_x, self.anchor_y, 0, None)
return texture
def get_texture(self, rectangle=False, force_rectangle=False):
if (not self._current_texture or
(not self._current_texture._is_rectangle and force_rectangle)):
self._current_texture = self.create_texture(Texture,
rectangle,
force_rectangle)
return self._current_texture
def get_mipmapped_texture(self):
"""Return a Texture with mipmaps.
If :py:class:`~pyglet.image.set_mipmap_Image` has been called with at least one image, the set
of images defined will be used. Otherwise, mipmaps will be
automatically generated.
The texture dimensions must be powers of 2 to use mipmaps.
:rtype: :py:class:`~pyglet.image.Texture`
.. versionadded:: 1.1
"""
if self._current_mipmap_texture:
return self._current_mipmap_texture
if not _is_pow2(self.width) or not _is_pow2(self.height):
raise ImageException(
'Image dimensions must be powers of 2 to use mipmaps.')
texture = Texture.create_for_size(GL_TEXTURE_2D, self.width, self.height)
if self.anchor_x or self.anchor_y:
texture.anchor_x = self.anchor_x
texture.anchor_y = self.anchor_y
internalformat = self._get_internalformat(self.format)
glBindTexture(texture.target, texture.id)
glTexParameteri(texture.target, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR)
if self.mipmap_images:
self.blit_to_texture(texture.target, texture.level,
self.anchor_x, self.anchor_y, 0, internalformat)
level = 0
for image in self.mipmap_images:
level += 1
if image:
image.blit_to_texture(texture.target, level,
self.anchor_x, self.anchor_y, 0, internalformat)
# TODO: should set base and max mipmap level if some mipmaps
# are missing.
elif gl_info.have_version(1, 4):
glTexParameteri(texture.target, GL_GENERATE_MIPMAP, GL_TRUE)
self.blit_to_texture(texture.target, texture.level,
self.anchor_x, self.anchor_y, 0, internalformat)
else:
raise NotImplementedError('TODO: gluBuild2DMipmaps')
self._current_mipmap_texture = texture
return texture
def get_region(self, x, y, width, height):
"""Retrieve a rectangular region of this image data.
:Parameters:
`x` : int
Left edge of region.
`y` : int
Bottom edge of region.
`width` : int
Width of region.
`height` : int
Height of region.
:rtype: ImageDataRegion
"""
return ImageDataRegion(x, y, width, height, self)
def blit(self, x, y, z=0, width=None, height=None):
self.get_texture().blit(x, y, z, width, height)
def blit_to_texture(self, target, level, x, y, z, internalformat=None):
"""Draw this image to to the currently bound texture at `target`.
This image's anchor point will be aligned to the given `x` and `y`
coordinates. If the currently bound texture is a 3D texture, the `z`
parameter gives the image slice to blit into.
If `internalformat` is specified, glTexImage is used to initialise
the texture; otherwise, glTexSubImage is used to update a region.
"""
x -= self.anchor_x
y -= self.anchor_y
data_format = self.format
data_pitch = abs(self._current_pitch)
# Determine pixel format from format string
matrix = None
format, type = self._get_gl_format_and_type(data_format)
if format is None:
if (len(data_format) in (3, 4) and
gl_info.have_extension('GL_ARB_imaging')):
# Construct a color matrix to convert to GL_RGBA
def component_column(component):
try:
pos = 'RGBA'.index(component)
return [0] * pos + [1] + [0] * (3 - pos)
except ValueError:
return [0, 0, 0, 0]
# pad to avoid index exceptions
lookup_format = data_format + 'XXX'
matrix = (component_column(lookup_format[0]) +
component_column(lookup_format[1]) +
component_column(lookup_format[2]) +
component_column(lookup_format[3]))
format = {
3: GL_RGB,
4: GL_RGBA}.get(len(data_format))
type = GL_UNSIGNED_BYTE
glMatrixMode(GL_COLOR)
glPushMatrix()
glLoadMatrixf((GLfloat * 16)(*matrix))
else:
# Need to convert data to a standard form
data_format = {
1: 'L',
2: 'LA',
3: 'RGB',
4: 'RGBA'}.get(len(data_format))
format, type = self._get_gl_format_and_type(data_format)
# Workaround: don't use GL_UNPACK_ROW_LENGTH
if gl.current_context._workaround_unpack_row_length:
data_pitch = self.width * len(data_format)
# Get data in required format (hopefully will be the same format it's
# already in, unless that's an obscure format, upside-down or the
# driver is old).
data = self._convert(data_format, data_pitch)
if data_pitch & 0x1:
alignment = 1
elif data_pitch & 0x2:
alignment = 2
else:
alignment = 4
row_length = data_pitch // len(data_format)
glPushClientAttrib(GL_CLIENT_PIXEL_STORE_BIT)
glPixelStorei(GL_UNPACK_ALIGNMENT, alignment)
glPixelStorei(GL_UNPACK_ROW_LENGTH, row_length)
self._apply_region_unpack()
if target == GL_TEXTURE_3D:
assert not internalformat
glTexSubImage3D(target, level,
x, y, z,
self.width, self.height, 1,
format, type,
data)
elif internalformat:
glTexImage2D(target, level,
internalformat,
self.width, self.height,
0,
format, type,
data)
else:
glTexSubImage2D(target, level,
x, y,
self.width, self.height,
format, type,
data)
glPopClientAttrib()
if matrix:
glPopMatrix()
glMatrixMode(GL_MODELVIEW)
# Flush image upload before data get GC'd.
glFlush()
def _apply_region_unpack(self):
pass
def _convert(self, format, pitch):
"""Return data in the desired format; does not alter this instance's
current format or pitch.
"""
if format == self._current_format and pitch == self._current_pitch:
if type(self._current_data) is str:
return asbytes(self._current_data)
return self._current_data
self._ensure_string_data()
data = self._current_data
current_pitch = self._current_pitch
current_format = self._current_format
sign_pitch = current_pitch // abs(current_pitch)
if format != self._current_format:
# Create replacement string, e.g. r'\4\1\2\3' to convert RGBA to
# ARGB
repl = asbytes('')
for c in format:
try:
idx = current_format.index(c) + 1
except ValueError:
idx = 1
repl += asbytes(r'\%d' % idx)
if len(current_format) == 1:
swap_pattern = self._swap1_pattern
elif len(current_format) == 2:
swap_pattern = self._swap2_pattern
elif len(current_format) == 3:
swap_pattern = self._swap3_pattern
elif len(current_format) == 4:
swap_pattern = self._swap4_pattern
else:
raise ImageException(
'Current image format is wider than 32 bits.')
packed_pitch = self.width * len(current_format)
if abs(self._current_pitch) != packed_pitch:
# Pitch is wider than pixel data, need to go row-by-row.
rows = re.findall(
asbytes('.') * abs(self._current_pitch), data, re.DOTALL)
rows = [swap_pattern.sub(repl, r[:packed_pitch]) for r in rows]
data = asbytes('').join(rows)
else:
# Rows are tightly packed, apply regex over whole image.
data = swap_pattern.sub(repl, data)
# After conversion, rows will always be tightly packed
current_pitch = sign_pitch * (len(format) * self.width)
if pitch != current_pitch:
diff = abs(current_pitch) - abs(pitch)
if diff > 0:
# New pitch is shorter than old pitch, chop bytes off each row
pattern = re.compile(
asbytes('(%s)%s' % ('.' * abs(pitch), '.' * diff)), re.DOTALL)
data = pattern.sub(asbytes(r'\1'), data)
elif diff < 0:
# New pitch is longer than old pitch, add '0' bytes to each row
pattern = re.compile(
asbytes('(%s)' % ('.' * abs(current_pitch))), re.DOTALL)
pad = '.' * -diff
data = pattern.sub(asbytes(r'\1%s' % pad), data)
if current_pitch * pitch < 0:
# Pitch differs in sign, swap row order
rows = re.findall(asbytes('.') * abs(pitch), data, re.DOTALL)
rows.reverse()
data = asbytes('').join(rows)
return asbytes(data)
def _ensure_string_data(self):
if type(self._current_data) is not bytes_type:
buf = create_string_buffer(len(self._current_data))
memmove(buf, self._current_data, len(self._current_data))
self._current_data = buf.raw
def _get_gl_format_and_type(self, format):
if format == 'I':
return GL_LUMINANCE, GL_UNSIGNED_BYTE
elif format == 'L':
return GL_LUMINANCE, GL_UNSIGNED_BYTE
elif format == 'LA':
return GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE
elif format == 'R':
return GL_RED, GL_UNSIGNED_BYTE
elif format == 'G':
return GL_GREEN, GL_UNSIGNED_BYTE
elif format == 'B':
return GL_BLUE, GL_UNSIGNED_BYTE
elif format == 'A':
return GL_ALPHA, GL_UNSIGNED_BYTE
elif format == 'RGB':
return GL_RGB, GL_UNSIGNED_BYTE
elif format == 'RGBA':
return GL_RGBA, GL_UNSIGNED_BYTE
elif (format == 'ARGB' and
gl_info.have_extension('GL_EXT_bgra') and
gl_info.have_extension('GL_APPLE_packed_pixels')):
return GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV
elif (format == 'ABGR' and
gl_info.have_extension('GL_EXT_abgr')):
return GL_ABGR_EXT, GL_UNSIGNED_BYTE
elif (format == 'BGR' and
gl_info.have_extension('GL_EXT_bgra')):
return GL_BGR, GL_UNSIGNED_BYTE
elif (format == 'BGRA' and
gl_info.have_extension('GL_EXT_bgra')):
return GL_BGRA, GL_UNSIGNED_BYTE
return None, None
def _get_internalformat(self, format):
if len(format) == 4:
return GL_RGBA
elif len(format) == 3:
return GL_RGB
elif len(format) == 2:
return GL_LUMINANCE_ALPHA
elif format == 'A':
return GL_ALPHA
elif format == 'L':
return GL_LUMINANCE
elif format == 'I':
return GL_INTENSITY
return GL_RGBA
class ImageDataRegion(ImageData):
def __init__(self, x, y, width, height, image_data):
super(ImageDataRegion, self).__init__(width, height,
image_data._current_format, image_data._current_data,
image_data._current_pitch)
self.x = x
self.y = y
def __getstate__(self):
return {
'width': self.width,
'height': self.height,
'_current_data':
self.get_data(self._current_format, self._current_pitch),
'_current_format': self._current_format,
'_desired_format': self._desired_format,
'_current_pitch': self._current_pitch,
'pitch': self.pitch,
'mipmap_images': self.mipmap_images,
'x': self.x,
'y': self.y
}
def _get_data(self):
# Crop the data first
x1 = len(self._current_format) * self.x
x2 = len(self._current_format) * (self.x + self.width)
self._ensure_string_data()
data = self._convert(self._current_format, abs(self._current_pitch))
rows = re.findall(b'.' * abs(self._current_pitch), data, re.DOTALL)
rows = [row[x1:x2] for row in rows[self.y:self.y + self.height]]
self._current_data = b''.join(rows)
self._current_pitch = self.width * len(self._current_format)
self._current_texture = None
self.x = 0
self.y = 0
return super(ImageDataRegion, self)._get_data()
def _set_data(self, data):
self.x = 0
self.y = 0
super(ImageDataRegion, self)._set_data(data)
@property
def data(self):
return self._get_data()
@data.setter
def data(self, data):
self._set_data(data)
def get_data(self, format, pitch):
x1 = len(self._current_format) * self.x
x2 = len(self._current_format) * (self.x + self.width)
self._ensure_string_data()
data = self._convert(self._current_format, abs(self._current_pitch))
rows = re.findall(asbytes('.') * abs(self._current_pitch), data,
re.DOTALL)
rows = [row[x1:x2] for row in rows[self.y:self.y + self.height]]
self._current_data = asbytes('').join(rows)
self._current_pitch = self.width * len(self._current_format)
self._current_texture = None
self.x = 0
self.y = 0
return super(ImageDataRegion, self).get_data(format, pitch)
def _apply_region_unpack(self):
glPixelStorei(GL_UNPACK_SKIP_PIXELS, self.x)
glPixelStorei(GL_UNPACK_SKIP_ROWS, self.y)
def _ensure_string_data(self):
super(ImageDataRegion, self)._ensure_string_data()
def get_region(self, x, y, width, height):
x += self.x
y += self.y
return super(ImageDataRegion, self).get_region(x, y, width, height)
class CompressedImageData(AbstractImage):
"""Image representing some compressed data suitable for direct uploading
to driver.
"""
_current_texture = None
_current_mipmapped_texture = None
def __init__(self, width, height, gl_format, data,
extension=None, decoder=None):
"""Construct a CompressedImageData with the given compressed data.
:Parameters:
`width` : int
Width of image
`height` : int
Height of image
`gl_format` : int
GL constant giving format of compressed data; for example,
``GL_COMPRESSED_RGBA_S3TC_DXT5_EXT``.
`data` : sequence
String or array/list of bytes giving compressed image data.
`extension` : str or None
If specified, gives the name of a GL extension to check for
before creating a texture.
`decoder` : function(data, width, height) -> AbstractImage
A function to decode the compressed data, to be used if the
required extension is not present.
"""
if not _is_pow2(width) or not _is_pow2(height):
raise ImageException('Dimensions of %r must be powers of 2' % self)
super(CompressedImageData, self).__init__(width, height)
self.data = data
self.gl_format = gl_format
self.extension = extension
self.decoder = decoder
self.mipmap_data = []
def set_mipmap_data(self, level, data):
"""Set data for a mipmap level.
Supplied data gives a compressed image for the given mipmap level.
The image must be of the correct dimensions for the level
(i.e., width >> level, height >> level); but this is not checked. If
any mipmap levels are specified, they are used; otherwise, mipmaps for
`mipmapped_texture` are generated automatically.
:Parameters:
`level` : int
Level of mipmap image to set.
`data` : sequence
String or array/list of bytes giving compressed image data.
Data must be in same format as specified in constructor.
"""
# Extend mipmap_data list to required level
self.mipmap_data += [None] * (level - len(self.mipmap_data))
self.mipmap_data[level - 1] = data
def _have_extension(self):
return self.extension is None or gl_info.have_extension(self.extension)
def _verify_driver_supported(self):
"""Assert that the extension required for this image data is
supported.
Raises `ImageException` if not.
"""
if not self._have_extension():
raise ImageException('%s is required to decode %r' % \
(self.extension, self))
def get_texture(self, rectangle=False, force_rectangle=False):
if force_rectangle:
raise ImageException(
'Compressed texture rectangles not supported')
if self._current_texture:
return self._current_texture
texture = Texture.create_for_size(
GL_TEXTURE_2D, self.width, self.height)
if self.anchor_x or self.anchor_y:
texture.anchor_x = self.anchor_x
texture.anchor_y = self.anchor_y
glBindTexture(texture.target, texture.id)
glTexParameteri(texture.target, GL_TEXTURE_MIN_FILTER, texture.min_filter)
glTexParameteri(texture.target, GL_TEXTURE_MAG_FILTER, texture.mag_filter)
if self._have_extension():
glCompressedTexImage2DARB(texture.target, texture.level,
self.gl_format,
self.width, self.height, 0,
len(self.data), self.data)
else:
image = self.decoder(self.data, self.width, self.height)
texture = image.get_texture()
assert texture.width == self.width
assert texture.height == self.height
glFlush()
self._current_texture = texture
return texture
def get_mipmapped_texture(self):
if self._current_mipmap_texture:
return self._current_mipmap_texture
if not self._have_extension():
# TODO mip-mapped software decoded compressed textures. For now,
# just return a non-mipmapped texture.
return self.get_texture()
texture = Texture.create_for_size(
GL_TEXTURE_2D, self.width, self.height)
if self.anchor_x or self.anchor_y:
texture.anchor_x = self.anchor_x
texture.anchor_y = self.anchor_y
glBindTexture(texture.target, texture.id)
glTexParameteri(texture.target, GL_TEXTURE_MIN_FILTER,
GL_LINEAR_MIPMAP_LINEAR)
if not self.mipmap_data:
if not gl_info.have_version(1, 4):
raise ImageException(
'Require GL 1.4 to generate mipmaps for compressed textures')
glTexParameteri(texture.target, GL_GENERATE_MIPMAP, GL_TRUE)
glCompressedTexImage2DARB(texture.target, texture.level,
self.gl_format,
self.width, self.height, 0,
len(self.data), self.data)
width, height = self.width, self.height
level = 0
for data in self.mipmap_data:
width >>= 1
height >>= 1
level += 1
glCompressedTexImage2DARB(texture.target, level,
self.gl_format,
width, height, 0,
len(data), data)
glFlush()
self._current_mipmap_texture = texture
return texture
def blit_to_texture(self, target, level, x, y, z):
self._verify_driver_supported()
if target == GL_TEXTURE_3D:
glCompressedTexSubImage3DARB(target, level,
x - self.anchor_x, y - self.anchor_y, z,
self.width, self.height, 1,
self.gl_format,
len(self.data), self.data)
else:
glCompressedTexSubImage2DARB(target, level,
x - self.anchor_x, y - self.anchor_y,
self.width, self.height,
self.gl_format,
len(self.data), self.data)
def _nearest_pow2(v):
# From http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
# Credit: Sean Anderson
v -= 1
v |= v >> 1
v |= v >> 2
v |= v >> 4
v |= v >> 8
v |= v >> 16
return v + 1
def _is_pow2(v):
# http://graphics.stanford.edu/~seander/bithacks.html#DetermineIfPowerOf2
return (v & (v - 1)) == 0
class Texture(AbstractImage):
"""An image loaded into video memory that can be efficiently drawn
to the framebuffer.
Typically you will get an instance of Texture by accessing the `texture`
member of any other AbstractImage.
:Ivariables:
`region_class` : class (subclass of TextureRegion)
Class to use when constructing regions of this texture.
`tex_coords` : tuple
12-tuple of float, named (u1, v1, r1, u2, v2, r2, ...). u, v, r
give the 3D texture coordinates for vertices 1-4. The vertices
are specified in the order bottom-left, bottom-right, top-right
and top-left.
`target` : int
The GL texture target (e.g., ``GL_TEXTURE_2D``).
`level` : int
The mipmap level of this texture.
"""
region_class = None # Set to TextureRegion after it's defined
tex_coords = (0., 0., 0., 1., 0., 0., 1., 1., 0., 0., 1., 0.)
tex_coords_order = (0, 1, 2, 3)
level = 0
images = 1
x = y = z = 0
def __init__(self, width, height, target, id):
super(Texture, self).__init__(width, height)
self.target = target
self.id = id
self._context = gl.current_context
def delete(self):
"""Delete the texture from video memory.
:deprecated: Textures are automatically released during object
finalization.
"""
warnings.warn(
'Texture.delete() is deprecated; textures are '
'released through GC now')
self._context.delete_texture(self.id)
self.id = 0
def __del__(self):
try:
self._context.delete_texture(self.id)
except:
pass
@classmethod
def create(cls, width, height, internalformat=GL_RGBA,
rectangle=False, force_rectangle=False, min_filter=GL_LINEAR, mag_filter=GL_LINEAR):
"""Create an empty Texture.
If `rectangle` is ``False`` or the appropriate driver extensions are
not available, a larger texture than requested will be created, and
a :py:class:`~pyglet.image.TextureRegion` corresponding to the requested size will be
returned.
:Parameters:
`width` : int
Width of the texture.
`height` : int
Height of the texture.
`internalformat` : int
GL constant giving the internal format of the texture; for
example, ``GL_RGBA``.
`rectangle` : bool
``True`` if a rectangular texture is permitted. See
`AbstractImage.get_texture`.
`force_rectangle` : bool
``True`` if a rectangular texture is required. See
`AbstractImage.get_texture`.
.. versionadded:: 1.1.4.
`min_filter` : int
The minifaction filter used for this texture, commonly ``GL_LINEAR`` or ``GL_NEAREST``
`mag_filter` : int
The magnification filter used for this texture, commonly ``GL_LINEAR`` or ``GL_NEAREST``
:rtype: :py:class:`~pyglet.image.Texture`
.. versionadded:: 1.1
"""
target = GL_TEXTURE_2D
if rectangle or force_rectangle:
if not force_rectangle and _is_pow2(width) and _is_pow2(height):
rectangle = False
elif gl_info.have_extension('GL_ARB_texture_rectangle'):
target = GL_TEXTURE_RECTANGLE_ARB
rectangle = True
elif gl_info.have_extension('GL_NV_texture_rectangle'):
target = GL_TEXTURE_RECTANGLE_NV
rectangle = True
else:
rectangle = False
if force_rectangle and not rectangle:
raise ImageException('Texture rectangle extensions not available')
if rectangle:
texture_width = width
texture_height = height
else:
texture_width = _nearest_pow2(width)
texture_height = _nearest_pow2(height)
id = GLuint()
glGenTextures(1, byref(id))
glBindTexture(target, id.value)
glTexParameteri(target, GL_TEXTURE_MIN_FILTER, min_filter)
glTexParameteri(target, GL_TEXTURE_MAG_FILTER, mag_filter)
blank = (GLubyte * (texture_width * texture_height * 4))()
glTexImage2D(target, 0,
internalformat,
texture_width, texture_height,
0,
GL_RGBA, GL_UNSIGNED_BYTE,
blank)
texture = cls(texture_width, texture_height, target, id.value)
texture.min_filter = min_filter
texture.mag_filter = mag_filter
if rectangle:
texture._is_rectangle = True
texture.tex_coords = (0., 0., 0.,
width, 0., 0.,
width, height, 0.,
0., height, 0.)
glFlush()
if texture_width == width and texture_height == height:
return texture
return texture.get_region(0, 0, width, height)
@classmethod
def create_for_size(cls, target, min_width, min_height,
internalformat=None, min_filter=GL_LINEAR, mag_filter=GL_LINEAR):
"""Create a Texture with dimensions at least min_width, min_height.
On return, the texture will be bound.
:Parameters:
`target` : int
GL constant giving texture target to use, typically
``GL_TEXTURE_2D``.
`min_width` : int
Minimum width of texture (may be increased to create a power
of 2).
`min_height` : int
Minimum height of texture (may be increased to create a power
of 2).
`internalformat` : int
GL constant giving internal format of texture; for example,
``GL_RGBA``. If unspecified, the texture will not be
initialised (only the texture name will be created on the
instance). If specified, the image will be initialised
to this format with zero'd data.
`min_filter` : int
The minifaction filter used for this texture, commonly ``GL_LINEAR`` or ``GL_NEAREST``
`mag_filter` : int
The magnification filter used for this texture, commonly ``GL_LINEAR`` or ``GL_NEAREST``
:rtype: :py:class:`~pyglet.image.Texture`
"""
if target not in (GL_TEXTURE_RECTANGLE_NV, GL_TEXTURE_RECTANGLE_ARB):
width = _nearest_pow2(min_width)
height = _nearest_pow2(min_height)
tex_coords = cls.tex_coords
else:
width = min_width
height = min_height
tex_coords = (0., 0., 0.,
width, 0., 0.,
width, height, 0.,
0., height, 0.)
id = GLuint()
glGenTextures(1, byref(id))
glBindTexture(target, id.value)
glTexParameteri(target, GL_TEXTURE_MIN_FILTER, min_filter)
glTexParameteri(target, GL_TEXTURE_MAG_FILTER, mag_filter)
if internalformat is not None:
blank = (GLubyte * (width * height * 4))()
glTexImage2D(target, 0,
internalformat,
width, height,
0,
GL_RGBA, GL_UNSIGNED_BYTE,
blank)
glFlush()
texture = cls(width, height, target, id.value)
texture.min_filter = min_filter
texture.mag_filter = mag_filter
texture.tex_coords = tex_coords
return texture
def get_image_data(self, z=0):
"""Get the image data of this texture.
Changes to the returned instance will not be reflected in this
texture.
:Parameters:
`z` : int
For 3D textures, the image slice to retrieve.
:rtype: :py:class:`~pyglet.image.ImageData`
"""
glBindTexture(self.target, self.id)
# Always extract complete RGBA data. Could check internalformat
# to only extract used channels. XXX
format = 'RGBA'
gl_format = GL_RGBA
glPushClientAttrib(GL_CLIENT_PIXEL_STORE_BIT)
glPixelStorei(GL_PACK_ALIGNMENT, 1)
buffer = \
(GLubyte * (self.width * self.height * self.images * len(format)))()
glGetTexImage(self.target, self.level,
gl_format, GL_UNSIGNED_BYTE, buffer)
glPopClientAttrib()
data = ImageData(self.width, self.height, format, buffer)
if self.images > 1:
data = data.get_region(0, z * self.height, self.width, self.height)
return data
@property
def image_data(self):
"""An ImageData view of this texture.
Changes to the returned instance will not be reflected in this
texture. If the texture is a 3D texture, the first image will be
returned. See also :py:meth:`~pyglet.image.ImageData.get_image_data`. Read-only.
:deprecated: Use :py:meth:`~pyglet.image.ImageData.get_image_data`.
:type: :py:class:`~pyglet.image.ImageData`
"""
return self.get_image_data()
def get_texture(self, rectangle=False, force_rectangle=False):
if force_rectangle and not self._is_rectangle:
raise ImageException('Texture is not a rectangle.')
return self
# no implementation of blit_to_texture yet (could use aux buffer)
def blit(self, x, y, z=0, width=None, height=None):
t = self.tex_coords
x1 = x - self.anchor_x
y1 = y - self.anchor_y
x2 = x1 + (width is None and self.width or width)
y2 = y1 + (height is None and self.height or height)
array = (GLfloat * 32)(
t[0], t[1], t[2], 1.,
x1, y1, z, 1.,
t[3], t[4], t[5], 1.,
x2, y1, z, 1.,
t[6], t[7], t[8], 1.,
x2, y2, z, 1.,
t[9], t[10], t[11], 1.,
x1, y2, z, 1.)
glPushAttrib(GL_ENABLE_BIT)
glEnable(self.target)
glBindTexture(self.target, self.id)
glPushClientAttrib(GL_CLIENT_VERTEX_ARRAY_BIT)
glInterleavedArrays(GL_T4F_V4F, 0, array)
glDrawArrays(GL_QUADS, 0, 4)
glPopClientAttrib()
glPopAttrib()
def blit_into(self, source, x, y, z):
glBindTexture(self.target, self.id)
source.blit_to_texture(self.target, self.level, x, y, z)
def get_region(self, x, y, width, height):
return self.region_class(x, y, 0, width, height, self)
def get_transform(self, flip_x=False, flip_y=False, rotate=0):
"""Create a copy of this image applying a simple transformation.
The transformation is applied to the texture coordinates only;
:py:meth:`~pyglet.image.ImageData.get_image_data` will return the untransformed data. The
transformation is applied around the anchor point.
:Parameters:
`flip_x` : bool
If True, the returned image will be flipped horizontally.
`flip_y` : bool
If True, the returned image will be flipped vertically.
`rotate` : int
Degrees of clockwise rotation of the returned image. Only
90-degree increments are supported.
:rtype: :py:class:`~pyglet.image.TextureRegion`
"""
transform = self.get_region(0, 0, self.width, self.height)
bl, br, tr, tl = 0, 1, 2, 3
transform.anchor_x = self.anchor_x
transform.anchor_y = self.anchor_y
if flip_x:
bl, br, tl, tr = br, bl, tr, tl
transform.anchor_x = self.width - self.anchor_x
if flip_y:
bl, br, tl, tr = tl, tr, bl, br
transform.anchor_y = self.height - self.anchor_y
rotate %= 360
if rotate < 0:
rotate += 360
if rotate == 0:
pass
elif rotate == 90:
bl, br, tr, tl = br, tr, tl, bl
transform.anchor_x, transform.anchor_y = \
transform.anchor_y, \
transform.width - transform.anchor_x
elif rotate == 180:
bl, br, tr, tl = tr, tl, bl, br
transform.anchor_x = transform.width - transform.anchor_x
transform.anchor_y = transform.height - transform.anchor_y
elif rotate == 270:
bl, br, tr, tl = tl, bl, br, tr
transform.anchor_x, transform.anchor_y = \
transform.height - transform.anchor_y, \
transform.anchor_x
else:
assert False, 'Only 90 degree rotations are supported.'
if rotate in (90, 270):
transform.width, transform.height = \
transform.height, transform.width
transform._set_tex_coords_order(bl, br, tr, tl)
return transform
def _set_tex_coords_order(self, bl, br, tr, tl):
tex_coords = (self.tex_coords[:3],
self.tex_coords[3:6],
self.tex_coords[6:9],
self.tex_coords[9:])
self.tex_coords = \
tex_coords[bl] + tex_coords[br] + tex_coords[tr] + tex_coords[tl]
order = self.tex_coords_order
self.tex_coords_order = \
(order[bl], order[br], order[tr], order[tl])
class TextureRegion(Texture):
"""A rectangular region of a texture, presented as if it were
a separate texture.
"""
def __init__(self, x, y, z, width, height, owner):
super(TextureRegion, self).__init__(
width, height, owner.target, owner.id)
self.x = x
self.y = y
self.z = z
self.owner = owner
owner_u1 = owner.tex_coords[0]
owner_v1 = owner.tex_coords[1]
owner_u2 = owner.tex_coords[3]
owner_v2 = owner.tex_coords[7]
scale_u = owner_u2 - owner_u1
scale_v = owner_v2 - owner_v1
u1 = x / owner.width * scale_u + owner_u1
v1 = y / owner.height * scale_v + owner_v1
u2 = (x + width) / owner.width * scale_u + owner_u1
v2 = (y + height) / owner.height * scale_v + owner_v1
r = z / owner.images + owner.tex_coords[2]
self.tex_coords = (u1, v1, r, u2, v1, r, u2, v2, r, u1, v2, r)
def get_image_data(self):
image_data = self.owner.get_image_data(self.z)
return image_data.get_region(self.x, self.y, self.width, self.height)
def get_region(self, x, y, width, height):
x += self.x
y += self.y
region = self.region_class(x, y, self.z, width, height, self.owner)
region._set_tex_coords_order(*self.tex_coords_order)
return region
def blit_into(self, source, x, y, z):
self.owner.blit_into(source, x + self.x, y + self.y, z + self.z)
def __del__(self):
# only the owner Texture should handle deletion
pass
Texture.region_class = TextureRegion
class Texture3D(Texture, UniformTextureSequence):
"""A texture with more than one image slice.
Use `create_for_images` or `create_for_image_grid` classmethod to
construct.
"""
item_width = 0
item_height = 0
items = ()
@classmethod
def create_for_images(cls, images, internalformat=GL_RGBA):
item_width = images[0].width
item_height = images[0].height
for image in images:
if image.width != item_width or image.height != item_height:
raise ImageException('Images do not have same dimensions.')
depth = len(images)
if not gl_info.have_version(2, 0):
depth = _nearest_pow2(depth)
texture = cls.create_for_size(GL_TEXTURE_3D, item_width, item_height)
if images[0].anchor_x or images[0].anchor_y:
texture.anchor_x = images[0].anchor_x
texture.anchor_y = images[0].anchor_y
texture.images = depth
blank = (GLubyte * (texture.width * texture.height * texture.images))()
glBindTexture(texture.target, texture.id)
glTexImage3D(texture.target, texture.level,
internalformat,
texture.width, texture.height, texture.images, 0,
GL_ALPHA, GL_UNSIGNED_BYTE,
blank)
items = []
for i, image in enumerate(images):
item = cls.region_class(0, 0, i, item_width, item_height, texture)
items.append(item)
image.blit_to_texture(texture.target, texture.level,
image.anchor_x, image.anchor_y, i)
glFlush()
texture.items = items
texture.item_width = item_width
texture.item_height = item_height
return texture
@classmethod
def create_for_image_grid(cls, grid, internalformat=GL_RGBA):
return cls.create_for_images(grid[:], internalformat)
def __len__(self):
return len(self.items)
def __getitem__(self, index):
return self.items[index]
def __setitem__(self, index, value):
if type(index) is slice:
for item, image in zip(self[index], value):
image.blit_to_texture(self.target, self.level,
image.anchor_x, image.anchor_y, item.z)
else:
value.blit_to_texture(self.target, self.level,
value.anchor_x, value.anchor_y, self[index].z)
def __iter__(self):
return iter(self.items)
class TileableTexture(Texture):
"""A texture that can be tiled efficiently.
Use :py:class:`~pyglet.image.create_for_Image` classmethod to construct.
"""
def __init__(self, width, height, target, id):
if not _is_pow2(width) or not _is_pow2(height):
raise ImageException(
'TileableTexture requires dimensions that are powers of 2')
super(TileableTexture, self).__init__(width, height, target, id)
def get_region(self, x, y, width, height):
raise ImageException('Cannot get region of %r' % self)
def blit_tiled(self, x, y, z, width, height):
"""Blit this texture tiled over the given area.
The image will be tiled with the bottom-left corner of the destination
rectangle aligned with the anchor point of this texture.
"""
u1 = self.anchor_x / self.width
v1 = self.anchor_y / self.height
u2 = u1 + width / self.width
v2 = v1 + height / self.height
w, h = width, height
t = self.tex_coords
array = (GLfloat * 32)(
u1, v1, t[2], 1.,
x, y, z, 1.,
u2, v1, t[5], 1.,
x + w, y, z, 1.,
u2, v2, t[8], 1.,
x + w, y + h, z, 1.,
u1, v2, t[11], 1.,
x, y + h, z, 1.)
glPushAttrib(GL_ENABLE_BIT)
glEnable(self.target)
glBindTexture(self.target, self.id)
glPushClientAttrib(GL_CLIENT_VERTEX_ARRAY_BIT)
glInterleavedArrays(GL_T4F_V4F, 0, array)
glDrawArrays(GL_QUADS, 0, 4)
glPopClientAttrib()
glPopAttrib()
@classmethod
def create_for_image(cls, image):
if not _is_pow2(image.width) or not _is_pow2(image.height):
# Potentially unnecessary conversion if a GL format exists.
image = image.get_image_data()
texture_width = _nearest_pow2(image.width)
texture_height = _nearest_pow2(image.height)
newdata = c_buffer(texture_width * texture_height * 4)
gluScaleImage(GL_RGBA,
image.width, image.height,
GL_UNSIGNED_BYTE,
image.get_data('RGBA', image.width * 4),
texture_width,
texture_height,
GL_UNSIGNED_BYTE,
newdata)
image = ImageData(texture_width, texture_height, 'RGBA',
newdata)
image = image.get_image_data()
return image.create_texture(cls)
class DepthTexture(Texture):
"""A texture with depth samples (typically 24-bit)."""
def blit_into(self, source, x, y, z):
glBindTexture(self.target, self.id)
source.blit_to_texture(self.level, x, y, z)
class BufferManager(object):
"""Manages the set of framebuffers for a context.
Use :py:func:`~pyglet.image.get_buffer_manager` to obtain the instance of this class for the
current context.
"""
def __init__(self):
self.color_buffer = None
self.depth_buffer = None
aux_buffers = GLint()
glGetIntegerv(GL_AUX_BUFFERS, byref(aux_buffers))
self.free_aux_buffers = [GL_AUX0,
GL_AUX1,
GL_AUX2,
GL_AUX3][:aux_buffers.value]
stencil_bits = GLint()
glGetIntegerv(GL_STENCIL_BITS, byref(stencil_bits))
self.free_stencil_bits = list(range(stencil_bits.value))
self.refs = []
def get_viewport(self):
"""Get the current OpenGL viewport dimensions.
:rtype: 4-tuple of float.
:return: Left, top, right and bottom dimensions.
"""
viewport = (GLint * 4)()
glGetIntegerv(GL_VIEWPORT, viewport)
return viewport
def get_color_buffer(self):
"""Get the color buffer.
:rtype: :py:class:`~pyglet.image.ColorBufferImage`
"""
viewport = self.get_viewport()
viewport_width = viewport[2]
viewport_height = viewport[3]
if (not self.color_buffer or
viewport_width != self.color_buffer.width or
viewport_height != self.color_buffer.height):
self.color_buffer = ColorBufferImage(*viewport)
return self.color_buffer
def get_aux_buffer(self):
"""Get a free auxiliary buffer.
If not aux buffers are available, `ImageException` is raised. Buffers
are released when they are garbage collected.
:rtype: :py:class:`~pyglet.image.ColorBufferImage`
"""
if not self.free_aux_buffers:
raise ImageException('No free aux buffer is available.')
gl_buffer = self.free_aux_buffers.pop(0)
viewport = self.get_viewport()
buffer = ColorBufferImage(*viewport)
buffer.gl_buffer = gl_buffer
def release_buffer(ref, self=self):
self.free_aux_buffers.insert(0, gl_buffer)
self.refs.append(weakref.ref(buffer, release_buffer))
return buffer
def get_depth_buffer(self):
"""Get the depth buffer.
:rtype: :py:class:`~pyglet.image.DepthBufferImage`
"""
viewport = self.get_viewport()
viewport_width = viewport[2]
viewport_height = viewport[3]
if (not self.depth_buffer or
viewport_width != self.depth_buffer.width or
viewport_height != self.depth_buffer.height):
self.depth_buffer = DepthBufferImage(*viewport)
return self.depth_buffer
def get_buffer_mask(self):
"""Get a free bitmask buffer.
A bitmask buffer is a buffer referencing a single bit in the stencil
buffer. If no bits are free, `ImageException` is raised. Bits are
released when the bitmask buffer is garbage collected.
:rtype: :py:class:`~pyglet.image.BufferImageMask`
"""
if not self.free_stencil_bits:
raise ImageException('No free stencil bits are available.')
stencil_bit = self.free_stencil_bits.pop(0)
x, y, width, height = self.get_viewport()
buffer = BufferImageMask(x, y, width, height)
buffer.stencil_bit = stencil_bit
def release_buffer(ref, self=self):
self.free_stencil_bits.insert(0, stencil_bit)
self.refs.append(weakref.ref(buffer, release_buffer))
return buffer
def get_buffer_manager():
"""Get the buffer manager for the current OpenGL context.
:rtype: :py:class:`~pyglet.image.BufferManager`
"""
context = gl.current_context
if not hasattr(context, 'image_buffer_manager'):
context.image_buffer_manager = BufferManager()
return context.image_buffer_manager
# XXX BufferImage could be generalised to support EXT_framebuffer_object's
# renderbuffer.
class BufferImage(AbstractImage):
"""An abstract framebuffer.
"""
#: The OpenGL read and write target for this buffer.
gl_buffer = GL_BACK
#: The OpenGL format constant for image data.
gl_format = 0
#: The format string used for image data.
format = ''
owner = None
# TODO: enable methods
def __init__(self, x, y, width, height):
self.x = x
self.y = y
self.width = width
self.height = height
def get_image_data(self):
buffer = (GLubyte * (len(self.format) * self.width * self.height))()
x = self.x
y = self.y
if self.owner:
x += self.owner.x
y += self.owner.y
glReadBuffer(self.gl_buffer)
glPushClientAttrib(GL_CLIENT_PIXEL_STORE_BIT)
glPixelStorei(GL_PACK_ALIGNMENT, 1)
glReadPixels(x, y, self.width, self.height,
self.gl_format, GL_UNSIGNED_BYTE, buffer)
glPopClientAttrib()
return ImageData(self.width, self.height, self.format, buffer)
def get_region(self, x, y, width, height):
if self.owner:
return self.owner.get_region(x + self.x, y + self.y, width, height)
region = self.__class__(x + self.x, y + self.y, width, height)
region.gl_buffer = self.gl_buffer
region.owner = self
return region
class ColorBufferImage(BufferImage):
"""A color framebuffer.
This class is used to wrap both the primary color buffer (i.e., the back
buffer) or any one of the auxiliary buffers.
"""
gl_format = GL_RGBA
format = 'RGBA'
def get_texture(self, rectangle=False, force_rectangle=False):
texture = Texture.create(self.width, self.height, GL_RGBA,
rectangle, force_rectangle)
self.blit_to_texture(texture.target, texture.level,
self.anchor_x, self.anchor_y, 0)
return texture
def blit_to_texture(self, target, level, x, y, z):
glReadBuffer(self.gl_buffer)
glCopyTexSubImage2D(target, level,
x - self.anchor_x, y - self.anchor_y,
self.x, self.y, self.width, self.height)
class DepthBufferImage(BufferImage):
"""The depth buffer.
"""
gl_format = GL_DEPTH_COMPONENT
format = 'L'
def get_texture(self, rectangle=False, force_rectangle=False):
assert rectangle == False and force_rectangle == False, \
'Depth textures cannot be rectangular'
if not _is_pow2(self.width) or not _is_pow2(self.height):
raise ImageException(
'Depth texture requires that buffer dimensions be powers of 2')
texture = DepthTexture.create_for_size(GL_TEXTURE_2D,
self.width, self.height)
if self.anchor_x or self.anchor_y:
texture.anchor_x = self.anchor_x
texture.anchor_y = self.anchor_y
glReadBuffer(self.gl_buffer)
glCopyTexImage2D(texture.target, 0,
GL_DEPTH_COMPONENT,
self.x, self.y, self.width, self.height,
0)
return texture
def blit_to_texture(self, target, level, x, y, z):
glReadBuffer(self.gl_buffer)
glCopyTexSubImage2D(target, level,
x - self.anchor_x, y - self.anchor_y,
self.x, self.y, self.width, self.height)
class BufferImageMask(BufferImage):
"""A single bit of the stencil buffer.
"""
gl_format = GL_STENCIL_INDEX
format = 'L'
# TODO mask methods
class ImageGrid(AbstractImage, AbstractImageSequence):
"""An imaginary grid placed over an image allowing easy access to
regular regions of that image.
The grid can be accessed either as a complete image, or as a sequence
of images. The most useful applications are to access the grid
as a :py:class:`~pyglet.image.TextureGrid`::
image_grid = ImageGrid(...)
texture_grid = image_grid.get_texture_sequence()
or as a :py:class:`~pyglet.image.Texture3D`::
image_grid = ImageGrid(...)
texture_3d = Texture3D.create_for_image_grid(image_grid)
"""
_items = ()
_texture_grid = None
def __init__(self, image, rows, columns,
item_width=None, item_height=None,
row_padding=0, column_padding=0):
"""Construct a grid for the given image.
You can specify parameters for the grid, for example setting
the padding between cells. Grids are always aligned to the
bottom-left corner of the image.
:Parameters:
`image` : AbstractImage
Image over which to construct the grid.
`rows` : int
Number of rows in the grid.
`columns` : int
Number of columns in the grid.
`item_width` : int
Width of each column. If unspecified, is calculated such
that the entire image width is used.
`item_height` : int
Height of each row. If unspecified, is calculated such that
the entire image height is used.
`row_padding` : int
Pixels separating adjacent rows. The padding is only
inserted between rows, not at the edges of the grid.
`column_padding` : int
Pixels separating adjacent columns. The padding is only
inserted between columns, not at the edges of the grid.
"""
super(ImageGrid, self).__init__(image.width, image.height)
if item_width is None:
item_width = \
(image.width - column_padding * (columns - 1)) // columns
if item_height is None:
item_height = \
(image.height - row_padding * (rows - 1)) // rows
self.image = image
self.rows = rows
self.columns = columns
self.item_width = item_width
self.item_height = item_height
self.row_padding = row_padding
self.column_padding = column_padding
def get_texture(self, rectangle=False, force_rectangle=False):
return self.image.get_texture(rectangle, force_rectangle)
def get_image_data(self):
return self.image.get_image_data()
def get_texture_sequence(self):
if not self._texture_grid:
self._texture_grid = TextureGrid(self)
return self._texture_grid
def __len__(self):
return self.rows * self.columns
def _update_items(self):
if not self._items:
self._items = []
y = 0
for row in range(self.rows):
x = 0
for col in range(self.columns):
self._items.append(self.image.get_region(
x, y, self.item_width, self.item_height))
x += self.item_width + self.column_padding
y += self.item_height + self.row_padding
def __getitem__(self, index):
self._update_items()
if type(index) is tuple:
row, column = index
assert row >= 0 and column >= 0 and row < self.rows and column < self.columns
return self._items[row * self.columns + column]
else:
return self._items[index]
def __iter__(self):
self._update_items()
return iter(self._items)
class TextureGrid(TextureRegion, UniformTextureSequence):
"""A texture containing a regular grid of texture regions.
To construct, create an :py:class:`~pyglet.image.ImageGrid` first::
image_grid = ImageGrid(...)
texture_grid = TextureGrid(image_grid)
The texture grid can be accessed as a single texture, or as a sequence
of :py:class:`~pyglet.image.TextureRegion`. When accessing as a sequence, you can specify
integer indexes, in which the images are arranged in rows from the
bottom-left to the top-right::
# assume the texture_grid is 3x3:
current_texture = texture_grid[3] # get the middle-left image
You can also specify tuples in the sequence methods, which are addressed
as ``row, column``::
# equivalent to the previous example:
current_texture = texture_grid[1, 0]
When using tuples in a slice, the returned sequence is over the
rectangular region defined by the slice::
# returns center, center-right, center-top, top-right images in that
# order:
images = texture_grid[(1,1):]
# equivalent to
images = texture_grid[(1,1):(3,3)]
"""
items = ()
rows = 1
columns = 1
item_width = 0
item_height = 0
def __init__(self, grid):
image = grid.get_texture()
if isinstance(image, TextureRegion):
owner = image.owner
else:
owner = image
super(TextureGrid, self).__init__(
image.x, image.y, image.z, image.width, image.height, owner)
items = []
y = 0
for row in range(grid.rows):
x = 0
for col in range(grid.columns):
items.append(
self.get_region(x, y, grid.item_width, grid.item_height))
x += grid.item_width + grid.column_padding
y += grid.item_height + grid.row_padding
self.items = items
self.rows = grid.rows
self.columns = grid.columns
self.item_width = grid.item_width
self.item_height = grid.item_height
def get(self, row, column):
return self[(row, column)]
def __getitem__(self, index):
if type(index) is slice:
if type(index.start) is not tuple and \
type(index.stop) is not tuple:
return self.items[index]
else:
row1 = 0
col1 = 0
row2 = self.rows
col2 = self.columns
if type(index.start) is tuple:
row1, col1 = index.start
elif type(index.start) is int:
row1 = index.start // self.columns
col1 = index.start % self.columns
assert row1 >= 0 and col1 >= 0 and row1 < self.rows and col1 < self.columns
if type(index.stop) is tuple:
row2, col2 = index.stop
elif type(index.stop) is int:
row2 = index.stop // self.columns
col2 = index.stop % self.columns
assert row2 >= 0 and col2 >= 0 and row2 <= self.rows and col2 <= self.columns
result = []
i = row1 * self.columns
for row in range(row1, row2):
result += self.items[i + col1:i + col2]
i += self.columns
return result
else:
if type(index) is tuple:
row, column = index
assert row >= 0 and column >= 0 and row < self.rows and column < self.columns
return self.items[row * self.columns + column]
elif type(index) is int:
return self.items[index]
def __setitem__(self, index, value):
if type(index) is slice:
for region, image in zip(self[index], value):
if image.width != self.item_width or image.height != self.item_height:
raise ImageException('Image has incorrect dimensions')
image.blit_into(region, image.anchor_x, image.anchor_y, 0)
else:
image = value
if image.width != self.item_width or image.height != self.item_height:
raise ImageException('Image has incorrect dimensions')
image.blit_into(self[index], image.anchor_x, image.anchor_y, 0)
def __len__(self):
return len(self.items)
def __iter__(self):
return iter(self.items)
# --------------------------------------------------------------------------
# Animation stuff here. Vote on if this should be in pyglet.image.animation
# or just leave it tacked on here.
# TODO:
# conversion Animation -> media.Source
# move to another module?
# pyglet.animation?
# pyglet.image.animation?
def load_animation(filename, file=None, decoder=None):
"""Load an animation from a file.
Currently, the only supported format is GIF.
:Parameters:
`filename` : str
Used to guess the animation format, and to load the file if `file`
is unspecified.
`file` : file-like object or None
File object containing the animation stream.
`decoder` : ImageDecoder or None
If unspecified, all decoders that are registered for the filename
extension are tried. If none succeed, the exception from the
first decoder is raised.
:rtype: Animation
"""
if not file:
file = open(filename, 'rb')
if not hasattr(file, 'seek'):
file = BytesIO(file.read())
if decoder:
return decoder.decode(file, filename)
else:
first_exception = None
for decoder in _codecs.get_animation_decoders(filename):
try:
image = decoder.decode_animation(file, filename)
return image
except _codecs.ImageDecodeException as e:
first_exception = first_exception or e
file.seek(0)
if not first_exception:
raise _codecs.ImageDecodeException('No image decoders are available')
raise first_exception
class Animation(object):
"""Sequence of images with timing information.
If no frames of the animation have a duration of ``None``, the animation
loops continuously; otherwise the animation stops at the first frame with
duration of ``None``.
:Ivariables:
`frames` : list of `~pyglet.image.AnimationFrame`
The frames that make up the animation.
"""
def __init__(self, frames):
"""Create an animation directly from a list of frames.
:Parameters:
`frames` : list of `~pyglet.image.AnimationFrame`
The frames that make up the animation.
"""
assert len(frames)
self.frames = frames
def add_to_texture_bin(self, bin):
"""Add the images of the animation to a :py:class:`~pyglet.image.atlas.TextureBin`.
The animation frames are modified in-place to refer to the texture bin
regions.
:Parameters:
`bin` : `~pyglet.image.atlas.TextureBin`
Texture bin to upload animation frames into.
"""
for frame in self.frames:
frame.image = bin.add(frame.image)
def get_transform(self, flip_x=False, flip_y=False, rotate=0):
"""Create a copy of this animation applying a simple transformation.
The transformation is applied around the image's anchor point of
each frame. The texture data is shared between the original animation
and the transformed animation.
:Parameters:
`flip_x` : bool
If True, the returned animation will be flipped horizontally.
`flip_y` : bool
If True, the returned animation will be flipped vertically.
`rotate` : int
Degrees of clockwise rotation of the returned animation. Only
90-degree increments are supported.
:rtype: :py:class:`~pyglet.image.Animation`
"""
frames = [AnimationFrame(frame.image.get_texture().get_transform(flip_x, flip_y, rotate),
frame.duration) for frame in self.frames]
return Animation(frames)
def get_duration(self):
"""Get the total duration of the animation in seconds.
:rtype: float
"""
return sum([frame.duration for frame in self.frames if frame.duration is not None])
def get_max_width(self):
"""Get the maximum image frame width.
This method is useful for determining texture space requirements: due
to the use of ``anchor_x`` the actual required playback area may be
larger.
:rtype: int
"""
return max([frame.image.width for frame in self.frames])
def get_max_height(self):
"""Get the maximum image frame height.
This method is useful for determining texture space requirements: due
to the use of ``anchor_y`` the actual required playback area may be
larger.
:rtype: int
"""
return max([frame.image.height for frame in self.frames])
@classmethod
def from_image_sequence(cls, sequence, period, loop=True):
"""Create an animation from a list of images and a constant framerate.
:Parameters:
`sequence` : list of `~pyglet.image.AbstractImage`
Images that make up the animation, in sequence.
`period` : float
Number of seconds to display each image.
`loop` : bool
If True, the animation will loop continuously.
:rtype: :py:class:`~pyglet.image.Animation`
"""
frames = [AnimationFrame(image, period) for image in sequence]
if not loop:
frames[-1].duration = None
return cls(frames)
class AnimationFrame(object):
"""A single frame of an animation.
"""
def __init__(self, image, duration):
"""Create an animation frame from an image.
:Parameters:
`image` : `~pyglet.image.AbstractImage`
The image of this frame.
`duration` : float
Number of seconds to display the frame, or ``None`` if it is
the last frame in the animation.
"""
self.image = image
self.duration = duration
def __repr__(self):
return 'AnimationFrame(%r, %r)' % (self.image, self.duration)
# Initialise default codecs
_codecs.add_default_image_codecs()
| 93,853 | 34.456743 | 104 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/pyglet/image/atlas.py
|
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
"""Group multiple small images into larger textures.
This module is used by :py:mod:`pyglet.resource` to efficiently pack small
images into larger textures. :py:class:`~pyglet.image.atlas.TextureAtlas` maintains one texture;
:py:class:`TextureBin` manages a collection of atlases of a given size.
Example usage::
# Load images from disk
car_image = pyglet.image.load('car.png')
boat_image = pyglet.image.load('boat.png')
# Pack these images into one or more textures
bin = TextureBin()
car_texture = bin.add(car_image)
boat_texture = bin.add(boat_image)
The result of :py:meth:`TextureBin.add` is a :py:class:`TextureRegion`
containing the image. Once added, an image cannot be removed from a bin (or an
atlas); nor can a list of images be obtained from a given bin or atlas -- it is
the application's responsibility to keep track of the regions returned by the
``add`` methods.
.. versionadded:: 1.1
"""
from __future__ import division
from builtins import object
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
from ctypes import c_int
import pyglet
def get_max_texture_size():
"""Query the maximum texture size available"""
size = c_int()
pyglet.gl.glGetIntegerv(pyglet.gl.GL_MAX_TEXTURE_SIZE, size)
return size.value
class AllocatorException(Exception):
"""The allocator does not have sufficient free space for the requested
image size."""
pass
class _Strip(object):
def __init__(self, y, max_height):
self.x = 0
self.y = y
self.max_height = max_height
self.y2 = y
def add(self, width, height):
assert width > 0 and height > 0
assert height <= self.max_height
x, y = self.x, self.y
self.x += width
self.y2 = max(self.y + height, self.y2)
return x, y
def compact(self):
self.max_height = self.y2 - self.y
class Allocator(object):
"""Rectangular area allocation algorithm.
Initialise with a given ``width`` and ``height``, then repeatedly
call `alloc` to retrieve free regions of the area and protect that
area from future allocations.
`Allocator` uses a fairly simple strips-based algorithm. It performs best
when rectangles are allocated in decreasing height order.
"""
def __init__(self, width, height):
"""Create an `Allocator` of the given size.
:Parameters:
`width` : int
Width of the allocation region.
`height` : int
Height of the allocation region.
"""
assert width > 0 and height > 0
self.width = width
self.height = height
self.strips = [_Strip(0, height)]
self.used_area = 0
def alloc(self, width, height):
"""Get a free area in the allocator of the given size.
After calling `alloc`, the requested area will no longer be used.
If there is not enough room to fit the given area `AllocatorException`
is raised.
:Parameters:
`width` : int
Width of the area to allocate.
`height` : int
Height of the area to allocate.
:rtype: int, int
:return: The X and Y coordinates of the bottom-left corner of the
allocated region.
"""
for strip in self.strips:
if self.width - strip.x >= width and strip.max_height >= height:
self.used_area += width * height
return strip.add(width, height)
if self.width >= width and self.height - strip.y2 >= height:
self.used_area += width * height
strip.compact()
newstrip = _Strip(strip.y2, self.height - strip.y2)
self.strips.append(newstrip)
return newstrip.add(width, height)
raise AllocatorException('No more space in %r for box %dx%d' % (
self, width, height))
def get_usage(self):
"""Get the fraction of area already allocated.
This method is useful for debugging and profiling only.
:rtype: float
"""
return self.used_area / float(self.width * self.height)
def get_fragmentation(self):
"""Get the fraction of area that's unlikely to ever be used, based on
current allocation behaviour.
This method is useful for debugging and profiling only.
:rtype: float
"""
# The total unused area in each compacted strip is summed.
if not self.strips:
return 0.
possible_area = self.strips[-1].y2 * self.width
return 1.0 - self.used_area / float(possible_area)
class TextureAtlas(object):
"""Collection of images within a texture."""
def __init__(self, width=2048, height=2048):
"""Create a texture atlas of the given size.
:Parameters:
`width` : int
Width of the underlying texture.
`height` : int
Height of the underlying texture.
"""
max_texture_size = get_max_texture_size()
width = min(width, max_texture_size)
height = min(height, max_texture_size)
self.texture = pyglet.image.Texture.create(
width, height, pyglet.gl.GL_RGBA, rectangle=True)
self.allocator = Allocator(width, height)
def add(self, img):
"""Add an image to the atlas.
This method will fail if the given image cannot be transferred
directly to a texture (for example, if it is another texture).
:py:class:`~pyglet.image.ImageData` is the usual image type for this method.
`AllocatorException` will be raised if there is no room in the atlas
for the image.
:Parameters:
`img` : `~pyglet.image.AbstractImage`
The image to add.
:rtype: :py:class:`~pyglet.image.TextureRegion`
:return: The region of the atlas containing the newly added image.
"""
x, y = self.allocator.alloc(img.width, img.height)
self.texture.blit_into(img, x, y, 0)
region = self.texture.get_region(x, y, img.width, img.height)
return region
class TextureBin(object):
"""Collection of texture atlases.
:py:class:`~pyglet.image.atlas.TextureBin` maintains a collection of texture atlases, and creates new
ones as necessary to accommodate images added to the bin.
"""
def __init__(self, texture_width=2048, texture_height=2048):
"""Create a texture bin for holding atlases of the given size.
:Parameters:
`texture_width` : int
Width of texture atlases to create.
`texture_height` : int
Height of texture atlases to create.
"""
max_texture_size = get_max_texture_size()
texture_width = min(texture_width, max_texture_size)
texture_height = min(texture_height, max_texture_size)
self.atlases = []
self.texture_width = texture_width
self.texture_height = texture_height
def add(self, img):
"""Add an image into this texture bin.
This method calls `TextureAtlas.add` for the first atlas that has room
for the image.
`AllocatorException` is raised if the image exceeds the dimensions of
``texture_width`` and ``texture_height``.
:Parameters:
`img` : `~pyglet.image.AbstractImage`
The image to add.
:rtype: :py:class:`~pyglet.image.TextureRegion`
:return: The region of an atlas containing the newly added image.
"""
for atlas in list(self.atlases):
try:
return atlas.add(img)
except AllocatorException:
# Remove atlases that are no longer useful (this is so their
# textures can later be freed if the images inside them get
# collected).
if img.width < 64 and img.height < 64:
self.atlases.remove(atlas)
atlas = TextureAtlas(self.texture_width, self.texture_height)
self.atlases.append(atlas)
return atlas.add(img)
| 9,892 | 34.08156 | 105 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/pyglet/image/codecs/quicktime.py
|
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
'''
'''
from __future__ import division
from builtins import chr
__docformat__ = 'restructuredtext'
__version__ = '$Id: pil.py 163 2006-11-13 04:15:46Z Alex.Holkner $'
import sys
from ctypes import *
from pyglet.gl import *
from pyglet.image import *
from pyglet.image.codecs import *
from pyglet.window.carbon import carbon, quicktime, _oscheck
from pyglet.libs.darwin.constants import _name
from pyglet.libs.darwin.types import *
Handle = POINTER(POINTER(c_byte))
GWorldPtr = c_void_p
carbon.NewHandle.restype = Handle
HandleDataHandlerSubType = _name('hndl')
PointerDataHandlerSubType = _name('ptr ')
kDataHCanRead = 1
kDataRefExtensionFileName = _name('fnam')
kDataRefExtensionMIMEType = _name('mime')
ComponentInstance = c_void_p
k1MonochromePixelFormat = 0x00000001
k2IndexedPixelFormat = 0x00000002
k4IndexedPixelFormat = 0x00000004
k8IndexedPixelFormat = 0x00000008
k16BE555PixelFormat = 0x00000010
k24RGBPixelFormat = 0x00000018
k32ARGBPixelFormat = 0x00000020
k32BGRAPixelFormat = _name('BGRA')
k1IndexedGrayPixelFormat = 0x00000021
k2IndexedGrayPixelFormat = 0x00000022
k4IndexedGrayPixelFormat = 0x00000024
k8IndexedGrayPixelFormat = 0x00000028
kNativeEndianPixMap = 1 << 8
kGraphicsImporterDontDoGammaCorrection = 1 << 0
kGraphicsImporterDontUseColorMatching = 1 << 3
newMovieActive = 1
noErr = 0
movieTrackMediaType = 1 << 0
movieTrackCharacteristic = 1 << 1
movieTrackEnabledOnly = 1 << 2
VisualMediaCharacteristic = _name('eyes')
nextTimeMediaSample = 1
class PointerDataRefRecord(Structure):
_fields_ = [
('data', c_void_p),
('dataLength', c_long)
]
def Str255(value):
return create_string_buffer(chr(len(value)) + value)
class QuickTimeImageDecoder(ImageDecoder):
def get_file_extensions(self):
# Only most common ones shown here
return ['.bmp', '.cur', '.gif', '.ico', '.jpg', '.jpeg', '.pcx', '.png',
'.tga', '.tif', '.tiff', '.xbm', '.xpm']
def get_animation_file_extensions(self):
return ['.gif']
def _get_data_ref(self, file, filename):
self._data_hold = data = create_string_buffer(file.read())
dataref = carbon.NewHandle(sizeof(PointerDataRefRecord))
datarec = cast(dataref,
POINTER(POINTER(PointerDataRefRecord))).contents.contents
datarec.data = addressof(data)
datarec.dataLength = len(data)
self._data_handler_holder = data_handler = ComponentInstance()
r = quicktime.OpenADataHandler(dataref, PointerDataHandlerSubType,
None, 0, None, kDataHCanRead, byref(data_handler))
_oscheck(r)
extension_handle = Handle()
self._filename_hold = filename = Str255(filename)
r = carbon.PtrToHand(filename, byref(extension_handle), len(filename))
r = quicktime.DataHSetDataRefExtension(data_handler, extension_handle,
kDataRefExtensionFileName)
_oscheck(r)
quicktime.DisposeHandle(extension_handle)
quicktime.DisposeHandle(dataref)
dataref = c_void_p()
r = quicktime.DataHGetDataRef(data_handler, byref(dataref))
_oscheck(r)
quicktime.CloseComponent(data_handler)
return dataref
def _get_formats(self):
# TODO choose 24 bit where appropriate.
if sys.byteorder == 'big':
format = 'ARGB'
qtformat = k32ARGBPixelFormat
else:
format = 'BGRA'
qtformat = k32BGRAPixelFormat
return format, qtformat
def decode(self, file, filename):
dataref = self._get_data_ref(file, filename)
importer = ComponentInstance()
quicktime.GetGraphicsImporterForDataRef(dataref,
PointerDataHandlerSubType, byref(importer))
if not importer:
raise ImageDecodeException(filename or file)
rect = Rect()
quicktime.GraphicsImportGetNaturalBounds(importer, byref(rect))
width = rect.right
height = rect.bottom
format, qtformat = self._get_formats()
buffer = (c_byte * (width * height * len(format)))()
world = GWorldPtr()
quicktime.QTNewGWorldFromPtr(byref(world), qtformat,
byref(rect), c_void_p(), c_void_p(), 0, buffer,
len(format) * width)
flags = (kGraphicsImporterDontUseColorMatching |
kGraphicsImporterDontDoGammaCorrection)
quicktime.GraphicsImportSetFlags(importer, flags)
quicktime.GraphicsImportSetGWorld(importer, world, c_void_p())
result = quicktime.GraphicsImportDraw(importer)
quicktime.DisposeGWorld(world)
quicktime.CloseComponent(importer)
if result != 0:
raise ImageDecodeException(filename or file)
pitch = len(format) * width
return ImageData(width, height, format, buffer, -pitch)
def decode_animation(self, file, filename):
# TODO: Stop playing chicken with the GC
# TODO: Cleanup in errors
quicktime.EnterMovies()
data_ref = self._get_data_ref(file, filename)
if not data_ref:
raise ImageDecodeException(filename or file)
movie = c_void_p()
id = c_short()
result = quicktime.NewMovieFromDataRef(byref(movie),
newMovieActive,
0,
data_ref,
PointerDataHandlerSubType)
if not movie:
#_oscheck(result)
raise ImageDecodeException(filename or file)
quicktime.GoToBeginningOfMovie(movie)
time_scale = float(quicktime.GetMovieTimeScale(movie))
format, qtformat = self._get_formats()
# Get movie width and height
rect = Rect()
quicktime.GetMovieBox(movie, byref(rect))
width = rect.right
height = rect.bottom
pitch = len(format) * width
# Set gworld
buffer = (c_byte * (width * height * len(format)))()
world = GWorldPtr()
quicktime.QTNewGWorldFromPtr(byref(world), qtformat,
byref(rect), c_void_p(), c_void_p(), 0, buffer,
len(format) * width)
quicktime.SetGWorld(world, 0)
quicktime.SetMovieGWorld(movie, world, 0)
visual = quicktime.GetMovieIndTrackType(movie, 1,
VisualMediaCharacteristic,
movieTrackCharacteristic)
if not visual:
raise ImageDecodeException('No video track')
time = 0
interesting_time = c_int()
quicktime.GetTrackNextInterestingTime(
visual,
nextTimeMediaSample,
time,
1,
byref(interesting_time),
None)
duration = interesting_time.value / time_scale
frames = []
while time >= 0:
result = quicktime.GetMoviesError()
if result == noErr:
# force redraw
result = quicktime.UpdateMovie(movie)
if result == noErr:
# process movie
quicktime.MoviesTask(movie, 0)
result = quicktime.GetMoviesError()
_oscheck(result)
buffer_copy = (c_byte * len(buffer))()
memmove(buffer_copy, buffer, len(buffer))
image = ImageData(width, height, format, buffer_copy, -pitch)
frames.append(AnimationFrame(image, duration))
interesting_time = c_int()
duration = c_int()
quicktime.GetTrackNextInterestingTime(
visual,
nextTimeMediaSample,
time,
1,
byref(interesting_time),
byref(duration))
quicktime.SetMovieTimeValue(movie, interesting_time)
time = interesting_time.value
duration = duration.value / time_scale
if duration <= 0.01:
duration = 0.1
quicktime.DisposeMovie(movie)
carbon.DisposeHandle(data_ref)
quicktime.ExitMovies()
return Animation(frames)
def get_decoders():
return [QuickTimeImageDecoder()]
def get_encoders():
return []
| 10,211 | 33.268456 | 80 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/pyglet/image/codecs/dds.py
|
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
'''DDS texture loader.
Reference: http://msdn2.microsoft.com/en-us/library/bb172993.aspx
'''
from __future__ import division
from __future__ import print_function
from builtins import range
from builtins import object
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
from ctypes import *
import struct
from pyglet.gl import *
from pyglet.image import CompressedImageData
from pyglet.image import codecs
from pyglet.image.codecs import s3tc
from pyglet.compat import izip_longest as compat_izip_longest
class DDSException(codecs.ImageDecodeException):
exception_priority = 0
# dwFlags of DDSURFACEDESC2
DDSD_CAPS = 0x00000001
DDSD_HEIGHT = 0x00000002
DDSD_WIDTH = 0x00000004
DDSD_PITCH = 0x00000008
DDSD_PIXELFORMAT = 0x00001000
DDSD_MIPMAPCOUNT = 0x00020000
DDSD_LINEARSIZE = 0x00080000
DDSD_DEPTH = 0x00800000
# ddpfPixelFormat of DDSURFACEDESC2
DDPF_ALPHAPIXELS = 0x00000001
DDPF_FOURCC = 0x00000004
DDPF_RGB = 0x00000040
# dwCaps1 of DDSCAPS2
DDSCAPS_COMPLEX = 0x00000008
DDSCAPS_TEXTURE = 0x00001000
DDSCAPS_MIPMAP = 0x00400000
# dwCaps2 of DDSCAPS2
DDSCAPS2_CUBEMAP = 0x00000200
DDSCAPS2_CUBEMAP_POSITIVEX = 0x00000400
DDSCAPS2_CUBEMAP_NEGATIVEX = 0x00000800
DDSCAPS2_CUBEMAP_POSITIVEY = 0x00001000
DDSCAPS2_CUBEMAP_NEGATIVEY = 0x00002000
DDSCAPS2_CUBEMAP_POSITIVEZ = 0x00004000
DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x00008000
DDSCAPS2_VOLUME = 0x00200000
class _filestruct(object):
def __init__(self, data):
if len(data) < self.get_size():
raise DDSException('Not a DDS file')
items = struct.unpack(self.get_format(), data)
for field, value in compat_izip_longest(self._fields,
items,
fillvalue=None):
setattr(self, field[0], value)
def __repr__(self):
name = self.__class__.__name__
return '%s(%s)' % \
(name, (', \n%s' % (' ' * (len(name) + 1))).join( \
['%s = %s' % (field[0], repr(getattr(self, field[0]))) \
for field in self._fields]))
@classmethod
def get_format(cls):
return '<' + ''.join([f[1] for f in cls._fields])
@classmethod
def get_size(cls):
return struct.calcsize(cls.get_format())
class DDSURFACEDESC2(_filestruct):
_fields = [
('dwMagic', '4s'),
('dwSize', 'I'),
('dwFlags', 'I'),
('dwHeight', 'I'),
('dwWidth', 'I'),
('dwPitchOrLinearSize', 'I'),
('dwDepth', 'I'),
('dwMipMapCount', 'I'),
('dwReserved1', '44s'),
('ddpfPixelFormat', '32s'),
('dwCaps1', 'I'),
('dwCaps2', 'I'),
('dwCapsReserved', '8s'),
('dwReserved2', 'I')
]
def __init__(self, data):
super(DDSURFACEDESC2, self).__init__(data)
self.ddpfPixelFormat = DDPIXELFORMAT(self.ddpfPixelFormat)
class DDPIXELFORMAT(_filestruct):
_fields = [
('dwSize', 'I'),
('dwFlags', 'I'),
('dwFourCC', '4s'),
('dwRGBBitCount', 'I'),
('dwRBitMask', 'I'),
('dwGBitMask', 'I'),
('dwBBitMask', 'I'),
('dwRGBAlphaBitMask', 'I')
]
_compression_formats = {
(b'DXT1', False): (GL_COMPRESSED_RGB_S3TC_DXT1_EXT, s3tc.decode_dxt1_rgb),
(b'DXT1', True): (GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, s3tc.decode_dxt1_rgba),
(b'DXT3', False): (GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, s3tc.decode_dxt3),
(b'DXT3', True): (GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, s3tc.decode_dxt3),
(b'DXT5', False): (GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, s3tc.decode_dxt5),
(b'DXT5', True): (GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, s3tc.decode_dxt5),
}
def _check_error():
e = glGetError()
if e != 0:
print('GL error %d' % e)
class DDSImageDecoder(codecs.ImageDecoder):
def get_file_extensions(self):
return ['.dds']
def decode(self, file, filename):
header = file.read(DDSURFACEDESC2.get_size())
desc = DDSURFACEDESC2(header)
if desc.dwMagic != b'DDS ' or desc.dwSize != 124:
raise DDSException('Invalid DDS file (incorrect header).')
width = desc.dwWidth
height = desc.dwHeight
mipmaps = 1
if desc.dwFlags & DDSD_DEPTH:
raise DDSException('Volume DDS files unsupported')
if desc.dwFlags & DDSD_MIPMAPCOUNT:
mipmaps = desc.dwMipMapCount
if desc.ddpfPixelFormat.dwSize != 32:
raise DDSException('Invalid DDS file (incorrect pixel format).')
if desc.dwCaps2 & DDSCAPS2_CUBEMAP:
raise DDSException('Cubemap DDS files unsupported')
if not desc.ddpfPixelFormat.dwFlags & DDPF_FOURCC:
raise DDSException('Uncompressed DDS textures not supported.')
has_alpha = desc.ddpfPixelFormat.dwRGBAlphaBitMask != 0
selector = (desc.ddpfPixelFormat.dwFourCC, has_alpha)
if selector not in _compression_formats:
raise DDSException('Unsupported texture compression %s' % \
desc.ddpfPixelFormat.dwFourCC)
dformat, decoder = _compression_formats[selector]
if dformat == GL_COMPRESSED_RGB_S3TC_DXT1_EXT:
block_size = 8
else:
block_size = 16
datas = []
w, h = width, height
for i in range(mipmaps):
if not w and not h:
break
if not w:
w = 1
if not h:
h = 1
size = ((w + 3) // 4) * ((h + 3) // 4) * block_size
data = file.read(size)
datas.append(data)
w >>= 1
h >>= 1
image = CompressedImageData(width, height, dformat, datas[0],
'GL_EXT_texture_compression_s3tc', decoder)
level = 0
for data in datas[1:]:
level += 1
image.set_mipmap_data(level, data)
return image
def get_decoders():
return [DDSImageDecoder()]
def get_encoders():
return []
| 7,829 | 32.319149 | 80 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/pyglet/image/codecs/gdkpixbuf2.py
|
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
from builtins import object
from ctypes import *
from pyglet.gl import *
from pyglet.image import *
from pyglet.image.codecs import *
from pyglet.image.codecs import gif
import pyglet.lib
import pyglet.window
gdk = pyglet.lib.load_library('gdk-x11-2.0')
gdkpixbuf = pyglet.lib.load_library('gdk_pixbuf-2.0')
GdkPixbufLoader = c_void_p
GdkPixbuf = c_void_p
guchar = c_char
gdkpixbuf.gdk_pixbuf_loader_new.restype = POINTER(GdkPixbufLoader)
gdkpixbuf.gdk_pixbuf_loader_get_pixbuf.restype = POINTER(GdkPixbuf)
gdkpixbuf.gdk_pixbuf_get_pixels.restype = POINTER(guchar)
gdkpixbuf.gdk_pixbuf_loader_get_animation.restype = POINTER(c_void_p)
gdkpixbuf.gdk_pixbuf_animation_get_iter.restype = POINTER(c_void_p)
gdkpixbuf.gdk_pixbuf_animation_iter_get_pixbuf.restype = POINTER(GdkPixbuf)
class GTimeVal(Structure):
_fields_ = [
('tv_sec', c_long),
('tv_usec', c_long)
]
GQuark = c_uint32
gint = c_int
gchar = c_char
class GError(Structure):
_fields_ = [
('domain', GQuark),
('code', gint),
('message', POINTER(gchar))
]
gerror_ptr = POINTER(GError)
def _gerror_to_string(error):
"""
Convert a GError to a string.
`error` should be a valid pointer to a GError struct.
"""
return 'GdkPixBuf Error: domain[{}], code[{}]: {}'.format(error.contents.domain,
error.contents.code,
error.contents.message)
class GdkPixBufLoader(object):
"""
Wrapper around GdkPixBufLoader object.
"""
def __init__(self, file_, filename):
self.closed = False
self._file = file_
self._filename = filename
self._loader = gdkpixbuf.gdk_pixbuf_loader_new()
if self._loader is None:
raise ImageDecodeException('Unable to instantiate gdk pixbuf loader')
self._load_file()
def __del__(self):
if self._loader is not None:
if not self.closed:
self._cancel_load()
gdk.g_object_unref(self._loader)
def _load_file(self):
assert self._file is not None
self._file.seek(0)
data = self._file.read()
self.write(data)
def _finish_load(self):
assert not self.closed
error = gerror_ptr()
all_data_passed = gdkpixbuf.gdk_pixbuf_loader_close(self._loader, byref(error))
self.closed = True
if not all_data_passed:
raise ImageDecodeException(_gerror_to_string(error))
def _cancel_load(self):
assert not self.closed
gdkpixbuf.gdk_pixbuf_loader_close(self._loader, None)
self.closed = True
def write(self, data):
assert not self.closed, 'Cannot write after closing loader'
error = gerror_ptr()
if not gdkpixbuf.gdk_pixbuf_loader_write(self._loader, data, len(data), byref(error)):
raise ImageDecodeException(_gerror_to_string(error))
def get_pixbuf(self):
self._finish_load()
pixbuf = gdkpixbuf.gdk_pixbuf_loader_get_pixbuf(self._loader)
if pixbuf is None:
raise ImageDecodeException('Failed to get pixbuf from loader')
return GdkPixBuf(self, pixbuf)
def get_animation(self):
self._finish_load()
anim = gdkpixbuf.gdk_pixbuf_loader_get_animation(self._loader)
if anim is None:
raise ImageDecodeException('Failed to get animation from loader')
gif_delays = self._get_gif_delays()
return GdkPixBufAnimation(self, anim, gif_delays)
def _get_gif_delays(self):
# GDK pixbuf animations will loop indefinitely if looping is enabled for the
# gif, so get number of frames and delays from gif metadata
assert self._file is not None
self._file.seek(0)
gif_stream = gif.read(self._file)
return [image.delay for image in gif_stream.images]
class GdkPixBuf(object):
"""
Wrapper around GdkPixBuf object.
"""
def __init__(self, loader, pixbuf):
# Keep reference to loader alive
self._loader = loader
self._pixbuf = pixbuf
gdk.g_object_ref(pixbuf)
def __del__(self):
if self._pixbuf is not None:
gdk.g_object_unref(self._pixbuf)
def load_next(self):
return self._pixbuf is not None
@property
def width(self):
assert self._pixbuf is not None
return gdkpixbuf.gdk_pixbuf_get_width(self._pixbuf)
@property
def height(self):
assert self._pixbuf is not None
return gdkpixbuf.gdk_pixbuf_get_height(self._pixbuf)
@property
def channels(self):
assert self._pixbuf is not None
return gdkpixbuf.gdk_pixbuf_get_n_channels(self._pixbuf)
@property
def rowstride(self):
assert self._pixbuf is not None
return gdkpixbuf.gdk_pixbuf_get_rowstride(self._pixbuf)
@property
def has_alpha(self):
assert self._pixbuf is not None
return gdkpixbuf.gdk_pixbuf_get_has_alpha(self._pixbuf) == 1
def get_pixels(self):
pixels = gdkpixbuf.gdk_pixbuf_get_pixels(self._pixbuf)
assert pixels is not None
buf = (c_ubyte * (self.rowstride * self.height))()
memmove(buf, pixels, self.rowstride * (self.height - 1) + self.width * self.channels)
return buf
def to_image(self):
if self.width < 1 or self.height < 1 or self.channels < 1 or self.rowstride < 1:
return None
pixels = self.get_pixels()
# Determine appropriate GL type
if self.channels == 3:
format = 'RGB'
else:
format = 'RGBA'
return ImageData(self.width, self.height, format, pixels, -self.rowstride)
class GdkPixBufAnimation(object):
"""
Wrapper for a GdkPixBufIter for an animation.
"""
def __init__(self, loader, anim, gif_delays):
self._loader = loader
self._anim = anim
self._gif_delays = gif_delays
gdk.g_object_ref(anim)
def __del__(self):
if self._anim is not None:
gdk.g_object_unref(self._anim)
def __iter__(self):
time = GTimeVal(0, 0)
anim_iter = gdkpixbuf.gdk_pixbuf_animation_get_iter(self._anim, byref(time))
return GdkPixBufAnimationIterator(self._loader, anim_iter, time, self._gif_delays)
def to_animation(self):
return Animation(list(self))
class GdkPixBufAnimationIterator(object):
def __init__(self, loader, anim_iter, start_time, gif_delays):
self._iter = anim_iter
self._first = True
self._time = start_time
self._loader = loader
self._gif_delays = gif_delays
self.delay_time = None
def __del__(self):
if self._iter is not None:
gdk.g_object_unref(self._iter)
# The pixbuf returned by the iter is owned by the iter, so no need to destroy that one
def __iter__(self):
return self
def __next__(self):
self._advance()
frame = self.get_frame()
if frame is None:
raise StopIteration
return frame
def _advance(self):
if not self._gif_delays:
raise StopIteration
self.delay_time = self._gif_delays.pop(0)
if self._first:
self._first = False
else:
if self.gdk_delay_time == -1:
raise StopIteration
else:
gdk_delay = self.gdk_delay_time * 1000 # milliseconds to microseconds
us = self._time.tv_usec + gdk_delay
self._time.tv_sec += us // 1000000
self._time.tv_usec = us % 1000000
gdkpixbuf.gdk_pixbuf_animation_iter_advance(self._iter, byref(self._time))
def get_frame(self):
pixbuf = gdkpixbuf.gdk_pixbuf_animation_iter_get_pixbuf(self._iter)
if pixbuf is None:
return None
image = GdkPixBuf(self._loader, pixbuf).to_image()
return AnimationFrame(image, self.delay_time)
@property
def gdk_delay_time(self):
assert self._iter is not None
return gdkpixbuf.gdk_pixbuf_animation_iter_get_delay_time(self._iter)
class GdkPixbuf2ImageDecoder(ImageDecoder):
def get_file_extensions(self):
return ['.png', '.xpm', '.jpg', '.jpeg', '.tif', '.tiff', '.pnm',
'.ras', '.bmp', '.gif']
def get_animation_file_extensions(self):
return ['.gif', '.ani']
def decode(self, file, filename):
loader = GdkPixBufLoader(file, filename)
return loader.get_pixbuf().to_image()
def decode_animation(self, file, filename):
loader = GdkPixBufLoader(file, filename)
return loader.get_animation().to_animation()
def get_decoders():
return [GdkPixbuf2ImageDecoder()]
def get_encoders():
return []
def init():
gdk.g_type_init()
init()
| 10,636 | 31.233333 | 94 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/pyglet/image/codecs/s3tc.py
|
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
# $Id:$
'''Software decoder for S3TC compressed texture (i.e., DDS).
http://oss.sgi.com/projects/ogl-sample/registry/EXT/texture_compression_s3tc.txt
'''
from __future__ import division
from builtins import range
import ctypes
import re
from pyglet.gl import *
from pyglet.gl import gl_info
from pyglet.image import AbstractImage, Texture
split_8byte = re.compile('.' * 8, flags=re.DOTALL)
split_16byte = re.compile('.' * 16, flags=re.DOTALL)
class PackedImageData(AbstractImage):
_current_texture = None
def __init__(self, width, height, format, packed_format, data):
super(PackedImageData, self).__init__(width, height)
self.format = format
self.packed_format = packed_format
self.data = data
def unpack(self):
if self.packed_format == GL_UNSIGNED_SHORT_5_6_5:
# Unpack to GL_RGB. Assume self.data is already 16-bit
i = 0
out = (ctypes.c_ubyte * (self.width * self.height * 3))()
for c in self.data:
out[i+2] = (c & 0x1f) << 3
out[i+1] = (c & 0x7e0) >> 3
out[i] = (c & 0xf800) >> 8
i += 3
self.data = out
self.packed_format = GL_UNSIGNED_BYTE
def _get_texture(self):
if self._current_texture:
return self._current_texture
texture = Texture.create_for_size(
GL_TEXTURE_2D, self.width, self.height)
glBindTexture(texture.target, texture.id)
glTexParameteri(texture.target, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
if not gl_info.have_version(1, 2) or True:
self.unpack()
glTexImage2D(texture.target, texture.level,
self.format, self.width, self.height, 0,
self.format, self.packed_format, self.data)
self._current_texture = texture
return texture
texture = property(_get_texture)
def get_texture(self, rectangle=False, force_rectangle=False):
'''The parameters 'rectangle' and 'force_rectangle' are ignored.
See the documentation of the method 'AbstractImage.get_texture' for
a more detailed documentation of the method. '''
return self._get_texture()
def decode_dxt1_rgb(data, width, height):
# Decode to 16-bit RGB UNSIGNED_SHORT_5_6_5
out = (ctypes.c_uint16 * (width * height))()
# Read 8 bytes at a time
image_offset = 0
for c0_lo, c0_hi, c1_lo, c1_hi, b0, b1, b2, b3 in split_8byte.findall(data):
color0 = ord(c0_lo) | ord(c0_hi) << 8
color1 = ord(c1_lo) | ord(c1_hi) << 8
bits = ord(b0) | ord(b1) << 8 | ord(b2) << 16 | ord(b3) << 24
r0 = color0 & 0x1f
g0 = (color0 & 0x7e0) >> 5
b0 = (color0 & 0xf800) >> 11
r1 = color1 & 0x1f
g1 = (color1 & 0x7e0) >> 5
b1 = (color1 & 0xf800) >> 11
# i is the dest ptr for this block
i = image_offset
for y in range(4):
for x in range(4):
code = bits & 0x3
if code == 0:
out[i] = color0
elif code == 1:
out[i] = color1
elif code == 3 and color0 <= color1:
out[i] = 0
else:
if code == 2 and color0 > color1:
r = (2 * r0 + r1) // 3
g = (2 * g0 + g1) // 3
b = (2 * b0 + b1) // 3
elif code == 3 and color0 > color1:
r = (r0 + 2 * r1) // 3
g = (g0 + 2 * g1) // 3
b = (b0 + 2 * b1) // 3
else:
assert code == 2 and color0 <= color1
r = (r0 + r1) // 2
g = (g0 + g1) // 2
b = (b0 + b1) // 2
out[i] = r | g << 5 | b << 11
bits >>= 2
i += 1
i += width - 4
# Move dest ptr to next 4x4 block
advance_row = (image_offset + 4) % width == 0
image_offset += width * 3 * advance_row + 4
return PackedImageData(width, height,
GL_RGB, GL_UNSIGNED_SHORT_5_6_5, out)
def decode_dxt1_rgba(data, width, height):
# Decode to GL_RGBA
out = (ctypes.c_ubyte * (width * height * 4))()
pitch = width << 2
# Read 8 bytes at a time
image_offset = 0
for c0_lo, c0_hi, c1_lo, c1_hi, b0, b1, b2, b3 in split_8byte.findall(data):
color0 = ord(c0_lo) | ord(c0_hi) << 8
color1 = ord(c1_lo) | ord(c1_hi) << 8
bits = ord(b0) | ord(b1) << 8 | ord(b2) << 16 | ord(b3) << 24
r0 = color0 & 0x1f
g0 = (color0 & 0x7e0) >> 5
b0 = (color0 & 0xf800) >> 11
r1 = color1 & 0x1f
g1 = (color1 & 0x7e0) >> 5
b1 = (color1 & 0xf800) >> 11
# i is the dest ptr for this block
i = image_offset
for y in range(4):
for x in range(4):
code = bits & 0x3
a = 255
if code == 0:
r, g, b = r0, g0, b0
elif code == 1:
r, g, b = r1, g1, b1
elif code == 3 and color0 <= color1:
r = g = b = a = 0
else:
if code == 2 and color0 > color1:
r = (2 * r0 + r1) // 3
g = (2 * g0 + g1) // 3
b = (2 * b0 + b1) // 3
elif code == 3 and color0 > color1:
r = (r0 + 2 * r1) // 3
g = (g0 + 2 * g1) // 3
b = (b0 + 2 * b1) // 3
else:
assert code == 2 and color0 <= color1
r = (r0 + r1) // 2
g = (g0 + g1) // 2
b = (b0 + b1) // 2
out[i] = b << 3
out[i+1] = g << 2
out[i+2] = r << 3
out[i+3] = a << 4
bits >>= 2
i += 4
i += pitch - 16
# Move dest ptr to next 4x4 block
advance_row = (image_offset + 16) % pitch == 0
image_offset += pitch * 3 * advance_row + 16
return PackedImageData(width, height, GL_RGBA, GL_UNSIGNED_BYTE, out)
def decode_dxt3(data, width, height):
# Decode to GL_RGBA
out = (ctypes.c_ubyte * (width * height * 4))()
pitch = width << 2
# Read 16 bytes at a time
image_offset = 0
for (a0, a1, a2, a3, a4, a5, a6, a7,
c0_lo, c0_hi, c1_lo, c1_hi,
b0, b1, b2, b3) in split_16byte.findall(data):
color0 = ord(c0_lo) | ord(c0_hi) << 8
color1 = ord(c1_lo) | ord(c1_hi) << 8
bits = ord(b0) | ord(b1) << 8 | ord(b2) << 16 | ord(b3) << 24
alpha = ord(a0) | ord(a1) << 8 | ord(a2) << 16 | ord(a3) << 24 | \
ord(a4) << 32 | ord(a5) << 40 | ord(a6) << 48 | ord(a7) << 56
r0 = color0 & 0x1f
g0 = (color0 & 0x7e0) >> 5
b0 = (color0 & 0xf800) >> 11
r1 = color1 & 0x1f
g1 = (color1 & 0x7e0) >> 5
b1 = (color1 & 0xf800) >> 11
# i is the dest ptr for this block
i = image_offset
for y in range(4):
for x in range(4):
code = bits & 0x3
a = alpha & 0xf
if code == 0:
r, g, b = r0, g0, b0
elif code == 1:
r, g, b = r1, g1, b1
elif code == 3 and color0 <= color1:
r = g = b = 0
else:
if code == 2 and color0 > color1:
r = (2 * r0 + r1) // 3
g = (2 * g0 + g1) // 3
b = (2 * b0 + b1) // 3
elif code == 3 and color0 > color1:
r = (r0 + 2 * r1) // 3
g = (g0 + 2 * g1) // 3
b = (b0 + 2 * b1) // 3
else:
assert code == 2 and color0 <= color1
r = (r0 + r1) // 2
g = (g0 + g1) // 2
b = (b0 + b1) // 2
out[i] = b << 3
out[i+1] = g << 2
out[i+2] = r << 3
out[i+3] = a << 4
bits >>= 2
alpha >>= 4
i += 4
i += pitch - 16
# Move dest ptr to next 4x4 block
advance_row = (image_offset + 16) % pitch == 0
image_offset += pitch * 3 * advance_row + 16
return PackedImageData(width, height, GL_RGBA, GL_UNSIGNED_BYTE, out)
def decode_dxt5(data, width, height):
# Decode to GL_RGBA
out = (ctypes.c_ubyte * (width * height * 4))()
pitch = width << 2
# Read 16 bytes at a time
image_offset = 0
for (alpha0, alpha1, ab0, ab1, ab2, ab3, ab4, ab5,
c0_lo, c0_hi, c1_lo, c1_hi,
b0, b1, b2, b3) in split_16byte.findall(data):
color0 = ord(c0_lo) | ord(c0_hi) << 8
color1 = ord(c1_lo) | ord(c1_hi) << 8
alpha0 = ord(alpha0)
alpha1 = ord(alpha1)
bits = ord(b0) | ord(b1) << 8 | ord(b2) << 16 | ord(b3) << 24
abits = ord(ab0) | ord(ab1) << 8 | ord(ab2) << 16 | ord(ab3) << 24 | \
ord(ab4) << 32 | ord(ab5) << 40
r0 = color0 & 0x1f
g0 = (color0 & 0x7e0) >> 5
b0 = (color0 & 0xf800) >> 11
r1 = color1 & 0x1f
g1 = (color1 & 0x7e0) >> 5
b1 = (color1 & 0xf800) >> 11
# i is the dest ptr for this block
i = image_offset
for y in range(4):
for x in range(4):
code = bits & 0x3
acode = abits & 0x7
if code == 0:
r, g, b = r0, g0, b0
elif code == 1:
r, g, b = r1, g1, b1
elif code == 3 and color0 <= color1:
r = g = b = 0
else:
if code == 2 and color0 > color1:
r = (2 * r0 + r1) // 3
g = (2 * g0 + g1) // 3
b = (2 * b0 + b1) // 3
elif code == 3 and color0 > color1:
r = (r0 + 2 * r1) // 3
g = (g0 + 2 * g1) // 3
b = (b0 + 2 * b1) // 3
else:
assert code == 2 and color0 <= color1
r = (r0 + r1) / 2
g = (g0 + g1) / 2
b = (b0 + b1) / 2
if acode == 0:
a = alpha0
elif acode == 1:
a = alpha1
elif alpha0 > alpha1:
if acode == 2:
a = (6 * alpha0 + 1 * alpha1) // 7
elif acode == 3:
a = (5 * alpha0 + 2 * alpha1) // 7
elif acode == 4:
a = (4 * alpha0 + 3 * alpha1) // 7
elif acode == 5:
a = (3 * alpha0 + 4 * alpha1) // 7
elif acode == 6:
a = (2 * alpha0 + 5 * alpha1) // 7
else:
assert acode == 7
a = (1 * alpha0 + 6 * alpha1) // 7
else:
if acode == 2:
a = (4 * alpha0 + 1 * alpha1) // 5
elif acode == 3:
a = (3 * alpha0 + 2 * alpha1) // 5
elif acode == 4:
a = (2 * alpha0 + 3 * alpha1) // 5
elif acode == 5:
a = (1 * alpha0 + 4 * alpha1) // 5
elif acode == 6:
a = 0
else:
assert acode == 7
a = 255
out[i] = b << 3
out[i+1] = g << 2
out[i+2] = r << 3
out[i+3] = a
bits >>= 2
abits >>= 3
i += 4
i += pitch - 16
# Move dest ptr to next 4x4 block
advance_row = (image_offset + 16) % pitch == 0
image_offset += pitch * 3 * advance_row + 16
return PackedImageData(width, height, GL_RGBA, GL_UNSIGNED_BYTE, out)
| 14,203 | 35.420513 | 80 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/pyglet/image/codecs/quartz.py
|
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
'''
'''
from builtins import range
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
from pyglet.image import ImageData, Animation, AnimationFrame
from pyglet.image.codecs import *
from pyglet.libs.darwin.cocoapy import *
class QuartzImageDecoder(ImageDecoder):
def get_file_extensions(self):
# Quartz can actually decode many more formats, but these are the most common.
return [ '.bmp', '.cur', '.gif', '.ico', '.jp2', '.jpg', '.jpeg',
'.pcx', '.png', '.tga', '.tif', '.tiff', '.xbm', '.xpm' ]
def get_animation_file_extensions(self):
return ['.gif']
def _get_pyglet_ImageData_from_source_at_index(self, sourceRef, index):
imageRef = c_void_p(quartz.CGImageSourceCreateImageAtIndex(sourceRef, index, None))
# Regardless of the internal format of the image (L, LA, RGB, RGBA, etc)
# we just automatically convert everything to an RGBA format.
format = 'RGBA'
rgbColorSpace = c_void_p(quartz.CGColorSpaceCreateDeviceRGB())
bitsPerComponent = 8
width = quartz.CGImageGetWidth(imageRef)
height = quartz.CGImageGetHeight(imageRef)
bytesPerRow = 4 * width
# Create a buffer to store the RGBA formatted data.
bufferSize = height * bytesPerRow
buffer = (c_ubyte * bufferSize)()
# Create a bitmap context for the RGBA formatted data.
# Note that premultiplied alpha is required:
# http://developer.apple.com/library/mac/#qa/qa1037/_index.html
bitmap = c_void_p(quartz.CGBitmapContextCreate(buffer,
width, height,
bitsPerComponent,
bytesPerRow,
rgbColorSpace,
kCGImageAlphaPremultipliedLast))
# Write the image data into the bitmap.
quartz.CGContextDrawImage(bitmap, NSMakeRect(0,0,width,height), imageRef)
quartz.CGImageRelease(imageRef)
quartz.CGContextRelease(bitmap)
quartz.CGColorSpaceRelease(rgbColorSpace)
pitch = bytesPerRow
return ImageData(width, height, format, buffer, -pitch)
def decode(self, file, filename):
file_bytes = file.read()
data = c_void_p(cf.CFDataCreate(None, file_bytes, len(file_bytes)))
# Second argument is an options dictionary. It might be a good idea to provide
# a value for kCGImageSourceTypeIdentifierHint here using filename extension.
sourceRef = c_void_p(quartz.CGImageSourceCreateWithData(data, None))
image = self._get_pyglet_ImageData_from_source_at_index(sourceRef, 0)
cf.CFRelease(data)
cf.CFRelease(sourceRef)
return image
def decode_animation(self, file, filename):
# If file is not an animated GIF, it will be loaded as a single-frame animation.
file_bytes = file.read()
data = c_void_p(cf.CFDataCreate(None, file_bytes, len(file_bytes)))
sourceRef = c_void_p(quartz.CGImageSourceCreateWithData(data, None))
# Get number of frames in the animation.
count = quartz.CGImageSourceGetCount(sourceRef)
frames = []
for index in range(count):
# Try to determine frame duration from GIF properties dictionary.
duration = 0.1 # default duration if none found
props = c_void_p(quartz.CGImageSourceCopyPropertiesAtIndex(sourceRef, index, None))
if cf.CFDictionaryContainsKey(props, kCGImagePropertyGIFDictionary):
gif_props = c_void_p(cf.CFDictionaryGetValue(props, kCGImagePropertyGIFDictionary))
if cf.CFDictionaryContainsKey(gif_props, kCGImagePropertyGIFDelayTime):
duration = cfnumber_to_number(c_void_p(cf.CFDictionaryGetValue(gif_props, kCGImagePropertyGIFDelayTime)))
cf.CFRelease(props)
image = self._get_pyglet_ImageData_from_source_at_index(sourceRef, index)
frames.append( AnimationFrame(image, duration) )
cf.CFRelease(data)
cf.CFRelease(sourceRef)
return Animation(frames)
def get_decoders():
return [ QuartzImageDecoder() ]
def get_encoders():
return []
| 6,155 | 42.659574 | 125 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/pyglet/image/codecs/bmp.py
|
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
'''Decoder for BMP files.
Currently supports version 3 and 4 bitmaps with BI_RGB and BI_BITFIELDS
encoding. Alpha channel is supported for 32-bit BI_RGB only.
'''
from builtins import range
# Official docs are at
# http://msdn2.microsoft.com/en-us/library/ms532311.aspx
#
# But some details including alignment and bit/byte order are omitted; see
# http://www.fileformat.info/format/bmp/egff.htm
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import ctypes
from pyglet.image import ImageData
from pyglet.image.codecs import ImageDecoder, ImageDecodeException
BYTE = ctypes.c_ubyte
WORD = ctypes.c_uint16
DWORD = ctypes.c_uint32
LONG = ctypes.c_int32
FXPT2DOT30 = ctypes.c_uint32
BI_RGB = 0
BI_RLE8 = 1
BI_RLE4 = 2
BI_BITFIELDS = 3
class BITMAPFILEHEADER(ctypes.LittleEndianStructure):
_pack_ = 1
_fields_ = [
('bfType', WORD),
('bfSize', DWORD),
('bfReserved1', WORD),
('bfReserved2', WORD),
('bfOffBits', DWORD)
]
class BITMAPINFOHEADER(ctypes.LittleEndianStructure):
_pack_ = 1
_fields_ = [
('biSize', DWORD),
('biWidth', LONG),
('biHeight', LONG),
('biPlanes', WORD),
('biBitCount', WORD),
('biCompression', DWORD),
('biSizeImage', DWORD),
('biXPelsPerMeter', LONG),
('biYPelsPerMeter', LONG),
('biClrUsed', DWORD),
('biClrImportant', DWORD)
]
CIEXYZTRIPLE = FXPT2DOT30 * 9
class BITMAPV4HEADER(ctypes.LittleEndianStructure):
_pack_ = 1
_fields_ = [
('biSize', DWORD),
('biWidth', LONG),
('biHeight', LONG),
('biPlanes', WORD),
('biBitCount', WORD),
('biCompression', DWORD),
('biSizeImage', DWORD),
('biXPelsPerMeter', LONG),
('biYPelsPerMeter', LONG),
('biClrUsed', DWORD),
('biClrImportant', DWORD),
('bV4RedMask', DWORD),
('bV4GreenMask', DWORD),
('bV4BlueMask', DWORD),
('bV4AlphaMask', DWORD),
('bV4CSType', DWORD),
('bV4Endpoints', CIEXYZTRIPLE),
('bV4GammaRed', DWORD),
('bV4GammaGreen', DWORD),
('bV4GammaBlue', DWORD),
]
class RGBFields(ctypes.LittleEndianStructure):
_pack_ = 1
_fields_ = [
('red', DWORD),
('green', DWORD),
('blue', DWORD),
]
class RGBQUAD(ctypes.LittleEndianStructure):
_pack_ = 1
_fields_ = [
('rgbBlue', BYTE),
('rgbGreen', BYTE),
('rgbRed', BYTE),
('rgbReserved', BYTE)
]
def __repr__(self):
return '<%d, %d, %d>' % (self.rgbRed, self.rgbGreen, self.rgbBlue)
def ptr_add(ptr, offset):
address = ctypes.addressof(ptr.contents) + offset
return ctypes.pointer(type(ptr.contents).from_address(address))
def to_ctypes(buffer, offset, type):
if offset + ctypes.sizeof(type) > len(buffer):
raise ImageDecodeException('BMP file is truncated')
ptr = ptr_add(ctypes.pointer(buffer), offset)
return ctypes.cast(ptr, ctypes.POINTER(type)).contents
class BMPImageDecoder(ImageDecoder):
def get_file_extensions(self):
return ['.bmp']
def decode(self, file, filename):
if not file:
file = open(filename, 'rb')
bytes = file.read()
buffer = ctypes.c_buffer(bytes)
if bytes[:2] != b'BM':
raise ImageDecodeException(
'Not a Windows bitmap file: %r' % (filename or file))
file_header = to_ctypes(buffer, 0, BITMAPFILEHEADER)
bits_offset = file_header.bfOffBits
info_header_offset = ctypes.sizeof(BITMAPFILEHEADER)
info_header = to_ctypes(buffer, info_header_offset, BITMAPINFOHEADER)
palette_offset = info_header_offset + info_header.biSize
if info_header.biSize < ctypes.sizeof(BITMAPINFOHEADER):
raise ImageDecodeException(
'Unsupported BMP type: %r' % (filename or file))
width = info_header.biWidth
height = info_header.biHeight
if width <= 0 or info_header.biPlanes != 1:
raise ImageDecodeException(
'BMP file has corrupt parameters: %r' % (filename or file))
pitch_sign = height < 0 and -1 or 1
height = abs(height)
compression = info_header.biCompression
if compression not in (BI_RGB, BI_BITFIELDS):
raise ImageDecodeException(
'Unsupported compression: %r' % (filename or file))
clr_used = 0
bitcount = info_header.biBitCount
if bitcount == 1:
pitch = (width + 7) // 8
bits_type = ctypes.c_ubyte
decoder = decode_1bit
elif bitcount == 4:
pitch = (width + 1) // 2
bits_type = ctypes.c_ubyte
decoder = decode_4bit
elif bitcount == 8:
bits_type = ctypes.c_ubyte
pitch = width
decoder = decode_8bit
elif bitcount == 16:
pitch = width * 2
bits_type = ctypes.c_uint16
decoder = decode_bitfields
elif bitcount == 24:
pitch = width * 3
bits_type = ctypes.c_ubyte
decoder = decode_24bit
elif bitcount == 32:
pitch = width * 4
if compression == BI_RGB:
decoder = decode_32bit_rgb
bits_type = ctypes.c_ubyte
elif compression == BI_BITFIELDS:
decoder = decode_bitfields
bits_type = ctypes.c_uint32
else:
raise ImageDecodeException(
'Unsupported compression: %r' % (filename or file))
else:
raise ImageDecodeException(
'Unsupported bit count %d: %r' % (bitcount, filename or file))
pitch = (pitch + 3) & ~3
packed_width = pitch // ctypes.sizeof(bits_type)
if bitcount < 16 and compression == BI_RGB:
clr_used = info_header.biClrUsed or (1 << bitcount)
palette = to_ctypes(buffer, palette_offset, RGBQUAD * clr_used)
bits = to_ctypes(buffer, bits_offset,
bits_type * packed_width * height)
return decoder(bits, palette, width, height, pitch, pitch_sign)
elif bitcount >= 16 and compression == BI_RGB:
bits = to_ctypes(buffer, bits_offset,
bits_type * (packed_width * height))
return decoder(bits, None, width, height, pitch, pitch_sign)
elif compression == BI_BITFIELDS:
if info_header.biSize >= ctypes.sizeof(BITMAPV4HEADER):
info_header = to_ctypes(buffer, info_header_offset,
BITMAPV4HEADER)
r_mask = info_header.bV4RedMask
g_mask = info_header.bV4GreenMask
b_mask = info_header.bV4BlueMask
else:
fields_offset = info_header_offset + \
ctypes.sizeof(BITMAPINFOHEADER)
fields = to_ctypes(buffer, fields_offset, RGBFields)
r_mask = fields.red
g_mask = fields.green
b_mask = fields.blue
class _BitsArray(ctypes.LittleEndianStructure):
_pack_ = 1
_fields_ = [
('data', bits_type * packed_width * height),
]
bits = to_ctypes(buffer, bits_offset, _BitsArray).data
return decoder(bits, r_mask, g_mask, b_mask,
width, height, pitch, pitch_sign)
def decode_1bit(bits, palette, width, height, pitch, pitch_sign):
rgb_pitch = (((pitch << 3) + 7) & ~0x7) * 3
buffer = (ctypes.c_ubyte * (height * rgb_pitch))()
i = 0
for row in bits:
for packed in row:
for _ in range(8):
rgb = palette[(packed & 0x80) >> 7]
buffer[i] = rgb.rgbRed
buffer[i + 1] = rgb.rgbGreen
buffer[i + 2] = rgb.rgbBlue
i += 3
packed <<= 1
return ImageData(width, height, 'RGB', buffer, pitch_sign * rgb_pitch)
def decode_4bit(bits, palette, width, height, pitch, pitch_sign):
rgb_pitch = (((pitch << 1) + 1) & ~0x1) * 3
buffer = (ctypes.c_ubyte * (height * rgb_pitch))()
i = 0
for row in bits:
for packed in row:
for index in ((packed & 0xf0) >> 4, packed & 0xf):
rgb = palette[index]
buffer[i] = rgb.rgbRed
buffer[i + 1] = rgb.rgbGreen
buffer[i + 2] = rgb.rgbBlue
i += 3
return ImageData(width, height, 'RGB', buffer, pitch_sign * rgb_pitch)
def decode_8bit(bits, palette, width, height, pitch, pitch_sign):
rgb_pitch = pitch * 3
buffer = (ctypes.c_ubyte * (height * rgb_pitch))()
i = 0
for row in bits:
for index in row:
rgb = palette[index]
buffer[i] = rgb.rgbRed
buffer[i + 1] = rgb.rgbGreen
buffer[i + 2] = rgb.rgbBlue
i += 3
return ImageData(width, height, 'RGB', buffer, pitch_sign * rgb_pitch)
def decode_24bit(bits, palette, width, height, pitch, pitch_sign):
buffer = (ctypes.c_ubyte * (height * pitch))()
ctypes.memmove(buffer, bits, len(buffer))
return ImageData(width, height, 'BGR', buffer, pitch_sign * pitch)
def decode_32bit_rgb(bits, palette, width, height, pitch, pitch_sign):
buffer = (ctypes.c_ubyte * (height * pitch))()
ctypes.memmove(buffer, bits, len(buffer))
return ImageData(width, height, 'BGRA', buffer, pitch_sign * pitch)
def get_shift(mask):
if not mask:
return 0
# Shift down
shift = 0
while not (1 << shift) & mask:
shift += 1
# Shift up
shift_up = 0
while (mask >> shift) >> shift_up:
shift_up += 1
s = shift - (8 - shift_up)
if s < 0:
return 0, -s
else:
return s, 0
def decode_bitfields(bits, r_mask, g_mask, b_mask,
width, height, pitch, pitch_sign):
r_shift1, r_shift2 = get_shift(r_mask)
g_shift1, g_shift2 = get_shift(g_mask)
b_shift1, b_shift2 = get_shift(b_mask)
rgb_pitch = 3 * len(bits[0])
buffer = (ctypes.c_ubyte * (height * rgb_pitch))()
i = 0
for row in bits:
for packed in row:
buffer[i] = (packed & r_mask) >> r_shift1 << r_shift2
buffer[i+1] = (packed & g_mask) >> g_shift1 << g_shift2
buffer[i+2] = (packed & b_mask) >> b_shift1 << b_shift2
i += 3
return ImageData(width, height, 'RGB', buffer, pitch_sign * rgb_pitch)
def get_decoders():
return [BMPImageDecoder()]
def get_encoders():
return []
| 12,445 | 33.476454 | 78 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/pyglet/image/codecs/gdiplus.py
|
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
'''
'''
from __future__ import division
from builtins import range
__docformat__ = 'restructuredtext'
__version__ = '$Id: pil.py 163 2006-11-13 04:15:46Z Alex.Holkner $'
from ctypes import *
from pyglet.com import IUnknown
from pyglet.gl import *
from pyglet.image import *
from pyglet.image.codecs import *
from pyglet.libs.win32.constants import *
from pyglet.libs.win32.types import *
from pyglet.libs.win32 import _kernel32 as kernel32
ole32 = windll.ole32
gdiplus = windll.gdiplus
LPSTREAM = c_void_p
REAL = c_float
PixelFormat1bppIndexed = 196865
PixelFormat4bppIndexed = 197634
PixelFormat8bppIndexed = 198659
PixelFormat16bppGrayScale = 1052676
PixelFormat16bppRGB555 = 135173
PixelFormat16bppRGB565 = 135174
PixelFormat16bppARGB1555 = 397319
PixelFormat24bppRGB = 137224
PixelFormat32bppRGB = 139273
PixelFormat32bppARGB = 2498570
PixelFormat32bppPARGB = 925707
PixelFormat48bppRGB = 1060876
PixelFormat64bppARGB = 3424269
PixelFormat64bppPARGB = 29622286
PixelFormatMax = 15
ImageLockModeRead = 1
ImageLockModeWrite = 2
ImageLockModeUserInputBuf = 4
class GdiplusStartupInput(Structure):
_fields_ = [
('GdiplusVersion', c_uint32),
('DebugEventCallback', c_void_p),
('SuppressBackgroundThread', BOOL),
('SuppressExternalCodecs', BOOL)
]
class GdiplusStartupOutput(Structure):
_fields = [
('NotificationHookProc', c_void_p),
('NotificationUnhookProc', c_void_p)
]
class BitmapData(Structure):
_fields_ = [
('Width', c_uint),
('Height', c_uint),
('Stride', c_int),
('PixelFormat', c_int),
('Scan0', POINTER(c_byte)),
('Reserved', POINTER(c_uint))
]
class Rect(Structure):
_fields_ = [
('X', c_int),
('Y', c_int),
('Width', c_int),
('Height', c_int)
]
PropertyTagFrameDelay = 0x5100
class PropertyItem(Structure):
_fields_ = [
('id', c_uint),
('length', c_ulong),
('type', c_short),
('value', c_void_p)
]
INT_PTR = POINTER(INT)
UINT_PTR = POINTER(UINT)
ole32.CreateStreamOnHGlobal.argtypes = [HGLOBAL, BOOL, LPSTREAM]
gdiplus.GdipBitmapLockBits.restype = c_int
gdiplus.GdipBitmapLockBits.argtypes = [c_void_p, c_void_p, UINT, c_int, c_void_p]
gdiplus.GdipBitmapUnlockBits.restype = c_int
gdiplus.GdipBitmapUnlockBits.argtypes = [c_void_p, c_void_p]
gdiplus.GdipCloneStringFormat.restype = c_int
gdiplus.GdipCloneStringFormat.argtypes = [c_void_p, c_void_p]
gdiplus.GdipCreateBitmapFromScan0.restype = c_int
gdiplus.GdipCreateBitmapFromScan0.argtypes = [c_int, c_int, c_int, c_int, POINTER(BYTE), c_void_p]
gdiplus.GdipCreateBitmapFromStream.restype = c_int
gdiplus.GdipCreateBitmapFromStream.argtypes = [c_void_p, c_void_p]
gdiplus.GdipCreateFont.restype = c_int
gdiplus.GdipCreateFont.argtypes = [c_void_p, REAL, INT, c_int, c_void_p]
gdiplus.GdipCreateFontFamilyFromName.restype = c_int
gdiplus.GdipCreateFontFamilyFromName.argtypes = [c_wchar_p, c_void_p, c_void_p]
gdiplus.GdipCreateMatrix.restype = None
gdiplus.GdipCreateMatrix.argtypes = [c_void_p]
gdiplus.GdipCreateSolidFill.restype = c_int
gdiplus.GdipCreateSolidFill.argtypes = [c_int, c_void_p] # ARGB
gdiplus.GdipDisposeImage.restype = c_int
gdiplus.GdipDisposeImage.argtypes = [c_void_p]
gdiplus.GdipDrawString.restype = c_int
gdiplus.GdipDrawString.argtypes = [c_void_p, c_wchar_p, c_int, c_void_p, c_void_p, c_void_p, c_void_p]
gdiplus.GdipGetFamilyName.restype = c_int
gdiplus.GdipGetFamilyName.argtypes = [c_void_p, c_wchar_p, c_wchar]
gdiplus.GdipFlush.restype = c_int
gdiplus.GdipFlush.argtypes = [c_void_p, c_int]
gdiplus.GdipGetFontCollectionFamilyCount.restype = c_int
gdiplus.GdipGetFontCollectionFamilyCount.argtypes = [c_void_p, INT_PTR]
gdiplus.GdipGetFontCollectionFamilyList.restype = c_int
gdiplus.GdipGetFontCollectionFamilyList.argtypes = [c_void_p, INT, c_void_p, INT_PTR]
gdiplus.GdipGetImageDimension.restype = c_int
gdiplus.GdipGetImageDimension.argtypes = [c_void_p, POINTER(REAL), POINTER(REAL)]
gdiplus.GdipGetImageGraphicsContext.restype = c_int
gdiplus.GdipGetImageGraphicsContext.argtypes = [c_void_p, c_void_p]
gdiplus.GdipGetImagePixelFormat.restype = c_int
gdiplus.GdipGetImagePixelFormat.argtypes = [c_void_p, c_void_p]
gdiplus.GdipGetPropertyItem.restype = c_int
gdiplus.GdipGetPropertyItem.argtypes = [c_void_p, c_uint, c_uint, c_void_p]
gdiplus.GdipGetPropertyItemSize.restype = c_int
gdiplus.GdipGetPropertyItemSize.argtypes = [c_void_p, c_uint, UINT_PTR]
gdiplus.GdipGraphicsClear.restype = c_int
gdiplus.GdipGraphicsClear.argtypes = [c_void_p, c_int] # ARGB
gdiplus.GdipImageGetFrameCount.restype = c_int
gdiplus.GdipImageGetFrameCount.argtypes = [c_void_p, c_void_p, UINT_PTR]
gdiplus.GdipImageGetFrameDimensionsCount.restype = c_int
gdiplus.GdipImageGetFrameDimensionsCount.argtypes = [c_void_p, UINT_PTR]
gdiplus.GdipImageGetFrameDimensionsList.restype = c_int
gdiplus.GdipImageGetFrameDimensionsList.argtypes = [c_void_p, c_void_p, UINT]
gdiplus.GdipImageSelectActiveFrame.restype = c_int
gdiplus.GdipImageSelectActiveFrame.argtypes = [c_void_p, c_void_p, UINT]
gdiplus.GdipMeasureString.restype = c_int
gdiplus.GdipMeasureString.argtypes = [c_void_p, c_wchar_p, c_int, c_void_p, c_void_p, c_void_p, c_void_p, INT_PTR, INT_PTR]
gdiplus.GdipNewPrivateFontCollection.restype = c_int
gdiplus.GdipNewPrivateFontCollection.argtypes = [c_void_p]
gdiplus.GdipPrivateAddMemoryFont.restype = c_int
gdiplus.GdipPrivateAddMemoryFont.argtypes = [c_void_p, c_void_p, c_int]
gdiplus.GdipSetPageUnit.restype = c_int
gdiplus.GdipSetPageUnit.argtypes = [c_void_p, c_int]
gdiplus.GdipSetStringFormatFlags.restype = c_int
gdiplus.GdipSetStringFormatFlags.argtypes = [c_void_p, c_int]
gdiplus.GdipSetTextRenderingHint.restype = c_int
gdiplus.GdipSetTextRenderingHint.argtypes = [c_void_p, c_int]
gdiplus.GdipStringFormatGetGenericTypographic.restype = c_int
gdiplus.GdipStringFormatGetGenericTypographic.argtypes = [c_void_p]
gdiplus.GdiplusShutdown.restype = None
gdiplus.GdiplusShutdown.argtypes = [POINTER(ULONG)]
gdiplus.GdiplusStartup.restype = c_int
gdiplus.GdiplusStartup.argtypes = [c_void_p, c_void_p, c_void_p]
class GDIPlusDecoder(ImageDecoder):
def get_file_extensions(self):
return ['.bmp', '.gif', '.jpg', '.jpeg', '.exif', '.png', '.tif',
'.tiff']
def get_animation_file_extensions(self):
# TIFF also supported as a multi-page image; but that's not really an
# animation, is it?
return ['.gif']
def _load_bitmap(self, file, filename):
data = file.read()
# Create a HGLOBAL with image data
hglob = kernel32.GlobalAlloc(GMEM_MOVEABLE, len(data))
ptr = kernel32.GlobalLock(hglob)
memmove(ptr, data, len(data))
kernel32.GlobalUnlock(hglob)
# Create IStream for the HGLOBAL
self.stream = IUnknown()
ole32.CreateStreamOnHGlobal(hglob, True, byref(self.stream))
# Load image from stream
bitmap = c_void_p()
status = gdiplus.GdipCreateBitmapFromStream(self.stream, byref(bitmap))
if status != 0:
self.stream.Release()
raise ImageDecodeException(
'GDI+ cannot load %r' % (filename or file))
return bitmap
def _get_image(self, bitmap):
# Get size of image (Bitmap subclasses Image)
width = REAL()
height = REAL()
gdiplus.GdipGetImageDimension(bitmap, byref(width), byref(height))
width = int(width.value)
height = int(height.value)
# Get image pixel format
pf = c_int()
gdiplus.GdipGetImagePixelFormat(bitmap, byref(pf))
pf = pf.value
# Reverse from what's documented because of Intel little-endianness.
format = 'BGRA'
if pf == PixelFormat24bppRGB:
format = 'BGR'
elif pf == PixelFormat32bppRGB:
pass
elif pf == PixelFormat32bppARGB:
pass
elif pf in (PixelFormat16bppARGB1555, PixelFormat32bppPARGB,
PixelFormat64bppARGB, PixelFormat64bppPARGB):
pf = PixelFormat32bppARGB
else:
format = 'BGR'
pf = PixelFormat24bppRGB
# Lock pixel data in best format
rect = Rect()
rect.X = 0
rect.Y = 0
rect.Width = width
rect.Height = height
bitmap_data = BitmapData()
gdiplus.GdipBitmapLockBits(bitmap,
byref(rect), ImageLockModeRead, pf, byref(bitmap_data))
# Create buffer for RawImage
buffer = create_string_buffer(bitmap_data.Stride * height)
memmove(buffer, bitmap_data.Scan0, len(buffer))
# Unlock data
gdiplus.GdipBitmapUnlockBits(bitmap, byref(bitmap_data))
return ImageData(width, height, format, buffer, -bitmap_data.Stride)
def _delete_bitmap(self, bitmap):
# Release image and stream
gdiplus.GdipDisposeImage(bitmap)
self.stream.Release()
def decode(self, file, filename):
bitmap = self._load_bitmap(file, filename)
image = self._get_image(bitmap)
self._delete_bitmap(bitmap)
return image
def decode_animation(self, file, filename):
bitmap = self._load_bitmap(file, filename)
dimension_count = c_uint()
gdiplus.GdipImageGetFrameDimensionsCount(bitmap, byref(dimension_count))
if dimension_count.value < 1:
self._delete_bitmap(bitmap)
raise ImageDecodeException('Image has no frame dimensions')
# XXX Make sure this dimension is time?
dimensions = (c_void_p * dimension_count.value)()
gdiplus.GdipImageGetFrameDimensionsList(bitmap, dimensions,
dimension_count.value)
frame_count = c_uint()
gdiplus.GdipImageGetFrameCount(bitmap, dimensions, byref(frame_count))
prop_id = PropertyTagFrameDelay
prop_size = c_uint()
gdiplus.GdipGetPropertyItemSize(bitmap, prop_id, byref(prop_size))
prop_buffer = c_buffer(prop_size.value)
prop_item = cast(prop_buffer, POINTER(PropertyItem)).contents
gdiplus.GdipGetPropertyItem(bitmap, prop_id, prop_size.value,
prop_buffer)
n_delays = prop_item.length // sizeof(c_long)
delays = cast(prop_item.value, POINTER(c_long * n_delays)).contents
frames = []
for i in range(frame_count.value):
gdiplus.GdipImageSelectActiveFrame(bitmap, dimensions, i)
image = self._get_image(bitmap)
delay = delays[i]
if delay <= 1:
delay = 10
frames.append(AnimationFrame(image, delay/100.))
self._delete_bitmap(bitmap)
return Animation(frames)
def get_decoders():
return [GDIPlusDecoder()]
def get_encoders():
return []
def init():
token = c_ulong()
startup_in = GdiplusStartupInput()
startup_in.GdiplusVersion = 1
startup_out = GdiplusStartupOutput()
gdiplus.GdiplusStartup(byref(token), byref(startup_in), byref(startup_out))
# Shutdown later?
# gdiplus.GdiplusShutdown(token)
init()
| 12,975 | 36.180516 | 123 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/pyglet/image/codecs/pil.py
|
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
'''
'''
from __future__ import absolute_import
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import os.path
from pyglet.gl import *
from pyglet.image import *
from pyglet.image.codecs import *
try:
import Image
except ImportError:
from PIL import Image
class PILImageDecoder(ImageDecoder):
def get_file_extensions(self):
# Only most common ones shown here
return ['.bmp', '.cur', '.gif', '.ico', '.jpg', '.jpeg', '.pcx', '.png',
'.tga', '.tif', '.tiff', '.xbm', '.xpm']
def decode(self, file, filename):
try:
image = Image.open(file)
except Exception as e:
raise ImageDecodeException(
'PIL cannot read %r: %s' % (filename or file, e))
try:
image = image.transpose(Image.FLIP_TOP_BOTTOM)
except Exception as e:
raise ImageDecodeException(
'PIL failed to transpose %r: %s' % (filename or file, e))
# Convert bitmap and palette images to component
if image.mode in ('1', 'P'):
image = image.convert()
if image.mode not in ('L', 'LA', 'RGB', 'RGBA'):
raise ImageDecodeException('Unsupported mode "%s"' % image.mode)
type = GL_UNSIGNED_BYTE
width, height = image.size
# tostring is deprecated, replaced by tobytes in Pillow (PIL fork)
# (1.1.7) PIL still uses it
image_data_fn = getattr(image, "tobytes", getattr(image, "tostring"))
return ImageData(width, height, image.mode, image_data_fn())
class PILImageEncoder(ImageEncoder):
def get_file_extensions(self):
# Most common only
return ['.bmp', '.eps', '.gif', '.jpg', '.jpeg',
'.pcx', '.png', '.ppm', '.tiff', '.xbm']
def encode(self, image, file, filename):
# File format is guessed from filename extension, otherwise defaults
# to PNG.
pil_format = (filename and os.path.splitext(filename)[1][1:]) or 'png'
if pil_format.lower() == 'jpg':
pil_format = 'JPEG'
image = image.get_image_data()
format = image.format
if format != 'RGB':
# Only save in RGB or RGBA formats.
format = 'RGBA'
pitch = -(image.width * len(format))
# fromstring is deprecated, replaced by frombytes in Pillow (PIL fork)
# (1.1.7) PIL still uses it
image_from_fn = getattr(Image, "frombytes", getattr(Image, "fromstring"))
pil_image = image_from_fn(
format, (image.width, image.height), image.get_data(format, pitch))
try:
pil_image.save(file, pil_format)
except Exception as e:
raise ImageEncodeException(e)
def get_decoders():
return [PILImageDecoder()]
def get_encoders():
return [PILImageEncoder()]
| 4,560 | 35.782258 | 81 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/pyglet/image/codecs/gif.py
|
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
'''Read GIF control data.
http://www.w3.org/Graphics/GIF/spec-gif89a.txt
'''
from __future__ import print_function
from __future__ import division
from builtins import object
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import struct
from pyglet.image.codecs import ImageDecodeException
class GIFStream(object):
def __init__(self):
self.images = []
class GIFImage(object):
delay = None
class GraphicsScope(object):
delay = None
# Appendix A.
LABEL_EXTENSION_INTRODUCER = 0x21
LABEL_GRAPHIC_CONTROL_EXTENSION = 0xf9
LABEL_IMAGE_DESCRIPTOR = 0x2c
LABEL_TRAILER = 0x3b
def unpack(format, file):
size = struct.calcsize(format)
data = file.read(size)
if len(data) < size:
raise ImageDecodeException('Unexpected EOF')
return struct.unpack(format, data)
def read_byte(file):
data = file.read(1)
if not len(data):
raise ImageDecodeException('Unexpected EOF')
return ord(data)
def read(file):
'''Read a GIF file stream.
:rtype: GIFStream
'''
# 17. Header
signature = file.read(3)
version = file.read(3)
if signature != b'GIF':
raise ImageDecodeException('Not a GIF stream')
stream = GIFStream()
# 18. Logical screen descriptor
(logical_screen_width,
logical_screen_height,
fields,
background_color_index,
pixel_aspect_ratio) = unpack('HHBBB', file)
global_color_table_flag = fields & 0x80
global_color_table_size = fields & 0x7
# 19. Global color table
if global_color_table_flag:
global_color_table = file.read(6 << global_color_table_size)
# <Data>*
graphics_scope = GraphicsScope()
block_type = read_byte(file)
while block_type != LABEL_TRAILER:
if block_type == LABEL_IMAGE_DESCRIPTOR:
read_table_based_image(file, stream, graphics_scope)
graphics_scope = GraphicsScope()
elif block_type == LABEL_EXTENSION_INTRODUCER:
extension_block_type = read_byte(file)
if extension_block_type == LABEL_GRAPHIC_CONTROL_EXTENSION:
read_graphic_control_extension(file, stream, graphics_scope)
else:
skip_data_sub_blocks(file)
else:
# Skip bytes until a valid start character is found
print(block_type)
pass
block_type = read_byte(file)
return stream
def skip_data_sub_blocks(file):
# 15. Data sub-blocks
block_size = read_byte(file)
while block_size != 0:
data = file.read(block_size)
block_size = read_byte(file)
def read_table_based_image(file, stream, graphics_scope):
gif_image = GIFImage()
stream.images.append(gif_image)
gif_image.delay = graphics_scope.delay
# 20. Image descriptor
(image_left_position,
image_top_position,
image_width,
image_height,
fields) = unpack('HHHHB', file)
local_color_table_flag = fields & 0x80
local_color_table_size = fields & 0x7
# 21. Local color table
if local_color_table_flag:
local_color_table = file.read(6 << local_color_table_size)
# 22. Table based image data
lzw_code_size = file.read(1)
skip_data_sub_blocks(file)
def read_graphic_control_extension(file, stream, graphics_scope):
# 23. Graphic control extension
(block_size,
fields,
delay_time,
transparent_color_index,
terminator) = unpack('BBHBB', file)
if block_size != 4:
raise ImageDecodeException('Incorrect block size')
if delay_time:
# Follow Firefox/Mac behaviour: use 100ms delay for any delay
# less than 10ms.
if delay_time <= 1:
delay_time = 10
graphics_scope.delay = float(delay_time) / 100
| 5,489 | 30.734104 | 78 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/pyglet/image/codecs/__init__.py
|
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
'''Collection of image encoders and decoders.
Modules must subclass ImageDecoder and ImageEncoder for each method of
decoding/encoding they support.
Modules must also implement the two functions::
def get_decoders():
# Return a list of ImageDecoder instances or []
return []
def get_encoders():
# Return a list of ImageEncoder instances or []
return []
'''
from builtins import object
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import os.path
from pyglet import compat_platform
_decoders = [] # List of registered ImageDecoders
_decoder_extensions = {} # Map str -> list of matching ImageDecoders
_decoder_animation_extensions = {}
# Map str -> list of matching ImageDecoders
_encoders = [] # List of registered ImageEncoders
_encoder_extensions = {} # Map str -> list of matching ImageEncoders
class ImageDecodeException(Exception):
exception_priority = 10
class ImageEncodeException(Exception):
pass
class ImageDecoder(object):
def get_file_extensions(self):
'''Return a list of accepted file extensions, e.g. ['.png', '.bmp']
Lower-case only.
'''
return []
def get_animation_file_extensions(self):
'''Return a list of accepted file extensions, e.g. ['.gif', '.flc']
Lower-case only.
'''
return []
def decode(self, file, filename):
'''Decode the given file object and return an instance of `Image`.
Throws ImageDecodeException if there is an error. filename
can be a file type hint.
'''
raise NotImplementedError()
def decode_animation(self, file, filename):
'''Decode the given file object and return an instance of :py:class:`~pyglet.image.Animation`.
Throws ImageDecodeException if there is an error. filename
can be a file type hint.
'''
raise ImageDecodeException('This decoder cannot decode animations.')
class ImageEncoder(object):
def get_file_extensions(self):
'''Return a list of accepted file extensions, e.g. ['.png', '.bmp']
Lower-case only.
'''
return []
def encode(self, image, file, filename, options={}):
'''Encode the given image to the given file. filename
provides a hint to the file format desired. options are
encoder-specific, and unknown options should be ignored or
issue warnings.
'''
raise NotImplementedError()
def get_encoders(filename=None):
'''Get an ordered list of encoders to attempt. filename can be used
as a hint for the filetype.
'''
encoders = []
if filename:
extension = os.path.splitext(filename)[1].lower()
encoders += _encoder_extensions.get(extension, [])
encoders += [e for e in _encoders if e not in encoders]
return encoders
def get_decoders(filename=None):
'''Get an ordered list of decoders to attempt. filename can be used
as a hint for the filetype.
'''
decoders = []
if filename:
extension = os.path.splitext(filename)[1].lower()
decoders += _decoder_extensions.get(extension, [])
decoders += [e for e in _decoders if e not in decoders]
return decoders
def get_animation_decoders(filename=None):
'''Get an ordered list of decoders to attempt. filename can be used
as a hint for the filetype.
'''
decoders = []
if filename:
extension = os.path.splitext(filename)[1].lower()
decoders += _decoder_animation_extensions.get(extension, [])
decoders += [e for e in _decoders if e not in decoders]
return decoders
def add_decoders(module):
'''Add a decoder module. The module must define `get_decoders`. Once
added, the appropriate decoders defined in the codec will be returned by
pyglet.image.codecs.get_decoders.
'''
for decoder in module.get_decoders():
_decoders.append(decoder)
for extension in decoder.get_file_extensions():
if extension not in _decoder_extensions:
_decoder_extensions[extension] = []
_decoder_extensions[extension].append(decoder)
for extension in decoder.get_animation_file_extensions():
if extension not in _decoder_animation_extensions:
_decoder_animation_extensions[extension] = []
_decoder_animation_extensions[extension].append(decoder)
def add_encoders(module):
'''Add an encoder module. The module must define `get_encoders`. Once
added, the appropriate encoders defined in the codec will be returned by
pyglet.image.codecs.get_encoders.
'''
for encoder in module.get_encoders():
_encoders.append(encoder)
for extension in encoder.get_file_extensions():
if extension not in _encoder_extensions:
_encoder_extensions[extension] = []
_encoder_extensions[extension].append(encoder)
def add_default_image_codecs():
# Add the codecs we know about. These should be listed in order of
# preference. This is called automatically by pyglet.image.
# Compressed texture in DDS format
try:
from pyglet.image.codecs import dds
add_encoders(dds)
add_decoders(dds)
except ImportError:
pass
# Mac OS X default: Quicktime for Carbon, Quartz for Cocoa.
# TODO: Make ctypes Quartz the default for both Carbon & Cocoa.
if compat_platform == 'darwin':
try:
from pyglet import options as pyglet_options
if pyglet_options['darwin_cocoa']:
import pyglet.image.codecs.quartz
add_encoders(quartz)
add_decoders(quartz)
else:
import pyglet.image.codecs.quicktime
add_encoders(quicktime)
add_decoders(quicktime)
except ImportError:
pass
# Windows XP default: GDI+
if compat_platform in ('win32', 'cygwin'):
try:
import pyglet.image.codecs.gdiplus
add_encoders(gdiplus)
add_decoders(gdiplus)
except ImportError:
pass
# Linux default: GdkPixbuf 2.0
if compat_platform.startswith('linux'):
try:
import pyglet.image.codecs.gdkpixbuf2
add_encoders(gdkpixbuf2)
add_decoders(gdkpixbuf2)
except ImportError:
pass
# Fallback: PIL
try:
import pyglet.image.codecs.pil
add_encoders(pil)
add_decoders(pil)
except ImportError:
pass
# Fallback: PNG loader (slow)
try:
import pyglet.image.codecs.png
add_encoders(png)
add_decoders(png)
except ImportError:
pass
# Fallback: BMP loader (slow)
try:
import pyglet.image.codecs.bmp
add_encoders(bmp)
add_decoders(bmp)
except ImportError:
pass
| 8,700 | 34.659836 | 102 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/pyglet/image/codecs/png.py
|
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
'''Encoder and decoder for PNG files, using PyPNG (png.py).
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import array
import itertools
from pyglet.gl import *
from pyglet.image import *
from pyglet.image.codecs import *
import pyglet.extlibs.png as pypng
class PNGImageDecoder(ImageDecoder):
def get_file_extensions(self):
return ['.png']
def decode(self, file, filename):
try:
reader = pypng.Reader(file=file)
width, height, pixels, metadata = reader.asDirect()
except Exception as e:
raise ImageDecodeException(
'PyPNG cannot read %r: %s' % (filename or file, e))
if metadata['greyscale']:
if metadata['alpha']:
format = 'LA'
else:
format = 'L'
else:
if metadata['alpha']:
format = 'RGBA'
else:
format = 'RGB'
pitch = len(format) * width
pixels = array.array('BH'[metadata['bitdepth']>8], itertools.chain(*pixels))
return ImageData(width, height, format, pixels.tostring(), -pitch)
class PNGImageEncoder(ImageEncoder):
def get_file_extensions(self):
return ['.png']
def encode(self, image, file, filename):
image = image.get_image_data()
has_alpha = 'A' in image.format
greyscale = len(image.format) < 3
if has_alpha:
if greyscale:
image.format = 'LA'
else:
image.format = 'RGBA'
else:
if greyscale:
image.format = 'L'
else:
image.format = 'RGB'
image.pitch = -(image.width * len(image.format))
writer = pypng.Writer(
image.width, image.height,
bytes_per_sample=1,
greyscale=greyscale,
alpha=has_alpha)
data = array.array('B')
data.fromstring(image.data)
writer.write_array(file, data)
def get_decoders():
return [PNGImageDecoder()]
def get_encoders():
return [PNGImageEncoder()]
| 3,835 | 32.356522 | 84 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/pyglet/media/threads.py
|
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
from __future__ import print_function
from future import standard_library
standard_library.install_aliases()
from builtins import object
import atexit
import threading
import time
import pyglet
from pyglet.debug import debug_print
_debug = debug_print('debug_media')
class MediaThread(object):
"""A thread that cleanly exits on interpreter shutdown, and provides
a sleep method that can be interrupted and a termination method.
:Ivariables:
`condition` : threading.Condition
Lock condition on all instance variables.
`stopped` : bool
True if `stop` has been called.
"""
_threads = set()
_threads_lock = threading.Lock()
def __init__(self, target=None):
self._thread = threading.Thread(target=self._thread_run)
self._thread.setDaemon(True)
if target is not None:
self.run = target
self.condition = threading.Condition()
self.stopped = False
@classmethod
def _atexit(cls):
with cls._threads_lock:
threads = list(cls._threads)
for thread in threads:
thread.stop()
def run(self):
pass
def _thread_run(self):
if pyglet.options['debug_trace']:
pyglet._install_trace()
with self._threads_lock:
self._threads.add(self)
self.run()
with self._threads_lock:
self._threads.remove(self)
def start(self):
self._thread.start()
def stop(self):
"""Stop the thread and wait for it to terminate.
The `stop` instance variable is set to ``True`` and the condition is
notified. It is the responsibility of the `run` method to check
the value of `stop` after each sleep or wait and to return if set.
"""
assert _debug('MediaThread.stop()')
with self.condition:
self.stopped = True
self.condition.notify()
self._thread.join()
def sleep(self, timeout):
"""Wait for some amount of time, or until notified.
:Parameters:
`timeout` : float
Time to wait, in seconds.
"""
assert _debug('MediaThread.sleep(%r)' % timeout)
with self.condition:
if not self.stopped:
self.condition.wait(timeout)
def notify(self):
"""Interrupt the current sleep operation.
If the thread is currently sleeping, it will be woken immediately,
instead of waiting the full duration of the timeout.
"""
assert _debug('MediaThread.notify()')
with self.condition:
self.condition.notify()
atexit.register(MediaThread._atexit)
class WorkerThread(MediaThread):
def __init__(self, target=None):
super(WorkerThread, self).__init__(target)
self._jobs = []
def run(self):
while True:
job = self.get_job()
if not job:
break
job()
def get_job(self):
with self.condition:
while self._empty() and not self.stopped:
self.condition.wait()
if self.stopped:
result = None
else:
result = self._get()
return result
def put_job(self, job):
with self.condition:
self._put(job)
self.condition.notify()
def clear_jobs(self):
with self.condition:
self._clear()
self.condition.notify()
def _empty(self):
return not self._jobs
def _get(self):
return self._jobs.pop(0)
def _put(self, job):
self._jobs.append(job)
def _clear(self):
del self._jobs[:]
class PlayerWorker(MediaThread):
"""
Worker thread for refilling players.
"""
# Time to wait if there are players, but they're all full.
_nap_time = 0.05
# Time to wait if there are no players.
_sleep_time = None
def __init__(self):
super(PlayerWorker, self).__init__()
self.players = set()
def run(self):
while True:
# This is a big lock, but ensures a player is not deleted while
# we're processing it -- this saves on extra checks in the
# player's methods that would otherwise have to check that it's
# still alive.
with self.condition:
assert _debug('PlayerWorker: woke up@{}'.format(time.time()))
if self.stopped:
break
sleep_time = -1
if self.players:
filled = False
for player in self.players:
write_size = player.get_write_size()
if write_size > player.min_buffer_size:
player.refill(write_size)
filled = True
if not filled:
sleep_time = self._nap_time
else:
assert _debug('PlayerWorker: No active players')
sleep_time = self._sleep_time
if sleep_time != -1:
self.sleep(sleep_time)
else:
# We MUST sleep, or we will starve pyglet's main loop. It
# also looks like if we don't sleep enough, we'll starve out
# various updates that stop us from properly removing players
# that should be removed.
self.sleep(self._nap_time)
def add(self, player):
assert player is not None
assert _debug('PlayerWorker: player added')
with self.condition:
self.players.add(player)
self.condition.notify()
def remove(self, player):
assert _debug('PlayerWorker: player removed')
with self.condition:
if player in self.players:
self.players.remove(player)
self.condition.notify()
| 7,735 | 30.835391 | 81 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/pyglet/media/events.py
|
from builtins import object
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
import time
import pyglet
class MediaEvent(object):
def __init__(self, timestamp, event, *args):
# Meaning of timestamp is dependent on context; and not seen by
# application.
self.timestamp = timestamp
self.event = event
self.args = args
def _sync_dispatch_to_player(self, player):
pyglet.app.platform_event_loop.post_event(player, self.event, *self.args)
time.sleep(0)
# TODO sync with media.dispatch_events
def __repr__(self):
return '%s(%r, %r, %r)' % (self.__class__.__name__,
self.timestamp, self.event, self.args)
def __lt__(self, other):
return hash(self) < hash(other)
| 2,445 | 38.451613 | 81 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/pyglet/media/exceptions.py
|
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
class MediaException(Exception):
pass
class MediaFormatException(MediaException):
pass
class CannotSeekException(MediaException):
pass
| 1,870 | 40.577778 | 78 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/pyglet/media/listener.py
|
from builtins import object
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
from abc import ABCMeta, abstractmethod
from future.utils import with_metaclass
class AbstractListener(with_metaclass(ABCMeta, object)):
"""The listener properties for positional audio.
You can obtain the singleton instance of this class by calling
`AbstractAudioDriver.get_listener`.
"""
_volume = 1.0
_position = (0, 0, 0)
_forward_orientation = (0, 0, -1)
_up_orientation = (0, 1, 0)
@abstractmethod
def _set_volume(self, volume):
pass
volume = property(lambda self: self._volume,
lambda self, volume: self._set_volume(volume),
doc="""The master volume for sound playback.
All sound volumes are multiplied by this master volume before being
played. A value of 0 will silence playback (but still consume
resources). The nominal volume is 1.0.
:type: float
""")
@abstractmethod
def _set_position(self, position):
pass
position = property(lambda self: self._position,
lambda self, position: self._set_position(position),
doc="""The position of the listener in 3D space.
The position is given as a tuple of floats (x, y, z). The unit
defaults to meters, but can be modified with the listener
properties.
:type: 3-tuple of float
""")
@abstractmethod
def _set_forward_orientation(self, orientation):
pass
forward_orientation = property(lambda self: self._forward_orientation,
lambda self, o: self._set_forward_orientation(o),
doc="""A vector giving the direction the
listener is facing.
The orientation is given as a tuple of floats (x, y, z), and has
no unit. The forward orientation should be orthagonal to the
up orientation.
:type: 3-tuple of float
""")
@abstractmethod
def _set_up_orientation(self, orientation):
pass
up_orientation = property(lambda self: self._up_orientation,
lambda self, o: self._set_up_orientation(o),
doc="""A vector giving the "up" orientation
of the listener.
The orientation is given as a tuple of floats (x, y, z), and has
no unit. The up orientation should be orthagonal to the
forward orientation.
:type: 3-tuple of float
""")
| 4,229 | 36.433628 | 80 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/pyglet/media/player.py
|
"""High-level sound and video player."""
from __future__ import print_function
from __future__ import division
from builtins import object
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
import pyglet
from pyglet.media.drivers import get_audio_driver, get_silent_audio_driver
from pyglet.media.events import MediaEvent
from pyglet.media.exceptions import MediaException
from pyglet.media.sources.base import SourceGroup, StaticSource
_debug = pyglet.options['debug_media']
class Player(pyglet.event.EventDispatcher):
"""High-level sound and video player.
"""
_last_video_timestamp = None
_texture = None
# Spacialisation attributes, preserved between audio players
_volume = 1.0
_min_distance = 1.0
_max_distance = 100000000.
_position = (0, 0, 0)
_pitch = 1.0
_cone_orientation = (0, 0, 1)
_cone_inner_angle = 360.
_cone_outer_angle = 360.
_cone_outer_gain = 1.
def __init__(self):
# List of queued source groups
self._groups = []
self._audio_player = None
# Desired play state (not an indication of actual state).
self._playing = False
self._paused_time = 0.0
def __del__(self):
"""Release the Player resources."""
self.delete()
def queue(self, source):
"""
Queue the source on this player.
If the player has no source, the player will be paused immediately on this source.
:param pyglet.media.Source source: The source to queue.
"""
if isinstance(source, SourceGroup):
self._groups.append(source)
else:
if (self._groups and
source.audio_format == self._groups[-1].audio_format and
source.video_format == self._groups[-1].video_format):
self._groups[-1].queue(source)
else:
group = SourceGroup(source.audio_format, source.video_format)
group.queue(source)
self._groups.append(group)
self._set_playing(self._playing)
def _set_playing(self, playing):
#stopping = self._playing and not playing
#starting = not self._playing and playing
self._playing = playing
source = self.source
if playing and source:
if not self._audio_player:
self._create_audio_player()
self._audio_player.play()
if source.video_format:
if not self._texture:
self._create_texture()
if self.source.video_format.frame_rate:
period = 1. / self.source.video_format.frame_rate
else:
period = 1. / 30.
pyglet.clock.schedule_interval(self.update_texture, period)
else:
if self._audio_player:
self._audio_player.stop()
pyglet.clock.unschedule(self.update_texture)
def _get_playing(self):
"""
Read-only. Determine if the player state is playing.
The *playing* property is irrespective of whether or not there is
actually a source to play. If *playing* is ``True`` and a source is
queued, it will begin playing immediately. If *playing* is ``False``,
it is implied that the player is paused. There is no other possible
state.
"""
return self._playing
playing = property(_get_playing)
def play(self):
"""
Begin playing the current source.
This has no effect if the player is already playing.
"""
self._set_playing(True)
def pause(self):
"""
Pause playback of the current source.
This has no effect if the player is already paused.
"""
self._set_playing(False)
if self._audio_player:
time = self._audio_player.get_time()
time = self._groups[0].translate_timestamp(time)
if time is not None:
self._paused_time = time
def delete(self):
"""Tear down the player and any child objects."""
if self._audio_player:
self._audio_player.delete()
self._audio_player = None
while self._groups:
del self._groups[0]
def next_source(self):
"""
Move immediately to the next queued source.
There may be a gap in playback while the audio buffer is refilled.
"""
if not self._groups:
return
group = self._groups[0]
if group.has_next():
group.next_source()
return
if self.source.video_format:
self._texture = None
pyglet.clock.unschedule(self.update_texture)
if self._audio_player:
self._audio_player.delete()
self._audio_player = None
del self._groups[0]
if self._groups:
self._set_playing(self._playing)
return
self._set_playing(False)
self.dispatch_event('on_player_eos')
#: :deprecated: Use `next_source` instead.
next = next_source # old API, worked badly with 2to3
def seek(self, time):
"""
Seek for playback to the indicated timestamp in seconds on the current
source. If the timestamp is outside the duration of the source, it
will be clamped to the end.
"""
if not self.source:
return
if _debug:
print('Player.seek(%r)' % time)
self._paused_time = time
self.source.seek(time)
if self._audio_player:
# XXX: According to docstring in AbstractAudioPlayer this cannot be called when the
# player is not stopped
self._audio_player.clear()
if self.source.video_format:
self._last_video_timestamp = None
self.update_texture(time=time)
def _create_audio_player(self):
assert not self._audio_player
assert self._groups
group = self._groups[0]
audio_format = group.audio_format
if audio_format:
audio_driver = get_audio_driver()
else:
audio_driver = get_silent_audio_driver()
self._audio_player = audio_driver.create_audio_player(group, self)
_class = self.__class__
def _set(name):
private_name = '_' + name
value = getattr(self, private_name)
if value != getattr(_class, private_name):
getattr(self._audio_player, 'set_' + name)(value)
_set('volume')
_set('min_distance')
_set('max_distance')
_set('position')
_set('pitch')
_set('cone_orientation')
_set('cone_inner_angle')
_set('cone_outer_angle')
_set('cone_outer_gain')
def _get_source(self):
"""Read-only. The current :py:class:`Source`, or ``None``."""
if not self._groups:
return None
return self._groups[0].get_current_source()
source = property(_get_source)
def _get_time(self):
"""
Read-only. Current playback time of the current source.
The playback time is a float expressed in seconds, with 0.0 being the
beginning of the sound. The playback time returned represents the time
encoded in the source, and may not reflect actual time passed due to
pitch shifting or pausing.
"""
time = None
if self._playing and self._audio_player:
time = self._audio_player.get_time()
time = self._groups[0].translate_timestamp(time)
if time is None:
return self._paused_time
else:
return time
time = property(_get_time)
def _create_texture(self):
video_format = self.source.video_format
self._texture = pyglet.image.Texture.create(
video_format.width, video_format.height, rectangle=True)
self._texture = self._texture.get_transform(flip_y=True)
self._texture.anchor_y = 0
def get_texture(self):
"""
Get the texture for the current video frame.
You should call this method every time you display a frame of video,
as multiple textures might be used. The return value will be None if
there is no video in the current source.
:return: :py:class:`pyglet.image.Texture`
"""
return self._texture
def seek_next_frame(self):
"""Step forwards one video frame in the current Source.
"""
time = self._groups[0].get_next_video_timestamp()
if time is None:
return
self.seek(time)
def update_texture(self, dt=None, time=None):
"""Manually update the texture from the current source. This happens
automatically, so you shouldn't need to call this method.
"""
if time is None:
time = self._audio_player.get_time()
if time is None:
return
if (self._last_video_timestamp is not None and
time <= self._last_video_timestamp):
return
ts = self._groups[0].get_next_video_timestamp()
while ts is not None and ts < time:
self._groups[0].get_next_video_frame() # Discard frame
ts = self._groups[0].get_next_video_timestamp()
if ts is None:
self._last_video_timestamp = None
return
image = self._groups[0].get_next_video_frame()
if image is not None:
if self._texture is None:
self._create_texture()
self._texture.blit_into(image, 0, 0, 0)
self._last_video_timestamp = ts
def _player_property(name, doc=None):
private_name = '_' + name
set_name = 'set_' + name
def _player_property_set(self, value):
setattr(self, private_name, value)
if self._audio_player:
getattr(self._audio_player, set_name)(value)
def _player_property_get(self):
return getattr(self, private_name)
return property(_player_property_get, _player_property_set, doc=doc)
volume = _player_property('volume', doc="""
The volume level of sound playback.
The nominal level is 1.0, and 0.0 is silence.
The volume level is affected by the distance from the listener (if
positioned).
""")
min_distance = _player_property('min_distance', doc="""
The distance beyond which the sound volume drops by half, and within
which no attenuation is applied.
The minimum distance controls how quickly a sound is attenuated as it
moves away from the listener. The gain is clamped at the nominal value
within the min distance. By default the value is 1.0.
The unit defaults to meters, but can be modified with the listener properties.
""")
max_distance = _player_property('max_distance', doc="""
The distance at which no further attenuation is applied.
When the distance from the listener to the player is greater than this
value, attenuation is calculated as if the distance were value. By
default the maximum distance is infinity.
The unit defaults to meters, but can be modified with the listener
properties.
""")
position = _player_property('position', doc="""
The position of the sound in 3D space.
The position is given as a tuple of floats (x, y, z). The unit
defaults to meters, but can be modified with the listener properties.
""")
pitch = _player_property('pitch', doc="""
The pitch shift to apply to the sound.
The nominal pitch is 1.0. A pitch of 2.0 will sound one octave higher,
and play twice as fast. A pitch of 0.5 will sound one octave lower, and
play twice as slow. A pitch of 0.0 is not permitted.
""")
cone_orientation = _player_property('cone_orientation', doc="""
The direction of the sound in 3D space.
The direction is specified as a tuple of floats (x, y, z), and has no
unit. The default direction is (0, 0, -1). Directional effects are only
noticeable if the other cone properties are changed from their default
values.
""")
cone_inner_angle = _player_property('cone_inner_angle', doc="""
The interior angle of the inner cone.
The angle is given in degrees, and defaults to 360. When the listener
is positioned within the volume defined by the inner cone, the sound is
played at normal gain (see :py:attr:`volume`).
""")
cone_outer_angle = _player_property('cone_outer_angle', doc="""
The interior angle of the outer cone.
The angle is given in degrees, and defaults to 360. When the listener
is positioned within the volume defined by the outer cone, but outside
the volume defined by the inner cone, the gain applied is a smooth
interpolation between :py:attr:`volume` and :py:attr:`cone_outer_gain`.
""")
cone_outer_gain = _player_property('cone_outer_gain', doc="""
The gain applied outside the cone.
When the listener is positioned outside the volume defined by the outer
cone, this gain is applied instead of :py:attr:`volume`.
""")
# Events
def on_player_eos(self):
"""The player ran out of sources.
:event:
"""
if _debug:
print('Player.on_player_eos')
def on_source_group_eos(self):
"""The current source group ran out of data.
The default behaviour is to advance to the next source group if
possible.
:event:
"""
self.next_source()
if _debug:
print('Player.on_source_group_eos')
def on_eos(self):
"""
:event:
"""
if _debug:
print('Player.on_eos')
Player.register_event_type('on_eos')
Player.register_event_type('on_player_eos')
Player.register_event_type('on_source_group_eos')
class PlayerGroup(object):
"""Group of players that can be played and paused simultaneously.
:Ivariables:
`players` : list of `Player`
Players in this group.
"""
def __init__(self, players):
"""Create a player group for the given set of players.
All players in the group must currently not belong to any other
group.
:Parameters:
`players` : Sequence of `Player`
Players to add to this group.
"""
self.players = list(players)
def play(self):
"""Begin playing all players in the group simultaneously.
"""
audio_players = [p._audio_player \
for p in self.players if p._audio_player]
if audio_players:
audio_players[0]._play_group(audio_players)
for player in self.players:
player.play()
def pause(self):
"""Pause all players in the group simultaneously.
"""
audio_players = [p._audio_player \
for p in self.players if p._audio_player]
if audio_players:
audio_players[0]._stop_group(audio_players)
for player in self.players:
player.pause()
| 16,838 | 32.213018 | 95 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/pyglet/media/__init__.py
|
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
"""Audio and video playback.
pyglet can play WAV files, and if AVbin is installed, many other audio and
video formats.
Playback is handled by the :py:class:`Player` class, which reads raw data from
:py:class:`Source` objects and provides methods for pausing, seeking, adjusting
the volume, and so on. The :py:class:`Player` class implements the best
available audio device (currently, only OpenAL is supported)::
player = Player()
A :py:class:`Source` is used to decode arbitrary audio and video files. It is
associated with a single player by "queuing" it::
source = load('background_music.mp3')
player.queue(source)
Use the :py:class:`Player` to control playback.
If the source contains video, the :py:meth:`Source.video_format` attribute will
be non-None, and the :py:attr:`Player.texture` attribute will contain the
current video image synchronised to the audio.
Decoding sounds can be processor-intensive and may introduce latency,
particularly for short sounds that must be played quickly, such as bullets or
explosions. You can force such sounds to be decoded and retained in memory
rather than streamed from disk by wrapping the source in a
:py:class:`StaticSource`::
bullet_sound = StaticSource(load('bullet.wav'))
The other advantage of a :py:class:`StaticSource` is that it can be queued on
any number of players, and so played many times simultaneously.
pyglet relies on Python's garbage collector to release resources when a player
has finished playing a source. In this way some operations that could affect
the application performance can be delayed.
The player provides a :py:meth:`Player.delete` method that can be used to
release resources immediately. Also an explicit call to ``gc.collect()`` can be
used to collect unused resources.
"""
# Collect public interface from all submodules/packages
from .drivers import get_audio_driver
from .exceptions import *
from .player import Player, PlayerGroup
from .sources import *
# For backwards compatibility, deprecate?
from .sources import procedural
| 3,767 | 41.818182 | 79 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/pyglet/media/drivers/base.py
|
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
from abc import ABCMeta, abstractmethod
from future.utils import with_metaclass
class AbstractAudioPlayer(with_metaclass(ABCMeta, object)):
"""Base class for driver audio players.
"""
def __init__(self, source_group, player):
"""Create a new audio player.
:Parameters:
`source_group` : `SourceGroup`
Source group to play from.
`player` : `Player`
Player to receive EOS and video frame sync events.
"""
self.source_group = source_group
self.player = player
@abstractmethod
def play(self):
"""Begin playback."""
@abstractmethod
def stop(self):
"""Stop (pause) playback."""
@abstractmethod
def delete(self):
"""Stop playing and clean up all resources used by player."""
def _play_group(self, audio_players):
"""Begin simultaneous playback on a list of audio players."""
# This should be overridden by subclasses for better synchrony.
for player in audio_players:
player.play()
def _stop_group(self, audio_players):
"""Stop simultaneous playback on a list of audio players."""
# This should be overridden by subclasses for better synchrony.
for player in audio_players:
player.stop()
@abstractmethod
def clear(self):
"""Clear all buffered data and prepare for replacement data.
The player should be stopped before calling this method.
"""
@abstractmethod
def get_time(self):
"""Return approximation of current playback time within current source.
Returns ``None`` if the audio player does not know what the playback
time is (for example, before any valid audio data has been read).
:rtype: float
:return: current play cursor time, in seconds.
"""
# TODO determine which source within group
def set_volume(self, volume):
"""See `Player.volume`."""
pass
def set_position(self, position):
"""See :py:attr:`~pyglet.media.Player.position`."""
pass
def set_min_distance(self, min_distance):
"""See `Player.min_distance`."""
pass
def set_max_distance(self, max_distance):
"""See `Player.max_distance`."""
pass
def set_pitch(self, pitch):
"""See :py:attr:`~pyglet.media.Player.pitch`."""
pass
def set_cone_orientation(self, cone_orientation):
"""See `Player.cone_orientation`."""
pass
def set_cone_inner_angle(self, cone_inner_angle):
"""See `Player.cone_inner_angle`."""
pass
def set_cone_outer_angle(self, cone_outer_angle):
"""See `Player.cone_outer_angle`."""
pass
def set_cone_outer_gain(self, cone_outer_gain):
"""See `Player.cone_outer_gain`."""
pass
class AbstractAudioDriver(with_metaclass(ABCMeta, object)):
@abstractmethod
def create_audio_player(self, source_group, player):
pass
@abstractmethod
def get_listener(self):
pass
@abstractmethod
def delete(self):
pass
| 4,870 | 32.136054 | 79 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/pyglet/media/drivers/silent.py
|
from __future__ import print_function
from __future__ import division
from builtins import object
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
import time
from pyglet.app import WeakSet
from pyglet.media.events import MediaEvent
from pyglet.media.drivers.base import AbstractAudioDriver, AbstractAudioPlayer
from pyglet.media.threads import MediaThread
import pyglet
_debug = pyglet.options['debug_media']
class SilentAudioPacket(object):
def __init__(self, timestamp, duration):
self.timestamp = timestamp
self.duration = duration
def consume(self, dt):
"""Try to consume `dt` seconds of audio data. Return number of seconds consumed."""
if dt > self.duration:
duration = self.duration
self.timestamp += self.duration
self.duration = 0.
return duration
else:
self.timestamp += dt
self.duration -= dt
return dt
def is_empty(self):
return self.duration == 0
class SilentAudioBuffer(object):
"""Buffer for silent audio packets"""
def __init__(self):
self.clear()
def clear(self):
# Buffered audio packets
self._packets = []
# Duration of the buffered contents
self.duration = 0.
def add_audio_data(self, audio_data):
assert audio_data is not None
packet = SilentAudioPacket(audio_data.timestamp, audio_data.duration)
self._add_packet(packet)
def consume_audio_data(self, dt):
assert dt >= 0.
while dt > 0. and not self.is_empty():
consumed = self._packets[0].consume(dt)
self.duration -= consumed
if self._packets[0].is_empty():
self._next_packet()
dt -= consumed
def is_empty(self):
return self.duration <= 0
def get_current_timestamp(self):
if self._packets:
return self._packets[0].timestamp
else:
return 0.
def get_time_to_next_update(self):
if self._packets and self.duration > 0.:
return self._packets[0].duration
else:
return None
def _add_packet(self, packet):
self.duration += packet.duration
self._packets.append(packet)
def _next_packet(self):
if len(self._packets) > 1:
self.duration -= self._packets[0].duration
del self._packets[0]
class EventBuffer(object):
"""Buffer for events from audio data"""
def __init__(self):
self.clear()
def clear(self):
# Events in the order they are retrieved from audio_data
self._events = []
def add_events(self, audio_data):
assert audio_data is not None
for event in audio_data.events:
assert event.timestamp <= audio_data.duration
event.timestamp += audio_data.timestamp
self._events.append(event)
def get_next_event_timestamp(self):
if self._events:
return self._events[0].timestamp
else:
return None
def get_time_to_next_event(self, timestamp):
if self._events:
dt = self._events[0].timestamp - timestamp
if dt < 0.:
return 0.
else:
return dt
else:
return None
def get_expired_events(self, timestamp):
expired_events = []
while self._events and self._events[0].timestamp <= timestamp:
expired_events.append(self._events[0])
del self._events[0]
return expired_events
class SilentAudioPlayerPacketConsumer(AbstractAudioPlayer):
# When playing video, length of audio (in secs) to buffer ahead.
_buffer_time = 0.4
# Minimum number of bytes to request from source
_min_update_bytes = 1024
# Minimum sleep time to prevent asymptotic behaviour
_min_sleep_time = 0.01
# Maximum sleep time
_max_sleep_time = 0.2
def __init__(self, source_group, player):
super(SilentAudioPlayerPacketConsumer, self).__init__(source_group, player)
# System time of first timestamp
self._last_update_system_time = None
# Buffered audio data and events
self._audio_buffer = SilentAudioBuffer()
self._event_buffer = EventBuffer()
# Actual play state.
self._playing = False
self._eos = False
# TODO Be nice to avoid creating this thread if user doesn't care
# about EOS events and there's no video format.
# NOTE Use thread.condition as lock for all instance vars used by worker
self._thread = MediaThread(target=self._worker_func)
if source_group.audio_format:
self._thread.start()
def delete(self):
if _debug:
print('SilentAudioPlayer.delete')
self._thread.stop()
def play(self):
if _debug:
print('SilentAudioPlayer.play')
with self._thread.condition:
self._eos = False
if not self._playing:
self._playing = True
self._update_time()
self._thread.notify()
def stop(self):
if _debug:
print('SilentAudioPlayer.stop')
with self._thread.condition:
if self._playing:
self._consume_data()
self._playing = False
def clear(self):
if _debug:
print('SilentAudioPlayer.clear')
with self._thread.condition:
self._event_buffer.clear()
self._audio_buffer.clear()
self._eos = False
self._thread.notify()
def get_time(self):
with self._thread.condition:
result = self._audio_buffer.get_current_timestamp() + self._calculate_offset()
if _debug:
print('SilentAudioPlayer.get_time() -> ', result)
return result
def _update_time(self):
self._last_update_system_time = time.time()
def _consume_data(self):
"""Consume content of packets that should have been played back up to now."""
with self._thread.condition:
offset = self._calculate_offset()
self._audio_buffer.consume_audio_data(offset)
self._update_time()
if self._audio_buffer.is_empty():
if _debug:
print('Out of packets')
timestamp = self.get_time()
MediaEvent(timestamp, 'on_eos')._sync_dispatch_to_player(self.player)
MediaEvent(timestamp, 'on_source_group_eos')._sync_dispatch_to_player(self.player)
def _calculate_offset(self):
"""Calculate the current offset into the cached packages."""
if self._last_update_system_time is None:
return 0.
if not self._playing:
return 0.
offset = time.time() - self._last_update_system_time
if offset > self._audio_buffer.duration:
return self._audio_buffer.duration
return offset
def _buffer_data(self):
"""Read data from the audio source into the internal buffer."""
with self._thread.condition:
# Calculate how much data to request from source
secs = self._buffer_time - self._audio_buffer.duration
bytes_to_read = int(secs * self.source_group.audio_format.bytes_per_second)
while bytes_to_read > self._min_update_bytes and not self._eos:
# Pull audio data from source
if _debug:
print('Trying to buffer %d bytes (%r secs)' % (bytes_to_read, secs))
audio_data = self.source_group.get_audio_data(bytes_to_read)
if not audio_data:
self._eos = True
break
else:
self._add_audio_data(audio_data)
bytes_to_read -= audio_data.length
def _add_audio_data(self, audio_data):
"""Add a package of audio data to the internal buffer. Update timestamps to reflect."""
with self._thread.condition:
self._audio_buffer.add_audio_data(audio_data)
self._event_buffer.add_events(audio_data)
def _get_sleep_time(self):
"""Determine how long to sleep until next event or next batch of data needs to be read."""
if not self._playing:
# Not playing, so no need to wake up
return None
if self._audio_buffer.duration < self._buffer_time/2 and not self._eos:
# More buffering required
return 0.
time_to_next_event = self._event_buffer.get_time_to_next_event(self.get_time())
time_to_next_buffer_update = self._audio_buffer.get_time_to_next_update()
if time_to_next_event is None and time_to_next_buffer_update is None and self._eos:
# Nothing to read and no events to handle:
return None
# Wait for first action to take (event or buffer) up to a maximum
if _debug:
print('Next event in {}, next buffer in {}'.format(time_to_next_event, time_to_next_buffer_update))
return max(min(time_to_next_buffer_update or self._max_sleep_time,
time_to_next_event or self._max_sleep_time,
self._max_sleep_time),
self._min_sleep_time)
def _dispatch_events(self):
"""Dispatch any events for the current timestamp."""
timestamp = self.get_time()
# Dispatch events
for event in self._event_buffer.get_expired_events(timestamp):
event._sync_dispatch_to_player(self.player)
if _debug:
print('Dispatched event {}'.format(event))
# Worker func that consumes audio data and dispatches events
def _worker_func(self):
while True:
with self._thread.condition:
if self._thread.stopped:
break
self._consume_data()
self._dispatch_events()
self._buffer_data()
sleep_time = self._get_sleep_time()
if _debug:
print('SilentAudioPlayer(Worker).sleep', sleep_time)
self._thread.sleep(sleep_time)
if _debug:
print('SilentAudioPlayer(Worker).wakeup')
if _debug:
print('SilentAudioPlayer(Worker) ended')
class SilentTimeAudioPlayer(AbstractAudioPlayer):
# Note that when using this player (automatic if playing back video with
# unsupported audio codec) no events are dispatched (because they are
# normally encoded in the audio packet -- so no EOS events are delivered.
# This is a design flaw.
#
# Also, seeking is broken because the timestamps aren't synchronized with
# the source group.
_time = 0.0
_systime = None
def play(self):
self._systime = time.time()
def stop(self):
self._time = self.get_time()
self._systime = None
def delete(self):
pass
def clear(self):
pass
def get_time(self):
if self._systime is None:
return self._time
else:
return time.time() - self._systime + self._time
class SilentAudioDriver(AbstractAudioDriver):
def __init__(self):
self._players = WeakSet()
def create_audio_player(self, source_group, player):
if source_group.audio_format:
p = SilentAudioPlayerPacketConsumer(source_group, player)
self._players.add(p)
return p
else:
return SilentTimeAudioPlayer(source_group, player)
def get_listener(self):
raise NotImplementedError('Silent audio driver does not support positional audio')
def delete(self):
while len(self._players) > 0:
self._players.pop().delete()
def create_audio_driver():
return SilentAudioDriver()
| 13,625 | 32.727723 | 111 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/pyglet/media/drivers/__init__.py
|
"""Drivers for playing back media."""
from __future__ import print_function
from __future__ import absolute_import
from builtins import str
import pyglet
_debug = pyglet.options['debug_media']
def get_audio_driver():
global _audio_driver
if _audio_driver:
return _audio_driver
_audio_driver = None
for driver_name in pyglet.options['audio']:
try:
if driver_name == 'pulse':
from . import pulse
_audio_driver = pulse.create_audio_driver()
break
elif driver_name == 'openal':
from . import openal
_audio_driver = openal.create_audio_driver()
break
elif driver_name == 'directsound':
from . import directsound
_audio_driver = directsound.create_audio_driver()
break
elif driver_name == 'silent':
_audio_driver = get_silent_audio_driver()
break
except Exception as exp:
if _debug:
print('Error importing driver %s:' % driver_name)
import traceback
traceback.print_exc()
return _audio_driver
def get_silent_audio_driver():
global _silent_audio_driver
if not _silent_audio_driver:
from . import silent
_silent_audio_driver = silent.create_audio_driver()
return _silent_audio_driver
_audio_driver = None
_silent_audio_driver = None
| 1,493 | 26.163636 | 65 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/pyglet/media/drivers/pulse/lib_pulseaudio.py
|
'''Wrapper for pulse
Generated with:
tools/genwrappers.py pulseaudio
Do not modify this file.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import ctypes
from ctypes import *
import pyglet.lib
_lib = pyglet.lib.load_library('pulse')
_int_types = (c_int16, c_int32)
if hasattr(ctypes, 'c_int64'):
# Some builds of ctypes apparently do not have c_int64
# defined; it's a pretty good bet that these builds do not
# have 64-bit pointers.
_int_types += (ctypes.c_int64,)
for t in _int_types:
if sizeof(t) == sizeof(c_size_t):
c_ptrdiff_t = t
class c_void(Structure):
# c_void_p is a buggy return type, converting to int, so
# POINTER(None) == c_void_p is actually written as
# POINTER(c_void), so it can be treated as a real pointer.
_fields_ = [('dummy', c_int)]
# /usr/include/pulse/version.h:40
pa_get_library_version = _lib.pa_get_library_version
pa_get_library_version.restype = c_char_p
pa_get_library_version.argtypes = []
PA_API_VERSION = 12 # /usr/include/pulse/version.h:46
PA_PROTOCOL_VERSION = 30 # /usr/include/pulse/version.h:50
PA_MAJOR = 6 # /usr/include/pulse/version.h:53
PA_MINOR = 0 # /usr/include/pulse/version.h:56
PA_MICRO = 0 # /usr/include/pulse/version.h:59
PA_CHANNELS_MAX = 32 # /usr/include/pulse/sample.h:128
PA_RATE_MAX = 192000 # /usr/include/pulse/sample.h:131
enum_pa_sample_format = c_int
PA_SAMPLE_U8 = 0
PA_SAMPLE_ALAW = 1
PA_SAMPLE_ULAW = 2
PA_SAMPLE_S16LE = 3
PA_SAMPLE_S16BE = 4
PA_SAMPLE_FLOAT32LE = 5
PA_SAMPLE_FLOAT32BE = 6
PA_SAMPLE_S32LE = 7
PA_SAMPLE_S32BE = 8
PA_SAMPLE_S24LE = 9
PA_SAMPLE_S24BE = 10
PA_SAMPLE_S24_32LE = 11
PA_SAMPLE_S24_32BE = 12
PA_SAMPLE_MAX = 13
PA_SAMPLE_INVALID = -1
pa_sample_format_t = enum_pa_sample_format # /usr/include/pulse/sample.h:179
class struct_pa_sample_spec(Structure):
__slots__ = [
'format',
'rate',
'channels',
]
struct_pa_sample_spec._fields_ = [
('format', pa_sample_format_t),
('rate', c_uint32),
('channels', c_uint8),
]
pa_sample_spec = struct_pa_sample_spec # /usr/include/pulse/sample.h:257
pa_usec_t = c_uint64 # /usr/include/pulse/sample.h:260
# /usr/include/pulse/sample.h:263
pa_bytes_per_second = _lib.pa_bytes_per_second
pa_bytes_per_second.restype = c_size_t
pa_bytes_per_second.argtypes = [POINTER(pa_sample_spec)]
# /usr/include/pulse/sample.h:266
pa_frame_size = _lib.pa_frame_size
pa_frame_size.restype = c_size_t
pa_frame_size.argtypes = [POINTER(pa_sample_spec)]
# /usr/include/pulse/sample.h:269
pa_sample_size = _lib.pa_sample_size
pa_sample_size.restype = c_size_t
pa_sample_size.argtypes = [POINTER(pa_sample_spec)]
# /usr/include/pulse/sample.h:273
pa_sample_size_of_format = _lib.pa_sample_size_of_format
pa_sample_size_of_format.restype = c_size_t
pa_sample_size_of_format.argtypes = [pa_sample_format_t]
# /usr/include/pulse/sample.h:278
pa_bytes_to_usec = _lib.pa_bytes_to_usec
pa_bytes_to_usec.restype = pa_usec_t
pa_bytes_to_usec.argtypes = [c_uint64, POINTER(pa_sample_spec)]
# /usr/include/pulse/sample.h:283
pa_usec_to_bytes = _lib.pa_usec_to_bytes
pa_usec_to_bytes.restype = c_size_t
pa_usec_to_bytes.argtypes = [pa_usec_t, POINTER(pa_sample_spec)]
# /usr/include/pulse/sample.h:288
pa_sample_spec_init = _lib.pa_sample_spec_init
pa_sample_spec_init.restype = POINTER(pa_sample_spec)
pa_sample_spec_init.argtypes = [POINTER(pa_sample_spec)]
# /usr/include/pulse/sample.h:291
#pa_sample_format_valid = _lib.pa_sample_format_valid
#pa_sample_format_valid.restype = c_int
#pa_sample_format_valid.argtypes = [c_uint]
# /usr/include/pulse/sample.h:294
#pa_sample_rate_valid = _lib.pa_sample_rate_valid
#pa_sample_rate_valid.restype = c_int
#pa_sample_rate_valid.argtypes = [c_uint32]
# /usr/include/pulse/sample.h:298
#pa_channels_valid = _lib.pa_channels_valid
#pa_channels_valid.restype = c_int
#pa_channels_valid.argtypes = [c_uint8]
# /usr/include/pulse/sample.h:301
pa_sample_spec_valid = _lib.pa_sample_spec_valid
pa_sample_spec_valid.restype = c_int
pa_sample_spec_valid.argtypes = [POINTER(pa_sample_spec)]
# /usr/include/pulse/sample.h:304
pa_sample_spec_equal = _lib.pa_sample_spec_equal
pa_sample_spec_equal.restype = c_int
pa_sample_spec_equal.argtypes = [POINTER(pa_sample_spec), POINTER(pa_sample_spec)]
# /usr/include/pulse/sample.h:307
pa_sample_format_to_string = _lib.pa_sample_format_to_string
pa_sample_format_to_string.restype = c_char_p
pa_sample_format_to_string.argtypes = [pa_sample_format_t]
# /usr/include/pulse/sample.h:310
pa_parse_sample_format = _lib.pa_parse_sample_format
pa_parse_sample_format.restype = pa_sample_format_t
pa_parse_sample_format.argtypes = [c_char_p]
PA_SAMPLE_SPEC_SNPRINT_MAX = 32 # /usr/include/pulse/sample.h:317
# /usr/include/pulse/sample.h:320
pa_sample_spec_snprint = _lib.pa_sample_spec_snprint
pa_sample_spec_snprint.restype = c_char_p
pa_sample_spec_snprint.argtypes = [c_char_p, c_size_t, POINTER(pa_sample_spec)]
PA_BYTES_SNPRINT_MAX = 11 # /usr/include/pulse/sample.h:327
# /usr/include/pulse/sample.h:330
pa_bytes_snprint = _lib.pa_bytes_snprint
pa_bytes_snprint.restype = c_char_p
pa_bytes_snprint.argtypes = [c_char_p, c_size_t, c_uint]
# /usr/include/pulse/sample.h:334
pa_sample_format_is_le = _lib.pa_sample_format_is_le
pa_sample_format_is_le.restype = c_int
pa_sample_format_is_le.argtypes = [pa_sample_format_t]
# /usr/include/pulse/sample.h:338
pa_sample_format_is_be = _lib.pa_sample_format_is_be
pa_sample_format_is_be.restype = c_int
pa_sample_format_is_be.argtypes = [pa_sample_format_t]
enum_pa_context_state = c_int
PA_CONTEXT_UNCONNECTED = 0
PA_CONTEXT_CONNECTING = 1
PA_CONTEXT_AUTHORIZING = 2
PA_CONTEXT_SETTING_NAME = 3
PA_CONTEXT_READY = 4
PA_CONTEXT_FAILED = 5
PA_CONTEXT_TERMINATED = 6
pa_context_state_t = enum_pa_context_state # /usr/include/pulse/def.h:45
enum_pa_stream_state = c_int
PA_STREAM_UNCONNECTED = 0
PA_STREAM_CREATING = 1
PA_STREAM_READY = 2
PA_STREAM_FAILED = 3
PA_STREAM_TERMINATED = 4
pa_stream_state_t = enum_pa_stream_state # /usr/include/pulse/def.h:74
enum_pa_operation_state = c_int
PA_OPERATION_RUNNING = 0
PA_OPERATION_DONE = 1
PA_OPERATION_CANCELLED = 2
pa_operation_state_t = enum_pa_operation_state # /usr/include/pulse/def.h:102
enum_pa_context_flags = c_int
PA_CONTEXT_NOFLAGS = 0
PA_CONTEXT_NOAUTOSPAWN = 1
PA_CONTEXT_NOFAIL = 2
pa_context_flags_t = enum_pa_context_flags # /usr/include/pulse/def.h:122
enum_pa_direction = c_int
PA_DIRECTION_OUTPUT = 1
PA_DIRECTION_INPUT = 2
pa_direction_t = enum_pa_direction # /usr/include/pulse/def.h:137
enum_pa_device_type = c_int
PA_DEVICE_TYPE_SINK = 0
PA_DEVICE_TYPE_SOURCE = 1
pa_device_type_t = enum_pa_device_type # /usr/include/pulse/def.h:148
enum_pa_stream_direction = c_int
PA_STREAM_NODIRECTION = 0
PA_STREAM_PLAYBACK = 1
PA_STREAM_RECORD = 2
PA_STREAM_UPLOAD = 3
pa_stream_direction_t = enum_pa_stream_direction # /usr/include/pulse/def.h:161
enum_pa_stream_flags = c_int
PA_STREAM_NOFLAGS = 0
PA_STREAM_START_CORKED = 1
PA_STREAM_INTERPOLATE_TIMING = 2
PA_STREAM_NOT_MONOTONIC = 4
PA_STREAM_AUTO_TIMING_UPDATE = 8
PA_STREAM_NO_REMAP_CHANNELS = 16
PA_STREAM_NO_REMIX_CHANNELS = 32
PA_STREAM_FIX_FORMAT = 64
PA_STREAM_FIX_RATE = 128
PA_STREAM_FIX_CHANNELS = 256
PA_STREAM_DONT_MOVE = 512
PA_STREAM_VARIABLE_RATE = 1024
PA_STREAM_PEAK_DETECT = 2048
PA_STREAM_START_MUTED = 4096
PA_STREAM_ADJUST_LATENCY = 8192
PA_STREAM_EARLY_REQUESTS = 16384
PA_STREAM_DONT_INHIBIT_AUTO_SUSPEND = 32768
PA_STREAM_START_UNMUTED = 65536
PA_STREAM_FAIL_ON_SUSPEND = 131072
PA_STREAM_RELATIVE_VOLUME = 262144
PA_STREAM_PASSTHROUGH = 524288
pa_stream_flags_t = enum_pa_stream_flags # /usr/include/pulse/def.h:355
class struct_pa_buffer_attr(Structure):
__slots__ = [
'maxlength',
'tlength',
'prebuf',
'minreq',
'fragsize',
]
struct_pa_buffer_attr._fields_ = [
('maxlength', c_uint32),
('tlength', c_uint32),
('prebuf', c_uint32),
('minreq', c_uint32),
('fragsize', c_uint32),
]
pa_buffer_attr = struct_pa_buffer_attr # /usr/include/pulse/def.h:452
enum_pa_error_code = c_int
PA_OK = 0
PA_ERR_ACCESS = 1
PA_ERR_COMMAND = 2
PA_ERR_INVALID = 3
PA_ERR_EXIST = 4
PA_ERR_NOENTITY = 5
PA_ERR_CONNECTIONREFUSED = 6
PA_ERR_PROTOCOL = 7
PA_ERR_TIMEOUT = 8
PA_ERR_AUTHKEY = 9
PA_ERR_INTERNAL = 10
PA_ERR_CONNECTIONTERMINATED = 11
PA_ERR_KILLED = 12
PA_ERR_INVALIDSERVER = 13
PA_ERR_MODINITFAILED = 14
PA_ERR_BADSTATE = 15
PA_ERR_NODATA = 16
PA_ERR_VERSION = 17
PA_ERR_TOOLARGE = 18
PA_ERR_NOTSUPPORTED = 19
PA_ERR_UNKNOWN = 20
PA_ERR_NOEXTENSION = 21
PA_ERR_OBSOLETE = 22
PA_ERR_NOTIMPLEMENTED = 23
PA_ERR_FORKED = 24
PA_ERR_IO = 25
PA_ERR_BUSY = 26
PA_ERR_MAX = 27
pa_error_code_t = enum_pa_error_code # /usr/include/pulse/def.h:484
enum_pa_subscription_mask = c_int
PA_SUBSCRIPTION_MASK_NULL = 0
PA_SUBSCRIPTION_MASK_SINK = 1
PA_SUBSCRIPTION_MASK_SOURCE = 2
PA_SUBSCRIPTION_MASK_SINK_INPUT = 4
PA_SUBSCRIPTION_MASK_SOURCE_OUTPUT = 8
PA_SUBSCRIPTION_MASK_MODULE = 16
PA_SUBSCRIPTION_MASK_CLIENT = 32
PA_SUBSCRIPTION_MASK_SAMPLE_CACHE = 64
PA_SUBSCRIPTION_MASK_SERVER = 128
PA_SUBSCRIPTION_MASK_AUTOLOAD = 256
PA_SUBSCRIPTION_MASK_CARD = 512
PA_SUBSCRIPTION_MASK_ALL = 767
pa_subscription_mask_t = enum_pa_subscription_mask # /usr/include/pulse/def.h:554
enum_pa_subscription_event_type = c_int
PA_SUBSCRIPTION_EVENT_SINK = 0
PA_SUBSCRIPTION_EVENT_SOURCE = 1
PA_SUBSCRIPTION_EVENT_SINK_INPUT = 2
PA_SUBSCRIPTION_EVENT_SOURCE_OUTPUT = 3
PA_SUBSCRIPTION_EVENT_MODULE = 4
PA_SUBSCRIPTION_EVENT_CLIENT = 5
PA_SUBSCRIPTION_EVENT_SAMPLE_CACHE = 6
PA_SUBSCRIPTION_EVENT_SERVER = 7
PA_SUBSCRIPTION_EVENT_AUTOLOAD = 8
PA_SUBSCRIPTION_EVENT_CARD = 9
PA_SUBSCRIPTION_EVENT_FACILITY_MASK = 15
PA_SUBSCRIPTION_EVENT_NEW = 0
PA_SUBSCRIPTION_EVENT_CHANGE = 16
PA_SUBSCRIPTION_EVENT_REMOVE = 32
PA_SUBSCRIPTION_EVENT_TYPE_MASK = 48
pa_subscription_event_type_t = enum_pa_subscription_event_type # /usr/include/pulse/def.h:605
class struct_pa_timing_info(Structure):
__slots__ = [
'timestamp',
'synchronized_clocks',
'sink_usec',
'source_usec',
'transport_usec',
'playing',
'write_index_corrupt',
'write_index',
'read_index_corrupt',
'read_index',
'configured_sink_usec',
'configured_source_usec',
'since_underrun',
]
class struct_timeval(Structure):
__slots__ = [
]
struct_timeval._fields_ = [
('_opaque_struct', c_int)
]
struct_pa_timing_info._fields_ = [
('timestamp', struct_timeval),
('synchronized_clocks', c_int),
('sink_usec', pa_usec_t),
('source_usec', pa_usec_t),
('transport_usec', pa_usec_t),
('playing', c_int),
('write_index_corrupt', c_int),
('write_index', c_int64),
('read_index_corrupt', c_int),
('read_index', c_int64),
('configured_sink_usec', pa_usec_t),
('configured_source_usec', pa_usec_t),
('since_underrun', c_int64),
]
pa_timing_info = struct_pa_timing_info # /usr/include/pulse/def.h:725
class struct_pa_spawn_api(Structure):
__slots__ = [
'prefork',
'postfork',
'atfork',
]
struct_pa_spawn_api._fields_ = [
('prefork', POINTER(CFUNCTYPE(None))),
('postfork', POINTER(CFUNCTYPE(None))),
('atfork', POINTER(CFUNCTYPE(None))),
]
pa_spawn_api = struct_pa_spawn_api # /usr/include/pulse/def.h:749
enum_pa_seek_mode = c_int
PA_SEEK_RELATIVE = 0
PA_SEEK_ABSOLUTE = 1
PA_SEEK_RELATIVE_ON_READ = 2
PA_SEEK_RELATIVE_END = 3
pa_seek_mode_t = enum_pa_seek_mode # /usr/include/pulse/def.h:764
enum_pa_sink_flags = c_int
PA_SINK_NOFLAGS = 0
PA_SINK_HW_VOLUME_CTRL = 1
PA_SINK_LATENCY = 2
PA_SINK_HARDWARE = 4
PA_SINK_NETWORK = 8
PA_SINK_HW_MUTE_CTRL = 16
PA_SINK_DECIBEL_VOLUME = 32
PA_SINK_FLAT_VOLUME = 64
PA_SINK_DYNAMIC_LATENCY = 128
PA_SINK_SET_FORMATS = 256
pa_sink_flags_t = enum_pa_sink_flags # /usr/include/pulse/def.h:829
enum_pa_sink_state = c_int
PA_SINK_INVALID_STATE = -1
PA_SINK_RUNNING = 0
PA_SINK_IDLE = 1
PA_SINK_SUSPENDED = 2
PA_SINK_INIT = -2
PA_SINK_UNLINKED = -3
pa_sink_state_t = enum_pa_sink_state # /usr/include/pulse/def.h:875
enum_pa_source_flags = c_int
PA_SOURCE_NOFLAGS = 0
PA_SOURCE_HW_VOLUME_CTRL = 1
PA_SOURCE_LATENCY = 2
PA_SOURCE_HARDWARE = 4
PA_SOURCE_NETWORK = 8
PA_SOURCE_HW_MUTE_CTRL = 16
PA_SOURCE_DECIBEL_VOLUME = 32
PA_SOURCE_DYNAMIC_LATENCY = 64
PA_SOURCE_FLAT_VOLUME = 128
pa_source_flags_t = enum_pa_source_flags # /usr/include/pulse/def.h:946
enum_pa_source_state = c_int
PA_SOURCE_INVALID_STATE = -1
PA_SOURCE_RUNNING = 0
PA_SOURCE_IDLE = 1
PA_SOURCE_SUSPENDED = 2
PA_SOURCE_INIT = -2
PA_SOURCE_UNLINKED = -3
pa_source_state_t = enum_pa_source_state # /usr/include/pulse/def.h:991
pa_free_cb_t = CFUNCTYPE(None, POINTER(None)) # /usr/include/pulse/def.h:1014
enum_pa_port_available = c_int
PA_PORT_AVAILABLE_UNKNOWN = 0
PA_PORT_AVAILABLE_NO = 1
PA_PORT_AVAILABLE_YES = 2
pa_port_available_t = enum_pa_port_available # /usr/include/pulse/def.h:1040
class struct_pa_mainloop_api(Structure):
__slots__ = [
]
struct_pa_mainloop_api._fields_ = [
('_opaque_struct', c_int)
]
class struct_pa_mainloop_api(Structure):
__slots__ = [
]
struct_pa_mainloop_api._fields_ = [
('_opaque_struct', c_int)
]
pa_mainloop_api = struct_pa_mainloop_api # /usr/include/pulse/mainloop-api.h:47
enum_pa_io_event_flags = c_int
PA_IO_EVENT_NULL = 0
PA_IO_EVENT_INPUT = 1
PA_IO_EVENT_OUTPUT = 2
PA_IO_EVENT_HANGUP = 4
PA_IO_EVENT_ERROR = 8
pa_io_event_flags_t = enum_pa_io_event_flags # /usr/include/pulse/mainloop-api.h:56
class struct_pa_io_event(Structure):
__slots__ = [
]
struct_pa_io_event._fields_ = [
('_opaque_struct', c_int)
]
class struct_pa_io_event(Structure):
__slots__ = [
]
struct_pa_io_event._fields_ = [
('_opaque_struct', c_int)
]
pa_io_event = struct_pa_io_event # /usr/include/pulse/mainloop-api.h:59
pa_io_event_cb_t = CFUNCTYPE(None, POINTER(pa_mainloop_api), POINTER(pa_io_event), c_int, pa_io_event_flags_t, POINTER(None)) # /usr/include/pulse/mainloop-api.h:61
pa_io_event_destroy_cb_t = CFUNCTYPE(None, POINTER(pa_mainloop_api), POINTER(pa_io_event), POINTER(None)) # /usr/include/pulse/mainloop-api.h:63
class struct_pa_time_event(Structure):
__slots__ = [
]
struct_pa_time_event._fields_ = [
('_opaque_struct', c_int)
]
class struct_pa_time_event(Structure):
__slots__ = [
]
struct_pa_time_event._fields_ = [
('_opaque_struct', c_int)
]
pa_time_event = struct_pa_time_event # /usr/include/pulse/mainloop-api.h:66
class struct_timeval(Structure):
__slots__ = [
]
struct_timeval._fields_ = [
('_opaque_struct', c_int)
]
class struct_timeval(Structure):
__slots__ = [
]
struct_timeval._fields_ = [
('_opaque_struct', c_int)
]
pa_time_event_cb_t = CFUNCTYPE(None, POINTER(pa_mainloop_api), POINTER(pa_time_event), POINTER(struct_timeval), POINTER(None)) # /usr/include/pulse/mainloop-api.h:68
pa_time_event_destroy_cb_t = CFUNCTYPE(None, POINTER(pa_mainloop_api), POINTER(pa_time_event), POINTER(None)) # /usr/include/pulse/mainloop-api.h:70
class struct_pa_defer_event(Structure):
__slots__ = [
]
struct_pa_defer_event._fields_ = [
('_opaque_struct', c_int)
]
class struct_pa_defer_event(Structure):
__slots__ = [
]
struct_pa_defer_event._fields_ = [
('_opaque_struct', c_int)
]
pa_defer_event = struct_pa_defer_event # /usr/include/pulse/mainloop-api.h:73
pa_defer_event_cb_t = CFUNCTYPE(None, POINTER(pa_mainloop_api), POINTER(pa_defer_event), POINTER(None)) # /usr/include/pulse/mainloop-api.h:75
pa_defer_event_destroy_cb_t = CFUNCTYPE(None, POINTER(pa_mainloop_api), POINTER(pa_defer_event), POINTER(None)) # /usr/include/pulse/mainloop-api.h:77
# /usr/include/pulse/mainloop-api.h:120
pa_mainloop_api_once = _lib.pa_mainloop_api_once
pa_mainloop_api_once.restype = None
pa_mainloop_api_once.argtypes = [POINTER(pa_mainloop_api), CFUNCTYPE(None, POINTER(pa_mainloop_api), POINTER(None)), POINTER(None)]
enum_pa_channel_position = c_int
PA_CHANNEL_POSITION_INVALID = -1
PA_CHANNEL_POSITION_MONO = 0
PA_CHANNEL_POSITION_FRONT_LEFT = 1
PA_CHANNEL_POSITION_FRONT_RIGHT = 2
PA_CHANNEL_POSITION_FRONT_CENTER = 3
PA_CHANNEL_POSITION_LEFT = 0
PA_CHANNEL_POSITION_RIGHT = 0
PA_CHANNEL_POSITION_CENTER = 0
PA_CHANNEL_POSITION_REAR_CENTER = 1
PA_CHANNEL_POSITION_REAR_LEFT = 2
PA_CHANNEL_POSITION_REAR_RIGHT = 3
PA_CHANNEL_POSITION_LFE = 4
PA_CHANNEL_POSITION_SUBWOOFER = 0
PA_CHANNEL_POSITION_FRONT_LEFT_OF_CENTER = 1
PA_CHANNEL_POSITION_FRONT_RIGHT_OF_CENTER = 2
PA_CHANNEL_POSITION_SIDE_LEFT = 3
PA_CHANNEL_POSITION_SIDE_RIGHT = 4
PA_CHANNEL_POSITION_AUX0 = 5
PA_CHANNEL_POSITION_AUX1 = 6
PA_CHANNEL_POSITION_AUX2 = 7
PA_CHANNEL_POSITION_AUX3 = 8
PA_CHANNEL_POSITION_AUX4 = 9
PA_CHANNEL_POSITION_AUX5 = 10
PA_CHANNEL_POSITION_AUX6 = 11
PA_CHANNEL_POSITION_AUX7 = 12
PA_CHANNEL_POSITION_AUX8 = 13
PA_CHANNEL_POSITION_AUX9 = 14
PA_CHANNEL_POSITION_AUX10 = 15
PA_CHANNEL_POSITION_AUX11 = 16
PA_CHANNEL_POSITION_AUX12 = 17
PA_CHANNEL_POSITION_AUX13 = 18
PA_CHANNEL_POSITION_AUX14 = 19
PA_CHANNEL_POSITION_AUX15 = 20
PA_CHANNEL_POSITION_AUX16 = 21
PA_CHANNEL_POSITION_AUX17 = 22
PA_CHANNEL_POSITION_AUX18 = 23
PA_CHANNEL_POSITION_AUX19 = 24
PA_CHANNEL_POSITION_AUX20 = 25
PA_CHANNEL_POSITION_AUX21 = 26
PA_CHANNEL_POSITION_AUX22 = 27
PA_CHANNEL_POSITION_AUX23 = 28
PA_CHANNEL_POSITION_AUX24 = 29
PA_CHANNEL_POSITION_AUX25 = 30
PA_CHANNEL_POSITION_AUX26 = 31
PA_CHANNEL_POSITION_AUX27 = 32
PA_CHANNEL_POSITION_AUX28 = 33
PA_CHANNEL_POSITION_AUX29 = 34
PA_CHANNEL_POSITION_AUX30 = 35
PA_CHANNEL_POSITION_AUX31 = 36
PA_CHANNEL_POSITION_TOP_CENTER = 37
PA_CHANNEL_POSITION_TOP_FRONT_LEFT = 38
PA_CHANNEL_POSITION_TOP_FRONT_RIGHT = 39
PA_CHANNEL_POSITION_TOP_FRONT_CENTER = 40
PA_CHANNEL_POSITION_TOP_REAR_LEFT = 41
PA_CHANNEL_POSITION_TOP_REAR_RIGHT = 42
PA_CHANNEL_POSITION_TOP_REAR_CENTER = 43
PA_CHANNEL_POSITION_MAX = 44
pa_channel_position_t = enum_pa_channel_position # /usr/include/pulse/channelmap.h:147
pa_channel_position_mask_t = c_uint64 # /usr/include/pulse/channelmap.h:210
enum_pa_channel_map_def = c_int
PA_CHANNEL_MAP_AIFF = 0
PA_CHANNEL_MAP_ALSA = 1
PA_CHANNEL_MAP_AUX = 2
PA_CHANNEL_MAP_WAVEEX = 3
PA_CHANNEL_MAP_OSS = 4
PA_CHANNEL_MAP_DEF_MAX = 5
PA_CHANNEL_MAP_DEFAULT = 0
pa_channel_map_def_t = enum_pa_channel_map_def # /usr/include/pulse/channelmap.h:247
class struct_pa_channel_map(Structure):
__slots__ = [
'channels',
'map',
]
struct_pa_channel_map._fields_ = [
('channels', c_uint8),
('map', pa_channel_position_t * 32),
]
pa_channel_map = struct_pa_channel_map # /usr/include/pulse/channelmap.h:268
# /usr/include/pulse/channelmap.h:273
pa_channel_map_init = _lib.pa_channel_map_init
pa_channel_map_init.restype = POINTER(pa_channel_map)
pa_channel_map_init.argtypes = [POINTER(pa_channel_map)]
# /usr/include/pulse/channelmap.h:276
pa_channel_map_init_mono = _lib.pa_channel_map_init_mono
pa_channel_map_init_mono.restype = POINTER(pa_channel_map)
pa_channel_map_init_mono.argtypes = [POINTER(pa_channel_map)]
# /usr/include/pulse/channelmap.h:279
pa_channel_map_init_stereo = _lib.pa_channel_map_init_stereo
pa_channel_map_init_stereo.restype = POINTER(pa_channel_map)
pa_channel_map_init_stereo.argtypes = [POINTER(pa_channel_map)]
# /usr/include/pulse/channelmap.h:285
pa_channel_map_init_auto = _lib.pa_channel_map_init_auto
pa_channel_map_init_auto.restype = POINTER(pa_channel_map)
pa_channel_map_init_auto.argtypes = [POINTER(pa_channel_map), c_uint, pa_channel_map_def_t]
# /usr/include/pulse/channelmap.h:291
pa_channel_map_init_extend = _lib.pa_channel_map_init_extend
pa_channel_map_init_extend.restype = POINTER(pa_channel_map)
pa_channel_map_init_extend.argtypes = [POINTER(pa_channel_map), c_uint, pa_channel_map_def_t]
# /usr/include/pulse/channelmap.h:294
pa_channel_position_to_string = _lib.pa_channel_position_to_string
pa_channel_position_to_string.restype = c_char_p
pa_channel_position_to_string.argtypes = [pa_channel_position_t]
# /usr/include/pulse/channelmap.h:297
pa_channel_position_from_string = _lib.pa_channel_position_from_string
pa_channel_position_from_string.restype = pa_channel_position_t
pa_channel_position_from_string.argtypes = [c_char_p]
# /usr/include/pulse/channelmap.h:300
pa_channel_position_to_pretty_string = _lib.pa_channel_position_to_pretty_string
pa_channel_position_to_pretty_string.restype = c_char_p
pa_channel_position_to_pretty_string.argtypes = [pa_channel_position_t]
PA_CHANNEL_MAP_SNPRINT_MAX = 336 # /usr/include/pulse/channelmap.h:307
# /usr/include/pulse/channelmap.h:310
pa_channel_map_snprint = _lib.pa_channel_map_snprint
pa_channel_map_snprint.restype = c_char_p
pa_channel_map_snprint.argtypes = [c_char_p, c_size_t, POINTER(pa_channel_map)]
# /usr/include/pulse/channelmap.h:316
pa_channel_map_parse = _lib.pa_channel_map_parse
pa_channel_map_parse.restype = POINTER(pa_channel_map)
pa_channel_map_parse.argtypes = [POINTER(pa_channel_map), c_char_p]
# /usr/include/pulse/channelmap.h:319
pa_channel_map_equal = _lib.pa_channel_map_equal
pa_channel_map_equal.restype = c_int
pa_channel_map_equal.argtypes = [POINTER(pa_channel_map), POINTER(pa_channel_map)]
# /usr/include/pulse/channelmap.h:322
pa_channel_map_valid = _lib.pa_channel_map_valid
pa_channel_map_valid.restype = c_int
pa_channel_map_valid.argtypes = [POINTER(pa_channel_map)]
# /usr/include/pulse/channelmap.h:326
pa_channel_map_compatible = _lib.pa_channel_map_compatible
pa_channel_map_compatible.restype = c_int
pa_channel_map_compatible.argtypes = [POINTER(pa_channel_map), POINTER(pa_sample_spec)]
# /usr/include/pulse/channelmap.h:329
pa_channel_map_superset = _lib.pa_channel_map_superset
pa_channel_map_superset.restype = c_int
pa_channel_map_superset.argtypes = [POINTER(pa_channel_map), POINTER(pa_channel_map)]
# /usr/include/pulse/channelmap.h:334
pa_channel_map_can_balance = _lib.pa_channel_map_can_balance
pa_channel_map_can_balance.restype = c_int
pa_channel_map_can_balance.argtypes = [POINTER(pa_channel_map)]
# /usr/include/pulse/channelmap.h:339
pa_channel_map_can_fade = _lib.pa_channel_map_can_fade
pa_channel_map_can_fade.restype = c_int
pa_channel_map_can_fade.argtypes = [POINTER(pa_channel_map)]
# /usr/include/pulse/channelmap.h:345
pa_channel_map_to_name = _lib.pa_channel_map_to_name
pa_channel_map_to_name.restype = c_char_p
pa_channel_map_to_name.argtypes = [POINTER(pa_channel_map)]
# /usr/include/pulse/channelmap.h:350
pa_channel_map_to_pretty_name = _lib.pa_channel_map_to_pretty_name
pa_channel_map_to_pretty_name.restype = c_char_p
pa_channel_map_to_pretty_name.argtypes = [POINTER(pa_channel_map)]
# /usr/include/pulse/channelmap.h:354
pa_channel_map_has_position = _lib.pa_channel_map_has_position
pa_channel_map_has_position.restype = c_int
pa_channel_map_has_position.argtypes = [POINTER(pa_channel_map), pa_channel_position_t]
# /usr/include/pulse/channelmap.h:357
pa_channel_map_mask = _lib.pa_channel_map_mask
pa_channel_map_mask.restype = pa_channel_position_mask_t
pa_channel_map_mask.argtypes = [POINTER(pa_channel_map)]
class struct_pa_operation(Structure):
__slots__ = [
]
struct_pa_operation._fields_ = [
('_opaque_struct', c_int)
]
class struct_pa_operation(Structure):
__slots__ = [
]
struct_pa_operation._fields_ = [
('_opaque_struct', c_int)
]
pa_operation = struct_pa_operation # /usr/include/pulse/operation.h:33
pa_operation_notify_cb_t = CFUNCTYPE(None, POINTER(pa_operation), POINTER(None)) # /usr/include/pulse/operation.h:36
# /usr/include/pulse/operation.h:39
pa_operation_ref = _lib.pa_operation_ref
pa_operation_ref.restype = POINTER(pa_operation)
pa_operation_ref.argtypes = [POINTER(pa_operation)]
# /usr/include/pulse/operation.h:42
pa_operation_unref = _lib.pa_operation_unref
pa_operation_unref.restype = None
pa_operation_unref.argtypes = [POINTER(pa_operation)]
# /usr/include/pulse/operation.h:49
pa_operation_cancel = _lib.pa_operation_cancel
pa_operation_cancel.restype = None
pa_operation_cancel.argtypes = [POINTER(pa_operation)]
# /usr/include/pulse/operation.h:52
pa_operation_get_state = _lib.pa_operation_get_state
pa_operation_get_state.restype = pa_operation_state_t
pa_operation_get_state.argtypes = [POINTER(pa_operation)]
# /usr/include/pulse/operation.h:60
pa_operation_set_state_callback = _lib.pa_operation_set_state_callback
pa_operation_set_state_callback.restype = None
pa_operation_set_state_callback.argtypes = [POINTER(pa_operation), pa_operation_notify_cb_t, POINTER(None)]
class struct_pa_context(Structure):
__slots__ = [
]
struct_pa_context._fields_ = [
('_opaque_struct', c_int)
]
class struct_pa_context(Structure):
__slots__ = [
]
struct_pa_context._fields_ = [
('_opaque_struct', c_int)
]
pa_context = struct_pa_context # /usr/include/pulse/context.h:154
pa_context_notify_cb_t = CFUNCTYPE(None, POINTER(pa_context), POINTER(None)) # /usr/include/pulse/context.h:157
pa_context_success_cb_t = CFUNCTYPE(None, POINTER(pa_context), c_int, POINTER(None)) # /usr/include/pulse/context.h:160
class struct_pa_proplist(Structure):
__slots__ = [
]
struct_pa_proplist._fields_ = [
('_opaque_struct', c_int)
]
class struct_pa_proplist(Structure):
__slots__ = [
]
struct_pa_proplist._fields_ = [
('_opaque_struct', c_int)
]
pa_proplist = struct_pa_proplist # /usr/include/pulse/proplist.h:272
pa_context_event_cb_t = CFUNCTYPE(None, POINTER(pa_context), c_char_p, POINTER(pa_proplist), POINTER(None)) # /usr/include/pulse/context.h:167
# /usr/include/pulse/context.h:172
pa_context_new = _lib.pa_context_new
pa_context_new.restype = POINTER(pa_context)
pa_context_new.argtypes = [POINTER(pa_mainloop_api), c_char_p]
# /usr/include/pulse/context.h:177
pa_context_new_with_proplist = _lib.pa_context_new_with_proplist
pa_context_new_with_proplist.restype = POINTER(pa_context)
pa_context_new_with_proplist.argtypes = [POINTER(pa_mainloop_api), c_char_p, POINTER(pa_proplist)]
# /usr/include/pulse/context.h:180
pa_context_unref = _lib.pa_context_unref
pa_context_unref.restype = None
pa_context_unref.argtypes = [POINTER(pa_context)]
# /usr/include/pulse/context.h:183
pa_context_ref = _lib.pa_context_ref
pa_context_ref.restype = POINTER(pa_context)
pa_context_ref.argtypes = [POINTER(pa_context)]
# /usr/include/pulse/context.h:186
pa_context_set_state_callback = _lib.pa_context_set_state_callback
pa_context_set_state_callback.restype = None
pa_context_set_state_callback.argtypes = [POINTER(pa_context), pa_context_notify_cb_t, POINTER(None)]
# /usr/include/pulse/context.h:190
pa_context_set_event_callback = _lib.pa_context_set_event_callback
pa_context_set_event_callback.restype = None
pa_context_set_event_callback.argtypes = [POINTER(pa_context), pa_context_event_cb_t, POINTER(None)]
# /usr/include/pulse/context.h:193
pa_context_errno = _lib.pa_context_errno
pa_context_errno.restype = c_int
pa_context_errno.argtypes = [POINTER(pa_context)]
# /usr/include/pulse/context.h:196
pa_context_is_pending = _lib.pa_context_is_pending
pa_context_is_pending.restype = c_int
pa_context_is_pending.argtypes = [POINTER(pa_context)]
# /usr/include/pulse/context.h:199
pa_context_get_state = _lib.pa_context_get_state
pa_context_get_state.restype = pa_context_state_t
pa_context_get_state.argtypes = [POINTER(pa_context)]
# /usr/include/pulse/context.h:209
pa_context_connect = _lib.pa_context_connect
pa_context_connect.restype = c_int
pa_context_connect.argtypes = [POINTER(pa_context), c_char_p, pa_context_flags_t, POINTER(pa_spawn_api)]
# /usr/include/pulse/context.h:212
pa_context_disconnect = _lib.pa_context_disconnect
pa_context_disconnect.restype = None
pa_context_disconnect.argtypes = [POINTER(pa_context)]
# /usr/include/pulse/context.h:215
pa_context_drain = _lib.pa_context_drain
pa_context_drain.restype = POINTER(pa_operation)
pa_context_drain.argtypes = [POINTER(pa_context), pa_context_notify_cb_t, POINTER(None)]
# /usr/include/pulse/context.h:220
pa_context_exit_daemon = _lib.pa_context_exit_daemon
pa_context_exit_daemon.restype = POINTER(pa_operation)
pa_context_exit_daemon.argtypes = [POINTER(pa_context), pa_context_success_cb_t, POINTER(None)]
# /usr/include/pulse/context.h:223
pa_context_set_default_sink = _lib.pa_context_set_default_sink
pa_context_set_default_sink.restype = POINTER(pa_operation)
pa_context_set_default_sink.argtypes = [POINTER(pa_context), c_char_p, pa_context_success_cb_t, POINTER(None)]
# /usr/include/pulse/context.h:226
pa_context_set_default_source = _lib.pa_context_set_default_source
pa_context_set_default_source.restype = POINTER(pa_operation)
pa_context_set_default_source.argtypes = [POINTER(pa_context), c_char_p, pa_context_success_cb_t, POINTER(None)]
# /usr/include/pulse/context.h:229
pa_context_is_local = _lib.pa_context_is_local
pa_context_is_local.restype = c_int
pa_context_is_local.argtypes = [POINTER(pa_context)]
# /usr/include/pulse/context.h:232
pa_context_set_name = _lib.pa_context_set_name
pa_context_set_name.restype = POINTER(pa_operation)
pa_context_set_name.argtypes = [POINTER(pa_context), c_char_p, pa_context_success_cb_t, POINTER(None)]
# /usr/include/pulse/context.h:235
pa_context_get_server = _lib.pa_context_get_server
pa_context_get_server.restype = c_char_p
pa_context_get_server.argtypes = [POINTER(pa_context)]
# /usr/include/pulse/context.h:238
pa_context_get_protocol_version = _lib.pa_context_get_protocol_version
pa_context_get_protocol_version.restype = c_uint32
pa_context_get_protocol_version.argtypes = [POINTER(pa_context)]
# /usr/include/pulse/context.h:241
pa_context_get_server_protocol_version = _lib.pa_context_get_server_protocol_version
pa_context_get_server_protocol_version.restype = c_uint32
pa_context_get_server_protocol_version.argtypes = [POINTER(pa_context)]
enum_pa_update_mode = c_int
PA_UPDATE_SET = 0
PA_UPDATE_MERGE = 1
PA_UPDATE_REPLACE = 2
pa_update_mode_t = enum_pa_update_mode # /usr/include/pulse/proplist.h:337
# /usr/include/pulse/context.h:248
pa_context_proplist_update = _lib.pa_context_proplist_update
pa_context_proplist_update.restype = POINTER(pa_operation)
pa_context_proplist_update.argtypes = [POINTER(pa_context), pa_update_mode_t, POINTER(pa_proplist), pa_context_success_cb_t, POINTER(None)]
# /usr/include/pulse/context.h:251
pa_context_proplist_remove = _lib.pa_context_proplist_remove
pa_context_proplist_remove.restype = POINTER(pa_operation)
pa_context_proplist_remove.argtypes = [POINTER(pa_context), POINTER(c_char_p), pa_context_success_cb_t, POINTER(None)]
# /usr/include/pulse/context.h:256
pa_context_get_index = _lib.pa_context_get_index
pa_context_get_index.restype = c_uint32
pa_context_get_index.argtypes = [POINTER(pa_context)]
# /usr/include/pulse/context.h:260
pa_context_rttime_new = _lib.pa_context_rttime_new
pa_context_rttime_new.restype = POINTER(pa_time_event)
pa_context_rttime_new.argtypes = [POINTER(pa_context), pa_usec_t, pa_time_event_cb_t, POINTER(None)]
# /usr/include/pulse/context.h:264
pa_context_rttime_restart = _lib.pa_context_rttime_restart
pa_context_rttime_restart.restype = None
pa_context_rttime_restart.argtypes = [POINTER(pa_context), POINTER(pa_time_event), pa_usec_t]
# /usr/include/pulse/context.h:279
pa_context_get_tile_size = _lib.pa_context_get_tile_size
pa_context_get_tile_size.restype = c_size_t
pa_context_get_tile_size.argtypes = [POINTER(pa_context), POINTER(pa_sample_spec)]
# /usr/include/pulse/context.h:287
pa_context_load_cookie_from_file = _lib.pa_context_load_cookie_from_file
pa_context_load_cookie_from_file.restype = c_int
pa_context_load_cookie_from_file.argtypes = [POINTER(pa_context), c_char_p]
pa_volume_t = c_uint32 # /usr/include/pulse/volume.h:120
class struct_pa_cvolume(Structure):
__slots__ = [
'channels',
'values',
]
struct_pa_cvolume._fields_ = [
('channels', c_uint8),
('values', pa_volume_t * 32),
]
pa_cvolume = struct_pa_cvolume # /usr/include/pulse/volume.h:151
# /usr/include/pulse/volume.h:154
pa_cvolume_equal = _lib.pa_cvolume_equal
pa_cvolume_equal.restype = c_int
pa_cvolume_equal.argtypes = [POINTER(pa_cvolume), POINTER(pa_cvolume)]
# /usr/include/pulse/volume.h:159
pa_cvolume_init = _lib.pa_cvolume_init
pa_cvolume_init.restype = POINTER(pa_cvolume)
pa_cvolume_init.argtypes = [POINTER(pa_cvolume)]
# /usr/include/pulse/volume.h:168
pa_cvolume_set = _lib.pa_cvolume_set
pa_cvolume_set.restype = POINTER(pa_cvolume)
pa_cvolume_set.argtypes = [POINTER(pa_cvolume), c_uint, pa_volume_t]
PA_CVOLUME_SNPRINT_MAX = 320 # /usr/include/pulse/volume.h:175
# /usr/include/pulse/volume.h:178
pa_cvolume_snprint = _lib.pa_cvolume_snprint
pa_cvolume_snprint.restype = c_char_p
pa_cvolume_snprint.argtypes = [c_char_p, c_size_t, POINTER(pa_cvolume)]
PA_SW_CVOLUME_SNPRINT_DB_MAX = 448 # /usr/include/pulse/volume.h:185
# /usr/include/pulse/volume.h:188
pa_sw_cvolume_snprint_dB = _lib.pa_sw_cvolume_snprint_dB
pa_sw_cvolume_snprint_dB.restype = c_char_p
pa_sw_cvolume_snprint_dB.argtypes = [c_char_p, c_size_t, POINTER(pa_cvolume)]
PA_CVOLUME_SNPRINT_VERBOSE_MAX = 1984 # /usr/include/pulse/volume.h:194
# /usr/include/pulse/volume.h:200
#pa_cvolume_snprint_verbose = _lib.pa_cvolume_snprint_verbose
#pa_cvolume_snprint_verbose.restype = c_char_p
#pa_cvolume_snprint_verbose.argtypes = [c_char_p, c_size_t, POINTER(pa_cvolume), POINTER(pa_channel_map), c_int]
PA_VOLUME_SNPRINT_MAX = 10 # /usr/include/pulse/volume.h:207
# /usr/include/pulse/volume.h:210
pa_volume_snprint = _lib.pa_volume_snprint
pa_volume_snprint.restype = c_char_p
pa_volume_snprint.argtypes = [c_char_p, c_size_t, pa_volume_t]
PA_SW_VOLUME_SNPRINT_DB_MAX = 11 # /usr/include/pulse/volume.h:217
# /usr/include/pulse/volume.h:220
pa_sw_volume_snprint_dB = _lib.pa_sw_volume_snprint_dB
pa_sw_volume_snprint_dB.restype = c_char_p
pa_sw_volume_snprint_dB.argtypes = [c_char_p, c_size_t, pa_volume_t]
PA_VOLUME_SNPRINT_VERBOSE_MAX = 35 # /usr/include/pulse/volume.h:226
# /usr/include/pulse/volume.h:231
#pa_volume_snprint_verbose = _lib.pa_volume_snprint_verbose
#pa_volume_snprint_verbose.restype = c_char_p
#pa_volume_snprint_verbose.argtypes = [c_char_p, c_size_t, pa_volume_t, c_int]
# /usr/include/pulse/volume.h:234
pa_cvolume_avg = _lib.pa_cvolume_avg
pa_cvolume_avg.restype = pa_volume_t
pa_cvolume_avg.argtypes = [POINTER(pa_cvolume)]
# /usr/include/pulse/volume.h:241
pa_cvolume_avg_mask = _lib.pa_cvolume_avg_mask
pa_cvolume_avg_mask.restype = pa_volume_t
pa_cvolume_avg_mask.argtypes = [POINTER(pa_cvolume), POINTER(pa_channel_map), pa_channel_position_mask_t]
# /usr/include/pulse/volume.h:244
pa_cvolume_max = _lib.pa_cvolume_max
pa_cvolume_max.restype = pa_volume_t
pa_cvolume_max.argtypes = [POINTER(pa_cvolume)]
# /usr/include/pulse/volume.h:251
pa_cvolume_max_mask = _lib.pa_cvolume_max_mask
pa_cvolume_max_mask.restype = pa_volume_t
pa_cvolume_max_mask.argtypes = [POINTER(pa_cvolume), POINTER(pa_channel_map), pa_channel_position_mask_t]
# /usr/include/pulse/volume.h:254
pa_cvolume_min = _lib.pa_cvolume_min
pa_cvolume_min.restype = pa_volume_t
pa_cvolume_min.argtypes = [POINTER(pa_cvolume)]
# /usr/include/pulse/volume.h:261
pa_cvolume_min_mask = _lib.pa_cvolume_min_mask
pa_cvolume_min_mask.restype = pa_volume_t
pa_cvolume_min_mask.argtypes = [POINTER(pa_cvolume), POINTER(pa_channel_map), pa_channel_position_mask_t]
# /usr/include/pulse/volume.h:264
pa_cvolume_valid = _lib.pa_cvolume_valid
pa_cvolume_valid.restype = c_int
pa_cvolume_valid.argtypes = [POINTER(pa_cvolume)]
# /usr/include/pulse/volume.h:267
pa_cvolume_channels_equal_to = _lib.pa_cvolume_channels_equal_to
pa_cvolume_channels_equal_to.restype = c_int
pa_cvolume_channels_equal_to.argtypes = [POINTER(pa_cvolume), pa_volume_t]
# /usr/include/pulse/volume.h:278
pa_sw_volume_multiply = _lib.pa_sw_volume_multiply
pa_sw_volume_multiply.restype = pa_volume_t
pa_sw_volume_multiply.argtypes = [pa_volume_t, pa_volume_t]
# /usr/include/pulse/volume.h:283
pa_sw_cvolume_multiply = _lib.pa_sw_cvolume_multiply
pa_sw_cvolume_multiply.restype = POINTER(pa_cvolume)
pa_sw_cvolume_multiply.argtypes = [POINTER(pa_cvolume), POINTER(pa_cvolume), POINTER(pa_cvolume)]
# /usr/include/pulse/volume.h:289
pa_sw_cvolume_multiply_scalar = _lib.pa_sw_cvolume_multiply_scalar
pa_sw_cvolume_multiply_scalar.restype = POINTER(pa_cvolume)
pa_sw_cvolume_multiply_scalar.argtypes = [POINTER(pa_cvolume), POINTER(pa_cvolume), pa_volume_t]
# /usr/include/pulse/volume.h:295
pa_sw_volume_divide = _lib.pa_sw_volume_divide
pa_sw_volume_divide.restype = pa_volume_t
pa_sw_volume_divide.argtypes = [pa_volume_t, pa_volume_t]
# /usr/include/pulse/volume.h:300
pa_sw_cvolume_divide = _lib.pa_sw_cvolume_divide
pa_sw_cvolume_divide.restype = POINTER(pa_cvolume)
pa_sw_cvolume_divide.argtypes = [POINTER(pa_cvolume), POINTER(pa_cvolume), POINTER(pa_cvolume)]
# /usr/include/pulse/volume.h:306
pa_sw_cvolume_divide_scalar = _lib.pa_sw_cvolume_divide_scalar
pa_sw_cvolume_divide_scalar.restype = POINTER(pa_cvolume)
pa_sw_cvolume_divide_scalar.argtypes = [POINTER(pa_cvolume), POINTER(pa_cvolume), pa_volume_t]
# /usr/include/pulse/volume.h:309
pa_sw_volume_from_dB = _lib.pa_sw_volume_from_dB
pa_sw_volume_from_dB.restype = pa_volume_t
pa_sw_volume_from_dB.argtypes = [c_double]
# /usr/include/pulse/volume.h:312
pa_sw_volume_to_dB = _lib.pa_sw_volume_to_dB
pa_sw_volume_to_dB.restype = c_double
pa_sw_volume_to_dB.argtypes = [pa_volume_t]
# /usr/include/pulse/volume.h:316
pa_sw_volume_from_linear = _lib.pa_sw_volume_from_linear
pa_sw_volume_from_linear.restype = pa_volume_t
pa_sw_volume_from_linear.argtypes = [c_double]
# /usr/include/pulse/volume.h:319
pa_sw_volume_to_linear = _lib.pa_sw_volume_to_linear
pa_sw_volume_to_linear.restype = c_double
pa_sw_volume_to_linear.argtypes = [pa_volume_t]
# /usr/include/pulse/volume.h:329
pa_cvolume_remap = _lib.pa_cvolume_remap
pa_cvolume_remap.restype = POINTER(pa_cvolume)
pa_cvolume_remap.argtypes = [POINTER(pa_cvolume), POINTER(pa_channel_map), POINTER(pa_channel_map)]
# /usr/include/pulse/volume.h:333
pa_cvolume_compatible = _lib.pa_cvolume_compatible
pa_cvolume_compatible.restype = c_int
pa_cvolume_compatible.argtypes = [POINTER(pa_cvolume), POINTER(pa_sample_spec)]
# /usr/include/pulse/volume.h:337
pa_cvolume_compatible_with_channel_map = _lib.pa_cvolume_compatible_with_channel_map
pa_cvolume_compatible_with_channel_map.restype = c_int
pa_cvolume_compatible_with_channel_map.argtypes = [POINTER(pa_cvolume), POINTER(pa_channel_map)]
# /usr/include/pulse/volume.h:344
pa_cvolume_get_balance = _lib.pa_cvolume_get_balance
pa_cvolume_get_balance.restype = c_float
pa_cvolume_get_balance.argtypes = [POINTER(pa_cvolume), POINTER(pa_channel_map)]
# /usr/include/pulse/volume.h:355
pa_cvolume_set_balance = _lib.pa_cvolume_set_balance
pa_cvolume_set_balance.restype = POINTER(pa_cvolume)
pa_cvolume_set_balance.argtypes = [POINTER(pa_cvolume), POINTER(pa_channel_map), c_float]
# /usr/include/pulse/volume.h:362
pa_cvolume_get_fade = _lib.pa_cvolume_get_fade
pa_cvolume_get_fade.restype = c_float
pa_cvolume_get_fade.argtypes = [POINTER(pa_cvolume), POINTER(pa_channel_map)]
# /usr/include/pulse/volume.h:373
pa_cvolume_set_fade = _lib.pa_cvolume_set_fade
pa_cvolume_set_fade.restype = POINTER(pa_cvolume)
pa_cvolume_set_fade.argtypes = [POINTER(pa_cvolume), POINTER(pa_channel_map), c_float]
# /usr/include/pulse/volume.h:378
pa_cvolume_scale = _lib.pa_cvolume_scale
pa_cvolume_scale.restype = POINTER(pa_cvolume)
pa_cvolume_scale.argtypes = [POINTER(pa_cvolume), pa_volume_t]
# /usr/include/pulse/volume.h:384
pa_cvolume_scale_mask = _lib.pa_cvolume_scale_mask
pa_cvolume_scale_mask.restype = POINTER(pa_cvolume)
pa_cvolume_scale_mask.argtypes = [POINTER(pa_cvolume), pa_volume_t, POINTER(pa_channel_map), pa_channel_position_mask_t]
# /usr/include/pulse/volume.h:391
pa_cvolume_set_position = _lib.pa_cvolume_set_position
pa_cvolume_set_position.restype = POINTER(pa_cvolume)
pa_cvolume_set_position.argtypes = [POINTER(pa_cvolume), POINTER(pa_channel_map), pa_channel_position_t, pa_volume_t]
# /usr/include/pulse/volume.h:397
pa_cvolume_get_position = _lib.pa_cvolume_get_position
pa_cvolume_get_position.restype = pa_volume_t
pa_cvolume_get_position.argtypes = [POINTER(pa_cvolume), POINTER(pa_channel_map), pa_channel_position_t]
# /usr/include/pulse/volume.h:402
pa_cvolume_merge = _lib.pa_cvolume_merge
pa_cvolume_merge.restype = POINTER(pa_cvolume)
pa_cvolume_merge.argtypes = [POINTER(pa_cvolume), POINTER(pa_cvolume), POINTER(pa_cvolume)]
# /usr/include/pulse/volume.h:406
pa_cvolume_inc_clamp = _lib.pa_cvolume_inc_clamp
pa_cvolume_inc_clamp.restype = POINTER(pa_cvolume)
pa_cvolume_inc_clamp.argtypes = [POINTER(pa_cvolume), pa_volume_t, pa_volume_t]
# /usr/include/pulse/volume.h:410
pa_cvolume_inc = _lib.pa_cvolume_inc
pa_cvolume_inc.restype = POINTER(pa_cvolume)
pa_cvolume_inc.argtypes = [POINTER(pa_cvolume), pa_volume_t]
# /usr/include/pulse/volume.h:414
pa_cvolume_dec = _lib.pa_cvolume_dec
pa_cvolume_dec.restype = POINTER(pa_cvolume)
pa_cvolume_dec.argtypes = [POINTER(pa_cvolume), pa_volume_t]
class struct_pa_stream(Structure):
__slots__ = [
]
struct_pa_stream._fields_ = [
('_opaque_struct', c_int)
]
class struct_pa_stream(Structure):
__slots__ = [
]
struct_pa_stream._fields_ = [
('_opaque_struct', c_int)
]
pa_stream = struct_pa_stream # /usr/include/pulse/stream.h:335
pa_stream_success_cb_t = CFUNCTYPE(None, POINTER(pa_stream), c_int, POINTER(None)) # /usr/include/pulse/stream.h:338
pa_stream_request_cb_t = CFUNCTYPE(None, POINTER(pa_stream), c_size_t, POINTER(None)) # /usr/include/pulse/stream.h:341
pa_stream_notify_cb_t = CFUNCTYPE(None, POINTER(pa_stream), POINTER(None)) # /usr/include/pulse/stream.h:344
pa_stream_event_cb_t = CFUNCTYPE(None, POINTER(pa_stream), c_char_p, POINTER(pa_proplist), POINTER(None)) # /usr/include/pulse/stream.h:352
# /usr/include/pulse/stream.h:357
pa_stream_new = _lib.pa_stream_new
pa_stream_new.restype = POINTER(pa_stream)
pa_stream_new.argtypes = [POINTER(pa_context), c_char_p, POINTER(pa_sample_spec), POINTER(pa_channel_map)]
# /usr/include/pulse/stream.h:366
pa_stream_new_with_proplist = _lib.pa_stream_new_with_proplist
pa_stream_new_with_proplist.restype = POINTER(pa_stream)
pa_stream_new_with_proplist.argtypes = [POINTER(pa_context), c_char_p, POINTER(pa_sample_spec), POINTER(pa_channel_map), POINTER(pa_proplist)]
class struct_pa_format_info(Structure):
__slots__ = [
'encoding',
'plist',
]
enum_pa_encoding = c_int
PA_ENCODING_ANY = 0
PA_ENCODING_PCM = 1
PA_ENCODING_AC3_IEC61937 = 2
PA_ENCODING_EAC3_IEC61937 = 3
PA_ENCODING_MPEG_IEC61937 = 4
PA_ENCODING_DTS_IEC61937 = 5
PA_ENCODING_MPEG2_AAC_IEC61937 = 6
PA_ENCODING_MAX = 7
PA_ENCODING_INVALID = -1
pa_encoding_t = enum_pa_encoding # /usr/include/pulse/format.h:64
struct_pa_format_info._fields_ = [
('encoding', pa_encoding_t),
('plist', POINTER(pa_proplist)),
]
pa_format_info = struct_pa_format_info # /usr/include/pulse/format.h:91
# /usr/include/pulse/stream.h:377
pa_stream_new_extended = _lib.pa_stream_new_extended
pa_stream_new_extended.restype = POINTER(pa_stream)
pa_stream_new_extended.argtypes = [POINTER(pa_context), c_char_p, POINTER(POINTER(pa_format_info)), c_uint, POINTER(pa_proplist)]
# /usr/include/pulse/stream.h:385
pa_stream_unref = _lib.pa_stream_unref
pa_stream_unref.restype = None
pa_stream_unref.argtypes = [POINTER(pa_stream)]
# /usr/include/pulse/stream.h:388
pa_stream_ref = _lib.pa_stream_ref
pa_stream_ref.restype = POINTER(pa_stream)
pa_stream_ref.argtypes = [POINTER(pa_stream)]
# /usr/include/pulse/stream.h:391
pa_stream_get_state = _lib.pa_stream_get_state
pa_stream_get_state.restype = pa_stream_state_t
pa_stream_get_state.argtypes = [POINTER(pa_stream)]
# /usr/include/pulse/stream.h:394
pa_stream_get_context = _lib.pa_stream_get_context
pa_stream_get_context.restype = POINTER(pa_context)
pa_stream_get_context.argtypes = [POINTER(pa_stream)]
# /usr/include/pulse/stream.h:400
pa_stream_get_index = _lib.pa_stream_get_index
pa_stream_get_index.restype = c_uint32
pa_stream_get_index.argtypes = [POINTER(pa_stream)]
# /usr/include/pulse/stream.h:411
pa_stream_get_device_index = _lib.pa_stream_get_device_index
pa_stream_get_device_index.restype = c_uint32
pa_stream_get_device_index.argtypes = [POINTER(pa_stream)]
# /usr/include/pulse/stream.h:422
pa_stream_get_device_name = _lib.pa_stream_get_device_name
pa_stream_get_device_name.restype = c_char_p
pa_stream_get_device_name.argtypes = [POINTER(pa_stream)]
# /usr/include/pulse/stream.h:428
pa_stream_is_suspended = _lib.pa_stream_is_suspended
pa_stream_is_suspended.restype = c_int
pa_stream_is_suspended.argtypes = [POINTER(pa_stream)]
# /usr/include/pulse/stream.h:432
pa_stream_is_corked = _lib.pa_stream_is_corked
pa_stream_is_corked.restype = c_int
pa_stream_is_corked.argtypes = [POINTER(pa_stream)]
# /usr/include/pulse/stream.h:458
pa_stream_connect_playback = _lib.pa_stream_connect_playback
pa_stream_connect_playback.restype = c_int
pa_stream_connect_playback.argtypes = [POINTER(pa_stream), c_char_p, POINTER(pa_buffer_attr), pa_stream_flags_t, POINTER(pa_cvolume), POINTER(pa_stream)]
# /usr/include/pulse/stream.h:467
pa_stream_connect_record = _lib.pa_stream_connect_record
pa_stream_connect_record.restype = c_int
pa_stream_connect_record.argtypes = [POINTER(pa_stream), c_char_p, POINTER(pa_buffer_attr), pa_stream_flags_t]
# /usr/include/pulse/stream.h:474
pa_stream_disconnect = _lib.pa_stream_disconnect
pa_stream_disconnect.restype = c_int
pa_stream_disconnect.argtypes = [POINTER(pa_stream)]
# /usr/include/pulse/stream.h:508
pa_stream_begin_write = _lib.pa_stream_begin_write
pa_stream_begin_write.restype = c_int
pa_stream_begin_write.argtypes = [POINTER(pa_stream), POINTER(POINTER(None)), POINTER(c_size_t)]
# /usr/include/pulse/stream.h:522
pa_stream_cancel_write = _lib.pa_stream_cancel_write
pa_stream_cancel_write.restype = c_int
pa_stream_cancel_write.argtypes = [POINTER(pa_stream)]
# /usr/include/pulse/stream.h:547
pa_stream_write = _lib.pa_stream_write
pa_stream_write.restype = c_int
pa_stream_write.argtypes = [POINTER(pa_stream), POINTER(None), c_size_t, pa_free_cb_t, c_int64, pa_seek_mode_t]
# /usr/include/pulse/stream.h:557
#pa_stream_write_ext_free = _lib.pa_stream_write_ext_free
#pa_stream_write_ext_free.restype = c_int
#pa_stream_write_ext_free.argtypes = [POINTER(pa_stream), POINTER(None), c_size_t, pa_free_cb_t, POINTER(None), c_int64, pa_seek_mode_t]
# /usr/include/pulse/stream.h:582
pa_stream_peek = _lib.pa_stream_peek
pa_stream_peek.restype = c_int
pa_stream_peek.argtypes = [POINTER(pa_stream), POINTER(POINTER(None)), POINTER(c_size_t)]
# /usr/include/pulse/stream.h:589
pa_stream_drop = _lib.pa_stream_drop
pa_stream_drop.restype = c_int
pa_stream_drop.argtypes = [POINTER(pa_stream)]
# /usr/include/pulse/stream.h:592
pa_stream_writable_size = _lib.pa_stream_writable_size
pa_stream_writable_size.restype = c_size_t
pa_stream_writable_size.argtypes = [POINTER(pa_stream)]
# /usr/include/pulse/stream.h:595
pa_stream_readable_size = _lib.pa_stream_readable_size
pa_stream_readable_size.restype = c_size_t
pa_stream_readable_size.argtypes = [POINTER(pa_stream)]
# /usr/include/pulse/stream.h:601
pa_stream_drain = _lib.pa_stream_drain
pa_stream_drain.restype = POINTER(pa_operation)
pa_stream_drain.argtypes = [POINTER(pa_stream), pa_stream_success_cb_t, POINTER(None)]
# /usr/include/pulse/stream.h:607
pa_stream_update_timing_info = _lib.pa_stream_update_timing_info
pa_stream_update_timing_info.restype = POINTER(pa_operation)
pa_stream_update_timing_info.argtypes = [POINTER(pa_stream), pa_stream_success_cb_t, POINTER(None)]
# /usr/include/pulse/stream.h:610
pa_stream_set_state_callback = _lib.pa_stream_set_state_callback
pa_stream_set_state_callback.restype = None
pa_stream_set_state_callback.argtypes = [POINTER(pa_stream), pa_stream_notify_cb_t, POINTER(None)]
# /usr/include/pulse/stream.h:614
pa_stream_set_write_callback = _lib.pa_stream_set_write_callback
pa_stream_set_write_callback.restype = None
pa_stream_set_write_callback.argtypes = [POINTER(pa_stream), pa_stream_request_cb_t, POINTER(None)]
# /usr/include/pulse/stream.h:617
pa_stream_set_read_callback = _lib.pa_stream_set_read_callback
pa_stream_set_read_callback.restype = None
pa_stream_set_read_callback.argtypes = [POINTER(pa_stream), pa_stream_request_cb_t, POINTER(None)]
# /usr/include/pulse/stream.h:620
pa_stream_set_overflow_callback = _lib.pa_stream_set_overflow_callback
pa_stream_set_overflow_callback.restype = None
pa_stream_set_overflow_callback.argtypes = [POINTER(pa_stream), pa_stream_notify_cb_t, POINTER(None)]
# /usr/include/pulse/stream.h:626
pa_stream_get_underflow_index = _lib.pa_stream_get_underflow_index
pa_stream_get_underflow_index.restype = c_int64
pa_stream_get_underflow_index.argtypes = [POINTER(pa_stream)]
# /usr/include/pulse/stream.h:629
pa_stream_set_underflow_callback = _lib.pa_stream_set_underflow_callback
pa_stream_set_underflow_callback.restype = None
pa_stream_set_underflow_callback.argtypes = [POINTER(pa_stream), pa_stream_notify_cb_t, POINTER(None)]
# /usr/include/pulse/stream.h:636
pa_stream_set_started_callback = _lib.pa_stream_set_started_callback
pa_stream_set_started_callback.restype = None
pa_stream_set_started_callback.argtypes = [POINTER(pa_stream), pa_stream_notify_cb_t, POINTER(None)]
# /usr/include/pulse/stream.h:641
pa_stream_set_latency_update_callback = _lib.pa_stream_set_latency_update_callback
pa_stream_set_latency_update_callback.restype = None
pa_stream_set_latency_update_callback.argtypes = [POINTER(pa_stream), pa_stream_notify_cb_t, POINTER(None)]
# /usr/include/pulse/stream.h:648
pa_stream_set_moved_callback = _lib.pa_stream_set_moved_callback
pa_stream_set_moved_callback.restype = None
pa_stream_set_moved_callback.argtypes = [POINTER(pa_stream), pa_stream_notify_cb_t, POINTER(None)]
# /usr/include/pulse/stream.h:658
pa_stream_set_suspended_callback = _lib.pa_stream_set_suspended_callback
pa_stream_set_suspended_callback.restype = None
pa_stream_set_suspended_callback.argtypes = [POINTER(pa_stream), pa_stream_notify_cb_t, POINTER(None)]
# /usr/include/pulse/stream.h:662
pa_stream_set_event_callback = _lib.pa_stream_set_event_callback
pa_stream_set_event_callback.restype = None
pa_stream_set_event_callback.argtypes = [POINTER(pa_stream), pa_stream_event_cb_t, POINTER(None)]
# /usr/include/pulse/stream.h:669
pa_stream_set_buffer_attr_callback = _lib.pa_stream_set_buffer_attr_callback
pa_stream_set_buffer_attr_callback.restype = None
pa_stream_set_buffer_attr_callback.argtypes = [POINTER(pa_stream), pa_stream_notify_cb_t, POINTER(None)]
# /usr/include/pulse/stream.h:681
pa_stream_cork = _lib.pa_stream_cork
pa_stream_cork.restype = POINTER(pa_operation)
pa_stream_cork.argtypes = [POINTER(pa_stream), c_int, pa_stream_success_cb_t, POINTER(None)]
# /usr/include/pulse/stream.h:686
pa_stream_flush = _lib.pa_stream_flush
pa_stream_flush.restype = POINTER(pa_operation)
pa_stream_flush.argtypes = [POINTER(pa_stream), pa_stream_success_cb_t, POINTER(None)]
# /usr/include/pulse/stream.h:690
pa_stream_prebuf = _lib.pa_stream_prebuf
pa_stream_prebuf.restype = POINTER(pa_operation)
pa_stream_prebuf.argtypes = [POINTER(pa_stream), pa_stream_success_cb_t, POINTER(None)]
# /usr/include/pulse/stream.h:695
pa_stream_trigger = _lib.pa_stream_trigger
pa_stream_trigger.restype = POINTER(pa_operation)
pa_stream_trigger.argtypes = [POINTER(pa_stream), pa_stream_success_cb_t, POINTER(None)]
# /usr/include/pulse/stream.h:698
pa_stream_set_name = _lib.pa_stream_set_name
pa_stream_set_name.restype = POINTER(pa_operation)
pa_stream_set_name.argtypes = [POINTER(pa_stream), c_char_p, pa_stream_success_cb_t, POINTER(None)]
# /usr/include/pulse/stream.h:731
pa_stream_get_time = _lib.pa_stream_get_time
pa_stream_get_time.restype = c_int
pa_stream_get_time.argtypes = [POINTER(pa_stream), POINTER(pa_usec_t)]
# /usr/include/pulse/stream.h:745
pa_stream_get_latency = _lib.pa_stream_get_latency
pa_stream_get_latency.restype = c_int
pa_stream_get_latency.argtypes = [POINTER(pa_stream), POINTER(pa_usec_t), POINTER(c_int)]
# /usr/include/pulse/stream.h:761
pa_stream_get_timing_info = _lib.pa_stream_get_timing_info
pa_stream_get_timing_info.restype = POINTER(pa_timing_info)
pa_stream_get_timing_info.argtypes = [POINTER(pa_stream)]
# /usr/include/pulse/stream.h:764
pa_stream_get_sample_spec = _lib.pa_stream_get_sample_spec
pa_stream_get_sample_spec.restype = POINTER(pa_sample_spec)
pa_stream_get_sample_spec.argtypes = [POINTER(pa_stream)]
# /usr/include/pulse/stream.h:767
pa_stream_get_channel_map = _lib.pa_stream_get_channel_map
pa_stream_get_channel_map.restype = POINTER(pa_channel_map)
pa_stream_get_channel_map.argtypes = [POINTER(pa_stream)]
# /usr/include/pulse/stream.h:770
pa_stream_get_format_info = _lib.pa_stream_get_format_info
pa_stream_get_format_info.restype = POINTER(pa_format_info)
pa_stream_get_format_info.argtypes = [POINTER(pa_stream)]
# /usr/include/pulse/stream.h:780
pa_stream_get_buffer_attr = _lib.pa_stream_get_buffer_attr
pa_stream_get_buffer_attr.restype = POINTER(pa_buffer_attr)
pa_stream_get_buffer_attr.argtypes = [POINTER(pa_stream)]
# /usr/include/pulse/stream.h:790
pa_stream_set_buffer_attr = _lib.pa_stream_set_buffer_attr
pa_stream_set_buffer_attr.restype = POINTER(pa_operation)
pa_stream_set_buffer_attr.argtypes = [POINTER(pa_stream), POINTER(pa_buffer_attr), pa_stream_success_cb_t, POINTER(None)]
# /usr/include/pulse/stream.h:797
pa_stream_update_sample_rate = _lib.pa_stream_update_sample_rate
pa_stream_update_sample_rate.restype = POINTER(pa_operation)
pa_stream_update_sample_rate.argtypes = [POINTER(pa_stream), c_uint32, pa_stream_success_cb_t, POINTER(None)]
# /usr/include/pulse/stream.h:805
pa_stream_proplist_update = _lib.pa_stream_proplist_update
pa_stream_proplist_update.restype = POINTER(pa_operation)
pa_stream_proplist_update.argtypes = [POINTER(pa_stream), pa_update_mode_t, POINTER(pa_proplist), pa_stream_success_cb_t, POINTER(None)]
# /usr/include/pulse/stream.h:809
pa_stream_proplist_remove = _lib.pa_stream_proplist_remove
pa_stream_proplist_remove.restype = POINTER(pa_operation)
pa_stream_proplist_remove.argtypes = [POINTER(pa_stream), POINTER(c_char_p), pa_stream_success_cb_t, POINTER(None)]
# /usr/include/pulse/stream.h:815
pa_stream_set_monitor_stream = _lib.pa_stream_set_monitor_stream
pa_stream_set_monitor_stream.restype = c_int
pa_stream_set_monitor_stream.argtypes = [POINTER(pa_stream), c_uint32]
# /usr/include/pulse/stream.h:820
pa_stream_get_monitor_stream = _lib.pa_stream_get_monitor_stream
pa_stream_get_monitor_stream.restype = c_uint32
pa_stream_get_monitor_stream.argtypes = [POINTER(pa_stream)]
class struct_pa_sink_port_info(Structure):
__slots__ = [
'name',
'description',
'priority',
'available',
]
struct_pa_sink_port_info._fields_ = [
('name', c_char_p),
('description', c_char_p),
('priority', c_uint32),
('available', c_int),
]
pa_sink_port_info = struct_pa_sink_port_info # /usr/include/pulse/introspect.h:232
class struct_pa_sink_info(Structure):
__slots__ = [
'name',
'index',
'description',
'sample_spec',
'channel_map',
'owner_module',
'volume',
'mute',
'monitor_source',
'monitor_source_name',
'latency',
'driver',
'flags',
'proplist',
'configured_latency',
'base_volume',
'state',
'n_volume_steps',
'card',
'n_ports',
'ports',
'active_port',
'n_formats',
'formats',
]
struct_pa_sink_info._fields_ = [
('name', c_char_p),
('index', c_uint32),
('description', c_char_p),
('sample_spec', pa_sample_spec),
('channel_map', pa_channel_map),
('owner_module', c_uint32),
('volume', pa_cvolume),
('mute', c_int),
('monitor_source', c_uint32),
('monitor_source_name', c_char_p),
('latency', pa_usec_t),
('driver', c_char_p),
('flags', pa_sink_flags_t),
('proplist', POINTER(pa_proplist)),
('configured_latency', pa_usec_t),
('base_volume', pa_volume_t),
('state', pa_sink_state_t),
('n_volume_steps', c_uint32),
('card', c_uint32),
('n_ports', c_uint32),
('ports', POINTER(POINTER(pa_sink_port_info))),
('active_port', POINTER(pa_sink_port_info)),
('n_formats', c_uint8),
('formats', POINTER(POINTER(pa_format_info))),
]
pa_sink_info = struct_pa_sink_info # /usr/include/pulse/introspect.h:262
pa_sink_info_cb_t = CFUNCTYPE(None, POINTER(pa_context), POINTER(pa_sink_info), c_int, POINTER(None)) # /usr/include/pulse/introspect.h:265
# /usr/include/pulse/introspect.h:268
pa_context_get_sink_info_by_name = _lib.pa_context_get_sink_info_by_name
pa_context_get_sink_info_by_name.restype = POINTER(pa_operation)
pa_context_get_sink_info_by_name.argtypes = [POINTER(pa_context), c_char_p, pa_sink_info_cb_t, POINTER(None)]
# /usr/include/pulse/introspect.h:271
pa_context_get_sink_info_by_index = _lib.pa_context_get_sink_info_by_index
pa_context_get_sink_info_by_index.restype = POINTER(pa_operation)
pa_context_get_sink_info_by_index.argtypes = [POINTER(pa_context), c_uint32, pa_sink_info_cb_t, POINTER(None)]
# /usr/include/pulse/introspect.h:274
pa_context_get_sink_info_list = _lib.pa_context_get_sink_info_list
pa_context_get_sink_info_list.restype = POINTER(pa_operation)
pa_context_get_sink_info_list.argtypes = [POINTER(pa_context), pa_sink_info_cb_t, POINTER(None)]
# /usr/include/pulse/introspect.h:277
pa_context_set_sink_volume_by_index = _lib.pa_context_set_sink_volume_by_index
pa_context_set_sink_volume_by_index.restype = POINTER(pa_operation)
pa_context_set_sink_volume_by_index.argtypes = [POINTER(pa_context), c_uint32, POINTER(pa_cvolume), pa_context_success_cb_t, POINTER(None)]
# /usr/include/pulse/introspect.h:280
pa_context_set_sink_volume_by_name = _lib.pa_context_set_sink_volume_by_name
pa_context_set_sink_volume_by_name.restype = POINTER(pa_operation)
pa_context_set_sink_volume_by_name.argtypes = [POINTER(pa_context), c_char_p, POINTER(pa_cvolume), pa_context_success_cb_t, POINTER(None)]
# /usr/include/pulse/introspect.h:283
pa_context_set_sink_mute_by_index = _lib.pa_context_set_sink_mute_by_index
pa_context_set_sink_mute_by_index.restype = POINTER(pa_operation)
pa_context_set_sink_mute_by_index.argtypes = [POINTER(pa_context), c_uint32, c_int, pa_context_success_cb_t, POINTER(None)]
# /usr/include/pulse/introspect.h:286
pa_context_set_sink_mute_by_name = _lib.pa_context_set_sink_mute_by_name
pa_context_set_sink_mute_by_name.restype = POINTER(pa_operation)
pa_context_set_sink_mute_by_name.argtypes = [POINTER(pa_context), c_char_p, c_int, pa_context_success_cb_t, POINTER(None)]
# /usr/include/pulse/introspect.h:289
pa_context_suspend_sink_by_name = _lib.pa_context_suspend_sink_by_name
pa_context_suspend_sink_by_name.restype = POINTER(pa_operation)
pa_context_suspend_sink_by_name.argtypes = [POINTER(pa_context), c_char_p, c_int, pa_context_success_cb_t, POINTER(None)]
# /usr/include/pulse/introspect.h:292
pa_context_suspend_sink_by_index = _lib.pa_context_suspend_sink_by_index
pa_context_suspend_sink_by_index.restype = POINTER(pa_operation)
pa_context_suspend_sink_by_index.argtypes = [POINTER(pa_context), c_uint32, c_int, pa_context_success_cb_t, POINTER(None)]
# /usr/include/pulse/introspect.h:295
pa_context_set_sink_port_by_index = _lib.pa_context_set_sink_port_by_index
pa_context_set_sink_port_by_index.restype = POINTER(pa_operation)
pa_context_set_sink_port_by_index.argtypes = [POINTER(pa_context), c_uint32, c_char_p, pa_context_success_cb_t, POINTER(None)]
# /usr/include/pulse/introspect.h:298
pa_context_set_sink_port_by_name = _lib.pa_context_set_sink_port_by_name
pa_context_set_sink_port_by_name.restype = POINTER(pa_operation)
pa_context_set_sink_port_by_name.argtypes = [POINTER(pa_context), c_char_p, c_char_p, pa_context_success_cb_t, POINTER(None)]
class struct_pa_source_port_info(Structure):
__slots__ = [
'name',
'description',
'priority',
'available',
]
struct_pa_source_port_info._fields_ = [
('name', c_char_p),
('description', c_char_p),
('priority', c_uint32),
('available', c_int),
]
pa_source_port_info = struct_pa_source_port_info # /usr/include/pulse/introspect.h:312
class struct_pa_source_info(Structure):
__slots__ = [
'name',
'index',
'description',
'sample_spec',
'channel_map',
'owner_module',
'volume',
'mute',
'monitor_of_sink',
'monitor_of_sink_name',
'latency',
'driver',
'flags',
'proplist',
'configured_latency',
'base_volume',
'state',
'n_volume_steps',
'card',
'n_ports',
'ports',
'active_port',
'n_formats',
'formats',
]
struct_pa_source_info._fields_ = [
('name', c_char_p),
('index', c_uint32),
('description', c_char_p),
('sample_spec', pa_sample_spec),
('channel_map', pa_channel_map),
('owner_module', c_uint32),
('volume', pa_cvolume),
('mute', c_int),
('monitor_of_sink', c_uint32),
('monitor_of_sink_name', c_char_p),
('latency', pa_usec_t),
('driver', c_char_p),
('flags', pa_source_flags_t),
('proplist', POINTER(pa_proplist)),
('configured_latency', pa_usec_t),
('base_volume', pa_volume_t),
('state', pa_source_state_t),
('n_volume_steps', c_uint32),
('card', c_uint32),
('n_ports', c_uint32),
('ports', POINTER(POINTER(pa_source_port_info))),
('active_port', POINTER(pa_source_port_info)),
('n_formats', c_uint8),
('formats', POINTER(POINTER(pa_format_info))),
]
pa_source_info = struct_pa_source_info # /usr/include/pulse/introspect.h:342
pa_source_info_cb_t = CFUNCTYPE(None, POINTER(pa_context), POINTER(pa_source_info), c_int, POINTER(None)) # /usr/include/pulse/introspect.h:345
# /usr/include/pulse/introspect.h:348
pa_context_get_source_info_by_name = _lib.pa_context_get_source_info_by_name
pa_context_get_source_info_by_name.restype = POINTER(pa_operation)
pa_context_get_source_info_by_name.argtypes = [POINTER(pa_context), c_char_p, pa_source_info_cb_t, POINTER(None)]
# /usr/include/pulse/introspect.h:351
pa_context_get_source_info_by_index = _lib.pa_context_get_source_info_by_index
pa_context_get_source_info_by_index.restype = POINTER(pa_operation)
pa_context_get_source_info_by_index.argtypes = [POINTER(pa_context), c_uint32, pa_source_info_cb_t, POINTER(None)]
# /usr/include/pulse/introspect.h:354
pa_context_get_source_info_list = _lib.pa_context_get_source_info_list
pa_context_get_source_info_list.restype = POINTER(pa_operation)
pa_context_get_source_info_list.argtypes = [POINTER(pa_context), pa_source_info_cb_t, POINTER(None)]
# /usr/include/pulse/introspect.h:357
pa_context_set_source_volume_by_index = _lib.pa_context_set_source_volume_by_index
pa_context_set_source_volume_by_index.restype = POINTER(pa_operation)
pa_context_set_source_volume_by_index.argtypes = [POINTER(pa_context), c_uint32, POINTER(pa_cvolume), pa_context_success_cb_t, POINTER(None)]
# /usr/include/pulse/introspect.h:360
pa_context_set_source_volume_by_name = _lib.pa_context_set_source_volume_by_name
pa_context_set_source_volume_by_name.restype = POINTER(pa_operation)
pa_context_set_source_volume_by_name.argtypes = [POINTER(pa_context), c_char_p, POINTER(pa_cvolume), pa_context_success_cb_t, POINTER(None)]
# /usr/include/pulse/introspect.h:363
pa_context_set_source_mute_by_index = _lib.pa_context_set_source_mute_by_index
pa_context_set_source_mute_by_index.restype = POINTER(pa_operation)
pa_context_set_source_mute_by_index.argtypes = [POINTER(pa_context), c_uint32, c_int, pa_context_success_cb_t, POINTER(None)]
# /usr/include/pulse/introspect.h:366
pa_context_set_source_mute_by_name = _lib.pa_context_set_source_mute_by_name
pa_context_set_source_mute_by_name.restype = POINTER(pa_operation)
pa_context_set_source_mute_by_name.argtypes = [POINTER(pa_context), c_char_p, c_int, pa_context_success_cb_t, POINTER(None)]
# /usr/include/pulse/introspect.h:369
pa_context_suspend_source_by_name = _lib.pa_context_suspend_source_by_name
pa_context_suspend_source_by_name.restype = POINTER(pa_operation)
pa_context_suspend_source_by_name.argtypes = [POINTER(pa_context), c_char_p, c_int, pa_context_success_cb_t, POINTER(None)]
# /usr/include/pulse/introspect.h:372
pa_context_suspend_source_by_index = _lib.pa_context_suspend_source_by_index
pa_context_suspend_source_by_index.restype = POINTER(pa_operation)
pa_context_suspend_source_by_index.argtypes = [POINTER(pa_context), c_uint32, c_int, pa_context_success_cb_t, POINTER(None)]
# /usr/include/pulse/introspect.h:375
pa_context_set_source_port_by_index = _lib.pa_context_set_source_port_by_index
pa_context_set_source_port_by_index.restype = POINTER(pa_operation)
pa_context_set_source_port_by_index.argtypes = [POINTER(pa_context), c_uint32, c_char_p, pa_context_success_cb_t, POINTER(None)]
# /usr/include/pulse/introspect.h:378
pa_context_set_source_port_by_name = _lib.pa_context_set_source_port_by_name
pa_context_set_source_port_by_name.restype = POINTER(pa_operation)
pa_context_set_source_port_by_name.argtypes = [POINTER(pa_context), c_char_p, c_char_p, pa_context_success_cb_t, POINTER(None)]
class struct_pa_server_info(Structure):
__slots__ = [
'user_name',
'host_name',
'server_version',
'server_name',
'sample_spec',
'default_sink_name',
'default_source_name',
'cookie',
'channel_map',
]
struct_pa_server_info._fields_ = [
('user_name', c_char_p),
('host_name', c_char_p),
('server_version', c_char_p),
('server_name', c_char_p),
('sample_spec', pa_sample_spec),
('default_sink_name', c_char_p),
('default_source_name', c_char_p),
('cookie', c_uint32),
('channel_map', pa_channel_map),
]
pa_server_info = struct_pa_server_info # /usr/include/pulse/introspect.h:397
pa_server_info_cb_t = CFUNCTYPE(None, POINTER(pa_context), POINTER(pa_server_info), POINTER(None)) # /usr/include/pulse/introspect.h:400
# /usr/include/pulse/introspect.h:403
pa_context_get_server_info = _lib.pa_context_get_server_info
pa_context_get_server_info.restype = POINTER(pa_operation)
pa_context_get_server_info.argtypes = [POINTER(pa_context), pa_server_info_cb_t, POINTER(None)]
class struct_pa_module_info(Structure):
__slots__ = [
'index',
'name',
'argument',
'n_used',
'auto_unload',
'proplist',
]
struct_pa_module_info._fields_ = [
('index', c_uint32),
('name', c_char_p),
('argument', c_char_p),
('n_used', c_uint32),
('auto_unload', c_int),
('proplist', POINTER(pa_proplist)),
]
pa_module_info = struct_pa_module_info # /usr/include/pulse/introspect.h:421
pa_module_info_cb_t = CFUNCTYPE(None, POINTER(pa_context), POINTER(pa_module_info), c_int, POINTER(None)) # /usr/include/pulse/introspect.h:424
# /usr/include/pulse/introspect.h:427
pa_context_get_module_info = _lib.pa_context_get_module_info
pa_context_get_module_info.restype = POINTER(pa_operation)
pa_context_get_module_info.argtypes = [POINTER(pa_context), c_uint32, pa_module_info_cb_t, POINTER(None)]
# /usr/include/pulse/introspect.h:430
pa_context_get_module_info_list = _lib.pa_context_get_module_info_list
pa_context_get_module_info_list.restype = POINTER(pa_operation)
pa_context_get_module_info_list.argtypes = [POINTER(pa_context), pa_module_info_cb_t, POINTER(None)]
pa_context_index_cb_t = CFUNCTYPE(None, POINTER(pa_context), c_uint32, POINTER(None)) # /usr/include/pulse/introspect.h:433
# /usr/include/pulse/introspect.h:436
pa_context_load_module = _lib.pa_context_load_module
pa_context_load_module.restype = POINTER(pa_operation)
pa_context_load_module.argtypes = [POINTER(pa_context), c_char_p, c_char_p, pa_context_index_cb_t, POINTER(None)]
# /usr/include/pulse/introspect.h:439
pa_context_unload_module = _lib.pa_context_unload_module
pa_context_unload_module.restype = POINTER(pa_operation)
pa_context_unload_module.argtypes = [POINTER(pa_context), c_uint32, pa_context_success_cb_t, POINTER(None)]
class struct_pa_client_info(Structure):
__slots__ = [
'index',
'name',
'owner_module',
'driver',
'proplist',
]
struct_pa_client_info._fields_ = [
('index', c_uint32),
('name', c_char_p),
('owner_module', c_uint32),
('driver', c_char_p),
('proplist', POINTER(pa_proplist)),
]
pa_client_info = struct_pa_client_info # /usr/include/pulse/introspect.h:454
pa_client_info_cb_t = CFUNCTYPE(None, POINTER(pa_context), POINTER(pa_client_info), c_int, POINTER(None)) # /usr/include/pulse/introspect.h:457
# /usr/include/pulse/introspect.h:460
pa_context_get_client_info = _lib.pa_context_get_client_info
pa_context_get_client_info.restype = POINTER(pa_operation)
pa_context_get_client_info.argtypes = [POINTER(pa_context), c_uint32, pa_client_info_cb_t, POINTER(None)]
# /usr/include/pulse/introspect.h:463
pa_context_get_client_info_list = _lib.pa_context_get_client_info_list
pa_context_get_client_info_list.restype = POINTER(pa_operation)
pa_context_get_client_info_list.argtypes = [POINTER(pa_context), pa_client_info_cb_t, POINTER(None)]
# /usr/include/pulse/introspect.h:466
pa_context_kill_client = _lib.pa_context_kill_client
pa_context_kill_client.restype = POINTER(pa_operation)
pa_context_kill_client.argtypes = [POINTER(pa_context), c_uint32, pa_context_success_cb_t, POINTER(None)]
class struct_pa_card_profile_info(Structure):
__slots__ = [
'name',
'description',
'n_sinks',
'n_sources',
'priority',
]
struct_pa_card_profile_info._fields_ = [
('name', c_char_p),
('description', c_char_p),
('n_sinks', c_uint32),
('n_sources', c_uint32),
('priority', c_uint32),
]
pa_card_profile_info = struct_pa_card_profile_info # /usr/include/pulse/introspect.h:479
class struct_pa_card_profile_info2(Structure):
__slots__ = [
'name',
'description',
'n_sinks',
'n_sources',
'priority',
'available',
]
struct_pa_card_profile_info2._fields_ = [
('name', c_char_p),
('description', c_char_p),
('n_sinks', c_uint32),
('n_sources', c_uint32),
('priority', c_uint32),
('available', c_int),
]
pa_card_profile_info2 = struct_pa_card_profile_info2 # /usr/include/pulse/introspect.h:496
class struct_pa_card_port_info(Structure):
__slots__ = [
'name',
'description',
'priority',
'available',
'direction',
'n_profiles',
'profiles',
'proplist',
'latency_offset',
'profiles2',
]
struct_pa_card_port_info._fields_ = [
('name', c_char_p),
('description', c_char_p),
('priority', c_uint32),
('available', c_int),
('direction', c_int),
('n_profiles', c_uint32),
('profiles', POINTER(POINTER(pa_card_profile_info))),
('proplist', POINTER(pa_proplist)),
('latency_offset', c_int64),
('profiles2', POINTER(POINTER(pa_card_profile_info2))),
]
pa_card_port_info = struct_pa_card_port_info # /usr/include/pulse/introspect.h:512
class struct_pa_card_info(Structure):
__slots__ = [
'index',
'name',
'owner_module',
'driver',
'n_profiles',
'profiles',
'active_profile',
'proplist',
'n_ports',
'ports',
'profiles2',
'active_profile2',
]
struct_pa_card_info._fields_ = [
('index', c_uint32),
('name', c_char_p),
('owner_module', c_uint32),
('driver', c_char_p),
('n_profiles', c_uint32),
('profiles', POINTER(pa_card_profile_info)),
('active_profile', POINTER(pa_card_profile_info)),
('proplist', POINTER(pa_proplist)),
('n_ports', c_uint32),
('ports', POINTER(POINTER(pa_card_port_info))),
('profiles2', POINTER(POINTER(pa_card_profile_info2))),
('active_profile2', POINTER(pa_card_profile_info2)),
]
pa_card_info = struct_pa_card_info # /usr/include/pulse/introspect.h:530
pa_card_info_cb_t = CFUNCTYPE(None, POINTER(pa_context), POINTER(pa_card_info), c_int, POINTER(None)) # /usr/include/pulse/introspect.h:533
# /usr/include/pulse/introspect.h:536
pa_context_get_card_info_by_index = _lib.pa_context_get_card_info_by_index
pa_context_get_card_info_by_index.restype = POINTER(pa_operation)
pa_context_get_card_info_by_index.argtypes = [POINTER(pa_context), c_uint32, pa_card_info_cb_t, POINTER(None)]
# /usr/include/pulse/introspect.h:539
pa_context_get_card_info_by_name = _lib.pa_context_get_card_info_by_name
pa_context_get_card_info_by_name.restype = POINTER(pa_operation)
pa_context_get_card_info_by_name.argtypes = [POINTER(pa_context), c_char_p, pa_card_info_cb_t, POINTER(None)]
# /usr/include/pulse/introspect.h:542
pa_context_get_card_info_list = _lib.pa_context_get_card_info_list
pa_context_get_card_info_list.restype = POINTER(pa_operation)
pa_context_get_card_info_list.argtypes = [POINTER(pa_context), pa_card_info_cb_t, POINTER(None)]
# /usr/include/pulse/introspect.h:545
pa_context_set_card_profile_by_index = _lib.pa_context_set_card_profile_by_index
pa_context_set_card_profile_by_index.restype = POINTER(pa_operation)
pa_context_set_card_profile_by_index.argtypes = [POINTER(pa_context), c_uint32, c_char_p, pa_context_success_cb_t, POINTER(None)]
# /usr/include/pulse/introspect.h:548
pa_context_set_card_profile_by_name = _lib.pa_context_set_card_profile_by_name
pa_context_set_card_profile_by_name.restype = POINTER(pa_operation)
pa_context_set_card_profile_by_name.argtypes = [POINTER(pa_context), c_char_p, c_char_p, pa_context_success_cb_t, POINTER(None)]
# /usr/include/pulse/introspect.h:551
pa_context_set_port_latency_offset = _lib.pa_context_set_port_latency_offset
pa_context_set_port_latency_offset.restype = POINTER(pa_operation)
pa_context_set_port_latency_offset.argtypes = [POINTER(pa_context), c_char_p, c_char_p, c_int64, pa_context_success_cb_t, POINTER(None)]
class struct_pa_sink_input_info(Structure):
__slots__ = [
'index',
'name',
'owner_module',
'client',
'sink',
'sample_spec',
'channel_map',
'volume',
'buffer_usec',
'sink_usec',
'resample_method',
'driver',
'mute',
'proplist',
'corked',
'has_volume',
'volume_writable',
'format',
]
struct_pa_sink_input_info._fields_ = [
('index', c_uint32),
('name', c_char_p),
('owner_module', c_uint32),
('client', c_uint32),
('sink', c_uint32),
('sample_spec', pa_sample_spec),
('channel_map', pa_channel_map),
('volume', pa_cvolume),
('buffer_usec', pa_usec_t),
('sink_usec', pa_usec_t),
('resample_method', c_char_p),
('driver', c_char_p),
('mute', c_int),
('proplist', POINTER(pa_proplist)),
('corked', c_int),
('has_volume', c_int),
('volume_writable', c_int),
('format', POINTER(pa_format_info)),
]
pa_sink_input_info = struct_pa_sink_input_info # /usr/include/pulse/introspect.h:579
pa_sink_input_info_cb_t = CFUNCTYPE(None, POINTER(pa_context), POINTER(pa_sink_input_info), c_int, POINTER(None)) # /usr/include/pulse/introspect.h:582
# /usr/include/pulse/introspect.h:585
pa_context_get_sink_input_info = _lib.pa_context_get_sink_input_info
pa_context_get_sink_input_info.restype = POINTER(pa_operation)
pa_context_get_sink_input_info.argtypes = [POINTER(pa_context), c_uint32, pa_sink_input_info_cb_t, POINTER(None)]
# /usr/include/pulse/introspect.h:588
pa_context_get_sink_input_info_list = _lib.pa_context_get_sink_input_info_list
pa_context_get_sink_input_info_list.restype = POINTER(pa_operation)
pa_context_get_sink_input_info_list.argtypes = [POINTER(pa_context), pa_sink_input_info_cb_t, POINTER(None)]
# /usr/include/pulse/introspect.h:591
pa_context_move_sink_input_by_name = _lib.pa_context_move_sink_input_by_name
pa_context_move_sink_input_by_name.restype = POINTER(pa_operation)
pa_context_move_sink_input_by_name.argtypes = [POINTER(pa_context), c_uint32, c_char_p, pa_context_success_cb_t, POINTER(None)]
# /usr/include/pulse/introspect.h:594
pa_context_move_sink_input_by_index = _lib.pa_context_move_sink_input_by_index
pa_context_move_sink_input_by_index.restype = POINTER(pa_operation)
pa_context_move_sink_input_by_index.argtypes = [POINTER(pa_context), c_uint32, c_uint32, pa_context_success_cb_t, POINTER(None)]
# /usr/include/pulse/introspect.h:597
pa_context_set_sink_input_volume = _lib.pa_context_set_sink_input_volume
pa_context_set_sink_input_volume.restype = POINTER(pa_operation)
pa_context_set_sink_input_volume.argtypes = [POINTER(pa_context), c_uint32, POINTER(pa_cvolume), pa_context_success_cb_t, POINTER(None)]
# /usr/include/pulse/introspect.h:600
pa_context_set_sink_input_mute = _lib.pa_context_set_sink_input_mute
pa_context_set_sink_input_mute.restype = POINTER(pa_operation)
pa_context_set_sink_input_mute.argtypes = [POINTER(pa_context), c_uint32, c_int, pa_context_success_cb_t, POINTER(None)]
# /usr/include/pulse/introspect.h:603
pa_context_kill_sink_input = _lib.pa_context_kill_sink_input
pa_context_kill_sink_input.restype = POINTER(pa_operation)
pa_context_kill_sink_input.argtypes = [POINTER(pa_context), c_uint32, pa_context_success_cb_t, POINTER(None)]
class struct_pa_source_output_info(Structure):
__slots__ = [
'index',
'name',
'owner_module',
'client',
'source',
'sample_spec',
'channel_map',
'buffer_usec',
'source_usec',
'resample_method',
'driver',
'proplist',
'corked',
'volume',
'mute',
'has_volume',
'volume_writable',
'format',
]
struct_pa_source_output_info._fields_ = [
('index', c_uint32),
('name', c_char_p),
('owner_module', c_uint32),
('client', c_uint32),
('source', c_uint32),
('sample_spec', pa_sample_spec),
('channel_map', pa_channel_map),
('buffer_usec', pa_usec_t),
('source_usec', pa_usec_t),
('resample_method', c_char_p),
('driver', c_char_p),
('proplist', POINTER(pa_proplist)),
('corked', c_int),
('volume', pa_cvolume),
('mute', c_int),
('has_volume', c_int),
('volume_writable', c_int),
('format', POINTER(pa_format_info)),
]
pa_source_output_info = struct_pa_source_output_info # /usr/include/pulse/introspect.h:631
pa_source_output_info_cb_t = CFUNCTYPE(None, POINTER(pa_context), POINTER(pa_source_output_info), c_int, POINTER(None)) # /usr/include/pulse/introspect.h:634
# /usr/include/pulse/introspect.h:637
pa_context_get_source_output_info = _lib.pa_context_get_source_output_info
pa_context_get_source_output_info.restype = POINTER(pa_operation)
pa_context_get_source_output_info.argtypes = [POINTER(pa_context), c_uint32, pa_source_output_info_cb_t, POINTER(None)]
# /usr/include/pulse/introspect.h:640
pa_context_get_source_output_info_list = _lib.pa_context_get_source_output_info_list
pa_context_get_source_output_info_list.restype = POINTER(pa_operation)
pa_context_get_source_output_info_list.argtypes = [POINTER(pa_context), pa_source_output_info_cb_t, POINTER(None)]
# /usr/include/pulse/introspect.h:643
pa_context_move_source_output_by_name = _lib.pa_context_move_source_output_by_name
pa_context_move_source_output_by_name.restype = POINTER(pa_operation)
pa_context_move_source_output_by_name.argtypes = [POINTER(pa_context), c_uint32, c_char_p, pa_context_success_cb_t, POINTER(None)]
# /usr/include/pulse/introspect.h:646
pa_context_move_source_output_by_index = _lib.pa_context_move_source_output_by_index
pa_context_move_source_output_by_index.restype = POINTER(pa_operation)
pa_context_move_source_output_by_index.argtypes = [POINTER(pa_context), c_uint32, c_uint32, pa_context_success_cb_t, POINTER(None)]
# /usr/include/pulse/introspect.h:649
pa_context_set_source_output_volume = _lib.pa_context_set_source_output_volume
pa_context_set_source_output_volume.restype = POINTER(pa_operation)
pa_context_set_source_output_volume.argtypes = [POINTER(pa_context), c_uint32, POINTER(pa_cvolume), pa_context_success_cb_t, POINTER(None)]
# /usr/include/pulse/introspect.h:652
pa_context_set_source_output_mute = _lib.pa_context_set_source_output_mute
pa_context_set_source_output_mute.restype = POINTER(pa_operation)
pa_context_set_source_output_mute.argtypes = [POINTER(pa_context), c_uint32, c_int, pa_context_success_cb_t, POINTER(None)]
# /usr/include/pulse/introspect.h:655
pa_context_kill_source_output = _lib.pa_context_kill_source_output
pa_context_kill_source_output.restype = POINTER(pa_operation)
pa_context_kill_source_output.argtypes = [POINTER(pa_context), c_uint32, pa_context_success_cb_t, POINTER(None)]
class struct_pa_stat_info(Structure):
__slots__ = [
'memblock_total',
'memblock_total_size',
'memblock_allocated',
'memblock_allocated_size',
'scache_size',
]
struct_pa_stat_info._fields_ = [
('memblock_total', c_uint32),
('memblock_total_size', c_uint32),
('memblock_allocated', c_uint32),
('memblock_allocated_size', c_uint32),
('scache_size', c_uint32),
]
pa_stat_info = struct_pa_stat_info # /usr/include/pulse/introspect.h:670
pa_stat_info_cb_t = CFUNCTYPE(None, POINTER(pa_context), POINTER(pa_stat_info), POINTER(None)) # /usr/include/pulse/introspect.h:673
# /usr/include/pulse/introspect.h:676
pa_context_stat = _lib.pa_context_stat
pa_context_stat.restype = POINTER(pa_operation)
pa_context_stat.argtypes = [POINTER(pa_context), pa_stat_info_cb_t, POINTER(None)]
class struct_pa_sample_info(Structure):
__slots__ = [
'index',
'name',
'volume',
'sample_spec',
'channel_map',
'duration',
'bytes',
'lazy',
'filename',
'proplist',
]
struct_pa_sample_info._fields_ = [
('index', c_uint32),
('name', c_char_p),
('volume', pa_cvolume),
('sample_spec', pa_sample_spec),
('channel_map', pa_channel_map),
('duration', pa_usec_t),
('bytes', c_uint32),
('lazy', c_int),
('filename', c_char_p),
('proplist', POINTER(pa_proplist)),
]
pa_sample_info = struct_pa_sample_info # /usr/include/pulse/introspect.h:696
pa_sample_info_cb_t = CFUNCTYPE(None, POINTER(pa_context), POINTER(pa_sample_info), c_int, POINTER(None)) # /usr/include/pulse/introspect.h:699
# /usr/include/pulse/introspect.h:702
pa_context_get_sample_info_by_name = _lib.pa_context_get_sample_info_by_name
pa_context_get_sample_info_by_name.restype = POINTER(pa_operation)
pa_context_get_sample_info_by_name.argtypes = [POINTER(pa_context), c_char_p, pa_sample_info_cb_t, POINTER(None)]
# /usr/include/pulse/introspect.h:705
pa_context_get_sample_info_by_index = _lib.pa_context_get_sample_info_by_index
pa_context_get_sample_info_by_index.restype = POINTER(pa_operation)
pa_context_get_sample_info_by_index.argtypes = [POINTER(pa_context), c_uint32, pa_sample_info_cb_t, POINTER(None)]
# /usr/include/pulse/introspect.h:708
pa_context_get_sample_info_list = _lib.pa_context_get_sample_info_list
pa_context_get_sample_info_list.restype = POINTER(pa_operation)
pa_context_get_sample_info_list.argtypes = [POINTER(pa_context), pa_sample_info_cb_t, POINTER(None)]
enum_pa_autoload_type = c_int
PA_AUTOLOAD_SINK = 0
PA_AUTOLOAD_SOURCE = 1
pa_autoload_type_t = enum_pa_autoload_type # /usr/include/pulse/introspect.h:720
class struct_pa_autoload_info(Structure):
__slots__ = [
'index',
'name',
'type',
'module',
'argument',
]
struct_pa_autoload_info._fields_ = [
('index', c_uint32),
('name', c_char_p),
('type', pa_autoload_type_t),
('module', c_char_p),
('argument', c_char_p),
]
pa_autoload_info = struct_pa_autoload_info # /usr/include/pulse/introspect.h:731
pa_autoload_info_cb_t = CFUNCTYPE(None, POINTER(pa_context), POINTER(pa_autoload_info), c_int, POINTER(None)) # /usr/include/pulse/introspect.h:734
# /usr/include/pulse/introspect.h:737
pa_context_get_autoload_info_by_name = _lib.pa_context_get_autoload_info_by_name
pa_context_get_autoload_info_by_name.restype = POINTER(pa_operation)
pa_context_get_autoload_info_by_name.argtypes = [POINTER(pa_context), c_char_p, pa_autoload_type_t, pa_autoload_info_cb_t, POINTER(None)]
# /usr/include/pulse/introspect.h:740
pa_context_get_autoload_info_by_index = _lib.pa_context_get_autoload_info_by_index
pa_context_get_autoload_info_by_index.restype = POINTER(pa_operation)
pa_context_get_autoload_info_by_index.argtypes = [POINTER(pa_context), c_uint32, pa_autoload_info_cb_t, POINTER(None)]
# /usr/include/pulse/introspect.h:743
pa_context_get_autoload_info_list = _lib.pa_context_get_autoload_info_list
pa_context_get_autoload_info_list.restype = POINTER(pa_operation)
pa_context_get_autoload_info_list.argtypes = [POINTER(pa_context), pa_autoload_info_cb_t, POINTER(None)]
# /usr/include/pulse/introspect.h:746
pa_context_add_autoload = _lib.pa_context_add_autoload
pa_context_add_autoload.restype = POINTER(pa_operation)
pa_context_add_autoload.argtypes = [POINTER(pa_context), c_char_p, pa_autoload_type_t, c_char_p, c_char_p, pa_context_index_cb_t, POINTER(None)]
# /usr/include/pulse/introspect.h:749
pa_context_remove_autoload_by_name = _lib.pa_context_remove_autoload_by_name
pa_context_remove_autoload_by_name.restype = POINTER(pa_operation)
pa_context_remove_autoload_by_name.argtypes = [POINTER(pa_context), c_char_p, pa_autoload_type_t, pa_context_success_cb_t, POINTER(None)]
# /usr/include/pulse/introspect.h:752
pa_context_remove_autoload_by_index = _lib.pa_context_remove_autoload_by_index
pa_context_remove_autoload_by_index.restype = POINTER(pa_operation)
pa_context_remove_autoload_by_index.argtypes = [POINTER(pa_context), c_uint32, pa_context_success_cb_t, POINTER(None)]
pa_context_subscribe_cb_t = CFUNCTYPE(None, POINTER(pa_context), pa_subscription_event_type_t, c_uint32, POINTER(None)) # /usr/include/pulse/subscribe.h:73
# /usr/include/pulse/subscribe.h:76
pa_context_subscribe = _lib.pa_context_subscribe
pa_context_subscribe.restype = POINTER(pa_operation)
pa_context_subscribe.argtypes = [POINTER(pa_context), pa_subscription_mask_t, pa_context_success_cb_t, POINTER(None)]
# /usr/include/pulse/subscribe.h:79
pa_context_set_subscribe_callback = _lib.pa_context_set_subscribe_callback
pa_context_set_subscribe_callback.restype = None
pa_context_set_subscribe_callback.argtypes = [POINTER(pa_context), pa_context_subscribe_cb_t, POINTER(None)]
pa_context_play_sample_cb_t = CFUNCTYPE(None, POINTER(pa_context), c_uint32, POINTER(None)) # /usr/include/pulse/scache.h:85
# /usr/include/pulse/scache.h:88
pa_stream_connect_upload = _lib.pa_stream_connect_upload
pa_stream_connect_upload.restype = c_int
pa_stream_connect_upload.argtypes = [POINTER(pa_stream), c_size_t]
# /usr/include/pulse/scache.h:93
pa_stream_finish_upload = _lib.pa_stream_finish_upload
pa_stream_finish_upload.restype = c_int
pa_stream_finish_upload.argtypes = [POINTER(pa_stream)]
# /usr/include/pulse/scache.h:96
pa_context_remove_sample = _lib.pa_context_remove_sample
pa_context_remove_sample.restype = POINTER(pa_operation)
pa_context_remove_sample.argtypes = [POINTER(pa_context), c_char_p, pa_context_success_cb_t, POINTER(None)]
# /usr/include/pulse/scache.h:101
pa_context_play_sample = _lib.pa_context_play_sample
pa_context_play_sample.restype = POINTER(pa_operation)
pa_context_play_sample.argtypes = [POINTER(pa_context), c_char_p, c_char_p, pa_volume_t, pa_context_success_cb_t, POINTER(None)]
# /usr/include/pulse/scache.h:113
pa_context_play_sample_with_proplist = _lib.pa_context_play_sample_with_proplist
pa_context_play_sample_with_proplist.restype = POINTER(pa_operation)
pa_context_play_sample_with_proplist.argtypes = [POINTER(pa_context), c_char_p, c_char_p, pa_volume_t, POINTER(pa_proplist), pa_context_play_sample_cb_t, POINTER(None)]
# /usr/include/pulse/error.h:33
pa_strerror = _lib.pa_strerror
pa_strerror.restype = c_char_p
pa_strerror.argtypes = [c_int]
# /usr/include/pulse/xmalloc.h:39
pa_xmalloc = _lib.pa_xmalloc
pa_xmalloc.restype = POINTER(c_void)
pa_xmalloc.argtypes = [c_size_t]
# /usr/include/pulse/xmalloc.h:42
pa_xmalloc0 = _lib.pa_xmalloc0
pa_xmalloc0.restype = POINTER(c_void)
pa_xmalloc0.argtypes = [c_size_t]
# /usr/include/pulse/xmalloc.h:45
pa_xrealloc = _lib.pa_xrealloc
pa_xrealloc.restype = POINTER(c_void)
pa_xrealloc.argtypes = [POINTER(None), c_size_t]
# /usr/include/pulse/xmalloc.h:48
pa_xfree = _lib.pa_xfree
pa_xfree.restype = None
pa_xfree.argtypes = [POINTER(None)]
# /usr/include/pulse/xmalloc.h:51
pa_xstrdup = _lib.pa_xstrdup
pa_xstrdup.restype = c_char_p
pa_xstrdup.argtypes = [c_char_p]
# /usr/include/pulse/xmalloc.h:54
pa_xstrndup = _lib.pa_xstrndup
pa_xstrndup.restype = c_char_p
pa_xstrndup.argtypes = [c_char_p, c_size_t]
# /usr/include/pulse/xmalloc.h:57
pa_xmemdup = _lib.pa_xmemdup
pa_xmemdup.restype = POINTER(c_void)
pa_xmemdup.argtypes = [POINTER(None), c_size_t]
# /usr/include/pulse/utf8.h:35
pa_utf8_valid = _lib.pa_utf8_valid
pa_utf8_valid.restype = c_char_p
pa_utf8_valid.argtypes = [c_char_p]
# /usr/include/pulse/utf8.h:38
pa_ascii_valid = _lib.pa_ascii_valid
pa_ascii_valid.restype = c_char_p
pa_ascii_valid.argtypes = [c_char_p]
# /usr/include/pulse/utf8.h:41
pa_utf8_filter = _lib.pa_utf8_filter
pa_utf8_filter.restype = c_char_p
pa_utf8_filter.argtypes = [c_char_p]
# /usr/include/pulse/utf8.h:44
pa_ascii_filter = _lib.pa_ascii_filter
pa_ascii_filter.restype = c_char_p
pa_ascii_filter.argtypes = [c_char_p]
# /usr/include/pulse/utf8.h:47
pa_utf8_to_locale = _lib.pa_utf8_to_locale
pa_utf8_to_locale.restype = c_char_p
pa_utf8_to_locale.argtypes = [c_char_p]
# /usr/include/pulse/utf8.h:50
pa_locale_to_utf8 = _lib.pa_locale_to_utf8
pa_locale_to_utf8.restype = c_char_p
pa_locale_to_utf8.argtypes = [c_char_p]
class struct_pa_threaded_mainloop(Structure):
__slots__ = [
]
struct_pa_threaded_mainloop._fields_ = [
('_opaque_struct', c_int)
]
class struct_pa_threaded_mainloop(Structure):
__slots__ = [
]
struct_pa_threaded_mainloop._fields_ = [
('_opaque_struct', c_int)
]
pa_threaded_mainloop = struct_pa_threaded_mainloop # /usr/include/pulse/thread-mainloop.h:246
# /usr/include/pulse/thread-mainloop.h:251
pa_threaded_mainloop_new = _lib.pa_threaded_mainloop_new
pa_threaded_mainloop_new.restype = POINTER(pa_threaded_mainloop)
pa_threaded_mainloop_new.argtypes = []
# /usr/include/pulse/thread-mainloop.h:256
pa_threaded_mainloop_free = _lib.pa_threaded_mainloop_free
pa_threaded_mainloop_free.restype = None
pa_threaded_mainloop_free.argtypes = [POINTER(pa_threaded_mainloop)]
# /usr/include/pulse/thread-mainloop.h:259
pa_threaded_mainloop_start = _lib.pa_threaded_mainloop_start
pa_threaded_mainloop_start.restype = c_int
pa_threaded_mainloop_start.argtypes = [POINTER(pa_threaded_mainloop)]
# /usr/include/pulse/thread-mainloop.h:263
pa_threaded_mainloop_stop = _lib.pa_threaded_mainloop_stop
pa_threaded_mainloop_stop.restype = None
pa_threaded_mainloop_stop.argtypes = [POINTER(pa_threaded_mainloop)]
# /usr/include/pulse/thread-mainloop.h:271
pa_threaded_mainloop_lock = _lib.pa_threaded_mainloop_lock
pa_threaded_mainloop_lock.restype = None
pa_threaded_mainloop_lock.argtypes = [POINTER(pa_threaded_mainloop)]
# /usr/include/pulse/thread-mainloop.h:274
pa_threaded_mainloop_unlock = _lib.pa_threaded_mainloop_unlock
pa_threaded_mainloop_unlock.restype = None
pa_threaded_mainloop_unlock.argtypes = [POINTER(pa_threaded_mainloop)]
# /usr/include/pulse/thread-mainloop.h:285
pa_threaded_mainloop_wait = _lib.pa_threaded_mainloop_wait
pa_threaded_mainloop_wait.restype = None
pa_threaded_mainloop_wait.argtypes = [POINTER(pa_threaded_mainloop)]
# /usr/include/pulse/thread-mainloop.h:292
pa_threaded_mainloop_signal = _lib.pa_threaded_mainloop_signal
pa_threaded_mainloop_signal.restype = None
pa_threaded_mainloop_signal.argtypes = [POINTER(pa_threaded_mainloop), c_int]
# /usr/include/pulse/thread-mainloop.h:298
pa_threaded_mainloop_accept = _lib.pa_threaded_mainloop_accept
pa_threaded_mainloop_accept.restype = None
pa_threaded_mainloop_accept.argtypes = [POINTER(pa_threaded_mainloop)]
# /usr/include/pulse/thread-mainloop.h:302
pa_threaded_mainloop_get_retval = _lib.pa_threaded_mainloop_get_retval
pa_threaded_mainloop_get_retval.restype = c_int
pa_threaded_mainloop_get_retval.argtypes = [POINTER(pa_threaded_mainloop)]
# /usr/include/pulse/thread-mainloop.h:307
pa_threaded_mainloop_get_api = _lib.pa_threaded_mainloop_get_api
pa_threaded_mainloop_get_api.restype = POINTER(pa_mainloop_api)
pa_threaded_mainloop_get_api.argtypes = [POINTER(pa_threaded_mainloop)]
# /usr/include/pulse/thread-mainloop.h:310
pa_threaded_mainloop_in_thread = _lib.pa_threaded_mainloop_in_thread
pa_threaded_mainloop_in_thread.restype = c_int
pa_threaded_mainloop_in_thread.argtypes = [POINTER(pa_threaded_mainloop)]
# /usr/include/pulse/thread-mainloop.h:313
#pa_threaded_mainloop_set_name = _lib.pa_threaded_mainloop_set_name
#pa_threaded_mainloop_set_name.restype = None
#pa_threaded_mainloop_set_name.argtypes = [POINTER(pa_threaded_mainloop), c_char_p]
class struct_pa_mainloop(Structure):
__slots__ = [
]
struct_pa_mainloop._fields_ = [
('_opaque_struct', c_int)
]
class struct_pa_mainloop(Structure):
__slots__ = [
]
struct_pa_mainloop._fields_ = [
('_opaque_struct', c_int)
]
pa_mainloop = struct_pa_mainloop # /usr/include/pulse/mainloop.h:78
# /usr/include/pulse/mainloop.h:81
pa_mainloop_new = _lib.pa_mainloop_new
pa_mainloop_new.restype = POINTER(pa_mainloop)
pa_mainloop_new.argtypes = []
# /usr/include/pulse/mainloop.h:84
pa_mainloop_free = _lib.pa_mainloop_free
pa_mainloop_free.restype = None
pa_mainloop_free.argtypes = [POINTER(pa_mainloop)]
# /usr/include/pulse/mainloop.h:89
pa_mainloop_prepare = _lib.pa_mainloop_prepare
pa_mainloop_prepare.restype = c_int
pa_mainloop_prepare.argtypes = [POINTER(pa_mainloop), c_int]
# /usr/include/pulse/mainloop.h:92
pa_mainloop_poll = _lib.pa_mainloop_poll
pa_mainloop_poll.restype = c_int
pa_mainloop_poll.argtypes = [POINTER(pa_mainloop)]
# /usr/include/pulse/mainloop.h:96
pa_mainloop_dispatch = _lib.pa_mainloop_dispatch
pa_mainloop_dispatch.restype = c_int
pa_mainloop_dispatch.argtypes = [POINTER(pa_mainloop)]
# /usr/include/pulse/mainloop.h:99
pa_mainloop_get_retval = _lib.pa_mainloop_get_retval
pa_mainloop_get_retval.restype = c_int
pa_mainloop_get_retval.argtypes = [POINTER(pa_mainloop)]
# /usr/include/pulse/mainloop.h:107
pa_mainloop_iterate = _lib.pa_mainloop_iterate
pa_mainloop_iterate.restype = c_int
pa_mainloop_iterate.argtypes = [POINTER(pa_mainloop), c_int, POINTER(c_int)]
# /usr/include/pulse/mainloop.h:110
pa_mainloop_run = _lib.pa_mainloop_run
pa_mainloop_run.restype = c_int
pa_mainloop_run.argtypes = [POINTER(pa_mainloop), POINTER(c_int)]
# /usr/include/pulse/mainloop.h:115
pa_mainloop_get_api = _lib.pa_mainloop_get_api
pa_mainloop_get_api.restype = POINTER(pa_mainloop_api)
pa_mainloop_get_api.argtypes = [POINTER(pa_mainloop)]
# /usr/include/pulse/mainloop.h:118
pa_mainloop_quit = _lib.pa_mainloop_quit
pa_mainloop_quit.restype = None
pa_mainloop_quit.argtypes = [POINTER(pa_mainloop), c_int]
# /usr/include/pulse/mainloop.h:121
pa_mainloop_wakeup = _lib.pa_mainloop_wakeup
pa_mainloop_wakeup.restype = None
pa_mainloop_wakeup.argtypes = [POINTER(pa_mainloop)]
class struct_pollfd(Structure):
__slots__ = [
]
struct_pollfd._fields_ = [
('_opaque_struct', c_int)
]
class struct_pollfd(Structure):
__slots__ = [
]
struct_pollfd._fields_ = [
('_opaque_struct', c_int)
]
pa_poll_func = CFUNCTYPE(c_int, POINTER(struct_pollfd), c_ulong, c_int, POINTER(None)) # /usr/include/pulse/mainloop.h:124
# /usr/include/pulse/mainloop.h:127
pa_mainloop_set_poll_func = _lib.pa_mainloop_set_poll_func
pa_mainloop_set_poll_func.restype = None
pa_mainloop_set_poll_func.argtypes = [POINTER(pa_mainloop), pa_poll_func, POINTER(None)]
class struct_pa_signal_event(Structure):
__slots__ = [
]
struct_pa_signal_event._fields_ = [
('_opaque_struct', c_int)
]
class struct_pa_signal_event(Structure):
__slots__ = [
]
struct_pa_signal_event._fields_ = [
('_opaque_struct', c_int)
]
pa_signal_event = struct_pa_signal_event # /usr/include/pulse/mainloop-signal.h:39
pa_signal_cb_t = CFUNCTYPE(None, POINTER(pa_mainloop_api), POINTER(pa_signal_event), c_int, POINTER(None)) # /usr/include/pulse/mainloop-signal.h:42
pa_signal_destroy_cb_t = CFUNCTYPE(None, POINTER(pa_mainloop_api), POINTER(pa_signal_event), POINTER(None)) # /usr/include/pulse/mainloop-signal.h:45
# /usr/include/pulse/mainloop-signal.h:48
pa_signal_init = _lib.pa_signal_init
pa_signal_init.restype = c_int
pa_signal_init.argtypes = [POINTER(pa_mainloop_api)]
# /usr/include/pulse/mainloop-signal.h:51
pa_signal_done = _lib.pa_signal_done
pa_signal_done.restype = None
pa_signal_done.argtypes = []
# /usr/include/pulse/mainloop-signal.h:54
pa_signal_new = _lib.pa_signal_new
pa_signal_new.restype = POINTER(pa_signal_event)
pa_signal_new.argtypes = [c_int, pa_signal_cb_t, POINTER(None)]
# /usr/include/pulse/mainloop-signal.h:57
pa_signal_free = _lib.pa_signal_free
pa_signal_free.restype = None
pa_signal_free.argtypes = [POINTER(pa_signal_event)]
# /usr/include/pulse/mainloop-signal.h:60
pa_signal_set_destroy = _lib.pa_signal_set_destroy
pa_signal_set_destroy.restype = None
pa_signal_set_destroy.argtypes = [POINTER(pa_signal_event), pa_signal_destroy_cb_t]
# /usr/include/pulse/util.h:35
pa_get_user_name = _lib.pa_get_user_name
pa_get_user_name.restype = c_char_p
pa_get_user_name.argtypes = [c_char_p, c_size_t]
# /usr/include/pulse/util.h:38
pa_get_host_name = _lib.pa_get_host_name
pa_get_host_name.restype = c_char_p
pa_get_host_name.argtypes = [c_char_p, c_size_t]
# /usr/include/pulse/util.h:41
pa_get_fqdn = _lib.pa_get_fqdn
pa_get_fqdn.restype = c_char_p
pa_get_fqdn.argtypes = [c_char_p, c_size_t]
# /usr/include/pulse/util.h:44
pa_get_home_dir = _lib.pa_get_home_dir
pa_get_home_dir.restype = c_char_p
pa_get_home_dir.argtypes = [c_char_p, c_size_t]
# /usr/include/pulse/util.h:48
pa_get_binary_name = _lib.pa_get_binary_name
pa_get_binary_name.restype = c_char_p
pa_get_binary_name.argtypes = [c_char_p, c_size_t]
# /usr/include/pulse/util.h:52
pa_path_get_filename = _lib.pa_path_get_filename
pa_path_get_filename.restype = c_char_p
pa_path_get_filename.argtypes = [c_char_p]
# /usr/include/pulse/util.h:55
pa_msleep = _lib.pa_msleep
pa_msleep.restype = c_int
pa_msleep.argtypes = [c_ulong]
class struct_timeval(Structure):
__slots__ = [
]
struct_timeval._fields_ = [
('_opaque_struct', c_int)
]
class struct_timeval(Structure):
__slots__ = [
]
struct_timeval._fields_ = [
('_opaque_struct', c_int)
]
# /usr/include/pulse/timeval.h:61
pa_gettimeofday = _lib.pa_gettimeofday
pa_gettimeofday.restype = POINTER(struct_timeval)
pa_gettimeofday.argtypes = [POINTER(struct_timeval)]
class struct_timeval(Structure):
__slots__ = [
]
struct_timeval._fields_ = [
('_opaque_struct', c_int)
]
class struct_timeval(Structure):
__slots__ = [
]
struct_timeval._fields_ = [
('_opaque_struct', c_int)
]
# /usr/include/pulse/timeval.h:65
pa_timeval_diff = _lib.pa_timeval_diff
pa_timeval_diff.restype = pa_usec_t
pa_timeval_diff.argtypes = [POINTER(struct_timeval), POINTER(struct_timeval)]
class struct_timeval(Structure):
__slots__ = [
]
struct_timeval._fields_ = [
('_opaque_struct', c_int)
]
class struct_timeval(Structure):
__slots__ = [
]
struct_timeval._fields_ = [
('_opaque_struct', c_int)
]
# /usr/include/pulse/timeval.h:68
pa_timeval_cmp = _lib.pa_timeval_cmp
pa_timeval_cmp.restype = c_int
pa_timeval_cmp.argtypes = [POINTER(struct_timeval), POINTER(struct_timeval)]
class struct_timeval(Structure):
__slots__ = [
]
struct_timeval._fields_ = [
('_opaque_struct', c_int)
]
# /usr/include/pulse/timeval.h:71
pa_timeval_age = _lib.pa_timeval_age
pa_timeval_age.restype = pa_usec_t
pa_timeval_age.argtypes = [POINTER(struct_timeval)]
class struct_timeval(Structure):
__slots__ = [
]
struct_timeval._fields_ = [
('_opaque_struct', c_int)
]
class struct_timeval(Structure):
__slots__ = [
]
struct_timeval._fields_ = [
('_opaque_struct', c_int)
]
# /usr/include/pulse/timeval.h:74
pa_timeval_add = _lib.pa_timeval_add
pa_timeval_add.restype = POINTER(struct_timeval)
pa_timeval_add.argtypes = [POINTER(struct_timeval), pa_usec_t]
class struct_timeval(Structure):
__slots__ = [
]
struct_timeval._fields_ = [
('_opaque_struct', c_int)
]
class struct_timeval(Structure):
__slots__ = [
]
struct_timeval._fields_ = [
('_opaque_struct', c_int)
]
# /usr/include/pulse/timeval.h:77
pa_timeval_sub = _lib.pa_timeval_sub
pa_timeval_sub.restype = POINTER(struct_timeval)
pa_timeval_sub.argtypes = [POINTER(struct_timeval), pa_usec_t]
class struct_timeval(Structure):
__slots__ = [
]
struct_timeval._fields_ = [
('_opaque_struct', c_int)
]
class struct_timeval(Structure):
__slots__ = [
]
struct_timeval._fields_ = [
('_opaque_struct', c_int)
]
# /usr/include/pulse/timeval.h:80
pa_timeval_store = _lib.pa_timeval_store
pa_timeval_store.restype = POINTER(struct_timeval)
pa_timeval_store.argtypes = [POINTER(struct_timeval), pa_usec_t]
class struct_timeval(Structure):
__slots__ = [
]
struct_timeval._fields_ = [
('_opaque_struct', c_int)
]
# /usr/include/pulse/timeval.h:83
pa_timeval_load = _lib.pa_timeval_load
pa_timeval_load.restype = pa_usec_t
pa_timeval_load.argtypes = [POINTER(struct_timeval)]
__all__ = ['pa_get_library_version', 'PA_API_VERSION', 'PA_PROTOCOL_VERSION',
'PA_MAJOR', 'PA_MINOR', 'PA_MICRO', 'PA_CHANNELS_MAX', 'PA_RATE_MAX',
'pa_sample_format_t', 'PA_SAMPLE_U8', 'PA_SAMPLE_ALAW', 'PA_SAMPLE_ULAW',
'PA_SAMPLE_S16LE', 'PA_SAMPLE_S16BE', 'PA_SAMPLE_FLOAT32LE',
'PA_SAMPLE_FLOAT32BE', 'PA_SAMPLE_S32LE', 'PA_SAMPLE_S32BE',
'PA_SAMPLE_S24LE', 'PA_SAMPLE_S24BE', 'PA_SAMPLE_S24_32LE',
'PA_SAMPLE_S24_32BE', 'PA_SAMPLE_MAX', 'PA_SAMPLE_INVALID', 'pa_sample_spec',
'pa_usec_t', 'pa_bytes_per_second', 'pa_frame_size', 'pa_sample_size',
'pa_sample_size_of_format', 'pa_bytes_to_usec', 'pa_usec_to_bytes',
'pa_sample_spec_init', 'pa_sample_format_valid', 'pa_sample_rate_valid',
'pa_channels_valid', 'pa_sample_spec_valid', 'pa_sample_spec_equal',
'pa_sample_format_to_string', 'pa_parse_sample_format',
'PA_SAMPLE_SPEC_SNPRINT_MAX', 'pa_sample_spec_snprint',
'PA_BYTES_SNPRINT_MAX', 'pa_bytes_snprint', 'pa_sample_format_is_le',
'pa_sample_format_is_be', 'pa_context_state_t', 'PA_CONTEXT_UNCONNECTED',
'PA_CONTEXT_CONNECTING', 'PA_CONTEXT_AUTHORIZING', 'PA_CONTEXT_SETTING_NAME',
'PA_CONTEXT_READY', 'PA_CONTEXT_FAILED', 'PA_CONTEXT_TERMINATED',
'pa_stream_state_t', 'PA_STREAM_UNCONNECTED', 'PA_STREAM_CREATING',
'PA_STREAM_READY', 'PA_STREAM_FAILED', 'PA_STREAM_TERMINATED',
'pa_operation_state_t', 'PA_OPERATION_RUNNING', 'PA_OPERATION_DONE',
'PA_OPERATION_CANCELLED', 'pa_context_flags_t', 'PA_CONTEXT_NOFLAGS',
'PA_CONTEXT_NOAUTOSPAWN', 'PA_CONTEXT_NOFAIL', 'pa_direction_t',
'PA_DIRECTION_OUTPUT', 'PA_DIRECTION_INPUT', 'pa_device_type_t',
'PA_DEVICE_TYPE_SINK', 'PA_DEVICE_TYPE_SOURCE', 'pa_stream_direction_t',
'PA_STREAM_NODIRECTION', 'PA_STREAM_PLAYBACK', 'PA_STREAM_RECORD',
'PA_STREAM_UPLOAD', 'pa_stream_flags_t', 'PA_STREAM_NOFLAGS',
'PA_STREAM_START_CORKED', 'PA_STREAM_INTERPOLATE_TIMING',
'PA_STREAM_NOT_MONOTONIC', 'PA_STREAM_AUTO_TIMING_UPDATE',
'PA_STREAM_NO_REMAP_CHANNELS', 'PA_STREAM_NO_REMIX_CHANNELS',
'PA_STREAM_FIX_FORMAT', 'PA_STREAM_FIX_RATE', 'PA_STREAM_FIX_CHANNELS',
'PA_STREAM_DONT_MOVE', 'PA_STREAM_VARIABLE_RATE', 'PA_STREAM_PEAK_DETECT',
'PA_STREAM_START_MUTED', 'PA_STREAM_ADJUST_LATENCY',
'PA_STREAM_EARLY_REQUESTS', 'PA_STREAM_DONT_INHIBIT_AUTO_SUSPEND',
'PA_STREAM_START_UNMUTED', 'PA_STREAM_FAIL_ON_SUSPEND',
'PA_STREAM_RELATIVE_VOLUME', 'PA_STREAM_PASSTHROUGH', 'pa_buffer_attr',
'pa_error_code_t', 'PA_OK', 'PA_ERR_ACCESS', 'PA_ERR_COMMAND',
'PA_ERR_INVALID', 'PA_ERR_EXIST', 'PA_ERR_NOENTITY',
'PA_ERR_CONNECTIONREFUSED', 'PA_ERR_PROTOCOL', 'PA_ERR_TIMEOUT',
'PA_ERR_AUTHKEY', 'PA_ERR_INTERNAL', 'PA_ERR_CONNECTIONTERMINATED',
'PA_ERR_KILLED', 'PA_ERR_INVALIDSERVER', 'PA_ERR_MODINITFAILED',
'PA_ERR_BADSTATE', 'PA_ERR_NODATA', 'PA_ERR_VERSION', 'PA_ERR_TOOLARGE',
'PA_ERR_NOTSUPPORTED', 'PA_ERR_UNKNOWN', 'PA_ERR_NOEXTENSION',
'PA_ERR_OBSOLETE', 'PA_ERR_NOTIMPLEMENTED', 'PA_ERR_FORKED', 'PA_ERR_IO',
'PA_ERR_BUSY', 'PA_ERR_MAX', 'pa_subscription_mask_t',
'PA_SUBSCRIPTION_MASK_NULL', 'PA_SUBSCRIPTION_MASK_SINK',
'PA_SUBSCRIPTION_MASK_SOURCE', 'PA_SUBSCRIPTION_MASK_SINK_INPUT',
'PA_SUBSCRIPTION_MASK_SOURCE_OUTPUT', 'PA_SUBSCRIPTION_MASK_MODULE',
'PA_SUBSCRIPTION_MASK_CLIENT', 'PA_SUBSCRIPTION_MASK_SAMPLE_CACHE',
'PA_SUBSCRIPTION_MASK_SERVER', 'PA_SUBSCRIPTION_MASK_AUTOLOAD',
'PA_SUBSCRIPTION_MASK_CARD', 'PA_SUBSCRIPTION_MASK_ALL',
'pa_subscription_event_type_t', 'PA_SUBSCRIPTION_EVENT_SINK',
'PA_SUBSCRIPTION_EVENT_SOURCE', 'PA_SUBSCRIPTION_EVENT_SINK_INPUT',
'PA_SUBSCRIPTION_EVENT_SOURCE_OUTPUT', 'PA_SUBSCRIPTION_EVENT_MODULE',
'PA_SUBSCRIPTION_EVENT_CLIENT', 'PA_SUBSCRIPTION_EVENT_SAMPLE_CACHE',
'PA_SUBSCRIPTION_EVENT_SERVER', 'PA_SUBSCRIPTION_EVENT_AUTOLOAD',
'PA_SUBSCRIPTION_EVENT_CARD', 'PA_SUBSCRIPTION_EVENT_FACILITY_MASK',
'PA_SUBSCRIPTION_EVENT_NEW', 'PA_SUBSCRIPTION_EVENT_CHANGE',
'PA_SUBSCRIPTION_EVENT_REMOVE', 'PA_SUBSCRIPTION_EVENT_TYPE_MASK',
'pa_timing_info', 'pa_spawn_api', 'pa_seek_mode_t', 'PA_SEEK_RELATIVE',
'PA_SEEK_ABSOLUTE', 'PA_SEEK_RELATIVE_ON_READ', 'PA_SEEK_RELATIVE_END',
'pa_sink_flags_t', 'PA_SINK_NOFLAGS', 'PA_SINK_HW_VOLUME_CTRL',
'PA_SINK_LATENCY', 'PA_SINK_HARDWARE', 'PA_SINK_NETWORK',
'PA_SINK_HW_MUTE_CTRL', 'PA_SINK_DECIBEL_VOLUME', 'PA_SINK_FLAT_VOLUME',
'PA_SINK_DYNAMIC_LATENCY', 'PA_SINK_SET_FORMATS', 'pa_sink_state_t',
'PA_SINK_INVALID_STATE', 'PA_SINK_RUNNING', 'PA_SINK_IDLE',
'PA_SINK_SUSPENDED', 'PA_SINK_INIT', 'PA_SINK_UNLINKED', 'pa_source_flags_t',
'PA_SOURCE_NOFLAGS', 'PA_SOURCE_HW_VOLUME_CTRL', 'PA_SOURCE_LATENCY',
'PA_SOURCE_HARDWARE', 'PA_SOURCE_NETWORK', 'PA_SOURCE_HW_MUTE_CTRL',
'PA_SOURCE_DECIBEL_VOLUME', 'PA_SOURCE_DYNAMIC_LATENCY',
'PA_SOURCE_FLAT_VOLUME', 'pa_source_state_t', 'PA_SOURCE_INVALID_STATE',
'PA_SOURCE_RUNNING', 'PA_SOURCE_IDLE', 'PA_SOURCE_SUSPENDED',
'PA_SOURCE_INIT', 'PA_SOURCE_UNLINKED', 'pa_free_cb_t', 'pa_port_available_t',
'PA_PORT_AVAILABLE_UNKNOWN', 'PA_PORT_AVAILABLE_NO', 'PA_PORT_AVAILABLE_YES',
'pa_mainloop_api', 'pa_io_event_flags_t', 'PA_IO_EVENT_NULL',
'PA_IO_EVENT_INPUT', 'PA_IO_EVENT_OUTPUT', 'PA_IO_EVENT_HANGUP',
'PA_IO_EVENT_ERROR', 'pa_io_event', 'pa_io_event_cb_t',
'pa_io_event_destroy_cb_t', 'pa_time_event', 'pa_time_event_cb_t',
'pa_time_event_destroy_cb_t', 'pa_defer_event', 'pa_defer_event_cb_t',
'pa_defer_event_destroy_cb_t', 'pa_mainloop_api_once',
'pa_channel_position_t', 'PA_CHANNEL_POSITION_INVALID',
'PA_CHANNEL_POSITION_MONO', 'PA_CHANNEL_POSITION_FRONT_LEFT',
'PA_CHANNEL_POSITION_FRONT_RIGHT', 'PA_CHANNEL_POSITION_FRONT_CENTER',
'PA_CHANNEL_POSITION_LEFT', 'PA_CHANNEL_POSITION_RIGHT',
'PA_CHANNEL_POSITION_CENTER', 'PA_CHANNEL_POSITION_REAR_CENTER',
'PA_CHANNEL_POSITION_REAR_LEFT', 'PA_CHANNEL_POSITION_REAR_RIGHT',
'PA_CHANNEL_POSITION_LFE', 'PA_CHANNEL_POSITION_SUBWOOFER',
'PA_CHANNEL_POSITION_FRONT_LEFT_OF_CENTER',
'PA_CHANNEL_POSITION_FRONT_RIGHT_OF_CENTER', 'PA_CHANNEL_POSITION_SIDE_LEFT',
'PA_CHANNEL_POSITION_SIDE_RIGHT', 'PA_CHANNEL_POSITION_AUX0',
'PA_CHANNEL_POSITION_AUX1', 'PA_CHANNEL_POSITION_AUX2',
'PA_CHANNEL_POSITION_AUX3', 'PA_CHANNEL_POSITION_AUX4',
'PA_CHANNEL_POSITION_AUX5', 'PA_CHANNEL_POSITION_AUX6',
'PA_CHANNEL_POSITION_AUX7', 'PA_CHANNEL_POSITION_AUX8',
'PA_CHANNEL_POSITION_AUX9', 'PA_CHANNEL_POSITION_AUX10',
'PA_CHANNEL_POSITION_AUX11', 'PA_CHANNEL_POSITION_AUX12',
'PA_CHANNEL_POSITION_AUX13', 'PA_CHANNEL_POSITION_AUX14',
'PA_CHANNEL_POSITION_AUX15', 'PA_CHANNEL_POSITION_AUX16',
'PA_CHANNEL_POSITION_AUX17', 'PA_CHANNEL_POSITION_AUX18',
'PA_CHANNEL_POSITION_AUX19', 'PA_CHANNEL_POSITION_AUX20',
'PA_CHANNEL_POSITION_AUX21', 'PA_CHANNEL_POSITION_AUX22',
'PA_CHANNEL_POSITION_AUX23', 'PA_CHANNEL_POSITION_AUX24',
'PA_CHANNEL_POSITION_AUX25', 'PA_CHANNEL_POSITION_AUX26',
'PA_CHANNEL_POSITION_AUX27', 'PA_CHANNEL_POSITION_AUX28',
'PA_CHANNEL_POSITION_AUX29', 'PA_CHANNEL_POSITION_AUX30',
'PA_CHANNEL_POSITION_AUX31', 'PA_CHANNEL_POSITION_TOP_CENTER',
'PA_CHANNEL_POSITION_TOP_FRONT_LEFT', 'PA_CHANNEL_POSITION_TOP_FRONT_RIGHT',
'PA_CHANNEL_POSITION_TOP_FRONT_CENTER', 'PA_CHANNEL_POSITION_TOP_REAR_LEFT',
'PA_CHANNEL_POSITION_TOP_REAR_RIGHT', 'PA_CHANNEL_POSITION_TOP_REAR_CENTER',
'PA_CHANNEL_POSITION_MAX', 'pa_channel_position_mask_t',
'pa_channel_map_def_t', 'PA_CHANNEL_MAP_AIFF', 'PA_CHANNEL_MAP_ALSA',
'PA_CHANNEL_MAP_AUX', 'PA_CHANNEL_MAP_WAVEEX', 'PA_CHANNEL_MAP_OSS',
'PA_CHANNEL_MAP_DEF_MAX', 'PA_CHANNEL_MAP_DEFAULT', 'pa_channel_map',
'pa_channel_map_init', 'pa_channel_map_init_mono',
'pa_channel_map_init_stereo', 'pa_channel_map_init_auto',
'pa_channel_map_init_extend', 'pa_channel_position_to_string',
'pa_channel_position_from_string', 'pa_channel_position_to_pretty_string',
'PA_CHANNEL_MAP_SNPRINT_MAX', 'pa_channel_map_snprint',
'pa_channel_map_parse', 'pa_channel_map_equal', 'pa_channel_map_valid',
'pa_channel_map_compatible', 'pa_channel_map_superset',
'pa_channel_map_can_balance', 'pa_channel_map_can_fade',
'pa_channel_map_to_name', 'pa_channel_map_to_pretty_name',
'pa_channel_map_has_position', 'pa_channel_map_mask', 'pa_operation',
'pa_operation_notify_cb_t', 'pa_operation_ref', 'pa_operation_unref',
'pa_operation_cancel', 'pa_operation_get_state',
'pa_operation_set_state_callback', 'pa_context', 'pa_context_notify_cb_t',
'pa_context_success_cb_t', 'pa_context_event_cb_t', 'pa_context_new',
'pa_context_new_with_proplist', 'pa_context_unref', 'pa_context_ref',
'pa_context_set_state_callback', 'pa_context_set_event_callback',
'pa_context_errno', 'pa_context_is_pending', 'pa_context_get_state',
'pa_context_connect', 'pa_context_disconnect', 'pa_context_drain',
'pa_context_exit_daemon', 'pa_context_set_default_sink',
'pa_context_set_default_source', 'pa_context_is_local', 'pa_context_set_name',
'pa_context_get_server', 'pa_context_get_protocol_version',
'pa_context_get_server_protocol_version', 'PA_UPDATE_SET', 'PA_UPDATE_MERGE',
'PA_UPDATE_REPLACE', 'pa_context_proplist_update',
'pa_context_proplist_remove', 'pa_context_get_index', 'pa_context_rttime_new',
'pa_context_rttime_restart', 'pa_context_get_tile_size',
'pa_context_load_cookie_from_file', 'pa_volume_t', 'pa_cvolume',
'pa_cvolume_equal', 'pa_cvolume_init', 'pa_cvolume_set',
'PA_CVOLUME_SNPRINT_MAX', 'pa_cvolume_snprint',
'PA_SW_CVOLUME_SNPRINT_DB_MAX', 'pa_sw_cvolume_snprint_dB',
'PA_CVOLUME_SNPRINT_VERBOSE_MAX', 'pa_cvolume_snprint_verbose',
'PA_VOLUME_SNPRINT_MAX', 'pa_volume_snprint', 'PA_SW_VOLUME_SNPRINT_DB_MAX',
'pa_sw_volume_snprint_dB', 'PA_VOLUME_SNPRINT_VERBOSE_MAX',
'pa_volume_snprint_verbose', 'pa_cvolume_avg', 'pa_cvolume_avg_mask',
'pa_cvolume_max', 'pa_cvolume_max_mask', 'pa_cvolume_min',
'pa_cvolume_min_mask', 'pa_cvolume_valid', 'pa_cvolume_channels_equal_to',
'pa_sw_volume_multiply', 'pa_sw_cvolume_multiply',
'pa_sw_cvolume_multiply_scalar', 'pa_sw_volume_divide',
'pa_sw_cvolume_divide', 'pa_sw_cvolume_divide_scalar', 'pa_sw_volume_from_dB',
'pa_sw_volume_to_dB', 'pa_sw_volume_from_linear', 'pa_sw_volume_to_linear',
'pa_cvolume_remap', 'pa_cvolume_compatible',
'pa_cvolume_compatible_with_channel_map', 'pa_cvolume_get_balance',
'pa_cvolume_set_balance', 'pa_cvolume_get_fade', 'pa_cvolume_set_fade',
'pa_cvolume_scale', 'pa_cvolume_scale_mask', 'pa_cvolume_set_position',
'pa_cvolume_get_position', 'pa_cvolume_merge', 'pa_cvolume_inc_clamp',
'pa_cvolume_inc', 'pa_cvolume_dec', 'pa_stream', 'pa_stream_success_cb_t',
'pa_stream_request_cb_t', 'pa_stream_notify_cb_t', 'pa_stream_event_cb_t',
'pa_stream_new', 'pa_stream_new_with_proplist', 'PA_ENCODING_ANY',
'PA_ENCODING_PCM', 'PA_ENCODING_AC3_IEC61937', 'PA_ENCODING_EAC3_IEC61937',
'PA_ENCODING_MPEG_IEC61937', 'PA_ENCODING_DTS_IEC61937',
'PA_ENCODING_MPEG2_AAC_IEC61937', 'PA_ENCODING_MAX', 'PA_ENCODING_INVALID',
'pa_stream_new_extended', 'pa_stream_unref', 'pa_stream_ref',
'pa_stream_get_state', 'pa_stream_get_context', 'pa_stream_get_index',
'pa_stream_get_device_index', 'pa_stream_get_device_name',
'pa_stream_is_suspended', 'pa_stream_is_corked', 'pa_stream_connect_playback',
'pa_stream_connect_record', 'pa_stream_disconnect', 'pa_stream_begin_write',
'pa_stream_cancel_write', 'pa_stream_write', 'pa_stream_write_ext_free',
'pa_stream_peek', 'pa_stream_drop', 'pa_stream_writable_size',
'pa_stream_readable_size', 'pa_stream_drain', 'pa_stream_update_timing_info',
'pa_stream_set_state_callback', 'pa_stream_set_write_callback',
'pa_stream_set_read_callback', 'pa_stream_set_overflow_callback',
'pa_stream_get_underflow_index', 'pa_stream_set_underflow_callback',
'pa_stream_set_started_callback', 'pa_stream_set_latency_update_callback',
'pa_stream_set_moved_callback', 'pa_stream_set_suspended_callback',
'pa_stream_set_event_callback', 'pa_stream_set_buffer_attr_callback',
'pa_stream_cork', 'pa_stream_flush', 'pa_stream_prebuf', 'pa_stream_trigger',
'pa_stream_set_name', 'pa_stream_get_time', 'pa_stream_get_latency',
'pa_stream_get_timing_info', 'pa_stream_get_sample_spec',
'pa_stream_get_channel_map', 'pa_stream_get_format_info',
'pa_stream_get_buffer_attr', 'pa_stream_set_buffer_attr',
'pa_stream_update_sample_rate', 'pa_stream_proplist_update',
'pa_stream_proplist_remove', 'pa_stream_set_monitor_stream',
'pa_stream_get_monitor_stream', 'pa_sink_port_info', 'pa_sink_info',
'pa_sink_info_cb_t', 'pa_context_get_sink_info_by_name',
'pa_context_get_sink_info_by_index', 'pa_context_get_sink_info_list',
'pa_context_set_sink_volume_by_index', 'pa_context_set_sink_volume_by_name',
'pa_context_set_sink_mute_by_index', 'pa_context_set_sink_mute_by_name',
'pa_context_suspend_sink_by_name', 'pa_context_suspend_sink_by_index',
'pa_context_set_sink_port_by_index', 'pa_context_set_sink_port_by_name',
'pa_source_port_info', 'pa_source_info', 'pa_source_info_cb_t',
'pa_context_get_source_info_by_name', 'pa_context_get_source_info_by_index',
'pa_context_get_source_info_list', 'pa_context_set_source_volume_by_index',
'pa_context_set_source_volume_by_name', 'pa_context_set_source_mute_by_index',
'pa_context_set_source_mute_by_name', 'pa_context_suspend_source_by_name',
'pa_context_suspend_source_by_index', 'pa_context_set_source_port_by_index',
'pa_context_set_source_port_by_name', 'pa_server_info', 'pa_server_info_cb_t',
'pa_context_get_server_info', 'pa_module_info', 'pa_module_info_cb_t',
'pa_context_get_module_info', 'pa_context_get_module_info_list',
'pa_context_index_cb_t', 'pa_context_load_module', 'pa_context_unload_module',
'pa_client_info', 'pa_client_info_cb_t', 'pa_context_get_client_info',
'pa_context_get_client_info_list', 'pa_context_kill_client',
'pa_card_profile_info', 'pa_card_profile_info2', 'pa_card_port_info',
'pa_card_info', 'pa_card_info_cb_t', 'pa_context_get_card_info_by_index',
'pa_context_get_card_info_by_name', 'pa_context_get_card_info_list',
'pa_context_set_card_profile_by_index', 'pa_context_set_card_profile_by_name',
'pa_context_set_port_latency_offset', 'pa_sink_input_info',
'pa_sink_input_info_cb_t', 'pa_context_get_sink_input_info',
'pa_context_get_sink_input_info_list', 'pa_context_move_sink_input_by_name',
'pa_context_move_sink_input_by_index', 'pa_context_set_sink_input_volume',
'pa_context_set_sink_input_mute', 'pa_context_kill_sink_input',
'pa_source_output_info', 'pa_source_output_info_cb_t',
'pa_context_get_source_output_info', 'pa_context_get_source_output_info_list',
'pa_context_move_source_output_by_name',
'pa_context_move_source_output_by_index',
'pa_context_set_source_output_volume', 'pa_context_set_source_output_mute',
'pa_context_kill_source_output', 'pa_stat_info', 'pa_stat_info_cb_t',
'pa_context_stat', 'pa_sample_info', 'pa_sample_info_cb_t',
'pa_context_get_sample_info_by_name', 'pa_context_get_sample_info_by_index',
'pa_context_get_sample_info_list', 'pa_autoload_type_t', 'PA_AUTOLOAD_SINK',
'PA_AUTOLOAD_SOURCE', 'pa_autoload_info', 'pa_autoload_info_cb_t',
'pa_context_get_autoload_info_by_name',
'pa_context_get_autoload_info_by_index', 'pa_context_get_autoload_info_list',
'pa_context_add_autoload', 'pa_context_remove_autoload_by_name',
'pa_context_remove_autoload_by_index', 'pa_context_subscribe_cb_t',
'pa_context_subscribe', 'pa_context_set_subscribe_callback',
'pa_context_play_sample_cb_t', 'pa_stream_connect_upload',
'pa_stream_finish_upload', 'pa_context_remove_sample',
'pa_context_play_sample', 'pa_context_play_sample_with_proplist',
'pa_strerror', 'pa_xmalloc', 'pa_xmalloc0', 'pa_xrealloc', 'pa_xfree',
'pa_xstrdup', 'pa_xstrndup', 'pa_xmemdup', '_pa_xnew_internal',
'_pa_xnew0_internal', '_pa_xnewdup_internal', '_pa_xrenew_internal',
'pa_utf8_valid', 'pa_ascii_valid', 'pa_utf8_filter', 'pa_ascii_filter',
'pa_utf8_to_locale', 'pa_locale_to_utf8', 'pa_threaded_mainloop',
'pa_threaded_mainloop_new', 'pa_threaded_mainloop_free',
'pa_threaded_mainloop_start', 'pa_threaded_mainloop_stop',
'pa_threaded_mainloop_lock', 'pa_threaded_mainloop_unlock',
'pa_threaded_mainloop_wait', 'pa_threaded_mainloop_signal',
'pa_threaded_mainloop_accept', 'pa_threaded_mainloop_get_retval',
'pa_threaded_mainloop_get_api', 'pa_threaded_mainloop_in_thread',
'pa_threaded_mainloop_set_name', 'pa_mainloop', 'pa_mainloop_new',
'pa_mainloop_free', 'pa_mainloop_prepare', 'pa_mainloop_poll',
'pa_mainloop_dispatch', 'pa_mainloop_get_retval', 'pa_mainloop_iterate',
'pa_mainloop_run', 'pa_mainloop_get_api', 'pa_mainloop_quit',
'pa_mainloop_wakeup', 'pa_poll_func', 'pa_mainloop_set_poll_func',
'pa_signal_event', 'pa_signal_cb_t', 'pa_signal_destroy_cb_t',
'pa_signal_init', 'pa_signal_done', 'pa_signal_new', 'pa_signal_free',
'pa_signal_set_destroy', 'pa_get_user_name', 'pa_get_host_name',
'pa_get_fqdn', 'pa_get_home_dir', 'pa_get_binary_name',
'pa_path_get_filename', 'pa_msleep', 'pa_gettimeofday', 'pa_timeval_diff',
'pa_timeval_cmp', 'pa_timeval_age', 'pa_timeval_add', 'pa_timeval_sub',
'pa_timeval_store', 'pa_timeval_load']
| 118,336 | 39.100644 | 168 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/pyglet/media/drivers/pulse/__init__.py
|
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
from __future__ import absolute_import
from .adaptation import PulseAudioDriver
import pyglet
_debug = pyglet.options['debug_media']
def create_audio_driver():
driver = PulseAudioDriver()
driver.connect()
if _debug:
driver.dump_debug_info()
return driver
| 1,997 | 41.510638 | 78 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/pyglet/media/drivers/pulse/interface.py
|
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
from __future__ import print_function
from __future__ import absolute_import
import ctypes
import sys
import weakref
from . import lib_pulseaudio as pa
from pyglet.media.exceptions import MediaException
import pyglet
_debug = pyglet.options['debug_media']
def get_uint32_or_none(value):
# Check for max uint32
if value is None or value == 4294967295:
return None
return value
def get_bool_or_none(value):
if value < 0:
return None
elif value == 1:
return True
else:
return False
def get_ascii_str_or_none(value):
if value is not None:
return value.decode('ascii')
return None
class PulseAudioException(MediaException):
def __init__(self, error_code, message):
super(PulseAudioException, self).__init__(message)
self.error_code = error_code
self.message = message
def __str__(self):
return '{}: [{}] {}'.format(self.__class__.__name__,
self.error_code,
self.message)
__repr__ = __str__
class PulseAudioMainLoop(object):
def __init__(self):
self._pa_threaded_mainloop = pa.pa_threaded_mainloop_new()
self._pa_mainloop = pa.pa_threaded_mainloop_get_api(
self._pa_threaded_mainloop)
self._lock_count = 0
def __del__(self):
self.delete()
def start(self):
"""Start running the mainloop."""
with self:
result = pa.pa_threaded_mainloop_start(self._pa_threaded_mainloop)
if result < 0:
raise PulseAudioException(0, "Failed to start PulseAudio mainloop")
if _debug:
print('PulseAudioMainLoop: Started')
def delete(self):
"""Clean up the mainloop."""
if self._pa_threaded_mainloop is not None:
if _debug:
print("PulseAudioMainLoop.delete")
pa.pa_threaded_mainloop_stop(self._pa_threaded_mainloop)
pa.pa_threaded_mainloop_free(self._pa_threaded_mainloop)
self._pa_threaded_mainloop = None
self._pa_mainloop = None
def lock(self):
"""Lock the threaded mainloop against events. Required for all
calls into PA."""
assert self._pa_threaded_mainloop is not None
pa.pa_threaded_mainloop_lock(self._pa_threaded_mainloop)
self._lock_count += 1
def unlock(self):
"""Unlock the mainloop thread."""
assert self._pa_threaded_mainloop is not None
# TODO: This is not completely safe. Unlock might be called without lock.
assert self._lock_count > 0
self._lock_count -= 1
pa.pa_threaded_mainloop_unlock(self._pa_threaded_mainloop)
def signal(self):
"""Signal the mainloop thread to break from a wait."""
assert self._pa_threaded_mainloop is not None
pa.pa_threaded_mainloop_signal(self._pa_threaded_mainloop, 0)
def wait(self):
"""Wait for a signal."""
assert self._pa_threaded_mainloop is not None
# Although lock and unlock can be called reentrantly, the wait call only releases one lock.
assert self._lock_count > 0
original_lock_count = self._lock_count
while self._lock_count > 1:
self.unlock()
pa.pa_threaded_mainloop_wait(self._pa_threaded_mainloop)
while self._lock_count < original_lock_count:
self.lock()
def create_context(self):
return PulseAudioContext(self, self._context_new())
def _context_new(self):
"""Construct a new context in this mainloop."""
assert self._pa_mainloop is not None
app_name = self._get_app_name()
context = pa.pa_context_new(self._pa_mainloop,
app_name.encode('ASCII')
)
return context
def _get_app_name(self):
"""Get the application name as advertised to the pulseaudio server."""
# TODO move app name into pyglet.app (also useful for OS X menu bar?).
return sys.argv[0]
def __enter__(self):
self.lock()
def __exit__(self, exc_type, exc_value, traceback):
self.unlock()
class PulseAudioLockable(object):
def __init__(self, mainloop):
assert mainloop is not None
self.mainloop = weakref.ref(mainloop)
def lock(self):
"""Lock the threaded mainloop against events. Required for all
calls into PA."""
self.mainloop().lock()
def unlock(self):
"""Unlock the mainloop thread."""
self.mainloop().unlock()
def signal(self):
"""Signal the mainloop thread to break from a wait."""
self.mainloop().signal()
def wait(self):
"""Wait for a signal."""
self.mainloop().wait()
def __enter__(self):
self.lock()
def __exit__(self, exc_type, exc_value, traceback):
self.unlock()
class PulseAudioContext(PulseAudioLockable):
"""Basic object for a connection to a PulseAudio server."""
_state_name = {pa.PA_CONTEXT_UNCONNECTED: 'Unconnected',
pa.PA_CONTEXT_CONNECTING: 'Connecting',
pa.PA_CONTEXT_AUTHORIZING: 'Authorizing',
pa.PA_CONTEXT_SETTING_NAME: 'Setting Name',
pa.PA_CONTEXT_READY: 'Ready',
pa.PA_CONTEXT_FAILED: 'Failed',
pa.PA_CONTEXT_TERMINATED: 'Terminated'}
def __init__(self, mainloop, pa_context):
super(PulseAudioContext, self).__init__(mainloop)
self._pa_context = pa_context
self.state = None
self._connect_callbacks()
def __del__(self):
if self._pa_context is not None:
with self:
self.delete()
def delete(self):
"""Completely shut down pulseaudio client."""
if self._pa_context is not None:
if _debug:
print("PulseAudioContext.delete")
pa.pa_context_disconnect(self._pa_context)
while self.state is not None and not self.is_terminated:
self.wait()
self._disconnect_callbacks()
pa.pa_context_unref(self._pa_context)
self._pa_context = None
@property
def is_ready(self):
return self.state == pa.PA_CONTEXT_READY
@property
def is_failed(self):
return self.state == pa.PA_CONTEXT_FAILED
@property
def is_terminated(self):
return self.state == pa.PA_CONTEXT_TERMINATED
@property
def server(self):
if self.is_ready:
return get_ascii_str_or_none(pa.pa_context_get_server(self._pa_context))
else:
return None
@property
def protocol_version(self):
if self._pa_context is not None:
return get_uint32_or_none(pa.pa_context_get_protocol_version(self._pa_context))
@property
def server_protocol_version(self):
if self._pa_context is not None:
return get_uint32_or_none(pa.pa_context_get_server_protocol_version(self._pa_context))
@property
def is_local(self):
if self._pa_context is not None:
return get_bool_or_none(pa.pa_context_is_local(self._pa_context))
def connect(self, server=None):
"""Connect the context to a PulseAudio server.
:Parameters:
`server` : str
Server to connect to, or ``None`` for the default local
server (which may be spawned as a daemon if no server is
found).
"""
assert self._pa_context is not None
self.state = None
with self:
self.check(
pa.pa_context_connect(self._pa_context, server, 0, None)
)
while not self.is_failed and not self.is_ready:
self.wait()
if self.is_failed:
self.raise_error()
def create_stream(self, audio_format):
"""
Create a new audio stream.
"""
mainloop = self.mainloop()
assert mainloop is not None
assert self.is_ready
sample_spec = self.create_sample_spec(audio_format)
channel_map = None
# TODO It is now recommended to use pa_stream_new_with_proplist()
stream = pa.pa_stream_new(self._pa_context,
str(id(self)).encode('ASCII'),
sample_spec,
channel_map)
self.check_not_null(stream)
return PulseAudioStream(mainloop, self, stream)
def create_sample_spec(self, audio_format):
"""
Create a PulseAudio sample spec from pyglet audio format.
"""
sample_spec = pa.pa_sample_spec()
if audio_format.sample_size == 8:
sample_spec.format = pa.PA_SAMPLE_U8
elif audio_format.sample_size == 16:
if sys.byteorder == 'little':
sample_spec.format = pa.PA_SAMPLE_S16LE
else:
sample_spec.format = pa.PA_SAMPLE_S16BE
else:
raise MediaException('Unsupported sample size')
sample_spec.rate = audio_format.sample_rate
sample_spec.channels = audio_format.channels
return sample_spec
def set_input_volume(self, stream, volume):
"""
Set the volume for a stream.
"""
cvolume = self._get_cvolume_from_linear(stream, volume)
with self:
idx = stream.index
op = pa.pa_context_set_sink_volume(self._pa_context,
idx,
cvolume,
self._success_cb_func,
None)
return op
def _get_cvolume_from_linear(self, stream, volume):
cvolume = pa.pa_cvolume()
volume = pa.pa_sw_volume_from_linear(volume)
pa.pa_cvolume_set(cvolume,
stream.audio_format.channels,
volume)
return cvolume
def _connect_callbacks(self):
self._state_cb_func = pa.pa_context_notify_cb_t(self._state_callback)
pa.pa_context_set_state_callback(self._pa_context,
self._state_cb_func, None)
def _disconnect_callbacks(self):
self._state_cb_func = None
pa.pa_context_set_state_callback(self._pa_context,
pa.pa_context_notify_cb_t(0),
None)
def _state_callback(self, context, userdata):
self.state = pa.pa_context_get_state(self._pa_context)
if _debug:
print('PulseAudioContext: state changed to {}'.format(self._state_name[self.state]))
self.signal()
def check(self, result):
if result < 0:
self.raise_error()
return result
def check_not_null(self, value):
if value is None:
self.raise_error()
return value
def check_ptr_not_null(self, value):
if not value:
self.raise_error()
return value
def raise_error(self):
error = pa.pa_context_errno(self._pa_context)
raise PulseAudioException(error, get_ascii_str_or_none(pa.pa_strerror(error)))
class PulseAudioStream(PulseAudioLockable, pyglet.event.EventDispatcher):
"""PulseAudio audio stream."""
_state_name = {pa.PA_STREAM_UNCONNECTED: 'Unconnected',
pa.PA_STREAM_CREATING: 'Creating',
pa.PA_STREAM_READY: 'Ready',
pa.PA_STREAM_FAILED: 'Failed',
pa.PA_STREAM_TERMINATED: 'Terminated'}
def __init__(self, mainloop, context, pa_stream):
PulseAudioLockable.__init__(self, mainloop)
self._pa_stream = pa_stream
self.context = weakref.ref(context)
self.state = None
self.underflow = False
pa.pa_stream_ref(self._pa_stream)
self._connect_callbacks()
self._refresh_state()
def __del__(self):
if self._pa_stream is not None:
self.delete()
def delete(self):
context = self.context()
if context is None:
if _debug:
print("No active context anymore. Cannot disconnect the stream")
self._pa_stream = None
return
if self._pa_stream is None:
assert _debug("No stream to delete.")
return
if _debug:
print("PulseAudioStream.delete")
print('PulseAudioStream: writable_size {}'.format(self.writable_size))
if not self.is_unconnected:
if _debug:
print("PulseAudioStream: disconnecting")
with self:
context.check(
pa.pa_stream_disconnect(self._pa_stream)
)
while not (self.is_terminated or self.is_failed):
self.wait()
self._disconnect_callbacks()
pa.pa_stream_unref(self._pa_stream)
self._pa_stream = None
@property
def is_unconnected(self):
return self.state == pa.PA_STREAM_UNCONNECTED
@property
def is_creating(self):
return self.state == pa.PA_STREAM_CREATING
@property
def is_ready(self):
return self.state == pa.PA_STREAM_READY
@property
def is_failed(self):
return self.state == pa.PA_STREAM_FAILED
@property
def is_terminated(self):
return self.state == pa.PA_STREAM_TERMINATED
@property
def writable_size(self):
assert self._pa_stream is not None
return pa.pa_stream_writable_size(self._pa_stream)
@property
def index(self):
assert self._pa_stream is not None
return pa.pa_stream_get_index(self._pa_stream)
@property
def is_corked(self):
assert self._pa_stream is not None
return get_bool_or_none(pa.pa_stream_is_corked(self._pa_stream))
def connect_playback(self):
context = self.context()
assert self._pa_stream is not None
assert context is not None
device = None
buffer_attr = None
flags = (pa.PA_STREAM_START_CORKED |
pa.PA_STREAM_INTERPOLATE_TIMING |
pa.PA_STREAM_VARIABLE_RATE)
volume = None
sync_stream = None # TODO use this
context.check(
pa.pa_stream_connect_playback(self._pa_stream,
device,
buffer_attr,
flags,
volume,
sync_stream)
)
while not self.is_ready and not self.is_failed:
self.wait()
if not self.is_ready:
context.raise_error()
if _debug:
print('PulseAudioStream: Playback connected')
def write(self, audio_data, length=None, seek_mode=pa.PA_SEEK_RELATIVE):
context = self.context()
assert context is not None
assert self._pa_stream is not None
assert self.is_ready
if length is None:
length = min(audio_data.length, self.writable_size)
if _debug:
print('PulseAudioStream: writing {} bytes'.format(length))
print('PulseAudioStream: writable size before write {} bytes'.format(self.writable_size))
context.check(
pa.pa_stream_write(self._pa_stream,
audio_data.data,
length,
pa.pa_free_cb_t(0), # Data is copied
0,
seek_mode)
)
if _debug:
print('PulseAudioStream: writable size after write {} bytes'.format(self.writable_size))
self.underflow = False
return length
def update_timing_info(self, callback=None):
context = self.context()
assert context is not None
assert self._pa_stream is not None
op = PulseAudioOperation(context, callback)
op.execute(
pa.pa_stream_update_timing_info(self._pa_stream,
op.pa_callback,
None)
)
return op
def get_timing_info(self):
context = self.context()
assert context is not None
assert self._pa_stream is not None
timing_info = context.check_ptr_not_null(
pa.pa_stream_get_timing_info(self._pa_stream)
)
return timing_info.contents
def trigger(self, callback=None):
context = self.context()
assert context is not None
assert self._pa_stream is not None
op = PulseAudioOperation(context)
op.execute(
pa.pa_stream_trigger(self._pa_stream,
op.pa_callback,
None)
)
return op
def prebuf(self, callback=None):
context = self.context()
assert context is not None
assert self._pa_stream is not None
op = PulseAudioOperation(context)
op.execute(
pa.pa_stream_prebuf(self._pa_stream,
op.pa_callback,
None)
)
return op
def resume(self, callback=None):
return self._cork(False, callback)
def pause(self, callback=None):
return self._cork(True, callback)
def update_sample_rate(self, sample_rate, callback=None):
context = self.context()
assert context is not None
assert self._pa_stream is not None
op = PulseAudioOperation(context)
op.execute(
pa.pa_stream_update_sample_rate(self._pa_stream,
int(sample_rate),
op.pa_callback,
None)
)
return op
def _cork(self, pause, callback):
context = self.context()
assert context is not None
assert self._pa_stream is not None
op = PulseAudioOperation(context)
op.execute(
pa.pa_stream_cork(self._pa_stream,
1 if pause else 0,
op.pa_callback,
None)
)
return op
def _connect_callbacks(self):
self._cb_underflow = pa.pa_stream_notify_cb_t(self._underflow_callback)
self._cb_write = pa.pa_stream_request_cb_t(self._write_callback)
self._cb_state = pa.pa_stream_notify_cb_t(self._state_callback)
pa.pa_stream_set_underflow_callback(self._pa_stream, self._cb_underflow, None)
pa.pa_stream_set_write_callback(self._pa_stream, self._cb_write, None)
pa.pa_stream_set_state_callback(self._pa_stream, self._cb_state, None)
def _disconnect_callbacks(self):
self._cb_underflow = None
self._cb_write = None
self._cb_state = None
pa.pa_stream_set_underflow_callback(self._pa_stream,
pa.pa_stream_notify_cb_t(0),
None)
pa.pa_stream_set_write_callback(self._pa_stream,
pa.pa_stream_request_cb_t(0),
None)
pa.pa_stream_set_state_callback(self._pa_stream,
pa.pa_stream_notify_cb_t(0),
None)
def _underflow_callback(self, stream, userdata):
if _debug:
print("PulseAudioStream: underflow")
self.underflow = True
self._write_needed()
self.signal()
def _write_callback(self, stream, nbytes, userdata):
if _debug:
print("PulseAudioStream: write requested")
self._write_needed(nbytes)
self.signal()
def _state_callback(self, stream, userdata):
self._refresh_state()
if _debug:
print("PulseAudioStream: state changed to {}".format(self._state_name[self.state]))
self.signal()
def _refresh_state(self):
if self._pa_stream is not None:
self.state = pa.pa_stream_get_state(self._pa_stream)
def _write_needed(self, nbytes=None):
if nbytes is None:
nbytes = self.writable_size
# This dispatch call is made from the threaded mainloop thread!
pyglet.app.platform_event_loop.post_event(
self, 'on_write_needed', nbytes, self.underflow)
def on_write_needed(self, nbytes, underflow):
"""A write is requested from PulseAudio.
Called from the PulseAudio mainloop, so no locking required.
:event:
"""
PulseAudioStream.register_event_type('on_write_needed')
class PulseAudioOperation(PulseAudioLockable):
"""Asynchronous PulseAudio operation"""
_state_name = {pa.PA_OPERATION_RUNNING: 'Running',
pa.PA_OPERATION_DONE: 'Done',
pa.PA_OPERATION_CANCELLED: 'Cancelled'}
def __init__(self, context, callback=None, pa_operation=None):
mainloop = context.mainloop()
assert mainloop is not None
PulseAudioLockable.__init__(self, mainloop)
self.context = weakref.ref(context)
self._callback = callback
self.pa_callback = pa.pa_stream_success_cb_t(self._success_callback)
if pa_operation is not None:
self.execute(pa_operation)
else:
self._pa_operation = None
def __del__(self):
if self._pa_operation is not None:
with self:
self.delete()
def delete(self):
if self._pa_operation is not None:
if _debug:
print("PulseAudioOperation.delete({})".format(id(self)))
pa.pa_operation_unref(self._pa_operation)
self._pa_operation = None
def execute(self, pa_operation):
context = self.context()
assert context is not None
context.check_ptr_not_null(pa_operation)
if _debug:
print("PulseAudioOperation.execute({})".format(id(self)))
self._pa_operation = pa_operation
self._get_state()
return self
def cancel(self):
assert self._pa_operation is not None
pa.pa_operation_cancel(self._pa_operation)
return self
@property
def is_running(self):
return self._get_state() == pa.PA_OPERATION_RUNNING
@property
def is_done(self):
return self._get_state() == pa.PA_OPERATION_DONE
@property
def is_cancelled(self):
return self._get_state() == pa.PA_OPERATION_CANCELLED
def wait(self):
"""Wait until operation is either done or cancelled."""
while self.is_running:
super(PulseAudioOperation, self).wait()
return self
def _get_state(self):
assert self._pa_operation is not None
return pa.pa_operation_get_state(self._pa_operation)
def _success_callback(self, stream, success, userdata):
if self._callback:
self._callback()
self.pa_callback = None # Clean up callback, not called anymore
self.signal()
| 25,304 | 33.149798 | 101 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/pyglet/media/drivers/pulse/adaptation.py
|
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
from __future__ import print_function
from __future__ import absolute_import
import weakref
from pyglet.media.drivers.base import AbstractAudioDriver, AbstractAudioPlayer
from pyglet.media.events import MediaEvent
from pyglet.media.exceptions import MediaException
from pyglet.media.listener import AbstractListener
from . import lib_pulseaudio as pa
from .interface import PulseAudioContext, PulseAudioContext, PulseAudioMainLoop, PulseAudioStream
import pyglet
_debug = pyglet.options['debug_media']
class PulseAudioDriver(AbstractAudioDriver):
def __init__(self):
self.mainloop = PulseAudioMainLoop()
self.mainloop.start()
self.lock = self.mainloop
self.context = None
self._players = pyglet.app.WeakSet()
self._listener = PulseAudioListener(self)
def __del__(self):
self.delete()
def create_audio_player(self, source_group, player):
assert self.context is not None
player = PulseAudioPlayer(source_group, player, self)
self._players.add(player)
return player
def connect(self, server=None):
"""Connect to pulseaudio server.
:Parameters:
`server` : str
Server to connect to, or ``None`` for the default local
server (which may be spawned as a daemon if no server is
found).
"""
# TODO disconnect from old
assert not self.context, 'Already connected'
self.context = self.mainloop.create_context()
self.context.connect(server)
def dump_debug_info(self):
print('Client version: ', pa.pa_get_library_version())
print('Server: ', self.context.server)
print('Protocol: ', self.context.protocol_version)
print('Server protocol:', self.context.server_protocol_version)
print('Local context: ', self.context.is_local and 'Yes' or 'No')
def delete(self):
"""Completely shut down pulseaudio client."""
if self.mainloop is not None:
with self.mainloop:
if self.context is not None:
self.context.delete()
self.context = None
if self.mainloop is not None:
self.mainloop.delete()
self.mainloop = None
self.lock = None
def get_listener(self):
return self._listener
class PulseAudioListener(AbstractListener):
def __init__(self, driver):
self.driver = weakref.proxy(driver)
def _set_volume(self, volume):
self._volume = volume
for player in self.driver._players:
player.set_volume(player._volume)
def _set_position(self, position):
self._position = position
def _set_forward_orientation(self, orientation):
self._forward_orientation = orientation
def _set_up_orientation(self, orientation):
self._up_orientation = orientation
class PulseAudioPlayer(AbstractAudioPlayer):
_volume = 1.0
def __init__(self, source_group, player, driver):
super(PulseAudioPlayer, self).__init__(source_group, player)
self.driver = weakref.ref(driver)
self._events = []
self._timestamps = [] # List of (ref_time, timestamp)
self._write_index = 0 # Current write index (tracked manually)
self._read_index_valid = False # True only if buffer has non-stale data
self._clear_write = False
self._buffered_audio_data = None
self._playing = False
self._current_audio_data = None
self._time_sync_operation = None
audio_format = source_group.audio_format
assert audio_format
with driver.mainloop:
self.stream = driver.context.create_stream(audio_format)
self.stream.push_handlers(self)
self.stream.connect_playback()
assert self.stream.is_ready
if _debug:
print('PulseAudioPlayer: __init__ finished')
def on_write_needed(self, nbytes, underflow):
if underflow:
self._handle_underflow()
else:
self._write_to_stream(nbytes)
# Asynchronously update time
if self._events:
if self._time_sync_operation is not None and self._time_sync_operation.is_done:
self._time_sync_operation.delete()
self._time_sync_operation = None
if self._time_sync_operation is None:
if _debug:
print('PulseAudioPlayer: trigger timing info update')
self._time_sync_operation = self.stream.update_timing_info(self._process_events)
def _get_audio_data(self, nbytes=None):
if self._current_audio_data is None and self.source_group is not None:
# Always try to buffer at least 1 second of audio data
min_bytes = 1 * self.source_group.audio_format.bytes_per_second
if nbytes is None:
nbytes = min_bytes
else:
nbytes = min(min_bytes, nbytes)
if _debug:
print('PulseAudioPlayer: Try to get {} bytes of audio data'.format(nbytes))
self._current_audio_data = self.source_group.get_audio_data(nbytes)
self._schedule_events()
if _debug:
if self._current_audio_data is None:
print('PulseAudioPlayer: No audio data available')
else:
print('PulseAudioPlayer: Got {} bytes of audio data'.format(self._current_audio_data.length))
return self._current_audio_data
def _has_audio_data(self):
return self._get_audio_data() is not None
def _consume_audio_data(self, nbytes):
if self._current_audio_data is not None:
if nbytes == self._current_audio_data.length:
self._current_audio_data = None
else:
self._current_audio_data.consume(nbytes, self.source_group.audio_format)
def _schedule_events(self):
if self._current_audio_data is not None:
for event in self._current_audio_data.events:
event_index = self._write_index + event.timestamp * \
self.source_group.audio_format.bytes_per_second
if _debug:
print('PulseAudioPlayer: Schedule event at index {}'.format(event_index))
self._events.append((event_index, event))
def _write_to_stream(self, nbytes=None):
if nbytes is None:
nbytes = self.stream.writable_size
if _debug:
print('PulseAudioPlayer: Requested to write %d bytes to stream' % nbytes)
seek_mode = pa.PA_SEEK_RELATIVE
if self._clear_write:
seek_mode = pa.PA_SEEK_RELATIVE_ON_READ
self._clear_write = False
if _debug:
print('PulseAudioPlayer: Clear buffer')
while self._has_audio_data() and nbytes > 0:
audio_data = self._get_audio_data()
write_length = min(nbytes, audio_data.length)
consumption = self.stream.write(audio_data, write_length, seek_mode)
seek_mode = pa.PA_SEEK_RELATIVE
self._read_index_valid = True
self._timestamps.append((self._write_index, audio_data.timestamp))
self._write_index += consumption
if _debug:
print('PulseAudioPlayer: Actually wrote %d bytes to stream' % consumption)
self._consume_audio_data(consumption)
nbytes -= consumption
if not self._has_audio_data():
# In case the source group wasn't long enough to prebuffer stream
# to PA's satisfaction, trigger immediate playback (has no effect
# if stream is already playing).
if self._playing:
op = self.stream.trigger()
op.delete() # Explicit delete to prevent locking
def _handle_underflow(self):
if _debug:
print('Player: underflow')
if self._has_audio_data():
self._write_to_stream()
else:
self._add_event_at_write_index('on_eos')
self._add_event_at_write_index('on_source_group_eos')
def _process_events(self):
if _debug:
print('PulseAudioPlayer: Process events')
if not self._events:
if _debug:
print('PulseAudioPlayer: No events')
return
# Assume this is called after time sync
timing_info = self.stream.get_timing_info()
if not timing_info:
if _debug:
print('PulseAudioPlayer: No timing info to process events')
return
read_index = timing_info.read_index
if _debug:
print('PulseAudioPlayer: Dispatch events at index {}'.format(read_index))
while self._events and self._events[0][0] <= read_index:
_, event = self._events.pop(0)
if _debug:
print('PulseAudioPlayer: Dispatch event', event)
event._sync_dispatch_to_player(self.player)
def _add_event_at_write_index(self, event_name):
if _debug:
print('PulseAudioPlayer: Add event at index {}'.format(self._write_index))
self._events.append((self._write_index, MediaEvent(0., event_name)))
def delete(self):
if _debug:
print('PulseAudioPlayer.delete')
self.stream.pop_handlers()
driver = self.driver()
if driver is None:
if _debug:
print('PulseAudioDriver has been garbage collected.')
self.stream = None
return
if driver.mainloop is None:
if _debug:
print('PulseAudioDriver already deleted. '
'PulseAudioPlayer could not clean up properly.')
return
if self._time_sync_operation is not None:
with self._time_sync_operation:
self._time_sync_operation.delete()
self._time_sync_operation = None
self.stream.delete()
self.stream = None
def clear(self):
if _debug:
print('PulseAudioPlayer.clear')
self._clear_write = True
self._write_index = self._get_read_index()
self._timestamps = []
self._events = []
with self.stream:
self._read_index_valid = False
self.stream.prebuf().wait()
def play(self):
if _debug:
print('PulseAudioPlayer.play')
with self.stream:
if self.stream.is_corked:
self.stream.resume().wait().delete()
if _debug:
print('PulseAudioPlayer: Resumed playback')
if self.stream.underflow:
self._write_to_stream()
if not self._has_audio_data():
self.stream.trigger().wait().delete()
if _debug:
print('PulseAudioPlayer: Triggered stream for immediate playback')
assert not self.stream.is_corked
self._playing = True
def stop(self):
if _debug:
print('PulseAudioPlayer.stop')
with self.stream:
if not self.stream.is_corked:
self.stream.pause().wait().delete()
self._playing = False
def _get_read_index(self):
with self.stream:
self.stream.update_timing_info().wait().delete()
timing_info = self.stream.get_timing_info()
if timing_info:
read_index = timing_info.read_index
else:
read_index = 0
if _debug:
print('_get_read_index ->', read_index)
return read_index
def _get_write_index(self):
timing_info = self.stream.get_timing_info()
if timing_info:
write_index = timing_info.write_index
else:
write_index = 0
if _debug:
print('_get_write_index ->', write_index)
return write_index
def get_time(self):
if not self._read_index_valid:
if _debug:
print('get_time <_read_index_valid = False> -> None')
return
read_index = self._get_read_index()
write_index = 0
timestamp = 0.0
try:
write_index, timestamp = self._timestamps[0]
write_index, timestamp = self._timestamps[1]
while read_index >= write_index:
del self._timestamps[0]
write_index, timestamp = self._timestamps[1]
except IndexError:
pass
bytes_per_second = self.source_group.audio_format.bytes_per_second
time = timestamp + (read_index - write_index) / float(bytes_per_second)
if _debug:
print('get_time ->', time)
return time
def set_volume(self, volume):
self._volume = volume
if self.stream:
volume *= self.driver._listener._volume
with self.context:
self.context.set_input_volume(self.stream, volume).wait()
def set_pitch(self, pitch):
with self.stream:
self.stream.update_sample_rate(int(pitch * self.sample_rate)).wait()
| 14,958 | 34.28066 | 109 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/pyglet/media/drivers/openal/lib_alc.py
|
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
'''Wrapper for openal
Generated with:
../tools/wraptypes/wrap.py /usr/include/AL/alc.h -lopenal -olib_alc.py
.. Hacked to fix ALCvoid argtypes.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import ctypes
from ctypes import *
import sys
import pyglet.lib
_lib = pyglet.lib.load_library('openal', win32='openal32',
framework='/System/Library/Frameworks/OpenAL.framework')
_int_types = (c_int16, c_int32)
if hasattr(ctypes, 'c_int64'):
# Some builds of ctypes apparently do not have c_int64
# defined; it's a pretty good bet that these builds do not
# have 64-bit pointers.
_int_types += (ctypes.c_int64,)
for t in _int_types:
if sizeof(t) == sizeof(c_size_t):
c_ptrdiff_t = t
class c_void(Structure):
# c_void_p is a buggy return type, converting to int, so
# POINTER(None) == c_void_p is actually written as
# POINTER(c_void), so it can be treated as a real pointer.
_fields_ = [('dummy', c_int)]
ALC_API = 0 # /usr/include/AL/alc.h:19
ALCAPI = 0 # /usr/include/AL/alc.h:37
ALC_INVALID = 0 # /usr/include/AL/alc.h:39
ALC_VERSION_0_1 = 1 # /usr/include/AL/alc.h:42
class struct_ALCdevice_struct(Structure):
__slots__ = [
]
struct_ALCdevice_struct._fields_ = [
('_opaque_struct', c_int)
]
class struct_ALCdevice_struct(Structure):
__slots__ = [
]
struct_ALCdevice_struct._fields_ = [
('_opaque_struct', c_int)
]
ALCdevice = struct_ALCdevice_struct # /usr/include/AL/alc.h:44
class struct_ALCcontext_struct(Structure):
__slots__ = [
]
struct_ALCcontext_struct._fields_ = [
('_opaque_struct', c_int)
]
class struct_ALCcontext_struct(Structure):
__slots__ = [
]
struct_ALCcontext_struct._fields_ = [
('_opaque_struct', c_int)
]
ALCcontext = struct_ALCcontext_struct # /usr/include/AL/alc.h:45
ALCboolean = c_char # /usr/include/AL/alc.h:49
ALCchar = c_char # /usr/include/AL/alc.h:52
ALCbyte = c_char # /usr/include/AL/alc.h:55
ALCubyte = c_ubyte # /usr/include/AL/alc.h:58
ALCshort = c_short # /usr/include/AL/alc.h:61
ALCushort = c_ushort # /usr/include/AL/alc.h:64
ALCint = c_int # /usr/include/AL/alc.h:67
ALCuint = c_uint # /usr/include/AL/alc.h:70
ALCsizei = c_int # /usr/include/AL/alc.h:73
ALCenum = c_int # /usr/include/AL/alc.h:76
ALCfloat = c_float # /usr/include/AL/alc.h:79
ALCdouble = c_double # /usr/include/AL/alc.h:82
ALCvoid = None # /usr/include/AL/alc.h:85
ALC_FALSE = 0 # /usr/include/AL/alc.h:91
ALC_TRUE = 1 # /usr/include/AL/alc.h:94
ALC_FREQUENCY = 4103 # /usr/include/AL/alc.h:99
ALC_REFRESH = 4104 # /usr/include/AL/alc.h:104
ALC_SYNC = 4105 # /usr/include/AL/alc.h:109
ALC_MONO_SOURCES = 4112 # /usr/include/AL/alc.h:114
ALC_STEREO_SOURCES = 4113 # /usr/include/AL/alc.h:119
ALC_NO_ERROR = 0 # /usr/include/AL/alc.h:128
ALC_INVALID_DEVICE = 40961 # /usr/include/AL/alc.h:133
ALC_INVALID_CONTEXT = 40962 # /usr/include/AL/alc.h:138
ALC_INVALID_ENUM = 40963 # /usr/include/AL/alc.h:143
ALC_INVALID_VALUE = 40964 # /usr/include/AL/alc.h:148
ALC_OUT_OF_MEMORY = 40965 # /usr/include/AL/alc.h:153
ALC_DEFAULT_DEVICE_SPECIFIER = 4100 # /usr/include/AL/alc.h:159
ALC_DEVICE_SPECIFIER = 4101 # /usr/include/AL/alc.h:160
ALC_EXTENSIONS = 4102 # /usr/include/AL/alc.h:161
ALC_MAJOR_VERSION = 4096 # /usr/include/AL/alc.h:163
ALC_MINOR_VERSION = 4097 # /usr/include/AL/alc.h:164
ALC_ATTRIBUTES_SIZE = 4098 # /usr/include/AL/alc.h:166
ALC_ALL_ATTRIBUTES = 4099 # /usr/include/AL/alc.h:167
ALC_CAPTURE_DEVICE_SPECIFIER = 784 # /usr/include/AL/alc.h:172
ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER = 785 # /usr/include/AL/alc.h:173
ALC_CAPTURE_SAMPLES = 786 # /usr/include/AL/alc.h:174
# /usr/include/AL/alc.h:180
alcCreateContext = _lib.alcCreateContext
alcCreateContext.restype = POINTER(ALCcontext)
alcCreateContext.argtypes = [POINTER(ALCdevice), POINTER(ALCint)]
# /usr/include/AL/alc.h:182
alcMakeContextCurrent = _lib.alcMakeContextCurrent
alcMakeContextCurrent.restype = ALCboolean
alcMakeContextCurrent.argtypes = [POINTER(ALCcontext)]
# /usr/include/AL/alc.h:184
alcProcessContext = _lib.alcProcessContext
alcProcessContext.restype = None
alcProcessContext.argtypes = [POINTER(ALCcontext)]
# /usr/include/AL/alc.h:186
alcSuspendContext = _lib.alcSuspendContext
alcSuspendContext.restype = None
alcSuspendContext.argtypes = [POINTER(ALCcontext)]
# /usr/include/AL/alc.h:188
alcDestroyContext = _lib.alcDestroyContext
alcDestroyContext.restype = None
alcDestroyContext.argtypes = [POINTER(ALCcontext)]
# /usr/include/AL/alc.h:190
alcGetCurrentContext = _lib.alcGetCurrentContext
alcGetCurrentContext.restype = POINTER(ALCcontext)
alcGetCurrentContext.argtypes = []
# /usr/include/AL/alc.h:192
alcGetContextsDevice = _lib.alcGetContextsDevice
alcGetContextsDevice.restype = POINTER(ALCdevice)
alcGetContextsDevice.argtypes = [POINTER(ALCcontext)]
# /usr/include/AL/alc.h:198
alcOpenDevice = _lib.alcOpenDevice
alcOpenDevice.restype = POINTER(ALCdevice)
alcOpenDevice.argtypes = [POINTER(ALCchar)]
# /usr/include/AL/alc.h:200
alcCloseDevice = _lib.alcCloseDevice
alcCloseDevice.restype = ALCboolean
alcCloseDevice.argtypes = [POINTER(ALCdevice)]
# /usr/include/AL/alc.h:207
alcGetError = _lib.alcGetError
alcGetError.restype = ALCenum
alcGetError.argtypes = [POINTER(ALCdevice)]
# /usr/include/AL/alc.h:215
alcIsExtensionPresent = _lib.alcIsExtensionPresent
alcIsExtensionPresent.restype = ALCboolean
alcIsExtensionPresent.argtypes = [POINTER(ALCdevice), POINTER(ALCchar)]
# /usr/include/AL/alc.h:217
alcGetProcAddress = _lib.alcGetProcAddress
alcGetProcAddress.restype = POINTER(c_void)
alcGetProcAddress.argtypes = [POINTER(ALCdevice), POINTER(ALCchar)]
# /usr/include/AL/alc.h:219
alcGetEnumValue = _lib.alcGetEnumValue
alcGetEnumValue.restype = ALCenum
alcGetEnumValue.argtypes = [POINTER(ALCdevice), POINTER(ALCchar)]
# /usr/include/AL/alc.h:225
alcGetString = _lib.alcGetString
alcGetString.restype = POINTER(ALCchar)
alcGetString.argtypes = [POINTER(ALCdevice), ALCenum]
# /usr/include/AL/alc.h:227
alcGetIntegerv = _lib.alcGetIntegerv
alcGetIntegerv.restype = None
alcGetIntegerv.argtypes = [POINTER(ALCdevice), ALCenum, ALCsizei, POINTER(ALCint)]
# /usr/include/AL/alc.h:233
alcCaptureOpenDevice = _lib.alcCaptureOpenDevice
alcCaptureOpenDevice.restype = POINTER(ALCdevice)
alcCaptureOpenDevice.argtypes = [POINTER(ALCchar), ALCuint, ALCenum, ALCsizei]
# /usr/include/AL/alc.h:235
alcCaptureCloseDevice = _lib.alcCaptureCloseDevice
alcCaptureCloseDevice.restype = ALCboolean
alcCaptureCloseDevice.argtypes = [POINTER(ALCdevice)]
# /usr/include/AL/alc.h:237
alcCaptureStart = _lib.alcCaptureStart
alcCaptureStart.restype = None
alcCaptureStart.argtypes = [POINTER(ALCdevice)]
# /usr/include/AL/alc.h:239
alcCaptureStop = _lib.alcCaptureStop
alcCaptureStop.restype = None
alcCaptureStop.argtypes = [POINTER(ALCdevice)]
# /usr/include/AL/alc.h:241
alcCaptureSamples = _lib.alcCaptureSamples
alcCaptureSamples.restype = None
alcCaptureSamples.argtypes = [POINTER(ALCdevice), POINTER(ALCvoid), ALCsizei]
LPALCCREATECONTEXT = CFUNCTYPE(POINTER(ALCcontext), POINTER(ALCdevice), POINTER(ALCint)) # /usr/include/AL/alc.h:246
LPALCMAKECONTEXTCURRENT = CFUNCTYPE(ALCboolean, POINTER(ALCcontext)) # /usr/include/AL/alc.h:247
LPALCPROCESSCONTEXT = CFUNCTYPE(None, POINTER(ALCcontext)) # /usr/include/AL/alc.h:248
LPALCSUSPENDCONTEXT = CFUNCTYPE(None, POINTER(ALCcontext)) # /usr/include/AL/alc.h:249
LPALCDESTROYCONTEXT = CFUNCTYPE(None, POINTER(ALCcontext)) # /usr/include/AL/alc.h:250
LPALCGETCURRENTCONTEXT = CFUNCTYPE(POINTER(ALCcontext)) # /usr/include/AL/alc.h:251
LPALCGETCONTEXTSDEVICE = CFUNCTYPE(POINTER(ALCdevice), POINTER(ALCcontext)) # /usr/include/AL/alc.h:252
LPALCOPENDEVICE = CFUNCTYPE(POINTER(ALCdevice), POINTER(ALCchar)) # /usr/include/AL/alc.h:253
LPALCCLOSEDEVICE = CFUNCTYPE(ALCboolean, POINTER(ALCdevice)) # /usr/include/AL/alc.h:254
LPALCGETERROR = CFUNCTYPE(ALCenum, POINTER(ALCdevice)) # /usr/include/AL/alc.h:255
LPALCISEXTENSIONPRESENT = CFUNCTYPE(ALCboolean, POINTER(ALCdevice), POINTER(ALCchar)) # /usr/include/AL/alc.h:256
LPALCGETPROCADDRESS = CFUNCTYPE(POINTER(c_void), POINTER(ALCdevice), POINTER(ALCchar)) # /usr/include/AL/alc.h:257
LPALCGETENUMVALUE = CFUNCTYPE(ALCenum, POINTER(ALCdevice), POINTER(ALCchar)) # /usr/include/AL/alc.h:258
LPALCGETSTRING = CFUNCTYPE(POINTER(ALCchar), POINTER(ALCdevice), ALCenum) # /usr/include/AL/alc.h:259
LPALCGETINTEGERV = CFUNCTYPE(None, POINTER(ALCdevice), ALCenum, ALCsizei, POINTER(ALCint)) # /usr/include/AL/alc.h:260
LPALCCAPTUREOPENDEVICE = CFUNCTYPE(POINTER(ALCdevice), POINTER(ALCchar), ALCuint, ALCenum, ALCsizei) # /usr/include/AL/alc.h:261
LPALCCAPTURECLOSEDEVICE = CFUNCTYPE(ALCboolean, POINTER(ALCdevice)) # /usr/include/AL/alc.h:262
LPALCCAPTURESTART = CFUNCTYPE(None, POINTER(ALCdevice)) # /usr/include/AL/alc.h:263
LPALCCAPTURESTOP = CFUNCTYPE(None, POINTER(ALCdevice)) # /usr/include/AL/alc.h:264
LPALCCAPTURESAMPLES = CFUNCTYPE(None, POINTER(ALCdevice), POINTER(ALCvoid), ALCsizei) # /usr/include/AL/alc.h:265
__all__ = ['ALC_API', 'ALCAPI', 'ALC_INVALID', 'ALC_VERSION_0_1', 'ALCdevice',
'ALCcontext', 'ALCboolean', 'ALCchar', 'ALCbyte', 'ALCubyte', 'ALCshort',
'ALCushort', 'ALCint', 'ALCuint', 'ALCsizei', 'ALCenum', 'ALCfloat',
'ALCdouble', 'ALCvoid', 'ALC_FALSE', 'ALC_TRUE', 'ALC_FREQUENCY',
'ALC_REFRESH', 'ALC_SYNC', 'ALC_MONO_SOURCES', 'ALC_STEREO_SOURCES',
'ALC_NO_ERROR', 'ALC_INVALID_DEVICE', 'ALC_INVALID_CONTEXT',
'ALC_INVALID_ENUM', 'ALC_INVALID_VALUE', 'ALC_OUT_OF_MEMORY',
'ALC_DEFAULT_DEVICE_SPECIFIER', 'ALC_DEVICE_SPECIFIER', 'ALC_EXTENSIONS',
'ALC_MAJOR_VERSION', 'ALC_MINOR_VERSION', 'ALC_ATTRIBUTES_SIZE',
'ALC_ALL_ATTRIBUTES', 'ALC_CAPTURE_DEVICE_SPECIFIER',
'ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER', 'ALC_CAPTURE_SAMPLES',
'alcCreateContext', 'alcMakeContextCurrent', 'alcProcessContext',
'alcSuspendContext', 'alcDestroyContext', 'alcGetCurrentContext',
'alcGetContextsDevice', 'alcOpenDevice', 'alcCloseDevice', 'alcGetError',
'alcIsExtensionPresent', 'alcGetProcAddress', 'alcGetEnumValue',
'alcGetString', 'alcGetIntegerv', 'alcCaptureOpenDevice',
'alcCaptureCloseDevice', 'alcCaptureStart', 'alcCaptureStop',
'alcCaptureSamples', 'LPALCCREATECONTEXT', 'LPALCMAKECONTEXTCURRENT',
'LPALCPROCESSCONTEXT', 'LPALCSUSPENDCONTEXT', 'LPALCDESTROYCONTEXT',
'LPALCGETCURRENTCONTEXT', 'LPALCGETCONTEXTSDEVICE', 'LPALCOPENDEVICE',
'LPALCCLOSEDEVICE', 'LPALCGETERROR', 'LPALCISEXTENSIONPRESENT',
'LPALCGETPROCADDRESS', 'LPALCGETENUMVALUE', 'LPALCGETSTRING',
'LPALCGETINTEGERV', 'LPALCCAPTUREOPENDEVICE', 'LPALCCAPTURECLOSEDEVICE',
'LPALCCAPTURESTART', 'LPALCCAPTURESTOP', 'LPALCCAPTURESAMPLES']
| 12,332 | 41.972125 | 129 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/pyglet/media/drivers/openal/lib_openal.py
|
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
'''Wrapper for openal
Generated with:
../tools/wraptypes/wrap.py /usr/include/AL/al.h -lopenal -olib_openal.py
.. Hacked to remove non-existent library functions.
TODO add alGetError check.
.. alListener3i and alListeneriv are present in my OS X 10.4 but not another
10.4 user's installation. They've also been removed for compatibility.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import ctypes
from ctypes import *
import sys
import pyglet.lib
_lib = pyglet.lib.load_library('openal', win32='openal32',
framework='/System/Library/Frameworks/OpenAL.framework')
_int_types = (c_int16, c_int32)
if hasattr(ctypes, 'c_int64'):
# Some builds of ctypes apparently do not have c_int64
# defined; it's a pretty good bet that these builds do not
# have 64-bit pointers.
_int_types += (ctypes.c_int64,)
for t in _int_types:
if sizeof(t) == sizeof(c_size_t):
c_ptrdiff_t = t
class c_void(Structure):
# c_void_p is a buggy return type, converting to int, so
# POINTER(None) == c_void_p is actually written as
# POINTER(c_void), so it can be treated as a real pointer.
_fields_ = [('dummy', c_int)]
AL_API = 0 # /usr/include/AL/al.h:39
ALAPI = 0 # /usr/include/AL/al.h:59
AL_INVALID = -1 # /usr/include/AL/al.h:61
AL_ILLEGAL_ENUM = 0 # /usr/include/AL/al.h:62
AL_ILLEGAL_COMMAND = 0 # /usr/include/AL/al.h:63
ALboolean = c_int # Better return type than c_char, as generated
ALchar = c_char # /usr/include/AL/al.h:73
ALbyte = c_char # /usr/include/AL/al.h:76
ALubyte = c_ubyte # /usr/include/AL/al.h:79
ALshort = c_short # /usr/include/AL/al.h:82
ALushort = c_ushort # /usr/include/AL/al.h:85
ALint = c_int # /usr/include/AL/al.h:88
ALuint = c_uint # /usr/include/AL/al.h:91
ALsizei = c_int # /usr/include/AL/al.h:94
ALenum = c_int # /usr/include/AL/al.h:97
ALfloat = c_float # /usr/include/AL/al.h:100
ALdouble = c_double # /usr/include/AL/al.h:103
ALvoid = None # /usr/include/AL/al.h:106
AL_NONE = 0 # /usr/include/AL/al.h:112
AL_FALSE = 0 # /usr/include/AL/al.h:115
AL_TRUE = 1 # /usr/include/AL/al.h:118
AL_SOURCE_RELATIVE = 514 # /usr/include/AL/al.h:121
AL_CONE_INNER_ANGLE = 4097 # /usr/include/AL/al.h:130
AL_CONE_OUTER_ANGLE = 4098 # /usr/include/AL/al.h:137
AL_PITCH = 4099 # /usr/include/AL/al.h:145
AL_POSITION = 4100 # /usr/include/AL/al.h:157
AL_DIRECTION = 4101 # /usr/include/AL/al.h:160
AL_VELOCITY = 4102 # /usr/include/AL/al.h:163
AL_LOOPING = 4103 # /usr/include/AL/al.h:171
AL_BUFFER = 4105 # /usr/include/AL/al.h:178
AL_GAIN = 4106 # /usr/include/AL/al.h:191
AL_MIN_GAIN = 4109 # /usr/include/AL/al.h:200
AL_MAX_GAIN = 4110 # /usr/include/AL/al.h:209
AL_ORIENTATION = 4111 # /usr/include/AL/al.h:216
AL_SOURCE_STATE = 4112 # /usr/include/AL/al.h:221
AL_INITIAL = 4113 # /usr/include/AL/al.h:222
AL_PLAYING = 4114 # /usr/include/AL/al.h:223
AL_PAUSED = 4115 # /usr/include/AL/al.h:224
AL_STOPPED = 4116 # /usr/include/AL/al.h:225
AL_BUFFERS_QUEUED = 4117 # /usr/include/AL/al.h:230
AL_BUFFERS_PROCESSED = 4118 # /usr/include/AL/al.h:231
AL_SEC_OFFSET = 4132 # /usr/include/AL/al.h:236
AL_SAMPLE_OFFSET = 4133 # /usr/include/AL/al.h:237
AL_BYTE_OFFSET = 4134 # /usr/include/AL/al.h:238
AL_SOURCE_TYPE = 4135 # /usr/include/AL/al.h:246
AL_STATIC = 4136 # /usr/include/AL/al.h:247
AL_STREAMING = 4137 # /usr/include/AL/al.h:248
AL_UNDETERMINED = 4144 # /usr/include/AL/al.h:249
AL_FORMAT_MONO8 = 4352 # /usr/include/AL/al.h:252
AL_FORMAT_MONO16 = 4353 # /usr/include/AL/al.h:253
AL_FORMAT_STEREO8 = 4354 # /usr/include/AL/al.h:254
AL_FORMAT_STEREO16 = 4355 # /usr/include/AL/al.h:255
AL_REFERENCE_DISTANCE = 4128 # /usr/include/AL/al.h:265
AL_ROLLOFF_FACTOR = 4129 # /usr/include/AL/al.h:273
AL_CONE_OUTER_GAIN = 4130 # /usr/include/AL/al.h:282
AL_MAX_DISTANCE = 4131 # /usr/include/AL/al.h:292
AL_FREQUENCY = 8193 # /usr/include/AL/al.h:300
AL_BITS = 8194 # /usr/include/AL/al.h:301
AL_CHANNELS = 8195 # /usr/include/AL/al.h:302
AL_SIZE = 8196 # /usr/include/AL/al.h:303
AL_UNUSED = 8208 # /usr/include/AL/al.h:310
AL_PENDING = 8209 # /usr/include/AL/al.h:311
AL_PROCESSED = 8210 # /usr/include/AL/al.h:312
AL_NO_ERROR = 0 # /usr/include/AL/al.h:316
AL_INVALID_NAME = 40961 # /usr/include/AL/al.h:321
AL_INVALID_ENUM = 40962 # /usr/include/AL/al.h:326
AL_INVALID_VALUE = 40963 # /usr/include/AL/al.h:331
AL_INVALID_OPERATION = 40964 # /usr/include/AL/al.h:336
AL_OUT_OF_MEMORY = 40965 # /usr/include/AL/al.h:342
AL_VENDOR = 45057 # /usr/include/AL/al.h:346
AL_VERSION = 45058 # /usr/include/AL/al.h:347
AL_RENDERER = 45059 # /usr/include/AL/al.h:348
AL_EXTENSIONS = 45060 # /usr/include/AL/al.h:349
AL_DOPPLER_FACTOR = 49152 # /usr/include/AL/al.h:356
AL_DOPPLER_VELOCITY = 49153 # /usr/include/AL/al.h:361
AL_SPEED_OF_SOUND = 49155 # /usr/include/AL/al.h:366
AL_DISTANCE_MODEL = 53248 # /usr/include/AL/al.h:375
AL_INVERSE_DISTANCE = 53249 # /usr/include/AL/al.h:376
AL_INVERSE_DISTANCE_CLAMPED = 53250 # /usr/include/AL/al.h:377
AL_LINEAR_DISTANCE = 53251 # /usr/include/AL/al.h:378
AL_LINEAR_DISTANCE_CLAMPED = 53252 # /usr/include/AL/al.h:379
AL_EXPONENT_DISTANCE = 53253 # /usr/include/AL/al.h:380
AL_EXPONENT_DISTANCE_CLAMPED = 53254 # /usr/include/AL/al.h:381
# /usr/include/AL/al.h:386
alEnable = _lib.alEnable
alEnable.restype = None
alEnable.argtypes = [ALenum]
# /usr/include/AL/al.h:388
alDisable = _lib.alDisable
alDisable.restype = None
alDisable.argtypes = [ALenum]
# /usr/include/AL/al.h:390
alIsEnabled = _lib.alIsEnabled
alIsEnabled.restype = ALboolean
alIsEnabled.argtypes = [ALenum]
# /usr/include/AL/al.h:396
alGetString = _lib.alGetString
alGetString.restype = POINTER(ALchar)
alGetString.argtypes = [ALenum]
# /usr/include/AL/al.h:398
alGetBooleanv = _lib.alGetBooleanv
alGetBooleanv.restype = None
alGetBooleanv.argtypes = [ALenum, POINTER(ALboolean)]
# /usr/include/AL/al.h:400
alGetIntegerv = _lib.alGetIntegerv
alGetIntegerv.restype = None
alGetIntegerv.argtypes = [ALenum, POINTER(ALint)]
# /usr/include/AL/al.h:402
alGetFloatv = _lib.alGetFloatv
alGetFloatv.restype = None
alGetFloatv.argtypes = [ALenum, POINTER(ALfloat)]
# /usr/include/AL/al.h:404
alGetDoublev = _lib.alGetDoublev
alGetDoublev.restype = None
alGetDoublev.argtypes = [ALenum, POINTER(ALdouble)]
# /usr/include/AL/al.h:406
alGetBoolean = _lib.alGetBoolean
alGetBoolean.restype = ALboolean
alGetBoolean.argtypes = [ALenum]
# /usr/include/AL/al.h:408
alGetInteger = _lib.alGetInteger
alGetInteger.restype = ALint
alGetInteger.argtypes = [ALenum]
# /usr/include/AL/al.h:410
alGetFloat = _lib.alGetFloat
alGetFloat.restype = ALfloat
alGetFloat.argtypes = [ALenum]
# /usr/include/AL/al.h:412
alGetDouble = _lib.alGetDouble
alGetDouble.restype = ALdouble
alGetDouble.argtypes = [ALenum]
# /usr/include/AL/al.h:419
alGetError = _lib.alGetError
alGetError.restype = ALenum
alGetError.argtypes = []
# /usr/include/AL/al.h:427
alIsExtensionPresent = _lib.alIsExtensionPresent
alIsExtensionPresent.restype = ALboolean
alIsExtensionPresent.argtypes = [POINTER(ALchar)]
# /usr/include/AL/al.h:429
alGetProcAddress = _lib.alGetProcAddress
alGetProcAddress.restype = POINTER(c_void)
alGetProcAddress.argtypes = [POINTER(ALchar)]
# /usr/include/AL/al.h:431
alGetEnumValue = _lib.alGetEnumValue
alGetEnumValue.restype = ALenum
alGetEnumValue.argtypes = [POINTER(ALchar)]
# /usr/include/AL/al.h:450
alListenerf = _lib.alListenerf
alListenerf.restype = None
alListenerf.argtypes = [ALenum, ALfloat]
# /usr/include/AL/al.h:452
alListener3f = _lib.alListener3f
alListener3f.restype = None
alListener3f.argtypes = [ALenum, ALfloat, ALfloat, ALfloat]
# /usr/include/AL/al.h:454
alListenerfv = _lib.alListenerfv
alListenerfv.restype = None
alListenerfv.argtypes = [ALenum, POINTER(ALfloat)]
# /usr/include/AL/al.h:456
alListeneri = _lib.alListeneri
alListeneri.restype = None
alListeneri.argtypes = [ALenum, ALint]
# /usr/include/AL/al.h:458
#alListener3i = _lib.alListener3i
#alListener3i.restype = None
#alListener3i.argtypes = [ALenum, ALint, ALint, ALint]
# /usr/include/AL/al.h:460
#alListeneriv = _lib.alListeneriv
#alListeneriv.restype = None
#alListeneriv.argtypes = [ALenum, POINTER(ALint)]
# /usr/include/AL/al.h:465
alGetListenerf = _lib.alGetListenerf
alGetListenerf.restype = None
alGetListenerf.argtypes = [ALenum, POINTER(ALfloat)]
# /usr/include/AL/al.h:467
alGetListener3f = _lib.alGetListener3f
alGetListener3f.restype = None
alGetListener3f.argtypes = [ALenum, POINTER(ALfloat), POINTER(ALfloat), POINTER(ALfloat)]
# /usr/include/AL/al.h:469
alGetListenerfv = _lib.alGetListenerfv
alGetListenerfv.restype = None
alGetListenerfv.argtypes = [ALenum, POINTER(ALfloat)]
# /usr/include/AL/al.h:471
alGetListeneri = _lib.alGetListeneri
alGetListeneri.restype = None
alGetListeneri.argtypes = [ALenum, POINTER(ALint)]
# /usr/include/AL/al.h:473
alGetListener3i = _lib.alGetListener3i
alGetListener3i.restype = None
alGetListener3i.argtypes = [ALenum, POINTER(ALint), POINTER(ALint), POINTER(ALint)]
# /usr/include/AL/al.h:475
alGetListeneriv = _lib.alGetListeneriv
alGetListeneriv.restype = None
alGetListeneriv.argtypes = [ALenum, POINTER(ALint)]
# /usr/include/AL/al.h:512
alGenSources = _lib.alGenSources
alGenSources.restype = None
alGenSources.argtypes = [ALsizei, POINTER(ALuint)]
# /usr/include/AL/al.h:515
alDeleteSources = _lib.alDeleteSources
alDeleteSources.restype = None
alDeleteSources.argtypes = [ALsizei, POINTER(ALuint)]
# /usr/include/AL/al.h:518
alIsSource = _lib.alIsSource
alIsSource.restype = ALboolean
alIsSource.argtypes = [ALuint]
# /usr/include/AL/al.h:523
alSourcef = _lib.alSourcef
alSourcef.restype = None
alSourcef.argtypes = [ALuint, ALenum, ALfloat]
# /usr/include/AL/al.h:525
alSource3f = _lib.alSource3f
alSource3f.restype = None
alSource3f.argtypes = [ALuint, ALenum, ALfloat, ALfloat, ALfloat]
# /usr/include/AL/al.h:527
alSourcefv = _lib.alSourcefv
alSourcefv.restype = None
alSourcefv.argtypes = [ALuint, ALenum, POINTER(ALfloat)]
# /usr/include/AL/al.h:529
alSourcei = _lib.alSourcei
alSourcei.restype = None
alSourcei.argtypes = [ALuint, ALenum, ALint]
# /usr/include/AL/al.h:531
#alSource3i = _lib.alSource3i
#alSource3i.restype = None
#alSource3i.argtypes = [ALuint, ALenum, ALint, ALint, ALint]
# /usr/include/AL/al.h:533
#alSourceiv = _lib.alSourceiv
#alSourceiv.restype = None
#alSourceiv.argtypes = [ALuint, ALenum, POINTER(ALint)]
# /usr/include/AL/al.h:538
alGetSourcef = _lib.alGetSourcef
alGetSourcef.restype = None
alGetSourcef.argtypes = [ALuint, ALenum, POINTER(ALfloat)]
# /usr/include/AL/al.h:540
alGetSource3f = _lib.alGetSource3f
alGetSource3f.restype = None
alGetSource3f.argtypes = [ALuint, ALenum, POINTER(ALfloat), POINTER(ALfloat), POINTER(ALfloat)]
# /usr/include/AL/al.h:542
alGetSourcefv = _lib.alGetSourcefv
alGetSourcefv.restype = None
alGetSourcefv.argtypes = [ALuint, ALenum, POINTER(ALfloat)]
# /usr/include/AL/al.h:544
alGetSourcei = _lib.alGetSourcei
alGetSourcei.restype = None
alGetSourcei.argtypes = [ALuint, ALenum, POINTER(ALint)]
# /usr/include/AL/al.h:546
#alGetSource3i = _lib.alGetSource3i
#alGetSource3i.restype = None
#alGetSource3i.argtypes = [ALuint, ALenum, POINTER(ALint), POINTER(ALint), POINTER(ALint)]
# /usr/include/AL/al.h:548
alGetSourceiv = _lib.alGetSourceiv
alGetSourceiv.restype = None
alGetSourceiv.argtypes = [ALuint, ALenum, POINTER(ALint)]
# /usr/include/AL/al.h:556
alSourcePlayv = _lib.alSourcePlayv
alSourcePlayv.restype = None
alSourcePlayv.argtypes = [ALsizei, POINTER(ALuint)]
# /usr/include/AL/al.h:559
alSourceStopv = _lib.alSourceStopv
alSourceStopv.restype = None
alSourceStopv.argtypes = [ALsizei, POINTER(ALuint)]
# /usr/include/AL/al.h:562
alSourceRewindv = _lib.alSourceRewindv
alSourceRewindv.restype = None
alSourceRewindv.argtypes = [ALsizei, POINTER(ALuint)]
# /usr/include/AL/al.h:565
alSourcePausev = _lib.alSourcePausev
alSourcePausev.restype = None
alSourcePausev.argtypes = [ALsizei, POINTER(ALuint)]
# /usr/include/AL/al.h:572
alSourcePlay = _lib.alSourcePlay
alSourcePlay.restype = None
alSourcePlay.argtypes = [ALuint]
# /usr/include/AL/al.h:575
alSourceStop = _lib.alSourceStop
alSourceStop.restype = None
alSourceStop.argtypes = [ALuint]
# /usr/include/AL/al.h:578
alSourceRewind = _lib.alSourceRewind
alSourceRewind.restype = None
alSourceRewind.argtypes = [ALuint]
# /usr/include/AL/al.h:581
alSourcePause = _lib.alSourcePause
alSourcePause.restype = None
alSourcePause.argtypes = [ALuint]
# /usr/include/AL/al.h:586
alSourceQueueBuffers = _lib.alSourceQueueBuffers
alSourceQueueBuffers.restype = None
alSourceQueueBuffers.argtypes = [ALuint, ALsizei, POINTER(ALuint)]
# /usr/include/AL/al.h:588
alSourceUnqueueBuffers = _lib.alSourceUnqueueBuffers
alSourceUnqueueBuffers.restype = None
alSourceUnqueueBuffers.argtypes = [ALuint, ALsizei, POINTER(ALuint)]
# /usr/include/AL/al.h:606
alGenBuffers = _lib.alGenBuffers
alGenBuffers.restype = None
alGenBuffers.argtypes = [ALsizei, POINTER(ALuint)]
# /usr/include/AL/al.h:609
alDeleteBuffers = _lib.alDeleteBuffers
alDeleteBuffers.restype = None
alDeleteBuffers.argtypes = [ALsizei, POINTER(ALuint)]
# /usr/include/AL/al.h:612
alIsBuffer = _lib.alIsBuffer
alIsBuffer.restype = ALboolean
alIsBuffer.argtypes = [ALuint]
# /usr/include/AL/al.h:615
alBufferData = _lib.alBufferData
alBufferData.restype = None
alBufferData.argtypes = [ALuint, ALenum, POINTER(ALvoid), ALsizei, ALsizei]
# /usr/include/AL/al.h:620
alBufferf = _lib.alBufferf
alBufferf.restype = None
alBufferf.argtypes = [ALuint, ALenum, ALfloat]
# /usr/include/AL/al.h:622
alBuffer3f = _lib.alBuffer3f
alBuffer3f.restype = None
alBuffer3f.argtypes = [ALuint, ALenum, ALfloat, ALfloat, ALfloat]
# /usr/include/AL/al.h:624
alBufferfv = _lib.alBufferfv
alBufferfv.restype = None
alBufferfv.argtypes = [ALuint, ALenum, POINTER(ALfloat)]
# /usr/include/AL/al.h:626
alBufferi = _lib.alBufferi
alBufferi.restype = None
alBufferi.argtypes = [ALuint, ALenum, ALint]
# /usr/include/AL/al.h:628
alBuffer3i = _lib.alBuffer3i
alBuffer3i.restype = None
alBuffer3i.argtypes = [ALuint, ALenum, ALint, ALint, ALint]
# /usr/include/AL/al.h:630
alBufferiv = _lib.alBufferiv
alBufferiv.restype = None
alBufferiv.argtypes = [ALuint, ALenum, POINTER(ALint)]
# /usr/include/AL/al.h:635
alGetBufferf = _lib.alGetBufferf
alGetBufferf.restype = None
alGetBufferf.argtypes = [ALuint, ALenum, POINTER(ALfloat)]
# /usr/include/AL/al.h:637
alGetBuffer3f = _lib.alGetBuffer3f
alGetBuffer3f.restype = None
alGetBuffer3f.argtypes = [ALuint, ALenum, POINTER(ALfloat), POINTER(ALfloat), POINTER(ALfloat)]
# /usr/include/AL/al.h:639
alGetBufferfv = _lib.alGetBufferfv
alGetBufferfv.restype = None
alGetBufferfv.argtypes = [ALuint, ALenum, POINTER(ALfloat)]
# /usr/include/AL/al.h:641
alGetBufferi = _lib.alGetBufferi
alGetBufferi.restype = None
alGetBufferi.argtypes = [ALuint, ALenum, POINTER(ALint)]
# /usr/include/AL/al.h:643
alGetBuffer3i = _lib.alGetBuffer3i
alGetBuffer3i.restype = None
alGetBuffer3i.argtypes = [ALuint, ALenum, POINTER(ALint), POINTER(ALint), POINTER(ALint)]
# /usr/include/AL/al.h:645
alGetBufferiv = _lib.alGetBufferiv
alGetBufferiv.restype = None
alGetBufferiv.argtypes = [ALuint, ALenum, POINTER(ALint)]
# /usr/include/AL/al.h:651
alDopplerFactor = _lib.alDopplerFactor
alDopplerFactor.restype = None
alDopplerFactor.argtypes = [ALfloat]
# /usr/include/AL/al.h:653
alDopplerVelocity = _lib.alDopplerVelocity
alDopplerVelocity.restype = None
alDopplerVelocity.argtypes = [ALfloat]
# /usr/include/AL/al.h:655
alSpeedOfSound = _lib.alSpeedOfSound
alSpeedOfSound.restype = None
alSpeedOfSound.argtypes = [ALfloat]
# /usr/include/AL/al.h:657
alDistanceModel = _lib.alDistanceModel
alDistanceModel.restype = None
alDistanceModel.argtypes = [ALenum]
LPALENABLE = CFUNCTYPE(None, ALenum) # /usr/include/AL/al.h:662
LPALDISABLE = CFUNCTYPE(None, ALenum) # /usr/include/AL/al.h:663
LPALISENABLED = CFUNCTYPE(ALboolean, ALenum) # /usr/include/AL/al.h:664
LPALGETSTRING = CFUNCTYPE(POINTER(ALchar), ALenum) # /usr/include/AL/al.h:665
LPALGETBOOLEANV = CFUNCTYPE(None, ALenum, POINTER(ALboolean)) # /usr/include/AL/al.h:666
LPALGETINTEGERV = CFUNCTYPE(None, ALenum, POINTER(ALint)) # /usr/include/AL/al.h:667
LPALGETFLOATV = CFUNCTYPE(None, ALenum, POINTER(ALfloat)) # /usr/include/AL/al.h:668
LPALGETDOUBLEV = CFUNCTYPE(None, ALenum, POINTER(ALdouble)) # /usr/include/AL/al.h:669
LPALGETBOOLEAN = CFUNCTYPE(ALboolean, ALenum) # /usr/include/AL/al.h:670
LPALGETINTEGER = CFUNCTYPE(ALint, ALenum) # /usr/include/AL/al.h:671
LPALGETFLOAT = CFUNCTYPE(ALfloat, ALenum) # /usr/include/AL/al.h:672
LPALGETDOUBLE = CFUNCTYPE(ALdouble, ALenum) # /usr/include/AL/al.h:673
LPALGETERROR = CFUNCTYPE(ALenum) # /usr/include/AL/al.h:674
LPALISEXTENSIONPRESENT = CFUNCTYPE(ALboolean, POINTER(ALchar)) # /usr/include/AL/al.h:675
LPALGETPROCADDRESS = CFUNCTYPE(POINTER(c_void), POINTER(ALchar)) # /usr/include/AL/al.h:676
LPALGETENUMVALUE = CFUNCTYPE(ALenum, POINTER(ALchar)) # /usr/include/AL/al.h:677
LPALLISTENERF = CFUNCTYPE(None, ALenum, ALfloat) # /usr/include/AL/al.h:678
LPALLISTENER3F = CFUNCTYPE(None, ALenum, ALfloat, ALfloat, ALfloat) # /usr/include/AL/al.h:679
LPALLISTENERFV = CFUNCTYPE(None, ALenum, POINTER(ALfloat)) # /usr/include/AL/al.h:680
LPALLISTENERI = CFUNCTYPE(None, ALenum, ALint) # /usr/include/AL/al.h:681
LPALLISTENER3I = CFUNCTYPE(None, ALenum, ALint, ALint, ALint) # /usr/include/AL/al.h:682
LPALLISTENERIV = CFUNCTYPE(None, ALenum, POINTER(ALint)) # /usr/include/AL/al.h:683
LPALGETLISTENERF = CFUNCTYPE(None, ALenum, POINTER(ALfloat)) # /usr/include/AL/al.h:684
LPALGETLISTENER3F = CFUNCTYPE(None, ALenum, POINTER(ALfloat), POINTER(ALfloat), POINTER(ALfloat)) # /usr/include/AL/al.h:685
LPALGETLISTENERFV = CFUNCTYPE(None, ALenum, POINTER(ALfloat)) # /usr/include/AL/al.h:686
LPALGETLISTENERI = CFUNCTYPE(None, ALenum, POINTER(ALint)) # /usr/include/AL/al.h:687
LPALGETLISTENER3I = CFUNCTYPE(None, ALenum, POINTER(ALint), POINTER(ALint), POINTER(ALint)) # /usr/include/AL/al.h:688
LPALGETLISTENERIV = CFUNCTYPE(None, ALenum, POINTER(ALint)) # /usr/include/AL/al.h:689
LPALGENSOURCES = CFUNCTYPE(None, ALsizei, POINTER(ALuint)) # /usr/include/AL/al.h:690
LPALDELETESOURCES = CFUNCTYPE(None, ALsizei, POINTER(ALuint)) # /usr/include/AL/al.h:691
LPALISSOURCE = CFUNCTYPE(ALboolean, ALuint) # /usr/include/AL/al.h:692
LPALSOURCEF = CFUNCTYPE(None, ALuint, ALenum, ALfloat) # /usr/include/AL/al.h:693
LPALSOURCE3F = CFUNCTYPE(None, ALuint, ALenum, ALfloat, ALfloat, ALfloat) # /usr/include/AL/al.h:694
LPALSOURCEFV = CFUNCTYPE(None, ALuint, ALenum, POINTER(ALfloat)) # /usr/include/AL/al.h:695
LPALSOURCEI = CFUNCTYPE(None, ALuint, ALenum, ALint) # /usr/include/AL/al.h:696
LPALSOURCE3I = CFUNCTYPE(None, ALuint, ALenum, ALint, ALint, ALint) # /usr/include/AL/al.h:697
LPALSOURCEIV = CFUNCTYPE(None, ALuint, ALenum, POINTER(ALint)) # /usr/include/AL/al.h:698
LPALGETSOURCEF = CFUNCTYPE(None, ALuint, ALenum, POINTER(ALfloat)) # /usr/include/AL/al.h:699
LPALGETSOURCE3F = CFUNCTYPE(None, ALuint, ALenum, POINTER(ALfloat), POINTER(ALfloat), POINTER(ALfloat)) # /usr/include/AL/al.h:700
LPALGETSOURCEFV = CFUNCTYPE(None, ALuint, ALenum, POINTER(ALfloat)) # /usr/include/AL/al.h:701
LPALGETSOURCEI = CFUNCTYPE(None, ALuint, ALenum, POINTER(ALint)) # /usr/include/AL/al.h:702
LPALGETSOURCE3I = CFUNCTYPE(None, ALuint, ALenum, POINTER(ALint), POINTER(ALint), POINTER(ALint)) # /usr/include/AL/al.h:703
LPALGETSOURCEIV = CFUNCTYPE(None, ALuint, ALenum, POINTER(ALint)) # /usr/include/AL/al.h:704
LPALSOURCEPLAYV = CFUNCTYPE(None, ALsizei, POINTER(ALuint)) # /usr/include/AL/al.h:705
LPALSOURCESTOPV = CFUNCTYPE(None, ALsizei, POINTER(ALuint)) # /usr/include/AL/al.h:706
LPALSOURCEREWINDV = CFUNCTYPE(None, ALsizei, POINTER(ALuint)) # /usr/include/AL/al.h:707
LPALSOURCEPAUSEV = CFUNCTYPE(None, ALsizei, POINTER(ALuint)) # /usr/include/AL/al.h:708
LPALSOURCEPLAY = CFUNCTYPE(None, ALuint) # /usr/include/AL/al.h:709
LPALSOURCESTOP = CFUNCTYPE(None, ALuint) # /usr/include/AL/al.h:710
LPALSOURCEREWIND = CFUNCTYPE(None, ALuint) # /usr/include/AL/al.h:711
LPALSOURCEPAUSE = CFUNCTYPE(None, ALuint) # /usr/include/AL/al.h:712
LPALSOURCEQUEUEBUFFERS = CFUNCTYPE(None, ALuint, ALsizei, POINTER(ALuint)) # /usr/include/AL/al.h:713
LPALSOURCEUNQUEUEBUFFERS = CFUNCTYPE(None, ALuint, ALsizei, POINTER(ALuint)) # /usr/include/AL/al.h:714
LPALGENBUFFERS = CFUNCTYPE(None, ALsizei, POINTER(ALuint)) # /usr/include/AL/al.h:715
LPALDELETEBUFFERS = CFUNCTYPE(None, ALsizei, POINTER(ALuint)) # /usr/include/AL/al.h:716
LPALISBUFFER = CFUNCTYPE(ALboolean, ALuint) # /usr/include/AL/al.h:717
LPALBUFFERDATA = CFUNCTYPE(None, ALuint, ALenum, POINTER(ALvoid), ALsizei, ALsizei) # /usr/include/AL/al.h:718
LPALBUFFERF = CFUNCTYPE(None, ALuint, ALenum, ALfloat) # /usr/include/AL/al.h:719
LPALBUFFER3F = CFUNCTYPE(None, ALuint, ALenum, ALfloat, ALfloat, ALfloat) # /usr/include/AL/al.h:720
LPALBUFFERFV = CFUNCTYPE(None, ALuint, ALenum, POINTER(ALfloat)) # /usr/include/AL/al.h:721
LPALBUFFERI = CFUNCTYPE(None, ALuint, ALenum, ALint) # /usr/include/AL/al.h:722
LPALBUFFER3I = CFUNCTYPE(None, ALuint, ALenum, ALint, ALint, ALint) # /usr/include/AL/al.h:723
LPALBUFFERIV = CFUNCTYPE(None, ALuint, ALenum, POINTER(ALint)) # /usr/include/AL/al.h:724
LPALGETBUFFERF = CFUNCTYPE(None, ALuint, ALenum, POINTER(ALfloat)) # /usr/include/AL/al.h:725
LPALGETBUFFER3F = CFUNCTYPE(None, ALuint, ALenum, POINTER(ALfloat), POINTER(ALfloat), POINTER(ALfloat)) # /usr/include/AL/al.h:726
LPALGETBUFFERFV = CFUNCTYPE(None, ALuint, ALenum, POINTER(ALfloat)) # /usr/include/AL/al.h:727
LPALGETBUFFERI = CFUNCTYPE(None, ALuint, ALenum, POINTER(ALint)) # /usr/include/AL/al.h:728
LPALGETBUFFER3I = CFUNCTYPE(None, ALuint, ALenum, POINTER(ALint), POINTER(ALint), POINTER(ALint)) # /usr/include/AL/al.h:729
LPALGETBUFFERIV = CFUNCTYPE(None, ALuint, ALenum, POINTER(ALint)) # /usr/include/AL/al.h:730
LPALDOPPLERFACTOR = CFUNCTYPE(None, ALfloat) # /usr/include/AL/al.h:731
LPALDOPPLERVELOCITY = CFUNCTYPE(None, ALfloat) # /usr/include/AL/al.h:732
LPALSPEEDOFSOUND = CFUNCTYPE(None, ALfloat) # /usr/include/AL/al.h:733
LPALDISTANCEMODEL = CFUNCTYPE(None, ALenum) # /usr/include/AL/al.h:734
__all__ = ['AL_API', 'ALAPI', 'AL_INVALID', 'AL_ILLEGAL_ENUM',
'AL_ILLEGAL_COMMAND', 'ALboolean', 'ALchar', 'ALbyte', 'ALubyte', 'ALshort',
'ALushort', 'ALint', 'ALuint', 'ALsizei', 'ALenum', 'ALfloat', 'ALdouble',
'ALvoid', 'AL_NONE', 'AL_FALSE', 'AL_TRUE', 'AL_SOURCE_RELATIVE',
'AL_CONE_INNER_ANGLE', 'AL_CONE_OUTER_ANGLE', 'AL_PITCH', 'AL_POSITION',
'AL_DIRECTION', 'AL_VELOCITY', 'AL_LOOPING', 'AL_BUFFER', 'AL_GAIN',
'AL_MIN_GAIN', 'AL_MAX_GAIN', 'AL_ORIENTATION', 'AL_SOURCE_STATE',
'AL_INITIAL', 'AL_PLAYING', 'AL_PAUSED', 'AL_STOPPED', 'AL_BUFFERS_QUEUED',
'AL_BUFFERS_PROCESSED', 'AL_SEC_OFFSET', 'AL_SAMPLE_OFFSET', 'AL_BYTE_OFFSET',
'AL_SOURCE_TYPE', 'AL_STATIC', 'AL_STREAMING', 'AL_UNDETERMINED',
'AL_FORMAT_MONO8', 'AL_FORMAT_MONO16', 'AL_FORMAT_STEREO8',
'AL_FORMAT_STEREO16', 'AL_REFERENCE_DISTANCE', 'AL_ROLLOFF_FACTOR',
'AL_CONE_OUTER_GAIN', 'AL_MAX_DISTANCE', 'AL_FREQUENCY', 'AL_BITS',
'AL_CHANNELS', 'AL_SIZE', 'AL_UNUSED', 'AL_PENDING', 'AL_PROCESSED',
'AL_NO_ERROR', 'AL_INVALID_NAME', 'AL_INVALID_ENUM', 'AL_INVALID_VALUE',
'AL_INVALID_OPERATION', 'AL_OUT_OF_MEMORY', 'AL_VENDOR', 'AL_VERSION',
'AL_RENDERER', 'AL_EXTENSIONS', 'AL_DOPPLER_FACTOR', 'AL_DOPPLER_VELOCITY',
'AL_SPEED_OF_SOUND', 'AL_DISTANCE_MODEL', 'AL_INVERSE_DISTANCE',
'AL_INVERSE_DISTANCE_CLAMPED', 'AL_LINEAR_DISTANCE',
'AL_LINEAR_DISTANCE_CLAMPED', 'AL_EXPONENT_DISTANCE',
'AL_EXPONENT_DISTANCE_CLAMPED', 'alEnable', 'alDisable', 'alIsEnabled',
'alGetString', 'alGetBooleanv', 'alGetIntegerv', 'alGetFloatv',
'alGetDoublev', 'alGetBoolean', 'alGetInteger', 'alGetFloat', 'alGetDouble',
'alGetError', 'alIsExtensionPresent', 'alGetProcAddress', 'alGetEnumValue',
'alListenerf', 'alListener3f', 'alListenerfv', 'alListeneri', 'alListener3i',
'alListeneriv', 'alGetListenerf', 'alGetListener3f', 'alGetListenerfv',
'alGetListeneri', 'alGetListener3i', 'alGetListeneriv', 'alGenSources',
'alDeleteSources', 'alIsSource', 'alSourcef', 'alSource3f', 'alSourcefv',
'alSourcei', 'alSource3i', 'alSourceiv', 'alGetSourcef', 'alGetSource3f',
'alGetSourcefv', 'alGetSourcei', 'alGetSource3i', 'alGetSourceiv',
'alSourcePlayv', 'alSourceStopv', 'alSourceRewindv', 'alSourcePausev',
'alSourcePlay', 'alSourceStop', 'alSourceRewind', 'alSourcePause',
'alSourceQueueBuffers', 'alSourceUnqueueBuffers', 'alGenBuffers',
'alDeleteBuffers', 'alIsBuffer', 'alBufferData', 'alBufferf', 'alBuffer3f',
'alBufferfv', 'alBufferi', 'alBuffer3i', 'alBufferiv', 'alGetBufferf',
'alGetBuffer3f', 'alGetBufferfv', 'alGetBufferi', 'alGetBuffer3i',
'alGetBufferiv', 'alDopplerFactor', 'alDopplerVelocity', 'alSpeedOfSound',
'alDistanceModel', 'LPALENABLE', 'LPALDISABLE', 'LPALISENABLED',
'LPALGETSTRING', 'LPALGETBOOLEANV', 'LPALGETINTEGERV', 'LPALGETFLOATV',
'LPALGETDOUBLEV', 'LPALGETBOOLEAN', 'LPALGETINTEGER', 'LPALGETFLOAT',
'LPALGETDOUBLE', 'LPALGETERROR', 'LPALISEXTENSIONPRESENT',
'LPALGETPROCADDRESS', 'LPALGETENUMVALUE', 'LPALLISTENERF', 'LPALLISTENER3F',
'LPALLISTENERFV', 'LPALLISTENERI', 'LPALLISTENER3I', 'LPALLISTENERIV',
'LPALGETLISTENERF', 'LPALGETLISTENER3F', 'LPALGETLISTENERFV',
'LPALGETLISTENERI', 'LPALGETLISTENER3I', 'LPALGETLISTENERIV',
'LPALGENSOURCES', 'LPALDELETESOURCES', 'LPALISSOURCE', 'LPALSOURCEF',
'LPALSOURCE3F', 'LPALSOURCEFV', 'LPALSOURCEI', 'LPALSOURCE3I', 'LPALSOURCEIV',
'LPALGETSOURCEF', 'LPALGETSOURCE3F', 'LPALGETSOURCEFV', 'LPALGETSOURCEI',
'LPALGETSOURCE3I', 'LPALGETSOURCEIV', 'LPALSOURCEPLAYV', 'LPALSOURCESTOPV',
'LPALSOURCEREWINDV', 'LPALSOURCEPAUSEV', 'LPALSOURCEPLAY', 'LPALSOURCESTOP',
'LPALSOURCEREWIND', 'LPALSOURCEPAUSE', 'LPALSOURCEQUEUEBUFFERS',
'LPALSOURCEUNQUEUEBUFFERS', 'LPALGENBUFFERS', 'LPALDELETEBUFFERS',
'LPALISBUFFER', 'LPALBUFFERDATA', 'LPALBUFFERF', 'LPALBUFFER3F',
'LPALBUFFERFV', 'LPALBUFFERI', 'LPALBUFFER3I', 'LPALBUFFERIV',
'LPALGETBUFFERF', 'LPALGETBUFFER3F', 'LPALGETBUFFERFV', 'LPALGETBUFFERI',
'LPALGETBUFFER3I', 'LPALGETBUFFERIV', 'LPALDOPPLERFACTOR',
'LPALDOPPLERVELOCITY', 'LPALSPEEDOFSOUND', 'LPALDISTANCEMODEL']
| 27,846 | 41.449695 | 131 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/pyglet/media/drivers/openal/__init__.py
|
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
# $Id$
from __future__ import print_function
from __future__ import absolute_import
import atexit
from .adaptation import OpenALDriver
import pyglet
_debug = pyglet.options['debug_media']
_debug_buffers = pyglet.options.get('debug_media_buffers', False)
_driver = None
def create_audio_driver(device_name=None):
global _driver
_driver = OpenALDriver(device_name)
if _debug:
print('OpenAL', _driver.get_version())
return _driver
def cleanup_audio_driver():
global _driver
if _debug:
print("Cleaning up audio driver")
if _driver:
_driver.delete()
_driver = None
if _debug:
print("Cleaning done")
atexit.register(cleanup_audio_driver)
| 2,432 | 32.791667 | 78 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/pyglet/media/drivers/openal/interface.py
|
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
# $Id$
from __future__ import print_function
from __future__ import absolute_import
from builtins import str
import ctypes
from collections import defaultdict, namedtuple
from . import lib_openal as al
from . import lib_alc as alc
import pyglet
from pyglet.debug import debug_print
from pyglet.media.exceptions import MediaException
_debug_media = debug_print('debug_media')
class OpenALException(MediaException):
def __init__(self, message=None, error_code=None, error_string=None):
self.message = message
self.error_code = error_code
self.error_string = error_string
def __str__(self):
if self.error_code is None:
return 'OpenAL Exception: {}'.format(self.message)
else:
return 'OpenAL Exception [{}: {}]: {}'.format(self.error_code,
self.error_string,
self.message)
class OpenALObject(object):
"""Base class for OpenAL objects."""
@classmethod
def _check_error(cls, message=None):
"""Check whether there is an OpenAL error and raise exception if present."""
error_code = al.alGetError()
if error_code != 0:
error_string = al.alGetString(error_code)
#TODO: Fix return type in generated code?
error_string = ctypes.cast(error_string, ctypes.c_char_p)
raise OpenALException(message=message,
error_code=error_code,
error_string=str(error_string.value))
@classmethod
def _raise_error(cls, message):
"""Raise an exception. Try to check for OpenAL error code too."""
cls._check_error(message)
raise OpenALException(message)
class OpenALDevice(OpenALObject):
"""OpenAL audio device."""
def __init__(self, device_name=None):
self._al_device = alc.alcOpenDevice(device_name)
self.check_context_error('Failed to open device.')
if self._al_device is None:
raise OpenALException('No OpenAL devices.')
def __del__(self):
self.delete()
def delete(self):
if self._al_device is not None:
if alc.alcCloseDevice(self._al_device) == alc.ALC_FALSE:
self._raise_context_error('Failed to close device.')
self._al_device = None
@property
def is_ready(self):
return self._al_device is not None
def create_context(self):
al_context = alc.alcCreateContext(self._al_device, None)
self.check_context_error('Failed to create context')
return OpenALContext(self, al_context)
def get_version(self):
major = alc.ALCint()
minor = alc.ALCint()
alc.alcGetIntegerv(self._al_device, alc.ALC_MAJOR_VERSION,
ctypes.sizeof(major), major)
self.check_context_error('Failed to get version.')
alc.alcGetIntegerv(self._al_device, alc.ALC_MINOR_VERSION,
ctypes.sizeof(minor), minor)
self.check_context_error('Failed to get version.')
return major.value, minor.value
def get_extensions(self):
extensions = alc.alcGetString(self._al_device, alc.ALC_EXTENSIONS)
self.check_context_error('Failed to get extensions.')
if pyglet.compat_platform == 'darwin' or pyglet.compat_platform.startswith('linux'):
return [x.decode('ascii')
for x
in ctypes.cast(extensions, ctypes.c_char_p).value.split(b' ')]
else:
return self._split_nul_strings(extensions)
@staticmethod
def _split_nul_strings(s):
# NUL-separated list of strings, double-NUL-terminated.
nul = False
i = 0
while True:
if s[i] == b'\0':
if nul:
break
else:
nul = True
else:
nul = False
i += 1
s = s[:i - 1]
return filter(None, [ss.strip().decode('ascii') for ss in s.split(b'\0')])
def check_context_error(self, message=None):
"""Check whether there is an OpenAL error and raise exception if present."""
error_code = alc.alcGetError(self._al_device)
if error_code != 0:
error_string = alc.alcGetString(self._al_device, error_code)
#TODO: Fix return type in generated code?
error_string = ctypes.cast(error_string, ctypes.c_char_p)
raise OpenALException(message=message,
error_code=error_code,
error_string=str(error_string.value))
def _raise_context_error(self, message):
"""Raise an exception. Try to check for OpenAL error code too."""
self.check_context_error(message)
raise OpenALException(message)
class OpenALContext(OpenALObject):
def __init__(self, device, al_context):
self.device = device
self._al_context = al_context
self.make_current()
def __del__(self):
self.delete()
def delete(self):
if self._al_context is not None:
# TODO: Check if this context is current
alc.alcMakeContextCurrent(None)
self.device.check_context_error('Failed to make context no longer current.')
alc.alcDestroyContext(self._al_context)
self.device.check_context_error('Failed to destroy context.')
self._al_context = None
def make_current(self):
alc.alcMakeContextCurrent(self._al_context)
self.device.check_context_error('Failed to make context current.')
def create_source(self):
self.make_current()
return OpenALSource(self)
class OpenALSource(OpenALObject):
def __init__(self, context):
self.context = context
self.buffer_pool = OpenALBufferPool(context)
self._al_source = al.ALuint()
al.alGenSources(1, self._al_source)
self._check_error('Failed to create source.')
self._state = None
self._get_state()
self._owned_buffers = {}
def __del__(self):
self.delete()
def delete(self):
if self._al_source is not None:
al.alDeleteSources(1, self._al_source)
self._check_error('Failed to delete source.')
# TODO: delete buffers in use
self.buffer_pool.clear()
self._al_source = None
@property
def is_initial(self):
self._get_state()
return self._state == al.AL_INITIAL
@property
def is_playing(self):
self._get_state()
return self._state == al.AL_PLAYING
@property
def is_paused(self):
self._get_state()
return self._state == al.AL_PAUSED
@property
def is_stopped(self):
self._get_state()
return self._state == al.AL_STOPPED
def _int_source_property(attribute):
return property(lambda self: self._get_int(attribute),
lambda self, value: self._set_int(attribute, value))
def _float_source_property(attribute):
return property(lambda self: self._get_float(attribute),
lambda self, value: self._set_float(attribute, value))
def _3floats_source_property(attribute):
return property(lambda self: self._get_3floats(attribute),
lambda self, value: self._set_3floats(attribute, value))
position = _3floats_source_property(al.AL_POSITION)
velocity = _3floats_source_property(al.AL_VELOCITY)
gain = _float_source_property(al.AL_GAIN)
buffers_queued = _int_source_property(al.AL_BUFFERS_QUEUED)
buffers_processed = _int_source_property(al.AL_BUFFERS_PROCESSED)
min_gain = _float_source_property(al.AL_MIN_GAIN)
max_gain = _float_source_property(al.AL_MAX_GAIN)
reference_distance = _float_source_property(al.AL_REFERENCE_DISTANCE)
rolloff_factor = _float_source_property(al.AL_ROLLOFF_FACTOR)
pitch = _float_source_property(al.AL_PITCH)
max_distance = _float_source_property(al.AL_MAX_DISTANCE)
direction = _3floats_source_property(al.AL_DIRECTION)
cone_inner_angle =_float_source_property(al.AL_CONE_INNER_ANGLE)
cone_outer_angle = _float_source_property(al.AL_CONE_OUTER_ANGLE)
cone_outer_gain = _float_source_property(al.AL_CONE_OUTER_GAIN)
sec_offset = _float_source_property(al.AL_SEC_OFFSET)
sample_offset = _float_source_property(al.AL_SAMPLE_OFFSET)
byte_offset = _float_source_property(al.AL_BYTE_OFFSET)
del _int_source_property
del _float_source_property
del _3floats_source_property
def play(self):
al.alSourcePlay(self._al_source)
self._check_error('Failed to play source.')
def pause(self):
al.alSourcePause(self._al_source)
self._check_error('Failed to pause source.')
def stop(self):
al.alSourceStop(self._al_source)
self._check_error('Failed to stop source.')
def get_buffer(self):
return self.buffer_pool.get_buffer()
def queue_buffer(self, buf):
assert buf.is_valid
al.alSourceQueueBuffers(self._al_source, 1, ctypes.byref(buf.al_buffer))
self._check_error('Failed to queue buffer.')
self._add_buffer(buf)
def unqueue_buffers(self):
processed = self.buffers_processed
assert _debug_media("Processed buffer count: {}".format(processed))
if processed > 0:
buffers = (al.ALuint * processed)()
al.alSourceUnqueueBuffers(self._al_source, len(buffers), buffers)
self._check_error('Failed to unqueue buffers from source.')
for buf in buffers:
self.buffer_pool.unqueue_buffer(self._pop_buffer(buf))
return processed
def _get_state(self):
if self._al_source is not None:
self._state = self._get_int(al.AL_SOURCE_STATE)
def _get_int(self, key):
assert self._al_source is not None
al_int = al.ALint()
al.alGetSourcei(self._al_source, key, al_int)
self._check_error('Failed to get value')
return al_int.value
def _set_int(self, key, value):
assert self._al_source is not None
al.alSourcei(self._al_source, key, int(value))
self._check_error('Failed to set value.')
def _get_float(self, key):
assert self._al_source is not None
al_float = al.ALfloat()
al.alGetSourcef(self._al_source, key, al_float)
self._check_error('Failed to get value')
return al_float.value
def _set_float(self, key, value):
assert self._al_source is not None
al.alSourcef(self._al_source, key, float(value))
self._check_error('Failed to set value.')
def _get_3floats(self, key):
assert self._al_source is not None
x = al.ALfloat()
y = al.ALfloat()
z = al.ALfloat()
al.alGetSource3f(self._al_source, key, x, y, z)
self._check_error('Failed to get value')
return x.value, y.value, z.value
def _set_3floats(self, key, values):
assert self._al_source is not None
x, y, z = map(float, values)
al.alSource3f(self._al_source, key, x, y, z)
self._check_error('Failed to set value.')
def _add_buffer(self, buf):
self._owned_buffers[buf.name] = buf
def _pop_buffer(self, al_buffer):
buf = self._owned_buffers.pop(al_buffer, None)
assert buf is not None
return buf
OpenALOrientation = namedtuple("OpenALOrientation", ['at', 'up'])
class OpenALListener(OpenALObject):
def _float_source_property(attribute):
return property(lambda self: self._get_float(attribute),
lambda self, value: self._set_float(attribute, value))
def _3floats_source_property(attribute):
return property(lambda self: self._get_3floats(attribute),
lambda self, value: self._set_3floats(attribute, value))
position = _3floats_source_property(al.AL_POSITION)
velocity = _3floats_source_property(al.AL_VELOCITY)
gain = _float_source_property(al.AL_GAIN)
@property
def orientation(self):
values = self._get_float_vector(al.AL_ORIENTATION, 6)
return OpenALOrientation(values[0:3], values[3:6])
@orientation.setter
def orientation(self, values):
if len(values) == 2:
actual_values = values[0] + values[1]
elif len(values) == 6:
actual_values = values
else:
actual_values = []
if len(actual_values) != 6:
raise ValueError("Need 2 tuples of 3 or 1 tuple of 6.")
self._set_float_vector(al.AL_ORIENTATION, actual_values)
def _get_float(self, key):
al_float = al.ALfloat()
al.alGetListenerf(key, al_float)
self._check_error('Failed to get value')
return al_float.value
def _set_float(self, key, value):
al.alListenerf(key, float(value))
self._check_error('Failed to set value.')
def _get_3floats(self, key):
x = al.ALfloat()
y = al.ALfloat()
z = al.ALfloat()
al.alGetListener3f(key, x, y, z)
self._check_error('Failed to get value')
return x.value, y.value, z.value
def _set_3floats(self, key, values):
x, y, z = map(float, values)
al.alListener3f(key, x, y, z)
self._check_error('Failed to set value.')
def _get_float_vector(self, key, count):
al_float_vector = (al.ALfloat * count)()
al.alGetListenerfv(key, al_float_vector)
self._check_error('Failed to get value')
return [x for x in al_float_vector]
def _set_float_vector(self, key, values):
al_float_vector = (al.ALfloat * len(values))(*values)
al.alListenerfv(key, al_float_vector)
self._check_error('Failed to set value.')
class OpenALBuffer(OpenALObject):
_format_map = {
(1, 8): al.AL_FORMAT_MONO8,
(1, 16): al.AL_FORMAT_MONO16,
(2, 8): al.AL_FORMAT_STEREO8,
(2, 16): al.AL_FORMAT_STEREO16,
}
def __init__(self, al_buffer, context):
self._al_buffer = al_buffer
self.context = context
assert self.is_valid
def __del__(self):
self.delete()
@property
def is_valid(self):
self._check_error('Before validate buffer.')
if self._al_buffer is None:
return False
valid = bool(al.alIsBuffer(self._al_buffer))
if not valid:
# Clear possible error due to invalid buffer
al.alGetError()
return valid
@property
def al_buffer(self):
assert self.is_valid
return self._al_buffer
@property
def name(self):
assert self.is_valid
return self._al_buffer.value
def delete(self):
if self.is_valid:
al.alDeleteBuffers(1, ctypes.byref(self._al_buffer))
self._check_error('Error deleting buffer.')
self._al_buffer = None
def data(self, audio_data, audio_format, length=None):
assert self.is_valid
length = length or audio_data.length
al_format = self._format_map[(audio_format.channels, audio_format.sample_size)]
al.alBufferData(self._al_buffer,
al_format,
audio_data.data,
length,
audio_format.sample_rate)
self._check_error('Failed to add data to buffer.')
class OpenALBufferPool(OpenALObject):
"""At least Mac OS X doesn't free buffers when a source is deleted; it just
detaches them from the source. So keep our own recycled queue.
"""
def __init__(self, context):
self.context = context
self._buffers = [] # list of free buffer names
def __del__(self):
self.clear()
def __len__(self):
return len(self._buffers)
def clear(self):
while self._buffers:
self._buffers.pop().delete()
def get_buffer(self):
"""Convenience for returning one buffer name"""
return self.get_buffers(1)[0]
def get_buffers(self, number):
"""Returns an array containing `number` buffer names. The returned list must
not be modified in any way, and may get changed by subsequent calls to
get_buffers.
"""
buffers = []
while number > 0:
if self._buffers:
b = self._buffers.pop()
else:
b = self.create_buffer()
if b.is_valid:
# Protect against implementations that DO free buffers
# when they delete a source - carry on.
buffers.append(b)
number -= 1
return buffers
def unqueue_buffer(self, buf):
"""A buffer has finished playing, free it."""
if buf.is_valid:
self._buffers.append(buf)
def create_buffer(self):
"""Create a new buffer."""
al_buffer = al.ALuint()
al.alGenBuffers(1, al_buffer)
self._check_error('Error allocating buffer.')
return OpenALBuffer(al_buffer, self.context)
| 18,981 | 34.480374 | 92 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/pyglet/media/drivers/openal/adaptation.py
|
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
from __future__ import print_function
from __future__ import absolute_import
import threading
import time
from . import interface
from pyglet.app import WeakSet
from pyglet.debug import debug_print
from pyglet.media.drivers.base import AbstractAudioDriver, AbstractAudioPlayer
from pyglet.media.events import MediaEvent
from pyglet.media.listener import AbstractListener
from pyglet.media.threads import PlayerWorker
_debug_media = debug_print('debug_media')
class OpenALDriver(AbstractAudioDriver):
def __init__(self, device_name=None):
super(OpenALDriver, self).__init__()
# TODO devices must be enumerated on Windows, otherwise 1.0 context is
# returned.
self.device = interface.OpenALDevice(device_name)
self.context = self.device.create_context()
self.context.make_current()
self.lock = threading.Lock()
self._listener = OpenALListener(self)
self._players = WeakSet()
# Start worker thread
self.worker = PlayerWorker()
self.worker.start()
def create_audio_player(self, source_group, player):
assert self.device is not None, "Device was closed"
if self.have_version(1, 1):
player = OpenALAudioPlayer11(self, source_group, player)
else:
player = OpenALAudioPlayer10(self, source_group, player)
self._players.add(player)
return player
def delete(self):
self.worker.stop()
for player in self._players:
player.delete()
with self.lock:
if self.context is not None:
self.context.delete()
self.context = None
if self.device is not None:
self.device.delete()
self.device = None
def have_version(self, major, minor):
return (major, minor) <= self.get_version()
def get_version(self):
assert self.device is not None, "Device was closed"
return self.device.get_version()
def get_extensions(self):
assert self.device is not None, "Device was closed"
return self.device.get_extensions()
def have_extension(self, extension):
return extension in self.get_extensions()
def get_listener(self):
return self._listener
def __enter__(self):
self.lock.acquire()
def __exit__(self, exc_type, exc_value, traceback):
self.lock.release()
class OpenALListener(AbstractListener):
def __init__(self, driver):
self._driver = driver
self._al_listener = interface.OpenALListener()
def _set_volume(self, volume):
with self._driver:
self._al_listener.gain = volume
self._volume = volume
def _set_position(self, position):
with self._driver:
self._al_listener.position = position
self._position = position
def _set_forward_orientation(self, orientation):
with self._driver:
self._al_listener = orientation + self._up_orientation
self._forward_orientation = orientation
def _set_up_orientation(self, orientation):
with self._driver:
self._al_listener.orientation = self._forward_orientation + orientation
self._up_orientation = orientation
class OpenALAudioPlayer11(AbstractAudioPlayer):
#: Minimum size of an OpenAL buffer worth bothering with, in bytes
min_buffer_size = 512
#: Aggregate (desired) buffer size, in seconds
_ideal_buffer_size = 1.
def __init__(self, driver, source_group, player):
super(OpenALAudioPlayer11, self).__init__(source_group, player)
self.driver = driver
self.source = driver.context.create_source()
# Lock policy: lock all instance vars (except constants). (AL calls
# are locked on context).
self._lock = threading.RLock()
# Cursor positions, like DSound and Pulse drivers, refer to a
# hypothetical infinite-length buffer. Cursor units are in bytes.
# Cursor position of current (head) AL buffer
self._buffer_cursor = 0
# Estimated playback cursor position (last seen)
self._play_cursor = 0
# Cursor position of end of queued AL buffer.
self._write_cursor = 0
# List of currently queued buffer sizes (in bytes)
self._buffer_sizes = []
# List of currently queued buffer timestamps
self._buffer_timestamps = []
# Timestamp at end of last written buffer (timestamp to return in case
# of underrun)
self._underrun_timestamp = None
# List of (cursor, MediaEvent)
self._events = []
# Desired play state (True even if stopped due to underrun)
self._playing = False
# When clearing, the play cursor can be incorrect
self._clearing = False
# Up to one audio data may be buffered if too much data was received
# from the source that could not be written immediately into the
# buffer. See refill().
self._audiodata_buffer = None
self.refill(self.ideal_buffer_size)
def __del__(self):
try:
self.delete()
except:
pass
def delete(self):
assert _debug_media('OpenALAudioPlayer.delete()')
# Do not lock self._lock before calling this, or you risk a deadlock with worker
self.driver.worker.remove(self)
with self._lock:
if not self.source:
return
assert self.driver is not None
with self.driver:
self.source.delete()
self.source = None
@property
def ideal_buffer_size(self):
return int(self._ideal_buffer_size * self.source_group.audio_format.bytes_per_second)
def play(self):
assert _debug_media('OpenALAudioPlayer.play()')
with self._lock:
assert self.driver is not None
assert self.source is not None
with self.driver:
if not self.source.is_playing:
self.source.play()
self._playing = True
self._clearing = False
self.driver.worker.add(self)
def stop(self):
assert _debug_media('OpenALAudioPlayer.stop()')
with self._lock:
assert self.driver is not None
assert self.source is not None
self._pause_timestamp = self.get_time()
with self.driver:
self.source.pause()
self._playing = False
def clear(self):
assert _debug_media('OpenALAudioPlayer.clear()')
with self._lock:
assert self.driver is not None
assert self.source is not None
with self.driver:
self.source.stop()
self.source.byte_offset = 0
self._playing = False
self._clearing = True
self._audiodata_buffer = None
del self._events[:]
self._update_play_cursor()
self.refill(self.ideal_buffer_size)
def _update_play_cursor(self):
with self._lock:
assert self.driver is not None
assert self.source is not None
self._handle_processed_buffers()
# Update play cursor using buffer cursor + estimate into current
# buffer
with self.driver:
if self._clearing:
self._play_cursor = self._buffer_cursor
else:
self._play_cursor = self._buffer_cursor + self.source.byte_offset
assert self._check_cursors()
self._dispatch_events()
def _handle_processed_buffers(self):
with self._lock:
with self.driver:
processed = self.source.unqueue_buffers()
if processed > 0:
if (len(self._buffer_timestamps) == processed
and self._buffer_timestamps[-1] is not None):
assert _debug_media('OpenALAudioPlayer: Underrun')
# Underrun, take note of timestamp.
# We check that the timestamp is not None, because otherwise
# our source could have been cleared.
self._underrun_timestamp = \
self._buffer_timestamps[-1] + \
self._buffer_sizes[-1] / \
float(self.source_group.audio_format.bytes_per_second)
self._update_buffer_cursor(processed)
return processed
def _update_buffer_cursor(self, processed):
self._buffer_cursor += sum(self._buffer_sizes[:processed])
del self._buffer_sizes[:processed]
del self._buffer_timestamps[:processed]
def _dispatch_events(self):
with self._lock:
while self._events and self._events[0][0] <= self._play_cursor:
_, event = self._events.pop(0)
event._sync_dispatch_to_player(self.player)
def get_write_size(self):
with self._lock:
self._update_play_cursor()
buffer_size = int(self._write_cursor - self._play_cursor)
# Only write when current buffer size is smaller than ideal
write_size = max(self.ideal_buffer_size - buffer_size, 0)
assert _debug_media("Write size {} bytes".format(write_size))
return write_size
def refill(self, write_size):
assert _debug_media('refill', write_size)
with self._lock:
while write_size > self.min_buffer_size:
audio_data = self._get_audiodata()
if audio_data is None:
break
length = min(write_size, audio_data.length)
assert _debug_media('Writing {} bytes'.format(length))
self._queue_audio_data(audio_data, length)
write_size -= length
# Check for underrun stopping playback
with self.driver:
if self._playing and not self.source.is_playing:
assert _debug_media('underrun')
self.source.play()
def _get_audiodata(self):
if self._audiodata_buffer is None or self._audiodata_buffer.length == 0:
self._get_new_audiodata()
return self._audiodata_buffer
def _get_new_audiodata(self):
assert _debug_media('Getting new audio data buffer.')
self._audiodata_buffer= self.source_group.get_audio_data(self.ideal_buffer_size)
if self._audiodata_buffer is not None:
assert _debug_media('New audio data available: {} bytes'.format(self._audiodata_buffer.length))
self._queue_events(self._audiodata_buffer)
else:
assert _debug_media('No audio data left')
if self._has_underrun():
assert _debug_media('Underrun')
MediaEvent(0, 'on_eos')._sync_dispatch_to_player(self.player)
MediaEvent(0, 'on_source_group_eos')._sync_dispatch_to_player(self.player)
def _queue_audio_data(self, audio_data, length):
with self.driver:
buf = self.source.get_buffer()
buf.data(audio_data, self.source_group.audio_format, length)
self.source.queue_buffer(buf)
self._update_write_cursor(audio_data, length)
def _update_write_cursor(self, audio_data, length):
self._write_cursor += length
self._buffer_sizes.append(length)
self._buffer_timestamps.append(audio_data.timestamp)
audio_data.consume(length, self.source_group.audio_format)
assert self._check_cursors()
def _queue_events(self, audio_data):
for event in audio_data.events:
cursor = self._write_cursor + event.timestamp * \
self.source_group.audio_format.bytes_per_second
self._events.append((cursor, event))
def _has_underrun(self):
with self.driver:
return self.source.buffers_queued == 0
def get_time(self):
with self._lock:
# Update first, might remove buffers
self._update_play_cursor()
if not self._buffer_timestamps:
timestamp = self._underrun_timestamp
assert _debug_media('OpenALAudioPlayer: Return underrun timestamp')
else:
timestamp = self._buffer_timestamps[0]
assert _debug_media('OpenALAudioPlayer: Buffer timestamp: {}'.format(timestamp))
if timestamp is not None:
timestamp += ((self._play_cursor - self._buffer_cursor) /
float(self.source_group.audio_format.bytes_per_second))
assert _debug_media('OpenALAudioPlayer: get_time = {}'.format(timestamp))
return timestamp
def _check_cursors(self):
assert self._play_cursor >= 0
assert self._buffer_cursor >= 0
assert self._write_cursor >= 0
assert self._buffer_cursor <= self._play_cursor
assert self._play_cursor <= self._write_cursor
assert _debug_media('Buffer[{}], Play[{}], Write[{}]'.format(self._buffer_cursor,
self._play_cursor,
self._write_cursor))
return True # Return true so it can be called in an assert (and optimized out)
def set_volume(self, volume):
with self.driver:
self.source.gain = volume
def set_position(self, position):
with self.driver:
self.source.position = position
def set_min_distance(self, min_distance):
with self.driver:
self.source.reference_distance = min_distance
def set_max_distance(self, max_distance):
with self.driver:
self.source.max_distance = max_distance
def set_pitch(self, pitch):
with self.driver:
self.source.pitch = pitch
def set_cone_orientation(self, cone_orientation):
with self.driver:
self.source.direction = cone_orientation
def set_cone_inner_angle(self, cone_inner_angle):
with self.driver:
self.source.cone_inner_angle = cone_inner_angle
def set_cone_outer_angle(self, cone_outer_angle):
with self.driver:
self.source.cone_outer_angle = cone_outer_angle
def set_cone_outer_gain(self, cone_outer_gain):
with self.driver:
self.source.cone_outer_gain = cone_outer_gain
class OpenALAudioPlayer10(OpenALAudioPlayer11):
"""Player compatible with OpenAL version 1.0. This version needs to interpolate
timestamps."""
def __init__(self, driver, source_group, player):
super(OpenALAudioPlayer10, self).__init__(driver, source_group, player)
# OpenAL 1.0 timestamp interpolation: system time of current buffer
# playback (best guess)
self._buffer_system_time = time.time()
def play(self):
with self._lock:
super(OpenALAudioPlayer10, self).play()
self._buffer_system_time = time.time()
def _update_play_cursor(self):
with self._lock:
assert self.driver is not None
assert self.source is not None
self._handle_processed_buffers()
# Interpolate system time past buffer timestamp
self._play_cursor = \
self._buffer_cursor + int(
(time.time() - self._buffer_system_time) * \
self.source_group.audio_format.bytes_per_second)
assert self._check_cursors()
assert _debug_media('Play cursor at {} bytes'.format(self._play_cursor))
self._dispatch_events()
def _handle_processed_buffers(self):
with self._lock:
processed = super(OpenALAudioPlayer10, self)._handle_processed_buffers()
if processed > 0:
self._buffer_system_time = time.time()
| 17,748 | 34.498 | 107 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/pyglet/media/drivers/directsound/exceptions.py
|
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
from pyglet.media.exceptions import MediaException
class DirectSoundException(MediaException):
pass
class DirectSoundNativeError(DirectSoundException):
def __init__(self, hresult):
self.hresult = hresult
def __repr__(self):
return "{}: Error {}".format(self.__class__.__name__, self.hresult)
| 2,047 | 39.156863 | 78 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/pyglet/media/drivers/directsound/lib_dsound.py
|
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
import ctypes
from pyglet import com
lib = ctypes.oledll.dsound
DWORD = ctypes.c_uint32
LPDWORD = ctypes.POINTER(DWORD)
LONG = ctypes.c_long
LPLONG = ctypes.POINTER(LONG)
WORD = ctypes.c_uint16
HWND = DWORD
LPUNKNOWN = ctypes.c_void_p
D3DVALUE = ctypes.c_float
PD3DVALUE = ctypes.POINTER(D3DVALUE)
class D3DVECTOR(ctypes.Structure):
_fields_ = [
('x', ctypes.c_float),
('y', ctypes.c_float),
('z', ctypes.c_float),
]
PD3DVECTOR = ctypes.POINTER(D3DVECTOR)
class WAVEFORMATEX(ctypes.Structure):
_fields_ = [
('wFormatTag', WORD),
('nChannels', WORD),
('nSamplesPerSec', DWORD),
('nAvgBytesPerSec', DWORD),
('nBlockAlign', WORD),
('wBitsPerSample', WORD),
('cbSize', WORD),
]
def __repr__(self):
return 'WAVEFORMATEX(wFormatTag={}, nChannels={}, nSamplesPerSec={}, nAvgBytesPersec={}' \
', nBlockAlign={}, wBitsPerSample={}, cbSize={})'.format(
self.wFormatTag, self.nChannels, self.nSamplesPerSec,
self.nAvgBytesPerSec, self.nBlockAlign, self.wBitsPerSample,
self.cbSize)
LPWAVEFORMATEX = ctypes.POINTER(WAVEFORMATEX)
WAVE_FORMAT_PCM = 1
class DSCAPS(ctypes.Structure):
_fields_ = [
('dwSize', DWORD),
('dwFlags', DWORD),
('dwMinSecondarySampleRate', DWORD),
('dwMaxSecondarySampleRate', DWORD),
('dwPrimaryBuffers', DWORD),
('dwMaxHwMixingAllBuffers', DWORD),
('dwMaxHwMixingStaticBuffers', DWORD),
('dwMaxHwMixingStreamingBuffers', DWORD),
('dwFreeHwMixingAllBuffers', DWORD),
('dwFreeHwMixingStaticBuffers', DWORD),
('dwFreeHwMixingStreamingBuffers', DWORD),
('dwMaxHw3DAllBuffers', DWORD),
('dwMaxHw3DStaticBuffers', DWORD),
('dwMaxHw3DStreamingBuffers', DWORD),
('dwFreeHw3DAllBuffers', DWORD),
('dwFreeHw3DStaticBuffers', DWORD),
('dwFreeHw3DStreamingBuffers', DWORD),
('dwTotalHwMemBytes', DWORD),
('dwFreeHwMemBytes', DWORD),
('dwMaxContigFreeHwMemBytes', DWORD),
('dwUnlockTransferRateHwBuffers', DWORD),
('dwPlayCpuOverheadSwBuffers', DWORD),
('dwReserved1', DWORD),
('dwReserved2', DWORD)
]
LPDSCAPS = ctypes.POINTER(DSCAPS)
class DSBCAPS(ctypes.Structure):
_fields_ = [
('dwSize', DWORD),
('dwFlags', DWORD),
('dwBufferBytes', DWORD),
('dwUnlockTransferRate', DWORD),
('dwPlayCpuOverhead', DWORD),
]
LPDSBCAPS = ctypes.POINTER(DSBCAPS)
class DSBUFFERDESC(ctypes.Structure):
_fields_ = [
('dwSize', DWORD),
('dwFlags', DWORD),
('dwBufferBytes', DWORD),
('dwReserved', DWORD),
('lpwfxFormat', LPWAVEFORMATEX),
]
def __repr__(self):
return 'DSBUFFERDESC(dwSize={}, dwFlags={}, dwBufferBytes={}, lpwfxFormat={})'.format(
self.dwSize, self.dwFlags, self.dwBufferBytes,
self.lpwfxFormat.contents if self.lpwfxFormat else None)
LPDSBUFFERDESC = ctypes.POINTER(DSBUFFERDESC)
class DS3DBUFFER(ctypes.Structure):
_fields_ = [
('dwSize', DWORD),
('vPosition', D3DVECTOR),
('vVelocity', D3DVECTOR),
('dwInsideConeAngle', DWORD),
('dwOutsideConeAngle', DWORD),
('vConeOrientation', D3DVECTOR),
('lConeOutsideVolume', LONG),
('flMinDistance', D3DVALUE),
('flMaxDistance', D3DVALUE),
('dwMode', DWORD),
]
LPDS3DBUFFER = ctypes.POINTER(DS3DBUFFER)
class DS3DLISTENER(ctypes.Structure):
_fields_ = [
('dwSize', DWORD),
('vPosition', D3DVECTOR),
('vVelocity', D3DVECTOR),
('vOrientFront', D3DVECTOR),
('vOrientTop', D3DVECTOR),
('flDistanceFactor', D3DVALUE),
('flRolloffFactor', D3DVALUE),
('flDopplerFactor', D3DVALUE),
]
LPDS3DLISTENER = ctypes.POINTER(DS3DLISTENER)
class IDirectSoundBuffer(com.IUnknown):
_methods_ = [
('GetCaps',
com.STDMETHOD(LPDSBCAPS)),
('GetCurrentPosition',
com.STDMETHOD(LPDWORD, LPDWORD)),
('GetFormat',
com.STDMETHOD(LPWAVEFORMATEX, DWORD, LPDWORD)),
('GetVolume',
com.STDMETHOD(LPLONG)),
('GetPan',
com.STDMETHOD(LPLONG)),
('GetFrequency',
com.STDMETHOD(LPDWORD)),
('GetStatus',
com.STDMETHOD(LPDWORD)),
('Initialize',
com.STDMETHOD(ctypes.c_void_p, LPDSBUFFERDESC)),
('Lock',
com.STDMETHOD(DWORD, DWORD,
ctypes.POINTER(ctypes.c_void_p), LPDWORD,
ctypes.POINTER(ctypes.c_void_p), LPDWORD,
DWORD)),
('Play',
com.STDMETHOD(DWORD, DWORD, DWORD)),
('SetCurrentPosition',
com.STDMETHOD(DWORD)),
('SetFormat',
com.STDMETHOD(LPWAVEFORMATEX)),
('SetVolume',
com.STDMETHOD(LONG)),
('SetPan',
com.STDMETHOD(LONG)),
('SetFrequency',
com.STDMETHOD(DWORD)),
('Stop',
com.STDMETHOD()),
('Unlock',
com.STDMETHOD(ctypes.c_void_p, DWORD, ctypes.c_void_p, DWORD)),
('Restore',
com.STDMETHOD()),
]
IID_IDirectSound3DListener = com.GUID(
0x279AFA84, 0x4981, 0x11CE, 0xA5, 0x21, 0x00, 0x20, 0xAF, 0x0B, 0xE5, 0x60)
class IDirectSound3DListener(com.IUnknown):
_methods_ = [
('GetAllParameters',
com.STDMETHOD(LPDS3DLISTENER)),
('GetDistanceFactor',
com.STDMETHOD(PD3DVALUE)),
('GetDopplerFactor',
com.STDMETHOD(PD3DVALUE)),
('GetOrientation',
com.STDMETHOD(PD3DVECTOR, PD3DVECTOR)),
('GetPosition',
com.STDMETHOD(PD3DVECTOR)),
('GetRolloffFactor',
com.STDMETHOD(PD3DVALUE)),
('GetVelocity',
com.STDMETHOD(PD3DVECTOR)),
('SetAllParameters',
com.STDMETHOD(LPDS3DLISTENER)),
('SetDistanceFactor',
com.STDMETHOD(D3DVALUE, DWORD)),
('SetDopplerFactor',
com.STDMETHOD(D3DVALUE, DWORD)),
('SetOrientation',
com.STDMETHOD(D3DVALUE, D3DVALUE, D3DVALUE,
D3DVALUE, D3DVALUE, D3DVALUE, DWORD)),
('SetPosition',
com.STDMETHOD(D3DVALUE, D3DVALUE, D3DVALUE, DWORD)),
('SetRolloffFactor',
com.STDMETHOD(D3DVALUE, DWORD)),
('SetVelocity',
com.STDMETHOD(D3DVALUE, D3DVALUE, D3DVALUE, DWORD)),
('CommitDeferredSettings',
com.STDMETHOD()),
]
IID_IDirectSound3DBuffer = com.GUID(
0x279AFA86, 0x4981, 0x11CE, 0xA5, 0x21, 0x00, 0x20, 0xAF, 0x0B, 0xE5, 0x60)
class IDirectSound3DBuffer(com.IUnknown):
_methods_ = [
('GetAllParameters',
com.STDMETHOD(LPDS3DBUFFER)),
('GetConeAngles',
com.STDMETHOD(LPDWORD, LPDWORD)),
('GetConeOrientation',
com.STDMETHOD(PD3DVECTOR)),
('GetConeOutsideVolume',
com.STDMETHOD(LPLONG)),
('GetMaxDistance',
com.STDMETHOD(PD3DVALUE)),
('GetMinDistance',
com.STDMETHOD(PD3DVALUE)),
('GetMode',
com.STDMETHOD(LPDWORD)),
('GetPosition',
com.STDMETHOD(PD3DVECTOR)),
('GetVelocity',
com.STDMETHOD(PD3DVECTOR)),
('SetAllParameters',
com.STDMETHOD(LPDS3DBUFFER, DWORD)),
('SetConeAngles',
com.STDMETHOD(DWORD, DWORD, DWORD)),
('SetConeOrientation',
com.STDMETHOD(D3DVALUE, D3DVALUE, D3DVALUE, DWORD)),
('SetConeOutsideVolume',
com.STDMETHOD(LONG, DWORD)),
('SetMaxDistance',
com.STDMETHOD(D3DVALUE, DWORD)),
('SetMinDistance',
com.STDMETHOD(D3DVALUE, DWORD)),
('SetMode',
com.STDMETHOD(DWORD, DWORD)),
('SetPosition',
com.STDMETHOD(D3DVALUE, D3DVALUE, D3DVALUE, DWORD)),
('SetVelocity',
com.STDMETHOD(D3DVALUE, D3DVALUE, D3DVALUE, DWORD)),
]
class IDirectSound(com.IUnknown):
_methods_ = [
('CreateSoundBuffer',
com.STDMETHOD(LPDSBUFFERDESC,
ctypes.POINTER(IDirectSoundBuffer),
LPUNKNOWN)),
('GetCaps',
com.STDMETHOD(LPDSCAPS)),
('DuplicateSoundBuffer',
com.STDMETHOD(IDirectSoundBuffer,
ctypes.POINTER(IDirectSoundBuffer))),
('SetCooperativeLevel',
com.STDMETHOD(HWND, DWORD)),
('Compact',
com.STDMETHOD()),
('GetSpeakerConfig',
com.STDMETHOD(LPDWORD)),
('SetSpeakerConfig',
com.STDMETHOD(DWORD)),
('Initialize',
com.STDMETHOD(com.LPGUID)),
]
_type_ = com.COMInterface
DirectSoundCreate = lib.DirectSoundCreate
DirectSoundCreate.argtypes = \
[com.LPGUID, ctypes.POINTER(IDirectSound), ctypes.c_void_p]
DSCAPS_PRIMARYMONO = 0x00000001
DSCAPS_PRIMARYSTEREO = 0x00000002
DSCAPS_PRIMARY8BIT = 0x00000004
DSCAPS_PRIMARY16BIT = 0x00000008
DSCAPS_CONTINUOUSRATE = 0x00000010
DSCAPS_EMULDRIVER = 0x00000020
DSCAPS_CERTIFIED = 0x00000040
DSCAPS_SECONDARYMONO = 0x00000100
DSCAPS_SECONDARYSTEREO = 0x00000200
DSCAPS_SECONDARY8BIT = 0x00000400
DSCAPS_SECONDARY16BIT = 0x00000800
DSSCL_NORMAL = 0x00000001
DSSCL_PRIORITY = 0x00000002
DSSCL_EXCLUSIVE = 0x00000003
DSSCL_WRITEPRIMARY = 0x00000004
DSSPEAKER_DIRECTOUT = 0x00000000
DSSPEAKER_HEADPHONE = 0x00000001
DSSPEAKER_MONO = 0x00000002
DSSPEAKER_QUAD = 0x00000003
DSSPEAKER_STEREO = 0x00000004
DSSPEAKER_SURROUND = 0x00000005
DSSPEAKER_5POINT1 = 0x00000006
DSSPEAKER_7POINT1 = 0x00000007
DSSPEAKER_GEOMETRY_MIN = 0x00000005 # 5 degrees
DSSPEAKER_GEOMETRY_NARROW = 0x0000000A # 10 degrees
DSSPEAKER_GEOMETRY_WIDE = 0x00000014 # 20 degrees
DSSPEAKER_GEOMETRY_MAX = 0x000000B4 # 180 degrees
DSBCAPS_PRIMARYBUFFER = 0x00000001
DSBCAPS_STATIC = 0x00000002
DSBCAPS_LOCHARDWARE = 0x00000004
DSBCAPS_LOCSOFTWARE = 0x00000008
DSBCAPS_CTRL3D = 0x00000010
DSBCAPS_CTRLFREQUENCY = 0x00000020
DSBCAPS_CTRLPAN = 0x00000040
DSBCAPS_CTRLVOLUME = 0x00000080
DSBCAPS_CTRLPOSITIONNOTIFY = 0x00000100
DSBCAPS_CTRLFX = 0x00000200
DSBCAPS_STICKYFOCUS = 0x00004000
DSBCAPS_GLOBALFOCUS = 0x00008000
DSBCAPS_GETCURRENTPOSITION2 = 0x00010000
DSBCAPS_MUTE3DATMAXDISTANCE = 0x00020000
DSBCAPS_LOCDEFER = 0x00040000
DSBPLAY_LOOPING = 0x00000001
DSBPLAY_LOCHARDWARE = 0x00000002
DSBPLAY_LOCSOFTWARE = 0x00000004
DSBPLAY_TERMINATEBY_TIME = 0x00000008
DSBPLAY_TERMINATEBY_DISTANCE = 0x000000010
DSBPLAY_TERMINATEBY_PRIORITY = 0x000000020
DSBSTATUS_PLAYING = 0x00000001
DSBSTATUS_BUFFERLOST = 0x00000002
DSBSTATUS_LOOPING = 0x00000004
DSBSTATUS_LOCHARDWARE = 0x00000008
DSBSTATUS_LOCSOFTWARE = 0x00000010
DSBSTATUS_TERMINATED = 0x00000020
DSBLOCK_FROMWRITECURSOR = 0x00000001
DSBLOCK_ENTIREBUFFER = 0x00000002
DSBFREQUENCY_MIN = 100
DSBFREQUENCY_MAX = 100000
DSBFREQUENCY_ORIGINAL = 0
DSBPAN_LEFT = -10000
DSBPAN_CENTER = 0
DSBPAN_RIGHT = 10000
DSBVOLUME_MIN = -10000
DSBVOLUME_MAX = 0
DSBSIZE_MIN = 4
DSBSIZE_MAX = 0x0FFFFFFF
DSBSIZE_FX_MIN = 150 # NOTE: Milliseconds, not bytes
DS3DMODE_NORMAL = 0x00000000
DS3DMODE_HEADRELATIVE = 0x00000001
DS3DMODE_DISABLE = 0x00000002
DS3D_IMMEDIATE = 0x00000000
DS3D_DEFERRED = 0x00000001
DS3D_MINDISTANCEFACTOR = -1000000.0 # XXX FLT_MIN
DS3D_MAXDISTANCEFACTOR = 1000000.0 # XXX FLT_MAX
DS3D_DEFAULTDISTANCEFACTOR = 1.0
DS3D_MINROLLOFFFACTOR = 0.0
DS3D_MAXROLLOFFFACTOR = 10.0
DS3D_DEFAULTROLLOFFFACTOR = 1.0
DS3D_MINDOPPLERFACTOR = 0.0
DS3D_MAXDOPPLERFACTOR = 10.0
DS3D_DEFAULTDOPPLERFACTOR = 1.0
DS3D_DEFAULTMINDISTANCE = 1.0
DS3D_DEFAULTMAXDISTANCE = 1000000000.0
DS3D_MINCONEANGLE = 0
DS3D_MAXCONEANGLE = 360
DS3D_DEFAULTCONEANGLE = 360
DS3D_DEFAULTCONEOUTSIDEVOLUME = DSBVOLUME_MAX
# Return codes
DS_OK = 0x00000000
DSERR_OUTOFMEMORY = 0x00000007
DSERR_NOINTERFACE = 0x000001AE
DS_NO_VIRTUALIZATION = 0x0878000A
DS_INCOMPLETE = 0x08780014
DSERR_UNSUPPORTED = 0x80004001
DSERR_GENERIC = 0x80004005
DSERR_ACCESSDENIED = 0x80070005
DSERR_INVALIDPARAM = 0x80070057
DSERR_ALLOCATED = 0x8878000A
DSERR_CONTROLUNAVAIL = 0x8878001E
DSERR_INVALIDCALL = 0x88780032
DSERR_PRIOLEVELNEEDED = 0x88780046
DSERR_BADFORMAT = 0x88780064
DSERR_NODRIVER = 0x88780078
DSERR_ALREADYINITIALIZED = 0x88780082
DSERR_BUFFERLOST = 0x88780096
DSERR_OTHERAPPHASPRIO = 0x887800A0
DSERR_UNINITALIZED = 0x887800AA
DSERR_BUFFERTOOSMALL = 0x887810B4
DSERR_DS8_REQUIRED = 0x887810BE
DSERR_SENDLOOP = 0x887810C8
DSERR_BADSENDBUFFERGUID = 0x887810D2
DSERR_FXUNAVAILABLE = 0x887810DC
DSERR_OBJECTNOTFOUND = 0x88781161
# Buffer status
DSBSTATUS_PLAYING = 0x00000001
DSBSTATUS_BUFFERLOST = 0x00000002
DSBSTATUS_LOOPING = 0x00000004
| 14,439 | 31.017738 | 98 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/pyglet/media/drivers/directsound/__init__.py
|
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
from __future__ import absolute_import
from . import adaptation
from .exceptions import DirectSoundException, DirectSoundNativeError
def create_audio_driver():
return adaptation.DirectSoundDriver()
__all__ = ["create_audio_driver", "DirectSoundException", "DirectSoundNativeError"]
| 2,008 | 44.659091 | 83 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/pyglet/media/drivers/directsound/interface.py
|
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
"""
Pythonic interface to DirectSound.
"""
from collections import namedtuple
import ctypes
from pyglet.debug import debug_print
from pyglet.window.win32 import _user32
from . import lib_dsound as lib
from .exceptions import DirectSoundNativeError
_debug_media = debug_print('debug_media')
def _check(hresult):
if hresult != lib.DS_OK:
raise DirectSoundNativeError(hresult)
class DirectSoundDriver(object):
def __init__(self):
assert _debug_media('Constructing DirectSoundDriver')
self._native_dsound = lib.IDirectSound()
_check(
lib.DirectSoundCreate(None, ctypes.byref(self._native_dsound), None)
)
# A trick used by mplayer.. use desktop as window handle since it
# would be complex to use pyglet window handles (and what to do when
# application is audio only?).
hwnd = _user32.GetDesktopWindow()
_check(
self._native_dsound.SetCooperativeLevel(hwnd, lib.DSSCL_NORMAL)
)
self._buffer_factory = DirectSoundBufferFactory(self, self._native_dsound)
self.primary_buffer = self._buffer_factory.create_primary_buffer()
def __del__(self):
assert _debug_media('Destroying DirectSoundDriver')
del self.primary_buffer
self._native_dsound.Release()
def create_buffer(self, audio_format):
return self._buffer_factory.create_buffer(audio_format)
def create_listener(self):
return self.primary_buffer.create_listener()
class DirectSoundBufferFactory(object):
default_buffer_size = 2.0
def __init__(self, driver, native_dsound):
self.driver = driver
self._native_dsound = native_dsound
def create_buffer(self, audio_format):
buffer_size = int(audio_format.sample_rate * self.default_buffer_size)
wave_format = self._create_wave_format(audio_format)
buffer_desc = self._create_buffer_desc(wave_format, buffer_size)
return DirectSoundBuffer(
self.driver,
self._create_buffer(buffer_desc),
audio_format,
buffer_size)
def create_primary_buffer(self):
return DirectSoundBuffer(
self,
self._create_buffer(self._create_primary_buffer_desc()),
None,
0)
def _create_buffer(self, buffer_desc):
buf = lib.IDirectSoundBuffer()
_check(
self._native_dsound.CreateSoundBuffer(buffer_desc, ctypes.byref(buf), None)
)
return buf
@staticmethod
def _create_wave_format(audio_format):
wfx = lib.WAVEFORMATEX()
wfx.wFormatTag = lib.WAVE_FORMAT_PCM
wfx.nChannels = audio_format.channels
wfx.nSamplesPerSec = audio_format.sample_rate
wfx.wBitsPerSample = audio_format.sample_size
wfx.nBlockAlign = wfx.wBitsPerSample * wfx.nChannels // 8
wfx.nAvgBytesPerSec = wfx.nSamplesPerSec * wfx.nBlockAlign
return wfx
@classmethod
def _create_buffer_desc(cls, wave_format, buffer_size):
dsbdesc = lib.DSBUFFERDESC()
dsbdesc.dwSize = ctypes.sizeof(dsbdesc)
dsbdesc.dwFlags = (lib.DSBCAPS_GLOBALFOCUS |
lib.DSBCAPS_GETCURRENTPOSITION2 |
lib.DSBCAPS_CTRLFREQUENCY |
lib.DSBCAPS_CTRLVOLUME)
if wave_format.nChannels == 1:
dsbdesc.dwFlags |= lib.DSBCAPS_CTRL3D
dsbdesc.dwBufferBytes = buffer_size
dsbdesc.lpwfxFormat = ctypes.pointer(wave_format)
return dsbdesc
@classmethod
def _create_primary_buffer_desc(cls):
"""Primary buffer with 3D and volume capabilities"""
buffer_desc = lib.DSBUFFERDESC()
buffer_desc.dwSize = ctypes.sizeof(buffer_desc)
buffer_desc.dwFlags = (lib.DSBCAPS_CTRL3D |
lib.DSBCAPS_CTRLVOLUME |
lib.DSBCAPS_PRIMARYBUFFER)
return buffer_desc
class DirectSoundBuffer(object):
def __init__(self, driver, native_buffer, audio_format, buffer_size):
self.driver = driver
self.audio_format = audio_format
self.buffer_size = buffer_size
self._native_buffer = native_buffer
if audio_format is not None and audio_format.channels == 1:
self._native_buffer3d = lib.IDirectSound3DBuffer()
self._native_buffer.QueryInterface(lib.IID_IDirectSound3DBuffer,
ctypes.byref(self._native_buffer3d))
else:
self._native_buffer3d = None
def __del__(self):
if self._native_buffer is not None:
self._native_buffer.Stop()
self._native_buffer.Release()
self._native_buffer = None
if self._native_buffer3d is not None:
self._native_buffer3d.Release()
self._native_buffer3d = None
@property
def volume(self):
vol = lib.LONG()
_check(
self._native_buffer.GetVolume(ctypes.byref(vol))
)
return vol.value
@volume.setter
def volume(self, value):
_check(
self._native_buffer.SetVolume(value)
)
_CurrentPosition = namedtuple('_CurrentPosition', ['play_cursor', 'write_cursor'])
@property
def current_position(self):
"""Tuple of current play position and current write position.
Only play position can be modified, so setter only accepts a single value."""
play_cursor = lib.DWORD()
write_cursor = lib.DWORD()
_check(
self._native_buffer.GetCurrentPosition(play_cursor,
write_cursor)
)
return self._CurrentPosition(play_cursor.value, write_cursor.value)
@current_position.setter
def current_position(self, value):
_check(
self._native_buffer.SetCurrentPosition(value)
)
@property
def is3d(self):
return self._native_buffer3d is not None
@property
def is_playing(self):
return (self._get_status() & lib.DSBSTATUS_PLAYING) != 0
@property
def is_buffer_lost(self):
return (self._get_status() & lib.DSBSTATUS_BUFFERLOST) != 0
def _get_status(self):
status = lib.DWORD()
_check(
self._native_buffer.GetStatus(status)
)
return status.value
@property
def position(self):
if self.is3d:
position = lib.D3DVECTOR()
_check(
self._native_buffer3d.GetPosition(ctypes.byref(position))
)
return position.x, position.y, position.z
else:
return 0, 0, 0
@position.setter
def position(self, position):
if self.is3d:
x, y, z = position
_check(
self._native_buffer3d.SetPosition(x, y, z, lib.DS3D_IMMEDIATE)
)
@property
def min_distance(self):
"""The minimum distance, which is the distance from the
listener at which sounds in this buffer begin to be attenuated."""
if self.is3d:
value = lib.D3DVALUE()
_check(
self._native_buffer3d.GetMinDistance(ctypes.byref(value))
)
return value.value
else:
return 0
@min_distance.setter
def min_distance(self, value):
if self.is3d:
_check(
self._native_buffer3d.SetMinDistance(value, lib.DS3D_IMMEDIATE)
)
@property
def max_distance(self):
"""The maximum distance, which is the distance from the listener beyond which
sounds in this buffer are no longer attenuated."""
if self.is3d:
value = lib.D3DVALUE()
_check(
self._native_buffer3d.GetMaxDistance(ctypes.byref(value))
)
return value.value
else:
return 0
@max_distance.setter
def max_distance(self, value):
if self.is3d:
_check(
self._native_buffer3d.SetMaxDistance(value, lib.DS3D_IMMEDIATE)
)
@property
def frequency(self):
value = lib.DWORD()
_check(
self._native_buffer.GetFrequency(value)
)
return value.value
@frequency.setter
def frequency(self, value):
"""The frequency, in samples per second, at which the buffer is playing."""
_check(
self._native_buffer.SetFrequency(value)
)
@property
def cone_orientation(self):
"""The orientation of the sound projection cone."""
if self.is3d:
orientation = lib.D3DVECTOR()
_check(
self._native_buffer3d.GetConeOrientation(ctypes.byref(orientation))
)
return orientation.x, orientation.y, orientation.z
else:
return 0, 0, 0
@cone_orientation.setter
def cone_orientation(self, value):
if self.is3d:
x, y, z = value
_check(
self._native_buffer3d.SetConeOrientation(x, y, z, lib.DS3D_IMMEDIATE)
)
_ConeAngles = namedtuple('_ConeAngles', ['inside', 'outside'])
@property
def cone_angles(self):
"""The inside and outside angles of the sound projection cone."""
if self.is3d:
inside = lib.DWORD()
outside = lib.DWORD()
_check(
self._native_buffer3d.GetConeAngles(ctypes.byref(inside), ctypes.byref(outside))
)
return self._ConeAngles(inside.value, outside.value)
else:
return self._ConeAngles(0, 0)
def set_cone_angles(self, inside, outside):
"""The inside and outside angles of the sound projection cone."""
if self.is3d:
_check(
self._native_buffer3d.SetConeAngles(inside, outside, lib.DS3D_IMMEDIATE)
)
@property
def cone_outside_volume(self):
"""The volume of the sound outside the outside angle of the sound projection cone."""
if self.is3d:
volume = lib.LONG()
_check(
self._native_buffer3d.GetConeOutsideVolume(ctypes.byref(volume))
)
return volume.value
else:
return 0
@cone_outside_volume.setter
def cone_outside_volume(self, value):
if self.is3d:
_check(
self._native_buffer3d.SetConeOutsideVolume(value, lib.DS3D_IMMEDIATE)
)
def create_listener(self):
native_listener = lib.IDirectSound3DListener()
self._native_buffer.QueryInterface(lib.IID_IDirectSound3DListener,
ctypes.byref(native_listener))
return DirectSoundListener(self, native_listener)
def play(self):
_check(
self._native_buffer.Play(0, 0, lib.DSBPLAY_LOOPING)
)
def stop(self):
_check(
self._native_buffer.Stop()
)
class _WritePointer(object):
def __init__(self):
self.audio_ptr_1 = ctypes.c_void_p()
self.audio_length_1 = lib.DWORD()
self.audio_ptr_2 = ctypes.c_void_p()
self.audio_length_2 = lib.DWORD()
def lock(self, write_cursor, write_size):
assert _debug_media('DirectSoundBuffer.lock({}, {})'.format(write_cursor, write_size))
pointer = self._WritePointer()
_check(
self._native_buffer.Lock(write_cursor,
write_size,
ctypes.byref(pointer.audio_ptr_1),
pointer.audio_length_1,
ctypes.byref(pointer.audio_ptr_2),
pointer.audio_length_2,
0)
)
return pointer
def unlock(self, pointer):
_check(
self._native_buffer.Unlock(pointer.audio_ptr_1,
pointer.audio_length_1,
pointer.audio_ptr_2,
pointer.audio_length_2)
)
class DirectSoundListener(object):
def __init__(self, ds_buffer, native_listener):
self.ds_buffer = ds_buffer
self._native_listener = native_listener
def __del__(self):
self._native_listener.Release()
@property
def position(self):
vector = lib.D3DVECTOR()
_check(
self._native_listener.GetPosition(ctypes.byref(vector))
)
return (vector.x, vector.y, vector.z)
@position.setter
def position(self, value):
_check(
self._native_listener.SetPosition(*(list(value) + [lib.DS3D_IMMEDIATE]))
)
@property
def orientation(self):
front = lib.D3DVECTOR()
top = lib.D3DVECTOR()
_check(
self._native_listener.GetOrientation(ctypes.byref(front), ctypes.byref(top))
)
return (front.x, front.y, front.z, top.x, top.y, top.z)
@orientation.setter
def orientation(self, orientation):
_check(
self._native_listener.SetOrientation(*(list(orientation) + [lib.DS3D_IMMEDIATE]))
)
| 15,103 | 32.714286 | 96 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/pyglet/media/drivers/directsound/adaptation.py
|
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
from __future__ import absolute_import, print_function
import ctypes
import math
import threading
from . import interface
from pyglet.debug import debug_print
from pyglet.media.events import MediaEvent
from pyglet.media.drivers.base import AbstractAudioDriver, AbstractAudioPlayer
from pyglet.media.listener import AbstractListener
from pyglet.media.threads import PlayerWorker
_debug = debug_print('debug_media')
def _convert_coordinates(coordinates):
x, y, z = coordinates
return (x, y, -z)
def _gain2db(gain):
"""
Convert linear gain in range [0.0, 1.0] to 100ths of dB.
Power gain = P1/P2
dB = 10 log(P1/P2)
dB * 100 = 1000 * log(power gain)
"""
if gain <= 0:
return -10000
return max(-10000, min(int(1000 * math.log10(min(gain, 1))), 0))
def _db2gain(db):
"""Convert 100ths of dB to linear gain."""
return math.pow(10.0, float(db)/1000.0)
class DirectSoundAudioPlayer(AbstractAudioPlayer):
# Need to cache these because pyglet API allows update separately, but
# DSound requires both to be set at once.
_cone_inner_angle = 360
_cone_outer_angle = 360
min_buffer_size = 9600
def __init__(self, driver, ds_driver, source_group, player):
super(DirectSoundAudioPlayer, self).__init__(source_group, player)
self.driver = driver
self._ds_driver = ds_driver
# Locking strategy:
# All DirectSound calls should be locked. All instance vars relating
# to buffering/filling/time/events should be locked (used by both
# application and worker thread). Other instance vars (consts and
# 3d vars) do not need to be locked.
self._lock = threading.RLock()
# Desired play state (may be actually paused due to underrun -- not
# implemented yet).
self._playing = False
# Up to one audio data may be buffered if too much data was received
# from the source that could not be written immediately into the
# buffer. See refill().
self._audiodata_buffer = None
# Theoretical write and play cursors for an infinite buffer. play
# cursor is always <= write cursor (when equal, underrun is
# happening).
self._write_cursor = 0
self._play_cursor = 0
# Cursor position of end of data. Silence is written after
# eos for one buffer size.
self._eos_cursor = None
# Indexes into DSound circular buffer. Complications ensue wrt each
# other to avoid writing over the play cursor. See get_write_size and
# write().
self._play_cursor_ring = 0
self._write_cursor_ring = 0
# List of (play_cursor, MediaEvent), in sort order
self._events = []
# List of (cursor, timestamp), in sort order (cursor gives expiry
# place of the timestamp)
self._timestamps = []
audio_format = source_group.audio_format
# DSound buffer
self._ds_buffer = self._ds_driver.create_buffer(audio_format)
self._buffer_size = self._ds_buffer.buffer_size
self._ds_buffer.current_position = 0
self.refill(self._buffer_size)
def __del__(self):
try:
self.delete()
except:
pass
def delete(self):
if self.driver and self.driver.worker:
self.driver.worker.remove(self)
with self._lock:
self._ds_buffer = None
def play(self):
assert _debug('DirectSound play')
self.driver.worker.add(self)
with self._lock:
if not self._playing:
self._get_audiodata() # prebuffer if needed
self._playing = True
self._ds_buffer.play()
assert _debug('return DirectSound play')
def stop(self):
assert _debug('DirectSound stop')
with self._lock:
if self._playing:
self._playing = False
self._ds_buffer.stop()
assert _debug('return DirectSound stop')
def clear(self):
assert _debug('DirectSound clear')
with self._lock:
self._ds_buffer.current_position = 0
self._play_cursor_ring = self._write_cursor_ring = 0
self._play_cursor = self._write_cursor
self._eos_cursor = None
self._audiodata_buffer = None
del self._events[:]
del self._timestamps[:]
def refill(self, write_size):
with self._lock:
while write_size > 0:
assert _debug('refill, write_size =', write_size)
audio_data = self._get_audiodata()
if audio_data is not None:
assert _debug('write', audio_data.length)
length = min(write_size, audio_data.length)
self.write(audio_data, length)
write_size -= length
else:
assert _debug('write silence')
self.write(None, write_size)
write_size = 0
def _has_underrun(self):
return (self._eos_cursor is not None
and self._play_cursor > self._eos_cursor)
def _dispatch_new_event(self, event_name):
MediaEvent(0, event_name)._sync_dispatch_to_player(self.player)
def _get_audiodata(self):
if self._audiodata_buffer is None or self._audiodata_buffer.length == 0:
self._get_new_audiodata()
return self._audiodata_buffer
def _get_new_audiodata(self):
assert _debug('Getting new audio data buffer.')
self._audiodata_buffer = self.source_group.get_audio_data(self._buffer_size)
if self._audiodata_buffer is not None:
assert _debug('New audio data available: {} bytes'.format(self._audiodata_buffer.length))
if self._eos_cursor is not None:
self._move_write_cursor_after_eos()
self._add_audiodata_events(self._audiodata_buffer)
self._add_audiodata_timestamp(self._audiodata_buffer)
self._eos_cursor = None
elif self._eos_cursor is None:
assert _debug('No more audio data.')
self._eos_cursor = self._write_cursor
def _move_write_cursor_after_eos(self):
# Set the write cursor back to eos_cursor or play_cursor to prevent gaps
if self._play_cursor < self._eos_cursor:
cursor_diff = self._write_cursor - self._eos_cursor
assert _debug('Moving cursor back', cursor_diff)
self._write_cursor = self._eos_cursor
self._write_cursor_ring -= cursor_diff
self._write_cursor_ring %= self._buffer_size
else:
cursor_diff = self._play_cursor - self._eos_cursor
assert _debug('Moving cursor back', cursor_diff)
self._write_cursor = self._play_cursor
self._write_cursor_ring -= cursor_diff
self._write_cursor_ring %= self._buffer_size
def _add_audiodata_events(self, audio_data):
for event in audio_data.events:
event_cursor = self._write_cursor + event.timestamp * \
self.source_group.audio_format.bytes_per_second
assert _debug('Adding event', event, 'at', event_cursor)
self._events.append((event_cursor, event))
def _add_audiodata_timestamp(self, audio_data):
ts_cursor = self._write_cursor + audio_data.length
self._timestamps.append(
(ts_cursor, audio_data.timestamp + audio_data.duration))
def update_play_cursor(self):
with self._lock:
play_cursor_ring = self._ds_buffer.current_position.play_cursor
if play_cursor_ring < self._play_cursor_ring:
# Wrapped around
self._play_cursor += self._buffer_size - self._play_cursor_ring
self._play_cursor_ring = 0
self._play_cursor += play_cursor_ring - self._play_cursor_ring
self._play_cursor_ring = play_cursor_ring
self._dispatch_pending_events()
self._cleanup_timestamps()
self._check_underrun()
def _dispatch_pending_events(self):
with self._lock:
pending_events = []
while self._events and self._events[0][0] <= self._play_cursor:
_, event = self._events.pop(0)
pending_events.append(event)
assert _debug('Dispatching pending events: {}'.format(pending_events))
assert _debug('Remaining events: {}'.format(self._events))
for event in pending_events:
event._sync_dispatch_to_player(self.player)
def _cleanup_timestamps(self):
with self._lock:
while self._timestamps and self._timestamps[0][0] < self._play_cursor:
del self._timestamps[0]
def _check_underrun(self):
if self._playing and self._has_underrun():
assert _debug('underrun, stopping')
self.stop()
self._dispatch_new_event('on_eos')
self._dispatch_new_event('on_source_group_eos')
def get_write_size(self):
self.update_play_cursor()
with self._lock:
play_cursor = self._play_cursor
write_cursor = self._write_cursor
return self._buffer_size - max(write_cursor - play_cursor, 0)
def write(self, audio_data, length):
# Pass audio_data=None to write silence
if length == 0:
return 0
with self._lock:
write_ptr = self._ds_buffer.lock(self._write_cursor_ring, length)
assert 0 < length <= self._buffer_size
assert length == write_ptr.audio_length_1.value + write_ptr.audio_length_2.value
if audio_data:
ctypes.memmove(write_ptr.audio_ptr_1, audio_data.data, write_ptr.audio_length_1.value)
audio_data.consume(write_ptr.audio_length_1.value, self.source_group.audio_format)
if write_ptr.audio_length_2.value > 0:
ctypes.memmove(write_ptr.audio_ptr_2, audio_data.data, write_ptr.audio_length_2.value)
audio_data.consume(write_ptr.audio_length_2.value, self.source_group.audio_format)
else:
if self.source_group.audio_format.sample_size == 8:
c = 0x80
else:
c = 0
ctypes.memset(write_ptr.audio_ptr_1, c, write_ptr.audio_length_1.value)
if write_ptr.audio_length_2.value > 0:
ctypes.memset(write_ptr.audio_ptr_2, c, write_ptr.audio_length_2.value)
self._ds_buffer.unlock(write_ptr)
self._write_cursor += length
self._write_cursor_ring += length
self._write_cursor_ring %= self._buffer_size
def get_time(self):
with self._lock:
if self._timestamps:
cursor, ts = self._timestamps[0]
result = ts + (self._play_cursor - cursor) / \
float(self.source_group.audio_format.bytes_per_second)
else:
result = None
return result
def set_volume(self, volume):
with self._lock:
self._ds_buffer.volume = _gain2db(volume)
def set_position(self, position):
if self._ds_buffer.is3d:
with self._lock:
self._ds_buffer.position = _convert_coordinates(position)
def set_min_distance(self, min_distance):
if self._ds_buffer.is3d:
with self._lock:
self._ds_buffer.min_distance = min_distance
def set_max_distance(self, max_distance):
if self._ds_buffer.is3d:
with self._lock:
self._ds_buffer.max_distance = max_distance
def set_pitch(self, pitch):
frequency = int(pitch * self.source_group.audio_format.sample_rate)
with self._lock:
self._ds_buffer.frequency = frequency
def set_cone_orientation(self, cone_orientation):
if self._ds_buffer.is3d:
with self._lock:
self._ds_buffer.cone_orientation = _convert_coordinates(cone_orientation)
def set_cone_inner_angle(self, cone_inner_angle):
if self._ds_buffer.is3d:
self._cone_inner_angle = int(cone_inner_angle)
self._set_cone_angles()
def set_cone_outer_angle(self, cone_outer_angle):
if self._ds_buffer.is3d:
self._cone_outer_angle = int(cone_outer_angle)
self._set_cone_angles()
def _set_cone_angles(self):
inner = min(self._cone_inner_angle, self._cone_outer_angle)
outer = max(self._cone_inner_angle, self._cone_outer_angle)
with self._lock:
self._ds_buffer.set_cone_angles(inner, outer)
def set_cone_outer_gain(self, cone_outer_gain):
if self._ds_buffer.is3d:
volume = _gain2db(cone_outer_gain)
with self._lock:
self._ds_buffer.cone_outside_volume = volume
class DirectSoundDriver(AbstractAudioDriver):
def __init__(self):
self._ds_driver = interface.DirectSoundDriver()
self._ds_listener = self._ds_driver.create_listener()
assert self._ds_driver is not None
assert self._ds_listener is not None
# Create worker thread
self.worker = PlayerWorker()
self.worker.start()
def __del__(self):
try:
if self._ds_driver:
self.delete()
except:
pass
def create_audio_player(self, source_group, player):
assert self._ds_driver is not None
return DirectSoundAudioPlayer(self, self._ds_driver, source_group, player)
def get_listener(self):
assert self._ds_driver is not None
assert self._ds_listener is not None
return DirectSoundListener(self._ds_listener, self._ds_driver.primary_buffer)
def delete(self):
self.worker.stop()
self._ds_listener = None
self._ds_driver = None
class DirectSoundListener(AbstractListener):
def __init__(self, ds_listener, ds_buffer):
self._ds_listener = ds_listener
self._ds_buffer = ds_buffer
def _set_volume(self, volume):
self._volume = volume
self._ds_buffer.volume = _gain2db(volume)
def _set_position(self, position):
self._position = position
self._ds_listener.position = _convert_coordinates(position)
def _set_forward_orientation(self, orientation):
self._forward_orientation = orientation
self._set_orientation()
def _set_up_orientation(self, orientation):
self._up_orientation = orientation
self._set_orientation()
def _set_orientation(self):
self._ds_listener.orientation = (_convert_coordinates(self._forward_orientation)
+ _convert_coordinates(self._up_orientation))
| 16,664 | 35.626374 | 106 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/pyglet/media/sources/base.py
|
from __future__ import print_function
from __future__ import division
from builtins import object
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
import ctypes
import sys
import pyglet
from pyglet.compat import bytes_type, BytesIO
from pyglet.media.events import MediaEvent
from pyglet.media.exceptions import MediaException
_debug = pyglet.options['debug_media']
class AudioFormat(object):
"""Audio details.
An instance of this class is provided by sources with audio tracks. You
should not modify the fields, as they are used internally to describe the
format of data provided by the source.
:Ivariables:
`channels` : int
The number of channels: 1 for mono or 2 for stereo (pyglet does
not yet support surround-sound sources).
`sample_size` : int
Bits per sample; only 8 or 16 are supported.
`sample_rate` : int
Samples per second (in Hertz).
"""
def __init__(self, channels, sample_size, sample_rate):
self.channels = channels
self.sample_size = sample_size
self.sample_rate = sample_rate
# Convenience
self.bytes_per_sample = (sample_size >> 3) * channels
self.bytes_per_second = self.bytes_per_sample * sample_rate
def __eq__(self, other):
return (self.channels == other.channels and
self.sample_size == other.sample_size and
self.sample_rate == other.sample_rate)
def __ne__(self, other):
return not self.__eq__(other)
def __repr__(self):
return '%s(channels=%d, sample_size=%d, sample_rate=%d)' % (
self.__class__.__name__, self.channels, self.sample_size,
self.sample_rate)
class VideoFormat(object):
"""Video details.
An instance of this class is provided by sources with a video track. You
should not modify the fields.
Note that the sample aspect has no relation to the aspect ratio of the
video image. For example, a video image of 640x480 with sample aspect 2.0
should be displayed at 1280x480. It is the responsibility of the
application to perform this scaling.
:Ivariables:
`width` : int
Width of video image, in pixels.
`height` : int
Height of video image, in pixels.
`sample_aspect` : float
Aspect ratio (width over height) of a single video pixel.
`frame_rate` : float
Frame rate (frames per second) of the video.
AVbin 8 or later is required, otherwise the frame rate will be
``None``.
.. versionadded:: 1.2.
"""
def __init__(self, width, height, sample_aspect=1.0):
self.width = width
self.height = height
self.sample_aspect = sample_aspect
self.frame_rate = None
class AudioData(object):
"""A single packet of audio data.
This class is used internally by pyglet.
:Ivariables:
`data` : str or ctypes array or pointer
Sample data.
`length` : int
Size of sample data, in bytes.
`timestamp` : float
Time of the first sample, in seconds.
`duration` : float
Total data duration, in seconds.
`events` : list of MediaEvent
List of events contained within this packet. Events are
timestamped relative to this audio packet.
"""
def __init__(self, data, length, timestamp, duration, events):
self.data = data
self.length = length
self.timestamp = timestamp
self.duration = duration
self.events = events
def consume(self, bytes, audio_format):
"""Remove some data from beginning of packet. All events are
cleared."""
self.events = ()
if bytes >= self.length:
self.data = None
self.length = 0
self.timestamp += self.duration
self.duration = 0.
return
elif bytes == 0:
return
if not isinstance(self.data, str):
# XXX Create a string buffer for the whole packet then
# chop it up. Could do some pointer arith here and
# save a bit of data pushing, but my guess is this is
# faster than fudging aruond with ctypes (and easier).
data = ctypes.create_string_buffer(self.length)
ctypes.memmove(data, self.data, self.length)
self.data = data
self.data = self.data[bytes:]
self.length -= bytes
self.duration -= bytes / float(audio_format.bytes_per_second)
self.timestamp += bytes / float(audio_format.bytes_per_second)
def get_string_data(self):
"""Return data as a string. (Python 3: return as bytes)"""
if self.data is None:
return b''
if isinstance(self.data, bytes_type):
return self.data
buf = ctypes.create_string_buffer(self.length)
ctypes.memmove(buf, self.data, self.length)
return buf.raw
class SourceInfo(object):
"""Source metadata information.
Fields are the empty string or zero if the information is not available.
:Ivariables:
`title` : str
Title
`author` : str
Author
`copyright` : str
Copyright statement
`comment` : str
Comment
`album` : str
Album name
`year` : int
Year
`track` : int
Track number
`genre` : str
Genre
.. versionadded:: 1.2
"""
title = ''
author = ''
copyright = ''
comment = ''
album = ''
year = 0
track = 0
genre = ''
class Source(object):
"""An audio and/or video source.
:Ivariables:
`audio_format` : `AudioFormat`
Format of the audio in this source, or None if the source is
silent.
`video_format` : `VideoFormat`
Format of the video in this source, or None if there is no
video.
`info` : `SourceInfo`
Source metadata such as title, artist, etc; or None if the
information is not available.
.. versionadded:: 1.2
"""
_duration = None
audio_format = None
video_format = None
info = None
def _get_duration(self):
return self._duration
duration = property(lambda self: self._get_duration(),
doc="""The length of the source, in seconds.
Not all source durations can be determined; in this case the value
is None.
Read-only.
:type: float
""")
def play(self):
"""Play the source.
This is a convenience method which creates a Player for
this source and plays it immediately.
:rtype: `Player`
"""
from pyglet.media.player import Player # XXX Nasty circular dependency
player = Player()
player.queue(self)
player.play()
return player
def get_animation(self):
"""Import all video frames into memory as an :py:class:`~pyglet.image.Animation`.
An empty animation will be returned if the source has no video.
Otherwise, the animation will contain all unplayed video frames (the
entire source, if it has not been queued on a player). After creating
the animation, the source will be at EOS.
This method is unsuitable for videos running longer than a
few seconds.
.. versionadded:: 1.1
:rtype: `pyglet.image.Animation`
"""
from pyglet.image import Animation, AnimationFrame
if not self.video_format:
# XXX: This causes an assertion in the constructor of Animation
return Animation([])
else:
frames = []
last_ts = 0
next_ts = self.get_next_video_timestamp()
while next_ts is not None:
image = self.get_next_video_frame()
if image is not None:
delay = next_ts - last_ts
frames.append(AnimationFrame(image, delay))
last_ts = next_ts
next_ts = self.get_next_video_timestamp()
return Animation(frames)
def get_next_video_timestamp(self):
"""Get the timestamp of the next video frame.
.. versionadded:: 1.1
:rtype: float
:return: The next timestamp, or ``None`` if there are no more video
frames.
"""
pass
def get_next_video_frame(self):
"""Get the next video frame.
Video frames may share memory: the previous frame may be invalidated
or corrupted when this method is called unless the application has
made a copy of it.
.. versionadded:: 1.1
:rtype: `pyglet.image.AbstractImage`
:return: The next video frame image, or ``None`` if the video frame
could not be decoded or there are no more video frames.
"""
pass
# Internal methods that SourceGroup calls on the source:
def seek(self, timestamp):
"""Seek to given timestamp."""
raise CannotSeekException()
def _get_queue_source(self):
"""Return the `Source` to be used as the queue source for a player.
Default implementation returns self."""
return self
def get_audio_data(self, bytes):
"""Get next packet of audio data.
:Parameters:
`bytes` : int
Maximum number of bytes of data to return.
:rtype: `AudioData`
:return: Next packet of audio data, or None if there is no (more)
data.
"""
return None
class StreamingSource(Source):
"""A source that is decoded as it is being played, and can only be
queued once.
"""
_is_queued = False
is_queued = property(lambda self: self._is_queued,
doc="""Determine if this source has been queued
on a :py:class:`~pyglet.media.player.Player` yet.
Read-only.
:type: bool
""")
def _get_queue_source(self):
"""Return the `Source` to be used as the queue source for a player.
Default implementation returns self."""
if self._is_queued:
raise MediaException('This source is already queued on a player.')
self._is_queued = True
return self
def delete(self):
pass
class StaticSource(Source):
"""A source that has been completely decoded in memory. This source can
be queued onto multiple players any number of times.
"""
def __init__(self, source):
"""Construct a :py:class:`~pyglet.media.StaticSource` for the data in `source`.
:Parameters:
`source` : `Source`
The source to read and decode audio and video data from.
"""
source = source._get_queue_source()
if source.video_format:
raise NotImplementedError(
'Static sources not supported for video yet.')
self.audio_format = source.audio_format
if not self.audio_format:
self._data = None
self._duration = 0.
return
# Arbitrary: number of bytes to request at a time.
buffer_size = 1 << 20 # 1 MB
# Naive implementation. Driver-specific implementations may override
# to load static audio data into device (or at least driver) memory.
data = BytesIO()
while True:
audio_data = source.get_audio_data(buffer_size)
if not audio_data:
break
data.write(audio_data.get_string_data())
self._data = data.getvalue()
self._duration = len(self._data) / \
float(self.audio_format.bytes_per_second)
def _get_queue_source(self):
if self._data is not None:
return StaticMemorySource(self._data, self.audio_format)
def get_audio_data(self, bytes):
raise RuntimeError('StaticSource cannot be queued.')
class StaticMemorySource(StaticSource):
"""Helper class for default implementation of :py:class:`~pyglet.media.StaticSource`. Do not use
directly."""
def __init__(self, data, audio_format):
"""Construct a memory source over the given data buffer.
"""
self._file = BytesIO(data)
self._max_offset = len(data)
self.audio_format = audio_format
self._duration = len(data) / float(audio_format.bytes_per_second)
def seek(self, timestamp):
offset = int(timestamp * self.audio_format.bytes_per_second)
# Align to sample
if self.audio_format.bytes_per_sample == 2:
offset &= 0xfffffffe
elif self.audio_format.bytes_per_sample == 4:
offset &= 0xfffffffc
self._file.seek(offset)
def get_audio_data(self, bytes):
offset = self._file.tell()
timestamp = float(offset) / self.audio_format.bytes_per_second
# Align to sample size
if self.audio_format.bytes_per_sample == 2:
bytes &= 0xfffffffe
elif self.audio_format.bytes_per_sample == 4:
bytes &= 0xfffffffc
data = self._file.read(bytes)
if not len(data):
return None
duration = float(len(data)) / self.audio_format.bytes_per_second
return AudioData(data, len(data), timestamp, duration, [])
class SourceGroup(object):
"""Read data from a queue of sources, with support for looping. All
sources must share the same audio format.
:Ivariables:
`audio_format` : `AudioFormat`
Required audio format for queued sources.
"""
# TODO can sources list go empty? what behaviour (ignore or error)?
_advance_after_eos = False
_loop = False
def __init__(self, audio_format, video_format):
self.audio_format = audio_format
self.video_format = video_format
self.duration = 0.
self._timestamp_offset = 0.
self._dequeued_durations = []
self._sources = []
def seek(self, time):
if self._sources:
self._sources[0].seek(time)
def queue(self, source):
source = source._get_queue_source()
assert(source.audio_format == self.audio_format)
self._sources.append(source)
self.duration += source.duration
def has_next(self):
return len(self._sources) > 1
def next_source(self, immediate=True):
if immediate:
self._advance()
else:
self._advance_after_eos = True
#: :deprecated: Use `next_source` instead.
next = next_source # old API, worked badly with 2to3
def get_current_source(self):
if self._sources:
return self._sources[0]
def _advance(self):
if self._sources:
self._timestamp_offset += self._sources[0].duration
self._dequeued_durations.insert(0, self._sources[0].duration)
old_source = self._sources.pop(0)
self.duration -= old_source.duration
if isinstance(old_source, StreamingSource):
old_source.delete()
del old_source
def _get_loop(self):
return self._loop
def _set_loop(self, loop):
self._loop = loop
loop = property(_get_loop, _set_loop,
doc="""Loop the current source indefinitely or until
`next` is called. Initially False.
:type: bool
""")
def get_audio_data(self, bytes):
"""Get next audio packet.
:Parameters:
`bytes` : int
Hint for preferred size of audio packet; may be ignored.
:rtype: `AudioData`
:return: Audio data, or None if there is no more data.
"""
if not self._sources:
return None
data = self._sources[0].get_audio_data(bytes)
eos = False
while not data:
eos = True
if self._loop and not self._advance_after_eos:
self._timestamp_offset += self._sources[0].duration
self._dequeued_durations.insert(0, self._sources[0].duration)
self._sources[0].seek(0)
else:
self._advance_after_eos = False
# Advance source if there's something to advance to.
# Otherwise leave last source paused at EOS.
if len(self._sources) > 1:
self._advance()
else:
return None
data = self._sources[0].get_audio_data(bytes) # TODO method rename
data.timestamp += self._timestamp_offset
if eos:
if _debug:
print('adding on_eos event to audio data')
data.events.append(MediaEvent(0, 'on_eos'))
return data
def translate_timestamp(self, timestamp):
"""Get source-relative timestamp for the audio player's timestamp."""
# XXX
if timestamp is None:
return None
timestamp = timestamp - self._timestamp_offset
if timestamp < 0:
# _dequeued_durations is already ordered last to first
for duration in self._dequeued_durations:
timestamp += duration
if timestamp > 0:
break
assert timestamp >= 0, 'Timestamp beyond dequeued source memory'
return timestamp
def get_next_video_timestamp(self):
"""Get the timestamp of the next video frame.
:rtype: float
:return: The next timestamp, or ``None`` if there are no more video
frames.
"""
# TODO track current video source independently from audio source for
# better prebuffering.
if not self._sources:
return None
timestamp = self._sources[0].get_next_video_timestamp()
if timestamp is not None:
timestamp += self._timestamp_offset
return timestamp
def get_next_video_frame(self):
"""Get the next video frame.
Video frames may share memory: the previous frame may be invalidated
or corrupted when this method is called unless the application has
made a copy of it.
:rtype: `pyglet.image.AbstractImage`
:return: The next video frame image, or ``None`` if the video frame
could not be decoded or there are no more video frames.
"""
if self._sources:
return self._sources[0].get_next_video_frame()
| 20,361 | 31.269414 | 101 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/pyglet/media/sources/procedural.py
|
from __future__ import division
from builtins import range
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
from pyglet.media.sources.base import Source, AudioFormat, AudioData
from collections import deque
import ctypes
import os
import math
import struct
import random
class Envelope(object):
"""Base class for ProceduralSource amplitude envelopes."""
def build_envelope(self, sample_rate, duration):
raise NotImplementedError
class FlatEnvelope(Envelope):
"""A flat envelope, providing basic amplitude setting.
:Parameters:
`amplitude` : float
The amplitude (volume) of the wave, from 0.0 to 1.0.
Values outside of this range will be clamped.
"""
def __init__(self, amplitude=0.5):
self.amplitude = max(min(1.0, amplitude), 0)
def build_envelope(self, sample_rate, duration):
amplitude = self.amplitude
total_bytes = int(sample_rate * duration)
return [amplitude for _ in range(total_bytes)]
class LinearDecayEnvelope(Envelope):
"""A linearly decaying envelope.
This envelope linearly decays the amplitude from the peak value
to 0, over the length of the waveform.
:Parameters:
`peak` : float
The Initial peak value of the envelope, from 0.0 to 1.0.
Values outside of this range will be clamped.
"""
def __init__(self, peak=1.0):
self.peak = max(min(1.0, peak), 0)
def build_envelope(self, sample_rate, duration):
peak = self.peak
total_bytes = int(sample_rate * duration)
envelope = []
for i in range(total_bytes):
envelope.append((total_bytes - i) / total_bytes * peak)
return envelope
class ADSREnvelope(Envelope):
"""A four part Attack, Decay, Suspend, Release envelope.
This is a four part ADSR envelope. The attack, decay, and release
parameters should be provided in seconds. For example, a value of
0.1 would be 100ms. The sustain_amplitude parameter affects the
sustain volume. This defaults to a value of 0.5, but can be provided
on a scale from 0.0 to 1.0.
:Parameters:
`attack` : float
The attack time, in seconds.
`decay` : float
The decay time, in seconds.
`release` : float
The release time, in seconds.
`sustain_amplitude` : float
The sustain amplitude (volume), from 0.0 to 1.0.
"""
def __init__(self, attack, decay, release, sustain_amplitude=0.5):
self.attack = attack
self.decay = decay
self.release = release
self.sustain_amplitude = max(min(1.0, sustain_amplitude), 0)
def build_envelope(self, sample_rate, duration):
sustain_amplitude = self.sustain_amplitude
total_bytes = int(sample_rate * duration)
attack_bytes = int(sample_rate * self.attack)
decay_bytes = int(sample_rate * self.decay)
release_bytes = int(sample_rate * self.release)
sustain_bytes = total_bytes - attack_bytes - decay_bytes - release_bytes
decay_step = (1 - sustain_amplitude) / decay_bytes
release_step = sustain_amplitude / release_bytes
envelope = []
for i in range(1, attack_bytes + 1):
envelope.append(i / attack_bytes)
for i in range(1, decay_bytes + 1):
envelope.append(1 - (i * decay_step))
for i in range(1, sustain_bytes + 1):
envelope.append(sustain_amplitude)
for i in range(1, release_bytes + 1):
envelope.append(sustain_amplitude - (i * release_step))
return envelope
class TremoloEnvelope(Envelope):
"""A tremolo envelope, for modulation amplitude.
A tremolo envelope that modulates the amplitude of the
waveform with a sinusoidal pattern. The depth and rate
of modulation can be specified. Depth is calculated as
a percentage of the maximum amplitude. For example:
a depth of 0.2 and amplitude of 0.5 will fluctuate
the amplitude between 0.4 an 0.5.
:Parameters:
`depth` : float
The amount of fluctuation, from 0.0 to 1.0.
`rate` : float
The fluctuation frequency, in seconds.
`amplitude` : float
The peak amplitude (volume), from 0.0 to 1.0.
"""
def __init__(self, depth, rate, amplitude=0.5):
self.depth = max(min(1.0, depth), 0)
self.rate = rate
self.amplitude = max(min(1.0, amplitude), 0)
def build_envelope(self, sample_rate, duration):
total_bytes = int(sample_rate * duration)
period = total_bytes / duration
max_amplitude = self.amplitude
min_amplitude = max(0, (1 - self.depth) * self.amplitude)
step = (math.pi * 2) / period / self.rate
envelope = []
for i in range(total_bytes):
value = math.sin(step * i)
envelope.append(value * (max_amplitude - min_amplitude) + min_amplitude)
return envelope
class ProceduralSource(Source):
"""Base class for procedurally defined and generated waveforms.
:Parameters:
`duration` : float
The length, in seconds, of audio that you wish to generate.
`sample_rate` : int
Audio samples per second. (CD quality is 44100).
`sample_size` : int
The bit precision. Must be either 8 or 16.
"""
def __init__(self, duration, sample_rate=44800, sample_size=16, envelope=None):
self._duration = float(duration)
self.audio_format = AudioFormat(
channels=1,
sample_size=sample_size,
sample_rate=sample_rate)
self._offset = 0
self._sample_rate = sample_rate
self._sample_size = sample_size
self._bytes_per_sample = sample_size >> 3
self._bytes_per_second = self._bytes_per_sample * sample_rate
self._max_offset = int(self._bytes_per_second * self._duration)
self._envelope = envelope
if self._bytes_per_sample == 2:
self._max_offset &= 0xfffffffe
if not self._envelope:
self._envelope = FlatEnvelope(amplitude=1.0)
self._envelope_array = self._envelope.build_envelope(self._sample_rate, self._duration)
@property
def envelope(self):
return self._envelope
@envelope.setter
def envelope(self, envelope):
self._envelope = envelope
self._envelope_array = envelope.build_envelope(self._sample_rate, self._duration)
def get_audio_data(self, num_bytes):
"""Return `num_bytes` bytes of audio data."""
num_bytes = min(num_bytes, self._max_offset - self._offset)
if num_bytes <= 0:
return None
timestamp = float(self._offset) / self._bytes_per_second
duration = float(num_bytes) / self._bytes_per_second
data = self._generate_data(num_bytes, self._offset)
self._offset += num_bytes
return AudioData(data, num_bytes, timestamp, duration, [])
def _generate_data(self, num_bytes, offset):
"""Generate `num_bytes` bytes of data.
Return data as ctypes array or string.
"""
raise NotImplementedError('abstract')
def seek(self, timestamp):
self._offset = int(timestamp * self._bytes_per_second)
# Bound within duration
self._offset = min(max(self._offset, 0), self._max_offset)
# Align to sample
if self._bytes_per_sample == 2:
self._offset &= 0xfffffffe
def save(self, filename):
"""Save the audio to disk as a standard RIFF Wave.
A standard RIFF wave header will be added to the raw PCM
audio data when it is saved to disk.
:Parameters:
`filename` : str
The file name to save as.
"""
offset = self._offset
self.seek(0)
data = self.get_audio_data(self._max_offset).get_string_data()
header = struct.pack('<4sI8sIHHIIHH4sI',
b"RIFF",
len(data) + 44 - 8,
b"WAVEfmt ",
16, # Default for PCM
1, # Default for PCM
1, # Number of channels
self._sample_rate,
self._bytes_per_second,
self._bytes_per_sample,
self._sample_size,
b"data",
len(data))
with open(filename, "wb") as f:
f.write(header)
f.write(data)
self._offset = offset
class Silence(ProceduralSource):
"""A silent waveform."""
def _generate_data(self, num_bytes, offset):
if self._bytes_per_sample == 1:
return b'\127' * num_bytes
else:
return b'\0' * num_bytes
class WhiteNoise(ProceduralSource):
"""A white noise, random waveform."""
def _generate_data(self, num_bytes, offset):
return os.urandom(num_bytes)
class Sine(ProceduralSource):
"""A procedurally generated sinusoid waveform.
:Parameters:
`duration` : float
The length, in seconds, of audio that you wish to generate.
`frequency` : int
The frequency, in Hz of the waveform you wish to produce.
`sample_rate` : int
Audio samples per second. (CD quality is 44100).
`sample_size` : int
The bit precision. Must be either 8 or 16.
"""
def __init__(self, duration, frequency=440, **kwargs):
super(Sine, self).__init__(duration, **kwargs)
self.frequency = frequency
def _generate_data(self, num_bytes, offset):
if self._bytes_per_sample == 1:
start = offset
samples = num_bytes
bias = 127
amplitude = 127
data = (ctypes.c_ubyte * samples)()
else:
start = offset >> 1
samples = num_bytes >> 1
bias = 0
amplitude = 32767
data = (ctypes.c_short * samples)()
step = self.frequency * (math.pi * 2) / self.audio_format.sample_rate
envelope = self._envelope_array
env_offset = offset // self._bytes_per_sample
for i in range(samples):
data[i] = int(math.sin(step * (i + start)) *
amplitude * envelope[i+env_offset] + bias)
return data
class Triangle(ProceduralSource):
"""A procedurally generated triangle waveform.
:Parameters:
`duration` : float
The length, in seconds, of audio that you wish to generate.
`frequency` : int
The frequency, in Hz of the waveform you wish to produce.
`sample_rate` : int
Audio samples per second. (CD quality is 44100).
`sample_size` : int
The bit precision. Must be either 8 or 16.
"""
def __init__(self, duration, frequency=440, **kwargs):
super(Triangle, self).__init__(duration, **kwargs)
self.frequency = frequency
def _generate_data(self, num_bytes, offset):
# XXX TODO consider offset
if self._bytes_per_sample == 1:
samples = num_bytes
value = 127
maximum = 255
minimum = 0
data = (ctypes.c_ubyte * samples)()
else:
samples = num_bytes >> 1
value = 0
maximum = 32767
minimum = -32768
data = (ctypes.c_short * samples)()
step = (maximum - minimum) * 2 * self.frequency / self.audio_format.sample_rate
envelope = self._envelope_array
env_offset = offset // self._bytes_per_sample
for i in range(samples):
value += step
if value > maximum:
value = maximum - (value - maximum)
step = -step
if value < minimum:
value = minimum - (value - minimum)
step = -step
data[i] = int(value * envelope[i+env_offset])
return data
class Sawtooth(ProceduralSource):
"""A procedurally generated sawtooth waveform.
:Parameters:
`duration` : float
The length, in seconds, of audio that you wish to generate.
`frequency` : int
The frequency, in Hz of the waveform you wish to produce.
`sample_rate` : int
Audio samples per second. (CD quality is 44100).
`sample_size` : int
The bit precision. Must be either 8 or 16.
"""
def __init__(self, duration, frequency=440, **kwargs):
super(Sawtooth, self).__init__(duration, **kwargs)
self.frequency = frequency
def _generate_data(self, num_bytes, offset):
# XXX TODO consider offset
if self._bytes_per_sample == 1:
samples = num_bytes
value = 127
maximum = 255
minimum = 0
data = (ctypes.c_ubyte * samples)()
else:
samples = num_bytes >> 1
value = 0
maximum = 32767
minimum = -32768
data = (ctypes.c_short * samples)()
step = (maximum - minimum) * self.frequency / self._sample_rate
envelope = self._envelope_array
env_offset = offset // self._bytes_per_sample
for i in range(samples):
value += step
if value > maximum:
value = minimum + (value % maximum)
data[i] = int(value * envelope[i+env_offset])
return data
class Square(ProceduralSource):
"""A procedurally generated square (or pulse) waveform.
:Parameters:
`duration` : float
The length, in seconds, of audio that you wish to generate.
`frequency` : int
The frequency, in Hz of the waveform you wish to produce.
`sample_rate` : int
Audio samples per second. (CD quality is 44100).
`sample_size` : int
The bit precision. Must be either 8 or 16.
"""
def __init__(self, duration, frequency=440, **kwargs):
super(Square, self).__init__(duration, **kwargs)
self.frequency = frequency
def _generate_data(self, num_bytes, offset):
# XXX TODO consider offset
if self._bytes_per_sample == 1:
start = offset
samples = num_bytes
bias = 127
amplitude = 127
data = (ctypes.c_ubyte * samples)()
else:
start = offset >> 1
samples = num_bytes >> 1
bias = 0
amplitude = 32767
data = (ctypes.c_short * samples)()
half_period = self.audio_format.sample_rate / self.frequency / 2
envelope = self._envelope_array
env_offset = offset // self._bytes_per_sample
value = 1
count = 0
for i in range(samples):
if count >= half_period:
value = -value
count %= half_period
count += 1
data[i] = int(value * amplitude * envelope[i+env_offset] + bias)
return data
# class Noise(ProceduralSource):
# """A pseudo-random Noise waveform.
#
# :Parameters:
# `duration` : float
# The length, in seconds, of audio that you wish to generate.
# `frequency` : int
# The frequency, in Hz of the waveform you wish to produce.
# `sample_rate` : int
# Audio samples per second. (CD quality is 44100).
# `sample_size` : int
# The bit precision. Must be either 8 or 16.
# """
# def __init__(self, duration, frequency=440, **kwargs):
# super(Noise, self).__init__(duration, **kwargs)
# self.frequency = frequency
# self.lfsr = _LFSR([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1])
#
# def _generate_data(self, num_bytes, offset):
# # XXX TODO consider offset
# if self._bytes_per_sample == 1:
# start = offset
# samples = num_bytes
# bias = 0
# amplitude = 255
# data = (ctypes.c_ubyte * samples)()
# else:
# start = offset >> 1
# samples = num_bytes >> 1
# bias = -32768
# amplitude = 32767
# data = (ctypes.c_short * samples)()
# envelope = self._envelope_array
# env_offset = offset // self._bytes_per_sample
# period = self._sample_rate / self.frequency
# lfsr = self.lfsr
# lfsr.advance(start)
# counter = 0
# for i in range(samples):
# counter += 1
# if counter > period:
# lfsr.reset()
# counter = 0
# value = lfsr.get()
# data[i] = int(value * amplitude * envelope[i+env_offset] + bias)
# return data
class FM(ProceduralSource):
"""A procedurally generated FM waveform.
This is a simplistic frequency modulated waveform, based on the
concepts by John Chowning. Basic sine waves are used for both
frequency carrier and modulator inputs, of which the frequencies can
be provided. The modulation index, or amplitude, can also be adjusted.
:Parameters:
`duration` : float
The length, in seconds, of audio that you wish to generate.
`carrier` : int
The carrier frequency, in Hz.
`modulator` : int
The modulator frequency, in Hz.
`mod_index` : int
The modulation index.
`sample_rate` : int
Audio samples per second. (CD quality is 44100).
`sample_size` : int
The bit precision. Must be either 8 or 16.
"""
def __init__(self, duration, carrier=440, modulator=440, mod_index=1, **kwargs):
super(FM, self).__init__(duration, **kwargs)
self.carrier = carrier
self.modulator = modulator
self.mod_index = mod_index
def _generate_data(self, num_bytes, offset):
if self._bytes_per_sample == 1:
start = offset
samples = num_bytes
bias = 127
amplitude = 127
data = (ctypes.c_ubyte * samples)()
else:
start = offset >> 1
samples = num_bytes >> 1
bias = 0
amplitude = 32767
data = (ctypes.c_short * samples)()
car_step = 2 * math.pi * self.carrier
mod_step = 2 * math.pi * self.modulator
mod_index = self.mod_index
sample_rate = self._sample_rate
envelope = self._envelope_array
env_offset = offset // self._bytes_per_sample
# FM equation: sin((2 * pi * carrier) + sin(2 * pi * modulator))
for i in range(samples):
increment = (i + start) / sample_rate
data[i] = int(math.sin(car_step * increment +
mod_index * math.sin(mod_step * increment))
* amplitude * envelope[i+env_offset] + bias)
return data
class Digitar(ProceduralSource):
"""A procedurally generated guitar-like waveform.
A guitar-like waveform, based on the Karplus-Strong algorithm.
The sound is similar to a plucked guitar string. The resulting
sound decays over time, and so the actual length will vary
depending on the frequency. Lower frequencies require a longer
`length` parameter to prevent cutting off abruptly.
:Parameters:
`duration` : float
The length, in seconds, of audio that you wish to generate.
`frequency` : int
The frequency, in Hz of the waveform you wish to produce.
`decay` : float
The decay rate of the effect. Defaults to 0.996.
`sample_rate` : int
Audio samples per second. (CD quality is 44100).
`sample_size` : int
The bit precision. Must be either 8 or 16.
"""
def __init__(self, duration, frequency=440, decay=0.996, **kwargs):
super(Digitar, self).__init__(duration, **kwargs)
self.frequency = frequency
self.decay = decay
self.period = int(self._sample_rate / self.frequency)
def _advance(self, positions):
# XXX create fresh ring buffer, and advance if necessary.
period = self.period
random.seed(10)
ring_buffer = deque([random.uniform(-1, 1) for _ in range(period)], maxlen=period)
for _ in range(positions):
decay = self.decay
ring_buffer.append(decay * (ring_buffer[0] + ring_buffer[1]) / 2)
self.ring_buffer = ring_buffer
def _generate_data(self, num_bytes, offset):
if self._bytes_per_sample == 1:
start = offset
samples = num_bytes
bias = 127
amplitude = 127
data = (ctypes.c_ubyte * samples)()
else:
start = offset >> 1
samples = num_bytes >> 1
bias = 0
amplitude = 32767
data = (ctypes.c_short * samples)()
self._advance(start)
ring_buffer = self.ring_buffer
decay = self.decay
for i in range(samples):
data[i] = int(ring_buffer[0] * amplitude + bias)
ring_buffer.append(decay * (ring_buffer[0] + ring_buffer[1]) / 2)
return data
| 23,114 | 35.401575 | 95 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/pyglet/media/sources/riff.py
|
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
"""Simple Python-only RIFF reader, supports uncompressed WAV files.
"""
from __future__ import division
from builtins import object
# RIFF reference:
# http://www.saettler.com/RIFFMCI/riffmci.html
#
# More readable WAVE summaries:
#
# http://www.borg.com/~jglatt/tech/wave.htm
# http://www.sonicspot.com/guide/wavefiles.html
from pyglet.media.exceptions import MediaFormatException
from pyglet.media.sources.base import StreamingSource, AudioData, AudioFormat
from pyglet.compat import BytesIO, asbytes
import struct
WAVE_FORMAT_PCM = 0x0001
IBM_FORMAT_MULAW = 0x0101
IBM_FORMAT_ALAW = 0x0102
IBM_FORMAT_ADPCM = 0x0103
class RIFFFormatException(MediaFormatException):
pass
class WAVEFormatException(RIFFFormatException):
pass
class RIFFChunk(object):
header_fmt = '<4sL'
header_length = struct.calcsize(header_fmt)
def __init__(self, file, name, length, offset):
self.file = file
self.name = name
self.length = length
self.offset = offset
def get_data(self):
self.file.seek(self.offset)
return self.file.read(self.length)
def __repr__(self):
return '%s(%r, offset=%r, length=%r)' % (
self.__class__.__name__,
self.name,
self.offset,
self.length)
class RIFFForm(object):
_chunks = None
def __init__(self, file, offset):
self.file = file
self.offset = offset
def get_chunks(self):
if self._chunks:
return self._chunks
self._chunks = []
self.file.seek(self.offset)
offset = self.offset
while True:
header = self.file.read(RIFFChunk.header_length)
if not header:
break
name, length = struct.unpack(RIFFChunk.header_fmt, header)
offset += RIFFChunk.header_length
cls = self._chunk_types.get(name, RIFFChunk)
chunk = cls(self.file, name, length, offset)
self._chunks.append(chunk)
offset += length
if offset & 0x3 != 0:
offset = (offset | 0x3) + 1
self.file.seek(offset)
return self._chunks
def __repr__(self):
return '%s(offset=%r)' % (self.__class__.__name__, self.offset)
class RIFFType(RIFFChunk):
def __init__(self, *args, **kwargs):
super(RIFFType, self).__init__(*args, **kwargs)
self.file.seek(self.offset)
form = self.file.read(4)
if form != asbytes('WAVE'):
raise RIFFFormatException('Unsupported RIFF form "%s"' % form)
self.form = WaveForm(self.file, self.offset + 4)
class RIFFFile(RIFFForm):
_chunk_types = {
asbytes('RIFF'): RIFFType,
}
def __init__(self, file):
if not hasattr(file, 'seek'):
file = BytesIO(file.read())
super(RIFFFile, self).__init__(file, 0)
def get_wave_form(self):
chunks = self.get_chunks()
if len(chunks) == 1 and isinstance(chunks[0], RIFFType):
return chunks[0].form
class WaveFormatChunk(RIFFChunk):
def __init__(self, *args, **kwargs):
super(WaveFormatChunk, self).__init__(*args, **kwargs)
fmt = '<HHLLHH'
if struct.calcsize(fmt) != self.length:
raise RIFFFormatException('Size of format chunk is incorrect.')
(self.wFormatTag,
self.wChannels,
self.dwSamplesPerSec,
self.dwAvgBytesPerSec,
self.wBlockAlign,
self.wBitsPerSample) = struct.unpack(fmt, self.get_data())
class WaveDataChunk(RIFFChunk):
pass
class WaveForm(RIFFForm):
_chunk_types = {
asbytes('fmt '): WaveFormatChunk,
asbytes('data'): WaveDataChunk
}
def get_format_chunk(self):
for chunk in self.get_chunks():
if isinstance(chunk, WaveFormatChunk):
return chunk
def get_data_chunk(self):
for chunk in self.get_chunks():
if isinstance(chunk, WaveDataChunk):
return chunk
class WaveSource(StreamingSource):
def __init__(self, filename, file=None):
if file is None:
file = open(filename, 'rb')
self._file = file
# Read RIFF format, get format and data chunks
riff = RIFFFile(file)
wave_form = riff.get_wave_form()
if wave_form:
format = wave_form.get_format_chunk()
data_chunk = wave_form.get_data_chunk()
if not wave_form or not format or not data_chunk:
if not filename or filename.lower().endswith('.wav'):
raise WAVEFormatException('Not a WAVE file')
else:
raise WAVEFormatException(
'AVbin is required to decode compressed media')
if format.wFormatTag != WAVE_FORMAT_PCM:
raise WAVEFormatException('Unsupported WAVE format category')
if format.wBitsPerSample not in (8, 16):
raise WAVEFormatException('Unsupported sample bit size: %d' %
format.wBitsPerSample)
self.audio_format = AudioFormat(
channels=format.wChannels,
sample_size=format.wBitsPerSample,
sample_rate=format.dwSamplesPerSec)
self._duration = \
float(data_chunk.length) / self.audio_format.bytes_per_second
self._start_offset = data_chunk.offset
self._max_offset = data_chunk.length
self._offset = 0
self._file.seek(self._start_offset)
def get_audio_data(self, bytes):
bytes = min(bytes, self._max_offset - self._offset)
if not bytes:
return None
data = self._file.read(bytes)
self._offset += len(data)
timestamp = float(self._offset) / self.audio_format.bytes_per_second
duration = float(bytes) / self.audio_format.bytes_per_second
return AudioData(data, len(data), timestamp, duration, [])
def seek(self, timestamp):
offset = int(timestamp * self.audio_format.bytes_per_second)
# Bound within duration
offset = min(max(offset, 0), self._max_offset)
# Align to sample
if self.audio_format.bytes_per_sample == 2:
offset &= 0xfffffffe
elif self.audio_format.bytes_per_sample == 4:
offset &= 0xfffffffc
self._file.seek(offset + self._start_offset)
self._offset = offset
| 8,134 | 31.802419 | 78 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/pyglet/media/sources/__init__.py
|
"""Sources for media playback."""
# Collect public interface
from .loader import load, have_avbin
from .base import AudioFormat, VideoFormat, AudioData, SourceInfo
from .base import Source, StreamingSource, StaticSource, SourceGroup
# help the docs figure out where these are supposed to live (they live here)
__all__ = [
'load',
'have_avbin',
'AudioFormat',
'VideoFormat',
'AudioData',
'SourceInfo',
'Source',
'StreamingSource',
'StaticSource',
'SourceGroup',
]
| 485 | 22.142857 | 76 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/pyglet/media/sources/avbin.py
|
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
"""Use avbin to decode audio and video media.
"""
from __future__ import print_function
from __future__ import division
from builtins import range
from builtins import object
import struct
import ctypes
import threading
import time
import pyglet
from pyglet import image
import pyglet.lib
from pyglet.media.sources.base import \
StreamingSource, VideoFormat, AudioFormat, \
AudioData, SourceInfo
from pyglet.media.events import MediaEvent
from pyglet.media.exceptions import MediaFormatException
from pyglet.media.threads import WorkerThread
from pyglet.compat import asbytes, asbytes_filename
if pyglet.compat_platform.startswith('win') and struct.calcsize('P') == 8:
av = 'avbin64'
else:
av = 'avbin'
av = pyglet.lib.load_library(av)
AVBIN_RESULT_ERROR = -1
AVBIN_RESULT_OK = 0
AVbinResult = ctypes.c_int
AVBIN_STREAM_TYPE_UNKNOWN = 0
AVBIN_STREAM_TYPE_VIDEO = 1
AVBIN_STREAM_TYPE_AUDIO = 2
AVbinStreamType = ctypes.c_int
AVBIN_SAMPLE_FORMAT_U8 = 0
AVBIN_SAMPLE_FORMAT_S16 = 1
AVBIN_SAMPLE_FORMAT_S24 = 2
AVBIN_SAMPLE_FORMAT_S32 = 3
AVBIN_SAMPLE_FORMAT_FLOAT = 4
AVbinSampleFormat = ctypes.c_int
AVBIN_LOG_QUIET = -8
AVBIN_LOG_PANIC = 0
AVBIN_LOG_FATAL = 8
AVBIN_LOG_ERROR = 16
AVBIN_LOG_WARNING = 24
AVBIN_LOG_INFO = 32
AVBIN_LOG_VERBOSE = 40
AVBIN_LOG_DEBUG = 48
AVbinLogLevel = ctypes.c_int
AVbinFileP = ctypes.c_void_p
AVbinStreamP = ctypes.c_void_p
Timestamp = ctypes.c_int64
class AVbinFileInfo(ctypes.Structure):
_fields_ = [
('structure_size', ctypes.c_size_t),
('n_streams', ctypes.c_int),
('start_time', Timestamp),
('duration', Timestamp),
('title', ctypes.c_char * 512),
('author', ctypes.c_char * 512),
('copyright', ctypes.c_char * 512),
('comment', ctypes.c_char * 512),
('album', ctypes.c_char * 512),
('year', ctypes.c_int),
('track', ctypes.c_int),
('genre', ctypes.c_char * 32),
]
class _AVbinStreamInfoVideo8(ctypes.Structure):
_fields_ = [
('width', ctypes.c_uint),
('height', ctypes.c_uint),
('sample_aspect_num', ctypes.c_uint),
('sample_aspect_den', ctypes.c_uint),
('frame_rate_num', ctypes.c_uint),
('frame_rate_den', ctypes.c_uint),
]
class _AVbinStreamInfoAudio8(ctypes.Structure):
_fields_ = [
('sample_format', ctypes.c_int),
('sample_rate', ctypes.c_uint),
('sample_bits', ctypes.c_uint),
('channels', ctypes.c_uint),
]
class _AVbinStreamInfoUnion8(ctypes.Union):
_fields_ = [
('video', _AVbinStreamInfoVideo8),
('audio', _AVbinStreamInfoAudio8),
]
class AVbinStreamInfo8(ctypes.Structure):
_fields_ = [
('structure_size', ctypes.c_size_t),
('type', ctypes.c_int),
('u', _AVbinStreamInfoUnion8)
]
class AVbinPacket(ctypes.Structure):
_fields_ = [
('structure_size', ctypes.c_size_t),
('timestamp', Timestamp),
('stream_index', ctypes.c_int),
('data', ctypes.POINTER(ctypes.c_uint8)),
('size', ctypes.c_size_t),
]
AVbinLogCallback = ctypes.CFUNCTYPE(None,
ctypes.c_char_p, ctypes.c_int, ctypes.c_char_p)
av.avbin_get_version.restype = ctypes.c_int
av.avbin_get_ffmpeg_revision.restype = ctypes.c_int
av.avbin_get_audio_buffer_size.restype = ctypes.c_size_t
av.avbin_have_feature.restype = ctypes.c_int
av.avbin_have_feature.argtypes = [ctypes.c_char_p]
av.avbin_init.restype = AVbinResult
av.avbin_set_log_level.restype = AVbinResult
av.avbin_set_log_level.argtypes = [AVbinLogLevel]
av.avbin_set_log_callback.argtypes = [AVbinLogCallback]
av.avbin_open_filename.restype = AVbinFileP
av.avbin_open_filename.argtypes = [ctypes.c_char_p]
av.avbin_close_file.argtypes = [AVbinFileP]
av.avbin_seek_file.argtypes = [AVbinFileP, Timestamp]
av.avbin_file_info.argtypes = [AVbinFileP, ctypes.POINTER(AVbinFileInfo)]
av.avbin_stream_info.argtypes = [AVbinFileP, ctypes.c_int,
ctypes.POINTER(AVbinStreamInfo8)]
av.avbin_open_stream.restype = ctypes.c_void_p
av.avbin_open_stream.argtypes = [AVbinFileP, ctypes.c_int]
av.avbin_close_stream.argtypes = [AVbinStreamP]
av.avbin_read.argtypes = [AVbinFileP, ctypes.POINTER(AVbinPacket)]
av.avbin_read.restype = AVbinResult
av.avbin_decode_audio.restype = ctypes.c_int
av.avbin_decode_audio.argtypes = [AVbinStreamP,
ctypes.c_void_p, ctypes.c_size_t,
ctypes.c_void_p, ctypes.POINTER(ctypes.c_int)]
av.avbin_decode_video.restype = ctypes.c_int
av.avbin_decode_video.argtypes = [AVbinStreamP,
ctypes.c_void_p, ctypes.c_size_t,
ctypes.c_void_p]
if True:
# XXX lock all avbin calls. not clear from ffmpeg documentation if this
# is necessary. leaving it on while debugging to rule out the possiblity
# of a problem.
def synchronize(func, lock):
def f(*args):
lock.acquire()
result = func(*args)
lock.release()
return result
return f
_avbin_lock = threading.Lock()
for name in dir(av):
if name.startswith('avbin_'):
setattr(av, name, synchronize(getattr(av, name), _avbin_lock))
def get_version():
return av.avbin_get_version()
class AVbinException(MediaFormatException):
pass
def timestamp_from_avbin(timestamp):
return float(timestamp) / 1000000
def timestamp_to_avbin(timestamp):
return int(timestamp * 1000000)
class VideoPacket(object):
_next_id = 0
def __init__(self, packet):
self.timestamp = timestamp_from_avbin(packet.timestamp)
self.data = (ctypes.c_uint8 * packet.size)()
self.size = packet.size
ctypes.memmove(self.data, packet.data, self.size)
# Decoded image. 0 == not decoded yet; None == Error or discarded
self.image = 0
self.id = self._next_id
self.__class__._next_id += 1
class AVbinSource(StreamingSource):
def __init__(self, filename, file=None):
if file is not None:
raise NotImplementedError('Loading from file stream is not supported')
self._file = av.avbin_open_filename(asbytes_filename(filename))
if not self._file:
raise AVbinException('Could not open "%s"' % filename)
self._video_stream = None
self._video_stream_index = -1
self._audio_stream = None
self._audio_stream_index = -1
file_info = AVbinFileInfo()
file_info.structure_size = ctypes.sizeof(file_info)
av.avbin_file_info(self._file, ctypes.byref(file_info))
self._duration = timestamp_from_avbin(file_info.duration)
self.info = SourceInfo()
self.info.title = file_info.title
self.info.author = file_info.author
self.info.copyright = file_info.copyright
self.info.comment = file_info.comment
self.info.album = file_info.album
self.info.year = file_info.year
self.info.track = file_info.track
self.info.genre = file_info.genre
# Pick the first video and audio streams found, ignore others.
for i in range(file_info.n_streams):
info = AVbinStreamInfo8()
info.structure_size = ctypes.sizeof(info)
av.avbin_stream_info(self._file, i, info)
if (info.type == AVBIN_STREAM_TYPE_VIDEO and
not self._video_stream):
stream = av.avbin_open_stream(self._file, i)
if not stream:
continue
self.video_format = VideoFormat(
width=info.u.video.width,
height=info.u.video.height)
if info.u.video.sample_aspect_num != 0:
self.video_format.sample_aspect = (
float(info.u.video.sample_aspect_num) /
info.u.video.sample_aspect_den)
if _have_frame_rate:
self.video_format.frame_rate = (
float(info.u.video.frame_rate_num) /
info.u.video.frame_rate_den)
self._video_stream = stream
self._video_stream_index = i
elif (info.type == AVBIN_STREAM_TYPE_AUDIO and
info.u.audio.sample_bits in (8, 16) and
info.u.audio.channels in (1, 2) and
not self._audio_stream):
stream = av.avbin_open_stream(self._file, i)
if not stream:
continue
self.audio_format = AudioFormat(
channels=info.u.audio.channels,
sample_size=info.u.audio.sample_bits,
sample_rate=info.u.audio.sample_rate)
self._audio_stream = stream
self._audio_stream_index = i
self._packet = AVbinPacket()
self._packet.structure_size = ctypes.sizeof(self._packet)
self._packet.stream_index = -1
self._events = []
# Timestamp of last video packet added to decoder queue.
self._video_timestamp = 0
self._buffered_audio_data = []
if self.audio_format:
self._audio_buffer = \
(ctypes.c_uint8 * av.avbin_get_audio_buffer_size())()
if self.video_format:
self._video_packets = []
self._decode_thread = WorkerThread()
self._decode_thread.start()
self._condition = threading.Condition()
def __del__(self):
if _debug:
print('del avbin source')
try:
if self._video_stream:
av.avbin_close_stream(self._video_stream)
if self._audio_stream:
av.avbin_close_stream(self._audio_stream)
av.avbin_close_file(self._file)
except:
pass
def delete(self):
if self.video_format:
self._decode_thread.stop()
def seek(self, timestamp):
if _debug:
print('AVbin seek', timestamp)
av.avbin_seek_file(self._file, timestamp_to_avbin(timestamp))
self._audio_packet_size = 0
del self._events[:]
del self._buffered_audio_data[:]
if self.video_format:
self._video_timestamp = 0
self._condition.acquire()
for packet in self._video_packets:
packet.image = None
self._condition.notify()
self._condition.release()
del self._video_packets[:]
self._decode_thread.clear_jobs()
def _get_packet(self):
# Read a packet into self._packet. Returns True if OK, False if no
# more packets are in stream.
return av.avbin_read(self._file, self._packet) == AVBIN_RESULT_OK
def _process_packet(self):
# Returns (packet_type, packet), where packet_type = 'video' or
# 'audio'; and packet is VideoPacket or AudioData. In either case,
# packet is buffered or queued for decoding; no further action is
# necessary. Returns (None, None) if packet was neither type.
if self._packet.stream_index == self._video_stream_index:
if self._packet.timestamp < 0:
# XXX TODO
# AVbin needs hack to decode timestamp for B frames in
# some containers (OGG?). See
# http://www.dranger.com/ffmpeg/tutorial05.html
# For now we just drop these frames.
return None, None
video_packet = VideoPacket(self._packet)
if _debug:
print('Created and queued frame %d (%f)' % \
(video_packet.id, video_packet.timestamp))
self._video_timestamp = max(self._video_timestamp,
video_packet.timestamp)
self._video_packets.append(video_packet)
self._decode_thread.put_job(
lambda: self._decode_video_packet(video_packet))
return 'video', video_packet
elif self._packet.stream_index == self._audio_stream_index:
audio_data = self._decode_audio_packet()
if audio_data:
if _debug:
print('Got an audio packet at', audio_data.timestamp)
self._buffered_audio_data.append(audio_data)
return 'audio', audio_data
return None, None
def get_audio_data(self, bytes):
try:
audio_data = self._buffered_audio_data.pop(0)
audio_data_timeend = audio_data.timestamp + audio_data.duration
except IndexError:
audio_data = None
audio_data_timeend = self._video_timestamp + 1
if _debug:
print('get_audio_data')
have_video_work = False
# Keep reading packets until we have an audio packet and all the
# associated video packets have been enqueued on the decoder thread.
while not audio_data or (
self._video_stream and self._video_timestamp < audio_data_timeend):
if not self._get_packet():
break
packet_type, packet = self._process_packet()
if packet_type == 'video':
have_video_work = True
elif not audio_data and packet_type == 'audio':
audio_data = self._buffered_audio_data.pop(0)
if _debug:
print('Got requested audio packet at', audio_data.timestamp)
audio_data_timeend = audio_data.timestamp + audio_data.duration
if have_video_work:
# Give decoder thread a chance to run before we return this audio
# data.
time.sleep(0)
if not audio_data:
if _debug:
print('get_audio_data returning None')
return None
while self._events and self._events[0].timestamp <= audio_data_timeend:
event = self._events.pop(0)
if event.timestamp >= audio_data.timestamp:
event.timestamp -= audio_data.timestamp
audio_data.events.append(event)
if _debug:
print('get_audio_data returning ts %f with events' % \
audio_data.timestamp, audio_data.events)
print('remaining events are', self._events)
return audio_data
def _decode_audio_packet(self):
packet = self._packet
size_out = ctypes.c_int(len(self._audio_buffer))
while True:
audio_packet_ptr = ctypes.cast(packet.data, ctypes.c_void_p)
audio_packet_size = packet.size
used = av.avbin_decode_audio(self._audio_stream,
audio_packet_ptr, audio_packet_size,
self._audio_buffer, size_out)
if used < 0:
self._audio_packet_size = 0
break
audio_packet_ptr.value += used
audio_packet_size -= used
if size_out.value <= 0:
continue
# XXX how did this ever work? replaced with copy below
# buffer = ctypes.string_at(self._audio_buffer, size_out)
# XXX to actually copy the data.. but it never used to crash, so
# maybe I'm missing something
buffer = ctypes.create_string_buffer(size_out.value)
ctypes.memmove(buffer, self._audio_buffer, len(buffer))
buffer = buffer.raw
duration = float(len(buffer)) / self.audio_format.bytes_per_second
self._audio_packet_timestamp = \
timestamp = timestamp_from_avbin(packet.timestamp)
return AudioData(buffer, len(buffer), timestamp, duration, [])
def _decode_video_packet(self, packet):
width = self.video_format.width
height = self.video_format.height
pitch = width * 3
buffer = (ctypes.c_uint8 * (pitch * height))()
result = av.avbin_decode_video(self._video_stream,
packet.data, packet.size,
buffer)
if result < 0:
image_data = None
else:
image_data = image.ImageData(width, height, 'RGB', buffer, pitch)
packet.image = image_data
# Notify get_next_video_frame() that another one is ready.
self._condition.acquire()
self._condition.notify()
self._condition.release()
def _ensure_video_packets(self):
"""Process packets until a video packet has been queued (and begun
decoding). Return False if EOS.
"""
if not self._video_packets:
if _debug:
print('No video packets...')
# Read ahead until we have another video packet
self._get_packet()
packet_type, _ = self._process_packet()
while packet_type and packet_type != 'video':
self._get_packet()
packet_type, _ = self._process_packet()
if not packet_type:
return False
if _debug:
print('Queued packet', _)
return True
def get_next_video_timestamp(self):
if not self.video_format:
return
if self._ensure_video_packets():
if _debug:
print('Next video timestamp is', self._video_packets[0].timestamp)
return self._video_packets[0].timestamp
def get_next_video_frame(self):
if not self.video_format:
return
if self._ensure_video_packets():
packet = self._video_packets.pop(0)
if _debug:
print('Waiting for', packet)
# Block until decoding is complete
self._condition.acquire()
while packet.image == 0:
self._condition.wait()
self._condition.release()
if _debug:
print('Returning', packet)
return packet.image
av.avbin_init()
if pyglet.options['debug_media']:
_debug = True
av.avbin_set_log_level(AVBIN_LOG_DEBUG)
else:
_debug = False
av.avbin_set_log_level(AVBIN_LOG_QUIET)
_have_frame_rate = av.avbin_have_feature(asbytes('frame_rate'))
| 19,942 | 33.865385 | 82 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/pyglet/media/sources/loader.py
|
from __future__ import print_function
from builtins import object
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
from abc import ABCMeta, abstractmethod
import pyglet
from .base import StaticSource
from future.utils import with_metaclass
_debug = pyglet.options['debug_media']
def load(filename, file=None, streaming=True):
"""Load a source from a file.
Currently the `file` argument is not supported; media files must exist
as real paths.
:Parameters:
`filename` : str
Filename of the media file to load.
`file` : file-like object
Not yet supported.
`streaming` : bool
If False, a :py:class:`~pyglet.media.StaticSource` will be returned; otherwise (default) a
`StreamingSource` is created.
:rtype: `Source`
"""
source = get_source_loader().load(filename, file)
if not streaming:
source = StaticSource(source)
return source
class AbstractSourceLoader(with_metaclass(ABCMeta, object)):
@abstractmethod
def load(self, filename, file):
pass
class AVbinSourceLoader(AbstractSourceLoader):
def load(self, filename, file):
from .avbin import AVbinSource
return AVbinSource(filename, file)
class RIFFSourceLoader(AbstractSourceLoader):
def load(self, filename, file):
from .riff import WaveSource
return WaveSource(filename, file)
def get_source_loader():
global _source_loader
if _source_loader is not None:
return _source_loader
if have_avbin():
_source_loader = AVbinSourceLoader()
if _debug:
print('AVbin available, using to load media files')
else:
_source_loader = RIFFSourceLoader()
if _debug:
print('AVbin not available. Only supporting wave files.')
return _source_loader
_source_loader = None
def have_avbin():
"""Returns ``True`` iff AVBin is installed and accessible on the user's
system.
"""
global _have_avbin
if _have_avbin is None:
try:
from .avbin import AVbinSource
_have_avbin = True
except ImportError:
_have_avbin = False
return _have_avbin
_have_avbin = None
| 3,901 | 30.983607 | 102 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/pyglet/graphics/vertexbuffer.py
|
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
# $Id:$
'''Byte abstractions of Vertex Buffer Objects and vertex arrays.
Use :py:func:`create_buffer` or :py:func:`create_mappable_buffer` to create a
Vertex Buffer Object, or a vertex array if VBOs are not supported by the
current context.
Buffers can optionally be created "mappable" (incorporating the
:py:class:`AbstractMappable` mix-in). In this case the buffer provides a
:py:meth:`~AbstractMappable.get_region` method which provides the most
efficient path for updating partial data within the buffer.
'''
from builtins import range
from builtins import object
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import ctypes
import sys
import pyglet
from pyglet.gl import *
_enable_vbo = pyglet.options['graphics_vbo']
# Enable workaround permanently if any VBO is created on a context that has
# this workaround. (On systems with multiple contexts where one is
# unaffected, the workaround will be enabled unconditionally on all of the
# contexts anyway. This is completely unlikely anyway).
_workaround_vbo_finish = False
def create_buffer(size,
target=GL_ARRAY_BUFFER,
usage=GL_DYNAMIC_DRAW,
vbo=True):
'''Create a buffer of vertex data.
:Parameters:
`size` : int
Size of the buffer, in bytes
`target` : int
OpenGL target buffer
`usage` : int
OpenGL usage constant
`vbo` : bool
True if a `VertexBufferObject` should be created if the driver
supports it; otherwise only a `VertexArray` is created.
:rtype: `AbstractBuffer`
'''
from pyglet import gl
if (vbo and
gl_info.have_version(1, 5) and
_enable_vbo and
not gl.current_context._workaround_vbo):
return VertexBufferObject(size, target, usage)
else:
return VertexArray(size)
def create_mappable_buffer(size,
target=GL_ARRAY_BUFFER,
usage=GL_DYNAMIC_DRAW,
vbo=True):
'''Create a mappable buffer of vertex data.
:Parameters:
`size` : int
Size of the buffer, in bytes
`target` : int
OpenGL target buffer
`usage` : int
OpenGL usage constant
`vbo` : bool
True if a :py:class:`VertexBufferObject` should be created if the driver
supports it; otherwise only a :py:class:`VertexArray` is created.
:rtype: :py:class:`AbstractBuffer` with :py:class:`AbstractMappable`
'''
from pyglet import gl
if (vbo and
gl_info.have_version(1, 5) and
_enable_vbo and
not gl.current_context._workaround_vbo):
return MappableVertexBufferObject(size, target, usage)
else:
return VertexArray(size)
class AbstractBuffer(object):
'''Abstract buffer of byte data.
:Ivariables:
`size` : int
Size of buffer, in bytes
`ptr` : int
Memory offset of the buffer, as used by the ``glVertexPointer``
family of functions
`target` : int
OpenGL buffer target, for example ``GL_ARRAY_BUFFER``
`usage` : int
OpenGL buffer usage, for example ``GL_DYNAMIC_DRAW``
'''
ptr = 0
size = 0
def bind(self):
'''Bind this buffer to its OpenGL target.'''
raise NotImplementedError('abstract')
def unbind(self):
'''Reset the buffer's OpenGL target.'''
raise NotImplementedError('abstract')
def set_data(self, data):
'''Set the entire contents of the buffer.
:Parameters:
`data` : sequence of int or ctypes pointer
The byte array to set.
'''
raise NotImplementedError('abstract')
def set_data_region(self, data, start, length):
'''Set part of the buffer contents.
:Parameters:
`data` : sequence of int or ctypes pointer
The byte array of data to set
`start` : int
Offset to start replacing data
`length` : int
Length of region to replace
'''
raise NotImplementedError('abstract')
def map(self, invalidate=False):
'''Map the entire buffer into system memory.
The mapped region must be subsequently unmapped with `unmap` before
performing any other operations on the buffer.
:Parameters:
`invalidate` : bool
If True, the initial contents of the mapped block need not
reflect the actual contents of the buffer.
:rtype: ``POINTER(ctypes.c_ubyte)``
:return: Pointer to the mapped block in memory
'''
raise NotImplementedError('abstract')
def unmap(self):
'''Unmap a previously mapped memory block.'''
raise NotImplementedError('abstract')
def resize(self, size):
'''Resize the buffer to a new size.
:Parameters:
`size` : int
New size of the buffer, in bytes
'''
def delete(self):
'''Delete this buffer, reducing system resource usage.'''
raise NotImplementedError('abstract')
class AbstractMappable(object):
def get_region(self, start, size, ptr_type):
'''Map a region of the buffer into a ctypes array of the desired
type. This region does not need to be unmapped, but will become
invalid if the buffer is resized.
Note that although a pointer type is required, an array is mapped.
For example::
get_region(0, ctypes.sizeof(c_int) * 20, ctypes.POINTER(c_int * 20))
will map bytes 0 to 80 of the buffer to an array of 20 ints.
Changes to the array may not be recognised until the region's
:py:meth:`AbstractBufferRegion.invalidate` method is called.
:Parameters:
`start` : int
Offset into the buffer to map from, in bytes
`size` : int
Size of the buffer region to map, in bytes
`ptr_type` : ctypes pointer type
Pointer type describing the array format to create
:rtype: :py:class:`AbstractBufferRegion`
'''
raise NotImplementedError('abstract')
class VertexArray(AbstractBuffer, AbstractMappable):
'''A ctypes implementation of a vertex array.
Many of the methods on this class are effectively no-op's, such as
:py:meth:`bind`, :py:meth:`unbind`, :py:meth:`map`, :py:meth:`unmap` and
:py:meth:`delete`; they exist in order to present
a consistent interface with :py:class:`VertexBufferObject`.
This buffer type is also mappable, and so :py:meth:`get_region` can be used.
'''
def __init__(self, size):
self.size = size
self.array = (ctypes.c_byte * size)()
self.ptr = ctypes.cast(self.array, ctypes.c_void_p).value
def bind(self):
pass
def unbind(self):
pass
def set_data(self, data):
ctypes.memmove(self.ptr, data, self.size)
def set_data_region(self, data, start, length):
ctypes.memmove(self.ptr + start, data, length)
def map(self, invalidate=False):
return self.array
def unmap(self):
pass
def get_region(self, start, size, ptr_type):
array = ctypes.cast(self.ptr + start, ptr_type).contents
return VertexArrayRegion(array)
def delete(self):
pass
def resize(self, size):
array = (ctypes.c_byte * size)()
ctypes.memmove(array, self.array, min(size, self.size))
self.size = size
self.array = array
self.ptr = ctypes.cast(self.array, ctypes.c_void_p).value
class VertexBufferObject(AbstractBuffer):
'''Lightweight representation of an OpenGL VBO.
The data in the buffer is not replicated in any system memory (unless it
is done so by the video driver). While this can improve memory usage and
possibly performance, updates to the buffer are relatively slow.
This class does not implement :py:class:`AbstractMappable`, and so has no
:py:meth:`~AbstractMappable.get_region` method. See
:py:class:`MappableVertexBufferObject` for a VBO class
that does implement :py:meth:`~AbstractMappable.get_region`.
'''
def __init__(self, size, target, usage):
self.size = size
self.target = target
self.usage = usage
self._context = pyglet.gl.current_context
id = GLuint()
glGenBuffers(1, id)
self.id = id.value
glPushClientAttrib(GL_CLIENT_VERTEX_ARRAY_BIT)
glBindBuffer(target, self.id)
glBufferData(target, self.size, None, self.usage)
glPopClientAttrib()
global _workaround_vbo_finish
if pyglet.gl.current_context._workaround_vbo_finish:
_workaround_vbo_finish = True
def bind(self):
glBindBuffer(self.target, self.id)
def unbind(self):
glBindBuffer(self.target, 0)
def set_data(self, data):
glPushClientAttrib(GL_CLIENT_VERTEX_ARRAY_BIT)
glBindBuffer(self.target, self.id)
glBufferData(self.target, self.size, data, self.usage)
glPopClientAttrib()
def set_data_region(self, data, start, length):
glPushClientAttrib(GL_CLIENT_VERTEX_ARRAY_BIT)
glBindBuffer(self.target, self.id)
glBufferSubData(self.target, start, length, data)
glPopClientAttrib()
def map(self, invalidate=False):
glPushClientAttrib(GL_CLIENT_VERTEX_ARRAY_BIT)
glBindBuffer(self.target, self.id)
if invalidate:
glBufferData(self.target, self.size, None, self.usage)
ptr = ctypes.cast(glMapBuffer(self.target, GL_WRITE_ONLY),
ctypes.POINTER(ctypes.c_byte * self.size)).contents
glPopClientAttrib()
return ptr
def unmap(self):
glPushClientAttrib(GL_CLIENT_VERTEX_ARRAY_BIT)
glUnmapBuffer(self.target)
glPopClientAttrib()
def __del__(self):
try:
if self.id is not None:
self._context.delete_buffer(self.id)
except:
pass
def delete(self):
id = GLuint(self.id)
glDeleteBuffers(1, id)
self.id = None
def resize(self, size):
# Map, create a copy, then reinitialize.
temp = (ctypes.c_byte * size)()
glPushClientAttrib(GL_CLIENT_VERTEX_ARRAY_BIT)
glBindBuffer(self.target, self.id)
data = glMapBuffer(self.target, GL_READ_ONLY)
ctypes.memmove(temp, data, min(size, self.size))
glUnmapBuffer(self.target)
self.size = size
glBufferData(self.target, self.size, temp, self.usage)
glPopClientAttrib()
class MappableVertexBufferObject(VertexBufferObject, AbstractMappable):
'''A VBO with system-memory backed store.
Updates to the data via :py:meth:`set_data`, :py:meth:`set_data_region` and
:py:meth:`map` will be held in local memory until :py:meth:`bind` is
called. The advantage is that fewer OpenGL calls are needed, increasing
performance.
There may also be less performance penalty for resizing this buffer.
Updates to data via :py:meth:`map` are committed immediately.
'''
def __init__(self, size, target, usage):
super(MappableVertexBufferObject, self).__init__(size, target, usage)
self.data = (ctypes.c_byte * size)()
self.data_ptr = ctypes.cast(self.data, ctypes.c_void_p).value
self._dirty_min = sys.maxsize
self._dirty_max = 0
def bind(self):
# Commit pending data
super(MappableVertexBufferObject, self).bind()
size = self._dirty_max - self._dirty_min
if size > 0:
if size == self.size:
glBufferData(self.target, self.size, self.data, self.usage)
else:
glBufferSubData(self.target, self._dirty_min, size,
self.data_ptr + self._dirty_min)
self._dirty_min = sys.maxsize
self._dirty_max = 0
def set_data(self, data):
super(MappableVertexBufferObject, self).set_data(data)
ctypes.memmove(self.data, data, self.size)
self._dirty_min = 0
self._dirty_max = self.size
def set_data_region(self, data, start, length):
ctypes.memmove(self.data_ptr + start, data, length)
self._dirty_min = min(start, self._dirty_min)
self._dirty_max = max(start + length, self._dirty_max)
def map(self, invalidate=False):
self._dirty_min = 0
self._dirty_max = self.size
return self.data
def unmap(self):
pass
def get_region(self, start, size, ptr_type):
array = ctypes.cast(self.data_ptr + start, ptr_type).contents
return VertexBufferObjectRegion(self, start, start + size, array)
def resize(self, size):
data = (ctypes.c_byte * size)()
ctypes.memmove(data, self.data, min(size, self.size))
self.data = data
self.data_ptr = ctypes.cast(self.data, ctypes.c_void_p).value
self.size = size
glPushClientAttrib(GL_CLIENT_VERTEX_ARRAY_BIT)
glBindBuffer(self.target, self.id)
glBufferData(self.target, self.size, self.data, self.usage)
glPopClientAttrib()
self._dirty_min = sys.maxsize
self._dirty_max = 0
class AbstractBufferRegion(object):
'''A mapped region of a buffer.
Buffer regions are obtained using :py:meth:`~AbstractMappable.get_region`.
:Ivariables:
`array` : ctypes array
Array of data, of the type and count requested by
:py:meth:`~AbstractMappable.get_region`.
'''
def invalidate(self):
'''Mark this region as changed.
The buffer may not be updated with the latest contents of the
array until this method is called. (However, it may not be updated
until the next time the buffer is used, for efficiency).
'''
pass
class VertexBufferObjectRegion(AbstractBufferRegion):
'''A mapped region of a VBO.'''
def __init__(self, buffer, start, end, array):
self.buffer = buffer
self.start = start
self.end = end
self.array = array
def invalidate(self):
buffer = self.buffer
buffer._dirty_min = min(buffer._dirty_min, self.start)
buffer._dirty_max = max(buffer._dirty_max, self.end)
class VertexArrayRegion(AbstractBufferRegion):
'''A mapped region of a vertex array.
The :py:meth:`~AbstractBufferRegion.invalidate` method is a no-op but is
provided in order to present a consistent interface with
:py:meth:`VertexBufferObjectRegion`.
'''
def __init__(self, array):
self.array = array
class IndirectArrayRegion(AbstractBufferRegion):
'''A mapped region in which data elements are not necessarily contiguous.
This region class is used to wrap buffer regions in which the data
must be accessed with some stride. For example, in an interleaved buffer
this region can be used to access a single interleaved component as if the
data was contiguous.
'''
def __init__(self, region, size, component_count, component_stride):
'''Wrap a buffer region.
Use the `component_count` and `component_stride` parameters to specify
the data layout of the encapsulated region. For example, if RGBA
data is to be accessed as if it were packed RGB, ``component_count``
would be set to 3 and ``component_stride`` to 4. If the region
contains 10 RGBA tuples, the ``size`` parameter is ``3 * 10 = 30``.
:Parameters:
`region` : `AbstractBufferRegion`
The region with interleaved data
`size` : int
The number of elements that this region will provide access to.
`component_count` : int
The number of elements that are contiguous before some must
be skipped.
`component_stride` : int
The number of elements of interleaved data separating
the contiguous sections.
'''
self.region = region
self.size = size
self.count = component_count
self.stride = component_stride
self.array = self
def __repr__(self):
return 'IndirectArrayRegion(size=%d, count=%d, stride=%d)' % (
self.size, self.count, self.stride)
def __getitem__(self, index):
count = self.count
if not isinstance(index, slice):
elem = index // count
j = index % count
return self.region.array[elem * self.stride + j]
start = index.start or 0
stop = index.stop
step = index.step or 1
if start < 0:
start = self.size + start
if stop is None:
stop = self.size
elif stop < 0:
stop = self.size + stop
assert step == 1 or step % count == 0, \
'Step must be multiple of component count'
data_start = (start // count) * self.stride + start % count
data_stop = (stop // count) * self.stride + stop % count
data_step = step * self.stride
# TODO stepped getitem is probably wrong, see setitem for correct.
value_step = step * count
# ctypes does not support stepped slicing, so do the work in a list
# and copy it back.
data = self.region.array[:]
value = [0] * ((stop - start) // step)
stride = self.stride
for i in range(count):
value[i::value_step] = \
data[data_start + i:data_stop + i:data_step]
return value
def __setitem__(self, index, value):
count = self.count
if not isinstance(index, slice):
elem = index // count
j = index % count
self.region.array[elem * self.stride + j] = value
return
start = index.start or 0
stop = index.stop
step = index.step or 1
if start < 0:
start = self.size + start
if stop is None:
stop = self.size
elif stop < 0:
stop = self.size + stop
assert step == 1 or step % count == 0, \
'Step must be multiple of component count'
data_start = (start // count) * self.stride + start % count
data_stop = (stop // count) * self.stride + stop % count
# ctypes does not support stepped slicing, so do the work in a list
# and copy it back.
data = self.region.array[:]
if step == 1:
data_step = self.stride
value_step = count
for i in range(count):
data[data_start + i:data_stop + i:data_step] = \
value[i::value_step]
else:
data_step = (step // count) * self.stride
data[data_start:data_stop:data_step] = value
self.region.array[:] = data
def invalidate(self):
self.region.invalidate()
| 20,803 | 33.386777 | 84 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/pyglet/graphics/vertexattribute.py
|
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
# $Id:$
'''Access byte arrays as arrays of vertex attributes.
Use :py:func:`create_attribute` to create an attribute accessor given a
simple format string. Alternatively, the classes may be constructed directly.
Attribute format strings
========================
An attribute format string specifies the format of a vertex attribute. Format
strings are accepted by the :py:func:`create_attribute` function as well as most
methods in the :py:mod:`pyglet.graphics` module.
Format strings have the following (BNF) syntax::
attribute ::= ( name | index 'g' 'n'? | texture 't' ) count type
``name`` describes the vertex attribute, and is one of the following
constants for the predefined attributes:
``c``
Vertex color
``e``
Edge flag
``f``
Fog coordinate
``n``
Normal vector
``s``
Secondary color
``t``
Texture coordinate
``v``
Vertex coordinate
You can alternatively create a generic indexed vertex attribute by
specifying its index in decimal followed by the constant ``g``. For
example, ``0g`` specifies the generic vertex attribute with index 0.
If the optional constant ``n`` is present after the ``g``, the
attribute is normalised to the range ``[0, 1]`` or ``[-1, 1]`` within
the range of the data type.
Texture coordinates for multiple texture units can be specified with the
texture number before the constant 't'. For example, ``1t`` gives the
texture coordinate attribute for texture unit 1.
``count`` gives the number of data components in the attribute. For
example, a 3D vertex position has a count of 3. Some attributes
constrain the possible counts that can be used; for example, a normal
vector must have a count of 3.
``type`` gives the data type of each component of the attribute. The
following types can be used:
``b``
``GLbyte``
``B``
``GLubyte``
``s``
``GLshort``
``S``
``GLushort``
``i``
``GLint``
``I``
``GLuint``
``f``
``GLfloat``
``d``
``GLdouble``
Some attributes constrain the possible data types; for example,
normal vectors must use one of the signed data types. The use of
some data types, while not illegal, may have severe performance
concerns. For example, the use of ``GLdouble`` is discouraged,
and colours should be specified with ``GLubyte``.
Whitespace is prohibited within the format string.
Some examples follow:
``v3f``
3-float vertex position
``c4b``
4-byte colour
``1eb``
Edge flag
``0g3f``
3-float generic vertex attribute 0
``1gn1i``
Integer generic vertex attribute 1, normalized to [-1, 1]
``2gn4B``
4-byte generic vertex attribute 2, normalized to [0, 1] (because
the type is unsigned)
``3t2f``
2-float texture coordinate for texture unit 3.
'''
from builtins import object
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import ctypes
import re
from pyglet.gl import *
from pyglet.graphics import vertexbuffer
_c_types = {
GL_BYTE: ctypes.c_byte,
GL_UNSIGNED_BYTE: ctypes.c_ubyte,
GL_SHORT: ctypes.c_short,
GL_UNSIGNED_SHORT: ctypes.c_ushort,
GL_INT: ctypes.c_int,
GL_UNSIGNED_INT: ctypes.c_uint,
GL_FLOAT: ctypes.c_float,
GL_DOUBLE: ctypes.c_double,
}
_gl_types = {
'b': GL_BYTE,
'B': GL_UNSIGNED_BYTE,
's': GL_SHORT,
'S': GL_UNSIGNED_SHORT,
'i': GL_INT,
'I': GL_UNSIGNED_INT,
'f': GL_FLOAT,
'd': GL_DOUBLE,
}
_attribute_format_re = re.compile(r'''
(?P<name>
[cefnstv] |
(?P<generic_index>[0-9]+) g (?P<generic_normalized>n?) |
(?P<texcoord_texture>[0-9]+) t)
(?P<count>[1234])
(?P<type>[bBsSiIfd])
''', re.VERBOSE)
_attribute_cache = {}
def _align(v, align):
return ((v - 1) & ~(align - 1)) + align
def interleave_attributes(attributes):
'''Interleave attribute offsets.
Adjusts the offsets and strides of the given attributes so that
they are interleaved. Alignment constraints are respected.
:Parameters:
`attributes` : sequence of `AbstractAttribute`
Attributes to interleave in-place.
'''
stride = 0
max_size = 0
for attribute in attributes:
stride = _align(stride, attribute.align)
attribute.offset = stride
stride += attribute.size
max_size = max(max_size, attribute.size)
stride = _align(stride, max_size)
for attribute in attributes:
attribute.stride = stride
def serialize_attributes(count, attributes):
'''Serialize attribute offsets.
Adjust the offsets of the given attributes so that they are
packed serially against each other for `count` vertices.
:Parameters:
`count` : int
Number of vertices.
`attributes` : sequence of `AbstractAttribute`
Attributes to serialize in-place.
'''
offset = 0
for attribute in attributes:
offset = _align(offset, attribute.align)
attribute.offset = offset
offset += count * attribute.stride
def create_attribute(format):
'''Create a vertex attribute description from a format string.
The initial stride and offset of the attribute will be 0.
:Parameters:
`format` : str
Attribute format string. See the module summary for details.
:rtype: `AbstractAttribute`
'''
try:
cls, args = _attribute_cache[format]
return cls(*args)
except KeyError:
pass
match = _attribute_format_re.match(format)
assert match, 'Invalid attribute format %r' % format
count = int(match.group('count'))
gl_type = _gl_types[match.group('type')]
generic_index = match.group('generic_index')
texcoord_texture = match.group('texcoord_texture')
if generic_index:
normalized = match.group('generic_normalized')
attr_class = GenericAttribute
args = int(generic_index), normalized, count, gl_type
elif texcoord_texture:
attr_class = MultiTexCoordAttribute
args = int(texcoord_texture), count, gl_type
else:
name = match.group('name')
attr_class = _attribute_classes[name]
if attr_class._fixed_count:
assert count == attr_class._fixed_count, \
'Attributes named "%s" must have count of %d' % (
name, attr_class._fixed_count)
args = (gl_type,)
else:
args = (count, gl_type)
_attribute_cache[format] = attr_class, args
return attr_class(*args)
class AbstractAttribute(object):
'''Abstract accessor for an attribute in a mapped buffer.
'''
_fixed_count = None
def __init__(self, count, gl_type):
'''Create the attribute accessor.
:Parameters:
`count` : int
Number of components in the attribute.
`gl_type` : int
OpenGL type enumerant; for example, ``GL_FLOAT``
'''
assert count in (1, 2, 3, 4), 'Component count out of range'
self.gl_type = gl_type
self.c_type = _c_types[gl_type]
self.count = count
self.align = ctypes.sizeof(self.c_type)
self.size = count * self.align
self.stride = self.size
self.offset = 0
def enable(self):
'''Enable the attribute using ``glEnableClientState``.'''
raise NotImplementedError('abstract')
def set_pointer(self, offset):
'''Setup this attribute to point to the currently bound buffer at
the given offset.
``offset`` should be based on the currently bound buffer's ``ptr``
member.
:Parameters:
`offset` : int
Pointer offset to the currently bound buffer for this
attribute.
'''
raise NotImplementedError('abstract')
def get_region(self, buffer, start, count):
'''Map a buffer region using this attribute as an accessor.
The returned region can be modified as if the buffer was a contiguous
array of this attribute (though it may actually be interleaved or
otherwise non-contiguous).
The returned region consists of a contiguous array of component
data elements. For example, if this attribute uses 3 floats per
vertex, and the `count` parameter is 4, the number of floats mapped
will be ``3 * 4 = 12``.
:Parameters:
`buffer` : `AbstractMappable`
The buffer to map.
`start` : int
Offset of the first vertex to map.
`count` : int
Number of vertices to map
:rtype: `AbstractBufferRegion`
'''
byte_start = self.stride * start
byte_size = self.stride * count
array_count = self.count * count
if self.stride == self.size or not array_count:
# non-interleaved
ptr_type = ctypes.POINTER(self.c_type * array_count)
return buffer.get_region(byte_start, byte_size, ptr_type)
else:
# interleaved
byte_start += self.offset
byte_size -= self.offset
elem_stride = self.stride // ctypes.sizeof(self.c_type)
elem_offset = self.offset // ctypes.sizeof(self.c_type)
ptr_type = ctypes.POINTER(
self.c_type * (count * elem_stride - elem_offset))
region = buffer.get_region(byte_start, byte_size, ptr_type)
return vertexbuffer.IndirectArrayRegion(
region, array_count, self.count, elem_stride)
def set_region(self, buffer, start, count, data):
'''Set the data over a region of the buffer.
:Parameters:
`buffer` : AbstractMappable`
The buffer to modify.
`start` : int
Offset of the first vertex to set.
`count` : int
Number of vertices to set.
`data` : sequence
Sequence of data components.
'''
if self.stride == self.size:
# non-interleaved
byte_start = self.stride * start
byte_size = self.stride * count
array_count = self.count * count
data = (self.c_type * array_count)(*data)
buffer.set_data_region(data, byte_start, byte_size)
else:
# interleaved
region = self.get_region(buffer, start, count)
region[:] = data
class ColorAttribute(AbstractAttribute):
'''Color vertex attribute.'''
plural = 'colors'
def __init__(self, count, gl_type):
assert count in (3, 4), 'Color attributes must have count of 3 or 4'
super(ColorAttribute, self).__init__(count, gl_type)
def enable(self):
glEnableClientState(GL_COLOR_ARRAY)
def set_pointer(self, pointer):
glColorPointer(self.count, self.gl_type, self.stride,
self.offset + pointer)
class EdgeFlagAttribute(AbstractAttribute):
'''Edge flag attribute.'''
plural = 'edge_flags'
_fixed_count = 1
def __init__(self, gl_type):
assert gl_type in (GL_BYTE, GL_UNSIGNED_BYTE, GL_BOOL), \
'Edge flag attribute must have boolean type'
super(EdgeFlagAttribute, self).__init__(1, gl_type)
def enable(self):
glEnableClientState(GL_EDGE_FLAG_ARRAY)
def set_pointer(self, pointer):
glEdgeFlagPointer(self.stride, self.offset + pointer)
class FogCoordAttribute(AbstractAttribute):
'''Fog coordinate attribute.'''
plural = 'fog_coords'
def __init__(self, count, gl_type):
super(FogCoordAttribute, self).__init__(count, gl_type)
def enable(self):
glEnableClientState(GL_FOG_COORD_ARRAY)
def set_pointer(self, pointer):
glFogCoordPointer(self.count, self.gl_type, self.stride,
self.offset + pointer)
class NormalAttribute(AbstractAttribute):
'''Normal vector attribute.'''
plural = 'normals'
_fixed_count = 3
def __init__(self, gl_type):
assert gl_type in (GL_BYTE, GL_SHORT, GL_INT, GL_FLOAT, GL_DOUBLE), \
'Normal attribute must have signed type'
super(NormalAttribute, self).__init__(3, gl_type)
def enable(self):
glEnableClientState(GL_NORMAL_ARRAY)
def set_pointer(self, pointer):
glNormalPointer(self.gl_type, self.stride, self.offset + pointer)
class SecondaryColorAttribute(AbstractAttribute):
'''Secondary color attribute.'''
plural = 'secondary_colors'
_fixed_count = 3
def __init__(self, gl_type):
super(SecondaryColorAttribute, self).__init__(3, gl_type)
def enable(self):
glEnableClientState(GL_SECONDARY_COLOR_ARRAY)
def set_pointer(self, pointer):
glSecondaryColorPointer(3, self.gl_type, self.stride,
self.offset + pointer)
class TexCoordAttribute(AbstractAttribute):
'''Texture coordinate attribute.'''
plural = 'tex_coords'
def __init__(self, count, gl_type):
assert gl_type in (GL_SHORT, GL_INT, GL_INT, GL_FLOAT, GL_DOUBLE), \
'Texture coord attribute must have non-byte signed type'
super(TexCoordAttribute, self).__init__(count, gl_type)
def enable(self):
glEnableClientState(GL_TEXTURE_COORD_ARRAY)
def set_pointer(self, pointer):
glTexCoordPointer(self.count, self.gl_type, self.stride,
self.offset + pointer)
def convert_to_multi_tex_coord_attribute(self):
'''Changes the class of the attribute to `MultiTexCoordAttribute`.
'''
self.__class__ = MultiTexCoordAttribute
self.texture = 0
class MultiTexCoordAttribute(AbstractAttribute):
'''Texture coordinate attribute.'''
def __init__(self, texture, count, gl_type):
assert gl_type in (GL_SHORT, GL_INT, GL_INT, GL_FLOAT, GL_DOUBLE), \
'Texture coord attribute must have non-byte signed type'
self.texture = texture
super(MultiTexCoordAttribute, self).__init__(count, gl_type)
def enable(self):
glClientActiveTexture(GL_TEXTURE0 + self.texture)
glEnableClientState(GL_TEXTURE_COORD_ARRAY)
def set_pointer(self, pointer):
glTexCoordPointer(self.count, self.gl_type, self.stride,
self.offset + pointer)
class VertexAttribute(AbstractAttribute):
'''Vertex coordinate attribute.'''
plural = 'vertices'
def __init__(self, count, gl_type):
assert count > 1, \
'Vertex attribute must have count of 2, 3 or 4'
assert gl_type in (GL_SHORT, GL_INT, GL_INT, GL_FLOAT, GL_DOUBLE), \
'Vertex attribute must have signed type larger than byte'
super(VertexAttribute, self).__init__(count, gl_type)
def enable(self):
glEnableClientState(GL_VERTEX_ARRAY)
def set_pointer(self, pointer):
glVertexPointer(self.count, self.gl_type, self.stride,
self.offset + pointer)
class GenericAttribute(AbstractAttribute):
'''Generic vertex attribute, used by shader programs.'''
def __init__(self, index, normalized, count, gl_type):
self.normalized = bool(normalized)
self.index = index
super(GenericAttribute, self).__init__(count, gl_type)
def enable(self):
glEnableVertexAttribArray(self.index)
def set_pointer(self, pointer):
glVertexAttribPointer(self.index, self.count, self.gl_type,
self.normalized, self.stride,
self.offset + pointer)
_attribute_classes = {
'c': ColorAttribute,
'e': EdgeFlagAttribute,
'f': FogCoordAttribute,
'n': NormalAttribute,
's': SecondaryColorAttribute,
't': TexCoordAttribute,
'v': VertexAttribute,
}
| 17,489 | 31.388889 | 80 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/pyglet/graphics/vertexdomain.py
|
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
# $Id:$
'''Manage related vertex attributes within a single vertex domain.
A vertex "domain" consists of a set of attribute descriptions that together
describe the layout of one or more vertex buffers which are used together to
specify the vertices in a primitive. Additionally, the domain manages the
buffers used to store the data and will resize them as necessary to accommodate
new vertices.
Domains can optionally be indexed, in which case they also manage a buffer
containing vertex indices. This buffer is grown separately and has no size
relation to the attribute buffers.
Applications can create vertices (and optionally, indices) within a domain
with the :py:meth:`VertexDomain.create` method. This returns a
:py:class:`VertexList` representing the list of vertices created. The vertex
attribute data within the group can be modified, and the changes will be made
to the underlying buffers automatically.
The entire domain can be efficiently drawn in one step with the
:py:meth:`VertexDomain.draw` method, assuming all the vertices comprise
primitives of the same OpenGL primitive mode.
'''
from builtins import zip
from builtins import range
from builtins import object
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import ctypes
import re
from pyglet.gl import *
from pyglet.graphics import allocation, vertexattribute, vertexbuffer
_usage_format_re = re.compile(r'''
(?P<attribute>[^/]*)
(/ (?P<usage> static|dynamic|stream|none))?
''', re.VERBOSE)
_gl_usages = {
'static': GL_STATIC_DRAW,
'dynamic': GL_DYNAMIC_DRAW,
'stream': GL_STREAM_DRAW,
'none': GL_STREAM_DRAW_ARB, # Force no VBO
}
def _nearest_pow2(v):
# From http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
# Credit: Sean Anderson
v -= 1
v |= v >> 1
v |= v >> 2
v |= v >> 4
v |= v >> 8
v |= v >> 16
return v + 1
def create_attribute_usage(format):
'''Create an attribute and usage pair from a format string. The
format string is as documented in `pyglet.graphics.vertexattribute`, with
the addition of an optional usage component::
usage ::= attribute ( '/' ('static' | 'dynamic' | 'stream' | 'none') )?
If the usage is not given it defaults to 'dynamic'. The usage corresponds
to the OpenGL VBO usage hint, and for ``static`` also indicates a
preference for interleaved arrays. If ``none`` is specified a buffer
object is not created, and vertex data is stored in system memory.
Some examples:
``v3f/stream``
3D vertex position using floats, for stream usage
``c4b/static``
4-byte color attribute, for static usage
:return: attribute, usage
'''
match = _usage_format_re.match(format)
attribute_format = match.group('attribute')
attribute = vertexattribute.create_attribute(attribute_format)
usage = match.group('usage')
if usage:
vbo = not usage == 'none'
usage = _gl_usages[usage]
else:
usage = GL_DYNAMIC_DRAW
vbo = True
return (attribute, usage, vbo)
def create_domain(*attribute_usage_formats):
'''Create a vertex domain covering the given attribute usage formats.
See documentation for :py:func:`create_attribute_usage` and
:py:func:`pyglet.graphics.vertexattribute.create_attribute` for the grammar
of these format strings.
:rtype: :py:class:`VertexDomain`
'''
attribute_usages = [create_attribute_usage(f) \
for f in attribute_usage_formats]
return VertexDomain(attribute_usages)
def create_indexed_domain(*attribute_usage_formats):
'''Create an indexed vertex domain covering the given attribute usage
formats. See documentation for :py:class:`create_attribute_usage` and
:py:func:`pyglet.graphics.vertexattribute.create_attribute` for the grammar
of these format strings.
:rtype: :py:class:`VertexDomain`
'''
attribute_usages = [create_attribute_usage(f) \
for f in attribute_usage_formats]
return IndexedVertexDomain(attribute_usages)
class VertexDomain(object):
'''Management of a set of vertex lists.
Construction of a vertex domain is usually done with the
:py:func:`create_domain` function.
'''
_version = 0
_initial_count = 16
def __init__(self, attribute_usages):
self.allocator = allocation.Allocator(self._initial_count)
# If there are any MultiTexCoord attributes, then a TexCoord attribute
# must be converted.
have_multi_texcoord = False
for attribute, _, _ in attribute_usages:
if isinstance(attribute, vertexattribute.MultiTexCoordAttribute):
have_multi_texcoord = True
break
static_attributes = []
attributes = []
self.buffer_attributes = [] # list of (buffer, attributes)
for attribute, usage, vbo in attribute_usages:
if (have_multi_texcoord and
isinstance(attribute, vertexattribute.TexCoordAttribute)):
attribute.convert_to_multi_tex_coord_attribute()
if usage == GL_STATIC_DRAW:
# Group attributes for interleaved buffer
static_attributes.append(attribute)
attributes.append(attribute)
else:
# Create non-interleaved buffer
attributes.append(attribute)
attribute.buffer = vertexbuffer.create_mappable_buffer(
attribute.stride * self.allocator.capacity,
usage=usage, vbo=vbo)
attribute.buffer.element_size = attribute.stride
attribute.buffer.attributes = (attribute,)
self.buffer_attributes.append(
(attribute.buffer, (attribute,)))
# Create buffer for interleaved data
if static_attributes:
vertexattribute.interleave_attributes(static_attributes)
stride = static_attributes[0].stride
buffer = vertexbuffer.create_mappable_buffer(
stride * self.allocator.capacity, usage=GL_STATIC_DRAW)
buffer.element_size = stride
self.buffer_attributes.append(
(buffer, static_attributes))
attributes.extend(static_attributes)
for attribute in static_attributes:
attribute.buffer = buffer
# Create named attributes for each attribute
self.attributes = attributes
self.attribute_names = {}
for attribute in attributes:
if isinstance(attribute, vertexattribute.GenericAttribute):
index = attribute.index
# TODO create a name and use it (e.g. 'generic3')
# XXX this won't migrate; not documented.
if 'generic' not in self.attribute_names:
self.attribute_names['generic'] = {}
assert index not in self.attribute_names['generic'], \
'More than one generic attribute with index %d' % index
self.attribute_names['generic'][index] = attribute
elif isinstance(attribute, vertexattribute.MultiTexCoordAttribute):
# XXX this won't migrate; not documented.
texture = attribute.texture
if 'multi_tex_coords' not in self.attribute_names:
self.attribute_names['multi_tex_coords'] = []
assert texture not in self.attribute_names['multi_tex_coords'],\
'More than one multi_tex_coord attribute for texture %d' % \
texture
self.attribute_names['multi_tex_coords'].insert(texture,attribute)
else:
name = attribute.plural
assert name not in self.attributes, \
'More than one "%s" attribute given' % name
self.attribute_names[name] = attribute
def __del__(self):
# Break circular refs that Python GC seems to miss even when forced
# collection.
for attribute in self.attributes:
try:
del attribute.buffer
except AttributeError:
pass
def _safe_alloc(self, count):
'''Allocate vertices, resizing the buffers if necessary.'''
try:
return self.allocator.alloc(count)
except allocation.AllocatorMemoryException as e:
capacity = _nearest_pow2(e.requested_capacity)
self._version += 1
for buffer, _ in self.buffer_attributes:
buffer.resize(capacity * buffer.element_size)
self.allocator.set_capacity(capacity)
return self.allocator.alloc(count)
def _safe_realloc(self, start, count, new_count):
'''Reallocate vertices, resizing the buffers if necessary.'''
try:
return self.allocator.realloc(start, count, new_count)
except allocation.AllocatorMemoryException as e:
capacity = _nearest_pow2(e.requested_capacity)
self._version += 1
for buffer, _ in self.buffer_attributes:
buffer.resize(capacity * buffer.element_size)
self.allocator.set_capacity(capacity)
return self.allocator.realloc(start, count, new_count)
def create(self, count):
'''Create a :py:class:`VertexList` in this domain.
:Parameters:
`count` : int
Number of vertices to create.
:rtype: :py:class:`VertexList`
'''
start = self._safe_alloc(count)
return VertexList(self, start, count)
def draw(self, mode, vertex_list=None):
'''Draw vertices in the domain.
If `vertex_list` is not specified, all vertices in the domain are
drawn. This is the most efficient way to render primitives.
If `vertex_list` specifies a :py:class:`VertexList`, only primitives in
that list will be drawn.
:Parameters:
`mode` : int
OpenGL drawing mode, e.g. ``GL_POINTS``, ``GL_LINES``, etc.
`vertex_list` : `~pyglet.graphics.vertexdomain.VertexList`
Vertex list to draw, or ``None`` for all lists in this domain.
'''
glPushClientAttrib(GL_CLIENT_VERTEX_ARRAY_BIT)
for buffer, attributes in self.buffer_attributes:
buffer.bind()
for attribute in attributes:
attribute.enable()
attribute.set_pointer(attribute.buffer.ptr)
if vertexbuffer._workaround_vbo_finish:
glFinish()
if vertex_list is not None:
glDrawArrays(mode, vertex_list.start, vertex_list.count)
else:
starts, sizes = self.allocator.get_allocated_regions()
primcount = len(starts)
if primcount == 0:
pass
elif primcount == 1:
# Common case
glDrawArrays(mode, starts[0], sizes[0])
elif gl_info.have_version(1, 4):
starts = (GLint * primcount)(*starts)
sizes = (GLsizei * primcount)(*sizes)
glMultiDrawArrays(mode, starts, sizes, primcount)
else:
for start, size in zip(starts, sizes):
glDrawArrays(mode, start, size)
for buffer, _ in self.buffer_attributes:
buffer.unbind()
glPopClientAttrib()
def _is_empty(self):
return not self.allocator.starts
def __repr__(self):
return '<%s@%x %s>' % (self.__class__.__name__, id(self),
self.allocator)
class VertexList(object):
'''A list of vertices within a :py:class:`VertexDomain`. Use
:py:meth:`VertexDomain.create` to construct this list.
'''
def __init__(self, domain, start, count):
# TODO make private
self.domain = domain
self.start = start
self.count = count
def get_size(self):
'''Get the number of vertices in the list.
:rtype: int
'''
return self.count
def get_domain(self):
'''Get the domain this vertex list belongs to.
:rtype: :py:class:`VertexDomain`
'''
return self.domain
def draw(self, mode):
'''Draw this vertex list in the given OpenGL mode.
:Parameters:
`mode` : int
OpenGL drawing mode, e.g. ``GL_POINTS``, ``GL_LINES``, etc.
'''
self.domain.draw(mode, self)
def resize(self, count):
'''Resize this group.
:Parameters:
`count` : int
New number of vertices in the list.
'''
new_start = self.domain._safe_realloc(self.start, self.count, count)
if new_start != self.start:
# Copy contents to new location
for attribute in self.domain.attributes:
old = attribute.get_region(attribute.buffer,
self.start, self.count)
new = attribute.get_region(attribute.buffer,
new_start, self.count)
new.array[:] = old.array[:]
new.invalidate()
self.start = new_start
self.count = count
self._colors_cache_version = None
self._fog_coords_cache_version = None
self._edge_flags_cache_version = None
self._normals_cache_version = None
self._secondary_colors_cache_version = None
self._tex_coords_cache_version = None
self._vertices_cache_version = None
def delete(self):
'''Delete this group.'''
self.domain.allocator.dealloc(self.start, self.count)
def migrate(self, domain):
'''Move this group from its current domain and add to the specified
one. Attributes on domains must match. (In practice, used to change
parent state of some vertices).
:Parameters:
`domain` : `VertexDomain`
Domain to migrate this vertex list to.
'''
assert list(domain.attribute_names.keys()) == \
list(self.domain.attribute_names.keys()), 'Domain attributes must match.'
new_start = domain._safe_alloc(self.count)
for key, old_attribute in self.domain.attribute_names.items():
old = old_attribute.get_region(old_attribute.buffer,
self.start, self.count)
new_attribute = domain.attribute_names[key]
new = new_attribute.get_region(new_attribute.buffer,
new_start, self.count)
new.array[:] = old.array[:]
new.invalidate()
self.domain.allocator.dealloc(self.start, self.count)
self.domain = domain
self.start = new_start
self._colors_cache_version = None
self._fog_coords_cache_version = None
self._edge_flags_cache_version = None
self._normals_cache_version = None
self._secondary_colors_cache_version = None
self._tex_coords_cache_version = None
self._vertices_cache_version = None
def _set_attribute_data(self, i, data):
attribute = self.domain.attributes[i]
# TODO without region
region = attribute.get_region(attribute.buffer, self.start, self.count)
region.array[:] = data
region.invalidate()
# ---
def _get_colors(self):
if (self._colors_cache_version != self.domain._version):
domain = self.domain
attribute = domain.attribute_names['colors']
self._colors_cache = attribute.get_region(
attribute.buffer, self.start, self.count)
self._colors_cache_version = domain._version
region = self._colors_cache
region.invalidate()
return region.array
def _set_colors(self, data):
self._get_colors()[:] = data
_colors_cache = None
_colors_cache_version = None
colors = property(_get_colors, _set_colors,
doc='''Array of color data.''')
# ---
def _get_fog_coords(self):
if (self._fog_coords_cache_version != self.domain._version):
domain = self.domain
attribute = domain.attribute_names['fog_coords']
self._fog_coords_cache = attribute.get_region(
attribute.buffer, self.start, self.count)
self._fog_coords_cache_version = domain._version
region = self._fog_coords_cache
region.invalidate()
return region.array
def _set_fog_coords(self, data):
self._get_fog_coords()[:] = data
_fog_coords_cache = None
_fog_coords_cache_version = None
fog_coords = property(_get_fog_coords, _set_fog_coords,
doc='''Array of fog coordinate data.''')
# ---
def _get_edge_flags(self):
if (self._edge_flags_cache_version != self.domain._version):
domain = self.domain
attribute = domain.attribute_names['edge_flags']
self._edge_flags_cache = attribute.get_region(
attribute.buffer, self.start, self.count)
self._edge_flags_cache_version = domain._version
region = self._edge_flags_cache
region.invalidate()
return region.array
def _set_edge_flags(self, data):
self._get_edge_flags()[:] = data
_edge_flags_cache = None
_edge_flags_cache_version = None
edge_flags = property(_get_edge_flags, _set_edge_flags,
doc='''Array of edge flag data.''')
# ---
def _get_normals(self):
if (self._normals_cache_version != self.domain._version):
domain = self.domain
attribute = domain.attribute_names['normals']
self._normals_cache = attribute.get_region(
attribute.buffer, self.start, self.count)
self._normals_cache_version = domain._version
region = self._normals_cache
region.invalidate()
return region.array
def _set_normals(self, data):
self._get_normals()[:] = data
_normals_cache = None
_normals_cache_version = None
normals = property(_get_normals, _set_normals,
doc='''Array of normal vector data.''')
# ---
def _get_secondary_colors(self):
if (self._secondary_colors_cache_version != self.domain._version):
domain = self.domain
attribute = domain.attribute_names['secondary_colors']
self._secondary_colors_cache = attribute.get_region(
attribute.buffer, self.start, self.count)
self._secondary_colors_cache_version = domain._version
region = self._secondary_colors_cache
region.invalidate()
return region.array
def _set_secondary_colors(self, data):
self._get_secondary_colors()[:] = data
_secondary_colors_cache = None
_secondary_colors_cache_version = None
secondary_colors = property(_get_secondary_colors, _set_secondary_colors,
doc='''Array of secondary color data.''')
# ---
_tex_coords_cache = None
_tex_coords_cache_version = None
def _get_tex_coords(self):
if 'multi_tex_coords' not in self.domain.attribute_names:
if (self._tex_coords_cache_version != self.domain._version):
domain = self.domain
attribute = domain.attribute_names['tex_coords']
self._tex_coords_cache = attribute.get_region(
attribute.buffer, self.start, self.count)
self._tex_coords_cache_version = domain._version
region = self._tex_coords_cache
region.invalidate()
return region.array
else:
return None
def _set_tex_coords(self, data):
if self._get_tex_coords() != None:
self._get_tex_coords()[:] = data
tex_coords = property(_get_tex_coords, _set_tex_coords,
doc='''Array of texture coordinate data.''')
# ---
def _get_multi_tex_coords(self):
if 'tex_coords' not in self.domain.attribute_names:
if (self._tex_coords_cache_version != self.domain._version):
domain = self.domain
attribute = domain.attribute_names['multi_tex_coords']
self._tex_coords_cache = []
for a in attribute:
self._tex_coords_cache.append(a.get_region(
a.buffer, self.start, self.count))
self._tex_coords_cache_version = domain._version
region = self._tex_coords_cache
array = []
for a in region:
a.invalidate()
array.append(a.array)
return array
else:
return None
def _set_multi_tex_coords(self, data):
if self._get_multi_tex_coords() != None:
for a in range(0, len(self._tex_coords_cache),1):
if a > len(data):
break
elif data[a] != None:
self._tex_coords_cache[a].array[:] = data[a]
multi_tex_coords = property(_get_multi_tex_coords, _set_multi_tex_coords,
doc='''Multi-array texture coordinate data.''')
# ---
_vertices_cache = None
_vertices_cache_version = None
def _get_vertices(self):
if (self._vertices_cache_version != self.domain._version):
domain = self.domain
attribute = domain.attribute_names['vertices']
self._vertices_cache = attribute.get_region(
attribute.buffer, self.start, self.count)
self._vertices_cache_version = domain._version
region = self._vertices_cache
region.invalidate()
return region.array
def _set_vertices(self, data):
self._get_vertices()[:] = data
vertices = property(_get_vertices, _set_vertices,
doc='''Array of vertex coordinate data.''')
class IndexedVertexDomain(VertexDomain):
'''Management of a set of indexed vertex lists.
Construction of an indexed vertex domain is usually done with the
`create_indexed_domain` function.
'''
_initial_index_count = 16
def __init__(self, attribute_usages, index_gl_type=GL_UNSIGNED_INT):
super(IndexedVertexDomain, self).__init__(attribute_usages)
self.index_allocator = allocation.Allocator(self._initial_index_count)
self.index_gl_type = index_gl_type
self.index_c_type = vertexattribute._c_types[index_gl_type]
self.index_element_size = ctypes.sizeof(self.index_c_type)
self.index_buffer = vertexbuffer.create_mappable_buffer(
self.index_allocator.capacity * self.index_element_size,
target=GL_ELEMENT_ARRAY_BUFFER)
def _safe_index_alloc(self, count):
'''Allocate indices, resizing the buffers if necessary.'''
try:
return self.index_allocator.alloc(count)
except allocation.AllocatorMemoryException as e:
capacity = _nearest_pow2(e.requested_capacity)
self._version += 1
self.index_buffer.resize(capacity * self.index_element_size)
self.index_allocator.set_capacity(capacity)
return self.index_allocator.alloc(count)
def _safe_index_realloc(self, start, count, new_count):
'''Reallocate indices, resizing the buffers if necessary.'''
try:
return self.index_allocator.realloc(start, count, new_count)
except allocation.AllocatorMemoryException as e:
capacity = _nearest_pow2(e.requested_capacity)
self._version += 1
self.index_buffer.resize(capacity * self.index_element_size)
self.index_allocator.set_capacity(capacity)
return self.index_allocator.realloc(start, count, new_count)
def create(self, count, index_count):
'''Create an :py:class:`IndexedVertexList` in this domain.
:Parameters:
`count` : int
Number of vertices to create
`index_count`
Number of indices to create
'''
start = self._safe_alloc(count)
index_start = self._safe_index_alloc(index_count)
return IndexedVertexList(self, start, count, index_start, index_count)
def get_index_region(self, start, count):
'''Get a region of the index buffer.
:Parameters:
`start` : int
Start of the region to map.
`count` : int
Number of indices to map.
:rtype: Array of int
'''
byte_start = self.index_element_size * start
byte_count = self.index_element_size * count
ptr_type = ctypes.POINTER(self.index_c_type * count)
return self.index_buffer.get_region(byte_start, byte_count, ptr_type)
def draw(self, mode, vertex_list=None):
'''Draw vertices in the domain.
If `vertex_list` is not specified, all vertices in the domain are
drawn. This is the most efficient way to render primitives.
If `vertex_list` specifies a :py:class:`VertexList`, only primitives in
that list will be drawn.
:Parameters:
`mode` : int
OpenGL drawing mode, e.g. ``GL_POINTS``, ``GL_LINES``, etc.
`vertex_list` : `IndexedVertexList`
Vertex list to draw, or ``None`` for all lists in this domain.
'''
glPushClientAttrib(GL_CLIENT_VERTEX_ARRAY_BIT)
for buffer, attributes in self.buffer_attributes:
buffer.bind()
for attribute in attributes:
attribute.enable()
attribute.set_pointer(attribute.buffer.ptr)
self.index_buffer.bind()
if vertexbuffer._workaround_vbo_finish:
glFinish()
if vertex_list is not None:
glDrawElements(mode, vertex_list.index_count, self.index_gl_type,
self.index_buffer.ptr +
vertex_list.index_start * self.index_element_size)
else:
starts, sizes = self.index_allocator.get_allocated_regions()
primcount = len(starts)
if primcount == 0:
pass
elif primcount == 1:
# Common case
glDrawElements(mode, sizes[0], self.index_gl_type,
self.index_buffer.ptr + starts[0])
elif gl_info.have_version(1, 4):
starts = [s * self.index_element_size + self.index_buffer.ptr for s in starts]
starts = (ctypes.POINTER(GLvoid) * primcount)(*(GLintptr * primcount)(*starts))
sizes = (GLsizei * primcount)(*sizes)
glMultiDrawElements(mode, sizes, self.index_gl_type, starts, primcount)
else:
for start, size in zip(starts, sizes):
glDrawElements(mode, size, self.index_gl_type,
self.index_buffer.ptr +
start * self.index_element_size)
self.index_buffer.unbind()
for buffer, _ in self.buffer_attributes:
buffer.unbind()
glPopClientAttrib()
class IndexedVertexList(VertexList):
'''A list of vertices within an :py:class:`IndexedVertexDomain` that are
indexed. Use :py:meth:`IndexedVertexDomain.create` to construct this list.
'''
def __init__(self, domain, start, count, index_start, index_count):
super(IndexedVertexList, self).__init__(domain, start, count)
self.index_start = index_start
self.index_count = index_count
def draw(self, mode):
self.domain.draw(mode, self)
def resize(self, count, index_count):
'''Resize this group.
:Parameters:
`count` : int
New number of vertices in the list.
`index_count` : int
New number of indices in the list.
'''
old_start = self.start
super(IndexedVertexList, self).resize(count)
# Change indices (because vertices moved)
if old_start != self.start:
diff = self.start - old_start
self.indices[:] = [i + diff for i in self.indices]
# Resize indices
new_start = self.domain._safe_index_realloc(
self.index_start, self.index_count, index_count)
if new_start != self.index_start:
old = self.domain.get_index_region(
self.index_start, self.index_count)
new = self.domain.get_index_region(
self.index_start, self.index_count)
new.array[:] = old.array[:]
new.invalidate()
self.index_start = new_start
self.index_count = index_count
self._indices_cache_version = None
def delete(self):
'''Delete this group.'''
super(IndexedVertexList, self).delete()
self.domain.index_allocator.dealloc(self.index_start, self.index_count)
def migrate(self, domain):
'''Move this group from its current indexed domain and add to the
specified one. Attributes on domains must match. (In practice, used
to change parent state of some vertices).
:Parameters:
`domain` : `IndexedVertexDomain`
Indexed domain to migrate this vertex list to.
'''
old_start = self.start
old_domain = self.domain
super(IndexedVertexList, self).migrate(domain)
# Note: this code renumber the indices of the *original* domain
# because the vertices are in a new position in the new domain
if old_start != self.start:
diff = self.start - old_start
region = old_domain.get_index_region(self.index_start,
self.index_count)
old_indices = region.array
old_indices[:] = [i + diff for i in old_indices]
region.invalidate()
# copy indices to new domain
old = old_domain.get_index_region(self.index_start, self.index_count)
# must delloc before calling safe_index_alloc or else problems when same
# batch is migrated to because index_start changes after dealloc
old_domain.index_allocator.dealloc(self.index_start, self.index_count)
new_start = self.domain._safe_index_alloc(self.index_count)
new = self.domain.get_index_region(new_start, self.index_count)
new.array[:] = old.array[:]
new.invalidate()
self.index_start = new_start
self._indices_cache_version = None
def _set_index_data(self, data):
# TODO without region
region = self.domain.get_index_region(
self.index_start, self.index_count)
region.array[:] = data
region.invalidate()
# ---
def _get_indices(self):
if self._indices_cache_version != self.domain._version:
domain = self.domain
self._indices_cache = domain.get_index_region(
self.index_start, self.index_count)
self._indices_cache_version = domain._version
region = self._indices_cache
region.invalidate()
return region.array
def _set_indices(self, data):
self._get_indices()[:] = data
_indices_cache = None
_indices_cache_version = None
indices = property(_get_indices, _set_indices,
doc='''Array of index data.''')
| 33,427 | 36.986364 | 95 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/pyglet/graphics/allocation.py
|
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
# $Id:$
'''Memory allocation algorithm for vertex arrays and buffers.
The region allocator is used to allocate vertex indices within a vertex
domain's multiple buffers. ("Buffer" refers to any abstract buffer presented
by :py:mod:`pyglet.graphics.vertexbuffer`.
The allocator will at times request more space from the buffers. The current
policy is to double the buffer size when there is not enough room to fulfil an
allocation. The buffer is never resized smaller.
The allocator maintains references to free space only; it is the caller's
responsibility to maintain the allocated regions.
'''
from __future__ import print_function
from __future__ import division
from builtins import str
from builtins import zip
from builtins import object
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
# Common cases:
# -regions will be the same size (instances of same object, e.g. sprites)
# -regions will not usually be resized (only exception is text)
# -alignment of 4 vertices (glyphs, sprites, images, ...)
#
# Optimise for:
# -keeping regions adjacent, reduce the number of entries in glMultiDrawArrays
# -finding large blocks of allocated regions quickly (for drawing)
# -finding block of unallocated space is the _uncommon_ case!
#
# Decisions:
# -don't over-allocate regions to any alignment -- this would require more
# work in finding the allocated spaces (for drawing) and would result in
# more entries in glMultiDrawArrays
# -don't move blocks when they truncate themselves. try not to allocate the
# space they freed too soon (they will likely need grow back into it later,
# and growing will usually require a reallocation).
# -allocator does not track individual allocated regions. Trusts caller
# to provide accurate (start, size) tuple, which completely describes
# a region from the allocator's point of view.
# -this means that compacting is probably not feasible, or would be hideously
# expensive
class AllocatorMemoryException(Exception):
'''The buffer is not large enough to fulfil an allocation.
Raised by `Allocator` methods when the operation failed due to lack of
buffer space. The buffer should be increased to at least
requested_capacity and then the operation retried (guaranteed to
pass second time).
'''
def __init__(self, requested_capacity):
self.requested_capacity = requested_capacity
class Allocator(object):
'''Buffer space allocation implementation.'''
def __init__(self, capacity):
'''Create an allocator for a buffer of the specified capacity.
:Parameters:
`capacity` : int
Maximum size of the buffer.
'''
self.capacity = capacity
# Allocated blocks. Start index and size in parallel lists.
#
# # = allocated, - = free
#
# 0 3 5 15 20 24 40
# |###--##########-----####----------------------|
#
# starts = [0, 5, 20]
# sizes = [3, 10, 4]
#
# To calculate free blocks:
# for i in range(0, len(starts)):
# free_start[i] = starts[i] + sizes[i]
# free_size[i] = starts[i+1] - free_start[i]
# free_size[i+1] = self.capacity - free_start[-1]
self.starts = []
self.sizes = []
def set_capacity(self, size):
'''Resize the maximum buffer size.
The capaity cannot be reduced.
:Parameters:
`size` : int
New maximum size of the buffer.
'''
assert size > self.capacity
self.capacity = size
def alloc(self, size):
'''Allocate memory in the buffer.
Raises `AllocatorMemoryException` if the allocation cannot be
fulfilled.
:Parameters:
`size` : int
Size of region to allocate.
:rtype: int
:return: Starting index of the allocated region.
'''
assert size >= 0
if size == 0:
return 0
# return start
# or raise AllocatorMemoryException
if not self.starts:
if size <= self.capacity:
self.starts.append(0)
self.sizes.append(size)
return 0
else:
raise AllocatorMemoryException(size)
# Allocate in a free space
free_start = self.starts[0] + self.sizes[0]
for i, (alloc_start, alloc_size) in \
enumerate(zip(self.starts[1:], self.sizes[1:])):
# Danger!
# i is actually index - 1 because of slicing above...
# starts[i] points to the block before this free space
# starts[i+1] points to the block after this free space, and is
# always valid.
free_size = alloc_start - free_start
if free_size == size:
# Merge previous block with this one (removing this free space)
self.sizes[i] += free_size + alloc_size
del self.starts[i+1]
del self.sizes[i+1]
return free_start
elif free_size > size:
# Increase size of previous block to intrude into this free
# space.
self.sizes[i] += size
return free_start
free_start = alloc_start + alloc_size
# Allocate at end of capacity
free_size = self.capacity - free_start
if free_size >= size:
self.sizes[-1] += size
return free_start
raise AllocatorMemoryException(self.capacity + size - free_size)
def realloc(self, start, size, new_size):
'''Reallocate a region of the buffer.
This is more efficient than separate `dealloc` and `alloc` calls, as
the region can often be resized in-place.
Raises `AllocatorMemoryException` if the allocation cannot be
fulfilled.
:Parameters:
`start` : int
Current starting index of the region.
`size` : int
Current size of the region.
`new_size` : int
New size of the region.
'''
assert size >= 0 and new_size >= 0
if new_size == 0:
if size != 0:
self.dealloc(start, size)
return 0
elif size == 0:
return self.alloc(new_size)
# return start
# or raise AllocatorMemoryException
# Truncation is the same as deallocating the tail cruft
if new_size < size:
self.dealloc(start + new_size, size - new_size)
return start
# Find which block it lives in
for i, (alloc_start, alloc_size) in \
enumerate(zip(*(self.starts, self.sizes))):
p = start - alloc_start
if p >= 0 and size <= alloc_size - p:
break
if not (p >= 0 and size <= alloc_size - p):
print(list(zip(self.starts, self.sizes)))
print(start, size, new_size)
print(p, alloc_start, alloc_size)
assert p >= 0 and size <= alloc_size - p, 'Region not allocated'
if size == alloc_size - p:
# Region is at end of block. Find how much free space is after
# it.
is_final_block = i == len(self.starts) - 1
if not is_final_block:
free_size = self.starts[i + 1] - (start + size)
else:
free_size = self.capacity - (start + size)
# TODO If region is an entire block being an island in free space,
# can possibly extend in both directions.
if free_size == new_size - size and not is_final_block:
# Merge block with next (region is expanded in place to
# exactly fill the free space)
self.sizes[i] += free_size + self.sizes[i + 1]
del self.starts[i + 1]
del self.sizes[i + 1]
return start
elif free_size > new_size - size:
# Expand region in place
self.sizes[i] += new_size - size
return start
# The block must be repositioned. Dealloc then alloc.
# But don't do this! If alloc fails, we've already silently dealloc'd
# the original block.
# self.dealloc(start, size)
# return self.alloc(new_size)
# It must be alloc'd first. We're not missing an optimisation
# here, because if freeing the block would've allowed for the block to
# be placed in the resulting free space, one of the above in-place
# checks would've found it.
result = self.alloc(new_size)
self.dealloc(start, size)
return result
def dealloc(self, start, size):
'''Free a region of the buffer.
:Parameters:
`start` : int
Starting index of the region.
`size` : int
Size of the region.
'''
assert size >= 0
if size == 0:
return
assert self.starts
# Find which block needs to be split
for i, (alloc_start, alloc_size) in \
enumerate(zip(*(self.starts, self.sizes))):
p = start - alloc_start
if p >= 0 and size <= alloc_size - p:
break
# Assert we left via the break
assert p >= 0 and size <= alloc_size - p, 'Region not allocated'
if p == 0 and size == alloc_size:
# Remove entire block
del self.starts[i]
del self.sizes[i]
elif p == 0:
# Truncate beginning of block
self.starts[i] += size
self.sizes[i] -= size
elif size == alloc_size - p:
# Truncate end of block
self.sizes[i] -= size
else:
# Reduce size of left side, insert block at right side
# $ = dealloc'd block, # = alloc'd region from same block
#
# <------8------>
# <-5-><-6-><-7->
# 1 2 3 4
# #####$$$$$#####
#
# 1 = alloc_start
# 2 = start
# 3 = start + size
# 4 = alloc_start + alloc_size
# 5 = start - alloc_start = p
# 6 = size
# 7 = {8} - ({5} + {6}) = alloc_size - (p + size)
# 8 = alloc_size
#
self.sizes[i] = p
self.starts.insert(i + 1, start + size)
self.sizes.insert(i + 1, alloc_size - (p + size))
def get_allocated_regions(self):
'''Get a list of (aggregate) allocated regions.
The result of this method is ``(starts, sizes)``, where ``starts`` is
a list of starting indices of the regions and ``sizes`` their
corresponding lengths.
:rtype: (list, list)
'''
# return (starts, sizes); len(starts) == len(sizes)
return (self.starts, self.sizes)
def get_fragmented_free_size(self):
'''Returns the amount of space unused, not including the final
free block.
:rtype: int
'''
if not self.starts:
return 0
# Variation of search for free block.
total_free = 0
free_start = self.starts[0] + self.sizes[0]
for i, (alloc_start, alloc_size) in \
enumerate(zip(self.starts[1:], self.sizes[1:])):
total_free += alloc_start - free_start
free_start = alloc_start + alloc_size
return total_free
def get_free_size(self):
'''Return the amount of space unused.
:rtype: int
'''
if not self.starts:
return self.capacity
free_end = self.capacity - (self.starts[-1] + self.sizes[-1])
return self.get_fragmented_free_size() + free_end
def get_usage(self):
'''Return fraction of capacity currently allocated.
:rtype: float
'''
return 1. - self.get_free_size() / float(self.capacity)
def get_fragmentation(self):
'''Return fraction of free space that is not expandable.
:rtype: float
'''
free_size = self.get_free_size()
if free_size == 0:
return 0.
return self.get_fragmented_free_size() / float(self.get_free_size())
def _is_empty(self):
return not self.starts
def __str__(self):
return 'allocs=' + repr(list(zip(self.starts, self.sizes)))
def __repr__(self):
return '<%s %s>' % (self.__class__.__name__, str(self))
| 14,520 | 34.417073 | 79 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/pyglet/graphics/__init__.py
|
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
# $Id:$
'''Low-level graphics rendering.
This module provides an efficient low-level abstraction over OpenGL. It gives
very good performance for rendering OpenGL primitives; far better than the
typical immediate-mode usage and, on modern graphics cards, better than using
display lists in many cases. The module is used internally by other areas of
pyglet.
See the :ref:`programming-guide-graphics` for details on how to use this graphics API.
Batches and groups
==================
Without even needing to understand the details on how to draw primitives with
the graphics API, developers can make use of :py:class:`~pyglet.graphics.Batch` and :py:class:`~pyglet.graphics.Group`
objects to improve performance of sprite and text rendering.
The :py:class:`~pyglet.sprite.Sprite`, :py:func:`~pyglet.text.Label` and :py:func:`~pyglet.text.layout.TextLayout` classes all accept a ``batch`` and
``group`` parameter in their constructors. A batch manages a set of objects
that will be drawn all at once, and a group describes the manner in which an
object is drawn.
The following example creates a batch, adds two sprites to the batch, and then
draws the entire batch::
batch = pyglet.graphics.Batch()
car = pyglet.sprite.Sprite(car_image, batch=batch)
boat = pyglet.sprite.Sprite(boat_image, batch=batch)
def on_draw()
batch.draw()
Drawing a complete batch is much faster than drawing the items in the batch
individually, especially when those items belong to a common group.
Groups describe the OpenGL state required for an item. This is for the most
part managed by the sprite and text classes, however you can also use groups
to ensure items are drawn in a particular order. For example, the following
example adds a background sprite which is guaranteed to be drawn before the
car and the boat::
batch = pyglet.graphics.Batch()
background = pyglet.graphics.OrderedGroup(0)
foreground = pyglet.graphics.OrderedGroup(1)
background = pyglet.sprite.Sprite(background_image,
batch=batch, group=background)
car = pyglet.sprite.Sprite(car_image, batch=batch, group=foreground)
boat = pyglet.sprite.Sprite(boat_image, batch=batch, group=foreground)
def on_draw()
batch.draw()
It's preferable to manage sprites and text objects within as few batches as
possible. If the drawing of sprites or text objects need to be interleaved
with other drawing that does not use the graphics API, multiple batches will
be required.
Data item parameters
====================
Many of the functions and methods in this module accept any number of ``data``
parameters as their final parameters. In the documentation these are notated
as ``*data`` in the formal parameter list.
A data parameter describes a vertex attribute format and an optional sequence
to initialise that attribute. Examples of common attribute formats are:
``"v3f"``
Vertex position, specified as three floats.
``"c4B"``
Vertex color, specified as four unsigned bytes.
``"t2f"``
Texture coordinate, specified as two floats.
See `pyglet.graphics.vertexattribute` for the complete syntax of the vertex
format string.
When no initial data is to be given, the data item is just the format string.
For example, the following creates a 2 element vertex list with position and
color attributes::
vertex_list = pyglet.graphics.vertex_list(2, 'v2f', 'c4B')
When initial data is required, wrap the format string and the initial data in
a tuple, for example::
vertex_list = pyglet.graphics.vertex_list(2,
('v2f', (0.0, 1.0, 1.0, 0.0)),
('c4B', (255, 255, 255, 255) * 2))
Drawing modes
=============
Methods in this module that accept a ``mode`` parameter will accept any value
in the OpenGL drawing mode enumeration: ``GL_POINTS``, ``GL_LINE_STRIP``,
``GL_LINE_LOOP``, ``GL_LINES``, ``GL_TRIANGLE_STRIP``, ``GL_TRIANGLE_FAN``,
``GL_TRIANGLES``, ``GL_QUAD_STRIP``, ``GL_QUADS``, and ``GL_POLYGON``.
::
pyglet.graphics.draw(1, GL_POINTS, ('v2i',(10,20)))
However, because of the way the graphics API renders multiple primitives with
shared state, ``GL_POLYGON``, ``GL_LINE_LOOP`` and ``GL_TRIANGLE_FAN`` cannot
be used --- the results are undefined.
When using ``GL_LINE_STRIP``, ``GL_TRIANGLE_STRIP`` or ``GL_QUAD_STRIP`` care
must be taken to insert degenerate vertices at the beginning and end of each
vertex list. For example, given the vertex list::
A, B, C, D
the correct vertex list to provide the vertex list is::
A, A, B, C, D, D
Alternatively, the ``NV_primitive_restart`` extension can be used if it is
present. This also permits use of ``GL_POLYGON``, ``GL_LINE_LOOP`` and
``GL_TRIANGLE_FAN``. Unfortunately the extension is not provided by older
video drivers, and requires indexed vertex lists.
.. versionadded:: 1.1
'''
from __future__ import print_function
from builtins import zip
from builtins import object
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import ctypes
import pyglet
from pyglet.gl import *
from pyglet import gl
from pyglet.graphics import vertexbuffer, vertexattribute, vertexdomain
_debug_graphics_batch = pyglet.options['debug_graphics_batch']
def draw(size, mode, *data):
'''Draw a primitive immediately.
:Parameters:
`size` : int
Number of vertices given
`mode` : gl primitive type
OpenGL drawing mode, e.g. ``GL_TRIANGLES``,
avoiding quotes.
`data` : data items
Attribute formats and data. See the module summary for
details.
'''
glPushClientAttrib(GL_CLIENT_VERTEX_ARRAY_BIT)
buffers = []
for format, array in data:
attribute = vertexattribute.create_attribute(format)
assert size == len(array) // attribute.count, \
'Data for %s is incorrect length' % format
buffer = vertexbuffer.create_mappable_buffer(
size * attribute.stride, vbo=False)
attribute.set_region(buffer, 0, size, array)
attribute.enable()
attribute.set_pointer(buffer.ptr)
buffers.append(buffer)
glDrawArrays(mode, 0, size)
glFlush()
glPopClientAttrib()
def draw_indexed(size, mode, indices, *data):
'''Draw a primitive with indexed vertices immediately.
:Parameters:
`size` : int
Number of vertices given
`mode` : int
OpenGL drawing mode, e.g. ``GL_TRIANGLES``
`indices` : sequence of int
Sequence of integers giving indices into the vertex list.
`data` : data items
Attribute formats and data. See the module summary for details.
'''
glPushClientAttrib(GL_CLIENT_VERTEX_ARRAY_BIT)
buffers = []
for format, array in data:
attribute = vertexattribute.create_attribute(format)
assert size == len(array) // attribute.count, \
'Data for %s is incorrect length' % format
buffer = vertexbuffer.create_mappable_buffer(
size * attribute.stride, vbo=False)
attribute.set_region(buffer, 0, size, array)
attribute.enable()
attribute.set_pointer(buffer.ptr)
buffers.append(buffer)
if size <= 0xff:
index_type = GL_UNSIGNED_BYTE
index_c_type = ctypes.c_ubyte
elif size <= 0xffff:
index_type = GL_UNSIGNED_SHORT
index_c_type = ctypes.c_ushort
else:
index_type = GL_UNSIGNED_INT
index_c_type = ctypes.c_uint
index_array = (index_c_type * len(indices))(*indices)
glDrawElements(mode, len(indices), index_type, index_array)
glFlush()
glPopClientAttrib()
def _parse_data(data):
'''Given a list of data items, returns (formats, initial_arrays).'''
assert data, 'No attribute formats given'
# Return tuple (formats, initial_arrays).
formats = []
initial_arrays = []
for i, format in enumerate(data):
if isinstance(format, tuple):
format, array = format
initial_arrays.append((i, array))
formats.append(format)
formats = tuple(formats)
return formats, initial_arrays
def _get_default_batch():
shared_object_space = gl.current_context.object_space
try:
return shared_object_space.pyglet_graphics_default_batch
except AttributeError:
shared_object_space.pyglet_graphics_default_batch = Batch()
return shared_object_space.pyglet_graphics_default_batch
def vertex_list(count, *data):
'''Create a :py:class:`~pyglet.graphics.vertexdomain.VertexList` not associated with a batch, group or mode.
:Parameters:
`count` : int
The number of vertices in the list.
`data` : data items
Attribute formats and initial data for the vertex list. See the
module summary for details.
:rtype: :py:class:`~pyglet.graphics.vertexdomain.VertexList`
'''
# Note that mode=0 because the default batch is never drawn: vertex lists
# returned from this function are drawn directly by the app.
return _get_default_batch().add(count, 0, None, *data)
def vertex_list_indexed(count, indices, *data):
'''Create an `IndexedVertexList` not associated with a batch, group or mode.
:Parameters:
`count` : int
The number of vertices in the list.
`indices` : sequence
Sequence of integers giving indices into the vertex list.
`data` : data items
Attribute formats and initial data for the vertex list. See the
module summary for details.
:rtype: `IndexedVertexList`
'''
# Note that mode=0 because the default batch is never drawn: vertex lists
# returned from this function are drawn directly by the app.
return _get_default_batch().add_indexed(count, 0, None, indices, *data)
class Batch(object):
'''Manage a collection of vertex lists for batched rendering.
Vertex lists are added to a :py:class:`~pyglet.graphics.Batch` using the `add` and `add_indexed`
methods. An optional group can be specified along with the vertex list,
which gives the OpenGL state required for its rendering. Vertex lists
with shared mode and group are allocated into adjacent areas of memory and
sent to the graphics card in a single operation.
Call `VertexList.delete` to remove a vertex list from the batch.
'''
def __init__(self):
'''Create a graphics batch.'''
# Mapping to find domain.
# group -> (attributes, mode, indexed) -> domain
self.group_map = {}
# Mapping of group to list of children.
self.group_children = {}
# List of top-level groups
self.top_groups = []
self._draw_list = []
self._draw_list_dirty = False
def invalidate(self):
'''Force the batch to update the draw list.
This method can be used to force the batch to re-compute the draw list
when the ordering of groups has changed.
.. versionadded:: 1.2
'''
self._draw_list_dirty = True
def add(self, count, mode, group, *data):
'''Add a vertex list to the batch.
:Parameters:
`count` : int
The number of vertices in the list.
`mode` : int
OpenGL drawing mode enumeration; for example, one of
``GL_POINTS``, ``GL_LINES``, ``GL_TRIANGLES``, etc.
See the module summary for additional information.
`group` : `~pyglet.graphics.Group`
Group of the vertex list, or ``None`` if no group is required.
`data` : data items
Attribute formats and initial data for the vertex list. See
the module summary for details.
:rtype: :py:class:`~pyglet.graphics.vertexdomain.VertexList`
'''
formats, initial_arrays = _parse_data(data)
domain = self._get_domain(False, mode, group, formats)
# Create vertex list and initialize
vlist = domain.create(count)
for i, array in initial_arrays:
vlist._set_attribute_data(i, array)
return vlist
def add_indexed(self, count, mode, group, indices, *data):
'''Add an indexed vertex list to the batch.
:Parameters:
`count` : int
The number of vertices in the list.
`mode` : int
OpenGL drawing mode enumeration; for example, one of
``GL_POINTS``, ``GL_LINES``, ``GL_TRIANGLES``, etc.
See the module summary for additional information.
`group` : `~pyglet.graphics.Group`
Group of the vertex list, or ``None`` if no group is required.
`indices` : sequence
Sequence of integers giving indices into the vertex list.
`data` : data items
Attribute formats and initial data for the vertex list. See
the module summary for details.
:rtype: `IndexedVertexList`
'''
formats, initial_arrays = _parse_data(data)
domain = self._get_domain(True, mode, group, formats)
# Create vertex list and initialize
vlist = domain.create(count, len(indices))
start = vlist.start
vlist._set_index_data([i + start for i in indices])
for i, array in initial_arrays:
vlist._set_attribute_data(i, array)
return vlist
def migrate(self, vertex_list, mode, group, batch):
'''Migrate a vertex list to another batch and/or group.
`vertex_list` and `mode` together identify the vertex list to migrate.
`group` and `batch` are new owners of the vertex list after migration.
The results are undefined if `mode` is not correct or if `vertex_list`
does not belong to this batch (they are not checked and will not
necessarily throw an exception immediately).
`batch` can remain unchanged if only a group change is desired.
:Parameters:
`vertex_list` : `~pyglet.graphics.vertexdomain.VertexList`
A vertex list currently belonging to this batch.
`mode` : int
The current GL drawing mode of the vertex list.
`group` : `~pyglet.graphics.Group`
The new group to migrate to.
`batch` : `~pyglet.graphics.Batch`
The batch to migrate to (or the current batch).
'''
formats = vertex_list.domain.__formats
if isinstance(vertex_list, vertexdomain.IndexedVertexList):
domain = batch._get_domain(True, mode, group, formats)
else:
domain = batch._get_domain(False, mode, group, formats)
vertex_list.migrate(domain)
def _get_domain(self, indexed, mode, group, formats):
if group is None:
group = null_group
# Batch group
if group not in self.group_map:
self._add_group(group)
domain_map = self.group_map[group]
# Find domain given formats, indices and mode
key = (formats, mode, indexed)
try:
domain = domain_map[key]
except KeyError:
# Create domain
if indexed:
domain = vertexdomain.create_indexed_domain(*formats)
else:
domain = vertexdomain.create_domain(*formats)
domain.__formats = formats
domain_map[key] = domain
self._draw_list_dirty = True
return domain
def _add_group(self, group):
self.group_map[group] = {}
if group.parent is None:
self.top_groups.append(group)
else:
if group.parent not in self.group_map:
self._add_group(group.parent)
if group.parent not in self.group_children:
self.group_children[group.parent] = []
self.group_children[group.parent].append(group)
self._draw_list_dirty = True
def _update_draw_list(self):
'''Visit group tree in preorder and create a list of bound methods
to call.
'''
def visit(group):
draw_list = []
# Draw domains using this group
domain_map = self.group_map[group]
for (formats, mode, indexed), domain in list(domain_map.items()):
# Remove unused domains from batch
if domain._is_empty():
del domain_map[(formats, mode, indexed)]
continue
draw_list.append(
(lambda d, m: lambda: d.draw(m))(domain, mode))
# Sort and visit child groups of this group
children = self.group_children.get(group)
if children:
children.sort()
for child in list(children):
draw_list.extend(visit(child))
if children or domain_map:
return [group.set_state] + draw_list + [group.unset_state]
else:
# Remove unused group from batch
del self.group_map[group]
if group.parent:
self.group_children[group.parent].remove(group)
try:
del self.group_children[group]
except KeyError:
pass
try:
self.top_groups.remove(group)
except ValueError:
pass
return []
self._draw_list = []
self.top_groups.sort()
for group in list(self.top_groups):
self._draw_list.extend(visit(group))
self._draw_list_dirty = False
if _debug_graphics_batch:
self._dump_draw_list()
def _dump_draw_list(self):
def dump(group, indent=''):
print(indent, 'Begin group', group)
domain_map = self.group_map[group]
for _, domain in domain_map.items():
print(indent, ' ', domain)
for start, size in zip(*domain.allocator.get_allocated_regions()):
print(indent, ' ', 'Region %d size %d:' % (start, size))
for key, attribute in domain.attribute_names.items():
print(indent, ' ', end=' ')
try:
region = attribute.get_region(attribute.buffer,
start, size)
print(key, region.array[:])
except:
print(key, '(unmappable)')
for child in self.group_children.get(group, ()):
dump(child, indent + ' ')
print(indent, 'End group', group)
print('Draw list for %r:' % self)
for group in self.top_groups:
dump(group)
def draw(self):
'''Draw the batch.
'''
if self._draw_list_dirty:
self._update_draw_list()
for func in self._draw_list:
func()
def draw_subset(self, vertex_lists):
'''Draw only some vertex lists in the batch.
The use of this method is highly discouraged, as it is quite
inefficient. Usually an application can be redesigned so that batches
can always be drawn in their entirety, using `draw`.
The given vertex lists must belong to this batch; behaviour is
undefined if this condition is not met.
:Parameters:
`vertex_lists` : sequence of `VertexList` or `IndexedVertexList`
Vertex lists to draw.
'''
# Horrendously inefficient.
def visit(group):
group.set_state()
# Draw domains using this group
domain_map = self.group_map[group]
for (_, mode, _), domain in domain_map.items():
for alist in vertex_lists:
if alist.domain is domain:
alist.draw(mode)
# Sort and visit child groups of this group
children = self.group_children.get(group)
if children:
children.sort()
for child in children:
visit(child)
group.unset_state()
self.top_groups.sort()
for group in self.top_groups:
visit(group)
class Group(object):
'''Group of common OpenGL state.
Before a vertex list is rendered, its group's OpenGL state is set; as are
that state's ancestors' states. This can be defined arbitrarily on
subclasses; the default state change has no effect, and groups vertex
lists only in the order in which they are drawn.
'''
def __init__(self, parent=None):
'''Create a group.
:Parameters:
`parent` : `~pyglet.graphics.Group`
Group to contain this group; its state will be set before this
state's.
'''
self.parent = parent
def __lt__(self, other):
return hash(self) < hash(other)
def set_state(self):
'''Apply the OpenGL state change.
The default implementation does nothing.'''
pass
def unset_state(self):
'''Repeal the OpenGL state change.
The default implementation does nothing.'''
pass
def set_state_recursive(self):
'''Set this group and its ancestry.
Call this method if you are using a group in isolation: the
parent groups will be called in top-down order, with this class's
`set` being called last.
'''
if self.parent:
self.parent.set_state_recursive()
self.set_state()
def unset_state_recursive(self):
'''Unset this group and its ancestry.
The inverse of `set_state_recursive`.
'''
self.unset_state()
if self.parent:
self.parent.unset_state_recursive()
class NullGroup(Group):
'''The default group class used when ``None`` is given to a batch.
This implementation has no effect.
'''
pass
#: The default group.
#:
#: :type: :py:class:`~pyglet.graphics.Group`
null_group = NullGroup()
class TextureGroup(Group):
'''A group that enables and binds a texture.
Texture groups are equal if their textures' targets and names are equal.
'''
# Don't use this, create your own group classes that are more specific.
# This is just an example.
def __init__(self, texture, parent=None):
'''Create a texture group.
:Parameters:
`texture` : `~pyglet.image.Texture`
Texture to bind.
`parent` : `~pyglet.graphics.Group`
Parent group.
'''
super(TextureGroup, self).__init__(parent)
self.texture = texture
def set_state(self):
glEnable(self.texture.target)
glBindTexture(self.texture.target, self.texture.id)
def unset_state(self):
glDisable(self.texture.target)
def __hash__(self):
return hash((self.texture.target, self.texture.id, self.parent))
def __eq__(self, other):
return (self.__class__ is other.__class__ and
self.texture.target == other.texture.target and
self.texture.id == other.texture.id and
self.parent == other.parent)
def __repr__(self):
return '%s(id=%d)' % (self.__class__.__name__, self.texture.id)
class OrderedGroup(Group):
'''A group with partial order.
Ordered groups with a common parent are rendered in ascending order of
their ``order`` field. This is a useful way to render multiple layers of
a scene within a single batch.
'''
# This can be useful as a top-level group, or as a superclass for other
# groups that need to be ordered.
#
# As a top-level group it's useful because graphics can be composited in a
# known order even if they don't know about each other or share any known
# group.
def __init__(self, order, parent=None):
'''Create an ordered group.
:Parameters:
`order` : int
Order of this group.
`parent` : `~pyglet.graphics.Group`
Parent of this group.
'''
super(OrderedGroup, self).__init__(parent)
self.order = order
def __lt__(self, other):
if isinstance(other, OrderedGroup):
return self.order < other.order
return super(OrderedGroup, self).__lt__(other)
def __eq__(self, other):
return (self.__class__ is other.__class__ and
self.order == other.order and
self.parent == other.parent)
def __hash__(self):
return hash((self.order, self.parent))
def __repr__(self):
return '%s(%d)' % (self.__class__.__name__, self.order)
| 26,789 | 34.911528 | 149 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/pyglet/window/event.py
|
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
"""Events for :py:mod:`pyglet.window`.
See :py:class:`~pyglet.window.Window` for a description of the window event types.
"""
from __future__ import print_function
from builtins import object
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import sys
from pyglet.window import key
from pyglet.window import mouse
class WindowExitHandler(object):
"""Determine if the window should be closed.
This event handler watches for the ESC key or the window close event
and sets `self.has_exit` to True when either is pressed. An instance
of this class is automatically attached to all new `pyglet.window.Window`
objects.
:deprecated: This class's functionality is provided directly on :py:class:`~pyglet.window.Window`
in pyglet 1.1.
"""
has_exit = False
"""True if the user wants to close the window."""
def on_close(self):
self.has_exit = True
def on_key_press(self, symbol, modifiers):
if symbol == key.ESCAPE:
self.has_exit = True
class WindowEventLogger(object):
"""Print all events to a file.
When this event handler is added to a window it prints out all events
and their parameters; useful for debugging or discovering which events
you need to handle.
Example::
win = window.Window()
win.push_handlers(WindowEventLogger())
"""
def __init__(self, logfile=None):
"""Create a `WindowEventLogger` which writes to `logfile`.
:Parameters:
`logfile` : file-like object
The file to write to. If unspecified, stdout will be used.
"""
if logfile is None:
logfile = sys.stdout
self.file = logfile
def on_key_press(self, symbol, modifiers):
print('on_key_press(symbol=%s, modifiers=%s)' % (
key.symbol_string(symbol), key.modifiers_string(modifiers)), file=self.file)
def on_key_release(self, symbol, modifiers):
print('on_key_release(symbol=%s, modifiers=%s)' % (
key.symbol_string(symbol), key.modifiers_string(modifiers)), file=self.file)
def on_text(self, text):
print('on_text(text=%r)' % text, file=self.file)
def on_text_motion(self, motion):
print('on_text_motion(motion=%s)' % (
key.motion_string(motion)), file=self.file)
def on_text_motion_select(self, motion):
print('on_text_motion_select(motion=%s)' % (
key.motion_string(motion)), file=self.file)
def on_mouse_motion(self, x, y, dx, dy):
print('on_mouse_motion(x=%d, y=%d, dx=%d, dy=%d)' % (
x, y, dx, dy), file=self.file)
def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers):
print('on_mouse_drag(x=%d, y=%d, dx=%d, dy=%d, '\
'buttons=%s, modifiers=%s)' % (
x, y, dx, dy,
mouse.buttons_string(buttons), key.modifiers_string(modifiers)), file=self.file)
def on_mouse_press(self, x, y, button, modifiers):
print('on_mouse_press(x=%d, y=%d, button=%r, '\
'modifiers=%s)' % (x, y,
mouse.buttons_string(button), key.modifiers_string(modifiers)), file=self.file)
def on_mouse_release(self, x, y, button, modifiers):
print('on_mouse_release(x=%d, y=%d, button=%r, '\
'modifiers=%s)' % (x, y,
mouse.buttons_string(button), key.modifiers_string(modifiers)), file=self.file)
def on_mouse_scroll(self, x, y, dx, dy):
print('on_mouse_scroll(x=%f, y=%f, dx=%f, dy=%f)' % (
x, y, dx, dy), file=self.file)
def on_close(self):
print('on_close()', file=self.file)
def on_mouse_enter(self, x, y):
print('on_mouse_enter(x=%d, y=%d)' % (x, y), file=self.file)
def on_mouse_leave(self, x, y):
print('on_mouse_leave(x=%d, y=%d)' % (x, y), file=self.file)
def on_expose(self):
print('on_expose()', file=self.file)
def on_resize(self, width, height):
print('on_resize(width=%d, height=%d)' % (width, height), file=self.file)
def on_move(self, x, y):
print('on_move(x=%d, y=%d)' % (x, y), file=self.file)
def on_activate(self):
print('on_activate()', file=self.file)
def on_deactivate(self):
print('on_deactivate()', file=self.file)
def on_show(self):
print('on_show()', file=self.file)
def on_hide(self):
print('on_hide()', file=self.file)
def on_context_lost(self):
print('on_context_lost()', file=self.file)
def on_context_state_lost(self):
print('on_context_state_lost()', file=self.file)
def on_draw(self):
print('on_draw()', file=self.file)
| 6,440 | 34.783333 | 101 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/pyglet/window/mouse.py
|
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
"""Mouse constants and utilities for pyglet.window.
"""
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
def buttons_string(buttons):
"""Return a string describing a set of active mouse buttons.
Example::
>>> buttons_string(LEFT | RIGHT)
'LEFT|RIGHT'
:Parameters:
`buttons` : int
Bitwise combination of mouse button constants.
:rtype: str
"""
button_names = []
if buttons & LEFT:
button_names.append('LEFT')
if buttons & MIDDLE:
button_names.append('MIDDLE')
if buttons & RIGHT:
button_names.append('RIGHT')
return '|'.join(button_names)
# Symbolic names for the mouse buttons
LEFT = 1 << 0
MIDDLE = 1 << 1
RIGHT = 1 << 2
| 2,458 | 35.161765 | 78 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/pyglet/window/key.py
|
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
"""Key constants and utilities for pyglet.window.
Usage::
from pyglet.window import Window
from pyglet.window import key
window = Window()
@window.event
def on_key_press(symbol, modifiers):
# Symbolic names:
if symbol == key.RETURN:
# Alphabet keys:
elif symbol == key.Z:
# Number keys:
elif symbol == key._1:
# Number keypad keys:
elif symbol == key.NUM_1:
# Modifiers:
if modifiers & key.MOD_CTRL:
"""
from builtins import str
from pyglet import compat_platform
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
class KeyStateHandler(dict):
"""Simple handler that tracks the state of keys on the keyboard. If a
key is pressed then this handler holds a True value for it.
For example::
>>> win = window.Window
>>> keyboard = key.KeyStateHandler()
>>> win.push_handlers(keyboard)
# Hold down the "up" arrow...
>>> keyboard[key.UP]
True
>>> keyboard[key.DOWN]
False
"""
def on_key_press(self, symbol, modifiers):
self[symbol] = True
def on_key_release(self, symbol, modifiers):
self[symbol] = False
def __getitem__(self, key):
return self.get(key, False)
def modifiers_string(modifiers):
"""Return a string describing a set of modifiers.
Example::
>>> modifiers_string(MOD_SHIFT | MOD_CTRL)
'MOD_SHIFT|MOD_CTRL'
:Parameters:
`modifiers` : int
Bitwise combination of modifier constants.
:rtype: str
"""
mod_names = []
if modifiers & MOD_SHIFT:
mod_names.append('MOD_SHIFT')
if modifiers & MOD_CTRL:
mod_names.append('MOD_CTRL')
if modifiers & MOD_ALT:
mod_names.append('MOD_ALT')
if modifiers & MOD_CAPSLOCK:
mod_names.append('MOD_CAPSLOCK')
if modifiers & MOD_NUMLOCK:
mod_names.append('MOD_NUMLOCK')
if modifiers & MOD_SCROLLLOCK:
mod_names.append('MOD_SCROLLLOCK')
if modifiers & MOD_COMMAND:
mod_names.append('MOD_COMMAND')
if modifiers & MOD_OPTION:
mod_names.append('MOD_OPTION')
if modifiers & MOD_FUNCTION:
mod_names.append('MOD_FUNCTION')
return '|'.join(mod_names)
def symbol_string(symbol):
"""Return a string describing a key symbol.
Example::
>>> symbol_string(BACKSPACE)
'BACKSPACE'
:Parameters:
`symbol` : int
Symbolic key constant.
:rtype: str
"""
if symbol < 1 << 32:
return _key_names.get(symbol, str(symbol))
else:
return 'user_key(%x)' % (symbol >> 32)
def motion_string(motion):
"""Return a string describing a text motion.
Example::
>>> motion_string(MOTION_NEXT_WORD)
'MOTION_NEXT_WORD'
:Parameters:
`motion` : int
Text motion constant.
:rtype: str
"""
return _motion_names.get(motion, str(motion))
def user_key(scancode):
"""Return a key symbol for a key not supported by pyglet.
This can be used to map virtual keys or scancodes from unsupported
keyboard layouts into a machine-specific symbol. The symbol will
be meaningless on any other machine, or under a different keyboard layout.
Applications should use user-keys only when user explicitly binds them
(for example, mapping keys to actions in a game options screen).
"""
assert scancode > 0
return scancode << 32
# Modifier mask constants
MOD_SHIFT = 1 << 0
MOD_CTRL = 1 << 1
MOD_ALT = 1 << 2
MOD_CAPSLOCK = 1 << 3
MOD_NUMLOCK = 1 << 4
MOD_WINDOWS = 1 << 5
MOD_COMMAND = 1 << 6
MOD_OPTION = 1 << 7
MOD_SCROLLLOCK = 1 << 8
MOD_FUNCTION = 1 << 9
#: Accelerator modifier. On Windows and Linux, this is ``MOD_CTRL``, on
#: Mac OS X it's ``MOD_COMMAND``.
MOD_ACCEL = MOD_CTRL
if compat_platform == 'darwin':
MOD_ACCEL = MOD_COMMAND
# Key symbol constants
# ASCII commands
BACKSPACE = 0xff08
TAB = 0xff09
LINEFEED = 0xff0a
CLEAR = 0xff0b
RETURN = 0xff0d
ENTER = 0xff0d # synonym
PAUSE = 0xff13
SCROLLLOCK = 0xff14
SYSREQ = 0xff15
ESCAPE = 0xff1b
SPACE = 0xff20
# Cursor control and motion
HOME = 0xff50
LEFT = 0xff51
UP = 0xff52
RIGHT = 0xff53
DOWN = 0xff54
PAGEUP = 0xff55
PAGEDOWN = 0xff56
END = 0xff57
BEGIN = 0xff58
# Misc functions
DELETE = 0xffff
SELECT = 0xff60
PRINT = 0xff61
EXECUTE = 0xff62
INSERT = 0xff63
UNDO = 0xff65
REDO = 0xff66
MENU = 0xff67
FIND = 0xff68
CANCEL = 0xff69
HELP = 0xff6a
BREAK = 0xff6b
MODESWITCH = 0xff7e
SCRIPTSWITCH = 0xff7e
FUNCTION = 0xffd2
# Text motion constants: these are allowed to clash with key constants
MOTION_UP = UP
MOTION_RIGHT = RIGHT
MOTION_DOWN = DOWN
MOTION_LEFT = LEFT
MOTION_NEXT_WORD = 1
MOTION_PREVIOUS_WORD = 2
MOTION_BEGINNING_OF_LINE = 3
MOTION_END_OF_LINE = 4
MOTION_NEXT_PAGE = PAGEDOWN
MOTION_PREVIOUS_PAGE = PAGEUP
MOTION_BEGINNING_OF_FILE = 5
MOTION_END_OF_FILE = 6
MOTION_BACKSPACE = BACKSPACE
MOTION_DELETE = DELETE
# Number pad
NUMLOCK = 0xff7f
NUM_SPACE = 0xff80
NUM_TAB = 0xff89
NUM_ENTER = 0xff8d
NUM_F1 = 0xff91
NUM_F2 = 0xff92
NUM_F3 = 0xff93
NUM_F4 = 0xff94
NUM_HOME = 0xff95
NUM_LEFT = 0xff96
NUM_UP = 0xff97
NUM_RIGHT = 0xff98
NUM_DOWN = 0xff99
NUM_PRIOR = 0xff9a
NUM_PAGE_UP = 0xff9a
NUM_NEXT = 0xff9b
NUM_PAGE_DOWN = 0xff9b
NUM_END = 0xff9c
NUM_BEGIN = 0xff9d
NUM_INSERT = 0xff9e
NUM_DELETE = 0xff9f
NUM_EQUAL = 0xffbd
NUM_MULTIPLY = 0xffaa
NUM_ADD = 0xffab
NUM_SEPARATOR = 0xffac
NUM_SUBTRACT = 0xffad
NUM_DECIMAL = 0xffae
NUM_DIVIDE = 0xffaf
NUM_0 = 0xffb0
NUM_1 = 0xffb1
NUM_2 = 0xffb2
NUM_3 = 0xffb3
NUM_4 = 0xffb4
NUM_5 = 0xffb5
NUM_6 = 0xffb6
NUM_7 = 0xffb7
NUM_8 = 0xffb8
NUM_9 = 0xffb9
# Function keys
F1 = 0xffbe
F2 = 0xffbf
F3 = 0xffc0
F4 = 0xffc1
F5 = 0xffc2
F6 = 0xffc3
F7 = 0xffc4
F8 = 0xffc5
F9 = 0xffc6
F10 = 0xffc7
F11 = 0xffc8
F12 = 0xffc9
F13 = 0xffca
F14 = 0xffcb
F15 = 0xffcc
F16 = 0xffcd
F17 = 0xffce
F18 = 0xffcf
F19 = 0xffd0
F20 = 0xffd1
# Modifiers
LSHIFT = 0xffe1
RSHIFT = 0xffe2
LCTRL = 0xffe3
RCTRL = 0xffe4
CAPSLOCK = 0xffe5
LMETA = 0xffe7
RMETA = 0xffe8
LALT = 0xffe9
RALT = 0xffea
LWINDOWS = 0xffeb
RWINDOWS = 0xffec
LCOMMAND = 0xffed
RCOMMAND = 0xffee
LOPTION = 0xffef
ROPTION = 0xfff0
# Latin-1
SPACE = 0x020
EXCLAMATION = 0x021
DOUBLEQUOTE = 0x022
HASH = 0x023
POUND = 0x023 # synonym
DOLLAR = 0x024
PERCENT = 0x025
AMPERSAND = 0x026
APOSTROPHE = 0x027
PARENLEFT = 0x028
PARENRIGHT = 0x029
ASTERISK = 0x02a
PLUS = 0x02b
COMMA = 0x02c
MINUS = 0x02d
PERIOD = 0x02e
SLASH = 0x02f
_0 = 0x030
_1 = 0x031
_2 = 0x032
_3 = 0x033
_4 = 0x034
_5 = 0x035
_6 = 0x036
_7 = 0x037
_8 = 0x038
_9 = 0x039
COLON = 0x03a
SEMICOLON = 0x03b
LESS = 0x03c
EQUAL = 0x03d
GREATER = 0x03e
QUESTION = 0x03f
AT = 0x040
BRACKETLEFT = 0x05b
BACKSLASH = 0x05c
BRACKETRIGHT = 0x05d
ASCIICIRCUM = 0x05e
UNDERSCORE = 0x05f
GRAVE = 0x060
QUOTELEFT = 0x060
A = 0x061
B = 0x062
C = 0x063
D = 0x064
E = 0x065
F = 0x066
G = 0x067
H = 0x068
I = 0x069
J = 0x06a
K = 0x06b
L = 0x06c
M = 0x06d
N = 0x06e
O = 0x06f
P = 0x070
Q = 0x071
R = 0x072
S = 0x073
T = 0x074
U = 0x075
V = 0x076
W = 0x077
X = 0x078
Y = 0x079
Z = 0x07a
BRACELEFT = 0x07b
BAR = 0x07c
BRACERIGHT = 0x07d
ASCIITILDE = 0x07e
_key_names = {}
_motion_names = {}
for _name, _value in locals().copy().items():
if _name[:2] != '__' and _name.upper() == _name and \
not _name.startswith('MOD_'):
if _name.startswith('MOTION_'):
_motion_names[_value] = _name
else:
_key_names[_value] = _name
| 10,731 | 24.251765 | 78 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/pyglet/window/__init__.py
|
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
"""Windowing and user-interface events.
This module allows applications to create and display windows with an
OpenGL context. Windows can be created with a variety of border styles
or set fullscreen.
You can register event handlers for keyboard, mouse and window events.
For games and kiosks you can also restrict the input to your windows,
for example disabling users from switching away from the application
with certain key combinations or capturing and hiding the mouse.
Getting started
---------------
Call the Window constructor to create a new window::
from pyglet.window import Window
win = Window(width=640, height=480)
Attach your own event handlers::
@win.event
def on_key_press(symbol, modifiers):
# ... handle this event ...
Place drawing code for the window within the `Window.on_draw` event handler::
@win.event
def on_draw():
# ... drawing code ...
Call `pyglet.app.run` to enter the main event loop (by default, this
returns when all open windows are closed)::
from pyglet import app
app.run()
Creating a game window
----------------------
Use :py:meth:`~pyglet.window.Window.set_exclusive_mouse` to hide the mouse cursor and receive relative
mouse movement events. Specify ``fullscreen=True`` as a keyword argument to
the :py:class:`~pyglet.window.Window` constructor to render to the entire screen rather than opening a
window::
win = Window(fullscreen=True)
win.set_exclusive_mouse()
Working with multiple screens
-----------------------------
By default, fullscreen windows are opened on the primary display (typically
set by the user in their operating system settings). You can retrieve a list
of attached screens and select one manually if you prefer. This is useful for
opening a fullscreen window on each screen::
display = window.get_platform().get_default_display()
screens = display.get_screens()
windows = []
for screen in screens:
windows.append(window.Window(fullscreen=True, screen=screen))
Specifying a screen has no effect if the window is not fullscreen.
Specifying the OpenGL context properties
----------------------------------------
Each window has its own context which is created when the window is created.
You can specify the properties of the context before it is created
by creating a "template" configuration::
from pyglet import gl
# Create template config
config = gl.Config()
config.stencil_size = 8
config.aux_buffers = 4
# Create a window using this config
win = window.Window(config=config)
To determine if a given configuration is supported, query the screen (see
above, "Working with multiple screens")::
configs = screen.get_matching_configs(config)
if not configs:
# ... config is not supported
else:
win = window.Window(config=configs[0])
"""
from __future__ import division
from builtins import object
from future.utils import with_metaclass
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import sys
import pyglet
from pyglet import gl
from pyglet.event import EventDispatcher
import pyglet.window.key
import pyglet.window.event
_is_pyglet_docgen = hasattr(sys, 'is_pyglet_docgen') and sys.is_pyglet_docgen
class WindowException(Exception):
"""The root exception for all window-related errors."""
pass
class NoSuchDisplayException(WindowException):
"""An exception indicating the requested display is not available."""
pass
class NoSuchConfigException(WindowException):
"""An exception indicating the requested configuration is not
available."""
pass
class NoSuchScreenModeException(WindowException):
"""An exception indicating the requested screen resolution could not be
met."""
pass
class MouseCursorException(WindowException):
"""The root exception for all mouse cursor-related errors."""
pass
class MouseCursor(object):
"""An abstract mouse cursor."""
#: Indicates if the cursor is drawn using OpenGL. This is True
#: for all mouse cursors except system cursors.
drawable = True
def draw(self, x, y):
"""Abstract render method.
The cursor should be drawn with the "hot" spot at the given
coordinates. The projection is set to the pyglet default (i.e.,
orthographic in window-space), however no other aspects of the
state can be assumed.
:Parameters:
`x` : int
X coordinate of the mouse pointer's hot spot.
`y` : int
Y coordinate of the mouse pointer's hot spot.
"""
raise NotImplementedError('abstract')
class DefaultMouseCursor(MouseCursor):
"""The default mouse cursor #sed by the operating system."""
drawable = False
class ImageMouseCursor(MouseCursor):
"""A user-defined mouse cursor created from an image.
Use this class to create your own mouse cursors and assign them
to windows. There are no constraints on the image size or format.
"""
drawable = True
def __init__(self, image, hot_x=0, hot_y=0):
"""Create a mouse cursor from an image.
:Parameters:
`image` : `pyglet.image.AbstractImage`
Image to use for the mouse cursor. It must have a
valid ``texture`` attribute.
`hot_x` : int
X coordinate of the "hot" spot in the image relative to the
image's anchor.
`hot_y` : int
Y coordinate of the "hot" spot in the image, relative to the
image's anchor.
"""
self.texture = image.get_texture()
self.hot_x = hot_x
self.hot_y = hot_y
def draw(self, x, y):
gl.glPushAttrib(gl.GL_ENABLE_BIT | gl.GL_CURRENT_BIT)
gl.glColor4f(1, 1, 1, 1)
gl.glEnable(gl.GL_BLEND)
gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)
self.texture.blit(x - self.hot_x, y - self.hot_y, 0)
gl.glPopAttrib()
def _PlatformEventHandler(data):
"""Decorator for platform event handlers.
Apply giving the platform-specific data needed by the window to associate
the method with an event. See platform-specific subclasses of this
decorator for examples.
The following attributes are set on the function, which is returned
otherwise unchanged:
_platform_event
True
_platform_event_data
List of data applied to the function (permitting multiple decorators
on the same method).
"""
def _event_wrapper(f):
f._platform_event = True
if not hasattr(f, '_platform_event_data'):
f._platform_event_data = []
f._platform_event_data.append(data)
return f
return _event_wrapper
def _ViewEventHandler(f):
f._view = True
return f
class _WindowMetaclass(type):
"""Sets the _platform_event_names class variable on the window
subclass.
"""
def __init__(cls, name, bases, dict):
cls._platform_event_names = set()
for base in bases:
if hasattr(base, '_platform_event_names'):
cls._platform_event_names.update(base._platform_event_names)
for name, func in dict.items():
if hasattr(func, '_platform_event'):
cls._platform_event_names.add(name)
super(_WindowMetaclass, cls).__init__(name, bases, dict)
class BaseWindow(with_metaclass(_WindowMetaclass, EventDispatcher)):
"""Platform-independent application window.
A window is a "heavyweight" object occupying operating system resources.
The "client" or "content" area of a window is filled entirely with
an OpenGL viewport. Applications have no access to operating system
widgets or controls; all rendering must be done via OpenGL.
Windows may appear as floating regions or can be set to fill an entire
screen (fullscreen). When floating, windows may appear borderless or
decorated with a platform-specific frame (including, for example, the
title bar, minimize and close buttons, resize handles, and so on).
While it is possible to set the location of a window, it is recommended
that applications allow the platform to place it according to local
conventions. This will ensure it is not obscured by other windows,
and appears on an appropriate screen for the user.
To render into a window, you must first call `switch_to`, to make
it the current OpenGL context. If you use only one window in the
application, there is no need to do this.
"""
# Filled in by metaclass with the names of all methods on this (sub)class
# that are platform event handlers.
_platform_event_names = set()
#: The default window style.
WINDOW_STYLE_DEFAULT = None
#: The window style for pop-up dialogs.
WINDOW_STYLE_DIALOG = 'dialog'
#: The window style for tool windows.
WINDOW_STYLE_TOOL = 'tool'
#: A window style without any decoration.
WINDOW_STYLE_BORDERLESS = 'borderless'
#: The default mouse cursor.
CURSOR_DEFAULT = None
#: A crosshair mouse cursor.
CURSOR_CROSSHAIR = 'crosshair'
#: A pointing hand mouse cursor.
CURSOR_HAND = 'hand'
#: A "help" mouse cursor; typically a question mark and an arrow.
CURSOR_HELP = 'help'
#: A mouse cursor indicating that the selected operation is not permitted.
CURSOR_NO = 'no'
#: A mouse cursor indicating the element can be resized.
CURSOR_SIZE = 'size'
#: A mouse cursor indicating the element can be resized from the top
#: border.
CURSOR_SIZE_UP = 'size_up'
#: A mouse cursor indicating the element can be resized from the
#: upper-right corner.
CURSOR_SIZE_UP_RIGHT = 'size_up_right'
#: A mouse cursor indicating the element can be resized from the right
#: border.
CURSOR_SIZE_RIGHT = 'size_right'
#: A mouse cursor indicating the element can be resized from the lower-right
#: corner.
CURSOR_SIZE_DOWN_RIGHT = 'size_down_right'
#: A mouse cursor indicating the element can be resized from the bottom
#: border.
CURSOR_SIZE_DOWN = 'size_down'
#: A mouse cursor indicating the element can be resized from the lower-left
#: corner.
CURSOR_SIZE_DOWN_LEFT = 'size_down_left'
#: A mouse cursor indicating the element can be resized from the left
#: border.
CURSOR_SIZE_LEFT = 'size_left'
#: A mouse cursor indicating the element can be resized from the upper-left
#: corner.
CURSOR_SIZE_UP_LEFT = 'size_up_left'
#: A mouse cursor indicating the element can be resized vertically.
CURSOR_SIZE_UP_DOWN = 'size_up_down'
#: A mouse cursor indicating the element can be resized horizontally.
CURSOR_SIZE_LEFT_RIGHT = 'size_left_right'
#: A text input mouse cursor (I-beam).
CURSOR_TEXT = 'text'
#: A "wait" mouse cursor; typically an hourglass or watch.
CURSOR_WAIT = 'wait'
#: The "wait" mouse cursor combined with an arrow.
CURSOR_WAIT_ARROW = 'wait_arrow'
#: True if the user has attempted to close the window.
#:
#: :deprecated: Windows are closed immediately by the default
#: :py:meth:`~pyglet.window.Window.on_close` handler when `pyglet.app.event_loop` is being
#: used.
has_exit = False
#: Window display contents validity. The :py:mod:`pyglet.app` event loop
#: examines every window each iteration and only dispatches the :py:meth:`~pyglet.window.Window.on_draw`
#: event to windows that have `invalid` set. By default, windows always
#: have `invalid` set to ``True``.
#:
#: You can prevent redundant redraws by setting this variable to ``False``
#: in the window's :py:meth:`~pyglet.window.Window.on_draw` handler, and setting it to True again in
#: response to any events that actually do require a window contents
#: update.
#:
#: :type: bool
#: .. versionadded:: 1.1
invalid = True
#: Legacy invalidation flag introduced in pyglet 1.2: set by all event
#: dispatches that go to non-empty handlers. The default 1.2 event loop
#: will therefore redraw after any handled event or scheduled function.
_legacy_invalid = True
# Instance variables accessible only via properties
_width = None
_height = None
_caption = None
_resizable = False
_style = WINDOW_STYLE_DEFAULT
_fullscreen = False
_visible = False
_vsync = False
_screen = None
_config = None
_context = None
# Used to restore window size and position after fullscreen
_windowed_size = None
_windowed_location = None
# Subclasses should update these after relevant events
_mouse_cursor = DefaultMouseCursor()
_mouse_x = 0
_mouse_y = 0
_mouse_visible = True
_mouse_exclusive = False
_mouse_in_window = False
_event_queue = None
_enable_event_queue = True # overridden by EventLoop.
_allow_dispatch_event = False # controlled by dispatch_events stack frame
# Class attributes
_default_width = 640
_default_height = 480
def __init__(self,
width=None,
height=None,
caption=None,
resizable=False,
style=WINDOW_STYLE_DEFAULT,
fullscreen=False,
visible=True,
vsync=True,
display=None,
screen=None,
config=None,
context=None,
mode=None):
"""Create a window.
All parameters are optional, and reasonable defaults are assumed
where they are not specified.
The `display`, `screen`, `config` and `context` parameters form
a hierarchy of control: there is no need to specify more than
one of these. For example, if you specify `screen` the `display`
will be inferred, and a default `config` and `context` will be
created.
`config` is a special case; it can be a template created by the
user specifying the attributes desired, or it can be a complete
`config` as returned from `Screen.get_matching_configs` or similar.
The context will be active as soon as the window is created, as if
`switch_to` was just called.
:Parameters:
`width` : int
Width of the window, in pixels. Defaults to 640, or the
screen width if `fullscreen` is True.
`height` : int
Height of the window, in pixels. Defaults to 480, or the
screen height if `fullscreen` is True.
`caption` : str or unicode
Initial caption (title) of the window. Defaults to
``sys.argv[0]``.
`resizable` : bool
If True, the window will be resizable. Defaults to False.
`style` : int
One of the ``WINDOW_STYLE_*`` constants specifying the
border style of the window.
`fullscreen` : bool
If True, the window will cover the entire screen rather
than floating. Defaults to False.
`visible` : bool
Determines if the window is visible immediately after
creation. Defaults to True. Set this to False if you
would like to change attributes of the window before
having it appear to the user.
`vsync` : bool
If True, buffer flips are synchronised to the primary screen's
vertical retrace, eliminating flicker.
`display` : `Display`
The display device to use. Useful only under X11.
`screen` : `Screen`
The screen to use, if in fullscreen.
`config` : `pyglet.gl.Config`
Either a template from which to create a complete config,
or a complete config.
`context` : `pyglet.gl.Context`
The context to attach to this window. The context must
not already be attached to another window.
`mode` : `ScreenMode`
The screen will be switched to this mode if `fullscreen` is
True. If None, an appropriate mode is selected to accomodate
`width` and `height.`
"""
EventDispatcher.__init__(self)
self._event_queue = []
if not display:
display = get_platform().get_default_display()
if not screen:
screen = display.get_default_screen()
if not config:
for template_config in [
gl.Config(double_buffer=True, depth_size=24),
gl.Config(double_buffer=True, depth_size=16),
None]:
try:
config = screen.get_best_config(template_config)
break
except NoSuchConfigException:
pass
if not config:
raise NoSuchConfigException('No standard config is available.')
if not config.is_complete():
config = screen.get_best_config(config)
if not context:
context = config.create_context(gl.current_context)
# Set these in reverse order to above, to ensure we get user
# preference
self._context = context
self._config = self._context.config
# XXX deprecate config's being screen-specific
if hasattr(self._config, 'screen'):
self._screen = self._config.screen
else:
display = self._config.canvas.display
self._screen = display.get_default_screen()
self._display = self._screen.display
if fullscreen:
if width is None and height is None:
self._windowed_size = self._default_width, self._default_height
width, height = self._set_fullscreen_mode(mode, width, height)
if not self._windowed_size:
self._windowed_size = width, height
else:
if width is None:
width = self._default_width
if height is None:
height = self._default_height
self._width = width
self._height = height
self._resizable = resizable
self._fullscreen = fullscreen
self._style = style
if pyglet.options['vsync'] is not None:
self._vsync = pyglet.options['vsync']
else:
self._vsync = vsync
if caption is None:
caption = sys.argv[0]
# Decode hack for Python2 unicode support:
if hasattr(caption, "decode"):
try:
caption = caption.decode("utf8")
except UnicodeDecodeError:
caption = "pyglet"
self._caption = caption
from pyglet import app
app.windows.add(self)
self._create()
self.switch_to()
if visible:
self.set_visible(True)
self.activate()
def __del__(self):
# Always try to clean up the window when it is dereferenced.
# Makes sure there are no dangling pointers or memory leaks.
# If the window is already closed, pass silently.
try:
self.close()
except: # XXX Avoid a NoneType error if already closed.
pass
def __repr__(self):
return '%s(width=%d, height=%d)' % \
(self.__class__.__name__, self.width, self.height)
def _create(self):
raise NotImplementedError('abstract')
def _recreate(self, changes):
"""Recreate the window with current attributes.
:Parameters:
`changes` : list of str
List of attribute names that were changed since the last
`_create` or `_recreate`. For example, ``['fullscreen']``
is given if the window is to be toggled to or from fullscreen.
"""
raise NotImplementedError('abstract')
def flip(self):
"""Swap the OpenGL front and back buffers.
Call this method on a double-buffered window to update the
visible display with the back buffer. The contents of the back buffer
is undefined after this operation.
Windows are double-buffered by default. This method is called
automatically by `EventLoop` after the :py:meth:`~pyglet.window.Window.on_draw` event.
"""
raise NotImplementedError('abstract')
def switch_to(self):
"""Make this window the current OpenGL rendering context.
Only one OpenGL context can be active at a time. This method sets
the current window's context to be current. You should use this
method in preference to `pyglet.gl.Context.set_current`, as it may
perform additional initialisation functions.
"""
raise NotImplementedError('abstract')
def set_fullscreen(self, fullscreen=True, screen=None, mode=None,
width=None, height=None):
"""Toggle to or from fullscreen.
After toggling fullscreen, the GL context should have retained its
state and objects, however the buffers will need to be cleared and
redrawn.
If `width` and `height` are specified and `fullscreen` is True, the
screen may be switched to a different resolution that most closely
matches the given size. If the resolution doesn't match exactly,
a higher resolution is selected and the window will be centered
within a black border covering the rest of the screen.
:Parameters:
`fullscreen` : bool
True if the window should be made fullscreen, False if it
should be windowed.
`screen` : Screen
If not None and fullscreen is True, the window is moved to the
given screen. The screen must belong to the same display as
the window.
`mode` : `ScreenMode`
The screen will be switched to the given mode. The mode must
have been obtained by enumerating `Screen.get_modes`. If
None, an appropriate mode will be selected from the given
`width` and `height`.
`width` : int
Optional width of the window. If unspecified, defaults to the
previous window size when windowed, or the screen size if
fullscreen.
.. versionadded:: 1.2
`height` : int
Optional height of the window. If unspecified, defaults to
the previous window size when windowed, or the screen size if
fullscreen.
.. versionadded:: 1.2
"""
if (fullscreen == self._fullscreen and
(screen is None or screen is self._screen) and
(width is None or width == self._width) and
(height is None or height == self._height)):
return
if not self._fullscreen:
# Save windowed size
self._windowed_size = self.get_size()
self._windowed_location = self.get_location()
if fullscreen and screen is not None:
assert screen.display is self.display
self._screen = screen
self._fullscreen = fullscreen
if self._fullscreen:
self._width, self._height = self._set_fullscreen_mode(
mode, width, height)
else:
self.screen.restore_mode()
self._width, self._height = self._windowed_size
if width is not None:
self._width = width
if height is not None:
self._height = height
self._recreate(['fullscreen'])
if not self._fullscreen and self._windowed_location:
# Restore windowed location.
# TODO: Move into platform _create?
# Not harmless on Carbon because upsets _width and _height
# via _on_window_bounds_changed.
if pyglet.compat_platform != 'darwin' or pyglet.options['darwin_cocoa']:
self.set_location(*self._windowed_location)
def _set_fullscreen_mode(self, mode, width, height):
if mode is not None:
self.screen.set_mode(mode)
if width is None:
width = self.screen.width
if height is None:
height = self.screen.height
elif width is not None or height is not None:
if width is None:
width = 0
if height is None:
height = 0
mode = self.screen.get_closest_mode(width, height)
if mode is not None:
self.screen.set_mode(mode)
elif self.screen.get_modes():
# Only raise exception if mode switching is at all possible.
raise NoSuchScreenModeException(
'No mode matching %dx%d' % (width, height))
else:
width = self.screen.width
height = self.screen.height
return width, height
def on_resize(self, width, height):
"""A default resize event handler.
This default handler updates the GL viewport to cover the entire
window and sets the ``GL_PROJECTION`` matrix to be orthogonal in
window space. The bottom-left corner is (0, 0) and the top-right
corner is the width and height of the window in pixels.
Override this event handler with your own to create another
projection, for example in perspective.
"""
viewport = self.get_viewport_size()
gl.glViewport(0, 0, max(1, viewport[0]), max(1, viewport[1]))
gl.glMatrixMode(gl.GL_PROJECTION)
gl.glLoadIdentity()
gl.glOrtho(0, max(1, width), 0, max(1, height), -1, 1)
gl.glMatrixMode(gl.GL_MODELVIEW)
def on_close(self):
"""Default on_close handler."""
self.has_exit = True
from pyglet import app
if app.event_loop.is_running:
self.close()
def on_key_press(self, symbol, modifiers):
"""Default on_key_press handler."""
if symbol == key.ESCAPE and not (modifiers & ~(key.MOD_NUMLOCK |
key.MOD_CAPSLOCK |
key.MOD_SCROLLLOCK)):
self.dispatch_event('on_close')
def close(self):
"""Close the window.
After closing the window, the GL context will be invalid. The
window instance cannot be reused once closed (see also `set_visible`).
The `pyglet.app.EventLoop.on_window_close` event is dispatched on
`pyglet.app.event_loop` when this method is called.
"""
from pyglet import app
if not self._context:
return
app.windows.remove(self)
self._context.destroy()
self._config = None
self._context = None
if app.event_loop:
app.event_loop.dispatch_event('on_window_close', self)
self._event_queue = []
def draw_mouse_cursor(self):
"""Draw the custom mouse cursor.
If the current mouse cursor has ``drawable`` set, this method
is called before the buffers are flipped to render it.
This method always leaves the ``GL_MODELVIEW`` matrix as current,
regardless of what it was set to previously. No other GL state
is affected.
There is little need to override this method; instead, subclass
:py:class:`MouseCursor` and provide your own
:py:meth:`~MouseCursor.draw` method.
"""
# Draw mouse cursor if set and visible.
# XXX leaves state in modelview regardless of starting state
if (self._mouse_cursor.drawable and
self._mouse_visible and
self._mouse_in_window):
gl.glMatrixMode(gl.GL_PROJECTION)
gl.glPushMatrix()
gl.glLoadIdentity()
gl.glOrtho(0, self.width, 0, self.height, -1, 1)
gl.glMatrixMode(gl.GL_MODELVIEW)
gl.glPushMatrix()
gl.glLoadIdentity()
self._mouse_cursor.draw(self._mouse_x, self._mouse_y)
gl.glMatrixMode(gl.GL_PROJECTION)
gl.glPopMatrix()
gl.glMatrixMode(gl.GL_MODELVIEW)
gl.glPopMatrix()
# Properties provide read-only access to instance variables. Use
# set_* methods to change them if applicable.
@property
def caption(self):
"""The window caption (title). Read-only.
:type: str
"""
return self._caption
@property
def resizeable(self):
"""True if the window is resizable. Read-only.
:type: bool
"""
return self._resizable
@property
def style(self):
"""The window style; one of the ``WINDOW_STYLE_*`` constants.
Read-only.
:type: int
"""
return self._style
@property
def fullscreen(self):
"""True if the window is currently fullscreen. Read-only.
:type: bool
"""
return self._fullscreen
@property
def visible(self):
"""True if the window is currently visible. Read-only.
:type: bool
"""
return self._visible
@property
def vsync(self):
"""True if buffer flips are synchronised to the screen's vertical
retrace. Read-only.
:type: bool
"""
return self._vsync
@property
def display(self):
"""The display this window belongs to. Read-only.
:type: :py:class:`Display`
"""
return self._display
@property
def screen(self):
"""The screen this window is fullscreen in. Read-only.
:type: :py:class:`Screen`
"""
return self._screen
@property
def config(self):
"""A GL config describing the context of this window. Read-only.
:type: :py:class:`pyglet.gl.Config`
"""
return self._config
@property
def context(self):
"""The OpenGL context attached to this window. Read-only.
:type: :py:class:`pyglet.gl.Context`
"""
return self._context
# These are the only properties that can be set
@property
def width(self):
"""The width of the window, in pixels. Read-write.
:type: int
"""
return self.get_size()[0]
@width.setter
def width(self, new_width):
self.set_size(new_width, self.height)
@property
def height(self):
"""The height of the window, in pixels. Read-write.
:type: int
"""
return self.get_size()[1]
@height.setter
def height(self, new_height):
self.set_size(self.width, new_height)
def set_caption(self, caption):
"""Set the window's caption.
The caption appears in the titlebar of the window, if it has one,
and in the taskbar on Windows and many X11 window managers.
:Parameters:
`caption` : str or unicode
The caption to set.
"""
raise NotImplementedError('abstract')
def set_minimum_size(self, width, height):
"""Set the minimum size of the window.
Once set, the user will not be able to resize the window smaller
than the given dimensions. There is no way to remove the
minimum size constraint on a window (but you could set it to 0,0).
The behaviour is undefined if the minimum size is set larger than
the current size of the window.
The window size does not include the border or title bar.
:Parameters:
`width` : int
Minimum width of the window, in pixels.
`height` : int
Minimum height of the window, in pixels.
"""
raise NotImplementedError('abstract')
def set_maximum_size(self, width, height):
"""Set the maximum size of the window.
Once set, the user will not be able to resize the window larger
than the given dimensions. There is no way to remove the
maximum size constraint on a window (but you could set it to a large
value).
The behaviour is undefined if the maximum size is set smaller than
the current size of the window.
The window size does not include the border or title bar.
:Parameters:
`width` : int
Maximum width of the window, in pixels.
`height` : int
Maximum height of the window, in pixels.
"""
raise NotImplementedError('abstract')
def set_size(self, width, height):
"""Resize the window.
The behaviour is undefined if the window is not resizable, or if
it is currently fullscreen.
The window size does not include the border or title bar.
:Parameters:
`width` : int
New width of the window, in pixels.
`height` : int
New height of the window, in pixels.
"""
raise NotImplementedError('abstract')
def get_size(self):
"""Return the current size of the window.
The window size does not include the border or title bar.
:rtype: (int, int)
:return: The width and height of the window, in pixels.
"""
raise NotImplementedError('abstract')
def get_viewport_size(self):
"""Return the size in actual pixels of the viewport.
When using HiDPI screens, the actual number of pixels used to render
is higher than that of the coordinates used. Each virtual pixel is made
up of multiple actual pixels in the hardware. When manually setting
the viewport using glViewport, this size should be used instead of
`Window.get_size()`.
:rtype: (int, int)
:return: The width and height of the viewport, in pixels.
"""
return self.get_size()
def set_location(self, x, y):
"""Set the position of the window.
:Parameters:
`x` : int
Distance of the left edge of the window from the left edge
of the virtual desktop, in pixels.
`y` : int
Distance of the top edge of the window from the top edge of
the virtual desktop, in pixels.
"""
raise NotImplementedError('abstract')
def get_location(self):
"""Return the current position of the window.
:rtype: (int, int)
:return: The distances of the left and top edges from their respective
edges on the virtual desktop, in pixels.
"""
raise NotImplementedError('abstract')
def activate(self):
"""Attempt to restore keyboard focus to the window.
Depending on the window manager or operating system, this may not
be successful. For example, on Windows XP an application is not
allowed to "steal" focus from another application. Instead, the
window's taskbar icon will flash, indicating it requires attention.
"""
raise NotImplementedError('abstract')
def set_visible(self, visible=True):
"""Show or hide the window.
:Parameters:
`visible` : bool
If True, the window will be shown; otherwise it will be
hidden.
"""
raise NotImplementedError('abstract')
def minimize(self):
"""Minimize the window.
"""
raise NotImplementedError('abstract')
def maximize(self):
"""Maximize the window.
The behaviour of this method is somewhat dependent on the user's
display setup. On a multi-monitor system, the window may maximize
to either a single screen or the entire virtual desktop.
"""
raise NotImplementedError('abstract')
def set_vsync(self, vsync):
"""Enable or disable vertical sync control.
When enabled, this option ensures flips from the back to the front
buffer are performed only during the vertical retrace period of the
primary display. This can prevent "tearing" or flickering when
the buffer is updated in the middle of a video scan.
Note that LCD monitors have an analogous time in which they are not
reading from the video buffer; while it does not correspond to
a vertical retrace it has the same effect.
With multi-monitor systems the secondary monitor cannot be
synchronised to, so tearing and flicker cannot be avoided when the
window is positioned outside of the primary display. In this case
it may be advisable to forcibly reduce the framerate (for example,
using `pyglet.clock.set_fps_limit`).
:Parameters:
`vsync` : bool
If True, vsync is enabled, otherwise it is disabled.
"""
raise NotImplementedError('abstract')
def set_mouse_visible(self, visible=True):
"""Show or hide the mouse cursor.
The mouse cursor will only be hidden while it is positioned within
this window. Mouse events will still be processed as usual.
:Parameters:
`visible` : bool
If True, the mouse cursor will be visible, otherwise it
will be hidden.
"""
self._mouse_visible = visible
self.set_mouse_platform_visible()
def set_mouse_platform_visible(self, platform_visible=None):
"""Set the platform-drawn mouse cursor visibility. This is called
automatically after changing the mouse cursor or exclusive mode.
Applications should not normally need to call this method, see
`set_mouse_visible` instead.
:Parameters:
`platform_visible` : bool or None
If None, sets platform visibility to the required visibility
for the current exclusive mode and cursor type. Otherwise,
a bool value will override and force a visibility.
"""
raise NotImplementedError()
def set_mouse_cursor(self, cursor=None):
"""Change the appearance of the mouse cursor.
The appearance of the mouse cursor is only changed while it is
within this window.
:Parameters:
`cursor` : `MouseCursor`
The cursor to set, or None to restore the default cursor.
"""
if cursor is None:
cursor = DefaultMouseCursor()
self._mouse_cursor = cursor
self.set_mouse_platform_visible()
def set_exclusive_mouse(self, exclusive=True):
"""Hide the mouse cursor and direct all mouse events to this
window.
When enabled, this feature prevents the mouse leaving the window. It
is useful for certain styles of games that require complete control of
the mouse. The position of the mouse as reported in subsequent events
is meaningless when exclusive mouse is enabled; you should only use
the relative motion parameters ``dx`` and ``dy``.
:Parameters:
`exclusive` : bool
If True, exclusive mouse is enabled, otherwise it is disabled.
"""
raise NotImplementedError('abstract')
def set_exclusive_keyboard(self, exclusive=True):
"""Prevent the user from switching away from this window using
keyboard accelerators.
When enabled, this feature disables certain operating-system specific
key combinations such as Alt+Tab (Command+Tab on OS X). This can be
useful in certain kiosk applications, it should be avoided in general
applications or games.
:Parameters:
`exclusive` : bool
If True, exclusive keyboard is enabled, otherwise it is
disabled.
"""
raise NotImplementedError('abstract')
def get_system_mouse_cursor(self, name):
"""Obtain a system mouse cursor.
Use `set_mouse_cursor` to make the cursor returned by this method
active. The names accepted by this method are the ``CURSOR_*``
constants defined on this class.
:Parameters:
`name` : str
Name describing the mouse cursor to return. For example,
``CURSOR_WAIT``, ``CURSOR_HELP``, etc.
:rtype: `MouseCursor`
:return: A mouse cursor which can be used with `set_mouse_cursor`.
"""
raise NotImplementedError()
def set_icon(self, *images):
"""Set the window icon.
If multiple images are provided, one with an appropriate size
will be selected (if the correct size is not provided, the image
will be scaled).
Useful sizes to provide are 16x16, 32x32, 64x64 (Mac only) and
128x128 (Mac only).
:Parameters:
`images` : sequence of `pyglet.image.AbstractImage`
List of images to use for the window icon.
"""
pass
def clear(self):
"""Clear the window.
This is a convenience method for clearing the color and depth
buffer. The window must be the active context (see `switch_to`).
"""
gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)
def dispatch_event(self, *args):
if not self._enable_event_queue or self._allow_dispatch_event:
if EventDispatcher.dispatch_event(self, *args) != False:
self._legacy_invalid = True
else:
self._event_queue.append(args)
def dispatch_events(self):
"""Poll the operating system event queue for new events and call
attached event handlers.
This method is provided for legacy applications targeting pyglet 1.0,
and advanced applications that must integrate their event loop
into another framework.
Typical applications should use `pyglet.app.run`.
"""
raise NotImplementedError('abstract')
# If documenting, show the event methods. Otherwise, leave them out
# as they are not really methods.
if _is_pyglet_docgen:
def on_key_press(symbol, modifiers):
"""A key on the keyboard was pressed (and held down).
In pyglet 1.0 the default handler sets `has_exit` to ``True`` if
the ``ESC`` key is pressed.
In pyglet 1.1 the default handler dispatches the :py:meth:`~pyglet.window.Window.on_close`
event if the ``ESC`` key is pressed.
:Parameters:
`symbol` : int
The key symbol pressed.
`modifiers` : int
Bitwise combination of the key modifiers active.
:event:
"""
def on_key_release(symbol, modifiers):
"""A key on the keyboard was released.
:Parameters:
`symbol` : int
The key symbol pressed.
`modifiers` : int
Bitwise combination of the key modifiers active.
:event:
"""
def on_text(text):
"""The user input some text.
Typically this is called after :py:meth:`~pyglet.window.Window.on_key_press` and before
:py:meth:`~pyglet.window.Window.on_key_release`, but may also be called multiple times if the key
is held down (key repeating); or called without key presses if
another input method was used (e.g., a pen input).
You should always use this method for interpreting text, as the
key symbols often have complex mappings to their unicode
representation which this event takes care of.
:Parameters:
`text` : unicode
The text entered by the user.
:event:
"""
def on_text_motion(motion):
"""The user moved the text input cursor.
Typically this is called after :py:meth:`~pyglet.window.Window.on_key_press` and before
:py:meth:`~pyglet.window.Window.on_key_release`, but may also be called multiple times if the key
is help down (key repeating).
You should always use this method for moving the text input cursor
(caret), as different platforms have different default keyboard
mappings, and key repeats are handled correctly.
The values that `motion` can take are defined in
:py:mod:`pyglet.window.key`:
* MOTION_UP
* MOTION_RIGHT
* MOTION_DOWN
* MOTION_LEFT
* MOTION_NEXT_WORD
* MOTION_PREVIOUS_WORD
* MOTION_BEGINNING_OF_LINE
* MOTION_END_OF_LINE
* MOTION_NEXT_PAGE
* MOTION_PREVIOUS_PAGE
* MOTION_BEGINNING_OF_FILE
* MOTION_END_OF_FILE
* MOTION_BACKSPACE
* MOTION_DELETE
:Parameters:
`motion` : int
The direction of motion; see remarks.
:event:
"""
def on_text_motion_select(motion):
"""The user moved the text input cursor while extending the
selection.
Typically this is called after :py:meth:`~pyglet.window.Window.on_key_press` and before
:py:meth:`~pyglet.window.Window.on_key_release`, but may also be called multiple times if the key
is help down (key repeating).
You should always use this method for responding to text selection
events rather than the raw :py:meth:`~pyglet.window.Window.on_key_press`, as different platforms
have different default keyboard mappings, and key repeats are
handled correctly.
The values that `motion` can take are defined in :py:mod:`pyglet.window.key`:
* MOTION_UP
* MOTION_RIGHT
* MOTION_DOWN
* MOTION_LEFT
* MOTION_NEXT_WORD
* MOTION_PREVIOUS_WORD
* MOTION_BEGINNING_OF_LINE
* MOTION_END_OF_LINE
* MOTION_NEXT_PAGE
* MOTION_PREVIOUS_PAGE
* MOTION_BEGINNING_OF_FILE
* MOTION_END_OF_FILE
:Parameters:
`motion` : int
The direction of selection motion; see remarks.
:event:
"""
def on_mouse_motion(x, y, dx, dy):
"""The mouse was moved with no buttons held down.
:Parameters:
`x` : int
Distance in pixels from the left edge of the window.
`y` : int
Distance in pixels from the bottom edge of the window.
`dx` : int
Relative X position from the previous mouse position.
`dy` : int
Relative Y position from the previous mouse position.
:event:
"""
def on_mouse_drag(x, y, dx, dy, buttons, modifiers):
"""The mouse was moved with one or more mouse buttons pressed.
This event will continue to be fired even if the mouse leaves
the window, so long as the drag buttons are continuously held down.
:Parameters:
`x` : int
Distance in pixels from the left edge of the window.
`y` : int
Distance in pixels from the bottom edge of the window.
`dx` : int
Relative X position from the previous mouse position.
`dy` : int
Relative Y position from the previous mouse position.
`buttons` : int
Bitwise combination of the mouse buttons currently pressed.
`modifiers` : int
Bitwise combination of any keyboard modifiers currently
active.
:event:
"""
def on_mouse_press(x, y, button, modifiers):
"""A mouse button was pressed (and held down).
:Parameters:
`x` : int
Distance in pixels from the left edge of the window.
`y` : int
Distance in pixels from the bottom edge of the window.
`button` : int
The mouse button that was pressed.
`modifiers` : int
Bitwise combination of any keyboard modifiers currently
active.
:event:
"""
def on_mouse_release(x, y, button, modifiers):
"""A mouse button was released.
:Parameters:
`x` : int
Distance in pixels from the left edge of the window.
`y` : int
Distance in pixels from the bottom edge of the window.
`button` : int
The mouse button that was released.
`modifiers` : int
Bitwise combination of any keyboard modifiers currently
active.
:event:
"""
def on_mouse_scroll(x, y, scroll_x, scroll_y):
"""The mouse wheel was scrolled.
Note that most mice have only a vertical scroll wheel, so
`scroll_x` is usually 0. An exception to this is the Apple Mighty
Mouse, which has a mouse ball in place of the wheel which allows
both `scroll_x` and `scroll_y` movement.
:Parameters:
`x` : int
Distance in pixels from the left edge of the window.
`y` : int
Distance in pixels from the bottom edge of the window.
`scroll_x` : int
Number of "clicks" towards the right (left if negative).
`scroll_y` : int
Number of "clicks" upwards (downwards if negative).
:event:
"""
def on_close():
"""The user attempted to close the window.
This event can be triggered by clicking on the "X" control box in
the window title bar, or by some other platform-dependent manner.
The default handler sets `has_exit` to ``True``. In pyglet 1.1, if
`pyglet.app.event_loop` is being used, `close` is also called,
closing the window immediately.
:event:
"""
def on_mouse_enter(x, y):
"""The mouse was moved into the window.
This event will not be trigged if the mouse is currently being
dragged.
:Parameters:
`x` : int
Distance in pixels from the left edge of the window.
`y` : int
Distance in pixels from the bottom edge of the window.
:event:
"""
def on_mouse_leave(x, y):
"""The mouse was moved outside of the window.
This event will not be trigged if the mouse is currently being
dragged. Note that the coordinates of the mouse pointer will be
outside of the window rectangle.
:Parameters:
`x` : int
Distance in pixels from the left edge of the window.
`y` : int
Distance in pixels from the bottom edge of the window.
:event:
"""
def on_expose():
"""A portion of the window needs to be redrawn.
This event is triggered when the window first appears, and any time
the contents of the window is invalidated due to another window
obscuring it.
There is no way to determine which portion of the window needs
redrawing. Note that the use of this method is becoming
increasingly uncommon, as newer window managers composite windows
automatically and keep a backing store of the window contents.
:event:
"""
def on_resize(width, height):
"""The window was resized.
The window will have the GL context when this event is dispatched;
there is no need to call `switch_to` in this handler.
:Parameters:
`width` : int
The new width of the window, in pixels.
`height` : int
The new height of the window, in pixels.
:event:
"""
def on_move(x, y):
"""The window was moved.
:Parameters:
`x` : int
Distance from the left edge of the screen to the left edge
of the window.
`y` : int
Distance from the top edge of the screen to the top edge of
the window. Note that this is one of few methods in pyglet
which use a Y-down coordinate system.
:event:
"""
def on_activate():
"""The window was activated.
This event can be triggered by clicking on the title bar, bringing
it to the foreground; or by some platform-specific method.
When a window is "active" it has the keyboard focus.
:event:
"""
def on_deactivate():
"""The window was deactivated.
This event can be triggered by clicking on another application
window. When a window is deactivated it no longer has the
keyboard focus.
:event:
"""
def on_show():
"""The window was shown.
This event is triggered when a window is restored after being
minimised, or after being displayed for the first time.
:event:
"""
def on_hide():
"""The window was hidden.
This event is triggered when a window is minimised or (on Mac OS X)
hidden by the user.
:event:
"""
def on_context_lost():
"""The window's GL context was lost.
When the context is lost no more GL methods can be called until it
is recreated. This is a rare event, triggered perhaps by the user
switching to an incompatible video mode. When it occurs, an
application will need to reload all objects (display lists, texture
objects, shaders) as well as restore the GL state.
:event:
"""
def on_context_state_lost():
"""The state of the window's GL context was lost.
pyglet may sometimes need to recreate the window's GL context if
the window is moved to another video device, or between fullscreen
or windowed mode. In this case it will try to share the objects
(display lists, texture objects, shaders) between the old and new
contexts. If this is possible, only the current state of the GL
context is lost, and the application should simply restore state.
:event:
"""
def on_draw():
"""The window contents must be redrawn.
The `EventLoop` will dispatch this event when the window
should be redrawn. This will happen during idle time after
any window events and after any scheduled functions were called.
The window will already have the GL context, so there is no
need to call `switch_to`. The window's `flip` method will
be called after this event, so your event handler should not.
You should make no assumptions about the window contents when
this event is triggered; a resize or expose event may have
invalidated the framebuffer since the last time it was drawn.
.. versionadded:: 1.1
:event:
"""
BaseWindow.register_event_type('on_key_press')
BaseWindow.register_event_type('on_key_release')
BaseWindow.register_event_type('on_text')
BaseWindow.register_event_type('on_text_motion')
BaseWindow.register_event_type('on_text_motion_select')
BaseWindow.register_event_type('on_mouse_motion')
BaseWindow.register_event_type('on_mouse_drag')
BaseWindow.register_event_type('on_mouse_press')
BaseWindow.register_event_type('on_mouse_release')
BaseWindow.register_event_type('on_mouse_scroll')
BaseWindow.register_event_type('on_mouse_enter')
BaseWindow.register_event_type('on_mouse_leave')
BaseWindow.register_event_type('on_close')
BaseWindow.register_event_type('on_expose')
BaseWindow.register_event_type('on_resize')
BaseWindow.register_event_type('on_move')
BaseWindow.register_event_type('on_activate')
BaseWindow.register_event_type('on_deactivate')
BaseWindow.register_event_type('on_show')
BaseWindow.register_event_type('on_hide')
BaseWindow.register_event_type('on_context_lost')
BaseWindow.register_event_type('on_context_state_lost')
BaseWindow.register_event_type('on_draw')
class FPSDisplay(object):
"""Display of a window's framerate.
This is a convenience class to aid in profiling and debugging. Typical
usage is to create an `FPSDisplay` for each window, and draw the display
at the end of the windows' :py:meth:`~pyglet.window.Window.on_draw` event handler::
window = pyglet.window.Window()
fps_display = FPSDisplay(window)
@window.event
def on_draw():
# ... perform ordinary window drawing operations ...
fps_display.draw()
The style and position of the display can be modified via the :py:func:`~pyglet.text.Label`
attribute. Different text can be substituted by overriding the
`set_fps` method. The display can be set to update more or less often
by setting the `update_period` attribute.
:Ivariables:
`label` : Label
The text label displaying the framerate.
"""
#: Time in seconds between updates.
#:
#: :type: float
update_period = 0.25
def __init__(self, window):
from time import time
from pyglet.text import Label
self.label = Label('', x=10, y=10,
font_size=24, bold=True,
color=(127, 127, 127, 127))
self.window = window
self._window_flip = window.flip
window.flip = self._hook_flip
self.time = 0.0
self.last_time = time()
self.count = 0
def update(self):
"""Records a new data point at the current time. This method
is called automatically when the window buffer is flipped.
"""
from time import time
t = time()
self.count += 1
self.time += t - self.last_time
self.last_time = t
if self.time >= self.update_period:
self.set_fps(self.count / self.update_period)
self.time %= self.update_period
self.count = 0
def set_fps(self, fps):
"""Set the label text for the given FPS estimation.
Called by `update` every `update_period` seconds.
:Parameters:
`fps` : float
Estimated framerate of the window.
"""
self.label.text = '%.2f' % fps
def draw(self):
"""Draw the label.
The OpenGL state is assumed to be at default values, except
that the MODELVIEW and PROJECTION matrices are ignored. At
the return of this method the matrix mode will be MODELVIEW.
"""
gl.glMatrixMode(gl.GL_MODELVIEW)
gl.glPushMatrix()
gl.glLoadIdentity()
gl.glMatrixMode(gl.GL_PROJECTION)
gl.glPushMatrix()
gl.glLoadIdentity()
gl.glOrtho(0, self.window.width, 0, self.window.height, -1, 1)
self.label.draw()
gl.glPopMatrix()
gl.glMatrixMode(gl.GL_MODELVIEW)
gl.glPopMatrix()
def _hook_flip(self):
self.update()
self._window_flip()
if _is_pyglet_docgen:
# We are building documentation
Window = BaseWindow
Window.__name__ = 'Window'
del BaseWindow
else:
# Try to determine which platform to use.
if pyglet.compat_platform == 'darwin':
if pyglet.options['darwin_cocoa']:
from pyglet.window.cocoa import CocoaWindow as Window
else:
from pyglet.window.carbon import CarbonWindow as Window
elif pyglet.compat_platform in ('win32', 'cygwin'):
from pyglet.window.win32 import Win32Window as Window
else:
# XXX HACK around circ problem, should be fixed after removal of
# shadow nonsense
#pyglet.window = sys.modules[__name__]
#import key, mouse
from pyglet.window.xlib import XlibWindow as Window
# Deprecated API
def get_platform():
"""Get an instance of the Platform most appropriate for this
system.
:deprecated: Use `pyglet.canvas.Display`.
:rtype: :py:class:`Platform`
:return: The platform instance.
"""
return Platform()
class Platform(object):
"""Operating-system-level functionality.
The platform instance can only be obtained with `get_platform`. Use
the platform to obtain a `Display` instance.
:deprecated: Use `pyglet.canvas.Display`
"""
def get_display(self, name):
"""Get a display device by name.
This is meaningful only under X11, where the `name` is a
string including the host name and display number; for example
``"localhost:1"``.
On platforms other than X11, `name` is ignored and the default
display is returned. pyglet does not support multiple multiple
video devices on Windows or OS X. If more than one device is
attached, they will appear as a single virtual device comprising
all the attached screens.
:deprecated: Use `pyglet.canvas.get_display`.
:Parameters:
`name` : str
The name of the display to connect to.
:rtype: `Display`
"""
for display in pyglet.app.displays:
if display.name == name:
return display
return pyglet.canvas.Display(name)
def get_default_display(self):
"""Get the default display device.
:deprecated: Use `pyglet.canvas.get_display`.
:rtype: `Display`
"""
return pyglet.canvas.get_display()
if _is_pyglet_docgen:
class Display(object):
"""A display device supporting one or more screens.
Use `Platform.get_display` or `Platform.get_default_display` to obtain
an instance of this class. Use a display to obtain `Screen` instances.
:deprecated: Use `pyglet.canvas.Display`.
"""
def __init__(self):
raise NotImplementedError('deprecated')
def get_screens(self):
"""Get the available screens.
A typical multi-monitor workstation comprises one `Display` with
multiple `Screen` s. This method returns a list of screens which
can be enumerated to select one for full-screen display.
For the purposes of creating an OpenGL config, the default screen
will suffice.
:rtype: list of `Screen`
"""
raise NotImplementedError('deprecated')
def get_default_screen(self):
"""Get the default screen as specified by the user's operating system
preferences.
:rtype: `Screen`
"""
raise NotImplementedError('deprecated')
def get_windows(self):
"""Get the windows currently attached to this display.
:rtype: sequence of `Window`
"""
raise NotImplementedError('deprecated')
else:
Display = pyglet.canvas.Display
Screen = pyglet.canvas.Screen
# XXX remove
# Create shadow window. (trickery is for circular import)
if not _is_pyglet_docgen:
pyglet.window = sys.modules[__name__]
gl._create_shadow_window()
| 66,336 | 33.951001 | 109 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/pyglet/window/carbon/__init__.py
|
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
'''
'''
from __future__ import division
from builtins import str
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
from ctypes import *
import os.path
import unicodedata
import warnings
import pyglet
from pyglet.window import WindowException, \
BaseWindow, MouseCursor, DefaultMouseCursor, _PlatformEventHandler
from pyglet.window import key
from pyglet.window import mouse
from pyglet.window import event
from pyglet.canvas.carbon import CarbonCanvas
from pyglet.libs.darwin import *
from pyglet.libs.darwin import _oscheck
from pyglet.libs.darwin.quartzkey import keymap, charmap
from pyglet.event import EventDispatcher
# Map symbol,modifiers -> motion
# Determined by experiment with TextEdit.app
_motion_map = {
(key.UP, False): key.MOTION_UP,
(key.RIGHT, False): key.MOTION_RIGHT,
(key.DOWN, False): key.MOTION_DOWN,
(key.LEFT, False): key.MOTION_LEFT,
(key.LEFT, key.MOD_OPTION): key.MOTION_PREVIOUS_WORD,
(key.RIGHT, key.MOD_OPTION): key.MOTION_NEXT_WORD,
(key.LEFT, key.MOD_COMMAND): key.MOTION_BEGINNING_OF_LINE,
(key.RIGHT, key.MOD_COMMAND): key.MOTION_END_OF_LINE,
(key.PAGEUP, False): key.MOTION_PREVIOUS_PAGE,
(key.PAGEDOWN, False): key.MOTION_NEXT_PAGE,
(key.HOME, False): key.MOTION_BEGINNING_OF_FILE,
(key.END, False): key.MOTION_END_OF_FILE,
(key.UP, key.MOD_COMMAND): key.MOTION_BEGINNING_OF_FILE,
(key.DOWN, key.MOD_COMMAND): key.MOTION_END_OF_FILE,
(key.BACKSPACE, False): key.MOTION_BACKSPACE,
(key.DELETE, False): key.MOTION_DELETE,
}
class CarbonMouseCursor(MouseCursor):
drawable = False
def __init__(self, theme):
self.theme = theme
def CarbonEventHandler(event_class, event_kind):
return _PlatformEventHandler((event_class, event_kind))
class CarbonWindow(BaseWindow):
_window = None # Carbon WindowRef
# Window properties
_minimum_size = None
_maximum_size = None
_event_dispatcher = None
_current_modifiers = 0
_mapped_modifers = 0
_carbon_event_handlers = []
_carbon_event_handler_refs = []
_track_ref = 0
_track_region = None
_mouse_exclusive = False
_mouse_platform_visible = True
_mouse_ignore_motion = False
_mouse_button_state = 0
def _recreate(self, changes):
# We can't destroy the window while event handlers are active,
# otherwise the (OS X) event dispatcher gets lost and segfaults.
#
# Defer actual recreation until dispatch_events next finishes.
from pyglet import app
app.platform_event_loop.post_event(self,
'on_recreate_immediate', changes)
def on_recreate_immediate(self, changes):
# The actual _recreate function.
if ('context' in changes):
self.context.detach()
self._create()
def _create(self):
if self._window:
# The window is about to be recreated; destroy everything
# associated with the old window, then the window itself.
self._remove_track_region()
self._remove_event_handlers()
self.context.detach()
self.canvas = None
carbon.DisposeWindow(self._window)
self._window = None
self._window = WindowRef()
if self._fullscreen:
rect = Rect()
rect.left = 0
rect.top = 0
rect.right = self.screen.width
rect.bottom = self.screen.height
r = carbon.CreateNewWindow(kSimpleWindowClass,
kWindowNoAttributes,
byref(rect),
byref(self._window))
_oscheck(r)
# Set window level to shield level
level = carbon.CGShieldingWindowLevel()
WindowGroupRef = c_void_p
group = WindowGroupRef()
_oscheck(carbon.CreateWindowGroup(0, byref(group)))
_oscheck(carbon.SetWindowGroup(self._window, group))
_oscheck(carbon.SetWindowGroupLevel(group, level))
# Set black background
color = RGBColor(0, 0, 0)
_oscheck(carbon.SetWindowContentColor(self._window, byref(color)))
self._mouse_in_window = True
self.dispatch_event('on_resize', self._width, self._height)
self.dispatch_event('on_show')
self.dispatch_event('on_expose')
self._view_x = (self.screen.width - self._width) // 2
self._view_y = (self.screen.height - self._height) // 2
self.canvas = CarbonCanvas(self.display, self.screen,
carbon.GetWindowPort(self._window))
self.canvas.bounds = (self._view_x, self._view_y,
self._width, self._height)
else:
# Create floating window
rect = Rect()
location = None # TODO
if location is not None:
rect.left = location[0]
rect.top = location[1]
else:
rect.top = rect.left = 0
rect.right = rect.left + self._width
rect.bottom = rect.top + self._height
styles = {
self.WINDOW_STYLE_DEFAULT: (kDocumentWindowClass,
kWindowCloseBoxAttribute |
kWindowCollapseBoxAttribute),
self.WINDOW_STYLE_DIALOG: (kDocumentWindowClass,
kWindowCloseBoxAttribute),
self.WINDOW_STYLE_TOOL: (kUtilityWindowClass,
kWindowCloseBoxAttribute),
self.WINDOW_STYLE_BORDERLESS: (kSimpleWindowClass,
kWindowNoAttributes)
}
window_class, window_attributes = \
styles.get(self._style, kDocumentWindowClass)
if self._resizable:
window_attributes |= (kWindowFullZoomAttribute |
kWindowLiveResizeAttribute |
kWindowResizableAttribute)
r = carbon.CreateNewWindow(window_class,
window_attributes,
byref(rect),
byref(self._window))
_oscheck(r)
if location is None:
carbon.RepositionWindow(self._window, c_void_p(),
kWindowCascadeOnMainScreen)
self.canvas = CarbonCanvas(self.display, self.screen,
carbon.GetWindowPort(self._window))
self._view_x = self._view_y = 0
self.context.attach(self.canvas)
self.set_caption(self._caption)
# Get initial state
self._event_dispatcher = carbon.GetEventDispatcherTarget()
self._current_modifiers = carbon.GetCurrentKeyModifiers().value
self._mapped_modifiers = self._map_modifiers(self._current_modifiers)
# (re)install Carbon event handlers
self._install_event_handlers()
self._create_track_region()
self.switch_to() # XXX
self.set_vsync(self._vsync)
if self._visible:
self.set_visible(True)
def _create_track_region(self):
self._remove_track_region()
# Create a tracking region for the content part of the window
# to receive enter/leave events.
track_id = MouseTrackingRegionID()
track_id.signature = DEFAULT_CREATOR_CODE
track_id.id = 1
self._track_ref = MouseTrackingRef()
self._track_region = carbon.NewRgn()
if self._fullscreen:
carbon.SetRectRgn(self._track_region,
self._view_x, self._view_y,
self._view_x + self._width, self._view_y + self._height)
options = kMouseTrackingOptionsGlobalClip
else:
carbon.GetWindowRegion(self._window,
kWindowContentRgn, self._track_region)
options = kMouseTrackingOptionsGlobalClip
carbon.CreateMouseTrackingRegion(self._window,
self._track_region, None, options,
track_id, None, None,
byref(self._track_ref))
def _remove_track_region(self):
if self._track_region:
carbon.ReleaseMouseTrackingRegion(self._track_region)
self._track_region = None
def close(self):
super(CarbonWindow, self).close()
self._remove_event_handlers()
self._remove_track_region()
# Restore cursor visibility
self.set_mouse_platform_visible(True)
self.set_exclusive_mouse(False)
if self._window:
carbon.DisposeWindow(self._window)
self._window = None
def switch_to(self):
self.context.set_current()
'''
agl.aglSetCurrentContext(self._agl_context)
self._context.set_current()
_aglcheck()
# XXX TODO transpose gl[u]_info to gl.Context.attach
gl_info.set_active_context()
glu_info.set_active_context()
'''
def flip(self):
self.draw_mouse_cursor()
if self.context:
self.context.flip()
def _get_vsync(self):
if self.context:
return self.context.get_vsync()
return self._vsync
vsync = property(_get_vsync) # overrides BaseWindow property
def set_vsync(self, vsync):
if pyglet.options['vsync'] is not None:
vsync = pyglet.options['vsync']
self._vsync = vsync # _recreate depends on this
if self.context:
self.context.set_vsync(vsync)
def dispatch_events(self):
from pyglet import app
app.platform_event_loop.dispatch_posted_events()
self._allow_dispatch_event = True
while self._event_queue:
EventDispatcher.dispatch_event(self, *self._event_queue.pop(0))
e = EventRef()
result = carbon.ReceiveNextEvent(0, c_void_p(), 0, True, byref(e))
while result == noErr:
carbon.SendEventToEventTarget(e, self._event_dispatcher)
carbon.ReleaseEvent(e)
result = carbon.ReceiveNextEvent(0, c_void_p(), 0, True, byref(e))
self._allow_dispatch_event = False
# Return value from ReceiveNextEvent can be ignored if not
# noErr; we check here only to look for new bugs.
# eventLoopQuitErr: the inner event loop was quit, see
# http://lists.apple.com/archives/Carbon-dev/2006/Jun/msg00850.html
# Can occur when mixing with other toolkits, e.g. Tk.
# Fixes issue 180.
if result not in (eventLoopTimedOutErr, eventLoopQuitErr):
raise WindowException('Error %d' % result)
def dispatch_pending_events(self):
while self._event_queue:
EventDispatcher.dispatch_event(self, *self._event_queue.pop(0))
def set_caption(self, caption):
self._caption = caption
s = create_cfstring(caption)
carbon.SetWindowTitleWithCFString(self._window, s)
carbon.CFRelease(s)
def set_location(self, x, y):
rect = Rect()
carbon.GetWindowBounds(self._window, kWindowContentRgn, byref(rect))
rect.right += x - rect.left
rect.bottom += y - rect.top
rect.left = x
rect.top = y
carbon.SetWindowBounds(self._window, kWindowContentRgn, byref(rect))
def get_location(self):
rect = Rect()
carbon.GetWindowBounds(self._window, kWindowContentRgn, byref(rect))
return rect.left, rect.top
def set_size(self, width, height):
if self._fullscreen:
raise WindowException('Cannot set size of fullscreen window.')
rect = Rect()
carbon.GetWindowBounds(self._window, kWindowContentRgn, byref(rect))
rect.right = rect.left + width
rect.bottom = rect.top + height
carbon.SetWindowBounds(self._window, kWindowContentRgn, byref(rect))
self._width = width
self._height = height
self.dispatch_event('on_resize', width, height)
self.dispatch_event('on_expose')
def get_size(self):
if self._fullscreen:
return self._width, self._height
rect = Rect()
carbon.GetWindowBounds(self._window, kWindowContentRgn, byref(rect))
return rect.right - rect.left, rect.bottom - rect.top
def set_minimum_size(self, width, height):
self._minimum_size = (width, height)
minimum = HISize()
minimum.width = width
minimum.height = height
if self._maximum_size:
maximum = HISize()
maximum.width, maximum.height = self._maximum_size
maximum = byref(maximum)
else:
maximum = None
carbon.SetWindowResizeLimits(self._window,
byref(minimum), maximum)
def set_maximum_size(self, width, height):
self._maximum_size = (width, height)
maximum = HISize()
maximum.width = width
maximum.height = height
if self._minimum_size:
minimum = HISize()
minimum.width, minimum.height = self._minimum_size
minimum = byref(minimum)
else:
minimum = None
carbon.SetWindowResizeLimits(self._window,
minimum, byref(maximum))
def activate(self):
carbon.ActivateWindow(self._window, 1)
# Also make the application the "front" application. TODO
# maybe don't bring forward all of the application's windows?
psn = ProcessSerialNumber()
psn.highLongOfPSN = 0
psn.lowLongOfPSN = kCurrentProcess
carbon.SetFrontProcess(byref(psn))
def set_visible(self, visible=True):
self._visible = visible
if visible:
self.dispatch_event('on_resize', self._width, self._height)
self.dispatch_event('on_show')
self.dispatch_event('on_expose')
carbon.ShowWindow(self._window)
else:
carbon.HideWindow(self._window)
def minimize(self):
self._mouse_in_window = False
self.set_mouse_platform_visible()
carbon.CollapseWindow(self._window, True)
def maximize(self):
# Maximum "safe" value, gets trimmed to screen size automatically.
p = Point()
p.v, p.h = 16000,16000
if not carbon.IsWindowInStandardState(self._window, byref(p), None):
carbon.ZoomWindowIdeal(self._window, inZoomOut, byref(p))
def set_mouse_platform_visible(self, platform_visible=None):
if platform_visible is None:
platform_visible = self._mouse_visible and \
not self._mouse_exclusive and \
not self._mouse_cursor.drawable
if not self._mouse_in_window:
platform_visible = True
if self._mouse_in_window and \
isinstance(self._mouse_cursor, CarbonMouseCursor):
carbon.SetThemeCursor(self._mouse_cursor.theme)
else:
carbon.SetThemeCursor(kThemeArrowCursor)
if self._mouse_platform_visible == platform_visible:
return
if platform_visible:
carbon.ShowCursor()
else:
carbon.HideCursor()
self._mouse_platform_visible = platform_visible
def set_exclusive_mouse(self, exclusive=True):
self._mouse_exclusive = exclusive
if exclusive:
# Move mouse to center of window
rect = Rect()
carbon.GetWindowBounds(self._window, kWindowContentRgn, byref(rect))
x = (rect.right + rect.left) / 2
y = (rect.bottom + rect.top) / 2
# Skip the next motion event, which would return a large delta.
self._mouse_ignore_motion = True
self.set_mouse_position(x, y, absolute=True)
carbon.CGAssociateMouseAndMouseCursorPosition(False)
else:
carbon.CGAssociateMouseAndMouseCursorPosition(True)
self.set_mouse_platform_visible()
def set_mouse_position(self, x, y, absolute=False):
point = CGPoint()
if absolute:
point.x = x
point.y = y
else:
rect = Rect()
carbon.GetWindowBounds(self._window, kWindowContentRgn, byref(rect))
point.x = x + rect.left
point.y = rect.top + (rect.bottom - rect.top) - y
carbon.CGWarpMouseCursorPosition(point)
def set_exclusive_keyboard(self, exclusive=True):
if exclusive:
# Note: power switch can also be disabled, with
# kUIOptionDisableSessionTerminate. That seems
# a little extreme though.
carbon.SetSystemUIMode(kUIModeAllHidden,
(kUIOptionDisableAppleMenu |
kUIOptionDisableProcessSwitch |
kUIOptionDisableForceQuit |
kUIOptionDisableHide))
else:
carbon.SetSystemUIMode(kUIModeNormal, 0)
def get_system_mouse_cursor(self, name):
if name == self.CURSOR_DEFAULT:
return DefaultMouseCursor()
themes = {
self.CURSOR_CROSSHAIR: kThemeCrossCursor,
self.CURSOR_HAND: kThemePointingHandCursor,
self.CURSOR_HELP: kThemeArrowCursor,
self.CURSOR_NO: kThemeNotAllowedCursor,
self.CURSOR_SIZE: kThemeArrowCursor,
self.CURSOR_SIZE_UP: kThemeResizeUpCursor,
self.CURSOR_SIZE_UP_RIGHT: kThemeArrowCursor,
self.CURSOR_SIZE_RIGHT: kThemeResizeRightCursor,
self.CURSOR_SIZE_DOWN_RIGHT: kThemeArrowCursor,
self.CURSOR_SIZE_DOWN: kThemeResizeDownCursor,
self.CURSOR_SIZE_DOWN_LEFT: kThemeArrowCursor,
self.CURSOR_SIZE_LEFT: kThemeResizeLeftCursor,
self.CURSOR_SIZE_UP_LEFT: kThemeArrowCursor,
self.CURSOR_SIZE_UP_DOWN: kThemeResizeUpDownCursor,
self.CURSOR_SIZE_LEFT_RIGHT: kThemeResizeLeftRightCursor,
self.CURSOR_TEXT: kThemeIBeamCursor,
self.CURSOR_WAIT: kThemeWatchCursor,
self.CURSOR_WAIT_ARROW: kThemeWatchCursor,
}
if name not in themes:
raise RuntimeError('Unknown cursor name "%s"' % name)
return CarbonMouseCursor(themes[name])
def set_icon(self, *images):
# Only use the biggest image
image = images[0]
size = image.width * image.height
for img in images:
if img.width * img.height > size:
size = img.width * img.height
image = img
image = image.get_image_data()
format = 'ARGB'
pitch = -len(format) * image.width
data = image.get_data(format, pitch)
provider = carbon.CGDataProviderCreateWithData(
None, data, len(data), None)
colorspace = carbon.CGColorSpaceCreateDeviceRGB()
cgi = carbon.CGImageCreate(
image.width, image.height, 8, 32, -pitch,
colorspace,
kCGImageAlphaFirst,
provider,
None,
True,
kCGRenderingIntentDefault)
carbon.SetApplicationDockTileImage(cgi)
carbon.CGDataProviderRelease(provider)
carbon.CGColorSpaceRelease(colorspace)
# Non-public utilities
def _update_drawable(self):
if self.context:
self.context.update_geometry()
# Need a redraw
self.dispatch_event('on_expose')
def _update_track_region(self):
if not self._fullscreen:
carbon.GetWindowRegion(self._window,
kWindowContentRgn, self._track_region)
carbon.ChangeMouseTrackingRegion(self._track_ref,
self._track_region, None)
def _install_event_handlers(self):
self._remove_event_handlers()
if self._fullscreen:
target = carbon.GetApplicationEventTarget()
else:
target = carbon.GetWindowEventTarget(self._window)
carbon.InstallStandardEventHandler(target)
self._carbon_event_handlers = []
self._carbon_event_handler_refs = []
for func_name in self._platform_event_names:
if not hasattr(self, func_name):
continue
func = getattr(self, func_name)
self._install_event_handler(func)
def _install_event_handler(self, func):
if self._fullscreen:
target = carbon.GetApplicationEventTarget()
else:
target = carbon.GetWindowEventTarget(self._window)
for event_class, event_kind in func._platform_event_data:
# TODO: could just build up array of class/kind
proc = EventHandlerProcPtr(func)
self._carbon_event_handlers.append(proc)
upp = carbon.NewEventHandlerUPP(proc)
types = EventTypeSpec()
types.eventClass = event_class
types.eventKind = event_kind
handler_ref = EventHandlerRef()
carbon.InstallEventHandler(
target,
upp,
1,
byref(types),
c_void_p(),
byref(handler_ref))
self._carbon_event_handler_refs.append(handler_ref)
def _remove_event_handlers(self):
for ref in self._carbon_event_handler_refs:
carbon.RemoveEventHandler(ref)
self._carbon_event_handler_refs = []
self._carbon_event_handlers = []
# Carbon event handlers
@CarbonEventHandler(kEventClassTextInput, kEventTextInputUnicodeForKeyEvent)
def _on_text_input(self, next_handler, ev, data):
size = c_uint32()
carbon.GetEventParameter(ev, kEventParamTextInputSendText,
typeUTF8Text, c_void_p(), 0, byref(size), c_void_p())
text = create_string_buffer(size.value)
carbon.GetEventParameter(ev, kEventParamTextInputSendText,
typeUTF8Text, c_void_p(), size.value, c_void_p(), byref(text))
text = text.value.decode('utf8')
raw_event = EventRef()
carbon.GetEventParameter(ev, kEventParamTextInputSendKeyboardEvent,
typeEventRef, c_void_p(), sizeof(raw_event), c_void_p(),
byref(raw_event))
symbol, modifiers = self._get_symbol_and_modifiers(raw_event)
motion_modifiers = modifiers & \
(key.MOD_COMMAND | key.MOD_CTRL | key.MOD_OPTION)
if (symbol, motion_modifiers) in _motion_map:
motion = _motion_map[symbol, motion_modifiers]
if modifiers & key.MOD_SHIFT:
self.dispatch_event('on_text_motion_select', motion)
else:
self.dispatch_event('on_text_motion', motion)
elif ((unicodedata.category(text[0]) != 'Cc' or text == u'\r') and
not (modifiers & key.MOD_COMMAND)):
self.dispatch_event('on_text', text)
return noErr
@CarbonEventHandler(kEventClassKeyboard, kEventRawKeyUp)
def _on_key_up(self, next_handler, ev, data):
symbol, modifiers = self._get_symbol_and_modifiers(ev)
if symbol:
self.dispatch_event('on_key_release', symbol, modifiers)
carbon.CallNextEventHandler(next_handler, ev)
return noErr
@CarbonEventHandler(kEventClassKeyboard, kEventRawKeyDown)
def _on_key_down(self, next_handler, ev, data):
symbol, modifiers = self._get_symbol_and_modifiers(ev)
if symbol:
self.dispatch_event('on_key_press', symbol, modifiers)
carbon.CallNextEventHandler(next_handler, ev)
return noErr
@staticmethod
def _get_symbol_and_modifiers(ev):
# The unicode char help processing virtual keycodes (see issue 405)
wchar = c_wchar()
carbon.GetEventParameter(ev, kEventParamKeyUnicodes,
typeUnicodeText, c_void_p(), sizeof(wchar), c_void_p(), byref(wchar))
try:
wchar = str((wchar.value)).upper()
except UnicodeEncodeError:
# (this fix for issue 405 caused a bug itself (see comments 6-7);
# this try/except fixes it)
wchar = None
# If the unicode char is within charmap keys (ascii value), then we use
# the corresponding symbol.
if wchar in charmap.keys():
symbol = charmap[wchar]
else:
sym = c_uint32()
carbon.GetEventParameter(ev, kEventParamKeyCode,
typeUInt32, c_void_p(), sizeof(sym), c_void_p(), byref(sym))
symbol = keymap.get(sym.value, None)
if symbol is None:
symbol = key.user_key(sym.value)
modifiers = c_uint32()
carbon.GetEventParameter(ev, kEventParamKeyModifiers,
typeUInt32, c_void_p(), sizeof(modifiers), c_void_p(),
byref(modifiers))
return (symbol, CarbonWindow._map_modifiers(modifiers.value))
@staticmethod
def _map_modifiers(modifiers):
mapped_modifiers = 0
if modifiers & (shiftKey | rightShiftKey):
mapped_modifiers |= key.MOD_SHIFT
if modifiers & (controlKey | rightControlKey):
mapped_modifiers |= key.MOD_CTRL
if modifiers & (optionKey | rightOptionKey):
mapped_modifiers |= key.MOD_OPTION
if modifiers & alphaLock:
mapped_modifiers |= key.MOD_CAPSLOCK
if modifiers & cmdKey:
mapped_modifiers |= key.MOD_COMMAND
return mapped_modifiers
@CarbonEventHandler(kEventClassKeyboard, kEventRawKeyModifiersChanged)
def _on_modifiers_changed(self, next_handler, ev, data):
modifiers = c_uint32()
carbon.GetEventParameter(ev, kEventParamKeyModifiers,
typeUInt32, c_void_p(), sizeof(modifiers), c_void_p(),
byref(modifiers))
modifiers = modifiers.value
deltas = modifiers ^ self._current_modifiers
for mask, k in [
(controlKey, key.LCTRL),
(shiftKey, key.LSHIFT),
(cmdKey, key.LCOMMAND),
(optionKey, key.LOPTION),
(rightShiftKey, key.RSHIFT),
(rightOptionKey, key.ROPTION),
(rightControlKey, key.RCTRL),
(alphaLock, key.CAPSLOCK),
(numLock, key.NUMLOCK)]:
if deltas & mask:
if modifiers & mask:
self.dispatch_event('on_key_press',
k, self._mapped_modifiers)
else:
self.dispatch_event('on_key_release',
k, self._mapped_modifiers)
carbon.CallNextEventHandler(next_handler, ev)
self._mapped_modifiers = self._map_modifiers(modifiers)
self._current_modifiers = modifiers
return noErr
def _get_mouse_position(self, ev):
position = HIPoint()
carbon.GetEventParameter(ev, kEventParamMouseLocation,
typeHIPoint, c_void_p(), sizeof(position), c_void_p(),
byref(position))
bounds = Rect()
carbon.GetWindowBounds(self._window, kWindowContentRgn, byref(bounds))
return (int(position.x - bounds.left - self._view_x),
int(position.y - bounds.top - self._view_y))
def _get_mouse_buttons_changed(self):
button_state = self._get_mouse_buttons()
change = self._mouse_button_state ^ button_state
self._mouse_button_state = button_state
return change
@staticmethod
def _get_mouse_buttons():
buttons = carbon.GetCurrentEventButtonState()
button_state = 0
if buttons & 0x1: button_state |= mouse.LEFT
if buttons & 0x2: button_state |= mouse.RIGHT
if buttons & 0x4: button_state |= mouse.MIDDLE
return button_state
@staticmethod
def _get_modifiers(ev):
modifiers = c_uint32()
carbon.GetEventParameter(ev, kEventParamKeyModifiers,
typeUInt32, c_void_p(), sizeof(modifiers), c_void_p(),
byref(modifiers))
return CarbonWindow._map_modifiers(modifiers.value)
def _get_mouse_in_content(self, ev, x, y):
if self._fullscreen:
return 0 <= x < self._width and 0 <= y < self._height
else:
position = Point()
carbon.GetEventParameter(ev, kEventParamMouseLocation,
typeQDPoint, c_void_p(), sizeof(position), c_void_p(),
byref(position))
return carbon.FindWindow(position, None) == inContent
@CarbonEventHandler(kEventClassMouse, kEventMouseDown)
def _on_mouse_down(self, next_handler, ev, data):
x, y = self._get_mouse_position(ev)
if self._get_mouse_in_content(ev, x, y):
button = self._get_mouse_buttons_changed()
modifiers = self._get_modifiers(ev)
if button is not None:
y = self.height - y
self.dispatch_event('on_mouse_press', x, y, button, modifiers)
carbon.CallNextEventHandler(next_handler, ev)
return noErr
@CarbonEventHandler(kEventClassMouse, kEventMouseUp)
def _on_mouse_up(self, next_handler, ev, data):
# Always report mouse up, even out of content area, because it's
# probably after a drag gesture.
button = self._get_mouse_buttons_changed()
modifiers = self._get_modifiers(ev)
if button is not None:
x, y = self._get_mouse_position(ev)
y = self.height - y
self.dispatch_event('on_mouse_release', x, y, button, modifiers)
carbon.CallNextEventHandler(next_handler, ev)
return noErr
@CarbonEventHandler(kEventClassMouse, kEventMouseMoved)
def _on_mouse_moved(self, next_handler, ev, data):
x, y = self._get_mouse_position(ev)
if (self._get_mouse_in_content(ev, x, y)
and not self._mouse_ignore_motion):
y = self.height - y
self._mouse_x = x
self._mouse_y = y
delta = HIPoint()
carbon.GetEventParameter(ev, kEventParamMouseDelta,
typeHIPoint, c_void_p(), sizeof(delta), c_void_p(),
byref(delta))
# Motion event
self.dispatch_event('on_mouse_motion',
x, y, delta.x, -delta.y)
elif self._mouse_ignore_motion:
self._mouse_ignore_motion = False
carbon.CallNextEventHandler(next_handler, ev)
return noErr
@CarbonEventHandler(kEventClassMouse, kEventMouseDragged)
def _on_mouse_dragged(self, next_handler, ev, data):
button = self._get_mouse_buttons()
modifiers = self._get_modifiers(ev)
if button is not None:
x, y = self._get_mouse_position(ev)
y = self.height - y
self._mouse_x = x
self._mouse_y = y
delta = HIPoint()
carbon.GetEventParameter(ev, kEventParamMouseDelta,
typeHIPoint, c_void_p(), sizeof(delta), c_void_p(),
byref(delta))
# Drag event
self.dispatch_event('on_mouse_drag',
x, y, delta.x, -delta.y, button, modifiers)
carbon.CallNextEventHandler(next_handler, ev)
return noErr
@CarbonEventHandler(kEventClassMouse, kEventMouseEntered)
def _on_mouse_entered(self, next_handler, ev, data):
x, y = self._get_mouse_position(ev)
y = self.height - y
self._mouse_x = x
self._mouse_y = y
self._mouse_in_window = True
self.set_mouse_platform_visible()
self.dispatch_event('on_mouse_enter', x, y)
carbon.CallNextEventHandler(next_handler, ev)
return noErr
@CarbonEventHandler(kEventClassMouse, kEventMouseExited)
def _on_mouse_exited(self, next_handler, ev, data):
x, y = self._get_mouse_position(ev)
y = self.height - y
self._mouse_in_window = False
self.set_mouse_platform_visible()
self.dispatch_event('on_mouse_leave', x, y)
carbon.CallNextEventHandler(next_handler, ev)
return noErr
@CarbonEventHandler(kEventClassMouse, kEventMouseWheelMoved)
def _on_mouse_wheel_moved(self, next_handler, ev, data):
x, y = self._get_mouse_position(ev)
y = self.height - y
axis = EventMouseWheelAxis()
carbon.GetEventParameter(ev, kEventParamMouseWheelAxis,
typeMouseWheelAxis, c_void_p(), sizeof(axis), c_void_p(),
byref(axis))
delta = c_long()
carbon.GetEventParameter(ev, kEventParamMouseWheelDelta,
typeSInt32, c_void_p(), sizeof(delta), c_void_p(),
byref(delta))
if axis.value == kEventMouseWheelAxisX:
self.dispatch_event('on_mouse_scroll',
x, y, delta.value, 0)
else:
self.dispatch_event('on_mouse_scroll',
x, y, 0, delta.value)
# _Don't_ call the next handler, which is application, as this then
# calls our window handler again.
#carbon.CallNextEventHandler(next_handler, ev)
return noErr
@CarbonEventHandler(kEventClassWindow, kEventWindowClose)
def _on_window_close(self, next_handler, ev, data):
self.dispatch_event('on_close')
# Presumably the next event handler is the one that closes
# the window; don't do that here.
#carbon.CallNextEventHandler(next_handler, ev)
return noErr
@CarbonEventHandler(kEventClassWindow, kEventWindowResizeStarted)
def _on_window_resize_started(self, next_handler, ev, data):
from pyglet import app
if app.event_loop is not None:
app.event_loop.enter_blocking()
carbon.CallNextEventHandler(next_handler, ev)
return noErr
@CarbonEventHandler(kEventClassWindow, kEventWindowResizeCompleted)
def _on_window_resize_completed(self, next_handler, ev, data):
from pyglet import app
if app.event_loop is not None:
app.event_loop.exit_blocking()
rect = Rect()
carbon.GetWindowBounds(self._window, kWindowContentRgn, byref(rect))
width = rect.right - rect.left
height = rect.bottom - rect.top
self.switch_to()
self.dispatch_event('on_resize', width, height)
self.dispatch_event('on_expose')
carbon.CallNextEventHandler(next_handler, ev)
return noErr
_dragging = False
@CarbonEventHandler(kEventClassWindow, kEventWindowDragStarted)
def _on_window_drag_started(self, next_handler, ev, data):
self._dragging = True
from pyglet import app
if app.event_loop is not None:
app.event_loop.enter_blocking()
carbon.CallNextEventHandler(next_handler, ev)
return noErr
@CarbonEventHandler(kEventClassWindow, kEventWindowDragCompleted)
def _on_window_drag_completed(self, next_handler, ev, data):
self._dragging = False
from pyglet import app
if app.event_loop is not None:
app.event_loop.exit_blocking()
rect = Rect()
carbon.GetWindowBounds(self._window, kWindowContentRgn, byref(rect))
self.dispatch_event('on_move', rect.left, rect.top)
carbon.CallNextEventHandler(next_handler, ev)
return noErr
@CarbonEventHandler(kEventClassWindow, kEventWindowBoundsChanging)
def _on_window_bounds_changing(self, next_handler, ev, data):
carbon.CallNextEventHandler(next_handler, ev)
return noErr
@CarbonEventHandler(kEventClassWindow, kEventWindowBoundsChanged)
def _on_window_bounds_change(self, next_handler, ev, data):
self._update_track_region()
rect = Rect()
carbon.GetWindowBounds(self._window, kWindowContentRgn, byref(rect))
width = rect.right - rect.left
height = rect.bottom - rect.top
if width != self._width or height != self._height:
self._update_drawable()
self.switch_to()
self.dispatch_event('on_resize', width, height)
from pyglet import app
if app.event_loop is not None:
app.event_loop.enter_blocking()
self._width = width
self._height = height
else:
self.dispatch_event('on_move', rect.left, rect.top)
carbon.CallNextEventHandler(next_handler, ev)
return noErr
@CarbonEventHandler(kEventClassWindow, kEventWindowZoomed)
def _on_window_zoomed(self, next_handler, ev, data):
rect = Rect()
carbon.GetWindowBounds(self._window, kWindowContentRgn, byref(rect))
width = rect.right - rect.left
height = rect.bottom - rect.top
self.dispatch_event('on_move', rect.left, rect.top)
self.dispatch_event('on_resize', width, height)
carbon.CallNextEventHandler(next_handler, ev)
return noErr
@CarbonEventHandler(kEventClassWindow, kEventWindowActivated)
def _on_window_activated(self, next_handler, ev, data):
self.dispatch_event('on_activate')
carbon.CallNextEventHandler(next_handler, ev)
return noErr
@CarbonEventHandler(kEventClassWindow, kEventWindowDeactivated)
def _on_window_deactivated(self, next_handler, ev, data):
self.dispatch_event('on_deactivate')
carbon.CallNextEventHandler(next_handler, ev)
return noErr
@CarbonEventHandler(kEventClassWindow, kEventWindowShown)
@CarbonEventHandler(kEventClassWindow, kEventWindowExpanded)
def _on_window_shown(self, next_handler, ev, data):
self._update_drawable() # XXX not needed here according to apple docs
self.dispatch_event('on_show')
carbon.CallNextEventHandler(next_handler, ev)
return noErr
@CarbonEventHandler(kEventClassWindow, kEventWindowHidden)
@CarbonEventHandler(kEventClassWindow, kEventWindowCollapsed)
def _on_window_hidden(self, next_handler, ev, data):
self.dispatch_event('on_hide')
carbon.CallNextEventHandler(next_handler, ev)
return noErr
@CarbonEventHandler(kEventClassWindow, kEventWindowDrawContent)
def _on_window_draw_content(self, next_handler, ev, data):
self.dispatch_event('on_expose')
carbon.CallNextEventHandler(next_handler, ev)
return noErr
CarbonWindow.register_event_type('on_recreate_immediate')
| 40,674 | 36.872439 | 97 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/pyglet/window/win32/__init__.py
|
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
'''
'''
from __future__ import division
from builtins import chr
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
from ctypes import *
import unicodedata
import warnings
from pyglet import compat_platform
if compat_platform not in ('cygwin', 'win32'):
raise ImportError('Not a win32 platform.')
import pyglet
from pyglet.window import BaseWindow, \
WindowException, MouseCursor, DefaultMouseCursor, _PlatformEventHandler, \
_ViewEventHandler
from pyglet.event import EventDispatcher
from pyglet.window import key
from pyglet.window import mouse
from pyglet.canvas.win32 import Win32Canvas
from pyglet.libs.win32 import _user32, _kernel32, _gdi32
from pyglet.libs.win32.constants import *
from pyglet.libs.win32.winkey import *
from pyglet.libs.win32.types import *
# symbol,ctrl -> motion mapping
_motion_map = {
(key.UP, False): key.MOTION_UP,
(key.RIGHT, False): key.MOTION_RIGHT,
(key.DOWN, False): key.MOTION_DOWN,
(key.LEFT, False): key.MOTION_LEFT,
(key.RIGHT, True): key.MOTION_NEXT_WORD,
(key.LEFT, True): key.MOTION_PREVIOUS_WORD,
(key.HOME, False): key.MOTION_BEGINNING_OF_LINE,
(key.END, False): key.MOTION_END_OF_LINE,
(key.PAGEUP, False): key.MOTION_PREVIOUS_PAGE,
(key.PAGEDOWN, False): key.MOTION_NEXT_PAGE,
(key.HOME, True): key.MOTION_BEGINNING_OF_FILE,
(key.END, True): key.MOTION_END_OF_FILE,
(key.BACKSPACE, False): key.MOTION_BACKSPACE,
(key.DELETE, False): key.MOTION_DELETE,
}
class Win32MouseCursor(MouseCursor):
drawable = False
def __init__(self, cursor):
self.cursor = cursor
# This is global state, we have to be careful not to set the same state twice,
# which will throw off the ShowCursor counter.
_win32_cursor_visible = True
Win32EventHandler = _PlatformEventHandler
ViewEventHandler = _ViewEventHandler
class Win32Window(BaseWindow):
_window_class = None
_hwnd = None
_dc = None
_wgl_context = None
_tracking = False
_hidden = False
_has_focus = False
_exclusive_keyboard = False
_exclusive_keyboard_focus = True
_exclusive_mouse = False
_exclusive_mouse_focus = True
_exclusive_mouse_screen = None
_exclusive_mouse_lpos = None
_exclusive_mouse_buttons = 0
_mouse_platform_visible = True
_ws_style = 0
_ex_ws_style = 0
_minimum_size = None
_maximum_size = None
def __init__(self, *args, **kwargs):
# Bind event handlers
self._event_handlers = {}
self._view_event_handlers = {}
for func_name in self._platform_event_names:
if not hasattr(self, func_name):
continue
func = getattr(self, func_name)
for message in func._platform_event_data:
if hasattr(func, '_view'):
self._view_event_handlers[message] = func
else:
self._event_handlers[message] = func
super(Win32Window, self).__init__(*args, **kwargs)
def _recreate(self, changes):
if 'context' in changes:
self._wgl_context = None
self._create()
def _create(self):
# Ensure style is set before determining width/height.
if self._fullscreen:
self._ws_style = WS_POPUP
self._ex_ws_style = 0 # WS_EX_TOPMOST
else:
styles = {
self.WINDOW_STYLE_DEFAULT: (WS_OVERLAPPEDWINDOW, 0),
self.WINDOW_STYLE_DIALOG: (WS_OVERLAPPED|WS_CAPTION|WS_SYSMENU,
WS_EX_DLGMODALFRAME),
self.WINDOW_STYLE_TOOL: (WS_OVERLAPPED|WS_CAPTION|WS_SYSMENU,
WS_EX_TOOLWINDOW),
self.WINDOW_STYLE_BORDERLESS: (WS_POPUP, 0),
}
self._ws_style, self._ex_ws_style = styles[self._style]
if self._resizable and not self._fullscreen:
self._ws_style |= WS_THICKFRAME
else:
self._ws_style &= ~(WS_THICKFRAME|WS_MAXIMIZEBOX)
if self._fullscreen:
width = self.screen.width
height = self.screen.height
else:
width, height = \
self._client_to_window_size(self._width, self._height)
if not self._window_class:
module = _kernel32.GetModuleHandleW(None)
white = _gdi32.GetStockObject(WHITE_BRUSH)
black = _gdi32.GetStockObject(BLACK_BRUSH)
self._window_class = WNDCLASS()
self._window_class.lpszClassName = u'GenericAppClass%d' % id(self)
self._window_class.lpfnWndProc = WNDPROC(
self._get_window_proc(self._event_handlers))
self._window_class.style = CS_VREDRAW | CS_HREDRAW
self._window_class.hInstance = 0
self._window_class.hIcon = _user32.LoadIconW(module, MAKEINTRESOURCE(1))
self._window_class.hbrBackground = black
self._window_class.lpszMenuName = None
self._window_class.cbClsExtra = 0
self._window_class.cbWndExtra = 0
_user32.RegisterClassW(byref(self._window_class))
self._view_window_class = WNDCLASS()
self._view_window_class.lpszClassName = \
u'GenericViewClass%d' % id(self)
self._view_window_class.lpfnWndProc = WNDPROC(
self._get_window_proc(self._view_event_handlers))
self._view_window_class.style = 0
self._view_window_class.hInstance = 0
self._view_window_class.hIcon = 0
self._view_window_class.hbrBackground = white
self._view_window_class.lpszMenuName = None
self._view_window_class.cbClsExtra = 0
self._view_window_class.cbWndExtra = 0
_user32.RegisterClassW(byref(self._view_window_class))
if not self._hwnd:
self._hwnd = _user32.CreateWindowExW(
self._ex_ws_style,
self._window_class.lpszClassName,
u'',
self._ws_style,
CW_USEDEFAULT,
CW_USEDEFAULT,
width,
height,
0,
0,
self._window_class.hInstance,
0)
self._view_hwnd = _user32.CreateWindowExW(
0,
self._view_window_class.lpszClassName,
u'',
WS_CHILD | WS_VISIBLE,
0, 0, 0, 0,
self._hwnd,
0,
self._view_window_class.hInstance,
0)
self._dc = _user32.GetDC(self._view_hwnd)
else:
# Window already exists, update it with new style
# We need to hide window here, otherwise Windows forgets
# to redraw the whole screen after leaving fullscreen.
_user32.ShowWindow(self._hwnd, SW_HIDE)
_user32.SetWindowLongW(self._hwnd,
GWL_STYLE,
self._ws_style)
_user32.SetWindowLongW(self._hwnd,
GWL_EXSTYLE,
self._ex_ws_style)
if self._fullscreen:
hwnd_after = HWND_TOPMOST
else:
hwnd_after = HWND_NOTOPMOST
# Position and size window
if self._fullscreen:
_user32.SetWindowPos(self._hwnd, hwnd_after,
self._screen.x, self._screen.y, width, height, SWP_FRAMECHANGED)
elif False: # TODO location not in pyglet API
x, y = self._client_to_window_pos(*factory.get_location())
_user32.SetWindowPos(self._hwnd, hwnd_after,
x, y, width, height, SWP_FRAMECHANGED)
else:
_user32.SetWindowPos(self._hwnd, hwnd_after,
0, 0, width, height, SWP_NOMOVE | SWP_FRAMECHANGED)
self._update_view_location(self._width, self._height)
# Context must be created after window is created.
if not self._wgl_context:
self.canvas = Win32Canvas(self.display, self._view_hwnd, self._dc)
self.context.attach(self.canvas)
self._wgl_context = self.context._context
self.set_caption(self._caption)
self.switch_to()
self.set_vsync(self._vsync)
if self._visible:
self.set_visible()
# Might need resize event if going from fullscreen to fullscreen
self.dispatch_event('on_resize', self._width, self._height)
self.dispatch_event('on_expose')
def _update_view_location(self, width, height):
if self._fullscreen:
x = (self.screen.width - width) // 2
y = (self.screen.height - height) // 2
else:
x = y = 0
_user32.SetWindowPos(self._view_hwnd, 0,
x, y, width, height, SWP_NOZORDER | SWP_NOOWNERZORDER)
def close(self):
if not self._hwnd:
super(Win32Window, self).close()
return
_user32.DestroyWindow(self._hwnd)
_user32.UnregisterClassW(self._window_class.lpszClassName, 0)
self._window_class = None
self._view_window_class = None
self._view_event_handlers.clear()
self._event_handlers.clear()
self.set_mouse_platform_visible(True)
self._hwnd = None
self._dc = None
self._wgl_context = None
super(Win32Window, self).close()
def _get_vsync(self):
return self.context.get_vsync()
vsync = property(_get_vsync) # overrides BaseWindow property
def set_vsync(self, vsync):
if pyglet.options['vsync'] is not None:
vsync = pyglet.options['vsync']
self.context.set_vsync(vsync)
def switch_to(self):
self.context.set_current()
def flip(self):
self.draw_mouse_cursor()
self.context.flip()
def set_location(self, x, y):
x, y = self._client_to_window_pos(x, y)
_user32.SetWindowPos(self._hwnd, 0, x, y, 0, 0,
(SWP_NOZORDER |
SWP_NOSIZE |
SWP_NOOWNERZORDER))
def get_location(self):
rect = RECT()
_user32.GetClientRect(self._hwnd, byref(rect))
point = POINT()
point.x = rect.left
point.y = rect.top
_user32.ClientToScreen(self._hwnd, byref(point))
return point.x, point.y
def set_size(self, width, height):
if self._fullscreen:
raise WindowException('Cannot set size of fullscreen window.')
width, height = self._client_to_window_size(width, height)
_user32.SetWindowPos(self._hwnd, 0, 0, 0, width, height,
(SWP_NOZORDER |
SWP_NOMOVE |
SWP_NOOWNERZORDER))
def get_size(self):
#rect = RECT()
#_user32.GetClientRect(self._hwnd, byref(rect))
#return rect.right - rect.left, rect.bottom - rect.top
return self._width, self._height
def set_minimum_size(self, width, height):
self._minimum_size = width, height
def set_maximum_size(self, width, height):
self._maximum_size = width, height
def activate(self):
_user32.SetForegroundWindow(self._hwnd)
def set_visible(self, visible=True):
if visible:
insertAfter = HWND_TOPMOST if self._fullscreen else HWND_TOP
_user32.SetWindowPos(self._hwnd, insertAfter, 0, 0, 0, 0,
SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW)
self.dispatch_event('on_resize', self._width, self._height)
self.activate()
self.dispatch_event('on_show')
else:
_user32.ShowWindow(self._hwnd, SW_HIDE)
self.dispatch_event('on_hide')
self._visible = visible
self.set_mouse_platform_visible()
def minimize(self):
_user32.ShowWindow(self._hwnd, SW_MINIMIZE)
def maximize(self):
_user32.ShowWindow(self._hwnd, SW_MAXIMIZE)
def set_caption(self, caption):
self._caption = caption
_user32.SetWindowTextW(self._hwnd, c_wchar_p(caption))
def set_mouse_platform_visible(self, platform_visible=None):
if platform_visible is None:
platform_visible = (self._mouse_visible and
not self._exclusive_mouse and
not self._mouse_cursor.drawable) or \
(not self._mouse_in_window or
not self._has_focus)
if platform_visible and not self._mouse_cursor.drawable:
if isinstance(self._mouse_cursor, Win32MouseCursor):
cursor = self._mouse_cursor.cursor
else:
cursor = _user32.LoadCursorW(None, MAKEINTRESOURCE(IDC_ARROW))
_user32.SetClassLongW(self._view_hwnd, GCL_HCURSOR, cursor)
_user32.SetCursor(cursor)
if platform_visible == self._mouse_platform_visible:
return
# Avoid calling ShowCursor with the current visibility (which would
# push the counter too far away from zero).
global _win32_cursor_visible
if _win32_cursor_visible != platform_visible:
_user32.ShowCursor(platform_visible)
_win32_cursor_visible = platform_visible
self._mouse_platform_visible = platform_visible
def _reset_exclusive_mouse_screen(self):
'''Recalculate screen coords of mouse warp point for exclusive
mouse.'''
p = POINT()
rect = RECT()
_user32.GetClientRect(self._view_hwnd, byref(rect))
_user32.MapWindowPoints(self._view_hwnd, HWND_DESKTOP, byref(rect), 2)
p.x = (rect.left + rect.right) // 2
p.y = (rect.top + rect.bottom) // 2
# This is the point the mouse will be kept at while in exclusive
# mode.
self._exclusive_mouse_screen = p.x, p.y
def set_exclusive_mouse(self, exclusive=True):
if self._exclusive_mouse == exclusive and \
self._exclusive_mouse_focus == self._has_focus:
return
# Mouse: UsagePage = 1, Usage = 2
raw_mouse = RAWINPUTDEVICE(0x01, 0x02, 0, None)
if exclusive:
raw_mouse.dwFlags = RIDEV_NOLEGACY
raw_mouse.hwndTarget = self._view_hwnd
else:
raw_mouse.dwFlags = RIDEV_REMOVE
raw_mouse.hwndTarget = None
if not _user32.RegisterRawInputDevices(
byref(raw_mouse), 1, sizeof(RAWINPUTDEVICE)):
if exclusive:
raise WindowException("Cannot enter mouse exclusive mode.")
self._exclusive_mouse_buttons = 0
if exclusive and self._has_focus:
# Clip to client area, to prevent large mouse movements taking
# it outside the client area.
rect = RECT()
_user32.GetClientRect(self._view_hwnd, byref(rect))
_user32.MapWindowPoints(self._view_hwnd, HWND_DESKTOP,
byref(rect), 2)
_user32.ClipCursor(byref(rect))
# Release mouse capture in case is was acquired during mouse click
_user32.ReleaseCapture()
else:
# Release clip
_user32.ClipCursor(None)
self._exclusive_mouse = exclusive
self._exclusive_mouse_focus = self._has_focus
self.set_mouse_platform_visible(not exclusive)
def set_mouse_position(self, x, y, absolute=False):
if not absolute:
rect = RECT()
_user32.GetClientRect(self._view_hwnd, byref(rect))
_user32.MapWindowPoints(self._view_hwnd, HWND_DESKTOP, byref(rect), 2)
x = x + rect.left
y = rect.top + (rect.bottom - rect.top) - y
_user32.SetCursorPos(x, y)
def set_exclusive_keyboard(self, exclusive=True):
if self._exclusive_keyboard == exclusive and \
self._exclusive_keyboard_focus == self._has_focus:
return
if exclusive and self._has_focus:
_user32.RegisterHotKey(self._hwnd, 0, WIN32_MOD_ALT, VK_TAB)
else:
_user32.UnregisterHotKey(self._hwnd, 0)
self._exclusive_keyboard = exclusive
self._exclusive_keyboard_focus = self._has_focus
def get_system_mouse_cursor(self, name):
if name == self.CURSOR_DEFAULT:
return DefaultMouseCursor()
names = {
self.CURSOR_CROSSHAIR: IDC_CROSS,
self.CURSOR_HAND: IDC_HAND,
self.CURSOR_HELP: IDC_HELP,
self.CURSOR_NO: IDC_NO,
self.CURSOR_SIZE: IDC_SIZEALL,
self.CURSOR_SIZE_UP: IDC_SIZENS,
self.CURSOR_SIZE_UP_RIGHT: IDC_SIZENESW,
self.CURSOR_SIZE_RIGHT: IDC_SIZEWE,
self.CURSOR_SIZE_DOWN_RIGHT: IDC_SIZENWSE,
self.CURSOR_SIZE_DOWN: IDC_SIZENS,
self.CURSOR_SIZE_DOWN_LEFT: IDC_SIZENESW,
self.CURSOR_SIZE_LEFT: IDC_SIZEWE,
self.CURSOR_SIZE_UP_LEFT: IDC_SIZENWSE,
self.CURSOR_SIZE_UP_DOWN: IDC_SIZENS,
self.CURSOR_SIZE_LEFT_RIGHT: IDC_SIZEWE,
self.CURSOR_TEXT: IDC_IBEAM,
self.CURSOR_WAIT: IDC_WAIT,
self.CURSOR_WAIT_ARROW: IDC_APPSTARTING,
}
if name not in names:
raise RuntimeError('Unknown cursor name "%s"' % name)
cursor = _user32.LoadCursorW(None, MAKEINTRESOURCE(names[name]))
return Win32MouseCursor(cursor)
def set_icon(self, *images):
# XXX Undocumented AFAICT, but XP seems happy to resize an image
# of any size, so no scaling necessary.
def best_image(width, height):
# A heuristic for finding closest sized image to required size.
image = images[0]
for img in images:
if img.width == width and img.height == height:
# Exact match always used
return img
elif img.width >= width and \
img.width * img.height > image.width * image.height:
# At least wide enough, and largest area
image = img
return image
def get_icon(image):
# Alpha-blended icon: see http://support.microsoft.com/kb/318876
format = 'BGRA'
pitch = len(format) * image.width
header = BITMAPV5HEADER()
header.bV5Size = sizeof(header)
header.bV5Width = image.width
header.bV5Height = image.height
header.bV5Planes = 1
header.bV5BitCount = 32
header.bV5Compression = BI_BITFIELDS
header.bV5RedMask = 0x00ff0000
header.bV5GreenMask = 0x0000ff00
header.bV5BlueMask = 0x000000ff
header.bV5AlphaMask = 0xff000000
hdc = _user32.GetDC(None)
dataptr = c_void_p()
bitmap = _gdi32.CreateDIBSection(hdc, byref(header), DIB_RGB_COLORS,
byref(dataptr), None, 0)
_user32.ReleaseDC(None, hdc)
image = image.get_image_data()
data = image.get_data(format, pitch)
memmove(dataptr, data, len(data))
mask = _gdi32.CreateBitmap(image.width, image.height, 1, 1, None)
iconinfo = ICONINFO()
iconinfo.fIcon = True
iconinfo.hbmMask = mask
iconinfo.hbmColor = bitmap
icon = _user32.CreateIconIndirect(byref(iconinfo))
_gdi32.DeleteObject(mask)
_gdi32.DeleteObject(bitmap)
return icon
# Set large icon
image = best_image(_user32.GetSystemMetrics(SM_CXICON),
_user32.GetSystemMetrics(SM_CYICON))
icon = get_icon(image)
_user32.SetClassLongPtrW(self._hwnd, GCL_HICON, icon)
# Set small icon
image = best_image(_user32.GetSystemMetrics(SM_CXSMICON),
_user32.GetSystemMetrics(SM_CYSMICON))
icon = get_icon(image)
_user32.SetClassLongPtrW(self._hwnd, GCL_HICONSM, icon)
# Private util
def _client_to_window_size(self, width, height):
rect = RECT()
rect.left = 0
rect.top = 0
rect.right = width
rect.bottom = height
_user32.AdjustWindowRectEx(byref(rect),
self._ws_style, False, self._ex_ws_style)
return rect.right - rect.left, rect.bottom - rect.top
def _client_to_window_pos(self, x, y):
rect = RECT()
rect.left = x
rect.top = y
_user32.AdjustWindowRectEx(byref(rect),
self._ws_style, False, self._ex_ws_style)
return rect.left, rect.top
# Event dispatching
def dispatch_events(self):
from pyglet import app
app.platform_event_loop.start()
self._allow_dispatch_event = True
self.dispatch_pending_events()
msg = MSG()
while _user32.PeekMessageW(byref(msg), 0, 0, 0, PM_REMOVE):
_user32.TranslateMessage(byref(msg))
_user32.DispatchMessageW(byref(msg))
self._allow_dispatch_event = False
def dispatch_pending_events(self):
while self._event_queue:
event = self._event_queue.pop(0)
if type(event[0]) is str:
# pyglet event
EventDispatcher.dispatch_event(self, *event)
else:
# win32 event
event[0](*event[1:])
def _get_window_proc(self, event_handlers):
def f(hwnd, msg, wParam, lParam):
event_handler = event_handlers.get(msg, None)
result = None
if event_handler:
if self._allow_dispatch_event or not self._enable_event_queue:
result = event_handler(msg, wParam, lParam)
else:
result = 0
self._event_queue.append((event_handler, msg,
wParam, lParam))
if result is None:
result = _user32.DefWindowProcW(hwnd, msg, wParam, lParam)
return result
return f
# Event handlers
def _get_modifiers(self, key_lParam=0):
modifiers = 0
if _user32.GetKeyState(VK_SHIFT) & 0xff00:
modifiers |= key.MOD_SHIFT
if _user32.GetKeyState(VK_CONTROL) & 0xff00:
modifiers |= key.MOD_CTRL
if _user32.GetKeyState(VK_LWIN) & 0xff00:
modifiers |= key.MOD_WINDOWS
if _user32.GetKeyState(VK_CAPITAL) & 0x00ff: # toggle
modifiers |= key.MOD_CAPSLOCK
if _user32.GetKeyState(VK_NUMLOCK) & 0x00ff: # toggle
modifiers |= key.MOD_NUMLOCK
if _user32.GetKeyState(VK_SCROLL) & 0x00ff: # toggle
modifiers |= key.MOD_SCROLLLOCK
if key_lParam:
if key_lParam & (1 << 29):
modifiers |= key.MOD_ALT
elif _user32.GetKeyState(VK_MENU) < 0:
modifiers |= key.MOD_ALT
return modifiers
@staticmethod
def _get_location(lParam):
x = c_int16(lParam & 0xffff).value
y = c_int16(lParam >> 16).value
return x, y
@Win32EventHandler(WM_KEYDOWN)
@Win32EventHandler(WM_KEYUP)
@Win32EventHandler(WM_SYSKEYDOWN)
@Win32EventHandler(WM_SYSKEYUP)
def _event_key(self, msg, wParam, lParam):
repeat = False
if lParam & (1 << 30):
if msg not in (WM_KEYUP, WM_SYSKEYUP):
repeat = True
ev = 'on_key_release'
else:
ev = 'on_key_press'
symbol = keymap.get(wParam, None)
if symbol is None:
ch = _user32.MapVirtualKeyW(wParam, MAPVK_VK_TO_CHAR)
symbol = chmap.get(ch)
if symbol is None:
symbol = key.user_key(wParam)
elif symbol == key.LCTRL and lParam & (1 << 24):
symbol = key.RCTRL
elif symbol == key.LALT and lParam & (1 << 24):
symbol = key.RALT
elif symbol == key.LSHIFT:
pass # TODO: some magic with getstate to find out if it's the
# right or left shift key.
modifiers = self._get_modifiers(lParam)
if not repeat:
self.dispatch_event(ev, symbol, modifiers)
ctrl = modifiers & key.MOD_CTRL != 0
if (symbol, ctrl) in _motion_map and msg not in (WM_KEYUP, WM_SYSKEYUP):
motion = _motion_map[symbol, ctrl]
if modifiers & key.MOD_SHIFT:
self.dispatch_event('on_text_motion_select', motion)
else:
self.dispatch_event('on_text_motion', motion)
# Send on to DefWindowProc if not exclusive.
if self._exclusive_keyboard:
return 0
else:
return None
@Win32EventHandler(WM_CHAR)
def _event_char(self, msg, wParam, lParam):
text = chr(wParam)
if unicodedata.category(text) != 'Cc' or text == '\r':
self.dispatch_event('on_text', text)
return 0
@ViewEventHandler
@Win32EventHandler(WM_INPUT)
def _event_raw_input(self, msg, wParam, lParam):
if not self._exclusive_mouse:
return 0
hRawInput = cast(lParam, HRAWINPUT)
inp = RAWINPUT()
size = UINT(sizeof(inp))
_user32.GetRawInputData(hRawInput, RID_INPUT, byref(inp),
byref(size), sizeof(RAWINPUTHEADER))
if inp.header.dwType == RIM_TYPEMOUSE:
rmouse = inp.data.mouse
if rmouse.usButtonFlags & RI_MOUSE_LEFT_BUTTON_DOWN:
self.dispatch_event('on_mouse_press', 0, 0, mouse.LEFT,
self._get_modifiers())
self._exclusive_mouse_buttons |= mouse.LEFT
if rmouse.usButtonFlags & RI_MOUSE_LEFT_BUTTON_UP:
self.dispatch_event('on_mouse_release', 0, 0, mouse.LEFT,
self._get_modifiers())
self._exclusive_mouse_buttons &= ~mouse.LEFT
if rmouse.usButtonFlags & RI_MOUSE_RIGHT_BUTTON_DOWN:
self.dispatch_event('on_mouse_press', 0, 0, mouse.RIGHT,
self._get_modifiers())
self._exclusive_mouse_buttons |= mouse.RIGHT
if rmouse.usButtonFlags & RI_MOUSE_RIGHT_BUTTON_UP:
self.dispatch_event('on_mouse_release', 0, 0, mouse.RIGHT,
self._get_modifiers())
self._exclusive_mouse_buttons &= ~mouse.RIGHT
if rmouse.usButtonFlags & RI_MOUSE_MIDDLE_BUTTON_DOWN:
self.dispatch_event('on_mouse_press', 0, 0, mouse.MIDDLE,
self._get_modifiers())
self._exclusive_mouse_buttons |= mouse.MIDDLE
if rmouse.usButtonFlags & RI_MOUSE_MIDDLE_BUTTON_UP:
self.dispatch_event('on_mouse_release', 0, 0, mouse.MIDDLE,
self._get_modifiers())
self._exclusive_mouse_buttons &= ~mouse.MIDDLE
if rmouse.usButtonFlags & RI_MOUSE_WHEEL:
delta = SHORT(rmouse.usButtonData).value
self.dispatch_event('on_mouse_scroll',
0, 0, 0, delta / float(WHEEL_DELTA))
if rmouse.usFlags & 0x01 == MOUSE_MOVE_RELATIVE:
if rmouse.lLastX != 0 or rmouse.lLastY != 0:
# Motion event
# In relative motion, Y axis is positive for below.
# We invert it for Pyglet so positive is motion up.
if self._exclusive_mouse_buttons:
self.dispatch_event('on_mouse_drag', 0, 0,
rmouse.lLastX, -rmouse.lLastY,
self._exclusive_mouse_buttons,
self._get_modifiers())
else:
self.dispatch_event('on_mouse_motion', 0, 0,
rmouse.lLastX, -rmouse.lLastY)
else:
if self._exclusive_mouse_lpos is None:
self._exclusive_mouse_lpos = rmouse.lLastX, rmouse.lLastY
last_x, last_y = self._exclusive_mouse_lpos
rel_x = rmouse.lLastX - last_x
rel_y = rmouse.lLastY - last_y
if rel_x != 0 or rel_y != 0.0:
# Motion event
if self._exclusive_mouse_buttons:
self.dispatch_event('on_mouse_drag', 0, 0,
rmouse.lLastX, -rmouse.lLastY,
self._exclusive_mouse_buttons,
self._get_modifiers())
else:
self.dispatch_event('on_mouse_motion', 0, 0,
rel_x, rel_y)
self._exclusive_mouse_lpos = rmouse.lLastX, rmouse.lLastY
return 0
@ViewEventHandler
@Win32EventHandler(WM_MOUSEMOVE)
def _event_mousemove(self, msg, wParam, lParam):
if self._exclusive_mouse and self._has_focus:
return 0
x, y = self._get_location(lParam)
y = self._height - y
dx = x - self._mouse_x
dy = y - self._mouse_y
if not self._tracking:
# There is no WM_MOUSEENTER message (!), so fake it from the
# first WM_MOUSEMOVE event after leaving. Use self._tracking
# to determine when to recreate the tracking structure after
# re-entering (to track the next WM_MOUSELEAVE).
self._mouse_in_window = True
self.set_mouse_platform_visible()
self.dispatch_event('on_mouse_enter', x, y)
self._tracking = True
track = TRACKMOUSEEVENT()
track.cbSize = sizeof(track)
track.dwFlags = TME_LEAVE
track.hwndTrack = self._view_hwnd
_user32.TrackMouseEvent(byref(track))
# Don't generate motion/drag events when mouse hasn't moved. (Issue
# 305)
if self._mouse_x == x and self._mouse_y == y:
return 0
self._mouse_x = x
self._mouse_y = y
buttons = 0
if wParam & MK_LBUTTON:
buttons |= mouse.LEFT
if wParam & MK_MBUTTON:
buttons |= mouse.MIDDLE
if wParam & MK_RBUTTON:
buttons |= mouse.RIGHT
if buttons:
# Drag event
modifiers = self._get_modifiers()
self.dispatch_event('on_mouse_drag',
x, y, dx, dy, buttons, modifiers)
else:
# Motion event
self.dispatch_event('on_mouse_motion', x, y, dx, dy)
return 0
@ViewEventHandler
@Win32EventHandler(WM_MOUSELEAVE)
def _event_mouseleave(self, msg, wParam, lParam):
point = POINT()
_user32.GetCursorPos(byref(point))
_user32.ScreenToClient(self._view_hwnd, byref(point))
x = point.x
y = self._height - point.y
self._tracking = False
self._mouse_in_window = False
self.set_mouse_platform_visible()
self.dispatch_event('on_mouse_leave', x, y)
return 0
def _event_mousebutton(self, ev, button, lParam):
if ev == 'on_mouse_press':
_user32.SetCapture(self._view_hwnd)
else:
_user32.ReleaseCapture()
x, y = self._get_location(lParam)
y = self._height - y
self.dispatch_event(ev, x, y, button, self._get_modifiers())
return 0
@ViewEventHandler
@Win32EventHandler(WM_LBUTTONDOWN)
def _event_lbuttondown(self, msg, wParam, lParam):
return self._event_mousebutton(
'on_mouse_press', mouse.LEFT, lParam)
@ViewEventHandler
@Win32EventHandler(WM_LBUTTONUP)
def _event_lbuttonup(self, msg, wParam, lParam):
return self._event_mousebutton(
'on_mouse_release', mouse.LEFT, lParam)
@ViewEventHandler
@Win32EventHandler(WM_MBUTTONDOWN)
def _event_mbuttondown(self, msg, wParam, lParam):
return self._event_mousebutton(
'on_mouse_press', mouse.MIDDLE, lParam)
@ViewEventHandler
@Win32EventHandler(WM_MBUTTONUP)
def _event_mbuttonup(self, msg, wParam, lParam):
return self._event_mousebutton(
'on_mouse_release', mouse.MIDDLE, lParam)
@ViewEventHandler
@Win32EventHandler(WM_RBUTTONDOWN)
def _event_rbuttondown(self, msg, wParam, lParam):
return self._event_mousebutton(
'on_mouse_press', mouse.RIGHT, lParam)
@ViewEventHandler
@Win32EventHandler(WM_RBUTTONUP)
def _event_rbuttonup(self, msg, wParam, lParam):
return self._event_mousebutton(
'on_mouse_release', mouse.RIGHT, lParam)
@Win32EventHandler(WM_MOUSEWHEEL)
def _event_mousewheel(self, msg, wParam, lParam):
delta = c_short(wParam >> 16).value
self.dispatch_event('on_mouse_scroll',
self._mouse_x, self._mouse_y, 0, delta / float(WHEEL_DELTA))
return 0
@Win32EventHandler(WM_CLOSE)
def _event_close(self, msg, wParam, lParam):
self.dispatch_event('on_close')
return 0
@ViewEventHandler
@Win32EventHandler(WM_PAINT)
def _event_paint(self, msg, wParam, lParam):
self.dispatch_event('on_expose')
# Validating the window using ValidateRect or ValidateRgn
# doesn't clear the paint message when more than one window
# is open [why?]; defer to DefWindowProc instead.
return None
@Win32EventHandler(WM_SIZING)
def _event_sizing(self, msg, wParam, lParam):
# rect = cast(lParam, POINTER(RECT)).contents
# width, height = self.get_size()
from pyglet import app
if app.event_loop is not None:
app.event_loop.enter_blocking()
return 1
@Win32EventHandler(WM_SIZE)
def _event_size(self, msg, wParam, lParam):
if not self._dc:
# Ignore window creation size event (appears for fullscreen
# only) -- we haven't got DC or HWND yet.
return None
if wParam == SIZE_MINIMIZED:
# Minimized, not resized.
self._hidden = True
self.dispatch_event('on_hide')
return 0
if self._hidden:
# Restored
self._hidden = False
self.dispatch_event('on_show')
w, h = self._get_location(lParam)
if not self._fullscreen:
self._width, self._height = w, h
self._update_view_location(self._width, self._height)
self.switch_to()
self.dispatch_event('on_resize', self._width, self._height)
return 0
@Win32EventHandler(WM_SYSCOMMAND)
def _event_syscommand(self, msg, wParam, lParam):
# check for ALT key to prevent app from hanging because there is
# no windows menu bar
if wParam == SC_KEYMENU and lParam & (1 >> 16) <= 0:
return 0
if wParam & 0xfff0 in (SC_MOVE, SC_SIZE):
# Should be in WM_ENTERSIZEMOVE, but we never get that message.
from pyglet import app
if app.event_loop is not None:
app.event_loop.enter_blocking()
@Win32EventHandler(WM_MOVE)
def _event_move(self, msg, wParam, lParam):
x, y = self._get_location(lParam)
self.dispatch_event('on_move', x, y)
return 0
@Win32EventHandler(WM_EXITSIZEMOVE)
def _event_entersizemove(self, msg, wParam, lParam):
from pyglet import app
if app.event_loop is not None:
app.event_loop.exit_blocking()
'''
# Alternative to using WM_SETFOCUS and WM_KILLFOCUS. Which
# is better?
@Win32EventHandler(WM_ACTIVATE)
def _event_activate(self, msg, wParam, lParam):
if wParam & 0xffff == WA_INACTIVE:
self.dispatch_event('on_deactivate')
else:
self.dispatch_event('on_activate')
_user32.SetFocus(self._hwnd)
return 0
'''
@Win32EventHandler(WM_SETFOCUS)
def _event_setfocus(self, msg, wParam, lParam):
self.dispatch_event('on_activate')
self._has_focus = True
self.set_exclusive_keyboard(self._exclusive_keyboard)
self.set_exclusive_mouse(self._exclusive_mouse)
return 0
@Win32EventHandler(WM_KILLFOCUS)
def _event_killfocus(self, msg, wParam, lParam):
self.dispatch_event('on_deactivate')
self._has_focus = False
exclusive_keyboard = self._exclusive_keyboard
exclusive_mouse = self._exclusive_mouse
# Disable both exclusive keyboard and mouse
self.set_exclusive_keyboard(False)
self.set_exclusive_mouse(False)
# But save desired state and note that we lost focus
# This will allow to reset the correct mode once we regain focus
self._exclusive_keyboard = exclusive_keyboard
self._exclusive_keyboard_focus = False
self._exclusive_mouse = exclusive_mouse
self._exclusive_mouse_focus = False
return 0
@Win32EventHandler(WM_GETMINMAXINFO)
def _event_getminmaxinfo(self, msg, wParam, lParam):
info = MINMAXINFO.from_address(lParam)
if self._minimum_size:
info.ptMinTrackSize.x, info.ptMinTrackSize.y = \
self._client_to_window_size(*self._minimum_size)
if self._maximum_size:
info.ptMaxTrackSize.x, info.ptMaxTrackSize.y = \
self._client_to_window_size(*self._maximum_size)
return 0
@Win32EventHandler(WM_ERASEBKGND)
def _event_erasebkgnd(self, msg, wParam, lParam):
# Prevent flicker during resize; but erase bkgnd if we're fullscreen.
if self._fullscreen:
return 0
else:
return 1
@ViewEventHandler
@Win32EventHandler(WM_ERASEBKGND)
def _event_erasebkgnd_view(self, msg, wParam, lParam):
# Prevent flicker during resize.
return 1
| 40,022 | 36.404673 | 84 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/pyglet/window/cocoa/systemcursor.py
|
from builtins import object
from pyglet.libs.darwin.cocoapy import *
# This class is a wrapper around NSCursor which prevents us from
# sending too many hide or unhide messages in a row. Apparently
# NSCursor treats them like retain/release messages, which can be
# problematic when we are e.g. switching between window & fullscreen.
class SystemCursor(object):
cursor_is_hidden = False
@classmethod
def hide(cls):
if not cls.cursor_is_hidden:
send_message('NSCursor', 'hide')
cls.cursor_is_hidden = True
@classmethod
def unhide(cls):
if cls.cursor_is_hidden:
send_message('NSCursor', 'unhide')
cls.cursor_is_hidden = False
| 710 | 34.55 | 69 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/pyglet/window/cocoa/pyglet_delegate.py
|
from __future__ import absolute_import
from builtins import object
from pyglet.libs.darwin.cocoapy import *
from .systemcursor import SystemCursor
NSNotificationCenter = ObjCClass('NSNotificationCenter')
NSApplication = ObjCClass('NSApplication')
class PygletDelegate_Implementation(object):
PygletDelegate = ObjCSubclass('NSObject', 'PygletDelegate')
@PygletDelegate.method(b'@'+PyObjectEncoding)
def initWithWindow_(self, window):
self = ObjCInstance(send_super(self, 'init'))
if not self:
return None
# CocoaWindow object.
self._window = window
window._nswindow.setDelegate_(self)
# Register delegate for hide and unhide notifications so that we
# can dispatch the corresponding pyglet events.
notificationCenter = NSNotificationCenter.defaultCenter()
notificationCenter.addObserver_selector_name_object_(
self, get_selector('applicationDidHide:'),
NSApplicationDidHideNotification, None)
notificationCenter.addObserver_selector_name_object_(
self, get_selector('applicationDidUnhide:'),
NSApplicationDidUnhideNotification, None)
# Flag set when we pause exclusive mouse mode if window loses key status.
self.did_pause_exclusive_mouse = False
return self
@PygletDelegate.method('v')
def dealloc(self):
# Unregister delegate from notification center.
notificationCenter = NSNotificationCenter.defaultCenter()
notificationCenter.removeObserver_(self)
self._window = None
send_super(self, 'dealloc')
@PygletDelegate.method('v@')
def applicationDidHide_(self, notification):
self._window.dispatch_event("on_hide")
@PygletDelegate.method('v@')
def applicationDidUnhide_(self, notification):
if self._window._is_mouse_exclusive and quartz.CGCursorIsVisible():
# The cursor should be hidden, but for some reason it's not;
# try to force the cursor to hide (without over-hiding).
SystemCursor.unhide()
SystemCursor.hide()
pass
self._window.dispatch_event("on_show")
@PygletDelegate.method('B@')
def windowShouldClose_(self, notification):
# The method is not called if [NSWindow close] was used.
self._window.dispatch_event("on_close")
return False
@PygletDelegate.method('v@')
def windowDidMove_(self, notification):
x, y = self._window.get_location()
self._window.dispatch_event("on_move", x, y)
@PygletDelegate.method('v@')
def windowDidBecomeKey_(self, notification):
# Restore exclusive mouse mode if it was active before we lost key status.
if self.did_pause_exclusive_mouse:
self._window.set_exclusive_mouse(True)
self.did_pause_exclusive_mouse = False
self._window._nswindow.setMovable_(True) # Mac OS 10.6
# Restore previous mouse visibility settings.
self._window.set_mouse_platform_visible()
self._window.dispatch_event("on_activate")
@PygletDelegate.method('v@')
def windowDidResignKey_(self, notification):
# Pause exclusive mouse mode if it is active.
if self._window._is_mouse_exclusive:
self._window.set_exclusive_mouse(False)
self.did_pause_exclusive_mouse = True
# We need to prevent the window from being unintentionally dragged
# (by the call to set_mouse_position in set_exclusive_mouse) when
# the window is reactivated by clicking on its title bar.
self._window._nswindow.setMovable_(False) # Mac OS X 10.6
# Make sure that cursor is visible.
self._window.set_mouse_platform_visible(True)
self._window.dispatch_event("on_deactivate")
@PygletDelegate.method('v@')
def windowDidMiniaturize_(self, notification):
self._window.dispatch_event("on_hide")
@PygletDelegate.method('v@')
def windowDidDeminiaturize_(self, notification):
if self._window._is_mouse_exclusive and quartz.CGCursorIsVisible():
# The cursor should be hidden, but for some reason it's not;
# try to force the cursor to hide (without over-hiding).
SystemCursor.unhide()
SystemCursor.hide()
pass
self._window.dispatch_event("on_show")
@PygletDelegate.method('v@')
def windowDidExpose_(self, notification):
self._window.dispatch_event("on_expose")
@PygletDelegate.method('v@')
def terminate_(self, sender):
NSApp = NSApplication.sharedApplication()
NSApp.terminate_(self)
@PygletDelegate.method('B@')
def validateMenuItem_(self, menuitem):
# Disable quitting with command-q when in keyboard exclusive mode.
if menuitem.action() == get_selector('terminate:'):
return not self._window._is_keyboard_exclusive
return True
PygletDelegate = ObjCClass('PygletDelegate')
| 5,070 | 38.310078 | 83 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/pyglet/window/cocoa/pyglet_textview.py
|
from builtins import chr
from builtins import object
import unicodedata
from pyglet.window import key
from pyglet.libs.darwin.cocoapy import *
NSArray = ObjCClass('NSArray')
NSApplication = ObjCClass('NSApplication')
# This custom NSTextView subclass is used for capturing all of the
# on_text, on_text_motion, and on_text_motion_select events.
class PygletTextView_Implementation(object):
PygletTextView = ObjCSubclass('NSTextView', 'PygletTextView')
@PygletTextView.method(b'@'+PyObjectEncoding)
def initWithCocoaWindow_(self, window):
self = ObjCInstance(send_super(self, 'init'))
if not self:
return None
self._window = window
# Interpret tab and return as raw characters
self.setFieldEditor_(False)
self.empty_string = CFSTR("")
return self
@PygletTextView.method('v')
def dealloc(self):
self.empty_string.release()
@PygletTextView.method('v@')
def keyDown_(self, nsevent):
array = NSArray.arrayWithObject_(nsevent)
self.interpretKeyEvents_(array)
@PygletTextView.method('v@')
def insertText_(self, text):
text = cfstring_to_string(text)
self.setString_(self.empty_string)
# Don't send control characters (tab, newline) as on_text events.
if unicodedata.category(text[0]) != 'Cc':
self._window.dispatch_event("on_text", text)
@PygletTextView.method('v@')
def insertNewline_(self, sender):
# Distinguish between carriage return (u'\r') and enter (u'\x03').
# Only the return key press gets sent as an on_text event.
event = NSApplication.sharedApplication().currentEvent()
chars = event.charactersIgnoringModifiers()
ch = chr(chars.characterAtIndex_(0))
if ch == u'\r':
self._window.dispatch_event("on_text", u'\r')
@PygletTextView.method('v@')
def moveUp_(self, sender):
self._window.dispatch_event("on_text_motion", key.MOTION_UP)
@PygletTextView.method('v@')
def moveDown_(self, sender):
self._window.dispatch_event("on_text_motion", key.MOTION_DOWN)
@PygletTextView.method('v@')
def moveLeft_(self, sender):
self._window.dispatch_event("on_text_motion", key.MOTION_LEFT)
@PygletTextView.method('v@')
def moveRight_(self, sender):
self._window.dispatch_event("on_text_motion", key.MOTION_RIGHT)
@PygletTextView.method('v@')
def moveWordLeft_(self, sender):
self._window.dispatch_event("on_text_motion", key.MOTION_PREVIOUS_WORD)
@PygletTextView.method('v@')
def moveWordRight_(self, sender):
self._window.dispatch_event("on_text_motion", key.MOTION_NEXT_WORD)
@PygletTextView.method('v@')
def moveToBeginningOfLine_(self, sender):
self._window.dispatch_event("on_text_motion", key.MOTION_BEGINNING_OF_LINE)
@PygletTextView.method('v@')
def moveToEndOfLine_(self, sender):
self._window.dispatch_event("on_text_motion", key.MOTION_END_OF_LINE)
@PygletTextView.method('v@')
def scrollPageUp_(self, sender):
self._window.dispatch_event("on_text_motion", key.MOTION_PREVIOUS_PAGE)
@PygletTextView.method('v@')
def scrollPageDown_(self, sender):
self._window.dispatch_event("on_text_motion", key.MOTION_NEXT_PAGE)
@PygletTextView.method('v@')
def scrollToBeginningOfDocument_(self, sender): # Mac OS X 10.6
self._window.dispatch_event("on_text_motion", key.MOTION_BEGINNING_OF_FILE)
@PygletTextView.method('v@')
def scrollToEndOfDocument_(self, sender): # Mac OS X 10.6
self._window.dispatch_event("on_text_motion", key.MOTION_END_OF_FILE)
@PygletTextView.method('v@')
def deleteBackward_(self, sender):
self._window.dispatch_event("on_text_motion", key.MOTION_BACKSPACE)
@PygletTextView.method('v@')
def deleteForward_(self, sender):
self._window.dispatch_event("on_text_motion", key.MOTION_DELETE)
@PygletTextView.method('v@')
def moveUpAndModifySelection_(self, sender):
self._window.dispatch_event("on_text_motion_select", key.MOTION_UP)
@PygletTextView.method('v@')
def moveDownAndModifySelection_(self, sender):
self._window.dispatch_event("on_text_motion_select", key.MOTION_DOWN)
@PygletTextView.method('v@')
def moveLeftAndModifySelection_(self, sender):
self._window.dispatch_event("on_text_motion_select", key.MOTION_LEFT)
@PygletTextView.method('v@')
def moveRightAndModifySelection_(self, sender):
self._window.dispatch_event("on_text_motion_select", key.MOTION_RIGHT)
@PygletTextView.method('v@')
def moveWordLeftAndModifySelection_(self, sender):
self._window.dispatch_event("on_text_motion_select", key.MOTION_PREVIOUS_WORD)
@PygletTextView.method('v@')
def moveWordRightAndModifySelection_(self, sender):
self._window.dispatch_event("on_text_motion_select", key.MOTION_NEXT_WORD)
@PygletTextView.method('v@')
def moveToBeginningOfLineAndModifySelection_(self, sender): # Mac OS X 10.6
self._window.dispatch_event("on_text_motion_select", key.MOTION_BEGINNING_OF_LINE)
@PygletTextView.method('v@')
def moveToEndOfLineAndModifySelection_(self, sender): # Mac OS X 10.6
self._window.dispatch_event("on_text_motion_select", key.MOTION_END_OF_LINE)
@PygletTextView.method('v@')
def pageUpAndModifySelection_(self, sender): # Mac OS X 10.6
self._window.dispatch_event("on_text_motion_select", key.MOTION_PREVIOUS_PAGE)
@PygletTextView.method('v@')
def pageDownAndModifySelection_(self, sender): # Mac OS X 10.6
self._window.dispatch_event("on_text_motion_select", key.MOTION_NEXT_PAGE)
@PygletTextView.method('v@')
def moveToBeginningOfDocumentAndModifySelection_(self, sender): # Mac OS X 10.6
self._window.dispatch_event("on_text_motion_select", key.MOTION_BEGINNING_OF_FILE)
@PygletTextView.method('v@')
def moveToEndOfDocumentAndModifySelection_(self, sender): # Mac OS X 10.6
self._window.dispatch_event("on_text_motion_select", key.MOTION_END_OF_FILE)
PygletTextView = ObjCClass('PygletTextView')
| 6,312 | 38.21118 | 94 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/pyglet/window/cocoa/pyglet_window.py
|
from builtins import object
from pyglet.libs.darwin.cocoapy import *
class PygletWindow_Implementation(object):
PygletWindow = ObjCSubclass('NSWindow', 'PygletWindow')
@PygletWindow.method('B')
def canBecomeKeyWindow(self):
return True
# When the window is being resized, it enters into a mini event loop that
# only looks at mouseDragged and mouseUp events, blocking everything else.
# Among other things, this makes it impossible to run an NSTimer to call the
# idle() function in order to update the view during the resize. So we
# override this method, called by the resizing event loop, and call the
# idle() function from here. This *almost* works. I can't figure out what
# is happening at the very beginning of a resize event. The NSView's
# viewWillStartLiveResize method is called and then nothing happens until
# the mouse is dragged. I think NSApplication's nextEventMatchingMask_etc
# method is being called instead of this one. I don't really feel like
# subclassing NSApplication just to fix this. Also, to prevent white flashes
# while resizing, we must also call idle() from the view's reshape method.
@PygletWindow.method(b'@'+NSUIntegerEncoding+b'@@B')
def nextEventMatchingMask_untilDate_inMode_dequeue_(self, mask, date, mode, dequeue):
if self.inLiveResize():
# Call the idle() method while we're stuck in a live resize event.
from pyglet import app
if app.event_loop is not None:
app.event_loop.idle()
event = send_super(self, 'nextEventMatchingMask:untilDate:inMode:dequeue:',
mask, date, mode, dequeue, argtypes=[NSUInteger, c_void_p, c_void_p, c_bool])
if event.value == None:
return 0
else:
return event.value
# Need this for set_size to not flash.
@PygletWindow.method(b'd'+NSRectEncoding)
def animationResizeTime_(self, newFrame):
return 0.0
class PygletToolWindow_Implementation(object):
PygletToolWindow = ObjCSubclass('NSPanel', 'PygletToolWindow')
@PygletToolWindow.method(b'@'+NSUIntegerEncoding+b'@@B')
def nextEventMatchingMask_untilDate_inMode_dequeue_(self, mask, date, mode, dequeue):
if self.inLiveResize():
# Call the idle() method while we're stuck in a live resize event.
from pyglet import app
if app.event_loop is not None:
app.event_loop.idle()
event = send_super(self, 'nextEventMatchingMask:untilDate:inMode:dequeue:',
mask, date, mode, dequeue, argtypes=[NSUInteger, c_void_p, c_void_p, c_bool])
if event.value == None:
return 0
else:
return event.value
# Need this for set_size to not flash.
@PygletToolWindow.method(b'd'+NSRectEncoding)
def animationResizeTime_(self, newFrame):
return 0.0
PygletWindow = ObjCClass('PygletWindow')
PygletToolWindow = ObjCClass('PygletToolWindow')
| 3,077 | 41.75 | 104 |
py
|
cba-pipeline-public
|
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/pyglet/window/cocoa/pyglet_view.py
|
from builtins import object
from pyglet.window import key, mouse
from pyglet.libs.darwin.quartzkey import keymap, charmap
from pyglet.libs.darwin.cocoapy import *
NSTrackingArea = ObjCClass('NSTrackingArea')
# Event data helper functions.
def getMouseDelta(nsevent):
dx = nsevent.deltaX()
dy = -nsevent.deltaY()
return int(round(dx)), int(round(dy))
def getMousePosition(self, nsevent):
in_window = nsevent.locationInWindow()
in_window = self.convertPoint_fromView_(in_window, None)
x = int(in_window.x)
y = int(in_window.y)
# Must record mouse position for BaseWindow.draw_mouse_cursor to work.
self._window._mouse_x = x
self._window._mouse_y = y
return x, y
def getModifiers(nsevent):
modifiers = 0
modifierFlags = nsevent.modifierFlags()
if modifierFlags & NSAlphaShiftKeyMask:
modifiers |= key.MOD_CAPSLOCK
if modifierFlags & NSShiftKeyMask:
modifiers |= key.MOD_SHIFT
if modifierFlags & NSControlKeyMask:
modifiers |= key.MOD_CTRL
if modifierFlags & NSAlternateKeyMask:
modifiers |= key.MOD_ALT
modifiers |= key.MOD_OPTION
if modifierFlags & NSCommandKeyMask:
modifiers |= key.MOD_COMMAND
if modifierFlags & NSFunctionKeyMask:
modifiers |= key.MOD_FUNCTION
return modifiers
def getSymbol(nsevent):
symbol = keymap.get(nsevent.keyCode(), None)
if symbol is not None:
return symbol
chars = cfstring_to_string(nsevent.charactersIgnoringModifiers())
if chars:
return charmap[chars[0].upper()]
return None
class PygletView_Implementation(object):
PygletView = ObjCSubclass('NSView', 'PygletView')
@PygletView.method(b'@'+NSRectEncoding+PyObjectEncoding)
def initWithFrame_cocoaWindow_(self, frame, window):
# The tracking area is used to get mouseEntered, mouseExited, and cursorUpdate
# events so that we can custom set the mouse cursor within the view.
self._tracking_area = None
self = ObjCInstance(send_super(self, 'initWithFrame:', frame, argtypes=[NSRect]))
if not self:
return None
# CocoaWindow object.
self._window = window
self.updateTrackingAreas()
# Create an instance of PygletTextView to handle text events.
# We must do this because NSOpenGLView doesn't conform to the
# NSTextInputClient protocol by default, and the insertText: method will
# not do the right thing with respect to translating key sequences like
# "Option-e", "e" if the protocol isn't implemented. So the easiest
# thing to do is to subclass NSTextView which *does* implement the
# protocol and let it handle text input.
PygletTextView = ObjCClass('PygletTextView')
self._textview = PygletTextView.alloc().initWithCocoaWindow_(window)
# Add text view to the responder chain.
self.addSubview_(self._textview)
return self
@PygletView.method('v')
def dealloc(self):
self._window = None
#send_message(self.objc_self, 'removeFromSuperviewWithoutNeedingDisplay')
self._textview.release()
self._textview = None
self._tracking_area.release()
self._tracking_area = None
send_super(self, 'dealloc')
@PygletView.method('v')
def updateTrackingAreas(self):
# This method is called automatically whenever the tracking areas need to be
# recreated, for example when window resizes.
if self._tracking_area:
self.removeTrackingArea_(self._tracking_area)
self._tracking_area.release()
self._tracking_area = None
tracking_options = NSTrackingMouseEnteredAndExited | NSTrackingActiveInActiveApp | NSTrackingCursorUpdate
frame = self.frame()
self._tracking_area = NSTrackingArea.alloc().initWithRect_options_owner_userInfo_(
frame, # rect
tracking_options, # options
self, # owner
None) # userInfo
self.addTrackingArea_(self._tracking_area)
@PygletView.method('B')
def canBecomeKeyView(self):
return True
@PygletView.method('B')
def isOpaque(self):
return True
## Event responders.
# This method is called whenever the view changes size.
@PygletView.method(b'v'+NSSizeEncoding)
def setFrameSize_(self, size):
send_super(self, 'setFrameSize:', size, argtypes=[NSSize])
# This method is called when view is first installed as the
# contentView of window. Don't do anything on first call.
# This also helps ensure correct window creation event ordering.
if not self._window.context.canvas:
return
width, height = int(size.width), int(size.height)
self._window.switch_to()
self._window.context.update_geometry()
self._window.dispatch_event("on_resize", width, height)
self._window.dispatch_event("on_expose")
# Can't get app.event_loop.enter_blocking() working with Cocoa, because
# when mouse clicks on the window's resize control, Cocoa enters into a
# mini-event loop that only responds to mouseDragged and mouseUp events.
# This means that using NSTimer to call idle() won't work. Our kludge
# is to override NSWindow's nextEventMatchingMask_etc method and call
# idle() from there.
if self.inLiveResize():
from pyglet import app
if app.event_loop is not None:
app.event_loop.idle()
@PygletView.method('v@')
def pygletKeyDown_(self, nsevent):
symbol = getSymbol(nsevent)
modifiers = getModifiers(nsevent)
self._window.dispatch_event('on_key_press', symbol, modifiers)
@PygletView.method('v@')
def pygletKeyUp_(self, nsevent):
symbol = getSymbol(nsevent)
modifiers = getModifiers(nsevent)
self._window.dispatch_event('on_key_release', symbol, modifiers)
@PygletView.method('v@')
def pygletFlagsChanged_(self, nsevent):
# Handles on_key_press and on_key_release events for modifier keys.
# Note that capslock is handled differently than other keys; it acts
# as a toggle, so on_key_release is only sent when it's turned off.
# TODO: Move these constants somewhere else.
# Undocumented left/right modifier masks found by experimentation:
NSLeftShiftKeyMask = 1 << 1
NSRightShiftKeyMask = 1 << 2
NSLeftControlKeyMask = 1 << 0
NSRightControlKeyMask = 1 << 13
NSLeftAlternateKeyMask = 1 << 5
NSRightAlternateKeyMask = 1 << 6
NSLeftCommandKeyMask = 1 << 3
NSRightCommandKeyMask = 1 << 4
maskForKey = { key.LSHIFT : NSLeftShiftKeyMask,
key.RSHIFT : NSRightShiftKeyMask,
key.LCTRL : NSLeftControlKeyMask,
key.RCTRL : NSRightControlKeyMask,
key.LOPTION : NSLeftAlternateKeyMask,
key.ROPTION : NSRightAlternateKeyMask,
key.LCOMMAND : NSLeftCommandKeyMask,
key.RCOMMAND : NSRightCommandKeyMask,
key.CAPSLOCK : NSAlphaShiftKeyMask,
key.FUNCTION : NSFunctionKeyMask }
symbol = keymap.get(nsevent.keyCode(), None)
# Ignore this event if symbol is not a modifier key. We must check this
# because e.g., we receive a flagsChanged message when using CMD-tab to
# switch applications, with symbol == "a" when command key is released.
if symbol is None or symbol not in maskForKey:
return
modifiers = getModifiers(nsevent)
modifierFlags = nsevent.modifierFlags()
if symbol and modifierFlags & maskForKey[symbol]:
self._window.dispatch_event('on_key_press', symbol, modifiers)
else:
self._window.dispatch_event('on_key_release', symbol, modifiers)
# Overriding this method helps prevent system beeps for unhandled events.
@PygletView.method('B@')
def performKeyEquivalent_(self, nsevent):
# Let arrow keys and certain function keys pass through the responder
# chain so that the textview can handle on_text_motion events.
modifierFlags = nsevent.modifierFlags()
if modifierFlags & NSNumericPadKeyMask:
return False
if modifierFlags & NSFunctionKeyMask:
ch = cfstring_to_string(nsevent.charactersIgnoringModifiers())
if ch in (NSHomeFunctionKey, NSEndFunctionKey,
NSPageUpFunctionKey, NSPageDownFunctionKey):
return False
# Send the key equivalent to the main menu to perform menu items.
NSApp = ObjCClass('NSApplication').sharedApplication()
NSApp.mainMenu().performKeyEquivalent_(nsevent)
# Indicate that we've handled the event so system won't beep.
return True
@PygletView.method('v@')
def mouseMoved_(self, nsevent):
if self._window._mouse_ignore_motion:
self._window._mouse_ignore_motion = False
return
# Don't send on_mouse_motion events if we're not inside the content rectangle.
if not self._window._mouse_in_window:
return
x, y = getMousePosition(self, nsevent)
dx, dy = getMouseDelta(nsevent)
self._window.dispatch_event('on_mouse_motion', x, y, dx, dy)
@PygletView.method('v@')
def scrollWheel_(self, nsevent):
x, y = getMousePosition(self, nsevent)
scroll_x, scroll_y = getMouseDelta(nsevent)
self._window.dispatch_event('on_mouse_scroll', x, y, scroll_x, scroll_y)
@PygletView.method('v@')
def mouseDown_(self, nsevent):
x, y = getMousePosition(self, nsevent)
buttons = mouse.LEFT
modifiers = getModifiers(nsevent)
self._window.dispatch_event('on_mouse_press', x, y, buttons, modifiers)
@PygletView.method('v@')
def mouseDragged_(self, nsevent):
x, y = getMousePosition(self, nsevent)
dx, dy = getMouseDelta(nsevent)
buttons = mouse.LEFT
modifiers = getModifiers(nsevent)
self._window.dispatch_event('on_mouse_drag', x, y, dx, dy, buttons, modifiers)
@PygletView.method('v@')
def mouseUp_(self, nsevent):
x, y = getMousePosition(self, nsevent)
buttons = mouse.LEFT
modifiers = getModifiers(nsevent)
self._window.dispatch_event('on_mouse_release', x, y, buttons, modifiers)
@PygletView.method('v@')
def rightMouseDown_(self, nsevent):
x, y = getMousePosition(self, nsevent)
buttons = mouse.RIGHT
modifiers = getModifiers(nsevent)
self._window.dispatch_event('on_mouse_press', x, y, buttons, modifiers)
@PygletView.method('v@')
def rightMouseDragged_(self, nsevent):
x, y = getMousePosition(self, nsevent)
dx, dy = getMouseDelta(nsevent)
buttons = mouse.RIGHT
modifiers = getModifiers(nsevent)
self._window.dispatch_event('on_mouse_drag', x, y, dx, dy, buttons, modifiers)
@PygletView.method('v@')
def rightMouseUp_(self, nsevent):
x, y = getMousePosition(self, nsevent)
buttons = mouse.RIGHT
modifiers = getModifiers(nsevent)
self._window.dispatch_event('on_mouse_release', x, y, buttons, modifiers)
@PygletView.method('v@')
def otherMouseDown_(self, nsevent):
x, y = getMousePosition(self, nsevent)
buttons = mouse.MIDDLE
modifiers = getModifiers(nsevent)
self._window.dispatch_event('on_mouse_press', x, y, buttons, modifiers)
@PygletView.method('v@')
def otherMouseDragged_(self, nsevent):
x, y = getMousePosition(self, nsevent)
dx, dy = getMouseDelta(nsevent)
buttons = mouse.MIDDLE
modifiers = getModifiers(nsevent)
self._window.dispatch_event('on_mouse_drag', x, y, dx, dy, buttons, modifiers)
@PygletView.method('v@')
def otherMouseUp_(self, nsevent):
x, y = getMousePosition(self, nsevent)
buttons = mouse.MIDDLE
modifiers = getModifiers(nsevent)
self._window.dispatch_event('on_mouse_release', x, y, buttons, modifiers)
@PygletView.method('v@')
def mouseEntered_(self, nsevent):
x, y = getMousePosition(self, nsevent)
self._window._mouse_in_window = True
# Don't call self._window.set_mouse_platform_visible() from here.
# Better to do it from cursorUpdate:
self._window.dispatch_event('on_mouse_enter', x, y)
@PygletView.method('v@')
def mouseExited_(self, nsevent):
x, y = getMousePosition(self, nsevent)
self._window._mouse_in_window = False
if not self._window._is_mouse_exclusive:
self._window.set_mouse_platform_visible()
self._window.dispatch_event('on_mouse_leave', x, y)
@PygletView.method('v@')
def cursorUpdate_(self, nsevent):
# Called when mouse cursor enters view. Unlike mouseEntered:,
# this method will be called if the view appears underneath a
# motionless mouse cursor, as can happen during window creation,
# or when switching into fullscreen mode.
# BUG: If the mouse enters the window via the resize control at the
# the bottom right corner, the resize control will set the cursor
# to the default arrow and screw up our cursor tracking.
self._window._mouse_in_window = True
if not self._window._is_mouse_exclusive:
self._window.set_mouse_platform_visible()
PygletView = ObjCClass('PygletView')
| 13,818 | 38.939306 | 113 |
py
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.