wirepod-vector-sdk-audio 0.9.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. anki_vector/__init__.py +43 -0
  2. anki_vector/animation.py +272 -0
  3. anki_vector/annotate.py +590 -0
  4. anki_vector/audio.py +212 -0
  5. anki_vector/audio_stream.py +335 -0
  6. anki_vector/behavior.py +1135 -0
  7. anki_vector/camera.py +670 -0
  8. anki_vector/camera_viewer/__init__.py +121 -0
  9. anki_vector/color.py +88 -0
  10. anki_vector/configure/__main__.py +331 -0
  11. anki_vector/connection.py +838 -0
  12. anki_vector/events.py +420 -0
  13. anki_vector/exceptions.py +185 -0
  14. anki_vector/faces.py +819 -0
  15. anki_vector/lights.py +210 -0
  16. anki_vector/mdns.py +131 -0
  17. anki_vector/messaging/__init__.py +45 -0
  18. anki_vector/messaging/alexa_pb2.py +36 -0
  19. anki_vector/messaging/alexa_pb2_grpc.py +3 -0
  20. anki_vector/messaging/behavior_pb2.py +40 -0
  21. anki_vector/messaging/behavior_pb2_grpc.py +3 -0
  22. anki_vector/messaging/client.py +33 -0
  23. anki_vector/messaging/cube_pb2.py +113 -0
  24. anki_vector/messaging/cube_pb2_grpc.py +3 -0
  25. anki_vector/messaging/extensions_pb2.py +25 -0
  26. anki_vector/messaging/extensions_pb2_grpc.py +3 -0
  27. anki_vector/messaging/external_interface_pb2.py +169 -0
  28. anki_vector/messaging/external_interface_pb2_grpc.py +1267 -0
  29. anki_vector/messaging/messages_pb2.py +431 -0
  30. anki_vector/messaging/messages_pb2_grpc.py +3 -0
  31. anki_vector/messaging/nav_map_pb2.py +33 -0
  32. anki_vector/messaging/nav_map_pb2_grpc.py +3 -0
  33. anki_vector/messaging/protocol.py +33 -0
  34. anki_vector/messaging/response_status_pb2.py +27 -0
  35. anki_vector/messaging/response_status_pb2_grpc.py +3 -0
  36. anki_vector/messaging/settings_pb2.py +72 -0
  37. anki_vector/messaging/settings_pb2_grpc.py +3 -0
  38. anki_vector/messaging/shared_pb2.py +54 -0
  39. anki_vector/messaging/shared_pb2_grpc.py +3 -0
  40. anki_vector/motors.py +127 -0
  41. anki_vector/nav_map.py +409 -0
  42. anki_vector/objects.py +1782 -0
  43. anki_vector/opengl/__init__.py +103 -0
  44. anki_vector/opengl/assets/LICENSE.txt +21 -0
  45. anki_vector/opengl/assets/cube.jpg +0 -0
  46. anki_vector/opengl/assets/cube.mtl +9 -0
  47. anki_vector/opengl/assets/cube.obj +1000 -0
  48. anki_vector/opengl/assets/vector.mtl +67 -0
  49. anki_vector/opengl/assets/vector.obj +13220 -0
  50. anki_vector/opengl/opengl.py +864 -0
  51. anki_vector/opengl/opengl_vector.py +620 -0
  52. anki_vector/opengl/opengl_viewer.py +689 -0
  53. anki_vector/photos.py +145 -0
  54. anki_vector/proximity.py +176 -0
  55. anki_vector/reserve_control/__main__.py +36 -0
  56. anki_vector/robot.py +930 -0
  57. anki_vector/screen.py +201 -0
  58. anki_vector/status.py +322 -0
  59. anki_vector/touch.py +119 -0
  60. anki_vector/user_intent.py +186 -0
  61. anki_vector/util.py +1132 -0
  62. anki_vector/version.py +15 -0
  63. anki_vector/viewer.py +403 -0
  64. anki_vector/vision.py +202 -0
  65. anki_vector/world.py +899 -0
  66. wirepod_vector_sdk_audio-0.9.0.dist-info/METADATA +80 -0
  67. wirepod_vector_sdk_audio-0.9.0.dist-info/RECORD +71 -0
  68. wirepod_vector_sdk_audio-0.9.0.dist-info/WHEEL +5 -0
  69. wirepod_vector_sdk_audio-0.9.0.dist-info/licenses/LICENSE.txt +180 -0
  70. wirepod_vector_sdk_audio-0.9.0.dist-info/top_level.txt +1 -0
  71. wirepod_vector_sdk_audio-0.9.0.dist-info/zip-safe +1 -0
