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

openmc-dev / openmc / 21926592529

11 Feb 2026 11:06PM UTC coverage: 81.697% (-0.2%) from 81.905%
21926592529

Pull #3789

github

web-flow
Merge 9044b337f into 96383fcb2
Pull Request #3789: SolidRayTracePlot CAPI

17496 of 24595 branches covered (71.14%)

Branch coverage included in aggregate %.

467 of 622 new or added lines in 2 files covered. (75.08%)

217 existing lines in 5 files now uncovered.

56853 of 66411 relevant lines covered (85.61%)

44164293.19 hits per line

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

70.98
/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 "xtensor/xmanipulation.hpp"
11
#include "xtensor/xview.hpp"
12
#include <fmt/core.h>
13
#include <fmt/ostream.h>
14
#ifdef USE_LIBPNG
15
#include <png.h>
16
#endif
17

18
#include "openmc/cell.h"
19
#include "openmc/constants.h"
20
#include "openmc/container_util.h"
21
#include "openmc/dagmc.h"
22
#include "openmc/error.h"
23
#include "openmc/file_utils.h"
24
#include "openmc/geometry.h"
25
#include "openmc/hdf5_interface.h"
26
#include "openmc/material.h"
27
#include "openmc/mesh.h"
28
#include "openmc/message_passing.h"
29
#include "openmc/openmp_interface.h"
30
#include "openmc/output.h"
31
#include "openmc/particle.h"
32
#include "openmc/progress_bar.h"
33
#include "openmc/random_lcg.h"
34
#include "openmc/settings.h"
35
#include "openmc/simulation.h"
36
#include "openmc/string_utils.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) : data_({v_res, h_res, 3}, NOT_FOUND)
4,673✔
49
{}
4,673✔
50

51
void IdData::set_value(size_t y, size_t x, const GeometryState& p, int level)
35,206,718✔
52
{
53
  // set cell data
54
  if (p.n_coord() <= level) {
35,206,718!
55
    data_(y, x, 0) = NOT_FOUND;
×
56
    data_(y, x, 1) = NOT_FOUND;
×
57
  } else {
58
    data_(y, x, 0) = model::cells.at(p.coord(level).cell())->id_;
35,206,718✔
59
    data_(y, x, 1) = level == p.n_coord() - 1
70,413,436✔
60
                       ? p.cell_instance()
35,206,718!
61
                       : cell_instance_at_level(p, level);
×
62
  }
63

64
  // set material data
65
  Cell* c = model::cells.at(p.lowest_coord().cell()).get();
35,206,718✔
66
  if (p.material() == MATERIAL_VOID) {
35,206,718✔
67
    data_(y, x, 2) = MATERIAL_VOID;
27,102,344✔
68
    return;
27,102,344✔
69
  } else if (c->type_ == Fill::MATERIAL) {
8,104,374!
70
    Material* m = model::materials.at(p.material()).get();
8,104,374✔
71
    data_(y, x, 2) = m->id_;
8,104,374✔
72
  }
73
}
74

75
void IdData::set_overlap(size_t y, size_t x)
340,280✔
76
{
77
  xt::view(data_, y, x, xt::all()) = OVERLAP;
340,280✔
78
}
340,280✔
79

80
PropertyData::PropertyData(size_t h_res, size_t v_res)
10✔
81
  : data_({v_res, h_res, 2}, NOT_FOUND)
10✔
82
{}
10✔
83

84
void PropertyData::set_value(
90✔
85
  size_t y, size_t x, const GeometryState& p, int level)
86
{
87
  Cell* c = model::cells.at(p.lowest_coord().cell()).get();
90✔
88
  data_(y, x, 0) = (p.sqrtkT() * p.sqrtkT()) / K_BOLTZMANN;
90✔
89
  if (c->type_ != Fill::UNIVERSE && p.material() != MATERIAL_VOID) {
90!
90
    Material* m = model::materials.at(p.material()).get();
90✔
91
    data_(y, x, 1) = m->density_gpcc_;
90✔
92
  }
93
}
90✔
94

95
void PropertyData::set_overlap(size_t y, size_t x)
×
96
{
97
  data_(y, x) = OVERLAP;
×
98
}
×
99

100
//==============================================================================
101
// Global variables
102
//==============================================================================
103

104
namespace model {
105

106
std::unordered_map<int, int> plot_map;
107
vector<std::unique_ptr<PlottableInterface>> plots;
108
uint64_t plotter_seed = 1;
109

110
} // namespace model
111

112
//==============================================================================
113
// RUN_PLOT controls the logic for making one or many plots
114
//==============================================================================
115

116
extern "C" int openmc_plot_geometry()
110✔
117
{
118

119
  for (auto& pl : model::plots) {
370✔
120
    write_message(5, "Processing plot {}: {}...", pl->id(), pl->path_plot());
260✔
121
    pl->create_output();
260✔
122
  }
123

124
  return 0;
110✔
125
}
126

127
void PlottableInterface::write_image(const ImageData& data) const
210✔
128
{
129
#ifdef USE_LIBPNG
130
  output_png(path_plot(), data);
210✔
131
#else
132
  output_ppm(path_plot(), data);
133
#endif
134
}
210✔
135

136
void Plot::create_output() const
180✔
137
{
138
  if (PlotType::slice == type_) {
180✔
139
    // create 2D image
140
    ImageData image = create_image();
130✔
141
    write_image(image);
130✔
142
  } else if (PlotType::voxel == type_) {
180!
143
    // create voxel file for 3D viewing
144
    create_voxel();
50✔
145
  }
146
}
180✔
147

148
void Plot::print_info() const
140✔
149
{
150
  // Plot type
151
  if (PlotType::slice == type_) {
140✔
152
    fmt::print("Plot Type: Slice\n");
110✔
153
  } else if (PlotType::voxel == type_) {
30!
154
    fmt::print("Plot Type: Voxel\n");
30✔
155
  }
156

157
  // Plot parameters
158
  fmt::print("Origin: {} {} {}\n", origin_[0], origin_[1], origin_[2]);
252✔
159

160
  if (PlotType::slice == type_) {
140✔
161
    fmt::print("Width: {:4} {:4}\n", width_[0], width_[1]);
220✔
162
  } else if (PlotType::voxel == type_) {
30!
163
    fmt::print("Width: {:4} {:4} {:4}\n", width_[0], width_[1], width_[2]);
60✔
164
  }
165

166
  if (PlotColorBy::cells == color_by_) {
140✔
167
    fmt::print("Coloring: Cells\n");
80✔
168
  } else if (PlotColorBy::mats == color_by_) {
60!
169
    fmt::print("Coloring: Materials\n");
60✔
170
  }
171

172
  if (PlotType::slice == type_) {
140✔
173
    switch (basis_) {
110!
174
    case PlotBasis::xy:
70✔
175
      fmt::print("Basis: XY\n");
56✔
176
      break;
70✔
177
    case PlotBasis::xz:
20✔
178
      fmt::print("Basis: XZ\n");
16✔
179
      break;
20✔
180
    case PlotBasis::yz:
20✔
181
      fmt::print("Basis: YZ\n");
16✔
182
      break;
20✔
183
    }
184
    fmt::print("Pixels: {} {}\n", pixels()[0], pixels()[1]);
220✔
185
  } else if (PlotType::voxel == type_) {
30!
186
    fmt::print("Voxels: {} {} {}\n", pixels()[0], pixels()[1], pixels()[2]);
60✔
187
  }
188
}
140✔
189

190
void read_plots_xml()
1,234✔
191
{
192
  // Check if plots.xml exists; this is only necessary when the plot runmode is
193
  // initiated. Otherwise, we want to read plots.xml because it may be called
194
  // later via the API. In that case, its ok for a plots.xml to not exist
195
  std::string filename = settings::path_input + "plots.xml";
1,234✔
196
  if (!file_exists(filename) && settings::run_mode == RunMode::PLOTTING) {
1,234!
197
    fatal_error(fmt::format("Plots XML file '{}' does not exist!", filename));
×
198
  }
199

200
  write_message("Reading plot XML file...", 5);
1,234✔
201

202
  // Parse plots.xml file
203
  pugi::xml_document doc;
1,234✔
204
  doc.load_file(filename.c_str());
1,234✔
205

206
  pugi::xml_node root = doc.document_element();
1,234✔
207

208
  read_plots_xml(root);
1,234✔
209
}
1,234✔
210

211
void read_plots_xml(pugi::xml_node root)
1,546✔
212
{
213
  for (auto node : root.children("plot")) {
2,300✔
214
    std::string plot_desc = "<auto>";
762✔
215
    if (check_for_node(node, "id")) {
762!
216
      plot_desc = get_node_value(node, "id", true);
762✔
217
    }
218

219
    if (check_for_node(node, "type")) {
762!
220
      std::string type_str = get_node_value(node, "type", true);
762✔
221
      if (type_str == "slice") {
762✔
222
        model::plots.emplace_back(
624✔
223
          std::make_unique<Plot>(node, Plot::PlotType::slice));
1,256✔
224
      } else if (type_str == "voxel") {
130✔
225
        model::plots.emplace_back(
50✔
226
          std::make_unique<Plot>(node, Plot::PlotType::voxel));
100✔
227
      } else if (type_str == "wireframe_raytrace") {
80✔
228
        model::plots.emplace_back(
50✔
229
          std::make_unique<WireframeRayTracePlot>(node));
100✔
230
      } else if (type_str == "solid_raytrace") {
30!
231
        model::plots.emplace_back(std::make_unique<SolidRayTracePlot>(node));
30✔
232
      } else {
NEW
233
        fatal_error(fmt::format(
×
234
          "Unsupported plot type '{}' in plot {}", type_str, plot_desc));
235
      }
236
      model::plot_map[model::plots.back()->id()] = model::plots.size() - 1;
754✔
237
    } else {
754✔
NEW
238
      fatal_error(fmt::format("Must specify plot type in plot {}", plot_desc));
×
239
    }
240
  }
754✔
241
}
1,538✔
242

243
void free_memory_plot()
7,505✔
244
{
245
  model::plots.clear();
7,505✔
246
  model::plot_map.clear();
7,505✔
247
}
7,505✔
248

249
// creates an image based on user input from a plots.xml <plot>
250
// specification in the PNG/PPM format
251
ImageData Plot::create_image() const
130✔
252
{
253
  size_t width = pixels()[0];
130✔
254
  size_t height = pixels()[1];
130✔
255

256
  ImageData data({width, height}, not_found_);
130✔
257

258
  // generate ids for the plot
259
  auto ids = get_map<IdData>();
130✔
260

261
  // assign colors
262
  for (size_t y = 0; y < height; y++) {
27,330✔
263
    for (size_t x = 0; x < width; x++) {
6,929,200✔
264
      int idx = color_by_ == PlotColorBy::cells ? 0 : 2;
6,902,000✔
265
      auto id = ids.data_(y, x, idx);
6,902,000✔
266
      // no setting needed if not found
267
      if (id == NOT_FOUND) {
6,902,000✔
268
        continue;
984,120✔
269
      }
270
      if (id == OVERLAP) {
5,943,560✔
271
        data(x, y) = overlap_color_;
25,680✔
272
        continue;
25,680✔
273
      }
274
      if (PlotColorBy::cells == color_by_) {
5,917,880✔
275
        data(x, y) = colors_[model::cell_map[id]];
2,737,880✔
276
      } else if (PlotColorBy::mats == color_by_) {
3,180,000!
277
        if (id == MATERIAL_VOID) {
3,180,000!
278
          data(x, y) = WHITE;
×
279
          continue;
×
280
        }
281
        data(x, y) = colors_[model::material_map[id]];
3,180,000✔
282
      } // color_by if-else
283
    }
284
  }
285

286
  // draw mesh lines if present
287
  if (index_meshlines_mesh_ >= 0) {
130✔
288
    draw_mesh_lines(data);
30✔
289
  }
290

291
  return data;
260✔
292
}
130✔
293

294
void PlottableInterface::set_id(pugi::xml_node plot_node)
762✔
295
{
296
  int id {C_NONE};
762✔
297
  if (check_for_node(plot_node, "id")) {
762!
298
    id = std::stoi(get_node_value(plot_node, "id"));
762✔
299
  }
300

301
  try {
302
    set_id(id);
762✔
NEW
303
  } catch (const std::runtime_error& e) {
×
NEW
304
    fatal_error(e.what());
×
UNCOV
305
  }
×
306
}
762✔
307

308
void PlottableInterface::set_id(int id)
772✔
309
{
310
  if (id < 0 && id != C_NONE) {
772!
NEW
311
    throw std::runtime_error {fmt::format("Invalid plot ID: {}", id)};
×
312
  }
313

314
  if (id == C_NONE) {
772✔
315
    id = 1;
10✔
316
    for (const auto& p : model::plots) {
20✔
317
      id = std::max(id, p->id() + 1);
10✔
318
    }
319
  }
320

321
  if (id_ == id)
772!
NEW
322
    return;
×
323

324
  // Check to make sure this ID doesn't already exist
325
  if (model::plot_map.find(id) != model::plot_map.end()) {
772!
NEW
326
    throw std::runtime_error {
×
NEW
327
      fmt::format("Two or more plots use the same unique ID: {}", id)};
×
328
  }
329

330
  id_ = id;
772✔
331
}
332

333
// Checks if png or ppm is already present
334
bool file_extension_present(
754✔
335
  const std::string& filename, const std::string& extension)
336
{
337
  std::string file_extension_if_present =
338
    filename.substr(filename.find_last_of(".") + 1);
754✔
339
  if (file_extension_if_present == extension)
754✔
340
    return true;
50✔
341
  return false;
704✔
342
}
754✔
343

