• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

openmc-dev / openmc / 29123958173

10 Jul 2026 09:12PM UTC coverage: 80.472% (-0.8%) from 81.292%
29123958173

Pull #3951

github

web-flow
Merge 62dca9136 into 7256d5046
Pull Request #3951: wwinp files: Fix MemoryError in WeightWindowsList.export_to_hdf5 and speed up from_wwinp. Alternative Approach

16757 of 24275 branches covered (69.03%)

Branch coverage included in aggregate %.

70 of 138 new or added lines in 10 files covered. (50.72%)

876 existing lines in 50 files now uncovered.

57507 of 68010 relevant lines covered (84.56%)

23274270.93 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

69.63
/src/plot.cpp
1
#include "openmc/plot.h"
2

3
#include <algorithm>
4
#define _USE_MATH_DEFINES // to make M_PI declared in Intel and MSVC compilers
5
#include <cmath>
6
#include <cstdio>
7
#include <fstream>
8
#include <sstream>
9

10
#include "openmc/tensor.h"
11
#include <fmt/core.h>
12
#include <fmt/ostream.h>
13
#ifdef USE_LIBPNG
14
#include <png.h>
15
#endif
16

17
#include "openmc/cell.h"
18
#include "openmc/constants.h"
19
#include "openmc/container_util.h"
20
#include "openmc/dagmc.h"
21
#include "openmc/error.h"
22
#include "openmc/file_utils.h"
23
#include "openmc/geometry.h"
24
#include "openmc/hdf5_interface.h"
25
#include "openmc/material.h"
26
#include "openmc/mesh.h"
27
#include "openmc/message_passing.h"
28
#include "openmc/openmp_interface.h"
29
#include "openmc/output.h"
30
#include "openmc/particle.h"
31
#include "openmc/progress_bar.h"
32
#include "openmc/random_lcg.h"
33
#include "openmc/settings.h"
34
#include "openmc/simulation.h"
35
#include "openmc/string_utils.h"
36
#include "openmc/tallies/filter.h"
37