@@ -0,0 +1,864 @@
1
+ # Copyright (c) 2018 Anki, Inc.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License in the file LICENSE.txt or at
6
+ #
7
+ # https://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """This module provides 3D support classes for OpenGL, used by opengl_viewer.py.
16
+
17
+ It uses PyOpenGL, a Python OpenGL 3D graphics library which is available on most
18
+ platforms. It also depends on the Pillow library for image processing.
19
+
20
+ Warning:
21
+ This package requires Python to have the PyOpenGL package installed, along
22
+ with an implementation of GLUT (OpenGL Utility Toolkit).
23
+
24
+ To install the Python packages on Mac and Linux do ``python3 -m pip install --user "wirepod_vector_sdk[3dviewer]"``
25
+
26
+ To install the Python packages on Windows do ``py -3 -m pip install --user "wirepod_vector_sdk[3dviewer]"``
27
+
28
+ On Windows and Linux you must also install freeglut (macOS / OSX has one
29
+ preinstalled).
30
+
31
+ On Linux: ``sudo apt-get install freeglut3``
32
+
33
+ On Windows: Go to http://freeglut.sourceforge.net/ to get a ``freeglut.dll``
34
+ file. It's included in any of the `Windows binaries` downloads. Place the DLL
35
+ next to your Python script, or install it somewhere in your PATH to allow any
36
+ script to use it."
37
+ """
38
+
39
+ # __all__ should order by constants, event classes, other classes, functions.
40
+ __all__ = ['Camera', 'DynamicTexture', 'MaterialLibrary', 'MeshData', 'MeshFace', 'MeshGroup', 'OpenGLWindow',
41
+ 'PrecomputedView', 'ResourceManager',
42
+ 'raise_opengl_or_pillow_import_error']
43
+
44
+ import math
45
+ import sys
46
+ from typing import List, Dict
47
+
48
+ from pkg_resources import resource_stream
49
+
50
+ from anki_vector import util
51
+
52
+
53
+ # TODO Move to exceptions.py
54
+ class InvalidOpenGLGlutImplementation(ImportError):
55
+ """Raised by OpenGLViewer if no valid GLUT implementation available."""
56
+
57
+
58
+ #: Adds context to exceptions raised from attempts to import OpenGL libraries
59
+ def raise_opengl_or_pillow_import_error(opengl_import_exc):
60
+ if isinstance(opengl_import_exc, InvalidOpenGLGlutImplementation):
61
+ raise NotImplementedError('GLUT (OpenGL Utility Toolkit) is not available:\n%s'
62
+ % opengl_import_exc)
63
+ raise NotImplementedError('OpenGL is not available; '
64
+ 'make sure the PyOpenGL and Pillow packages are installed:\n'
65
+ 'Do `pip3 install --user "wirepod_vector_sdk[3dviewer]"` to install. Error: %s' % opengl_import_exc)
66
+
67
+
68
+ try:
69
+ from OpenGL.GL import (GL_AMBIENT, GL_AMBIENT_AND_DIFFUSE, GL_CCW, GL_COLOR_BUFFER_BIT, GL_COMPILE, GL_DEPTH_BUFFER_BIT, GL_DEPTH_TEST, GL_DIFFUSE,
70
+ GL_FRONT, GL_LIGHT0, GL_LINEAR, GL_MODELVIEW, GL_POLYGON, GL_PROJECTION, GL_POSITION, GL_RGBA, GL_SHININESS, GL_SMOOTH, GL_SPECULAR,
71
+ GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_TEXTURE_MAG_FILTER, GL_UNSIGNED_BYTE,
72
+ glBegin, glBindTexture, glCallList, glClear, glClearColor, glColor, glDisable, glEnable,
73
+ glEnd, glEndList, glFrontFace, glGenLists, glGenTextures, glLoadIdentity, glLightfv, glMaterialfv, glMatrixMode, glNewList,
74
+ glNormal3fv, glScalef, glShadeModel, glTexCoord2fv, glTexImage2D, glTexParameteri,
75
+ glTexSubImage2D, glVertex3fv, glViewport)
76
+ from OpenGL.GLU import gluLookAt, gluPerspective
77
+ from OpenGL.GLUT import (glutCreateWindow, glutDisplayFunc, glutIdleFunc, glutInit, glutInitDisplayMode,
78
+ glutInitWindowPosition, glutInitWindowSize, glutPostRedisplay, glutReshapeFunc,
79
+ glutSetWindow, glutSwapBuffers, glutVisibilityFunc,
80
+ GLUT_DEPTH, GLUT_DOUBLE, GLUT_RGB, GLUT_VISIBLE)
81
+ from OpenGL.error import NullFunctionError
82
+
83
+ from PIL import Image
84
+
85
+ except ImportError as import_exc:
86
+ raise_opengl_or_pillow_import_error(import_exc)
87
+
88
+
89
+ # Check if OpenGL imported correctly and bound to a valid GLUT implementation
90
+
91
+
92
+ def _glut_install_instructions():
93
+ if sys.platform.startswith('linux'):
94
+ return "Install freeglut: `sudo apt-get install freeglut3`"
95
+ if sys.platform.startswith('darwin'):
96
+ return "GLUT should already be installed by default on macOS!"
97
+ if sys.platform in ('win32', 'cygwin'):
98
+ return "Install freeglut: You can download it from http://freeglut.sourceforge.net/ \n"\
99
+ "You just need the `freeglut.dll` file, from any of the 'Windows binaries' downloads. "\
100
+ "Place the DLL next to your Python script, or install it somewhere in your PATH "\
101
+ "to allow any script to use it."
102
+ return "(Instructions unknown for platform %s)" % sys.platform
103
+
104
+
105
+ def _verify_glut_init():
106
+ # According to the documentation, just checking bool(glutInit) is supposed to be enough
107
+ # However on Windows with no GLUT DLL that can still pass, even if calling the method throws a null function error.
108
+ if bool(glutInit):
109
+ try:
110
+ glutInit()
111
+ return True
112
+ except NullFunctionError as _:
113
+ pass
114
+
115
+ return False
116
+
117
+
118
+ if not _verify_glut_init():
119
+ raise InvalidOpenGLGlutImplementation(_glut_install_instructions())
120
+
121
+
122
+ class ResourceManager():
123
+ """Handles returning file resources by keys. The current implementation delegates to resource_stream
124
+ directly.
125
+
126
+ :param context_id: Key used for identifying this context
127
+ """
128
+
129
+ def __init__(self, context_id: str):
130
+ self._context_id = context_id
131
+
132
+ @property
133
+ def context_id(self) -> str:
134
+ """Key used for identifying this context."""
135
+ return self._context_id
136
+
137
+ def load(self, *args: str):
138
+ """Loads a resource given a groups of key arguments.
139
+
140
+ Since the resource_stream path is non_stantard with os.path.join, this resolve is encapsulated inside
141
+ the resource manager. The context that these resources are files on disk is similarly encapsulated.
142
+ All client classes only need match keys with returned data.
143
+
144
+ :param args: string keys for identifying the asset.
145
+ """
146
+ resource_path = '/'.join(map(str, args)) # Note: Deliberately not os.path.join, for use with pkg_resources
147
+ return resource_stream(self._context_id, resource_path)
148
+
149
+
150
+ class DynamicTexture:
151
+ """Wrapper around An OpenGL Texture that can be dynamically updated."""
152
+
153
+ def __init__(self):
154
+ self._texId = glGenTextures(1)
155
+ self._width = None
156
+ self._height = None
157
+ # Bind an ID for this texture
158
+ glBindTexture(GL_TEXTURE_2D, self._texId)
159
+ # Use bilinear filtering if the texture has to be scaled
160
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
161
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
162
+
163
+ def bind(self):
164
+ """Bind the texture for rendering."""
165
+ glBindTexture(GL_TEXTURE_2D, self._texId)
166
+
167
+ def update(self, pil_image: Image.Image):
168
+ """Update the texture to contain the provided image.
169
+
170
+ :param pil_image: The image to write into the texture.
171
+ """
172
+ # Ensure the image is in RGBA format and convert to the raw RGBA bytes.
173
+ image_width, image_height = pil_image.size
174
+ image = pil_image.convert("RGBA").tobytes("raw", "RGBA")
175
+
176
+ # Bind the texture so that it can be modified.
177
+ self.bind()
178
+ if (self._width == image_width) and (self._height == image_height):
179
+ # Same size - just need to update the texels.
180
+ glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, image_width, image_height,
181
+ GL_RGBA, GL_UNSIGNED_BYTE, image)
182
+ else:
183
+ # Different size than the last frame (e.g. the Window is resizing)
184
+ # Create a new texture of the correct size.
185
+ glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image_width, image_height,
186
+ 0, GL_RGBA, GL_UNSIGNED_BYTE, image)
187
+
188
+ self._width = image_width
189
+ self._height = image_height
190
+
191
+
192
+ class MaterialLibrary(): # pylint: disable=too-few-public-methods
193
+ """Load a .mtl material asset, and return the contents as a dictionary.
194
+
195
+ Supports the subset of MTL required for the Vector 3D Viewer assets.
196
+
197
+ :param resource_manager: Manager to load resources from.
198
+ :param asset_key: The key of the asset to load.
199
+ """
200
+
201
+ def __init__(self, resource_context: ResourceManager, asset_key: str):
202
+ self._contents = {}
203
+ current_mtl: dict = None
204
+
205
+ file_data = resource_context.load('assets', asset_key)
206
+
207
+ for line in file_data:
208
+ line = line.decode("utf-8") # Convert bytes line to a string
209
+ if line.startswith('#'):
210
+ # Ignore comments in the file.
211
+ continue
212
+
213
+ values = line.split()
214
+ if not values:
215
+ # Ignore empty lines.
216
+ continue
217
+
218
+ attribute_name = values[0]
219
+ if attribute_name == 'newmtl':
220
+ # Create a new empty material.
221
+ current_mtl = self._contents[values[1]] = {}
222
+ elif current_mtl is None:
223
+ raise ValueError("mtl file must start with newmtl statement")
224
+ elif attribute_name == 'map_Kd':
225
+ # Diffuse texture map - load the image into memory.
226
+ image_name = values[1]
227
+ image_file_data = resource_context.load('assets', image_name)
228
+ with Image.open(image_file_data) as image:
229
+ image_width, image_height = image.size
230
+ image = image.convert("RGBA").tobytes("raw", "RGBA")
231
+
232
+ # Bind the image as a texture that can be used for rendering.
233
+ texture_id = glGenTextures(1)
234
+ current_mtl['texture_Kd'] = texture_id # pylint: disable=unsupported-assignment-operation
235
+
236
+ glBindTexture(GL_TEXTURE_2D, texture_id)
237
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
238
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
239
+ glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image_width, image_height,
240
+ 0, GL_RGBA, GL_UNSIGNED_BYTE, image)
241
+ else:
242
+ # Store the values for this attribute as a list of float values.
243
+ current_mtl[attribute_name] = list(map(float, values[1:])) # pylint: disable=unsupported-assignment-operation
244
+
245
+ def get_material_by_name(self, name: str) -> dict:
246
+ """Returns a dict of material attributes"""
247
+ return self._contents[name]
248
+
249
+
250
+ class MeshFace():
251
+ """A face polygon in 3d space - the basic building block of 3D models.
252
+
253
+ The actual coordinate data is stored in tables on the host mesh, the face contains
254
+ indexes to those table denoting which values should be used in rendering.
255
+
256
+ :param position_ids: Worldspace position ids on the host mesh for this face's vertices.
257
+ :param normal_ids: Normal direction ids on the host mesh for this face's vertices.
258
+ :param tex_ids: Texture coordinate ids on the host mesh for this face's vertices.
259
+ :param active_material: Material name used to render this face.
260
+ """
261
+
262
+ def __init__(self, position_ids: List[int], normal_ids: List[int], tex_ids: List[int], active_material: str):
263
+ self._position_ids = position_ids
264
+ self._normal_ids = normal_ids
265
+ self._tex_ids = tex_ids
266
+
267
+ self._vertex_count = len(position_ids)
268
+
269
+ self._material = active_material
270
+
271
+ @property
272
+ def position_ids(self) -> List[int]:
273
+ """Worldspace position ids on the host mesh for this face's vertices."""
274
+ return self._position_ids
275
+
276
+ @property
277
+ def normal_ids(self) -> List[int]:
278
+ """Normal direction ids on the host mesh for this face's vertices."""
279
+ return self._normal_ids
280
+
281
+ @property
282
+ def tex_ids(self) -> List[int]:
283
+ """Texture coordinate ids on the host mesh for this face's vertices."""
284
+ return self._tex_ids
285
+
286
+ @property
287
+ def material(self) -> str:
288
+ """Material name used to render this face."""
289
+ return self._material
290
+
291
+ @property
292
+ def vertex_count(self) -> int:
293
+ """The number of vertices on this face - will be either 3 for a triangle, or 4 for a quad"""
294
+ return self._vertex_count
295
+
296
+
297
+ class MeshGroup():
298
+ """A colletions of face polygons which can be rendered as a group by name.
299
+
300
+ :param name: The name associated with this part of the 3d mesh collection.
301
+ """
302
+
303
+ def __init__(self, name: str):
304
+ self._name = name
305
+ self._faces: List(MeshFace) = []
306
+
307
+ @property
308
+ def name(self) -> str:
309
+ """The name associated with the mesh group."""
310
+ return self._name
311
+
312
+ @property
313
+ def faces(self) -> List[MeshFace]:
314
+ """All faces associated with the mesh group."""
315
+ return self._faces
316
+
317
+ def add_face_by_obj_data(self, source_values: list, active_material: str):
318
+ """Adds a new face to the mesh group.
319
+
320
+ Face source data is made up of 3 or 4 vertices
321
+ - e.g. `f v1 v2 v3` or `f v1 v2 v3 v4`
322
+
323
+ where each vertex definition is multiple indexes seperated by
324
+ slashes and can follow the following formats:
325
+
326
+ position_index
327
+ position_index/tex_coord_index
328
+ position_index/tex_coord_index/normal_index
329
+ position_index//normal_index
330
+
331
+ :param source_values: obj data to parse for this face
332
+ :param active_material: the material used to render this face
333
+ """
334
+
335
+ position_ids: List(int) = []
336
+ normal_ids: List(int) = []
337
+ tex_ids: List(int) = []
338
+
339
+ for vertex in source_values:
340
+ vertex_components = vertex.split('/')
341
+
342
+ position_ids.append(int(vertex_components[0]))
343
+
344
+ # There's only a texture coordinate if there's at least 2 entries and the 2nd entry is non-zero length
345
+ if len(vertex_components) >= 2 and vertex_components[1]:
346
+ tex_ids.append(int(vertex_components[1]))
347
+ else:
348
+ # OBJ file indexing starts at 1, so use 0 to indicate no entry
349
+ tex_ids.append(0)
350
+
351
+ # There's only a normal if there's at least 2 entries and the 2nd entry is non-zero length
352
+ if len(vertex_components) >= 3 and vertex_components[2]:
353
+ normal_ids.append(int(vertex_components[2]))
354
+ else:
355
+ # OBJ file indexing starts at 1, so use 0 to indicate no entry
356
+ normal_ids.append(0)
357
+
358
+ self._faces.append(MeshFace(position_ids, normal_ids, tex_ids, active_material))
359
+
360
+
361
+ class MeshData():
362
+ """The loaded / parsed contents of a 3D Wavefront OBJ file.
363
+
364
+ This is the intermediary step between the file on the disk, and a renderable
365
+ 3D object. It supports the subset of the OBJ file that was used in the
366
+ Vector and Cube assets, and does not attempt to exhaustively support every
367
+ possible setting.
368
+
369
+ :param resource_manager: The resource manager to load this mesh from.
370
+ :param asset_key: The key of the OBJ file to load from the resource manager.
371
+ """
372
+
373
+ def __init__(self, resource_manager: ResourceManager, asset_key: str):
374
+
375
+ # All worldspace vertex positions in this mesh (coordinates stored as list of 3 floats).
376
+ self._vertices: List[List[float]] = []
377
+ # All directional vertex normals in this mesh (coordinates stored as list of 3 floats).
378
+ self._normals: List[List[float]] = []
379
+ # All texture coordinates in this mesh (coordinates stored as list of 2 floats).
380
+ self._tex_coords: List[List[float]] = []
381
+
382
+ # All supported mesh groups, indexed by group name.
383
+ self._groups: Dict[str, MeshGroup] = {}
384
+
385
+ # A container that MTL material attribute dicts can be fetched from by string key.
386
+ self._material_library: MaterialLibrary = None
387
+
388
+ # Resource manager that can be used to load internally referenced assets
389
+ self._resource_manager = resource_manager
390
+
391
+ self._logger = util.get_class_logger(__name__, self)
392
+
393
+ self.load_from_obj_asset(asset_key)
394
+
395
+ @property
396
+ def vertices(self) -> List[List[float]]:
397
+ """All worldspace vertex positions in this mesh."""
398
+ return self._vertices
399
+
400
+ @property
401
+ def normals(self) -> List[List[float]]:
402
+ """All directional vertex normals in this mesh."""
403
+ return self._normals
404
+
405
+ @property
406
+ def tex_coords(self) -> List[List[float]]:
407
+ """All texture coordinates in this mesh."""
408
+ return self._tex_coords
409
+
410
+ @property
411
+ def groups(self) -> Dict[str, MeshGroup]:
412
+ """All supported mesh groups, indexed by group name."""
413
+ return self._groups
414
+
415
+ @property
416
+ def material_library(self) -> MaterialLibrary:
417
+ """A container that MTL material attribute dicts can be fetched from by string key."""
418
+ return self._material_library
419
+
420
+ def load_from_obj_asset(self, asset_key: str): # pylint: disable=too-many-branches
421
+ """Loads all mesh data from a specified resource.
422
+
423
+ :param asset_key: Key for the desired OBJ asset in the resource_manager.
424
+ """
425
+ active_group_name: str = None
426
+ active_material: str = None
427
+
428
+ file_data = self._resource_manager.load('assets', asset_key)
429
+
430
+ for data_entry in file_data:
431
+
432
+ line = data_entry.decode("utf-8") # Convert bytes to string
433
+ if line.startswith('#'):
434
+ # ignore comments in the file
435
+ continue
436
+
437
+ values = line.split()
438
+ if not values:
439
+ # ignore empty lines
440
+ continue
441
+
442
+ if values[0] == 'v':
443
+ # vertex position
444
+ v = list(map(float, values[1:4]))
445
+ self._vertices.append(v)
446
+ elif values[0] == 'vn':
447
+ # vertex normal
448
+ v = list(map(float, values[1:4]))
449
+ self._normals.append(v)
450
+ elif values[0] == 'vt':
451
+ # texture coordinate
452
+ v = list(map(float, values[1:3]))
453
+ self._tex_coords.append(v)
454
+ elif values[0] in ('usemtl', 'usemat'):
455
+ # material
456
+ active_material = values[1]
457
+ elif values[0] == 'mtllib':
458
+ # material library (a filename)
459
+ self._material_library = MaterialLibrary(self._resource_manager, values[1])
460
+ elif values[0] == 'f':
461
+ if active_group_name not in self._groups:
462
+ self._groups[active_group_name] = MeshGroup(active_group_name)
463
+
464
+ group = self._groups[active_group_name]
465
+ group.add_face_by_obj_data(values[1:], active_material)
466
+
467
+ elif values[0] == 'o':
468
+ # object name - ignore
469
+ continue
470
+ elif values[0] == 'g':
471
+ # group name (for a sub-mesh)
472
+ active_group_name = values[1]
473
+ elif values[0] == 's':
474
+ # smooth shading (1..20, and 'off') - ignore
475
+ continue
476
+ else:
477
+ self._logger.warning("LoadedObjFile Ignoring unhandled type '%s' in line %s",
478
+ values[0], values)
479
+
480
+
481
+ class PrecomputedView():
482
+ """A collection of static 3D object which are pre-computed on the graphics card, so they can
483
+ be quickly drawn when needed."""
484
+
485
+ def __init__(self):
486
+ self._display_lists = {}
487
+
488
+ @staticmethod
489
+ def _apply_material(material: dict):
490
+ """Utility function to apply a specific MTL material to the current
491
+ OpenGL rendering state.
492
+
493
+ :param material: A dictionary of MTL attributes defining a material.
494
+ """
495
+ def _as_rgba(color):
496
+ if len(color) >= 4:
497
+ return color
498
+ # RGB - add alpha defaulted to 1
499
+ return color + [1.0]
500
+
501
+ if 'texture_Kd' in material:
502
+ # use diffuse texture map
503
+ glBindTexture(GL_TEXTURE_2D, material['texture_Kd'])
504
+ else:
505
+ # No texture map
506
+ glBindTexture(GL_TEXTURE_2D, 0)
507
+
508
+ # Diffuse light
509
+ mtl_kd_rgba = _as_rgba(material['Kd'])
510
+ glColor(mtl_kd_rgba)
511
+
512
+ # Ambient light
513
+ if 'Ka' in material:
514
+ mtl_ka_rgba = _as_rgba(material['Ka'])
515
+ glMaterialfv(GL_FRONT, GL_AMBIENT, mtl_ka_rgba)
516
+ glMaterialfv(GL_FRONT, GL_DIFFUSE, mtl_kd_rgba)
517
+ else:
518
+ glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, mtl_kd_rgba)
519
+
520
+ # Specular light
521
+ if 'Ks' in material:
522
+ mtl_ks_rgba = _as_rgba(material['Ks'])
523
+ glMaterialfv(GL_FRONT, GL_SPECULAR, mtl_ks_rgba)
524
+ if 'Ns' in material:
525
+ specular_exponent = material['Ns']
526
+ glMaterialfv(GL_FRONT, GL_SHININESS, specular_exponent)
527
+
528
+ def build_from_mesh_data(self, mesh_data: MeshData):
529
+ """Uses a loaded mesh to create 3d geometry to store in the view.
530
+
531
+ All groups in the mesh will pre-computed and stored by name.
532
+
533
+ :param mesh_data: the source data that 3d geometry will be pre-computed from.
534
+ """
535
+ material_library = mesh_data.material_library
536
+
537
+ for key in mesh_data.groups:
538
+ new_gl_list = glGenLists(1) # pylint: disable=assignment-from-no-return
539
+ glNewList(new_gl_list, GL_COMPILE)
540
+
541
+ group = mesh_data.groups[key]
542
+
543
+ glEnable(GL_TEXTURE_2D)
544
+ glFrontFace(GL_CCW)
545
+
546
+ for face in group.faces:
547
+ self._apply_material(material_library.get_material_by_name(face.material))
548
+
549
+ # Polygon (N verts) with optional normals and tex coords
550
+ glBegin(GL_POLYGON)
551
+ for i in range(face.vertex_count):
552
+ normal_index = face.normal_ids[i]
553
+ if normal_index > 0:
554
+ glNormal3fv(mesh_data.normals[normal_index - 1])
555
+ tex_coord_index = face.tex_ids[i]
556
+ if tex_coord_index > 0:
557
+ glTexCoord2fv(mesh_data.tex_coords[tex_coord_index - 1])
558
+ glVertex3fv(mesh_data.vertices[face.position_ids[i] - 1])
559
+ glEnd()
560
+
561
+ glDisable(GL_TEXTURE_2D)
562
+ glEndList()
563
+
564
+ self._display_lists[key] = new_gl_list
565
+
566
+ def build_from_render_function(self, name: str, f: callable, *args):
567
+ """Uses an externally provided function to create 3d geometry to store in the view.
568
+
569
+ :param name: the key this pre-computed geometry can be draw from.
570
+ :param f: the function used to create the 3d geometry.
571
+ :param args: any parameters the supplied function is expecting.
572
+ """
573
+ new_gl_list = glGenLists(1) # pylint: disable=assignment-from-no-return
574
+ glNewList(new_gl_list, GL_COMPILE)
575
+ f(*args)
576
+ glEndList()
577
+
578
+ self._display_lists[name] = new_gl_list
579
+
580
+ def display_by_key(self, key: str):
581
+ """Renders a specific piece of geometry from the view collection.
582
+
583
+ :param key: The pre-computed object to render.
584
+ """
585
+ try:
586
+ glCallList(self._display_lists[key])
587
+ except KeyError:
588
+ raise KeyError('No display list with key {0} present on PrerenderedView'.format(key))
589
+
590
+ def display_all(self):
591
+ """Renders all pre-computed geometry in the view collection."""
592
+ for display_list in self._display_lists.values():
593
+ glCallList(display_list)
594
+
595
+
596
+ class Camera():
597
+ """Class containing the state of a 3d camera, used to transform all object in a scene with
598
+ relation to a particular point of view.
599
+
600
+ This class is meant to be mutated at run time.
601
+
602
+ :param look_at: The initial target of the camera.
603
+ :param up: The initial up vector of the camera.
604
+ :param distance: The initial distance between the camera and it's target.
605
+ :param pitch: The camera's current rotation about its X axis
606
+ :param yaw: The camera's current rotation about its up axis
607
+ """
608
+
609
+ def __init__(self, look_at: util.Vector3, up: util.Vector3, distance: float, pitch: float, yaw: float):
610
+ # Camera position and orientation defined by a look-at positions
611
+ # and a pitch/and yaw to rotate around that along with a distance
612
+ self._look_at = look_at
613
+ self._pitch = pitch
614
+ self._yaw = yaw
615
+ self._distance = distance
616
+ self._pos = util.Vector3(0, 0, 0)
617
+ self._up = up
618
+ self._update_pos()
619
+
620
+ @property
621
+ def look_at(self) -> util.Vector3:
622
+ """The target position of the camera"""
623
+ return self._look_at
624
+
625
+ @look_at.setter
626
+ def look_at(self, look_at):
627
+ self._look_at = look_at
628
+
629
+ def move(self, forward_amount: float = 0.0, right_amount: float = 0.0, up_amount: float = 0.0):
630
+ """Offsets the camera's position incrementally.
631
+
632
+ :param forward_amount: distance to move along the camera's current forward heading.
633
+ :param right_amount: distance to move along a right angle to the camera's current forward heading.
634
+ :param up_amount: distance to move along the camera's up vector.
635
+ """
636
+ self._look_at += self._up * up_amount
637
+
638
+ # Move forward/back and left/right
639
+ pitch = self._pitch
640
+ yaw = self._yaw
641
+ camera_offset = util.Vector3(math.cos(yaw), math.sin(yaw), math.sin(pitch))
642
+
643
+ heading = math.atan2(camera_offset.y, camera_offset.x)
644
+ half_pi = math.pi * 0.5
645
+
646
+ self._look_at += util.Vector3(
647
+ right_amount * math.cos(heading + half_pi),
648
+ right_amount * math.sin(heading + half_pi),
649
+ 0.0)
650
+
651
+ self._look_at += util.Vector3(
652
+ forward_amount * math.cos(heading),
653
+ forward_amount * math.sin(heading),
654
+ 0.0)
655
+
656
+ def zoom(self, amount: float):
657
+ """Moves the camera closer or further from it's target point.
658
+
659
+ :param amount: distance to zoom in or out, automatically minimized at 0.1
660
+ """
661
+ self._distance = max(0.1, self._distance + amount)
662
+
663
+ def turn(self, yaw_delta: float, pitch_delta: float):
664
+ """Incrementally turns the camera.
665
+
666
+ :param yaw_delta: Amount to rotate around the camera's up axis.
667
+ :param pitch_delta: Amount to rotate around the camera's X axis. This is automatically capped between +/- pi/2
668
+ """
669
+ # Adjust the Camera pitch and yaw
670
+ self._pitch = (self._pitch - pitch_delta)
671
+ self._yaw = (self._yaw + yaw_delta) % (2.0 * math.pi)
672
+
673
+ # Clamp pitch to slightyly less than pi/2 to avoid lock/errors at full up/down
674
+ max_rotation = math.pi * 0.49
675
+ self._pitch = max(-max_rotation, min(max_rotation, self._pitch))
676
+
677
+ def _update_pos(self):
678
+ """Calculate camera position based on look-at, distance and angles."""
679
+ cos_pitch = math.cos(self._pitch)
680
+ sin_pitch = math.sin(self._pitch)
681
+ cos_yaw = math.cos(self._yaw)
682
+ sin_yaw = math.sin(self._yaw)
683
+ cam_distance = self._distance
684
+ cam_look_at = self._look_at
685
+
686
+ self._pos = util.Vector3(
687
+ cam_look_at.x + (cam_distance * cos_pitch * cos_yaw),
688
+ cam_look_at.y + (cam_distance * cos_pitch * sin_yaw),
689
+ cam_look_at.z + (cam_distance * sin_pitch))
690
+
691
+ def apply(self):
692
+ """Applies the transform this camera represents to the active OpenGL context."""
693
+ self._update_pos()
694
+
695
+ gluLookAt(*self._pos.x_y_z,
696
+ *self._look_at.x_y_z,
697
+ *self._up.x_y_z)
698
+
699
+
700
+ class Projector(): # pylint: disable=too-few-public-methods
701
+ """Configuration for how 3d objects are projected onto the 2d window.
702
+
703
+ :param fov: (Field of View) The viewing angle in degrees between the center of the window, and the top/bottom.
704
+ :param near_clip_plane: The minimum distance from the camera at which geometry can be rendered.
705
+ :param far_clip_plane: The maximum distance from the camera at which geometry can be rendered.
706
+ """
707
+
708
+ def __init__(self, fov: float, near_clip_plane: float, far_clip_plane: float):
709
+ self._fov = fov
710
+ self._near_clip_plane = near_clip_plane
711
+ self._far_clip_plane = far_clip_plane
712
+
713
+ def apply(self, window):
714
+ """Applies the transform this projection represents to the active OpenGL context."""
715
+
716
+ # Set up the projection matrix
717
+ glMatrixMode(GL_PROJECTION)
718
+ glLoadIdentity()
719
+ fov = self._fov
720
+ aspect_ratio = window.width / window.height
721
+ near_clip_plane = self._near_clip_plane
722
+ far_clip_plane = self._far_clip_plane
723
+ gluPerspective(fov, aspect_ratio, near_clip_plane, far_clip_plane)
724
+
725
+ # Switch to model matrix for rendering everything
726
+ glMatrixMode(GL_MODELVIEW)
727
+ glLoadIdentity()
728
+
729
+
730
+ class Light(): # pylint: disable=too-few-public-methods
731
+ """Configuration for a light in the OpenGL scene that effects the shading of 3d geometry.
732
+
733
+ :param ambient_color: Color applied to all geometry in the scene regardless of their relation to the light.
734
+ :param diffuse_color: Color applied to geometry in the scene which is facing the light.
735
+ :param specular_color: Color applied to geometry that is facing signficantly enough toward the light (depending on it's material's shininess).
736
+ :param position: The location of the light (or direction vector in the case of direction lights).
737
+ :param is_directional: Flag that sets the light to shine globally from a specified direction rather than an origin point (i.e. Sun light).
738
+ """
739
+
740
+ def __init__(self, ambient_color: List[float], diffuse_color: List[float], specular_color: List[float], position: util.Vector3, is_directional: bool = False):
741
+ self._ambient_color = ambient_color
742
+ self._diffuse_color = diffuse_color
743
+ self._specular_color = specular_color
744
+ # w coordinate of '1' indicates a positional light in OpenGL, while '0' would indicate a directional light
745
+ self._position_coords = [position.x, position.y, position.z, 0 if is_directional else 1]
746
+
747
+ def apply(self, index: int):
748
+ """Applies this light to the active OpenGL context.
749
+
750
+ :param index: the internal OpenGL light index to apply this class's data to.
751
+ """
752
+ opengl_index = GL_LIGHT0 + index
753
+ glLightfv(opengl_index, GL_AMBIENT, self._ambient_color)
754
+ glLightfv(opengl_index, GL_DIFFUSE, self._diffuse_color)
755
+ glLightfv(opengl_index, GL_SPECULAR, self._specular_color)
756
+ glLightfv(opengl_index, GL_POSITION, self._position_coords)
757
+ glEnable(opengl_index)
758
+
759
+
760
+ class OpenGLWindow():
761
+ """A Window displaying an OpenGL viewport.
762
+
763
+ :param x: The initial x coordinate of the window in pixels.
764
+ :param y: The initial y coordinate of the window in pixels.
765
+ :param width: The initial height of the window in pixels.
766
+ :param height: The initial height of the window in pixels.
767
+ :param window_name: The name / title for the window.
768
+ """
769
+
770
+ def __init__(self, x: int, y: int, width: int, height: int, window_name: str):
771
+ self._pos = (x, y)
772
+ #: int: The width of the window
773
+ self._width = width
774
+ #: int: The height of the window
775
+ self._height = height
776
+ self._gl_window = None
777
+ self._window_name = window_name
778
+
779
+ @property
780
+ def width(self):
781
+ """The horizontal width of the window"""
782
+ return self._width
783
+
784
+ @property
785
+ def height(self):
786
+ """The vertical height of the window:"""
787
+ return self._height
788
+
789
+ def initialize(self, display_function: callable):
790
+ """Initialze the OpenGL display parts of the Window.
791
+
792
+ Warning:
793
+ Must be called on the same thread as OpenGL (usually the main thread),
794
+ """
795
+
796
+ glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH)
797
+
798
+ glutInitWindowSize(self.width, self.height)
799
+ glutInitWindowPosition(*self._pos)
800
+ self._gl_window = glutCreateWindow(self._window_name)
801
+
802
+ glClearColor(0, 0, 0, 0)
803
+ glEnable(GL_DEPTH_TEST)
804
+ glShadeModel(GL_SMOOTH)
805
+
806
+ glutIdleFunc(self._idle)
807
+ glutVisibilityFunc(self._visible)
808
+ glutReshapeFunc(self._reshape)
809
+
810
+ glutDisplayFunc(display_function)
811
+
812
+ def prepare_for_rendering(self, projector: Projector, camera: Camera, lights: List[Light]):
813
+ """Selects the window, clears buffers, and sets up the scene transform and lighting state.
814
+
815
+ :param projector: The projector configuration to use for this rendering pass.
816
+ :param camera: The camera object to use for this rendering pass.
817
+ :param lights: The light list to use for this rendering pass.
818
+ """
819
+ glutSetWindow(self._gl_window)
820
+
821
+ # Clear the screen and the depth buffer
822
+ glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
823
+
824
+ # Apply our projection so the window is ready to render in perspective
825
+ projector.apply(self)
826
+
827
+ # Add scene lights
828
+ light_count = len(lights)
829
+ for i in range(light_count):
830
+ lights[i].apply(i)
831
+
832
+ # Set scale from mm to cm
833
+ glScalef(0.1, 0.1, 0.1)
834
+
835
+ # Orient the camera
836
+ camera.apply()
837
+
838
+ @staticmethod
839
+ def display_rendered_content():
840
+ """Swaps buffers once rendering is finished.
841
+ """
842
+ glutSwapBuffers()
843
+
844
+ def _idle(self): # pylint: disable=no-self-use
845
+ """Called from OpenGL when idle."""
846
+ glutPostRedisplay()
847
+
848
+ def _visible(self, vis):
849
+ """Called from OpenGL when visibility changes (windows are either visible
850
+ or completely invisible/hidden)."""
851
+ if vis == GLUT_VISIBLE:
852
+ glutIdleFunc(self._idle)
853
+ else:
854
+ glutIdleFunc(None)
855
+
856
+ def _reshape(self, width: int, height: int):
857
+ """Called from OpenGL whenever this window is resized.
858
+
859
+ :param width: the new width of the window in pixels.
860
+ :param height: the new height of the window in pixels.
861
+ """
862
+ self._width = width
863
+ self._height = height
864
+ glViewport(0, 0, width, height)