344
void Plot::set_output_path(pugi::xml_node plot_node)
682✔
345
{
346
  // Set output file path
347
  std::string filename;
682✔
348

349
  if (check_for_node(plot_node, "filename")) {
682✔
350
    filename = get_node_value(plot_node, "filename");
222✔
351
  } else {
352
    filename = fmt::format("plot_{}", id());
920✔
353
  }
354
  const std::string dir_if_present =
355
    filename.substr(0, filename.find_last_of("/") + 1);
682✔
356
  if (dir_if_present.size() > 0 && !dir_exists(dir_if_present)) {
682✔
357
    fatal_error(fmt::format("Directory '{}' does not exist!", dir_if_present));
8✔
358
  }
359
  // add appropriate file extension to name
360
  switch (type_) {
674!
361
  case PlotType::slice:
624✔
362
#ifdef USE_LIBPNG
363
    if (!file_extension_present(filename, "png"))
624!
364
      filename.append(".png");
624✔
365
#else
366
    if (!file_extension_present(filename, "ppm"))
367
      filename.append(".ppm");
368
#endif
369
    break;
624✔
370
  case PlotType::voxel:
50✔
371
    if (!file_extension_present(filename, "h5"))
50!
372
      filename.append(".h5");
50✔
373
    break;
50✔
374
  }
375

376
  path_plot_ = filename;
674✔
377

378
  // Copy plot pixel size
379
  vector<int> pxls = get_node_array<int>(plot_node, "pixels");
1,348✔
380
  if (PlotType::slice == type_) {
674✔
381
    if (pxls.size() == 2) {
624!
382
      pixels()[0] = pxls[0];
624✔
383
      pixels()[1] = pxls[1];
624✔
384
    } else {
385
      fatal_error(
×
386
        fmt::format("<pixels> must be length 2 in slice plot {}", id()));
×
387
    }
388
  } else if (PlotType::voxel == type_) {
50!
389
    if (pxls.size() == 3) {
50!
390
      pixels()[0] = pxls[0];
50✔
391
      pixels()[1] = pxls[1];
50✔
392
      pixels()[2] = pxls[2];
50✔
393
    } else {
394
      fatal_error(
×
395
        fmt::format("<pixels> must be length 3 in voxel plot {}", id()));
×
396
    }
397
  }
398
}
674✔
399

400
void PlottableInterface::set_bg_color(pugi::xml_node plot_node)
762✔
401
{
402
  // Copy plot background color
403
  if (check_for_node(plot_node, "background")) {
762✔
404
    vector<int> bg_rgb = get_node_array<int>(plot_node, "background");
40✔
405
    if (bg_rgb.size() == 3) {
40!
406
      not_found_ = bg_rgb;
40✔
407
    } else {
408
      fatal_error(fmt::format("Bad background RGB in plot {}", id()));
×
409
    }
410
  }
40✔
411
}
762✔
412

413
void Plot::set_basis(pugi::xml_node plot_node)
674✔
414
{
415
  // Copy plot basis
416
  if (PlotType::slice == type_) {
674✔
417
    std::string pl_basis = "xy";
624✔
418
    if (check_for_node(plot_node, "basis")) {
624!
419
      pl_basis = get_node_value(plot_node, "basis", true);
624✔
420
    }
421
    if ("xy" == pl_basis) {
624✔
422
      basis_ = PlotBasis::xy;
556✔
423
    } else if ("xz" == pl_basis) {
68✔
424
      basis_ = PlotBasis::xz;
20✔
425
    } else if ("yz" == pl_basis) {
48!
426
      basis_ = PlotBasis::yz;
48✔
427
    } else {
428
      fatal_error(
×
429
        fmt::format("Unsupported plot basis '{}' in plot {}", pl_basis, id()));
×
430
    }
431
  }
624✔
432
}
674✔
433

434
void Plot::set_origin(pugi::xml_node plot_node)
674✔
435
{
436
  // Copy plotting origin
437
  auto pl_origin = get_node_array<double>(plot_node, "origin");
674✔
438
  if (pl_origin.size() == 3) {
674!
439
    origin_ = pl_origin;
674✔
440
  } else {
441
    fatal_error(fmt::format("Origin must be length 3 in plot {}", id()));
×
442
  }
443
}
674✔
444

445
void Plot::set_width(pugi::xml_node plot_node)
674✔
446
{
447
  // Copy plotting width
448
  vector<double> pl_width = get_node_array<double>(plot_node, "width");
674✔
449
  if (PlotType::slice == type_) {
674✔
450
    if (pl_width.size() == 2) {
624!
451
      width_.x = pl_width[0];
624✔
452
      width_.y = pl_width[1];
624✔
453
    } else {
454
      fatal_error(
×
455
        fmt::format("<width> must be length 2 in slice plot {}", id()));
×
456
    }
457
  } else if (PlotType::voxel == type_) {
50!
458
    if (pl_width.size() == 3) {
50!
459
      pl_width = get_node_array<double>(plot_node, "width");
50✔
460
      width_ = pl_width;
50✔
461
    } else {
462
      fatal_error(
×
463
        fmt::format("<width> must be length 3 in voxel plot {}", id()));
×
464
    }
465
  }
466
}
674✔
467

468
void PlottableInterface::set_universe(pugi::xml_node plot_node)
762✔
469
{
470
  // Copy plot universe level
471
  if (check_for_node(plot_node, "level")) {
762!
472
    level_ = std::stoi(get_node_value(plot_node, "level"));
×
473
    if (level_ < 0) {
×
474
      fatal_error(fmt::format("Bad universe level in plot {}", id()));
×
475
    }
476
  } else {
477
    level_ = PLOT_LEVEL_LOWEST;
762✔
478
  }
479
}
762✔
480

481
void PlottableInterface::set_color_by(pugi::xml_node plot_node)
762✔
482
{
483
  // Copy plot color type
484
  std::string pl_color_by = "cell";
762✔
485
  if (check_for_node(plot_node, "color_by")) {
762✔
486
    pl_color_by = get_node_value(plot_node, "color_by", true);
732✔
487
  }
488
  if ("cell" == pl_color_by) {
762✔
489
    color_by_ = PlotColorBy::cells;
262✔
490
  } else if ("material" == pl_color_by) {
500!
491
    color_by_ = PlotColorBy::mats;
500✔
492
  } else {
493
    fatal_error(fmt::format(
×
494
      "Unsupported plot color type '{}' in plot {}", pl_color_by, id()));
×
495
  }
496
}
762✔
497

498
void PlottableInterface::set_default_colors()
772✔
499
{
500
  // Copy plot color type and initialize all colors randomly
501
  if (PlotColorBy::cells == color_by_) {
772✔
502
    colors_.resize(model::cells.size());
262✔
503
  } else if (PlotColorBy::mats == color_by_) {
510!
504
    colors_.resize(model::materials.size());
510✔
505
  }
506

507
  for (auto& c : colors_) {
3,526✔
508
    c = random_color();
2,754✔
509
    // make sure we don't interfere with some default colors
510
    while (c == RED || c == WHITE) {
2,754!
511
      c = random_color();
×
512
    }
513
  }
514
}
772✔
515

516
void PlottableInterface::set_user_colors(pugi::xml_node plot_node)
762✔
517
{
518
  for (auto cn : plot_node.children("color")) {
932✔
519
    // Make sure 3 values are specified for RGB
520
    vector<int> user_rgb = get_node_array<int>(cn, "rgb");
170✔
521
    if (user_rgb.size() != 3) {
170!
522
      fatal_error(fmt::format("Bad RGB in plot {}", id()));
×
523
    }
524
    // Ensure that there is an id for this color specification
525
    int col_id;
526
    if (check_for_node(cn, "id")) {
170!
527
      col_id = std::stoi(get_node_value(cn, "id"));
170✔
528
    } else {
529
      fatal_error(fmt::format(
×
530
        "Must specify id for color specification in plot {}", id()));
×
531
    }
532
    // Add RGB
533
    if (PlotColorBy::cells == color_by_) {
170✔
534
      if (model::cell_map.find(col_id) != model::cell_map.end()) {
80!
535
        col_id = model::cell_map[col_id];
80✔
536
        colors_[col_id] = user_rgb;
80✔
537
      } else {
538
        warning(fmt::format(
×
539
          "Could not find cell {} specified in plot {}", col_id, id()));
×
540
      }
541
    } else if (PlotColorBy::mats == color_by_) {
90!
542
      if (model::material_map.find(col_id) != model::material_map.end()) {
90!
543
        col_id = model::material_map[col_id];
90✔
544
        colors_[col_id] = user_rgb;
90✔
545
      } else {
546
        warning(fmt::format(
×
547
          "Could not find material {} specified in plot {}", col_id, id()));
×
548
      }
549
    }
550
  } // color node loop
170✔
551
}
762✔
552

553
void Plot::set_meshlines(pugi::xml_node plot_node)
674✔
554
{
555
  // Deal with meshlines
556
  pugi::xpath_node_set mesh_line_nodes = plot_node.select_nodes("meshlines");
674✔
557

558
  if (!mesh_line_nodes.empty()) {
674✔
559
    if (PlotType::voxel == type_) {
30!
560
      warning(fmt::format("Meshlines ignored in voxel plot {}", id()));
×
561
    }
562

563
    if (mesh_line_nodes.size() == 1) {
30!
564
      // Get first meshline node
565
      pugi::xml_node meshlines_node = mesh_line_nodes[0].node();
30✔
566

567
      // Check mesh type
568
      std::string meshtype;
30✔
569
      if (check_for_node(meshlines_node, "meshtype")) {
30!
570
        meshtype = get_node_value(meshlines_node, "meshtype");
30✔
571
      } else {
572
        fatal_error(fmt::format(
×
573
          "Must specify a meshtype for meshlines specification in plot {}",
574
          id()));
×
575
      }
576

577
      // Ensure that there is a linewidth for this meshlines specification
578
      std::string meshline_width;
30✔
579
      if (check_for_node(meshlines_node, "linewidth")) {
30!
580
        meshline_width = get_node_value(meshlines_node, "linewidth");
30✔
581
        meshlines_width_ = std::stoi(meshline_width);
30✔
582
      } else {
583
        fatal_error(fmt::format(
×
584
          "Must specify a linewidth for meshlines specification in plot {}",
585
          id()));
×
586
      }
587

588
      // Check for color
589
      if (check_for_node(meshlines_node, "color")) {
30!
590
        // Check and make sure 3 values are specified for RGB
591
        vector<int> ml_rgb = get_node_array<int>(meshlines_node, "color");
×
592
        if (ml_rgb.size() != 3) {
×
593
          fatal_error(
×
594
            fmt::format("Bad RGB for meshlines color in plot {}", id()));
×
595
        }
596
        meshlines_color_ = ml_rgb;
×
597
      }
×
598

599
      // Set mesh based on type
600
      if ("ufs" == meshtype) {
30!
601
        if (!simulation::ufs_mesh) {
×
602
          fatal_error(
×
603
            fmt::format("No UFS mesh for meshlines on plot {}", id()));
×
604
        } else {
605
          for (int i = 0; i < model::meshes.size(); ++i) {
×
606
            if (const auto* m =
×
607
                  dynamic_cast<const RegularMesh*>(model::meshes[i].get())) {
×
608
              if (m == simulation::ufs_mesh) {
×
609
                index_meshlines_mesh_ = i;
×
610
              }
611
            }
612
          }
613
          if (index_meshlines_mesh_ == -1)
×
614
            fatal_error("Could not find the UFS mesh for meshlines plot");
×
615
        }
616
      } else if ("entropy" == meshtype) {
30✔
617
        if (!simulation::entropy_mesh) {
20!
618
          fatal_error(
×
619
            fmt::format("No entropy mesh for meshlines on plot {}", id()));
×
620
        } else {
621
          for (int i = 0; i < model::meshes.size(); ++i) {
50✔
622
            if (const auto* m =
30✔
623
                  dynamic_cast<const RegularMesh*>(model::meshes[i].get())) {
30!
624
              if (m == simulation::entropy_mesh) {
20!
625
                index_meshlines_mesh_ = i;
20✔
626
              }
627
            }
628
          }
629
          if (index_meshlines_mesh_ == -1)
20!
630
            fatal_error("Could not find the entropy mesh for meshlines plot");
×
631
        }
632
      } else if ("tally" == meshtype) {
10!
633
        // Ensure that there is a mesh id if the type is tally
634
        int tally_mesh_id;
635
        if (check_for_node(meshlines_node, "id")) {
10!
636
          tally_mesh_id = std::stoi(get_node_value(meshlines_node, "id"));
10✔
637
        } else {
638
          std::stringstream err_msg;
×
639
          fatal_error(fmt::format("Must specify a mesh id for meshlines tally "
×
640
                                  "mesh specification in plot {}",
641
            id()));
×
642
        }
×
643
        // find the tally index
644
        int idx;
645
        int err = openmc_get_mesh_index(tally_mesh_id, &idx);
10✔
646
        if (err != 0) {
10!
647
          fatal_error(fmt::format("Could not find mesh {} specified in "
×
648
                                  "meshlines for plot {}",
649
            tally_mesh_id, id()));
×
650
        }
651
        index_meshlines_mesh_ = idx;
10✔
652
      } else {
653
        fatal_error(fmt::format("Invalid type for meshlines on plot {}", id()));
×
654
      }
655
    } else {
30✔
656
      fatal_error(fmt::format("Mutliple meshlines specified in plot {}", id()));
×
657
    }
658
  }
659
}
674✔
660

661
void PlottableInterface::set_mask(pugi::xml_node plot_node)
762✔
662
{
663
  // Deal with masks
664
  pugi::xpath_node_set mask_nodes = plot_node.select_nodes("mask");
762✔
665

666
  if (!mask_nodes.empty()) {
762✔
667
    if (mask_nodes.size() == 1) {
30!
668
      // Get pointer to mask
669
      pugi::xml_node mask_node = mask_nodes[0].node();
30✔
670

671
      // Determine how many components there are and allocate
672
      vector<int> iarray = get_node_array<int>(mask_node, "components");
30✔
673
      if (iarray.size() == 0) {
30!
674
        fatal_error(
×
675
          fmt::format("Missing <components> in mask of plot {}", id()));
×
676
      }
677

678
      // First we need to change the user-specified identifiers to indices
679
      // in the cell and material arrays
680
      for (auto& col_id : iarray) {
90✔
681
        if (PlotColorBy::cells == color_by_) {
60!
682
          if (model::cell_map.find(col_id) != model::cell_map.end()) {
60!
683
            col_id = model::cell_map[col_id];
60✔
684
          } else {
685
            fatal_error(fmt::format("Could not find cell {} specified in the "
×
686
                                    "mask in plot {}",
687
              col_id, id()));
×
688
          }
689
        } else if (PlotColorBy::mats == color_by_) {
×
690
          if (model::material_map.find(col_id) != model::material_map.end()) {
×
691
            col_id = model::material_map[col_id];
×
692
          } else {
693
            fatal_error(fmt::format("Could not find material {} specified in "
×
694
                                    "the mask in plot {}",
695
              col_id, id()));
×
696
          }
697
        }
698
      }
699

700
      // Alter colors based on mask information
701
      for (int j = 0; j < colors_.size(); j++) {
120✔
702
        if (contains(iarray, j)) {
90✔
703
          if (check_for_node(mask_node, "background")) {
60!
704
            vector<int> bg_rgb = get_node_array<int>(mask_node, "background");
60✔
705
            colors_[j] = bg_rgb;
60✔
706
          } else {
60✔
707
            colors_[j] = WHITE;
×
708
          }
709
        }
710
      }
711

712
    } else {
30✔
713
      fatal_error(fmt::format("Mutliple masks specified in plot {}", id()));
×
714
    }
715
  }
716
}
762✔
717

