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

openmc-dev / openmc / 21728712162

05 Feb 2026 09:13PM UTC coverage: 81.763% (-0.003%) from 81.766%
21728712162

Pull #3776

github

web-flow
Merge 06cb586bc into 1039b5d9f
Pull Request #3776: Modifications to C++ plots for interactive raytrace plots

17310 of 24268 branches covered (71.33%)

Branch coverage included in aggregate %.

90 of 94 new or added lines in 2 files covered. (95.74%)

309 existing lines in 26 files now uncovered.

55957 of 65341 relevant lines covered (85.64%)

50685327.01 hits per line

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

75.36
/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)
5,140✔
49
{}
5,140✔
50

51
void IdData::set_value(size_t y, size_t x, const GeometryState& p, int level)
38,716,247✔
52
{
53
  // set cell data
54
  if (p.n_coord() <= level) {
38,716,247!
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_;
38,716,247✔
59
    data_(y, x, 1) = level == p.n_coord() - 1
77,432,494✔
60
                       ? p.cell_instance()
38,716,247!
61
                       : cell_instance_at_level(p, level);
×
62
  }
63

64
  // set material data
65
  Cell* c = model::cells.at(p.lowest_coord().cell()).get();
38,716,247✔
66
  if (p.material() == MATERIAL_VOID) {
38,716,247✔
67
    data_(y, x, 2) = MATERIAL_VOID;
29,804,276✔
68
    return;
29,804,276✔
69
  } else if (c->type_ == Fill::MATERIAL) {
8,911,971!
70
    Material* m = model::materials.at(p.material()).get();
8,911,971✔
71
    data_(y, x, 2) = m->id_;
8,911,971✔
72
  }
73
}
74

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

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

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

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

124
  return 0;
121✔
125
}
126

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

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

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

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

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

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

172
  if (PlotType::slice == type_) {
154✔
173
    switch (basis_) {
121!
174
    case PlotBasis::xy:
77✔
175
      fmt::print("Basis: XY\n");
63✔
176
      break;
77✔
177
    case PlotBasis::xz:
22✔
178
      fmt::print("Basis: XZ\n");
18✔
179
      break;
22✔
180
    case PlotBasis::yz:
22✔
181
      fmt::print("Basis: YZ\n");
18✔
182
      break;
22✔
183
    }
184
    fmt::print("Pixels: {} {}\n", pixels()[0], pixels()[1]);
242✔
185
  } else if (PlotType::voxel == type_) {
33!
186
    fmt::print("Voxels: {} {} {}\n", pixels()[0], pixels()[1], pixels()[2]);
66✔
187
  }
188
}
154✔
189

190
void read_plots_xml()
1,371✔
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,371✔
196
  if (!file_exists(filename) && settings::run_mode == RunMode::PLOTTING) {
1,371!
197
    fatal_error(fmt::format("Plots XML file '{}' does not exist!", filename));
×
198
  }
199

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

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

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

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

211
void read_plots_xml(pugi::xml_node root)
1,693✔
212
{
213
  for (auto node : root.children("plot")) {
2,504✔
214
    std::string id_string = get_node_value(node, "id", true);
820✔
215
    int id = std::stoi(id_string);
820✔
216
    if (check_for_node(node, "type")) {
820!
217
      std::string type_str = get_node_value(node, "type", true);
820✔
218
      if (type_str == "slice") {
820✔
219
        model::plots.emplace_back(
668✔
220
          std::make_unique<Plot>(node, Plot::PlotType::slice));
1,345✔
221
      } else if (type_str == "voxel") {
143✔
222
        model::plots.emplace_back(
55✔
223
          std::make_unique<Plot>(node, Plot::PlotType::voxel));
110✔
224
      } else if (type_str == "wireframe_raytrace") {
88✔
225
        model::plots.emplace_back(
55✔
226
          std::make_unique<WireframeRayTracePlot>(node));
110✔
227
      } else if (type_str == "solid_raytrace") {
33!
228
        model::plots.emplace_back(std::make_unique<SolidRayTracePlot>(node));
33✔
229
      } else {
230
        fatal_error(
×
231
          fmt::format("Unsupported plot type '{}' in plot {}", type_str, id));
×
232
      }
233
      model::plot_map[model::plots.back()->id()] = model::plots.size() - 1;
811✔
234
    } else {
811✔
235
      fatal_error(fmt::format("Must specify plot type in plot {}", id));
×
236
    }
237
  }
811✔
238
}
1,684✔
239

240
void free_memory_plot()
8,186✔
241
{
242
  model::plots.clear();
8,186✔
243
  model::plot_map.clear();
8,186✔
244
}
8,186✔
245

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

253
  ImageData data({width, height}, not_found_);
143✔
254

255
  // generate ids for the plot
256
  auto ids = get_map<IdData>();
143✔
257

258
  // assign colors
259
  for (size_t y = 0; y < height; y++) {
30,063✔
260
    for (size_t x = 0; x < width; x++) {
7,622,120✔
261
      int idx = color_by_ == PlotColorBy::cells ? 0 : 2;
7,592,200✔
262
      auto id = ids.data_(y, x, idx);
7,592,200✔
263
      // no setting needed if not found
264
      if (id == NOT_FOUND) {
7,592,200✔
265
        continue;
1,082,532✔
266
      }
267
      if (id == OVERLAP) {
6,537,916✔
268
        data(x, y) = overlap_color_;
28,248✔
269
        continue;
28,248✔
270
      }
271
      if (PlotColorBy::cells == color_by_) {
6,509,668✔
272
        data(x, y) = colors_[model::cell_map[id]];
3,011,668✔
273
      } else if (PlotColorBy::mats == color_by_) {
3,498,000!
274
        if (id == MATERIAL_VOID) {
3,498,000!
275
          data(x, y) = WHITE;
×
276
          continue;
×
277
        }
278
        data(x, y) = colors_[model::material_map[id]];
3,498,000✔
279
      } // color_by if-else
280
    }
281
  }
282

283
  // draw mesh lines if present
284
  if (index_meshlines_mesh_ >= 0) {
143✔
285
    draw_mesh_lines(data);
33✔
286
  }
287

288
  return data;
286✔
289
}
143✔
290

291
void PlottableInterface::set_id(pugi::xml_node plot_node)
820✔
292
{
293
  // Copy data into plots
294
  if (check_for_node(plot_node, "id")) {
820!
295
    id_ = std::stoi(get_node_value(plot_node, "id"));
820✔
296
  } else {
297
    fatal_error("Must specify plot id in plots XML file.");
×
298
  }
299

300
  // Check to make sure 'id' hasn't been used
301
  if (model::plot_map.find(id_) != model::plot_map.end()) {
820!
302
    fatal_error(
×
303
      fmt::format("Two or more plots use the same unique ID: {}", id_));
×
304
  }
305
}
820✔
306

307
// Checks if png or ppm is already present
308
bool file_extension_present(
811✔
309
  const std::string& filename, const std::string& extension)
310
{
311
  std::string file_extension_if_present =
312
    filename.substr(filename.find_last_of(".") + 1);
811✔
313
  if (file_extension_if_present == extension)
811✔
314
    return true;
55✔
315
  return false;
756✔
316
}
811✔
317

318
void Plot::set_output_path(pugi::xml_node plot_node)
732✔
319
{
320
  // Set output file path
321
  std::string filename;
732✔
322

323
  if (check_for_node(plot_node, "filename")) {
732✔
324
    filename = get_node_value(plot_node, "filename");
248✔
325
  } else {
326
    filename = fmt::format("plot_{}", id());
968✔
327
  }
328
  const std::string dir_if_present =
329
    filename.substr(0, filename.find_last_of("/") + 1);
732✔
330
  if (dir_if_present.size() > 0 && !dir_exists(dir_if_present)) {
732✔
331
    fatal_error(fmt::format("Directory '{}' does not exist!", dir_if_present));
9✔
332
  }
333
  // add appropriate file extension to name
334
  switch (type_) {
723!
335
  case PlotType::slice:
668✔
336
#ifdef USE_LIBPNG
337
    if (!file_extension_present(filename, "png"))
668!
338
      filename.append(".png");
668✔
339
#else
340
    if (!file_extension_present(filename, "ppm"))
341
      filename.append(".ppm");
342
#endif
343
    break;
668✔
344
  case PlotType::voxel:
55✔
345
    if (!file_extension_present(filename, "h5"))
55!
346
      filename.append(".h5");
55✔
347
    break;
55✔
348
  }
349

350
  path_plot_ = filename;
723✔
351

352
  // Copy plot pixel size
353
  vector<int> pxls = get_node_array<int>(plot_node, "pixels");
1,446✔
354
  if (PlotType::slice == type_) {
723✔
355
    if (pxls.size() == 2) {
668!
356
      pixels()[0] = pxls[0];
668✔
357
      pixels()[1] = pxls[1];
668✔
358
    } else {
359
      fatal_error(
×
360
        fmt::format("<pixels> must be length 2 in slice plot {}", id()));
×
361
    }
362
  } else if (PlotType::voxel == type_) {
55!
363
    if (pxls.size() == 3) {
55!
364
      pixels()[0] = pxls[0];
55✔
365
      pixels()[1] = pxls[1];
55✔
366
      pixels()[2] = pxls[2];
55✔
367
    } else {
368
      fatal_error(
×
369
        fmt::format("<pixels> must be length 3 in voxel plot {}", id()));
×
370
    }
371
  }
372
}
723✔
373

374
void PlottableInterface::set_bg_color(pugi::xml_node plot_node)
820✔
375
{
376
  // Copy plot background color
377
  if (check_for_node(plot_node, "background")) {
820✔
378
    vector<int> bg_rgb = get_node_array<int>(plot_node, "background");
44✔
379
    if (bg_rgb.size() == 3) {
44!
380
      not_found_ = bg_rgb;
44✔
381
    } else {
382
      fatal_error(fmt::format("Bad background RGB in plot {}", id()));
×
383
    }
384
  }
44✔
385
}
820✔
386

