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

openmc-dev / openmc / 29052849368

09 Jul 2026 09:53PM UTC coverage: 81.29% (+0.01%) from 81.28%
29052849368

Pull #4006

github

web-flow
Merge 1b1346d52 into 3cdb67e50
Pull Request #4006: Support cell densities per instances in plots

18198 of 26402 branches covered (68.93%)

Branch coverage included in aggregate %.

4 of 6 new or added lines in 2 files covered. (66.67%)

1 existing line in 1 file now uncovered.

59366 of 69014 relevant lines covered (86.02%)

48644690.94 hits per line

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

69.71
/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*/)
4,873✔
49
  : data_({v_res, h_res, 3}, NOT_FOUND)
4,873✔
50
{}
4,873✔
51

52
void IdData::set_value(size_t y, size_t x, const Particle& p, int level,
35,403,192✔
53
  Filter* /*filter*/, FilterMatch* /*match*/)
54
{
55
  // set cell data
56
  if (p.n_coord() <= level) {
35,403,192!
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_;
35,403,192!
61
    data_(y, x, 1) = level == p.n_coord() - 1
35,403,192✔
62
                       ? p.cell_instance()
35,403,192!
63
                       : cell_instance_at_level(p, level);
×
64
  }
65

66
  // set material data
67
  Cell* c = model::cells.at(p.lowest_coord().cell()).get();
35,403,192✔
68
  if (p.material() == MATERIAL_VOID) {
35,403,192✔
69
    data_(y, x, 2) = MATERIAL_VOID;
27,301,736✔
70
  } else if (c->type_ == Fill::MATERIAL) {
8,101,456!
71
    Material* m = model::materials.at(p.material()).get();
8,101,456✔
72
    data_(y, x, 2) = m->id_;
8,101,456✔
73
  }
74
}
35,403,192✔
75

76
void IdData::set_overlap(size_t y, size_t x, int /*overlap_idx*/)
28,248✔
77
{
78
  for (size_t k = 0; k < data_.shape(2); ++k)
225,984!
79
    data_(y, x, k) = OVERLAP;
84,744✔
80
}
28,248✔
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;
×
NEW
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)
432✔
104
  : id_data_({v_res, h_res, include_filter ? 4u : 3u}, NOT_FOUND),
842✔
105
    property_data_({v_res, h_res, 2}, static_cast<double>(NOT_FOUND)),
432✔
106
    include_filter_(include_filter)
432✔
107
{}
432✔
108

109
void RasterData::set_value(size_t y, size_t x, const Particle& p, int level,
3,747,753✔
110
  Filter* filter, FilterMatch* match)
111
{
112
  // set cell data
113
  if (p.n_coord() <= level) {
3,747,753!
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_;
3,747,753!
118
    id_data_(y, x, 1) = level == p.n_coord() - 1
3,747,753✔
119
                          ? p.cell_instance()
3,747,753!
120
                          : cell_instance_at_level(p, level);
×
121
  }
122

123
  // set material data
124
  Cell* c = model::cells.at(p.lowest_coord().cell()).get();
3,747,753✔
125
  if (p.material() == MATERIAL_VOID) {
3,747,753✔
126
    id_data_(y, x, 2) = MATERIAL_VOID;
2,548,124✔
127
  } else if (c->type_ == Fill::MATERIAL) {
1,199,629!
128
    Material* m = model::materials.at(p.material()).get();
1,199,629✔
129
    id_data_(y, x, 2) = m->id_;
1,199,629✔
130
  }
131

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

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

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

154
void RasterData::set_overlap(size_t y, size_t x, int overlap_idx)
365,772✔
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;
365,772✔
160
  id_data_(y, x, 1) = OVERLAP;
365,772✔
161
  id_data_(y, x, 2) = OVERLAP;
365,772✔
162

163
  property_data_(y, x, 0) = OVERLAP;
365,772✔
164
  property_data_(y, x, 1) = OVERLAP;
365,772✔
165
}
365,772✔
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()
121✔
184
{
185

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

191
  return 0;
121✔
192
}
193

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

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

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

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

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

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

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

257
void read_plots_xml()
1,399✔
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";
1,399✔
263
  if (!file_exists(filename) && settings::run_mode == RunMode::PLOTTING) {
1,399!
264
    fatal_error(fmt::format("Plots XML file '{}' does not exist!", filename));
×
265
  }
266

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

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

273
  pugi::xml_node root = doc.document_element();
1,399✔
274

275
  read_plots_xml(root);
1,399✔
276
}
1,399✔
277

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

286
    if (check_for_node(node, "type")) {
979!
287
      std::string type_str = get_node_value(node, "type", true);
979✔
288
      if (type_str == "slice") {
979✔
289
        model::plots.emplace_back(
827✔
290
          std::make_unique<Plot>(node, Plot::PlotType::slice));
1,663✔
291
      } else if (type_str == "voxel") {
143✔
292
        model::plots.emplace_back(
55✔
293
          std::make_unique<Plot>(node, Plot::PlotType::voxel));
110✔
294
      } else if (type_str == "wireframe_raytrace") {
88✔
295
        model::plots.emplace_back(
55✔
296
          std::make_unique<WireframeRayTracePlot>(node));
110✔
297
      } else if (type_str == "solid_raytrace") {
33!
298
        model::plots.emplace_back(std::make_unique<SolidRayTracePlot>(node));
33✔
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;
970✔
304
    } else {
970✔
305
      fatal_error(fmt::format("Must specify plot type in plot {}", plot_desc));
×
306
    }
307
  }