718
void PlottableInterface::set_overlap_color(pugi::xml_node plot_node)
762✔
719
{
720
  color_overlaps_ = false;
762✔
721
  if (check_for_node(plot_node, "show_overlaps")) {
762✔
722
    color_overlaps_ = get_node_value_bool(plot_node, "show_overlaps");
20✔
723
    // check for custom overlap color
724
    if (check_for_node(plot_node, "overlap_color")) {
20✔
725
      if (!color_overlaps_) {
10!
726
        warning(fmt::format(
×
727
          "Overlap color specified in plot {} but overlaps won't be shown.",
728
          id()));
×
729
      }
730
      vector<int> olap_clr = get_node_array<int>(plot_node, "overlap_color");
10✔
731
      if (olap_clr.size() == 3) {
10!
732
        overlap_color_ = olap_clr;
10✔
733
      } else {
734
        fatal_error(fmt::format("Bad overlap RGB in plot {}", id()));
×
735
      }
736
    }
10✔
737
  }
738

739
  // make sure we allocate the vector for counting overlap checks if
740
  // they're going to be plotted
741
  if (color_overlaps_ && settings::run_mode == RunMode::PLOTTING) {
762!
742
    settings::check_overlaps = true;
20✔
743
    model::overlap_check_count.resize(model::cells.size(), 0);
20✔
744
  }
745
}
762✔
746

747
PlottableInterface::PlottableInterface(pugi::xml_node plot_node)
762✔
748
{
749
  set_id(plot_node);
762✔
750
  set_bg_color(plot_node);
762✔
751
  set_universe(plot_node);
762✔
752
  set_color_by(plot_node);
762✔
753
  set_default_colors();
762✔
754
  set_user_colors(plot_node);
762✔
755
  set_mask(plot_node);
762✔
756
  set_overlap_color(plot_node);
762✔
757
}
762✔
758

759
Plot::Plot(pugi::xml_node plot_node, PlotType type)
682✔
760
  : PlottableInterface(plot_node), type_(type), index_meshlines_mesh_ {-1}
682✔
761
{
762
  set_output_path(plot_node);
682✔
763
  set_basis(plot_node);
674✔
764
  set_origin(plot_node);
674✔
765
  set_width(plot_node);
674✔
766
  set_meshlines(plot_node);
674✔
767
  slice_level_ = level_; // Copy level employed in SlicePlotBase::get_map
674✔
768
  slice_color_overlaps_ = color_overlaps_;
674✔
769
}
674✔
770

771
//==============================================================================
772
// OUTPUT_PPM writes out a previously generated image to a PPM file
773
//==============================================================================
774

775
void output_ppm(const std::string& filename, const ImageData& data)
×
776
{
777
  // Open PPM file for writing
778
  std::string fname = filename;
×
779
  fname = strtrim(fname);
×
780
  std::ofstream of;
×
781

782
  of.open(fname);
×
783

784
  // Write header
785
  of << "P6\n";
×
786
  of << data.shape()[0] << " " << data.shape()[1] << "\n";
×
787
  of << "255\n";
×
788
  of.close();
×
789

790
  of.open(fname, std::ios::binary | std::ios::app);
×
791
  // Write color for each pixel
792
  for (int y = 0; y < data.shape()[1]; y++) {
×
793
    for (int x = 0; x < data.shape()[0]; x++) {
×
794
      RGBColor rgb = data(x, y);
×
795
      of << rgb.red << rgb.green << rgb.blue;
×
796
    }
797
  }
798
  of << "\n";
×
799
}
×
800

801
//==============================================================================
802
// OUTPUT_PNG writes out a previously generated image to a PNG file
803
//==============================================================================
804

805
#ifdef USE_LIBPNG
806
void output_png(const std::string& filename, const ImageData& data)
210✔
807
{
808
  // Open PNG file for writing
809
  std::string fname = filename;
210✔
810
  fname = strtrim(fname);
210✔
811
  auto fp = std::fopen(fname.c_str(), "wb");
210✔
812

813
  // Initialize write and info structures
814
  auto png_ptr =
815
    png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);
210✔
816
  auto info_ptr = png_create_info_struct(png_ptr);
210✔
817

818
  // Setup exception handling
819
  if (setjmp(png_jmpbuf(png_ptr)))
210!
820
    fatal_error("Error during png creation");
×
821

822
  png_init_io(png_ptr, fp);
210✔
823

824
  // Write header (8 bit colour depth)
825
  int width = data.shape()[0];
210✔
826
  int height = data.shape()[1];
210✔
827
  png_set_IHDR(png_ptr, info_ptr, width, height, 8, PNG_COLOR_TYPE_RGB,
210✔
828
    PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
829
  png_write_info(png_ptr, info_ptr);
210✔
830

831
  // Allocate memory for one row (3 bytes per pixel - RGB)
832
  std::vector<png_byte> row(3 * width);
210✔
833

834
  // Write color for each pixel
835
  for (int y = 0; y < height; y++) {
43,410✔
836
    for (int x = 0; x < width; x++) {
10,145,200✔
837
      RGBColor rgb = data(x, y);
10,102,000✔
838
      row[3 * x] = rgb.red;
10,102,000✔
839
      row[3 * x + 1] = rgb.green;
10,102,000✔
840
      row[3 * x + 2] = rgb.blue;
10,102,000✔
841
    }
842
    png_write_row(png_ptr, row.data());
43,200✔
843
  }
844

845
  // End write
846
  png_write_end(png_ptr, nullptr);
210✔
847

848
  // Clean up data structures
849
  std::fclose(fp);
210✔
850
  png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
210✔
851
  png_destroy_write_struct(&png_ptr, &info_ptr);
210✔
852
}
210✔
853
#endif
854

855
//==============================================================================
856
// DRAW_MESH_LINES draws mesh line boundaries on an image
857
//==============================================================================
858

859
void Plot::draw_mesh_lines(ImageData& data) const
30✔
860
{
861
  RGBColor rgb;
30✔
862
  rgb = meshlines_color_;
30✔
863

864
  int ax1, ax2;
865
  switch (basis_) {
30!
866
  case PlotBasis::xy:
20✔
867
    ax1 = 0;
20✔
868
    ax2 = 1;
20✔
869
    break;
20✔
870
  case PlotBasis::xz:
10✔
871
    ax1 = 0;
10✔
872
    ax2 = 2;
10✔
873
    break;
10✔
874
  case PlotBasis::yz:
×
875
    ax1 = 1;
×
876
    ax2 = 2;
×
877
    break;
×
878
  default:
×
879
    UNREACHABLE();
×
880
  }
881

882
  Position ll_plot {origin_};
30✔
883
  Position ur_plot {origin_};
30✔
884

885
  ll_plot[ax1] -= width_[0] / 2.;
30✔
886
  ll_plot[ax2] -= width_[1] / 2.;
30✔
887
  ur_plot[ax1] += width_[0] / 2.;
30✔
888
  ur_plot[ax2] += width_[1] / 2.;
30✔
889

890
  Position width = ur_plot - ll_plot;
30✔
891

892
  // Find the (axis-aligned) lines of the mesh that intersect this plot.
893
  auto axis_lines =
894
    model::meshes[index_meshlines_mesh_]->plot(ll_plot, ur_plot);
30✔
895

896
  // Find the bounds along the second axis (accounting for low-D meshes).
897
  int ax2_min, ax2_max;
898
  if (axis_lines.second.size() > 0) {
30!
899
    double frac = (axis_lines.second.back() - ll_plot[ax2]) / width[ax2];
30✔
900
    ax2_min = (1.0 - frac) * pixels()[1];
30✔
901
    if (ax2_min < 0)
30!
902
      ax2_min = 0;
×
903
    frac = (axis_lines.second.front() - ll_plot[ax2]) / width[ax2];
30✔
904
    ax2_max = (1.0 - frac) * pixels()[1];
30✔
905
    if (ax2_max > pixels()[1])
30!
906
      ax2_max = pixels()[1];
×
907
  } else {
908
    ax2_min = 0;
×
909
    ax2_max = pixels()[1];
×
910
  }
911

912
  // Iterate across the first axis and draw lines.
913
  for (auto ax1_val : axis_lines.first) {
170✔
914
    double frac = (ax1_val - ll_plot[ax1]) / width[ax1];
140✔
915
    int ax1_ind = frac * pixels()[0];
140✔
916
    for (int ax2_ind = ax2_min; ax2_ind < ax2_max; ++ax2_ind) {
22,680✔
917
      for (int plus = 0; plus <= meshlines_width_; plus++) {
45,080✔
918
        if (ax1_ind + plus >= 0 && ax1_ind + plus < pixels()[0])
22,540!
919
          data(ax1_ind + plus, ax2_ind) = rgb;
22,540✔
920
        if (ax1_ind - plus >= 0 && ax1_ind - plus < pixels()[0])
22,540!
921
          data(ax1_ind - plus, ax2_ind) = rgb;
22,540✔
922
      }
923
    }
924
  }
925

926
  // Find the bounds along the first axis.
927
  int ax1_min, ax1_max;
928
  if (axis_lines.first.size() > 0) {
30!
929
    double frac = (axis_lines.first.front() - ll_plot[ax1]) / width[ax1];
30✔
930
    ax1_min = frac * pixels()[0];
30✔
931
    if (ax1_min < 0)
30!
932
      ax1_min = 0;
×
933
    frac = (axis_lines.first.back() - ll_plot[ax1]) / width[ax1];
30✔
934
    ax1_max = frac * pixels()[0];
30✔
935
    if (ax1_max > pixels()[0])
30!
936
      ax1_max = pixels()[0];
×
937
  } else {
938
    ax1_min = 0;
×
939
    ax1_max = pixels()[0];
×
940
  }
941

942
  // Iterate across the second axis and draw lines.
943
  for (auto ax2_val : axis_lines.second) {
190✔
944
    double frac = (ax2_val - ll_plot[ax2]) / width[ax2];
160✔
945
    int ax2_ind = (1.0 - frac) * pixels()[1];
160✔
946
    for (int ax1_ind = ax1_min; ax1_ind < ax1_max; ++ax1_ind) {
25,760✔
947
      for (int plus = 0; plus <= meshlines_width_; plus++) {
51,200✔
948
        if (ax2_ind + plus >= 0 && ax2_ind + plus < pixels()[1])
25,600!
949
          data(ax1_ind, ax2_ind + plus) = rgb;
25,600✔
950
        if (ax2_ind - plus >= 0 && ax2_ind - plus < pixels()[1])
25,600!
951
          data(ax1_ind, ax2_ind - plus) = rgb;
25,600✔
952
      }
953
    }
954
  }
955
}
30✔
956

957
/* outputs a binary file that can be input into silomesh for 3D geometry
958
 * visualization.  It works the same way as create_image by dragging a particle
959
 * across the geometry for the specified number of voxels. The first 3 int's in
960
 * the binary are the number of x, y, and z voxels.  The next 3 double's are
961
 * the widths of the voxels in the x, y, and z directions. The next 3 double's
962
 * are the x, y, and z coordinates of the lower left point. Finally the binary
963
 * is filled with entries of four int's each. Each 'row' in the binary contains
964
 * four int's: 3 for x,y,z position and 1 for cell or material id.  For 1
965
 * million voxels this produces a file of approximately 15MB.
966
 */
967
void Plot::create_voxel() const
50✔
968
{
969
  // compute voxel widths in each direction
970
  array<double, 3> vox;
971
  vox[0] = width_[0] / static_cast<double>(pixels()[0]);
50✔
972
  vox[1] = width_[1] / static_cast<double>(pixels()[1]);
50✔
973
  vox[2] = width_[2] / static_cast<double>(pixels()[2]);
50✔
974

975
  // initial particle position
976
  Position ll = origin_ - width_ / 2.;
50✔
977

978
  // Open binary plot file for writing
979
  std::ofstream of;
50✔
980
  std::string fname = std::string(path_plot_);
50✔
981
  fname = strtrim(fname);
50✔
982
  hid_t file_id = file_open(fname, 'w');
50✔
983

984
  // write header info
985
  write_attribute(file_id, "filetype", "voxel");
50✔
986
  write_attribute(file_id, "version", VERSION_VOXEL);
50✔
987
  write_attribute(file_id, "openmc_version", VERSION);
50✔
988

989
#ifdef GIT_SHA1
990
  write_attribute(file_id, "git_sha1", GIT_SHA1);
991
#endif
992

993
  // Write current date and time
994
  write_attribute(file_id, "date_and_time", time_stamp().c_str());
50✔
995
  array<int, 3> h5_pixels;
996
  std::copy(pixels().begin(), pixels().end(), h5_pixels.begin());
50✔
997
  write_attribute(file_id, "num_voxels", h5_pixels);
50✔
998
  write_attribute(file_id, "voxel_width", vox);
50✔
999
  write_attribute(file_id, "lower_left", ll);
50✔
1000

1001
  // Create dataset for voxel data -- note that the dimensions are reversed
1002
  // since we want the order in the file to be z, y, x
1003
  hsize_t dims[3];
1004
  dims[0] = pixels()[2];
50✔
1005
  dims[1] = pixels()[1];
50✔
1006
  dims[2] = pixels()[0];
50✔
1007
  hid_t dspace, dset, memspace;
1008
  voxel_init(file_id, &(dims[0]), &dspace, &dset, &memspace);
50✔
1009

1010
  SlicePlotBase pltbase;
50✔
1011
  pltbase.width_ = width_;
50✔
1012
  pltbase.origin_ = origin_;
50✔
1013
  pltbase.basis_ = PlotBasis::xy;
50✔
1014
  pltbase.pixels() = pixels();
50✔
1015
  pltbase.slice_color_overlaps_ = color_overlaps_;
50✔
1016

1017
  ProgressBar pb;
50✔
1018
  for (int z = 0; z < pixels()[2]; z++) {
4,350✔
1019
    // update z coordinate
1020
    pltbase.origin_.z = ll.z + z * vox[2];
4,300✔
1021

1022
    // generate ids using plotbase
1023
    IdData ids = pltbase.get_map<IdData>();
4,300✔
1024

1025
    // select only cell/material ID data and flip the y-axis
1026
    int idx = color_by_ == PlotColorBy::cells ? 0 : 2;
4,300!
1027
    xt::xtensor<int32_t, 2> data_slice =
1028
      xt::view(ids.data_, xt::all(), xt::all(), idx);
4,300✔
1029
    xt::xtensor<int32_t, 2> data_flipped = xt::flip(data_slice, 0);
4,300✔
1030

1031
    // Write to HDF5 dataset
1032
    voxel_write_slice(z, dspace, dset, memspace, data_flipped.data());
4,300✔
1033

1034
    // update progress bar
1035
    pb.set_value(
4,300✔
1036
      100. * static_cast<double>(z + 1) / static_cast<double>((pixels()[2])));
4,300✔
1037
  }
4,300✔
1038

1039
  voxel_finalize(dspace, dset, memspace);
50✔
1040
  file_close(file_id);
50✔
1041
}
50✔
1042

