-
Notifications
You must be signed in to change notification settings - Fork 270
/
render_source.py
1588 lines (1265 loc) · 50.5 KB
/
render_source.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import abc
import warnings
from functools import wraps
from types import ModuleType
from typing import Literal, Optional, Union
import numpy as np
from yt.config import ytcfg
from yt.data_objects.image_array import ImageArray
from yt.funcs import ensure_numpy_array, is_sequence, mylog
from yt.geometry.grid_geometry_handler import GridIndex
from yt.geometry.oct_geometry_handler import OctreeIndex
from yt.utilities.amr_kdtree.api import AMRKDTree
from yt.utilities.configure import YTConfig, configuration_callbacks
from yt.utilities.lib.bounding_volume_hierarchy import BVH
from yt.utilities.lib.misc_utilities import zlines, zpoints
from yt.utilities.lib.octree_raytracing import OctreeRayTracing
from yt.utilities.lib.partitioned_grid import PartitionedGrid
from yt.utilities.on_demand_imports import NotAModule
from yt.utilities.parallel_tools.parallel_analysis_interface import (
ParallelAnalysisInterface,
)
from yt.visualization.image_writer import apply_colormap
from .transfer_function_helper import TransferFunctionHelper
from .transfer_functions import (
ColorTransferFunction,
ProjectionTransferFunction,
TransferFunction,
)
from .utils import (
data_source_or_all,
get_corners,
new_interpolated_projection_sampler,
new_mesh_sampler,
new_projection_sampler,
new_volume_render_sampler,
)
from .zbuffer_array import ZBuffer
OptionalModule = Union[ModuleType, NotAModule]
mesh_traversal: OptionalModule = NotAModule("pyembree")
mesh_construction: OptionalModule = NotAModule("pyembree")
def set_raytracing_engine(
engine: Literal["yt", "embree"],
) -> None:
"""
Safely switch raytracing engines at runtime.
Parameters
----------
engine: 'yt' or 'embree'
- 'yt' selects the default engine.
- 'embree' requires extra installation steps, see
https://yt-project.org/doc/visualizing/unstructured_mesh_rendering.html?highlight=pyembree#optional-embree-installation
Raises
------
UserWarning
Raised if the required engine is not available.
In this case, the default engine is restored.
"""
from yt.config import ytcfg
global mesh_traversal, mesh_construction
if engine == "embree":
try:
from yt.utilities.lib.embree_mesh import ( # type: ignore
mesh_construction,
mesh_traversal,
)
except (ImportError, ValueError) as exc:
# Catch ValueError in case size of objects in Cython change
warnings.warn(
"Failed to switch to embree raytracing engine. "
f"The following error was raised:\n{exc}",
stacklevel=2,
)
mesh_traversal = NotAModule("pyembree")
mesh_construction = NotAModule("pyembree")
ytcfg["yt", "ray_tracing_engine"] = "yt"
else:
ytcfg["yt", "ray_tracing_engine"] = "embree"
else:
mesh_traversal = NotAModule("pyembree")
mesh_construction = NotAModule("pyembree")
ytcfg["yt", "ray_tracing_engine"] = "yt"
def _init_raytracing_engine(ytcfg: YTConfig) -> None:
# validate option from configuration file or fall back to default engine
set_raytracing_engine(engine=ytcfg["yt", "ray_tracing_engine"])
configuration_callbacks.append(_init_raytracing_engine)
def invalidate_volume(f):
@wraps(f)
def wrapper(*args, **kwargs):
ret = f(*args, **kwargs)
obj = args[0]
if isinstance(obj._transfer_function, ProjectionTransferFunction):
obj.sampler_type = "projection"
obj._log_field = False
obj._use_ghost_zones = False
del obj.volume
obj._volume_valid = False
return ret
return wrapper
def validate_volume(f):
@wraps(f)
def wrapper(*args, **kwargs):
obj = args[0]
fields = [obj.field]
log_fields = [obj.log_field]
if obj.weight_field is not None:
fields.append(obj.weight_field)
log_fields.append(obj.log_field)
if not obj._volume_valid:
obj.volume.set_fields(
fields, log_fields, no_ghost=(not obj.use_ghost_zones)
)
obj._volume_valid = True
return f(*args, **kwargs)
return wrapper
class RenderSource(ParallelAnalysisInterface, abc.ABC):
"""Base Class for Render Sources.
Will be inherited for volumes, streamlines, etc.
"""
volume_method: Optional[str] = None
def __init__(self):
super().__init__()
self.opaque = False
self.zbuffer = None
@abc.abstractmethod
def render(self, camera, zbuffer=None):
pass
@abc.abstractmethod
def _validate(self):
pass
class OpaqueSource(RenderSource):
"""A base class for opaque render sources.
Will be inherited from for LineSources, BoxSources, etc.
"""
def __init__(self):
super().__init__()
self.opaque = True
def set_zbuffer(self, zbuffer):
self.zbuffer = zbuffer
def create_volume_source(data_source, field):
data_source = data_source_or_all(data_source)
ds = data_source.ds
index_class = ds.index.__class__
if issubclass(index_class, GridIndex):
return KDTreeVolumeSource(data_source, field)
elif issubclass(index_class, OctreeIndex):
return OctreeVolumeSource(data_source, field)
else:
raise NotImplementedError
class VolumeSource(RenderSource, abc.ABC):
"""A class for rendering data from a volumetric data source
Examples of such sources include a sphere, cylinder, or the
entire computational domain.
A :class:`VolumeSource` provides the framework to decompose an arbitrary
yt data source into bricks that can be traversed and volume rendered.
Parameters
----------
data_source: :class:`AMR3DData` or :class:`Dataset`, optional
This is the source to be rendered, which can be any arbitrary yt
data object or dataset.
field : string
The name of the field to be rendered.
Examples
--------
The easiest way to make a VolumeSource is to use the volume_render
function, so that the VolumeSource gets created automatically. This
example shows how to do this and then access the resulting source:
>>> import yt
>>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030")
>>> im, sc = yt.volume_render(ds)
>>> volume_source = sc.get_source(0)
You can also create VolumeSource instances by hand and add them to Scenes.
This example manually creates a VolumeSource, adds it to a scene, sets the
camera, and renders an image.
>>> import yt
>>> from yt.visualization.volume_rendering.api import (
... Camera, Scene, create_volume_source)
>>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030")
>>> sc = Scene()
>>> source = create_volume_source(ds.all_data(), "density")
>>> sc.add_source(source)
>>> sc.add_camera()
>>> im = sc.render()
"""
_image = None
data_source = None
def __init__(self, data_source, field):
r"""Initialize a new volumetric source for rendering."""
super().__init__()
self.data_source = data_source_or_all(data_source)
field = self.data_source._determine_fields(field)[0]
self.current_image = None
self.check_nans = False
self.num_threads = 0
self.num_samples = 10
self.sampler_type = "volume-render"
self._volume_valid = False
# these are caches for properties, defined below
self._volume = None
self._transfer_function = None
self._field = field
self._log_field = self.data_source.ds.field_info[field].take_log
self._use_ghost_zones = False
self._weight_field = None
self.tfh = TransferFunctionHelper(self.data_source.pf)
self.tfh.set_field(self.field)
@property
def transfer_function(self):
"""The transfer function associated with this VolumeSource"""
if self._transfer_function is not None:
return self._transfer_function
if self.tfh.tf is not None:
self._transfer_function = self.tfh.tf
return self._transfer_function
mylog.info("Creating transfer function")
self.tfh.set_field(self.field)
self.tfh.set_log(self.log_field)
self.tfh.build_transfer_function()
self.tfh.setup_default()
self._transfer_function = self.tfh.tf
return self._transfer_function
@transfer_function.setter
def transfer_function(self, value):
self.tfh.tf = None
valid_types = (
TransferFunction,
ColorTransferFunction,
ProjectionTransferFunction,
type(None),
)
if not isinstance(value, valid_types):
raise RuntimeError(
"transfer_function not a valid type, "
"received object of type %s" % type(value)
)
if isinstance(value, ProjectionTransferFunction):
self.sampler_type = "projection"
if self._volume is not None:
fields = [self.field]
if self.weight_field is not None:
fields.append(self.weight_field)
self._volume_valid = False
self._transfer_function = value
@property
def volume(self):
"""The abstract volume associated with this VolumeSource
This object does the heavy lifting to access data in an efficient manner
using a KDTree
"""
return self._get_volume()
@volume.setter
def volume(self, value):
assert isinstance(value, AMRKDTree)
del self._volume
self._field = value.fields
self._log_field = value.log_fields
self._volume = value
assert self._volume_valid
@volume.deleter
def volume(self):
del self._volume
self._volume = None
@property
def field(self):
"""The field to be rendered"""
return self._field
@field.setter
@invalidate_volume
def field(self, value):
field = self.data_source._determine_fields(value)
if len(field) > 1:
raise RuntimeError(
"VolumeSource.field can only be a single field but received "
"multiple fields: %s"
) % field
field = field[0]
if self._field != field:
log_field = self.data_source.ds.field_info[field].take_log
self.tfh.bounds = None
else:
log_field = self._log_field
self._log_field = log_field
self._field = value
self.transfer_function = None
self.tfh.set_field(value)
self.tfh.set_log(log_field)
@property
def log_field(self):
"""Whether or not the field rendering is computed in log space"""
return self._log_field
@log_field.setter
@invalidate_volume
def log_field(self, value):
self.transfer_function = None
self.tfh.set_log(value)
self._log_field = value
@property
def use_ghost_zones(self):
"""Whether or not ghost zones are used to estimate vertex-centered data
values at grid boundaries"""
return self._use_ghost_zones
@use_ghost_zones.setter
@invalidate_volume
def use_ghost_zones(self, value):
self._use_ghost_zones = value
@property
def weight_field(self):
"""The weight field for the rendering
Currently this is only used for off-axis projections.
"""
return self._weight_field
@weight_field.setter
@invalidate_volume
def weight_field(self, value):
self._weight_field = value
def set_transfer_function(self, transfer_function):
"""Set transfer function for this source"""
self.transfer_function = transfer_function
return self
def _validate(self):
"""Make sure that all dependencies have been met"""
if self.data_source is None:
raise RuntimeError("Data source not initialized")
def set_volume(self, volume):
"""Associates an AMRKDTree with the VolumeSource"""
self.volume = volume
return self
def set_field(self, field):
"""Set the source's field to render
Parameters
----------
field: field name
The field to render
"""
self.field = field
return self
def set_log(self, log_field):
"""Set whether the rendering of the source's field is done in log space
Generally volume renderings of data whose values span a large dynamic
range should be done on log space and volume renderings of data with
small dynamic range should be done in linear space.
Parameters
----------
log_field: boolean
If True, the volume rendering will be done in log space, and if False
will be done in linear space.
"""
self.log_field = log_field
return self
def set_weight_field(self, weight_field):
"""Set the source's weight field
.. note::
This is currently only used for renderings using the
ProjectionTransferFunction
Parameters
----------
weight_field: field name
The weight field to use in the rendering
"""
self.weight_field = weight_field
return self
def set_use_ghost_zones(self, use_ghost_zones):
"""Set whether or not interpolation at grid edges uses ghost zones
Parameters
----------
use_ghost_zones: boolean
If True, the AMRKDTree estimates vertex centered data using ghost
zones, which can eliminate seams in the resulting volume rendering.
Defaults to False for performance reasons.
"""
self.use_ghost_zones = use_ghost_zones
return self
def set_sampler(self, camera, interpolated=True):
"""Sets a volume render sampler
The type of sampler is determined based on the ``sampler_type`` attribute
of the VolumeSource. Currently the ``volume_render`` and ``projection``
sampler types are supported.
The 'interpolated' argument is only meaningful for projections. If True,
the data is first interpolated to the cell vertices, and then
tri-linearly interpolated to the ray sampling positions. If False, then
the cell-centered data is simply accumulated along the
ray. Interpolation is always performed for volume renderings.
"""
if self.sampler_type == "volume-render":
sampler = new_volume_render_sampler(camera, self)
elif self.sampler_type == "projection" and interpolated:
sampler = new_interpolated_projection_sampler(camera, self)
elif self.sampler_type == "projection":
sampler = new_projection_sampler(camera, self)
else:
NotImplementedError(f"{self.sampler_type} not implemented yet")
self.sampler = sampler
assert self.sampler is not None
@abc.abstractmethod
def _get_volume(self):
"""The abstract volume associated with this VolumeSource
This object does the heavy lifting to access data in an efficient manner
using a KDTree
"""
pass
@abc.abstractmethod
@validate_volume
def render(self, camera, zbuffer=None):
"""Renders an image using the provided camera
Parameters
----------
camera: :class:`yt.visualization.volume_rendering.camera.Camera` instance
A volume rendering camera. Can be any type of camera.
zbuffer: :class:`yt.visualization.volume_rendering.zbuffer_array.Zbuffer` instance # noqa: E501
A zbuffer array. This is used for opaque sources to determine the
z position of the source relative to other sources. Only useful if
you are manually calling render on multiple sources. Scene.render
uses this internally.
Returns
-------
A :class:`yt.data_objects.image_array.ImageArray` instance containing
the rendered image.
"""
pass
def finalize_image(self, camera, image):
"""Parallel reduce the image.
Parameters
----------
camera: :class:`yt.visualization.volume_rendering.camera.Camera` instance
The camera used to produce the volume rendering image.
image: :class:`yt.data_objects.image_array.ImageArray` instance
A reference to an image to fill
"""
image.shape = camera.resolution[0], camera.resolution[1], 4
# If the call is from VR, the image is rotated by 180 to get correct
# up direction
if not self.transfer_function.grey_opacity:
image[:, :, 3] = 1
return image
def __repr__(self):
disp = f"<Volume Source>:{str(self.data_source)} "
disp += f"transfer_function:{str(self._transfer_function)}"
return disp
class KDTreeVolumeSource(VolumeSource):
volume_method = "KDTree"
def _get_volume(self):
"""The abstract volume associated with this VolumeSource
This object does the heavy lifting to access data in an efficient manner
using a KDTree
"""
if self._volume is None:
mylog.info("Creating volume")
volume = AMRKDTree(self.data_source.ds, data_source=self.data_source)
self._volume = volume
return self._volume
@validate_volume
def render(self, camera, zbuffer=None):
"""Renders an image using the provided camera
Parameters
----------
camera: :class:`yt.visualization.volume_rendering.camera.Camera`
A volume rendering camera. Can be any type of camera.
zbuffer: :class:`yt.visualization.volume_rendering.zbuffer_array.Zbuffer`
A zbuffer array. This is used for opaque sources to determine the
z position of the source relative to other sources. Only useful if
you are manually calling render on multiple sources. Scene.render
uses this internally.
Returns
-------
A :class:`yt.data_objects.image_array.ImageArray` containing
the rendered image.
"""
self.zbuffer = zbuffer
self.set_sampler(camera)
assert self.sampler is not None
mylog.debug("Casting rays")
total_cells = 0
if self.check_nans:
for brick in self.volume.bricks:
for data in brick.my_data:
if np.any(np.isnan(data)):
raise RuntimeError
for brick in self.volume.traverse(camera.lens.viewpoint):
mylog.debug("Using sampler %s", self.sampler)
self.sampler(brick, num_threads=self.num_threads)
total_cells += np.prod(brick.my_data[0].shape)
mylog.debug("Done casting rays")
self.current_image = self.finalize_image(camera, self.sampler.aimage)
if zbuffer is None:
self.zbuffer = ZBuffer(
self.current_image, np.full(self.current_image.shape[:2], np.inf)
)
return self.current_image
def finalize_image(self, camera, image):
if self._volume is not None:
image = self.volume.reduce_tree_images(image, camera.lens.viewpoint)
return super().finalize_image(camera, image)
class OctreeVolumeSource(VolumeSource):
volume_method = "Octree"
def __init__(self, *args, **kwa):
super().__init__(*args, **kwa)
self.set_use_ghost_zones(True)
def _get_volume(self):
"""The abstract volume associated with this VolumeSource
This object does the heavy lifting to access data in an efficient manner
using an octree.
"""
if self._volume is None:
mylog.info("Creating volume")
volume = OctreeRayTracing(self.data_source)
self._volume = volume
return self._volume
@validate_volume
def render(self, camera, zbuffer=None):
"""Renders an image using the provided camera
Parameters
----------
camera: :class:`yt.visualization.volume_rendering.camera.Camera` instance
A volume rendering camera. Can be any type of camera.
zbuffer: :class:`yt.visualization.volume_rendering.zbuffer_array.Zbuffer` instance # noqa: E501
A zbuffer array. This is used for opaque sources to determine the
z position of the source relative to other sources. Only useful if
you are manually calling render on multiple sources. Scene.render
uses this internally.
Returns
-------
A :class:`yt.data_objects.image_array.ImageArray` instance containing
the rendered image.
"""
self.zbuffer = zbuffer
self.set_sampler(camera)
if self.sampler is None:
raise RuntimeError(
"No sampler set. This is likely a bug as it should never happen."
)
data = self.data_source
dx = data["dx"].to_value("unitary")[:, None]
xyz = np.stack([data[_].to_value("unitary") for _ in "xyz"], axis=-1)
LE = xyz - dx / 2
RE = xyz + dx / 2
mylog.debug("Gathering data")
dt = np.stack(list(self.volume.data) + [*LE.T, *RE.T], axis=-1).reshape(
1, len(dx), 14, 1
)
mask = np.full(dt.shape[1:], 1, dtype=np.uint8)
dims = np.array([1, 1, 1], dtype="int64")
pg = PartitionedGrid(0, dt, mask, LE.flatten(), RE.flatten(), dims, n_fields=1)
mylog.debug("Casting rays")
self.sampler(pg, oct=self.volume.octree)
mylog.debug("Done casting rays")
self.current_image = self.finalize_image(camera, self.sampler.aimage)
if zbuffer is None:
self.zbuffer = ZBuffer(
self.current_image, np.full(self.current_image.shape[:2], np.inf)
)
return self.current_image
class MeshSource(OpaqueSource):
"""A source for unstructured mesh data.
This functionality requires the embree ray-tracing engine and the
associated pyembree python bindings to be installed in order to
function.
A :class:`MeshSource` provides the framework to volume render
unstructured mesh data.
Parameters
----------
data_source: :class:`AMR3DData` or :class:`Dataset`, optional
This is the source to be rendered, which can be any arbitrary yt
data object or dataset.
field : string
The name of the field to be rendered.
Examples
--------
>>> source = MeshSource(ds, ("connect1", "convected"))
"""
_image = None
data_source = None
def __init__(self, data_source, field):
r"""Initialize a new unstructured mesh source for rendering."""
super().__init__()
self.data_source = data_source_or_all(data_source)
field = self.data_source._determine_fields(field)[0]
self.field = field
self.volume = None
self.current_image = None
self.engine = ytcfg.get("yt", "ray_tracing_engine")
# default color map
self._cmap = ytcfg.get("yt", "default_colormap")
self._color_bounds = None
# default mesh annotation options
self._annotate_mesh = False
self._mesh_line_color = None
self._mesh_line_alpha = 1.0
# Error checking
assert self.field is not None
assert self.data_source is not None
if self.field[0] == "all":
raise NotImplementedError(
"Mesh unions are not implemented for 3D rendering"
)
if self.engine == "embree":
self.volume = mesh_traversal.YTEmbreeScene()
self.build_volume_embree()
elif self.engine == "yt":
self.build_volume_bvh()
else:
raise NotImplementedError(
"Invalid ray-tracing engine selected. Choices are 'embree' and 'yt'."
)
@property
def cmap(self):
"""
This is the name of the colormap that will be used when rendering
this MeshSource object. Should be a string, like 'cmyt.arbre', or 'cmyt.dusk'.
"""
return self._cmap
@cmap.setter
def cmap(self, cmap_name):
self._cmap = cmap_name
if hasattr(self, "data"):
self.current_image = self.apply_colormap()
@property
def color_bounds(self):
"""
These are the bounds that will be used with the colormap to the display
the rendered image. Should be a (vmin, vmax) tuple, like (0.0, 2.0). If
None, the bounds will be automatically inferred from the max and min of
the rendered data.
"""
return self._color_bounds
@color_bounds.setter
def color_bounds(self, bounds):
self._color_bounds = bounds
if hasattr(self, "data"):
self.current_image = self.apply_colormap()
def _validate(self):
"""Make sure that all dependencies have been met"""
if self.data_source is None:
raise RuntimeError("Data source not initialized.")
if self.volume is None:
raise RuntimeError("Volume not initialized.")
def build_volume_embree(self):
"""
This constructs the mesh that will be ray-traced by pyembree.
"""
ftype, fname = self.field
mesh_id = int(ftype[-1]) - 1
index = self.data_source.ds.index
offset = index.meshes[mesh_id]._index_offset
field_data = self.data_source[self.field].d # strip units
vertices = index.meshes[mesh_id].connectivity_coords
indices = index.meshes[mesh_id].connectivity_indices - offset
# if this is an element field, promote to 2D here
if len(field_data.shape) == 1:
field_data = np.expand_dims(field_data, 1)
# Here, we decide whether to render based on high-order or
# low-order geometry. Right now, high-order geometry is only
# implemented for 20-point hexes.
if indices.shape[1] == 20 or indices.shape[1] == 10:
self.mesh = mesh_construction.QuadraticElementMesh(
self.volume, vertices, indices, field_data
)
else:
# if this is another type of higher-order element, we demote
# to 1st order here, for now.
if indices.shape[1] == 27:
# hexahedral
mylog.warning("27-node hexes not yet supported, dropping to 1st order.")
field_data = field_data[:, 0:8]
indices = indices[:, 0:8]
self.mesh = mesh_construction.LinearElementMesh(
self.volume, vertices, indices, field_data
)
def build_volume_bvh(self):
"""
This constructs the mesh that will be ray-traced.
"""
ftype, fname = self.field
mesh_id = int(ftype[-1]) - 1
index = self.data_source.ds.index
offset = index.meshes[mesh_id]._index_offset
field_data = self.data_source[self.field].d # strip units
vertices = index.meshes[mesh_id].connectivity_coords
indices = index.meshes[mesh_id].connectivity_indices - offset
# if this is an element field, promote to 2D here
if len(field_data.shape) == 1:
field_data = np.expand_dims(field_data, 1)
# Here, we decide whether to render based on high-order or
# low-order geometry.
if indices.shape[1] == 27:
# hexahedral
mylog.warning("27-node hexes not yet supported, dropping to 1st order.")
field_data = field_data[:, 0:8]
indices = indices[:, 0:8]
self.volume = BVH(vertices, indices, field_data)
def render(self, camera, zbuffer=None):
"""Renders an image using the provided camera
Parameters
----------
camera: :class:`yt.visualization.volume_rendering.camera.Camera`
A volume rendering camera. Can be any type of camera.
zbuffer: :class:`yt.visualization.volume_rendering.zbuffer_array.Zbuffer`
A zbuffer array. This is used for opaque sources to determine the
z position of the source relative to other sources. Only useful if
you are manually calling render on multiple sources. Scene.render
uses this internally.
Returns
-------
A :class:`yt.data_objects.image_array.ImageArray` containing
the rendered image.
"""
shape = (camera.resolution[0], camera.resolution[1], 4)
if zbuffer is None:
empty = np.empty(shape, dtype="float64")
z = np.empty(empty.shape[:2], dtype="float64")
empty[:] = 0.0
z[:] = np.inf
zbuffer = ZBuffer(empty, z)
elif zbuffer.rgba.shape != shape:
zbuffer = ZBuffer(zbuffer.rgba.reshape(shape), zbuffer.z.reshape(shape[:2]))
self.zbuffer = zbuffer
self.sampler = new_mesh_sampler(camera, self, engine=self.engine)
mylog.debug("Casting rays")
self.sampler(self.volume)
mylog.debug("Done casting rays")
self.finalize_image(camera)
self.current_image = self.apply_colormap()
zbuffer += ZBuffer(self.current_image.astype("float64"), self.sampler.azbuffer)
zbuffer.rgba = ImageArray(zbuffer.rgba)
self.zbuffer = zbuffer
self.current_image = self.zbuffer.rgba
if self._annotate_mesh:
self.current_image = self.annotate_mesh_lines(
self._mesh_line_color, self._mesh_line_alpha
)
return self.current_image
def finalize_image(self, camera):
sam = self.sampler
# reshape data
Nx = camera.resolution[0]
Ny = camera.resolution[1]
self.data = sam.aimage[:, :, 0].reshape(Nx, Ny)
def annotate_mesh_lines(self, color=None, alpha=1.0):
r"""
Modifies this MeshSource by drawing the mesh lines.
This modifies the current image by drawing the element
boundaries and returns the modified image.
Parameters
----------
color: array_like of shape (4,), optional
The RGBA value to use to draw the mesh lines.
Default is black.
alpha : float, optional
The opacity of the mesh lines. Default is 255 (solid).
"""
self.annotate_mesh = True
self._mesh_line_color = color
self._mesh_line_alpha = alpha
if color is None:
color = np.array([0, 0, 0, alpha])
locs = (self.sampler.amesh_lines == 1,)
self.current_image[:, :, 0][locs] = color[0]
self.current_image[:, :, 1][locs] = color[1]
self.current_image[:, :, 2][locs] = color[2]
self.current_image[:, :, 3][locs] = color[3]
return self.current_image
def apply_colormap(self):
"""
Applies a colormap to the current image without re-rendering.
Returns
-------
current_image : A new image with the specified color scale applied to
the underlying data.
"""
image = (
apply_colormap(
self.data, color_bounds=self._color_bounds, cmap_name=self._cmap
)
/ 255.0
)
alpha = image[:, :, 3]
alpha[self.sampler.aimage_used == -1] = 0.0
image[:, :, 3] = alpha
return image
def __repr__(self):
disp = f"<Mesh Source>:{str(self.data_source)} "
return disp
class PointSource(OpaqueSource):
r"""A rendering source of opaque points in the scene.
This class provides a mechanism for adding points to a scene; these
points will be opaque, and can also be colored.
Parameters
----------
positions: array_like of shape (N, 3)
The positions of points to be added to the scene. If specified with no
units, the positions will be assumed to be in code units.
colors : array_like of shape (N, 4), optional
The colors of the points, including an alpha channel, in floating
point running from 0..1.
color_stride : int, optional
The stride with which to access the colors when putting them on the