970✔
308
}
1,876✔
309

310
void free_memory_plot()
9,012✔
311
{
312
  model::plots.clear();
9,012✔
313
  model::plot_map.clear();
9,012✔
314
}
9,012✔
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
143✔
319
{
320
  size_t width = pixels()[0];
143✔
321
  size_t height = pixels()[1];
143✔
322

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

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

328
  // assign colors
329
  for (size_t y = 0; y < height; y++) {
30,063✔
330
    for (size_t x = 0; x < width; x++) {
7,622,120✔
331
      int idx = color_by_ == PlotColorBy::cells ? 0 : 2;
7,592,200✔
332
      auto id = ids.data_(y, x, idx);
7,592,200✔
333
      // no setting needed if not found
334
      if (id == NOT_FOUND) {
7,592,200✔
335
        continue;
1,082,532✔
336
      }
337
      if (id == OVERLAP) {
6,537,916✔
338
        data(x, y) = overlap_color_;
28,248✔
339
        continue;
28,248✔
340
      }
341
      if (PlotColorBy::cells == color_by_) {
6,509,668✔
342
        data(x, y) = colors_[model::cell_map[id]];
3,011,668✔
343
      } else if (PlotColorBy::mats == color_by_) {
3,498,000!
344
        if (id == MATERIAL_VOID) {
3,498,000!
345
          data(x, y) = WHITE;
×
346
          continue;
×
347
        }
348
        data(x, y) = colors_[model::material_map[id]];
3,498,000✔
349
      } // color_by if-else
350
    }
351
  }
352

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

358
  return data;
143✔
359
}
143✔
360

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

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

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

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

388
  if (id_ == id)
990!
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()) {
990!
393
    throw std::runtime_error {
×
394
      fmt::format("Two or more plots use the same unique ID: {}", id)};
×
395
  }
396

397
  id_ = id;
990✔
398
}
399

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

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

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

443
  path_plot_ = filename;
882✔
444

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

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

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

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