1043
void voxel_init(hid_t file_id, const hsize_t* dims, hid_t* dspace, hid_t* dset,
50✔
1044
  hid_t* memspace)
1045
{
1046
  // Create dataspace/dataset for voxel data
1047
  *dspace = H5Screate_simple(3, dims, nullptr);
50✔
1048
  *dset = H5Dcreate(file_id, "data", H5T_NATIVE_INT, *dspace, H5P_DEFAULT,
50✔
1049
    H5P_DEFAULT, H5P_DEFAULT);
1050

1051
  // Create dataspace for a slice of the voxel
1052
  hsize_t dims_slice[2] {dims[1], dims[2]};
50✔
1053
  *memspace = H5Screate_simple(2, dims_slice, nullptr);
50✔
1054

1055
  // Select hyperslab in dataspace
1056
  hsize_t start[3] {0, 0, 0};
50✔
1057
  hsize_t count[3] {1, dims[1], dims[2]};
50✔
1058
  H5Sselect_hyperslab(*dspace, H5S_SELECT_SET, start, nullptr, count, nullptr);
50✔
1059
}
50✔
1060

1061
void voxel_write_slice(
4,300✔
1062
  int x, hid_t dspace, hid_t dset, hid_t memspace, void* buf)
1063
{
1064
  hssize_t offset[3] {x, 0, 0};
4,300✔
1065
  H5Soffset_simple(dspace, offset);
4,300✔
1066
  H5Dwrite(dset, H5T_NATIVE_INT, memspace, dspace, H5P_DEFAULT, buf);
4,300✔
1067
}
4,300✔
1068

1069
void voxel_finalize(hid_t dspace, hid_t dset, hid_t memspace)
50✔
1070
{
1071
  H5Dclose(dset);
50✔
1072
  H5Sclose(dspace);
50✔
1073
  H5Sclose(memspace);
50✔
1074
}
50✔
1075

1076
RGBColor random_color(void)
2,754✔
1077
{
1078
  return {int(prn(&model::plotter_seed) * 255),
2,754✔
1079
    int(prn(&model::plotter_seed) * 255), int(prn(&model::plotter_seed) * 255)};
2,754✔
1080
}
1081

1082
RayTracePlot::RayTracePlot(pugi::xml_node node) : PlottableInterface(node)
80✔
1083
{
1084
  set_look_at(node);
80✔
1085
  set_camera_position(node);
80✔
1086
  set_field_of_view(node);
80✔
1087
  set_pixels(node);
80✔
1088
  set_orthographic_width(node);
80✔
1089
  set_output_path(node);
80✔
1090

1091
  if (check_for_node(node, "orthographic_width") &&
90!
1092
      check_for_node(node, "field_of_view"))
10!
1093
    fatal_error("orthographic_width and field_of_view are mutually exclusive "
×
1094
                "parameters.");
1095
}
80✔
1096

1097
void RayTracePlot::update_view()
100✔
1098
{
1099
  // Get centerline vector for camera-to-model. We create vectors around this
1100
  // that form a pixel array, and then trace rays along that.
1101
  auto up = up_ / up_.norm();
100✔
1102
  Direction looking_direction = look_at_ - camera_position_;
100✔
1103
  looking_direction /= looking_direction.norm();
100✔
1104
  if (std::abs(std::abs(looking_direction.dot(up)) - 1.0) < 1e-9)
100!
1105
    fatal_error("Up vector cannot align with vector between camera position "
×
1106
                "and look_at!");
1107
  Direction cam_yaxis = looking_direction.cross(up);
100✔
1108
  cam_yaxis /= cam_yaxis.norm();
100✔
1109
  Direction cam_zaxis = cam_yaxis.cross(looking_direction);
100✔
1110
  cam_zaxis /= cam_zaxis.norm();
100✔
1111

1112
  // Cache the camera-to-model matrix
1113
  camera_to_model_ = {looking_direction.x, cam_yaxis.x, cam_zaxis.x,
100✔
1114
    looking_direction.y, cam_yaxis.y, cam_zaxis.y, looking_direction.z,
100✔
1115
    cam_yaxis.z, cam_zaxis.z};
100✔
1116
}
100✔
1117

1118
WireframeRayTracePlot::WireframeRayTracePlot(pugi::xml_node node)
50✔
1119
  : RayTracePlot(node)
50✔
1120
{
1121
  set_opacities(node);
50✔
1122
  set_wireframe_thickness(node);
50✔
1123
  set_wireframe_ids(node);
50✔
1124
  set_wireframe_color(node);
50✔
1125
  update_view();
50✔
1126
}
50✔
1127

1128
void WireframeRayTracePlot::set_wireframe_color(pugi::xml_node plot_node)
50✔
1129
{
1130
  // Copy plot wireframe color
1131
  if (check_for_node(plot_node, "wireframe_color")) {
50!
1132
    vector<int> w_rgb = get_node_array<int>(plot_node, "wireframe_color");
×
1133
    if (w_rgb.size() == 3) {
×
1134
      wireframe_color_ = w_rgb;
×
1135
    } else {
1136
      fatal_error(fmt::format("Bad wireframe RGB in plot {}", id()));
×
1137
    }
1138
  }
×
1139
}
50✔
1140

1141
void RayTracePlot::set_output_path(pugi::xml_node node)
80✔
1142
{
1143
  // Set output file path
1144
  std::string filename;
80✔
1145

1146
  if (check_for_node(node, "filename")) {
80✔
1147
    filename = get_node_value(node, "filename");
70✔
1148
  } else {
1149
    filename = fmt::format("plot_{}", id());
20✔
1150
  }
1151

1152
#ifdef USE_LIBPNG
1153
  if (!file_extension_present(filename, "png"))
80✔
1154
    filename.append(".png");
30✔
1155
#else
1156
  if (!file_extension_present(filename, "ppm"))
1157
    filename.append(".ppm");
1158
#endif
1159
  path_plot_ = filename;
80✔
1160
}
80✔
1161

1162
bool WireframeRayTracePlot::trackstack_equivalent(
2,764,690✔
1163
  const std::vector<TrackSegment>& track1,
1164
  const std::vector<TrackSegment>& track2) const
1165
{
1166
  if (wireframe_ids_.empty()) {
2,764,690✔
1167
    // Draw wireframe for all surfaces/cells/materials
1168
    if (track1.size() != track2.size())
2,313,700✔
1169
      return false;
49,070✔
1170
    for (int i = 0; i < track1.size(); ++i) {
6,098,140✔
1171
      if (track1[i].id != track2[i].id ||
7,703,100✔
1172
          track1[i].surface_index != track2[i].surface_index) {
3,851,490✔
1173
        return false;
18,100✔
1174
      }
1175
    }
1176
    return true;
2,246,530✔
1177
  } else {
1178
    // This runs in O(nm) where n is the intersection stack size
1179
    // and m is the number of IDs we are wireframing. A simpler
1180
    // algorithm can likely be found.
1181
    for (const int id : wireframe_ids_) {
896,540✔
1182
      int t1_i = 0;
450,990✔
1183
      int t2_i = 0;
450,990✔
1184

1185
      // Advance to first instance of the ID
1186
      while (t1_i < track1.size() && t2_i < track2.size()) {
511,300✔
1187
        while (t1_i < track1.size() && track1[t1_i].id != id)
357,120✔
1188
          t1_i++;
208,230✔
1189
        while (t2_i < track2.size() && track2[t2_i].id != id)
357,880✔
1190
          t2_i++;
208,990✔
1191

1192
        // This one is really important!
1193
        if ((t1_i == track1.size() && t2_i != track2.size()) ||
360,470✔
1194
            (t1_i != track1.size() && t2_i == track2.size()))
211,580✔
1195
          return false;
5,440✔
1196
        if (t1_i == track1.size() && t2_i == track2.size())
145,510!
1197
          break;
83,140✔
1198
        // Check if surface different
1199
        if (track1[t1_i].surface_index != track2[t2_i].surface_index)
62,370✔
1200
          return false;
1,350✔
1201

1202
        // Pretty sure this should not be used:
1203
        // if (t2_i != track2.size() - 1 &&
1204
        //     t1_i != track1.size() - 1 &&
1205
        //     track1[t1_i+1].id != track2[t2_i+1].id) return false;
1206
        if (t2_i != 0 && t1_i != 0 &&
110,060!
1207
            track1[t1_i - 1].surface_index != track2[t2_i - 1].surface_index)
49,040✔
1208
          return false;
710✔
1209

1210
        // Check if neighboring cells are different
1211
        // if (track1[t1_i ? t1_i - 1 : 0].id != track2[t2_i ? t2_i - 1 : 0].id)
1212
        // return false; if (track1[t1_i < track1.size() - 1 ? t1_i + 1 : t1_i
1213
        // ].id !=
1214
        //    track2[t2_i < track2.size() - 1 ? t2_i + 1 : t2_i].id) return
1215
        //    false;
1216
        t1_i++, t2_i++;
60,310✔
1217
      }
1218
    }
1219
    return true;
445,550✔
1220
  }
1221
}
1222

1223
std::pair<Position, Direction> RayTracePlot::get_pixel_ray(
3,200,960✔
1224
  int horiz, int vert) const
1225
{
1226
  // Compute field of view in radians
1227
  constexpr double DEGREE_TO_RADIAN = M_PI / 180.0;
3,200,960✔
1228
  double horiz_fov_radians = horizontal_field_of_view_ * DEGREE_TO_RADIAN;
3,200,960✔
1229
  double p0 = static_cast<double>(pixels()[0]);
3,200,960✔
1230
  double p1 = static_cast<double>(pixels()[1]);
3,200,960✔
1231
  double vert_fov_radians = horiz_fov_radians * p1 / p0;
3,200,960✔
1232

1233
  // focal_plane_dist can be changed to alter the perspective distortion
1234
  // effect. This is in units of cm. This seems to look good most of the
1235
  // time. TODO let this variable be set through XML.
1236
  constexpr double focal_plane_dist = 10.0;
3,200,960✔
1237
  const double dx = 2.0 * focal_plane_dist * std::tan(0.5 * horiz_fov_radians);
3,200,960✔
1238
  const double dy = p1 / p0 * dx;
3,200,960✔
1239

1240
  std::pair<Position, Direction> result;
3,200,960✔
1241

1242
  // Generate the starting position/direction of the ray
1243
  if (orthographic_width_ == C_NONE) { // perspective projection
3,200,960✔
1244
    Direction camera_local_vec;
2,800,960✔
1245
    camera_local_vec.x = focal_plane_dist;
2,800,960✔
1246
    camera_local_vec.y = -0.5 * dx + horiz * dx / p0;
2,800,960✔
1247
    camera_local_vec.z = 0.5 * dy - vert * dy / p1;
2,800,960✔
1248
    camera_local_vec /= camera_local_vec.norm();
2,800,960✔
1249

1250
    result.first = camera_position_;
2,800,960✔
1251
    result.second = camera_local_vec.rotate(camera_to_model_);
2,800,960✔
1252
  } else { // orthographic projection
1253

1254
    double x_pix_coord = (static_cast<double>(horiz) - p0 / 2.0) / p0;
400,000✔
1255
    double y_pix_coord = (static_cast<double>(vert) - p1 / 2.0) / p1;
400,000✔
1256

1257
    result.first = camera_position_ +
1258
                   camera_y_axis() * x_pix_coord * orthographic_width_ +
400,000✔
1259
                   camera_z_axis() * y_pix_coord * orthographic_width_;
400,000✔
1260
    result.second = camera_x_axis();
400,000✔
1261
  }
1262

1263
  return result;
3,200,960✔
1264
}
1265