387
void Plot::set_basis(pugi::xml_node plot_node)
723✔
388
{
389
  // Copy plot basis
390
  if (PlotType::slice == type_) {
723✔
391
    std::string pl_basis = "xy";
668✔
392
    if (check_for_node(plot_node, "basis")) {
668!
393
      pl_basis = get_node_value(plot_node, "basis", true);
668✔
394
    }
395
    if ("xy" == pl_basis) {
668✔
396
      basis_ = PlotBasis::xy;
592✔
397
    } else if ("xz" == pl_basis) {
76✔
398
      basis_ = PlotBasis::xz;
22✔
399
    } else if ("yz" == pl_basis) {
54!
400
      basis_ = PlotBasis::yz;
54✔
401
    } else {
402
      fatal_error(
×
403
        fmt::format("Unsupported plot basis '{}' in plot {}", pl_basis, id()));
×
404
    }
405
  }
668✔
406
}
723✔
407

408
void Plot::set_origin(pugi::xml_node plot_node)
723✔
409
{
410
  // Copy plotting origin
411
  auto pl_origin = get_node_array<double>(plot_node, "origin");
723✔
412
  if (pl_origin.size() == 3) {
723!
413
    origin_ = pl_origin;
723✔
414
  } else {
415
    fatal_error(fmt::format("Origin must be length 3 in plot {}", id()));
×
416
  }
417
}
723✔
418

419
void Plot::set_width(pugi::xml_node plot_node)
723✔
420
{
421
  // Copy plotting width
422
  vector<double> pl_width = get_node_array<double>(plot_node, "width");
723✔
423
  if (PlotType::slice == type_) {
723✔
424
    if (pl_width.size() == 2) {
668!
425
      width_.x = pl_width[0];
668✔
426
      width_.y = pl_width[1];
668✔
427
    } else {
428
      fatal_error(
×
429
        fmt::format("<width> must be length 2 in slice plot {}", id()));
×
430
    }
431
  } else if (PlotType::voxel == type_) {
55!
432
    if (pl_width.size() == 3) {
55!
433
      pl_width = get_node_array<double>(plot_node, "width");
55✔
434
      width_ = pl_width;
55✔
435
    } else {
436
      fatal_error(
×
437
        fmt::format("<width> must be length 3 in voxel plot {}", id()));
×
438
    }
439
  }
440
}
723✔
441

442
void PlottableInterface::set_universe(pugi::xml_node plot_node)
820✔
443
{
444
  // Copy plot universe level
445
  if (check_for_node(plot_node, "level")) {
820!
446
    level_ = std::stoi(get_node_value(plot_node, "level"));
×
447
    if (level_ < 0) {
×
448
      fatal_error(fmt::format("Bad universe level in plot {}", id()));
×
449
    }
450
  } else {
451
    level_ = PLOT_LEVEL_LOWEST;
820✔
452
  }
453
}
820✔
454

455
void PlottableInterface::set_color_by(pugi::xml_node plot_node)
820✔
456
{
457
  // Copy plot color type
458
  std::string pl_color_by = "cell";
820✔
459
  if (check_for_node(plot_node, "color_by")) {
820✔
460
    pl_color_by = get_node_value(plot_node, "color_by", true);
787✔
461
  }
462
  if ("cell" == pl_color_by) {
820✔
463
    color_by_ = PlotColorBy::cells;
290✔
464
  } else if ("material" == pl_color_by) {
530!
465
    color_by_ = PlotColorBy::mats;
530✔
466
  } else {
UNCOV
467
    fatal_error(fmt::format(
×
468
      "Unsupported plot color type '{}' in plot {}", pl_color_by, id()));
×
469
  }
470
}
820✔
471

472
void PlottableInterface::set_default_colors()
820✔
473
{
474
  // Copy plot color type and initialize all colors randomly
475
  if (PlotColorBy::cells == color_by_) {
820✔
476
    colors_.resize(model::cells.size());
290✔
477
  } else if (PlotColorBy::mats == color_by_) {
530!
478
    colors_.resize(model::materials.size());
530✔
479
  }
480

481
  for (auto& c : colors_) {
3,778✔
482
    c = random_color();
2,958✔
483
    // make sure we don't interfere with some default colors
484
    while (c == RED || c == WHITE) {
2,958!
485
      c = random_color();
×
486
    }
487
  }
488
}
820✔
489

490
void PlottableInterface::set_user_colors(pugi::xml_node plot_node)
820✔
491
{
492
  for (auto cn : plot_node.children("color")) {
1,007✔
493
    // Make sure 3 values are specified for RGB
494
    vector<int> user_rgb = get_node_array<int>(cn, "rgb");
187✔
495
    if (user_rgb.size() != 3) {
187!
496
      fatal_error(fmt::format("Bad RGB in plot {}", id()));
×
497
    }
498
    // Ensure that there is an id for this color specification
499
    int col_id;
500
    if (check_for_node(cn, "id")) {
187!
501
      col_id = std::stoi(get_node_value(cn, "id"));
187✔
502
    } else {
503
      fatal_error(fmt::format(
×
504
        "Must specify id for color specification in plot {}", id()));
×
505
    }
506
    // Add RGB
507
    if (PlotColorBy::cells == color_by_) {
187✔
508
      if (model::cell_map.find(col_id) != model::cell_map.end()) {
88!
509
        col_id = model::cell_map[col_id];
88✔
510
        colors_[col_id] = user_rgb;
88✔
511
      } else {
512
        warning(fmt::format(
×
513
          "Could not find cell {} specified in plot {}", col_id, id()));
×
514
      }
515
    } else if (PlotColorBy::mats == color_by_) {
99!
516
      if (model::material_map.find(col_id) != model::material_map.end()) {
99!
517
        col_id = model::material_map[col_id];
99✔
518
        colors_[col_id] = user_rgb;
99✔
519
      } else {
520
        warning(fmt::format(
×
521
          "Could not find material {} specified in plot {}", col_id, id()));
×
522
      }
523
    }
524
  } // color node loop
187✔
525
}
820✔
526

527
void Plot::set_meshlines(pugi::xml_node plot_node)
723✔
528
{
529
  // Deal with meshlines
530
  pugi::xpath_node_set mesh_line_nodes = plot_node.select_nodes("meshlines");
723✔
531

532
  if (!mesh_line_nodes.empty()) {
723✔
533
    if (PlotType::voxel == type_) {
33!
534
      warning(fmt::format("Meshlines ignored in voxel plot {}", id()));
×
535
    }
536

537
    if (mesh_line_nodes.size() == 1) {
33!
538
      // Get first meshline node
539
      pugi::xml_node meshlines_node = mesh_line_nodes[0].node();
33✔
540

541
      // Check mesh type
542
      std::string meshtype;
33✔
543
      if (check_for_node(meshlines_node, "meshtype")) {
33!
544
        meshtype = get_node_value(meshlines_node, "meshtype");
33✔
545
      } else {
546
        fatal_error(fmt::format(
×
547
          "Must specify a meshtype for meshlines specification in plot {}",
548
          id()));
×
549
      }
550

551
      // Ensure that there is a linewidth for this meshlines specification
552
      std::string meshline_width;
33✔
553
      if (check_for_node(meshlines_node, "linewidth")) {
33!
554
        meshline_width = get_node_value(meshlines_node, "linewidth");
33✔
555
        meshlines_width_ = std::stoi(meshline_width);
33✔
556
      } else {
557
        fatal_error(fmt::format(
×
558
          "Must specify a linewidth for meshlines specification in plot {}",
559
          id()));
×
560
      }
561

562
      // Check for color
563
      if (check_for_node(meshlines_node, "color")) {
33!
564
        // Check and make sure 3 values are specified for RGB
565
        vector<int> ml_rgb = get_node_array<int>(meshlines_node, "color");
×
566
        if (ml_rgb.size() != 3) {
×
567
          fatal_error(
×
568
            fmt::format("Bad RGB for meshlines color in plot {}", id()));
×
569
        }
570
        meshlines_color_ = ml_rgb;
×
571
      }
×
572

573
      // Set mesh based on type
574
      if ("ufs" == meshtype) {
33!
575
        if (!simulation::ufs_mesh) {
×
576
          fatal_error(
×
577
            fmt::format("No UFS mesh for meshlines on plot {}", id()));
×
578
        } else {
579
          for (int i = 0; i < model::meshes.size(); ++i) {
×
580
            if (const auto* m =
×
581
                  dynamic_cast<const RegularMesh*>(model::meshes[i].get())) {
×
582
              if (m == simulation::ufs_mesh) {
×
583
                index_meshlines_mesh_ = i;
×
584
              }
585
            }
586
          }
587
          if (index_meshlines_mesh_ == -1)
×
588
            fatal_error("Could not find the UFS mesh for meshlines plot");
×
589
        }
590
      } else if ("entropy" == meshtype) {
33✔
591
        if (!simulation::entropy_mesh) {
22!
592
          fatal_error(
×
593
            fmt::format("No entropy mesh for meshlines on plot {}", id()));
×
594
        } else {
595
          for (int i = 0; i < model::meshes.size(); ++i) {
55✔
596
            if (const auto* m =
33✔
597
                  dynamic_cast<const RegularMesh*>(model::meshes[i].get())) {
33!
598
              if (m == simulation::entropy_mesh) {
22!
599
                index_meshlines_mesh_ = i;
22✔
600
              }
601
            }
602
          }
603
          if (index_meshlines_mesh_ == -1)
22!
604
            fatal_error("Could not find the entropy mesh for meshlines plot");
×
605
        }
606
      } else if ("tally" == meshtype) {
11!
607
        // Ensure that there is a mesh id if the type is tally
608
        int tally_mesh_id;
609
        if (check_for_node(meshlines_node, "id")) {
11!
610
          tally_mesh_id = std::stoi(get_node_value(meshlines_node, "id"));
11✔
611
        } else {
612
          std::stringstream err_msg;
×
613
          fatal_error(fmt::format("Must specify a mesh id for meshlines tally "
×
614
                                  "mesh specification in plot {}",
615
            id()));
×
616
        }
×
617
        // find the tally index
618
        int idx;
619
        int err = openmc_get_mesh_index(tally_mesh_id, &idx);
11✔
620
        if (err != 0) {
11!
621
          fatal_error(fmt::format("Could not find mesh {} specified in "
×
622
                                  "meshlines for plot {}",
623
            tally_mesh_id, id()));
×
624
        }
625
        index_meshlines_mesh_ = idx;
11✔
626
      } else {
627
        fatal_error(fmt::format("Invalid type for meshlines on plot {}", id()));
×
628
      }
629
    } else {
33✔
630
      fatal_error(fmt::format("Mutliple meshlines specified in plot {}", id()));
×
631
    }
632
  }
633
}
723✔
634