512
void Plot::set_width(pugi::xml_node plot_node)
882✔
513
{
514
  // Copy plotting width
515
  vector<double> pl_width = get_node_array<double>(plot_node, "width");
882✔
516
  if (PlotType::slice == type_) {
882✔
517
    if (pl_width.size() == 2) {
827!
518
      width_.x = pl_width[0];
827✔
519
      width_.y = pl_width[1];
827✔
520
      switch (basis_) {
827!
521
      case PlotBasis::xy:
753✔
522
        u_span_ = {width_.x, 0.0, 0.0};
753✔
523
        v_span_ = {0.0, width_.y, 0.0};
753✔
524
        break;
753✔
525
      case PlotBasis::xz:
22✔
526
        u_span_ = {width_.x, 0.0, 0.0};
22✔
527
        v_span_ = {0.0, 0.0, width_.y};
22✔
528
        break;
22✔
529
      case PlotBasis::yz:
52✔
530
        u_span_ = {0.0, width_.x, 0.0};
52✔
531
        v_span_ = {0.0, 0.0, width_.y};
52✔
532
        break;
52✔
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_) {
55!
541
    if (pl_width.size() == 3) {
55!
542
      pl_width = get_node_array<double>(plot_node, "width");
110✔
543
      width_ = pl_width;
55✔
544
    } else {
545
      fatal_error(
×
546
        fmt::format("<width> must be length 3 in voxel plot {}", id()));
×
547
    }
548
  }
549
}
882✔
550

551
void PlottableInterface::set_universe(pugi::xml_node plot_node)
979✔
552
{
553
  // Copy plot universe level
554
  if (check_for_node(plot_node, "level")) {
979!
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;
979✔
561
  }
562
}
979✔
563

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

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

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

599
void PlottableInterface::set_user_colors(pugi::xml_node plot_node)
979✔
600
{
601
  for (auto cn : plot_node.children("color")) {
1,166✔
602
    // Make sure 3 values are specified for RGB
603
    vector<int> user_rgb = get_node_array<int>(cn, "rgb");
187✔
604
    if (user_rgb.size() != 3) {
187!
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;
187✔
609
    if (check_for_node(cn, "id")) {
187!
610
      col_id = std::stoi(get_node_value(cn, "id"));
374✔
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_) {
187✔
617
      if (model::cell_map.find(col_id) != model::cell_map.end()) {
88!
618
        col_id = model::cell_map[col_id];
88✔
619
        colors_[col_id] = user_rgb;
88✔
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_) {
99!
625
      if (model::material_map.find(col_id) != model::material_map.end()) {
99!
626
        col_id = model::material_map[col_id];
99✔
627
        colors_[col_id] = user_rgb;
99✔
628
      } else {
629
        warning(fmt::format(
×
630
          "Could not find material {} specified in plot {}", col_id, id()));
×
631
      }
632
    }
633
  } // color node loop
187✔
634
}
979✔
635

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

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

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

650
      // Check mesh type
651
      std::string meshtype;
33✔
652
      if (check_for_node(meshlines_node, "meshtype")) {
33!
653
        meshtype = get_node_value(meshlines_node, "meshtype");
33✔
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;
33✔
662
      if (check_for_node(meshlines_node, "linewidth")) {
33!
663
        meshline_width = get_node_value(meshlines_node, "linewidth");
33✔
664
        meshlines_width_ = std::stoi(meshline_width);
33✔
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")) {
33!
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;
×
UNCOV
680
      }
×
681

682
      // Set mesh based on type
683
      if ("ufs" == meshtype) {
33!
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) {
33✔
700
        if (!simulation::entropy_mesh) {
22!
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) {
55✔
705
            if (const auto* m =
66✔
706
                  dynamic_cast<const RegularMesh*>(model::meshes[i].get())) {
55!
707
              if (m == simulation::entropy_mesh) {
22!
708
                index_meshlines_mesh_ = i;
22✔
709
              }
710
            }
711
          }
712
          if (index_meshlines_mesh_ == -1)
22!
713
            fatal_error("Could not find the entropy mesh for meshlines plot");
×
714
        }
715
      } else if ("tally" == meshtype) {
11!
716
        // Ensure that there is a mesh id if the type is tally
717
        int tally_mesh_id;
11✔
718
        if (check_for_node(meshlines_node, "id")) {
11!
719
          tally_mesh_id = std::stoi(get_node_value(meshlines_node, "id"));
22✔
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;
11✔
728
        int err = openmc_get_mesh_index(tally_mesh_id, &idx);
11✔
729
        if (err != 0) {
11!
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;
11✔
735
      } else {
736
        fatal_error(fmt::format("Invalid type for meshlines on plot {}", id()));
×
737
      }
738
    } else {
33✔
739
      fatal_error(fmt::format("Mutliple meshlines specified in plot {}", id()));
×
740
    }
741
  }
742
}
882✔
743

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

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

754
      // Determine how many components there are and allocate
755
      vector<int> iarray = get_node_array<int>(mask_node, "components");
33✔
756
      if (iarray.size() == 0) {
33!
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) {
99✔
764
        if (PlotColorBy::cells == color_by_) {
66!
765
          if (model::cell_map.find(col_id) != model::cell_map.end()) {
66!
766
            col_id = model::cell_map[col_id];
66✔
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++) {
132✔
785
        if (contains(iarray, j)) {
99✔
786
          if (check_for_node(mask_node, "background")) {
66!
787
            vector<int> bg_rgb = get_node_array<int>(mask_node, "background");
66✔
788
            colors_[j] = bg_rgb;
66✔
789
          } else {
66✔
790
            colors_[j] = WHITE;
×
791
          }
792
        }
793
      }
794

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

801
void PlottableInterface::set_overlap_color(pugi::xml_node plot_node)
979✔
802
{
803
  color_overlaps_ = false;
979✔
804
  if (check_for_node(plot_node, "show_overlaps")) {
979✔
805
    color_overlaps_ = get_node_value_bool(plot_node, "show_overlaps");
22✔
806
    // check for custom overlap color
807
    if (check_for_node(plot_node, "overlap_color")) {
22✔
808
      if (!color_overlaps_) {
11!
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");
11✔
814
      if (olap_clr.size() == 3) {
11!
815
        overlap_color_ = olap_clr;
11✔
816
      } else {
817
        fatal_error(fmt::format("Bad overlap RGB in plot {}", id()));
×
818
      }
819
    }
11✔
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) {
979!
825
    settings::check_overlaps = true;
22✔
826
    model::overlap_check_count.resize(model::cells.size(), 0);
22✔
827
  }
828
}
979✔
829

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

842
Plot::Plot(pugi::xml_node plot_node, PlotType type)
891✔
843
  : PlottableInterface(plot_node), type_(type), index_meshlines_mesh_ {-1}
891✔
844
{
845
  set_output_path(plot_node);
891✔
846
  set_basis(plot_node);
882✔
847
  set_origin(plot_node);
882✔
848
  set_width(plot_node);
882✔
849
  set_meshlines(plot_node);
882✔
850
  slice_level_ = level_; // Copy level employed in SlicePlotBase::get_map
882✔
851
  show_overlaps_ = color_overlaps_;
882✔
852
}
882✔
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)
231✔
890
{
891
  // Open PNG file for writing
892
  std::string fname = filename;
231✔
893
  fname = strtrim(fname);
231✔
894
  auto fp = std::fopen(fname.c_str(), "wb");
231✔
895

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

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

905
  png_init_io(png_ptr, fp);
231✔
906

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

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

917
  // Write color for each pixel
918
  for (int y = 0; y < height; y++) {
47,751✔
919
    for (int x = 0; x < width; x++) {
11,159,720✔
920
      RGBColor rgb = data(x, y);
11,112,200✔
921
      row[3 * x] = rgb.red;
11,112,200✔
922
      row[3 * x + 1] = rgb.green;
11,112,200✔
923
      row[3 * x + 2] = rgb.blue;
11,112,200✔
924
    }
925
    png_write_row(png_ptr, row.data());
47,520✔
926
  }
927

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

931
  // Clean up data structures
932
  std::fclose(fp);
231✔
933
  png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
231✔
934
  png_destroy_write_struct(&png_ptr, &info_ptr);
231✔
935
}
231✔
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
33✔
943
{
944
  RGBColor rgb;
33!
945
  rgb = meshlines_color_;
33✔
946

947
  int ax1, ax2;
33✔
948
  Position expected_u {};
33✔
949
  Position expected_v {};
33✔
950
  switch (basis_) {
33!
951
  case PlotBasis::xy:
22✔
952
    ax1 = 0;
22✔
953
    ax2 = 1;
22✔
954
    expected_u = {width_[0], 0.0, 0.0};
22✔
955
    expected_v = {0.0, width_[1], 0.0};
22✔
956
    break;
22✔
957
  case PlotBasis::xz:
11✔
958
    ax1 = 0;
11✔
959
    ax2 = 2;
11✔
960
    expected_u = {width_[0], 0.0, 0.0};
11✔
961
    expected_v = {0.0, 0.0, width_[1]};
11✔
962
    break;
11✔
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};
33✔
975
  double span_tol = rel_tol * (1.0 + u_span_.norm() + v_span_.norm());
33✔
976
  if ((u_span_ - expected_u).norm() > span_tol ||
66!
977
      (v_span_ - expected_v).norm() > span_tol) {
33✔
978
    fatal_error("Meshlines are only supported for axis-aligned slice plots.");
×
979
  }
980

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

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

989
  Position width = ur_plot - ll_plot;
33✔
990

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

995
  // Find the bounds along the second axis (accounting for low-D meshes).
996
  int ax2_min, ax2_max;
33✔
997
  if (axis_lines.second.size() > 0) {
33!
998
    double frac = (axis_lines.second.back() - ll_plot[ax2]) / width[ax2];
33✔
999
    ax2_min = (1.0 - frac) * pixels()[1];
33✔
1000
    if (ax2_min < 0)
33✔
1001
      ax2_min = 0;
1002
    frac = (axis_lines.second.front() - ll_plot[ax2]) / width[ax2];
33✔
1003
    ax2_max = (1.0 - frac) * pixels()[1];
33!
1004
    if (ax2_max > pixels()[1])
33!
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) {
187✔
1013
    double frac = (ax1_val - ll_plot[ax1]) / width[ax1];
154✔
1014
    int ax1_ind = frac * pixels()[0];
154✔
1015
    for (int ax2_ind = ax2_min; ax2_ind < ax2_max; ++ax2_ind) {
24,948✔
1016
      for (int plus = 0; plus <= meshlines_width_; plus++) {
49,588✔
1017
        if (ax1_ind + plus >= 0 && ax1_ind + plus < pixels()[0])
24,794!
1018
          data(ax1_ind + plus, ax2_ind) = rgb;
24,794✔
1019
        if (ax1_ind - plus >= 0 && ax1_ind - plus < pixels()[0])
24,794!
1020
          data(ax1_ind - plus, ax2_ind) = rgb;
24,794✔
1021
      }
1022
    }
1023
  }
1024

1025
  // Find the bounds along the first axis.
1026
  int ax1_min, ax1_max;
33✔
1027
  if (axis_lines.first.size() > 0) {
33!
1028
    double frac = (axis_lines.first.front() - ll_plot[ax1]) / width[ax1];
33✔
1029
    ax1_min = frac * pixels()[0];
33✔
1030
    if (ax1_min < 0)
33✔
1031
      ax1_min = 0;
1032
    frac = (axis_lines.first.back() - ll_plot[ax1]) / width[ax1];
33✔
1033
    ax1_max = frac * pixels()[0];
33!
1034
    if (ax1_max > pixels()[0])
33!
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) {
209✔
1043
    double frac = (ax2_val - ll_plot[ax2]) / width[ax2];
176✔
1044
    int ax2_ind = (1.0 - frac) * pixels()[1];
176✔
1045
    for (int ax1_ind = ax1_min; ax1_ind < ax1_max; ++ax1_ind) {
28,336✔
1046
      for (int plus = 0; plus <= meshlines_width_; plus++) {
56,320✔
1047
        if (ax2_ind + plus >= 0 && ax2_ind + plus < pixels()[1])
28,160!
1048
          data(ax1_ind, ax2_ind + plus) = rgb;
28,160✔
1049
        if (ax2_ind - plus >= 0 && ax2_ind - plus < pixels()[1])
28,160!
1050
          data(ax1_ind, ax2_ind - plus) = rgb;
28,160✔
1051
      }
1052
    }
1053
  }
1054
}
33✔
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
55✔
1067
{
1068
  // compute voxel widths in each direction
1069
  array<double, 3> vox;
55✔
1070
  vox[0] = width_[0] / static_cast<double>(pixels()[0]);
55✔
1071
  vox[1] = width_[1] / static_cast<double>(pixels()[1]);
55✔
1072
  vox[2] = width_[2] / static_cast<double>(pixels()[2]);
55✔
1073

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

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

1083
  // write header info
1084
  write_attribute(file_id, "filetype", "voxel");
55✔
1085
  write_attribute(file_id, "version", VERSION_VOXEL);
55✔
1086
  write_attribute(file_id, "openmc_version", VERSION);
55✔
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());
110✔
1094
  array<int, 3> h5_pixels;
55✔
1095
  std::copy(pixels().begin(), pixels().end(), h5_pixels.begin());
55✔
1096
  write_attribute(file_id, "num_voxels", h5_pixels);
55✔
1097
  write_attribute(file_id, "voxel_width", vox);
55✔
1098
  write_attribute(file_id, "lower_left", ll);
55✔
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];
55✔
1103
  dims[0] = pixels()[2];
55✔
1104
  dims[1] = pixels()[1];
55✔
1105
  dims[2] = pixels()[0];
55✔
1106
  hid_t dspace, dset, memspace;
55✔
1107
  voxel_init(file_id, &(dims[0]), &dspace, &dset, &memspace);
55✔
1108

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

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

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

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

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

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

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

1147
void voxel_init(hid_t file_id, const hsize_t* dims, hid_t* dspace, hid_t* dset,
55✔
1148
  hid_t* memspace)
1149
{
1150
  // Create dataspace/dataset for voxel data
1151
  *dspace = H5Screate_simple(3, dims, nullptr);
55✔
1152
  *dset = H5Dcreate(file_id, "data", H5T_NATIVE_INT, *dspace, H5P_DEFAULT,
55✔
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]};
55✔
1157
  *memspace = H5Screate_simple(2, dims_slice, nullptr);
55✔
1158

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

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

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

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

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

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

1201
void RayTracePlot::update_view()
110✔
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();
110✔
1206
  Direction looking_direction = look_at_ - camera_position_;
110✔
1207
  looking_direction /= looking_direction.norm();
110✔
1208
  if (std::abs(std::abs(looking_direction.dot(up)) - 1.0) < 1e-9)
110!
1209
    fatal_error("Up vector cannot align with vector between camera position "
×
1210
                "and look_at!");
1211
  Direction cam_yaxis = looking_direction.cross(up);
110✔
1212
  cam_yaxis /= cam_yaxis.norm();
110✔
1213
  Direction cam_zaxis = cam_yaxis.cross(looking_direction);
110✔
1214
  cam_zaxis /= cam_zaxis.norm();
110✔
1215

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

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

1232
void WireframeRayTracePlot::set_wireframe_color(pugi::xml_node plot_node)
55✔
1233
{
1234
  // Copy plot wireframe color
1235
  if (check_for_node(plot_node, "wireframe_color")) {
55!
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
}
55✔
1244

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

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

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

1266
bool WireframeRayTracePlot::trackstack_equivalent(
3,041,159✔
1267
  const std::vector<TrackSegment>& track1,
1268
  const std::vector<TrackSegment>& track2) const
1269
{
1270
  if (wireframe_ids_.empty()) {
3,041,159✔
1271
    // Draw wireframe for all surfaces/cells/materials
1272
    if (track1.size() != track2.size())
2,545,070✔
1273
      return false;
1274
    for (int i = 0; i < track1.size(); ++i) {
6,707,954✔
1275
      if (track1[i].id != track2[i].id ||
4,236,771✔
1276
          track1[i].surface_index != track2[i].surface_index) {
4,236,639✔
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_) {
986,194✔
1286
      int t1_i = 0;
496,089✔
1287
      int t2_i = 0;
496,089✔
1288

1289
      // Advance to first instance of the ID
1290
      while (t1_i < track1.size() && t2_i < track2.size()) {
562,430✔
1291
        while (t1_i < track1.size() && track1[t1_i].id != id)
392,832✔
1292
          t1_i++;
229,053✔
1293
        while (t2_i < track2.size() && track2[t2_i].id != id)
393,668✔
1294
          t2_i++;
229,889✔
1295

1296
        // This one is really important!
1297
        if ((t1_i == track1.size() && t2_i != track2.size()) ||
163,779✔
1298
            (t1_i != track1.size() && t2_i == track2.size()))
162,096✔
1299
          return false;
3,718✔
1300
        if (t1_i == track1.size() && t2_i == track2.size())
160,061!
1301
          break;
1302
        // Check if surface different
1303
        if (track1[t1_i].surface_index != track2[t2_i].surface_index)
68,607✔
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 &&
67,122✔
1311
            track1[t1_i - 1].surface_index != track2[t2_i - 1].surface_index)
53,944✔
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++;
66,341✔
1321
      }
1322
    }
1323
    return true;
1324
  }
1325
}
1326

1327
std::pair<Position, Direction> RayTracePlot::get_pixel_ray(
3,521,056✔
1328
  int horiz, int vert) const
1329
{
1330
  // Compute field of view in radians
1331
  constexpr double DEGREE_TO_RADIAN = M_PI / 180.0;
3,521,056✔
1332
  double horiz_fov_radians = horizontal_field_of_view_ * DEGREE_TO_RADIAN;
3,521,056✔
1333
  double p0 = static_cast<double>(pixels()[0]);
3,521,056✔
1334
  double p1 = static_cast<double>(pixels()[1]);
3,521,056✔
1335
  double vert_fov_radians = horiz_fov_radians * p1 / p0;
3,521,056✔
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;
3,521,056✔
1341
  const double dx = 2.0 * focal_plane_dist * std::tan(0.5 * horiz_fov_radians);
3,521,056✔
1342
  const double dy = p1 / p0 * dx;
3,521,056✔
1343

1344
  std::pair<Position, Direction> result;
3,521,056✔
1345

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

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

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

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

1367
  return result;
3,521,056✔
1368
}
1369

1370
ImageData WireframeRayTracePlot::create_image() const
55✔
1371
{
1372
  size_t width = pixels()[0];
55✔
1373
  size_t height = pixels()[1];
55✔
1374
  ImageData data({width, height}, not_found_);
55✔
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(
55✔
1380
    {static_cast<size_t>(width), static_cast<size_t>(height)}, 0);
55✔
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();
55✔
1394
  std::vector<std::vector<std::vector<TrackSegment>>> this_line_segments(
55✔
1395
    n_threads);
55✔
1396
  for (int t = 0; t < n_threads; ++t) {
140✔
1397
    this_line_segments[t].resize(pixels()[0]);
85✔
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]);
55✔
1402

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

1408
    int vert = tid;
25✔
1409
    for (int iter = 0; iter <= pixels()[1] / n_threads; iter++) {
5,050✔
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)
5,025✔
1416
        old_segments = this_line_segments[n_threads - 1];
5,025✔
1417

1418
      if (vert < pixels()[1]) {
5,025✔
1419

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

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

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

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

1431
          // Now color the pixel based on what we have intersected...
1432
          // Loops backwards over intersections.
1433
          Position current_color(
1,000,000✔
1434
            not_found_.red, not_found_.green, not_found_.blue);
1,000,000✔
1435
          const auto& segments = this_line_segments[tid][horiz];
1,000,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)
1,000,000✔
1442
            continue;
616,655✔
1443

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

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

1464
          // Check to draw wireframe in horizontal direction. No inter-thread
1465
          // comm.
1466
          if (horiz > 0) {
383,345✔
1467
            if (!trackstack_equivalent(this_line_segments[tid][horiz],
382,345✔
1468
                  this_line_segments[tid][horiz - 1])) {
382,345✔
1469
              wireframe_initial(horiz, vert) = 1;
15,710✔
1470
            }
1471
          }
1472
        }
1,000,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]) {
5,025✔
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) {
1,005,000✔
1493
          if (!trackstack_equivalent(
1,000,000✔
1494
                this_line_segments[tid][horiz], (*top_cmp)[horiz])) {
1,000,000✔
1495
            wireframe_initial(horiz, vert) = 1;
20,595✔
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;
5,025✔
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) {
11,055✔
1510
    for (int horiz = 0; horiz < pixels()[0]; ++horiz) {
2,211,000✔
1511
      if (wireframe_initial(horiz, vert)) {
2,200,000✔
1512
        if (wireframe_thickness_ == 1)
70,983✔
1513
          data(horiz, vert) = wireframe_color_;
30,195✔
1514
        for (int i = -wireframe_thickness_ / 2; i < wireframe_thickness_ / 2;
195,723✔
1515
             ++i)
1516
          for (int j = -wireframe_thickness_ / 2; j < wireframe_thickness_ / 2;
546,876✔
1517
               ++j)
1518
            if (i * i + j * j < wireframe_thickness_ * wireframe_thickness_) {
422,136!
1519

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

1529
  return data;
110✔
1530
}
110✔
1531

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

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

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

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

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

1563
    // Add RGB
1564
    if (PlotColorBy::cells == color_by_) {
66!
1565
      if (model::cell_map.find(col_id) != model::cell_map.end()) {
66!
1566
        col_id = model::cell_map[col_id];
66✔
1567
        xs_[col_id] = user_xs;
66✔
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
}
55✔
1583

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

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

1606
void WireframeRayTracePlot::set_wireframe_ids(pugi::xml_node node)
55✔
1607
{
1608
  if (check_for_node(node, "wireframe_ids")) {
55✔
1609
    wireframe_ids_ = get_node_array<int>(node, "wireframe_ids");
11✔
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_)
22✔
1613
      x = color_by_ == PlotColorBy::mats ? model::material_map[x]
22!
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());
55✔
1619
}
55✔
1620

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

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

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

1654
void RayTracePlot::set_field_of_view(pugi::xml_node node)
88✔
1655
{
1656
  // Defaults to 70 degree horizontal field of view (see .h file)
1657
  if (check_for_node(node, "horizontal_field_of_view")) {
88!
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
}
88✔
1669

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

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

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

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

1701
  return data;
55✔
1702
}
1703

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

1710
void SolidRayTracePlot::set_opaque_ids(pugi::xml_node node)
33✔
1711
{
1712
  if (check_for_node(node, "opaque_ids")) {
33!
1713
    auto opaque_ids_tmp = get_node_array<int>(node, "opaque_ids");
33✔
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)
99✔
1718
      x = color_by_ == PlotColorBy::mats ? model::material_map[x]
132!
1719
                                         : model::cell_map[x];
×
1720

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

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

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

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

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

1751
void ProjectionRay::on_intersection()
2,359,148✔
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(
2,359,148✔
1760
    plot_.color_by_ == PlottableInterface::PlotColorBy::mats
2,359,148✔
1761
      ? material()
545,919✔
1762
      : lowest_coord().cell(),
1,813,229✔
1763
    traversal_distance_, boundary().surface_index());
2,359,148✔
1764
}
2,359,148✔
1765

1766
void PhongRay::on_intersection()
905,971✔
1767
{
1768
  // Check if we hit an opaque material or cell
1769
  int hit_id = plot_.color_by_ == PlottableInterface::PlotColorBy::mats
905,971✔
1770
                 ? material()
905,971!
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) {
905,971!
1777
    stop();
×
1778
    return;
164,340✔
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())
905,971✔
1783
    return;
1784

1785
  if (!reflected_) {
741,631✔
1786
    // reflect the particle and set the color to be colored by
1787
    // the normal or the diffuse lighting contribution
1788
    reflected_ = true;
706,068✔
1789
    result_color_ = plot_.colors_[hit_id];
706,068✔
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();
706,068✔
1793
    Direction to_light = plot_.light_location_ - r_hit;
706,068✔
1794
    to_light /= to_light.norm();
706,068✔
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) {
706,068!
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());
706,068✔
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;
706,068!
1819
    // ensure surface level is within bounds of current coordinate stack
1820
    surf_level = std::max(0, std::min(surf_level, n_coord() - 1));
706,068!
1821

1822
    Position r_hit_level =
706,068✔
1823
      coord(surf_level).r() - TINY_BIT * coord(surf_level).u();
706,068✔
1824
    Direction normal = surf->normal(r_hit_level);
706,068✔
1825
    normal /= normal.norm();
706,068✔
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) {
706,068!
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) {
706,068✔
1838
      normal *= -1.0;
63,789✔
1839
    }
1840

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

1845
    double modulation =
706,068✔
1846
      plot_.diffuse_fraction_ + (1.0 - plot_.diffuse_fraction_) * dotprod;
706,068✔
1847
    result_color_ *= modulation;
706,068✔
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;
706,068✔
1852

1853
    orig_hit_id_ = hit_id;
706,068✔
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) {
706,068!
1859
      surface() = 0;
×
1860
    } else {
1861
      surface() = -surface(); // go to other side
706,068✔
1862
    }
1863

1864
    // Must fully restart coordinate search. Why? Not sure.
1865
    clear();
706,068✔
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);
706,068✔
1872
    if (!found) {
706,068!
1873
      fatal_error("Lost particle after reflection.");
×
1874
    }
1875

1876
    // Must recalculate distance to boundary due to the
1877
    // direction change
1878
    compute_distance();
706,068✔
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)
35,563!
1886
      fatal_error("somehow a ray got reflected but not original ID set?");
×
1887

1888
    result_color_ = plot_.colors_[orig_hit_id_];
35,563✔
1889
    result_color_ *= plot_.diffuse_fraction_;
35,563✔
1890
    stop();
741,631✔
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],
432✔
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]};
432✔
1954
  Direction v_span_pos {v_span[0], v_span[1], v_span[2]};