1266
ImageData WireframeRayTracePlot::create_image() const
50✔
1267
{
1268
  size_t width = pixels()[0];
50✔
1269
  size_t height = pixels()[1];
50✔
1270
  ImageData data({width, height}, not_found_);
50✔
1271

1272
  // This array marks where the initial wireframe was drawn. We convolve it with
1273
  // a filter that gets adjusted with the wireframe thickness in order to
1274
  // thicken the lines.
1275
  xt::xtensor<int, 2> wireframe_initial({width, height}, 0);
50✔
1276

1277
  /* Holds all of the track segments for the current rendered line of pixels.
1278
   * old_segments holds a copy of this_line_segments from the previous line.
1279
   * By holding both we can check if the cell/material intersection stack
1280
   * differs from the left or upper neighbor. This allows a robustly drawn
1281
   * wireframe. If only checking the left pixel (which requires substantially
1282
   * less memory), the wireframe tends to be spotty and be disconnected for
1283
   * surface edges oriented horizontally in the rendering.
1284
   *
1285
   * Note that a vector of vectors is required rather than a 2-tensor,
1286
   * since the stack size varies within each column.
1287
   */
1288
  const int n_threads = num_threads();
50✔
1289
  std::vector<std::vector<std::vector<TrackSegment>>> this_line_segments(
1290
    n_threads);
50✔
1291
  for (int t = 0; t < n_threads; ++t) {
130✔
1292
    this_line_segments[t].resize(pixels()[0]);
80✔
1293
  }
1294

1295
  // The last thread writes to this, and the first thread reads from it.
1296
  std::vector<std::vector<TrackSegment>> old_segments(pixels()[0]);
50✔
1297

1298
#pragma omp parallel
30✔
1299
  {
1300
    const int n_threads = num_threads();
20✔
1301
    const int tid = thread_num();
20✔
1302

1303
    int vert = tid;
20✔
1304
    for (int iter = 0; iter <= pixels()[1] / n_threads; iter++) {
4,040✔
1305

1306
      // Save bottom line of current work chunk to compare against later. This
1307
      // used to be inside the below if block, but it causes a spurious line to
1308
      // be drawn at the bottom of the image. Not sure why, but moving it here
1309
      // fixes things.
1310
      if (tid == n_threads - 1)
4,020!
1311
        old_segments = this_line_segments[n_threads - 1];
4,020✔
1312

1313
      if (vert < pixels()[1]) {
4,020✔
1314

1315
        for (int horiz = 0; horiz < pixels()[0]; ++horiz) {
804,000✔
1316

1317
          // RayTracePlot implements camera ray generation
1318
          std::pair<Position, Direction> ru = get_pixel_ray(horiz, vert);
800,000✔
1319

1320
          this_line_segments[tid][horiz].clear();
800,000✔
1321
          ProjectionRay ray(
1322
            ru.first, ru.second, *this, this_line_segments[tid][horiz]);
800,000✔
1323

1324
          ray.trace();
800,000✔
1325

1326
          // Now color the pixel based on what we have intersected...
1327
          // Loops backwards over intersections.
1328
          Position current_color(
1329
            not_found_.red, not_found_.green, not_found_.blue);
800,000✔
1330
          const auto& segments = this_line_segments[tid][horiz];
800,000✔
1331

1332
          // There must be at least two cell intersections to color, front and
1333
          // back of the cell. Maybe an infinitely thick cell could be present
1334
          // with no back, but why would you want to color that? It's easier to
1335
          // just skip that edge case and not even color it.
1336
          if (segments.size() <= 1)
800,000✔
1337
            continue;
493,324✔
1338

1339
          for (int i = segments.size() - 2; i >= 0; --i) {
857,868✔
1340
            int colormap_idx = segments[i].id;
551,192✔
1341
            RGBColor seg_color = colors_[colormap_idx];
551,192✔
1342
            Position seg_color_vec(
1343
              seg_color.red, seg_color.green, seg_color.blue);
551,192✔
1344
            double mixing =
1345
              std::exp(-xs_[colormap_idx] *
551,192✔
1346
                       (segments[i + 1].length - segments[i].length));
551,192✔
1347
            current_color =
1348
              current_color * mixing + (1.0 - mixing) * seg_color_vec;
551,192✔
1349
          }
1350

1351
          // save result converting from double-precision color coordinates to
1352
          // byte-sized
1353
          RGBColor result;
306,676✔
1354
          result.red = static_cast<uint8_t>(current_color.x);
306,676✔
1355
          result.green = static_cast<uint8_t>(current_color.y);
306,676✔
1356
          result.blue = static_cast<uint8_t>(current_color.z);
306,676✔
1357
          data(horiz, vert) = result;
306,676✔
1358

1359
          // Check to draw wireframe in horizontal direction. No inter-thread
1360
          // comm.
1361
          if (horiz > 0) {
306,676✔
1362
            if (!trackstack_equivalent(this_line_segments[tid][horiz],
305,876✔
1363
                  this_line_segments[tid][horiz - 1])) {
305,876✔
1364
              wireframe_initial(horiz, vert) = 1;
12,568✔
1365
            }
1366
          }
1367
        }
800,000✔
1368
      } // end "if" vert in correct range
1369

1370
      // We require a barrier before comparing vertical neighbors' intersection
1371
      // stacks. i.e. all threads must be done with their line.
1372
#pragma omp barrier
1373

1374
      // Now that the horizontal line has finished rendering, we can fill in
1375
      // wireframe entries that require comparison among all the threads. Hence
1376
      // the omp barrier being used. It has to be OUTSIDE any if blocks!
1377
      if (vert < pixels()[1]) {
4,020✔
1378
        // Loop over horizontal pixels, checking intersection stack of upper
1379
        // neighbor
1380

1381
        const std::vector<std::vector<TrackSegment>>* top_cmp = nullptr;
4,000✔
1382
        if (tid == 0)
4,000!
1383
          top_cmp = &old_segments;
4,000✔
1384
        else
1385
          top_cmp = &this_line_segments[tid - 1];
1386

1387
        for (int horiz = 0; horiz < pixels()[0]; ++horiz) {
804,000✔
1388
          if (!trackstack_equivalent(
800,000✔
1389
                this_line_segments[tid][horiz], (*top_cmp)[horiz])) {
800,000✔
1390
            wireframe_initial(horiz, vert) = 1;
16,476✔
1391
          }
1392
        }
1393
      }
1394

1395
      // We need another barrier to ensure threads don't proceed to modify their
1396
      // intersection stacks on that horizontal line while others are
1397
      // potentially still working on the above.
1398
#pragma omp barrier
1399
      vert += n_threads;
4,020✔
1400
    }
1401
  } // end omp parallel
1402

1403
  // Now thicken the wireframe lines and apply them to our image
1404
  for (int vert = 0; vert < pixels()[1]; ++vert) {
10,050✔
1405
    for (int horiz = 0; horiz < pixels()[0]; ++horiz) {
2,010,000✔
1406
      if (wireframe_initial(horiz, vert)) {
2,000,000✔
1407
        if (wireframe_thickness_ == 1)
64,530✔
1408
          data(horiz, vert) = wireframe_color_;
27,450✔
1409
        for (int i = -wireframe_thickness_ / 2; i < wireframe_thickness_ / 2;
177,930✔
1410
             ++i)
1411
          for (int j = -wireframe_thickness_ / 2; j < wireframe_thickness_ / 2;
497,160✔
1412
               ++j)
1413
            if (i * i + j * j < wireframe_thickness_ * wireframe_thickness_) {
383,760!
1414

1415
              // Check if wireframe pixel is out of bounds
1416
              int w_i = std::max(std::min(horiz + i, pixels()[0] - 1), 0);
383,760✔
1417
              int w_j = std::max(std::min(vert + j, pixels()[1] - 1), 0);
383,760✔
1418
              data(w_i, w_j) = wireframe_color_;
383,760✔
1419
            }
1420
      }
1421
    }
1422
  }
1423

1424
  return data;
100✔
1425
}
50✔
1426

1427
void WireframeRayTracePlot::create_output() const
50✔
1428
{
1429
  ImageData data = create_image();
50✔
1430
  write_image(data);
50✔
1431
}
50✔
1432

1433
void RayTracePlot::print_info() const
80✔
1434
{
1435
  fmt::print("Camera position: {} {} {}\n", camera_position_.x,
64✔
1436
    camera_position_.y, camera_position_.z);
80✔
1437
  fmt::print("Look at: {} {} {}\n", look_at_.x, look_at_.y, look_at_.z);
144✔
1438
  fmt::print(
64✔
1439
    "Horizontal field of view: {} degrees\n", horizontal_field_of_view_);
80✔
1440
  fmt::print("Pixels: {} {}\n", pixels()[0], pixels()[1]);
144✔
1441
}
80✔
1442

1443
void WireframeRayTracePlot::print_info() const
50✔
1444
{
1445
  fmt::print("Plot Type: Wireframe ray-traced\n");
50✔
1446
  RayTracePlot::print_info();
50✔
1447
}
50✔
1448

1449
void WireframeRayTracePlot::set_opacities(pugi::xml_node node)
50✔
1450
{
1451
  xs_.resize(colors_.size(), 1e6); // set to large value for opaque by default
50✔
1452

1453
  for (auto cn : node.children("color")) {
110✔
1454
    // Make sure 3 values are specified for RGB
1455
    double user_xs = std::stod(get_node_value(cn, "xs"));
60✔
1456
    int col_id = std::stoi(get_node_value(cn, "id"));
60✔
1457

1458
    // Add RGB
1459
    if (PlotColorBy::cells == color_by_) {
60!
1460
      if (model::cell_map.find(col_id) != model::cell_map.end()) {
60!
1461
        col_id = model::cell_map[col_id];
60✔
1462
        xs_[col_id] = user_xs;
60✔
1463
      } else {
1464
        warning(fmt::format(
×
1465
          "Could not find cell {} specified in plot {}", col_id, id()));
×
1466
      }
1467
    } else if (PlotColorBy::mats == color_by_) {
×
1468
      if (model::material_map.find(col_id) != model::material_map.end()) {
×
1469
        col_id = model::material_map[col_id];
×
1470
        xs_[col_id] = user_xs;
×
1471
      } else {
1472
        warning(fmt::format(
×
1473
          "Could not find material {} specified in plot {}", col_id, id()));
×
1474
      }
1475
    }
1476
  }
1477
}
50✔
1478

1479
void RayTracePlot::set_orthographic_width(pugi::xml_node node)
80✔
1480
{
1481
  if (check_for_node(node, "orthographic_width")) {
80✔
1482
    double orthographic_width =
1483
      std::stod(get_node_value(node, "orthographic_width", true));
10✔
1484
    if (orthographic_width < 0.0)
10!
1485
      fatal_error("Requires positive orthographic_width");
×
1486
    orthographic_width_ = orthographic_width;
10✔
1487
  }
1488
}
80✔
1489

1490
void WireframeRayTracePlot::set_wireframe_thickness(pugi::xml_node node)
50✔
1491
{
1492
  if (check_for_node(node, "wireframe_thickness")) {
50✔
1493
    int wireframe_thickness =
1494
      std::stoi(get_node_value(node, "wireframe_thickness", true));
20✔
1495
    if (wireframe_thickness < 0)
20!
1496
      fatal_error("Requires non-negative wireframe thickness");
×
1497
    wireframe_thickness_ = wireframe_thickness;
20✔
1498
  }
1499
}
50✔
1500

1501
void WireframeRayTracePlot::set_wireframe_ids(pugi::xml_node node)
50✔
1502
{
1503
  if (check_for_node(node, "wireframe_ids")) {
50✔
1504
    wireframe_ids_ = get_node_array<int>(node, "wireframe_ids");
10✔
1505
    // It is read in as actual ID values, but we have to convert to indices in
1506
    // mat/cell array
1507
    for (auto& x : wireframe_ids_)
20✔
1508
      x = color_by_ == PlotColorBy::mats ? model::material_map[x]
10!
1509
                                         : model::cell_map[x];
×
1510
  }
1511
  // We make sure the list is sorted in order to later use
1512
  // std::binary_search.
1513
  std::sort(wireframe_ids_.begin(), wireframe_ids_.end());
50✔
1514
}
50✔
1515

1516
void RayTracePlot::set_pixels(pugi::xml_node node)
80✔
1517
{
1518
  vector<int> pxls = get_node_array<int>(node, "pixels");
80✔
1519
  if (pxls.size() != 2)
80!
1520
    fatal_error(
×
1521
      fmt::format("<pixels> must be length 2 in projection plot {}", id()));
×
1522
  pixels()[0] = pxls[0];
80✔
1523
  pixels()[1] = pxls[1];
80✔
1524
}
80✔
1525

1526
void RayTracePlot::set_camera_position(pugi::xml_node node)
80✔
1527
{
1528
  vector<double> camera_pos = get_node_array<double>(node, "camera_position");
80✔
1529
  if (camera_pos.size() != 3) {
80!
1530
    fatal_error(fmt::format(
×
1531
      "camera_position element must have three floating point values"));
1532
  }
1533
  camera_position_.x = camera_pos[0];
80✔
1534
  camera_position_.y = camera_pos[1];
80✔
1535
  camera_position_.z = camera_pos[2];
80✔
1536
}
80✔
1537

1538
void RayTracePlot::set_look_at(pugi::xml_node node)
80✔
1539
{
1540
  vector<double> look_at = get_node_array<double>(node, "look_at");
80✔
1541
  if (look_at.size() != 3) {
80!
1542
    fatal_error("look_at element must have three floating point values");
×
1543
  }
1544
  look_at_.x = look_at[0];
80✔
1545
  look_at_.y = look_at[1];
80✔
1546
  look_at_.z = look_at[2];
80✔
1547
}
80✔
1548

1549
void RayTracePlot::set_field_of_view(pugi::xml_node node)
80✔
1550
{
1551
  // Defaults to 70 degree horizontal field of view (see .h file)
1552
  if (check_for_node(node, "horizontal_field_of_view")) {
80!
1553
    double fov =
1554
      std::stod(get_node_value(node, "horizontal_field_of_view", true));
×
1555
    if (fov < 180.0 && fov > 0.0) {
×
1556
      horizontal_field_of_view_ = fov;
×
1557
    } else {
1558
      fatal_error(fmt::format("Horizontal field of view for plot {} "
×
1559
                              "out-of-range. Must be in (0, 180) degrees.",
1560
        id()));
×
1561
    }
1562
  }
1563
}
80✔
1564

1565
SolidRayTracePlot::SolidRayTracePlot(pugi::xml_node node) : RayTracePlot(node)
30✔
1566
{
1567
  set_opaque_ids(node);
30✔
1568
  set_diffuse_fraction(node);
30✔
1569
  set_light_position(node);
30✔
1570
  update_view();
30✔
1571
}
30✔
1572

1573
void SolidRayTracePlot::print_info() const
30✔
1574
{
1575
  fmt::print("Plot Type: Solid ray-traced\n");
30✔
1576
  RayTracePlot::print_info();
30✔
1577
}
30✔
1578

1579
ImageData SolidRayTracePlot::create_image() const
50✔
1580
{
1581
  size_t width = pixels()[0];
50✔
1582
  size_t height = pixels()[1];
50✔
1583
  ImageData data({width, height}, not_found_);
50✔
1584

1585
#pragma omp parallel for schedule(dynamic) collapse(2)
30✔
1586
  for (int horiz = 0; horiz < pixels()[0]; ++horiz) {
2,484✔
1587
    for (int vert = 0; vert < pixels()[1]; ++vert) {
482,848✔
1588
      // RayTracePlot implements camera ray generation
1589
      std::pair<Position, Direction> ru = get_pixel_ray(horiz, vert);
480,384✔
1590
      PhongRay ray(ru.first, ru.second, *this);
480,384✔
1591
      ray.trace();
480,384✔
1592
      data(horiz, vert) = ray.result_color();
480,384✔
1593
    }
480,384✔
1594
  }
1595

1596
  return data;
50✔
1597
}
1598

1599
void SolidRayTracePlot::create_output() const
30✔
1600
{
1601
  ImageData data = create_image();
30✔
1602
  write_image(data);
30✔
1603
}
30✔
1604

1605
void SolidRayTracePlot::set_opaque_ids(pugi::xml_node node)
30✔
1606
{
1607
  if (check_for_node(node, "opaque_ids")) {
30!
1608
    auto opaque_ids_tmp = get_node_array<int>(node, "opaque_ids");
30✔
1609

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 : opaque_ids_tmp)
90✔
1613
      x = color_by_ == PlotColorBy::mats ? model::material_map[x]
60!
1614
                                         : model::cell_map[x];
×
1615

1616
    opaque_ids_.insert(opaque_ids_tmp.begin(), opaque_ids_tmp.end());
30✔
1617
  }
30✔
1618
}
30✔
1619

1620
void SolidRayTracePlot::set_light_position(pugi::xml_node node)
30✔
1621
{
1622
  if (check_for_node(node, "light_position")) {
30✔
1623
    auto light_pos_tmp = get_node_array<double>(node, "light_position");
10✔
1624

1625
    if (light_pos_tmp.size() != 3)
10!
1626
      fatal_error("Light position must be given as 3D coordinates");
×
1627

1628
    light_location_.x = light_pos_tmp[0];
10✔
1629
    light_location_.y = light_pos_tmp[1];
10✔
1630
    light_location_.z = light_pos_tmp[2];
10✔
1631
  } else {
10✔
1632
    light_location_ = camera_position();
20✔
1633
  }
1634
}
30✔
1635

1636
void SolidRayTracePlot::set_diffuse_fraction(pugi::xml_node node)
30✔
1637
{
1638
  if (check_for_node(node, "diffuse_fraction")) {
30✔
1639
    diffuse_fraction_ = std::stod(get_node_value(node, "diffuse_fraction"));
10✔
1640
    if (diffuse_fraction_ < 0.0 || diffuse_fraction_ > 1.0) {
10!
1641
      fatal_error("Must have 0 <= diffuse fraction <= 1");
×
1642
    }
1643
  }
1644
}
30✔
1645

1646
void Ray::compute_distance()
2,740,580✔
1647
{
1648
  boundary() = distance_to_boundary(*this);
2,740,580✔
1649
}
2,740,580✔
1650

1651
void Ray::trace()
3,200,960✔
1652
{
1653
  // To trace the ray from its origin all the way through the model, we have
1654
  // to proceed in two phases. In the first, the ray may or may not be found
1655
  // inside the model. If the ray is already in the model, phase one can be
1656
  // skipped. Otherwise, the ray has to be advanced to the boundary of the
1657
  // model where all the cells are defined. Importantly, this is assuming that
1658
  // the model is convex, which is a very reasonable assumption for any
1659
  // radiation transport model.
1660
  //
1661
  // After phase one is done, we can starting tracing from cell to cell within
1662
  // the model. This step can use neighbor lists to accelerate the ray tracing.
1663

1664
  // Attempt to initialize the particle. We may have to enter a loop to move
1665
  // it up to the edge of the model.
1666
  bool inside_cell = exhaustive_find_cell(*this, settings::verbosity >= 10);
3,200,960✔
1667

1668
  // Advance to the boundary of the model
1669
  while (!inside_cell) {
14,198,580!
1670
    advance_to_boundary_from_void();
14,198,580✔
1671
    inside_cell = exhaustive_find_cell(*this, settings::verbosity >= 10);
14,198,580✔
1672

1673
    // If true this means no surface was intersected. See cell.cpp and search
1674
    // for numeric_limits to see where we return it.
1675
    if (surface() == std::numeric_limits<int>::max()) {
14,198,580!
1676
      warning(fmt::format("Lost a ray, r = {}, u = {}", r(), u()));
×
1677
      return;
×
1678
    }
1679

1680
    // Exit this loop and enter into cell-to-cell ray tracing (which uses
1681
    // neighbor lists)
1682
    if (inside_cell)
14,198,580✔
1683
      break;
1,408,940✔
1684

1685
    // if there is no intersection with the model, we're done
1686
    if (boundary().surface() == SURFACE_NONE)
12,789,640✔
1687
      return;
1,792,020✔
1688

1689
    event_counter_++;
10,997,620✔
1690
    if (event_counter_ > MAX_INTERSECTIONS) {
10,997,620!
1691
      warning("Likely infinite loop in ray traced plot");
×
1692
      return;
×
1693
    }
1694
  }
1695

1696
  // Call the specialized logic for this type of ray. This is for the
1697
  // intersection for the first intersection if we had one.
1698
  if (boundary().surface() != SURFACE_NONE) {
1,408,940!
1699
    // set the geometry state's surface attribute to be used for
1700
    // surface normal computation
1701
    surface() = boundary().surface();
1,408,940✔
1702
    on_intersection();
1,408,940✔
1703
    if (stop_)
1,408,940!
1704
      return;
×
1705
  }
1706

1707
  // reset surface attribute to zero after the first intersection so that it
1708
  // doesn't perturb surface crossing logic from here on out
1709
  surface() = 0;
1,408,940✔
1710

1711
  // This is the ray tracing loop within the model. It exits after exiting
1712
  // the model, which is equivalent to assuming that the model is convex.
1713
  // It would be nice to factor out the on_intersection at the end of this
1714
  // loop and then do "while (inside_cell)", but we can't guarantee it's
1715
  // on a surface in that case. There might be some other way to set it
1716
  // up that is perhaps a little more elegant, but this is what works just
1717
  // fine.
1718
  while (true) {
1719

1720
    compute_distance();
2,098,700✔
1721

1722
    // There are no more intersections to process
1723
    // if we hit the edge of the model, so stop
1724
    // the particle in that case. Also, just exit
1725
    // if a negative distance was somehow computed.
1726
    if (boundary().distance() == INFTY || boundary().distance() == INFINITY ||
4,197,400!
1727
        boundary().distance() < 0) {
2,098,700!
1728
      return;
×
1729
    }
1730

1731
    // See below comment where call_on_intersection is checked in an
1732
    // if statement for an explanation of this.
1733
    bool call_on_intersection {true};
2,098,700✔
1734
    if (boundary().distance() < 10 * TINY_BIT) {
2,098,700✔
1735
      call_on_intersection = false;
539,350✔
1736
    }
1737

1738
    // DAGMC surfaces expect us to go a little bit further than the advance
1739
    // distance to properly check cell inclusion.
1740
    boundary().distance() += TINY_BIT;
2,098,700✔
1741

1742
    // Advance particle, prepare for next intersection
1743
    for (int lev = 0; lev < n_coord(); ++lev) {
4,197,400✔
1744
      coord(lev).r() += boundary().distance() * coord(lev).u();
2,098,700✔
1745
    }
1746
    surface() = boundary().surface();
2,098,700✔
1747
    n_coord_last() = n_coord();
2,098,700✔
1748
    n_coord() = boundary().coord_level();
2,098,700✔
1749
    if (boundary().lattice_translation()[0] != 0 ||
2,098,700✔
1750
        boundary().lattice_translation()[1] != 0 ||
4,197,400!
1751
        boundary().lattice_translation()[2] != 0) {
2,098,700!
1752
      cross_lattice(*this, boundary(), settings::verbosity >= 10);
×
1753
    }
1754

1755
    // Record how far the ray has traveled
1756
    traversal_distance_ += boundary().distance();
2,098,700✔
1757
    inside_cell = neighbor_list_find_cell(*this, settings::verbosity >= 10);
2,098,700✔
1758

1759
    // Call the specialized logic for this type of ray. Note that we do not
1760
    // call this if the advance distance is very small. Unfortunately, it seems
1761
    // darn near impossible to get the particle advanced to the model boundary
1762
    // and through it without sometimes accidentally calling on_intersection
1763
    // twice. This incorrectly shades the region as occluded when it might not
1764
    // actually be. By screening out intersection distances smaller than a
1765
    // threshold 10x larger than the scoot distance used to advance up to the
1766
    // model boundary, we can avoid that situation.
1767
    if (call_on_intersection) {
2,098,700✔
1768
      on_intersection();
1,559,350✔
1769
      if (stop_)
1,559,350✔
1770
        return;
32,330✔
1771
    }
1772

1773
    if (!inside_cell)
2,066,370✔
1774
      return;
1,376,610✔
1775

1776
    event_counter_++;
689,760✔
1777
    if (event_counter_ > MAX_INTERSECTIONS) {
689,760!
1778
      warning("Likely infinite loop in ray traced plot");
×
1779
      return;
×
1780
    }
1781
  }
689,760✔
1782
}
1783

1784
void ProjectionRay::on_intersection()
2,144,680✔
1785
{
1786
  // This records a tuple with the following info
1787
  //
1788
  // 1) ID (material or cell depending on color_by_)
1789
  // 2) Distance traveled by the ray through that ID
1790
  // 3) Index of the intersected surface (starting from 1)
1791

1792
  line_segments_.emplace_back(
2,144,680✔
1793
    plot_.color_by_ == PlottableInterface::PlotColorBy::mats
2,144,680✔
1794
      ? material()
496,290✔
1795
      : lowest_coord().cell(),
1,648,390✔
1796
    traversal_distance_, boundary().surface_index());
2,144,680✔
1797
}
2,144,680✔
1798

1799
void PhongRay::on_intersection()
823,610✔
1800
{
1801
  // Check if we hit an opaque material or cell
1802
  int hit_id = plot_.color_by_ == PlottableInterface::PlotColorBy::mats
823,610✔
1803
                 ? material()
823,610!
1804
                 : lowest_coord().cell();
×
1805

1806
  // If we are reflected and have advanced beyond the camera,
1807
  // the ray is done. This is checked here because we should
1808
  // kill the ray even if the material is not opaque.
1809
  if (reflected_ && (r() - plot_.camera_position()).dot(u()) >= 0.0) {
823,610!
1810
    stop();
×
1811
    return;
149,400✔
1812
  }
1813

1814
  // Anything that's not opaque has zero impact on the plot.
1815
  if (plot_.opaque_ids_.find(hit_id) == plot_.opaque_ids_.end())
823,610✔
1816
    return;
149,400✔
1817

1818
  if (!reflected_) {
674,210✔
1819
    // reflect the particle and set the color to be colored by
1820
    // the normal or the diffuse lighting contribution
1821
    reflected_ = true;
641,880✔
1822
    result_color_ = plot_.colors_[hit_id];
641,880✔
1823
    Direction to_light = plot_.light_location_ - r();
641,880✔
1824
    to_light /= to_light.norm();
641,880✔
1825

1826
    // TODO
1827
    // Not sure what can cause a surface token to be invalid here, although it
1828
    // sometimes happens for a few pixels. It's very very rare, so proceed by
1829
    // coloring the pixel with the overlap color. It seems to happen only for a
1830
    // few pixels on the outer boundary of a hex lattice.
1831
    //
1832
    // We cannot detect it in the outer loop, and it only matters here, so
1833
    // that's why the error handling is a little different than for a lost
1834
    // ray.
1835
    if (surface() == 0) {
641,880!
1836
      result_color_ = plot_.overlap_color_;
×
1837
      stop();
×
1838
      return;
×
1839
    }
1840

1841
    // Get surface pointer
1842
    const auto& surf = model::surfaces.at(surface_index());
641,880✔
1843

1844
    Direction normal = surf->normal(r_local());
641,880✔
1845
    normal /= normal.norm();
641,880✔
1846

1847
    // Need to apply translations to find the normal vector in
1848
    // the base level universe's coordinate system.
1849
    for (int lev = n_coord() - 2; lev >= 0; --lev) {
641,880!
1850
      if (coord(lev + 1).rotated()) {
×
1851
        const Cell& c {*model::cells[coord(lev).cell()]};
×
1852
        normal = normal.inverse_rotate(c.rotation_);
×
1853
      }
1854
    }
1855

1856
    // use the normal opposed to the ray direction
1857
    if (normal.dot(u()) > 0.0) {
641,880✔
1858
      normal *= -1.0;
57,990✔
1859
    }
1860

1861
    // Facing away from the light means no lighting
1862
    double dotprod = normal.dot(to_light);
641,880✔
1863
    dotprod = std::max(0.0, dotprod);
641,880✔
1864

1865
    double modulation =
641,880✔
1866
      plot_.diffuse_fraction_ + (1.0 - plot_.diffuse_fraction_) * dotprod;
641,880✔
1867
    result_color_ *= modulation;
641,880✔
1868

1869
    // Now point the particle to the camera. We now begin
1870
    // checking to see if it's occluded by another surface
1871
    u() = to_light;
641,880✔
1872

1873
    orig_hit_id_ = hit_id;
641,880✔
1874

1875
    // OpenMC native CSG and DAGMC surfaces have some slight differences
1876
    // in how they interpret particles that are sitting on a surface.
1877
    // I don't know exactly why, but this makes everything work beautifully.
1878
    if (surf->geom_type() == GeometryType::DAG) {
641,880!
1879
      surface() = 0;
×
1880
    } else {
1881
      surface() = -surface(); // go to other side
641,880✔
1882
    }
1883

1884
    // Must fully restart coordinate search. Why? Not sure.
1885
    clear();
641,880✔
1886

1887
    // Note this could likely be faster if we cached the previous
1888
    // cell we were in before the reflection. This is the easiest
1889
    // way to fully initialize all the sub-universe coordinates and
1890
    // directions though.
1891
    bool found = exhaustive_find_cell(*this);
641,880✔
1892
    if (!found) {
641,880!
1893
      fatal_error("Lost particle after reflection.");
×
1894
    }
1895

1896
    // Must recalculate distance to boundary due to the
1897
    // direction change
1898
    compute_distance();
641,880✔
1899

1900
  } else {
1901
    // If it's not facing the light, we color with the diffuse contribution, so
1902
    // next we check if we're going to occlude the last reflected surface. if
1903
    // so, color by the diffuse contribution instead
1904

1905
    if (orig_hit_id_ == -1)
32,330!
1906
      fatal_error("somehow a ray got reflected but not original ID set?");
×
1907

1908
    result_color_ = plot_.colors_[orig_hit_id_];
32,330✔
1909
    result_color_ *= plot_.diffuse_fraction_;
32,330✔
1910
    stop();
32,330✔
1911
  }
1912
}
1913

1914
extern "C" int openmc_id_map(const void* plot, int32_t* data_out)
243✔
1915
{
1916

1917
  auto plt = reinterpret_cast<const SlicePlotBase*>(plot);
243✔
1918
  if (!plt) {
243!
1919
    set_errmsg("Invalid slice pointer passed to openmc_id_map");
×
1920
    return OPENMC_E_INVALID_ARGUMENT;
×
1921
  }
1922

1923
  if (plt->slice_color_overlaps_ && model::overlap_check_count.size() == 0) {
243!
1924
    model::overlap_check_count.resize(model::cells.size());
20✔
1925
  }
1926

1927
  auto ids = plt->get_map<IdData>();
243✔
1928

1929
  // write id data to array
1930
  std::copy(ids.data_.begin(), ids.data_.end(), data_out);
243✔
1931

1932
  return 0;
243✔
1933
}
243✔
1934

1935
extern "C" int openmc_property_map(const void* plot, double* data_out)
10✔
1936
{
1937

1938
  auto plt = reinterpret_cast<const SlicePlotBase*>(plot);
10✔
1939
  if (!plt) {
10!
1940
    set_errmsg("Invalid slice pointer passed to openmc_id_map");
×
1941
    return OPENMC_E_INVALID_ARGUMENT;
×
1942
  }
1943

1944
  if (plt->slice_color_overlaps_ && model::overlap_check_count.size() == 0) {
10!
1945
    model::overlap_check_count.resize(model::cells.size());
×
1946
  }
1947

1948
  auto props = plt->get_map<PropertyData>();
10✔
1949

1950
  // write id data to array
1951
  std::copy(props.data_.begin(), props.data_.end(), data_out);
10✔
1952

1953
  return 0;
10✔
1954
}
10✔
1955

1956
extern "C" int openmc_get_plot_index(int32_t id, int32_t* index)
20✔
1957
{
1958
  auto it = model::plot_map.find(id);
20✔
1959
  if (it == model::plot_map.end()) {
20!
NEW
1960
    set_errmsg("No plot exists with ID=" + std::to_string(id) + ".");
×
NEW
1961
    return OPENMC_E_INVALID_ID;
×
1962
  }
1963

1964
  *index = it->second;
20✔
1965
  return 0;
20✔
1966
}
1967

1968
extern "C" int openmc_plot_get_id(int32_t index, int32_t* id)
50✔
1969
{
1970
  if (index < 0 || index >= model::plots.size()) {
50!
NEW
1971
    set_errmsg("Index in plots array is out of bounds.");
×
NEW
1972
    return OPENMC_E_OUT_OF_BOUNDS;
×
1973
  }
1974

1975
  *id = model::plots[index]->id();
50✔
1976
  return 0;
50✔
1977
}
1978

NEW
1979
extern "C" int openmc_plot_set_id(int32_t index, int32_t id)
×
1980
{
NEW
1981
  if (index < 0 || index >= model::plots.size()) {
×
NEW
1982
    set_errmsg("Index in plots array is out of bounds.");
×
NEW
1983
    return OPENMC_E_OUT_OF_BOUNDS;
×
1984
  }
1985

NEW
1986
  if (id < 0 && id != C_NONE) {
×
NEW
1987
    set_errmsg("Invalid plot ID.");
×
NEW
1988
    return OPENMC_E_INVALID_ARGUMENT;
×
1989
  }
1990

NEW
1991
  auto* plot = model::plots[index].get();
×
NEW
1992
  int32_t old_id = plot->id();
×
NEW
1993
  if (id == old_id)
×
NEW
1994
    return 0;
×
1995

NEW
1996
  model::plot_map.erase(old_id);
×
1997
  try {
NEW
1998
    plot->set_id(id);
×
NEW
1999
  } catch (const std::runtime_error& e) {
×
NEW
2000
    model::plot_map[old_id] = index;
×
NEW
2001
    set_errmsg(e.what());
×
NEW
2002
    return OPENMC_E_INVALID_ID;
×
NEW
2003
  }
×
NEW
2004
  model::plot_map[plot->id()] = index;
×
NEW
2005
  return 0;
×
2006
}
2007

2008
extern "C" size_t openmc_plots_size()
20✔
2009
{
2010
  return model::plots.size();
20✔
2011
}
2012

2013
int map_phong_domain_id(
50✔
2014
  const SolidRayTracePlot* plot, int32_t id, int32_t* index_out)
2015
{
2016
  if (!plot || !index_out) {
50!
NEW
2017
    set_errmsg("Invalid plot pointer passed to map_phong_domain_id");
×
NEW
2018
    return OPENMC_E_INVALID_ARGUMENT;
×
2019
  }
2020

2021
  if (plot->color_by_ == PlottableInterface::PlotColorBy::mats) {
50!
2022
    auto it = model::material_map.find(id);
50✔
2023
    if (it == model::material_map.end()) {
50!
NEW
2024
      set_errmsg("Invalid material ID for SolidRayTracePlot");
×
NEW
2025
      return OPENMC_E_INVALID_ID;
×
2026
    }
2027
    *index_out = it->second;
50✔
2028
    return 0;
50✔
2029
  }
2030

NEW
2031
  if (plot->color_by_ == PlottableInterface::PlotColorBy::cells) {
×
NEW
2032
    auto it = model::cell_map.find(id);
×
NEW
2033
    if (it == model::cell_map.end()) {
×
NEW
2034
      set_errmsg("Invalid cell ID for SolidRayTracePlot");
×
NEW
2035
      return OPENMC_E_INVALID_ID;
×
2036
    }
NEW
2037
    *index_out = it->second;
×
NEW
2038
    return 0;
×
2039
  }
2040

NEW
2041
  set_errmsg("Unsupported color_by for SolidRayTracePlot");
×
NEW
2042
  return OPENMC_E_INVALID_TYPE;
×
2043
}
2044

2045
int get_solidraytrace_plot_by_index(int32_t index, SolidRayTracePlot** plot)
280✔
2046
{
2047
  if (!plot) {
280!
NEW
2048
    set_errmsg("Null output pointer passed to get_solidraytrace_plot_by_index");
×
NEW
2049
    return OPENMC_E_INVALID_ARGUMENT;
×
2050
  }
2051

2052
  if (index < 0 || index >= model::plots.size()) {
280!
NEW
2053
    set_errmsg("Index in plots array is out of bounds.");
×
NEW
2054
    return OPENMC_E_OUT_OF_BOUNDS;
×
2055
  }
2056

2057
  auto* plottable = model::plots[index].get();
280✔
2058
  auto* solid_plot = dynamic_cast<SolidRayTracePlot*>(plottable);
280!
2059
  if (!solid_plot) {
280!
NEW
2060
    set_errmsg("Plot at index=" + std::to_string(index) +
×
2061
               " is not a solid raytrace plot.");
NEW
2062
    return OPENMC_E_INVALID_TYPE;
×
2063
  }
2064

2065
  *plot = solid_plot;
280✔
2066
  return 0;
280✔
2067
}
2068

2069
extern "C" int openmc_solidraytrace_plot_create(int32_t* index)
10✔
2070
{
2071
  if (!index) {
10!
NEW
2072
    set_errmsg(
×
2073
      "Null output pointer passed to openmc_solidraytrace_plot_create");
NEW
2074
    return OPENMC_E_INVALID_ARGUMENT;
×
2075
  }
2076

2077
  try {
2078
    auto new_plot = std::make_unique<SolidRayTracePlot>();
10✔
2079
    new_plot->set_id();
10✔
2080
    int32_t new_plot_id = new_plot->id();
10✔
2081
    new_plot->color_by_ = PlottableInterface::PlotColorBy::mats;
10✔
2082
    new_plot->pixels()[0] = 400;
10✔
2083
    new_plot->pixels()[1] = 400;
10✔
2084
#ifdef USE_LIBPNG
2085
    new_plot->path_plot() = fmt::format("plot_{}.png", new_plot_id);
10✔
2086
#else
2087
    new_plot->path_plot() = fmt::format("plot_{}.ppm", new_plot_id);
2088
#endif
2089
    int32_t new_plot_index = model::plots.size();
10✔
2090
    model::plots.emplace_back(std::move(new_plot));
10✔
2091
    model::plot_map[new_plot_id] = new_plot_index;
10✔
2092
    *index = new_plot_index;
10✔
2093
  } catch (const std::exception& e) {
10!
NEW
2094
    set_errmsg(e.what());
×
NEW
2095
    return OPENMC_E_ALLOCATE;
×
NEW
2096
  }
×
2097

2098
  return 0;
10✔
2099
}
2100

2101
extern "C" int openmc_solidraytrace_plot_get_pixels(
30✔
2102
  int32_t index, int32_t* width, int32_t* height)
2103
{
2104
  if (!width || !height) {
30!
NEW
2105
    set_errmsg(
×
2106
      "Invalid arguments passed to openmc_solidraytrace_plot_get_pixels");
NEW
2107
    return OPENMC_E_INVALID_ARGUMENT;
×
2108
  }
2109

2110
  SolidRayTracePlot* plt = nullptr;
30✔
2111
  int err = get_solidraytrace_plot_by_index(index, &plt);
30✔
2112
  if (err)
30!
NEW
2113
    return err;
×
2114

2115
  *width = plt->pixels()[0];
30✔
2116
  *height = plt->pixels()[1];
30✔
2117
  return 0;
30✔
2118
}
2119

2120
extern "C" int openmc_solidraytrace_plot_set_pixels(
10✔
2121
  int32_t index, int32_t width, int32_t height)
2122
{
2123
  if (width <= 0 || height <= 0) {
10!
NEW
2124
    set_errmsg(
×
2125
      "Invalid arguments passed to openmc_solidraytrace_plot_set_pixels");
NEW
2126
    return OPENMC_E_INVALID_ARGUMENT;
×
2127
  }
2128

2129
  SolidRayTracePlot* plt = nullptr;
10✔
2130
  int err = get_solidraytrace_plot_by_index(index, &plt);
10✔
2131
  if (err)
10!
NEW
2132
    return err;
×
2133

2134
  plt->pixels()[0] = width;
10✔
2135
  plt->pixels()[1] = height;
10✔
2136
  return 0;
10✔
2137
}
2138

2139
extern "C" int openmc_solidraytrace_plot_get_color_by(
10✔
2140
  int32_t index, int32_t* color_by)
2141
{
2142
  if (!color_by) {
10!
NEW
2143
    set_errmsg(
×
2144
      "Invalid arguments passed to openmc_solidraytrace_plot_get_color_by");
NEW
2145
    return OPENMC_E_INVALID_ARGUMENT;
×
2146
  }
2147

2148
  SolidRayTracePlot* plt = nullptr;
10✔
2149
  int err = get_solidraytrace_plot_by_index(index, &plt);
10✔
2150
  if (err)
10!
NEW
2151
    return err;
×
2152

2153
  if (plt->color_by_ == PlottableInterface::PlotColorBy::mats) {
10!
2154
    *color_by = 0;
10✔
NEW
2155
  } else if (plt->color_by_ == PlottableInterface::PlotColorBy::cells) {
×
NEW
2156
    *color_by = 1;
×
2157
  } else {
NEW
2158
    set_errmsg("Unsupported color_by for SolidRayTracePlot");
×
NEW
2159
    return OPENMC_E_INVALID_TYPE;
×
2160
  }
2161

2162
  return 0;
10✔
2163
}
2164

2165
extern "C" int openmc_solidraytrace_plot_set_color_by(
10✔
2166
  int32_t index, int32_t color_by)
2167
{
2168
  SolidRayTracePlot* plt = nullptr;
10✔
2169
  int err = get_solidraytrace_plot_by_index(index, &plt);
10✔
2170
  if (err)
10!
NEW
2171
    return err;
×
2172

2173
  if (color_by == 0) {
10!
2174
    plt->color_by_ = PlottableInterface::PlotColorBy::mats;
10✔
NEW
2175
  } else if (color_by == 1) {
×
NEW
2176
    plt->color_by_ = PlottableInterface::PlotColorBy::cells;
×
2177
  } else {
NEW
2178
    set_errmsg("Invalid color_by value for SolidRayTracePlot");
×
NEW
2179
    return OPENMC_E_INVALID_ARGUMENT;
×
2180
  }
2181

2182
  return 0;
10✔
2183
}
2184

2185
extern "C" int openmc_solidraytrace_plot_set_default_colors(int32_t index)
10✔
2186
{
2187
  SolidRayTracePlot* plt = nullptr;
10✔
2188
  int err = get_solidraytrace_plot_by_index(index, &plt);
10✔
2189
  if (err)
10!
NEW
2190
    return err;
×
2191

2192
  plt->set_default_colors();
10✔
2193
  return 0;
10✔
2194
}
2195

NEW
2196
extern "C" int openmc_solidraytrace_plot_set_all_opaque(int32_t index)
×
2197
{
NEW
2198
  SolidRayTracePlot* plt = nullptr;
×
NEW
2199
  int err = get_solidraytrace_plot_by_index(index, &plt);
×
NEW
2200
  if (err)
×
NEW
2201
    return err;
×
2202

NEW
2203
  plt->opaque_ids().clear();
×
NEW
2204
  if (plt->color_by_ == PlottableInterface::PlotColorBy::mats) {
×
NEW
2205
    for (int32_t i = 0; i < model::materials.size(); ++i) {
×
NEW
2206
      plt->opaque_ids().insert(i);
×
2207
    }
NEW
2208
    return 0;
×
2209
  }
2210

NEW
2211
  if (plt->color_by_ == PlottableInterface::PlotColorBy::cells) {
×
NEW
2212
    for (int32_t i = 0; i < model::cells.size(); ++i) {
×
NEW
2213
      plt->opaque_ids().insert(i);
×
2214
    }
NEW
2215
    return 0;
×
2216
  }
2217

NEW
2218
  set_errmsg("Unsupported color_by for SolidRayTracePlot");
×
NEW
2219
  return OPENMC_E_INVALID_TYPE;
×
2220
}
2221