635
void PlottableInterface::set_mask(pugi::xml_node plot_node)
820✔
636
{
637
  // Deal with masks
638
  pugi::xpath_node_set mask_nodes = plot_node.select_nodes("mask");
820✔
639

640
  if (!mask_nodes.empty()) {
820✔
641
    if (mask_nodes.size() == 1) {
33!
642
      // Get pointer to mask
643
      pugi::xml_node mask_node = mask_nodes[0].node();
33✔
644

645
      // Determine how many components there are and allocate
646
      vector<int> iarray = get_node_array<int>(mask_node, "components");
33✔
647
      if (iarray.size() == 0) {
33!
648
        fatal_error(
×
649
          fmt::format("Missing <components> in mask of plot {}", id()));
×
650
      }
651

652
      // First we need to change the user-specified identifiers to indices
653
      // in the cell and material arrays
654
      for (auto& col_id : iarray) {
99✔
655
        if (PlotColorBy::cells == color_by_) {
66!
656
          if (model::cell_map.find(col_id) != model::cell_map.end()) {
66!
657
            col_id = model::cell_map[col_id];
66✔
658
          } else {
659
            fatal_error(fmt::format("Could not find cell {} specified in the "
×
660
                                    "mask in plot {}",
661
              col_id, id()));
×
662
          }
663
        } else if (PlotColorBy::mats == color_by_) {
×
664
          if (model::material_map.find(col_id) != model::material_map.end()) {
×
665
            col_id = model::material_map[col_id];
×
666
          } else {
667
            fatal_error(fmt::format("Could not find material {} specified in "
×
668
                                    "the mask in plot {}",
669
              col_id, id()));
×
670
          }
671
        }
672
      }
673

674
      // Alter colors based on mask information
675
      for (int j = 0; j < colors_.size(); j++) {
132✔
676
        if (contains(iarray, j)) {
99✔
677
          if (check_for_node(mask_node, "background")) {
66!
678
            vector<int> bg_rgb = get_node_array<int>(mask_node, "background");
66✔
679
            colors_[j] = bg_rgb;
66✔
680
          } else {
66✔
681
            colors_[j] = WHITE;
×
682
          }
683
        }
684
      }
685

686
    } else {
33✔
687
      fatal_error(fmt::format("Mutliple masks specified in plot {}", id()));
×
688
    }
689
  }
690
}
820✔
691

692
void PlottableInterface::set_overlap_color(pugi::xml_node plot_node)
820✔
693
{
694
  color_overlaps_ = false;
820✔
695
  if (check_for_node(plot_node, "show_overlaps")) {
820✔
696
    color_overlaps_ = get_node_value_bool(plot_node, "show_overlaps");
22✔
697
    // check for custom overlap color
698
    if (check_for_node(plot_node, "overlap_color")) {
22✔
699
      if (!color_overlaps_) {
11!
700
        warning(fmt::format(
×
701
          "Overlap color specified in plot {} but overlaps won't be shown.",
702
          id()));
×
703
      }
704
      vector<int> olap_clr = get_node_array<int>(plot_node, "overlap_color");
11✔
705
      if (olap_clr.size() == 3) {
11!
706
        overlap_color_ = olap_clr;
11✔
707
      } else {
708
        fatal_error(fmt::format("Bad overlap RGB in plot {}", id()));
×
709
      }
710
    }
11✔
711
  }
712

713
  // make sure we allocate the vector for counting overlap checks if
714
  // they're going to be plotted
715
  if (color_overlaps_ && settings::run_mode == RunMode::PLOTTING) {
820!
716
    settings::check_overlaps = true;
22✔
717
    model::overlap_check_count.resize(model::cells.size(), 0);
22✔
718
  }
719
}
820✔
720

721
PlottableInterface::PlottableInterface(pugi::xml_node plot_node)
820✔
722
{
723
  set_id(plot_node);
820✔
724
  set_bg_color(plot_node);
820✔
725
  set_universe(plot_node);
820✔
726
  set_color_by(plot_node);
820✔
727
  set_default_colors();
820✔
728
  set_user_colors(plot_node);
820✔
729
  set_mask(plot_node);
820✔
730
  set_overlap_color(plot_node);
820✔
731
}
820✔
732

733
Plot::Plot(pugi::xml_node plot_node, PlotType type)
732✔
734
  : PlottableInterface(plot_node), type_(type), index_meshlines_mesh_ {-1}
732✔
735
{
736
  set_output_path(plot_node);
732✔
737
  set_basis(plot_node);
723✔
738
  set_origin(plot_node);
723✔
739
  set_width(plot_node);
723✔
740
  set_meshlines(plot_node);
723✔
741
  slice_level_ = level_; // Copy level employed in SlicePlotBase::get_map
723✔
742
  slice_color_overlaps_ = color_overlaps_;
723✔
743
}
723✔
744

745
//==============================================================================
746
// OUTPUT_PPM writes out a previously generated image to a PPM file
747
//==============================================================================
748

749
void output_ppm(const std::string& filename, const ImageData& data)
×
750
{
751
  // Open PPM file for writing
752
  std::string fname = filename;
×
753
  fname = strtrim(fname);
×
754
  std::ofstream of;
×
755

756
  of.open(fname);
×
757

758
  // Write header
759
  of << "P6\n";
×
760
  of << data.shape()[0] << " " << data.shape()[1] << "\n";
×
761
  of << "255\n";
×
762
  of.close();
×
763

764
  of.open(fname, std::ios::binary | std::ios::app);
×
765
  // Write color for each pixel
766
  for (int y = 0; y < data.shape()[1]; y++) {
×
767
    for (int x = 0; x < data.shape()[0]; x++) {
×
768
      RGBColor rgb = data(x, y);
×
769
      of << rgb.red << rgb.green << rgb.blue;
×
770
    }
771
  }
772
  of << "\n";
×
773
}
×
774

775
//==============================================================================
776
// OUTPUT_PNG writes out a previously generated image to a PNG file
777
//==============================================================================
778

779
#ifdef USE_LIBPNG
780
void output_png(const std::string& filename, const ImageData& data)
231✔
781
{
782
  // Open PNG file for writing
783
  std::string fname = filename;
231✔
784
  fname = strtrim(fname);
231✔
785
  auto fp = std::fopen(fname.c_str(), "wb");
231✔
786

787
  // Initialize write and info structures
788
  auto png_ptr =
789
    png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);
231✔
790
  auto info_ptr = png_create_info_struct(png_ptr);
231✔
791

792
  // Setup exception handling
793
  if (setjmp(png_jmpbuf(png_ptr)))
231!
794
    fatal_error("Error during png creation");
×
795

796
  png_init_io(png_ptr, fp);
231✔
797

798
  // Write header (8 bit colour depth)
799
  int width = data.shape()[0];
231✔
800
  int height = data.shape()[1];
231✔
801
  png_set_IHDR(png_ptr, info_ptr, width, height, 8, PNG_COLOR_TYPE_RGB,
231✔
802
    PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
803
  png_write_info(png_ptr, info_ptr);
231✔
804

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

808
  // Write color for each pixel
809
  for (int y = 0; y < height; y++) {
47,751✔
810
    for (int x = 0; x < width; x++) {
11,159,720✔
811
      RGBColor rgb = data(x, y);
11,112,200✔
812
      row[3 * x] = rgb.red;
11,112,200✔
813
      row[3 * x + 1] = rgb.green;
11,112,200✔
814
      row[3 * x + 2] = rgb.blue;
11,112,200✔
815
    }
816
    png_write_row(png_ptr, row.data());
47,520✔
817
  }
818

819
  // End write
820
  png_write_end(png_ptr, nullptr);
231✔
821

822
  // Clean up data structures
823
  std::fclose(fp);
231✔
824
  png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
231✔
825
  png_destroy_write_struct(&png_ptr, &info_ptr);
231✔
826
}
231✔
827
#endif
828

829
//==============================================================================
830
// DRAW_MESH_LINES draws mesh line boundaries on an image
831
//==============================================================================
832