432✔
1955
  double u_norm = u_span_pos.norm();
432✔
1956
  double v_norm = v_span_pos.norm();
432✔
1957
  if (u_norm == 0.0 || v_norm == 0.0) {
432!
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;
432✔
1963
  double dot = u_span_pos.dot(v_span_pos);
432!
1964
  if (std::abs(dot) > ORTHO_REL_TOL * u_norm * v_norm) {
432!
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) {
432✔
1971
    if (int err = verify_filter(filter_index))
22!
1972
      return err;
1973
  }
1974

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

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

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

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

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

2009
  return 0;
432✔
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)
22✔
2014
{
2015
  if (!count) {
22!
2016
    set_errmsg("Null pointer passed for overlap count.");
×
2017
    return OPENMC_E_INVALID_ARGUMENT;
×
2018
  }
2019
  *count = model::overlap_keys.size();
22✔
2020

2021
  return 0;
22✔
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(
11✔
2027
  size_t count, int32_t* overlap_info)
2028
{
2029
  for (size_t i = 0; i < count; ++i) {
33✔
2030
    overlap_info[i * 3] = model::overlap_keys[i].universe_id;
22✔
2031
    overlap_info[i * 3 + 1] = model::overlap_keys[i].cell1_id;
22✔
2032
    overlap_info[i * 3 + 2] = model::overlap_keys[i].cell2_id;
22✔
2033
  }
2034

2035
  return 0;
11✔
2036
}
2037

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

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

2050
extern "C" int openmc_plot_get_id(int32_t index, int32_t* id)
55✔
2051
{
2052
  if (index < 0 || index >= model::plots.size()) {
55!
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();
55✔
2058
  return 0;
55✔
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()
22✔
2091
{
2092
  return model::plots.size();
22✔
2093
}
2094

2095
int map_phong_domain_id(
55✔
2096
  const SolidRayTracePlot* plot, int32_t id, int32_t* index_out)
2097
{
2098
  if (!plot || !index_out) {
55!
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) {
55!
2104
    auto it = model::material_map.find(id);
55!
2105
    if (it == model::material_map.end()) {
55!
2106
      set_errmsg("Invalid material ID for SolidRayTracePlot");
×
2107
      return OPENMC_E_INVALID_ID;
×
2108
    }
2109
    *index_out = it->second;
55✔
2110
    return 0;
55✔
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)
308✔
2128
{
2129
  if (!plot) {
308!
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()) {
308!
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();
308!
2140
  auto* solid_plot = dynamic_cast<SolidRayTracePlot*>(plottable);
308!
2141
  if (!solid_plot) {
308!
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;
308✔
2148
  return 0;
308✔
2149
}
2150

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

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

2177
  return 0;
11✔
2178
}
2179

2180
extern "C" int openmc_solidraytrace_plot_get_pixels(
33✔
2181
  int32_t index, int32_t* width, int32_t* height)
2182
{
2183
  if (!width || !height) {
33!
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;
33✔
2190
  int err = get_solidraytrace_plot_by_index(index, &plt);
33✔
2191
  if (err)
33!
2192
    return err;
2193

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

2199
extern "C" int openmc_solidraytrace_plot_set_pixels(
11✔
2200
  int32_t index, int32_t width, int32_t height)
2201
{
2202
  if (width <= 0 || height <= 0) {
11!
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;
11✔
2209
  int err = get_solidraytrace_plot_by_index(index, &plt);
11✔
2210
  if (err)
11!
2211
    return err;
2212

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

2218
extern "C" int openmc_solidraytrace_plot_get_color_by(
11✔
2219
  int32_t index, int32_t* color_by)
2220
{
2221
  if (!color_by) {
11!
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;
11✔
2228
  int err = get_solidraytrace_plot_by_index(index, &plt);
11✔
2229
  if (err)
11!
2230
    return err;
2231

2232
  if (plt->color_by_ == PlottableInterface::PlotColorBy::mats) {
11!
2233
    *color_by = 0;
11✔
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(
11✔
2245
  int32_t index, int32_t color_by)
2246
{
2247
  SolidRayTracePlot* plt = nullptr;
11✔
2248
  int err = get_solidraytrace_plot_by_index(index, &plt);
11✔
2249
  if (err)
11!
2250
    return err;
2251

2252
  if (color_by == 0) {
11!
2253
    plt->color_by_ = PlottableInterface::PlotColorBy::mats;
11✔
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)
11✔
2265
{
2266
  SolidRayTracePlot* plt = nullptr;
11✔
2267
  int err = get_solidraytrace_plot_by_index(index, &plt);
11✔
2268
  if (err)
11!
2269
    return err;
2270

2271
  plt->set_default_colors();
11✔
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(
22✔
2302
  int32_t index, int32_t id, bool visible)
2303
{
2304
  SolidRayTracePlot* plt = nullptr;
22✔
2305
  int err = get_solidraytrace_plot_by_index(index, &plt);
22✔
2306
  if (err)
22!
2307
    return err;
2308

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

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

2320
  return 0;
2321
}
2322

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

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

2336
  if (domain_index < 0 ||
22!
2337
      static_cast<size_t>(domain_index) >= plt->colors_.size()) {
22!
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);
22✔
2343
  return 0;
22✔
2344
}
2345

2346
extern "C" int openmc_solidraytrace_plot_get_camera_position(
11✔
2347
  int32_t index, double* x, double* y, double* z)
2348
{
2349
  if (!x || !y || !z) {
11!
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;
11✔
2356
  int err = get_solidraytrace_plot_by_index(index, &plt);
11✔
2357
  if (err)
11!
2358
    return err;
2359

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

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

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

2379
extern "C" int openmc_solidraytrace_plot_get_look_at(
11✔
2380
  int32_t index, double* x, double* y, double* z)
2381
{
2382
  if (!x || !y || !z) {
11!
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;
11✔
2389
  int err = get_solidraytrace_plot_by_index(index, &plt);
11✔
2390
  if (err)
11!
2391
    return err;
2392

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

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

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

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

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

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

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

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

2444
extern "C" int openmc_solidraytrace_plot_get_light_position(
11✔
2445
  int32_t index, double* x, double* y, double* z)
2446
{
2447
  if (!x || !y || !z) {
11!
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;
11✔
2454
  int err = get_solidraytrace_plot_by_index(index, &plt);
11✔
2455
  if (err)
11!
2456
    return err;
2457

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

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

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

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

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

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

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

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

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

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

2515
extern "C" int openmc_solidraytrace_plot_create_image(
22✔
2516
  int32_t index, uint8_t* data_out, int32_t width, int32_t height)
2517
{
2518
  if (!data_out || width <= 0 || height <= 0) {
22!
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;
22✔
2525
  int err = get_solidraytrace_plot_by_index(index, &plt);
22✔
2526
  if (err)
22!
2527
    return err;
2528

2529
  if (plt->pixels()[0] != width || plt->pixels()[1] != height) {
22!
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();
22✔
2536
  if (static_cast<int32_t>(data.shape()[0]) != width ||
22!
2537
      static_cast<int32_t>(data.shape()[1]) != height) {
22!
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) {
154✔
2543
    for (int32_t x = 0; x < width; ++x) {
1,188✔
2544
      const auto& color = data(x, y);
1,056✔
2545
      size_t idx = (static_cast<size_t>(y) * width + x) * 3;
1,056✔
2546
      data_out[idx + 0] = color.red;
1,056✔
2547
      data_out[idx + 1] = color.green;
1,056✔
2548
      data_out[idx + 2] = color.blue;
1,056✔
2549
    }
2550
  }
2551

2552
  return 0;
2553
}
22✔
2554

2555
extern "C" int openmc_solidraytrace_plot_get_color(
11✔
2556
  int32_t index, int32_t id, uint8_t* r, uint8_t* g, uint8_t* b)
2557
{
2558
  if (!r || !g || !b) {
11!
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;
11✔
2565
  int err = get_solidraytrace_plot_by_index(index, &plt);
11✔
2566
  if (err)
11!
2567
    return err;
2568

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

2574
  if (domain_index < 0 ||
11!
2575
      static_cast<size_t>(domain_index) >= plt->colors_.size()) {
11!
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];
11✔
2581
  *r = color.red;
11✔
2582
  *g = color.green;
11✔
2583
  *b = color.blue;
11✔
2584
  return 0;
11✔
2585
}
2586

2587
extern "C" int openmc_solidraytrace_plot_get_diffuse_fraction(
11✔
2588
  int32_t index, double* diffuse_fraction)
2589
{
2590
  if (!diffuse_fraction) {
11!
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;
11✔
2597
  int err = get_solidraytrace_plot_by_index(index, &plt);
11✔
2598
  if (err)
11!
2599
    return err;
2600

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

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

2613
  if (diffuse_fraction < 0.0 || diffuse_fraction > 1.0) {
11!
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;
11✔
2619
  return 0;
11✔
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