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

openmc-dev / openmc / 12835925524

17 Jan 2025 07:55PM UTC coverage: 84.906% (+0.04%) from 84.867%
12835925524

Pull #2655

github

web-flow
Merge 05d6dc4b6 into bd874f1b3
Pull Request #2655: Raytrace plots

392 of 432 new or added lines in 5 files covered. (90.74%)

1 existing line in 1 file now uncovered.

50290 of 59230 relevant lines covered (84.91%)

33715955.31 hits per line

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

83.6
/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/constants.h"
19
#include "openmc/container_util.h"
20
#include "openmc/dagmc.h"
21
#include "openmc/error.h"
22
#include "openmc/file_utils.h"
23
#include "openmc/geometry.h"
24
#include "openmc/hdf5_interface.h"
25
#include "openmc/material.h"
26
#include "openmc/mesh.h"
27
#include "openmc/message_passing.h"
28
#include "openmc/openmp_interface.h"
29
#include "openmc/output.h"
30
#include "openmc/particle.h"
31
#include "openmc/progress_bar.h"
32
#include "openmc/random_lcg.h"
33
#include "openmc/settings.h"
34
#include "openmc/simulation.h"
35
#include "openmc/string_utils.h"
36

37
namespace openmc {
38

39
//==============================================================================
40
// Constants
41
//==============================================================================
42

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

47
IdData::IdData(size_t h_res, size_t v_res) : data_({v_res, h_res, 3}, NOT_FOUND)
5,484✔
48
{}
5,484✔
49

50
void IdData::set_value(size_t y, size_t x, const GeometryState& p, int level)
40,887,708✔
51
{
52
  // set cell data
53
  if (p.n_coord() <= level) {
40,887,708✔
54
    data_(y, x, 0) = NOT_FOUND;
×
55
    data_(y, x, 1) = NOT_FOUND;
×
56
  } else {
57
    data_(y, x, 0) = model::cells.at(p.coord(level).cell)->id_;
40,887,708✔
58
    data_(y, x, 1) = level == p.n_coord() - 1
81,775,416✔
59
                       ? p.cell_instance()
40,887,708✔
60
                       : cell_instance_at_level(p, level);
×
61
  }
62

63
  // set material data
64
  Cell* c = model::cells.at(p.lowest_coord().cell).get();
40,887,708✔
65
  if (p.material() == MATERIAL_VOID) {
40,887,708✔
66
    data_(y, x, 2) = MATERIAL_VOID;
32,044,128✔
67
    return;
32,044,128✔
68
  } else if (c->type_ == Fill::MATERIAL) {
8,843,580✔
69
    Material* m = model::materials.at(p.material()).get();
8,843,580✔
70
    data_(y, x, 2) = m->id_;
8,843,580✔
71
  }
72
}
73

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

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

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

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

99
//==============================================================================
100
// Global variables
101
//==============================================================================
102

103
namespace model {
104

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

109
} // namespace model
110

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

115
extern "C" int openmc_plot_geometry()
288✔
116
{
117

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

123
  return 0;
288✔
124
}
125

126
void Plot::create_output() const
372✔
127
{
128
  if (PlotType::slice == type_) {
372✔
129
    // create 2D image
130
    create_image();
312✔
131
  } else if (PlotType::voxel == type_) {
60✔
132
    // create voxel file for 3D viewing
133
    create_voxel();
60✔
134
  }
135
}
372✔
136

137
void Plot::print_info() const
348✔
138
{
139
  // Plot type
140
  if (PlotType::slice == type_) {
348✔
141
    fmt::print("Plot Type: Slice\n");
288✔
142
  } else if (PlotType::voxel == type_) {
60✔
143
    fmt::print("Plot Type: Voxel\n");
60✔
144
  }
145

146
  // Plot parameters
147
  fmt::print("Origin: {} {} {}\n", origin_[0], origin_[1], origin_[2]);
638✔
148

149
  if (PlotType::slice == type_) {
348✔
150
    fmt::print("Width: {:4} {:4}\n", width_[0], width_[1]);
576✔
151
  } else if (PlotType::voxel == type_) {
60✔
152
    fmt::print("Width: {:4} {:4} {:4}\n", width_[0], width_[1], width_[2]);
120✔
153
  }
154

155
  if (PlotColorBy::cells == color_by_) {
348✔
156
    fmt::print("Coloring: Cells\n");
240✔
157
  } else if (PlotColorBy::mats == color_by_) {
108✔
158
    fmt::print("Coloring: Materials\n");
108✔
159
  }
160

161
  if (PlotType::slice == type_) {
348✔
162
    switch (basis_) {
288✔
163
    case PlotBasis::xy:
168✔
164
      fmt::print("Basis: XY\n");
140✔
165
      break;
168✔
166
    case PlotBasis::xz:
60✔
167
      fmt::print("Basis: XZ\n");
50✔
168
      break;
60✔
169
    case PlotBasis::yz:
60✔
170
      fmt::print("Basis: YZ\n");
50✔
171
      break;
60✔
172
    }
173
    fmt::print("Pixels: {} {}\n", pixels_[0], pixels_[1]);
576✔
174
  } else if (PlotType::voxel == type_) {
60✔
175
    fmt::print("Voxels: {} {} {}\n", pixels_[0], pixels_[1], pixels_[2]);
120✔
176
  }
177
}
348✔
178

179
void read_plots_xml()
1,515✔
180
{
181
  // Check if plots.xml exists; this is only necessary when the plot runmode is
182
  // initiated. Otherwise, we want to read plots.xml because it may be called
183
  // later via the API. In that case, its ok for a plots.xml to not exist
184
  std::string filename = settings::path_input + "plots.xml";
1,515✔
185
  if (!file_exists(filename) && settings::run_mode == RunMode::PLOTTING) {
1,515✔
186
    fatal_error(fmt::format("Plots XML file '{}' does not exist!", filename));
×
187
  }
188

189
  write_message("Reading plot XML file...", 5);
1,515✔
190

191
  // Parse plots.xml file
192
  pugi::xml_document doc;
1,515✔
193
  doc.load_file(filename.c_str());
1,515✔
194

195
  pugi::xml_node root = doc.document_element();
1,515✔
196

197
  read_plots_xml(root);
1,515✔
198
}
1,515✔
199

200
void read_plots_xml(pugi::xml_node root)
1,962✔
201
{
202
  for (auto node : root.children("plot")) {
2,928✔
203
    std::string id_string = get_node_value(node, "id", true);
976✔
204
    int id = std::stoi(id_string);
976✔
205
    if (check_for_node(node, "type")) {
976✔
206
      std::string type_str = get_node_value(node, "type", true);
976✔
207
      if (type_str == "slice")
976✔
208
        model::plots.emplace_back(
810✔
209
          std::make_unique<Plot>(node, Plot::PlotType::slice));
1,630✔
210
      else if (type_str == "voxel")
156✔
211
        model::plots.emplace_back(
60✔
212
          std::make_unique<Plot>(node, Plot::PlotType::voxel));
120✔
213
      else if (type_str == "projection")
96✔
214
        model::plots.emplace_back(std::make_unique<ProjectionPlot>(node));
60✔
215
      else if (type_str == "phong")
36✔
216
        model::plots.emplace_back(std::make_unique<PhongPlot>(node));
36✔
217
      else
218
        fatal_error(
×
219
          fmt::format("Unsupported plot type '{}' in plot {}", type_str, id));
×
220

221
      model::plot_map[model::plots.back()->id()] = model::plots.size() - 1;
966✔
222
    } else {
966✔
223
      fatal_error(fmt::format("Must specify plot type in plot {}", id));
×
224
    }
225
  }
966✔
226
}
1,952✔
227

228
void free_memory_plot()
6,864✔
229
{
230
  model::plots.clear();
6,864✔
231
  model::plot_map.clear();
6,864✔
232
}
6,864✔
233

234
// creates an image based on user input from a plots.xml <plot>
235
// specification in the PNG/PPM format
236
void Plot::create_image() const
312✔
237
{
238

239
  size_t width = pixels_[0];
312✔
240
  size_t height = pixels_[1];
312✔
241

242
  ImageData data({width, height}, not_found_);
312✔
243

244
  // generate ids for the plot
245
  auto ids = get_map<IdData>();
312✔
246

247
  // assign colors
248
  for (size_t y = 0; y < height; y++) {
49,176✔
249
    for (size_t x = 0; x < width; x++) {
11,216,808✔
250
      int idx = color_by_ == PlotColorBy::cells ? 0 : 2;
11,167,944✔
251
      auto id = ids.data_(y, x, idx);
11,167,944✔
252
      // no setting needed if not found
253
      if (id == NOT_FOUND) {
11,167,944✔
254
        continue;
1,800,552✔
255
      }
256
      if (id == OVERLAP) {
9,398,208✔
257
        data(x, y) = overlap_color_;
30,816✔
258
        continue;
30,816✔
259
      }
260
      if (PlotColorBy::cells == color_by_) {
9,367,392✔
261
        data(x, y) = colors_[model::cell_map[id]];
5,549,712✔
262
      } else if (PlotColorBy::mats == color_by_) {
3,817,680✔
263
        if (id == MATERIAL_VOID) {
3,817,680✔
264
          data(x, y) = WHITE;
×
265
          continue;
×
266
        }
267
        data(x, y) = colors_[model::material_map[id]];
3,817,680✔
268
      } // color_by if-else
269
    }
270
  }
271

272
  // draw mesh lines if present
273
  if (index_meshlines_mesh_ >= 0) {
312✔
274
    draw_mesh_lines(data);
36✔
275
  }
276

277
// create image file
278
#ifdef USE_LIBPNG
279
  output_png(path_plot(), data);
312✔
280
#else
281
  output_ppm(path_plot(), data);
282
#endif
283
}
312✔
284

285
void PlottableInterface::set_id(pugi::xml_node plot_node)
976✔
286
{
287
  // Copy data into plots
288
  if (check_for_node(plot_node, "id")) {
976✔
289
    id_ = std::stoi(get_node_value(plot_node, "id"));
976✔
290
  } else {
291
    fatal_error("Must specify plot id in plots XML file.");
×
292
  }
293

294
  // Check to make sure 'id' hasn't been used
295
  if (model::plot_map.find(id_) != model::plot_map.end()) {
976✔
296
    fatal_error(
×
297
      fmt::format("Two or more plots use the same unique ID: {}", id_));
×
298
  }
299
}
976✔
300

301
// Checks if png or ppm is already present
302
bool file_extension_present(
966✔
303
  const std::string& filename, const std::string& extension)
304
{
305
  std::string file_extension_if_present =
306
    filename.substr(filename.find_last_of(".") + 1);
966✔
307
  if (file_extension_if_present == extension)
966✔
308
    return true;
60✔
309
  return false;
906✔
310
}
966✔
311

312
void Plot::set_output_path(pugi::xml_node plot_node)
880✔
313
{
314
  // Set output file path
315
  std::string filename;
880✔
316

317
  if (check_for_node(plot_node, "filename")) {
880✔
318
    filename = get_node_value(plot_node, "filename");
268✔
319
  } else {
320
    filename = fmt::format("plot_{}", id());
1,224✔
321
  }
322
  const std::string dir_if_present =
323
    filename.substr(0, filename.find_last_of("/") + 1);
880✔
324
  if (dir_if_present.size() > 0 && !dir_exists(dir_if_present)) {
880✔
325
    fatal_error(fmt::format("Directory '{}' does not exist!", dir_if_present));
10✔
326
  }
327
  // add appropriate file extension to name
328
  switch (type_) {
870✔
329
  case PlotType::slice:
810✔
330
#ifdef USE_LIBPNG
331
    if (!file_extension_present(filename, "png"))
810✔
332
      filename.append(".png");
810✔
333
#else
334
    if (!file_extension_present(filename, "ppm"))
335
      filename.append(".ppm");
336
#endif
337
    break;
810✔
338
  case PlotType::voxel:
60✔
339
    if (!file_extension_present(filename, "h5"))
60✔
340
      filename.append(".h5");
60✔
341
    break;
60✔
342
  }
343

344
  path_plot_ = filename;
870✔
345

346
  // Copy plot pixel size
347
  vector<int> pxls = get_node_array<int>(plot_node, "pixels");
1,740✔
348
  if (PlotType::slice == type_) {
870✔
349
    if (pxls.size() == 2) {
810✔
350
      pixels_[0] = pxls[0];
810✔
351
      pixels_[1] = pxls[1];
810✔
352
    } else {
353
      fatal_error(
×
354
        fmt::format("<pixels> must be length 2 in slice plot {}", id()));
×
355
    }
356
  } else if (PlotType::voxel == type_) {
60✔
357
    if (pxls.size() == 3) {
60✔
358
      pixels_[0] = pxls[0];
60✔
359
      pixels_[1] = pxls[1];
60✔
360
      pixels_[2] = pxls[2];
60✔
361
    } else {
362
      fatal_error(
×
363
        fmt::format("<pixels> must be length 3 in voxel plot {}", id()));
×
364
    }
365
  }
366
}
870✔
367

368
void PlottableInterface::set_bg_color(pugi::xml_node plot_node)
976✔
369
{
370
  // Copy plot background color
371
  if (check_for_node(plot_node, "background")) {
976✔
372
    vector<int> bg_rgb = get_node_array<int>(plot_node, "background");
48✔
373
    if (bg_rgb.size() == 3) {
48✔
374
      not_found_ = bg_rgb;
48✔
375
    } else {
376
      fatal_error(fmt::format("Bad background RGB in plot {}", id()));
×
377
    }
378
  }
48✔
379
}
976✔
380

381
void Plot::set_basis(pugi::xml_node plot_node)
870✔
382
{
383
  // Copy plot basis
384
  if (PlotType::slice == type_) {
870✔
385
    std::string pl_basis = "xy";
810✔
386
    if (check_for_node(plot_node, "basis")) {
810✔
387
      pl_basis = get_node_value(plot_node, "basis", true);
810✔
388
    }
389
    if ("xy" == pl_basis) {
810✔
390
      basis_ = PlotBasis::xy;
656✔
391
    } else if ("xz" == pl_basis) {
154✔
392
      basis_ = PlotBasis::xz;
60✔
393
    } else if ("yz" == pl_basis) {
94✔
394
      basis_ = PlotBasis::yz;
94✔
395
    } else {
396
      fatal_error(
×
397
        fmt::format("Unsupported plot basis '{}' in plot {}", pl_basis, id()));
×
398
    }
399
  }
810✔
400
}
870✔
401

402
void Plot::set_origin(pugi::xml_node plot_node)
870✔
403
{
404
  // Copy plotting origin
405
  auto pl_origin = get_node_array<double>(plot_node, "origin");
870✔
406
  if (pl_origin.size() == 3) {
870✔
407
    origin_ = pl_origin;
870✔
408
  } else {
409
    fatal_error(fmt::format("Origin must be length 3 in plot {}", id()));
×
410
  }
411
}
870✔
412

413
void Plot::set_width(pugi::xml_node plot_node)
870✔
414
{
415
  // Copy plotting width
416
  vector<double> pl_width = get_node_array<double>(plot_node, "width");
870✔
417
  if (PlotType::slice == type_) {
870✔
418
    if (pl_width.size() == 2) {
810✔
419
      width_.x = pl_width[0];
810✔
420
      width_.y = pl_width[1];
810✔
421
    } else {
422
      fatal_error(
×
423
        fmt::format("<width> must be length 2 in slice plot {}", id()));
×
424
    }
425
  } else if (PlotType::voxel == type_) {
60✔
426
    if (pl_width.size() == 3) {
60✔
427
      pl_width = get_node_array<double>(plot_node, "width");
60✔
428
      width_ = pl_width;
60✔
429
    } else {
430
      fatal_error(
×
431
        fmt::format("<width> must be length 3 in voxel plot {}", id()));
×
432
    }
433
  }
434
}
870✔
435

436
void PlottableInterface::set_universe(pugi::xml_node plot_node)
976✔
437
{
438
  // Copy plot universe level
439
  if (check_for_node(plot_node, "level")) {
976✔
440
    level_ = std::stoi(get_node_value(plot_node, "level"));
×
441
    if (level_ < 0) {
×
442
      fatal_error(fmt::format("Bad universe level in plot {}", id()));
×
443
    }
444
  } else {
445
    level_ = PLOT_LEVEL_LOWEST;
976✔
446
  }
447
}
976✔
448

449
void PlottableInterface::set_default_colors(pugi::xml_node plot_node)
976✔
450
{
451
  // Copy plot color type and initialize all colors randomly
452
  std::string pl_color_by = "cell";
976✔
453
  if (check_for_node(plot_node, "color_by")) {
976✔
454
    pl_color_by = get_node_value(plot_node, "color_by", true);
940✔
455
  }
456
  if ("cell" == pl_color_by) {
976✔
457
    color_by_ = PlotColorBy::cells;
435✔
458
    colors_.resize(model::cells.size());
435✔
459
  } else if ("material" == pl_color_by) {
541✔
460
    color_by_ = PlotColorBy::mats;
541✔
461
    colors_.resize(model::materials.size());
541✔
462
  } else {
463
    fatal_error(fmt::format(
×
464
      "Unsupported plot color type '{}' in plot {}", pl_color_by, id()));
×
465
  }
466

467
  for (auto& c : colors_) {
4,195✔
468
    c = random_color();
3,219✔
469
    // make sure we don't interfere with some default colors
470
    while (c == RED || c == WHITE) {
3,219✔
471
      c = random_color();
×
472
    }
473
  }
474
}
976✔
475

476
void PlottableInterface::set_user_colors(pugi::xml_node plot_node)
976✔
477
{
478
  for (auto cn : plot_node.children("color")) {
1,324✔
479
    // Make sure 3 values are specified for RGB
480
    vector<int> user_rgb = get_node_array<int>(cn, "rgb");
348✔
481
    if (user_rgb.size() != 3) {
348✔
482
      fatal_error(fmt::format("Bad RGB in plot {}", id()));
×
483
    }
484
    // Ensure that there is an id for this color specification
485
    int col_id;
486
    if (check_for_node(cn, "id")) {
348✔
487
      col_id = std::stoi(get_node_value(cn, "id"));
348✔
488
    } else {
489
      fatal_error(fmt::format(
×
490
        "Must specify id for color specification in plot {}", id()));
×
491
    }
492
    // Add RGB
493
    if (PlotColorBy::cells == color_by_) {
348✔
494
      if (model::cell_map.find(col_id) != model::cell_map.end()) {
132✔
495
        col_id = model::cell_map[col_id];
96✔
496
        colors_[col_id] = user_rgb;
96✔
497
      } else {
498
        warning(fmt::format(
36✔
499
          "Could not find cell {} specified in plot {}", col_id, id()));
72✔
500
      }
501
    } else if (PlotColorBy::mats == color_by_) {
216✔
502
      if (model::material_map.find(col_id) != model::material_map.end()) {
216✔
503
        col_id = model::material_map[col_id];
216✔
504
        colors_[col_id] = user_rgb;
216✔
505
      } else {
506
        warning(fmt::format(
×
507
          "Could not find material {} specified in plot {}", col_id, id()));
×
508
      }
509
    }
510
  } // color node loop
348✔
511
}
976✔
512

513
void Plot::set_meshlines(pugi::xml_node plot_node)
870✔
514
{
515
  // Deal with meshlines
516
  pugi::xpath_node_set mesh_line_nodes = plot_node.select_nodes("meshlines");
870✔
517

518
  if (!mesh_line_nodes.empty()) {
870✔
519
    if (PlotType::voxel == type_) {
36✔
520
      warning(fmt::format("Meshlines ignored in voxel plot {}", id()));
×
521
    }
522

523
    if (mesh_line_nodes.size() == 1) {
36✔
524
      // Get first meshline node
525
      pugi::xml_node meshlines_node = mesh_line_nodes[0].node();
36✔
526

527
      // Check mesh type
528
      std::string meshtype;
36✔
529
      if (check_for_node(meshlines_node, "meshtype")) {
36✔
530
        meshtype = get_node_value(meshlines_node, "meshtype");
36✔
531
      } else {
532
        fatal_error(fmt::format(
×
533
          "Must specify a meshtype for meshlines specification in plot {}",
534
          id()));
×
535
      }
536

537
      // Ensure that there is a linewidth for this meshlines specification
538
      std::string meshline_width;
36✔
539
      if (check_for_node(meshlines_node, "linewidth")) {
36✔
540
        meshline_width = get_node_value(meshlines_node, "linewidth");
36✔
541
        meshlines_width_ = std::stoi(meshline_width);
36✔
542
      } else {
543
        fatal_error(fmt::format(
×
544
          "Must specify a linewidth for meshlines specification in plot {}",
545
          id()));
×
546
      }
547

548
      // Check for color
549
      if (check_for_node(meshlines_node, "color")) {
36✔
550
        // Check and make sure 3 values are specified for RGB
551
        vector<int> ml_rgb = get_node_array<int>(meshlines_node, "color");
×
552
        if (ml_rgb.size() != 3) {
×
553
          fatal_error(
×
554
            fmt::format("Bad RGB for meshlines color in plot {}", id()));
×
555
        }
556
        meshlines_color_ = ml_rgb;
×
557
      }
558

559
      // Set mesh based on type
560
      if ("ufs" == meshtype) {
36✔
561
        if (!simulation::ufs_mesh) {
×
562
          fatal_error(
×
563
            fmt::format("No UFS mesh for meshlines on plot {}", id()));
×
564
        } else {
565
          for (int i = 0; i < model::meshes.size(); ++i) {
×
566
            if (const auto* m =
×
567
                  dynamic_cast<const RegularMesh*>(model::meshes[i].get())) {
×
568
              if (m == simulation::ufs_mesh) {
×
569
                index_meshlines_mesh_ = i;
×
570
              }
571
            }
572
          }
573
          if (index_meshlines_mesh_ == -1)
×
574
            fatal_error("Could not find the UFS mesh for meshlines plot");
×
575
        }
576
      } else if ("entropy" == meshtype) {
36✔
577
        if (!simulation::entropy_mesh) {
24✔
578
          fatal_error(
×
579
            fmt::format("No entropy mesh for meshlines on plot {}", id()));
×
580
        } else {
581
          for (int i = 0; i < model::meshes.size(); ++i) {
60✔
582
            if (const auto* m =
36✔
583
                  dynamic_cast<const RegularMesh*>(model::meshes[i].get())) {
36✔
584
              if (m == simulation::entropy_mesh) {
24✔
585
                index_meshlines_mesh_ = i;
24✔
586
              }
587
            }
588
          }
589
          if (index_meshlines_mesh_ == -1)
24✔
590
            fatal_error("Could not find the entropy mesh for meshlines plot");
×
591
        }
592
      } else if ("tally" == meshtype) {
12✔
593
        // Ensure that there is a mesh id if the type is tally
594
        int tally_mesh_id;
595
        if (check_for_node(meshlines_node, "id")) {
12✔
596
          tally_mesh_id = std::stoi(get_node_value(meshlines_node, "id"));
12✔
597
        } else {
598
          std::stringstream err_msg;
×
599
          fatal_error(fmt::format("Must specify a mesh id for meshlines tally "
×
600
                                  "mesh specification in plot {}",
601
            id()));
×
602
        }
×
603
        // find the tally index
604
        int idx;
605
        int err = openmc_get_mesh_index(tally_mesh_id, &idx);
12✔
606
        if (err != 0) {
12✔
607
          fatal_error(fmt::format("Could not find mesh {} specified in "
×
608
                                  "meshlines for plot {}",
609
            tally_mesh_id, id()));
×
610
        }
611
        index_meshlines_mesh_ = idx;
12✔
612
      } else {
613
        fatal_error(fmt::format("Invalid type for meshlines on plot {}", id()));
×
614
      }
615
    } else {
36✔
616
      fatal_error(fmt::format("Mutliple meshlines specified in plot {}", id()));
×
617
    }
618
  }
619
}
870✔
620

621
void PlottableInterface::set_mask(pugi::xml_node plot_node)
976✔
622
{
623
  // Deal with masks
624
  pugi::xpath_node_set mask_nodes = plot_node.select_nodes("mask");
976✔
625

626
  if (!mask_nodes.empty()) {
976✔
627
    if (mask_nodes.size() == 1) {
36✔
628
      // Get pointer to mask
629
      pugi::xml_node mask_node = mask_nodes[0].node();
36✔
630

631
      // Determine how many components there are and allocate
632
      vector<int> iarray = get_node_array<int>(mask_node, "components");
36✔
633
      if (iarray.size() == 0) {
36✔
634
        fatal_error(
×
635
          fmt::format("Missing <components> in mask of plot {}", id()));
×
636
      }
637

638
      // First we need to change the user-specified identifiers to indices
639
      // in the cell and material arrays
640
      for (auto& col_id : iarray) {
108✔
641
        if (PlotColorBy::cells == color_by_) {
72✔
642
          if (model::cell_map.find(col_id) != model::cell_map.end()) {
72✔
643
            col_id = model::cell_map[col_id];
72✔
644
          } else {
645
            fatal_error(fmt::format("Could not find cell {} specified in the "
×
646
                                    "mask in plot {}",
647
              col_id, id()));
×
648
          }
649
        } else if (PlotColorBy::mats == color_by_) {
×
650
          if (model::material_map.find(col_id) != model::material_map.end()) {
×
651
            col_id = model::material_map[col_id];
×
652
          } else {
653
            fatal_error(fmt::format("Could not find material {} specified in "
×
654
                                    "the mask in plot {}",
655
              col_id, id()));
×
656
          }
657
        }
658
      }
659

660
      // Alter colors based on mask information
661
      for (int j = 0; j < colors_.size(); j++) {
144✔
662
        if (contains(iarray, j)) {
108✔
663
          if (check_for_node(mask_node, "background")) {
72✔
664
            vector<int> bg_rgb = get_node_array<int>(mask_node, "background");
72✔
665
            colors_[j] = bg_rgb;
72✔
666
          } else {
72✔
667
            colors_[j] = WHITE;
×
668
          }
669
        }
670
      }
671

672
    } else {
36✔
673
      fatal_error(fmt::format("Mutliple masks specified in plot {}", id()));
×
674
    }
675
  }
676
}
976✔
677

678
void PlottableInterface::set_overlap_color(pugi::xml_node plot_node)
976✔
679
{
680
  color_overlaps_ = false;
976✔
681
  if (check_for_node(plot_node, "show_overlaps")) {
976✔
682
    color_overlaps_ = get_node_value_bool(plot_node, "show_overlaps");
24✔
683
    // check for custom overlap color
684
    if (check_for_node(plot_node, "overlap_color")) {
24✔
685
      if (!color_overlaps_) {
12✔
686
        warning(fmt::format(
×
687
          "Overlap color specified in plot {} but overlaps won't be shown.",
688
          id()));
×
689
      }
690
      vector<int> olap_clr = get_node_array<int>(plot_node, "overlap_color");
12✔
691
      if (olap_clr.size() == 3) {
12✔
692
        overlap_color_ = olap_clr;
12✔
693
      } else {
694
        fatal_error(fmt::format("Bad overlap RGB in plot {}", id()));
×
695
      }
696
    }
12✔
697
  }
698

699
  // make sure we allocate the vector for counting overlap checks if
700
  // they're going to be plotted
701
  if (color_overlaps_ && settings::run_mode == RunMode::PLOTTING) {
976✔
702
    settings::check_overlaps = true;
24✔
703
    model::overlap_check_count.resize(model::cells.size(), 0);
24✔
704
  }
705
}
976✔
706

707
PlottableInterface::PlottableInterface(pugi::xml_node plot_node)
976✔
708
{
709
  set_id(plot_node);
976✔
710
  set_bg_color(plot_node);
976✔
711
  set_universe(plot_node);
976✔
712
  set_default_colors(plot_node);
976✔
713
  set_user_colors(plot_node);
976✔
714
  set_mask(plot_node);
976✔
715
  set_overlap_color(plot_node);
976✔
716
}
976✔
717

718
Plot::Plot(pugi::xml_node plot_node, PlotType type)
880✔
719
  : PlottableInterface(plot_node), type_(type), index_meshlines_mesh_ {-1}
880✔
720
{
721
  set_output_path(plot_node);
880✔
722
  set_basis(plot_node);
870✔
723
  set_origin(plot_node);
870✔
724
  set_width(plot_node);
870✔
725
  set_meshlines(plot_node);
870✔
726
  slice_level_ = level_; // Copy level employed in SlicePlotBase::get_map
870✔
727
  slice_color_overlaps_ = color_overlaps_;
870✔
728
}
870✔
729

730
//==============================================================================
731
// OUTPUT_PPM writes out a previously generated image to a PPM file
732
//==============================================================================
733

734
void output_ppm(const std::string& filename, const ImageData& data)
×
735
{
736
  // Open PPM file for writing
737
  std::string fname = filename;
×
738
  fname = strtrim(fname);
×
739
  std::ofstream of;
×
740

741
  of.open(fname);
×
742

743
  // Write header
744
  of << "P6\n";
×
745
  of << data.shape()[0] << " " << data.shape()[1] << "\n";
×
746
  of << "255\n";
×
747
  of.close();
×
748

749
  of.open(fname, std::ios::binary | std::ios::app);
×
750
  // Write color for each pixel
751
  for (int y = 0; y < data.shape()[1]; y++) {
×
752
    for (int x = 0; x < data.shape()[0]; x++) {
×
753
      RGBColor rgb = data(x, y);
×
754
      of << rgb.red << rgb.green << rgb.blue;
×
755
    }
756
  }
757
  of << "\n";
×
758
}
759

760
//==============================================================================
761
// OUTPUT_PNG writes out a previously generated image to a PNG file
762
//==============================================================================
763

764
#ifdef USE_LIBPNG
765
void output_png(const std::string& filename, const ImageData& data)
408✔
766
{
767
  // Open PNG file for writing
768
  std::string fname = filename;
408✔
769
  fname = strtrim(fname);
408✔
770
  auto fp = std::fopen(fname.c_str(), "wb");
408✔
771

772
  // Initialize write and info structures
773
  auto png_ptr =
774
    png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);
408✔
775
  auto info_ptr = png_create_info_struct(png_ptr);
408✔
776

777
  // Setup exception handling
778
  if (setjmp(png_jmpbuf(png_ptr)))
408✔
779
    fatal_error("Error during png creation");
×
780

781
  png_init_io(png_ptr, fp);
408✔
782

783
  // Write header (8 bit colour depth)
784
  int width = data.shape()[0];
408✔
785
  int height = data.shape()[1];
408✔
786
  png_set_IHDR(png_ptr, info_ptr, width, height, 8, PNG_COLOR_TYPE_RGB,
408✔
787
    PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
788
  png_write_info(png_ptr, info_ptr);
408✔
789

790
  // Allocate memory for one row (3 bytes per pixel - RGB)
791
  std::vector<png_byte> row(3 * width);
408✔
792

793
  // Write color for each pixel
794
  for (int y = 0; y < height; y++) {
68,472✔
795
    for (int x = 0; x < width; x++) {
15,076,008✔
796
      RGBColor rgb = data(x, y);
15,007,944✔
797
      row[3 * x] = rgb.red;
15,007,944✔
798
      row[3 * x + 1] = rgb.green;
15,007,944✔
799
      row[3 * x + 2] = rgb.blue;
15,007,944✔
800
    }
801
    png_write_row(png_ptr, row.data());
68,064✔
802
  }
803

804
  // End write
805
  png_write_end(png_ptr, nullptr);
408✔
806

807
  // Clean up data structures
808
  std::fclose(fp);
408✔
809
  png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
408✔
810
  png_destroy_write_struct(&png_ptr, &info_ptr);
408✔
811
}
408✔
812
#endif
813

814
//==============================================================================
815
// DRAW_MESH_LINES draws mesh line boundaries on an image
816
//==============================================================================
817

818
void Plot::draw_mesh_lines(ImageData& data) const
36✔
819
{
820
  RGBColor rgb;
36✔
821
  rgb = meshlines_color_;
36✔
822

823
  int ax1, ax2;
824
  switch (basis_) {
36✔
825
  case PlotBasis::xy:
24✔
826
    ax1 = 0;
24✔
827
    ax2 = 1;
24✔
828
    break;
24✔
829
  case PlotBasis::xz:
12✔
830
    ax1 = 0;
12✔
831
    ax2 = 2;
12✔
832
    break;
12✔
833
  case PlotBasis::yz:
×
834
    ax1 = 1;
×
835
    ax2 = 2;
×
836
    break;
×
837
  default:
×
838
    UNREACHABLE();
×
839
  }
840

841
  Position ll_plot {origin_};
36✔
842
  Position ur_plot {origin_};
36✔
843

844
  ll_plot[ax1] -= width_[0] / 2.;
36✔
845
  ll_plot[ax2] -= width_[1] / 2.;
36✔
846
  ur_plot[ax1] += width_[0] / 2.;
36✔
847
  ur_plot[ax2] += width_[1] / 2.;
36✔
848

849
  Position width = ur_plot - ll_plot;
36✔
850

851
  // Find the (axis-aligned) lines of the mesh that intersect this plot.
852
  auto axis_lines =
853
    model::meshes[index_meshlines_mesh_]->plot(ll_plot, ur_plot);
36✔
854

855
  // Find the bounds along the second axis (accounting for low-D meshes).
856
  int ax2_min, ax2_max;
857
  if (axis_lines.second.size() > 0) {
36✔
858
    double frac = (axis_lines.second.back() - ll_plot[ax2]) / width[ax2];
36✔
859
    ax2_min = (1.0 - frac) * pixels_[1];
36✔
860
    if (ax2_min < 0)
36✔
861
      ax2_min = 0;
×
862
    frac = (axis_lines.second.front() - ll_plot[ax2]) / width[ax2];
36✔
863
    ax2_max = (1.0 - frac) * pixels_[1];
36✔
864
    if (ax2_max > pixels_[1])
36✔
865
      ax2_max = pixels_[1];
×
866
  } else {
867
    ax2_min = 0;
×
868
    ax2_max = pixels_[1];
×
869
  }
870

871
  // Iterate across the first axis and draw lines.
872
  for (auto ax1_val : axis_lines.first) {
204✔
873
    double frac = (ax1_val - ll_plot[ax1]) / width[ax1];
168✔
874
    int ax1_ind = frac * pixels_[0];
168✔
875
    for (int ax2_ind = ax2_min; ax2_ind < ax2_max; ++ax2_ind) {
27,216✔
876
      for (int plus = 0; plus <= meshlines_width_; plus++) {
54,096✔
877
        if (ax1_ind + plus >= 0 && ax1_ind + plus < pixels_[0])
27,048✔
878
          data(ax1_ind + plus, ax2_ind) = rgb;
27,048✔
879
        if (ax1_ind - plus >= 0 && ax1_ind - plus < pixels_[0])
27,048✔
880
          data(ax1_ind - plus, ax2_ind) = rgb;
27,048✔
881
      }
882
    }
883
  }
884

885
  // Find the bounds along the first axis.
886
  int ax1_min, ax1_max;
887
  if (axis_lines.first.size() > 0) {
36✔
888
    double frac = (axis_lines.first.front() - ll_plot[ax1]) / width[ax1];
36✔
889
    ax1_min = frac * pixels_[0];
36✔
890
    if (ax1_min < 0)
36✔
891
      ax1_min = 0;
×
892
    frac = (axis_lines.first.back() - ll_plot[ax1]) / width[ax1];
36✔
893
    ax1_max = frac * pixels_[0];
36✔
894
    if (ax1_max > pixels_[0])
36✔
895
      ax1_max = pixels_[0];
×
896
  } else {
897
    ax1_min = 0;
×
898
    ax1_max = pixels_[0];
×
899
  }
900

901
  // Iterate across the second axis and draw lines.
902
  for (auto ax2_val : axis_lines.second) {
228✔
903
    double frac = (ax2_val - ll_plot[ax2]) / width[ax2];
192✔
904
    int ax2_ind = (1.0 - frac) * pixels_[1];
192✔
905
    for (int ax1_ind = ax1_min; ax1_ind < ax1_max; ++ax1_ind) {
30,912✔
906
      for (int plus = 0; plus <= meshlines_width_; plus++) {
61,440✔
907
        if (ax2_ind + plus >= 0 && ax2_ind + plus < pixels_[1])
30,720✔
908
          data(ax1_ind, ax2_ind + plus) = rgb;
30,720✔
909
        if (ax2_ind - plus >= 0 && ax2_ind - plus < pixels_[1])
30,720✔
910
          data(ax1_ind, ax2_ind - plus) = rgb;
30,720✔
911
      }
912
    }
913
  }
914
}
36✔
915

916
/* outputs a binary file that can be input into silomesh for 3D geometry
917
 * visualization.  It works the same way as create_image by dragging a particle
918
 * across the geometry for the specified number of voxels. The first 3 int's in
919
 * the binary are the number of x, y, and z voxels.  The next 3 double's are
920
 * the widths of the voxels in the x, y, and z directions. The next 3 double's
921
 * are the x, y, and z coordinates of the lower left point. Finally the binary
922
 * is filled with entries of four int's each. Each 'row' in the binary contains
923
 * four int's: 3 for x,y,z position and 1 for cell or material id.  For 1
924
 * million voxels this produces a file of approximately 15MB.
925
 */
926
void Plot::create_voxel() const
60✔
927
{
928
  // compute voxel widths in each direction
929
  array<double, 3> vox;
930
  vox[0] = width_[0] / static_cast<double>(pixels_[0]);
60✔
931
  vox[1] = width_[1] / static_cast<double>(pixels_[1]);
60✔
932
  vox[2] = width_[2] / static_cast<double>(pixels_[2]);
60✔
933

934
  // initial particle position
935
  Position ll = origin_ - width_ / 2.;
60✔
936

937
  // Open binary plot file for writing
938
  std::ofstream of;
60✔
939
  std::string fname = std::string(path_plot_);
60✔
940
  fname = strtrim(fname);
60✔
941
  hid_t file_id = file_open(fname, 'w');
60✔
942

943
  // write header info
944
  write_attribute(file_id, "filetype", "voxel");
60✔
945
  write_attribute(file_id, "version", VERSION_VOXEL);
60✔
946
  write_attribute(file_id, "openmc_version", VERSION);
60✔
947

948
#ifdef GIT_SHA1
949
  write_attribute(file_id, "git_sha1", GIT_SHA1);
60✔
950
#endif
951

952
  // Write current date and time
953
  write_attribute(file_id, "date_and_time", time_stamp().c_str());
60✔
954
  array<int, 3> pixels;
955
  std::copy(pixels_.begin(), pixels_.end(), pixels.begin());
60✔
956
  write_attribute(file_id, "num_voxels", pixels);
60✔
957
  write_attribute(file_id, "voxel_width", vox);
60✔
958
  write_attribute(file_id, "lower_left", ll);
60✔
959

960
  // Create dataset for voxel data -- note that the dimensions are reversed
961
  // since we want the order in the file to be z, y, x
962
  hsize_t dims[3];
963
  dims[0] = pixels_[2];
60✔
964
  dims[1] = pixels_[1];
60✔
965
  dims[2] = pixels_[0];
60✔
966
  hid_t dspace, dset, memspace;
967
  voxel_init(file_id, &(dims[0]), &dspace, &dset, &memspace);
60✔
968

969
  SlicePlotBase pltbase;
60✔
970
  pltbase.width_ = width_;
60✔
971
  pltbase.origin_ = origin_;
60✔
972
  pltbase.basis_ = PlotBasis::xy;
60✔
973
  pltbase.pixels_ = pixels_;
60✔
974
  pltbase.slice_color_overlaps_ = color_overlaps_;
60✔
975

976
  ProgressBar pb;
60✔
977
  for (int z = 0; z < pixels_[2]; z++) {
5,220✔
978
    // update z coordinate
979
    pltbase.origin_.z = ll.z + z * vox[2];
5,160✔
980

981
    // generate ids using plotbase
982
    IdData ids = pltbase.get_map<IdData>();
5,160✔
983

984
    // select only cell/material ID data and flip the y-axis
985
    int idx = color_by_ == PlotColorBy::cells ? 0 : 2;
5,160✔
986
    xt::xtensor<int32_t, 2> data_slice =
987
      xt::view(ids.data_, xt::all(), xt::all(), idx);
5,160✔
988
    xt::xtensor<int32_t, 2> data_flipped = xt::flip(data_slice, 0);
5,160✔
989

990
    // Write to HDF5 dataset
991
    voxel_write_slice(z, dspace, dset, memspace, data_flipped.data());
5,160✔
992

993
    // update progress bar
994
    pb.set_value(
5,160✔
995
      100. * static_cast<double>(z + 1) / static_cast<double>((pixels_[2])));
5,160✔
996
  }
5,160✔
997

998
  voxel_finalize(dspace, dset, memspace);
60✔
999
  file_close(file_id);
60✔
1000
}
60✔
1001

1002
void voxel_init(hid_t file_id, const hsize_t* dims, hid_t* dspace, hid_t* dset,
60✔
1003
  hid_t* memspace)
1004
{
1005
  // Create dataspace/dataset for voxel data
1006
  *dspace = H5Screate_simple(3, dims, nullptr);
60✔
1007
  *dset = H5Dcreate(file_id, "data", H5T_NATIVE_INT, *dspace, H5P_DEFAULT,
60✔
1008
    H5P_DEFAULT, H5P_DEFAULT);
1009

1010
  // Create dataspace for a slice of the voxel
1011
  hsize_t dims_slice[2] {dims[1], dims[2]};
60✔
1012
  *memspace = H5Screate_simple(2, dims_slice, nullptr);
60✔
1013

1014
  // Select hyperslab in dataspace
1015
  hsize_t start[3] {0, 0, 0};
60✔
1016
  hsize_t count[3] {1, dims[1], dims[2]};
60✔
1017
  H5Sselect_hyperslab(*dspace, H5S_SELECT_SET, start, nullptr, count, nullptr);
60✔
1018
}
60✔
1019

1020
void voxel_write_slice(
5,160✔
1021
  int x, hid_t dspace, hid_t dset, hid_t memspace, void* buf)
1022
{
1023
  hssize_t offset[3] {x, 0, 0};
5,160✔
1024
  H5Soffset_simple(dspace, offset);
5,160✔
1025
  H5Dwrite(dset, H5T_NATIVE_INT, memspace, dspace, H5P_DEFAULT, buf);
5,160✔
1026
}
5,160✔
1027

1028
void voxel_finalize(hid_t dspace, hid_t dset, hid_t memspace)
60✔
1029
{
1030
  H5Dclose(dset);
60✔
1031
  H5Sclose(dspace);
60✔
1032
  H5Sclose(memspace);
60✔
1033
}
60✔
1034

1035
RGBColor random_color(void)
3,219✔
1036
{
1037
  return {int(prn(&model::plotter_seed) * 255),
3,219✔
1038
    int(prn(&model::plotter_seed) * 255), int(prn(&model::plotter_seed) * 255)};
3,219✔
1039
}
1040

1041
RayTracePlot::RayTracePlot(pugi::xml_node node) : PlottableInterface(node)
96✔
1042
{
1043
  set_look_at(node);
96✔
1044
  set_camera_position(node);
96✔
1045
  set_field_of_view(node);
96✔
1046
  set_pixels(node);
96✔
1047
  set_orthographic_width(node);
96✔
1048
  set_output_path(node);
96✔
1049

1050
  if (check_for_node(node, "orthographic_width") &&
108✔
1051
      check_for_node(node, "field_of_view"))
12✔
1052
    fatal_error("orthographic_width and field_of_view are mutually exclusive "
×
1053
                "parameters.");
1054

1055
  // Get centerline vector for camera-to-model. We create vectors around this
1056
  // that form a pixel array, and then trace rays along that.
1057
  auto up = up_ / up_.norm();
96✔
1058
  Direction looking_direction = look_at_ - camera_position_;
96✔
1059
  looking_direction /= looking_direction.norm();
96✔
1060
  if (std::abs(std::abs(looking_direction.dot(up)) - 1.0) < 1e-9)
96✔
NEW
1061
    fatal_error("Up vector cannot align with vector between camera position "
×
1062
                "and look_at!");
1063
  Direction cam_yaxis = looking_direction.cross(up);
96✔
1064
  cam_yaxis /= cam_yaxis.norm();
96✔
1065
  Direction cam_zaxis = cam_yaxis.cross(looking_direction);
96✔
1066
  cam_zaxis /= cam_zaxis.norm();
96✔
1067

1068
  // Cache the camera-to-model matrix
1069
  camera_to_model_ = {looking_direction.x, cam_yaxis.x, cam_zaxis.x,
96✔
1070
    looking_direction.y, cam_yaxis.y, cam_zaxis.y, looking_direction.z,
96✔
1071
    cam_yaxis.z, cam_zaxis.z};
96✔
1072
}
96✔
1073

1074
ProjectionPlot::ProjectionPlot(pugi::xml_node node) : RayTracePlot(node)
60✔
1075
{
1076
  set_opacities(node);
60✔
1077
  set_wireframe_thickness(node);
60✔
1078
  set_wireframe_ids(node);
60✔
1079
  set_wireframe_color(node);
60✔
1080
}
60✔
1081

1082
void ProjectionPlot::set_wireframe_color(pugi::xml_node plot_node)
60✔
1083
{
1084
  // Copy plot background color
1085
  if (check_for_node(plot_node, "wireframe_color")) {
60✔
1086
    vector<int> w_rgb = get_node_array<int>(plot_node, "wireframe_color");
×
1087
    if (w_rgb.size() == 3) {
×
1088
      wireframe_color_ = w_rgb;
×
1089
    } else {
1090
      fatal_error(fmt::format("Bad wireframe RGB in plot {}", id()));
×
1091
    }
1092
  }
1093
}
60✔
1094

1095
void RayTracePlot::set_output_path(pugi::xml_node node)
96✔
1096
{
1097
  // Set output file path
1098
  std::string filename;
96✔
1099

1100
  if (check_for_node(node, "filename")) {
96✔
1101
    filename = get_node_value(node, "filename");
84✔
1102
  } else {
1103
    filename = fmt::format("plot_{}", id());
24✔
1104
  }
1105

1106
#ifdef USE_LIBPNG
1107
  if (!file_extension_present(filename, "png"))
96✔
1108
    filename.append(".png");
36✔
1109
#else
1110
  if (!file_extension_present(filename, "ppm"))
1111
    filename.append(".ppm");
1112
#endif
1113
  path_plot_ = filename;
96✔
1114
}
96✔
1115

1116
bool ProjectionPlot::trackstack_equivalent(
3,226,476✔
1117
  const std::vector<TrackSegment>& track1,
1118
  const std::vector<TrackSegment>& track2) const
1119
{
1120
  if (wireframe_ids_.empty()) {
3,226,476✔
1121
    // Draw wireframe for all surfaces/cells/materials
1122
    if (track1.size() != track2.size())
2,685,288✔
1123
      return false;
57,264✔
1124
    for (int i = 0; i < track1.size(); ++i) {
6,467,856✔
1125
      if (track1[i].id != track2[i].id ||
7,723,080✔
1126
          track1[i].surface_index != track2[i].surface_index) {
3,861,468✔
1127
        return false;
21,780✔
1128
      }
1129
    }
1130
    return true;
2,606,244✔
1131
  } else {
1132
    // This runs in O(nm) where n is the intersection stack size
1133
    // and m is the number of IDs we are wireframing. A simpler
1134
    // algorithm can likely be found.
1135
    for (const int id : wireframe_ids_) {
1,075,848✔
1136
      int t1_i = 0;
541,188✔
1137
      int t2_i = 0;
541,188✔
1138

1139
      // Advance to first instance of the ID
1140
      while (t1_i < track1.size() && t2_i < track2.size()) {
613,560✔
1141
        while (t1_i < track1.size() && track1[t1_i].id != id)
428,544✔
1142
          t1_i++;
249,876✔
1143
        while (t2_i < track2.size() && track2[t2_i].id != id)
429,456✔
1144
          t2_i++;
250,788✔
1145

1146
        // This one is really important!
1147
        if ((t1_i == track1.size() && t2_i != track2.size()) ||
432,564✔
1148
            (t1_i != track1.size() && t2_i == track2.size()))
253,896✔
1149
          return false;
6,528✔
1150
        if (t1_i == track1.size() && t2_i == track2.size())
174,612✔
1151
          break;
99,768✔
1152
        // Check if surface different
1153
        if (track1[t1_i].surface_index != track2[t2_i].surface_index)
74,844✔
1154
          return false;
1,620✔
1155

1156
        // Pretty sure this should not be used:
1157
        // if (t2_i != track2.size() - 1 &&
1158
        //     t1_i != track1.size() - 1 &&
1159
        //     track1[t1_i+1].id != track2[t2_i+1].id) return false;
1160
        if (t2_i != 0 && t1_i != 0 &&
132,072✔
1161
            track1[t1_i - 1].surface_index != track2[t2_i - 1].surface_index)
58,848✔
1162
          return false;
852✔
1163

1164
        // Check if neighboring cells are different
1165
        // if (track1[t1_i ? t1_i - 1 : 0].id != track2[t2_i ? t2_i - 1 : 0].id)
1166
        // return false; if (track1[t1_i < track1.size() - 1 ? t1_i + 1 : t1_i
1167
        // ].id !=
1168
        //    track2[t2_i < track2.size() - 1 ? t2_i + 1 : t2_i].id) return
1169
        //    false;
1170
        t1_i++, t2_i++;
72,372✔
1171
      }
1172
    }
1173
    return true;
534,660✔
1174
  }
1175
}
1176

1177
std::pair<Position, Direction> RayTracePlot::get_pixel_ray(
3,840,000✔
1178
  int horiz, int vert) const
1179
{
1180
  // Compute field of view in radians
1181
  constexpr double DEGREE_TO_RADIAN = M_PI / 180.0;
3,840,000✔
1182
  double horiz_fov_radians = horizontal_field_of_view_ * DEGREE_TO_RADIAN;
3,840,000✔
1183
  double p0 = static_cast<double>(pixels_[0]);
3,840,000✔
1184
  double p1 = static_cast<double>(pixels_[1]);
3,840,000✔
1185
  double vert_fov_radians = horiz_fov_radians * p1 / p0;
3,840,000✔
1186

1187
  // focal_plane_dist can be changed to alter the perspective distortion
1188
  // effect. This is in units of cm. This seems to look good most of the
1189
  // time. TODO let this variable be set through XML.
1190
  constexpr double focal_plane_dist = 10.0;
3,840,000✔
1191
  const double dx = 2.0 * focal_plane_dist * std::tan(0.5 * horiz_fov_radians);
3,840,000✔
1192
  const double dy = p1 / p0 * dx;
3,840,000✔
1193

1194
  std::pair<Position, Direction> result;
3,840,000✔
1195

1196
  // Generate the starting position/direction of the ray
1197
  if (orthographic_width_ == C_NONE) { // perspective projection
3,840,000✔
1198
    Direction camera_local_vec;
3,360,000✔
1199
    camera_local_vec.x = focal_plane_dist;
3,360,000✔
1200
    camera_local_vec.y = -0.5 * dx + horiz * dx / p0;
3,360,000✔
1201
    camera_local_vec.z = 0.5 * dy - vert * dy / p1;
3,360,000✔
1202
    camera_local_vec /= camera_local_vec.norm();
3,360,000✔
1203

1204
    result.first = camera_position_;
3,360,000✔
1205
    result.second = camera_local_vec.rotate(camera_to_model_);
3,360,000✔
1206
  } else { // orthographic projection
1207

1208
    double x_pix_coord = (static_cast<double>(horiz) - p0 / 2.0) / p0;
480,000✔
1209
    double y_pix_coord = (static_cast<double>(vert) - p1 / 2.0) / p1;
480,000✔
1210

1211
    result.first = camera_position_ +
1212
                   camera_y_axis() * x_pix_coord * orthographic_width_ +
480,000✔
1213
                   camera_z_axis() * y_pix_coord * orthographic_width_;
480,000✔
1214
    result.second = camera_x_axis();
480,000✔
1215
  }
1216

1217
  return result;
3,840,000✔
1218
}
1219

1220
void ProjectionPlot::create_output() const
60✔
1221
{
1222
  size_t width = pixels_[0];
60✔
1223
  size_t height = pixels_[1];
60✔
1224
  ImageData data({width, height}, not_found_);
60✔
1225

1226
  // This array marks where the initial wireframe was drawn.
1227
  // We convolve it with a filter that gets adjusted with the
1228
  // wireframe thickness in order to thicken the lines.
1229
  xt::xtensor<int, 2> wireframe_initial({width, height}, 0);
60✔
1230

1231
  /* Holds all of the track segments for the current rendered line of pixels.
1232
   * old_segments holds a copy of this_line_segments from the previous line.
1233
   * By holding both we can check if the cell/material intersection stack
1234
   * differs from the left or upper neighbor. This allows a robustly drawn
1235
   * wireframe. If only checking the left pixel (which requires substantially
1236
   * less memory), the wireframe tends to be spotty and be disconnected for
1237
   * surface edges oriented horizontally in the rendering.
1238
   *
1239
   * Note that a vector of vectors is required rather than a 2-tensor,
1240
   * since the stack size varies within each column.
1241
   */
1242
  const int n_threads = num_threads();
60✔
1243
  std::vector<std::vector<std::vector<TrackSegment>>> this_line_segments(
1244
    n_threads);
60✔
1245
  for (int t = 0; t < n_threads; ++t) {
150✔
1246
    this_line_segments[t].resize(pixels_[0]);
90✔
1247
  }
1248

1249
  // The last thread writes to this, and the first thread reads from it.
1250
  std::vector<std::vector<TrackSegment>> old_segments(pixels_[0]);
60✔
1251

1252
#pragma omp parallel
30✔
1253
  {
1254
    const int n_threads = num_threads();
30✔
1255
    const int tid = thread_num();
30✔
1256

1257
    int vert = tid;
30✔
1258
    for (int iter = 0; iter <= pixels_[1] / n_threads; iter++) {
6,060✔
1259

1260
      // Save bottom line of current work chunk to compare against later
1261
      // I used to have this inside the below if block, but it causes a
1262
      // spurious line to be drawn at the bottom of the image. Not sure
1263
      // why, but moving it here fixes things.
1264
      if (tid == n_threads - 1)
6,030✔
1265
        old_segments = this_line_segments[n_threads - 1];
6,030✔
1266

1267
      if (vert < pixels_[1]) {
6,030✔
1268

1269
        for (int horiz = 0; horiz < pixels_[0]; ++horiz) {
1,206,000✔
1270

1271
          // RayTracePlot implements camera ray generation
1272
          std::pair<Position, Direction> ru = get_pixel_ray(horiz, vert);
1,200,000✔
1273

1274
          this_line_segments[tid][horiz].clear();
1,200,000✔
1275
          ProjectionRay ray(
1276
            ru.first, ru.second, *this, this_line_segments[tid][horiz]);
1,200,000✔
1277

1278
          ray.trace();
1,200,000✔
1279

1280
          // Now color the pixel based on what we have intersected...
1281
          // Loops backwards over intersections.
1282
          Position current_color(
1283
            not_found_.red, not_found_.green, not_found_.blue);
1,200,000✔
1284
          const auto& segments = this_line_segments[tid][horiz];
1,200,000✔
1285

1286
          // There must be at least two cell intersections to color,
1287
          // front and back of the cell. Maybe an infinitely thick
1288
          // cell could be present with no back, but why would you
1289
          // want to color that? It's easier to just skip that edge
1290
          // case and not even color it.
1291
          if (segments.size() <= 1)
1,200,000✔
1292
            continue;
786,444✔
1293

1294
          for (int i = segments.size() - 2; i >= 0; --i) {
1,092,894✔
1295
            int colormap_idx = segments[i].id;
679,338✔
1296
            RGBColor seg_color = colors_[colormap_idx];
679,338✔
1297
            Position seg_color_vec(
1298
              seg_color.red, seg_color.green, seg_color.blue);
679,338✔
1299
            double mixing =
1300
              std::exp(-xs_[colormap_idx] *
679,338✔
1301
                       (segments[i + 1].length - segments[i].length));
679,338✔
1302
            current_color =
1303
              current_color * mixing + (1.0 - mixing) * seg_color_vec;
679,338✔
1304
          }
1305

1306
          // save result converting from double-precision color coordinates to
1307
          // byte-sized
1308
          RGBColor result;
413,556✔
1309
          result.red = static_cast<uint8_t>(current_color.x);
413,556✔
1310
          result.green = static_cast<uint8_t>(current_color.y);
413,556✔
1311
          result.blue = static_cast<uint8_t>(current_color.z);
413,556✔
1312
          data(horiz, vert) = result;
413,556✔
1313

1314
          // Check to draw wireframe in horizontal direction. No inter-thread
1315
          // comm.
1316
          if (horiz > 0) {
413,556✔
1317
            if (!trackstack_equivalent(this_line_segments[tid][horiz],
413,238✔
1318
                  this_line_segments[tid][horiz - 1])) {
413,238✔
1319
              wireframe_initial(horiz, vert) = 1;
18,936✔
1320
            }
1321
          }
1322
        }
1,200,000✔
1323
      } // end "if" vert in correct range
1324

1325
      // We require a barrier before comparing vertical neighbors' intersection
1326
      // stacks. i.e. all threads must be done with their line.
1327
#pragma omp barrier
1328

1329
      // Now that the horizontal line has finished rendering, we can fill in
1330
      // wireframe entries that require comparison among all the threads. Hence
1331
      // the omp barrier being used. It has to be OUTSIDE any if blocks!
1332
      if (vert < pixels_[1]) {
6,030✔
1333
        // Loop over horizontal pixels, checking intersection stack of upper
1334
        // neighbor
1335

1336
        const std::vector<std::vector<TrackSegment>>* top_cmp = nullptr;
6,000✔
1337
        if (tid == 0)
6,000✔
1338
          top_cmp = &old_segments;
6,000✔
1339
        else
1340
          top_cmp = &this_line_segments[tid - 1];
1341

1342
        for (int horiz = 0; horiz < pixels_[0]; ++horiz) {
1,206,000✔
1343
          if (!trackstack_equivalent(
1,200,000✔
1344
                this_line_segments[tid][horiz], (*top_cmp)[horiz])) {
1,200,000✔
1345
            wireframe_initial(horiz, vert) = 1;
23,850✔
1346
          }
1347
        }
1348
      }
1349

1350
      // We need another barrier to ensure threads don't proceed to modify their
1351
      // intersection stacks on that horizontal line while others are
1352
      // potentially still working on the above.
1353
#pragma omp barrier
1354
      vert += n_threads;
6,030✔
1355
    }
1356
  } // end omp parallel
1357

1358
  // Now thicken the wireframe lines and apply them to our image
1359
  for (int vert = 0; vert < pixels_[1]; ++vert) {
12,060✔
1360
    for (int horiz = 0; horiz < pixels_[0]; ++horiz) {
2,412,000✔
1361
      if (wireframe_initial(horiz, vert)) {
2,400,000✔
1362
        if (wireframe_thickness_ == 1)
75,756✔
1363
          data(horiz, vert) = wireframe_color_;
32,940✔
1364
        for (int i = -wireframe_thickness_ / 2; i < wireframe_thickness_ / 2;
205,116✔
1365
             ++i)
1366
          for (int j = -wireframe_thickness_ / 2; j < wireframe_thickness_ / 2;
562,992✔
1367
               ++j)
1368
            if (i * i + j * j < wireframe_thickness_ * wireframe_thickness_) {
433,632✔
1369

1370
              // Check if wireframe pixel is out of bounds
1371
              int w_i = std::max(std::min(horiz + i, pixels_[0] - 1), 0);
433,632✔
1372
              int w_j = std::max(std::min(vert + j, pixels_[1] - 1), 0);
433,632✔
1373
              data(w_i, w_j) = wireframe_color_;
433,632✔
1374
            }
1375
      }
1376
    }
1377
  }
1378

1379
#ifdef USE_LIBPNG
1380
  output_png(path_plot(), data);
60✔
1381
#else
1382
  output_ppm(path_plot(), data);
1383
#endif
1384
}
60✔
1385

1386
void RayTracePlot::print_info() const
96✔
1387
{
1388
  fmt::print("Camera position: {} {} {}\n", camera_position_.x,
80✔
1389
    camera_position_.y, camera_position_.z);
96✔
1390
  fmt::print("Look at: {} {} {}\n", look_at_.x, look_at_.y, look_at_.z);
176✔
1391
  fmt::print(
80✔
1392
    "Horizontal field of view: {} degrees\n", horizontal_field_of_view_);
96✔
1393
  fmt::print("Pixels: {} {}\n", pixels_[0], pixels_[1]);
176✔
1394
}
96✔
1395

1396
void ProjectionPlot::print_info() const
60✔
1397
{
1398
  fmt::print("Plot Type: Projection\n");
60✔
1399
  RayTracePlot::print_info();
60✔
1400
}
60✔
1401

1402
void ProjectionPlot::set_opacities(pugi::xml_node node)
60✔
1403
{
1404
  xs_.resize(colors_.size(), 1e6); // set to large value for opaque by default
60✔
1405

1406
  for (auto cn : node.children("color")) {
132✔
1407
    // Make sure 3 values are specified for RGB
1408
    double user_xs = std::stod(get_node_value(cn, "xs"));
72✔
1409
    int col_id = std::stoi(get_node_value(cn, "id"));
72✔
1410

1411
    // Add RGB
1412
    if (PlotColorBy::cells == color_by_) {
72✔
1413
      if (model::cell_map.find(col_id) != model::cell_map.end()) {
72✔
1414
        col_id = model::cell_map[col_id];
72✔
1415
        xs_[col_id] = user_xs;
72✔
1416
      } else {
1417
        warning(fmt::format(
×
1418
          "Could not find cell {} specified in plot {}", col_id, id()));
×
1419
      }
1420
    } else if (PlotColorBy::mats == color_by_) {
×
1421
      if (model::material_map.find(col_id) != model::material_map.end()) {
×
1422
        col_id = model::material_map[col_id];
×
1423
        xs_[col_id] = user_xs;
×
1424
      } else {
1425
        warning(fmt::format(
×
1426
          "Could not find material {} specified in plot {}", col_id, id()));
×
1427
      }
1428
    }
1429
  }
1430
}
60✔
1431

1432
void RayTracePlot::set_orthographic_width(pugi::xml_node node)
96✔
1433
{
1434
  if (check_for_node(node, "orthographic_width")) {
96✔
1435
    double orthographic_width =
1436
      std::stod(get_node_value(node, "orthographic_width", true));
12✔
1437
    if (orthographic_width < 0.0)
12✔
1438
      fatal_error("Requires positive orthographic_width");
×
1439
    orthographic_width_ = orthographic_width;
12✔
1440
  }
1441
}
96✔
1442

1443
void ProjectionPlot::set_wireframe_thickness(pugi::xml_node node)
60✔
1444
{
1445
  if (check_for_node(node, "wireframe_thickness")) {
60✔
1446
    int wireframe_thickness =
1447
      std::stoi(get_node_value(node, "wireframe_thickness", true));
24✔
1448
    if (wireframe_thickness < 0)
24✔
1449
      fatal_error("Requires non-negative wireframe thickness");
×
1450
    wireframe_thickness_ = wireframe_thickness;
24✔
1451
  }
1452
}
60✔
1453

1454
void ProjectionPlot::set_wireframe_ids(pugi::xml_node node)
60✔
1455
{
1456
  if (check_for_node(node, "wireframe_ids")) {
60✔
1457
    wireframe_ids_ = get_node_array<int>(node, "wireframe_ids");
12✔
1458
    // It is read in as actual ID values, but we have to convert to indices in
1459
    // mat/cell array
1460
    for (auto& x : wireframe_ids_)
24✔
1461
      x = color_by_ == PlotColorBy::mats ? model::material_map[x]
12✔
1462
                                         : model::cell_map[x];
×
1463
  }
1464
  // We make sure the list is sorted in order to later use
1465
  // std::binary_search.
1466
  std::sort(wireframe_ids_.begin(), wireframe_ids_.end());
60✔
1467
}
60✔
1468

1469
void RayTracePlot::set_pixels(pugi::xml_node node)
96✔
1470
{
1471
  vector<int> pxls = get_node_array<int>(node, "pixels");
96✔
1472
  if (pxls.size() != 2)
96✔
1473
    fatal_error(
×
1474
      fmt::format("<pixels> must be length 2 in projection plot {}", id()));
×
1475
  pixels_[0] = pxls[0];
96✔
1476
  pixels_[1] = pxls[1];
96✔
1477
}
96✔
1478

1479
void RayTracePlot::set_camera_position(pugi::xml_node node)
96✔
1480
{
1481
  vector<double> camera_pos = get_node_array<double>(node, "camera_position");
96✔
1482
  if (camera_pos.size() != 3) {
96✔
NEW
1483
    fatal_error(fmt::format(
×
1484
      "camera_position element must have three floating point values"));
1485
  }
1486
  camera_position_.x = camera_pos[0];
96✔
1487
  camera_position_.y = camera_pos[1];
96✔
1488
  camera_position_.z = camera_pos[2];
96✔
1489
}
96✔
1490

1491
void RayTracePlot::set_look_at(pugi::xml_node node)
96✔
1492
{
1493
  vector<double> look_at = get_node_array<double>(node, "look_at");
96✔
1494
  if (look_at.size() != 3) {
96✔
1495
    fatal_error("look_at element must have three floating point values");
×
1496
  }
1497
  look_at_.x = look_at[0];
96✔
1498
  look_at_.y = look_at[1];
96✔
1499
  look_at_.z = look_at[2];
96✔
1500
}
96✔
1501

1502
void RayTracePlot::set_field_of_view(pugi::xml_node node)
96✔
1503
{
1504
  // Defaults to 70 degree horizontal field of view (see .h file)
1505
  if (check_for_node(node, "field_of_view")) {
96✔
1506
    double fov = std::stod(get_node_value(node, "field_of_view", true));
24✔
1507
    if (fov < 180.0 && fov > 0.0) {
24✔
1508
      horizontal_field_of_view_ = fov;
24✔
1509
    } else {
1510
      fatal_error(fmt::format(
×
1511
        "Field of view for plot {} out-of-range. Must be in (0, 180).", id()));
×
1512
    }
1513
  }
1514
}
96✔
1515

1516
PhongPlot::PhongPlot(pugi::xml_node node) : RayTracePlot(node)
36✔
1517
{
1518
  set_opaque_ids(node);
36✔
1519
  set_diffuse_fraction(node);
36✔
1520
  set_light_position(node);
36✔
1521
}
36✔
1522

1523
void PhongPlot::print_info() const
36✔
1524
{
1525
  fmt::print("Plot Type: Phong\n");
36✔
1526
  RayTracePlot::print_info();
36✔
1527
}
36✔
1528

1529
void PhongPlot::create_output() const
36✔
1530
{
1531
  size_t width = pixels_[0];
36✔
1532
  size_t height = pixels_[1];
36✔
1533
  ImageData data({width, height}, not_found_);
36✔
1534

1535
#pragma omp parallel for schedule(dynamic) collapse(2)
18✔
1536
  for (int horiz = 0; horiz < pixels_[0]; ++horiz) {
3,618✔
1537
    for (int vert = 0; vert < pixels_[1]; ++vert) {
723,600✔
1538
      // RayTracePlot implements camera ray generation
1539
      std::pair<Position, Direction> ru = get_pixel_ray(horiz, vert);
720,000✔
1540
      PhongRay ray(ru.first, ru.second, *this);
720,000✔
1541
      ray.trace();
720,000✔
1542
      data(horiz, vert) = ray.result_color();
720,000✔
1543
    }
720,000✔
1544
  }
1545

1546
#ifdef USE_LIBPNG
1547
  output_png(path_plot(), data);
36✔
1548
#else
1549
  output_ppm(path_plot(), data);
1550
#endif
1551
}
36✔
1552

1553
void PhongPlot::set_opaque_ids(pugi::xml_node node)
36✔
1554
{
1555
  if (check_for_node(node, "opaque_ids")) {
36✔
1556
    auto opaque_ids_tmp = get_node_array<int>(node, "opaque_ids");
36✔
1557

1558
    // It is read in as actual ID values, but we have to convert to indices in
1559
    // mat/cell array
1560
    for (auto& x : opaque_ids_tmp)
108✔
1561
      x = color_by_ == PlotColorBy::mats ? model::material_map[x]
72✔
NEW
1562
                                         : model::cell_map[x];
×
1563

1564
    opaque_ids_.insert(opaque_ids_tmp.begin(), opaque_ids_tmp.end());
36✔
1565
  }
36✔
1566
}
36✔
1567

1568
void PhongPlot::set_light_position(pugi::xml_node node)
36✔
1569
{
1570
  if (check_for_node(node, "light_position")) {
36✔
1571
    auto light_pos_tmp = get_node_array<double>(node, "light_position");
12✔
1572

1573
    if (light_pos_tmp.size() != 3)
12✔
NEW
1574
      fatal_error("Light position must be given as 3D coordinates");
×
1575

1576
    light_location_.x = light_pos_tmp[0];
12✔
1577
    light_location_.y = light_pos_tmp[1];
12✔
1578
    light_location_.z = light_pos_tmp[2];
12✔
1579
  } else {
12✔
1580
    light_location_ = camera_position();
24✔
1581
  }
1582
}
36✔
1583

1584
void PhongPlot::set_diffuse_fraction(pugi::xml_node node)
36✔
1585
{
1586
  if (check_for_node(node, "diffuse_fraction")) {
36✔
1587
    diffuse_fraction_ = std::stod(get_node_value(node, "diffuse_fraction"));
12✔
1588
    if (diffuse_fraction_ < 0.0 || diffuse_fraction_ > 1.0) {
12✔
NEW
1589
      fatal_error("Must have 0<=diffuse fraction<= 1");
×
1590
    }
1591
  }
1592
}
36✔
1593

1594
void Ray::compute_distance()
2,991,288✔
1595
{
1596
  boundary() = distance_to_boundary(*this);
2,991,288✔
1597
}
2,991,288✔
1598

1599
void Ray::trace()
3,840,000✔
1600
{
1601
  // To trace the ray from its origin all the way through the model, we have
1602
  // to proceed in two phases. In the first, the ray may or may not be found
1603
  // inside the model. If the ray is already in the model, phase one can be
1604
  // skipped. Otherwise, the ray has to be advanced to the boundary of the
1605
  // model where all the cells are defined. Importantly, this is assuming that
1606
  // the model is convex, which is a very reasonable assumption for any
1607
  // radiation transport model.
1608
  //
1609
  // After phase one is done, we can starting tracing from cell to cell within
1610
  // the model. This step can use neighbor lists to accelerate the ray tracing.
1611

1612
  // Attempt to initialize the particle. We may have to enter a loop to move
1613
  // it up to the edge of the model.
1614
  bool inside_cell = exhaustive_find_cell(*this, settings::verbosity >= 10);
3,840,000✔
1615

1616
  // Advance to the boundary of the model
1617
  while (!inside_cell) {
17,406,180✔
1618
    advance_to_boundary_from_void();
17,406,180✔
1619
    //
1620
    inside_cell = exhaustive_find_cell(*this, settings::verbosity >= 10);
17,406,180✔
1621

1622
    // If true this means no surface was intersected. See cell.cpp and search
1623
    // for numeric_limits to see where we return it.
1624
    if (surface() == std::numeric_limits<int>::max()) {
17,406,180✔
NEW
1625
      warning(fmt::format("Lost a ray, r = {}, u = {}", r(), u()));
×
NEW
1626
      return;
×
1627
    }
1628

1629
    // Exit this loop and enter into cell-to-cell ray tracing (which uses
1630
    // neighbor lists)
1631
    if (inside_cell)
17,406,180✔
1632
      break;
1,596,984✔
1633

1634
    // if there is no intersection with the model, we're done
1635
    if (boundary().surface == SURFACE_NONE)
15,809,196✔
1636
      return;
2,243,016✔
1637

1638
    event_counter_++;
13,566,180✔
1639
    if (event_counter_ > MAX_INTERSECTIONS) {
13,566,180✔
NEW
1640
      warning("Likely infinite loop in ray traced plot");
×
NEW
1641
      return;
×
1642
    }
1643
  }
1644

1645
  // Call the specialized logic for this type of ray. This is for the
1646
  // intersection for the first intersection if we had one.
1647
  if (boundary().surface != SURFACE_NONE) {
1,596,984✔
1648
    // set the geometry state's surface attribute to be used for
1649
    // surface normal computation
1650
    surface() = boundary().surface;
1,596,984✔
1651
    on_intersection();
1,596,984✔
1652
    if (stop_)
1,596,984✔
NEW
1653
      return;
×
1654
  }
1655

1656
  // reset surface attribute to zero after the first intersection so that it
1657
  // doesn't perturb surface crossing logic from here on out
1658
  surface() = 0;
1,596,984✔
1659

1660
  // This is the ray tracing loop within the model. It exits after exiting
1661
  // the model, which is equivalent to assuming that the model is convex.
1662
  // It would be nice to factor out the on_intersection at the end of this
1663
  // loop and then do "while (inside_cell)", but we can't guarantee it's
1664
  // on a surface in that case. There might be some other way to set it
1665
  // up that is perhaps a little more elegant, but this is what works just
1666
  // fine.
1667
  while (true) {
1668

1669
    compute_distance();
2,221,464✔
1670

1671
    // There are no more intersections to process
1672
    // if we hit the edge of the model, so stop
1673
    // the particle in that case. Also, just exit
1674
    // if a negative distance was somehow computed.
1675
    if (boundary().distance == INFTY || boundary().distance == INFINITY ||
4,442,928✔
1676
        boundary().distance < 0) {
2,221,464✔
NEW
1677
      return;
×
1678
    }
1679

1680
    // See below comment where call_on_intersection is checked in an
1681
    // if statement for an explanation of this.
1682
    bool call_on_intersection {true};
2,221,464✔
1683
    if (boundary().distance < 10 * TINY_BIT) {
2,221,464✔
1684
      call_on_intersection = false;
647,256✔
1685
    }
1686

1687
    // DAGMC surfaces expect us to go a little bit further than the advance
1688
    // distance to properly check cell inclusion.
1689
    boundary().distance += TINY_BIT;
2,221,464✔
1690

1691
    // Advance particle, prepare for next intersection
1692
    for (int lev = 0; lev < n_coord(); ++lev) {
4,442,928✔
1693
      coord(lev).r += boundary().distance * coord(lev).u;
2,221,464✔
1694
    }
1695
    surface() = boundary().surface;
2,221,464✔
1696
    n_coord_last() = n_coord();
2,221,464✔
1697
    n_coord() = boundary().coord_level;
2,221,464✔
1698
    if (boundary().lattice_translation[0] != 0 ||
2,221,464✔
1699
        boundary().lattice_translation[1] != 0 ||
4,442,928✔
1700
        boundary().lattice_translation[2] != 0) {
2,221,464✔
NEW
1701
      cross_lattice(*this, boundary(), settings::verbosity >= 10);
×
1702
    }
1703

1704
    // Record how far the ray has traveled
1705
    traversal_distance_ += boundary().distance;
2,221,464✔
1706
    inside_cell = neighbor_list_find_cell(*this, settings::verbosity >= 10);
2,221,464✔
1707

1708
    // Call the specialized logic for this type of ray. Note that we do not
1709
    // call this if the advance distance is very small. Unfortunately, it seems
1710
    // darn near impossible to get the particle advanced to the model boundary
1711
    // and through it without sometimes accidentally calling on_intersection
1712
    // twice. This incorrectly shades the region as occluded when it might not
1713
    // actually be. By screening out intersection distances smaller than a
1714
    // threshold 10x larger than the scoot distance used to advance up to the
1715
    // model boundary, we can avoid that situation.
1716
    if (call_on_intersection) {
2,221,464✔
1717
      on_intersection();
1,574,208✔
1718
      if (stop_)
1,574,208✔
1719
        return;
38,748✔
1720
    }
1721

1722
    if (!inside_cell)
2,182,716✔
1723
      return;
1,558,236✔
1724

1725
    event_counter_++;
624,480✔
1726
    if (event_counter_ > MAX_INTERSECTIONS) {
624,480✔
NEW
1727
      warning("Likely infinite loop in ray traced plot");
×
NEW
1728
      return;
×
1729
    }
1730
  }
624,480✔
1731
}
1732

1733
void ProjectionRay::on_intersection()
2,185,836✔
1734
{
1735
  // This records a tuple with the following info
1736
  //
1737
  // 1) ID (material or cell depending on color_by_)
1738
  // 2) Distance traveled by the ray through that ID
1739
  // 3) Index of the intersected surface (starting from 1)
1740

1741
  line_segments_.emplace_back(
2,185,836✔
1742
    plot_.color_by_ == PlottableInterface::PlotColorBy::mats
2,185,836✔
1743
      ? material()
595,548✔
1744
      : lowest_coord().cell,
1,590,288✔
1745
    traversal_distance_, boundary().surface_index());
2,185,836✔
1746
}
2,185,836✔
1747

1748
void PhongRay::on_intersection()
985,356✔
1749
{
1750
  // Check if we hit an opaque material or cell
1751
  int hit_id = plot_.color_by_ == PlottableInterface::PlotColorBy::mats
985,356✔
1752
                 ? material()
985,356✔
NEW
1753
                 : lowest_coord().cell;
×
1754

1755
  // If we are reflected and have advanced beyond the camera,
1756
  // the ray is done. This is checked here because we should
1757
  // kill the ray even if the material is not opaque.
1758
  if (reflected_ && (r() - plot_.camera_position()).dot(u()) >= 0.0) {
985,356✔
NEW
1759
    stop();
×
1760
    return;
176,784✔
1761
  }
1762

1763
  // Anything that's not opaque has zero impact on the plot.
1764
  if (plot_.opaque_ids_.find(hit_id) == plot_.opaque_ids_.end())
985,356✔
1765
    return;
176,784✔
1766

1767
  if (!reflected_) {
808,572✔
1768
    // reflect the particle and set the color to be colored by
1769
    // the normal or the diffuse lighting contribution
1770
    reflected_ = true;
769,824✔
1771
    result_color_ = plot_.colors_[hit_id];
769,824✔
1772
    Direction to_light = plot_.light_location_ - r();
769,824✔
1773
    to_light /= to_light.norm();
769,824✔
1774

1775
    // TODO
1776
    // Not sure what can cause a surface token to be invalid here, although it
1777
    // sometimes happens for a few pixels. It's very very rare, so proceed by
1778
    // coloring the pixel with the overlap color. It seems to happen only for a
1779
    // few pixels on the outer boundary of a hex lattice.
1780
    //
1781
    // We cannot detect it in the outer loop, and it only matters here, so
1782
    // that's why the error handling is a little different than for a lost
1783
    // ray.
1784
    if (surface() == 0) {
769,824✔
NEW
1785
      result_color_ = plot_.overlap_color_;
×
NEW
1786
      stop();
×
NEW
1787
      return;
×
1788
    }
1789

1790
    // Get surface pointer
1791
    const auto& surf = model::surfaces.at(surface_index());
769,824✔
1792

1793
    Direction normal = surf->normal(r_local());
769,824✔
1794
    normal /= normal.norm();
769,824✔
1795

1796
    // Need to apply translations to find the normal vector in
1797
    // the base level universe's coordinate system.
1798
    for (int lev = n_coord() - 2; lev >= 0; --lev) {
769,824✔
NEW
1799
      if (coord(lev + 1).rotated) {
×
NEW
1800
        const Cell& c {*model::cells[coord(lev).cell]};
×
NEW
1801
        normal = normal.inverse_rotate(c.rotation_);
×
1802
      }
1803
    }
1804

1805
    // use the normal opposed to the ray direction
1806
    if (normal.dot(u()) > 0.0) {
769,824✔
1807
      normal *= -1.0;
69,588✔
1808
    }
1809

1810
    // Facing away from the light means no lighting
1811
    double dotprod = normal.dot(to_light);
769,824✔
1812
    dotprod = std::max(0.0, dotprod);
769,824✔
1813

1814
    double modulation =
769,824✔
1815
      plot_.diffuse_fraction_ + (1.0 - plot_.diffuse_fraction_) * dotprod;
769,824✔
1816
    result_color_ *= modulation;
769,824✔
1817

1818
    // Now point the particle to the camera. We now begin
1819
    // checking to see if it's occluded by another surface
1820
    u() = to_light;
769,824✔
1821

1822
    orig_hit_id_ = hit_id;
769,824✔
1823

1824
    // OpenMC native CSG and DAGMC surfaces have some slight differences
1825
    // in how they interpret particles that are sitting on a surface.
1826
    // I don't know exactly why, but this makes everything work beautifully.
1827
    if (surf->geom_type() == GeometryType::DAG) {
769,824✔
NEW
1828
      surface() = 0;
×
1829
    } else {
1830
      surface() = -surface(); // go to other side
769,824✔
1831
    }
1832

1833
    // Must fully restart coordinate search. Why? Not sure.
1834
    clear();
769,824✔
1835

1836
    // Note this could likely be faster if we cached the previous
1837
    // cell we were in before the reflection. This is the easiest
1838
    // way to fully initialize all the sub-universe coordinates and
1839
    // directions though.
1840
    bool found = exhaustive_find_cell(*this);
769,824✔
1841
    if (!found) {
769,824✔
NEW
1842
      fatal_error("Lost particle after reflection.");
×
1843
    }
1844

1845
    // Must recalculate distance to boundary due to the
1846
    // direction change
1847
    compute_distance();
769,824✔
1848

1849
  } else {
1850
    // If it's not facing the light, we color with the diffuse contribution, so
1851
    // next we check if we're going to occlude the last reflected surface. if
1852
    // so, color by the diffuse contribution instead
1853

1854
    if (orig_hit_id_ == -1)
38,748✔
NEW
1855
      fatal_error("somehow a ray got reflected but not original ID set?");
×
1856

1857
    result_color_ = plot_.colors_[orig_hit_id_];
38,748✔
1858
    result_color_ *= plot_.diffuse_fraction_;
38,748✔
1859
    stop();
38,748✔
1860
  }
1861
}
1862

1863
extern "C" int openmc_id_map(const void* plot, int32_t* data_out)
12✔
1864
{
1865

1866
  auto plt = reinterpret_cast<const SlicePlotBase*>(plot);
12✔
1867
  if (!plt) {
12✔
1868
    set_errmsg("Invalid slice pointer passed to openmc_id_map");
×
1869
    return OPENMC_E_INVALID_ARGUMENT;
×
1870
  }
1871

1872
  if (plt->slice_color_overlaps_ && model::overlap_check_count.size() == 0) {
12✔
1873
    model::overlap_check_count.resize(model::cells.size());
×
1874
  }
1875

1876
  auto ids = plt->get_map<IdData>();
12✔
1877

1878
  // write id data to array
1879
  std::copy(ids.data_.begin(), ids.data_.end(), data_out);
12✔
1880

1881
  return 0;
12✔
1882
}
12✔
1883

1884
extern "C" int openmc_property_map(const void* plot, double* data_out)
12✔
1885
{
1886

1887
  auto plt = reinterpret_cast<const SlicePlotBase*>(plot);
12✔
1888
  if (!plt) {
12✔
1889
    set_errmsg("Invalid slice pointer passed to openmc_id_map");
×
1890
    return OPENMC_E_INVALID_ARGUMENT;
×
1891
  }
1892

1893
  if (plt->slice_color_overlaps_ && model::overlap_check_count.size() == 0) {
12✔
1894
    model::overlap_check_count.resize(model::cells.size());
×
1895
  }
1896

1897
  auto props = plt->get_map<PropertyData>();
12✔
1898

1899
  // write id data to array
1900
  std::copy(props.data_.begin(), props.data_.end(), data_out);
12✔
1901

1902
  return 0;
12✔
1903
}
12✔
1904

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

© 2025 Coveralls, Inc