2222
extern "C" int openmc_solidraytrace_plot_set_opaque(
20✔
2223
  int32_t index, int32_t id, bool visible)
2224
{
2225
  SolidRayTracePlot* plt = nullptr;
20✔
2226
  int err = get_solidraytrace_plot_by_index(index, &plt);
20✔
2227
  if (err)
20!
NEW
2228
    return err;
×
2229

2230
  int32_t domain_index = -1;
20✔
2231
  err = map_phong_domain_id(plt, id, &domain_index);
20✔
2232
  if (err)
20!
NEW
2233
    return err;
×
2234

2235
  if (visible) {
20✔
2236
    plt->opaque_ids().insert(domain_index);
10✔
2237
  } else {
2238
    plt->opaque_ids().erase(domain_index);
10✔
2239
  }
2240

2241
  return 0;
20✔
2242
}
2243

2244
extern "C" int openmc_solidraytrace_plot_set_color(
20✔
2245
  int32_t index, int32_t id, uint8_t r, uint8_t g, uint8_t b)
2246
{
2247
  SolidRayTracePlot* plt = nullptr;
20✔
2248
  int err = get_solidraytrace_plot_by_index(index, &plt);
20✔
2249
  if (err)
20!
NEW
2250
    return err;
×
2251

2252
  int32_t domain_index = -1;
20✔
2253
  err = map_phong_domain_id(plt, id, &domain_index);
20✔
2254
  if (err)
20!
NEW
2255
    return err;
×
2256

2257
  if (domain_index < 0 ||
40!
2258
      static_cast<size_t>(domain_index) >= plt->colors_.size()) {
20✔
NEW
2259
    set_errmsg("Color index out of range for SolidRayTracePlot");
×
NEW
2260
    return OPENMC_E_OUT_OF_BOUNDS;
×
2261
  }
2262

2263
  plt->colors_[domain_index] = RGBColor(r, g, b);
20✔
2264
  return 0;
20✔
2265
}
2266

2267
extern "C" int openmc_solidraytrace_plot_get_camera_position(
10✔
2268
  int32_t index, double* x, double* y, double* z)
2269
{
2270
  if (!x || !y || !z) {
10!
NEW
2271
    set_errmsg("Invalid arguments passed to "
×
2272
               "openmc_solidraytrace_plot_get_camera_position");
NEW
2273
    return OPENMC_E_INVALID_ARGUMENT;
×
2274
  }
2275

2276
  SolidRayTracePlot* plt = nullptr;
10✔
2277
  int err = get_solidraytrace_plot_by_index(index, &plt);
10✔
2278
  if (err)
10!
NEW
2279
    return err;
×
2280

2281
  const auto& camera_position = plt->camera_position();
10✔
2282
  *x = camera_position.x;
10✔
2283
  *y = camera_position.y;
10✔
2284
  *z = camera_position.z;
10✔
2285
  return 0;
10✔
2286
}
2287

2288
extern "C" int openmc_solidraytrace_plot_set_camera_position(
10✔
2289
  int32_t index, double x, double y, double z)
2290
{
2291
  SolidRayTracePlot* plt = nullptr;
10✔
2292
  int err = get_solidraytrace_plot_by_index(index, &plt);
10✔
2293
  if (err)
10!
NEW
2294
    return err;
×
2295

2296
  plt->camera_position() = {x, y, z};
10✔
2297
  return 0;
10✔
2298
}
2299

2300
extern "C" int openmc_solidraytrace_plot_get_look_at(
10✔
2301
  int32_t index, double* x, double* y, double* z)
2302
{
2303
  if (!x || !y || !z) {
10!
NEW
2304
    set_errmsg(
×
2305
      "Invalid arguments passed to openmc_solidraytrace_plot_get_look_at");
NEW
2306
    return OPENMC_E_INVALID_ARGUMENT;
×
2307
  }
2308

2309
  SolidRayTracePlot* plt = nullptr;
10✔
2310
  int err = get_solidraytrace_plot_by_index(index, &plt);
10✔
2311
  if (err)
10!
NEW
2312
    return err;
×
2313

2314
  const auto& look_at = plt->look_at();
10✔
2315
  *x = look_at.x;
10✔
2316
  *y = look_at.y;
10✔
2317
  *z = look_at.z;
10✔
2318
  return 0;
10✔
2319
}
2320

2321
extern "C" int openmc_solidraytrace_plot_set_look_at(
10✔
2322
  int32_t index, double x, double y, double z)
2323
{
2324
  SolidRayTracePlot* plt = nullptr;
10✔
2325
  int err = get_solidraytrace_plot_by_index(index, &plt);
10✔
2326
  if (err)
10!
NEW
2327
    return err;
×
2328

2329
  plt->look_at() = {x, y, z};
10✔
2330
  return 0;
10✔
2331
}
2332

2333
extern "C" int openmc_solidraytrace_plot_get_up(
10✔
2334
  int32_t index, double* x, double* y, double* z)
2335
{
2336
  if (!x || !y || !z) {
10!
NEW
2337
    set_errmsg("Invalid arguments passed to openmc_solidraytrace_plot_get_up");
×
NEW
2338
    return OPENMC_E_INVALID_ARGUMENT;
×
2339
  }
2340

2341
  SolidRayTracePlot* plt = nullptr;
10✔
2342
  int err = get_solidraytrace_plot_by_index(index, &plt);
10✔
2343
  if (err)
10!
NEW
2344
    return err;
×
2345

2346
  const auto& up = plt->up();
10✔
2347
  *x = up.x;
10✔
2348
  *y = up.y;
10✔
2349
  *z = up.z;
10✔
2350
  return 0;
10✔
2351
}
2352

2353
extern "C" int openmc_solidraytrace_plot_set_up(
10✔
2354
  int32_t index, double x, double y, double z)
2355
{
2356
  SolidRayTracePlot* plt = nullptr;
10✔
2357
  int err = get_solidraytrace_plot_by_index(index, &plt);
10✔
2358
  if (err)
10!
NEW
2359
    return err;
×
2360

2361
  plt->up() = {x, y, z};
10✔
2362
  return 0;
10✔
2363
}
2364

2365
extern "C" int openmc_solidraytrace_plot_get_light_position(
10✔
2366
  int32_t index, double* x, double* y, double* z)
2367
{
2368
  if (!x || !y || !z) {
10!
NEW
2369
    set_errmsg("Invalid arguments passed to "
×
2370
               "openmc_solidraytrace_plot_get_light_position");
NEW
2371
    return OPENMC_E_INVALID_ARGUMENT;
×
2372
  }
2373

2374
  SolidRayTracePlot* plt = nullptr;
10✔
2375
  int err = get_solidraytrace_plot_by_index(index, &plt);
10✔
2376
  if (err)
10!
NEW
2377
    return err;
×
2378

2379
  const auto& light_position = plt->light_location();
10✔
2380
  *x = light_position.x;
10✔
2381
  *y = light_position.y;
10✔
2382
  *z = light_position.z;
10✔
2383
  return 0;
10✔
2384
}
2385

2386
extern "C" int openmc_solidraytrace_plot_set_light_position(
10✔
2387
  int32_t index, double x, double y, double z)
2388
{
2389
  SolidRayTracePlot* plt = nullptr;
10✔
2390
  int err = get_solidraytrace_plot_by_index(index, &plt);
10✔
2391
  if (err)
10!
NEW
2392
    return err;
×
2393

2394
  plt->light_location() = {x, y, z};
10✔
2395
  return 0;
10✔
2396
}
2397

2398
extern "C" int openmc_solidraytrace_plot_get_fov(int32_t index, double* fov)
10✔
2399
{
2400
  if (!fov) {
10!
NEW
2401
    set_errmsg("Invalid arguments passed to openmc_solidraytrace_plot_get_fov");
×
NEW
2402
    return OPENMC_E_INVALID_ARGUMENT;
×
2403
  }
2404

2405
  SolidRayTracePlot* plt = nullptr;
10✔
2406
  int err = get_solidraytrace_plot_by_index(index, &plt);
10✔
2407
  if (err)
10!
NEW
2408
    return err;
×
2409

2410
  *fov = plt->horizontal_field_of_view();
10✔
2411
  return 0;
10✔
2412
}
2413

2414
extern "C" int openmc_solidraytrace_plot_set_fov(int32_t index, double fov)
10✔
2415
{
2416
  SolidRayTracePlot* plt = nullptr;
10✔
2417
  int err = get_solidraytrace_plot_by_index(index, &plt);
10✔
2418
  if (err)
10!
NEW
2419
    return err;
×
2420

2421
  plt->horizontal_field_of_view() = fov;
10✔
2422
  return 0;
10✔
2423
}
2424

2425
extern "C" int openmc_solidraytrace_plot_update_view(int32_t index)
20✔
2426
{
2427
  SolidRayTracePlot* plt = nullptr;
20✔
2428
  int err = get_solidraytrace_plot_by_index(index, &plt);
20✔
2429
  if (err)
20!
NEW
2430
    return err;
×
2431

2432
  plt->update_view();
20✔
2433
  return 0;
20✔
2434
}
2435

2436
extern "C" int openmc_solidraytrace_plot_create_image(
20✔
2437
  int32_t index, uint8_t* data_out, int32_t width, int32_t height)
2438
{
2439
  if (!data_out || width <= 0 || height <= 0) {
20!
NEW
2440
    set_errmsg(
×
2441
      "Invalid arguments passed to openmc_solidraytrace_plot_create_image");
NEW
2442
    return OPENMC_E_INVALID_ARGUMENT;
×
2443
  }
2444

2445
  SolidRayTracePlot* plt = nullptr;
20✔
2446
  int err = get_solidraytrace_plot_by_index(index, &plt);
20✔
2447
  if (err)
20!
NEW
2448
    return err;
×
2449

2450
  if (plt->pixels()[0] != width || plt->pixels()[1] != height) {
20!
NEW
2451
    set_errmsg(
×
2452
      "Requested image size does not match SolidRayTracePlot pixel settings");
NEW
2453
    return OPENMC_E_INVALID_SIZE;
×
2454
  }
2455

2456
  ImageData data = plt->create_image();
20✔
2457
  if (static_cast<int32_t>(data.shape()[0]) != width ||
40!
2458
      static_cast<int32_t>(data.shape()[1]) != height) {
20!
NEW
2459
    set_errmsg("Unexpected image size from SolidRayTracePlot create_image");
×
NEW
2460
    return OPENMC_E_INVALID_SIZE;
×
2461
  }
2462

2463
  for (int32_t y = 0; y < height; ++y) {
140✔
2464
    for (int32_t x = 0; x < width; ++x) {
1,080✔
2465
      const auto& color = data(x, y);
960✔
2466
      size_t idx = (static_cast<size_t>(y) * width + x) * 3;
960✔
2467
      data_out[idx + 0] = color.red;
960✔
2468
      data_out[idx + 1] = color.green;
960✔
2469
      data_out[idx + 2] = color.blue;
960✔
2470
    }
2471
  }
2472

2473
  return 0;
20✔
2474
}
20✔
2475

2476
extern "C" int openmc_solidraytrace_plot_get_color(
10✔
2477
  int32_t index, int32_t id, uint8_t* r, uint8_t* g, uint8_t* b)
2478
{
2479
  if (!r || !g || !b) {
10!
NEW
2480
    set_errmsg(
×
2481
      "Invalid arguments passed to openmc_solidraytrace_plot_get_color");
NEW
2482
    return OPENMC_E_INVALID_ARGUMENT;
×
2483
  }
2484

2485
  SolidRayTracePlot* plt = nullptr;
10✔
2486
  int err = get_solidraytrace_plot_by_index(index, &plt);
10✔
2487
  if (err)
10!
NEW
2488
    return err;
×
2489

2490
  int32_t domain_index = -1;
10✔
2491
  err = map_phong_domain_id(plt, id, &domain_index);
10✔
2492
  if (err)
10!
NEW
2493
    return err;
×
2494

2495
  if (domain_index < 0 ||
20!
2496
      static_cast<size_t>(domain_index) >= plt->colors_.size()) {
10✔
NEW
2497
    set_errmsg("Color index out of range for SolidRayTracePlot");
×
NEW
2498
    return OPENMC_E_OUT_OF_BOUNDS;
×
2499
  }
2500

2501
  const auto& color = plt->colors_[domain_index];
10✔
2502
  *r = color.red;
10✔
2503
  *g = color.green;
10✔
2504
  *b = color.blue;
10✔
2505
  return 0;
10✔
2506
}
2507

2508
extern "C" int openmc_solidraytrace_plot_get_diffuse_fraction(
10✔
2509
  int32_t index, double* diffuse_fraction)
2510
{
2511
  if (!diffuse_fraction) {
10!
NEW
2512
    set_errmsg("Invalid arguments passed to "
×
2513
               "openmc_solidraytrace_plot_get_diffuse_fraction");
NEW
2514
    return OPENMC_E_INVALID_ARGUMENT;
×
2515
  }
2516

2517
  SolidRayTracePlot* plt = nullptr;
10✔
2518
  int err = get_solidraytrace_plot_by_index(index, &plt);
10✔
2519
  if (err)
10!
NEW
2520
    return err;
×
2521

2522
  *diffuse_fraction = plt->diffuse_fraction();
10✔
2523
  return 0;
10✔
2524
}
2525

2526
extern "C" int openmc_solidraytrace_plot_set_diffuse_fraction(
10✔
2527
  int32_t index, double diffuse_fraction)
2528
{
2529
  SolidRayTracePlot* plt = nullptr;
10✔
2530
  int err = get_solidraytrace_plot_by_index(index, &plt);
10✔
2531
  if (err)
10!
NEW
2532
    return err;
×
2533

2534
  if (diffuse_fraction < 0.0 || diffuse_fraction > 1.0) {
10!
NEW
2535
    set_errmsg("Diffuse fraction must be between 0 and 1");
×
NEW
2536
    return OPENMC_E_INVALID_ARGUMENT;
×
2537
  }
2538

2539
  plt->diffuse_fraction() = diffuse_fraction;
10✔
2540
  return 0;
10✔
2541
}
2542

2543
} // 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