833
void Plot::draw_mesh_lines(ImageData& data) const
33✔
834
{
835
  RGBColor rgb;
33✔
836
  rgb = meshlines_color_;
33✔
837

838
  int ax1, ax2;
839
  switch (basis_) {
33!
840
  case PlotBasis::xy:
22✔
841
    ax1 = 0;
22✔
842
    ax2 = 1;
22✔
843
    break;
22✔
844
  case PlotBasis::xz:
11✔
845
    ax1 = 0;
11✔
846
    ax2 = 2;
11✔
847
    break;
11✔
848
  case PlotBasis::yz:
×
849
    ax1 = 1;
×
850
    ax2 = 2;
×
851
    break;
×
852
  default:
×
853
    UNREACHABLE();
×
854
  }
855

856
  Position ll_plot {origin_};
33✔
857
  Position ur_plot {origin_};
33✔
858

859
  ll_plot[ax1] -= width_[0] / 2.;
33✔
860
  ll_plot[ax2] -= width_[1] / 2.;
33✔
861
  ur_plot[ax1] += width_[0] / 2.;
33✔
862
  ur_plot[ax2] += width_[1] / 2.;
33✔
863

864
  Position width = ur_plot - ll_plot;
33✔
865

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

870
  // Find the bounds along the second axis (accounting for low-D meshes).
871
  int ax2_min, ax2_max;
872
  if (axis_lines.second.size() > 0) {
33!
873
    double frac = (axis_lines.second.back() - ll_plot[ax2]) / width[ax2];
33✔
874
    ax2_min = (1.0 - frac) * pixels()[1];
33✔
875
    if (ax2_min < 0)
33!
876
      ax2_min = 0;
×
877
    frac = (axis_lines.second.front() - ll_plot[ax2]) / width[ax2];
33✔
878
    ax2_max = (1.0 - frac) * pixels()[1];
33✔
879
    if (ax2_max > pixels()[1])
33!
NEW
880
      ax2_max = pixels()[1];
×
881
  } else {
882
    ax2_min = 0;
×
NEW
883
    ax2_max = pixels()[1];
×
884
  }
885

886
  // Iterate across the first axis and draw lines.
887
  for (auto ax1_val : axis_lines.first) {
187✔
888
    double frac = (ax1_val - ll_plot[ax1]) / width[ax1];
154✔
889
    int ax1_ind = frac * pixels()[0];
154✔
890
    for (int ax2_ind = ax2_min; ax2_ind < ax2_max; ++ax2_ind) {
24,948✔
891
      for (int plus = 0; plus <= meshlines_width_; plus++) {
49,588✔
892
        if (ax1_ind + plus >= 0 && ax1_ind + plus < pixels()[0])
24,794!
893
          data(ax1_ind + plus, ax2_ind) = rgb;
24,794✔
894
        if (ax1_ind - plus >= 0 && ax1_ind - plus < pixels()[0])
24,794!
895
          data(ax1_ind - plus, ax2_ind) = rgb;
24,794✔
896
      }
897
    }
898
  }
899

900
  // Find the bounds along the first axis.
901
  int ax1_min, ax1_max;
902
  if (axis_lines.first.size() > 0) {
33!
903
    double frac = (axis_lines.first.front() - ll_plot[ax1]) / width[ax1];
33✔
904
    ax1_min = frac * pixels()[0];
33✔
905
    if (ax1_min < 0)
33!
906
      ax1_min = 0;
×
907
    frac = (axis_lines.first.back() - ll_plot[ax1]) / width[ax1];
33✔
908
    ax1_max = frac * pixels()[0];
33✔
909
    if (ax1_max > pixels()[0])
33!
NEW
910
      ax1_max = pixels()[0];
×
911
  } else {
912
    ax1_min = 0;
×
NEW
913
    ax1_max = pixels()[0];
×
914
  }
915

916
  // Iterate across the second axis and draw lines.
917
  for (auto ax2_val : axis_lines.second) {
209✔
918
    double frac = (ax2_val - ll_plot[ax2]) / width[ax2];
176✔
919
    int ax2_ind = (1.0 - frac) * pixels()[1];
176✔
920
    for (int ax1_ind = ax1_min; ax1_ind < ax1_max; ++ax1_ind) {
28,336✔
921
      for (int plus = 0; plus <= meshlines_width_; plus++) {
56,320✔
922
        if (ax2_ind + plus >= 0 && ax2_ind + plus < pixels()[1])
28,160!
923
          data(ax1_ind, ax2_ind + plus) = rgb;
28,160✔
924
        if (ax2_ind - plus >= 0 && ax2_ind - plus < pixels()[1])
28,160!
925
          data(ax1_ind, ax2_ind - plus) = rgb;
28,160✔
926
      }
927
    }
928
  }
929
}
33✔
930

931
/* outputs a binary file that can be input into silomesh for 3D geometry
932
 * visualization.  It works the same way as create_image by dragging a particle
933
 * across the geometry for the specified number of voxels. The first 3 int's in
934
 * the binary are the number of x, y, and z voxels.  The next 3 double's are
935
 * the widths of the voxels in the x, y, and z directions. The next 3 double's
936
 * are the x, y, and z coordinates of the lower left point. Finally the binary
937
 * is filled with entries of four int's each. Each 'row' in the binary contains
938
 * four int's: 3 for x,y,z position and 1 for cell or material id.  For 1
939
 * million voxels this produces a file of approximately 15MB.
940
 */
941
void Plot::create_voxel() const
55✔
942
{
943
  // compute voxel widths in each direction
944
  array<double, 3> vox;
945
  vox[0] = width_[0] / static_cast<double>(pixels()[0]);
55✔
946
  vox[1] = width_[1] / static_cast<double>(pixels()[1]);
55✔
947
  vox[2] = width_[2] / static_cast<double>(pixels()[2]);
55✔
948

949
  // initial particle position
950
  Position ll = origin_ - width_ / 2.;
55✔
951

952
  // Open binary plot file for writing
953
  std::ofstream of;
55✔
954
  std::string fname = std::string(path_plot_);
55✔
955
  fname = strtrim(fname);
55✔
956
  hid_t file_id = file_open(fname, 'w');
55✔
957

958
  // write header info
959
  write_attribute(file_id, "filetype", "voxel");
55✔
960
  write_attribute(file_id, "version", VERSION_VOXEL);
55✔
961
  write_attribute(file_id, "openmc_version", VERSION);
55✔
962

963
#ifdef GIT_SHA1
964
  write_attribute(file_id, "git_sha1", GIT_SHA1);
965
#endif
966

967
  // Write current date and time
968
  write_attribute(file_id, "date_and_time", time_stamp().c_str());
55✔
969
  array<int, 3> h5_pixels;
970
  std::copy(pixels().begin(), pixels().end(), h5_pixels.begin());
55✔
971
  write_attribute(file_id, "num_voxels", h5_pixels);
55✔
972
  write_attribute(file_id, "voxel_width", vox);
55✔
973
  write_attribute(file_id, "lower_left", ll);
55✔
974

975
  // Create dataset for voxel data -- note that the dimensions are reversed
976
  // since we want the order in the file to be z, y, x
977
  hsize_t dims[3];
978
  dims[0] = pixels()[2];
55✔
979
  dims[1] = pixels()[1];
55✔
980
  dims[2] = pixels()[0];
55✔
981
  hid_t dspace, dset, memspace;
982
  voxel_init(file_id, &(dims[0]), &dspace, &dset, &memspace);
55✔
983

984
  SlicePlotBase pltbase;
55✔
985
  pltbase.width_ = width_;
55✔
986
  pltbase.origin_ = origin_;
55✔
987
  pltbase.basis_ = PlotBasis::xy;
55✔
988
  pltbase.pixels() = pixels();
55✔
989
  pltbase.slice_color_overlaps_ = color_overlaps_;
55✔
990

991
  ProgressBar pb;
55✔
992
  for (int z = 0; z < pixels()[2]; z++) {
4,785✔
993
    // update z coordinate
994
    pltbase.origin_.z = ll.z + z * vox[2];
4,730✔
995

996
    // generate ids using plotbase
997
    IdData ids = pltbase.get_map<IdData>();
4,730✔
998

999
    // select only cell/material ID data and flip the y-axis
1000
    int idx = color_by_ == PlotColorBy::cells ? 0 : 2;
4,730!
1001
    xt::xtensor<int32_t, 2> data_slice =
1002
      xt::view(ids.data_, xt::all(), xt::all(), idx);
4,730✔
1003
    xt::xtensor<int32_t, 2> data_flipped = xt::flip(data_slice, 0);
4,730✔
1004

1005
    // Write to HDF5 dataset
1006
    voxel_write_slice(z, dspace, dset, memspace, data_flipped.data());
4,730✔
1007

1008
    // update progress bar
1009
    pb.set_value(
4,730✔
1010
      100. * static_cast<double>(z + 1) / static_cast<double>((pixels()[2])));
4,730✔
1011
  }
4,730✔
1012

1013
  voxel_finalize(dspace, dset, memspace);
55✔
1014
  file_close(file_id);
55✔
1015
}
55✔
1016

1017
void voxel_init(hid_t file_id, const hsize_t* dims, hid_t* dspace, hid_t* dset,
55✔
1018
  hid_t* memspace)
1019
{
1020
  // Create dataspace/dataset for voxel data
1021
  *dspace = H5Screate_simple(3, dims, nullptr);
55✔
1022
  *dset = H5Dcreate(file_id, "data", H5T_NATIVE_INT, *dspace, H5P_DEFAULT,
55✔
1023
    H5P_DEFAULT, H5P_DEFAULT);
1024

1025
  // Create dataspace for a slice of the voxel
1026
  hsize_t dims_slice[2] {dims[1], dims[2]};
55✔
1027
  *memspace = H5Screate_simple(2, dims_slice, nullptr);
55✔
1028

1029
  // Select hyperslab in dataspace
1030
  hsize_t start[3] {0, 0, 0};
55✔
1031
  hsize_t count[3] {1, dims[1], dims[2]};
55✔
1032
  H5Sselect_hyperslab(*dspace, H5S_SELECT_SET, start, nullptr, count, nullptr);
55✔
1033
}
55✔
1034

1035
void voxel_write_slice(
4,730✔
1036
  int x, hid_t dspace, hid_t dset, hid_t memspace, void* buf)
1037
{
1038
  hssize_t offset[3] {x, 0, 0};
4,730✔
1039
  H5Soffset_simple(dspace, offset);
4,730✔
1040
  H5Dwrite(dset, H5T_NATIVE_INT, memspace, dspace, H5P_DEFAULT, buf);
4,730✔
1041
}
4,730✔
1042

1043
void voxel_finalize(hid_t dspace, hid_t dset, hid_t memspace)
55✔
1044
{
1045
  H5Dclose(dset);
55✔
1046
  H5Sclose(dspace);
55✔
1047
  H5Sclose(memspace);
55✔
1048
}
55✔
1049

1050
RGBColor random_color(void)
2,958✔
1051
{
1052
  return {int(prn(&model::plotter_seed) * 255),
2,958✔
1053
    int(prn(&model::plotter_seed) * 255), int(prn(&model::plotter_seed) * 255)};
2,958✔
1054
}
1055

1056
RayTracePlot::RayTracePlot(pugi::xml_node node) : PlottableInterface(node)
88✔
1057
{
1058
  set_look_at(node);
88✔
1059
  set_camera_position(node);
88✔
1060
  set_field_of_view(node);
88✔
1061
  set_pixels(node);
88✔
1062
  set_orthographic_width(node);
88✔
1063
  set_output_path(node);
88✔
1064

1065
  if (check_for_node(node, "orthographic_width") &&
99!
1066
      check_for_node(node, "field_of_view"))
11!
1067
    fatal_error("orthographic_width and field_of_view are mutually exclusive "
×
1068
                "parameters.");
1069
}
88✔
1070

1071
void RayTracePlot::update_view()
88✔
1072
{
1073
  // Get centerline vector for camera-to-model. We create vectors around this
1074
  // that form a pixel array, and then trace rays along that.
1075
  auto up = up_ / up_.norm();
88✔
1076
  Direction looking_direction = look_at_ - camera_position_;
88✔
1077
  looking_direction /= looking_direction.norm();
88✔
1078
  if (std::abs(std::abs(looking_direction.dot(up)) - 1.0) < 1e-9)
88!
1079
    fatal_error("Up vector cannot align with vector between camera position "
×
1080
                "and look_at!");
1081
  Direction cam_yaxis = looking_direction.cross(up);
88✔
1082
  cam_yaxis /= cam_yaxis.norm();
88✔
1083
  Direction cam_zaxis = cam_yaxis.cross(looking_direction);
88✔
1084
  cam_zaxis /= cam_zaxis.norm();
88✔
1085

1086
  // Cache the camera-to-model matrix
1087
  camera_to_model_ = {looking_direction.x, cam_yaxis.x, cam_zaxis.x,
88✔
1088
    looking_direction.y, cam_yaxis.y, cam_zaxis.y, looking_direction.z,
88✔
1089
    cam_yaxis.z, cam_zaxis.z};
88✔
1090
}
88✔
1091

1092
WireframeRayTracePlot::WireframeRayTracePlot(pugi::xml_node node)
55✔
1093
  : RayTracePlot(node)
55✔
1094
{
1095
  set_opacities(node);
55✔
1096
  set_wireframe_thickness(node);
55✔
1097
  set_wireframe_ids(node);
55✔
1098
  set_wireframe_color(node);
55✔
1099
  update_view();
55✔
1100
}
55✔
1101

1102
void WireframeRayTracePlot::set_wireframe_color(pugi::xml_node plot_node)
55✔
1103
{
1104
  // Copy plot wireframe color
1105
  if (check_for_node(plot_node, "wireframe_color")) {
55!
1106
    vector<int> w_rgb = get_node_array<int>(plot_node, "wireframe_color");
×
1107
    if (w_rgb.size() == 3) {
×
1108
      wireframe_color_ = w_rgb;
×
1109
    } else {
1110
      fatal_error(fmt::format("Bad wireframe RGB in plot {}", id()));
×
1111
    }
1112
  }
×
1113
}
55✔
1114

1115
void RayTracePlot::set_output_path(pugi::xml_node node)
88✔
1116
{
1117
  // Set output file path
1118
  std::string filename;
88✔
1119

1120
  if (check_for_node(node, "filename")) {
88✔
1121
    filename = get_node_value(node, "filename");
77✔
1122
  } else {
1123
    filename = fmt::format("plot_{}", id());
22✔
1124
  }
1125

1126
#ifdef USE_LIBPNG
1127
  if (!file_extension_present(filename, "png"))
88✔
1128
    filename.append(".png");
33✔
1129
#else
1130
  if (!file_extension_present(filename, "ppm"))
1131
    filename.append(".ppm");
1132
#endif
1133
  path_plot_ = filename;
88✔
1134
}
88✔
1135

1136
bool WireframeRayTracePlot::trackstack_equivalent(
3,041,159✔
1137
  const std::vector<TrackSegment>& track1,
1138
  const std::vector<TrackSegment>& track2) const
1139
{
1140
  if (wireframe_ids_.empty()) {
3,041,159✔
1141
    // Draw wireframe for all surfaces/cells/materials
1142
    if (track1.size() != track2.size())
2,545,070✔
1143
      return false;
53,977✔
1144
    for (int i = 0; i < track1.size(); ++i) {
6,707,954✔
1145
      if (track1[i].id != track2[i].id ||
8,473,410✔
1146
          track1[i].surface_index != track2[i].surface_index) {
4,236,639✔
1147
        return false;
19,910✔
1148
      }
1149
    }
1150
    return true;
2,471,183✔
1151
  } else {
1152
    // This runs in O(nm) where n is the intersection stack size
1153
    // and m is the number of IDs we are wireframing. A simpler
1154
    // algorithm can likely be found.
1155
    for (const int id : wireframe_ids_) {
986,194✔
1156
      int t1_i = 0;
496,089✔
1157
      int t2_i = 0;
496,089✔
1158

1159
      // Advance to first instance of the ID
1160
      while (t1_i < track1.size() && t2_i < track2.size()) {
562,430✔
1161
        while (t1_i < track1.size() && track1[t1_i].id != id)
392,832✔
1162
          t1_i++;
229,053✔
1163
        while (t2_i < track2.size() && track2[t2_i].id != id)
393,668✔
1164
          t2_i++;
229,889✔
1165

1166
        // This one is really important!
1167
        if ((t1_i == track1.size() && t2_i != track2.size()) ||
396,517✔
1168
            (t1_i != track1.size() && t2_i == track2.size()))
232,738✔
1169
          return false;
5,984✔
1170
        if (t1_i == track1.size() && t2_i == track2.size())
160,061!
1171
          break;
91,454✔
1172
        // Check if surface different
1173
        if (track1[t1_i].surface_index != track2[t2_i].surface_index)
68,607✔
1174
          return false;
1,485✔
1175

1176
        // Pretty sure this should not be used:
1177
        // if (t2_i != track2.size() - 1 &&
1178
        //     t1_i != track1.size() - 1 &&
1179
        //     track1[t1_i+1].id != track2[t2_i+1].id) return false;
1180
        if (t2_i != 0 && t1_i != 0 &&
121,066!
1181
            track1[t1_i - 1].surface_index != track2[t2_i - 1].surface_index)
53,944✔
1182
          return false;
781✔
1183

1184
        // Check if neighboring cells are different
1185
        // if (track1[t1_i ? t1_i - 1 : 0].id != track2[t2_i ? t2_i - 1 : 0].id)
1186
        // return false; if (track1[t1_i < track1.size() - 1 ? t1_i + 1 : t1_i
1187
        // ].id !=
1188
        //    track2[t2_i < track2.size() - 1 ? t2_i + 1 : t2_i].id) return
1189
        //    false;
1190
        t1_i++, t2_i++;
66,341✔
1191
      }
1192
    }
1193
    return true;
490,105✔
1194
  }
1195
}
1196

1197
std::pair<Position, Direction> RayTracePlot::get_pixel_ray(
3,520,000✔
1198
  int horiz, int vert) const
1199
{
1200
  // Compute field of view in radians
1201
  constexpr double DEGREE_TO_RADIAN = M_PI / 180.0;
3,520,000✔
1202
  double horiz_fov_radians = horizontal_field_of_view_ * DEGREE_TO_RADIAN;
3,520,000✔
1203
  double p0 = static_cast<double>(pixels()[0]);
3,520,000✔
1204
  double p1 = static_cast<double>(pixels()[1]);
3,520,000✔
1205
  double vert_fov_radians = horiz_fov_radians * p1 / p0;
3,520,000✔
1206

1207
  // focal_plane_dist can be changed to alter the perspective distortion
1208
  // effect. This is in units of cm. This seems to look good most of the
1209
  // time. TODO let this variable be set through XML.
1210
  constexpr double focal_plane_dist = 10.0;
3,520,000✔
1211
  const double dx = 2.0 * focal_plane_dist * std::tan(0.5 * horiz_fov_radians);
3,520,000✔
1212
  const double dy = p1 / p0 * dx;
3,520,000✔
1213

1214
  std::pair<Position, Direction> result;
3,520,000✔
1215

1216
  // Generate the starting position/direction of the ray
1217
  if (orthographic_width_ == C_NONE) { // perspective projection
3,520,000✔
1218
    Direction camera_local_vec;
3,080,000✔
1219
    camera_local_vec.x = focal_plane_dist;
3,080,000✔
1220
    camera_local_vec.y = -0.5 * dx + horiz * dx / p0;
3,080,000✔
1221
    camera_local_vec.z = 0.5 * dy - vert * dy / p1;
3,080,000✔
1222
    camera_local_vec /= camera_local_vec.norm();
3,080,000✔
1223

1224
    result.first = camera_position_;
3,080,000✔
1225
    result.second = camera_local_vec.rotate(camera_to_model_);
3,080,000✔
1226
  } else { // orthographic projection
1227

1228
    double x_pix_coord = (static_cast<double>(horiz) - p0 / 2.0) / p0;
440,000✔
1229
    double y_pix_coord = (static_cast<double>(vert) - p1 / 2.0) / p1;
440,000✔
1230

1231
    result.first = camera_position_ +
1232
                   camera_y_axis() * x_pix_coord * orthographic_width_ +
440,000✔
1233
                   camera_z_axis() * y_pix_coord * orthographic_width_;
440,000✔
1234
    result.second = camera_x_axis();
440,000✔
1235
  }
1236

1237
  return result;
3,520,000✔
1238
}
1239

1240
ImageData WireframeRayTracePlot::create_image() const
55✔
1241
{
1242
  size_t width = pixels()[0];
55✔
1243
  size_t height = pixels()[1];
55✔
1244
  ImageData data({width, height}, not_found_);
55✔
1245

1246
  // This array marks where the initial wireframe was drawn. We convolve it with
1247
  // a filter that gets adjusted with the wireframe thickness in order to
1248
  // thicken the lines.
1249
  xt::xtensor<int, 2> wireframe_initial({width, height}, 0);
55✔
1250

1251
  /* Holds all of the track segments for the current rendered line of pixels.
1252
   * old_segments holds a copy of this_line_segments from the previous line.
1253
   * By holding both we can check if the cell/material intersection stack
1254
   * differs from the left or upper neighbor. This allows a robustly drawn
1255
   * wireframe. If only checking the left pixel (which requires substantially
1256
   * less memory), the wireframe tends to be spotty and be disconnected for
1257
   * surface edges oriented horizontally in the rendering.
1258
   *
1259
   * Note that a vector of vectors is required rather than a 2-tensor,
1260
   * since the stack size varies within each column.
1261
   */
1262
  const int n_threads = num_threads();
55✔
1263
  std::vector<std::vector<std::vector<TrackSegment>>> this_line_segments(
1264
    n_threads);
55✔
1265
  for (int t = 0; t < n_threads; ++t) {
140✔
1266
    this_line_segments[t].resize(pixels()[0]);
85✔
1267
  }
1268

1269
  // The last thread writes to this, and the first thread reads from it.
1270
  std::vector<std::vector<TrackSegment>> old_segments(pixels()[0]);
55✔
1271

1272
#pragma omp parallel
30✔
1273
  {
1274
    const int n_threads = num_threads();
25✔
1275
    const int tid = thread_num();
25✔
1276

1277
    int vert = tid;
25✔
1278
    for (int iter = 0; iter <= pixels()[1] / n_threads; iter++) {
5,050✔
1279

1280
      // Save bottom line of current work chunk to compare against later. This
1281
      // used to be inside the below if block, but it causes a spurious line to
1282
      // be drawn at the bottom of the image. Not sure why, but moving it here
1283
      // fixes things.
1284
      if (tid == n_threads - 1)
5,025!
1285
        old_segments = this_line_segments[n_threads - 1];
5,025✔
1286

1287
      if (vert < pixels()[1]) {
5,025✔
1288

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

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

1294
          this_line_segments[tid][horiz].clear();
1,000,000✔
1295
          ProjectionRay ray(
1296
            ru.first, ru.second, *this, this_line_segments[tid][horiz]);
1,000,000✔
1297

1298
          ray.trace();
1,000,000✔
1299

1300
          // Now color the pixel based on what we have intersected...
1301
          // Loops backwards over intersections.
1302
          Position current_color(
1303
            not_found_.red, not_found_.green, not_found_.blue);
1,000,000✔
1304
          const auto& segments = this_line_segments[tid][horiz];
1,000,000✔
1305

1306
          // There must be at least two cell intersections to color, front and
1307
          // back of the cell. Maybe an infinitely thick cell could be present
1308
          // with no back, but why would you want to color that? It's easier to
1309
          // just skip that edge case and not even color it.
1310
          if (segments.size() <= 1)
1,000,000✔
1311
            continue;
616,655✔
1312

1313
          for (int i = segments.size() - 2; i >= 0; --i) {
1,072,335✔
1314
            int colormap_idx = segments[i].id;
688,990✔
1315
            RGBColor seg_color = colors_[colormap_idx];
688,990✔
1316
            Position seg_color_vec(
1317
              seg_color.red, seg_color.green, seg_color.blue);
688,990✔
1318
            double mixing =
1319
              std::exp(-xs_[colormap_idx] *
688,990✔
1320
                       (segments[i + 1].length - segments[i].length));
688,990✔
1321
            current_color =
1322
              current_color * mixing + (1.0 - mixing) * seg_color_vec;
688,990✔
1323
          }
1324

1325
          // save result converting from double-precision color coordinates to
1326
          // byte-sized
1327
          RGBColor result;
383,345✔
1328
          result.red = static_cast<uint8_t>(current_color.x);
383,345✔
1329
          result.green = static_cast<uint8_t>(current_color.y);
383,345✔
1330
          result.blue = static_cast<uint8_t>(current_color.z);
383,345✔
1331
          data(horiz, vert) = result;
383,345✔
1332

1333
          // Check to draw wireframe in horizontal direction. No inter-thread
1334
          // comm.
1335
          if (horiz > 0) {
383,345✔
1336
            if (!trackstack_equivalent(this_line_segments[tid][horiz],
382,345✔
1337
                  this_line_segments[tid][horiz - 1])) {
382,345✔
1338
              wireframe_initial(horiz, vert) = 1;
15,710✔
1339
            }
1340
          }
1341
        }
1,000,000✔
1342
      } // end "if" vert in correct range
1343

1344
      // We require a barrier before comparing vertical neighbors' intersection
1345
      // stacks. i.e. all threads must be done with their line.
1346
#pragma omp barrier
1347

1348
      // Now that the horizontal line has finished rendering, we can fill in
1349
      // wireframe entries that require comparison among all the threads. Hence
1350
      // the omp barrier being used. It has to be OUTSIDE any if blocks!
1351
      if (vert < pixels()[1]) {
5,025✔
1352
        // Loop over horizontal pixels, checking intersection stack of upper
1353
        // neighbor
1354

1355
        const std::vector<std::vector<TrackSegment>>* top_cmp = nullptr;
5,000✔
1356
        if (tid == 0)
5,000!
1357
          top_cmp = &old_segments;
5,000✔
1358
        else
1359
          top_cmp = &this_line_segments[tid - 1];
1360

1361
        for (int horiz = 0; horiz < pixels()[0]; ++horiz) {
1,005,000✔
1362
          if (!trackstack_equivalent(
1,000,000✔
1363
                this_line_segments[tid][horiz], (*top_cmp)[horiz])) {
1,000,000✔
1364
            wireframe_initial(horiz, vert) = 1;
20,595✔
1365
          }
1366
        }
1367
      }
1368

1369
      // We need another barrier to ensure threads don't proceed to modify their
1370
      // intersection stacks on that horizontal line while others are
1371
      // potentially still working on the above.
1372
#pragma omp barrier
1373
      vert += n_threads;
5,025✔
1374
    }
1375
  } // end omp parallel
1376

1377
  // Now thicken the wireframe lines and apply them to our image
1378
  for (int vert = 0; vert < pixels()[1]; ++vert) {
11,055✔
1379
    for (int horiz = 0; horiz < pixels()[0]; ++horiz) {
2,211,000✔
1380
      if (wireframe_initial(horiz, vert)) {
2,200,000✔
1381
        if (wireframe_thickness_ == 1)
70,983✔
1382
          data(horiz, vert) = wireframe_color_;
30,195✔
1383
        for (int i = -wireframe_thickness_ / 2; i < wireframe_thickness_ / 2;
195,723✔
1384
             ++i)
1385
          for (int j = -wireframe_thickness_ / 2; j < wireframe_thickness_ / 2;
546,876✔
1386
               ++j)
1387
            if (i * i + j * j < wireframe_thickness_ * wireframe_thickness_) {
422,136!
1388

1389
              // Check if wireframe pixel is out of bounds
1390
              int w_i = std::max(std::min(horiz + i, pixels()[0] - 1), 0);
422,136✔
1391
              int w_j = std::max(std::min(vert + j, pixels()[1] - 1), 0);
422,136✔
1392
              data(w_i, w_j) = wireframe_color_;
422,136✔
1393
            }
1394
      }
1395
    }
1396
  }
1397

1398
  return data;
110✔
1399
}
55✔
1400

1401
void WireframeRayTracePlot::create_output() const
55✔
1402
{
1403
  ImageData data = create_image();
55✔
1404
  write_image(data);
55✔
1405
}
55✔
1406

1407
void RayTracePlot::print_info() const
88✔
1408
{
1409
  fmt::print("Camera position: {} {} {}\n", camera_position_.x,
72✔
1410
    camera_position_.y, camera_position_.z);
88✔
1411
  fmt::print("Look at: {} {} {}\n", look_at_.x, look_at_.y, look_at_.z);
160✔
1412
  fmt::print(
72✔
1413
    "Horizontal field of view: {} degrees\n", horizontal_field_of_view_);
88✔
1414
  fmt::print("Pixels: {} {}\n", pixels()[0], pixels()[1]);
160✔
1415
}
88✔
1416

1417
void WireframeRayTracePlot::print_info() const
55✔
1418
{
1419
  fmt::print("Plot Type: Wireframe ray-traced\n");
55✔
1420
  RayTracePlot::print_info();
55✔
1421
}
55✔
1422

1423
void WireframeRayTracePlot::set_opacities(pugi::xml_node node)
55✔
1424
{
1425
  xs_.resize(colors_.size(), 1e6); // set to large value for opaque by default
55✔
1426

1427
  for (auto cn : node.children("color")) {
121✔
1428
    // Make sure 3 values are specified for RGB
1429
    double user_xs = std::stod(get_node_value(cn, "xs"));
66✔
1430
    int col_id = std::stoi(get_node_value(cn, "id"));
66✔
1431

1432
    // Add RGB
1433
    if (PlotColorBy::cells == color_by_) {
66!
1434
      if (model::cell_map.find(col_id) != model::cell_map.end()) {
66!
1435
        col_id = model::cell_map[col_id];
66✔
1436
        xs_[col_id] = user_xs;
66✔
1437
      } else {
1438
        warning(fmt::format(
×
1439
          "Could not find cell {} specified in plot {}", col_id, id()));
×
1440
      }
1441
    } else if (PlotColorBy::mats == color_by_) {
×
1442
      if (model::material_map.find(col_id) != model::material_map.end()) {
×
1443
        col_id = model::material_map[col_id];
×
1444
        xs_[col_id] = user_xs;
×
1445
      } else {
1446
        warning(fmt::format(
×
1447
          "Could not find material {} specified in plot {}", col_id, id()));
×
1448
      }
1449
    }
1450
  }
1451
}
55✔
1452

1453
void RayTracePlot::set_orthographic_width(pugi::xml_node node)
88✔
1454
{
1455
  if (check_for_node(node, "orthographic_width")) {
88✔
1456
    double orthographic_width =
1457
      std::stod(get_node_value(node, "orthographic_width", true));
11✔
1458
    if (orthographic_width < 0.0)
11!
1459
      fatal_error("Requires positive orthographic_width");
×
1460
    orthographic_width_ = orthographic_width;
11✔
1461
  }
1462
}
88✔
1463

1464
void WireframeRayTracePlot::set_wireframe_thickness(pugi::xml_node node)
55✔
1465
{
1466
  if (check_for_node(node, "wireframe_thickness")) {
55✔
1467
    int wireframe_thickness =
1468
      std::stoi(get_node_value(node, "wireframe_thickness", true));
22✔
1469
    if (wireframe_thickness < 0)
22!
1470
      fatal_error("Requires non-negative wireframe thickness");
×
1471
    wireframe_thickness_ = wireframe_thickness;
22✔
1472
  }
1473
}
55✔
1474

1475
void WireframeRayTracePlot::set_wireframe_ids(pugi::xml_node node)
55✔
1476
{
1477
  if (check_for_node(node, "wireframe_ids")) {
55✔
1478
    wireframe_ids_ = get_node_array<int>(node, "wireframe_ids");
11✔
1479
    // It is read in as actual ID values, but we have to convert to indices in
1480
    // mat/cell array
1481
    for (auto& x : wireframe_ids_)
22✔
1482
      x = color_by_ == PlotColorBy::mats ? model::material_map[x]
11!
1483
                                         : model::cell_map[x];
×
1484
  }
1485
  // We make sure the list is sorted in order to later use
1486
  // std::binary_search.
1487
  std::sort(wireframe_ids_.begin(), wireframe_ids_.end());
55✔
1488
}
55✔
1489

1490
void RayTracePlot::set_pixels(pugi::xml_node node)
88✔
1491
{
1492
  vector<int> pxls = get_node_array<int>(node, "pixels");
88✔
1493
  if (pxls.size() != 2)
88!
1494
    fatal_error(
×
1495
      fmt::format("<pixels> must be length 2 in projection plot {}", id()));
×
1496
  pixels()[0] = pxls[0];
88✔
1497
  pixels()[1] = pxls[1];
88✔
1498
}
88✔
1499

1500
void RayTracePlot::set_camera_position(pugi::xml_node node)
88✔
1501
{
1502
  vector<double> camera_pos = get_node_array<double>(node, "camera_position");
88✔
1503
  if (camera_pos.size() != 3) {
88!
1504
    fatal_error(fmt::format(
×
1505
      "camera_position element must have three floating point values"));
1506
  }
1507
  camera_position_.x = camera_pos[0];
88✔
1508
  camera_position_.y = camera_pos[1];
88✔
1509
  camera_position_.z = camera_pos[2];
88✔
1510
}
88✔
1511

1512
void RayTracePlot::set_look_at(pugi::xml_node node)
88✔
1513
{
1514
  vector<double> look_at = get_node_array<double>(node, "look_at");
88✔
1515
  if (look_at.size() != 3) {
88!
1516
    fatal_error("look_at element must have three floating point values");
×
1517
  }
1518
  look_at_.x = look_at[0];
88✔
1519
  look_at_.y = look_at[1];
88✔
1520
  look_at_.z = look_at[2];
88✔
1521
}
88✔
1522

1523
void RayTracePlot::set_field_of_view(pugi::xml_node node)
88✔
1524
{
1525
  // Defaults to 70 degree horizontal field of view (see .h file)
1526
  if (check_for_node(node, "horizontal_field_of_view")) {
88!
1527
    double fov =
1528
      std::stod(get_node_value(node, "horizontal_field_of_view", true));
×
1529
    if (fov < 180.0 && fov > 0.0) {
×
1530
      horizontal_field_of_view_ = fov;
×
1531
    } else {
1532
      fatal_error(fmt::format("Horizontal field of view for plot {} "
×
1533
                              "out-of-range. Must be in (0, 180) degrees.",
1534
        id()));
×
1535
    }
1536
  }
1537
}
88✔
1538

1539
SolidRayTracePlot::SolidRayTracePlot(pugi::xml_node node) : RayTracePlot(node)
33✔
1540
{
1541
  set_opaque_ids(node);
33✔
1542
  set_diffuse_fraction(node);
33✔
1543
  set_light_position(node);
33✔
1544
  update_view();
33✔
1545
}
33✔
1546

1547
void SolidRayTracePlot::print_info() const
33✔
1548
{
1549
  fmt::print("Plot Type: Solid ray-traced\n");
33✔
1550
  RayTracePlot::print_info();
33✔
1551
}
33✔
1552

1553
ImageData SolidRayTracePlot::create_image() const
33✔
1554
{
1555
  size_t width = pixels()[0];
33✔
1556
  size_t height = pixels()[1];
33✔
1557
  ImageData data({width, height}, not_found_);
33✔
1558

1559
#pragma omp parallel for schedule(dynamic) collapse(2)
18✔
1560
  for (int horiz = 0; horiz < pixels()[0]; ++horiz) {
3,015✔
1561
    for (int vert = 0; vert < pixels()[1]; ++vert) {
603,000✔
1562
      // RayTracePlot implements camera ray generation
1563
      std::pair<Position, Direction> ru = get_pixel_ray(horiz, vert);
600,000✔
1564
      PhongRay ray(ru.first, ru.second, *this);
600,000✔
1565
      ray.trace();
600,000✔
1566
      data(horiz, vert) = ray.result_color();
600,000✔
1567
    }
600,000✔
1568
  }
1569

1570
  return data;
33✔
1571
}
1572

1573
void SolidRayTracePlot::create_output() const
33✔
1574
{
1575
  ImageData data = create_image();
33✔
1576
  write_image(data);
33✔
1577
}
33✔
1578

1579
void SolidRayTracePlot::set_opaque_ids(pugi::xml_node node)
33✔
1580
{
1581
  if (check_for_node(node, "opaque_ids")) {
33!
1582
    auto opaque_ids_tmp = get_node_array<int>(node, "opaque_ids");
33✔
1583

1584
    // It is read in as actual ID values, but we have to convert to indices in
1585
    // mat/cell array
1586
    for (auto& x : opaque_ids_tmp)
99✔
1587
      x = color_by_ == PlotColorBy::mats ? model::material_map[x]
66!
1588
                                         : model::cell_map[x];
×
1589

1590
    opaque_ids_.insert(opaque_ids_tmp.begin(), opaque_ids_tmp.end());
33✔
1591
  }
33✔
1592
}
33✔
1593

1594
void SolidRayTracePlot::set_light_position(pugi::xml_node node)
33✔
1595
{
1596
  if (check_for_node(node, "light_position")) {
33✔
1597
    auto light_pos_tmp = get_node_array<double>(node, "light_position");
11✔
1598

1599
    if (light_pos_tmp.size() != 3)
11!
1600
      fatal_error("Light position must be given as 3D coordinates");
×
1601

1602
    light_location_.x = light_pos_tmp[0];
11✔
1603
    light_location_.y = light_pos_tmp[1];
11✔
1604
    light_location_.z = light_pos_tmp[2];
11✔
1605
  } else {
11✔
1606
    light_location_ = camera_position();
22✔
1607
  }
1608
}
33✔
1609

1610
void SolidRayTracePlot::set_diffuse_fraction(pugi::xml_node node)
33✔
1611
{
1612
  if (check_for_node(node, "diffuse_fraction")) {
33✔
1613
    diffuse_fraction_ = std::stod(get_node_value(node, "diffuse_fraction"));
11✔
1614
    if (diffuse_fraction_ < 0.0 || diffuse_fraction_ > 1.0) {
11!
1615
      fatal_error("Must have 0 <= diffuse fraction <= 1");
×
1616
    }
1617
  }
1618
}
33✔
1619

1620
void Ray::compute_distance()
3,012,306✔
1621
{
1622
  boundary() = distance_to_boundary(*this);
3,012,306✔
1623
}
3,012,306✔
1624

1625
void Ray::trace()
3,520,000✔
1626
{
1627
  // To trace the ray from its origin all the way through the model, we have
1628
  // to proceed in two phases. In the first, the ray may or may not be found
1629
  // inside the model. If the ray is already in the model, phase one can be
1630
  // skipped. Otherwise, the ray has to be advanced to the boundary of the
1631
  // model where all the cells are defined. Importantly, this is assuming that
1632
  // the model is convex, which is a very reasonable assumption for any
1633
  // radiation transport model.
1634
  //
1635
  // After phase one is done, we can starting tracing from cell to cell within
1636
  // the model. This step can use neighbor lists to accelerate the ray tracing.
1637

1638
  // Attempt to initialize the particle. We may have to enter a loop to move
1639
  // it up to the edge of the model.
1640
  bool inside_cell = exhaustive_find_cell(*this, settings::verbosity >= 10);
3,520,000✔
1641

1642
  // Advance to the boundary of the model
1643
  while (!inside_cell) {
15,616,590!
1644
    advance_to_boundary_from_void();
15,616,590✔
1645
    inside_cell = exhaustive_find_cell(*this, settings::verbosity >= 10);
15,616,590✔
1646

1647
    // If true this means no surface was intersected. See cell.cpp and search
1648
    // for numeric_limits to see where we return it.
1649
    if (surface() == std::numeric_limits<int>::max()) {
15,616,590!
1650
      warning(fmt::format("Lost a ray, r = {}, u = {}", r(), u()));
×
1651
      return;
×
1652
    }
1653

1654
    // Exit this loop and enter into cell-to-cell ray tracing (which uses
1655
    // neighbor lists)
1656
    if (inside_cell)
15,616,590✔
1657
      break;
1,549,042✔
1658

1659
    // if there is no intersection with the model, we're done
1660
    if (boundary().surface() == SURFACE_NONE)
14,067,548✔
1661
      return;
1,970,958✔
1662

1663
    event_counter_++;
12,096,590✔
1664
    if (event_counter_ > MAX_INTERSECTIONS) {
12,096,590!
1665
      warning("Likely infinite loop in ray traced plot");
×
1666
      return;
×
1667
    }
1668
  }
1669

1670
  // Call the specialized logic for this type of ray. This is for the
1671
  // intersection for the first intersection if we had one.
1672
  if (boundary().surface() != SURFACE_NONE) {
1,549,042!
1673
    // set the geometry state's surface attribute to be used for
1674
    // surface normal computation
1675
    surface() = boundary().surface();
1,549,042✔
1676
    on_intersection();
1,549,042✔
1677
    if (stop_)
1,549,042!
1678
      return;
×
1679
  }
1680

1681
  // reset surface attribute to zero after the first intersection so that it
1682
  // doesn't perturb surface crossing logic from here on out
1683
  surface() = 0;
1,549,042✔
1684

1685
  // This is the ray tracing loop within the model. It exits after exiting
1686
  // the model, which is equivalent to assuming that the model is convex.
1687
  // It would be nice to factor out the on_intersection at the end of this
1688
  // loop and then do "while (inside_cell)", but we can't guarantee it's
1689
  // on a surface in that case. There might be some other way to set it
1690
  // up that is perhaps a little more elegant, but this is what works just
1691
  // fine.
1692
  while (true) {
1693

1694
    compute_distance();
2,306,634✔
1695

1696
    // There are no more intersections to process
1697
    // if we hit the edge of the model, so stop
1698
    // the particle in that case. Also, just exit
1699
    // if a negative distance was somehow computed.
1700
    if (boundary().distance() == INFTY || boundary().distance() == INFINITY ||
4,613,268!
1701
        boundary().distance() < 0) {
2,306,634!
1702
      return;
×
1703
    }
1704

1705
    // See below comment where call_on_intersection is checked in an
1706
    // if statement for an explanation of this.
1707
    bool call_on_intersection {true};
2,306,634✔
1708
    if (boundary().distance() < 10 * TINY_BIT) {
2,306,634✔
1709
      call_on_intersection = false;
593,285✔
1710
    }
1711

1712
    // DAGMC surfaces expect us to go a little bit further than the advance
1713
    // distance to properly check cell inclusion.
1714
    boundary().distance() += TINY_BIT;
2,306,634✔
1715

1716
    // Advance particle, prepare for next intersection
1717
    for (int lev = 0; lev < n_coord(); ++lev) {
4,613,268✔
1718
      coord(lev).r() += boundary().distance() * coord(lev).u();
2,306,634✔
1719
    }
1720
    surface() = boundary().surface();
2,306,634✔
1721
    n_coord_last() = n_coord();
2,306,634✔
1722
    n_coord() = boundary().coord_level();
2,306,634✔
1723
    if (boundary().lattice_translation()[0] != 0 ||
2,306,634✔
1724
        boundary().lattice_translation()[1] != 0 ||
4,613,268!
1725
        boundary().lattice_translation()[2] != 0) {
2,306,634!
1726
      cross_lattice(*this, boundary(), settings::verbosity >= 10);
×
1727
    }
1728

1729
    // Record how far the ray has traveled
1730
    traversal_distance_ += boundary().distance();
2,306,634✔
1731
    inside_cell = neighbor_list_find_cell(*this, settings::verbosity >= 10);
2,306,634✔
1732

1733
    // Call the specialized logic for this type of ray. Note that we do not
1734
    // call this if the advance distance is very small. Unfortunately, it seems
1735
    // darn near impossible to get the particle advanced to the model boundary
1736
    // and through it without sometimes accidentally calling on_intersection
1737
    // twice. This incorrectly shades the region as occluded when it might not
1738
    // actually be. By screening out intersection distances smaller than a
1739
    // threshold 10x larger than the scoot distance used to advance up to the
1740
    // model boundary, we can avoid that situation.
1741
    if (call_on_intersection) {
2,306,634✔
1742
      on_intersection();
1,713,349✔
1743
      if (stop_)
1,713,349✔
1744
        return;
35,519✔
1745
    }
1746

1747
    if (!inside_cell)
2,271,115✔
1748
      return;
1,513,523✔
1749

1750
    event_counter_++;
757,592✔
1751
    if (event_counter_ > MAX_INTERSECTIONS) {
757,592!
1752
      warning("Likely infinite loop in ray traced plot");
×
1753
      return;
×
1754
    }
1755
  }
757,592✔
1756
}
1757

1758
void ProjectionRay::on_intersection()
2,359,148✔
1759
{
1760
  // This records a tuple with the following info
1761
  //
1762
  // 1) ID (material or cell depending on color_by_)
1763
  // 2) Distance traveled by the ray through that ID
1764
  // 3) Index of the intersected surface (starting from 1)
1765

1766
  line_segments_.emplace_back(
2,359,148✔
1767
    plot_.color_by_ == PlottableInterface::PlotColorBy::mats
2,359,148✔
1768
      ? material()
545,919✔
1769
      : lowest_coord().cell(),
1,813,229✔
1770
    traversal_distance_, boundary().surface_index());
2,359,148✔
1771
}
2,359,148✔
1772

1773
void PhongRay::on_intersection()
903,243✔
1774
{
1775
  // Check if we hit an opaque material or cell
1776
  int hit_id = plot_.color_by_ == PlottableInterface::PlotColorBy::mats
903,243✔
1777
                 ? material()
903,243!
1778
                 : lowest_coord().cell();
×
1779

1780
  // If we are reflected and have advanced beyond the camera,
1781
  // the ray is done. This is checked here because we should
1782
  // kill the ray even if the material is not opaque.
1783
  if (reflected_ && (r() - plot_.camera_position()).dot(u()) >= 0.0) {
903,243!
1784
    stop();
×
1785
    return;
162,052✔
1786
  }
1787

1788
  // Anything that's not opaque has zero impact on the plot.
1789
  if (plot_.opaque_ids_.find(hit_id) == plot_.opaque_ids_.end())
903,243✔
1790
    return;
162,052✔
1791

1792
  if (!reflected_) {
741,191✔
1793
    // reflect the particle and set the color to be colored by
1794
    // the normal or the diffuse lighting contribution
1795
    reflected_ = true;
705,672✔
1796
    result_color_ = plot_.colors_[hit_id];
705,672✔
1797
    Direction to_light = plot_.light_location_ - r();
705,672✔
1798
    to_light /= to_light.norm();
705,672✔
1799

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

1815
    // Get surface pointer
1816
    const auto& surf = model::surfaces.at(surface_index());
705,672✔
1817

1818
    Direction normal = surf->normal(r_local());
705,672✔
1819
    normal /= normal.norm();
705,672✔
1820

1821
    // Need to apply translations to find the normal vector in
1822
    // the base level universe's coordinate system.
1823
    for (int lev = n_coord() - 2; lev >= 0; --lev) {
705,672!
1824
      if (coord(lev + 1).rotated()) {
×
1825
        const Cell& c {*model::cells[coord(lev).cell()]};
×
1826
        normal = normal.inverse_rotate(c.rotation_);
×
1827
      }
1828
    }
1829

1830
    // use the normal opposed to the ray direction
1831
    if (normal.dot(u()) > 0.0) {
705,672✔
1832
      normal *= -1.0;
63,789✔
1833
    }
1834

1835
    // Facing away from the light means no lighting
1836
    double dotprod = normal.dot(to_light);
705,672✔
1837
    dotprod = std::max(0.0, dotprod);
705,672✔
1838

1839
    double modulation =
705,672✔
1840
      plot_.diffuse_fraction_ + (1.0 - plot_.diffuse_fraction_) * dotprod;
705,672✔
1841
    result_color_ *= modulation;
705,672✔
1842

1843
    // Now point the particle to the camera. We now begin
1844
    // checking to see if it's occluded by another surface
1845
    u() = to_light;
705,672✔
1846

1847
    orig_hit_id_ = hit_id;
705,672✔
1848

1849
    // OpenMC native CSG and DAGMC surfaces have some slight differences
1850
    // in how they interpret particles that are sitting on a surface.
1851
    // I don't know exactly why, but this makes everything work beautifully.
1852
    if (surf->geom_type() == GeometryType::DAG) {
705,672!
1853
      surface() = 0;
×
1854
    } else {
1855
      surface() = -surface(); // go to other side
705,672✔
1856
    }
1857

1858
    // Must fully restart coordinate search. Why? Not sure.
1859
    clear();
705,672✔
1860

1861
    // Note this could likely be faster if we cached the previous
1862
    // cell we were in before the reflection. This is the easiest
1863
    // way to fully initialize all the sub-universe coordinates and
1864
    // directions though.
1865
    bool found = exhaustive_find_cell(*this);
705,672✔
1866
    if (!found) {
705,672!
1867
      fatal_error("Lost particle after reflection.");
×
1868
    }
1869

1870
    // Must recalculate distance to boundary due to the
1871
    // direction change
1872
    compute_distance();
705,672✔
1873

1874
  } else {
1875
    // If it's not facing the light, we color with the diffuse contribution, so
1876
    // next we check if we're going to occlude the last reflected surface. if
1877
    // so, color by the diffuse contribution instead
1878

1879
    if (orig_hit_id_ == -1)
35,519!
1880
      fatal_error("somehow a ray got reflected but not original ID set?");
×
1881

1882
    result_color_ = plot_.colors_[orig_hit_id_];
35,519✔
1883
    result_color_ *= plot_.diffuse_fraction_;
35,519✔
1884
    stop();
35,519✔
1885
  }
1886
}
1887

1888
extern "C" int openmc_id_map(const void* plot, int32_t* data_out)
267✔
1889
{
1890

1891
  auto plt = reinterpret_cast<const SlicePlotBase*>(plot);
267✔
1892
  if (!plt) {
267!
1893
    set_errmsg("Invalid slice pointer passed to openmc_id_map");
×
1894
    return OPENMC_E_INVALID_ARGUMENT;
×
1895
  }
1896

1897
  if (plt->slice_color_overlaps_ && model::overlap_check_count.size() == 0) {
267!
1898
    model::overlap_check_count.resize(model::cells.size());
22✔
1899
  }
1900

1901
  auto ids = plt->get_map<IdData>();
267✔
1902

1903
  // write id data to array
1904
  std::copy(ids.data_.begin(), ids.data_.end(), data_out);
267✔
1905

1906
  return 0;
267✔
1907
}
267✔
1908

1909
extern "C" int openmc_property_map(const void* plot, double* data_out)
11✔
1910
{
1911

1912
  auto plt = reinterpret_cast<const SlicePlotBase*>(plot);
11✔
1913
  if (!plt) {
11!
1914
    set_errmsg("Invalid slice pointer passed to openmc_id_map");
×
1915
    return OPENMC_E_INVALID_ARGUMENT;
×
1916
  }
1917

1918
  if (plt->slice_color_overlaps_ && model::overlap_check_count.size() == 0) {
11!
1919
    model::overlap_check_count.resize(model::cells.size());
×
1920
  }
1921

1922
  auto props = plt->get_map<PropertyData>();
11✔
1923

1924
  // write id data to array
1925
  std::copy(props.data_.begin(), props.data_.end(), data_out);
11✔
1926

1927
  return 0;
11✔
1928
}
11✔
1929

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