38
namespace openmc {
39

40
//==============================================================================
41
// Constants
42
//==============================================================================
43

44
constexpr int PLOT_LEVEL_LOWEST {-1}; //!< lower bound on plot universe level
45
constexpr int32_t NOT_FOUND {-2};
46
constexpr int32_t OVERLAP {-3};
47

48
IdData::IdData(size_t h_res, size_t v_res, bool /*include_filter*/)
1,329✔
49
  : data_({v_res, h_res, 3}, NOT_FOUND)
1,329✔
50
{}
1,329✔
51

52
void IdData::set_value(size_t y, size_t x, const Particle& p, int level,
9,655,416✔
53
  Filter* /*filter*/, FilterMatch* /*match*/)
54
{
55
  // set cell data
56
  if (p.n_coord() <= level) {
9,655,416!
57
    data_(y, x, 0) = NOT_FOUND;
×
58
    data_(y, x, 1) = NOT_FOUND;
×
59
  } else {
60
    data_(y, x, 0) = model::cells.at(p.coord(level).cell())->id_;
9,655,416!
61
    data_(y, x, 1) = level == p.n_coord() - 1
9,655,416✔
62
                       ? p.cell_instance()
9,655,416!
63
                       : cell_instance_at_level(p, level);
×
64
  }
65

66
  // set material data
67
  Cell* c = model::cells.at(p.lowest_coord().cell()).get();
9,655,416✔
68
  if (p.material() == MATERIAL_VOID) {
9,655,416✔
69
    data_(y, x, 2) = MATERIAL_VOID;
7,445,928✔
70
  } else if (c->type_ == Fill::MATERIAL) {
2,209,488!
71
    Material* m = model::materials.at(p.material()).get();
2,209,488✔
72
    data_(y, x, 2) = m->id_;
2,209,488✔
73
  }
74
}
9,655,416✔
75

76
void IdData::set_overlap(size_t y, size_t x, int /*overlap_idx*/)
7,704✔
77
{
78
  for (size_t k = 0; k < data_.shape(2); ++k)
61,632!
79
    data_(y, x, k) = OVERLAP;
23,112✔
80
}
7,704✔
81

82
PropertyData::PropertyData(size_t h_res, size_t v_res, bool /*include_filter*/)
×
83
  : data_({v_res, h_res, 2}, NOT_FOUND)
×
84
{}
×
85

86
void PropertyData::set_value(size_t y, size_t x, const Particle& p, int level,
×
87
  Filter* /*filter*/, FilterMatch* /*match*/)
88
{
89
  Cell* c = model::cells.at(p.lowest_coord().cell()).get();
×
90
  data_(y, x, 0) = (p.sqrtkT() * p.sqrtkT()) / K_BOLTZMANN;
×
91
  data_(y, x, 1) = c->density(p.cell_instance());
×
92
}
×
93

94
void PropertyData::set_overlap(size_t y, size_t x, int /*overlap_idx*/)
×
95
{
96
  data_(y, x) = OVERLAP;
×
97
}
×
98

99
//==============================================================================
100
// RasterData implementation
101
//==============================================================================
102

103
RasterData::RasterData(size_t h_res, size_t v_res, bool include_filter)
117✔
104
  : id_data_({v_res, h_res, include_filter ? 4u : 3u}, NOT_FOUND),
228✔
105
    property_data_({v_res, h_res, 2}, static_cast<double>(NOT_FOUND)),
117✔
106
    include_filter_(include_filter)
117✔
107
{}
117✔
108

109
void RasterData::set_value(size_t y, size_t x, const Particle& p, int level,
991,725✔
110
  Filter* filter, FilterMatch* match)
111
{
112
  // set cell data
113
  if (p.n_coord() <= level) {
991,725!
114
    id_data_(y, x, 0) = NOT_FOUND;
×
115
    id_data_(y, x, 1) = NOT_FOUND;
×
116
  } else {
117
    id_data_(y, x, 0) = model::cells.at(p.coord(level).cell())->id_;
991,725!
118
    id_data_(y, x, 1) = level == p.n_coord() - 1
991,725✔
119
                          ? p.cell_instance()
991,725!
120
                          : cell_instance_at_level(p, level);
×
121
  }
122

123
  // set material data
124
  Cell* c = model::cells.at(p.lowest_coord().cell()).get();
991,725✔
125
  if (p.material() == MATERIAL_VOID) {
991,725✔
126
    id_data_(y, x, 2) = MATERIAL_VOID;
672,300✔
127
  } else if (c->type_ == Fill::MATERIAL) {
319,425!
128
    Material* m = model::materials.at(p.material()).get();
319,425✔
129
    id_data_(y, x, 2) = m->id_;
319,425✔
130
  }
131

132
  // set filter index (only if filter is being used)
133
  if (include_filter_ && filter) {
991,725!
134
    filter->get_all_bins(p, TallyEstimator::COLLISION, *match);
15,000✔
135
    if (match->bins_.empty()) {
15,000!
136
      id_data_(y, x, 3) = -1;
×
137
    } else {
138
      id_data_(y, x, 3) = match->bins_[0];
15,000✔
139
    }
140
    match->bins_.clear();
15,000!
141
    match->weights_.clear();
15,000!
142
  }
143

144
  // set temperature (in K)
145
  property_data_(y, x, 0) = (p.sqrtkT() * p.sqrtkT()) / K_BOLTZMANN;
991,725✔
146

147
  // set density (g/cm³)
148
  if (c->type_ != Fill::UNIVERSE && p.material() != MATERIAL_VOID) {
991,725!
149
    Material* m = model::materials.at(p.material()).get();
319,425✔
150
    property_data_(y, x, 1) = c->density(p.cell_instance());
319,425✔
151
  }
152
}
991,725✔
153

154
void RasterData::set_overlap(size_t y, size_t x, int overlap_idx)
99,756✔
155
{
156
  // Set cell, instance, and material to OVERLAP, but preserve filter bin for
157
  // tally plotting. Cell encodes the overlap index as a negative number so that
158
  // it can be used to look up overlap information in the plotter.
159
  id_data_(y, x, 0) = OVERLAP - overlap_idx - 1;
99,756✔
160
  id_data_(y, x, 1) = OVERLAP;
99,756✔
161
  id_data_(y, x, 2) = OVERLAP;
99,756✔
162

163
  property_data_(y, x, 0) = OVERLAP;
99,756✔
164
  property_data_(y, x, 1) = OVERLAP;
99,756✔
165
}
99,756✔
166

167
//==============================================================================
168
// Global variables
169
//==============================================================================
170

171
namespace model {
172

173
std::unordered_map<int, int> plot_map;
174
vector<std::unique_ptr<PlottableInterface>> plots;
175
uint64_t plotter_seed = 1;
176

177
} // namespace model
178

179
//==============================================================================
180
// RUN_PLOT controls the logic for making one or many plots
181
//==============================================================================
182

183
extern "C" int openmc_plot_geometry()
33✔
184
{
185

186
  for (auto& pl : model::plots) {
111✔
187
    write_message(5, "Processing plot {}: {}...", pl->id(), pl->path_plot());
78✔
188
    pl->create_output();
78✔
189
  }
190

191
  return 0;
33✔
192
}
193

194
void PlottableInterface::write_image(const ImageData& data) const
63✔
195
{
196
#ifdef USE_LIBPNG
197
  output_png(path_plot(), data);
63✔
198
#else
199
  output_ppm(path_plot(), data);
200
#endif
201
}
63✔
202

203
void Plot::create_output() const
54✔
204
{
205
  if (PlotType::slice == type_) {
54✔
206
    // create 2D image
207
    ImageData image = create_image();
39✔
208
    write_image(image);
39✔
209
  } else if (PlotType::voxel == type_) {
54!
210
    // create voxel file for 3D viewing
211
    create_voxel();
15✔
212
  }
213
}
54✔
214

215
void Plot::print_info() const
42✔
216
{
217
  // Plot type
218
  if (PlotType::slice == type_) {
42✔
219
    fmt::print("Plot Type: Slice\n");
33✔
220
  } else if (PlotType::voxel == type_) {
9!
221
    fmt::print("Plot Type: Voxel\n");
9✔
222
  }
223

224
  // Plot parameters
225
  fmt::print("Origin: {} {} {}\n", origin_[0], origin_[1], origin_[2]);
42✔
226

227
  if (PlotType::slice == type_) {
42✔
228
    fmt::print("Width: {:4} {:4}\n", width_[0], width_[1]);
33✔
229
  } else if (PlotType::voxel == type_) {
9!
230
    fmt::print("Width: {:4} {:4} {:4}\n", width_[0], width_[1], width_[2]);
9✔
231
  }
232

233
  if (PlotColorBy::cells == color_by_) {
42✔
234
    fmt::print("Coloring: Cells\n");
24✔
235
  } else if (PlotColorBy::mats == color_by_) {
18!
236
    fmt::print("Coloring: Materials\n");
18✔
237
  }
238

239
  if (PlotType::slice == type_) {
42✔
240
    switch (basis_) {
33!
241
    case PlotBasis::xy:
21✔
242
      fmt::print("Basis: XY\n");
21✔
243
      break;
21✔
244
    case PlotBasis::xz:
6✔
245
      fmt::print("Basis: XZ\n");
6✔
246
      break;
6✔
247
    case PlotBasis::yz:
6✔
248
      fmt::print("Basis: YZ\n");
6✔
249
      break;
6✔
250
    }
251
    fmt::print("Pixels: {} {}\n", pixels()[0], pixels()[1]);
33✔
252
  } else if (PlotType::voxel == type_) {
9!
253
    fmt::print("Voxels: {} {} {}\n", pixels()[0], pixels()[1], pixels()[2]);
9✔
254
  }
255
}
42✔
256

257
void read_plots_xml()
327✔
258
{
259
  // Check if plots.xml exists; this is only necessary when the plot runmode is
260
  // initiated. Otherwise, we want to read plots.xml because it may be called
261
  // later via the API. In that case, its ok for a plots.xml to not exist
262
  std::string filename = settings::path_input + "plots.xml";
327✔
263
  if (!file_exists(filename) && settings::run_mode == RunMode::PLOTTING) {
327!
264
    fatal_error(fmt::format("Plots XML file '{}' does not exist!", filename));
×
265
  }
266

267
  write_message("Reading plot XML file...", 5);
327✔
268

269
  // Parse plots.xml file
270
  pugi::xml_document doc;
327✔
271
  doc.load_file(filename.c_str());
327✔
272

273
  pugi::xml_node root = doc.document_element();
327✔
274

275
  read_plots_xml(root);
327✔
276
}
327✔
277

278
void read_plots_xml(pugi::xml_node root)
459✔
279
{
280
  for (auto node : root.children("plot")) {
717✔
281
    std::string plot_desc = "<auto>";
261✔
282
    if (check_for_node(node, "id")) {
261!
283
      plot_desc = get_node_value(node, "id", true);
261✔
284
    }
285

286
    if (check_for_node(node, "type")) {
261!
287
      std::string type_str = get_node_value(node, "type", true);
261✔
288
      if (type_str == "slice") {
261✔
289
        model::plots.emplace_back(
219✔
290
          std::make_unique<Plot>(node, Plot::PlotType::slice));
441✔
291
      } else if (type_str == "voxel") {
39✔
292
        model::plots.emplace_back(
15✔
293
          std::make_unique<Plot>(node, Plot::PlotType::voxel));
30✔
294
      } else if (type_str == "wireframe_raytrace") {
24✔
295
        model::plots.emplace_back(
15✔
296
          std::make_unique<WireframeRayTracePlot>(node));
30✔
297
      } else if (type_str == "solid_raytrace") {
9!
298
        model::plots.emplace_back(std::make_unique<SolidRayTracePlot>(node));
9✔
299
      } else {
300
        fatal_error(fmt::format(
×
301
          "Unsupported plot type '{}' in plot {}", type_str, plot_desc));
302
      }
303
      model::plot_map[model::plots.back()->id()] = model::plots.size() - 1;
258✔
304
    } else {
258✔
305
      fatal_error(fmt::format("Must specify plot type in plot {}", plot_desc));
×
306
    }
307
  }
258✔
308
}
456✔
309

310
void free_memory_plot()
2,166✔
311
{
312
  model::plots.clear();
2,166✔
313
  model::plot_map.clear();
2,166✔
314
}
2,166✔
315

316
// creates an image based on user input from a plots.xml <plot>
317
// specification in the PNG/PPM format
318
ImageData Plot::create_image() const
39✔
319
{
320
  size_t width = pixels()[0];
39✔
321
  size_t height = pixels()[1];
39✔
322

323
  ImageData data({width, height}, not_found_);
39✔
324

325
  // generate ids for the plot
326
  auto ids = get_map<IdData>();
39✔
327

328
  // assign colors
329
  for (size_t y = 0; y < height; y++) {
8,199✔
330
    for (size_t x = 0; x < width; x++) {
2,078,760✔
331
      int idx = color_by_ == PlotColorBy::cells ? 0 : 2;
2,070,600✔
332
      auto id = ids.data_(y, x, idx);
2,070,600✔
333
      // no setting needed if not found
334
      if (id == NOT_FOUND) {
2,070,600✔
335
        continue;
295,236✔
336
      }
337
      if (id == OVERLAP) {
1,783,068✔
338
        data(x, y) = overlap_color_;
7,704✔
339
        continue;
7,704✔
340
      }
341
      if (PlotColorBy::cells == color_by_) {
1,775,364✔
342
        data(x, y) = colors_[model::cell_map[id]];
821,364✔
343
      } else if (PlotColorBy::mats == color_by_) {
954,000!
344
        if (id == MATERIAL_VOID) {
954,000!
345
          data(x, y) = WHITE;
×
346
          continue;
×
347
        }
348
        data(x, y) = colors_[model::material_map[id]];
954,000✔
349
      } // color_by if-else
350
    }
351
  }
352

353
  // draw mesh lines if present
354
  if (index_meshlines_mesh_ >= 0) {
39✔
355
    draw_mesh_lines(data);
9✔
356
  }
357

358
  return data;
39✔
359
}
39✔
360

361
void PlottableInterface::set_id(pugi::xml_node plot_node)
261✔
362
{
363
  int id {C_NONE};
261✔
364
  if (check_for_node(plot_node, "id")) {
261!
365
    id = std::stoi(get_node_value(plot_node, "id"));
261✔
366
  }
367

368
  try {
261✔
369
    set_id(id);
261✔
370
  } catch (const std::runtime_error& e) {
×
371
    fatal_error(e.what());
×
372
  }
×
373
}
261✔
374

375
void PlottableInterface::set_id(int id)
264✔
376
{
377
  if (id < 0 && id != C_NONE) {
264!
378
    throw std::runtime_error {fmt::format("Invalid plot ID: {}", id)};
×
379
  }
380

381
  if (id == C_NONE) {
264✔
382
    id = 1;
3✔
383
    for (const auto& p : model::plots) {
6✔
384
      id = std::max(id, p->id() + 1);
6!
385
    }
386
  }
387

388
  if (id_ == id)
264!
389
    return;
390

391
  // Check to make sure this ID doesn't already exist
392
  if (model::plot_map.find(id) != model::plot_map.end()) {
264!
393
    throw std::runtime_error {
×
394
      fmt::format("Two or more plots use the same unique ID: {}", id)};
×
395
  }
396

397
  id_ = id;
264✔
398
}
399

400
// Checks if png or ppm is already present
401
bool file_extension_present(
258✔
402
  const std::string& filename, const std::string& extension)
403
{
404
  std::string file_extension_if_present =
258✔
405
    filename.substr(filename.find_last_of(".") + 1);
258✔
406
  if (file_extension_if_present == extension)
258✔
407
    return true;
15✔
408
  return false;
409
}
258✔
410

411
void Plot::set_output_path(pugi::xml_node plot_node)
237✔
412
{
413
  // Set output file path
414
  std::string filename;
237✔
415

416
  if (check_for_node(plot_node, "filename")) {
237✔
417
    filename = get_node_value(plot_node, "filename");
60✔
418
  } else {
419
    filename = fmt::format("plot_{}", id());
177✔
420
  }
421
  const std::string dir_if_present =
237✔
422
    filename.substr(0, filename.find_last_of("/") + 1);
237✔
423
  if (dir_if_present.size() > 0 && !dir_exists(dir_if_present)) {
237✔
424
    fatal_error(fmt::format("Directory '{}' does not exist!", dir_if_present));
3✔
425
  }
426
  // add appropriate file extension to name
427
  switch (type_) {
234!
428
  case PlotType::slice:
219✔
429
#ifdef USE_LIBPNG
430
    if (!file_extension_present(filename, "png"))
219!
431
      filename.append(".png");
219✔
432
#else
433
    if (!file_extension_present(filename, "ppm"))
434
      filename.append(".ppm");
435
#endif
436
    break;
437
  case PlotType::voxel:
15✔
438
    if (!file_extension_present(filename, "h5"))
15!
439
      filename.append(".h5");
15✔
440
    break;
441
  }
442

443
  path_plot_ = filename;
234✔
444

445
  // Copy plot pixel size
446
  vector<int> pxls = get_node_array<int>(plot_node, "pixels");
468✔
447
  if (PlotType::slice == type_) {
234✔
448
    if (pxls.size() == 2) {
219!
449
      pixels()[0] = pxls[0];
219✔
450
      pixels()[1] = pxls[1];
219✔
451
    } else {
452
      fatal_error(
×
453
        fmt::format("<pixels> must be length 2 in slice plot {}", id()));
×
454
    }
455
  } else if (PlotType::voxel == type_) {
15!
456
    if (pxls.size() == 3) {
15!
457
      pixels()[0] = pxls[0];
15✔
458
      pixels()[1] = pxls[1];
15✔
459
      pixels()[2] = pxls[2];
15✔
460
    } else {
461
      fatal_error(
×
462
        fmt::format("<pixels> must be length 3 in voxel plot {}", id()));
×
463
    }
464
  }
465
}
234✔
466

467
void PlottableInterface::set_bg_color(pugi::xml_node plot_node)
261✔
468
{
469
  // Copy plot background color
470
  if (check_for_node(plot_node, "background")) {
261✔
471
    vector<int> bg_rgb = get_node_array<int>(plot_node, "background");
12✔
472
    if (bg_rgb.size() == 3) {
12!
473
      not_found_ = bg_rgb;
12✔
474
    } else {
475
      fatal_error(fmt::format("Bad background RGB in plot {}", id()));
×
476
    }
477
  }
12✔
478
}
261✔
479

480
void Plot::set_basis(pugi::xml_node plot_node)
234✔
481
{
482
  // Copy plot basis
483
  if (PlotType::slice == type_) {
234✔
484
    std::string pl_basis = "xy";
219✔
485
    if (check_for_node(plot_node, "basis")) {
219!
486
      pl_basis = get_node_value(plot_node, "basis", true);
219✔
487
    }
488
    if ("xy" == pl_basis) {
219✔
489
      basis_ = PlotBasis::xy;
201✔
490
    } else if ("xz" == pl_basis) {
18✔
491
      basis_ = PlotBasis::xz;
6✔
492
    } else if ("yz" == pl_basis) {
12!
493
      basis_ = PlotBasis::yz;
12✔
494
    } else {
495
      fatal_error(
×
496
        fmt::format("Unsupported plot basis '{}' in plot {}", pl_basis, id()));
×
497
    }
498
  }
219✔
499
}
234✔
500

501
void Plot::set_origin(pugi::xml_node plot_node)
234✔
502
{
503
  // Copy plotting origin
504
  auto pl_origin = get_node_array<double>(plot_node, "origin");
234✔
505
  if (pl_origin.size() == 3) {
234!
506
    origin_ = pl_origin;
234✔
507
  } else {
508
    fatal_error(fmt::format("Origin must be length 3 in plot {}", id()));
×
509
  }
510
}
234✔
511

512
void Plot::set_width(pugi::xml_node plot_node)
234✔
513
{
514
  // Copy plotting width
515
  vector<double> pl_width = get_node_array<double>(plot_node, "width");
234✔
516
  if (PlotType::slice == type_) {
234✔
517
    if (pl_width.size() == 2) {
219!
518
      width_.x = pl_width[0];
219✔
519
      width_.y = pl_width[1];
219✔
520
      switch (basis_) {
219!
521
      case PlotBasis::xy:
201✔
522
        u_span_ = {width_.x, 0.0, 0.0};
201✔
523
        v_span_ = {0.0, width_.y, 0.0};
201✔
524
        break;
201✔
525
      case PlotBasis::xz:
6✔
526
        u_span_ = {width_.x, 0.0, 0.0};
6✔
527
        v_span_ = {0.0, 0.0, width_.y};
6✔
528
        break;
6✔
529
      case PlotBasis::yz:
12✔
530
        u_span_ = {0.0, width_.x, 0.0};
12✔
531
        v_span_ = {0.0, 0.0, width_.y};
12✔
532
        break;
12✔
533
      default:
×
534
        UNREACHABLE();
×
535
      }
536
    } else {
537
      fatal_error(
×
538
        fmt::format("<width> must be length 2 in slice plot {}", id()));
×
539
    }
540
  } else if (PlotType::voxel == type_) {
15!
541
    if (pl_width.size() == 3) {
15!
542
      pl_width = get_node_array<double>(plot_node, "width");
30✔
543
      width_ = pl_width;
15✔
544
    } else {
545
      fatal_error(
×
546
        fmt::format("<width> must be length 3 in voxel plot {}", id()));
×
547
    }
548
  }
549
}
234✔
550

551
void PlottableInterface::set_universe(pugi::xml_node plot_node)
261✔
552
{
553
  // Copy plot universe level
554
  if (check_for_node(plot_node, "level")) {
261!
555
    level_ = std::stoi(get_node_value(plot_node, "level"));
×
556
    if (level_ < 0) {
×
557
      fatal_error(fmt::format("Bad universe level in plot {}", id()));
×
558
    }
559
  } else {
560
    level_ = PLOT_LEVEL_LOWEST;
261✔
561
  }
562
}
261✔
563

564
void PlottableInterface::set_color_by(pugi::xml_node plot_node)
261✔
565
{
566
  // Copy plot color type
567
  std::string pl_color_by = "cell";
261✔
568
  if (check_for_node(plot_node, "color_by")) {
261✔
569
    pl_color_by = get_node_value(plot_node, "color_by", true);
252✔
570
  }
571
  if ("cell" == pl_color_by) {
261✔
572
    color_by_ = PlotColorBy::cells;
75✔
573
  } else if ("material" == pl_color_by) {
186!
574
    color_by_ = PlotColorBy::mats;
186✔
575
  } else {
576
    fatal_error(fmt::format(
×
577
      "Unsupported plot color type '{}' in plot {}", pl_color_by, id()));
×
578
  }
579
}
261✔
580

581
void PlottableInterface::set_default_colors()
264✔
582
{
583
  // Copy plot color type and initialize all colors randomly
584
  if (PlotColorBy::cells == color_by_) {
264✔
585
    colors_.resize(model::cells.size());
75✔
586
  } else if (PlotColorBy::mats == color_by_) {
189!
587
    colors_.resize(model::materials.size());
189✔
588
  }
589

590
  for (auto& c : colors_) {
1,155✔
591
    c = random_color();
891✔
592
    // make sure we don't interfere with some default colors
593
    while (c == RED || c == WHITE) {
891!
594
      c = random_color();
×
595
    }
596
  }
597
}
264✔
598

599
void PlottableInterface::set_user_colors(pugi::xml_node plot_node)
261✔
600
{
601
  for (auto cn : plot_node.children("color")) {
312✔
602
    // Make sure 3 values are specified for RGB
603
    vector<int> user_rgb = get_node_array<int>(cn, "rgb");
51✔
604
    if (user_rgb.size() != 3) {
51!
605
      fatal_error(fmt::format("Bad RGB in plot {}", id()));
×
606
    }
607
    // Ensure that there is an id for this color specification
608
    int col_id;
51✔
609
    if (check_for_node(cn, "id")) {
51!
610
      col_id = std::stoi(get_node_value(cn, "id"));
102✔
611
    } else {
612
      fatal_error(fmt::format(
×
613
        "Must specify id for color specification in plot {}", id()));
×
614
    }
615
    // Add RGB
616
    if (PlotColorBy::cells == color_by_) {
51✔
617
      if (model::cell_map.find(col_id) != model::cell_map.end()) {
24!
618
        col_id = model::cell_map[col_id];
24✔
619
        colors_[col_id] = user_rgb;
24✔
620
      } else {
621
        warning(fmt::format(
×
622
          "Could not find cell {} specified in plot {}", col_id, id()));
×
623
      }
624
    } else if (PlotColorBy::mats == color_by_) {
27!
625
      if (model::material_map.find(col_id) != model::material_map.end()) {
27!
626
        col_id = model::material_map[col_id];
27✔
627
        colors_[col_id] = user_rgb;
27✔
628
      } else {
629
        warning(fmt::format(
×
630
          "Could not find material {} specified in plot {}", col_id, id()));
×
631
      }
632
    }
633
  } // color node loop
51✔
634
}
261✔
635

636
void Plot::set_meshlines(pugi::xml_node plot_node)
234✔
637
{
638
  // Deal with meshlines
639
  pugi::xpath_node_set mesh_line_nodes = plot_node.select_nodes("meshlines");
234✔
640

641
  if (!mesh_line_nodes.empty()) {
234✔
642
    if (PlotType::voxel == type_) {
9!
643
      warning(fmt::format("Meshlines ignored in voxel plot {}", id()));
×
644
    }
645

646
    if (mesh_line_nodes.size() == 1) {
9!
647
      // Get first meshline node
648
      pugi::xml_node meshlines_node = mesh_line_nodes[0].node();
9✔
649

650
      // Check mesh type
651
      std::string meshtype;
9✔
652
      if (check_for_node(meshlines_node, "meshtype")) {
9!
653
        meshtype = get_node_value(meshlines_node, "meshtype");
9✔
654
      } else {
655
        fatal_error(fmt::format(
×
656
          "Must specify a meshtype for meshlines specification in plot {}",
657
          id()));
×
658
      }
659

660
      // Ensure that there is a linewidth for this meshlines specification
661
      std::string meshline_width;
9✔
662
      if (check_for_node(meshlines_node, "linewidth")) {
9!
663
        meshline_width = get_node_value(meshlines_node, "linewidth");
9✔
664
        meshlines_width_ = std::stoi(meshline_width);
9✔
665
      } else {
666
        fatal_error(fmt::format(
×
667
          "Must specify a linewidth for meshlines specification in plot {}",
668
          id()));
×
669
      }
670

671
      // Check for color
672
      if (check_for_node(meshlines_node, "color")) {
9!
673
        // Check and make sure 3 values are specified for RGB
674
        vector<int> ml_rgb = get_node_array<int>(meshlines_node, "color");
×
675
        if (ml_rgb.size() != 3) {
×
676
          fatal_error(
×
677
            fmt::format("Bad RGB for meshlines color in plot {}", id()));
×
678
        }
679
        meshlines_color_ = ml_rgb;
×
680
      }
×
681

682
      // Set mesh based on type
683
      if ("ufs" == meshtype) {
9!
684
        if (!simulation::ufs_mesh) {
×
685
          fatal_error(
×
686
            fmt::format("No UFS mesh for meshlines on plot {}", id()));
×
687
        } else {
688
          for (int i = 0; i < model::meshes.size(); ++i) {
×
689
            if (const auto* m =
×
690
                  dynamic_cast<const RegularMesh*>(model::meshes[i].get())) {
×
691
              if (m == simulation::ufs_mesh) {
×
692
                index_meshlines_mesh_ = i;
×
693
              }
694
            }
695
          }
696
          if (index_meshlines_mesh_ == -1)
×
697
            fatal_error("Could not find the UFS mesh for meshlines plot");
×
698
        }
699
      } else if ("entropy" == meshtype) {
9✔
700
        if (!simulation::entropy_mesh) {
6!
701
          fatal_error(
×
702
            fmt::format("No entropy mesh for meshlines on plot {}", id()));
×
703
        } else {
704
          for (int i = 0; i < model::meshes.size(); ++i) {
15✔
705
            if (const auto* m =
18✔
706
                  dynamic_cast<const RegularMesh*>(model::meshes[i].get())) {
15!
707
              if (m == simulation::entropy_mesh) {
6!
708
                index_meshlines_mesh_ = i;
6✔
709
              }
710
            }
711
          }
712
          if (index_meshlines_mesh_ == -1)
6!
713
            fatal_error("Could not find the entropy mesh for meshlines plot");
×
714
        }
715
      } else if ("tally" == meshtype) {
3!
716
        // Ensure that there is a mesh id if the type is tally
717
        int tally_mesh_id;
3✔
718
        if (check_for_node(meshlines_node, "id")) {
3!
719
          tally_mesh_id = std::stoi(get_node_value(meshlines_node, "id"));
6✔
720
        } else {
721
          std::stringstream err_msg;
×
722
          fatal_error(fmt::format("Must specify a mesh id for meshlines tally "
×
723
                                  "mesh specification in plot {}",
724
            id()));
×
725
        }
×
726
        // find the tally index
727
        int idx;
3✔
728
        int err = openmc_get_mesh_index(tally_mesh_id, &idx);
3✔
729
        if (err != 0) {
3!
730
          fatal_error(fmt::format("Could not find mesh {} specified in "
×
731
                                  "meshlines for plot {}",
732
            tally_mesh_id, id()));
×
733
        }
734
        index_meshlines_mesh_ = idx;
3✔
735
      } else {
736
        fatal_error(fmt::format("Invalid type for meshlines on plot {}", id()));
×
737
      }
738
    } else {
9✔
739
      fatal_error(fmt::format("Mutliple meshlines specified in plot {}", id()));
×
740
    }
741
  }
742
}
234✔
743

744
void PlottableInterface::set_mask(pugi::xml_node plot_node)
261✔
745
{
746
  // Deal with masks
747
  pugi::xpath_node_set mask_nodes = plot_node.select_nodes("mask");
261✔
748

749
  if (!mask_nodes.empty()) {
261✔
750
    if (mask_nodes.size() == 1) {
9!
751
      // Get pointer to mask
752
      pugi::xml_node mask_node = mask_nodes[0].node();
9✔
753

754
      // Determine how many components there are and allocate
755
      vector<int> iarray = get_node_array<int>(mask_node, "components");
9✔
756
      if (iarray.size() == 0) {
9!
757
        fatal_error(
×
758
          fmt::format("Missing <components> in mask of plot {}", id()));
×
759
      }
760

761
      // First we need to change the user-specified identifiers to indices
762
      // in the cell and material arrays
763
      for (auto& col_id : iarray) {
27✔
764
        if (PlotColorBy::cells == color_by_) {
18!
765
          if (model::cell_map.find(col_id) != model::cell_map.end()) {
18!
766
            col_id = model::cell_map[col_id];
18✔
767
          } else {
768
            fatal_error(fmt::format("Could not find cell {} specified in the "
×
769
                                    "mask in plot {}",
770
              col_id, id()));
×
771
          }
772
        } else if (PlotColorBy::mats == color_by_) {
×
773
          if (model::material_map.find(col_id) != model::material_map.end()) {
×
774
            col_id = model::material_map[col_id];
×
775
          } else {
776
            fatal_error(fmt::format("Could not find material {} specified in "
×
777
                                    "the mask in plot {}",
778
              col_id, id()));
×
779
          }
780
        }
781
      }
782

783
      // Alter colors based on mask information
784
      for (int j = 0; j < colors_.size(); j++) {
36✔
785
        if (contains(iarray, j)) {
27✔
786
          if (check_for_node(mask_node, "background")) {
18!
787
            vector<int> bg_rgb = get_node_array<int>(mask_node, "background");
18✔
788
            colors_[j] = bg_rgb;
18✔
789
          } else {
18✔
790
            colors_[j] = WHITE;
×
791
          }
792
        }
793
      }
794

795
    } else {
9✔
796
      fatal_error(fmt::format("Mutliple masks specified in plot {}", id()));
×
797
    }
798
  }
799
}
261✔
800

801
void PlottableInterface::set_overlap_color(pugi::xml_node plot_node)
261✔
802
{
803
  color_overlaps_ = false;
261✔
804
  if (check_for_node(plot_node, "show_overlaps")) {
261✔
805
    color_overlaps_ = get_node_value_bool(plot_node, "show_overlaps");
6✔
806
    // check for custom overlap color
807
    if (check_for_node(plot_node, "overlap_color")) {
6✔
808
      if (!color_overlaps_) {
3!
809
        warning(fmt::format(
×
810
          "Overlap color specified in plot {} but overlaps won't be shown.",
811
          id()));
×
812
      }
813
      vector<int> olap_clr = get_node_array<int>(plot_node, "overlap_color");
3✔
814
      if (olap_clr.size() == 3) {
3!
815
        overlap_color_ = olap_clr;
3✔
816
      } else {
817
        fatal_error(fmt::format("Bad overlap RGB in plot {}", id()));
×
818
      }
819
    }
3✔
820
  }
821

822
  // make sure we allocate the vector for counting overlap checks if
823
  // they're going to be plotted
824
  if (color_overlaps_ && settings::run_mode == RunMode::PLOTTING) {
261!
825
    settings::check_overlaps = true;
6✔
826
    model::overlap_check_count.resize(model::cells.size(), 0);
6✔
827
  }
828
}
261✔
829

830
PlottableInterface::PlottableInterface(pugi::xml_node plot_node)
261✔
831
{
832
  set_id(plot_node);
261✔
833
  set_bg_color(plot_node);
261✔
834
  set_universe(plot_node);
261✔
835
  set_color_by(plot_node);
261✔
836
  set_default_colors();
261✔
837
  set_user_colors(plot_node);
261✔
838
  set_mask(plot_node);
261✔
839
  set_overlap_color(plot_node);
261✔
840
}
261✔
841

842
Plot::Plot(pugi::xml_node plot_node, PlotType type)
237✔
843
  : PlottableInterface(plot_node), type_(type), index_meshlines_mesh_ {-1}
237✔
844
{
845
  set_output_path(plot_node);
237✔
846
  set_basis(plot_node);
234✔
847
  set_origin(plot_node);
234✔
848
  set_width(plot_node);
234✔
849
  set_meshlines(plot_node);
234✔
850
  slice_level_ = level_; // Copy level employed in SlicePlotBase::get_map
234✔
851
  show_overlaps_ = color_overlaps_;
234✔
852
}
234✔
853

854
//==============================================================================
855
// OUTPUT_PPM writes out a previously generated image to a PPM file
856
//==============================================================================
857

858
void output_ppm(const std::string& filename, const ImageData& data)
×
859
{
860
  // Open PPM file for writing
861
  std::string fname = filename;
×
862
  fname = strtrim(fname);
×
863
  std::ofstream of;
×
864

865
  of.open(fname);
×
866

867
  // Write header
868
  of << "P6\n";
×
869
  of << data.shape(0) << " " << data.shape(1) << "\n";
×
870
  of << "255\n";
×
871
  of.close();
×
872

873
  of.open(fname, std::ios::binary | std::ios::app);
×
874
  // Write color for each pixel
875
  for (int y = 0; y < data.shape(1); y++) {
×
876
    for (int x = 0; x < data.shape(0); x++) {
×
877
      RGBColor rgb = data(x, y);
×
878
      of << rgb.red << rgb.green << rgb.blue;
×
879
    }
880
  }
881
  of << "\n";
×
882
}
×
883

884
//==============================================================================
885
// OUTPUT_PNG writes out a previously generated image to a PNG file
886
//==============================================================================
887

888
#ifdef USE_LIBPNG
889
void output_png(const std::string& filename, const ImageData& data)
63✔
890
{
891
  // Open PNG file for writing
892
  std::string fname = filename;
63✔
893
  fname = strtrim(fname);
63✔
894
  auto fp = std::fopen(fname.c_str(), "wb");
63✔
895

896
  // Initialize write and info structures
897
  auto png_ptr =
63✔
898
    png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);
63✔
899
  auto info_ptr = png_create_info_struct(png_ptr);
63✔
900

901
  // Setup exception handling
902
  if (setjmp(png_jmpbuf(png_ptr)))
63!
903
    fatal_error("Error during png creation");
×
904

905
  png_init_io(png_ptr, fp);
63✔
906

907
  // Write header (8 bit colour depth)
908
  int width = data.shape(0);
63!
909
  int height = data.shape(1);
63!
910
  png_set_IHDR(png_ptr, info_ptr, width, height, 8, PNG_COLOR_TYPE_RGB,
63✔
911
    PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
912
  png_write_info(png_ptr, info_ptr);
63✔
913

914
  // Allocate memory for one row (3 bytes per pixel - RGB)
915
  std::vector<png_byte> row(3 * width);
63✔
916

917
  // Write color for each pixel
918
  for (int y = 0; y < height; y++) {
13,023✔
919
    for (int x = 0; x < width; x++) {
3,043,560✔
920
      RGBColor rgb = data(x, y);
3,030,600✔
921
      row[3 * x] = rgb.red;
3,030,600✔
922
      row[3 * x + 1] = rgb.green;
3,030,600✔
923
      row[3 * x + 2] = rgb.blue;
3,030,600✔
924
    }
925
    png_write_row(png_ptr, row.data());
12,960✔
926
  }
927

928
  // End write
929
  png_write_end(png_ptr, nullptr);
63✔
930

931
  // Clean up data structures
932
  std::fclose(fp);
63✔
933
  png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
63✔
934
  png_destroy_write_struct(&png_ptr, &info_ptr);
63✔
935
}
63✔
936
#endif
937

938
//==============================================================================
939
// DRAW_MESH_LINES draws mesh line boundaries on an image
940
//==============================================================================
941

942
void Plot::draw_mesh_lines(ImageData& data) const
9✔
943
{
944
  RGBColor rgb;
9!
945
  rgb = meshlines_color_;
9✔
946

947
  int ax1, ax2;
9✔
948
  Position expected_u {};
9✔
949
  Position expected_v {};
9✔
950
  switch (basis_) {
9!
951
  case PlotBasis::xy:
6✔
952
    ax1 = 0;
6✔
953
    ax2 = 1;
6✔
954
    expected_u = {width_[0], 0.0, 0.0};
6✔
955
    expected_v = {0.0, width_[1], 0.0};
6✔
956
    break;
6✔
957
  case PlotBasis::xz:
3✔
958
    ax1 = 0;
3✔
959
    ax2 = 2;
3✔
960
    expected_u = {width_[0], 0.0, 0.0};
3✔
961
    expected_v = {0.0, 0.0, width_[1]};
3✔
962
    break;
3✔
963
  case PlotBasis::yz:
×
964
    ax1 = 1;
×
965
    ax2 = 2;
×
966
    expected_u = {0.0, width_[0], 0.0};
×
967
    expected_v = {0.0, 0.0, width_[1]};
×
968
    break;
×
969
  default:
×
970
    UNREACHABLE();
×
971
  }
972

973
  // Meshlines rely on axis-aligned indexing in global coordinates.
974
  constexpr double rel_tol {1e-12};
9✔
975
  double span_tol = rel_tol * (1.0 + u_span_.norm() + v_span_.norm());
9✔
976
  if ((u_span_ - expected_u).norm() > span_tol ||
18!
977
      (v_span_ - expected_v).norm() > span_tol) {
9✔
978
    fatal_error("Meshlines are only supported for axis-aligned slice plots.");
×
979
  }
980

981
  Position ll_plot {origin_};
9✔
982
  Position ur_plot {origin_};
9✔
983

984
  ll_plot[ax1] -= width_[0] / 2.;
9✔
985
  ll_plot[ax2] -= width_[1] / 2.;
9✔
986
  ur_plot[ax1] += width_[0] / 2.;
9✔
987
  ur_plot[ax2] += width_[1] / 2.;
9✔
988

989
  Position width = ur_plot - ll_plot;
9✔
990

991
  // Find the (axis-aligned) lines of the mesh that intersect this plot.
992
  auto axis_lines =
9✔
993
    model::meshes[index_meshlines_mesh_]->plot(ll_plot, ur_plot);
9✔
994

995
  // Find the bounds along the second axis (accounting for low-D meshes).
996
  int ax2_min, ax2_max;
9✔
997
  if (axis_lines.second.size() > 0) {
9!
998
    double frac = (axis_lines.second.back() - ll_plot[ax2]) / width[ax2];
9✔
999
    ax2_min = (1.0 - frac) * pixels()[1];
9✔
1000
    if (ax2_min < 0)
9✔
1001
      ax2_min = 0;
1002
    frac = (axis_lines.second.front() - ll_plot[ax2]) / width[ax2];
9✔
1003
    ax2_max = (1.0 - frac) * pixels()[1];
9!
1004
    if (ax2_max > pixels()[1])
9!
1005
      ax2_max = pixels()[1];
×
1006
  } else {
1007
    ax2_min = 0;
×
1008
    ax2_max = pixels()[1];
×
1009
  }
1010

1011
  // Iterate across the first axis and draw lines.
1012
  for (auto ax1_val : axis_lines.first) {
51✔
1013
    double frac = (ax1_val - ll_plot[ax1]) / width[ax1];
42✔
1014
    int ax1_ind = frac * pixels()[0];
42✔
1015
    for (int ax2_ind = ax2_min; ax2_ind < ax2_max; ++ax2_ind) {
6,804✔
1016
      for (int plus = 0; plus <= meshlines_width_; plus++) {
13,524✔
1017
        if (ax1_ind + plus >= 0 && ax1_ind + plus < pixels()[0])
6,762!
1018
          data(ax1_ind + plus, ax2_ind) = rgb;
6,762✔
1019
        if (ax1_ind - plus >= 0 && ax1_ind - plus < pixels()[0])
6,762!
1020
          data(ax1_ind - plus, ax2_ind) = rgb;
6,762✔
1021
      }
1022
    }
1023
  }
1024

1025
  // Find the bounds along the first axis.
1026
  int ax1_min, ax1_max;
9✔
1027
  if (axis_lines.first.size() > 0) {
9!
1028
    double frac = (axis_lines.first.front() - ll_plot[ax1]) / width[ax1];
9✔
1029
    ax1_min = frac * pixels()[0];
9✔
1030
    if (ax1_min < 0)
9✔
1031
      ax1_min = 0;
1032
    frac = (axis_lines.first.back() - ll_plot[ax1]) / width[ax1];
9✔
1033
    ax1_max = frac * pixels()[0];
9!
1034
    if (ax1_max > pixels()[0])
9!
1035
      ax1_max = pixels()[0];
×
1036
  } else {
1037
    ax1_min = 0;
×
1038
    ax1_max = pixels()[0];
×
1039
  }
1040

1041
  // Iterate across the second axis and draw lines.
1042
  for (auto ax2_val : axis_lines.second) {
57✔
1043
    double frac = (ax2_val - ll_plot[ax2]) / width[ax2];
48✔
1044
    int ax2_ind = (1.0 - frac) * pixels()[1];
48✔
1045
    for (int ax1_ind = ax1_min; ax1_ind < ax1_max; ++ax1_ind) {
7,728✔
1046
      for (int plus = 0; plus <= meshlines_width_; plus++) {
15,360✔
1047
        if (ax2_ind + plus >= 0 && ax2_ind + plus < pixels()[1])
7,680!
1048
          data(ax1_ind, ax2_ind + plus) = rgb;
7,680✔
1049
        if (ax2_ind - plus >= 0 && ax2_ind - plus < pixels()[1])
7,680!
1050
          data(ax1_ind, ax2_ind - plus) = rgb;
7,680✔
1051
      }
1052
    }
1053
  }
1054
}
9✔
1055

1056
/* outputs a binary file that can be input into silomesh for 3D geometry
1057
 * visualization.  It works the same way as create_image by dragging a particle
1058
 * across the geometry for the specified number of voxels. The first 3 int's in
1059
 * the binary are the number of x, y, and z voxels.  The next 3 double's are
1060
 * the widths of the voxels in the x, y, and z directions. The next 3 double's
1061
 * are the x, y, and z coordinates of the lower left point. Finally the binary
1062
 * is filled with entries of four int's each. Each 'row' in the binary contains
1063
 * four int's: 3 for x,y,z position and 1 for cell or material id.  For 1
1064
 * million voxels this produces a file of approximately 15MB.
1065
 */
1066
void Plot::create_voxel() const
15✔
1067
{
1068
  // compute voxel widths in each direction
1069
  array<double, 3> vox;
15✔
1070
  vox[0] = width_[0] / static_cast<double>(pixels()[0]);
15✔
1071
  vox[1] = width_[1] / static_cast<double>(pixels()[1]);
15✔
1072
  vox[2] = width_[2] / static_cast<double>(pixels()[2]);
15✔
1073

1074
  // initial particle position
1075
  Position ll = origin_ - width_ / 2.;
15✔
1076

1077
  // Open binary plot file for writing
1078
  std::ofstream of;
15✔
1079
  std::string fname = std::string(path_plot_);
15✔
1080
  fname = strtrim(fname);
15✔
1081
  hid_t file_id = file_open(fname, 'w');
15✔
1082

1083
  // write header info
1084
  write_attribute(file_id, "filetype", "voxel");
15✔
1085
  write_attribute(file_id, "version", VERSION_VOXEL);
15✔
1086
  write_attribute(file_id, "openmc_version", VERSION);
15✔
1087

1088
#ifdef GIT_SHA1
1089
  write_attribute(file_id, "git_sha1", GIT_SHA1);
1090
#endif
1091

1092
  // Write current date and time
1093
  write_attribute(file_id, "date_and_time", time_stamp().c_str());
30✔
1094
  array<int, 3> h5_pixels;
15✔
1095
  std::copy(pixels().begin(), pixels().end(), h5_pixels.begin());
15✔
1096
  write_attribute(file_id, "num_voxels", h5_pixels);
15✔
1097
  write_attribute(file_id, "voxel_width", vox);
15✔
1098
  write_attribute(file_id, "lower_left", ll);
15✔
1099

1100
  // Create dataset for voxel data -- note that the dimensions are reversed
1101
  // since we want the order in the file to be z, y, x
1102
  hsize_t dims[3];
15✔
1103
  dims[0] = pixels()[2];
15✔
1104
  dims[1] = pixels()[1];
15✔
1105
  dims[2] = pixels()[0];
15✔
1106
  hid_t dspace, dset, memspace;
15✔
1107
  voxel_init(file_id, &(dims[0]), &dspace, &dset, &memspace);
15✔
1108

1109
  SlicePlotBase pltbase;
15✔
1110
  pltbase.origin_ = origin_;
15✔
1111
  pltbase.u_span_ = {width_.x, 0.0, 0.0};
15✔
1112
  pltbase.v_span_ = {0.0, width_.y, 0.0};
15✔
1113
  pltbase.pixels() = pixels();
15✔
1114
  pltbase.show_overlaps_ = color_overlaps_;
15✔
1115

1116
  ProgressBar pb;
15✔
1117
  for (int z = 0; z < pixels()[2]; z++) {
1,305✔
1118
    // update z coordinate
1119
    pltbase.origin_.z = ll.z + z * vox[2];
1,290✔
1120

1121
    // generate ids using plotbase
1122
    IdData ids = pltbase.get_map<IdData>();
1,290✔
1123

1124
    // select only cell/material ID data and flip the y-axis
1125
    int idx = color_by_ == PlotColorBy::cells ? 0 : 2;
1,290!
1126
    // Extract 2D slice at index idx from 3D data
1127
    size_t rows = ids.data_.shape(0);
1,290!
1128
    size_t cols = ids.data_.shape(1);
1,290!
1129
    tensor::Tensor<int32_t> data_slice({rows, cols});
1,290✔
1130
    for (size_t r = 0; r < rows; ++r)
248,790✔
1131
      for (size_t c = 0; c < cols; ++c)
48,922,500✔
1132
        data_slice(r, c) = ids.data_(r, c, idx);
48,675,000✔
1133
    tensor::Tensor<int32_t> data_flipped = data_slice.flip(0);
1,290✔
1134

1135
    // Write to HDF5 dataset
1136
    voxel_write_slice(z, dspace, dset, memspace, data_flipped.data());
1,290✔
1137

1138
    // update progress bar
1139
    pb.set_value(
1,290✔
1140
      100. * static_cast<double>(z + 1) / static_cast<double>((pixels()[2])));
1,290✔
1141
  }
3,870✔
1142

1143
  voxel_finalize(dspace, dset, memspace);
15✔
1144
  file_close(file_id);
15✔
1145
}
15✔
1146

1147
void voxel_init(hid_t file_id, const hsize_t* dims, hid_t* dspace, hid_t* dset,
15✔
1148
  hid_t* memspace)
1149
{
1150
  // Create dataspace/dataset for voxel data
1151
  *dspace = H5Screate_simple(3, dims, nullptr);
15✔
1152
  *dset = H5Dcreate(file_id, "data", H5T_NATIVE_INT, *dspace, H5P_DEFAULT,
15✔
1153
    H5P_DEFAULT, H5P_DEFAULT);
1154

1155
  // Create dataspace for a slice of the voxel
1156
  hsize_t dims_slice[2] {dims[1], dims[2]};
15✔
1157
  *memspace = H5Screate_simple(2, dims_slice, nullptr);
15✔
1158

1159
  // Select hyperslab in dataspace
1160
  hsize_t start[3] {0, 0, 0};
15✔
1161
  hsize_t count[3] {1, dims[1], dims[2]};
15✔
1162
  H5Sselect_hyperslab(*dspace, H5S_SELECT_SET, start, nullptr, count, nullptr);
15✔
1163
}
15✔
1164

1165
void voxel_write_slice(
1,290✔
1166
  int x, hid_t dspace, hid_t dset, hid_t memspace, void* buf)
1167
{
1168
  hssize_t offset[3] {x, 0, 0};
1,290✔
1169
  H5Soffset_simple(dspace, offset);
1,290✔
1170
  H5Dwrite(dset, H5T_NATIVE_INT, memspace, dspace, H5P_DEFAULT, buf);
1,290✔
1171
}
1,290✔
1172

1173
void voxel_finalize(hid_t dspace, hid_t dset, hid_t memspace)
15✔
1174
{
1175
  H5Dclose(dset);
15✔
1176
  H5Sclose(dspace);
15✔
1177
  H5Sclose(memspace);
15✔
1178
}
15✔
1179

1180
RGBColor random_color(void)
891✔
1181
{
1182
  return {int(prn(&model::plotter_seed) * 255),
891✔
1183
    int(prn(&model::plotter_seed) * 255), int(prn(&model::plotter_seed) * 255)};
891✔
1184
}
1185

1186
RayTracePlot::RayTracePlot(pugi::xml_node node) : PlottableInterface(node)
24✔
1187
{
1188
  set_look_at(node);
24✔
1189
  set_camera_position(node);
24✔
1190
  set_field_of_view(node);
24✔
1191
  set_pixels(node);
24✔
1192
  set_orthographic_width(node);
24✔
1193
  set_output_path(node);
24✔
1194

1195
  if (check_for_node(node, "orthographic_width") &&
27!
1196
      check_for_node(node, "field_of_view"))
3✔
1197
    fatal_error("orthographic_width and field_of_view are mutually exclusive "
×
1198
                "parameters.");
1199
}
24✔
1200

1201
void RayTracePlot::update_view()
30✔
1202
{
1203
  // Get centerline vector for camera-to-model. We create vectors around this
1204
  // that form a pixel array, and then trace rays along that.
1205
  auto up = up_ / up_.norm();
30✔
1206
  Direction looking_direction = look_at_ - camera_position_;
30✔
1207
  looking_direction /= looking_direction.norm();
30✔
1208
  if (std::abs(std::abs(looking_direction.dot(up)) - 1.0) < 1e-9)
30!
1209
    fatal_error("Up vector cannot align with vector between camera position "
×
1210
                "and look_at!");
1211
  Direction cam_yaxis = looking_direction.cross(up);
30✔
1212
  cam_yaxis /= cam_yaxis.norm();
30✔
1213
  Direction cam_zaxis = cam_yaxis.cross(looking_direction);
30✔
1214
  cam_zaxis /= cam_zaxis.norm();
30✔
1215

1216
  // Cache the camera-to-model matrix
1217
  camera_to_model_ = {looking_direction.x, cam_yaxis.x, cam_zaxis.x,
30✔
1218
    looking_direction.y, cam_yaxis.y, cam_zaxis.y, looking_direction.z,
30✔
1219
    cam_yaxis.z, cam_zaxis.z};
30✔
1220
}
30✔
1221

1222
WireframeRayTracePlot::WireframeRayTracePlot(pugi::xml_node node)
15✔
1223
  : RayTracePlot(node)
15✔
1224
{
1225
  set_opacities(node);
15✔
1226
  set_wireframe_thickness(node);
15✔
1227
  set_wireframe_ids(node);
15✔
1228
  set_wireframe_color(node);
15✔
1229
  update_view();
15✔
1230
}
15✔
1231

1232
void WireframeRayTracePlot::set_wireframe_color(pugi::xml_node plot_node)
15✔
1233
{
1234
  // Copy plot wireframe color
1235
  if (check_for_node(plot_node, "wireframe_color")) {
15!
1236
    vector<int> w_rgb = get_node_array<int>(plot_node, "wireframe_color");
×
1237
    if (w_rgb.size() == 3) {
×
1238
      wireframe_color_ = w_rgb;
×
1239
    } else {
1240
      fatal_error(fmt::format("Bad wireframe RGB in plot {}", id()));
×
1241
    }
1242
  }
×
1243
}
15✔
1244

1245
void RayTracePlot::set_output_path(pugi::xml_node node)
24✔
1246
{
1247
  // Set output file path
1248
  std::string filename;
24✔
1249

1250
  if (check_for_node(node, "filename")) {
24✔
1251
    filename = get_node_value(node, "filename");
21✔
1252
  } else {
1253
    filename = fmt::format("plot_{}", id());
3✔
1254
  }
1255

1256
#ifdef USE_LIBPNG
1257
  if (!file_extension_present(filename, "png"))
24✔
1258
    filename.append(".png");
9✔
1259
#else
1260
  if (!file_extension_present(filename, "ppm"))
1261
    filename.append(".ppm");
1262
#endif
1263
  path_plot_ = filename;
48✔
1264
}
24✔
1265

1266
bool WireframeRayTracePlot::trackstack_equivalent(
829,407✔
1267
  const std::vector<TrackSegment>& track1,
1268
  const std::vector<TrackSegment>& track2) const
1269
{
1270
  if (wireframe_ids_.empty()) {
829,407✔
1271
    // Draw wireframe for all surfaces/cells/materials
1272
    if (track1.size() != track2.size())
694,110✔
1273
      return false;
1274
    for (int i = 0; i < track1.size(); ++i) {
1,829,442✔
1275
      if (track1[i].id != track2[i].id ||
1,155,483✔
1276
          track1[i].surface_index != track2[i].surface_index) {
1,155,447✔
1277
        return false;
1278
      }
1279
    }
1280
    return true;
1281
  } else {
1282
    // This runs in O(nm) where n is the intersection stack size
1283
    // and m is the number of IDs we are wireframing. A simpler
1284
    // algorithm can likely be found.
1285
    for (const int id : wireframe_ids_) {
268,962✔
1286
      int t1_i = 0;
135,297✔
1287
      int t2_i = 0;
135,297✔
1288

1289
      // Advance to first instance of the ID
1290
      while (t1_i < track1.size() && t2_i < track2.size()) {
153,390✔
1291
        while (t1_i < track1.size() && track1[t1_i].id != id)
107,136✔
1292
          t1_i++;
62,469✔
1293
        while (t2_i < track2.size() && track2[t2_i].id != id)
107,364✔
1294
          t2_i++;
62,697✔
1295

1296
        // This one is really important!
1297
        if ((t1_i == track1.size() && t2_i != track2.size()) ||
44,667✔
1298
            (t1_i != track1.size() && t2_i == track2.size()))
44,208✔
1299
          return false;
1,014✔
1300
        if (t1_i == track1.size() && t2_i == track2.size())
43,653!
1301
          break;
1302
        // Check if surface different
1303
        if (track1[t1_i].surface_index != track2[t2_i].surface_index)
18,711✔
1304
          return false;
1305

1306
        // Pretty sure this should not be used:
1307
        // if (t2_i != track2.size() - 1 &&
1308
        //     t1_i != track1.size() - 1 &&
1309
        //     track1[t1_i+1].id != track2[t2_i+1].id) return false;
1310
        if (t2_i != 0 && t1_i != 0 &&
18,306✔
1311
            track1[t1_i - 1].surface_index != track2[t2_i - 1].surface_index)
14,712✔
1312
          return false;
1313

1314
        // Check if neighboring cells are different
1315
        // if (track1[t1_i ? t1_i - 1 : 0].id != track2[t2_i ? t2_i - 1 : 0].id)
1316
        // return false; if (track1[t1_i < track1.size() - 1 ? t1_i + 1 : t1_i
1317
        // ].id !=
1318
        //    track2[t2_i < track2.size() - 1 ? t2_i + 1 : t2_i].id) return
1319
        //    false;
1320
        t1_i++, t2_i++;
18,093✔
1321
      }
1322
    }
1323
    return true;
1324
  }
1325
}
1326

1327
std::pair<Position, Direction> RayTracePlot::get_pixel_ray(
960,288✔
1328
  int horiz, int vert) const
1329
{
1330
  // Compute field of view in radians
1331
  constexpr double DEGREE_TO_RADIAN = M_PI / 180.0;
960,288✔
1332
  double horiz_fov_radians = horizontal_field_of_view_ * DEGREE_TO_RADIAN;
960,288✔
1333
  double p0 = static_cast<double>(pixels()[0]);
960,288✔
1334
  double p1 = static_cast<double>(pixels()[1]);
960,288✔
1335
  double vert_fov_radians = horiz_fov_radians * p1 / p0;
960,288✔
1336

1337
  // focal_plane_dist can be changed to alter the perspective distortion
1338
  // effect. This is in units of cm. This seems to look good most of the
1339
  // time. TODO let this variable be set through XML.
1340
  constexpr double focal_plane_dist = 10.0;
960,288✔
1341
  const double dx = 2.0 * focal_plane_dist * std::tan(0.5 * horiz_fov_radians);
960,288✔
1342
  const double dy = p1 / p0 * dx;
960,288✔
1343

1344
  std::pair<Position, Direction> result;
960,288✔
1345

1346
  // Generate the starting position/direction of the ray
1347
  if (orthographic_width_ == C_NONE) { // perspective projection
960,288✔
1348
    Direction camera_local_vec;
840,288✔
1349
    camera_local_vec.x = focal_plane_dist;
840,288✔
1350
    camera_local_vec.y = -0.5 * dx + horiz * dx / p0;
840,288✔
1351
    camera_local_vec.z = 0.5 * dy - vert * dy / p1;
840,288✔
1352
    camera_local_vec /= camera_local_vec.norm();
840,288✔
1353

1354
    result.first = camera_position_;
840,288✔
1355
    result.second = camera_local_vec.rotate(camera_to_model_);
840,288✔
1356
  } else { // orthographic projection
1357

1358
    double x_pix_coord = (static_cast<double>(horiz) - p0 / 2.0) / p0;
120,000✔
1359
    double y_pix_coord = (static_cast<double>(vert) - p1 / 2.0) / p1;
120,000✔
1360

1361
    result.first = camera_position_ +
120,000✔
1362
                   camera_y_axis() * x_pix_coord * orthographic_width_ +
120,000✔
1363
                   camera_z_axis() * y_pix_coord * orthographic_width_;
120,000✔
1364
    result.second = camera_x_axis();
120,000✔
1365
  }
1366

1367
  return result;
960,288✔
1368
}
1369

1370
ImageData WireframeRayTracePlot::create_image() const
15✔
1371
{
1372
  size_t width = pixels()[0];
15✔
1373
  size_t height = pixels()[1];
15✔
1374
  ImageData data({width, height}, not_found_);
15✔
1375

1376
  // This array marks where the initial wireframe was drawn. We convolve it with
1377
  // a filter that gets adjusted with the wireframe thickness in order to
1378
  // thicken the lines.
1379
  tensor::Tensor<int> wireframe_initial(
15✔
1380
    {static_cast<size_t>(width), static_cast<size_t>(height)}, 0);
15✔
1381

1382
  /* Holds all of the track segments for the current rendered line of pixels.
1383
   * old_segments holds a copy of this_line_segments from the previous line.
1384
   * By holding both we can check if the cell/material intersection stack
1385
   * differs from the left or upper neighbor. This allows a robustly drawn
1386
   * wireframe. If only checking the left pixel (which requires substantially
1387
   * less memory), the wireframe tends to be spotty and be disconnected for
1388
   * surface edges oriented horizontally in the rendering.
1389
   *
1390
   * Note that a vector of vectors is required rather than a 2-tensor,
1391
   * since the stack size varies within each column.
1392
   */
1393
  const int n_threads = num_threads();
15✔
1394
  std::vector<std::vector<std::vector<TrackSegment>>> this_line_segments(
15✔
1395
    n_threads);
15✔
1396
  for (int t = 0; t < n_threads; ++t) {
30✔
1397
    this_line_segments[t].resize(pixels()[0]);
15✔
1398
  }
1399

1400
  // The last thread writes to this, and the first thread reads from it.
1401
  std::vector<std::vector<TrackSegment>> old_segments(pixels()[0]);
15✔
1402

1403
#pragma omp parallel
1404
  {
15✔
1405
    const int n_threads = num_threads();
15✔
1406
    const int tid = thread_num();
15✔
1407

1408
    int vert = tid;
15✔
1409
    for (int iter = 0; iter <= pixels()[1] / n_threads; iter++) {
3,030✔
1410

1411
      // Save bottom line of current work chunk to compare against later. This
1412
      // used to be inside the below if block, but it causes a spurious line to
1413
      // be drawn at the bottom of the image. Not sure why, but moving it here
1414
      // fixes things.
1415
      if (tid == n_threads - 1)
3,015✔
1416
        old_segments = this_line_segments[n_threads - 1];
3,015✔
1417

1418
      if (vert < pixels()[1]) {
3,015✔
1419

1420
        for (int horiz = 0; horiz < pixels()[0]; ++horiz) {
603,000✔
1421

1422
          // RayTracePlot implements camera ray generation
1423
          std::pair<Position, Direction> ru = get_pixel_ray(horiz, vert);
600,000✔
1424

1425
          this_line_segments[tid][horiz].clear();
600,000✔
1426
          ProjectionRay ray(
600,000✔
1427
            ru.first, ru.second, *this, this_line_segments[tid][horiz]);
600,000✔
1428

1429
          ray.trace();
600,000✔
1430

1431
          // Now color the pixel based on what we have intersected...
1432
          // Loops backwards over intersections.
1433
          Position current_color(
600,000✔
1434
            not_found_.red, not_found_.green, not_found_.blue);
600,000✔
1435
          const auto& segments = this_line_segments[tid][horiz];
600,000✔
1436

1437
          // There must be at least two cell intersections to color, front and
1438
          // back of the cell. Maybe an infinitely thick cell could be present
1439
          // with no back, but why would you want to color that? It's easier to
1440
          // just skip that edge case and not even color it.
1441
          if (segments.size() <= 1)
600,000✔
1442
            continue;
369,993✔
1443

1444
          for (int i = segments.size() - 2; i >= 0; --i) {
643,401✔
1445
            int colormap_idx = segments[i].id;
413,394✔
1446
            RGBColor seg_color = colors_[colormap_idx];
413,394✔
1447
            Position seg_color_vec(
413,394✔
1448
              seg_color.red, seg_color.green, seg_color.blue);
413,394✔
1449
            double mixing =
413,394✔
1450
              std::exp(-xs_[colormap_idx] *
826,788✔
1451
                       (segments[i + 1].length - segments[i].length));
413,394✔
1452
            current_color =
413,394✔
1453
              current_color * mixing + (1.0 - mixing) * seg_color_vec;
413,394✔
1454
          }
1455

1456
          // save result converting from double-precision color coordinates to
1457
          // byte-sized
1458
          RGBColor result;
230,007✔
1459
          result.red = static_cast<uint8_t>(current_color.x);
230,007✔
1460
          result.green = static_cast<uint8_t>(current_color.y);
230,007✔
1461
          result.blue = static_cast<uint8_t>(current_color.z);
230,007✔
1462
          data(horiz, vert) = result;
230,007✔
1463

1464
          // Check to draw wireframe in horizontal direction. No inter-thread
1465
          // comm.
1466
          if (horiz > 0) {
230,007✔
1467
            if (!trackstack_equivalent(this_line_segments[tid][horiz],
229,407✔
1468
                  this_line_segments[tid][horiz - 1])) {
229,407✔
1469
              wireframe_initial(horiz, vert) = 1;
9,426✔
1470
            }
1471
          }
1472
        }
600,000✔
1473
      } // end "if" vert in correct range
1474

1475
      // We require a barrier before comparing vertical neighbors' intersection
1476
      // stacks. i.e. all threads must be done with their line.
1477
#pragma omp barrier
1478

1479
      // Now that the horizontal line has finished rendering, we can fill in
1480
      // wireframe entries that require comparison among all the threads. Hence
1481
      // the omp barrier being used. It has to be OUTSIDE any if blocks!
1482
      if (vert < pixels()[1]) {
3,015✔
1483
        // Loop over horizontal pixels, checking intersection stack of upper
1484
        // neighbor
1485

1486
        const std::vector<std::vector<TrackSegment>>* top_cmp = nullptr;
1487
        if (tid == 0)
1488
          top_cmp = &old_segments;
1489
        else
1490
          top_cmp = &this_line_segments[tid - 1];
1491

1492
        for (int horiz = 0; horiz < pixels()[0]; ++horiz) {
603,000✔
1493
          if (!trackstack_equivalent(
600,000✔
1494
                this_line_segments[tid][horiz], (*top_cmp)[horiz])) {
600,000✔
1495
            wireframe_initial(horiz, vert) = 1;
12,357✔
1496
          }
1497
        }
1498
      }
1499

1500
      // We need another barrier to ensure threads don't proceed to modify their
1501
      // intersection stacks on that horizontal line while others are
1502
      // potentially still working on the above.
1503
#pragma omp barrier
1504
      vert += n_threads;
3,015✔
1505
    }
1506
  } // end omp parallel
1507

1508
  // Now thicken the wireframe lines and apply them to our image
1509
  for (int vert = 0; vert < pixels()[1]; ++vert) {
3,015✔
1510
    for (int horiz = 0; horiz < pixels()[0]; ++horiz) {
603,000✔
1511
      if (wireframe_initial(horiz, vert)) {
600,000✔
1512
        if (wireframe_thickness_ == 1)
19,359✔
1513
          data(horiz, vert) = wireframe_color_;
8,235✔
1514
        for (int i = -wireframe_thickness_ / 2; i < wireframe_thickness_ / 2;
53,379✔
1515
             ++i)
1516
          for (int j = -wireframe_thickness_ / 2; j < wireframe_thickness_ / 2;
149,148✔
1517
               ++j)
1518
            if (i * i + j * j < wireframe_thickness_ * wireframe_thickness_) {
115,128!
1519

1520
              // Check if wireframe pixel is out of bounds
1521
              int w_i = std::max(std::min(horiz + i, pixels()[0] - 1), 0);
115,128!
1522
              int w_j = std::max(std::min(vert + j, pixels()[1] - 1), 0);
115,164✔
1523
              data(w_i, w_j) = wireframe_color_;
115,128✔
1524
            }
1525
      }
1526
    }
1527
  }
1528

1529
  return data;
30✔
1530
}
30✔
1531

1532
void WireframeRayTracePlot::create_output() const
15✔
1533
{
1534
  ImageData data = create_image();
15✔
1535
  write_image(data);
15✔
1536
}
15✔
1537

1538
void RayTracePlot::print_info() const
24✔
1539
{
1540
  fmt::print("Camera position: {} {} {}\n", camera_position_.x,
48✔
1541
    camera_position_.y, camera_position_.z);
24✔
1542
  fmt::print("Look at: {} {} {}\n", look_at_.x, look_at_.y, look_at_.z);
24✔
1543
  fmt::print(
48✔
1544
    "Horizontal field of view: {} degrees\n", horizontal_field_of_view_);
24✔
1545
  fmt::print("Pixels: {} {}\n", pixels()[0], pixels()[1]);
24✔
1546
}
24✔
1547

1548
void WireframeRayTracePlot::print_info() const
15✔
1549
{
1550
  fmt::print("Plot Type: Wireframe ray-traced\n");
15✔
1551
  RayTracePlot::print_info();
15✔
1552
}
15✔
1553

1554
void WireframeRayTracePlot::set_opacities(pugi::xml_node node)
15✔
1555
{
1556
  xs_.resize(colors_.size(), 1e6); // set to large value for opaque by default
15✔
1557

1558
  for (auto cn : node.children("color")) {
33✔
1559
    // Make sure 3 values are specified for RGB
1560
    double user_xs = std::stod(get_node_value(cn, "xs"));
36✔
1561
    int col_id = std::stoi(get_node_value(cn, "id"));
36✔
1562

1563
    // Add RGB
1564
    if (PlotColorBy::cells == color_by_) {
18!
1565
      if (model::cell_map.find(col_id) != model::cell_map.end()) {
18!
1566
        col_id = model::cell_map[col_id];
18✔
1567
        xs_[col_id] = user_xs;
18✔
1568
      } else {
1569
        warning(fmt::format(
×
1570
          "Could not find cell {} specified in plot {}", col_id, id()));
×
1571
      }
1572
    } else if (PlotColorBy::mats == color_by_) {
×
1573
      if (model::material_map.find(col_id) != model::material_map.end()) {
×
1574
        col_id = model::material_map[col_id];
×
1575
        xs_[col_id] = user_xs;
×
1576
      } else {
1577
        warning(fmt::format(
×
1578
          "Could not find material {} specified in plot {}", col_id, id()));
×
1579
      }
1580
    }
1581
  }
1582
}
15✔
1583

1584
void RayTracePlot::set_orthographic_width(pugi::xml_node node)
24✔
1585
{
1586
  if (check_for_node(node, "orthographic_width")) {
24✔
1587
    double orthographic_width =
3✔
1588
      std::stod(get_node_value(node, "orthographic_width", true));
3✔
1589
    if (orthographic_width < 0.0)
3!
1590
      fatal_error("Requires positive orthographic_width");
×
1591
    orthographic_width_ = orthographic_width;
3✔
1592
  }
1593
}
24✔
1594

1595
void WireframeRayTracePlot::set_wireframe_thickness(pugi::xml_node node)
15✔
1596
{
1597
  if (check_for_node(node, "wireframe_thickness")) {
15✔
1598
    int wireframe_thickness =
6✔
1599
      std::stoi(get_node_value(node, "wireframe_thickness", true));
6✔
1600
    if (wireframe_thickness < 0)
6!
1601
      fatal_error("Requires non-negative wireframe thickness");
×
1602
    wireframe_thickness_ = wireframe_thickness;
6✔
1603
  }
1604
}
15✔
1605

1606
void WireframeRayTracePlot::set_wireframe_ids(pugi::xml_node node)
15✔
1607
{
1608
  if (check_for_node(node, "wireframe_ids")) {
15✔
1609
    wireframe_ids_ = get_node_array<int>(node, "wireframe_ids");
3✔
1610
    // It is read in as actual ID values, but we have to convert to indices in
1611
    // mat/cell array
1612
    for (auto& x : wireframe_ids_)
6✔
1613
      x = color_by_ == PlotColorBy::mats ? model::material_map[x]
6!
1614
                                         : model::cell_map[x];
×
1615
  }
1616
  // We make sure the list is sorted in order to later use
1617
  // std::binary_search.
1618
  std::sort(wireframe_ids_.begin(), wireframe_ids_.end());
15✔
1619
}
15✔
1620

1621
void RayTracePlot::set_pixels(pugi::xml_node node)
24✔
1622
{
1623
  vector<int> pxls = get_node_array<int>(node, "pixels");
24✔
1624
  if (pxls.size() != 2)
24!
1625
    fatal_error(
×
1626
      fmt::format("<pixels> must be length 2 in projection plot {}", id()));
×
1627
  pixels()[0] = pxls[0];
24✔
1628
  pixels()[1] = pxls[1];
24✔
1629
}
24✔
1630

1631
void RayTracePlot::set_camera_position(pugi::xml_node node)
24✔
1632
{
1633
  vector<double> camera_pos = get_node_array<double>(node, "camera_position");
24✔
1634
  if (camera_pos.size() != 3) {
24!
1635
    fatal_error(fmt::format(
×
1636
      "camera_position element must have three floating point values"));
1637
  }
1638
  camera_position_.x = camera_pos[0];
24✔
1639
  camera_position_.y = camera_pos[1];
24✔
1640
  camera_position_.z = camera_pos[2];
24✔
1641
}
24✔
1642

1643
void RayTracePlot::set_look_at(pugi::xml_node node)
24✔
1644
{
1645
  vector<double> look_at = get_node_array<double>(node, "look_at");
24✔
1646
  if (look_at.size() != 3) {
24!
1647
    fatal_error("look_at element must have three floating point values");
×
1648
  }
1649
  look_at_.x = look_at[0];
24✔
1650
  look_at_.y = look_at[1];
24✔
1651
  look_at_.z = look_at[2];
24✔
1652
}
24✔
1653

1654
void RayTracePlot::set_field_of_view(pugi::xml_node node)
24✔
1655
{
1656
  // Defaults to 70 degree horizontal field of view (see .h file)
1657
  if (check_for_node(node, "horizontal_field_of_view")) {
24!
1658
    double fov =
×
1659
      std::stod(get_node_value(node, "horizontal_field_of_view", true));
×
1660
    if (fov < 180.0 && fov > 0.0) {
×
1661
      horizontal_field_of_view_ = fov;
×
1662
    } else {
1663
      fatal_error(fmt::format("Horizontal field of view for plot {} "
×
1664
                              "out-of-range. Must be in (0, 180) degrees.",
1665
        id()));
×
1666
    }
1667
  }
1668
}
24✔
1669

1670
SolidRayTracePlot::SolidRayTracePlot(pugi::xml_node node) : RayTracePlot(node)
9✔
1671
{
1672
  set_opaque_ids(node);
9✔
1673
  set_diffuse_fraction(node);
9✔
1674
  set_light_position(node);
9✔
1675
  update_view();
9✔
1676
}
9✔
1677

1678
void SolidRayTracePlot::print_info() const
9✔
1679
{
1680
  fmt::print("Plot Type: Solid ray-traced\n");
9✔
1681
  RayTracePlot::print_info();
9✔
1682
}
9✔
1683

1684
ImageData SolidRayTracePlot::create_image() const
15✔
1685
{
1686
  size_t width = pixels()[0];
15✔
1687
  size_t height = pixels()[1];
15✔
1688
  ImageData data({width, height}, not_found_);
15✔
1689

1690
#pragma omp parallel for schedule(dynamic) collapse(2)
1691
  for (int horiz = 0; horiz < pixels()[0]; ++horiz) {
1,863✔
1692
    for (int vert = 0; vert < pixels()[1]; ++vert) {
362,136✔
1693
      // RayTracePlot implements camera ray generation
1694
      std::pair<Position, Direction> ru = get_pixel_ray(horiz, vert);
360,288✔
1695
      PhongRay ray(ru.first, ru.second, *this);
360,288✔
1696
      ray.trace();
360,288✔
1697
      data(horiz, vert) = ray.result_color();
360,288✔
1698
    }
360,288✔
1699
  }
1700

1701
  return data;
15✔
UNCOV
1702
}
×
1703

1704
void SolidRayTracePlot::create_output() const
9✔
1705
{
1706
  ImageData data = create_image();
9✔
1707
  write_image(data);
9✔
1708
}
9✔
1709

1710
void SolidRayTracePlot::set_opaque_ids(pugi::xml_node node)
9✔
1711
{
1712
  if (check_for_node(node, "opaque_ids")) {
9!
1713
    auto opaque_ids_tmp = get_node_array<int>(node, "opaque_ids");
9✔
1714

1715
    // It is read in as actual ID values, but we have to convert to indices in
1716
    // mat/cell array
1717
    for (auto& x : opaque_ids_tmp)
27✔
1718
      x = color_by_ == PlotColorBy::mats ? model::material_map[x]
36!
1719
                                         : model::cell_map[x];
×
1720

1721
    opaque_ids_.insert(opaque_ids_tmp.begin(), opaque_ids_tmp.end());
9✔
1722
  }
9✔
1723
}
9✔
1724

1725
void SolidRayTracePlot::set_light_position(pugi::xml_node node)
9✔
1726
{
1727
  if (check_for_node(node, "light_position")) {
9✔
1728
    auto light_pos_tmp = get_node_array<double>(node, "light_position");
3✔
1729

1730
    if (light_pos_tmp.size() != 3)
3!
1731
      fatal_error("Light position must be given as 3D coordinates");
×
1732

1733
    light_location_.x = light_pos_tmp[0];
3✔
1734
    light_location_.y = light_pos_tmp[1];
3✔
1735
    light_location_.z = light_pos_tmp[2];
3✔
1736
  } else {
3✔
1737
    light_location_ = camera_position();
6✔
1738
  }
1739
}
9✔
1740

1741
void SolidRayTracePlot::set_diffuse_fraction(pugi::xml_node node)
9✔
1742
{
1743
  if (check_for_node(node, "diffuse_fraction")) {
9✔
1744
    diffuse_fraction_ = std::stod(get_node_value(node, "diffuse_fraction"));
3✔
1745
    if (diffuse_fraction_ < 0.0 || diffuse_fraction_ > 1.0) {
3!
1746
      fatal_error("Must have 0 <= diffuse fraction <= 1");
×
1747
    }
1748
  }
1749
}
9✔
1750

1751
void ProjectionRay::on_intersection()
643,404✔
1752
{
1753
  // This records a tuple with the following info
1754
  //
1755
  // 1) ID (material or cell depending on color_by_)
1756
  // 2) Distance traveled by the ray through that ID
1757
  // 3) Index of the intersected surface (starting from 1)
1758

1759
  line_segments_.emplace_back(
643,404✔
1760
    plot_.color_by_ == PlottableInterface::PlotColorBy::mats
643,404✔
1761
      ? material()
148,887✔
1762
      : lowest_coord().cell(),
494,517✔
1763
    traversal_distance_, boundary().surface_index());
643,404✔
1764
}
643,404✔
1765

1766
void PhongRay::on_intersection()
247,083✔
1767
{
1768
  // Check if we hit an opaque material or cell
1769
  int hit_id = plot_.color_by_ == PlottableInterface::PlotColorBy::mats
247,083✔
1770
                 ? material()
247,083!
1771
                 : lowest_coord().cell();
×
1772

1773
  // If we are reflected and have advanced beyond the camera,
1774
  // the ray is done. This is checked here because we should
1775
  // kill the ray even if the material is not opaque.
1776
  if (reflected_ && (r() - plot_.camera_position()).dot(u()) >= 0.0) {
247,083!
1777
    stop();
×
1778
    return;
44,820✔
1779
  }
1780

1781
  // Anything that's not opaque has zero impact on the plot.
1782
  if (plot_.opaque_ids_.find(hit_id) == plot_.opaque_ids_.end())
247,083✔
1783
    return;
1784

1785
  if (!reflected_) {
202,263✔
1786
    // reflect the particle and set the color to be colored by
1787
    // the normal or the diffuse lighting contribution
1788
    reflected_ = true;
192,564✔
1789
    result_color_ = plot_.colors_[hit_id];
192,564✔
1790
    // The ray has been advanced slightly past the boundary. Use an
1791
    // approximation to the actual hit point for stable normal/lighting.
1792
    Position r_hit = r() - TINY_BIT * u();
192,564✔
1793
    Direction to_light = plot_.light_location_ - r_hit;
192,564✔
1794
    to_light /= to_light.norm();
192,564✔
1795

1796
    // TODO
1797
    // Not sure what can cause a surface token to be invalid here, although it
1798
    // sometimes happens for a few pixels. It's very very rare, so proceed by
1799
    // coloring the pixel with the overlap color. It seems to happen only for a
1800
    // few pixels on the outer boundary of a hex lattice.
1801
    //
1802
    // We cannot detect it in the outer loop, and it only matters here, so
1803
    // that's why the error handling is a little different than for a lost
1804
    // ray.
1805
    if (surface() == 0) {
192,564!
1806
      result_color_ = plot_.overlap_color_;
×
1807
      stop();
×
1808
      return;
×
1809
    }
1810

1811
    // Get surface pointer
1812
    const auto& surf = model::surfaces.at(surface_index());
192,564✔
1813

1814
    // The crossed surface may be on a higher coordinate level than the
1815
    // innermost local coordinates, so we check the surface's coordinate level
1816
    // to find the appropriate coordinate level to use for the normal
1817
    // calculation
1818
    int surf_level = boundary().coord_level() - 1;
192,564!
1819
    // ensure surface level is within bounds of current coordinate stack
1820
    surf_level = std::max(0, std::min(surf_level, n_coord() - 1));
192,564!
1821

1822
    Position r_hit_level =
192,564✔
1823
      coord(surf_level).r() - TINY_BIT * coord(surf_level).u();
192,564✔
1824
    Direction normal = surf->normal(r_hit_level);
192,564✔
1825
    normal /= normal.norm();
192,564✔
1826

1827
    // Need to apply rotations to find the normal vector in
1828
    // the base level universe's coordinate system.
1829
    for (int lev = surf_level - 1; lev >= 0; --lev) {
192,564!
1830
      if (coord(lev + 1).rotated()) {
×
1831
        const Cell& c {*model::cells[coord(lev).cell()]};
×
1832
        normal = normal.inverse_rotate(c.rotation_);
×
1833
      }
1834
    }
1835

1836
    // use the normal opposed to the ray direction
1837
    if (normal.dot(u()) > 0.0) {
192,564✔
1838
      normal *= -1.0;
17,397✔
1839
    }
1840

1841
    // Facing away from the light means no lighting
1842
    double dotprod = normal.dot(to_light);
192,564✔
1843
    dotprod = std::max(0.0, dotprod);
192,564✔
1844

1845
    double modulation =
192,564✔
1846
      plot_.diffuse_fraction_ + (1.0 - plot_.diffuse_fraction_) * dotprod;
192,564✔
1847
    result_color_ *= modulation;
192,564✔
1848

1849
    // Now point the particle to the camera. We now begin
1850
    // checking to see if it's occluded by another surface
1851
    u() = to_light;
192,564✔
1852

1853
    orig_hit_id_ = hit_id;
192,564✔
1854

1855
    // OpenMC native CSG and DAGMC surfaces have some slight differences
1856
    // in how they interpret particles that are sitting on a surface.
1857
    // I don't know exactly why, but this makes everything work beautifully.
1858
    if (surf->geom_type() == GeometryType::DAG) {
192,564!
1859
      surface() = 0;
×
1860
    } else {
1861
      surface() = -surface(); // go to other side
192,564✔
1862
    }
1863

1864
    // Must fully restart coordinate search. Why? Not sure.
1865
    clear();
192,564✔
1866

1867
    // Note this could likely be faster if we cached the previous
1868
    // cell we were in before the reflection. This is the easiest
1869
    // way to fully initialize all the sub-universe coordinates and
1870
    // directions though.
1871
    bool found = exhaustive_find_cell(*this);
192,564✔
1872
    if (!found) {
192,564!
1873
      fatal_error("Lost particle after reflection.");
×
1874
    }
1875

1876
    // Must recalculate distance to boundary due to the
1877
    // direction change
1878
    compute_distance();
192,564✔
1879

1880
  } else {
1881
    // If it's not facing the light, we color with the diffuse contribution, so
1882
    // next we check if we're going to occlude the last reflected surface. if
1883
    // so, color by the diffuse contribution instead
1884

1885
    if (orig_hit_id_ == -1)
9,699!
1886
      fatal_error("somehow a ray got reflected but not original ID set?");
×
1887

1888
    result_color_ = plot_.colors_[orig_hit_id_];
9,699✔
1889
    result_color_ *= plot_.diffuse_fraction_;
9,699✔
1890
    stop();
202,263✔
1891
  }
1892
}
1893

1894
extern "C" int openmc_id_map(const void* plot, int32_t* data_out)
×
1895
{
1896
  static bool warned {false};
×
1897
  if (!warned) {
×
1898
    warning("openmc_id_map is deprecated and will be removed in a future "
×
1899
            "release. Use openmc_slice_data.");
1900
    warned = true;
×
1901
  }
1902

1903
  auto plt = reinterpret_cast<const SlicePlotBase*>(plot);
×
1904
  if (!plt) {
×
1905
    set_errmsg("Invalid slice pointer passed to openmc_id_map");
×
1906
    return OPENMC_E_INVALID_ARGUMENT;
×
1907
  }
1908

1909
  if (plt->show_overlaps_ && model::overlap_check_count.size() == 0) {
×
1910
    model::overlap_check_count.resize(model::cells.size());
×
1911
  }
1912

1913
  auto ids = plt->get_map<IdData>();
×
1914

1915
  // write id data to array
1916
  std::copy(ids.data_.begin(), ids.data_.end(), data_out);
×
1917

1918
  return 0;
×
1919
}
×
1920

1921
extern "C" int openmc_property_map(const void* plot, double* data_out)
×
1922
{
1923
  static bool warned {false};
×
1924
  if (!warned) {
×
1925
    warning("openmc_property_map is deprecated and will be removed in a future "
×
1926
            "release. Use openmc_slice_data.");
1927
    warned = true;
×
1928
  }
1929

1930
  auto plt = reinterpret_cast<const SlicePlotBase*>(plot);
×
1931
  if (!plt) {
×
1932
    set_errmsg("Invalid slice pointer passed to openmc_property_map");
×
1933
    return OPENMC_E_INVALID_ARGUMENT;
×
1934
  }
1935

1936
  if (plt->show_overlaps_ && model::overlap_check_count.size() == 0) {
×
1937
    model::overlap_check_count.resize(model::cells.size());
×
1938
  }
1939

1940
  auto props = plt->get_map<PropertyData>();
×
1941

1942
  // write id data to array
1943
  std::copy(props.data_.begin(), props.data_.end(), data_out);
×
1944

1945
  return 0;
×
1946
}
×
1947

1948
extern "C" int openmc_slice_data(const double origin[3], const double u_span[3],
117✔
1949
  const double v_span[3], const size_t pixels[2], bool color_overlaps,
1950
  int level, int32_t filter_index, int32_t* geom_data, double* property_data)
1951
{
1952
  // Validate span vectors
1953
  Direction u_span_pos {u_span[0], u_span[1], u_span[2]};
117✔
1954
  Direction v_span_pos {v_span[0], v_span[1], v_span[2]};
117✔
1955
  double u_norm = u_span_pos.norm();
117✔
1956
  double v_norm = v_span_pos.norm();
117✔
1957
  if (u_norm == 0.0 || v_norm == 0.0) {
117!
1958
    set_errmsg("Slice span vectors must be non-zero.");
×
1959
    return OPENMC_E_INVALID_ARGUMENT;
×
1960
  }
1961

1962
  constexpr double ORTHO_REL_TOL = 1e-10;
117✔
1963
  double dot = u_span_pos.dot(v_span_pos);
117!
1964
  if (std::abs(dot) > ORTHO_REL_TOL * u_norm * v_norm) {
117!
1965
    set_errmsg("Slice span vectors must be orthogonal.");
×
1966
    return OPENMC_E_INVALID_ARGUMENT;
×
1967
  }
1968

1969
  // Validate filter index if provided
1970
  if (filter_index >= 0) {
117✔
1971
    if (int err = verify_filter(filter_index))
6!
1972
      return err;
1973
  }
1974

1975
  // Initialize overlap check vector if needed
1976
  if (color_overlaps && model::overlap_check_count.size() == 0) {
117!
1977
    model::overlap_check_count.resize(model::cells.size());
15✔
1978
  }
1979

1980
  try {
117✔
1981
    // Create a temporary SlicePlotBase object to reuse get_map logic
1982
    SlicePlotBase plot_params;
117✔
1983
    plot_params.origin_ = Position {origin[0], origin[1], origin[2]};
117✔
1984
    plot_params.u_span_ = u_span_pos;
117✔
1985
    plot_params.v_span_ = v_span_pos;
117✔
1986
    plot_params.pixels_[0] = pixels[0];
117✔
1987
    plot_params.pixels_[1] = pixels[1];
117✔
1988
    plot_params.show_overlaps_ = color_overlaps;
117✔
1989
    plot_params.slice_level_ = level;
117✔
1990

1991
    // Clear overlap data structures on new slice call
1992
    model::overlap_keys.clear();
117✔
1993
    model::overlap_key_index.clear();
117✔
1994

1995
    // Use get_map<RasterData> to generate data
1996
    auto data = plot_params.get_map<RasterData>(filter_index);
117✔
1997
    std::copy(data.id_data_.begin(), data.id_data_.end(), geom_data);
117✔
1998

1999
    // Copy property data if requested
2000
    if (property_data != nullptr) {
117✔
2001
      std::copy(
21✔
2002
        data.property_data_.begin(), data.property_data_.end(), property_data);
2003
    }
2004
  } catch (const std::exception& e) {
117!
2005
    set_errmsg(e.what());
×
2006
    return OPENMC_E_UNASSIGNED;
×
2007
  }
×
2008

2009
  return 0;
117✔
2010
}
2011

2012
// Gets the number of overlaps that we need data for
2013
extern "C" int openmc_slice_data_overlap_count(size_t* count)
6✔
2014
{
2015
  if (!count) {
6!
2016
    set_errmsg("Null pointer passed for overlap count.");
×
2017
    return OPENMC_E_INVALID_ARGUMENT;
×
2018
  }
2019
  *count = model::overlap_keys.size();
6✔
2020

2021
  return 0;
6✔
2022
}
2023

2024
// Plotter pre-allocates array size based on what is returned with
2025
// overlap_count; populates an array of size 3*count
2026
extern "C" int openmc_slice_data_overlap_info(
3✔
2027
  size_t count, int32_t* overlap_info)
2028
{
2029
  for (size_t i = 0; i < count; ++i) {
9✔
2030
    overlap_info[i * 3] = model::overlap_keys[i].universe_id;
6✔
2031
    overlap_info[i * 3 + 1] = model::overlap_keys[i].cell1_id;
6✔
2032
    overlap_info[i * 3 + 2] = model::overlap_keys[i].cell2_id;
6✔
2033
  }
2034

2035
  return 0;
3✔
2036
}
2037

2038
extern "C" int openmc_get_plot_index(int32_t id, int32_t* index)
6✔
2039
{
2040
  auto it = model::plot_map.find(id);
6!
2041
  if (it == model::plot_map.end()) {
6!
2042
    set_errmsg("No plot exists with ID=" + std::to_string(id) + ".");
×
2043
    return OPENMC_E_INVALID_ID;
×
2044
  }
2045

2046
  *index = it->second;
6✔
2047
  return 0;
6✔
2048
}
2049

2050
extern "C" int openmc_plot_get_id(int32_t index, int32_t* id)
15✔
2051
{
2052
  if (index < 0 || index >= model::plots.size()) {
15!
2053
    set_errmsg("Index in plots array is out of bounds.");
×
2054
    return OPENMC_E_OUT_OF_BOUNDS;
×
2055
  }
2056

2057
  *id = model::plots[index]->id();
15✔
2058
  return 0;
15✔
2059
}
2060

2061
extern "C" int openmc_plot_set_id(int32_t index, int32_t id)
×
2062
{
2063
  if (index < 0 || index >= model::plots.size()) {
×
2064
    set_errmsg("Index in plots array is out of bounds.");
×
2065
    return OPENMC_E_OUT_OF_BOUNDS;
×
2066
  }
2067

2068
  if (id < 0 && id != C_NONE) {
×
2069
    set_errmsg("Invalid plot ID.");
×
2070
    return OPENMC_E_INVALID_ARGUMENT;
×
2071
  }
2072

2073
  auto* plot = model::plots[index].get();
×
2074
  int32_t old_id = plot->id();
×
2075
  if (id == old_id)
×
2076
    return 0;
2077

2078
  model::plot_map.erase(old_id);
×
2079
  try {
×
2080
    plot->set_id(id);
×
2081
  } catch (const std::runtime_error& e) {
×
2082
    model::plot_map[old_id] = index;
×
2083
    set_errmsg(e.what());
×
2084
    return OPENMC_E_INVALID_ID;
×
2085
  }
×
2086
  model::plot_map[plot->id()] = index;
×
2087
  return 0;
×
2088
}
2089

2090
extern "C" size_t openmc_plots_size()
6✔
2091
{
2092
  return model::plots.size();
6✔
2093
}
2094

2095
int map_phong_domain_id(
15✔
2096
  const SolidRayTracePlot* plot, int32_t id, int32_t* index_out)
2097
{
2098
  if (!plot || !index_out) {
15!
2099
    set_errmsg("Invalid plot pointer passed to map_phong_domain_id");
×
2100
    return OPENMC_E_INVALID_ARGUMENT;
×
2101
  }
2102

2103
  if (plot->color_by_ == PlottableInterface::PlotColorBy::mats) {
15!
2104
    auto it = model::material_map.find(id);
15!
2105
    if (it == model::material_map.end()) {
15!
2106
      set_errmsg("Invalid material ID for SolidRayTracePlot");
×
2107
      return OPENMC_E_INVALID_ID;
×
2108
    }
2109
    *index_out = it->second;
15✔
2110
    return 0;
15✔
2111
  }
2112

2113
  if (plot->color_by_ == PlottableInterface::PlotColorBy::cells) {
×
2114
    auto it = model::cell_map.find(id);
×
2115
    if (it == model::cell_map.end()) {
×
2116
      set_errmsg("Invalid cell ID for SolidRayTracePlot");
×
2117
      return OPENMC_E_INVALID_ID;
×
2118
    }
2119
    *index_out = it->second;
×
2120
    return 0;
×
2121
  }
2122

2123
  set_errmsg("Unsupported color_by for SolidRayTracePlot");
×
2124
  return OPENMC_E_INVALID_TYPE;
×
2125
}
2126

2127
int get_solidraytrace_plot_by_index(int32_t index, SolidRayTracePlot** plot)
84✔
2128
{
2129
  if (!plot) {
84!
2130
    set_errmsg("Null output pointer passed to get_solidraytrace_plot_by_index");
×
2131
    return OPENMC_E_INVALID_ARGUMENT;
×
2132
  }
2133

2134
  if (index < 0 || index >= model::plots.size()) {
84!
2135
    set_errmsg("Index in plots array is out of bounds.");
×
2136
    return OPENMC_E_OUT_OF_BOUNDS;
×
2137
  }
2138

2139
  auto* plottable = model::plots[index].get();
84!
2140
  auto* solid_plot = dynamic_cast<SolidRayTracePlot*>(plottable);
84!
2141
  if (!solid_plot) {
84!
2142
    set_errmsg("Plot at index=" + std::to_string(index) +
×
2143
               " is not a solid raytrace plot.");
2144
    return OPENMC_E_INVALID_TYPE;
×
2145
  }
2146

2147
  *plot = solid_plot;
84✔
2148
  return 0;
84✔
2149
}
2150

2151
extern "C" int openmc_solidraytrace_plot_create(int32_t* index)
3✔
2152
{
2153
  if (!index) {
3!
2154
    set_errmsg(
×
2155
      "Null output pointer passed to openmc_solidraytrace_plot_create");
2156
    return OPENMC_E_INVALID_ARGUMENT;
×
2157
  }
2158

2159
  try {
3✔
2160
    auto new_plot = std::make_unique<SolidRayTracePlot>();
3✔
2161
    new_plot->set_id();
3✔
2162
    int32_t new_plot_id = new_plot->id();
3✔
2163
#ifdef USE_LIBPNG
2164
    new_plot->path_plot() = fmt::format("plot_{}.png", new_plot_id);
3✔
2165
#else
2166
    new_plot->path_plot() = fmt::format("plot_{}.ppm", new_plot_id);
2167
#endif
2168
    int32_t new_plot_index = model::plots.size();
3✔
2169
    model::plots.emplace_back(std::move(new_plot));
3✔
2170
    model::plot_map[new_plot_id] = new_plot_index;
3✔
2171
    *index = new_plot_index;
3✔
2172
  } catch (const std::exception& e) {
3!
2173
    set_errmsg(e.what());
×
2174
    return OPENMC_E_ALLOCATE;
×
2175
  }
×
2176

2177
  return 0;
3✔
2178
}
2179

2180
extern "C" int openmc_solidraytrace_plot_get_pixels(
9✔
2181
  int32_t index, int32_t* width, int32_t* height)
2182
{
2183
  if (!width || !height) {
9!
2184
    set_errmsg(
×
2185
      "Invalid arguments passed to openmc_solidraytrace_plot_get_pixels");
2186
    return OPENMC_E_INVALID_ARGUMENT;
×
2187
  }
2188

2189
  SolidRayTracePlot* plt = nullptr;
9✔
2190
  int err = get_solidraytrace_plot_by_index(index, &plt);
9✔
2191
  if (err)
9!
2192
    return err;
2193

2194
  *width = plt->pixels()[0];
9✔
2195
  *height = plt->pixels()[1];
9✔
2196
  return 0;
9✔
2197
}
2198

2199
extern "C" int openmc_solidraytrace_plot_set_pixels(
3✔
2200
  int32_t index, int32_t width, int32_t height)
2201
{
2202
  if (width <= 0 || height <= 0) {
3!
2203
    set_errmsg(
×
2204
      "Invalid arguments passed to openmc_solidraytrace_plot_set_pixels");
2205
    return OPENMC_E_INVALID_ARGUMENT;
×
2206
  }
2207

2208
  SolidRayTracePlot* plt = nullptr;
3✔
2209
  int err = get_solidraytrace_plot_by_index(index, &plt);
3✔
2210
  if (err)
3!
2211
    return err;
2212

2213
  plt->pixels()[0] = width;
3✔
2214
  plt->pixels()[1] = height;
3✔
2215
  return 0;
3✔
2216
}
2217

2218
extern "C" int openmc_solidraytrace_plot_get_color_by(
3✔
2219
  int32_t index, int32_t* color_by)
2220
{
2221
  if (!color_by) {
3!
2222
    set_errmsg(
×
2223
      "Invalid arguments passed to openmc_solidraytrace_plot_get_color_by");
2224
    return OPENMC_E_INVALID_ARGUMENT;
×
2225
  }
2226

2227
  SolidRayTracePlot* plt = nullptr;
3✔
2228
  int err = get_solidraytrace_plot_by_index(index, &plt);
3✔
2229
  if (err)
3!
2230
    return err;
2231

2232
  if (plt->color_by_ == PlottableInterface::PlotColorBy::mats) {
3!
2233
    *color_by = 0;
3✔
2234
  } else if (plt->color_by_ == PlottableInterface::PlotColorBy::cells) {
×
2235
    *color_by = 1;
×
2236
  } else {
2237
    set_errmsg("Unsupported color_by for SolidRayTracePlot");
×
2238
    return OPENMC_E_INVALID_TYPE;
×
2239
  }
2240

2241
  return 0;
2242
}
2243

2244
extern "C" int openmc_solidraytrace_plot_set_color_by(
3✔
2245
  int32_t index, int32_t color_by)
2246
{
2247
  SolidRayTracePlot* plt = nullptr;
3✔
2248
  int err = get_solidraytrace_plot_by_index(index, &plt);
3✔
2249
  if (err)
3!
2250
    return err;
2251

2252
  if (color_by == 0) {
3!
2253
    plt->color_by_ = PlottableInterface::PlotColorBy::mats;
3✔
2254
  } else if (color_by == 1) {
×
2255
    plt->color_by_ = PlottableInterface::PlotColorBy::cells;
×
2256
  } else {
2257
    set_errmsg("Invalid color_by value for SolidRayTracePlot");
×
2258
    return OPENMC_E_INVALID_ARGUMENT;
×
2259
  }
2260

2261
  return 0;
2262
}
2263

2264
extern "C" int openmc_solidraytrace_plot_set_default_colors(int32_t index)
3✔
2265
{
2266
  SolidRayTracePlot* plt = nullptr;
3✔
2267
  int err = get_solidraytrace_plot_by_index(index, &plt);
3✔
2268
  if (err)
3!
2269
    return err;
2270

2271
  plt->set_default_colors();
3✔
2272
  return 0;
2273
}
2274

2275
extern "C" int openmc_solidraytrace_plot_set_all_opaque(int32_t index)
×
2276
{
2277
  SolidRayTracePlot* plt = nullptr;
×
2278
  int err = get_solidraytrace_plot_by_index(index, &plt);
×
2279
  if (err)
×
2280
    return err;
2281

2282
  plt->opaque_ids().clear();
×
2283
  if (plt->color_by_ == PlottableInterface::PlotColorBy::mats) {
×
2284
    for (int32_t i = 0; i < model::materials.size(); ++i) {
×
2285
      plt->opaque_ids().insert(i);
×
2286
    }
2287
    return 0;
×
2288
  }
2289

2290
  if (plt->color_by_ == PlottableInterface::PlotColorBy::cells) {
×
2291
    for (int32_t i = 0; i < model::cells.size(); ++i) {
×
2292
      plt->opaque_ids().insert(i);
×
2293
    }
2294
    return 0;
×
2295
  }
2296

2297
  set_errmsg("Unsupported color_by for SolidRayTracePlot");
×
2298
  return OPENMC_E_INVALID_TYPE;
×
2299
}
2300

2301
extern "C" int openmc_solidraytrace_plot_set_opaque(
6✔
2302
  int32_t index, int32_t id, bool visible)
2303
{
2304
  SolidRayTracePlot* plt = nullptr;
6✔
2305
  int err = get_solidraytrace_plot_by_index(index, &plt);
6✔
2306
  if (err)
6!
2307
    return err;
2308

2309
  int32_t domain_index = -1;
6✔
2310
  err = map_phong_domain_id(plt, id, &domain_index);
6✔
2311
  if (err)
6!
2312
    return err;
2313

2314
  if (visible) {
6✔
2315
    plt->opaque_ids().insert(domain_index);
3✔
2316
  } else {
2317
    plt->opaque_ids().erase(domain_index);
3✔
2318
  }
2319

2320
  return 0;
2321
}
2322

2323
extern "C" int openmc_solidraytrace_plot_set_color(
6✔
2324
  int32_t index, int32_t id, uint8_t r, uint8_t g, uint8_t b)
2325
{
2326
  SolidRayTracePlot* plt = nullptr;
6✔
2327
  int err = get_solidraytrace_plot_by_index(index, &plt);
6✔
2328
  if (err)
6!
2329
    return err;
2330

2331
  int32_t domain_index = -1;
6✔
2332
  err = map_phong_domain_id(plt, id, &domain_index);
6✔
2333
  if (err)
6!
2334
    return err;
2335

2336
  if (domain_index < 0 ||
6!
2337
      static_cast<size_t>(domain_index) >= plt->colors_.size()) {
6!
2338
    set_errmsg("Color index out of range for SolidRayTracePlot");
×
2339
    return OPENMC_E_OUT_OF_BOUNDS;
×
2340
  }
2341

2342
  plt->colors_[domain_index] = RGBColor(r, g, b);
6✔
2343
  return 0;
6✔
2344
}
2345

2346
extern "C" int openmc_solidraytrace_plot_get_camera_position(
3✔
2347
  int32_t index, double* x, double* y, double* z)
2348
{
2349
  if (!x || !y || !z) {
3!
2350
    set_errmsg("Invalid arguments passed to "
×
2351
               "openmc_solidraytrace_plot_get_camera_position");
2352
    return OPENMC_E_INVALID_ARGUMENT;
×
2353
  }
2354

2355
  SolidRayTracePlot* plt = nullptr;
3✔
2356
  int err = get_solidraytrace_plot_by_index(index, &plt);
3✔
2357
  if (err)
3!
2358
    return err;
2359

2360
  const auto& camera_position = plt->camera_position();
3✔
2361
  *x = camera_position.x;
3✔
2362
  *y = camera_position.y;
3✔
2363
  *z = camera_position.z;
3✔
2364
  return 0;
3✔
2365
}
2366

2367
extern "C" int openmc_solidraytrace_plot_set_camera_position(
3✔
2368
  int32_t index, double x, double y, double z)
2369
{
2370
  SolidRayTracePlot* plt = nullptr;
3✔
2371
  int err = get_solidraytrace_plot_by_index(index, &plt);
3✔
2372
  if (err)
3!
2373
    return err;
2374

2375
  plt->camera_position() = {x, y, z};
3✔
2376
  return 0;
3✔
2377
}
2378

2379
extern "C" int openmc_solidraytrace_plot_get_look_at(
3✔
2380
  int32_t index, double* x, double* y, double* z)
2381
{
2382
  if (!x || !y || !z) {
3!
2383
    set_errmsg(
×
2384
      "Invalid arguments passed to openmc_solidraytrace_plot_get_look_at");
2385
    return OPENMC_E_INVALID_ARGUMENT;
×
2386
  }
2387

2388
  SolidRayTracePlot* plt = nullptr;
3✔
2389
  int err = get_solidraytrace_plot_by_index(index, &plt);
3✔
2390
  if (err)
3!
2391
    return err;
2392

2393
  const auto& look_at = plt->look_at();
3✔
2394
  *x = look_at.x;
3✔
2395
  *y = look_at.y;
3✔
2396
  *z = look_at.z;
3✔
2397
  return 0;
3✔
2398
}
2399

2400
extern "C" int openmc_solidraytrace_plot_set_look_at(
3✔
2401
  int32_t index, double x, double y, double z)
2402
{
2403
  SolidRayTracePlot* plt = nullptr;
3✔
2404
  int err = get_solidraytrace_plot_by_index(index, &plt);
3✔
2405
  if (err)
3!
2406
    return err;
2407

2408
  plt->look_at() = {x, y, z};
3✔
2409
  return 0;
3✔
2410
}
2411

2412
extern "C" int openmc_solidraytrace_plot_get_up(
3✔
2413
  int32_t index, double* x, double* y, double* z)
2414
{
2415
  if (!x || !y || !z) {
3!
2416
    set_errmsg("Invalid arguments passed to openmc_solidraytrace_plot_get_up");
×
2417
    return OPENMC_E_INVALID_ARGUMENT;
×
2418
  }
2419

2420
  SolidRayTracePlot* plt = nullptr;
3✔
2421
  int err = get_solidraytrace_plot_by_index(index, &plt);
3✔
2422
  if (err)
3!
2423
    return err;
2424

2425
  const auto& up = plt->up();
3✔
2426
  *x = up.x;
3✔
2427
  *y = up.y;
3✔
2428
  *z = up.z;
3✔
2429
  return 0;
3✔
2430
}
2431

2432
extern "C" int openmc_solidraytrace_plot_set_up(
3✔
2433
  int32_t index, double x, double y, double z)
2434
{
2435
  SolidRayTracePlot* plt = nullptr;
3✔
2436
  int err = get_solidraytrace_plot_by_index(index, &plt);
3✔
2437
  if (err)
3!
2438
    return err;
2439

2440
  plt->up() = {x, y, z};
3✔
2441
  return 0;
3✔
2442
}
2443

2444
extern "C" int openmc_solidraytrace_plot_get_light_position(
3✔
2445
  int32_t index, double* x, double* y, double* z)
2446
{
2447
  if (!x || !y || !z) {
3!
2448
    set_errmsg("Invalid arguments passed to "
×
2449
               "openmc_solidraytrace_plot_get_light_position");
2450
    return OPENMC_E_INVALID_ARGUMENT;
×
2451
  }
2452

2453
  SolidRayTracePlot* plt = nullptr;
3✔
2454
  int err = get_solidraytrace_plot_by_index(index, &plt);
3✔
2455
  if (err)
3!
2456
    return err;
2457

2458
  const auto& light_position = plt->light_location();
3✔
2459
  *x = light_position.x;
3✔
2460
  *y = light_position.y;
3✔
2461
  *z = light_position.z;
3✔
2462
  return 0;
3✔
2463
}
2464

2465
extern "C" int openmc_solidraytrace_plot_set_light_position(
3✔
2466
  int32_t index, double x, double y, double z)
2467
{
2468
  SolidRayTracePlot* plt = nullptr;
3✔
2469
  int err = get_solidraytrace_plot_by_index(index, &plt);
3✔
2470
  if (err)
3!
2471
    return err;
2472

2473
  plt->light_location() = {x, y, z};
3✔
2474
  return 0;
3✔
2475
}
2476

2477
extern "C" int openmc_solidraytrace_plot_get_fov(int32_t index, double* fov)
3✔
2478
{
2479
  if (!fov) {
3!
2480
    set_errmsg("Invalid arguments passed to openmc_solidraytrace_plot_get_fov");
×
2481
    return OPENMC_E_INVALID_ARGUMENT;
×
2482
  }
2483

2484
  SolidRayTracePlot* plt = nullptr;
3✔
2485
  int err = get_solidraytrace_plot_by_index(index, &plt);
3✔
2486
  if (err)
3!
2487
    return err;
2488

2489
  *fov = plt->horizontal_field_of_view();
3✔
2490
  return 0;
3✔
2491
}
2492

2493
extern "C" int openmc_solidraytrace_plot_set_fov(int32_t index, double fov)
3✔
2494
{
2495
  SolidRayTracePlot* plt = nullptr;
3✔
2496
  int err = get_solidraytrace_plot_by_index(index, &plt);
3✔
2497
  if (err)
3!
2498
    return err;
2499

2500
  plt->horizontal_field_of_view() = fov;
3✔
2501
  return 0;
3✔
2502
}
2503

2504
extern "C" int openmc_solidraytrace_plot_update_view(int32_t index)
6✔
2505
{
2506
  SolidRayTracePlot* plt = nullptr;
6✔
2507
  int err = get_solidraytrace_plot_by_index(index, &plt);
6✔
2508
  if (err)
6!
2509
    return err;
2510

2511
  plt->update_view();
6✔
2512
  return 0;
2513
}
2514

2515
extern "C" int openmc_solidraytrace_plot_create_image(
6✔
2516
  int32_t index, uint8_t* data_out, int32_t width, int32_t height)
2517
{
2518
  if (!data_out || width <= 0 || height <= 0) {
6!
2519
    set_errmsg(
×
2520
      "Invalid arguments passed to openmc_solidraytrace_plot_create_image");
2521
    return OPENMC_E_INVALID_ARGUMENT;
×
2522
  }
2523

2524
  SolidRayTracePlot* plt = nullptr;
6✔
2525
  int err = get_solidraytrace_plot_by_index(index, &plt);
6✔
2526
  if (err)
6!
2527
    return err;
2528

2529
  if (plt->pixels()[0] != width || plt->pixels()[1] != height) {
6!
2530
    set_errmsg(
×
2531
      "Requested image size does not match SolidRayTracePlot pixel settings");
2532
    return OPENMC_E_INVALID_SIZE;
×
2533
  }
2534

2535
  ImageData data = plt->create_image();
6✔
2536
  if (static_cast<int32_t>(data.shape()[0]) != width ||
6!
2537
      static_cast<int32_t>(data.shape()[1]) != height) {
6!
2538
    set_errmsg("Unexpected image size from SolidRayTracePlot create_image");
×
2539
    return OPENMC_E_INVALID_SIZE;
×
2540
  }
2541

2542
  for (int32_t y = 0; y < height; ++y) {
42✔
2543
    for (int32_t x = 0; x < width; ++x) {
324✔
2544
      const auto& color = data(x, y);
288✔
2545
      size_t idx = (static_cast<size_t>(y) * width + x) * 3;
288✔
2546
      data_out[idx + 0] = color.red;
288✔
2547
      data_out[idx + 1] = color.green;
288✔
2548
      data_out[idx + 2] = color.blue;
288✔
2549
    }
2550
  }
2551

2552
  return 0;
2553
}
6✔
2554

2555
extern "C" int openmc_solidraytrace_plot_get_color(
3✔
2556
  int32_t index, int32_t id, uint8_t* r, uint8_t* g, uint8_t* b)
2557
{
2558
  if (!r || !g || !b) {
3!
2559
    set_errmsg(
×
2560
      "Invalid arguments passed to openmc_solidraytrace_plot_get_color");
2561
    return OPENMC_E_INVALID_ARGUMENT;
×
2562
  }
2563

2564
  SolidRayTracePlot* plt = nullptr;
3✔
2565
  int err = get_solidraytrace_plot_by_index(index, &plt);
3✔
2566
  if (err)
3!
2567
    return err;
2568

2569
  int32_t domain_index = -1;
3✔
2570
  err = map_phong_domain_id(plt, id, &domain_index);
3✔
2571
  if (err)
3!
2572
    return err;
2573

2574
  if (domain_index < 0 ||
3!
2575
      static_cast<size_t>(domain_index) >= plt->colors_.size()) {
3!
2576
    set_errmsg("Color index out of range for SolidRayTracePlot");
×
2577
    return OPENMC_E_OUT_OF_BOUNDS;
×
2578
  }
2579

2580
  const auto& color = plt->colors_[domain_index];
3✔
2581
  *r = color.red;
3✔
2582
  *g = color.green;
3✔
2583
  *b = color.blue;
3✔
2584
  return 0;
3✔
2585
}
2586

2587
extern "C" int openmc_solidraytrace_plot_get_diffuse_fraction(
3✔
2588
  int32_t index, double* diffuse_fraction)
2589
{
2590
  if (!diffuse_fraction) {
3!
2591
    set_errmsg("Invalid arguments passed to "
×
2592
               "openmc_solidraytrace_plot_get_diffuse_fraction");
2593
    return OPENMC_E_INVALID_ARGUMENT;
×
2594
  }
2595

2596
  SolidRayTracePlot* plt = nullptr;
3✔
2597
  int err = get_solidraytrace_plot_by_index(index, &plt);
3✔
2598
  if (err)
3!
2599
    return err;
2600

2601
  *diffuse_fraction = plt->diffuse_fraction();
3✔
2602
  return 0;
3✔
2603
}
2604

2605
extern "C" int openmc_solidraytrace_plot_set_diffuse_fraction(
3✔
2606
  int32_t index, double diffuse_fraction)
2607
{
2608
  SolidRayTracePlot* plt = nullptr;
3✔
2609
  int err = get_solidraytrace_plot_by_index(index, &plt);
3✔
2610
  if (err)
3!
2611
    return err;
2612

2613
  if (diffuse_fraction < 0.0 || diffuse_fraction > 1.0) {
3!
2614
    set_errmsg("Diffuse fraction must be between 0 and 1");
×
2615
    return OPENMC_E_INVALID_ARGUMENT;
×
2616
  }
2617

2618
  plt->diffuse_fraction() = diffuse_fraction;
3✔
2619
  return 0;
3✔
2620
}
2621

2622
} // namespace openmc
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc