hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
899275074ae9778439e777220e8eff24f133fb2b
31,542
cpp
C++
libs/tex/texture_patch.cpp
Hivemapper/HM-colony-mvs-texturing
2930c8926886d33fcec5ed42137d2f21ce834c2a
[ "BSD-3-Clause" ]
1
2019-12-04T16:38:50.000Z
2019-12-04T16:38:50.000Z
libs/tex/texture_patch.cpp
Hivemapper/HM-colony-mvs-texturing
2930c8926886d33fcec5ed42137d2f21ce834c2a
[ "BSD-3-Clause" ]
2
2019-07-15T21:58:26.000Z
2020-10-06T02:56:46.000Z
libs/tex/texture_patch.cpp
Hivemapper/HM-colony-mvs-texturing
2930c8926886d33fcec5ed42137d2f21ce834c2a
[ "BSD-3-Clause" ]
1
2019-03-28T18:15:52.000Z
2019-03-28T18:15:52.000Z
/* * Copyright (C) 2015, Nils Moehrle * TU Darmstadt - Graphics, Capture and Massively Parallel Computing * All rights reserved. * * This software may be modified and distributed under the terms * of the BSD 3-Clause license. See the LICENSE.txt file for details. */ #include <cmath> #include <set> #include <math/functions.h> #include <mve/image_color.h> #include <mve/image_tools.h> #include <mve/mesh_io_ply.h> #include "texture_patch.h" TexturePatch::TexturePatch( int label, std::vector<std::size_t> const& faces, std::vector<math::Vec2f> const& texcoords, mve::FloatImage::Ptr image) : label(label), faces(faces), texcoords(texcoords), image(image) { validity_mask = mve::ByteImage::create(get_width(), get_height(), 1); validity_mask->fill(255); blending_mask = mve::ByteImage::create(get_width(), get_height(), 1); } TexturePatch::TexturePatch(TexturePatch const& texture_patch) { label = texture_patch.label; faces = std::vector<std::size_t>(texture_patch.faces); texcoords = std::vector<math::Vec2f>(texture_patch.texcoords); image = texture_patch.image->duplicate(); validity_mask = texture_patch.validity_mask->duplicate(); if (texture_patch.blending_mask != nullptr) { blending_mask = texture_patch.blending_mask->duplicate(); } } TexturePatch::TexturePatch( TexturePatch const& texture_patch, const std::vector<std::size_t>& new_face_indices) { label = texture_patch.label; faces.clear(); texcoords.clear(); float pre_x_max, pre_y_max, pre_x_min, pre_y_min, post_x_max, post_y_max, post_x_min, post_y_min; pre_x_max = pre_y_max = post_x_max = post_y_max = 0; pre_x_min = pre_y_min = post_x_min = post_y_min = 1e6; for (std::size_t i = 0; i < texture_patch.faces.size(); i++) { bool valid = (new_face_indices[texture_patch.faces[i]] != std::numeric_limits<std::size_t>::max()); if (valid) { faces.push_back(new_face_indices[texture_patch.faces[i]]); texcoords.push_back(texture_patch.texcoords[i * 3]); texcoords.push_back(texture_patch.texcoords[i * 3 + 1]); texcoords.push_back(texture_patch.texcoords[i * 3 + 2]); } } bool resize = false; if (!texcoords.empty() && texcoords.size() != texture_patch.texcoords.size()) { for (std::size_t i = 0; i < texture_patch.texcoords.size(); ++i) { pre_x_max = std::max(pre_x_max, texture_patch.texcoords[i][0]); pre_x_min = std::min(pre_x_min, texture_patch.texcoords[i][0]); pre_y_max = std::max(pre_y_max, texture_patch.texcoords[i][1]); pre_y_min = std::min(pre_y_min, texture_patch.texcoords[i][1]); } for (std::size_t i = 0; i < texcoords.size(); ++i) { post_x_max = std::max(post_x_max, texcoords[i][0]); post_x_min = std::min(post_x_min, texcoords[i][0]); post_y_max = std::max(post_y_max, texcoords[i][1]); post_y_min = std::min(post_y_min, texcoords[i][1]); } float threshold = 5.0; if (pre_x_max - post_x_max > threshold || pre_y_max - post_y_max > threshold || post_x_min - pre_x_min > threshold || post_y_min - pre_y_min > threshold) { resize = true; } } if (!resize) { image = texture_patch.image->duplicate(); validity_mask = texture_patch.validity_mask->duplicate(); if (texture_patch.blending_mask != nullptr) { blending_mask = texture_patch.blending_mask->duplicate(); } } else { int new_x_start = std::max(0, (int)std::floor(post_x_min - 2)); int new_y_start = std::max(0, (int)std::floor(post_y_min - 2)); int new_x_width = std::min(texture_patch.image->width(), (int)std::ceil(post_x_max + 2)) - new_x_start; int new_y_width = std::min(texture_patch.image->height(), (int)std::ceil(post_y_max + 2)) - new_y_start; int n_im_channels = texture_patch.image->channels(); int n_vm_channels = texture_patch.validity_mask->channels(); image = mve::FloatImage::create(new_x_width, new_y_width, n_im_channels); validity_mask = mve::ByteImage::create(new_x_width, new_y_width, n_vm_channels); for (int ci = 0; ci < n_im_channels; ++ci) { for (int yi = 0; yi < new_y_width; ++yi) { for (int xi = 0; xi < new_x_width; ++xi) { image->at(xi, yi, ci) = texture_patch.image->at(xi + new_x_start, yi + new_y_start, ci); } } } for (int ci = 0; ci < n_vm_channels; ++ci) { for (int yi = 0; yi < new_y_width; ++yi) { for (int xi = 0; xi < new_x_width; ++xi) { validity_mask->at(xi, yi, ci) = texture_patch.validity_mask->at( xi + new_x_start, yi + new_y_start, ci); } } } for (auto& coord : texcoords) { coord[0] -= new_x_start; coord[1] -= new_y_start; } } } /** @brief Transform the supplied texture coordinate. @details The coordinate transformation mirrors the one used for image scaling in rescale_area. In particular, it assumes that both the old and new images being pointed into have unused texture_patch_border-pixel-wide borders outset from the actual image data. */ math::Vec2f scale_texcoord( math::Vec2f const& tc, int old_width_i, int old_height_i, int new_width_i, int new_height_i); math::Vec2f scale_texcoord( math::Vec2f const& tc, int old_width_i, int old_height_i, int new_width_i, int new_height_i) { math::Vec2f nrv {0.0f}; const auto offset = static_cast<float>(texture_patch_border); const auto w0_a = old_width_i - 2 * offset; const auto h0_a = old_height_i - 2 * offset; const auto w1_a = new_width_i - 2 * offset; const auto h1_a = new_height_i - 2 * offset; const auto x_scale = static_cast<float>(w1_a) / static_cast<float>(w0_a); const auto y_scale = static_cast<float>(h1_a) / static_cast<float>(h0_a); auto x = (tc[0] - offset) * x_scale + offset; auto y = (tc[1] - offset) * y_scale + offset; auto clamp = [](auto v, auto min_v, auto max_v) { return (v < min_v) ? min_v : ((v > max_v) ? max_v : v); }; auto adj_x = clamp(x, offset, new_width_i - offset); auto adj_y = clamp(y, offset, new_height_i - offset); #define HM_ASSERT(test_) \ if (!(test_)) {\ std::cout << "clamped: " << #test_ << std::endl; \ std::cout \ << "old: (" \ << old_width_i << ", " \ << old_height_i << ")" \ << ", new: (" \ << new_width_i << ", " \ << new_height_i << ")" \ << ", offset: " << offset \ << ", tc: (" \ << tc[0] << ", " \ << tc[1] << ")" \ << ", calc: (" \ << x << ", " \ << y << ")" \ << ", adj: (" \ << adj_x << ", " \ << adj_y << ")" \ << std::endl; \ } HM_ASSERT(x == adj_x); HM_ASSERT(y == adj_y); nrv = {adj_x, adj_y}; #undef HM_ASSERT return nrv; } /** @brief Moire-free image scaling. @details Smear the original texel over a grid up to 2x2 texels large based on the conversion from the original coordinates. Note that this algorithm is content-agnostic; every texel in the rescale area will be processed regardless of whether it contains any signal. */ mve::FloatImage::Ptr rescale_area( mve::FloatImage::Ptr image_i, const int new_width_i, const int new_height_i); mve::FloatImage::Ptr rescale_area( mve::FloatImage::Ptr image_i, const int new_width_i, const int new_height_i) { assert(!!image_i); // Note that mve-cropped images incorporate a border. We need to maintain // that border at the precise width it started at, even after scaling. To // accommodate this, we subtract out the border and then add it back in // after scaling. const auto offset = texture_patch_border; const auto w0 = image_i->width(); const auto h0 = image_i->height(); const auto w0_a = image_i->width() - 2 * offset; const auto h0_a = image_i->height() - 2 * offset; const auto w1 = new_width_i; const auto h1 = new_height_i; const auto w1_a = new_width_i - 2 * offset; const auto h1_a = new_height_i - 2 * offset; const auto x_scale = static_cast<float>(w1_a) / static_cast<float>(w0_a); const auto y_scale = static_cast<float>(h1_a) / static_cast<float>(h0_a); const auto scale = x_scale * y_scale; auto out_image(mve::FloatImage::create()); out_image->allocate(w1, h1, image_i->channels()); out_image->fill(0.0f); // Track where we are in the fractional pixel. auto calc_prop = [](auto low, auto scale){ return std::min(1.0f, (std::floor(low) + 1.0f - low) / scale); }; auto test_prop = [](auto prop){ const float k_prop_threshold = 0.999f; return prop > k_prop_threshold; }; // Test against a half-open range of [min, max> auto test_range = [](auto test_x, auto test_y, auto min_x, auto min_y, auto max_x, auto max_y){ return (min_x <= test_x) && (min_y <= test_y) && (test_x < max_x) && (test_y < max_y); }; for (int yi = 0; yi < h0; ++yi) { auto src_y = (yi < offset) ? offset : ((h0 - offset - 1 < yi) ? (h0 - offset - 1) : yi); auto dst_y_calc = static_cast<float>(src_y - offset) * y_scale + offset; auto dst_y = (yi < offset) ? yi : ((h0_a + offset <= yi) ? (yi + h1_a - h0_a) : static_cast<int>(std::floor(dst_y_calc))); auto y_prop = calc_prop(dst_y_calc, y_scale); auto y_pure = test_prop(y_prop); for (int xi = 0; xi < w0; ++xi) { auto src_x = (xi < offset) ? offset : ((w0 - offset - 1 < xi) ? (w0 - offset - 1) : xi); auto dst_x_calc = static_cast<float>(src_x - offset) * x_scale + offset; auto dst_x = (xi < offset) ? xi : ((w0_a + offset <= xi) ? (xi + w1_a - w0_a) : static_cast<int>(std::floor(dst_x_calc))); auto x_prop = calc_prop(dst_x_calc, x_scale); auto x_pure = test_prop(x_prop); for (int ci = 0; ci < image_i->channels(); ++ci) { auto val = image_i->at(src_x, src_y, ci) * scale; // Peform 2x2 linear filtering, avoiding out-of-bounds writes. if (x_pure && y_pure) { if (test_range (dst_x, dst_y, 0, 0, w1, h1)) { out_image->at(dst_x, dst_y, ci) += val; } } else if (x_pure) { if (test_range (dst_x, dst_y, 0, 0, w1, h1)) { out_image->at(dst_x, dst_y, ci) += val * y_prop; } if (test_range (dst_x, dst_y + 1, 0, 0, w1, h1)) { out_image->at(dst_x, dst_y + 1, ci) += val * (1 - y_prop); } } else if (y_pure) { if (test_range (dst_x, dst_y, 0, 0, w1, h1)) { out_image->at(dst_x, dst_y, ci) += val * x_prop; } if (test_range (dst_x + 1, dst_y, 0, 0, w1, h1)) { out_image->at(dst_x + 1, dst_y, ci) += val * (1 - x_prop); } } else { if (test_range (dst_x, dst_y, 0, 0, w1, h1)) { out_image->at(dst_x, dst_y, ci) += val * x_prop * y_prop; } if (test_range (dst_x + 1, dst_y, 0, 0, w1, h1)) { out_image->at(dst_x + 1, dst_y, ci) += val * (1 - x_prop) * y_prop; } if (test_range (dst_x, dst_y + 1, 0, 0, w1, h1)) { out_image->at(dst_x, dst_y + 1, ci) += val * x_prop * (1 - y_prop); } if (test_range (dst_x + 1, dst_y + 1, 0, 0, w1, h1)) { out_image->at(dst_x + 1, dst_y + 1, ci) += val * (1 - x_prop) * (1 - y_prop); } } } } } // border reinforcement for (int yi = 0; yi < h1; ++yi) { auto src_y = (yi < offset) ? offset : ((h1 - offset - 1 < yi) ? (h1 - offset - 1) : yi); for (int xi = 0; xi < w1; ++xi) { auto src_x = (xi < offset) ? offset : ((w1 - offset - 1 < xi) ? (w1 - offset - 1) : xi); for (int ci = 0; ci < image_i->channels(); ++ci) { auto val = image_i->at(src_x, src_y, ci); if ((yi < offset) || (yi >= h1_a + offset) || (xi < offset) || (xi >= w1_a + offset)) { out_image->at(xi, yi, ci) = val; } } } } return out_image; } /** @brief Rescale a patch and underlying imagery. @details Note that the output image will be slightly larger than was actually requested due to the addition of a `texture_patch_border`-wide border around it, as per mvs-texturing’s expectation. */ void TexturePatch::rescale(double ratio) { int old_width = get_width(); int old_height = get_height(); int new_width = std::ceil(old_width * ratio) + 2 * texture_patch_border; int new_height = std::ceil(old_height * ratio) + 2 * texture_patch_border; // SEEME - bitweeder // It appears that there were moiré patterns being generated with the // image scaling being done originally, necessitating an image scaling // replacement function. // image = mve::image::rescale<float>(image, // mve::image::RescaleInterpolation::RESCALE_LINEAR, new_width, new_height); image = rescale_area(image, new_width, new_height); // We recalculate the validity_mask and blending_mask from scratch to avoid // rounding errors of all kinds. validity_mask = mve::ByteImage::create(get_width(), get_height(), 1); blending_mask = mve::ByteImage::create(get_width(), get_height(), 1); // SEEME - bitweeder // Strictly speaking, these calls end up being redundant. Most likely, they // should remain here and the other places we set them should have // zero-fill as a precondition. validity_mask->fill(0); blending_mask->fill(0); if (texcoords.size() >= 3) { // SEEME - bitweeder // We handle these as triples in case the relative positioning turns out // to be important to avoid degeneration when applying scaling to the // triangle. This is more likely to come into play if we start supporting // rotation during texture chart packing. for (std::size_t i = 0; i < texcoords.size(); i += 3) { auto& v1 = texcoords[i]; auto& v2 = texcoords[i + 1]; auto& v3 = texcoords[i + 2]; v1 = scale_texcoord(v1, old_width, old_height, new_width, new_height); v2 = scale_texcoord(v2, old_width, old_height, new_width, new_height); v3 = scale_texcoord(v3, old_width, old_height, new_width, new_height); } } std::vector<math::Vec3f> patch_adjust_values( get_faces().size() * 3, math::Vec3f(0.0f)); adjust_colors(patch_adjust_values); } void TexturePatch::expose_blending_mask() { if (!!blending_mask) { for (int y = 0; y < image->height(); ++y) { for (int x = 0; x < image->width(); ++x) { image->at(x, y, 0) = image->at(x, y, 0) / 2.0f + static_cast<float>(blending_mask->at(x, y, 0)) / 255.0f / 2.0f; if ((0 == x) or (0 == y) or (image->width() - 1 == x) or (image->height() - 1 == y)) { image->at(x, y, 0) = image->at(x, y, 0) / 2.0f + 0.5; image->at(x, y, 1) = image->at(x, y, 1) / 2.0f + 0.5; image->at(x, y, 2) = image->at(x, y, 2) / 2.0f + 0.5; } } } } for (auto const& tc : texcoords) { image->at(tc[0], tc[1], 0) = 1.0; image->at(tc[0], tc[1], 1) = 1.0; image->at(tc[0], tc[1], 2) = 1.0; } } void TexturePatch::expose_validity_mask() { if (!!validity_mask) { for (int y = 0; y < image->height(); ++y) { for (int x = 0; x < image->width(); ++x) { image->at(x, y, 0) = image->at(x, y, 0) / 2.0f + static_cast<float>(validity_mask->at(x, y, 0)) / 255.0f / 2.0f; if ((0 == x) or (0 == y) or (image->width() - 1 == x) or (image->height() - 1 == y)) { image->at(x, y, 0) = image->at(x, y, 0) / 2.0f + 0.5; image->at(x, y, 1) = image->at(x, y, 1) / 2.0f + 0.5; image->at(x, y, 2) = image->at(x, y, 2) / 2.0f + 0.5; } } } } for (auto const& tc : texcoords) { image->at(tc[0], tc[1], 0) = 1.0; image->at(tc[0], tc[1], 1) = 1.0; image->at(tc[0], tc[1], 2) = 1.0; } } void TexturePatch::adjust_colors( std::vector<math::Vec3f> const& adjust_values, bool only_regenerate_masks, int num_channels, std::shared_ptr<std::vector<std::vector<uint8_t>>> texture_atlas_colors) { assert(!!blending_mask); assert(!!validity_mask); validity_mask->fill(0); blending_mask->fill(0); if (texcoords.size() < 3) { return; } const float k_sqrt_2 = std::sqrt(2); mve::FloatImage::Ptr iadjust_values {}; if (!only_regenerate_masks) { iadjust_values = mve::FloatImage::create(get_width(), get_height(), num_channels); } for (std::size_t i = 0; i < texcoords.size(); i += 3) { auto const& v1 = texcoords[i]; auto const& v2 = texcoords[i + 1]; auto const& v3 = texcoords[i + 2]; Tri tri {v1, v2, v3}; auto area = tri.get_area(); if (area < std::numeric_limits<float>::epsilon()) { continue; } auto aabb = tri.get_aabb(); int min_x = static_cast<int>(std::floor(aabb.min_x)) - texture_patch_border; int min_y = static_cast<int>(std::floor(aabb.min_y)) - texture_patch_border; int max_x = static_cast<int>(std::ceil(aabb.max_x)) + texture_patch_border; int max_y = static_cast<int>(std::ceil(aabb.max_y)) + texture_patch_border; #define HM_ASSERT(test_) \ if (!(test_)) {\ std::cout << "failed: " << #test_ << std::endl; \ std::cout \ << "min: (" \ << min_x << ", " \ << min_y << "), " \ << "max: (" \ << max_x << ", " \ << max_y << "), " \ << "size: (" \ << get_width() << ", " \ << get_height() << ")" \ << std::endl; \ } HM_ASSERT(0 <= min_x); HM_ASSERT(0 <= min_y); HM_ASSERT(max_x <= get_width()); HM_ASSERT(max_y <= get_height()); min_x = std::max (0, min_x); min_y = std::max (0, min_y); max_x = std::min (get_width(), max_x); max_y = std::min (get_height(), max_y); for (int y = min_y; y < max_y; ++y) { for (int x = min_x; x < max_x; ++x) { auto bcoords = tri.get_barycentric_coords(x, y); bool inside = bcoords.minimum() >= 0.0f; if (inside) { HM_ASSERT(x != 0); HM_ASSERT(y != 0); if (!only_regenerate_masks) { for (int c = 0; c < num_channels; ++c) { iadjust_values->at(x, y, c) = math::interpolate( adjust_values[i][c], adjust_values[i + 1][c], adjust_values[i + 2][c], bcoords[0], bcoords[1], bcoords[2]); } } validity_mask->at(x, y, 0) = 255; blending_mask->at(x, y, 0) = 255; } else { if (validity_mask->at(x, y, 0) == 255) { continue; } // Check whether the pixel’s distance from the triangle is more than // one pixel. float ha = 2.0f * -bcoords[0] * area / (v2 - v3).norm(); float hb = 2.0f * -bcoords[1] * area / (v1 - v3).norm(); float hc = 2.0f * -bcoords[2] * area / (v1 - v2).norm(); if (ha > k_sqrt_2 || hb > k_sqrt_2 || hc > k_sqrt_2) { continue; } if (!only_regenerate_masks) { for (int c = 0; c < num_channels; ++c) { iadjust_values->at(x, y, c) = math::interpolate( adjust_values[i][c], adjust_values[i + 1][c], adjust_values[i + 2][c], bcoords[0], bcoords[1], bcoords[2]); } } validity_mask->at(x, y, 0) = 255; blending_mask->at(x, y, 0) = 64; } } } #undef HM_ASSERT } if (!only_regenerate_masks) { if (num_channels <= 3) { for (int i = 0; i < image->get_pixel_amount(); ++i) { if (validity_mask->at(i, 0) != 0) { for (int c = 0; c < num_channels; ++c) { image->at(i, c) += iadjust_values->at(i, c); } } else { for (int c = 0; c < num_channels; ++c) { image->at(i, c) = 0.0f; } } } } else { for (int i = 0; i < image->get_pixel_amount(); ++i) { std::vector<float> raw_color(num_channels); if (validity_mask->at(i, 0) != 0) { std::copy( &image->at(i, 0), &image->at(i, 0) + num_channels, raw_color.begin()); for (auto&& sub_color : raw_color) { sub_color += iadjust_values->at(i); } auto color = compute_object_class_color(&raw_color, texture_atlas_colors); std::copy(color.begin(), color.end(), &image->at(i, 0)); } else { // Just set the rgb channels to 0 math::Vec3f color {0.0f, 0.0f, 0.0f}; std::copy(color.begin(), color.end(), &image->at(i, 0)); } } } } } bool TexturePatch::valid_pixel(math::Vec2f pixel) const { float x = pixel[0]; float y = pixel[1]; auto const height = static_cast<float>(get_height()); auto const width = static_cast<float>(get_width()); bool valid = (0.0f <= x && x < width && 0.0f <= y && y < height); if (valid && validity_mask != nullptr) { /* Only pixel which can be correctly interpolated are valid. */ float cx = std::max(0.0f, std::min(width - 1.0f, x)); float cy = std::max(0.0f, std::min(height - 1.0f, y)); int const floor_x = static_cast<int>(cx); int const floor_y = static_cast<int>(cy); int const floor_xp1 = std::min(floor_x + 1, get_width() - 1); int const floor_yp1 = std::min(floor_y + 1, get_height() - 1); float const w1 = cx - static_cast<float>(floor_x); float const w0 = 1.0f - w1; float const w3 = cy - static_cast<float>(floor_y); float const w2 = 1.0f - w3; valid = (w0 * w2 == 0.0f || validity_mask->at(floor_x, floor_y, 0) == 255) && (w1 * w2 == 0.0f || validity_mask->at(floor_xp1, floor_y, 0) == 255) && (w0 * w3 == 0.0f || validity_mask->at(floor_x, floor_yp1, 0) == 255) && (w1 * w3 == 0.0f || validity_mask->at(floor_xp1, floor_yp1, 0) == 255); } return valid; } bool TexturePatch::valid_pixel(math::Vec2i pixel) const { int const x = pixel[0]; int const y = pixel[1]; bool valid = (0 <= x && x < get_width() && 0 <= y && y < get_height()); if (valid && validity_mask != nullptr) { valid = validity_mask->at(x, y, 0) == 255; } return valid; } math::Vec3f TexturePatch::get_pixel_value(math::Vec2f pixel) const { assert(valid_pixel(pixel)); math::Vec3f color; image->linear_at(pixel[0], pixel[1], *color); return color; } std::vector<float> TexturePatch::get_pixel_value_n( math::Vec2f pixel, int num_channels) const { // TODO dwh: for some reason this fails here but not above // assert(valid_pixel(pixel)); std::vector<float> color(num_channels); for (int i = 0; i < num_channels; i++) { color[i] = image->linear_at(pixel[0], pixel[1], i); } return color; } double TexturePatch::compute_geometric_area( const std::vector<math::Vec3f>& vertices, const std::vector<uint>& mesh_faces) const { double total_area = 0; for (auto f : faces) { total_area += std::abs(math::geom::triangle_area( vertices[mesh_faces[f * 3 + 0]], vertices[mesh_faces[f * 3 + 1]], vertices[mesh_faces[f * 3 + 2]])); } return total_area; } double TexturePatch::compute_pixel_area() const { double total_area = 0; for (std::size_t i = 0; i < faces.size(); ++i) { Tri tri(texcoords[i * 3], texcoords[i * 3 + 1], texcoords[i * 3 + 2]); total_area += tri.get_area(); } return total_area; } void TexturePatch::set_pixel_value(math::Vec2i pixel, math::Vec3f color) { assert(blending_mask != NULL); assert(valid_pixel(pixel)); std::copy(color.begin(), color.end(), &image->at(pixel[0], pixel[1], 0)); blending_mask->at(pixel[0], pixel[1], 0) = 128; } void TexturePatch::set_pixel_value( math::Vec2i pixel, const std::vector<float>* all_channels) { assert(blending_mask != NULL); assert(valid_pixel(pixel)); // Only copy the color channels // TODO dwh: remove hard-coded number of colors=3 auto num_colors = std::min(static_cast<int>(all_channels->size()), 3); std::copy( all_channels->begin(), all_channels->begin() + num_colors, &image->at(pixel[0], pixel[1], 0)); blending_mask->at(pixel[0], pixel[1], 0) = 128; } math::Vec3f TexturePatch::compute_object_class_color( const std::vector<float>* color, std::shared_ptr<std::vector<std::vector<uint8_t>>> texture_atlas_colors) { // TODO dwh: remove hard-coded number of colors=3 auto num_colors = std::min(static_cast<int>(color->size()), 3); long arg_max = std::distance( color->begin() + num_colors, std::max_element(color->begin() + num_colors, color->end())); math::Vec3f final_class_color(0, 0, 0); if (texture_atlas_colors) { auto color_vec = (*texture_atlas_colors)[arg_max]; // std::cout << "Color for class " << arg_max << " is " << static_cast<int>(color_vec[0]) << ", " << static_cast<int>(color_vec[1]) << ", " << static_cast<int>(color_vec[2]) << std::endl; if (color_vec.size() == 3) { math::Vec3f class_color(static_cast<float>(color_vec[0]) / 255.f, static_cast<float>(color_vec[1]) / 255.f, static_cast<float>(color_vec[2]) / 255.f); final_class_color = class_color; } else { std::cout << "ERROR!! Bad class color from color vector--setting color to default" << std::endl; } return final_class_color; } else { // Old 7-class is fallback if we don't have texture atlas color info // REDUCE_MAP = {0: (0, 0, 0), 1: (255, 0, 0), 2: (0, 255, 0), 3: (205, // 133, 63), 4: (255, 255, 0), 5: (255, 255, 255), 6: (0, 0, 255)} switch (arg_max) { case 0: { math::Vec3f class_color(0.f, 0.f, 0.f); final_class_color = class_color; break; } case 1: { math::Vec3f class_color(1.f, 0.f, 0.f); final_class_color = class_color; break; } case 2: { math::Vec3f class_color(0.f, 1.f, 0.f); final_class_color = class_color; break; } case 3: { math::Vec3f class_color(205.f / 255.f, 133.f / 255.f, 63.f / 255.f); final_class_color = class_color; break; } case 4: { math::Vec3f class_color(1.f, 1.f, 0.f); final_class_color = class_color; break; } case 5: { math::Vec3f class_color(1.f, 1.f, 1.f); final_class_color = class_color; break; } case 6: { math::Vec3f class_color(0.f, 0.f, 1.f); final_class_color = class_color; break; } default: { math::Vec3f class_color(0.f, 0.f, 0.f); final_class_color = class_color; std::cout << "ERROR!! Bad class " << arg_max << " given raw channels "; for (auto pcolor : *color) { std::cout << pcolor << " "; } std::cout << std::endl; std::cout << " setting to default color "; for (auto fcolor : final_class_color){ std::cout << fcolor << " "; } std::cout << std::endl; } } } return final_class_color; // * color[arg_max]; } void TexturePatch::set_pixel_object_class_value( math::Vec2i pixel, const std::vector<float>* color, std::shared_ptr<std::vector<std::vector<uint8_t>>> texture_atlas_colors) { assert(valid_pixel(pixel)); math::Vec3f final_class_color = TexturePatch::compute_object_class_color(color, texture_atlas_colors); set_pixel_value(pixel, final_class_color); } void TexturePatch::blend(mve::FloatImage::ConstPtr orig) { poisson_blend(orig, blending_mask, image, 1.0f); /* Invalidate all pixels outside the boundary. */ for (int y = 0; y < blending_mask->height(); ++y) { for (int x = 0; x < blending_mask->width(); ++x) { if (blending_mask->at(x, y, 0) == 64) { validity_mask->at(x, y, 0) = 0; } } } } typedef std::vector<std::pair<int, int>> PixelVector; typedef std::set<std::pair<int, int>> PixelSet; void TexturePatch::prepare_blending_mask(std::size_t strip_width) { int const width = blending_mask->width(); int const height = blending_mask->height(); /* Calculate the set of valid pixels at the border of texture patch. */ PixelSet valid_border_pixels; for (int y = 0; y < height; ++y) { for (int x = 0; x < width; ++x) { if (validity_mask->at(x, y, 0) == 0) continue; /* Valid border pixels need no invalid neighbours. */ if (x == 0 || x == width - 1 || y == 0 || y == height - 1) { valid_border_pixels.insert(std::pair<int, int>(x, y)); continue; } /* Check the direct neighbourhood of all invalid pixels. */ for (int j = -1; j <= 1; ++j) { for (int i = -1; i <= 1; ++i) { int nx = x + i; int ny = y + j; /* If the valid pixel has a invalid neighbour: */ if (validity_mask->at(nx, ny, 0) == 0) { /* Add the pixel to the set of valid border pixels. */ valid_border_pixels.insert(std::pair<int, int>(x, y)); } } } } } mve::ByteImage::Ptr inner_pixel = validity_mask->duplicate(); /* Iteratively erode all border pixels. */ for (std::size_t i = 0; i < strip_width; ++i) { PixelVector new_invalid_pixels( valid_border_pixels.begin(), valid_border_pixels.end()); PixelVector::iterator it; valid_border_pixels.clear(); /* Mark the new invalid pixels invalid in the validity mask. */ for (it = new_invalid_pixels.begin(); it != new_invalid_pixels.end(); ++it) { int x = it->first; int y = it->second; inner_pixel->at(x, y, 0) = 0; } /* Calculate the set of valid pixels at the border of the valid area. */ for (it = new_invalid_pixels.begin(); it != new_invalid_pixels.end(); ++it) { int x = it->first; int y = it->second; for (int j = -1; j <= 1; j++) { for (int i = -1; i <= 1; i++) { int nx = x + i; int ny = y + j; if (0 <= nx && nx < width && 0 <= ny && ny < height && inner_pixel->at(nx, ny, 0) == 255) { valid_border_pixels.insert(std::pair<int, int>(nx, ny)); } } } } } /* Sanitize blending mask. */ for (int y = 1; y < height - 1; ++y) { for (int x = 1; x < width - 1; ++x) { if (blending_mask->at(x, y, 0) == 128) { uint8_t n[] = {blending_mask->at(x - 1, y, 0), blending_mask->at(x + 1, y, 0), blending_mask->at(x, y - 1, 0), blending_mask->at(x, y + 1, 0)}; bool valid = true; for (uint8_t v : n) { if (v == 255) continue; valid = false; } if (valid) blending_mask->at(x, y, 0) = 255; } } } /* Mark all remaining pixels invalid in the blending_mask. */ for (int i = 0; i < inner_pixel->get_pixel_amount(); ++i) { if (inner_pixel->at(i) == 255) blending_mask->at(i) = 0; } /* Mark all border pixels. */ PixelSet::iterator it; for (it = valid_border_pixels.begin(); it != valid_border_pixels.end(); ++it) { int x = it->first; int y = it->second; blending_mask->at(x, y, 0) = 128; } }
33.237092
190
0.571999
[ "vector", "transform" ]
899911e458a821d1ece52f0a8e4dbf2b4d879750
4,891
cpp
C++
Timelab/src/DateTime.cpp
Ryandry1st/DateTime
dcda168b31863eaafbac371f14b837165cee3500
[ "MIT" ]
null
null
null
Timelab/src/DateTime.cpp
Ryandry1st/DateTime
dcda168b31863eaafbac371f14b837165cee3500
[ "MIT" ]
null
null
null
Timelab/src/DateTime.cpp
Ryandry1st/DateTime
dcda168b31863eaafbac371f14b837165cee3500
[ "MIT" ]
null
null
null
/* * DateTime.cpp * * Created on: Apr 10, 2017 * Author: dreifuerstrm * DateTime class definitions which describe the implementation of the combined Date and Time classes */ #include "DateTime.h" DateTime::DateTime() { // default constructor, sets all data to 0 my_date = Date(0,0,0); my_time = Time(0); } DateTime::~DateTime() { //default destructor } DateTime::DateTime(Date d, Time t){ //parameter constructor which initializes the data members setdate(d); settime(t); } //set functions which ensure illegal data is not entered into the data members void DateTime::setdate(Date d){ if(d < Date(0,0,0)){ cout<< "illegal parameter input" << endl; } else{ my_date = d; } } void DateTime::settime(Time t){ if(t < Time(0)){ cout << "illegal parameter input" << endl; } else{ my_time = t; } } //get functions which return the desired data value Date DateTime::getdate(){ return my_date; } Time DateTime::gettime(){ return my_time; } string DateTime::print(){ //function which returns a string of the date and time of a DateTime object for printing string dat = my_date.print(); string tim = my_time.print(); return dat+ " " + tim; } //three different addition operators for defining the different objects that can be added to a datetime object DateTime DateTime::operator+(const DateTime& rhs) const{ //adds two datetimes by adding both the date and the time and rolling over if the times add another day DateTime sum; sum.setdate(this->my_date + rhs.my_date); sum.settime(this->my_time + rhs.my_time); if(sum.gettime() < this->my_time){ sum.setdate(sum.my_date + Date(0,0,1)); } return sum; //returns the datetime object sum of the two datetime objects } DateTime DateTime::operator+(const Time& rhs) const{ //adds a time to a datetime, generally not changing the date, but it can roll over if necesarry DateTime sum; sum.setdate(this->my_date); sum.settime(this->my_time + rhs); if(sum.gettime() < this->my_time){ sum.setdate(sum.my_date + Date(0,0,1)); } return sum; //return the datetime object sum } DateTime DateTime::operator+(const Date& rhs) const{ //last addition option which is adding a date with a datetime, causing the date to change DateTime sum; sum.settime(this->my_time); sum.setdate(this->my_date + rhs); //returns the new datetime object with the same time but a new date return sum; } //subtraction operator for the three different subtraction cases, similar to the addition cases DateTime DateTime::operator-(const Time& rhs) const{ //subtracts the time from a datetime, however does not permit negative time, or reverse rolling days DateTime difference; difference.setdate(this->my_date); difference.settime(this->my_time - rhs); return difference; //returns the new datetime object } DateTime DateTime::operator-(const Date& rhs) const{ //subtracts the date from a datetime, and keeps the time the same DateTime difference; difference.my_time = this->my_time; difference.setdate(this->my_date - rhs); //does not permit negative dates return difference; //returns the new datetime object } DateTime DateTime::operator-(const DateTime& rhs) const{ //subtracts two datetime objects, but does not allow for negative times or dates to occur DateTime difference; difference.setdate(this->my_date - rhs.my_date); difference.settime(this->my_time - rhs.my_time); return difference; //returns the difference of the two datetimes } bool DateTime::operator==(const DateTime& rhs) const{ //checks if both the time and date of two datetimes are the same bool dat; bool tim; dat = (this->my_date == rhs.my_date); tim = (this->my_time == rhs.my_time); return dat&tim; } bool DateTime::operator<(const DateTime& rhs) const{ //checks if a datetime is less recent than another datetime bool dat; bool tim; if(this->my_date < rhs.my_date){ //if the date is less, it is automatically less dat = true; } else if(this->my_date == rhs.my_date){ //if the dates are equal, the time must be compared tim = (this->my_time < rhs.my_time); if(tim) dat = true; } else dat = false; return dat; //returns the boolean result } bool DateTime::operator>(const DateTime& rhs) const{ //checks if the datetime is more recent than another bool lt = (*this < rhs); bool rt = (*this == rhs); //checks if it is not equal to or less than the other datetime return(!(lt|rt)); } void DateTime::operator=(const DateTime& rhs){ //sets one datetime equal to another so long as it is not the same object if(this != &rhs){ my_date = rhs.my_date; my_time = rhs.my_time; } } bool DateTime::operator!=(const DateTime& rhs) const{ //checks for the opposite of the two Datetimes being equal return(!(*this == rhs)); }
29.823171
111
0.695972
[ "object" ]
899c3d7d26d04242711f850f1bb6abf8002d8030
1,793
cpp
C++
04.InheritanceExtended/04.InheritanceExtended/04.InheritanceExtended.cpp
zvet80/CppCourse
a8d488dba1ba649dfc6e6d906ed25e506ff30d99
[ "MIT" ]
null
null
null
04.InheritanceExtended/04.InheritanceExtended/04.InheritanceExtended.cpp
zvet80/CppCourse
a8d488dba1ba649dfc6e6d906ed25e506ff30d99
[ "MIT" ]
null
null
null
04.InheritanceExtended/04.InheritanceExtended/04.InheritanceExtended.cpp
zvet80/CppCourse
a8d488dba1ba649dfc6e6d906ed25e506ff30d99
[ "MIT" ]
null
null
null
// 04.InheritanceExtended.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> #include "Invoice.h" #include "Store.h" using namespace std; int main() { Item bonbon = Item("001", "bonbon", 2.5); Item gum = Item("002", "gum", 1.3); Item buiskit = Item("003", "buiskit", 5.2); Item gum2 = Item(gum); gum2.setId("004"); vector<Item> inventory = vector<Item>{ bonbon, gum, buiskit, gum2 }; vector<Item> invoiceItems = vector<Item>{}; Invoice invoice = Invoice(invoiceItems); Store candy = Store("CandyShop", 12345678, "Somewhere in the middle of nowhere", inventory); cout << "Welcome to CandyShop!\nType:\nP - to make a purchase\nC - to clear all purchases\nT - to get total amount\nG - to get your change\nA - to enter admin mode and change item price" << endl; string inputItem; float inputGiven; float newPrice; char choice; cin >> choice; while (choice != '0') { switch (choice) { case 'P':cout << "Add an item to purchase"; cout << "\nInput item id: "; cin >> inputItem; invoice.AddItem(candy.GetItemById(inputItem)); invoice.toString(candy, 0); break; case 'C': invoice.Clear(); cout << "Invoice cleared"; break; case 'T': cout << "Invoice total: " << invoice.GetTotal(); break; case 'G': cout << "Please enter the amount of money: " << endl; cin >> inputGiven; cout << "The change is " << invoice.GetChange(inputGiven) << " leva" << endl; break; case 'A': cout << "Admin mode:Change the price of item: "; cin >> inputItem; cout << "Enter new price: "; cin >> newPrice; candy.changePrice(inputItem, newPrice); break; default: cout << "Sorry, no such operation"; break; } cout << "\nChoose another operation or enter 0" << endl; cin >> choice; } return 0; }
30.389831
196
0.654211
[ "vector" ]
89a6bb1eb7381e857563b2c89c3f2ac64de9d9ec
1,174
hpp
C++
GameEngineX/Source/Core/Physics/Physics2DContactListener.hpp
GeorgeHanna/BarebonesGameEngine
39a122832a4b050fff117114d1ba37bbd72edd42
[ "MIT" ]
null
null
null
GameEngineX/Source/Core/Physics/Physics2DContactListener.hpp
GeorgeHanna/BarebonesGameEngine
39a122832a4b050fff117114d1ba37bbd72edd42
[ "MIT" ]
null
null
null
GameEngineX/Source/Core/Physics/Physics2DContactListener.hpp
GeorgeHanna/BarebonesGameEngine
39a122832a4b050fff117114d1ba37bbd72edd42
[ "MIT" ]
null
null
null
// // Physics2DContactListener.hpp // GameEngineX // // Created by George Hanna on 29/05/16. // Copyright © 2016 George Hanna. All rights reserved. // #ifndef Physics2DContactListener_hpp #define Physics2DContactListener_hpp #include <stdio.h> #include <vector> #include <Box2D.h> #include "../Subject.hpp" struct Contact { b2Fixture* A; b2Fixture* B; b2Vec2 normal; b2Vec2 point; float collisionForce; bool operator==(const Contact& otherC)const { return (A == otherC.A) && (B == otherC.B); } }; class Physics2DContactListener : public b2ContactListener{ private: Subject<Contact*> _collisionEvent; public: std::vector<Contact> contacts_vec; virtual void BeginContact(b2Contact* contact); virtual void EndContact(b2Contact* contact); virtual void PreSolve(b2Contact * contact, const b2Manifold* oldManifold); virtual void PostSolve(b2Contact* contact, const b2ContactImpulse* impulse); virtual void AddCollisionEventListener(std::function<void(Contact*)> eventfunction) { _collisionEvent += eventfunction; }; }; #endif /* Physics2DContactListener_hpp */
22.576923
87
0.696763
[ "vector" ]
89ad2580267c6124d091107d5b6d4591eea63a0d
7,302
cpp
C++
escriptcore/src/MPIScalarReducer.cpp
markendr/esys-escript.github.io
0023eab09cd71f830ab098cb3a468e6139191e8d
[ "Apache-2.0" ]
null
null
null
escriptcore/src/MPIScalarReducer.cpp
markendr/esys-escript.github.io
0023eab09cd71f830ab098cb3a468e6139191e8d
[ "Apache-2.0" ]
null
null
null
escriptcore/src/MPIScalarReducer.cpp
markendr/esys-escript.github.io
0023eab09cd71f830ab098cb3a468e6139191e8d
[ "Apache-2.0" ]
null
null
null
/***************************************************************************** * * Copyright (c) 2014-2018 by The University of Queensland * http://www.uq.edu.au * * Primary Business: Queensland, Australia * Licensed under the Apache License, version 2.0 * http://www.apache.org/licenses/LICENSE-2.0 * * Development until 2012 by Earth Systems Science Computational Center (ESSCC) * Development 2012-2013 by School of Earth Sciences * Development from 2014-2017 by Centre for Geoscience Computing (GeoComp) * Development from 2019 by School of Earth and Environmental Sciences ** *****************************************************************************/ #include "MPIScalarReducer.h" #include "SplitWorldException.h" #include <limits> #include <sstream> #include <boost/python/extract.hpp> #include <boost/scoped_array.hpp> using namespace boost::python; using namespace escript; namespace escript { Reducer_ptr makeScalarReducer(std::string type) { MPI_Op op; if (type=="SUM") { op=MPI_SUM; } else if (type=="MAX") { op=MPI_MAX; } else if (type=="MIN") { op=MPI_MIN; } else if (type=="SET") { op=MPI_OP_NULL; } else { throw SplitWorldException("Unsupported operation for makeScalarReducer."); } MPIScalarReducer* m=new MPIScalarReducer(op); return Reducer_ptr(m); } } // namespace escript namespace { void combineDouble(double& d1, const double d2, MPI_Op op) { if (op==MPI_SUM) { d1+=d2; } else if (op==MPI_MAX) { d1=(d2>d1)?d2:d1; } else if (op==MPI_MIN) { d1=(d2<d1)?d2:d1; } else if (op==MPI_OP_NULL) { throw SplitWorldException("Multiple 'simultaneous' attempts to export a 'SET' variable."); } } } // anonymous namespace MPIScalarReducer::MPIScalarReducer(MPI_Op op) : reduceop(op), had_an_export_this_round(false) { valueadded=false; if ((op==MPI_SUM) || (op==MPI_OP_NULL)) // why not switch? because we don't know MPI_Op is scalar { identity=0; } else if (op==MPI_MAX) { identity=std::numeric_limits<double>::min(); } else if (op==MPI_MIN) { identity=std::numeric_limits<double>::max(); } else { throw SplitWorldException("Unsupported MPI_Op"); } } void MPIScalarReducer::setDomain(escript::Domain_ptr d) { // deliberately left blank } std::string MPIScalarReducer::description() { std::string op; if (reduceop==MPI_SUM) { op="SUM"; } else if (reduceop==MPI_MAX) { op="MAX"; } else if (reduceop==MPI_MIN) { op="MIN"; } else if (reduceop==MPI_OP_NULL) { op="SET"; } else { throw SplitWorldException("Unsupported MPI reduction operation"); } return "Reducer("+op+") for double scalars"; } void MPIScalarReducer::newRunJobs() { had_an_export_this_round=false; } bool MPIScalarReducer::valueCompatible(boost::python::object v) { extract<double> ex(v); if (!ex.check()) { return false; } return true; } bool MPIScalarReducer::reduceLocalValue(boost::python::object v, std::string& errstring) { extract<double> ex(v); if (!ex.check()) { errstring="reduceLocalValue: expected double value. Got something else."; return false; } if (!valueadded || !had_an_export_this_round) { // first value so answer becomes this one value=ex(); valueadded=true; had_an_export_this_round=true; } else { if (reduceop==MPI_OP_NULL) { if (had_an_export_this_round) { reset(); errstring="reduceLocalValue: Multiple 'simultaneous' attempts to export a 'SET' variable."; return false; } value=ex(); } else { combineDouble(value, ex(), reduceop); } had_an_export_this_round=true; } return true; } void MPIScalarReducer::reset() { valueadded=false; value=0; } bool MPIScalarReducer::checkRemoteCompatibility(JMPI& mpi_info, std::string& errstring) { return true; } // By the time this function is called, we know that all the values // are compatible bool MPIScalarReducer::reduceRemoteValues(MPI_Comm& com) { #ifdef ESYS_MPI if (reduceop==MPI_OP_NULL) { reset(); return false; // this will stop bad things happening but won't give an informative error message } double rvalue; if (MPI_Allreduce(&value, &rvalue, 1, MPI_DOUBLE, reduceop, com)!=MPI_SUCCESS) { return false; } value=rvalue; return true; #else return true; #endif } // populate a vector of ints with enough information to ensure two values are compatible // or to construct a container for incomming data // Format for this: // [0] Type of Data: {0 : error, 1: DataEmpty, 10: constant, 11:tagged, 12:expanded} // [1] Functionspace type code // [2] Only used for tagged --- gives the number of tags (which exist in the data object) // [3..6] Components of the shape void MPIScalarReducer::getCompatibilityInfo(std::vector<unsigned>& params) { params.resize(1); // in case someone tries to do something with it } // Get a value for this variable from another process // This is not a reduction and will replace any existing value bool MPIScalarReducer::recvFrom(int localid, int source, JMPI& mpiinfo) { #ifdef ESYS_MPI MPI_Status stat; if (MPI_Recv(&value, 1, MPI_DOUBLE, source, PARAMTAG, mpiinfo->comm, &stat)!=MPI_SUCCESS) return false; #endif return true; } // Send a value to this variable to another process // This is not a reduction and will replace any existing value bool MPIScalarReducer::sendTo(int localid, int target, JMPI& mpiinfo) { #ifdef ESYS_MPI if (MPI_Send(&value, 1, MPI_DOUBLE, target, PARAMTAG, mpiinfo->comm)!=MPI_SUCCESS) return false; #endif return true; } double MPIScalarReducer::getDouble() { return value; } boost::python::object MPIScalarReducer::getPyObj() { boost::python::object o(value); return o; } #ifdef ESYS_MPI // send from proc 0 in the communicator to all others bool MPIScalarReducer::groupSend(MPI_Comm& com, bool imsending) { if (MPI_Bcast(&value, 1, MPI_DOUBLE, 0, com)==MPI_SUCCESS) { valueadded=true; return true; } return false; } bool MPIScalarReducer::groupReduce(MPI_Comm& com, char mystate) { double answer=0; if (reduceop==MPI_OP_NULL) return false; if (MPI_Allreduce((mystate==reducerstatus::NEW)?&value:&identity, &answer, 1, MPI_DOUBLE, reduceop, com)==MPI_SUCCESS) { value=answer; valueadded=true; return true; } return false; } #endif // ESYS_MPI void MPIScalarReducer::copyValueFrom(boost::shared_ptr<AbstractReducer>& src) { MPIScalarReducer* sr=dynamic_cast<MPIScalarReducer*>(src.get()); if (sr==0) { throw SplitWorldException("Source and destination need to be the same reducer types."); } value=sr->value; valueadded=true; } bool MPIScalarReducer::canClash() { return (reduceop==MPI_OP_NULL); }
23.180952
122
0.627773
[ "object", "shape", "vector" ]
89b28dfe963966a482e29b8df0c38b9f04c79968
11,388
hpp
C++
include/GlobalNamespace/MultiplayerLocalActivePlayerFacade.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
include/GlobalNamespace/MultiplayerLocalActivePlayerFacade.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
include/GlobalNamespace/MultiplayerLocalActivePlayerFacade.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: UnityEngine.MonoBehaviour #include "UnityEngine/MonoBehaviour.hpp" // Including type: IMultiplayerLevelEndActionsPublisher #include "GlobalNamespace/IMultiplayerLevelEndActionsPublisher.hpp" // Including type: IMultiplayerLevelEndActionsListener #include "GlobalNamespace/IMultiplayerLevelEndActionsListener.hpp" // Including type: IStartSeekSongControllerProvider #include "GlobalNamespace/IStartSeekSongControllerProvider.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: GlobalNamespace namespace GlobalNamespace { // Forward declaring type: IStartSeekSongController class IStartSeekSongController; // Forward declaring type: MultiplayerLocalActivePlayerIntroAnimator class MultiplayerLocalActivePlayerIntroAnimator; // Forward declaring type: GameSongController class GameSongController; // Forward declaring type: BeatmapObjectManager class BeatmapObjectManager; // Forward declaring type: IBeatmapObjectCallbackController class IBeatmapObjectCallbackController; // Forward declaring type: MultiplayerLevelCompletionResults class MultiplayerLevelCompletionResults; } // Forward declaring namespace: UnityEngine namespace UnityEngine { // Forward declaring type: GameObject class GameObject; } // Forward declaring namespace: System namespace System { // Forward declaring type: Action`1<T> template<typename T> class Action_1; } // Completed forward declares // Type namespace: namespace GlobalNamespace { // Size: 0x60 #pragma pack(push, 1) // Autogenerated type: MultiplayerLocalActivePlayerFacade class MultiplayerLocalActivePlayerFacade : public UnityEngine::MonoBehaviour/*, public GlobalNamespace::IMultiplayerLevelEndActionsPublisher, public GlobalNamespace::IMultiplayerLevelEndActionsListener, public GlobalNamespace::IStartSeekSongControllerProvider*/ { public: // Nested type: GlobalNamespace::MultiplayerLocalActivePlayerFacade::Factory class Factory; // private UnityEngine.GameObject[] _activeOnlyGameObjects // Size: 0x8 // Offset: 0x18 ::Array<UnityEngine::GameObject*>* activeOnlyGameObjects; // Field size check static_assert(sizeof(::Array<UnityEngine::GameObject*>*) == 0x8); // private UnityEngine.GameObject _outroAnimator // Size: 0x8 // Offset: 0x20 UnityEngine::GameObject* outroAnimator; // Field size check static_assert(sizeof(UnityEngine::GameObject*) == 0x8); // [InjectAttribute] Offset: 0xE1D370 // private readonly IStartSeekSongController _songController // Size: 0x8 // Offset: 0x28 GlobalNamespace::IStartSeekSongController* songController; // Field size check static_assert(sizeof(GlobalNamespace::IStartSeekSongController*) == 0x8); // [InjectAttribute] Offset: 0xE1D380 // private readonly MultiplayerLocalActivePlayerIntroAnimator _introAnimator // Size: 0x8 // Offset: 0x30 GlobalNamespace::MultiplayerLocalActivePlayerIntroAnimator* introAnimator; // Field size check static_assert(sizeof(GlobalNamespace::MultiplayerLocalActivePlayerIntroAnimator*) == 0x8); // [InjectAttribute] Offset: 0xE1D390 // private readonly GameSongController _gameSongController // Size: 0x8 // Offset: 0x38 GlobalNamespace::GameSongController* gameSongController; // Field size check static_assert(sizeof(GlobalNamespace::GameSongController*) == 0x8); // [InjectAttribute] Offset: 0xE1D3A0 // private readonly BeatmapObjectManager _beatmapObjectManager // Size: 0x8 // Offset: 0x40 GlobalNamespace::BeatmapObjectManager* beatmapObjectManager; // Field size check static_assert(sizeof(GlobalNamespace::BeatmapObjectManager*) == 0x8); // [InjectAttribute] Offset: 0xE1D3B0 // private readonly IBeatmapObjectCallbackController _beatmapObjectCallbackController // Size: 0x8 // Offset: 0x48 GlobalNamespace::IBeatmapObjectCallbackController* beatmapObjectCallbackController; // Field size check static_assert(sizeof(GlobalNamespace::IBeatmapObjectCallbackController*) == 0x8); // [CompilerGeneratedAttribute] Offset: 0xE1D3C0 // private System.Action`1<MultiplayerLevelCompletionResults> playerDidFinishEvent // Size: 0x8 // Offset: 0x50 System::Action_1<GlobalNamespace::MultiplayerLevelCompletionResults*>* playerDidFinishEvent; // Field size check static_assert(sizeof(System::Action_1<GlobalNamespace::MultiplayerLevelCompletionResults*>*) == 0x8); // [CompilerGeneratedAttribute] Offset: 0xE1D3D0 // private System.Action`1<PlayerNetworkFailReason> playerNetworkDidFailedEvent // Size: 0x8 // Offset: 0x58 System::Action_1<GlobalNamespace::PlayerNetworkFailReason>* playerNetworkDidFailedEvent; // Field size check static_assert(sizeof(System::Action_1<GlobalNamespace::PlayerNetworkFailReason>*) == 0x8); // Creating value type constructor for type: MultiplayerLocalActivePlayerFacade MultiplayerLocalActivePlayerFacade(::Array<UnityEngine::GameObject*>* activeOnlyGameObjects_ = {}, UnityEngine::GameObject* outroAnimator_ = {}, GlobalNamespace::IStartSeekSongController* songController_ = {}, GlobalNamespace::MultiplayerLocalActivePlayerIntroAnimator* introAnimator_ = {}, GlobalNamespace::GameSongController* gameSongController_ = {}, GlobalNamespace::BeatmapObjectManager* beatmapObjectManager_ = {}, GlobalNamespace::IBeatmapObjectCallbackController* beatmapObjectCallbackController_ = {}, System::Action_1<GlobalNamespace::MultiplayerLevelCompletionResults*>* playerDidFinishEvent_ = {}, System::Action_1<GlobalNamespace::PlayerNetworkFailReason>* playerNetworkDidFailedEvent_ = {}) noexcept : activeOnlyGameObjects{activeOnlyGameObjects_}, outroAnimator{outroAnimator_}, songController{songController_}, introAnimator{introAnimator_}, gameSongController{gameSongController_}, beatmapObjectManager{beatmapObjectManager_}, beatmapObjectCallbackController{beatmapObjectCallbackController_}, playerDidFinishEvent{playerDidFinishEvent_}, playerNetworkDidFailedEvent{playerNetworkDidFailedEvent_} {} // Creating interface conversion operator: operator GlobalNamespace::IMultiplayerLevelEndActionsPublisher operator GlobalNamespace::IMultiplayerLevelEndActionsPublisher() noexcept { return *reinterpret_cast<GlobalNamespace::IMultiplayerLevelEndActionsPublisher*>(this); } // Creating interface conversion operator: operator GlobalNamespace::IMultiplayerLevelEndActionsListener operator GlobalNamespace::IMultiplayerLevelEndActionsListener() noexcept { return *reinterpret_cast<GlobalNamespace::IMultiplayerLevelEndActionsListener*>(this); } // Creating interface conversion operator: operator GlobalNamespace::IStartSeekSongControllerProvider operator GlobalNamespace::IStartSeekSongControllerProvider() noexcept { return *reinterpret_cast<GlobalNamespace::IStartSeekSongControllerProvider*>(this); } // Deleting conversion operator: operator System::IntPtr constexpr operator System::IntPtr() const noexcept = delete; // public MultiplayerLocalActivePlayerIntroAnimator get_introAnimator() // Offset: 0x23FF914 GlobalNamespace::MultiplayerLocalActivePlayerIntroAnimator* get_introAnimator(); // public UnityEngine.GameObject get_outroAnimator() // Offset: 0x23FF91C UnityEngine::GameObject* get_outroAnimator(); // public IStartSeekSongController get_songController() // Offset: 0x23FF924 GlobalNamespace::IStartSeekSongController* get_songController(); // public System.Void add_playerDidFinishEvent(System.Action`1<MultiplayerLevelCompletionResults> value) // Offset: 0x23FF92C void add_playerDidFinishEvent(System::Action_1<GlobalNamespace::MultiplayerLevelCompletionResults*>* value); // public System.Void remove_playerDidFinishEvent(System.Action`1<MultiplayerLevelCompletionResults> value) // Offset: 0x23FF9D0 void remove_playerDidFinishEvent(System::Action_1<GlobalNamespace::MultiplayerLevelCompletionResults*>* value); // public System.Void add_playerNetworkDidFailedEvent(System.Action`1<PlayerNetworkFailReason> value) // Offset: 0x23FFA74 void add_playerNetworkDidFailedEvent(System::Action_1<GlobalNamespace::PlayerNetworkFailReason>* value); // public System.Void remove_playerNetworkDidFailedEvent(System.Action`1<PlayerNetworkFailReason> value) // Offset: 0x23FFB18 void remove_playerNetworkDidFailedEvent(System::Action_1<GlobalNamespace::PlayerNetworkFailReason>* value); // public System.Void ReportPlayerDidFinish(MultiplayerLevelCompletionResults results) // Offset: 0x23FFBBC void ReportPlayerDidFinish(GlobalNamespace::MultiplayerLevelCompletionResults* results); // public System.Void ReportPlayerNetworkDidFailed(PlayerNetworkFailReason failReason) // Offset: 0x23FFC30 void ReportPlayerNetworkDidFailed(GlobalNamespace::PlayerNetworkFailReason failReason); // public System.Void DisablePlayer() // Offset: 0x23FFCA4 void DisablePlayer(); // public System.Void PauseSpawning() // Offset: 0x23FFD14 void PauseSpawning(); // public System.Void ResumeSpawning() // Offset: 0x23FFDC8 void ResumeSpawning(); // public System.Void __ForceStopSong() // Offset: 0x23FFE7C void __ForceStopSong(); // public UnityEngine.GameObject[] __GetActiveOnlyGameObjects() // Offset: 0x23FFEC4 ::Array<UnityEngine::GameObject*>* __GetActiveOnlyGameObjects(); // public System.Void .ctor() // Offset: 0x23FFECC // Implemented from: UnityEngine.MonoBehaviour // Base method: System.Void MonoBehaviour::.ctor() // Base method: System.Void Behaviour::.ctor() // Base method: System.Void Component::.ctor() // Base method: System.Void Object::.ctor() // Base method: System.Void Object::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static MultiplayerLocalActivePlayerFacade* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("GlobalNamespace::MultiplayerLocalActivePlayerFacade::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<MultiplayerLocalActivePlayerFacade*, creationType>())); } }; // MultiplayerLocalActivePlayerFacade #pragma pack(pop) static check_size<sizeof(MultiplayerLocalActivePlayerFacade), 88 + sizeof(System::Action_1<GlobalNamespace::PlayerNetworkFailReason>*)> __GlobalNamespace_MultiplayerLocalActivePlayerFacadeSizeCheck; static_assert(sizeof(MultiplayerLocalActivePlayerFacade) == 0x60); } DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::MultiplayerLocalActivePlayerFacade*, "", "MultiplayerLocalActivePlayerFacade");
58.4
1,121
0.770899
[ "object" ]
89b4edcbe49abd0336383938b6edb1427abd5d51
8,346
cpp
C++
analytics/src/lib/indices/build_indexes.cpp
David-Durst/csknow
5b31585c6be63cee117ce5910545c8cc34627fd4
[ "MIT" ]
8
2021-03-08T21:24:42.000Z
2022-03-20T23:18:09.000Z
analytics/src/lib/indices/build_indexes.cpp
David-Durst/csknow
5b31585c6be63cee117ce5910545c8cc34627fd4
[ "MIT" ]
2
2021-12-27T01:26:12.000Z
2022-02-24T19:51:48.000Z
analytics/src/lib/indices/build_indexes.cpp
David-Durst/csknow
5b31585c6be63cee117ce5910545c8cc34627fd4
[ "MIT" ]
null
null
null
#include "load_data.h" #include "load_cover.h" #include <algorithm> #include <iostream> #include <assert.h> using std::cout; using std::endl; void buildRangeIndex(const vector<int64_t> &primaryKeyCol, int64_t primarySize, const int64_t * foreignKeyCol, int64_t foreignSize, RangeIndex rangeIndexCol, string primaryName, string foreignName) { for (int64_t primaryIndex = 0, foreignIndex = 0; primaryIndex < primarySize; primaryIndex++) { if (foreignIndex >= foreignSize || foreignKeyCol[foreignIndex] > primaryKeyCol[primaryIndex]) { rangeIndexCol[primaryIndex].minId = -1; rangeIndexCol[primaryIndex].maxId = -1; } else { // sometimes have mistakes where point to 0 as uninitalized, skip entries for(; foreignKeyCol[foreignIndex] <= 0 && foreignKeyCol[foreignIndex] < primaryKeyCol[primaryIndex]; foreignIndex++); if (foreignKeyCol[foreignIndex] < primaryKeyCol[primaryIndex]) { cout << "bad foreign " << foreignIndex << " val " << foreignKeyCol[foreignIndex] << " for foreign column " << foreignName << " and primary " << primaryIndex << " val " << primaryKeyCol[primaryIndex] << " for primary column " << primaryName << endl; assert(foreignKeyCol[foreignIndex] >= primaryKeyCol[primaryIndex]); } assert(foreignIndex < foreignSize); rangeIndexCol[primaryIndex].minId = foreignIndex; for (; foreignIndex < foreignSize && foreignKeyCol[foreignIndex] == primaryKeyCol[primaryIndex]; foreignIndex++) ; rangeIndexCol[primaryIndex].maxId = foreignIndex - 1; } } } void buildHashmapIndex(const vector<int64_t *> foreignKeyCols, int64_t foreignSize, HashmapIndex hashIndexCol) { for (int64_t foreignIndex = 0; foreignIndex < foreignSize; foreignIndex++) { // collect all primary key entries that are in range the foreign keys int64_t minPrimaryIndex = foreignKeyCols[0][foreignIndex], maxPrimaryIndex = foreignKeyCols[0][foreignIndex]; for (int col = 1; col < foreignKeyCols.size(); col++) { minPrimaryIndex = std::min(minPrimaryIndex, foreignKeyCols[col][foreignIndex]); maxPrimaryIndex = std::max(maxPrimaryIndex, foreignKeyCols[col][foreignIndex]); } // insert into all key cols in range for (int64_t primaryIndex = minPrimaryIndex; primaryIndex <= maxPrimaryIndex; primaryIndex++) { hashIndexCol[primaryIndex].push_back(foreignIndex); } } } void buildIndexes(Equipment & equipment, GameTypes & gameTypes, HitGroups & hitGroups, Games & games, Players & players, Rounds & rounds, Ticks & ticks, PlayerAtTick & playerAtTick, Spotted & spotted, WeaponFire & weaponFire, Kills & kills, Hurt & hurt, Grenades & grenades, Flashed & flashed, GrenadeTrajectories & grenadeTrajectories, Plants & plants, Defusals & defusals, Explosions & explosions) { cout << "building range indexes" << endl; buildRangeIndex(games.id, games.size, rounds.gameId, rounds.size, games.roundsPerGame, "games", "rounds"); buildRangeIndex(games.id, games.size, players.gameId, players.size, games.playersPerGame, "games", "players"); buildRangeIndex(rounds.id, rounds.size, ticks.roundId, ticks.size, rounds.ticksPerRound, "rounds", "ticks"); buildRangeIndex(ticks.id, ticks.size, playerAtTick.tickId, playerAtTick.size, ticks.patPerTick, "ticks", "playerAtTick"); buildRangeIndex(ticks.id, ticks.size, spotted.tickId, spotted.size, ticks.spottedPerTick, "ticks", "spotted"); buildRangeIndex(grenades.id, grenades.size, flashed.grenadeId, flashed.size, grenades.flashedPerGrenade, "grenades", "flashed"); buildRangeIndex(grenades.id, grenades.size, grenadeTrajectories.grenadeId, grenadeTrajectories.size, grenades.trajectoryPerGrenade, "grenades", "grenadeTrajectories"); buildRangeIndex(plants.id, plants.size, defusals.plantId, defusals.size, plants.defusalsPerGrenade, "plants", "defusals"); buildRangeIndex(plants.id, plants.size, explosions.plantId, explosions.size, plants.explosionsPerGrenade, "plants", "explosions"); cout << "building hashmap indexes" << endl; buildHashmapIndex({weaponFire.tickId}, weaponFire.size, ticks.weaponFirePerTick); buildHashmapIndex({kills.tickId}, kills.size, ticks.killsPerTick); buildHashmapIndex({hurt.tickId}, hurt.size, ticks.hurtPerTick); buildHashmapIndex({grenades.throwTick, grenades.activeTick, grenades.expiredTick, grenades.destroyTick}, grenades.size, ticks.grenadesPerTick); buildHashmapIndex({grenades.throwTick}, grenades.size, ticks.grenadesThrowPerTick); buildHashmapIndex({grenades.activeTick}, grenades.size, ticks.grenadesActivePerTick); buildHashmapIndex({grenades.expiredTick}, grenades.size, ticks.grenadesExpiredPerTick); buildHashmapIndex({grenades.activeTick}, grenades.size, ticks.grenadesActivePerTick); buildHashmapIndex({flashed.tickId}, flashed.size, ticks.flashedPerTick); buildHashmapIndex({plants.startTick, plants.endTick}, plants.size, ticks.plantsPerTick); buildHashmapIndex({plants.startTick}, plants.size, ticks.plantsStartPerTick); buildHashmapIndex({plants.endTick}, plants.size, ticks.plantsEndPerTick); buildHashmapIndex({defusals.startTick, defusals.endTick}, defusals.size, ticks.defusalsPerTick); buildHashmapIndex({defusals.startTick}, defusals.size, ticks.defusalsStartPerTick); buildHashmapIndex({defusals.endTick}, defusals.size, ticks.defusalsEndPerTick); buildHashmapIndex({explosions.tickId}, explosions.size, ticks.explosionsPerTick); } void buildGridIndex(const vector<int64_t> &primaryKeyCol, const Vec3 * points, GridIndex &index) { // get min and max values index.minValues = points[0]; index.maxValues = points[0]; for (int64_t i = 0; i < primaryKeyCol.size(); i++) { index.minValues = min(points[i], index.minValues); index.maxValues = max(points[i], index.maxValues); } // compute number of cells index.numCells = index.getCellCoordinates(index.maxValues); index.numCells.x += 1; index.numCells.y += 1; index.numCells.z += 1; size_t totalCells = index.numCells.x * index.numCells.y * index.numCells.z; index.minIdIndex.resize(totalCells, -1); index.numIds.resize(totalCells, 0); // sort ids by coordinates index.sortedIds = primaryKeyCol; GridComparator comparator(index); std::sort(index.sortedIds.begin(), index.sortedIds.end(), comparator); // get ranges within each cell IVec3 curCell{-1, -1, -1}; for (int64_t idIndex = 0; idIndex < index.sortedIds.size(); idIndex++) { const int64_t id = index.sortedIds[idIndex]; IVec3 newCell = index.getCellCoordinates(points[id]); int64_t cellIndex = index.getCellIndex(newCell); if (curCell != newCell) { curCell = newCell; index.minIdIndex[cellIndex] = idIndex; } index.numIds[cellIndex]++; } } void buildAABBIndex(const RangeIndex rangeIndex, int64_t rangeSize, const AABB * aabbCol, AABBIndex aabbIndexCol) { for (int64_t rangeId = 0; rangeId < rangeSize; rangeId++) { bool firstAABB = true; for (int64_t aabbId = rangeIndex[rangeId].minId; aabbId != -1 && aabbId <= rangeIndex[rangeId].maxId; aabbId++) { AABB aabb = aabbCol[aabbId]; if (firstAABB) { firstAABB = false; aabbIndexCol[rangeId] = aabb; } else { aabbIndexCol[rangeId].min = min(aabbIndexCol[rangeId].min, aabb.min); aabbIndexCol[rangeId].max = max(aabbIndexCol[rangeId].max, aabb.max); } } } } void buildCoverIndex(CoverOrigins & origins, CoverEdges & edges) { cout << "building cover indexes" << endl; buildGridIndex(origins.id, origins.origins, origins.originsGrid); buildRangeIndex(origins.id, origins.size, edges.originId, edges.size, origins.coverEdgesPerOrigin, "origins", "edges"); buildAABBIndex(origins.coverEdgesPerOrigin, origins.size, edges.aabbs, origins.coverEdgeBoundsPerOrigin); }
57.164384
171
0.687156
[ "vector" ]
89b5400d2abb88b98cb5c43a5f0bf31aa3c59344
5,816
cpp
C++
Phasma/Code/Systems/PostProcessSystem.cpp
christoskaramou/VulkanMonkey3D
303bcdea9e1650a5bf0d2f937d90316ab46aabbd
[ "MIT" ]
30
2018-12-21T00:55:17.000Z
2020-09-17T16:35:04.000Z
Phasma/Code/Systems/PostProcessSystem.cpp
christoskaramou/PhasmaEngine
303bcdea9e1650a5bf0d2f937d90316ab46aabbd
[ "MIT" ]
2
2019-06-06T17:09:24.000Z
2019-07-14T21:41:34.000Z
Phasma/Code/Systems/PostProcessSystem.cpp
christoskaramou/VulkanMonkey3D
303bcdea9e1650a5bf0d2f937d90316ab46aabbd
[ "MIT" ]
6
2020-02-26T12:16:48.000Z
2020-08-26T08:55:35.000Z
/* Copyright (c) 2018-2021 Christos Karamoustos Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "Systems/PostProcessSystem.h" #include "Systems/RendererSystem.h" #include "Systems/CameraSystem.h" #include "PostProcess/Bloom.h" #include "PostProcess/DOF.h" #include "PostProcess/FXAA.h" #include "PostProcess/MotionBlur.h" #include "PostProcess/SSAO.h" #include "PostProcess/SSR.h" #include "PostProcess/TAA.h" #include "PostProcess/SSGI.h" #if BINDLESS_TESTING #include "PostProcess/Test.h" #endif namespace pe { PostProcessSystem::PostProcessSystem() { } PostProcessSystem::~PostProcessSystem() { } void PostProcessSystem::Init() { Bloom &bloom = *WORLD_ENTITY->CreateComponent<Bloom>(); DOF &dof = *WORLD_ENTITY->CreateComponent<DOF>(); FXAA &fxaa = *WORLD_ENTITY->CreateComponent<FXAA>(); MotionBlur &motionBlur = *WORLD_ENTITY->CreateComponent<MotionBlur>(); SSAO &ssao = *WORLD_ENTITY->CreateComponent<SSAO>(); SSR &ssr = *WORLD_ENTITY->CreateComponent<SSR>(); TAA &taa = *WORLD_ENTITY->CreateComponent<TAA>(); SSGI &ssgi = *WORLD_ENTITY->CreateComponent<SSGI>(); bloom.Init(); dof.Init(); fxaa.Init(); motionBlur.Init(); taa.Init(); ssgi.Init(); auto &renderTargets = CONTEXT->GetSystem<RendererSystem>()->GetRenderTargets(); // Render passes ssao.createRenderPasses(renderTargets); ssr.createRenderPass(renderTargets); fxaa.createRenderPass(renderTargets); taa.createRenderPasses(renderTargets); bloom.createRenderPasses(renderTargets); dof.createRenderPass(renderTargets); motionBlur.createRenderPass(renderTargets); ssgi.createRenderPass(renderTargets); // Frame buffers ssao.createFrameBuffers(renderTargets); ssr.createFrameBuffers(renderTargets); fxaa.createFrameBuffers(renderTargets); taa.createFrameBuffers(renderTargets); bloom.createFrameBuffers(renderTargets); dof.createFrameBuffers(renderTargets); motionBlur.createFrameBuffers(renderTargets); ssgi.createFrameBuffers(renderTargets); // Pipelines ssao.createPipelines(renderTargets); ssr.createPipeline(renderTargets); fxaa.createPipeline(renderTargets); taa.createPipelines(renderTargets); bloom.createPipelines(renderTargets); dof.createPipeline(renderTargets); motionBlur.createPipeline(renderTargets); ssgi.createPipeline(renderTargets); // Descriptor Sets ssao.createUniforms(renderTargets); ssr.createSSRUniforms(renderTargets); fxaa.createUniforms(renderTargets); taa.createUniforms(renderTargets); bloom.createUniforms(renderTargets); dof.createUniforms(renderTargets); motionBlur.createMotionBlurUniforms(renderTargets); ssgi.createUniforms(renderTargets); #if BINDLESS_TESTING Test &test = *WORLD_ENTITY->CreateComponent<Test>(); test.Init(); test.createRenderPass(renderTargets); test.createFrameBuffers(renderTargets); test.createPipeline(renderTargets); test.createUniforms(renderTargets); #endif } void PostProcessSystem::Update(double delta) { SSAO *ssao = WORLD_ENTITY->GetComponent<SSAO>(); SSR *ssr = WORLD_ENTITY->GetComponent<SSR>(); TAA *taa = WORLD_ENTITY->GetComponent<TAA>(); MotionBlur *motionBlur = WORLD_ENTITY->GetComponent<MotionBlur>(); Camera *camera_main = CONTEXT->GetSystem<CameraSystem>()->GetCamera(0); auto updateSSAO = [camera_main, ssao]() { ssao->update(*camera_main); }; auto updateSSR = [camera_main, ssr]() { ssr->update(*camera_main); }; auto updateTAA = [camera_main, taa]() { taa->update(*camera_main); }; auto updateMotionBlur = [camera_main, motionBlur]() { motionBlur->update(*camera_main); }; Queue<Launch::Async>::Request(updateSSAO); Queue<Launch::Async>::Request(updateSSR); Queue<Launch::Async>::Request(updateTAA); Queue<Launch::Async>::Request(updateMotionBlur); } void PostProcessSystem::Destroy() { WORLD_ENTITY->GetComponent<Bloom>()->destroy(); WORLD_ENTITY->GetComponent<DOF>()->destroy(); WORLD_ENTITY->GetComponent<FXAA>()->destroy(); WORLD_ENTITY->GetComponent<MotionBlur>()->destroy(); WORLD_ENTITY->GetComponent<SSAO>()->destroy(); WORLD_ENTITY->GetComponent<SSR>()->destroy(); WORLD_ENTITY->GetComponent<TAA>()->destroy(); WORLD_ENTITY->GetComponent<SSGI>()->destroy(); #if BINDLESS_TESTING WORLD_ENTITY->GetComponent<Test>()->destroy(); #endif } }
36.578616
87
0.691369
[ "render" ]
89b5427a71d0b5734c16b1783b5047ef5523a7f9
2,259
cpp
C++
c++/src/objtools/format/ostream_text_ostream.cpp
OpenHero/gblastn
a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8
[ "MIT" ]
31
2016-12-09T04:56:59.000Z
2021-12-31T17:19:10.000Z
c++/src/objtools/format/ostream_text_ostream.cpp
OpenHero/gblastn
a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8
[ "MIT" ]
6
2017-03-10T17:25:13.000Z
2021-09-22T15:49:49.000Z
c++/src/objtools/format/ostream_text_ostream.cpp
OpenHero/gblastn
a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8
[ "MIT" ]
20
2015-01-04T02:15:17.000Z
2021-12-03T02:31:43.000Z
/* $Id: ostream_text_ostream.cpp 380171 2012-11-08 17:40:34Z rafanovi $ * =========================================================================== * * PUBLIC DOMAIN NOTICE * National Center for Biotechnology Information * * This software/database is a "United States Government Work" under the * terms of the United States Copyright Act. It was written as part of * the author's official duties as a United States Government employee and * thus cannot be copyrighted. This software/database is freely available * to the public for use. The National Library of Medicine and the U.S. * Government have not placed any restriction on its use or reproduction. * * Although all reasonable efforts have been taken to ensure the accuracy * and reliability of the software and data, the NLM and the U.S. * Government do not and cannot warrant the performance or results that * may be obtained by using this software or data. The NLM and the U.S. * Government disclaim all warranties, express or implied, including * warranties of performance, merchantability or fitness for any particular * purpose. * * Please cite the author in any work or product based on this material. * * =========================================================================== * * Author: Mati Shomrat * * * File Description: * */ #include <ncbi_pch.hpp> #include <corelib/ncbistd.hpp> #include <objtools/format/ostream_text_ostream.hpp> BEGIN_NCBI_SCOPE BEGIN_SCOPE(objects) ///////////////////////////////////////////////////////////////////////////// // // TextOStream COStreamTextOStream::COStreamTextOStream(void) : m_Ostream(cout) { } COStreamTextOStream::COStreamTextOStream(CNcbiOstream &os) : m_Ostream(os) { } void COStreamTextOStream::AddParagraph (const list<string>& text, const CSerialObject* obj) { ITERATE(list<string>, line, text) { m_Ostream << *line << '\n'; } // we don't care about the object } void COStreamTextOStream::AddLine( const CTempString& line, const CSerialObject* obj, EAddNewline add_newline ) { m_Ostream << line; if( add_newline == eAddNewline_Yes ) { m_Ostream << '\n'; } } END_SCOPE(objects) END_NCBI_SCOPE
27.54878
77
0.641434
[ "object" ]
89b80ef2444f04f69634243770697461428e7960
1,383
cpp
C++
src/process.cpp
barzanisar/System-Monitor
f0010babcddcb45c6cc192aef5c6a0d409f3c2c2
[ "MIT" ]
null
null
null
src/process.cpp
barzanisar/System-Monitor
f0010babcddcb45c6cc192aef5c6a0d409f3c2c2
[ "MIT" ]
null
null
null
src/process.cpp
barzanisar/System-Monitor
f0010babcddcb45c6cc192aef5c6a0d409f3c2c2
[ "MIT" ]
null
null
null
#include <unistd.h> #include <cctype> #include <iostream> #include <sstream> #include <string> #include <vector> #include "linux_parser.h" #include "process.h" using std::string; using std::to_string; using std::vector; Process::Process(int pid) : pid_(pid), user_(LinuxParser::User(pid)), cmd_(LinuxParser::Command(pid)), cpuUtilization_(0.0) { //UpdateCpuUtilization(); } // Return this process's ID int Process::Pid() const { return pid_; } // Return this process's CPU utilization float Process::CpuUtilization() const { return cpuUtilization_; } // Return this process's CPU utilization void Process::UpdateCpuUtilization() { cpuUtilization_ = (float(LinuxParser::ActiveJiffies(Pid())) / sysconf(_SC_CLK_TCK)) / float(UpTime()); } // Return the command that generated this process string Process::Command() const { return cmd_; } // Return this process's memory utilization string Process::Ram() const { return LinuxParser::Ram(Pid()); } // Return the user (name) that generated this process string Process::User() const { return user_; } // Return the age of this process (in seconds) long int Process::UpTime() const { return LinuxParser::UpTime(Pid()); } // Overload the "less than" comparison operator for Process objects bool Process::operator<(Process const& a) const { return (CpuUtilization() > a.CpuUtilization()); }
26.09434
73
0.711497
[ "vector" ]
89c62f4a95fd7867854859f5ab379aa9fd6e035c
509
hxx
C++
Packages/java/nio/file/PathMatcher.hxx
Brandon-T/Aries
4e8c4f5454e8c7c5cd0611b1b38b5be8186f86ca
[ "MIT" ]
null
null
null
Packages/java/nio/file/PathMatcher.hxx
Brandon-T/Aries
4e8c4f5454e8c7c5cd0611b1b38b5be8186f86ca
[ "MIT" ]
null
null
null
Packages/java/nio/file/PathMatcher.hxx
Brandon-T/Aries
4e8c4f5454e8c7c5cd0611b1b38b5be8186f86ca
[ "MIT" ]
null
null
null
// // PathMatcher.hxx // Aries // // Created by Brandon on 2018-02-25. // Copyright © 2018 Brandon. All rights reserved. // #ifndef PathMatcher_hxx #define PathMatcher_hxx #include "Array.hxx" #include "Object.hxx" namespace java::nio::file { using java::lang::Object; using java::nio::file::Path; class PathMatcher : public Object { public: PathMatcher(JVM* vm, jobject instance); bool matches(Path path); }; } #endif /* PathMatcher_hxx */
15.90625
50
0.624754
[ "object" ]
89cccd3742d12828d408b6b3f40d5fbc7d73c231
2,081
cpp
C++
5. Backtracking/2_Rat_in_Maze_four_direction.cpp
manishhedau/Data-Structure-Algorithm
d45de87aa44d3af18d58fd59491993cf98dbe6fc
[ "MIT" ]
3
2021-02-01T07:56:21.000Z
2021-02-01T11:56:50.000Z
5. Backtracking/2_Rat_in_Maze_four_direction.cpp
manishhedau/Data-Structure-Algorithm
d45de87aa44d3af18d58fd59491993cf98dbe6fc
[ "MIT" ]
null
null
null
5. Backtracking/2_Rat_in_Maze_four_direction.cpp
manishhedau/Data-Structure-Algorithm
d45de87aa44d3af18d58fd59491993cf98dbe6fc
[ "MIT" ]
null
null
null
#include<iostream> #include<vector> using namespace std; int res = 0; bool isValid(vector<vector<int>> &grid, vector<vector<int>> &visied, int n, int i, int j){ return i>=0 && i<n && j>=0 && j<n && grid[i][j]==0 && visied[i][j]==0; } void ratInMaze(vector<vector<int>> &grid, vector<vector<int>> &visied, int n, int i, int j){ // base case if(i==n-1 && j==n-1){ visied[i][j] = 1; for(int a = 0; a<n; a++){ for(int b = 0; b<n; b++){ cout<<visied[a][b]<<" "; } cout<<endl; } cout<<endl; visied[i][j] = 0; res++; return ; } if(i>n || j>n) return; if(grid[i][j]==1) return; visied[i][j] = 1; // up if(isValid(grid, visied, n, i-1, j)){ ratInMaze(grid, visied, n, i-1, j); }// down if(isValid(grid, visied, n, i+1, j)){ ratInMaze(grid, visied, n, i+1, j); }// left if(isValid(grid, visied, n, i, j-1)){ ratInMaze(grid, visied, n, i, j-1); }// right if(isValid(grid, visied, n, i, j+1)){ ratInMaze(grid, visied, n, i, j+1); } visied[i][j] = 0; return; } int main() { int n; cin>>n; vector<vector<int>> grid(n, vector<int> (n, 0)); vector<vector<int>> visied(n, vector<int> (n, 0)); for(int i = 0; i<n; i++){ for(int j = 0; j<n; j++){ cin>>grid[i][j]; } } ratInMaze(grid, visied, n, 0, 0); cout<<"Total paths : "<<res<<endl; return 0; } /* Input :- 7 0 0 1 0 0 1 0 1 0 1 1 0 0 0 0 0 0 0 1 0 1 1 0 1 0 0 0 0 1 0 1 1 0 1 0 1 0 0 0 0 1 0 1 1 1 1 0 0 0 Output :- 1 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 1 1 1 0 1 0 0 1 0 1 0 1 1 1 1 0 1 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 1 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 Total paths : 4 */
18.918182
92
0.471408
[ "vector" ]
89e58b4f906423a201e09de8dd9b998eaf7fbdff
3,207
cpp
C++
src/huffman_encoder.cpp
thousandvoices/memb
edbee1773a762d7fbe5eaebd15b95803b23254a6
[ "MIT" ]
5
2019-02-05T09:46:33.000Z
2019-02-11T12:29:41.000Z
src/huffman_encoder.cpp
thousandvoices/memb
edbee1773a762d7fbe5eaebd15b95803b23254a6
[ "MIT" ]
null
null
null
src/huffman_encoder.cpp
thousandvoices/memb
edbee1773a762d7fbe5eaebd15b95803b23254a6
[ "MIT" ]
1
2019-02-05T16:50:08.000Z
2019-02-05T16:50:08.000Z
#include "huffman_encoder.h" #include "bit_stream.h" #include <queue> namespace memb { namespace { struct TreeNode { uint8_t key; size_t count; std::shared_ptr<TreeNode> left; std::shared_ptr<TreeNode> right; }; struct TreeNodeComparator { bool operator()(std::shared_ptr<TreeNode>& lhs, std::shared_ptr<TreeNode>& rhs) const { return lhs->count > rhs->count; } }; void aggregatePrefixCodes( const std::shared_ptr<TreeNode>& node, size_t length, std::vector<CodeInfo>* codeLengths) { if (node->left && node->right) { aggregatePrefixCodes( node->left, length + 1, codeLengths); aggregatePrefixCodes( node->right, length + 1, codeLengths); } else { codeLengths->push_back({node->key, length}); } } std::vector<CodeInfo> calculatePrefixCodeLengths( const std::unordered_map<uint8_t, size_t>& valueCounts) { std::priority_queue< std::shared_ptr<TreeNode>, std::vector<std::shared_ptr<TreeNode>>, TreeNodeComparator > mergedCounts; for (const auto& count : valueCounts) { mergedCounts.push(std::make_shared<TreeNode>( TreeNode{count.first, count.second, nullptr, nullptr})); } while (mergedCounts.size() > 1) { auto newLeftNode = mergedCounts.top(); mergedCounts.pop(); auto newRightNode = mergedCounts.top(); mergedCounts.pop(); mergedCounts.push(std::make_shared<TreeNode>( TreeNode{0, newLeftNode->count + newRightNode->count, newLeftNode, newRightNode})); } auto rootNode = mergedCounts.top(); std::vector<CodeInfo> codeLengths; aggregatePrefixCodes(rootNode, 0, &codeLengths); return codeLengths; } } // namespace HuffmanEncoder::HuffmanEncoder(const std::unordered_map<uint8_t, size_t>& counts): codeLengths_(calculatePrefixCodeLengths(counts)) { std::sort( codeLengths_.begin(), codeLengths_.end(), [](const CodeInfo& lhs, const CodeInfo& rhs) { return lhs.length < rhs.length; }); codebook_ = createCanonicalPrefixCodes(codeLengths_); } std::vector<uint8_t> HuffmanEncoder::encode(const std::vector<uint8_t>& data) const { BitStream valuesStream; for (const auto& value : data) { valuesStream.push(codebook_.at(value)); } return valuesStream.data(); } HuffmanDecoder HuffmanEncoder::createDecoder() const { std::vector<uint8_t> keys; std::vector<uint32_t> sizeOffsets; size_t currentSize = 0; for (size_t i = 0; i < codeLengths_.size(); ++i) { while (currentSize < codeLengths_[i].length) { ++currentSize; sizeOffsets.push_back(i); } keys.push_back(codeLengths_[i].key); } sizeOffsets.push_back(codeLengths_.size()); return HuffmanDecoder(keys, sizeOffsets); } void HuffmanEncoderBuilder::updateFrequencies(const std::vector<uint8_t>& data) { for (auto value : data) { counts_[value] += 1; } } HuffmanEncoder HuffmanEncoderBuilder::createEncoder() const { return HuffmanEncoder(counts_); } }
24.295455
95
0.638291
[ "vector" ]
88521cf37e4b5bbac1c44fdba13022f3e3e61feb
13,715
cpp
C++
plansys2_problem_expert/src/plansys2_problem_expert/Utils.cpp
jonatanolofsson/ros2_planning_system
135f99cd06f6daa86d5815bd7dcc6595d1ca0160
[ "Apache-2.0" ]
213
2019-12-08T13:34:31.000Z
2022-03-31T18:11:57.000Z
plansys2_problem_expert/src/plansys2_problem_expert/Utils.cpp
jonatanolofsson/ros2_planning_system
135f99cd06f6daa86d5815bd7dcc6595d1ca0160
[ "Apache-2.0" ]
159
2019-12-07T07:20:56.000Z
2022-03-31T16:18:14.000Z
plansys2_problem_expert/src/plansys2_problem_expert/Utils.cpp
jonatanolofsson/ros2_planning_system
135f99cd06f6daa86d5815bd7dcc6595d1ca0160
[ "Apache-2.0" ]
60
2019-12-08T13:34:34.000Z
2022-03-31T10:58:15.000Z
// Copyright 2019 Intelligent Robotics Lab // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <tuple> #include <memory> #include <string> #include <vector> #include <set> #include <map> #include <utility> #include "plansys2_problem_expert/Utils.hpp" #include "plansys2_pddl_parser/Utils.h" namespace plansys2 { std::tuple<bool, bool, double> evaluate( const plansys2_msgs::msg::Tree & tree, std::shared_ptr<plansys2::ProblemExpertClient> problem_client, std::vector<plansys2::Predicate> & predicates, std::vector<plansys2::Function> & functions, bool apply, bool use_state, uint8_t node_id, bool negate) { if (tree.nodes.empty()) { // No expression return std::make_tuple(true, true, 0); } switch (tree.nodes[node_id].node_type) { case plansys2_msgs::msg::Node::AND: { bool success = true; bool truth_value = true; for (auto & child_id : tree.nodes[node_id].children) { std::tuple<bool, bool, double> result = evaluate( tree, problem_client, predicates, functions, apply, use_state, child_id, negate); success = success && std::get<0>(result); truth_value = truth_value && std::get<1>(result); } return std::make_tuple(success, truth_value, 0); } case plansys2_msgs::msg::Node::OR: { bool success = true; bool truth_value = false; for (auto & child_id : tree.nodes[node_id].children) { std::tuple<bool, bool, double> result = evaluate( tree, problem_client, predicates, functions, apply, use_state, child_id, negate); success = success && std::get<0>(result); truth_value = truth_value || std::get<1>(result); } return std::make_tuple(success, truth_value, 0); } case plansys2_msgs::msg::Node::NOT: { return evaluate( tree, problem_client, predicates, functions, apply, use_state, tree.nodes[node_id].children[0], !negate); } case plansys2_msgs::msg::Node::PREDICATE: { bool success = true; bool value = true; if (apply) { if (use_state) { auto it = std::find_if( predicates.begin(), predicates.end(), std::bind( &parser::pddl::checkNodeEquality, std::placeholders::_1, tree.nodes[node_id])); if (negate) { if (it != predicates.end()) { predicates.erase(it); } value = false; } else { if (it == predicates.end()) { predicates.push_back(tree.nodes[node_id]); } } } else { if (negate) { success = success && problem_client->removePredicate(tree.nodes[node_id]); value = false; } else { success = success && problem_client->addPredicate(tree.nodes[node_id]); } } } else { // negate | exist | output // F | F | F // F | T | T // T | F | T // T | T | F if (use_state) { value = negate ^ (std::find_if( predicates.begin(), predicates.end(), std::bind( &parser::pddl::checkNodeEquality, std::placeholders::_1, tree.nodes[node_id])) != predicates.end()); } else { value = negate ^ problem_client->existPredicate(tree.nodes[node_id]); } } return std::make_tuple(success, value, 0); } case plansys2_msgs::msg::Node::FUNCTION: { bool success = true; double value = 0; if (use_state) { auto it = std::find_if( functions.begin(), functions.end(), std::bind( &parser::pddl::checkNodeEquality, std::placeholders::_1, tree.nodes[node_id])); if (it != functions.end()) { value = it->value; } else { success = false; } } else { std::optional<plansys2_msgs::msg::Node> func = problem_client->getFunction(parser::pddl::toString(tree, node_id)); if (func.has_value()) { value = func.value().value; } else { success = false; } } return std::make_tuple(success, false, value); } case plansys2_msgs::msg::Node::EXPRESSION: { std::tuple<bool, bool, double> left = evaluate( tree, problem_client, predicates, functions, apply, use_state, tree.nodes[node_id].children[0], negate); std::tuple<bool, bool, double> right = evaluate( tree, problem_client, predicates, functions, apply, use_state, tree.nodes[node_id].children[1], negate); if (!std::get<0>(left) || !std::get<0>(right)) { return std::make_tuple(false, false, 0); } switch (tree.nodes[node_id].expression_type) { case plansys2_msgs::msg::Node::COMP_GE: if (std::get<2>(left) >= std::get<2>(right)) { return std::make_tuple(true, true, 0); } else { return std::make_tuple(true, false, 0); } break; case plansys2_msgs::msg::Node::COMP_GT: if (std::get<2>(left) > std::get<2>(right)) { return std::make_tuple(true, true, 0); } else { return std::make_tuple(true, false, 0); } break; case plansys2_msgs::msg::Node::COMP_LE: if (std::get<2>(left) <= std::get<2>(right)) { return std::make_tuple(true, true, 0); } else { return std::make_tuple(true, false, 0); } break; case plansys2_msgs::msg::Node::COMP_LT: if (std::get<2>(left) < std::get<2>(right)) { return std::make_tuple(true, true, 0); } else { return std::make_tuple(true, false, 0); } break; case plansys2_msgs::msg::Node::ARITH_MULT: return std::make_tuple(true, false, std::get<2>(left) * std::get<2>(right)); break; case plansys2_msgs::msg::Node::ARITH_DIV: if (std::abs(std::get<2>(right)) > 1e-5) { return std::make_tuple(true, false, std::get<2>(left) / std::get<2>(right)); } else { // Division by zero not allowed. return std::make_tuple(false, false, 0); } break; case plansys2_msgs::msg::Node::ARITH_ADD: return std::make_tuple(true, false, std::get<2>(left) + std::get<2>(right)); break; case plansys2_msgs::msg::Node::ARITH_SUB: return std::make_tuple(true, false, std::get<2>(left) - std::get<2>(right)); break; default: break; } return std::make_tuple(false, false, 0); } case plansys2_msgs::msg::Node::FUNCTION_MODIFIER: { std::tuple<bool, bool, double> left = evaluate( tree, problem_client, predicates, functions, apply, use_state, tree.nodes[node_id].children[0], negate); std::tuple<bool, bool, double> right = evaluate( tree, problem_client, predicates, functions, apply, use_state, tree.nodes[node_id].children[1], negate); if (!std::get<0>(left) || !std::get<0>(right)) { return std::make_tuple(false, false, 0); } bool success = true; double value = 0; switch (tree.nodes[node_id].modifier_type) { case plansys2_msgs::msg::Node::ASSIGN: value = std::get<2>(right); break; case plansys2_msgs::msg::Node::INCREASE: value = std::get<2>(left) + std::get<2>(right); break; case plansys2_msgs::msg::Node::DECREASE: value = std::get<2>(left) - std::get<2>(right); break; case plansys2_msgs::msg::Node::SCALE_UP: value = std::get<2>(left) * std::get<2>(right); break; case plansys2_msgs::msg::Node::SCALE_DOWN: // Division by zero not allowed. if (std::abs(std::get<2>(right)) > 1e-5) { value = std::get<2>(left) / std::get<2>(right); } else { success = false; } break; default: success = false; break; } if (success && apply) { uint8_t left_id = tree.nodes[node_id].children[0]; if (use_state) { auto it = std::find_if( functions.begin(), functions.end(), std::bind( &parser::pddl::checkNodeEquality, std::placeholders::_1, tree.nodes[left_id])); if (it != functions.end()) { it->value = value; } else { success = false; } } else { std::stringstream ss; ss << "(= " << parser::pddl::toString(tree, left_id) << " " << value << ")"; problem_client->updateFunction(parser::pddl::fromStringFunction(ss.str())); } } return std::make_tuple(success, false, value); } case plansys2_msgs::msg::Node::NUMBER: { return std::make_tuple(true, true, tree.nodes[node_id].value); } default: std::cerr << "evaluate: Error parsing expresion [" << parser::pddl::toString(tree, node_id) << "]" << std::endl; } return std::make_tuple(false, false, 0); } std::tuple<bool, bool, double> evaluate( const plansys2_msgs::msg::Tree & tree, std::shared_ptr<plansys2::ProblemExpertClient> problem_client, bool apply, uint32_t node_id) { std::vector<plansys2::Predicate> predicates; std::vector<plansys2::Function> functions; return evaluate(tree, problem_client, predicates, functions, apply, false, node_id); } std::tuple<bool, bool, double> evaluate( const plansys2_msgs::msg::Tree & tree, std::vector<plansys2::Predicate> & predicates, std::vector<plansys2::Function> & functions, bool apply, uint32_t node_id) { std::shared_ptr<plansys2::ProblemExpertClient> problem_client; return evaluate(tree, problem_client, predicates, functions, apply, true, node_id); } bool check( const plansys2_msgs::msg::Tree & tree, std::shared_ptr<plansys2::ProblemExpertClient> problem_client, uint32_t node_id) { std::tuple<bool, bool, double> ret = evaluate(tree, problem_client, false, node_id); return std::get<1>(ret); } bool check( const plansys2_msgs::msg::Tree & tree, std::vector<plansys2::Predicate> & predicates, std::vector<plansys2::Function> & functions, uint32_t node_id) { std::tuple<bool, bool, double> ret = evaluate(tree, predicates, functions, false, node_id); return std::get<1>(ret); } bool apply( const plansys2_msgs::msg::Tree & tree, std::shared_ptr<plansys2::ProblemExpertClient> problem_client, uint32_t node_id) { std::tuple<bool, bool, double> ret = evaluate(tree, problem_client, true, node_id); return std::get<0>(ret); } bool apply( const plansys2_msgs::msg::Tree & tree, std::vector<plansys2::Predicate> & predicates, std::vector<plansys2::Function> & functions, uint32_t node_id) { std::tuple<bool, bool, double> ret = evaluate(tree, predicates, functions, true, node_id); return std::get<0>(ret); } std::pair<std::string, int> parse_action(const std::string & input) { std::string action = parser::pddl::getReducedString(input); int time = -1; size_t delim = action.find(":"); if (delim != std::string::npos) { time = std::stoi(action.substr(delim + 1, action.length() - delim - 1)); action.erase(action.begin() + delim, action.end()); } action.erase(0, 1); // remove initial ( action.pop_back(); // remove last ) return std::make_pair(action, time); } std::string get_action_expression(const std::string & input) { auto action = parse_action(input); return action.first; } int get_action_time(const std::string & input) { auto action = parse_action(input); return action.second; } std::string get_action_name(const std::string & input) { auto expr = get_action_expression(input); size_t delim = expr.find(" "); return expr.substr(0, delim); } std::vector<std::string> get_action_params(const std::string & input) { std::vector<std::string> ret; auto expr = get_action_expression(input); size_t delim = expr.find(" "); if (delim != std::string::npos) { expr.erase(expr.begin(), expr.begin() + delim + 1); } size_t start = 0, end = 0; while (end != std::string::npos) { end = expr.find(" ", start); auto param = expr.substr( start, (end == std::string::npos) ? std::string::npos : end - start); ret.push_back(param); start = ((end > (std::string::npos - 1)) ? std::string::npos : end + 1); } return ret; } } // namespace plansys2
31.969697
93
0.565512
[ "vector" ]
8859efe74049bdbadf7cce8781b545c7b9ef11ee
998
hpp
C++
ConStorm/include/cons/files/load.hpp
drake200120xx/ConStorm
bfc47b6424154e8258d375d0a5eaff687d0cad27
[ "Apache-2.0" ]
null
null
null
ConStorm/include/cons/files/load.hpp
drake200120xx/ConStorm
bfc47b6424154e8258d375d0a5eaff687d0cad27
[ "Apache-2.0" ]
null
null
null
ConStorm/include/cons/files/load.hpp
drake200120xx/ConStorm
bfc47b6424154e8258d375d0a5eaff687d0cad27
[ "Apache-2.0" ]
null
null
null
/* Code by Drake Johnson Defines the 'FilesLoad' class, which is a wrapper for multi-threaded file loading. */ #ifndef CONS_FILE_LOAD_HEADER__ #define CONS_FILE_LOAD_HEADER__ #ifdef _MSC_VER # pragma once #endif // _MSC_VER #include "file.hpp" #include <future> namespace cons { /** Loads a vector of files async. File objects are stored in a vector of shared pointers and can be retrieved using 'get_files()'. */ class FilesLoad { public: using file_vec = std::vector<File>; explicit FilesLoad( const std::vector<std::filesystem::path>& file_paths, File::openmode open_mode = File::openmode::input_and_output); explicit FilesLoad( const std::vector<std::string>& file_paths, File::openmode open_mode = File::openmode::input_and_output); ~FilesLoad() = default; [[nodiscard]] file_vec get_files() const { return m_files; } private: file_vec m_files; std::vector<std::future<void>> m_futures; }; } // namespace cons #endif // !CONS_FILE_LOAD_HEADER__
22.177778
71
0.725451
[ "vector" ]
886754ba54ffebbf2a6effd37040e97db696e139
4,817
cc
C++
src/conf/fill_configuration.cc
tic-toc/caesar.sdd
fa152df96bde9d7babbdffbd5b082d53b3f25e0c
[ "BSD-2-Clause" ]
1
2020-04-21T20:49:11.000Z
2020-04-21T20:49:11.000Z
src/conf/fill_configuration.cc
tic-toc/caesar.sdd
fa152df96bde9d7babbdffbd5b082d53b3f25e0c
[ "BSD-2-Clause" ]
4
2017-11-14T10:10:44.000Z
2019-08-09T22:01:22.000Z
src/conf/fill_configuration.cc
tic-toc/caesar.sdd
fa152df96bde9d7babbdffbd5b082d53b3f25e0c
[ "BSD-2-Clause" ]
1
2019-08-09T20:14:33.000Z
2019-08-09T20:14:33.000Z
#include <iostream> #include <string> #pragma GCC diagnostic push #if defined(__GNUC__) && !defined(__clang__) # pragma GCC diagnostic ignored "-Wunused-local-typedefs" #endif #include <boost/program_options.hpp> #pragma GCC diagnostic pop #include "conf/configuration.hh" #include "conf/fill_configuration.hh" namespace caesar { namespace conf { /*------------------------------------------------------------------------------------------------*/ namespace po = boost::program_options; const std::string version = "Caesar.SDD (built " + std::string(__DATE__) + " " + std::string(__TIME__) + ")"; /*------------------------------------------------------------------------------------------------*/ // General options constexpr auto help_str = "help"; constexpr auto version_str = "version"; // Order options constexpr auto order_show_str = "order-show"; constexpr auto order_force_str = "order-force"; constexpr auto order_force_iterations_str = "order-force-iterations"; // Petri net options constexpr auto check_safe_net_str = "check"; // Statistics options constexpr auto show_nb_states_str = "show-nb-states"; constexpr auto show_time_str = "show-time"; // CADP options constexpr auto dead_str = "dead-transitions"; constexpr auto unit_str = "concurrent-units"; boost::optional<caesar_configuration> fill_configuration(int argc, char** argv) { caesar_configuration conf; po::options_description general_options("General options"); general_options.add_options() ( help_str , "Show this help") ( version_str , "Show version"); po::options_description order_options("Order options"); order_options.add_options() (order_show_str , "Show the order") (order_force_str , "Use the FORCE ordering heuristic") (order_force_iterations_str , po::value<unsigned int>()->default_value(100) , "Number of FORCE iterations") ; po::options_description pn_options("Petri net options"); pn_options.add_options() (check_safe_net_str , "Interrupt computation if a marking > 1") ; po::options_description stats_options("Statistics options"); stats_options.add_options() (show_nb_states_str , "Show the number of states") (show_time_str , "Show miscellaneous execution times") ; po::options_description cadp_options("CADP options"); cadp_options.add_options() (dead_str , "Compute dead transitions") (unit_str , "Compute concurrent units"); po::options_description hidden_options("Hidden options"); hidden_options.add_options() ("input-file", po::value<std::string>(), "The Petri net file to analyse"); po::positional_options_description p; p.add("input-file", 1); po::options_description cmdline_options; cmdline_options .add(general_options) .add(order_options) .add(pn_options) .add(cadp_options) .add(stats_options) .add(hidden_options); po::variables_map vm; po::parsed_options parsed = po::command_line_parser(argc, argv) .options(cmdline_options) .style (po::command_line_style::default_style) .positional(p) .allow_unregistered() .run(); po::store(parsed, vm); po::notify(vm); std::vector<std::string> unrecognized = po::collect_unrecognized(parsed.options,po::exclude_positional); if (vm.count(help_str) or unrecognized.size() > 0) { std::cout << version << std::endl; std::cout << "Usage: " << argv[0] << " [options] file " << std::endl << std::endl; std::cout << general_options << std::endl; std::cout << order_options << std::endl; std::cout << pn_options << std::endl; std::cout << cadp_options << std::endl; std::cout << stats_options << std::endl; return boost::optional<caesar_configuration>(); } if (vm.count("version")) { std::cout << version << std::endl; return boost::optional<caesar_configuration>(); } conf.read_stdin = (not vm.count("input-file") or vm["input-file"].as<std::string>() == "-"); if (not conf.read_stdin) { conf.file_name = vm["input-file"].as<std::string>(); } conf.show_nb_states = vm.count(show_nb_states_str); conf.order_show = vm.count(order_show_str); conf.order_force = vm.count(order_force_str); conf.show_time = vm.count(show_time_str); conf.compute_dead_transitions = vm.count(dead_str); conf.compute_concurrent_units = vm.count(unit_str); conf.check_one_safe = vm.count(check_safe_net_str); return conf; } /*------------------------------------------------------------------------------------------------*/ }} // namespace caesar::conf
33.22069
100
0.621756
[ "vector" ]
8869812f6700accf4000e4ff2cc2121995015a9f
4,069
cpp
C++
Samples/Omni/Source/DynamicSprites.cpp
Gravecat/BearLibTerminal
64fec04101350a99a71db872c513e17bdd2cc94d
[ "MIT" ]
80
2020-06-17T15:26:27.000Z
2022-03-29T11:17:01.000Z
Samples/Omni/Source/DynamicSprites.cpp
Gravecat/BearLibTerminal
64fec04101350a99a71db872c513e17bdd2cc94d
[ "MIT" ]
11
2020-07-19T15:22:06.000Z
2022-03-31T03:33:13.000Z
Samples/Omni/Source/DynamicSprites.cpp
Gravecat/BearLibTerminal
64fec04101350a99a71db872c513e17bdd2cc94d
[ "MIT" ]
18
2020-09-16T01:29:46.000Z
2022-03-27T18:48:09.000Z
/* * DynamicSprites.cpp * * Created on: Dec 2, 2013 * Author: cfyz */ #include "Common.hpp" #include <vector> #include <stdlib.h> #include <time.h> #include <string.h> #include <string> #include <map> std::vector<std::wstring> map = { L" ", L" ------ ", // - Wall L" |....| ############ ", // # Unlit hallway L" |....| # # ", // . Lit area L" |.$..+######## # ", // $ Some quantity of gold L" |....| # ---+--- ", // + A door L" ------ # |.....| ", // | Wall L" # |.!...| ", // ! A magic potion L" # |.....| ", // L" # |.....| ", // @ The adventurer L" ---- # |.....| ", // L" |..| #######+.....| ", // D A red dragon L" |..+### # |.....| ", // < Stairs to a higher level L" ---- # # |.?...| ", // ? A magic scroll L" ###### ------- ", L" " }; struct symbol_t { color_t color; int tile; }; std::map<wchar_t, symbol_t> palette = { {L'-', {0xFFAAAAAA, 8}}, {L'|', {0xFFAAAAAA, 8}}, {L'.', {0xFF808080, 20}}, {L'#', {0xFF808080, 20}}, {L'+', {0xFFFF8000, 21}}, {L'!', {0xFFFF00FF, 22}}, {L'D', {0xFFFF0000, 6}}, {L'?', {0xFF008000, 23}}, {L'$', {0xFFFFFF00, 29}}, {L'<', {0xFFFFFFFF, 9}} }; void TestDynamicSprites() { terminal_set("window.title='Omni: dynamic sprites'"); terminal_set("U+E000: ../Media/Tiles.png, size=32x32, align=top-left"); int map_width = map[0].length(); int map_height = map.size(); std::vector<color_t> minimap(map_width*map_height, 0); int x0 = 0; int y0 = 0; int view_height = 10; int view_width = 14; int minimap_scale = 4; int panel_width = (terminal_state(TK_WIDTH) - view_width*4 - 1)*terminal_state(TK_CELL_WIDTH); int margin = (panel_width - map_width*minimap_scale)/2; auto DrawMap = [&] { terminal_color("white"); for (int y=y0; y<y0+view_height; y++) { for (int x=x0; x<x0+view_width; x++) { wchar_t code = map[y][x]; if (!palette.count(code)) continue; symbol_t s = palette[code]; terminal_put((x-x0)*4, (y-y0)*2, 0xE000+s.tile); } } }; auto BlendColors = [](color_t one, color_t two) -> color_t { uint8_t* pone = (uint8_t*)&one; uint8_t* ptwo = (uint8_t*)&two; float f = ptwo[3] / 255.0f; for (int i=0; i<3; i++) pone[i] = pone[i]*(1.0f-f) + ptwo[i]*f; return one; }; auto MakeMinimap = [&] { for (int y=0; y<map_height; y++) { for (int x=0; x<map_width && x<map[y].length(); x++) { wchar_t code = map[y][x]; color_t color = palette.count(code)? palette[code].color: 0xFF000000; minimap[y*map_width+x] = color; } } for (int y=y0; y<y0+view_height; y++) { for (int x=x0; x<x0+view_width; x++) { color_t& dst = minimap[y*map_width+x]; dst = BlendColors(dst, 0x60FFFFFF); } } terminal_setf ( "U+E100: %#p, raw-size=%dx%d, resize=%dx%d, resize-filter=nearest", (void*)minimap.data(), map_width, map_height, map_width*4, map_height*4 ); }; while (true) { terminal_clear(); DrawMap(); terminal_color("light gray"); for (int x=0; x<80; x++) terminal_put(x, view_height*2, 0x2580); for (int y=0; y<view_height*2; y++) terminal_put(view_width*4, y, 0x2588); MakeMinimap(); terminal_color("white"); terminal_put_ext(view_width*4+1, 0, margin, margin, 0xE100, nullptr); terminal_print(1, view_height*2+1, "[color=orange]Tip:[/color] use arrow keys to move viewport over the map"); terminal_refresh(); int key = terminal_read(); if (key == TK_CLOSE || key == TK_ESCAPE) { break; } else if (key == TK_RIGHT && (x0 < map_width-view_width)) { x0 += 1; } else if (key == TK_LEFT && x0 > 0) { x0 -= 1; } else if (key == TK_DOWN && (y0 < map_height-view_height)) { y0 += 1; } else if (key == TK_UP && y0 > 0) { y0 -= 1; } } terminal_set("U+E000: none; U+E100: none;"); }
24.076923
112
0.509708
[ "vector" ]
886dc4a1bb5833129617766f6d939cf2411095e8
2,850
cpp
C++
src/Train.cpp
V0XNIHILI/lab3-cnn
b5b72477b17390c3f9a6f5e3f2a15d067ff9f1ce
[ "W3C" ]
2
2019-11-28T17:11:42.000Z
2020-09-30T16:23:34.000Z
src/Train.cpp
V0XNIHILI/lab3-cnn
b5b72477b17390c3f9a6f5e3f2a15d067ff9f1ce
[ "W3C" ]
null
null
null
src/Train.cpp
V0XNIHILI/lab3-cnn
b5b72477b17390c3f9a6f5e3f2a15d067ff9f1ce
[ "W3C" ]
5
2018-10-05T13:41:42.000Z
2021-10-03T19:21:10.000Z
#include "Train.h" #include "utils/io.h" std::vector<case_t> readTrainingData() { std::vector<case_t> cases{}; auto train_image = readFile("../train-images.idx3-ubyte"); auto train_labels = readFile("../train-labels.idx1-ubyte"); // Swap endianness of case count: uint32_t case_count = bswap_32(*(uint32_t *) (train_image.data() + sizeof(uint32_t))); // Convert each image to a test case for (int i = 0; i < case_count; i++) { case_t c{tensor_t<float>(img_dim, img_dim, 1), tensor_t<float>(num_digits, 1, 1)}; // Actual images start at offset 16 uint8_t *img = train_image.data() + 16 + i * (img_dim * img_dim); // Actual labels start at offset 8 uint8_t *label = train_labels.data() + 8 + i; // Normalize the pixel intensity values to a floating point number between 0 and 1. for (int x = 0; x < img_dim; x++) { for (int y = 0; y < img_dim; y++) { c.data(x, y, 0) = img[x + y * img_dim] / 255.f; } } // Convert the labels to a floating point number at the correct digit index for (int b = 0; b < num_digits; b++) { c.out(b, 0, 0) = *label == b ? 1.0f : 0.0f; } cases.push_back(c); } return cases; } float trainIterate(std::vector<layer_t *> &layers, tensor_t<float> &train_tensor, tensor_t<float> &expected_output) { // Activate each layer with the training tensor as input for (int i = 0; i < layers.size(); i++) { if (i == 0) activate(layers[i], train_tensor); else activate(layers[i], layers[i - 1]->out); } // Check the difference with the label / expected output tensor_t<float> grads = layers.back()->out - expected_output; // Calculate the gradients for (ssize_t i = layers.size() - 1; i >= 0; i--) { if (i == layers.size() - 1) calc_grads(layers[i], grads); else calc_grads(layers[i], layers[i + 1]->grads_in); } // Potentially update the weights for (auto &layer : layers) { fix_weights(layer); } // Calculate the error float err = 0; for (int i = 0; i < grads.size.x * grads.size.y * grads.size.z; i++) { float f = expected_output.data[i]; if (f > 0.5) err += abs(grads.data[i]); } return err * 100; } float trainCNN(std::vector<layer_t *> &layers, std::vector<case_t> &cases) { float total_error = 0.0f; // Iterate over all the test cases int count = 0; for (case_t &c : cases) { // Train the model with a new test case, and retreive the new error. float xerr = trainIterate(layers, c.data, c.out); // Accumulate the total error for all test cases. total_error += xerr; // Once every 6000 training iterations, report the total error. count++; if (count % 6000 == 0) { std::cout << "Case " << std::setw(5) << count << ". Err=" << total_error / count << std::endl; } } return total_error; }
30.319149
117
0.612632
[ "vector", "model" ]
886f9e366fab1798730382dffd37382fc2bdab6d
11,092
cpp
C++
blast/src/objtools/readers/psl_data.cpp
mycolab/ncbi-blast
e59746cec78044d2bf6d65de644717c42f80b098
[ "Apache-2.0" ]
null
null
null
blast/src/objtools/readers/psl_data.cpp
mycolab/ncbi-blast
e59746cec78044d2bf6d65de644717c42f80b098
[ "Apache-2.0" ]
null
null
null
blast/src/objtools/readers/psl_data.cpp
mycolab/ncbi-blast
e59746cec78044d2bf6d65de644717c42f80b098
[ "Apache-2.0" ]
null
null
null
/* $Id: psl_data.cpp 632526 2021-06-02 17:25:01Z ivanov $ * =========================================================================== * * PUBLIC DOMAIN NOTICE * National Center for Biotechnology Information * * This software/database is a "United States Government Work" under the * terms of the United States Copyright Act. It was written as part of * the author's official duties as a United States Government employee and * thus cannot be copyrighted. This software/database is freely available * to the public for use. The National Library of Medicine and the U.S. * Government have not placed any restriction on its use or reproduction. * * Although all reasonable efforts have been taken to ensure the accuracy * and reliability of the software and data, the NLM and the U.S. * Government do not and cannot warrant the performance or results that * may be obtained by using this software or data. The NLM and the U.S. * Government disclaim all warranties, express or implied, including * warranties of performance, merchantability or fitness for any particular * purpose. * * Please cite the author in any work or product based on this material. * * =========================================================================== * * Author: Frank Ludwig * * File Description: * PSL data handling * */ #include <ncbi_pch.hpp> #include <corelib/ncbistd.hpp> #include <objects/seq/Seq_annot.hpp> #include <objects/seqalign/Seq_align.hpp> #include <objects/seqalign/Dense_seg.hpp> #include <objects/seqalign/Score.hpp> #include <objtools/readers/read_util.hpp> #include "psl_data.hpp" BEGIN_NCBI_SCOPE BEGIN_objects_SCOPE // namespace ncbi::objects:: // ---------------------------------------------------------------------------- CPslData::CPslData( CReaderMessageHandler* pEL): mpEL(pEL) // ---------------------------------------------------------------------------- { xReset(); } // ---------------------------------------------------------------------------- void CPslData::xReset() // ---------------------------------------------------------------------------- { mMatches = mMisMatches = mRepMatches = mCountN = 0; mNumInsertQ = mBaseInsertQ = 0; mNumInsertT = mBaseInsertT = 0; mStrandT = eNa_strand_unknown; mNameQ.clear(); mSizeQ = mStartQ = mEndQ = 0; mNameT.clear(); mSizeT = mStartT = mEndT = 0; mBlockCount = 0; mBlockSizes.clear(); mBlockStartsQ.clear(); mBlockStartsT.clear(); } // ---------------------------------------------------------------------------- void CPslData::Initialize( const CPslReader::TReaderLine& readerLine) // // https://genome.ucsc.edu/FAQ/FAQformat.html#format2 // ---------------------------------------------------------------------------- { const int PSL_COLUMN_COUNT(21); vector<string> columns; NStr::Split(readerLine.mData, "\t", columns, NStr::fSplit_Tokenize); if (-1 == mFirstDataColumn) { auto columnCount = columns.size(); if (columnCount != PSL_COLUMN_COUNT && columnCount != PSL_COLUMN_COUNT+1) { throw CReaderMessage( eDiag_Error, readerLine.mLine, "PSL Error: Record has invalid column count."); } mFirstDataColumn = static_cast<int>(columnCount - PSL_COLUMN_COUNT); } xReset(); mMatches = NStr::StringToInt(columns[mFirstDataColumn]); mMisMatches = NStr::StringToInt(columns[mFirstDataColumn + 1]); mRepMatches = NStr::StringToInt(columns[mFirstDataColumn + 2]); mCountN = NStr::StringToInt(columns[mFirstDataColumn + 3]); mNumInsertQ = NStr::StringToInt(columns[mFirstDataColumn + 4]); mBaseInsertQ = NStr::StringToInt(columns[mFirstDataColumn + 5]); mNumInsertT = NStr::StringToInt(columns[mFirstDataColumn + 6]); mBaseInsertT = NStr::StringToInt(columns[mFirstDataColumn + 7]); string strand = columns[mFirstDataColumn + 8]; mStrandT = (strand == "-" ? eNa_strand_minus : eNa_strand_plus); mNameQ = columns[mFirstDataColumn + 9]; mSizeQ = NStr::StringToInt(columns[mFirstDataColumn + 10]); mStartQ = NStr::StringToInt(columns[mFirstDataColumn + 11]); mEndQ = NStr::StringToInt(columns[mFirstDataColumn + 12]); mNameT = columns[mFirstDataColumn + 13]; mSizeT = NStr::StringToInt(columns[mFirstDataColumn + 14]); mStartT = NStr::StringToInt(columns[mFirstDataColumn + 15]); mEndT = NStr::StringToInt(columns[mFirstDataColumn + 16]); mBlockCount = NStr::StringToInt(columns[mFirstDataColumn + 17]); mBlockSizes.reserve(mBlockCount); mBlockStartsQ.reserve(mBlockCount); mBlockStartsQ.reserve(mBlockCount); vector<string> values; values.reserve(mBlockCount); NStr::Split(columns[mFirstDataColumn + 18], ",", values, NStr::fSplit_Tokenize); for (const auto& value: values) { mBlockSizes.push_back(NStr::StringToInt(value)); } values.clear(); NStr::Split(columns[mFirstDataColumn + 19], ",", values, NStr::fSplit_Tokenize); for (const auto& value: values) { mBlockStartsQ.push_back(NStr::StringToInt(value)); } values.clear(); NStr::Split(columns[mFirstDataColumn + 20], ",", values, NStr::fSplit_Tokenize); for (const auto& value: values) { mBlockStartsT.push_back(NStr::StringToInt(value)); } // some basic validation: if (mBlockCount != mBlockSizes.size()) { throw CReaderMessage( eDiag_Error, readerLine.mLine, "PSL Error: Number of blockSizes does not match blockCount."); } if (mBlockCount != mBlockStartsQ.size()) { throw CReaderMessage( eDiag_Error, readerLine.mLine, "PSL Error: Number of blockStartsQ does not match blockCount."); } if (mBlockCount != mBlockStartsT.size()) { throw CReaderMessage( eDiag_Error, readerLine.mLine, "PSL Error: Number of blockStartsT does not match blockCount."); } } // ---------------------------------------------------------------------------- void CPslData::Dump( ostream& ostr) // ---------------------------------------------------------------------------- { string strand = (mStrandT == eNa_strand_minus ? "-" : "+"); string nameQ = (mNameQ.empty() ? "." : mNameQ); string nameT = (mNameT.empty() ? "." : mNameT); ostr << "matches : " << mMatches <<endl; ostr << "misMatches : " << mMisMatches <<endl; ostr << "repMatches : " << mRepMatches <<endl; ostr << "nCount : " << mCountN <<endl; ostr << "qNumInsert : " << mNumInsertQ <<endl; ostr << "qBaseInsert : " << mBaseInsertQ <<endl; ostr << "tNumInsert : " << mNumInsertT <<endl; ostr << "tBaseInsert : " << mBaseInsertT <<endl; ostr << "strand : " << strand << endl; ostr << "qName : " << nameQ << endl; ostr << "qSize : " << mSizeQ << endl; ostr << "qStart : " << mStartQ << endl; ostr << "qEnd : " << mEndQ << endl; ostr << "tName : " << nameT << endl; ostr << "tSize : " << mSizeT << endl; ostr << "tStart : " << mStartQ << endl; ostr << "tEnd : " << mEndT << endl; ostr << "blockCount : " << mBlockCount << endl; if (mBlockCount) { string blockSizes = NStr::JoinNumeric(mBlockSizes.begin(), mBlockSizes.end(), ","); string blockStartsQ = NStr::JoinNumeric(mBlockStartsQ.begin(), mBlockStartsQ.end(), ","); string blockStartsT = NStr::JoinNumeric(mBlockStartsT.begin(), mBlockStartsT.end(), ","); ostr << "blockSizes : " << blockSizes << endl; ostr << "blockStartsQ : " << blockStartsQ << endl; ostr << "blockStartsT : " << blockStartsT << endl; } ostr << endl; if (mBlockCount < 5) { cerr << ""; } } // ---------------------------------------------------------------------------- void CPslData::ExportToSeqAlign( CPslReader::SeqIdResolver idResolver, CSeq_align& seqAlign) // ---------------------------------------------------------------------------- { seqAlign.SetType(CSeq_align::eType_partial); CDense_seg& denseSeg = seqAlign.SetSegs().SetDenseg(); auto& ids = denseSeg.SetIds(); ids.push_back(idResolver(mNameQ, 0, true)); ids.push_back(idResolver(mNameT, 0, true)); vector<SAlignSegment> segments; xConvertBlocksToSegments(segments); for (const auto& segment: segments) { denseSeg.SetLens().push_back(segment.mLen); denseSeg.SetStarts().push_back(segment.mStartQ); denseSeg.SetStarts().push_back(segment.mStartT); denseSeg.SetStrands().push_back(segment.mStrandQ); denseSeg.SetStrands().push_back(segment.mStrandT); } denseSeg.SetNumseg(static_cast<int>(segments.size())); // cram whatever hasn't been disposed of otherwise into // scores CRef<CScore> pMatches(new CScore); pMatches->SetId().SetStr("num_match"); pMatches->SetValue().SetInt(mMatches); denseSeg.SetScores().push_back(pMatches); CRef<CScore> pMisMatches(new CScore); pMisMatches->SetId().SetStr("num_mismatch"); pMisMatches->SetValue().SetInt(mMisMatches); denseSeg.SetScores().push_back(pMisMatches); CRef<CScore> pRepMatches(new CScore); pRepMatches->SetId().SetStr("num_repmatch"); pRepMatches->SetValue().SetInt(mRepMatches); denseSeg.SetScores().push_back(pRepMatches); CRef<CScore> pCountN(new CScore); pCountN->SetId().SetStr("num_n"); pCountN->SetValue().SetInt(mCountN); denseSeg.SetScores().push_back(pCountN); } // ---------------------------------------------------------------------------- void CPslData::xConvertBlocksToSegments( vector<SAlignSegment>& segments) const // ---------------------------------------------------------------------------- { segments.clear(); if (mBlockCount == 0) { return; } segments.push_back(SAlignSegment{ mBlockSizes[0], mBlockStartsQ[0], mBlockStartsT[0], eNa_strand_plus, mStrandT}); int currentPosQ = mBlockStartsQ[0] + mBlockSizes[0]; int currentPosT = mBlockStartsT[0] + mBlockSizes[0]; for (int i=1; i < mBlockCount; ++i) { auto diffQ = mBlockStartsQ[i] - currentPosQ; if (diffQ) { segments.push_back(SAlignSegment{ diffQ, currentPosQ, -1, eNa_strand_plus, mStrandT}); } auto diffT = mBlockStartsT[i] - currentPosT; if (diffT) { segments.push_back(SAlignSegment{ diffT, -1, currentPosT, eNa_strand_plus, mStrandT}); } segments.push_back(SAlignSegment{ mBlockSizes[i], mBlockStartsQ[i], mBlockStartsT[i], eNa_strand_plus, mStrandT}); currentPosQ = mBlockStartsQ[i] + mBlockSizes[i]; currentPosT = mBlockStartsT[i] + mBlockSizes[i]; } } END_objects_SCOPE END_NCBI_SCOPE
37.856655
85
0.576812
[ "vector" ]
8887af5d812d8db283c164a1a0eea9f72d1010fb
2,378
cpp
C++
Calibration/Tools/bin/recalibEE.cpp
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
852
2015-01-11T21:03:51.000Z
2022-03-25T21:14:00.000Z
Calibration/Tools/bin/recalibEE.cpp
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
30,371
2015-01-02T00:14:40.000Z
2022-03-31T23:26:05.000Z
Calibration/Tools/bin/recalibEE.cpp
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
3,240
2015-01-02T05:53:18.000Z
2022-03-31T17:24:21.000Z
#include "Geometry/Records/interface/IdealGeometryRecord.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "Geometry/Records/interface/IdealGeometryRecord.h" #include "Geometry/CaloGeometry/interface/CaloCellGeometry.h" #include "Geometry/CaloGeometry/interface/CaloGeometry.h" #include "Geometry/CaloGeometry/interface/CaloSubdetectorGeometry.h" #include "CondFormats/DataRecord/interface/EcalIntercalibConstantsRcd.h" #include "Calibration/Tools/interface/calibXMLwriter.h" #include "CalibCalorimetry/CaloMiscalibTools/interface/CaloMiscalibTools.h" #include "CalibCalorimetry/CaloMiscalibTools/interface/CaloMiscalibMapEcal.h" #include "CalibCalorimetry/CaloMiscalibTools/interface/MiscalibReaderFromXMLEcalBarrel.h" #include "CalibCalorimetry/CaloMiscalibTools/interface/MiscalibReaderFromXMLEcalEndcap.h" #include "CondFormats/EcalObjects/interface/EcalIntercalibConstants.h" #include "FWCore/Framework/interface/EventSetup.h" #include "FWCore/Framework/interface/ESHandle.h" #include "TFile.h" int main() { calibXMLwriter endcapWriter(EcalEndcap); CaloMiscalibMapEcal map; std::string endcapfile = "/afs/cern.ch/user/p/presotto/CMSSW_1_6_0/src/CalibCalorimetry/CaloMiscalibTools/data/ecal_endcap_startup.xml"; map.prefillMap(); MiscalibReaderFromXMLEcalEndcap endcapreader(map); if (!endcapfile.empty()) endcapreader.parseXMLMiscalibFile(endcapfile); EcalIntercalibConstants* constants = new EcalIntercalibConstants(map.get()); const EcalIntercalibConstantMap& imap = constants->getMap(); std::string endcapfile2 = "EEcalib.xml"; CaloMiscalibMapEcal map2; map2.prefillMap(); MiscalibReaderFromXMLEcalEndcap endcapreader2(map2); if (!endcapfile2.empty()) endcapreader2.parseXMLMiscalibFile(endcapfile2); EcalIntercalibConstants* constants2 = new EcalIntercalibConstants(map2.get()); const EcalIntercalibConstantMap& imap2 = constants2->getMap(); for (int x = 1; x <= 100; ++x) for (int y = 1; y < 100; ++y) { if (!EEDetId::validDetId(x, y, -1)) continue; EEDetId ee(x, y, -1, EEDetId::XYMODE); endcapWriter.writeLine(ee, *(imap.find(ee.rawId())) * *(imap2.find(ee.rawId()))); if (!EEDetId::validDetId(x, y, 1)) continue; EEDetId e2(x, y, 1, EEDetId::XYMODE); endcapWriter.writeLine(e2, *(imap.find(e2.rawId())) * *(imap2.find(e2.rawId()))); } }
45.730769
117
0.767452
[ "geometry" ]
889660aa83394cfdee5117c06faf2525e80c23f8
6,108
hpp
C++
include/nornir/configuration.hpp
DanieleDeSensi/Nornir
60587824d6b0a6e61b8fc75bdea37c9fc69199c7
[ "MIT" ]
2
2018-10-31T08:09:03.000Z
2021-01-18T19:23:54.000Z
include/nornir/configuration.hpp
DanieleDeSensi/Nornir
60587824d6b0a6e61b8fc75bdea37c9fc69199c7
[ "MIT" ]
1
2020-02-02T11:58:22.000Z
2020-02-02T11:58:22.000Z
include/nornir/configuration.hpp
DanieleDeSensi/Nornir
60587824d6b0a6e61b8fc75bdea37c9fc69199c7
[ "MIT" ]
1
2019-04-13T09:54:49.000Z
2019-04-13T09:54:49.000Z
/* * configuration.hpp * * Created on: 05/12/2015 * * ========================================================================= * Copyright (C) 2015-, Daniele De Sensi (d.desensi.software@gmail.com) * * This file is part of nornir. * * nornir is free software: you can redistribute it and/or * modify it under the terms of the Lesser GNU General Public * License as published by the Free Software Foundation, either * version 3 of the License, or (at your option) any later version. * nornir is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * Lesser GNU General Public License for more details. * * You should have received a copy of the Lesser GNU General Public * License along with nornir. * If not, see <http://www.gnu.org/licenses/>. * * ========================================================================= */ #ifndef NORNIR_CONFIGURATION_HPP_ #define NORNIR_CONFIGURATION_HPP_ #include "knob.hpp" #include "node.hpp" #include "parameters.hpp" #include "stats.hpp" #include "trigger.hpp" #include <mammut/utils.hpp> namespace ff{ class ff_gatherer; } namespace nornir{ class ManagerTest; class Configuration: public mammut::utils::NonCopyable { friend class ManagerTest; protected: std::vector<std::array<Knob*, KNOB_NUM>> _knobs; Trigger* _triggers[TRIGGER_TYPE_NUM]; uint _numServiceNodes; uint _numHMPs; private: const Parameters& _p; bool _combinationsCreated; std::vector<KnobsValues> _combinations; ReconfigurationStats _reconfigurationStats; void combinations(std::vector<std::vector<double> > array, size_t i, std::vector<double> accum); bool virtualCoresWillChange(const KnobsValues& values) const; ticks startReconfigurationStatsKnob() const; void stopReconfigurationStatsKnob(ticks start, KnobType type, bool vcChanged); ticks startReconfigurationStatsTotal() const; void stopReconfigurationStatsTotal(ticks start); public: // If numCpus > 1, different knobs for each cpu (useful for HMP) explicit Configuration(const Parameters& p, uint numHMPs); virtual ~Configuration() = 0; /** * @brief getNumCpus * @return If the system is an HMP system, the number of CPUs, otherwise returns 1. */ uint getNumHMP() const; /** * Returns true if the values of this configuration are equal to those * passed as parameters, false otherwise. * @return true if the values of this configuration are equal to those * passed as parameters, false otherwise. */ bool equal(const KnobsValues& values) const; /** * Given some knobs values, returns the corresponding real values. * @param values The knobs values. * @return The corresponding real values. */ KnobsValues getRealValues(const KnobsValues& values) const; /** * Returns true if the knobs values need to be changed, false otherwise. * @return True if the knobs values need to be changed, false otherwise. */ bool knobsChangeNeeded() const; /** * Creates all the possible knobs combinations. */ void createAllRealCombinations(); /** * Gets all the possible combinations of knobs values. * @return A std::vector containing all the possible combinations * of knobs values. */ const std::vector<KnobsValues>& getAllRealCombinations() const; /** * Sets the highest frequency to reduce the reconfiguration time. */ void setFastReconfiguration(); Knob* getKnob(KnobType t) const; /** * Returns a specified knob. * @param cpuId The cpuId. * @param t The type of the knob to return. * @return The specified knob. */ Knob* getKnob(uint cpuId, KnobType t) const; /** * Sets all the knobs to their maximum. */ void maxAllKnobs(); /** * Returns the real value of a specific knob. * @param t The type of the knob. * @return The real value of the specified knob. */ double getRealValue(KnobType t) const; /** * Returns the real value of a specific knob. * @param cpuId The cpuId. * @param t The type of the knob. * @return The real value of the specified knob. */ double getRealValue(uint cpuId, KnobType t) const; /** * Returns the real values for all the knobs. * @return The real values for all the knobs. */ KnobsValues getRealValues() const; /** * Sets values for the knobs (may be relative or real). * @param values The values of the knobs. */ virtual void setValues(const KnobsValues& values); /** * Triggers the triggers. */ void trigger(); /** * Returns the reconfiguration statistics. * @return The reconfiguration statistics. */ inline ReconfigurationStats getReconfigurationStats() const{ return _reconfigurationStats; } inline uint getNumServiceNodes() const{return _numServiceNodes;} }; class ConfigurationExternal: public Configuration{ public: explicit ConfigurationExternal(const Parameters& p, uint numHMPs = 1); }; class ConfigurationFarm: public Configuration{ public: ConfigurationFarm(const Parameters& p, Smoother<MonitoredSample> const* samples, AdaptiveNode* emitter, std::vector<AdaptiveNode*> workers, AdaptiveNode* collector, ff::ff_gatherer* gt, volatile bool* terminated, uint numHMPs = 1); }; class ConfigurationPipe: public Configuration{ public: ConfigurationPipe(const Parameters& p, Smoother<MonitoredSample> const* samples, std::vector<KnobVirtualCoresFarm*> farms, std::vector<std::vector<double>> allowedValues, uint numHMPs = 1); }; } #endif /* NORNIR_CONFIGURATION_HPP_ */
29.22488
87
0.645056
[ "vector" ]
88971e2e4676235bcc393733b1bc84c685128e0b
1,456
cpp
C++
src/types/bpb.cpp
simonowen/samdisk
9b1391dd233015db633cb83b43d62c15a98f4e3a
[ "MIT" ]
52
2016-05-26T19:24:37.000Z
2022-03-24T16:13:48.000Z
src/types/bpb.cpp
simonowen/samdisk
9b1391dd233015db633cb83b43d62c15a98f4e3a
[ "MIT" ]
17
2017-02-04T00:10:50.000Z
2022-01-19T09:56:18.000Z
src/types/bpb.cpp
simonowen/samdisk
9b1391dd233015db633cb83b43d62c15a98f4e3a
[ "MIT" ]
9
2016-05-13T02:16:05.000Z
2020-08-30T11:34:34.000Z
// BIOS Parameter Block, for MS-DOS and compatible disks #include "SAMdisk.h" #include "bpb.h" bool ReadBPB(MemFile& file, std::shared_ptr<Disk>& disk) { BIOS_PARAMETER_BLOCK bpb{}; if (!file.rewind() || !file.read(&bpb, sizeof(bpb))) return false; // Check for a sensible media byte if (bpb.bMedia != 0xf0 && bpb.bMedia < 0xf8) return false; // Extract the full geometry auto total_sectors = util::le_value(bpb.abSectors); auto sector_size = util::le_value(bpb.abBytesPerSec); auto sectors = util::le_value(bpb.abSecPerTrack); auto heads = util::le_value(bpb.abHeads); auto cyls = (sectors && heads) ? (total_sectors / (sectors * heads)) : 0; Format fmt{ RegularFormat::PC720 }; fmt.cyls = static_cast<uint8_t>(cyls); fmt.heads = static_cast<uint8_t>(heads); fmt.sectors = static_cast<uint8_t>(sectors); fmt.size = SizeToCode(sector_size); fmt.gap3 = 0; // auto if (!fmt.TryValidate()) return false; if (fmt.track_size() < 6000) fmt.datarate = DataRate::_250K; else if (fmt.track_size() < 12000) fmt.datarate = DataRate::_500K; else fmt.datarate = DataRate::_1M; // Reject disks larger than geometry suggests, but accept space-saver truncated images if (file.size() > fmt.disk_size()) return false; file.rewind(); disk->format(fmt, file.data()); disk->strType = "BPB"; return true; }
29.714286
90
0.639423
[ "geometry" ]
889ef8fc53e0f7ba7bd77283844566123d6be304
4,987
cpp
C++
PROX/FOUNDATION/MESH_ARRAY/MESH_ARRAY/src/factory/mesh_array_make_sphere.cpp
diku-dk/PROX
c6be72cc253ff75589a1cac28e4e91e788376900
[ "MIT" ]
2
2019-11-27T09:44:45.000Z
2020-01-13T00:24:21.000Z
PROX/FOUNDATION/MESH_ARRAY/MESH_ARRAY/src/factory/mesh_array_make_sphere.cpp
erleben/matchstick
1cfdc32b95437bbb0063ded391c34c9ee9b9583b
[ "MIT" ]
null
null
null
PROX/FOUNDATION/MESH_ARRAY/MESH_ARRAY/src/factory/mesh_array_make_sphere.cpp
erleben/matchstick
1cfdc32b95437bbb0063ded391c34c9ee9b9583b
[ "MIT" ]
null
null
null
#include <factory/mesh_array_make_sphere.h> #include <factory/mesh_array_profile_sweep.h> #include <tiny_math_types.h> #include <cmath> #include <cassert> namespace mesh_array { template<typename MT> void make_sphere( typename MT::real_type const & radius , size_t const & slices , size_t const & segments , T3Mesh & mesh , VertexAttribute<typename MT::real_type,T3Mesh> & X , VertexAttribute<typename MT::real_type,T3Mesh> & Y , VertexAttribute<typename MT::real_type,T3Mesh> & Z ) { typedef typename MT::real_type T; typedef typename MT::value_traits VT; typedef typename MT::vector3_type V; typedef typename MT::quaternion_type Q; std::vector<V> profile; profile.resize(segments); T const dtheta = VT::pi() / (segments-1); for(size_t i=0;i < segments; ++i ) { T const theta = dtheta*i; Q const R = Q::Ru( theta ,V::k() ); profile[ i ] = rotate( R, V::make( VT::zero(), -radius, VT::zero() ) ); } profile_sweep<MT>( profile, slices, mesh, X, Y, Z ); // typedef typename MT::real_type T; // typedef typename MT::value_traits VT; // typedef typename MT::vector3_type V; // typedef typename MT::quaternion_type Q; // // using std::cos; // using std::sin; // // assert(slices>2u || !"make_sphere(): must have at least 3 slices" ); // assert(segments>1u || !"make_sphere(): must have at least 2 segments"); // // size_t const no_quads = segments*slices; // // mesh.clear(); // // mesh.set_capacity( no_quads*4, no_quads*2 ); // // X.bind(mesh); // Y.bind(mesh); // Z.bind(mesh); // // T const delta_theta = VT::two()*VT::pi()/slices; // T const delta_phi = VT::pi()/segments; // // size_t vertex_offset = 0u; // for(size_t i=0u; i<segments; ++i) // { // for(size_t j=0u; j<slices; ++j) // { // T const theta = j*delta_theta; // T const phi = i*delta_phi; // // mesh.push_vertex(); // mesh.push_vertex(); // mesh.push_vertex(); // mesh.push_vertex(); // // Vertex const vi = mesh.vertex(vertex_offset + 0); // Vertex const vj = mesh.vertex(vertex_offset + 1); // Vertex const vk = mesh.vertex(vertex_offset + 2); // Vertex const vm = mesh.vertex(vertex_offset + 3); // // V const pi = radius * V::make( // cos(theta)*sin(phi+delta_phi) // ,sin(theta)*sin(phi+delta_phi) // , cos(phi+delta_phi) // ); // V const pj =radius * V::make( // cos(theta+delta_theta)*sin(phi+delta_phi) // ,sin(theta+delta_theta)*sin(phi+delta_phi) // , cos(phi+delta_phi) // ); // V const pk =radius * V::make( // cos(theta+delta_theta)*sin(phi) // ,sin(theta+delta_theta)*sin(phi) // , cos(phi) // ); // V const pm =radius * V::make( // cos(theta)*sin(phi) // ,sin(theta)*sin(phi) // , cos(phi) // ); // // X(vi) = pi(0); Y(vi) = pi(1); Z(vi) = pi(2); // X(vj) = pj(0); Y(vj) = pj(1); Z(vj) = pj(2); // X(vk) = pk(0); Y(vk) = pk(1); Z(vk) = pk(2); // X(vm) = pm(0); Y(vm) = pm(1); Z(vm) = pm(2); // // mesh.push_triangle( vi, vj, vk ); // mesh.push_triangle( vi, vk, vm ); // // vertex_offset += 4u; // } // } } typedef tiny::MathTypes<float> MTf; typedef tiny::MathTypes<double> MTd; template void make_sphere<MTf>( MTf::real_type const & radius , size_t const & slices , size_t const & segments , T3Mesh & mesh , VertexAttribute<MTf::real_type,T3Mesh> & X , VertexAttribute<MTf::real_type,T3Mesh> & Y , VertexAttribute<MTf::real_type,T3Mesh> & Z ); template void make_sphere<MTd>( MTd::real_type const & radius , size_t const & slices , size_t const & segments , T3Mesh & mesh , VertexAttribute<MTd::real_type,T3Mesh> & X , VertexAttribute<MTd::real_type,T3Mesh> & Y , VertexAttribute<MTd::real_type,T3Mesh> & Z ); } //namespace mesh_array
33.92517
81
0.464809
[ "mesh", "vector" ]
889f1b401eb4b6117754310773aba90b5356f5f2
864
cpp
C++
Space Harrier Clone/EngineExt/RectangleRenderer.cpp
BrunoAOR/Space-Harrier-Clone
35465ad2d421f69a75a02855627c8ea726b248c6
[ "MIT" ]
12
2018-12-07T16:05:02.000Z
2021-09-06T01:46:50.000Z
Space Harrier Clone/EngineExt/RectangleRenderer.cpp
BrunoAOR/Space-Harrier-Clone
35465ad2d421f69a75a02855627c8ea726b248c6
[ "MIT" ]
null
null
null
Space Harrier Clone/EngineExt/RectangleRenderer.cpp
BrunoAOR/Space-Harrier-Clone
35465ad2d421f69a75a02855627c8ea726b248c6
[ "MIT" ]
1
2020-06-03T03:37:27.000Z
2020-06-03T03:37:27.000Z
#include "RectangleRenderer.h" #include "../Engine/gameConfig.h" RectangleRenderer::RectangleRenderer() { } RectangleRenderer::~RectangleRenderer() { } void RectangleRenderer::render() { SDL_SetRenderDrawBlendMode(m_renderer, SDL_BLENDMODE_BLEND); SDL_Color oldColor; SDL_Rect drawRect; Vector2 posPivot = getPositionPivot(); drawRect.x = (int)((rect.x - posPivot.x * rect.w) * SCREEN_SIZE); drawRect.y = (int)((SCREEN_HEIGHT - (rect.y - posPivot.y * rect.h) - rect.h) * SCREEN_SIZE); drawRect.w = rect.w * SCREEN_SIZE; drawRect.h = rect.h * SCREEN_SIZE; SDL_GetRenderDrawColor(m_renderer, &oldColor.r, &oldColor.g, &oldColor.b, &oldColor.a); SDL_SetRenderDrawColor(m_renderer, color.r, color.g, color.b, color.a); SDL_RenderFillRect(m_renderer, &drawRect); SDL_SetRenderDrawColor(m_renderer, oldColor.r, oldColor.g, oldColor.b, oldColor.a); }
27
93
0.744213
[ "render" ]
88a97d2c32dced100895313f03ad87319aad60f3
4,312
cpp
C++
moci/moci_math/geometry/line_test.cpp
tobanteAudio/moci
a0a764e8a5270f9344ff57366fea36f72e7e3aa4
[ "BSD-2-Clause" ]
null
null
null
moci/moci_math/geometry/line_test.cpp
tobanteAudio/moci
a0a764e8a5270f9344ff57366fea36f72e7e3aa4
[ "BSD-2-Clause" ]
16
2020-03-19T22:08:47.000Z
2020-06-18T18:55:00.000Z
moci/moci_math/geometry/line_test.cpp
tobanteAudio/moci
a0a764e8a5270f9344ff57366fea36f72e7e3aa4
[ "BSD-2-Clause" ]
null
null
null
/** * @file line_test.cpp * @copyright Copyright 2019-2020 tobanteAudio. */ #include "catch2/catch.hpp" #include "moci_math/geometry/line.hpp" TEST_CASE("moci_math/geometry: LineConstructDefault", "[geometry]") { constexpr auto line = moci::Line<float>(); REQUIRE(line.IsEmpty() == true); REQUIRE(line.GetMidPoint().GetX() == 0.0f); REQUIRE(line.GetMidPoint().GetY() == 0.0f); REQUIRE(line.GetStart().GetX() == 0.0f); REQUIRE(line.GetStart().GetY() == 0.0f); REQUIRE(line.GetEnd().GetX() == 0.0f); REQUIRE(line.GetEnd().GetY() == 0.0f); } TEST_CASE("moci_math/geometry: LineConstructFromPoints", "[geometry]") { constexpr auto line = moci::Line<float>({0.0f, 0.0f}, {1.0f, 0.0f}); REQUIRE(line.IsEmpty() == false); REQUIRE(line.GetMidPoint().GetX() == 0.5f); REQUIRE(line.GetMidPoint().GetY() == 0.0f); REQUIRE(line.GetStart().GetX() == 0.0f); REQUIRE(line.GetStart().GetY() == 0.0f); REQUIRE(line.GetEnd().GetX() == 1.0f); REQUIRE(line.GetEnd().GetY() == 0.0f); } TEST_CASE("moci_math/geometry: LineGetMidPoint", "[geometry]") { constexpr auto line = moci::Line<float>({-1.0f, 2.0f}, {3.0f, -6.0f}); REQUIRE(line.GetMidPoint().GetX() == 1.0f); REQUIRE(line.GetMidPoint().GetY() == -2.0f); } TEST_CASE("moci_math/geometry: LineGetSlope", "[geometry]") { // empty constexpr auto l0 = moci::Line<float>(); REQUIRE(l0.GetSlope().has_value() == false); constexpr auto l1 = moci::Line<float>({0.0f, 0.0f}, {1.0f, 0.0f}); REQUIRE(l1.GetSlope().has_value() == true); REQUIRE(l1.GetSlope().value() == 0.0f); constexpr auto l2 = moci::Line<float>({0.0f, 0.0f}, {1.0f, 1.0f}); REQUIRE(l2.GetSlope().has_value() == true); REQUIRE(l2.GetSlope().value() == 1.0f); constexpr auto l3 = moci::Line<float>({0.0f, 0.0f}, {-0.5f, -0.5f}); REQUIRE(l3.GetSlope().has_value() == true); REQUIRE(l3.GetSlope().value() == 1.0f); constexpr auto l4 = moci::Line<float>({0.0f, 0.0f}, {0.5f, -0.5f}); REQUIRE(l4.GetSlope().has_value() == true); REQUIRE(l4.GetSlope().value() == -1.0f); // slope would be inf constexpr auto l5 = moci::Line<float>({0.0f, 0.0f}, {0.0f, 1.0f}); REQUIRE(l5.GetSlope().has_value() == false); } TEST_CASE("moci_math/geometry: LineGetAngleRadians", "[geometry]") { constexpr auto l1 = moci::Line<int> {}; REQUIRE(l1.GetAngleRadians() == 0); constexpr auto l2 = moci::Line<float> {{0.0f, 0.0f}, {1.0f, 1.0f}}; REQUIRE(l2.GetAngleRadians() == Approx(0.7854f)); constexpr auto l3 = moci::Line<float> {{0.0f, 0.0f}, {1.0f, -1.0f}}; REQUIRE(l3.GetAngleRadians() == Approx(-0.7854f)); } TEST_CASE("moci_math/geometry: LineGetAngleDegrees", "[geometry]") { constexpr auto l1 = moci::Line<int> {}; REQUIRE(l1.GetAngleDegrees() == 0); constexpr auto l2 = moci::Line<float> {{0.0f, 0.0f}, {1.0f, 1.0f}}; REQUIRE(l2.GetAngleDegrees() == Approx(45.0f)); constexpr auto l3 = moci::Line<float> {{0.0f, 0.0f}, {1.0f, -1.0f}}; REQUIRE(l3.GetAngleDegrees() == Approx(-45.0f)); } TEST_CASE("moci_math/geometry: LineGetLength", "[geometry]") { constexpr auto l1 = moci::Line<int> {}; REQUIRE(l1.GetLength() == 0); constexpr auto l2 = moci::Line<float> {{0.0f, 0.0f}, {1.0f, 0.0f}}; REQUIRE(l2.GetLength() == Approx(1.0f)); constexpr auto l3 = moci::Line<float> {{0.0f, 0.0f}, {0.0f, -1.0f}}; REQUIRE(l3.GetLength() == Approx(1.0f)); constexpr auto l4 = moci::Line<float> {{0.0f, 0.0f}, {10.0f, 0.0f}}; REQUIRE(l4.GetLength() == Approx(10.0f)); } TEST_CASE("moci_math/geometry: LineOperatorEqual", "[geometry]") { { constexpr auto l1 = moci::Line<int> {}; constexpr auto l2 = moci::Line<int> {}; REQUIRE(l1 == l2); } { constexpr auto l1 = moci::Line<int> {}; constexpr auto l2 = moci::Line<int>({1, 2}, {1, 1}); REQUIRE((l1 == l2) == false); } } TEST_CASE("moci_math/geometry: LineOperatorNotEqual", "[geometry]") { { constexpr auto l1 = moci::Line<int> {}; constexpr auto l2 = moci::Line<int> {}; REQUIRE((l1 != l2) == false); } { constexpr auto l1 = moci::Line<int> {}; constexpr auto l2 = moci::Line<int>({1, 2}, {1, 1}); REQUIRE(l1 != l2); } }
31.021583
74
0.592069
[ "geometry" ]
88a9d6d8840559a23c62d3ab7ec91ac5b7d03086
650
cpp
C++
Array/MergeIntervals.cpp
HARDY8118/LeetCode-Solutions
ec42cabc618b0c85a80864795242b589a286f420
[ "MIT" ]
null
null
null
Array/MergeIntervals.cpp
HARDY8118/LeetCode-Solutions
ec42cabc618b0c85a80864795242b589a286f420
[ "MIT" ]
null
null
null
Array/MergeIntervals.cpp
HARDY8118/LeetCode-Solutions
ec42cabc618b0c85a80864795242b589a286f420
[ "MIT" ]
null
null
null
class Solution { public: vector<vector<int>> merge(vector<vector<int>>& intervals) { sort(intervals.begin(),intervals.end()); int s=intervals[0][0]; int e=intervals[0][1]; vector<vector<int>> r; vector<int> v; for(unsigned int i=1;i<intervals.size();i++){ if(intervals[i][0]<=e){ e=max(intervals[i][1],e); }else{ v={s,e}; r.push_back(v); s=intervals[i][0]; e=intervals[i][1]; } } v={s,e}; r.push_back(v); return r; } };
25
63
0.42
[ "vector" ]
88ad282de117e9236f7fea463939fd9d53387bfa
2,768
cpp
C++
remisen_run/src/application.cpp
tobanteGaming/template-opengl
7eac0d5c49f93b0567cc49fae2b88fd72686e554
[ "MIT" ]
4
2021-07-11T02:07:38.000Z
2022-03-19T06:14:32.000Z
remisen_run/src/application.cpp
tobanteGaming/template-opengl
7eac0d5c49f93b0567cc49fae2b88fd72686e554
[ "MIT" ]
null
null
null
remisen_run/src/application.cpp
tobanteGaming/template-opengl
7eac0d5c49f93b0567cc49fae2b88fd72686e554
[ "MIT" ]
null
null
null
#include "application.hpp" namespace tobanteGaming { Application::Application(String name) : m_name(name) {} Application::~Application() {} void Application::Init() { // glfw, glew, imgui & callbacks m_window.reset(new Window()); m_window->init(); // Shader m_shader.reset(new Shader(VERTEX_SHADER_SOURCE, FRAGMENT_SHADER_SOURCE)); // Object m_cube.reset(new Cube()); } void Application::Run() { const auto f_width = static_cast<float>(WIDTH); const auto f_height = static_cast<float>(HEIGHT); const auto fov = glm::radians(45.0f); // 45° FOV, 4:3 ratio, display range : 0.1 unit <-> 100 units auto projection = glm::perspective(fov, f_width / f_height, 0.1f, 100.0f); // Time & frame count for animation double lastTime = glfwGetTime(); int nbFrames = 0; // Main loop while (m_window->isOpen()) { // FPS auto currentTime = static_cast<float>(glfwGetTime()); nbFrames++; // If last print was more than 1 sec ago if (currentTime - lastTime >= 1.0) { LOG_INFO("{} fps", ImGui::GetIO().Framerate); nbFrames = 0; lastTime += 1.0; } // Clear glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); // Color const float greenValue = sin(currentTime) / 2.0f + 0.5f; m_shader->use(); m_shader->setFloat4("ourColor", greenValue); // Camera matrix glm::mat4 view = glm::lookAt( glm::vec3(nbFrames / currentTime, 2 * nbFrames / currentTime, 3), glm::vec3(0, 0, 0), // Looks at the origin glm::vec3(0, 1, 0) // Head is up ); // Iidentity matrix (model will be at the origin) glm::mat4 model = glm::mat4(1.0f); glm::mat4 mvp = projection * view * model; m_shader->setMatrix4("MVP", mvp); // Render m_cube->render(); drawImgui(); m_window->swapBuffers(); } } void Application::openGLInit() {} void Application::imguiInit() {} void Application::registerCallbacks() {} void Application::drawImgui() { // New frame ImGui_ImplOpenGL3_NewFrame(); ImGui_ImplGlfw_NewFrame(); ImGui::NewFrame(); static float f = 0.0f; ImGui::Begin("Test"); ImGui::Text("Hello, world!"); ImGui::SliderFloat("float", &f, 0.0f, 1.0f); ImGui::ColorEdit3("clear color", (float*)&clear_color); ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); ImGui::End(); // Render ImGui::Render(); ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); } } // namespace tobanteGaming
26.615385
78
0.589234
[ "render", "object", "model" ]
88aefdc451d9a88b3527d790bf80aa9ffaced901
13,527
cpp
C++
components/serenity/config/main.cpp
SBKarr/stappler
d9311cba0b0e9362be55feca39a866d7bccd6dff
[ "MIT" ]
10
2015-06-16T16:52:53.000Z
2021-04-15T09:21:22.000Z
components/serenity/config/main.cpp
SBKarr/stappler
d9311cba0b0e9362be55feca39a866d7bccd6dff
[ "MIT" ]
3
2015-09-23T10:04:00.000Z
2020-09-10T15:47:34.000Z
components/serenity/config/main.cpp
SBKarr/stappler
d9311cba0b0e9362be55feca39a866d7bccd6dff
[ "MIT" ]
3
2018-11-11T00:37:49.000Z
2020-09-07T03:04:31.000Z
/** Copyright (c) 2020 Roman Katuntsev <sbkarr@stappler.org> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. **/ #include "SPCommon.h" #include "SPData.h" #include "SPFilesystem.h" #include "SPValid.h" NS_SP_BEGIN struct Config { enum Flags { None = 0, PortsChanged = 1, AdminChanged = 2, RootServerNameChanged = 4, ServerNameChanged = 8, ServerAliasesChanged = 16, DBParamsChanged = 16, SessionKeyChanged = 32, }; String httpPort = "8080"; String httpsPort = "8443"; String serverAdmin = "you@localhost"; String rootServerName = "localhost"; String serverName = "localhost"; Set<String> serverAliases; String dbParams = "host=localhost dbname=postgres user=postgres password=postgres"; String sessionKey = "SerenityDockerKey"; String privateKey; String publicKey; String customConfig; bool hasHttps = false; Set<String> allow; Flags flags = None; }; SP_DEFINE_ENUM_AS_MASK(Config::Flags); static constexpr auto HELP_STRING( R"HelpString(Docker container configuration script for Serenity handlers Usage: config <handlers-conf-dir> <options> # directly from shell -- OR -- docker container run <container-name> start <options> # From docker entrypoint docker container run <container-name> help # From docker entrypoint This tool configures Apache HTTPD before it's started in Docker container. Example: docker container run serenity-test start \ --db="host=172.17.0.1 dbname=test user=serenity password=serenity" \ --port=7777 --allow=172.17.0.1/24 Starts server on port 7777 instead of default in configuration, with 172.17.0.1/24 (range 172.17.0.0 - 172.17.0.255) as local network addresses for Serenity authentication. Connect to Postgresql database with "host=172.17.0.1 dbname=test user=serenity password=serenity" connection string. Options are one of: -v (--verbose) -h (--help) --allow=<ip-mask> IPv4 mask in form AA.BB.CC.DD/XX or range in form AA.BB.CC.DD-AA.BB.CC.DD to allow serenity secure auth from (for insecure connections). Should be used when there is no HTTPS support in container. You can add multiple ranges with multiple --allow options. --db="<db-params>" Postgresql connection string as described in https://www.postgresql.org/docs/12/libpq-connect.html#LIBPQ-CONNSTRING. Should be quoted to pass it as a single argument with spaces inside --port=<http-port> HTTP port replacement --sport=<https-port> HTTPS port replacement (if HTTPS is enabled in handler's config) --name=<server-name> ServerName replacement for both HTTP/HTTPS hosts --alias=<server-alias> ServerAlias replacement for both HTTP/HTTPS hosts. You can add multiple aliases with multiple --alias options. --root=<root-server-name> ServerName replacement for root configuration (rarely used) --admin=<server-admin> ServerAdmin replacement for root configuration --session=<session-key> SerenitySession `key` component replacement )HelpString"); static int parseOptionSwitch(data::Value &ret, char c, const char *str) { if (c == 'h') { ret.setBool(true, "help"); } else if (c == 'v') { ret.setBool(true, "verbose"); } return 1; } static int parseOptionString(data::Value &ret, const StringView &str, int argc, const char * argv[]) { if (str == "help") { ret.setBool(true, "help"); } else if (str == "verbose") { ret.setBool(true, "verbose"); } else if (str.starts_with("db=")) { ret.setString(StringView(str, "db="_len, str.size() - "db="_len), "db"); } else if (str.starts_with("port=")) { ret.setString(StringView(str, "port="_len, str.size() - "port="_len), "port"); } else if (str.starts_with("sport=")) { ret.setString(StringView(str, "sport="_len, str.size() - "sport="_len), "sport"); } else if (str.starts_with("name=")) { ret.setString(StringView(str, "name="_len, str.size() - "name="_len), "name"); } else if (str.starts_with("alias=")) { ret.emplace("alias").addString(StringView(str, "alias="_len, str.size() - "alias="_len)); } else if (str.starts_with("root=")) { ret.setString(StringView(str, "root="_len, str.size() - "root="_len), "root"); } else if (str.starts_with("admin=")) { ret.setString(StringView(str, "admin="_len, str.size() - "admin="_len), "admin"); } else if (str.starts_with("session=")) { ret.setString(StringView(str, "session="_len, str.size() - "session="_len), "session"); } else if (str.starts_with("allow=")) { ret.emplace("allow").addString(StringView(str, "allow="_len, str.size() - "allow="_len)); } return 1; } struct HttpdConfig { Map<StringView, StringView> cfg; Map<StringView, Map<StringView, StringView>> vhosts; }; static bool parse(HttpdConfig &cfg, StringView v) { Vector<Pair<StringView, Map<StringView, StringView> *>> stack; stack.emplace_back(v, &cfg.cfg); while (!v.empty()) { auto line = v.readUntil<StringView::Chars<'\n', '\r'>>(); v.skipChars<StringView::Chars<'\n', '\r'>>(); line.trimChars<StringView::CharGroup<CharGroupId::WhiteSpace>>(); if (!line.empty()) { if (line.is('<')) { ++ line; auto tag = line.readUntil<StringView::Chars<'>'>>(); auto name = tag.readUntil<StringView::Chars<':', ','>, StringView::CharGroup<CharGroupId::WhiteSpace>>(); if (name.is('/')) { ++ name; if (stack.back().first == name) { stack.pop_back(); } else { std::cerr << "Invalid original config\n"; return false; } } else if (name == "VirtualHost") { tag.skipChars<StringView::Chars<':', ','>, StringView::CharGroup<CharGroupId::WhiteSpace>>(); auto &vhost = cfg.vhosts.emplace(tag, Map<StringView, StringView>()).first->second; stack.emplace_back(name, &vhost); } else { stack.emplace_back(name, nullptr); } } else { if (stack.back().second) { auto name = line.readUntil<StringView::CharGroup<CharGroupId::WhiteSpace>>(); if (!name.empty()) { line.skipChars<StringView::CharGroup<CharGroupId::WhiteSpace>>(); if (!line.empty()) { stack.back().second->emplace(name, line); } else { stack.back().second->emplace(name, StringView()); } } } } } } return true; } static bool process(Config &cfg, HttpdConfig &httpd) { for (auto &it : httpd.cfg) { if (it.first == "ServerAdmin") { cfg.serverAdmin = it.second.str(); } else if (it.first == "ServerName") { cfg.rootServerName = it.second.str(); } } for (auto &it : httpd.vhosts) { auto port = it.first; port.skipUntil<StringView::Chars<':'>>(); if (port.is(':')) { ++ port; } if (!port.empty()) { auto iit = it.second.find(StringView("SSLEngine")); if (iit != it.second.end() && string::tolower(iit->second) == "on") { cfg.httpsPort = port.str(); cfg.hasHttps = true; } else { cfg.httpPort = port.str(); } } for (auto &iit : it.second) { if (iit.first == "ServerName") { cfg.serverName = iit.second.str(); } else if (iit.first == "ServerAlias") { cfg.serverAliases.emplace(iit.second.str()); } else if (iit.first == "DBDParams") { cfg.dbParams = iit.second.str(); } else if (iit.first == "SerenitySession") { auto v = iit.second; v.skipUntilString("key="); if (v.is("key=")) { v += "key="_len; auto key = v.readUntil<StringView::CharGroup<CharGroupId::WhiteSpace>>(); if (!key.empty()) { cfg.sessionKey = key.str(); } } } } } return true; } static bool write(Config &cfg, HttpdConfig &httpd, StringView path) { filesystem::remove(path); std::ofstream stream(path.data()); stream << "# Generated by serenity docker config tool\n\n"; stream << "Listen " << cfg.httpPort << "\n"; if (cfg.hasHttps) { stream << "Listen " << cfg.httpsPort << "\n"; } stream << "\n"; if (!cfg.allow.empty()) { stream << "SerenityAllowIp"; for (auto &it : cfg.allow) { stream << " " << it; } stream << "\n"; } for (auto &it : httpd.cfg) { if (it.first == "ServerAdmin" && (cfg.flags & Config::Flags::AdminChanged)) { stream << it.first << " " << cfg.serverAdmin << "\n"; } else if (it.first == "ServerName" && (cfg.flags & Config::Flags::RootServerNameChanged)) { stream << it.first << " " << cfg.rootServerName << "\n"; } else if (it.first != "Listen") { stream << it.first << " " << it.second << "\n"; } } for (auto &it : httpd.vhosts) { stream << "\n<VirtualHost *:"; auto iit = it.second.find(StringView("SSLEngine")); if (iit != it.second.end() && string::tolower(iit->second) == "on") { stream << cfg.httpsPort; } else { stream << cfg.httpPort; } stream << ">\n"; for (auto &iit : it.second) { if (iit.first == "ServerName" && (cfg.flags & Config::Flags::ServerNameChanged)) { stream << "\t" << iit.first << " " << cfg.serverName << "\n"; } else if (iit.first == "ServerAlias" && (cfg.flags & Config::Flags::ServerAliasesChanged)) { stream << "\t" << iit.first; for (auto &ait : cfg.serverAliases) { stream << " " << ait; } stream << "\n"; } else if (iit.first == "DBDParams" && (cfg.flags & Config::Flags::DBParamsChanged)) { stream << "\t" << iit.first << " \"" << cfg.dbParams << "\"\n"; } else if (iit.first == "SerenitySession" && (cfg.flags & Config::Flags::SessionKeyChanged)) { stream << "\t" << iit.first << " "; auto v = iit.second; stream << v.readUntilString("key="); if (v.is("key=")) { v += "key="_len; v.skipUntil<StringView::CharGroup<CharGroupId::WhiteSpace>>(); stream << "key=" << cfg.sessionKey; } stream << v << "\n"; } else { stream << "\t" << iit.first << " " << iit.second << "\n"; } } stream << "</VirtualHost>\n"; } stream.close(); return true; } SP_EXTERN_C int _spMain(argc, argv) { data::Value opts = data::parseCommandLineOptions(argc, argv, &parseOptionSwitch, &parseOptionString); if (opts.getBool("help")) { std::cout << HELP_STRING << "\n"; return 0; } if (opts.getBool("verbose")) { std::cout << " Current work dir: " << stappler::filesystem::currentDir() << "\n"; std::cout << " Documents dir: " << stappler::filesystem::documentsPath() << "\n"; std::cout << " Cache dir: " << stappler::filesystem::cachesPath() << "\n"; std::cout << " Writable dir: " << stappler::filesystem::writablePath() << "\n"; std::cout << " Options: " << stappler::data::EncodeFormat::Pretty << opts << "\n"; } auto args = opts.getValue("args"); if (args.size() < 2) { return 1; } auto path = args.getString(1); if (!filesystem::exists(path)) { std::cerr << "[Fail] Config file not found: " << path << "\n"; return 1; } Config cfg; HttpdConfig httpd; auto str = filesystem::readTextFile(path); if (!parse(httpd, str)) { std::cerr << "[Fail] fail to parse httpd config\n"; return 1; } if (!process(cfg, httpd)) { std::cerr << "[Fail] Fail to process httpd config\n"; return 1; } for (auto &it : opts.asDict()) { if (it.first == "db") { cfg.dbParams = it.second.getString(); cfg.flags |= Config::DBParamsChanged; } else if (it.first == "port") { cfg.httpPort = it.second.getString(); cfg.flags |= Config::PortsChanged; } else if (it.first == "sport") { cfg.httpsPort = it.second.getString(); cfg.flags |= Config::PortsChanged; } else if (it.first == "name") { cfg.serverName = it.second.getString(); cfg.flags |= Config::ServerNameChanged; } else if (it.first == "alias") { cfg.serverAliases.clear(); for (auto &iit : it.second.asArray()) { cfg.serverAliases.emplace(iit.asString()); } cfg.flags |= Config::ServerAliasesChanged; } else if (it.first == "root") { cfg.rootServerName = it.second.getString(); cfg.flags |= Config::RootServerNameChanged; } else if (it.first == "admin") { cfg.serverAdmin = it.second.getString(); cfg.flags |= Config::AdminChanged; } else if (it.first == "session") { cfg.sessionKey = it.second.getString(); cfg.flags |= Config::SessionKeyChanged; } else if (it.first == "allow") { cfg.allow.clear(); for (auto &iit : it.second.asArray()) { if (valid::readIpRange(iit.getString()) != pair(uint32_t(0), uint32_t(0))) { cfg.allow.emplace(iit.asString()); } } } } auto newName = toString(filepath::root(path), "/gen-", filepath::lastComponent(path)); if (!write(cfg, httpd, newName)) { std::cerr << "[Fail] Fail to write new config to " << newName << "\n"; return 1; } std::cout << "[Success] " << newName << "\n"; return 0; } NS_SP_END
31.385151
109
0.63924
[ "vector" ]
88b9ce873c9e4c453da14a01aef13f9b65b30404
2,940
cpp
C++
src/Transmission.cpp
Sar-Kerson/dehazeProcessor
94ec841aa09aac3783e7fde8f5268a5395a8bde6
[ "MIT" ]
35
2017-12-06T08:33:36.000Z
2022-03-28T12:53:17.000Z
src/Transmission.cpp
Sar-Kerson/dehazeProcessor
94ec841aa09aac3783e7fde8f5268a5395a8bde6
[ "MIT" ]
1
2019-12-04T05:20:33.000Z
2019-12-04T05:20:33.000Z
src/Transmission.cpp
Sar-Kerson/dehazeProcessor
94ec841aa09aac3783e7fde8f5268a5395a8bde6
[ "MIT" ]
14
2018-01-25T15:14:22.000Z
2022-03-28T05:11:17.000Z
#include "../include/Transmission.h" void Transmission::getTransmission(cv::Mat & output) { output = this->t; } void Transmission::calTransmission(cv::Mat & darkchannel, float_t w = 0.95) { cv::Mat temp; if (darkchannel.type() != CV_8UC1) darkchannel.convertTo(temp, CV_8UC1, 1.0 / 255, 0); this->t = 255 - w * darkchannel; } void Transmission::calTransmission(cv::Mat & srcImg, cv::Vec3f & A, cvflann::Index< cvflann::L2_Simple<float> > & kdtree, const int NUM_SPH) { cv::Mat img_scale; if (srcImg.type() != CV_32FC3) srcImg.convertTo(img_scale, CV_32FC3, 1.0 / 255, 0); else img_scale = srcImg; std::vector<float> max_dist(NUM_SPH); float ** dist = new float*[img_scale.rows]; for (int i = 0; i < img_scale.rows; ++i) { dist[i] = new float[img_scale.cols]; } float * query_ar = new float[img_scale.rows * img_scale.cols * 2]; int count = 0; cv::Mat T(img_scale.size(), CV_32FC1); for (int i = 0; i < img_scale.rows; ++i) { for (int j = 0; j < img_scale.cols; ++j) { cv::Vec3f & pixel = img_scale.at<cv::Vec3f>(i, j); cv::Vec3f refine = pixel - A, nrefine; cv::normalize(refine, nrefine); //normalization, point to search float r = sqrt(nrefine[0] * nrefine[0] + nrefine[1] * nrefine[1] + nrefine[2] * nrefine[2]); query_ar[count++] = acos(nrefine[2] / r); query_ar[count++] = atan(nrefine[1] / nrefine[0]); dist[i][j] = sqrt(refine[0] * refine[0] + refine[1] * refine[1] + refine[2] * refine[2]); } } int num_query = img_scale.rows * img_scale.cols; cvflann::Matrix<float> query(query_ar, num_query, 2); cvflann::Matrix<int> vecIndex(new int[num_query], num_query, 1); cvflann::Matrix<float> vecDist(new float[num_query], num_query, 1); kdtree.knnSearch(query, vecIndex, vecDist, 1, cvflann::SearchParams(32, 0, false)); for (int i = 0; i < img_scale.rows; ++i) { for (int j = 0; j < img_scale.cols; ++j) { int ind = vecIndex[i * img_scale.cols + j][0]; if (dist[i][j] > max_dist[ind]) max_dist[ind] = dist[i][j]; } } for (int i = 0; i < img_scale.rows; ++i) { for (int j = 0; j < img_scale.cols; ++j) { int ind = vecIndex[i * img_scale.cols + j][0]; T.at<float>(i, j) = dist[i][j] / max_dist[ind]; } } T.convertTo(this->t, CV_8UC1, 255, 0); } void getTransmission(cv::Mat & darkchannel, cv::Mat & output) { Transmission t; t.calTransmission(darkchannel); t.getTransmission(output); } void getTransmission(cv::Mat & input, cv::Mat & output, cv::Vec3f & A, cvflann::Index< cvflann::L2_Simple<float> > & kdtree, const int NUM_SPH) { Transmission t; t.calTransmission(input, A, kdtree, NUM_SPH); t.getTransmission(output); }
32.666667
101
0.578912
[ "vector" ]
88bf055af0bcfb6d9bd071b66c210d60f1d59398
1,573
cpp
C++
main.cpp
youda97/TopSpin
b5573cf320b8583b8d50bc54e727aad53edfb053
[ "MIT" ]
null
null
null
main.cpp
youda97/TopSpin
b5573cf320b8583b8d50bc54e727aad53edfb053
[ "MIT" ]
null
null
null
main.cpp
youda97/TopSpin
b5573cf320b8583b8d50bc54e727aad53edfb053
[ "MIT" ]
null
null
null
#include "TopSpin.h" #include <iostream> #include <ctime> #include <conio.h> using namespace std; int main() { srand(unsigned(time(NULL))); char option; int ans; TopSpin * spinner = new TopSpin(20, 4); //Creates a TopSpin object of size 20 and spinSize 4. //Asks the user for a number of random moves to initialize the puzzle with cout << "Please enter a number of random moves to initialize the game: "; cin >> ans; //A random move shifting left randomly 1-19 pieces followed by a spin. for (int i = 0; i < ans %19 + 1; i++) { int j = ((rand() % 19) + 1); for (i = 0; i < j; i++) { spinner->shiftLeft(); } spinner->spin(); } //menu which asks if they want to : shift, spin, or quit cout << "\nPress RIGHT to move right, LEFT to move left, SPACE to spin, or ESC to exit\n" << endl; cout << *spinner << endl; while (true) { do { option = _getch(); } while (option != 27 && option != 77 && option != 75 && option != 32); //execute the requested shift, spin or exit if (option == 27) { cout << "Please try again ..." << endl; break; //exits loop } else if (option == 75) { // move left spinner->shiftLeft(); cout << *spinner << endl; } else if (option == 77) { // move right spinner->shiftRight(); cout << *spinner << endl; } else if (option == 32) { // spin spinner->spin(); cout << *spinner << endl; //displays the following message when puzzle is solved if (spinner->isSolved()) { cout << "\n CONGRATULATIONS! \n" << endl; break; //exits loop } } } system("pause"); }
25.370968
99
0.601399
[ "object" ]
88bf471dce8dfb726760be1532aa965bcca7f01b
10,630
hpp
C++
cpp/src/io/read.hpp
dylex/wecall
35d24cefa4fba549e737cd99329ae1b17dd0156b
[ "MIT" ]
8
2018-10-08T15:47:21.000Z
2021-11-09T07:13:05.000Z
cpp/src/io/read.hpp
dylex/wecall
35d24cefa4fba549e737cd99329ae1b17dd0156b
[ "MIT" ]
4
2018-11-05T09:16:27.000Z
2020-04-09T12:32:56.000Z
cpp/src/io/read.hpp
dylex/wecall
35d24cefa4fba549e737cd99329ae1b17dd0156b
[ "MIT" ]
4
2019-09-03T15:46:39.000Z
2021-06-04T07:28:33.000Z
// All content Copyright (C) 2018 Genomics plc #ifndef READ_HPP #define READ_HPP #include "common.hpp" #include "io/pysam.hpp" #include "alignment/cigar.hpp" #include "utils/sequence.hpp" #include "variant/type/variant.hpp" #include "variant/type/breakpoint.hpp" #include <memory> #include <string> #include <cstdint> namespace wecall { namespace io { class Read; using readPtr_t = std::shared_ptr< Read >; /// The Read class represents a sequence read that has been mapped and aligned to a /// reference genome. class Read { public: class ReadParams { public: ReadParams(); ReadParams( const bam1_t * bamRecord ); ReadParams( std::string seq, utils::QualitySequence qual, std::string readGroupID, alignment::Cigar cigar, int32_t tid, int32_t startPos, uint16_t flag, uint8_t mappingQuality, int32_t insertSize, int32_t mateTid, int32_t mateStartPos, const std::string & qname ); std::string m_sequenceStr; utils::QualitySequence m_qualities; std::string m_qname; std::string m_readGroupID; alignment::Cigar m_cigar; int32_t m_tid; int32_t m_startPos; // Start position of read in reference int32_t m_endPos; // End position of read in reference uint16_t m_flag; uint8_t m_mappingQuality; int32_t m_insertSize; int32_t m_mateTid; int32_t m_mateStartPos; // Start position of mate, for paired-end reads. }; Read( const ReadParams & params, utils::referenceSequencePtr_t refSequence ); /// Construct a Read from a Samtools BAM record /// /// @param a Samtools BAM record Read( const bam1_t * bamRecord, utils::referenceSequencePtr_t refSequence ); /// Construct a Read from data, /// /// @param seq The read seqeunce /// @param qual The read quality scores, as PHRED values Read( utils::BasePairSequence seq, utils::QualitySequence qual, std::string readGroupID, alignment::Cigar cigar, int32_t tid, int32_t startPos, uint16_t flag, uint8_t mappingQuality, int32_t insertSize, int32_t mateTid, int32_t mateStartPos, utils::referenceSequencePtr_t refSequence, std::string qname = std::string() ); /// Move constructor /// /// @param rhs Read to be moved Read( Read && rhs ) = default; /// Move assignment operator /// /// @param rhs Read to be moved /// @return reference to this read Read & operator=( Read && rhs ) = default; /// Return a string representation of this read std::string toString() const; /// Return the sequence of As, Cs, Ts and Gs const utils::BasePairSequence & sequence() const { if ( m_sequence.size() == 0 and m_isReference ) { const_cast< utils::BasePairSequence & >( m_sequence ) = makeRefSequence(); } return m_sequence; } /// Return the unique name (usually refered to as qname) of the read. const std::string & getQName() const { return m_qname; } /// Return the sequence of quality scores (one per base) as PHRED scores. const utils::QualitySequence & getQualities() const { return m_qualities; } const alignment::Cigar & cigar() const { return m_cigar; } // Allows to modify qualities in-place and reuse the rest of this data structure // if you change qualities tag this read appropriately; presently we only // modify qualities through error corrector so don't support tags but rather // call setErrorCorrectorModifiedQualities() through which we also communicate // error-corrector specific information about where error corrector kicked in utils::QualitySequence & qualities() { return m_qualities; } /// Return the start position of the read int64_t getStartPos() const { return m_startPos; } caller::Region getRegion() const { return caller::Region( m_refSequence->contig(), m_startPos, m_alignedEndPos ); } // TODO(ES): Add abilty to retrieve the mate's contig. bool isMateOnSameContig() const { return m_tid == m_mateTid; } // TODO(ES): Use insert size to make this exact. utils::Interval getMateIntervalInRef() const { return utils::Interval( m_mateStartPos, m_mateStartPos + getAlignedLength() ); } utils::Interval getMaximalReadInterval() const; /// Return the end position of the read (eqivalent to startPos + readLength) int64_t getEndPos() const { return m_endPos; } /// Return the flag from the original BAM record int64_t getFlag() const { return m_flag; } /// Return the aligned end position of the read. This is not always equal to the value /// returned by getEndPos as it takes into account alignment gaps i.e. insertions and /// deletions int64_t getAlignedEndPos() const { return m_alignedEndPos; } /// Return the amount of read that is before the start position. The start position is taken from the reference. /// If the cigar starts with insertions then these will be before the (aligned) start position. int64_t getLengthBeforeAlignedStartPos() const { return m_cigar.lengthBeforeRefStartPos(); } /// Return the amount of read that is after the aligned end position. The aligned end position refers to the /// reference. /// If the cigar ends with insertions then these will be after the aligned end position. int64_t getLengthAfterAlignedEndPos() const; /// Return the length of the read int64_t getLength() const { return m_endPos - m_startPos; } /// Return the aligned length of the read on the reference sequence, taking into account /// insertions and deletions int64_t getAlignedLength() const { return m_alignedEndPos - m_startPos; } /// Return the length of the original read-pair fragment, as inferred by the read-mapper from /// the start positions of read1 and read2. This can be negative. int64_t getInsertSize() const { return m_insertSize; } /// Return the start position of the mate of this read int64_t getMateStartPos() const { return m_mateStartPos; } /// Return mapping quality as a PHRED score int64_t getMappingQuality() const { return m_mappingQuality; } /// Return the ID of this read as listed in the @RG tag. std::string getReadGroupID() const { return m_readGroupID; } /// Is this read in the reverse direction (the reference sequence is always forward, by /// convention). bool isReverse() const; /// Is this read one of a pair bool isPaired() const; /// Has this read been marked as a duplicate e.g. by Samtools or PICARD bool isDuplicate() const; /// Is this secondary alignment bool isSecondary() const; /// Return true if the read is not mapped. Unmapped reads with mapped mates are placed next /// to their mates in the BAM format, whilst pairs of unmapped reads go at the end of the file bool isUnMapped() const; /// Is the mate of this read unmapped bool isMateUnMapped() const; /// Is the mate of this read in the reverse direction bool isMateReverse() const; /// Is this read the first read of the pair bool isReadOne() const; /// Return true if each segment is properly aligned to according to the aligner. bool isProperPair() const; // matches the reference genome. bool isReference() const { return m_isReference; } /// Trim overlapping part of forward read, in pairs where the read length is greater than the insert size /// N.B Insert size is from start of forward read to end of reverse read, i.e. fragment size. This is done to /// remove duplicate information, which gives systematic errors when pcr errors have occured in library prep. void trimOverlap(); /// Trim the end of any read where the insert size is < read length. If these have not been /// already filtered out then they need trimming, as adapter contamination will cause a /// high FP rate otherwise. void trimReadOfShortFragment(); /// For each character in the sequence return a the corresponding position in the reference. /// Uses emptyPos of -1 for inserted sequence. alignment::referencePositions_t getReferencePositions() const; // Take an interval aligned to the reference and return corresponding interval in read space. utils::Interval getIntervalInRead( const utils::Interval & refInterval ) const; std::vector< variant::varPtr_t > getVariants() const; std::vector< variant::breakpointPtr_t > getBreakpoints() const; private: Read( const Read & rhs ) = delete; utils::BasePairSequence makeRefSequence() const; std::pair< utils::BasePairSequence::const_iterator, utils::BasePairSequence::const_iterator > getRefSequenceRange() const; private: const utils::BasePairSequence m_sequence; utils::QualitySequence m_qualities; std::string m_qname; std::string m_readGroupID; alignment::Cigar m_cigar; const int32_t m_tid; const int32_t m_startPos; // Start position of read in reference const int32_t m_endPos; // End position of read in reference const int32_t m_alignedEndPos; // Actual end of read in reference, when alignment is taken into account const int32_t m_insertSize; const int32_t m_mateTid; const int32_t m_mateStartPos; // Start position of mate, for paired-end reads. utils::referenceSequencePtr_t m_refSequence; const uint16_t m_flag; const uint8_t m_mappingQuality; uint8_t m_isReference = false; }; } } #endif
39.080882
120
0.629257
[ "vector" ]
88c7ac350193ea9336e01a7017d50d727f7ad15c
2,077
cpp
C++
27. Closest pair of points.cpp
VasuGoel/algorithms
c8779a42d72bb5bbe37c76cdf3862d5fc991c055
[ "MIT" ]
null
null
null
27. Closest pair of points.cpp
VasuGoel/algorithms
c8779a42d72bb5bbe37c76cdf3862d5fc991c055
[ "MIT" ]
null
null
null
27. Closest pair of points.cpp
VasuGoel/algorithms
c8779a42d72bb5bbe37c76cdf3862d5fc991c055
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; typedef struct Point { int x, y; } point; bool compareX(point a, point b) { return a.x < b.x; } bool compareY(point a, point b) { return a.y < b.y; } double coord_distance(point a, point b) { return sqrt(pow((a.x - b.x), 2) + pow((a.y - b.y), 2)); } double brute_force(vector<point> &points) { double min = DBL_MAX; for(int i = 0; i < points.size()-1; i++) { for(int j = i+1; j < points.size(); j++) { if(coord_distance(points[i], points[j]) < min) min = coord_distance(points[i], points[j]); } } return min; } double strip_closest_pair(vector<point> &strip, double d) { double min = d; sort(strip.begin(), strip.end(), &compareY); for(int i = 0; i < strip.size(); i++) { for(int j = i+1; j < strip.size() && (strip[j].y - strip[i].y) < min; j++) { if(coord_distance(strip[i], strip[j]) < min) min = coord_distance(strip[i], strip[j]); } } return min; } double closest_pair_util(vector<point> &points, int n) { if(n <= 3) return brute_force(points); int mid = n/2; point midpoint = points[mid]; vector<point> points_left = std::vector<point>(points.begin(), points.begin()+mid); double dl = closest_pair_util(points_left, mid); vector<point> points_right = std::vector<point>(points.begin()+mid, points.end()); double dr = closest_pair_util(points_right, n-mid); double d = min(dl, dr); vector<point> strip; for(int i = 0; i < n; i++) { if(abs(points[i].x - midpoint.x) < d) strip.push_back(points[i]); } return min(d, strip_closest_pair(strip, d)); } double closest_pair(vector<point> &points) { sort(points.begin(), points.end(), &compareX); return closest_pair_util(points, points.size()); } int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); vector<point> points{{2, 3}, {12, 30}, {40, 50}, {5, 1}, {12, 10}, {3, 4}}; cout << "Distance between closest pair of points: " << closest_pair(points); return 0; }
29.671429
103
0.595571
[ "vector" ]
88ceee32d78de65d1d4c845ef79e82900f2cfac6
3,495
cc
C++
c/region_test.cc
mathiasbynens/2im
ab5795ac9548946f01f5d05d8541b8b8c4893067
[ "MIT" ]
null
null
null
c/region_test.cc
mathiasbynens/2im
ab5795ac9548946f01f5d05d8541b8b8c4893067
[ "MIT" ]
null
null
null
c/region_test.cc
mathiasbynens/2im
ab5795ac9548946f01f5d05d8541b8b8c4893067
[ "MIT" ]
null
null
null
#include "region.h" #include "codec_params.h" #include "distance_range.h" #include "gtest/gtest.h" #include "platform.h" #include "sin_cos.h" namespace twim { template <size_t N> void Set(Vector<int32_t>* to, const std::array<int32_t, N>& from) { size_t count = N / 3; size_t step = to->capacity / 3; int32_t* RESTRICT y = to->data(); int32_t* RESTRICT x0 = y + step; int32_t* RESTRICT x1 = x0 + step; for (size_t i = 0; i < count; i++) { y[i] = from.cbegin()[3 * i]; x0[i] = from.cbegin()[3 * i + 1]; x1[i] = from.cbegin()[3 * i + 2]; } to->len = count; } template <size_t N> void ExpectEq(const std::array<int32_t, N>& expected, const Vector<int32_t>* actual) { size_t count = N / 3; size_t step = actual->capacity / 3; const int32_t* RESTRICT y = actual->data(); const int32_t* RESTRICT x0 = y + step; const int32_t* RESTRICT x1 = x0 + step; EXPECT_EQ(count, actual->len); for (size_t i = 0; i < count; ++i) { EXPECT_EQ(expected.data()[3 * i], y[i]); EXPECT_EQ(expected.data()[3 * i + 1], x0[i]); EXPECT_EQ(expected.data()[3 * i + 2], x1[i]); } } TEST(RegionTest, HorizontalSplit) { int32_t step1 = vecSize(1); Vector<int32_t>* region = allocVector<int32_t>(3 * step1); Set<3>(region, {0, 0, 4}); int32_t angle = SinCos.kMaxAngle / 2; CodecParams cp(4, 4); DistanceRange distanceRange(*region, angle, cp); EXPECT_EQ(3, distanceRange.num_lines); Vector<int32_t>* left = allocVector<int32_t>(3 * step1); Vector<int32_t>* right = allocVector<int32_t>(3 * step1); // 1/3 Region::splitLine(*region, angle, distanceRange.distance(0), left, right); ExpectEq<3>({0, 1, 4}, left); ExpectEq<3>({0, 0, 1}, right); // 2/3 Region::splitLine(*region, angle, distanceRange.distance(1), left, right); ExpectEq<3>({0, 2, 4}, left); ExpectEq<3>({0, 0, 2}, right); // 3/3 Region::splitLine(*region, angle, distanceRange.distance(2), left, right); ExpectEq<3>({0, 3, 4}, left); ExpectEq<3>({0, 0, 3}, right); delete region; delete left; delete right; } TEST(RegionTest, VerticalSplit) { int32_t step1 = vecSize(1); int32_t step2 = vecSize(2); int32_t step3 = vecSize(3); int32_t step4 = vecSize(4); Vector<int32_t>* region = allocVector<int32_t>(3 * step4); Set<12>(region, {0, 0, 1, /**/ 1, 0, 1, /**/ 2, 0, 1, /**/ 3, 0, 1}); int32_t angle = 0; CodecParams cp(4, 4); cp.line_limit = 63; DistanceRange distanceRange(*region, angle, cp); EXPECT_EQ(3, distanceRange.num_lines); // 1/3 Vector<int32_t>* left = allocVector<int32_t>(3 * step3); Vector<int32_t>* right = allocVector<int32_t>(3 * step1); Region::splitLine(*region, angle, distanceRange.distance(0), left, right); ExpectEq<9>({1, 0, 1, /**/ 2, 0, 1, /**/ 3, 0, 1}, left); ExpectEq<3>({0, 0, 1}, right); delete left; delete right; // 2/3 left = allocVector<int32_t>(3 * step2); right = allocVector<int32_t>(3 * step2); Region::splitLine(*region, angle, distanceRange.distance(1), left, right); ExpectEq<6>({2, 0, 1, /**/ 3, 0, 1}, left); ExpectEq<6>({0, 0, 1, /**/ 1, 0, 1}, right); delete left; delete right; // 3/3 left = allocVector<int32_t>(3 * step1); right = allocVector<int32_t>(3 * step3); Region::splitLine(*region, angle, distanceRange.distance(2), left, right); ExpectEq<3>({3, 0, 1}, left); ExpectEq<9>({0, 0, 1, /**/ 1, 0, 1, /**/ 2, 0, 1}, right); delete left; delete right; delete region; } } // namespace twim
29.369748
76
0.616595
[ "vector" ]
88d06f513e4bcfeddff8572d6d4ad274988e18f3
6,899
cpp
C++
CUDA-RayTracer/backends/ray_tracing/RayTracingOpenMP.cpp
apardyl/cuda-raytracer
cc0f6a148706fb66f7c4b15e67600deb2e00eed1
[ "MIT" ]
null
null
null
CUDA-RayTracer/backends/ray_tracing/RayTracingOpenMP.cpp
apardyl/cuda-raytracer
cc0f6a148706fb66f7c4b15e67600deb2e00eed1
[ "MIT" ]
null
null
null
CUDA-RayTracer/backends/ray_tracing/RayTracingOpenMP.cpp
apardyl/cuda-raytracer
cc0f6a148706fb66f7c4b15e67600deb2e00eed1
[ "MIT" ]
null
null
null
#include "RayTracingOpenMP.h" #include <boost/math/constants/constants.hpp> #include "Camera.h" #include "KdTree.h" namespace math = boost::math::constants; const Color BACKGROUND_COLOR(0, 0, 0); RayTracingOpenMP::RayTracingOpenMP() { lights = new Light[20]; Ia = Color(0.2, 0.2, 0.2); } RayTracingOpenMP::~RayTracingOpenMP() { delete[] data; } Image RayTracingOpenMP::render() { Light light(Point(0, 0, -1), Color(1, 1, 1), Color(1, 1, 1)); lights[0] = light; numberOfLights = 1; Resolution resolution = Resolution(width, height); Camera camera(Point(0, 0, -1), Point(0, math::pi<float>(), 0), math::pi<float>() / 2, resolution, 1); #pragma omp parallel for for (int y = 0; y < height; ++y) { for (int x = 0; x < width; ++x) { Vector vector = camera.getPrimaryVector(x, y); Color color = trace(vector, 0); camera.update(x, y, color); } } data = new Color[width * height]; #pragma omp parallel for for (int y = 0; y < resolution.height; ++y) { for (int x = 0; x < resolution.width; ++x) { data[width * y + x] = camera.getPixelColor(x, y); } } return Image(resolution.width, resolution.height, data); } Color RayTracingOpenMP::trace(Vector vector, int depth, int ignoredTriangle, float weight) { if (depth > MAX_DEPTH || weight < MINIMUM_WEIGHT) { return BACKGROUND_COLOR; } int triangleIndex = kdTree->getNearestTriangle(vector, ignoredTriangle); if (triangleIndex == -1) { return BACKGROUND_COLOR; } Triangle &triangle = scene->getTriangles()[triangleIndex]; Vector reflectionVector = triangle.getReflectedVector(vector); reflectionVector.normalize(); Point reflectionPoint = reflectionVector.startPoint; Vector normal = scene->getTriangles()[triangleIndex].getNormal(); Material material = scene->getMaterial((scene->getTriangles()[triangleIndex]).materialCode); Vector toViewer = vector.mul(-1); Color refractionColor(0, 0, 0); Color reflectionColor = Ia * material.ambient; float refractivity = 0; if (material.dissolve < FULLY_OPAQUE_RATIO) { float ior = material.refractiveIndex; float reflectivity = fresnel(vector, normal, ior); refractivity = (1 - reflectivity) * (1 - material.dissolve); Vector refractionVector = refract(vector, triangle.getNormal(), ior); refractionVector.startPoint = reflectionPoint; refractionColor = trace(refractionVector, depth + 1, triangleIndex, weight * refractivity) * material.transparent; } if (material.dissolve > FULLY_TRANSPARENT_RATIO) { for (int light = 0; light < numberOfLights; ++light) { Vector toLight = Vector(reflectionPoint, lights[light].point); toLight.normalize(); // Check if the light is blocked out if (normal.isObtuse(toLight)) { continue; } // Cast shadow ray, take refraction into account (simplified version) float intensity = 1; float dist = 0; float lightDistance = lights[light].point.getDist(reflectionPoint); int lightTriangleIndex = triangleIndex; for (int lightDepth = depth; lightDepth < MAX_DEPTH && intensity > 0.01f; ++lightDepth) { lightTriangleIndex = kdTree->getNearestTriangle(toLight, lightTriangleIndex); if (lightTriangleIndex == -1) { break; } const Intersection &intersection = scene->getTriangles()[lightTriangleIndex].intersect(toLight); dist += intersection.distance; if (dist >= lightDistance) { break; } toLight.startPoint = intersection.point; intensity *= (1 - scene->getMaterial(triangle.materialCode).dissolve); } if (intensity <= 0.01f) { continue; } // Calculate reflection color Vector fromLight(lights[light].point, reflectionPoint); Vector fromLightReflected = scene->getTriangles()[triangleIndex].getReflectedVector( fromLight); fromLightReflected.normalize(); reflectionColor += lights[light].diffuse * intensity * std::max(0.f, normal.dot(toLight)) * material.diffuse; reflectionColor += lights[light].specular * intensity * powf(std::max(0.f, toViewer.dot(fromLightReflected)), material.specularExponent) * material.specular; } reflectionColor += trace(reflectionVector, depth + 1, triangleIndex, weight * (1 - refractivity)) * powf(std::max(0.f, toViewer.dot(normal)), material.specularExponent) * material.specular; } if (material.dissolve >= FULLY_OPAQUE_RATIO) { return reflectionColor; } else if (material.dissolve <= FULLY_TRANSPARENT_RATIO) { return refractionColor; } return reflectionColor * (1 - refractivity) + refractionColor * refractivity; } Vector RayTracingOpenMP::refract(const Vector &vector, const Vector &normal, float ior) const { float dot = vector.dot(normal); float eta1 = 1; float eta2 = ior; Vector localNormal = normal; if (dot < 0) { // Ray entering the object dot *= -1; } else { // Ray going out of the object localNormal = normal.mul(-1); std::swap(eta1, eta2); } float eta = eta1 / eta2; float k = 1 - eta * eta * (1 - dot * dot); if (k < 0) { // Total internal reflection return Vector::ZERO; } Vector returnVector = vector.mul(eta).add(localNormal.mul(eta * dot - sqrtf(k))); returnVector.normalize(); return returnVector; } float RayTracingOpenMP::fresnel(const Vector &vector, const Vector &normal, float ior) const { float cos1 = vector.dot(normal); float eta1 = 1; float eta2 = ior; if (cos1 > 0) { std::swap(eta1, eta2); } float sin2 = eta1 / eta2 * sqrtf(std::max(0.f, 1 - cos1 * cos1)); if (sin2 >= 1.f) { // Total internal reflection return 1; } float cos2 = sqrtf(1 - sin2 * sin2); cos1 = fabsf(cos1); float reflectS = (eta1 * cos1 - eta2 * cos2) / (eta1 * cos1 + eta2 * cos2); float reflectP = (eta1 * cos2 - eta2 * cos1) / (eta1 * cos2 + eta2 * cos1); return (reflectS * reflectS + reflectP * reflectP) / 2; } void RayTracingOpenMP::setScene(std::unique_ptr<Scene> scene) { Backend::setScene(std::move(scene)); kdTree = std::make_unique<KdTree>(this->scene.get()); }
33.818627
96
0.593999
[ "render", "object", "vector" ]
88d207cab452dbfd692123608d099e262aa8be0c
3,664
cpp
C++
Classes/Component/Buff.cpp
PlusOneZ/OOPCourseProject
4b058167ec7ef79eacf7faaba05f13b6bee1d631
[ "DOC" ]
5
2020-05-16T08:30:45.000Z
2021-06-05T07:39:44.000Z
Classes/Component/Buff.cpp
PlusOneZ/OOPCourseProject
4b058167ec7ef79eacf7faaba05f13b6bee1d631
[ "DOC" ]
null
null
null
Classes/Component/Buff.cpp
PlusOneZ/OOPCourseProject
4b058167ec7ef79eacf7faaba05f13b6bee1d631
[ "DOC" ]
4
2020-05-25T05:22:14.000Z
2021-07-15T06:27:31.000Z
/** *@file Buff.cpp *@author 肖杨 *@date 6/21/2020 */ #include "Buff.h" Buff* Buff::HeroBuff = nullptr; Animate* Buff::creatBuffAnimate(const char * pAnimateName) { log("Trying to create buff effect"); int moveFrameNum = 6; SpriteFrame*frame = nullptr; Vector<SpriteFrame*> frameVec; for (int i = 1; i <= moveFrameNum; i++) { frame = SpriteFrame::create(StringUtils::format("%s%d.png", pAnimateName, i), Rect(0, 0, 46, 48)); if (frame == nullptr) { log("animate %s%d.png lost", pAnimateName, i); } else { frame->setAnchorPoint(Vec2(0.5f, 0.f)); frameVec.pushBack(frame); } } Animation*animation = Animation::createWithSpriteFrames(frameVec); animation->setLoops(-1); animation->setDelayPerUnit(0.1f); Animate*action = Animate::create(animation); action->retain(); return action; } void Buff::immortal() { Hero::m_pPresentHero->m_ifMortal = false; log("immortal"); m_immortal++; } void Buff::immortalEnd() { if (m_immortal > 1) { m_immortal--; } else if (m_immortal == 1) { Hero::m_pPresentHero->m_ifMortal = true; m_immortal = 0; } } void Buff::speedUp(float up) { Hero::m_pPresentHero->m_speed *= up; Hero::m_pPresentHero->m_ifStateChanged = true; log("speedup"); m_speedUp++; } void Buff::speedUpEnd(float up) { if (m_speedUp > 1) { Hero::m_pPresentHero->m_speed /= up; } else if (m_speedUp == 1) { Hero::m_pPresentHero->m_speed = gHeroSpeed; } if (m_speedUp > 0) { Hero::m_pPresentHero->m_ifStateChanged = true; log("speedup end"); m_speedUp--; } } void Buff::rooted(double rootedTime) { Hero::m_pPresentHero->m_speed = 0; Hero::m_pPresentHero->m_ifStateChanged = true; if (m_rootedTime == 0) { auto freeze = Sprite::create("item/freeze_effect.png"); freeze->setTag(sk::tag::kFreezeTrap); freeze->setPosition(10., 0.); Hero::m_pPresentHero->addChild(freeze); } log("rooted"); m_rootedTime = m_rootedTime > rootedTime ? m_rootedTime : rootedTime; } void Buff::rootedEnd(double rootedTime) { if (m_rootedTime > 0) { if (m_rootedTime - rootedTime <= 0.1) { Hero::m_pPresentHero->m_speed = gHeroSpeed; m_rootedTime = 0; log("rooted end"); auto ice = Hero::m_pPresentHero->getChildByTag(sk::tag::kFreezeTrap); if (ice != nullptr) { ice->removeFromParentAndCleanup(true); } } else { m_rootedTime -= rootedTime; } } } void Buff::increaseATK(int amount) { Hero::m_pPresentHero->m_baseDamage += amount; log("atk up"); if (m_increaseDamage == 0) { auto angry = Sprite::create("Actor/atk_up.png"); angry->setTag(sk::tag::kIncreaseDamage); angry->setPosition(0., 60.); Hero::m_pPresentHero->addChild(angry, 3); } m_increaseDamage++; } void Buff::increaseATKEnd(int amount) { if (m_increaseDamage > 0) { Hero::m_pPresentHero->m_baseDamage -= amount; log("atk up end"); if (m_increaseDamage == 1) { auto atkup = Hero::m_pPresentHero->getChildByTag(sk::tag::kIncreaseDamage); if (atkup != nullptr) { atkup->removeFromParentAndCleanup(true); } } m_increaseDamage--; } } void Buff::flaming() { if (m_flaming == 0) { auto flame = Sprite::create("item/flame_effect1.png"); flame->runAction(m_pFlaming); flame->setPosition(0., 10.); flame->setTag(sk::tag::kFlameTrap); Hero::m_pPresentHero->addChild(flame, 3); log("flaming"); } m_flaming++; } void Buff::flamingEnd() { if (m_flaming > 0) { if (m_flaming == 1) { auto flame = Hero::m_pPresentHero->getChildByTag(sk::tag::kFlameTrap); if (flame != nullptr) { flame->removeFromParentAndCleanup(true); } log("flaming end"); } m_flaming--; } } Buff* Buff::getInstance() { return HeroBuff; }
19.386243
79
0.662391
[ "vector" ]
88d368bec40817de44a0444093a4a0a189d8228f
1,102
cpp
C++
Algorithms/Two Sum II - Input array is sorted/solution.cpp
MishaVernik/LeetCode
5f4823706f472b59fbc0c936524477dc039a46ee
[ "MIT" ]
null
null
null
Algorithms/Two Sum II - Input array is sorted/solution.cpp
MishaVernik/LeetCode
5f4823706f472b59fbc0c936524477dc039a46ee
[ "MIT" ]
null
null
null
Algorithms/Two Sum II - Input array is sorted/solution.cpp
MishaVernik/LeetCode
5f4823706f472b59fbc0c936524477dc039a46ee
[ "MIT" ]
null
null
null
/* Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number. The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Note: Your returned answers (both index1 and index2) are not zero-based. You may assume that each input would have exactly one solution and you may not use the same element twice. Example: Input: numbers = [2,7,11,15], target = 9 Output: [1,2] Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2. */ class Solution { public: vector<int> twoSum(vector<int>& numbers, int target) { int i = 0; int j = numbers.size()-1; int f1 = numbers[0]; int f2 = numbers[0]; while (i < j){ if (numbers[i] + numbers[j] > target) j--;else if (numbers[i] + numbers[j] < target) i++;else if (numbers[i] + numbers[j] == target) { return vector<int>{i+1, j+1}; } } return vector<int>{1,2}; } };
34.4375
137
0.621597
[ "vector" ]
88e2012cdf6aab92ee2d38f676d0b63b6aa91072
8,609
cpp
C++
src/download_manager.cpp
TeamPopplio/browservice-wii-pr
e542cbe937a4335954ddf6f8ecca5ec7e6e0a1cb
[ "MIT" ]
1
2021-02-18T00:30:26.000Z
2021-02-18T00:30:26.000Z
src/download_manager.cpp
TeamPopplio/browservice-wii-pr
e542cbe937a4335954ddf6f8ecca5ec7e6e0a1cb
[ "MIT" ]
null
null
null
src/download_manager.cpp
TeamPopplio/browservice-wii-pr
e542cbe937a4335954ddf6f8ecca5ec7e6e0a1cb
[ "MIT" ]
null
null
null
#include "download_manager.hpp" #include "http.hpp" #include "temp_dir.hpp" #include "include/cef_download_handler.h" namespace { pair<string, string> extractExtension(const string& filename) { int lastDot = (int)filename.size() - 1; while(lastDot >= 0 && filename[lastDot] != '.') { --lastDot; } if(lastDot >= 0) { int extLength = (int)filename.size() - 1 - lastDot; if(extLength >= 1 && extLength <= 5) { bool ok = true; for(int i = lastDot + 1; i < (int)filename.size(); ++i) { char c = filename[i]; if(!( (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') )) { ok = false; break; } } if(ok) { return make_pair( filename.substr(0, lastDot), filename.substr(lastDot + 1) ); } } } return make_pair(filename, "bin"); } string sanitizeBase(const string& base) { string ret; for(char c : base) { if( (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') ) { ret.push_back(c); } else { if(!ret.empty() && ret.back() != '_') { ret.push_back('_'); } } } if(ret.empty() || !( (ret[0] >= 'a' && ret[0] <= 'z') || (ret[0] >= 'A' && ret[0] <= 'Z') )) { ret = "file_" + ret; } ret = ret.substr(0, 32); if(ret.back() == '_') { ret.pop_back(); } return ret; } string sanitizeFilename(const string& filename) { string base, ext; tie(base, ext) = extractExtension(filename); string sanitizedBase = sanitizeBase(base); return sanitizedBase + "." + ext; } } CompletedDownload::CompletedDownload(CKey, shared_ptr<TempDir> tempDir, string path, string name, uint64_t length ) { tempDir_ = tempDir; path_ = move(path); name_ = move(name); length_ = length; } CompletedDownload::~CompletedDownload() { if(unlink(path_.c_str())) { WARNING_LOG("Unlinking file ", path_, " failed"); } } string CompletedDownload::name() { REQUIRE_UI_THREAD(); return name_; } void CompletedDownload::serve(shared_ptr<HTTPRequest> request) { REQUIRE_UI_THREAD(); shared_ptr<CompletedDownload> self = shared_from_this(); function<void(ostream&)> body = [self](ostream& out) { ifstream fp; fp.open(self->path_, ifstream::binary); if(!fp.good()) { ERROR_LOG("Opening downloaded file ", self->path_, " failed"); return; } const uint64_t BufSize = 1 << 16; char buf[BufSize]; uint64_t left = self->length_; while(left) { uint64_t readSize = min(left, BufSize); fp.read(buf, readSize); if(!fp.good()) { ERROR_LOG("Reading downloaded file ", self->path_, " failed"); return; } out.write(buf, readSize); left -= readSize; } fp.close(); }; request->sendResponse( 200, "application/download", length_, body, false, {{"Content-Disposition", "attachment; filename=\"" + name_ + "\""}} ); } class DownloadManager::DownloadHandler : public CefDownloadHandler { public: DownloadHandler(shared_ptr<DownloadManager> downloadManager) { downloadManager_ = downloadManager; } // CefDownloadHandler: virtual void OnBeforeDownload( CefRefPtr<CefBrowser> browser, CefRefPtr<CefDownloadItem> downloadItem, const CefString& suggestedName, CefRefPtr<CefBeforeDownloadCallback> callback ) override { REQUIRE_UI_THREAD(); REQUIRE(downloadItem->IsValid()); uint32_t id = downloadItem->GetId(); REQUIRE(!downloadManager_->infos_.count(id)); DownloadInfo& info = downloadManager_->infos_[id]; info.fileIdx = downloadManager_->nextFileIdx_++; info.name = sanitizeFilename(suggestedName); info.startCallback = callback; info.cancelCallback = nullptr; info.progress = 0; downloadManager_->pending_.push(id); downloadManager_->pendingDownloadCountChanged_(); } virtual void OnDownloadUpdated( CefRefPtr<CefBrowser> browser, CefRefPtr<CefDownloadItem> downloadItem, CefRefPtr<CefDownloadItemCallback> callback ) override { REQUIRE_UI_THREAD(); REQUIRE(downloadItem->IsValid()); uint32_t id = downloadItem->GetId(); if(!downloadManager_->infos_.count(id)) { return; } DownloadInfo& info = downloadManager_->infos_[id]; if(info.startCallback) { return; } info.cancelCallback = callback; if(downloadItem->IsComplete()) { int64_t length = downloadItem->GetReceivedBytes(); REQUIRE(length >= 0); shared_ptr<CompletedDownload> file = CompletedDownload::create( downloadManager_->tempDir_, downloadManager_->getFilePath_(info.fileIdx), move(info.name), (uint64_t)length ); downloadManager_->infos_.erase(id); postTask( downloadManager_->eventHandler_, &DownloadManagerEventHandler::onDownloadCompleted, file ); } else if(!downloadItem->IsInProgress()) { info.cancelCallback->Cancel(); downloadManager_->unlinkFile_(info.fileIdx); downloadManager_->infos_.erase(id); } else { info.progress = downloadItem->GetPercentComplete(); if(info.progress == -1) { info.progress = 50; } info.progress = max(0, min(100, info.progress)); } downloadManager_->downloadProgressChanged_(); } private: shared_ptr<DownloadManager> downloadManager_; IMPLEMENT_REFCOUNTING(DownloadHandler); }; DownloadManager::DownloadManager(CKey, weak_ptr<DownloadManagerEventHandler> eventHandler ) { REQUIRE_UI_THREAD(); eventHandler_ = eventHandler; nextFileIdx_ = 1; } DownloadManager::~DownloadManager() { for(const pair<uint32_t, DownloadInfo>& p : infos_) { const DownloadInfo& info = p.second; if(!info.startCallback) { if(info.cancelCallback) { info.cancelCallback->Cancel(); } unlinkFile_(info.fileIdx); } } } void DownloadManager::acceptPendingDownload() { REQUIRE_UI_THREAD(); if(!pending_.empty()) { uint32_t id = pending_.front(); pending_.pop(); pendingDownloadCountChanged_(); REQUIRE(infos_.count(id)); DownloadInfo& info = infos_[id]; string path = getFilePath_(info.fileIdx); REQUIRE(info.startCallback); info.startCallback->Continue(path, false); info.startCallback = nullptr; downloadProgressChanged_(); } } CefRefPtr<CefDownloadHandler> DownloadManager::createCefDownloadHandler() { REQUIRE_UI_THREAD(); return new DownloadHandler(shared_from_this()); } string DownloadManager::getFilePath_(int fileIdx) { if(!tempDir_) { tempDir_ = TempDir::create(); } return tempDir_->path() + "/file_" + toString(fileIdx) + ".bin"; } void DownloadManager::unlinkFile_(int fileIdx) { string path = getFilePath_(fileIdx); if(unlink(path.c_str())) { WARNING_LOG("Unlinking file ", path, " failed"); } } void DownloadManager::pendingDownloadCountChanged_() { postTask( eventHandler_, &DownloadManagerEventHandler::onPendingDownloadCountChanged, (int)pending_.size() ); } void DownloadManager::downloadProgressChanged_() { vector<pair<int, int>> pairs; for(const pair<uint32_t, DownloadInfo>& elem : infos_) { if(!elem.second.startCallback) { pairs.emplace_back(elem.second.fileIdx, elem.second.progress); } } sort(pairs.begin(), pairs.end()); vector<int> progress; for(pair<int, int> p : pairs) { progress.push_back(p.second); } postTask( eventHandler_, &DownloadManagerEventHandler::onDownloadProgressChanged, progress ); }
27.157729
78
0.563945
[ "vector" ]
88f2bc6842e0c3da1a785ffbd78ab16f7d20aa88
11,294
cpp
C++
src/algos/binghamthread.cpp
rdmenezes/fibernavigator2
bbb8bc8ff16790580d5b03fce7e1fad45fae1b91
[ "MIT" ]
null
null
null
src/algos/binghamthread.cpp
rdmenezes/fibernavigator2
bbb8bc8ff16790580d5b03fce7e1fad45fae1b91
[ "MIT" ]
null
null
null
src/algos/binghamthread.cpp
rdmenezes/fibernavigator2
bbb8bc8ff16790580d5b03fce7e1fad45fae1b91
[ "MIT" ]
null
null
null
/* * BinghamThread.cpp * * Created on: 27.12.2012 * @author Ralph Schurade */ #include "binghamthread.h" #include "fmath.h" #include "sorts.h" #include "../data/datasets/datasetsh.h" #include "../data/mesh/tesselation.h" #include "../gui/gl/glfunctions.h" BinghamThread::BinghamThread( DatasetSH* ds, int lod, int id ) : m_ds( ds ), m_lod( lod ), m_id( id ) { } BinghamThread::~BinghamThread() { m_resultVector.clear(); } QVector<QVector<float> > BinghamThread::getResultVector() { return m_resultVector; } void BinghamThread::run() { int numThreads = GLFunctions::idealThreadCount; QVector<ColumnVector>* data = m_ds->getData(); int num_max = 3; int neighbourhood = 3; const Matrix* vertices = tess::vertices( m_lod ); const int* faces = tess::faces( m_lod ); int numVerts = tess::n_vertices( m_lod ); int numTris = tess::n_faces( m_lod ); QVector<QSet<int> > neighs; QSet<int> v; for ( int i = 0; i < numVerts; ++i ) { neighs.push_back( v ); } for ( int i = 0; i < numTris; ++i ) { int v1 = faces[i * 3]; int v2 = faces[i * 3 + 1]; int v3 = faces[i * 3 + 2]; neighs[v1].insert( v2 ); neighs[v1].insert( v3 ); neighs[v2].insert( v1 ); neighs[v2].insert( v3 ); neighs[v3].insert( v2 ); neighs[v3].insert( v1 ); } const int order( ( -3 + static_cast<int>( sqrt( 8 * data->at( 0 ).Nrows() + 1 ) ) ) / 2 ); Matrix base = ( FMath::sh_base( ( *vertices ), order ) ); QVector<float> bv( 3 * 9, 0 ); m_resultVector.reserve( data->size() / numThreads + numThreads ); // For all voxels: int done = 0; for ( int i = m_id ; i < data->size(); i += numThreads ) { { QVector<float> v = fit_bingham( data->at( i ), *vertices, neighs, base, neighbourhood, num_max ); m_resultVector.push_back( v ); ++done; } } } QVector<float> BinghamThread::fit_bingham( const ColumnVector& sh_data, const Matrix& tess, const QVector<QSet<int> >& adj, const Matrix& base, const int neighborhood, const int num_max ) { unsigned int mod = 9; // reserve memory: QVector<float> result( 27, 0 ); // if no CSD no fit necessary. if ( sh_data( 1 ) == 0 ) { return result; } // get maxima: ColumnVector radius = base * sh_data; QVector<float> qfRadius( radius.Nrows() ); for ( int i = 0; i < qfRadius.size(); ++i ) { qfRadius[i] = radius( i + 1 ); } QVector<int> qiRadius( radius.Nrows() ); for ( int i = 0; i < qiRadius.size(); ++i ) { qiRadius[i] = i; } QVector<int> maxima; for ( int i = 0; i < qfRadius.size(); ++i ) { QSet<int> n = adj[i]; float r = qfRadius[i]; if ( r > 0 ) { bool isMax = true; foreach (const int &value, n) { if ( r < qfRadius[value] ) { isMax = false; } } if ( isMax ) { maxima.push_back( i ); } } } if ( maxima.size() > 2 ) { Sorts::quickSort( maxima, qfRadius, 0, maxima.size() - 1 ); } // qDebug() << "found the following maxima:"; // for ( int i = 0; i < maxima.size(); ++i ) // { // qDebug() << i << maxima[i] << qfRadius[maxima[i]] << adj[maxima[i]]; // } // For all maxima: for ( int n_max = 0; ( n_max < maxima.size() / 2 ) && ( n_max < num_max ); ++n_max ) { // add all maxima and their surrounding points within range of (neighborhood) to the vector gv QSet<int> g; // = adj[maxima[2 * n_max]]; g.insert( maxima[2 * n_max] ); for ( int neighborIterations = 0; neighborIterations < neighborhood; ++neighborIterations ) { QSet<int> h( g ); foreach (const int &value, h ) { g.unite( adj[value] ); } g.unite( h ); } QSet<int> g2; // = adj[maxima[2 * n_max + 1]]; g2.insert( maxima[2 * n_max + 1] ); for ( int neighborIterations = 0; neighborIterations < neighborhood; ++neighborIterations ) { QSet<int> h( g2 ); foreach (const int &value, h ) { g2.unite( adj[value] ); } g2.unite( h ); } g.unite( g2 ); QVector<int> gv = g.toList().toVector(); // testing if there is a neighbor with a negative value, skipping that maximum if true bool negNeigh = false; for ( int i = 0; i < gv.size(); ++i ) { if ( qfRadius[gv[i]] < 0 ) { negNeigh = true; } } if ( negNeigh ) { break; } // sort maxima biggest radi first Sorts::quickSort( gv, qfRadius, 0, gv.size() - 1 ); // qDebug() << "================================================="; // for ( int i = 0; i < gv.size(); ++i ) // { // qDebug() << gv[i] << qfRadius[gv[i]]; // } // qDebug() << "================================================="; // preprocessing for moment of inertia matrix: ColumnVector values( gv.size() ); QVector<ColumnVector> points; ColumnVector maxV( 3 ); maxV( 1 ) = tess( gv[0] + 1, 1 ); maxV( 2 ) = tess( gv[0] + 1, 2 ); maxV( 3 ) = tess( gv[0] + 1, 3 ); double f0 = qfRadius[gv[0]]; for ( int i = 0, j = 0; i < gv.size(); ++i ) { ColumnVector cur( 3 ); cur( 1 ) = tess( gv[i] + 1, 1 ); cur( 2 ) = tess( gv[i] + 1, 2 ); cur( 3 ) = tess( gv[i] + 1, 3 ); double temp = qfRadius[gv[i]]; if ( temp > 0.0 && temp <= f0 ) { if ( FMath::iprod( cur, maxV ) < 0 ) { cur = cur * -1; } points.push_back( cur ); values( ++j ) = temp; } } // calculate moment_of_inertia and extract values: SymmetricMatrix m_inertia( FMath::moment_of_inertia( values, points ) ); DiagonalMatrix m_inertiaEvals( 3 ); Matrix m_inertiaEvecs( 3, 3 ); EigenValues( m_inertia, m_inertiaEvals, m_inertiaEvecs ); QVector<ColumnVector> vecs; ColumnVector vals( 3 ); for ( int i = 1; i < 4; ++i ) { ColumnVector tmp( 3 ); tmp( 1 ) = m_inertiaEvecs( 1, 4 - i ); tmp( 2 ) = m_inertiaEvecs( 2, 4 - i ); tmp( 3 ) = m_inertiaEvecs( 3, 4 - i ); vecs.push_back( tmp ); vals( i ) = m_inertiaEvals( 4 - i ); } // the eigenvectors are the bingham parameter mu: //FMath::evd3x3_2( m_inertia, vecs, vals ); //qDebug() << vecs[0](1) << vecs[0](2) << vecs[0](3); maxV = FMath::sphere2cart( FMath::SH_opt_max( FMath::cart2sphere( vecs[0] ), sh_data ) ); double angle( acos( FMath::iprod( maxV, vecs[0] ) ) ); ColumnVector ax( FMath::cprod( maxV, vecs[0] ) ); //axis Matrix R( FMath::RotationMatrix( angle, ax ) ); vecs[0] = maxV; vecs[1] = R * vecs[1]; vecs[2] = R * vecs[2]; // copies of these vectors in spherical coordinates: ColumnVector z0( FMath::cart2sphere( vecs[0] ) ); //ColumnVector z1( FMath::cart2sphere( vecs[1] ) ); //ColumnVector z2( FMath::cart2sphere( vecs[2] ) ); // get function value at maximum: f0 = FMath::sh_eval( z0, sh_data ); if ( gv.size() > 2 ) { // reserve calculation variables: Matrix A_tmp( gv.size(), 2 ); ColumnVector b_tmp( gv.size() ); ColumnVector index( gv.size() ); index = 0.0; int size( 0 ); // build matrix for least square solution: for ( int i = 0; i < gv.size(); ++i ) { ColumnVector cur( 3 ); cur( 1 ) = tess( gv[i] + 1, 1 ); cur( 2 ) = tess( gv[i] + 1, 2 ); cur( 3 ) = tess( gv[i] + 1, 3 ); double f( radius( gv[i] + 1 ) ); if ( f0 > f && f > 0.0 ) { A_tmp( i + 1, 1 ) = -FMath::iprod( vecs[1], cur ) * FMath::iprod( vecs[1], cur ); A_tmp( i + 1, 2 ) = -FMath::iprod( vecs[2], cur ) * FMath::iprod( vecs[2], cur ); b_tmp( i + 1 ) = log( f / f0 ); ++size; index( i + 1 ) = 1.0; } } Matrix A( size, 2 ); ColumnVector b( size ); if ( size != gv.size() ) { size = 0; for ( int i = 0; i < gv.size(); ++i ) { if ( index( i + 1 ) != 0.0 ) { A( size + 1, 1 ) = A_tmp( i + 1, 1 ); A( size + 1, 2 ) = A_tmp( i + 1, 2 ); b( size + 1 ) = b_tmp( i + 1 ); ++size; } } } else { A = A_tmp; b = b_tmp; } if ( size > 2 ) { ColumnVector k_s( FMath::pseudoInverse( A ) * b ); if ( k_s( 1 ) > 0.0 && k_s( 2 ) > 0.0 ) { // order accordingly: if ( k_s( 1 ) > k_s( 2 ) ) { ColumnVector tmp_v( vecs[1] ); vecs[1] = vecs[2]; vecs[2] = tmp_v; double tmp_d( k_s( 2 ) ); k_s( 2 ) = k_s( 1 ); k_s( 1 ) = tmp_d; } // format output: result[n_max * mod + 0] = vecs[1]( 1 ); result[n_max * mod + 1] = vecs[1]( 2 ); result[n_max * mod + 2] = vecs[1]( 3 ); result[n_max * mod + 3] = vecs[2]( 1 ); result[n_max * mod + 4] = vecs[2]( 2 ); result[n_max * mod + 5] = vecs[2]( 3 ); result[n_max * mod + 6] = k_s( 1 ); result[n_max * mod + 7] = k_s( 2 ); result[n_max * mod + 8] = f0; } } } } return result; }
29.95756
110
0.407296
[ "mesh", "vector" ]
88f41cda1e341c6d8f3ee3d73f54ddccc671d226
5,176
cpp
C++
build/linux-build/Sources/src/kha/AlignedQuad.cpp
5Mixer/GGJ20
a12a14d596ab150e8d96dda5a21defcd176f251f
[ "MIT" ]
null
null
null
build/linux-build/Sources/src/kha/AlignedQuad.cpp
5Mixer/GGJ20
a12a14d596ab150e8d96dda5a21defcd176f251f
[ "MIT" ]
null
null
null
build/linux-build/Sources/src/kha/AlignedQuad.cpp
5Mixer/GGJ20
a12a14d596ab150e8d96dda5a21defcd176f251f
[ "MIT" ]
null
null
null
// Generated by Haxe 4.0.5 #include <hxcpp.h> #ifndef INCLUDED_kha_AlignedQuad #include <hxinc/kha/AlignedQuad.h> #endif HX_DEFINE_STACK_FRAME(_hx_pos_26390ef81ec94f5e_10_new,"kha.AlignedQuad","new",0x3c073353,"kha.AlignedQuad.new","kha/Kravur.hx",10,0xdd7a3f9a) namespace kha{ void AlignedQuad_obj::__construct(){ HX_STACKFRAME(&_hx_pos_26390ef81ec94f5e_10_new) } Dynamic AlignedQuad_obj::__CreateEmpty() { return new AlignedQuad_obj; } void *AlignedQuad_obj::_hx_vtable = 0; Dynamic AlignedQuad_obj::__Create(hx::DynamicArray inArgs) { hx::ObjectPtr< AlignedQuad_obj > _hx_result = new AlignedQuad_obj(); _hx_result->__construct(); return _hx_result; } bool AlignedQuad_obj::_hx_isInstanceOf(int inClassId) { return inClassId==(int)0x00000001 || inClassId==(int)0x1e29b4f3; } AlignedQuad_obj::AlignedQuad_obj() { } hx::Val AlignedQuad_obj::__Field(const ::String &inName,hx::PropertyAccess inCallProp) { switch(inName.length) { case 2: if (HX_FIELD_EQ(inName,"x0") ) { return hx::Val( x0 ); } if (HX_FIELD_EQ(inName,"y0") ) { return hx::Val( y0 ); } if (HX_FIELD_EQ(inName,"s0") ) { return hx::Val( s0 ); } if (HX_FIELD_EQ(inName,"t0") ) { return hx::Val( t0 ); } if (HX_FIELD_EQ(inName,"x1") ) { return hx::Val( x1 ); } if (HX_FIELD_EQ(inName,"y1") ) { return hx::Val( y1 ); } if (HX_FIELD_EQ(inName,"s1") ) { return hx::Val( s1 ); } if (HX_FIELD_EQ(inName,"t1") ) { return hx::Val( t1 ); } break; case 8: if (HX_FIELD_EQ(inName,"xadvance") ) { return hx::Val( xadvance ); } } return super::__Field(inName,inCallProp); } hx::Val AlignedQuad_obj::__SetField(const ::String &inName,const hx::Val &inValue,hx::PropertyAccess inCallProp) { switch(inName.length) { case 2: if (HX_FIELD_EQ(inName,"x0") ) { x0=inValue.Cast< Float >(); return inValue; } if (HX_FIELD_EQ(inName,"y0") ) { y0=inValue.Cast< Float >(); return inValue; } if (HX_FIELD_EQ(inName,"s0") ) { s0=inValue.Cast< Float >(); return inValue; } if (HX_FIELD_EQ(inName,"t0") ) { t0=inValue.Cast< Float >(); return inValue; } if (HX_FIELD_EQ(inName,"x1") ) { x1=inValue.Cast< Float >(); return inValue; } if (HX_FIELD_EQ(inName,"y1") ) { y1=inValue.Cast< Float >(); return inValue; } if (HX_FIELD_EQ(inName,"s1") ) { s1=inValue.Cast< Float >(); return inValue; } if (HX_FIELD_EQ(inName,"t1") ) { t1=inValue.Cast< Float >(); return inValue; } break; case 8: if (HX_FIELD_EQ(inName,"xadvance") ) { xadvance=inValue.Cast< Float >(); return inValue; } } return super::__SetField(inName,inValue,inCallProp); } void AlignedQuad_obj::__GetFields(Array< ::String> &outFields) { outFields->push(HX_("x0",b8,68,00,00)); outFields->push(HX_("y0",97,69,00,00)); outFields->push(HX_("s0",5d,64,00,00)); outFields->push(HX_("t0",3c,65,00,00)); outFields->push(HX_("x1",b9,68,00,00)); outFields->push(HX_("y1",98,69,00,00)); outFields->push(HX_("s1",5e,64,00,00)); outFields->push(HX_("t1",3d,65,00,00)); outFields->push(HX_("xadvance",0a,87,b1,be)); super::__GetFields(outFields); }; #ifdef HXCPP_SCRIPTABLE static hx::StorageInfo AlignedQuad_obj_sMemberStorageInfo[] = { {hx::fsFloat,(int)offsetof(AlignedQuad_obj,x0),HX_("x0",b8,68,00,00)}, {hx::fsFloat,(int)offsetof(AlignedQuad_obj,y0),HX_("y0",97,69,00,00)}, {hx::fsFloat,(int)offsetof(AlignedQuad_obj,s0),HX_("s0",5d,64,00,00)}, {hx::fsFloat,(int)offsetof(AlignedQuad_obj,t0),HX_("t0",3c,65,00,00)}, {hx::fsFloat,(int)offsetof(AlignedQuad_obj,x1),HX_("x1",b9,68,00,00)}, {hx::fsFloat,(int)offsetof(AlignedQuad_obj,y1),HX_("y1",98,69,00,00)}, {hx::fsFloat,(int)offsetof(AlignedQuad_obj,s1),HX_("s1",5e,64,00,00)}, {hx::fsFloat,(int)offsetof(AlignedQuad_obj,t1),HX_("t1",3d,65,00,00)}, {hx::fsFloat,(int)offsetof(AlignedQuad_obj,xadvance),HX_("xadvance",0a,87,b1,be)}, { hx::fsUnknown, 0, null()} }; static hx::StaticInfo *AlignedQuad_obj_sStaticStorageInfo = 0; #endif static ::String AlignedQuad_obj_sMemberFields[] = { HX_("x0",b8,68,00,00), HX_("y0",97,69,00,00), HX_("s0",5d,64,00,00), HX_("t0",3c,65,00,00), HX_("x1",b9,68,00,00), HX_("y1",98,69,00,00), HX_("s1",5e,64,00,00), HX_("t1",3d,65,00,00), HX_("xadvance",0a,87,b1,be), ::String(null()) }; hx::Class AlignedQuad_obj::__mClass; void AlignedQuad_obj::__register() { AlignedQuad_obj _hx_dummy; AlignedQuad_obj::_hx_vtable = *(void **)&_hx_dummy; hx::Static(__mClass) = new hx::Class_obj(); __mClass->mName = HX_("kha.AlignedQuad",e1,8d,58,04); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &hx::Class_obj::GetNoStaticField; __mClass->mSetStaticField = &hx::Class_obj::SetNoStaticField; __mClass->mStatics = hx::Class_obj::dupFunctions(0 /* sStaticFields */); __mClass->mMembers = hx::Class_obj::dupFunctions(AlignedQuad_obj_sMemberFields); __mClass->mCanCast = hx::TCanCast< AlignedQuad_obj >; #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = AlignedQuad_obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = AlignedQuad_obj_sStaticStorageInfo; #endif hx::_hx_RegisterClass(__mClass->mName, __mClass); } } // end namespace kha
36.70922
141
0.701314
[ "3d" ]
88f6a69999a568b5151b8b6198a437b14d393634
4,747
cpp
C++
test_main/src/renderer/blocks.cpp
jgavert/FazE
7cf63655869c285a7e5ca8f5a48f296d9548bd6c
[ "MIT" ]
15
2020-01-15T13:04:36.000Z
2022-02-18T17:08:25.000Z
test_main/src/renderer/blocks.cpp
jgavert/FazE
7cf63655869c285a7e5ca8f5a48f296d9548bd6c
[ "MIT" ]
3
2015-09-09T08:16:30.000Z
2015-11-24T16:22:48.000Z
test_main/src/renderer/blocks.cpp
jgavert/FazE
7cf63655869c285a7e5ca8f5a48f296d9548bd6c
[ "MIT" ]
1
2021-12-06T07:19:05.000Z
2021-12-06T07:19:05.000Z
#include "blocks.hpp" #include <higanbana/core/profiling/profiling.hpp> #include <higanbana/core/global_debug.hpp> namespace app::renderer { Blocks::Blocks(higanbana::GpuGroup& device, higanbana::ShaderArgumentsLayout cameras, higanbana::ShaderArgumentsLayout materials) { using namespace higanbana; higanbana::ShaderArgumentsLayoutDescriptor triangleLayoutDesc = ShaderArgumentsLayoutDescriptor() .readOnly(ShaderResourceType::ByteAddressBuffer, "vertexInput"); triangleLayout = device.createShaderArgumentsLayout(triangleLayoutDesc); PipelineInterfaceDescriptor instancePipeline = PipelineInterfaceDescriptor() .structDecl<ActiveCameraInfo>() .constants<Blocks::Constants>() .shaderArguments(0, triangleLayout) .shaderArguments(1, cameras) .shaderArguments(2, materials); auto pipelineDescriptor = GraphicsPipelineDescriptor() .setInterface(instancePipeline) .setVertexShader("/shaders/blocksSimple") .setPixelShader("/shaders/blocksSimple") .setPrimitiveTopology(PrimitiveTopology::Triangle) .setRTVFormat(0, FormatType::Float16RGBA) .setRTVFormat(1, FormatType::Float16RGBA) .setDSVFormat(FormatType::Depth32) //.setRasterizer(RasterizerDescriptor().setCullMode(CullMode::None)) .setRenderTargetCount(2) .setDepthStencil(DepthStencilDescriptor() .setDepthEnable(true) .setDepthFunc(ComparisonFunc::Greater)); m_pipeline = device.createGraphicsPipeline(pipelineDescriptor); m_renderpass = device.createRenderpass(); // cube index buffer; } void Blocks::beginRenderpass(higanbana::CommandGraphNode& node, higanbana::TextureRTV& target, higanbana::TextureRTV& motionVecs, higanbana::TextureDSV& depth) { using namespace higanbana; HIGAN_CPU_FUNCTION_SCOPE(); HIGAN_ASSERT(target.desc().desc.format == FormatType::Float16RGBA, ""); HIGAN_ASSERT(motionVecs.desc().desc.format == FormatType::Float16RGBA, ""); HIGAN_ASSERT(depth.desc().desc.format == FormatType::Depth32, ""); node.renderpass(m_renderpass, target, motionVecs, depth); } void Blocks::endRenderpass(higanbana::CommandGraphNode& node) { HIGAN_CPU_FUNCTION_SCOPE(); node.endRenderpass(); } higanbana::ShaderArgumentsBinding Blocks::bindPipeline(higanbana::CommandGraphNode& node) { return node.bind(m_pipeline); } void Blocks::renderBlocks(higanbana::GpuGroup& dev, higanbana::CommandGraphNode& node, higanbana::TextureRTV& backbuffer, higanbana::TextureRTV& motionVecs, higanbana::TextureDSV& depth, higanbana::ShaderArguments cameraArgs, higanbana::ShaderArguments materials, int cameraIndex, int prevCamera, higanbana::vector<ChunkBlockDraw>& instances) { using namespace higanbana; HIGAN_CPU_FUNCTION_SCOPE(); backbuffer.setOp(LoadOp::Load); depth.clearOp({}); beginRenderpass(node, backbuffer, motionVecs, depth); vector<uint> vertexData = { 0, 1, 1, //0.f, 0.66f, // 0 0, 0, 1, //0.25f, 0.66f, // 1 0, 1, 0, //0.f, 0.33f, // 2 0, 0, 0, //0.25f, 0.33f, // 3 1, 0, 1, //0.5f, 0.66f, // 4 1, 0, 0, //0.5f, 0.33f, // 5 1, 1, 1, //0.75f, 0.66f, // 6 1, 1, 0, //0.75f, 0.33f, // 7 0, 1, 1, //1.f, 0.66f, // 8 0, 1, 0, //1.f, 0.33f, // 9 0, 1, 1, //0.25f, 1.f, // 10 1, 1, 1, //.0.5f, 1.f, // 11 0, 1, 0, //0.25f, 0.f, // 12 1, 1, 0, //0.5f, 0.f, // 13 }; vector<uint> vertexData2; for (int i = 0; i < vertexData.size(); i+=3) { uint compressed = (vertexData[i] << 2) | (vertexData[i+1] << 1) | vertexData[i+2]; vertexData2.push_back(compressed); } auto vert = dev.dynamicBuffer<uint>(vertexData2, FormatType::Raw32); auto args = dev.createShaderArguments(ShaderArgumentsDescriptor("vertexdata", triangleLayout) .bind("vertexInput", vert)); vector<uint> indexData = { 0, 2, 1, 2, 3, 1, 1, 3, 4, 3, 5, 4, 4, 5, 6, 5, 7, 6, 6, 7, 8, 7, 9, 8, 10, 1, 11, 1, 4, 11, 3, 12, 5, 12, 13, 5, }; for (int i = 0; i < indexData.size(); ++i) { auto face = i / 6; indexData[i] = indexData[i] | (face << 4); } auto ind = dev.dynamicBuffer<uint>(indexData, FormatType::Uint32); auto binding = bindPipeline(node); binding.arguments(0, args); binding.arguments(1, cameraArgs); binding.arguments(2, materials); Constants consts{}; consts.camera.current = cameraIndex; consts.camera.previous = prevCamera; consts.time = 0; consts.scale = 0; consts.outputSize = backbuffer.desc().desc.size3D().xy(); for (auto&& instance : instances) { consts.position = float4(instance.position, 1.f); consts.cubeMaterial = instance.materialIndex; binding.constants(consts); node.drawIndexed(binding, ind, 12*3); } endRenderpass(node); } }
35.962121
344
0.680851
[ "vector" ]
88fe4c418e8a9cc375b658a375d76326f69b7136
6,778
cpp
C++
anim/Interpolator.cpp
Andrewich/deadjustice
48bea56598e79a1a10866ad41aa3517bf7d7c724
[ "BSD-3-Clause" ]
3
2019-04-20T10:16:36.000Z
2021-03-21T19:51:38.000Z
anim/Interpolator.cpp
Andrewich/deadjustice
48bea56598e79a1a10866ad41aa3517bf7d7c724
[ "BSD-3-Clause" ]
null
null
null
anim/Interpolator.cpp
Andrewich/deadjustice
48bea56598e79a1a10866ad41aa3517bf7d7c724
[ "BSD-3-Clause" ]
2
2020-04-18T20:04:24.000Z
2021-09-19T05:07:41.000Z
#include "Interpolator.h" #include "PtrLess.h" #include <lang/String.h> #include <lang/Exception.h> #include <math.h> #include <algorithm> #include "config.h" //----------------------------------------------------------------------------- using namespace lang; using namespace util; //----------------------------------------------------------------------------- namespace anim { Interpolator::Interpolator( int channels ) : m_times( Allocator<float>(__FILE__,__LINE__) ), m_values( Allocator<float>(__FILE__,__LINE__) ), m_temp( Allocator<float>(__FILE__,__LINE__) ), m_channels( channels ), m_endBehaviour(BEHAVIOUR_REPEAT), m_preBehaviour(BEHAVIOUR_CONSTANT) { } Interpolator::Interpolator( const Interpolator& other ) : m_times( other.m_times ), m_values( other.m_values ), m_temp( other.m_temp ), m_channels( other.m_channels ), m_endBehaviour( other.m_endBehaviour ), m_preBehaviour( other.m_preBehaviour ) { } void Interpolator::setKeys( int count ) { m_times.setSize( count ); m_values.setSize( count*m_channels ); } void Interpolator::setKeyValue( int i, const float* value, int size ) { assert( i >= 0 && i < keys() ); assert( size == m_channels ); float* v = m_values.begin() + i*m_channels; for ( int i = 0 ; i < size ; ++i ) v[i] = value[i]; } void Interpolator::setKeyTime( int i, float time ) { assert( i >= 0 && i < keys() ); m_times[i] = time; } void Interpolator::setEndBehaviour( Interpolator::BehaviourType behaviour ) { m_endBehaviour = behaviour; } void Interpolator::setPreBehaviour( Interpolator::BehaviourType behaviour ) { m_preBehaviour = behaviour; } void Interpolator::getKeyValue( int i, float* value, int size ) const { assert( i >= 0 && i < keys() ); assert( size == m_channels ); const float* v = m_values.begin() + i*m_channels; for ( int i = 0 ; i < size ; ++i ) value[i] = v[i]; } const float* Interpolator::getKeyValue( int i ) const { assert( i >= 0 && i < keys() ); return m_values.begin() + i*m_channels; } float Interpolator::getKeyTime( int i ) const { assert( i >= 0 && i < keys() ); return m_times[i]; } Interpolator::BehaviourType Interpolator::endBehaviour() const { return m_endBehaviour; } Interpolator::BehaviourType Interpolator::preBehaviour() const { return m_preBehaviour; } float* Interpolator::getTempBuffer( int size ) const { assert( size > 0 ); m_temp.setSize( size ); return m_temp.begin(); } int Interpolator::findKey( float time, int hint ) const { assert( keys() > 0 ); // validate hint int last = m_times.size() - 1; if ( hint < 0 || hint > last ) hint = 0; // check start/end boundaries if ( time <= m_times[0] ) return 0; else if ( time >= m_times.lastElement() ) return last; assert( time > m_times[0] && time < m_times.lastElement() ); // find correct interval, starting from hint for ( int i = hint ; i < last ; ++i ) { assert( i == last || m_times[i] < m_times[i+1] ); // ensure order if ( time >= m_times[i] && time < m_times[i+1] ) return i; } for ( int i = 0 ; i < hint ; ++i ) { assert( i == last || m_times[i] < m_times[i+1] ); // ensure order if ( time >= m_times[i] && time < m_times[i+1] ) return i; } return 0; } float Interpolator::getTimeDirection( float time ) const { if ( m_endBehaviour == BEHAVIOUR_OSCILLATE && keys() > 2 ) { float startTime = m_times[0]; float endTime = m_times.lastElement(); float length = endTime - startTime; assert( length > 1e-9f ); // start behaviour if ( time < startTime ) time = startTime; time = fmodf( time-startTime, 2.f*length ); if ( time >= length ) return -1.f; } return 1.f; } float Interpolator::getNormalizedTime( float time ) const { assert( keys() > 0 ); if ( keys() < 2 ) return m_times[0]; float startTime = m_times[0]; float endTime = m_times.lastElement(); float length = endTime - startTime; assert( length > 1e-9f ); // start behaviour if ( time < startTime ) { switch ( m_preBehaviour ) { case BEHAVIOUR_RESET: time = endTime; break; case BEHAVIOUR_CONSTANT: time = startTime; break; case BEHAVIOUR_REPEAT: time = endTime - fmodf( startTime-time, length ); break; case BEHAVIOUR_OSCILLATE: time = -fmodf( startTime-time, 2.f*length ); if ( time >= length ) time = 2.f*length - time; time += startTime; break; } } // end behaviour switch ( m_endBehaviour ) { case BEHAVIOUR_RESET: if ( time >= endTime ) time = startTime; break; case BEHAVIOUR_CONSTANT: if ( time > endTime ) time = endTime; break; case BEHAVIOUR_REPEAT: time = startTime + fmodf( time-startTime, length ); break; case BEHAVIOUR_OSCILLATE: time = fmodf( time-startTime, 2.f*length ); if ( time >= length ) time = 2.f*length - time; time += startTime; break; } // ensure limits if ( time < startTime ) time = startTime; else if ( time > endTime ) time = endTime; assert( time >= startTime ); assert( time <= endTime ); return time; } void Interpolator::sortKeys() { Vector<int> order( Allocator<int>(__FILE__,__LINE__) ); order.setSize( m_times.size() ); for ( int i = 0 ; i < m_times.size() ; ++i ) order[i] = i; std::sort( order.begin(), order.end(), PtrLess<float>(m_times.begin()) ); reorderKeys( order.begin() ); } void Interpolator::reorderKeys( const int* order ) { int keys = this->keys(); // key times Vector<float> times( Allocator<float>(__FILE__,__LINE__) ); times.setSize( m_times.size() ); for ( int i = 0 ; i < keys ; ++i ) times[i] = m_times[ order[i] ]; // key values Vector<float> values( Allocator<float>(__FILE__,__LINE__) ); values.setSize( m_values.size() ); for ( int i = 0 ; i < keys ; ++i ) { const float* src = &m_values[ order[i] * m_channels ]; float* dst = &values[ i * m_channels ]; for ( int k = 0 ; k < m_channels ; ++k ) dst[k] = src[k]; } m_times = times; m_values = values; } Interpolator::BehaviourType Interpolator::toBehaviour( const String& str ) { if ( str == "RESET" ) return Interpolator::BEHAVIOUR_RESET; else if ( str == "CONSTANT" ) return Interpolator::BEHAVIOUR_CONSTANT; else if ( str == "REPEAT" ) return Interpolator::BEHAVIOUR_REPEAT; else if ( str == "OSCILLATE" ) return Interpolator::BEHAVIOUR_OSCILLATE; else throw Exception( Format("String {0} is not valid animation end behaviour", str) ); } float Interpolator::endTime() const { float t = 0.f; if ( m_times.size() > 0 ) t = m_times.lastElement(); return t; } } // anim
22.976271
85
0.609914
[ "vector" ]
322ee1d5973f7ccf6ecb865b9ebd2c778eab5191
9,808
cpp
C++
OrbitGl/CaptureSerializer.cpp
EmperorYP7/orb
33210e928243eb803b4b01fe9b82f89656d2f061
[ "BSD-2-Clause" ]
1
2021-01-10T16:32:07.000Z
2021-01-10T16:32:07.000Z
OrbitGl/CaptureSerializer.cpp
EmperorYP7/orbit
33210e928243eb803b4b01fe9b82f89656d2f061
[ "BSD-2-Clause" ]
null
null
null
OrbitGl/CaptureSerializer.cpp
EmperorYP7/orbit
33210e928243eb803b4b01fe9b82f89656d2f061
[ "BSD-2-Clause" ]
null
null
null
// Copyright (c) 2020 The Orbit Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "CaptureSerializer.h" #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/io/zero_copy_stream_impl.h> #include <google/protobuf/message.h> #include <fstream> #include <memory> #include "App.h" #include "Callstack.h" #include "Capture.h" #include "EventTracer.h" #include "FunctionUtils.h" #include "OrbitBase/MakeUniqueForOverwrite.h" #include "OrbitModule.h" #include "OrbitProcess.h" #include "SamplingProfiler.h" #include "TextBox.h" #include "TimeGraph.h" #include "TimerChain.h" #include "absl/strings/str_format.h" #include "capture_data.pb.h" using orbit_client_protos::CallstackEvent; using orbit_client_protos::CallstackInfo; using orbit_client_protos::CaptureInfo; using orbit_client_protos::FunctionInfo; using orbit_client_protos::FunctionStats; using orbit_client_protos::TimerInfo; ErrorMessageOr<void> CaptureSerializer::Save(const std::string& filename) { header.set_version(kRequiredCaptureVersion); std::ofstream file(filename, std::ios::binary); if (file.fail()) { ERROR("Saving capture in \"%s\": %s", filename, "file.fail()"); return ErrorMessage("Error opening the file for writing"); } { SCOPE_TIMER_LOG(absl::StrFormat("Saving capture in \"%s\"", filename)); Save(file); } return outcome::success(); } void CaptureSerializer::WriteMessage(const google::protobuf::Message* message, google::protobuf::io::CodedOutputStream* output) { uint32_t message_size = message->ByteSizeLong(); output->WriteLittleEndian32(message_size); message->SerializeToCodedStream(output); } void CaptureSerializer::FillCaptureData(CaptureInfo* capture_info) { for (const auto& pair : Capture::capture_data_.selected_functions()) { capture_info->add_selected_functions()->CopyFrom(pair.second); } capture_info->set_process_id(Capture::capture_data_.process_id()); capture_info->set_process_name(Capture::capture_data_.process_name()); capture_info->mutable_thread_names()->insert(Capture::capture_data_.thread_names().begin(), Capture::capture_data_.thread_names().end()); capture_info->mutable_address_infos()->Reserve(Capture::capture_data_.address_infos().size()); for (const auto& address_info : Capture::capture_data_.address_infos()) { capture_info->add_address_infos()->CopyFrom(address_info.second); } const absl::flat_hash_map<uint64_t, FunctionStats>& functions_stats = Capture::capture_data_.functions_stats(); capture_info->mutable_function_stats()->insert(functions_stats.begin(), functions_stats.end()); // TODO: this is not really synchronized, since GetCallstacks processing below // is not under the same mutex lock we could end up having list of callstacks // inconsistent with unique_callstacks. Revisit sampling profiler data // thread-safety. Capture::capture_data_.GetCallstackData()->ForEachUniqueCallstack( [&capture_info](const CallStack& call_stack) { CallstackInfo* callstack = capture_info->add_callstacks(); *callstack->mutable_data() = {call_stack.GetFrames().begin(), call_stack.GetFrames().end()}; }); const auto& callstacks = Capture::capture_data_.GetCallstackData()->callstack_events(); capture_info->mutable_callstack_events()->Reserve(callstacks.size()); for (const auto& callstack : callstacks) { capture_info->add_callstack_events()->CopyFrom(callstack); } const auto& key_to_string_map = time_graph_->GetStringManager()->GetKeyToStringMap(); capture_info->mutable_key_to_string()->insert(key_to_string_map.begin(), key_to_string_map.end()); } void CaptureSerializer::Save(std::ostream& stream) { google::protobuf::io::OstreamOutputStream out_stream(&stream); google::protobuf::io::CodedOutputStream coded_output(&out_stream); CHECK(time_graph_ != nullptr); int timers_count = time_graph_->GetNumTimers(); WriteMessage(&header, &coded_output); CaptureInfo capture_info; FillCaptureData(&capture_info); WriteMessage(&capture_info, &coded_output); // Timers int writes_count = 0; std::vector<std::shared_ptr<TimerChain>> chains = time_graph_->GetAllTimerChains(); for (auto& chain : chains) { if (!chain) continue; for (TimerChainIterator it = chain->begin(); it != chain->end(); ++it) { TimerBlock& block = *it; for (uint32_t k = 0; k < block.size(); ++k) { WriteMessage(&block[k].GetTimerInfo(), &coded_output); if (++writes_count > timers_count) { return; } } } } } ErrorMessageOr<void> CaptureSerializer::Load(const std::string& filename) { SCOPE_TIMER_LOG(absl::StrFormat("Loading capture from \"%s\"", filename)); // Binary std::ifstream file(filename, std::ios::binary); if (file.fail()) { ERROR("Loading capture from \"%s\": %s", filename, "file.fail()"); return ErrorMessage("Error opening the file for reading"); } return Load(file); } bool CaptureSerializer::ReadMessage(google::protobuf::Message* message, google::protobuf::io::CodedInputStream* input) { uint32_t message_size; if (!input->ReadLittleEndian32(&message_size)) { return false; } std::unique_ptr<char[]> buffer = make_unique_for_overwrite<char[]>(message_size); if (!input->ReadRaw(buffer.get(), message_size)) { return false; } message->ParseFromArray(buffer.get(), message_size); return true; } static void FillEventBuffer() { GEventTracer.GetEventBuffer().Reset(); for (const CallstackEvent& callstack_event : Capture::capture_data_.GetCallstackData()->callstack_events()) { GEventTracer.GetEventBuffer().AddCallstackEvent( callstack_event.time(), callstack_event.callstack_hash(), callstack_event.thread_id()); } } void CaptureSerializer::ProcessCaptureData(const CaptureInfo& capture_info) { // Clear the old capture GOrbitApp->ClearSelectedFunctions(); absl::flat_hash_map<uint64_t, orbit_client_protos::FunctionInfo> selected_functions; absl::flat_hash_set<uint64_t> visible_functions; for (const auto& function : capture_info.selected_functions()) { uint64_t address = FunctionUtils::GetAbsoluteAddress(function); selected_functions[address] = function; visible_functions.insert(address); } GOrbitApp->SetVisibleFunctions(std::move(visible_functions)); absl::flat_hash_map<uint64_t, FunctionStats> functions_stats{ capture_info.function_stats().begin(), capture_info.function_stats().end()}; CaptureData capture_data(capture_info.process_id(), capture_info.process_name(), std::make_shared<Process>(), std::move(selected_functions), std::move(functions_stats)); absl::flat_hash_map<uint64_t, orbit_client_protos::LinuxAddressInfo> address_infos; address_infos.reserve(capture_info.address_infos_size()); for (const auto& address_info : capture_info.address_infos()) { address_infos[address_info.absolute_address()] = address_info; } capture_data.set_address_infos(std::move(address_infos)); absl::flat_hash_map<int32_t, std::string> thread_names{capture_info.thread_names().begin(), capture_info.thread_names().end()}; capture_data.set_thread_names(thread_names); Capture::capture_data_ = std::move(capture_data); for (CallstackInfo callstack : capture_info.callstacks()) { CallStack unique_callstack({callstack.data().begin(), callstack.data().end()}); Capture::capture_data_.AddUniqueCallStack(std::move(unique_callstack)); } for (CallstackEvent callstack_event : capture_info.callstack_events()) { Capture::capture_data_.AddCallstackEvent(std::move(callstack_event)); } Capture::capture_data_.UpdateSamplingProfiler(); time_graph_->Clear(); StringManager* string_manager = time_graph_->GetStringManager(); string_manager->Clear(); for (const auto& entry : capture_info.key_to_string()) { string_manager->AddIfNotPresent(entry.first, entry.second); } FillEventBuffer(); } ErrorMessageOr<void> CaptureSerializer::Load(std::istream& stream) { google::protobuf::io::IstreamInputStream input_stream(&stream); google::protobuf::io::CodedInputStream coded_input(&input_stream); std::string error_message = "Error parsing the capture.\nNote: If the capture " "was taken with a previous Orbit version, it could be incompatible. " "Please check release notes for more information."; if (!ReadMessage(&header, &coded_input) || header.version().empty()) { ERROR("%s", error_message); return ErrorMessage(error_message); } if (header.version() != kRequiredCaptureVersion) { std::string incompatible_version_error_message = absl::StrFormat( "This capture format is no longer supported but could be opened with " "Orbit version %s.", header.version()); ERROR("%s", incompatible_version_error_message); return ErrorMessage(incompatible_version_error_message); } CaptureInfo capture_info; if (!ReadMessage(&capture_info, &coded_input)) { ERROR("%s", error_message); return ErrorMessage(error_message); } ProcessCaptureData(capture_info); // Timers TimerInfo timer_info; while (ReadMessage(&timer_info, &coded_input)) { time_graph_->ProcessTimer(timer_info); } GOrbitApp->AddSamplingReport(Capture::capture_data_.GetSamplingProfiler(), Capture::capture_data_.GetCallstackData()); GOrbitApp->AddTopDownView(Capture::capture_data_.GetSamplingProfiler()); GOrbitApp->FireRefreshCallbacks(); return outcome::success(); }
38.163424
100
0.723797
[ "vector" ]
3237ef01c01e9f6bba26f9e781fae68c90be44a6
5,235
cpp
C++
src/main.cpp
Reesy/sdl-tridents-of-ardeus
4e806d6ae64177949b24c5f31ecdffee9588c1d0
[ "MIT" ]
null
null
null
src/main.cpp
Reesy/sdl-tridents-of-ardeus
4e806d6ae64177949b24c5f31ecdffee9588c1d0
[ "MIT" ]
null
null
null
src/main.cpp
Reesy/sdl-tridents-of-ardeus
4e806d6ae64177949b24c5f31ecdffee9588c1d0
[ "MIT" ]
null
null
null
#include <stdio.h> #include <string> #include <iostream> #include <components/AnimationComponent.hpp> #include <components/GraphicsComponent.hpp> #include <components/InputComponent.hpp> #include <components/TileComponent.hpp> #include <interfaces/AIInterface.hpp> #include <interfaces/GraphicsInterface.hpp> #include <interfaces/ColliderInterface.hpp> #include <interfaces/InputInterface.hpp> #include <interfaces/SceneInterface.hpp> #include <Entities.hpp> #include <GameEntity.hpp> #include <Resources.hpp> #if __EMSCRIPTEN__ #include <emscripten/emscripten.h> #include <SDL2/SDL.h> #include <SDL2/SDL_image.h> #else #include <SDL.h> #include <SDL_image.h> #endif #undef main #if __EMSCRIPTEN__ //Example on how to interact with JS functions via emscripten if needed EM_JS(int, canvas_get_width, (), { return canvas.width; }); EM_JS(int, canvas_get_height, (), { return canvas.height; }); #endif SDL_Window *window = NULL; SDL_Renderer *renderer = NULL; SDL_Event *event = NULL; SDL_Texture *circle = NULL; SDL_Texture *playerTexture = NULL; SDL_Texture *tileSheet = NULL; SDL_Rect textureRect; SDL_Rect positionRect; Resources resources; InputComponent* sceneInput; bool quit = false; bool falling = true; int SCREEN_WIDTH = 640; //640; int SCREEN_HEIGHT = 480;//480; double dt = 10; //The interval between updating the physics. IE update physics every 100th of a second double currentTime = SDL_GetTicks(); // in miliseconds double accumulator = 0.0; //This will hold the accumulation of physics steps (any time left over if the graphics renders faster than the physics simulates) double velocity = 1; //Scene objects GameEntity* ballEntity = NULL; GameEntity* playerEntity = NULL; GameEntity* levelEntity = NULL; void init() { //Start up SDL and make sure it went ok if (SDL_Init(SDL_INIT_VIDEO) != 0) { throw("SDL failed to initialise"); }; window = SDL_CreateWindow("Tridents Of Ardeus!", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE); if (window == nullptr) { SDL_Quit(); throw("Failed to create window"); }; renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); if(!SDL_RenderSetLogicalSize(renderer, 640, 480)) { std::cout << SDL_GetError() << std::endl; }; if (renderer == nullptr) { window = NULL; SDL_Quit(); throw("Failed to create renderer"); } event = new SDL_Event(); circle = resources.loadTexture("resources/example_texture.png", renderer); playerTexture = resources.loadTexture("resources/player_spritesheet.png", renderer); tileSheet = resources.loadTexture("resources/tilesheet.png", renderer); Entities* Level = new Entities(); playerEntity = Level->createPlayer(playerTexture); levelEntity = Level->createLevel(tileSheet); sceneInput = new InputComponent(); } void input() { if (event->type == SDL_QUIT) { quit = true; }; if (event->window.event == SDL_WINDOWEVENT_RESIZED) { SDL_GetWindowSize(window, &SCREEN_WIDTH, &SCREEN_HEIGHT); std::cout << "The window was resized: " << SCREEN_WIDTH << std::endl; }; if (event->type == SDL_KEYDOWN) { switch (event->key.keysym.sym) { case SDLK_a: levelEntity->x -= 40; break; case SDLK_d: levelEntity->x += 40; break; default: break; }; }; sceneInput->update(event); } void update(double _dt) { playerEntity->components->AnimationComponent->update(*playerEntity, _dt); } void render() { //Sets a background color for the scene SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255); //clears previous frame. SDL_RenderClear(renderer); levelEntity->components->GraphicsComponent->render(*levelEntity, renderer); playerEntity->components->GraphicsComponent->render(*playerEntity, renderer); //Renders current frame. SDL_RenderPresent(renderer); } void mainLoop() { double newTime = SDL_GetTicks(); //in miliseconds double frameTime = newTime - currentTime; //Essentially stores how long the previous frame ran for in miliseconds //limits frame time to 100th of a second if (frameTime > 250) { std::cout << "UPPER BOUND HIT, LAG ENCOUNTERED" << std::endl; frameTime = 250; //Upper bound on the time between processing this loop. If physics simulation is slower than render calculation then the game could halt. }; #if __EMSCRIPTEN__ int canvasWidth = canvas_get_width(); std::cout << "The canvas width was: " << canvasWidth << std::endl; #endif currentTime = newTime; accumulator += frameTime; while ( accumulator >= dt) { update(dt); //consumes dt accumulator -= dt; }; render(); //Produces dt (takes time to calculate) //Event Polling while (SDL_PollEvent(event)) { input(); }; } int main(int, char**) { init(); //When creating a native app (.exe on windows or sh on OSX/Linux this will directly call mainLoop. when running in browser emscripten deals with calls to the main method) #if __EMSCRIPTEN__ emscripten_set_main_loop(mainLoop, -1, 1); #else while (quit != true) { mainLoop(); } #endif SDL_DestroyRenderer( renderer ); SDL_DestroyWindow( window ); renderer = NULL; window = NULL; IMG_Quit(); SDL_Quit(); return 0; }
22.276596
171
0.721108
[ "render" ]
3238c1684129ce959d7bd6b70ccea9e21da58d8d
13,007
cpp
C++
PiratesEngine/src/PiratesEngine/Renderer/Renderer2D.cpp
michaelzaki-12/PiratesEngine
69e875eb2d21350c499245316351552bc217cbcb
[ "MIT" ]
null
null
null
PiratesEngine/src/PiratesEngine/Renderer/Renderer2D.cpp
michaelzaki-12/PiratesEngine
69e875eb2d21350c499245316351552bc217cbcb
[ "MIT" ]
null
null
null
PiratesEngine/src/PiratesEngine/Renderer/Renderer2D.cpp
michaelzaki-12/PiratesEngine
69e875eb2d21350c499245316351552bc217cbcb
[ "MIT" ]
null
null
null
#include "PEPCH.h" #include "Renderer2D.h" #include "glm/gtc/matrix_transform.hpp" #include "RenderCommand.h" namespace Pirates { struct QuadVertex { glm::vec3 position; glm::vec4 Color; glm::vec2 TexCoord; float TexIndex; float TillingFactor = 1.0f; //TODO: Have A texid, may be Something else; }; struct Renderer2DData { static const uint32_t MaxQuads = 100000; static const uint32_t MaxVerticies = MaxQuads * 4; static const uint32_t MaxIndecies= MaxQuads * 6; static const uint32_t MaxTextureSlot = 32; uint32_t IndexCount = 0; Ref<VertexArray> QuadVertexArray; Ref<VertexBuffer> QuadVertexBuffer; Ref<Shader> TextureShader; Ref<Texture2D> Whitetexture; QuadVertex* QuadVertexBufferBase = nullptr; QuadVertex* QuadVertexBufferptr= nullptr; std::array< Ref<Texture2D>, MaxTextureSlot> TextureSlots; uint32_t TextureSlotsIndex = 1; glm::vec4 QuadVertexPosition[4]; Renderer2D::Statistics Stats; }; static Renderer2DData s_Data; void Renderer2D::Init() { PR_PROFILE_FUNCTION(); s_Data.QuadVertexArray = VertexArray::Create(); s_Data.QuadVertexBuffer = VertexBuffer::Create(s_Data.MaxVerticies * sizeof(QuadVertex)); s_Data.QuadVertexBuffer->SetLayout({ { ShaderDataType::Float3, "a_Position" }, { ShaderDataType::Float4, "a_Color" }, { ShaderDataType::Float2, "a_TexCoord" }, { ShaderDataType::Float, "a_TexIndex" }, { ShaderDataType::Float, "a_TillingFactor" }, }); s_Data.QuadVertexArray->AddVertexBuffer(s_Data.QuadVertexBuffer); s_Data.QuadVertexBufferBase = new QuadVertex[s_Data.MaxVerticies]; uint32_t* QuadIndcies = new uint32_t[s_Data.MaxIndecies]; uint32_t offset = 0; for (uint32_t i = 0; i < s_Data.MaxIndecies; i += 6) { QuadIndcies[i + 0] = offset + 0; QuadIndcies[i + 1] = offset + 1; QuadIndcies[i + 2] = offset + 2; QuadIndcies[i + 3] = offset + 2; QuadIndcies[i + 4] = offset + 3; QuadIndcies[i + 5] = offset + 0; offset += 4; } Ref<IndexBuffer> squareIB = IndexBuffer::Create(QuadIndcies, s_Data.MaxIndecies); s_Data.QuadVertexArray->SetIndexBuffer(squareIB); delete[] QuadIndcies; s_Data.Whitetexture = Texture2D::Create(1, 1); uint32_t WhiteTextureData = 0xffffffff; s_Data.Whitetexture->SetData(&WhiteTextureData, sizeof(WhiteTextureData)); uint32_t samplers[s_Data.MaxTextureSlot]; for (int i = 0; i < s_Data.MaxTextureSlot; i++) { samplers[i] = i; } s_Data.TextureShader = Shader::Create("Shaders/texture.glsl"); s_Data.TextureShader->Bind(); s_Data.TextureShader->SetIntArray("u_Texture", (int*)samplers ,s_Data.MaxTextureSlot); //set all texture slots to zero s_Data.TextureSlots[0] = s_Data.Whitetexture; s_Data.QuadVertexPosition[0] = { -0.5f,-0.5f,0.0f,1.0f }; s_Data.QuadVertexPosition[1] = { 0.5f,-0.5f,0.0f,1.0f }; s_Data.QuadVertexPosition[2] = { 0.5f,0.5f,0.0f,1.0f }; s_Data.QuadVertexPosition[3] = { -0.5f,0.5f,0.0f,1.0f }; } void Renderer2D::ShutDown() { PR_PROFILE_FUNCTION(); } void Renderer2D::BeginScene(const OrthoGraphicCamera& m_Camera) { PR_PROFILE_FUNCTION(); s_Data.TextureShader->Bind(); s_Data.TextureShader->SetMat4("u_ViewProjectionMatrix", m_Camera.GetViewProjectionMatrix()); s_Data.IndexCount = 0; s_Data.QuadVertexBufferptr = s_Data.QuadVertexBufferBase; s_Data.TextureSlotsIndex = 1; } void Renderer2D::EndScene() { PR_PROFILE_FUNCTION(); uint32_t datasize = (uint8_t*)s_Data.QuadVertexBufferptr - (uint8_t*)s_Data.QuadVertexBufferBase; s_Data.QuadVertexBuffer->SetData(s_Data.QuadVertexBufferBase, datasize); Flush(); } void Renderer2D::Flush() { for (uint32_t i = 0; i < s_Data.TextureSlotsIndex;i++) { s_Data.TextureSlots[i]->Bind(i); } RenderCommand::DrawIndexed(s_Data.QuadVertexArray, s_Data.IndexCount); s_Data.Stats.DrawCalls++; } void Renderer2D::FlushAndReset() { EndScene(); s_Data.IndexCount = 0; s_Data.QuadVertexBufferptr = s_Data.QuadVertexBufferBase; s_Data.TextureSlotsIndex = 1; } void Renderer2D::DrawQuad(const glm::vec2& Position, const glm::vec2& Size, const glm::vec4& color, const float TillingFactor) { DrawQuad({ Position.x, Position.y, 0.0f }, Size, color, TillingFactor); } void Renderer2D::DrawQuad(const glm::vec3& Position, const glm::vec2& Size, const glm::vec4& color, const float TillingFactor) { PR_PROFILE_FUNCTION(); constexpr float whitetexture = 0.0f; if (s_Data.IndexCount >= Renderer2DData::MaxIndecies) FlushAndReset(); glm::mat4 transform = glm::translate(glm::mat4(1.0f), Position) * glm::scale(glm::mat4(1.0f), { Size.x, Size.y, 1.0f }); s_Data.QuadVertexBufferptr->position = transform * s_Data.QuadVertexPosition[0]; s_Data.QuadVertexBufferptr->Color = color; s_Data.QuadVertexBufferptr->TexCoord = { 0.0f, 0.0f }; s_Data.QuadVertexBufferptr->TexIndex = whitetexture; s_Data.QuadVertexBufferptr++; s_Data.QuadVertexBufferptr->position = transform * s_Data.QuadVertexPosition[1]; s_Data.QuadVertexBufferptr->Color = color; s_Data.QuadVertexBufferptr->TexCoord = { 1.0f, 0.0f }; s_Data.QuadVertexBufferptr->TexIndex = whitetexture; s_Data.QuadVertexBufferptr++; s_Data.QuadVertexBufferptr->position = transform * s_Data.QuadVertexPosition[2]; s_Data.QuadVertexBufferptr->Color = color; s_Data.QuadVertexBufferptr->TexCoord = { 1.0f, 1.0f }; s_Data.QuadVertexBufferptr->TexIndex = whitetexture; s_Data.QuadVertexBufferptr++; s_Data.QuadVertexBufferptr->position = transform * s_Data.QuadVertexPosition[3]; s_Data.QuadVertexBufferptr->Color = color; s_Data.QuadVertexBufferptr->TexCoord = { 0.0f, 1.0f }; s_Data.QuadVertexBufferptr->TexIndex = whitetexture; s_Data.QuadVertexBufferptr++; s_Data.IndexCount += 6; s_Data.Stats.QuadCount++; } void Renderer2D::DrawQuad(const glm::vec2& Position, const glm::vec2& Size, const Ref<Texture2D>& texture, const float TillingFactor) { DrawQuad({ Position.x, Position.y, 0.0f }, Size, texture, TillingFactor); } void Renderer2D::DrawQuad(const glm::vec3& Position, const glm::vec2& Size, const Ref<Texture2D>& texture, const float TillingFactor) { PR_PROFILE_FUNCTION(); if (s_Data.IndexCount >= Renderer2DData::MaxIndecies) FlushAndReset(); constexpr glm::vec4 color = { 1.0f,1.0f ,1.0f ,1.0f }; float textureindex = 0; for (uint32_t i = 1; i < s_Data.TextureSlotsIndex; i++) { if (*s_Data.TextureSlots[i].get() == *texture.get()) { textureindex = (float)i; break; } } if (textureindex == 0.0f) { textureindex = (float)s_Data.TextureSlotsIndex; s_Data.TextureSlots[s_Data.TextureSlotsIndex] = texture; s_Data.TextureSlotsIndex++; } glm::mat4 transform = glm::translate(glm::mat4(1.0f), Position) * glm::scale(glm::mat4(1.0f), { Size.x, Size.y, 1.0f }); s_Data.QuadVertexBufferptr->position = transform * s_Data.QuadVertexPosition[0]; s_Data.QuadVertexBufferptr->Color = color; s_Data.QuadVertexBufferptr->TexCoord = { 0.0f, 0.0f }; s_Data.QuadVertexBufferptr->TexIndex = textureindex; s_Data.QuadVertexBufferptr->TillingFactor = TillingFactor; s_Data.QuadVertexBufferptr++; s_Data.QuadVertexBufferptr->position = transform * s_Data.QuadVertexPosition[1]; s_Data.QuadVertexBufferptr->Color = color; s_Data.QuadVertexBufferptr->TexCoord = { 1.0f, 0.0f }; s_Data.QuadVertexBufferptr->TexIndex = textureindex; s_Data.QuadVertexBufferptr->TillingFactor = TillingFactor; s_Data.QuadVertexBufferptr++; s_Data.QuadVertexBufferptr->position = transform * s_Data.QuadVertexPosition[2]; s_Data.QuadVertexBufferptr->Color = color; s_Data.QuadVertexBufferptr->TexCoord = { 1.0f, 1.0f }; s_Data.QuadVertexBufferptr->TexIndex = textureindex; s_Data.QuadVertexBufferptr->TillingFactor = TillingFactor; s_Data.QuadVertexBufferptr++; s_Data.QuadVertexBufferptr->position = transform * s_Data.QuadVertexPosition[3]; s_Data.QuadVertexBufferptr->Color = color; s_Data.QuadVertexBufferptr->TexCoord = { 0.0f, 1.0f }; s_Data.QuadVertexBufferptr->TexIndex = textureindex; s_Data.QuadVertexBufferptr->TillingFactor = TillingFactor; s_Data.QuadVertexBufferptr++; s_Data.IndexCount += 6; s_Data.Stats.QuadCount++; } void Renderer2D::DrawRotatedQuad(const glm::vec2& Position, const glm::vec2& Size, float Rotation, const glm::vec4& color, const float TillingFactor) { DrawRotatedQuad({ Position.x, Position.y, 0.0f }, Size, Rotation, color, TillingFactor); } void Renderer2D::DrawRotatedQuad(const glm::vec3& Position, const glm::vec2& Size, float Rotation, const glm::vec4& color, const float TillingFactor) { if (s_Data.IndexCount >= Renderer2DData::MaxIndecies) FlushAndReset(); float textureindex = 0; glm::mat4 transform = glm::translate(glm::mat4(1.0f), Position) * glm::rotate(glm::mat4(1.0f), Rotation,{ 0.0f, 0.0f, 1.0f }) * glm::scale(glm::mat4(1.0f), { Size.x, Size.y, 1.0f }); s_Data.QuadVertexBufferptr->position = transform * s_Data.QuadVertexPosition[0]; s_Data.QuadVertexBufferptr->Color = color; s_Data.QuadVertexBufferptr->TexCoord = { 0.0f, 0.0f }; s_Data.QuadVertexBufferptr->TexIndex = textureindex; s_Data.QuadVertexBufferptr->TillingFactor = TillingFactor; s_Data.QuadVertexBufferptr++; s_Data.QuadVertexBufferptr->position = transform * s_Data.QuadVertexPosition[1]; s_Data.QuadVertexBufferptr->Color = color; s_Data.QuadVertexBufferptr->TexCoord = { 1.0f, 0.0f }; s_Data.QuadVertexBufferptr->TexIndex = textureindex; s_Data.QuadVertexBufferptr->TillingFactor = TillingFactor; s_Data.QuadVertexBufferptr++; s_Data.QuadVertexBufferptr->position = transform * s_Data.QuadVertexPosition[2]; s_Data.QuadVertexBufferptr->Color = color; s_Data.QuadVertexBufferptr->TexCoord = { 1.0f, 1.0f }; s_Data.QuadVertexBufferptr->TexIndex = textureindex; s_Data.QuadVertexBufferptr->TillingFactor = TillingFactor; s_Data.QuadVertexBufferptr++; s_Data.QuadVertexBufferptr->position = transform * s_Data.QuadVertexPosition[3]; s_Data.QuadVertexBufferptr->Color = color; s_Data.QuadVertexBufferptr->TexCoord = { 0.0f, 1.0f }; s_Data.QuadVertexBufferptr->TexIndex = textureindex; s_Data.QuadVertexBufferptr->TillingFactor = TillingFactor; s_Data.QuadVertexBufferptr++; s_Data.IndexCount += 6; s_Data.Stats.QuadCount++; } void Renderer2D::DrawRotatedQuad(const glm::vec2& Position, const glm::vec2& Size, float Rotation, const Ref<Texture2D>& texture, const float TillingFactor) { DrawRotatedQuad({ Position.x, Position.y, 0.0f}, Size, Rotation, texture, TillingFactor); } void Renderer2D::DrawRotatedQuad(const glm::vec3& Position, const glm::vec2& Size, float Rotation, const Ref<Texture2D>& texture, const float TillingFactor) { PR_PROFILE_FUNCTION(); if (s_Data.IndexCount >= Renderer2DData::MaxIndecies) FlushAndReset(); constexpr glm::vec4 color = { 1.0f,1.0f ,1.0f ,1.0f }; float textureindex = 0; for (uint32_t i = 1; i < s_Data.TextureSlotsIndex; i++) { if (*s_Data.TextureSlots[i].get() == *texture.get()) { textureindex = (float)i; break; } } if (textureindex == 0.0f) { textureindex = (float)s_Data.TextureSlotsIndex; s_Data.TextureSlots[s_Data.TextureSlotsIndex] = texture; s_Data.TextureSlotsIndex++; } glm::mat4 transform = glm::translate(glm::mat4(1.0f), Position) * glm::rotate(glm::mat4(1.0f), Rotation, { 0.0f, 0.0f, 1.0f }) * glm::scale(glm::mat4(1.0f), { Size.x, Size.y, 1.0f }); s_Data.QuadVertexBufferptr->position = transform * s_Data.QuadVertexPosition[0]; s_Data.QuadVertexBufferptr->Color = color; s_Data.QuadVertexBufferptr->TexCoord = { 0.0f, 0.0f }; s_Data.QuadVertexBufferptr->TexIndex = textureindex; s_Data.QuadVertexBufferptr->TillingFactor = TillingFactor; s_Data.QuadVertexBufferptr++; s_Data.QuadVertexBufferptr->position = transform * s_Data.QuadVertexPosition[1]; s_Data.QuadVertexBufferptr->Color = color; s_Data.QuadVertexBufferptr->TexCoord = { 1.0f, 0.0f }; s_Data.QuadVertexBufferptr->TexIndex = textureindex; s_Data.QuadVertexBufferptr->TillingFactor = TillingFactor; s_Data.QuadVertexBufferptr++; s_Data.QuadVertexBufferptr->position = transform * s_Data.QuadVertexPosition[2]; s_Data.QuadVertexBufferptr->Color = color; s_Data.QuadVertexBufferptr->TexCoord = { 1.0f, 1.0f }; s_Data.QuadVertexBufferptr->TexIndex = textureindex; s_Data.QuadVertexBufferptr->TillingFactor = TillingFactor; s_Data.QuadVertexBufferptr++; s_Data.QuadVertexBufferptr->position = transform * s_Data.QuadVertexPosition[3]; s_Data.QuadVertexBufferptr->Color = color; s_Data.QuadVertexBufferptr->TexCoord = { 0.0f, 1.0f }; s_Data.QuadVertexBufferptr->TexIndex = textureindex; s_Data.QuadVertexBufferptr->TillingFactor = TillingFactor; s_Data.QuadVertexBufferptr++; s_Data.IndexCount += 6; s_Data.Stats.QuadCount++; } Renderer2D::Statistics Renderer2D::GetStats() { return s_Data.Stats; } void Renderer2D::ResetStats() { memset(&s_Data.Stats, 0, sizeof(Statistics)); } }
33.096692
157
0.731452
[ "transform" ]
323cda181d68cb8f3a1f85e34dcc34fb8fe05f2b
4,505
cpp
C++
puzzle15/puzzle15_2.cpp
schnaader/AdventOfCode2021
0808282f90e4ef97edf130f228435860f332e1d3
[ "Apache-2.0" ]
1
2021-12-19T12:34:03.000Z
2021-12-19T12:34:03.000Z
puzzle15/puzzle15_2.cpp
schnaader/AdventOfCode2021
0808282f90e4ef97edf130f228435860f332e1d3
[ "Apache-2.0" ]
null
null
null
puzzle15/puzzle15_2.cpp
schnaader/AdventOfCode2021
0808282f90e4ef97edf130f228435860f332e1d3
[ "Apache-2.0" ]
null
null
null
#include <stdio.h> #include <iostream> #include <fstream> #include <sstream> #include <string> #include <vector> #include <unordered_set> #include <array> #include <stack> #include <map> #include <set> #include <algorithm> #include <cmath> #include <chrono> std::array<int, 500*500> map; std::array<int, 500*500> bigger_map; int w, h; double distance(int x1, int y1, int x2, int y2) { int dx = x2 - x1; int dy = y2 - y1; return sqrt(dx * dx + dy*dy); } struct Node { int id; int x; int y; bool is_open; double risk_so_far; double estimated_risk; double risk_sum; }; Node create_node(int id, int x, int y, double risk_so_far) { Node result; result.id = 0; result.is_open = true; result.x = x; result.y = y; result.risk_so_far = risk_so_far; result.estimated_risk = distance(x, y, w - 1, h - 1); result.risk_sum = risk_so_far + result.estimated_risk; return result; } int main() { //bool input_is_larger_version = true; //std::ifstream input("example_part2.txt"); // expected result: 315 //bool input_is_larger_version = false; //std::ifstream input("example.txt"); // expected result: 315 bool input_is_larger_version = false; std::ifstream input("input.txt"); // note: takes some time (27 minutes on my machine) if (!input.is_open()) { printf("Error opening file\n"); return -1; } w = 0; h = 0; std::string line; while (getline(input, line)) { if (w == 0) { w = line.length(); } else if (w != line.length()) { printf("Error: Input is not consistent\n"); return -1; } for (int x = 0; x < w; x++) { map[h * w + x] = line[x] - '0'; } h++; } if (!input_is_larger_version) { // generate complete map by copying and incrementing for (int ym = 0; ym < 5; ym++) { for (int xm = 0; xm < 5; xm++) { int increment = xm + ym; for (int y = 0; y < w; y++) { for (int x = 0; x < w; x++) { int new_value = map[y * w + x] + increment; if ((new_value) > 9) new_value -= 9; bigger_map[(h * ym + y) * w * 5 + (w * xm + x)] = new_value; } } } } map = bigger_map; w *= 5; h *= 5; } std::vector<Node> nodes; Node start = create_node(0, 0, 0, 0); nodes.push_back(start); auto begin = std::chrono::steady_clock::now(); for (;;) { // find (open) node with smallest risk sum auto sorted_nodes = nodes; std::erase_if(sorted_nodes, [](Node n) { return !n.is_open; }); std::sort(sorted_nodes.begin(), sorted_nodes.end(), [](Node a, Node b) { return a.risk_sum < b.risk_sum; }); auto smallest_risk_node = sorted_nodes[0]; //printf("Smallest risk at (%i, %i)\n", smallest_risk_node.x, smallest_risk_node.y); // close node ... for (auto& n : nodes) { if (n.id == smallest_risk_node.id) { n.is_open = false; } } // ... and expand std::vector<Node> expanded_nodes; int x = smallest_risk_node.x; int y = smallest_risk_node.y; int r = smallest_risk_node.risk_so_far; if (x > 0) { expanded_nodes.push_back(create_node(0, x - 1, y, r + map[y * w + x - 1])); } if (x < w - 1) { expanded_nodes.push_back(create_node(0, x + 1, y, r + map[y * w + x + 1])); } if (y > 0) { expanded_nodes.push_back(create_node(0, x, y - 1, r + map[(y - 1) * w + x])); } if (y < h - 1) { expanded_nodes.push_back(create_node(0, x, y + 1, r + map[(y + 1) * w + x])); } // only add expanded nodes if the position is new - else check if old node has to be replaced // also check if any of the expanded nodes reached the goal for (auto& e : expanded_nodes) { if ((e.x == w - 1) && (e.y == h - 1)) { std::cout << "Total risk: " << e.risk_sum << "\n"; auto end = std::chrono::steady_clock::now(); std::cout << "Elapsed time: " << std::chrono::duration_cast<std::chrono::milliseconds>(end - begin).count() << "ms\n"; return 0; } bool position_is_new = true; for (auto& n : nodes) { if ((n.x == e.x) && (n.y == e.y)) { position_is_new = false; if (e.risk_sum < n.risk_sum) { n.risk_so_far = e.risk_so_far; n.estimated_risk = e.estimated_risk; n.risk_sum = e.risk_sum; n.is_open = true; } break; } } if (position_is_new) { e.id = nodes.size(); nodes.push_back(e); } } //printf("Node count: %li\n", nodes.size()); } return 0; }
24.752747
122
0.56626
[ "vector" ]
32443f526be43b245398d4007258b626c78f6c42
18,373
cpp
C++
Source/WebCore/bindings/scripts/test/JS/JSTestPromiseRejectionEvent.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
6
2021-07-05T16:09:39.000Z
2022-03-06T22:44:42.000Z
Source/WebCore/bindings/scripts/test/JS/JSTestPromiseRejectionEvent.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
7
2022-03-15T13:25:39.000Z
2022-03-15T13:25:44.000Z
Source/WebCore/bindings/scripts/test/JS/JSTestPromiseRejectionEvent.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
null
null
null
/* This file is part of the WebKit open source project. This file has been generated by generate-bindings.pl. DO NOT MODIFY! This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "config.h" #include "JSTestPromiseRejectionEvent.h" #include "ActiveDOMObject.h" #include "DOMIsoSubspaces.h" #include "DOMPromiseProxy.h" #include "JSDOMAttribute.h" #include "JSDOMBinding.h" #include "JSDOMConstructor.h" #include "JSDOMConvertAny.h" #include "JSDOMConvertBoolean.h" #include "JSDOMConvertInterface.h" #include "JSDOMConvertPromise.h" #include "JSDOMConvertStrings.h" #include "JSDOMExceptionHandling.h" #include "JSDOMGlobalObject.h" #include "JSDOMWrapperCache.h" #include "ScriptExecutionContext.h" #include "WebCoreJSClientData.h" #include <JavaScriptCore/HeapAnalyzer.h> #include <JavaScriptCore/JSCInlines.h> #include <JavaScriptCore/JSDestructibleObjectHeapCellType.h> #include <JavaScriptCore/SubspaceInlines.h> #include <wtf/GetPtr.h> #include <wtf/PointerPreparations.h> #include <wtf/URL.h> namespace WebCore { using namespace JSC; template<> TestPromiseRejectionEvent::Init convertDictionary<TestPromiseRejectionEvent::Init>(JSGlobalObject& lexicalGlobalObject, JSValue value) { VM& vm = JSC::getVM(&lexicalGlobalObject); auto throwScope = DECLARE_THROW_SCOPE(vm); bool isNullOrUndefined = value.isUndefinedOrNull(); auto* object = isNullOrUndefined ? nullptr : value.getObject(); if (UNLIKELY(!isNullOrUndefined && !object)) { throwTypeError(&lexicalGlobalObject, throwScope); return { }; } TestPromiseRejectionEvent::Init result; JSValue bubblesValue; if (isNullOrUndefined) bubblesValue = jsUndefined(); else { bubblesValue = object->get(&lexicalGlobalObject, Identifier::fromString(vm, "bubbles")); RETURN_IF_EXCEPTION(throwScope, { }); } if (!bubblesValue.isUndefined()) { result.bubbles = convert<IDLBoolean>(lexicalGlobalObject, bubblesValue); RETURN_IF_EXCEPTION(throwScope, { }); } else result.bubbles = false; JSValue cancelableValue; if (isNullOrUndefined) cancelableValue = jsUndefined(); else { cancelableValue = object->get(&lexicalGlobalObject, Identifier::fromString(vm, "cancelable")); RETURN_IF_EXCEPTION(throwScope, { }); } if (!cancelableValue.isUndefined()) { result.cancelable = convert<IDLBoolean>(lexicalGlobalObject, cancelableValue); RETURN_IF_EXCEPTION(throwScope, { }); } else result.cancelable = false; JSValue composedValue; if (isNullOrUndefined) composedValue = jsUndefined(); else { composedValue = object->get(&lexicalGlobalObject, Identifier::fromString(vm, "composed")); RETURN_IF_EXCEPTION(throwScope, { }); } if (!composedValue.isUndefined()) { result.composed = convert<IDLBoolean>(lexicalGlobalObject, composedValue); RETURN_IF_EXCEPTION(throwScope, { }); } else result.composed = false; JSValue promiseValue; if (isNullOrUndefined) promiseValue = jsUndefined(); else { promiseValue = object->get(&lexicalGlobalObject, Identifier::fromString(vm, "promise")); RETURN_IF_EXCEPTION(throwScope, { }); } if (!promiseValue.isUndefined()) { result.promise = convert<IDLPromise<IDLAny>>(lexicalGlobalObject, promiseValue); RETURN_IF_EXCEPTION(throwScope, { }); } else { throwRequiredMemberTypeError(lexicalGlobalObject, throwScope, "promise", "TestPromiseRejectionEventInit", "Promise"); return { }; } JSValue reasonValue; if (isNullOrUndefined) reasonValue = jsUndefined(); else { reasonValue = object->get(&lexicalGlobalObject, Identifier::fromString(vm, "reason")); RETURN_IF_EXCEPTION(throwScope, { }); } if (!reasonValue.isUndefined()) { result.reason = convert<IDLAny>(lexicalGlobalObject, reasonValue); RETURN_IF_EXCEPTION(throwScope, { }); } else result.reason = jsUndefined(); return result; } // Attributes JSC::EncodedJSValue jsTestPromiseRejectionEventConstructor(JSC::JSGlobalObject*, JSC::EncodedJSValue, JSC::PropertyName); bool setJSTestPromiseRejectionEventConstructor(JSC::JSGlobalObject*, JSC::EncodedJSValue, JSC::EncodedJSValue); JSC::EncodedJSValue jsTestPromiseRejectionEventPromise(JSC::JSGlobalObject*, JSC::EncodedJSValue, JSC::PropertyName); JSC::EncodedJSValue jsTestPromiseRejectionEventReason(JSC::JSGlobalObject*, JSC::EncodedJSValue, JSC::PropertyName); class JSTestPromiseRejectionEventPrototype final : public JSC::JSNonFinalObject { public: using Base = JSC::JSNonFinalObject; static JSTestPromiseRejectionEventPrototype* create(JSC::VM& vm, JSDOMGlobalObject* globalObject, JSC::Structure* structure) { JSTestPromiseRejectionEventPrototype* ptr = new (NotNull, JSC::allocateCell<JSTestPromiseRejectionEventPrototype>(vm.heap)) JSTestPromiseRejectionEventPrototype(vm, globalObject, structure); ptr->finishCreation(vm); return ptr; } DECLARE_INFO; template<typename CellType, JSC::SubspaceAccess> static JSC::IsoSubspace* subspaceFor(JSC::VM& vm) { STATIC_ASSERT_ISO_SUBSPACE_SHARABLE(JSTestPromiseRejectionEventPrototype, Base); return &vm.plainObjectSpace; } static JSC::Structure* createStructure(JSC::VM& vm, JSC::JSGlobalObject* globalObject, JSC::JSValue prototype) { return JSC::Structure::create(vm, globalObject, prototype, JSC::TypeInfo(JSC::ObjectType, StructureFlags), info()); } private: JSTestPromiseRejectionEventPrototype(JSC::VM& vm, JSC::JSGlobalObject*, JSC::Structure* structure) : JSC::JSNonFinalObject(vm, structure) { } void finishCreation(JSC::VM&); }; STATIC_ASSERT_ISO_SUBSPACE_SHARABLE(JSTestPromiseRejectionEventPrototype, JSTestPromiseRejectionEventPrototype::Base); using JSTestPromiseRejectionEventConstructor = JSDOMConstructor<JSTestPromiseRejectionEvent>; template<> EncodedJSValue JSC_HOST_CALL JSTestPromiseRejectionEventConstructor::construct(JSGlobalObject* lexicalGlobalObject, CallFrame* callFrame) { VM& vm = lexicalGlobalObject->vm(); auto throwScope = DECLARE_THROW_SCOPE(vm); auto* castedThis = jsCast<JSTestPromiseRejectionEventConstructor*>(callFrame->jsCallee()); ASSERT(castedThis); if (UNLIKELY(callFrame->argumentCount() < 2)) return throwVMError(lexicalGlobalObject, throwScope, createNotEnoughArgumentsError(lexicalGlobalObject)); EnsureStillAliveScope argument0 = callFrame->uncheckedArgument(0); auto type = convert<IDLDOMString>(*lexicalGlobalObject, argument0.value()); RETURN_IF_EXCEPTION(throwScope, encodedJSValue()); EnsureStillAliveScope argument1 = callFrame->uncheckedArgument(1); auto eventInitDict = convert<IDLDictionary<TestPromiseRejectionEvent::Init>>(*lexicalGlobalObject, argument1.value()); RETURN_IF_EXCEPTION(throwScope, encodedJSValue()); auto object = TestPromiseRejectionEvent::create(*castedThis->globalObject(), WTFMove(type), WTFMove(eventInitDict)); static_assert(decltype(object)::isRef); auto jsValue = toJSNewlyCreated<IDLInterface<TestPromiseRejectionEvent>>(*lexicalGlobalObject, *castedThis->globalObject(), WTFMove(object)); setSubclassStructureIfNeeded<TestPromiseRejectionEvent>(lexicalGlobalObject, callFrame, asObject(jsValue)); RETURN_IF_EXCEPTION(throwScope, { }); return JSValue::encode(jsValue); } template<> JSValue JSTestPromiseRejectionEventConstructor::prototypeForStructure(JSC::VM& vm, const JSDOMGlobalObject& globalObject) { return JSEvent::getConstructor(vm, &globalObject); } template<> void JSTestPromiseRejectionEventConstructor::initializeProperties(VM& vm, JSDOMGlobalObject& globalObject) { putDirect(vm, vm.propertyNames->prototype, JSTestPromiseRejectionEvent::prototype(vm, globalObject), JSC::PropertyAttribute::DontDelete | JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::DontEnum); putDirect(vm, vm.propertyNames->name, jsNontrivialString(vm, "TestPromiseRejectionEvent"_s), JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::DontEnum); putDirect(vm, vm.propertyNames->length, jsNumber(2), JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::DontEnum); } template<> const ClassInfo JSTestPromiseRejectionEventConstructor::s_info = { "TestPromiseRejectionEvent", &Base::s_info, nullptr, nullptr, CREATE_METHOD_TABLE(JSTestPromiseRejectionEventConstructor) }; /* Hash table for prototype */ static const HashTableValue JSTestPromiseRejectionEventPrototypeTableValues[] = { { "constructor", static_cast<unsigned>(JSC::PropertyAttribute::DontEnum), NoIntrinsic, { (intptr_t)static_cast<PropertySlot::GetValueFunc>(jsTestPromiseRejectionEventConstructor), (intptr_t) static_cast<PutPropertySlot::PutValueFunc>(setJSTestPromiseRejectionEventConstructor) } }, { "promise", static_cast<unsigned>(JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::CustomAccessor), NoIntrinsic, { (intptr_t)static_cast<PropertySlot::GetValueFunc>(jsTestPromiseRejectionEventPromise), (intptr_t) static_cast<PutPropertySlot::PutValueFunc>(0) } }, { "reason", static_cast<unsigned>(JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::CustomAccessor | JSC::PropertyAttribute::DOMAttribute), NoIntrinsic, { (intptr_t)static_cast<PropertySlot::GetValueFunc>(jsTestPromiseRejectionEventReason), (intptr_t) static_cast<PutPropertySlot::PutValueFunc>(0) } }, }; const ClassInfo JSTestPromiseRejectionEventPrototype::s_info = { "TestPromiseRejectionEvent", &Base::s_info, nullptr, nullptr, CREATE_METHOD_TABLE(JSTestPromiseRejectionEventPrototype) }; void JSTestPromiseRejectionEventPrototype::finishCreation(VM& vm) { Base::finishCreation(vm); reifyStaticProperties(vm, JSTestPromiseRejectionEvent::info(), JSTestPromiseRejectionEventPrototypeTableValues, *this); JSC_TO_STRING_TAG_WITHOUT_TRANSITION(); } const ClassInfo JSTestPromiseRejectionEvent::s_info = { "TestPromiseRejectionEvent", &Base::s_info, nullptr, nullptr, CREATE_METHOD_TABLE(JSTestPromiseRejectionEvent) }; JSTestPromiseRejectionEvent::JSTestPromiseRejectionEvent(Structure* structure, JSDOMGlobalObject& globalObject, Ref<TestPromiseRejectionEvent>&& impl) : JSEvent(structure, globalObject, WTFMove(impl)) { } void JSTestPromiseRejectionEvent::finishCreation(VM& vm) { Base::finishCreation(vm); ASSERT(inherits(vm, info())); static_assert(!std::is_base_of<ActiveDOMObject, TestPromiseRejectionEvent>::value, "Interface is not marked as [ActiveDOMObject] even though implementation class subclasses ActiveDOMObject."); } JSObject* JSTestPromiseRejectionEvent::createPrototype(VM& vm, JSDOMGlobalObject& globalObject) { return JSTestPromiseRejectionEventPrototype::create(vm, &globalObject, JSTestPromiseRejectionEventPrototype::createStructure(vm, &globalObject, JSEvent::prototype(vm, globalObject))); } JSObject* JSTestPromiseRejectionEvent::prototype(VM& vm, JSDOMGlobalObject& globalObject) { return getDOMPrototype<JSTestPromiseRejectionEvent>(vm, globalObject); } JSValue JSTestPromiseRejectionEvent::getConstructor(VM& vm, const JSGlobalObject* globalObject) { return getDOMConstructor<JSTestPromiseRejectionEventConstructor>(vm, *jsCast<const JSDOMGlobalObject*>(globalObject)); } template<> inline JSTestPromiseRejectionEvent* IDLAttribute<JSTestPromiseRejectionEvent>::cast(JSGlobalObject& lexicalGlobalObject, EncodedJSValue thisValue) { return jsDynamicCast<JSTestPromiseRejectionEvent*>(JSC::getVM(&lexicalGlobalObject), JSValue::decode(thisValue)); } EncodedJSValue jsTestPromiseRejectionEventConstructor(JSGlobalObject* lexicalGlobalObject, EncodedJSValue thisValue, PropertyName) { VM& vm = JSC::getVM(lexicalGlobalObject); auto throwScope = DECLARE_THROW_SCOPE(vm); auto* prototype = jsDynamicCast<JSTestPromiseRejectionEventPrototype*>(vm, JSValue::decode(thisValue)); if (UNLIKELY(!prototype)) return throwVMTypeError(lexicalGlobalObject, throwScope); return JSValue::encode(JSTestPromiseRejectionEvent::getConstructor(JSC::getVM(lexicalGlobalObject), prototype->globalObject())); } bool setJSTestPromiseRejectionEventConstructor(JSGlobalObject* lexicalGlobalObject, EncodedJSValue thisValue, EncodedJSValue encodedValue) { VM& vm = JSC::getVM(lexicalGlobalObject); auto throwScope = DECLARE_THROW_SCOPE(vm); auto* prototype = jsDynamicCast<JSTestPromiseRejectionEventPrototype*>(vm, JSValue::decode(thisValue)); if (UNLIKELY(!prototype)) { throwVMTypeError(lexicalGlobalObject, throwScope); return false; } // Shadowing a built-in constructor return prototype->putDirect(vm, vm.propertyNames->constructor, JSValue::decode(encodedValue)); } static inline JSValue jsTestPromiseRejectionEventPromiseGetter(JSGlobalObject& lexicalGlobalObject, JSTestPromiseRejectionEvent& thisObject) { auto& vm = JSC::getVM(&lexicalGlobalObject); auto throwScope = DECLARE_THROW_SCOPE(vm); auto& impl = thisObject.wrapped(); RELEASE_AND_RETURN(throwScope, (toJS<IDLPromise<IDLAny>>(lexicalGlobalObject, *thisObject.globalObject(), throwScope, impl.promise()))); } EncodedJSValue jsTestPromiseRejectionEventPromise(JSGlobalObject* lexicalGlobalObject, EncodedJSValue thisValue, PropertyName) { return IDLAttribute<JSTestPromiseRejectionEvent>::get<jsTestPromiseRejectionEventPromiseGetter, CastedThisErrorBehavior::RejectPromise>(*lexicalGlobalObject, thisValue, "promise"); } static inline JSValue jsTestPromiseRejectionEventReasonGetter(JSGlobalObject& lexicalGlobalObject, JSTestPromiseRejectionEvent& thisObject) { auto& vm = JSC::getVM(&lexicalGlobalObject); auto throwScope = DECLARE_THROW_SCOPE(vm); auto& impl = thisObject.wrapped(); RELEASE_AND_RETURN(throwScope, (toJS<IDLAny>(lexicalGlobalObject, throwScope, impl.reason()))); } EncodedJSValue jsTestPromiseRejectionEventReason(JSGlobalObject* lexicalGlobalObject, EncodedJSValue thisValue, PropertyName) { return IDLAttribute<JSTestPromiseRejectionEvent>::get<jsTestPromiseRejectionEventReasonGetter, CastedThisErrorBehavior::Assert>(*lexicalGlobalObject, thisValue, "reason"); } JSC::IsoSubspace* JSTestPromiseRejectionEvent::subspaceForImpl(JSC::VM& vm) { auto& clientData = *static_cast<JSVMClientData*>(vm.clientData); auto& spaces = clientData.subspaces(); if (auto* space = spaces.m_subspaceForTestPromiseRejectionEvent.get()) return space; static_assert(std::is_base_of_v<JSC::JSDestructibleObject, JSTestPromiseRejectionEvent> || !JSTestPromiseRejectionEvent::needsDestruction); if constexpr (std::is_base_of_v<JSC::JSDestructibleObject, JSTestPromiseRejectionEvent>) spaces.m_subspaceForTestPromiseRejectionEvent = makeUnique<IsoSubspace> ISO_SUBSPACE_INIT(vm.heap, vm.destructibleObjectHeapCellType.get(), JSTestPromiseRejectionEvent); else spaces.m_subspaceForTestPromiseRejectionEvent = makeUnique<IsoSubspace> ISO_SUBSPACE_INIT(vm.heap, vm.cellHeapCellType.get(), JSTestPromiseRejectionEvent); auto* space = spaces.m_subspaceForTestPromiseRejectionEvent.get(); IGNORE_WARNINGS_BEGIN("unreachable-code") IGNORE_WARNINGS_BEGIN("tautological-compare") if (&JSTestPromiseRejectionEvent::visitOutputConstraints != &JSC::JSCell::visitOutputConstraints) clientData.outputConstraintSpaces().append(space); IGNORE_WARNINGS_END IGNORE_WARNINGS_END return space; } void JSTestPromiseRejectionEvent::analyzeHeap(JSCell* cell, HeapAnalyzer& analyzer) { auto* thisObject = jsCast<JSTestPromiseRejectionEvent*>(cell); analyzer.setWrappedObjectForCell(cell, &thisObject->wrapped()); if (thisObject->scriptExecutionContext()) analyzer.setLabelForCell(cell, "url " + thisObject->scriptExecutionContext()->url().string()); Base::analyzeHeap(cell, analyzer); } #if ENABLE(BINDING_INTEGRITY) #if PLATFORM(WIN) #pragma warning(disable: 4483) extern "C" { extern void (*const __identifier("??_7TestPromiseRejectionEvent@WebCore@@6B@")[])(); } #else extern "C" { extern void* _ZTVN7WebCore25TestPromiseRejectionEventE[]; } #endif #endif JSC::JSValue toJSNewlyCreated(JSC::JSGlobalObject*, JSDOMGlobalObject* globalObject, Ref<TestPromiseRejectionEvent>&& impl) { #if ENABLE(BINDING_INTEGRITY) const void* actualVTablePointer = getVTablePointer(impl.ptr()); #if PLATFORM(WIN) void* expectedVTablePointer = __identifier("??_7TestPromiseRejectionEvent@WebCore@@6B@"); #else void* expectedVTablePointer = &_ZTVN7WebCore25TestPromiseRejectionEventE[2]; #endif // If this fails TestPromiseRejectionEvent does not have a vtable, so you need to add the // ImplementationLacksVTable attribute to the interface definition static_assert(std::is_polymorphic<TestPromiseRejectionEvent>::value, "TestPromiseRejectionEvent is not polymorphic"); // If you hit this assertion you either have a use after free bug, or // TestPromiseRejectionEvent has subclasses. If TestPromiseRejectionEvent has subclasses that get passed // to toJS() we currently require TestPromiseRejectionEvent you to opt out of binding hardening // by adding the SkipVTableValidation attribute to the interface IDL definition RELEASE_ASSERT(actualVTablePointer == expectedVTablePointer); #endif return createWrapper<TestPromiseRejectionEvent>(globalObject, WTFMove(impl)); } JSC::JSValue toJS(JSC::JSGlobalObject* lexicalGlobalObject, JSDOMGlobalObject* globalObject, TestPromiseRejectionEvent& impl) { return wrap(lexicalGlobalObject, globalObject, impl); } }
48.60582
315
0.773907
[ "object" ]
324a599e095058113a3038d6e13b32d6c7191d55
1,132
cpp
C++
catkin_ws/src/agitr/src/spawn_turtle.cpp
gromovnik1337/ROS_OD_SC
e11ea0780e193a3b045b578d7bf3688ee4aa99f0
[ "Apache-2.0" ]
null
null
null
catkin_ws/src/agitr/src/spawn_turtle.cpp
gromovnik1337/ROS_OD_SC
e11ea0780e193a3b045b578d7bf3688ee4aa99f0
[ "Apache-2.0" ]
null
null
null
catkin_ws/src/agitr/src/spawn_turtle.cpp
gromovnik1337/ROS_OD_SC
e11ea0780e193a3b045b578d7bf3688ee4aa99f0
[ "Apache-2.0" ]
null
null
null
// This program spawns a new turtlesim turtle by calling the appropriate ros service. #include <ros/ros.h> // srv class for the service. #include <turtlesim/Spawn.h> int main(int argc, char **argv) { ros::init(argc, argv, "spawn_turtle"); ros::NodeHandle nh; // Create a client object which takes the data type of the service and its name as an argument. ros::ServiceClient spawnClient = nh.serviceClient<turtlesim::Spawn>("spawn"); // Create the request and response objects. turtlesim::Spawn::Request req; turtlesim::Spawn::Response resp; // Fill in the request object data members. Response object data members are not filled because those informations are provided by the server. req.x = 2; req.y = 3; req.theta = M_PI / 2; req.name = "Leo"; // Call the service. This call will return nothing until the service is complete. bool success = spawnClient.call(req, resp); // Check for success and use the response. if(success) { ROS_INFO_STREAM("Spawned a turtle named " << resp.name); } else { ROS_ERROR_STREAM("Failed to spawn."); } }
33.294118
146
0.681095
[ "object" ]
324da04cc26fb8feb1bc0d803e8834fb69169050
1,389
hpp
C++
cpp/include/cg3/common/kd_tree.hpp
tychota/cg3-path-tracer
548519121cacb01a4be835c0bece21238b56f92b
[ "Beerware" ]
null
null
null
cpp/include/cg3/common/kd_tree.hpp
tychota/cg3-path-tracer
548519121cacb01a4be835c0bece21238b56f92b
[ "Beerware" ]
null
null
null
cpp/include/cg3/common/kd_tree.hpp
tychota/cg3-path-tracer
548519121cacb01a4be835c0bece21238b56f92b
[ "Beerware" ]
null
null
null
# pragma once # include "cg3/common/primitive_group.hpp" # include "cg3/common/box.hpp" # ifdef _MSC_VER # pragma warning (disable: 4996) # endif //kd_tree_group class kd_tree : public primitive_group { public: //abstract class of a node of a kd-tree. class kd_node { public: virtual ~kd_node(){} virtual bool is_leaf() const=0; }; //root node of the tree kd_node* root; // bounding box of the whole tree box bounds; //The maximum depth of the tree std::size_t max_depth; //The minimum number of primitives per leaf node. std::size_t min_size; public: kd_tree( std::size_t max_depth = 25, std::size_t min_size = 4 ); bool add_obj_mesh( std::string const& filename, bool scale = true ); void add_primitive( primitive* p ); void clear(); void build_tree_spatial_median(); ~kd_tree(); // kD-tree traversal algorithm TA_rec_B by Vlastimil Havran // see Havran's dissertation thesis (Nov 2000), Appendix C virtual bool closest_intersection( intersection_info* hit, si::length min_lambda ); virtual bool any_intersection( ray& r, si::length min_lambda, si::length max_lambda ); protected: kd_node* build_tree_spatial_median( std::vector<primitive*> &primitives, box &bounds, unsigned int depth ); };
25.722222
113
0.649388
[ "vector" ]
3252403116502e2f234980f06e39fbecf4672cfa
12,040
cc
C++
src/Clustering/Gmm.cc
alexanderrichard/squirrel
12614a9eb429500c8f341654043f33a1b6bd1d31
[ "AFL-3.0" ]
63
2016-07-08T13:35:27.000Z
2021-01-13T18:37:13.000Z
src/Clustering/Gmm.cc
alexanderrichard/squirrel
12614a9eb429500c8f341654043f33a1b6bd1d31
[ "AFL-3.0" ]
4
2017-08-04T09:25:10.000Z
2022-02-24T15:38:52.000Z
src/Clustering/Gmm.cc
alexanderrichard/squirrel
12614a9eb429500c8f341654043f33a1b6bd1d31
[ "AFL-3.0" ]
30
2016-05-11T02:24:46.000Z
2021-11-12T14:06:20.000Z
/* * Copyright 2016 Alexander Richard * * This file is part of Squirrel. * * Licensed under the Academic Free License 3.0 (the "License"). * You may not use this file except in compliance with the License. * You should have received a copy of the License along with Squirrel. * If not, see <https://opensource.org/licenses/AFL-3.0>. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ /* * GmmTrainer.cc * * Created on: Jan 13, 2015 * Author: richard */ #include "Gmm.hh" using namespace Clustering; /* * GmmBase */ const Core::ParameterString GmmBase::paramMeanInputFile_("mean-input-file", "", "clustering.gaussian-mixture-model"); const Core::ParameterString GmmBase::paramVarianceInputFile_("variance-input-file", "", "clustering.gaussian-mixture-model"); const Core::ParameterString GmmBase::paramWeightsInputFile_("weights-input-file", "", "clustering.gaussian-mixture-model"); const Core::ParameterString GmmBase::paramMeanOutputFile_("mean-output-file", "", "clustering.gaussian-mixture-model"); const Core::ParameterString GmmBase::paramVarianceOutputFile_("variance-output-file", "", "clustering.gaussian-mixture-model"); const Core::ParameterString GmmBase::paramWeightsOutputFile_("weights-output-file", "", "clustering.gaussian-mixture-model"); GmmBase::GmmBase() : meanInputFile_(Core::Configuration::config(paramMeanInputFile_)), varianceInputFile_(Core::Configuration::config(paramVarianceInputFile_)), weightsInputFile_(Core::Configuration::config(paramWeightsInputFile_)), meanOutputFile_(Core::Configuration::config(paramMeanOutputFile_)), varianceOutputFile_(Core::Configuration::config(paramVarianceOutputFile_)), weightsOutputFile_(Core::Configuration::config(paramWeightsOutputFile_)) {} /* * GmmTrainer */ const Core::ParameterFloat GmmTrainer::paramMinVariance_("minimal-variance", 1e-07, "clustering.gaussian-mixture-model"); const Core::ParameterInt GmmTrainer::paramMaxIterations_("iterations", 10, "clustering.gaussian-mixture-model"); const Core::ParameterInt GmmTrainer::paramNumberOfDensities_("number-of-densities", 1, "clustering.gaussian-mixture-model"); const Core::ParameterInt GmmTrainer::paramBatchSize_("batch-size", 4096, "clustering.gaussian-mixture-model"); const Core::ParameterBool GmmTrainer::paramMaximumApproximation_("maximum-approximation", false, "clustering.gaussian-mixture-model"); GmmTrainer::GmmTrainer() : minVariance_(Core::Configuration::config(paramMinVariance_)), maxIterations_(Core::Configuration::config(paramMaxIterations_)), nMixtures_(Core::Configuration::config(paramNumberOfDensities_)), batchSize_(Core::Configuration::config(paramBatchSize_)), maximumApproximation_(Core::Configuration::config(paramMaximumApproximation_)), logLik_(Types::max<Float>()) {} void GmmTrainer::initializeParameters() { /* initialize mean */ if (!meanInputFile_.empty()) { Core::Log::os("load means from ") << meanInputFile_; oldMu_.read(meanInputFile_, true); require_eq(featureReader_.featureDimension(), oldMu_.nRows()); require_eq(nMixtures_, oldMu_.nColumns()); } else { Core::Log::os("initialize means randomly"); oldMu_.resize(featureReader_.featureDimension(), nMixtures_); Math::Random::initializeSRand(); // generate random indices std::vector<u32> indices(featureReader_.totalNumberOfFeatures()); for (u32 i = 0; i < featureReader_.totalNumberOfFeatures(); i++) { indices[i] = i; } std::random_shuffle(indices.begin(), indices.end(), Math::Random::randomIntBelow); // make a reversely sorted index array out of this indices.resize(nMixtures_); std::sort(indices.begin(), indices.end()); std::reverse(indices.begin(), indices.end()); // assign the features with the selected indices to the clusters u32 c = 0; for (u32 i = 0; i < featureReader_.totalNumberOfFeatures(); i++) { const Math::Vector<Float>& f = featureReader_.next(); if (indices.back() == i) { indices.pop_back(); for (u32 d = 0; d < featureReader_.featureDimension(); d++) { oldMu_.at(d, c) = f.at(d); } c++; } } } /* initialize variance */ if (!varianceInputFile_.empty()) { Core::Log::os("load variances from ") << varianceInputFile_; oldSigma_.read(varianceInputFile_, true); require_eq(featureReader_.featureDimension(), oldSigma_.nRows()); require_eq(nMixtures_, oldSigma_.nColumns()); } else { oldSigma_.resize(featureReader_.featureDimension(), nMixtures_); oldSigma_.initComputation(); oldSigma_.fill(1); } /* initialize weights */ if (!weightsInputFile_.empty()) { Core::Log::os("load weights from ") << weightsInputFile_; oldWeights_.read(weightsInputFile_); require_eq(nMixtures_, oldWeights_.nRows()); } else { oldWeights_.resize(nMixtures_); oldWeights_.initComputation(); oldWeights_.fill(1.0 / nMixtures_); } } void GmmTrainer::initialize() { featureReader_.initialize(); // initialize parameters initializeParameters(); // set to computation mode oldMu_.initComputation(); oldSigma_.initComputation(); oldWeights_.initComputation(); newMu_.initComputation(); newSigma_.initComputation(); newWeights_.initComputation(); posteriors_.initComputation(); lambda_.initComputation(); bias_.initComputation(); tmpMatrix_.initComputation(); tmpVector_.initComputation(); // resize newMu_.resize(featureReader_.featureDimension(), nMixtures_); newSigma_.resize(featureReader_.featureDimension(), nMixtures_); newWeights_.resize(nMixtures_); lambda_.resize(2 * featureReader_.featureDimension(), nMixtures_); bias_.resize(nMixtures_); } void GmmTrainer::writeParameters() { require(!meanOutputFile_.empty()); require(!varianceOutputFile_.empty()); require(!weightsOutputFile_.empty()); oldMu_.finishComputation(); oldSigma_.finishComputation(); oldWeights_.finishComputation(); oldMu_.write(meanOutputFile_, true); oldSigma_.write(varianceOutputFile_, true); oldWeights_.write(weightsOutputFile_); } void GmmTrainer::transformForSoftmax() { bias_.setToZero(); lambda_.finishComputation(false); bias_.finishComputation(); oldMu_.finishComputation(); oldSigma_.finishComputation(); oldWeights_.finishComputation(); for (u32 c = 0; c < nMixtures_; c++) { for (u32 d = 0; d < featureReader_.featureDimension(); d++) { lambda_.at(d, c) = oldMu_.at(d, c) / oldSigma_.at(d, c); lambda_.at(d + featureReader_.featureDimension(), c) = -0.5 / oldSigma_.at(d, c); bias_.at(c) += pow(oldMu_.at(d, c), 2) / oldSigma_.at(d, c) + log(oldSigma_.at(d, c)); } bias_.at(c) = log(oldWeights_.at(c)) -0.5 * (bias_.at(c) + featureReader_.featureDimension() * log(2*M_PI)); } bias_.initComputation(); lambda_.initComputation(); oldMu_.initComputation(false); oldSigma_.initComputation(false); oldWeights_.initComputation(false); } void GmmTrainer::computePosteriors() { tmpMatrix_.resize(buffer_.nRows() * 2, buffer_.nColumns()); tmpMatrix_.setToDiagonalSecondOrderFeatures(buffer_); posteriors_.resize(nMixtures_, tmpMatrix_.nColumns()); posteriors_.setToZero(); posteriors_.addMatrixProduct(lambda_, tmpMatrix_, 0, 1, true, false); posteriors_.addToAllColumns(bias_); // compute log likelihood score in a numerically stable way if (maximumApproximation_) { tmpVector_.resize(buffer_.nColumns()); tmpVector_.getMaxOfColumns(posteriors_); logLik_ += tmpVector_.sum(); } else { tmpVector_.resize(buffer_.nColumns()); tmpVector_.setToZero(); tmpMatrix_.resize(posteriors_.nRows(), posteriors_.nColumns()); tmpMatrix_.copy(posteriors_); tmpVector_.swap(tmpMatrix_); Float max = tmpVector_.get(tmpVector_.argMax()); tmpVector_.swap(tmpMatrix_); tmpMatrix_.resize(posteriors_.nRows(), posteriors_.nColumns()); tmpMatrix_.addConstantElementwise(-max); tmpMatrix_.exp(); tmpVector_.addSummedRows(tmpMatrix_); tmpVector_.log(); logLik_ += tmpVector_.sum() + tmpVector_.size() * max; } if (maximumApproximation_) posteriors_.max(); else posteriors_.softmax(); } void GmmTrainer::updateParameters() { computePosteriors(); newWeights_.addSummedColumns(posteriors_); newMu_.addMatrixProduct(buffer_, posteriors_, 1, 1, false, true); buffer_.elementwiseMultiplication(buffer_); newSigma_.addMatrixProduct(buffer_, posteriors_, 1, 1, false, true); } void GmmTrainer::finalizeEstimation() { newMu_.divideColumnsByScalars(newWeights_); newSigma_.divideColumnsByScalars(newWeights_); tmpMatrix_.resize(newMu_.nRows(), newMu_.nColumns()); tmpMatrix_.copy(newMu_); tmpMatrix_.elementwiseMultiplication(tmpMatrix_); newSigma_.add(tmpMatrix_, (Float)-1); newWeights_.scale(1.0 / featureReader_.totalNumberOfFeatures()); newSigma_.ensureMinimalValue(minVariance_); } void GmmTrainer::bufferFeatures() { buffer_.finishComputation(false); buffer_.resize(featureReader_.featureDimension(), batchSize_); u32 nBufferedFeatures = 0; while ((featureReader_.hasFeatures()) && (nBufferedFeatures < batchSize_)) { const Math::Vector<Float>& f = featureReader_.next(); for (u32 i = 0; i < f.size(); i++) { buffer_.at(i, nBufferedFeatures) = f.at(i); } nBufferedFeatures++; } buffer_.safeResize(buffer_.nRows(), nBufferedFeatures); buffer_.initComputation(); } void GmmTrainer::generateClustering() { Core::Log::openTag("gaussian-mixture-model-generation"); Float oldLogLik = Types::min<Float>(); for (u32 iter = 0; iter < maxIterations_; iter++) { Core::Log::os("Start iteration ") << iter + 1; newMu_.setToZero(); newSigma_.setToZero(); newWeights_.setToZero(); transformForSoftmax(); logLik_ = 0; featureReader_.newEpoch(); while (featureReader_.hasFeatures()) { bufferFeatures(); updateParameters(); } finalizeEstimation(); Core::Log::os("log-likelihood score: ") << logLik_; oldMu_.swap(newMu_); oldSigma_.swap(newSigma_); oldWeights_.swap(newWeights_); //TODO: implement as two-pass algorithm for numerical stability logLik_ /= featureReader_.totalNumberOfFeatures(); if ((logLik_ > Types::min<Float>()) && (logLik_ < Types::max<Float>()) && (oldLogLik >= logLik_)) { break; } oldLogLik = logLik_; } Core::Log::closeTag(); writeParameters(); } /* * GmmDensitySplitter */ void GmmDensitySplitter::readParameters() { require(!meanInputFile_.empty()); require(!varianceInputFile_.empty()); require(!weightsInputFile_.empty()); oldMu_.read(meanInputFile_, true); oldSigma_.read(varianceInputFile_, true); oldWeights_.read(weightsInputFile_); } void GmmDensitySplitter::writeParameters() { require(!meanOutputFile_.empty()); require(!varianceOutputFile_.empty()); require(!weightsOutputFile_.empty()); // save new parameters in scientific format newMu_.write(meanOutputFile_, true, true); newSigma_.write(varianceOutputFile_, true, true); newWeights_.write(weightsOutputFile_, true); } void GmmDensitySplitter::split() { readParameters(); // split means // TODO: shift in direction of largest variance oldMu_.scale(1.0001); newMu_.resize(oldMu_.nRows(), 2 * oldMu_.nColumns()); newMu_.copyBlockFromMatrix(oldMu_, 0, 0, 0, 0, oldMu_.nRows(), oldMu_.nColumns()); oldMu_.scale(0.999 / 1.0001); newMu_.copyBlockFromMatrix(oldMu_, 0, 0, 0, oldMu_.nColumns(), oldMu_.nRows(), oldMu_.nColumns()); // split variances newSigma_.resize(oldSigma_.nRows(), 2 * oldSigma_.nColumns()); newSigma_.copyBlockFromMatrix(oldSigma_, 0, 0, 0, 0, oldSigma_.nRows(), oldSigma_.nColumns()); newSigma_.copyBlockFromMatrix(oldSigma_, 0, 0, 0, oldSigma_.nColumns(), oldSigma_.nRows(), oldSigma_.nColumns()); // split weights newWeights_.resize(2 * oldWeights_.nRows()); Math::Matrix<Float> tmp1; Math::Matrix<Float> tmp2; tmp1.swap(oldWeights_); tmp2.swap(newWeights_); tmp2.copyBlockFromMatrix(tmp1, 0, 0, 0, 0, tmp1.nRows(), tmp1.nColumns()); tmp2.copyBlockFromMatrix(tmp1, 0, 0, tmp1.nRows(), 0, tmp1.nRows(), tmp1.nColumns()); tmp2.swap(newWeights_); newWeights_.scale(0.5); writeParameters(); }
35.204678
134
0.742691
[ "vector", "model" ]
32524483c0facde855a3449ca859f0219e9d81af
1,054
cpp
C++
comp-prog-club/spring-2019/practice-3/reachableroads/mitch/reachableroads.cpp
sudopluto/comp-prog-practice
f4bcb9c1ef4aed4e18393bf6953b152e2788331e
[ "MIT" ]
null
null
null
comp-prog-club/spring-2019/practice-3/reachableroads/mitch/reachableroads.cpp
sudopluto/comp-prog-practice
f4bcb9c1ef4aed4e18393bf6953b152e2788331e
[ "MIT" ]
null
null
null
comp-prog-club/spring-2019/practice-3/reachableroads/mitch/reachableroads.cpp
sudopluto/comp-prog-practice
f4bcb9c1ef4aed4e18393bf6953b152e2788331e
[ "MIT" ]
null
null
null
#include <iostream> #include <string.h> #include <vector> using namespace std; class Node { public: vector<Node*> neighbors; bool isVisited; void search() { isVisited = true; for (auto node : neighbors) { if (!node->isVisited) { node->search(); } } } Node() { isVisited = false; } void addNeighbor(Node* n) { neighbors.push_back(n); } }; int main(int argc, char* argv[]) { int x; cin >> x; for (int i = 0; i < x; i++) { int acc = 0; int y; cin >> y; vector<Node*> graph; for (int j = 0; j < y; j++) { Node* n = new Node(); graph.push_back(n); } int z; cin >> z; for (int k = 0; k < z; k++) { int a, b; cin >> a; cin >> b; graph.at(a)->addNeighbor(graph.at(b)); graph.at(b)->addNeighbor(graph.at(a)); } for (auto n : graph) { if (!n->isVisited) { acc++; n->search(); } } cout << acc - 1 << endl; } return 0; }
14.84507
44
0.455408
[ "vector" ]
32577f740ecf6e6ec3779d421e88aa48eb7f9de4
1,483
cpp
C++
PTA/1036.cpp
wenbo1188/Data-Structure-Review
727f65af03c8c76eafefd5dff6208392ce7a1298
[ "MIT" ]
null
null
null
PTA/1036.cpp
wenbo1188/Data-Structure-Review
727f65af03c8c76eafefd5dff6208392ce7a1298
[ "MIT" ]
null
null
null
PTA/1036.cpp
wenbo1188/Data-Structure-Review
727f65af03c8c76eafefd5dff6208392ce7a1298
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; typedef struct { string name; string gen; string id; int grade; }Student; vector<Student> m; vector<Student> f; int cmp1(Student a, Student b) { return a.grade < b.grade; } int cmp2(Student a, Student b) { return a.grade > b.grade; } int main() { // freopen("in.txt", "r", stdin); int N = 0; string name; string gen; string id; int grade = 0; Student tmp; scanf("%d", &N); for (int i = 0;i < N;++i) { cin >> name >> gen >> id >> grade; // cout << name << gen << id << grade; tmp.name = name; tmp.gen = gen; tmp.id = id; tmp.grade = grade; if (gen == "M") { m.push_back(tmp); } else { f.push_back(tmp); } } if (m.size() == 0) { sort(f.begin(), f.end(), cmp2); cout << f[0].name << " " << f[0].id << endl; printf("Absent\n"); cout << "NA" << endl; return 0; } if (f.size() == 0) { printf("Absent\n"); sort(m.begin(), m.end(), cmp1); cout << m[0].name << " " << m[0].id << endl; cout << "NA" << endl; return 0; } sort(m.begin(), m.end(), cmp1); sort(f.begin(), f.end(), cmp2); cout << f[0].name << " " << f[0].id << endl; cout << m[0].name << " " << m[0].id << endl; cout << f[0].grade - m[0].grade << endl; return 0; }
20.040541
52
0.439649
[ "vector" ]
3259a2a6bacec33ae6985ad763f378229c328202
17,316
cpp
C++
src/Util.cpp
nguyentientungduong/node-api
84cb0fee6890c71a598f3b8f521cead1a5b10fdd
[ "Apache-2.0" ]
null
null
null
src/Util.cpp
nguyentientungduong/node-api
84cb0fee6890c71a598f3b8f521cead1a5b10fdd
[ "Apache-2.0" ]
null
null
null
src/Util.cpp
nguyentientungduong/node-api
84cb0fee6890c71a598f3b8f521cead1a5b10fdd
[ "Apache-2.0" ]
null
null
null
/* Copyright (c) 2020 TOSHIBA Digital Solutions Corporation. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <string> #include <limits> #include "Util.h" #include "Macro.h" #include "GSException.h" /** * @brief Allocate new memory and setup string data from source string data for the new memory * @param *from A pointer stores source string data * @return A pointer variable that refers to new string data */ const GSChar* Util::strdup(const GSChar *from) { if (from == NULL) { return NULL; } GSChar *temp = new char[strlen(from) + 1](); strncpy(temp, from, strlen(from)); return temp; } Napi::Value Util::fromRow(const Napi::Env &env, GSRow *row, int columnCount, GSType *typeList) { Napi::Array ouput = Napi::Array::New(env); for (int i = 0; i < columnCount; i++) { ouput[i] = Util::fromField(env, row, i, typeList[i]); } return ouput; } static bool isNull(GSRow* row, int32_t rowField) { GSBool nullValue; GSResult ret; ret = gsGetRowFieldNull(row, (int32_t) rowField, &nullValue); if (ret != GS_RESULT_OK) { return false; } if (nullValue == GS_TRUE) { return true; } return false; } void Util::freeStrData(Napi::Env env, void* data) { delete [] reinterpret_cast<GSChar *>(data); } static Napi::Value fromFieldAsLong(const Napi::Env& env, GSRow* row, int column) { int64_t longValue; GSResult ret = gsGetRowFieldAsLong(row, (int32_t) column, &longValue); ENSURE_SUCCESS_CPP(Util::fromFieldAsLong, ret) if (longValue) { return Napi::Number::New(env, longValue); } else if (isNull(row, column)) { // NULL value return env.Null(); } else { return Napi::Number::New(env, longValue); } } static Napi::Value fromFieldAsString(const Napi::Env& env, GSRow* row, int column) { GSChar *stringValue; GSResult ret = gsGetRowFieldAsString(row, (int32_t) column, (const GSChar**) &stringValue); ENSURE_SUCCESS_CPP(Util::fromFieldAsString, ret) if ((stringValue != NULL) && (stringValue[0] == '\0')) { // Empty string if (isNull(row, column)) { // NULL value return env.Null(); } else { return Napi::String::New(env, stringValue); } } else { return Napi::String::New(env, stringValue); } } static Napi::Value fromFieldAsBlob(const Napi::Env& env, GSRow* row, int column) { GSBlob blobValue; GSResult ret = gsGetRowFieldAsBlob(row, (int32_t) column, &blobValue); ENSURE_SUCCESS_CPP(Util::fromFieldAsBlob, ret) const GSChar* string; if (blobValue.size) { string = Util::strdup((const GSChar *) blobValue.data); return Napi::Buffer<char>::New(env, const_cast<char*>(string), blobValue.size, Util::freeStrData); } else if (isNull(row, column)) { // NULL value return env.Null(); } else { string = Util::strdup((const GSChar *) blobValue.data); return Napi::Buffer<char>::New(env, const_cast<char*>(string), blobValue.size, Util::freeStrData); } } static Napi::Value fromFieldAsBool(const Napi::Env& env, GSRow* row, int column) { GSBool boolValue; GSResult ret = gsGetRowFieldAsBool(row, (int32_t) column, &boolValue); ENSURE_SUCCESS_CPP(Util::fromFieldAsBool, ret) if (boolValue) { return Napi::Boolean::New(env, static_cast<bool>(boolValue)); } else if (isNull(row, column)) { // NULL value return env.Null(); } else { return Napi::Boolean::New(env, static_cast<bool>(boolValue)); } } static Napi::Value fromFieldAsInteger(const Napi::Env& env, GSRow* row, int column) { int32_t intValue; GSResult ret = gsGetRowFieldAsInteger(row, (int32_t) column, &intValue); ENSURE_SUCCESS_CPP(Util::fromFieldAsInteger, ret) if (intValue) { return Napi::Number::New(env, intValue); } else if (isNull(row, column)) { // NULL value return env.Null(); } else { return Napi::Number::New(env, intValue); } } static Napi::Value fromFieldAsFloat(const Napi::Env& env, GSRow* row, int column) { float floatValue; GSResult ret = gsGetRowFieldAsFloat(row, (int32_t) column, &floatValue); ENSURE_SUCCESS_CPP(Util::fromFieldAsFloat, ret) if (floatValue) { return Napi::Number::New(env, floatValue); } else if (isNull(row, column)) { // NULL value return env.Null(); } else { return Napi::Number::New(env, floatValue); } } static Napi::Value fromFieldAsDouble(const Napi::Env& env, GSRow* row, int column) { double doubleValue; GSResult ret = gsGetRowFieldAsDouble(row, (int32_t) column, &doubleValue); ENSURE_SUCCESS_CPP(Util::fromFieldAsDouble, ret) if (doubleValue) { return Napi::Number::New(env, doubleValue); } else if (isNull(row, column)) { // NULL value return env.Null(); } else { return Napi::Number::New(env, doubleValue); } } static Napi::Value fromFieldAsTimestamp(const Napi::Env &env, GSRow *row, int column) { GSTimestamp timestampValue; GSResult ret = gsGetRowFieldAsTimestamp(row, (int32_t) column, &timestampValue); ENSURE_SUCCESS_CPP(Util::fromFieldAsTimestamp, ret) if (timestampValue) { return Util::fromTimestamp(env, &timestampValue); } else if (isNull(row, column)) { // NULL value return env.Null(); } else { return Util::fromTimestamp(env, &timestampValue); } } static Napi::Value fromFieldAsByte(const Napi::Env& env, GSRow* row, int column) { int8_t byteValue; GSResult ret = gsGetRowFieldAsByte(row, (int32_t) column, &byteValue); ENSURE_SUCCESS_CPP(Util::fromFieldAsInteger, ret) if (byteValue) { return Napi::Number::New(env, byteValue); } else if (isNull(row, column)) { // NULL value return env.Null(); } else { return Napi::Number::New(env, byteValue); } } static Napi::Value fromFieldAsShort(const Napi::Env& env, GSRow* row, int column) { int16_t shortValue; GSResult ret = gsGetRowFieldAsShort(row, (int32_t) column, &shortValue); ENSURE_SUCCESS_CPP(Util::fromFieldAsShort, ret) if (shortValue) { return Napi::Number::New(env, shortValue); } else if (isNull(row, column)) { // NULL value return env.Null(); } else { return Napi::Number::New(env, shortValue); } } static Napi::Value fromFieldAsGeometry(const Napi::Env& env, GSRow* row, int column) { GSChar *geoValue; GSResult ret = gsGetRowFieldAsGeometry(row, (int32_t) column, (const GSChar**) &geoValue); ENSURE_SUCCESS_CPP(Util::fromFieldAsGeometry, ret) if ((geoValue != NULL) && (geoValue[0] == '\0')) { // Empty string if (isNull(row, column)) { // NULL value return env.Null(); } else { return Napi::String::New(env, geoValue); } } else { return Napi::String::New(env, geoValue); } } Napi::Value Util::fromField(const Napi::Env& env, GSRow* row, int column, GSType type) { switch (type) { case GS_TYPE_LONG: return fromFieldAsLong(env, row, column); break; case GS_TYPE_STRING: return fromFieldAsString(env, row, column); break; case GS_TYPE_BLOB: return fromFieldAsBlob(env, row, column); break; case GS_TYPE_BOOL: return fromFieldAsBool(env, row, column); break; case GS_TYPE_INTEGER: return fromFieldAsInteger(env, row, column); break; case GS_TYPE_FLOAT: return fromFieldAsFloat(env, row, column); break; case GS_TYPE_DOUBLE: return fromFieldAsDouble(env, row, column); break; case GS_TYPE_TIMESTAMP: return fromFieldAsTimestamp(env, row, column); break; case GS_TYPE_BYTE: return fromFieldAsByte(env, row, column); break; case GS_TYPE_SHORT: return fromFieldAsShort(env, row, column); break; case GS_TYPE_GEOMETRY: return fromFieldAsGeometry(env, row, column); break; default: THROW_EXCEPTION_WITH_STR(env, "Type is not support.", NULL) } return env.Null(); } Napi::Value Util::fromTimestamp(const Napi::Env& env, GSTimestamp *timestamp) { #if (NAPI_VERSION > 4) return Napi::Date::New(env, *timestamp); #else return Napi::Number::New(env, *timestamp); #endif } static void toFieldAsString(const Napi::Env &env, Napi::Value *value, GSRow *row, int column) { if (!value->IsString()) { THROW_CPP_EXCEPTION_WITH_STR(env, "Input error, should be string") return; } std::string stringVal; stringVal = value->As<Napi::String>().Utf8Value(); GSResult ret = gsSetRowFieldByString(row, column, stringVal.c_str()); ENSURE_SUCCESS_CPP(Util::toFieldAsString, ret) } static void toFieldAsLong(const Napi::Env &env, Napi::Value *value, GSRow *row, int column) { if (!value->IsNumber()) { THROW_CPP_EXCEPTION_WITH_STR(env, "Input error, should be long") return; } // input can be integer int64_t longVal = value->As<Napi::Number>().Int64Value(); // When input value is integer, // it should be between -9007199254740992(-2^53)/9007199254740992(2^53). if (!(MIN_LONG <= longVal && MAX_LONG >= longVal)) { THROW_EXCEPTION_WITH_STR(env, "Input error, should be in range of long", NULL) return; } GSResult ret = gsSetRowFieldByLong(row, column, longVal); ENSURE_SUCCESS_CPP(Util::toFieldAsLong, ret) } static void toFieldAsBool(const Napi::Env &env, Napi::Value *value, GSRow *row, int column) { bool boolVal; if (value->IsBoolean() || value->IsNumber()) { boolVal = value->ToBoolean().Value(); } else { THROW_CPP_EXCEPTION_WITH_STR(env, "Input error, should be bool") return; } GSResult ret = gsSetRowFieldByBool(row, column, boolVal); ENSURE_SUCCESS_CPP(Util::toFieldAsBool, ret) } static void toFieldAsByte(const Napi::Env &env, Napi::Value *value, GSRow *row, int column) { if (!value->IsNumber()) { THROW_CPP_EXCEPTION_WITH_STR(env, "Input error, should be byte") return; } int tmpInt = value->As<Napi::Number>().Int32Value(); if (tmpInt < std::numeric_limits < int8_t > ::min() || tmpInt > std::numeric_limits < int8_t > ::max()) { THROW_CPP_EXCEPTION_WITH_STR(env, "Input error, should be in range of byte") return; } GSResult ret = gsSetRowFieldByByte(row, column, tmpInt); ENSURE_SUCCESS_CPP(Util::toFieldAsByte, ret) } static void toFieldAsShort(const Napi::Env &env, Napi::Value *value, GSRow *row, int column) { if (!value->IsNumber()) { THROW_CPP_EXCEPTION_WITH_STR(env, "Input error, should be short") return; } int tmpInt = value->As<Napi::Number>().Int32Value(); if (tmpInt < std::numeric_limits < int16_t > ::min() || tmpInt > std::numeric_limits < int16_t > ::max()) { THROW_CPP_EXCEPTION_WITH_STR(env, "Input error, should be in range of short") return; } GSResult ret = gsSetRowFieldByShort(row, column, tmpInt); ENSURE_SUCCESS_CPP(Util::toFieldAsShort, ret) } static void toFieldAsInteger(const Napi::Env &env, Napi::Value *value, GSRow *row, int column) { if (!value->IsNumber()) { THROW_CPP_EXCEPTION_WITH_STR(env, "Input error, should be integer") return; } int tmpInt = value->As<Napi::Number>().Int32Value(); GSResult ret = gsSetRowFieldByInteger(row, column, tmpInt); ENSURE_SUCCESS_CPP(Util::toFieldAsInteger, ret) } static void toFieldAsFloat(const Napi::Env &env, Napi::Value *value, GSRow *row, int column) { if (!value->IsNumber()) { THROW_CPP_EXCEPTION_WITH_STR(env, "Input error, should be float") return; } float floatVal = value->As<Napi::Number>().FloatValue(); GSResult ret = gsSetRowFieldByFloat(row, column, floatVal); ENSURE_SUCCESS_CPP(Util::toFieldAsFloat, ret) } static void toFieldAsDouble(const Napi::Env &env, Napi::Value *value, GSRow *row, int column) { if (!value->IsNumber()) { Napi::Object gsException = griddb::GSException::New(env, "Input error, should be double"); THROW_GSEXCEPTION(gsException) return; } double doubleVal = value->As<Napi::Number>().DoubleValue(); GSResult ret = gsSetRowFieldByDouble(row, column, doubleVal); ENSURE_SUCCESS_CPP(Util::toFieldAsDouble, ret) } GSTimestamp Util::toGsTimestamp(const Napi::Env &env, Napi::Value *value) { GSTimestamp timestampVal; #if (NAPI_VERSION > 4) if (value->IsDate()) { timestampVal = value->As<Napi::Date>().ValueOf(); return timestampVal; } #endif if (value->IsString()) { std::string datetimestring = value->As<Napi::String>().ToString().Utf8Value(); GSBool ret = gsParseTime( (const GSChar *)datetimestring.c_str(), &timestampVal); if (ret != GS_TRUE) { Napi::Object gsException = griddb::GSException::New( env, "Invalid datetime string"); THROW_GSEXCEPTION(gsException) return 0; } } else if (value->IsNumber()) { timestampVal = value->As<Napi::Number>().Int64Value(); if (timestampVal > (UTC_TIMESTAMP_MAX * 1000)) { // miliseconds Napi::Object gsException = griddb::GSException::New( env, "Invalid timestamp"); THROW_GSEXCEPTION(gsException) return 0; } } else { // Invalid input Napi::Object gsException = griddb::GSException::New( env, "Invalid input"); THROW_GSEXCEPTION(gsException) return 0; } return timestampVal; } static void toFieldAsTimestamp(const Napi::Env &env, Napi::Value *value, GSRow *row, int column) { GSTimestamp timestampVal = Util::toGsTimestamp(env, value); GSBool ret = gsSetRowFieldByTimestamp(row, column, timestampVal); ENSURE_SUCCESS_CPP(Util::toFieldAsTimestamp, ret) } static void toFieldAsBlob(const Napi::Env &env, Napi::Value *value, GSRow *row, int column) { GSBlob blobVal; if (!value->IsBuffer()) { Napi::Object gsException = griddb::GSException::New(env, "Input error, should be buffer"); THROW_GSEXCEPTION(gsException) return; } Napi::Buffer<char> stringBuffer = value->As<Napi::Buffer<char>>(); char *v = static_cast<char*>(stringBuffer.Data()); size_t size = stringBuffer.Length(); blobVal.data = v; blobVal.size = size; GSBool ret = gsSetRowFieldByBlob(row, column, (const GSBlob*) &blobVal); ENSURE_SUCCESS_CPP(Util::toFieldAsBlob, ret) } static void toFieldAsNull(const Napi::Env &env, Napi::Value *value, GSRow *row, int column) { GSResult ret = gsSetRowFieldNull(row, column); ENSURE_SUCCESS_CPP(Util::toFieldAsNull, ret) } void Util::toField(const Napi::Env &env, Napi::Value *value, GSRow *row, int column, GSType type) { if (value->IsNull() || value->IsUndefined()) { toFieldAsNull(env, value, row, column); return; } switch (type) { case GS_TYPE_STRING: { toFieldAsString(env, value, row, column); break; } case GS_TYPE_LONG: { toFieldAsLong(env, value, row, column); break; } case GS_TYPE_BOOL: { toFieldAsBool(env, value, row, column); break; } case GS_TYPE_BYTE: { toFieldAsByte(env, value, row, column); break; } case GS_TYPE_SHORT: { toFieldAsShort(env, value, row, column); break; } case GS_TYPE_INTEGER: { toFieldAsInteger(env, value, row, column); break; } case GS_TYPE_FLOAT: { toFieldAsFloat(env, value, row, column); break; } case GS_TYPE_DOUBLE: { toFieldAsDouble(env, value, row, column); break; } case GS_TYPE_TIMESTAMP: { toFieldAsTimestamp(env, value, row, column); break; } case GS_TYPE_BLOB: { toFieldAsBlob(env, value, row, column); break; } default: THROW_CPP_EXCEPTION_WITH_STR(env, "Type is not support") break; } }
32.30597
94
0.620524
[ "object" ]
3262559fc179ca74d4534686bb28cdf70ad820c4
539
cpp
C++
Dataset/Leetcode/train/55/157.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
Dataset/Leetcode/train/55/157.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
Dataset/Leetcode/train/55/157.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
class Solution { public: int n; vector<bool> v; int ans = false; bool XXX(vector<int>& nums) { if(nums.size() == 1) return true; n = nums.size() - 1; v = vector<bool>(n, true); dfs(nums, 0); return ans; } void dfs(vector<int>& nums, int idx){ if(!v[idx] || ans) return; if(idx == n){ ans = true; return; } for(int i = 1; i <= nums[idx]; i ++) dfs(nums, idx + i); if(!ans) v[idx] = false; } };
20.730769
44
0.428571
[ "vector" ]
326da2bd5c60e52681068a04f2f39041526b5ffa
243
hpp
C++
src/Engine/IOManager.hpp
kazaamjt/ThendrallEngine
3af7e685c3a7b89d00b47814749f53244e7e6e76
[ "MIT" ]
null
null
null
src/Engine/IOManager.hpp
kazaamjt/ThendrallEngine
3af7e685c3a7b89d00b47814749f53244e7e6e76
[ "MIT" ]
null
null
null
src/Engine/IOManager.hpp
kazaamjt/ThendrallEngine
3af7e685c3a7b89d00b47814749f53244e7e6e76
[ "MIT" ]
null
null
null
#pragma once #include <memory> #include <string> #include <vector> namespace Engine { class IOManager { public: static std::unique_ptr<std::vector<unsigned char>> read_file_to_buffer(const std::string &file_path); private: }; } // Engine
15.1875
102
0.736626
[ "vector" ]
3277311f1a27770bc479488103dd29c8248a1204
15,486
cpp
C++
dockerfiles/gaas_tutorial_2/GAAS/software/SLAM/ygz_slam_ros/Thirdparty/PCL/apps/point_cloud_editor/src/mainWindow.cpp
hddxds/scripts_from_gi
afb8977c001b860335f9062464e600d9115ea56e
[ "Apache-2.0" ]
2
2019-04-10T14:04:52.000Z
2019-05-29T03:41:58.000Z
software/SLAM/ygz_slam_ros/Thirdparty/PCL/apps/point_cloud_editor/src/mainWindow.cpp
glider54321/GAAS
5c3b8c684e72fdf7f62c5731a260021e741069e7
[ "BSD-3-Clause" ]
null
null
null
software/SLAM/ygz_slam_ros/Thirdparty/PCL/apps/point_cloud_editor/src/mainWindow.cpp
glider54321/GAAS
5c3b8c684e72fdf7f62c5731a260021e741069e7
[ "BSD-3-Clause" ]
1
2021-12-20T06:54:41.000Z
2021-12-20T06:54:41.000Z
/// /// Copyright (c) 2012, Texas A&M University /// All rights reserved. /// /// Redistribution and use in source and binary forms, with or without /// modification, are permitted provided that the following conditions /// are met: /// /// * Redistributions of source code must retain the above copyright /// notice, this list of conditions and the following disclaimer. /// * Redistributions in binary form must reproduce the above /// copyright notice, this list of conditions and the following /// disclaimer in the documentation and/or other materials provided /// with the distribution. /// * Neither the name of Texas A&M University nor the names of its /// contributors may be used to endorse or promote products derived /// from this software without specific prior written permission. /// /// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS /// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT /// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS /// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE /// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, /// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, /// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; /// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER /// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT /// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN /// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE /// POSSIBILITY OF SUCH DAMAGE. /// /// The following software was written as part of a collaboration with the /// University of South Carolina, Interdisciplinary Mathematics Institute. /// /// @file mainWindow.cpp /// @details the implementation of the MainWindow class /// @author Yue Li and Matthew Hielsberg #include <algorithm> #include <pcl/apps/point_cloud_editor/mainWindow.h> #include <pcl/apps/point_cloud_editor/cloudEditorWidget.h> #include <pcl/apps/point_cloud_editor/localTypes.h> MainWindow::MainWindow () : window_width_(WINDOW_WIDTH), window_height_(WINDOW_HEIGHT) { initWindow(); } MainWindow::MainWindow (int argc, char **argv) : window_width_(WINDOW_WIDTH), window_height_(WINDOW_HEIGHT) { initWindow(); if (argc > 1) cloud_editor_widget_->loadFile(argv[1]); } MainWindow::~MainWindow() { } void MainWindow::about () { QMessageBox::about(this, tr("Point Cloud Editor"), tr("PCL 3D Editor\n\nAuthors: \n Matthew Hielsberg (hielsber@tamu.edu) and\n" " Yue Li (yli@cse.tamu.edu)\n Texas A&M University\n\n" "This software was written as part of a collaboration with the " "University of South Carolina, Interdisciplinary Mathematics Institute.")); } void MainWindow::help () { QMessageBox::about(this, tr("Point Cloud Editor"), tr("View Mode\n" " Drag:\t\tRotate about origin\n" " Alt Drag:\t\tTranslate Z\n" " Ctrl Drag:\t\tPan\n" " Shift Drag:\t\tZoom\n" "\n" "Selection Transform Mode\n" " Drag:\t\tRotate about centeroid\n" " Alt Drag:\t\tTranslate Z\n" " Ctrl Drag:\t\tPan\n" "\n" "Mouse Picking\n" " Left Click:\t\tSelect Point\n" " Ctrl Left Click:\tDeselect Point\n" " Shift Left Click:\tAppend to Selection\n" "\n" "2D Picking (Rubberband)\n" " Drag:\t\tSelect Region\n" " Ctrl Drag:\t\tDeselect Region\n" " Shift Drag:\t\tAppend to Selection\n" "\n" "Shortcut Keys\n" " 1:\t\tColor Points White\n" " 2:\t\tUse ColorWheel X\n" " 3:\t\tUse ColorWheel Y\n" " 4:\t\tUse ColorWheel Z\n" " 5:\t\tUse RGB Color\n" " Ctrl C:\t\tCopy Selection\n" " Ctrl X:\t\tCut Selection\n" " Ctrl V:\t\tPaste Selection\n" " Ctrl Z:\t\tUndo\n" " V:\t\tView Mode\n" " T:\t\tSelection Transform Mode\n" " E:\t\tPoint Selection Mode\n" " S:\t\t2D Selection Mode\n" " Del:\t\tDelete Selection\n" " +:\t\tIncrease Point Size\n" " -:\t\tDecrease Point Size\n" " Ctrl +:\t\tInc. Selection Point Size\n" " Ctrl -:\t\tDec. Selection Point Size\n" " Esc:\t\tCancel Selection\n" )); } void MainWindow::initWindow () { cloud_editor_widget_ = new CloudEditorWidget(this); cloud_editor_widget_->setAttribute(Qt::WA_DeleteOnClose); setCentralWidget(cloud_editor_widget_); createActions(); createMenus(); createToolBars(); setWindowTitle(tr("PCL 3D Editor (TAMU)")); resize(window_width_, window_height_); } void MainWindow::createActions () { action_group_ = new QActionGroup(this); QString icon_path(":/"); open_action_ = new QAction(QIcon(icon_path+"open.png"),tr("Open..."),this); open_action_ -> setShortcut(tr("Ctrl+O")); connect(open_action_, SIGNAL(triggered()), cloud_editor_widget_, SLOT(load())); save_action_ = new QAction(QIcon(icon_path+"save.png"), tr("Save as.."), this); save_action_ -> setShortcut(tr("Ctrl+S")); connect(save_action_,SIGNAL(triggered()),cloud_editor_widget_,SLOT(save())); exit_action_ = new QAction(tr("Exit..."), this); exit_action_ -> setShortcut(tr("Ctrl+Q")); connect(exit_action_, SIGNAL(triggered()), this, SLOT(close())); about_action_ = new QAction(tr("About"), this); connect(about_action_, SIGNAL(triggered()), this, SLOT(about())); help_action_ = new QAction(tr("Keyboard/Mouse Control"), this); connect(help_action_, SIGNAL(triggered()), this, SLOT(help())); copy_action_ = new QAction(QIcon(icon_path+"copy.png"), tr("Copy"), action_group_); copy_action_ -> setShortcut(tr("Ctrl+C")); connect(copy_action_, SIGNAL(triggered()), cloud_editor_widget_, SLOT(copy())); copy_action_->setCheckable(false); delete_action_ = new QAction(QIcon(icon_path+"delete.png"), tr("Delete"), action_group_); delete_action_ -> setShortcut(tr("D")); connect(delete_action_, SIGNAL(triggered()), cloud_editor_widget_, SLOT(remove())); delete_action_->setCheckable(false); cut_action_ = new QAction(QIcon(icon_path+"cut.png"), tr("Cut"), action_group_); cut_action_ -> setShortcut(tr("Ctrl+X")); connect(cut_action_, SIGNAL(triggered()), cloud_editor_widget_,SLOT(cut())); cut_action_ -> setCheckable(false); paste_action_ = new QAction(QIcon(icon_path+"paste.png"), tr("Paste"), action_group_); paste_action_ -> setShortcut(tr("Ctrl+V")); connect(paste_action_, SIGNAL(triggered()), cloud_editor_widget_, SLOT(paste())); paste_action_ -> setCheckable(false); toggle_blend_action_ = new QAction(tr("Outline Points"), this); connect(toggle_blend_action_, SIGNAL(triggered()), cloud_editor_widget_, SLOT(toggleBlendMode())); toggle_blend_action_->setCheckable(true); toggle_blend_action_->setChecked(false); view_action_ = new QAction(QIcon(icon_path+"view.png"), tr("View"), action_group_); view_action_ -> setShortcut(tr("V")); connect(view_action_, SIGNAL(triggered()), cloud_editor_widget_, SLOT(view())); view_action_->setCheckable(true); view_action_->setChecked(true); undo_action_ = new QAction(QIcon(icon_path+"undo.png"), tr("Undo"), action_group_); undo_action_ -> setShortcut(tr("Ctrl+Z")); connect(undo_action_, SIGNAL(triggered()), cloud_editor_widget_, SLOT(undo())); undo_action_->setCheckable(false); transform_action_ = new QAction(QIcon(icon_path+"move.png"), tr("Transform Selection"), action_group_); transform_action_ -> setShortcut(tr("T")); connect(transform_action_, SIGNAL(triggered()), cloud_editor_widget_, SLOT(transform())); transform_action_->setCheckable(true); denoise_action_ = new QAction(tr("Denoise"), this); connect(denoise_action_, SIGNAL(triggered()), cloud_editor_widget_, SLOT(denoise())); select_action_ = new QAction(QIcon(icon_path+"click.png"), tr("Point Selection"), action_group_); select_action_->setShortcut(tr("E")); connect(select_action_, SIGNAL(triggered()), cloud_editor_widget_, SLOT(select1D())); select_action_->setCheckable(true); invert_select_action_ = new QAction(QIcon(icon_path+"invert.png"), tr("Invert Selection"), action_group_); connect(invert_select_action_, SIGNAL(triggered()), cloud_editor_widget_, SLOT(invertSelect())); invert_select_action_->setCheckable(false); select_2D_action_ = new QAction(QIcon(icon_path+"select.png"), tr("Rubberband Selection"), action_group_); select_2D_action_->setShortcut(tr("S")); connect(select_2D_action_, SIGNAL(triggered()), cloud_editor_widget_, SLOT(select2D())); select_2D_action_->setCheckable(true); //select_3D_action_ = new QAction(QIcon(icon_path+"cube.png"), // tr("3D Selection"), action_group_); //select_3D_action_->setShortcut(tr("A")); //connect(select_3D_action_, SIGNAL(triggered()), cloud_editor_widget_, // SLOT(select3D())); //select_3D_action_->setCheckable(true); show_stat_action_ = new QAction(QIcon(icon_path+"info.png"), tr("Show statistics"), action_group_); connect(show_stat_action_, SIGNAL(triggered()), cloud_editor_widget_, SLOT(showStat())); show_stat_action_->setCheckable(false); } void MainWindow::createMenus () { file_menu_ = new QMenu(tr("&File"), this); file_menu_ -> setAttribute(Qt::WA_DeleteOnClose); file_menu_ -> addAction(open_action_); file_menu_ -> addSeparator(); file_menu_ -> addAction(save_action_); file_menu_ -> addSeparator(); file_menu_ -> addAction(exit_action_); edit_menu_ = new QMenu(tr("&Edit"), this); edit_menu_ -> setAttribute(Qt::WA_DeleteOnClose); edit_menu_ -> addAction(undo_action_); edit_menu_ -> addSeparator(); edit_menu_ -> addAction(cut_action_); edit_menu_ -> addAction(copy_action_); edit_menu_ -> addAction(paste_action_); edit_menu_ -> addAction(delete_action_); edit_menu_ -> addSeparator(); edit_menu_ -> addAction(transform_action_); select_menu_ = new QMenu(tr("&Select"), this); select_menu_ -> setAttribute(Qt::WA_DeleteOnClose); select_menu_ -> addAction(select_action_); select_menu_ -> addAction(select_2D_action_); //select_menu_ -> addAction(select_3D_action_); display_menu_ = new QMenu(tr("&Display"), this); display_menu_ -> setAttribute(Qt::WA_DeleteOnClose); display_menu_ -> addAction(toggle_blend_action_); view_menu_ = new QMenu(tr("&View"), this); view_menu_ -> setAttribute(Qt::WA_DeleteOnClose); view_menu_ -> addAction(view_action_); view_menu_ -> addAction(show_stat_action_); tool_menu_ = new QMenu(tr("&Algorithm"), this); tool_menu_ -> setAttribute(Qt::WA_DeleteOnClose); tool_menu_ -> addAction(denoise_action_); help_menu_ = new QMenu(tr("&Help"), this); help_menu_ -> setAttribute(Qt::WA_DeleteOnClose); help_menu_ -> addAction(about_action_); help_menu_ -> addAction(help_action_); menuBar() -> addMenu(file_menu_); menuBar() -> addMenu(edit_menu_); menuBar() -> addMenu(select_menu_); menuBar() -> addMenu(display_menu_); menuBar() -> addMenu(tool_menu_); menuBar() -> addMenu(help_menu_); } void MainWindow::createToolBars () { createSpinBoxes(); createSliders(); view_tool_bar_ = addToolBar(tr("File")); view_tool_bar_ -> addAction(open_action_); view_tool_bar_ -> addAction(save_action_); view_tool_bar_ = addToolBar(tr("View")); view_tool_bar_ -> addAction(view_action_); view_tool_bar_ -> addAction(select_action_); view_tool_bar_ -> addAction(select_2D_action_); //view_tool_bar_ -> addAction(select_3D_action_); view_tool_bar_ -> addAction(invert_select_action_); QLabel *ptSizeLabel = new QLabel(tr("Point Size:")); ptSizeLabel -> setAttribute(Qt::WA_DeleteOnClose); view_tool_bar_ -> addWidget(ptSizeLabel); view_tool_bar_ -> addWidget(point_size_spin_box_); QLabel *selectedPtSizeLabel = new QLabel(tr("Selected Point Size:")); selectedPtSizeLabel -> setAttribute(Qt::WA_DeleteOnClose); view_tool_bar_ -> addWidget(selectedPtSizeLabel); view_tool_bar_ -> addWidget(selected_point_size_spin_box_); edit_tool_bar_ = addToolBar(tr("Edit")); edit_tool_bar_ -> addAction(undo_action_); edit_tool_bar_ -> addAction(copy_action_); edit_tool_bar_ -> addAction(cut_action_); edit_tool_bar_ -> addAction(delete_action_); edit_tool_bar_ -> addAction(paste_action_); edit_tool_bar_ -> addAction(transform_action_); edit_tool_bar_ -> addAction(show_stat_action_); } void MainWindow::increaseSpinBoxValue() { point_size_spin_box_ -> setValue(point_size_spin_box_->value() + 1); } void MainWindow::decreaseSpinBoxValue() { point_size_spin_box_ -> setValue(point_size_spin_box_->value() - 1); } int MainWindow::getSpinBoxValue() { return (point_size_spin_box_->value()); } void MainWindow::increaseSelectedSpinBoxValue() { selected_point_size_spin_box_ -> setValue(selected_point_size_spin_box_->value() + 1); } void MainWindow::decreaseSelectedSpinBoxValue() { selected_point_size_spin_box_ -> setValue(selected_point_size_spin_box_->value() - 1); } int MainWindow::getSelectedSpinBoxValue() { return (selected_point_size_spin_box_->value()); } void MainWindow::createSpinBoxes () { point_size_spin_box_ = new QSpinBox; point_size_spin_box_ -> setAttribute(Qt::WA_DeleteOnClose); point_size_spin_box_ -> setRange(1, 20); point_size_spin_box_ -> setSingleStep(1); point_size_spin_box_ -> setValue(2); connect(point_size_spin_box_, SIGNAL(valueChanged(int)), cloud_editor_widget_, SLOT(setPointSize(int))); selected_point_size_spin_box_ = new QSpinBox; selected_point_size_spin_box_ -> setAttribute(Qt::WA_DeleteOnClose); selected_point_size_spin_box_ -> setRange(1, 20); selected_point_size_spin_box_ -> setSingleStep(1); selected_point_size_spin_box_ -> setValue(4); connect(selected_point_size_spin_box_, SIGNAL(valueChanged(int)), cloud_editor_widget_, SLOT(setSelectedPointSize(int))); } void MainWindow::createSliders () { move_speed_slider_ = new QSlider(Qt::Horizontal); move_speed_slider_ -> setAttribute(Qt::WA_DeleteOnClose); move_speed_slider_ -> setFocusPolicy(Qt::StrongFocus); move_speed_slider_ -> setTickPosition(QSlider::TicksBothSides); move_speed_slider_ -> setTickInterval(10); move_speed_slider_ -> setSingleStep(1); }
38.04914
88
0.664084
[ "transform", "3d" ]
32797db3b10cc784d64b946a06aef017df69202f
4,536
hpp
C++
src/math/transform.hpp
Shinigami072/3DGameProgrammingTutorial
4679f756f3df851210e2b4cc7dc8b16ef3e3855a
[ "MIT" ]
83
2018-03-29T02:28:26.000Z
2021-06-10T23:56:24.000Z
src/math/transform.hpp
Shinigami072/3DGameProgrammingTutorial
4679f756f3df851210e2b4cc7dc8b16ef3e3855a
[ "MIT" ]
14
2018-04-11T18:38:47.000Z
2018-09-20T21:56:36.000Z
src/math/transform.hpp
Shinigami072/3DGameProgrammingTutorial
4679f756f3df851210e2b4cc7dc8b16ef3e3855a
[ "MIT" ]
32
2018-03-29T02:39:28.000Z
2022-03-16T16:36:32.000Z
#pragma once #include "vector.hpp" #include "quaternion.hpp" #include "matrix.hpp" class Transform { public: FORCEINLINE Transform() : translation(0.0f, 0.0f, 0.0f), rotation(0.0f, 0.0f, 0.0f, 1.0f), scale(1.0f, 1.0f, 1.0f) {} FORCEINLINE Transform(const Vector3f& translationIn) : translation(translationIn), rotation(0.0f, 0.0f, 0.0f, 1.0f), scale(1.0f, 1.0f, 1.0f) {} FORCEINLINE Transform(const Quaternion& rotationIn) : translation(0.0f, 0.0f, 0.0f), rotation(rotationIn), scale(1.0f, 1.0f, 1.0f) {} FORCEINLINE Transform(const Vector3f& translationIn, const Quaternion& rotationIn, const Vector3f& scaleIn) : translation(translationIn), rotation(rotationIn), scale(scaleIn) {} FORCEINLINE Vector transform(const Vector& vector) const; FORCEINLINE Vector transform(const Vector3f& vector, float w) const; FORCEINLINE Vector inverseTransform(const Vector& vector) const; FORCEINLINE Vector inverseTransform(const Vector3f& vector, float w) const; FORCEINLINE Matrix toMatrix() const; Matrix inverse() const; FORCEINLINE void normalizeRotation(); FORCEINLINE bool isRotationNormalized(); FORCEINLINE Transform operator+(const Transform& other) const; FORCEINLINE Transform operator+=(const Transform& other); FORCEINLINE Transform operator*(const Transform& other) const; FORCEINLINE Transform operator*=(const Transform& other); FORCEINLINE Transform operator*(float other) const; FORCEINLINE Transform operator*=(float other); FORCEINLINE Vector3f getTranslation() const; FORCEINLINE Quaternion getRotation() const; FORCEINLINE Vector3f getScale() const; FORCEINLINE void set(const Vector3f& translation, const Quaternion& rotation, const Vector3f& scale); FORCEINLINE void setTranslation(const Vector3f& translation); FORCEINLINE void setRotation(const Quaternion& rotation); FORCEINLINE void setScale(const Vector3f& scale); private: Vector3f translation; Quaternion rotation; Vector3f scale; }; FORCEINLINE Matrix Transform::toMatrix() const { return Matrix::transformMatrix(translation, rotation, scale); } FORCEINLINE void Transform::normalizeRotation() { rotation = rotation.normalized(); } FORCEINLINE bool Transform::isRotationNormalized() { return rotation.isNormalized(); } FORCEINLINE Transform Transform::operator+(const Transform& other) const { return Transform(translation + other.translation, rotation + other.rotation, scale + other.scale); } FORCEINLINE Transform Transform::operator+=(const Transform& other) { translation += other.translation; rotation += other.rotation; scale += other.scale; return *this; } FORCEINLINE Transform Transform::operator*(const Transform& other) const { return Transform(translation * other.translation, rotation * other.rotation, scale * other.scale); } FORCEINLINE Transform Transform::operator*=(const Transform& other) { translation *= other.translation; rotation *= other.rotation; scale *= other.scale; return *this; } FORCEINLINE Transform Transform::operator*(float other) const { return Transform(translation * other, rotation * other, scale * other); } FORCEINLINE Transform Transform::operator*=(float other) { translation *= other; rotation *= other; scale *= other; return *this; } FORCEINLINE Vector Transform::transform(const Vector3f& vector, float w) const { return (rotation.rotate(scale * vector) + translation * w).toVector(0.0f); } FORCEINLINE Vector Transform::transform(const Vector& vector) const { return transform(Vector3f(vector), vector[3]); } FORCEINLINE Vector Transform::inverseTransform(const Vector3f& vector, float w) const { return (rotation.inverse().rotate(vector - translation * w) * scale.reciprocal()).toVector(0.0f); } FORCEINLINE Vector Transform::inverseTransform(const Vector& vector) const { return inverseTransform(Vector3f(vector), vector[3]); } FORCEINLINE Vector3f Transform::getTranslation() const { return translation; } FORCEINLINE Quaternion Transform::getRotation() const { return rotation; } FORCEINLINE Vector3f Transform::getScale() const { return scale; } FORCEINLINE void Transform::set(const Vector3f& translationIn, const Quaternion& rotationIn, const Vector3f& scaleIn) { translation = translationIn; rotation = rotationIn; scale = scaleIn; } FORCEINLINE void Transform::setTranslation(const Vector3f& val) { translation = val; } FORCEINLINE void Transform::setRotation(const Quaternion& val) { rotation = val; } FORCEINLINE void Transform::setScale(const Vector3f& val) { scale = val; }
25.627119
98
0.760802
[ "vector", "transform" ]
327eb4db69f2582cb8e29e5d9747de62c69c6aa3
3,823
cpp
C++
src/geode/model/helpers/simplicial_section_creator.cpp
Geode-solutions/OpenGeode
e47621989e6fc152f529d4e1e7e3b9ef9e7d6ccc
[ "MIT" ]
64
2019-08-02T14:31:01.000Z
2022-03-30T07:46:50.000Z
src/geode/model/helpers/simplicial_section_creator.cpp
Geode-solutions/OpenGeode
e47621989e6fc152f529d4e1e7e3b9ef9e7d6ccc
[ "MIT" ]
395
2019-08-02T17:15:10.000Z
2022-03-31T15:10:27.000Z
src/geode/model/helpers/simplicial_section_creator.cpp
Geode-solutions/OpenGeode
e47621989e6fc152f529d4e1e7e3b9ef9e7d6ccc
[ "MIT" ]
8
2019-08-19T21:32:15.000Z
2022-03-06T18:41:10.000Z
/* * Copyright (c) 2019 - 2021 Geode-solutions * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ #include <geode/model/helpers/simplicial_section_creator.h> #include <geode/basic/pimpl_impl.h> #include <geode/model/helpers/private/simplicial_model_creator.h> #include <geode/model/representation/builder/section_builder.h> #include <geode/model/representation/core/section.h> namespace geode { class SimplicialSectionCreator::Impl : public detail::SimplicialModelCreator< Section, SectionBuilder, 2 > { public: Impl( Section& section, std::vector< Point2D > unique_points ) : detail::SimplicialModelCreator< Section, SectionBuilder, 2 >( section, std::move( unique_points ) ) { } std::vector< uuid > create_model_boundaries( absl::Span< const uuid > lines, absl::Span< const BoundaryDefinition > definitions ) { std::vector< geode::uuid > boundaries; boundaries.reserve( definitions.size() ); for( const auto& definition : definitions ) { const auto& bonudary_id = builder().add_model_boundary(); const auto& boundary = model().model_boundary( bonudary_id ); boundaries.push_back( bonudary_id ); for( const auto line : definition.boundaries ) { builder().add_line_in_model_boundary( model().line( lines[line] ), boundary ); } } return boundaries; } }; SimplicialSectionCreator::SimplicialSectionCreator( Section& section, std::vector< Point2D > unique_points ) : impl_{ section, std::move( unique_points ) } { } SimplicialSectionCreator::~SimplicialSectionCreator() {} std::vector< uuid > SimplicialSectionCreator::create_corners( absl::Span< const CornerDefinition > definitions ) { return impl_->create_corners( definitions ); } std::vector< uuid > SimplicialSectionCreator::create_lines( absl::Span< const uuid > corners, absl::Span< const LineDefinition > definitions ) { return impl_->create_lines( corners, definitions ); } std::vector< uuid > SimplicialSectionCreator::create_surfaces( absl::Span< const uuid > lines, absl::Span< const SurfaceDefinition > definitions ) { return impl_->create_surfaces( lines, definitions ); } std::vector< uuid > SimplicialSectionCreator::create_model_boundaries( absl::Span< const uuid > lines, absl::Span< const BoundaryDefinition > definitions ) { return impl_->create_model_boundaries( lines, definitions ); } } // namespace geode
38.616162
80
0.665446
[ "vector", "model" ]
3284f4f6949076fb7e2bd4aefc01ffd4399f136b
6,724
cpp
C++
c-source/ProtoChecker/CsvReader.cpp
Vegas007/Proto-Checker
757a968fefa1275845eb6dc91ebd997805ddfc21
[ "MIT" ]
2
2020-01-26T18:32:23.000Z
2022-01-13T10:27:37.000Z
c-source/ProtoChecker/CsvReader.cpp
Vegas007/Proto-Checker
757a968fefa1275845eb6dc91ebd997805ddfc21
[ "MIT" ]
null
null
null
c-source/ProtoChecker/CsvReader.cpp
Vegas007/Proto-Checker
757a968fefa1275845eb6dc91ebd997805ddfc21
[ "MIT" ]
2
2020-03-29T22:34:25.000Z
2020-10-07T21:06:14.000Z
#include "pch.h" #include "CsvReader.h" #include <fstream> #include <algorithm> #ifndef Assert #include <assert.h> #define Assert assert #define LogToFile (void)(0); #endif namespace { enum ParseState { STATE_NORMAL = 0, STATE_QUOTE }; std::string Trim(std::string str) { str = str.erase(str.find_last_not_of(" \t\r\n") + 1); str = str.erase(0, str.find_first_not_of(" \t\r\n")); return str; } std::string Lower(std::string original) { std::transform(original.begin(), original.end(), original.begin(), tolower); return original; } } auto cCsvAlias::AddAlias(const char* name, size_t index) -> void { const auto & converted(Lower(name)); Assert(m_Name2Index.find(converted) == m_Name2Index.end()); Assert(m_Index2Name.find(index) == m_Index2Name.end()); m_Name2Index.insert(NAME2INDEX_MAP::value_type(converted, index)); m_Index2Name.insert(INDEX2NAME_MAP::value_type(index, name)); } auto cCsvAlias::Destroy() -> void { m_Name2Index.clear(); m_Index2Name.clear(); } auto cCsvAlias::operator [](size_t index) const -> const char* { const auto & it = m_Index2Name.find(index); if (it == m_Index2Name.end()) { Assert(false && "cannot find suitable conversion"); return nullptr; } return it->second.c_str(); } auto cCsvAlias::operator [](const char* name) const -> size_t { const auto & it = m_Name2Index.find(Lower(name)); if (it == m_Name2Index.end()) { Assert(false && "cannot find suitable conversion"); return 0; } return it->second; } auto cCsvFile::Load(const char* fileName, const char seperator, const char quote) -> bool { Assert(seperator != quote); std::ifstream file(fileName, std::ios::in); if (!file) return false; Destroy(); cCsvRow * row = nullptr; ParseState state = STATE_NORMAL; std::string token; char buf[2048+1] = {0,}; while (file.good()) { file.getline(buf, 2048); buf[sizeof(buf)-1] = 0; std::string line(Trim(buf)); if (line.empty() || (state == STATE_NORMAL && line[0] == '#')) continue; const auto & text = std::string(line) + " "; size_t cur = 0; while (cur < text.size()) { if (state == STATE_QUOTE) { if (text[cur] == quote) { if (text[cur+1] == quote) { token += quote; ++cur; } else { state = STATE_NORMAL; } } else { token += text[cur]; } } else if (state == STATE_NORMAL) { if (row == nullptr) row = new cCsvRow(); if (text[cur] == seperator) { row->push_back(token); token.clear(); } else if (text[cur] == quote) { state = STATE_QUOTE; } else { token += text[cur]; } } ++cur; } if (state == STATE_NORMAL) { Assert(row != NULL); row->push_back(token.substr(0, token.size()-2)); m_Rows.push_back(row); token.clear(); row = nullptr; } else { token = token.substr(0, token.size()-2) + "\r\n"; } } file.close(); return true; } auto cCsvFile::Save(const char* fileName, bool append, char seperator, char quote) const -> bool { Assert(seperator != quote); std::ofstream file; file.open(fileName, std::ios::out | (append ? std::ios::app : std::ios::trunc)); if (!file) return false; char special_chars[5] = { seperator, quote, '\r', '\n', 0 }; char quote_escape_string[3] = { quote, quote, 0 }; for (size_t i = 0; i < m_Rows.size(); i++) { const auto & row = *((*this)[i]); std::string line; for (size_t j = 0; j < row.size(); j++) { const auto & token = row[j]; if (token.find_first_of(special_chars) == std::string::npos) { line += token; } else { line += quote; for (auto k : token) { if (k == quote) line += quote_escape_string; else line += k; } line += quote; } if (j != row.size() - 1) line += seperator; } file << line << std::endl; } return true; } auto cCsvFile::Destroy() -> void { for (auto itr(m_Rows.begin()); itr != m_Rows.end(); ++itr) delete *itr; m_Rows.clear(); } auto cCsvFile::operator [](size_t index) -> cCsvRow * { Assert(index < m_Rows.size()); return m_Rows[index]; } auto cCsvFile::operator [](size_t index) const -> const cCsvRow * { Assert(index < m_Rows.size()); return m_Rows[index]; } cCsvTable::cCsvTable() : m_CurRow(-1) { } cCsvTable::~cCsvTable() { } auto cCsvTable::Load(const char* fileName, const char seperator, const char quote) -> bool { Destroy(); return m_File.Load(fileName, seperator, quote); } auto cCsvTable::Next() -> bool { return ++m_CurRow < static_cast<int>(m_File.GetRowCount()); } auto cCsvTable::ColCount() const -> size_t { return CurRow()->size(); } auto cCsvTable::AsInt(size_t index) const -> int { const cCsvRow* const row = CurRow(); Assert(row); Assert(index < row->size()); return row->AsInt(index); } auto cCsvTable::AsDouble(size_t index) const -> double { const auto row = CurRow(); Assert(row); Assert(index < row->size()); return row->AsDouble(index); } auto cCsvTable::AsStringByIndex(size_t index) const -> std::string { const auto row = CurRow(); Assert(row); Assert(index < row->size()); return row->AsString(index); } auto cCsvTable::Destroy() -> void { m_File.Destroy(); m_Alias.Destroy(); m_CurRow = -1; } auto cCsvTable::CurRow() const -> const cCsvRow* { if (m_CurRow < 0) { Assert(false && "call Next() first!"); return nullptr; } else if (m_CurRow >= static_cast<int>(m_File.GetRowCount())) { Assert(false && "no more rows!"); return nullptr; } return m_File[m_CurRow]; }
22.191419
96
0.508775
[ "transform" ]
32870ad9bb58b5791346052ce60789944e6d91e3
2,552
cpp
C++
gallery/src/char2double.cpp
LTLA/tatami
134dbb98a0e47f4fa75426f37f08980efe61369b
[ "MIT" ]
1
2021-09-13T01:10:45.000Z
2021-09-13T01:10:45.000Z
gallery/src/char2double.cpp
LTLA/libbioc
134dbb98a0e47f4fa75426f37f08980efe61369b
[ "MIT" ]
9
2021-07-22T08:29:24.000Z
2022-03-24T11:25:42.000Z
gallery/src/char2double.cpp
LTLA/tatami
134dbb98a0e47f4fa75426f37f08980efe61369b
[ "MIT" ]
null
null
null
#include "tatami/tatami.h" #include <vector> #include <iostream> #include <numeric> #include <iomanip> /* INTRODUCTION: * * In this example, we will demonstrate how the interface type does not * necessarily need to be the same as the storage type. This allows developers * to use a more memory-efficient representation (e.g., by using a smaller * integer type or by reducing the precision of floats) while still retaining * compatibility with downstream functions that expect a certain type. */ template<class IT> void print_vector(IT start, IT end) { bool first = true; std::cout << "[ "; for (IT it = start; it != end; ++it) { if (!first) { std::cout << ", "; } std::cout << std::setw(6) << std::fixed << std::setprecision(2) << *it; first = false; } std::cout << " ]" << std::endl; } int main(int argc, char** argv) { std::vector<uint8_t> rows = { 3, 5, 0, 1, 8, 4, 7, 5, 6, 9, 0, 1, 2, 3, 4 }; std::vector<uint8_t> cols = { 0, 1, 3, 2, 0, 4, 1, 2, 4, 0, 1, 3, 0, 3, 2 }; std::vector<char> vals = { -4, 1, -7, 12, 12, -1, -4, 2, 3, 4, -1, 5, -8, 1, 2 }; auto indptrs = tatami::compress_sparse_triplets<false>(10, 5, vals, rows, cols); /* Here, we create a matrix where the values are chars and the indices are * 8-bit unsigned integers. This enables us to be extremely space-efficient * if we know that the values will not exceed the limits of the type. */ std::shared_ptr<tatami::NumericMatrix> mat(new tatami::CompressedSparseColumnMatrix<double, int, decltype(vals), decltype(rows)>(10, 5, vals, rows, indptrs)); std::cout << "Matrix preview: " << std::endl; std::vector<double> buffer(mat->ncol()); for (size_t i = 0; i < mat->nrow(); ++i) { auto ptr = mat->row(i, buffer.data()); print_vector(ptr, ptr + mat->ncol()); } std::cout << std::endl; /* However, this improved memory efficiency does come at the cost of mandatory * type conversions (and the associated implicit copy). For example, it is no * longer possible to return a direct pointer to the underlying store. (In * contrast, if vals was a vector of doubles, the code below would print 'false'.) */ std::vector<double> vbuffer(mat->nrow()); std::vector<int> ibuffer(mat->nrow()); auto range = mat->sparse_column(0, vbuffer.data(), ibuffer.data()); std::cout << "Using buffer instead of underlying store: " << (range.value==vbuffer.data() ? "true" : "false") << std::endl; return 0; }
41.16129
162
0.622649
[ "vector" ]
32887890989dd4a0b2eab4b4e14d37dbd1a549c6
29,209
cpp
C++
ricochet/dlls/dll.cpp
Defal7c/zecachet
b5a09da4796f734b5942d30c527ee71cc2721543
[ "Unlicense" ]
null
null
null
ricochet/dlls/dll.cpp
Defal7c/zecachet
b5a09da4796f734b5942d30c527ee71cc2721543
[ "Unlicense" ]
null
null
null
ricochet/dlls/dll.cpp
Defal7c/zecachet
b5a09da4796f734b5942d30c527ee71cc2721543
[ "Unlicense" ]
null
null
null
/* Ricobot (C) Copyright 2004, Wei Mingzhi All rights reserved. Redistribution and use in source and binary forms with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of this project nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY WEI MINGZHI "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // // Ricobot - a bot example for Valve Software's Ricochet MOD // // dll.cpp // #include "bot.h" char welcome_msg[] = "Welcome to Ricobot by Wei Mingzhi\n" "Visit http://yapb.mapzap.org\n" "Compile date: " __DATE__ "\n"; DLL_FUNCTIONS other_gFunctionTable; DLL_GLOBAL const Vector g_vecZero = Vector(0,0,0); int default_bot_skill = 2; float bot_check_time = 30.0; int min_bots = -1; int max_bots = -1; int num_bots = 0; int prev_num_bots = 0; bool g_GameRules = FALSE; edict_t *listenserver_edict = NULL; float welcome_time = 0.0; bool welcome_sent = FALSE; FILE *bot_cfg_fp = NULL; bool need_to_open_cfg = TRUE; float bot_cfg_pause_time = 0.0; float respawn_time = 0.0; bool spawn_time_reset = FALSE; char bot_whine[MAX_BOT_WHINE][81]; int whine_count; int recent_bot_whine[5]; void BotNameInit(void); void ProcessBotCfgFile(void); void ServerCommand(void) { if (strcmp(CMD_ARGV(1), "addbot") == 0) { BotCreate( NULL, CMD_ARGV(2), CMD_ARGV(3) ); bot_check_time = gpGlobals->time + 5.0; } else if (strcmp(CMD_ARGV(1), "min_bots") == 0) { min_bots = atoi( CMD_ARGV(2) ); if ((min_bots < 0) || (min_bots > 31)) min_bots = 1; printf("min_bots set to %d\n", min_bots); } else if (strcmp(CMD_ARGV(1), "max_bots") == 0) { max_bots = atoi( CMD_ARGV(2) ); if ((max_bots < 0) || (max_bots > 31)) max_bots = 1; printf("max_bots set to %d\n", max_bots); } } void GameDLLInit( void ) { char filename[256]; char buffer[256]; int i, length; FILE *bfp; char *ptr; // Register server command (*g_engfuncs.pfnAddServerCommand)("bot", ServerCommand); whine_count = 0; // initialize the bots array of structures... memset(bots, 0, sizeof(bots)); for (i=0; i < 5; i++) recent_bot_whine[i] = -1; BotNameInit(); UTIL_BuildFileName(filename, "bot_whine.txt", NULL); bfp = fopen(filename, "r"); if (bfp != NULL) { while ((whine_count < MAX_BOT_WHINE) && (fgets(buffer, 80, bfp) != NULL)) { length = strlen(buffer); if (buffer[length-1] == '\n') { buffer[length-1] = 0; // remove '\n' length--; } if ((ptr = strstr(buffer, "%n")) != NULL) { *(ptr+1) = 's'; // change %n to %s } if (length > 0) { strcpy(bot_whine[whine_count], buffer); whine_count++; } } fclose(bfp); } (*other_gFunctionTable.pfnGameInit)(); } int DispatchSpawn( edict_t *pent ) { if (gpGlobals->deathmatch) { char *pClassname = (char *)STRING(pent->v.classname); if (strcmp(pClassname, "worldspawn") == 0) { g_GameRules = TRUE; bot_cfg_pause_time = 0.0; respawn_time = 0.0; spawn_time_reset = FALSE; prev_num_bots = num_bots; num_bots = 0; bot_check_time = gpGlobals->time + 30.0; } } return (*other_gFunctionTable.pfnSpawn)(pent); } void DispatchThink( edict_t *pent ) { (*other_gFunctionTable.pfnThink)(pent); } void DispatchUse( edict_t *pentUsed, edict_t *pentOther ) { (*other_gFunctionTable.pfnUse)(pentUsed, pentOther); } void DispatchTouch( edict_t *pentTouched, edict_t *pentOther ) { (*other_gFunctionTable.pfnTouch)(pentTouched, pentOther); } void DispatchBlocked( edict_t *pentBlocked, edict_t *pentOther ) { (*other_gFunctionTable.pfnBlocked)(pentBlocked, pentOther); } void DispatchKeyValue( edict_t *pentKeyvalue, KeyValueData *pkvd ) { (*other_gFunctionTable.pfnKeyValue)(pentKeyvalue, pkvd); } void DispatchSave( edict_t *pent, SAVERESTOREDATA *pSaveData ) { (*other_gFunctionTable.pfnSave)(pent, pSaveData); } int DispatchRestore( edict_t *pent, SAVERESTOREDATA *pSaveData, int globalEntity ) { return (*other_gFunctionTable.pfnRestore)(pent, pSaveData, globalEntity); } void DispatchObjectCollsionBox( edict_t *pent ) { (*other_gFunctionTable.pfnSetAbsBox)(pent); } void SaveWriteFields( SAVERESTOREDATA *pSaveData, const char *pname, void *pBaseData, TYPEDESCRIPTION *pFields, int fieldCount ) { (*other_gFunctionTable.pfnSaveWriteFields)(pSaveData, pname, pBaseData, pFields, fieldCount); } void SaveReadFields( SAVERESTOREDATA *pSaveData, const char *pname, void *pBaseData, TYPEDESCRIPTION *pFields, int fieldCount ) { (*other_gFunctionTable.pfnSaveReadFields)(pSaveData, pname, pBaseData, pFields, fieldCount); } void SaveGlobalState( SAVERESTOREDATA *pSaveData ) { (*other_gFunctionTable.pfnSaveGlobalState)(pSaveData); } void RestoreGlobalState( SAVERESTOREDATA *pSaveData ) { (*other_gFunctionTable.pfnRestoreGlobalState)(pSaveData); } void ResetGlobalState( void ) { (*other_gFunctionTable.pfnResetGlobalState)(); } BOOL ClientConnect( edict_t *pEntity, const char *pszName, const char *pszAddress, char szRejectReason[ 128 ] ) { if (gpGlobals->deathmatch) { int i; int count = 0; // check if this client is the listen server client if (strcmp(pszAddress, "loopback") == 0) listenserver_edict = pEntity; // save the edict of the listen server client... // check if this is NOT a bot joining the server... if (strcmp(pszAddress, "127.0.0.1") != 0) { // don't try to add bots for 60 seconds, give client time to get added bot_check_time = gpGlobals->time + 60.0; for (i = 0; i < 32; i++) { if (bots[i].is_used) // count the number of bots in use count++; } // if there are currently more than the minimum number of bots running // then kick one of the bots off the server... if (count > min_bots && min_bots != -1) { for (i=0; i < 32; i++) { if (bots[i].is_used) // is this slot used? { char cmd[80]; sprintf(cmd, "kick \"%s\"\n", STRING(bots[i].pEdict->v.netname)); SERVER_COMMAND(cmd); // kick the bot using (kick "name") break; } } } } } return (*other_gFunctionTable.pfnClientConnect)(pEntity, pszName, pszAddress, szRejectReason); } void ClientDisconnect( edict_t *pEntity ) { if (gpGlobals->deathmatch) { for (int i = 0; i < 32; i++) { if (bots[i].pEdict == pEntity) { // someone kicked this bot off of the server... bots[i].is_used = FALSE; // this slot is now free to use bots[i].kick_time = gpGlobals->time; // save the kicked time break; } } } (*other_gFunctionTable.pfnClientDisconnect)(pEntity); } void ClientKill( edict_t *pEntity ) { (*other_gFunctionTable.pfnClientKill)(pEntity); } void ClientPutInServer( edict_t *pEntity ) { (*other_gFunctionTable.pfnClientPutInServer)(pEntity); } void ClientCommand( edict_t *pEntity ) { // only allow custom commands if deathmatch mode and NOT dedicated server and // client sending command is the listen server client... if ((gpGlobals->deathmatch) && (!IS_DEDICATED_SERVER()) && (pEntity == listenserver_edict)) { const char *pcmd = CMD_ARGV(0); const char *arg1 = CMD_ARGV(1); const char *arg2 = CMD_ARGV(2); char msg[80]; if (FStrEq(pcmd, "addbot")) { BotCreate( pEntity, arg1, arg2 ); bot_check_time = gpGlobals->time + 5.0; return; } else if (FStrEq(pcmd, "observer")) { if ((arg1 != NULL) && (*arg1 != 0)) { int temp = atoi(arg1); if (temp) b_observer_mode = TRUE; else b_observer_mode = FALSE; } if (b_observer_mode) ClientPrint(pEntity, HUD_PRINTNOTIFY, "observer mode ENABLED\n"); else ClientPrint(pEntity, HUD_PRINTNOTIFY, "observer mode DISABLED\n"); return; } else if (FStrEq(pcmd, "botskill")) { if ((arg1 != NULL) && (*arg1 != 0)) { int temp = atoi(arg1); if (temp < 1 || temp > 5) ClientPrint(pEntity, HUD_PRINTNOTIFY, "invalid botskill value!\n"); else default_bot_skill = temp; } sprintf(msg, "botskill is %d\n", default_bot_skill); ClientPrint(pEntity, HUD_PRINTNOTIFY, msg); return; } else if (FStrEq(pcmd, "botdontshoot")) { if ((arg1 != NULL) && (*arg1 != 0)) { int temp = atoi(arg1); if (temp) b_botdontshoot = TRUE; else b_botdontshoot = FALSE; } if (b_botdontshoot) ClientPrint(pEntity, HUD_PRINTNOTIFY, "botdontshoot ENABLED\n"); else ClientPrint(pEntity, HUD_PRINTNOTIFY, "botdontshoot DISABLED\n"); return; } else if (FStrEq(pcmd, "bot_chat_percent")) { if ((arg1 != NULL) && (*arg1 != 0)) { int temp = atoi(arg1); if ((temp < 0) || (temp > 100)) ClientPrint(pEntity, HUD_PRINTNOTIFY, "invalid bot_chat_percent value!\n"); else bot_chat_percent = temp; } sprintf(msg, "bot_chat_percent is %d\n", bot_chat_percent); ClientPrint(pEntity, HUD_PRINTNOTIFY, msg); return; } } (*other_gFunctionTable.pfnClientCommand)(pEntity); } void ClientUserInfoChanged( edict_t *pEntity, char *infobuffer ) { (*other_gFunctionTable.pfnClientUserInfoChanged)(pEntity, infobuffer); } void ServerActivate( edict_t *pEdictList, int edictCount, int clientMax ) { (*other_gFunctionTable.pfnServerActivate)(pEdictList, edictCount, clientMax); } void ServerDeactivate( void ) { (*other_gFunctionTable.pfnServerDeactivate)(); } void PlayerPreThink( edict_t *pEntity ) { (*other_gFunctionTable.pfnPlayerPreThink)(pEntity); } void PlayerPostThink( edict_t *pEntity ) { (*other_gFunctionTable.pfnPlayerPostThink)(pEntity); } void StartFrame( void ) { if (gpGlobals->deathmatch) { static int i, index, bot_index; static float previous_time = -1.0; int count; // if a new map has started then (MUST BE FIRST IN StartFrame)... if (gpGlobals->time + 0.1 < previous_time) { char filename[256]; char mapname[64]; // check if mapname_bot.cfg file exists... strcpy(mapname, STRING(gpGlobals->mapname)); strcat(mapname, "_bot.cfg"); UTIL_BuildFileName(filename, "maps", mapname); if ((bot_cfg_fp = fopen(filename, "r")) != NULL) { for (index = 0; index < 32; index++) { bots[index].is_used = FALSE; bots[index].respawn_state = 0; bots[index].kick_time = 0.0; } if (IS_DEDICATED_SERVER()) bot_cfg_pause_time = gpGlobals->time + 5.0; else bot_cfg_pause_time = gpGlobals->time + 20.0; } else { count = 0; // mark the bots as needing to be respawned... for (index = 0; index < 32; index++) { if (count >= prev_num_bots) { bots[index].is_used = FALSE; bots[index].respawn_state = 0; bots[index].kick_time = 0.0; } if (bots[index].is_used) // is this slot used? { bots[index].respawn_state = RESPAWN_NEED_TO_RESPAWN; count++; } // check for any bots that were very recently kicked... if ((bots[index].kick_time + 5.0) > previous_time) { bots[index].respawn_state = RESPAWN_NEED_TO_RESPAWN; count++; } else bots[index].kick_time = 0.0; // reset to prevent false spawns later } // set the respawn time if (IS_DEDICATED_SERVER()) respawn_time = gpGlobals->time + 5.0; else respawn_time = gpGlobals->time + 20.0; } bot_check_time = gpGlobals->time + 30.0; } if (!IS_DEDICATED_SERVER()) { if ((listenserver_edict != NULL) && (welcome_sent == FALSE) && (welcome_time < 1.0)) { // are they out of observer mode yet? if (IsAlive(listenserver_edict)) welcome_time = gpGlobals->time + 5.0; // welcome in 5 seconds } if ((welcome_time > 0.0) && (welcome_time < gpGlobals->time) && (welcome_sent == FALSE)) { } } count = 0; for (bot_index = 0; bot_index < gpGlobals->maxClients; bot_index++) { if ((bots[bot_index].is_used) && // is this slot used AND (bots[bot_index].respawn_state == RESPAWN_IDLE)) // not respawning { BotThink(&bots[bot_index]); count++; } } if (count > num_bots) num_bots = count; // are we currently respawning bots and is it time to spawn one yet? if (respawn_time > 1.0 && respawn_time <= gpGlobals->time) { int index = 0; // find bot needing to be respawned... while (index < 32 && bots[index].respawn_state != RESPAWN_NEED_TO_RESPAWN) index++; if (index < 32) { bots[index].respawn_state = RESPAWN_IS_RESPAWNING; bots[index].is_used = FALSE; // free up this slot // respawn 1 bot then wait a while (otherwise engine crashes) char c_skill[2]; sprintf(c_skill, "%d", bots[index].bot_skill); BotCreate(NULL, bots[index].name, c_skill); respawn_time = gpGlobals->time + 2.0; // set next respawn time bot_check_time = gpGlobals->time + 5.0; } else respawn_time = 0.0; } if (g_GameRules) { if (need_to_open_cfg) // have we open bot.cfg file yet? { char filename[256]; char mapname[64]; need_to_open_cfg = FALSE; // only do this once!!! // check if mapname_bot.cfg file exists... strcpy(mapname, STRING(gpGlobals->mapname)); strcat(mapname, "_bot.cfg"); UTIL_BuildFileName(filename, "maps", mapname); if ((bot_cfg_fp = fopen(filename, "r")) == NULL) { UTIL_BuildFileName(filename, "bot.cfg", NULL); bot_cfg_fp = fopen(filename, "r"); } if (IS_DEDICATED_SERVER()) bot_cfg_pause_time = gpGlobals->time + 5.0; else bot_cfg_pause_time = gpGlobals->time + 20.0; } if (!IS_DEDICATED_SERVER() && !spawn_time_reset) { if (listenserver_edict != NULL) { if (IsAlive(listenserver_edict)) { spawn_time_reset = TRUE; if (respawn_time >= 1.0) respawn_time = min(respawn_time, gpGlobals->time + (float)1.0); if (bot_cfg_pause_time >= 1.0) bot_cfg_pause_time = min(bot_cfg_pause_time, gpGlobals->time + (float)1.0); } } } if ((bot_cfg_fp) && (bot_cfg_pause_time >= 1.0) && (bot_cfg_pause_time <= gpGlobals->time)) { // process bot.cfg file options... ProcessBotCfgFile(); } } // check if time to see if a bot needs to be created... if (bot_check_time < gpGlobals->time) { int count = 0; bot_check_time = gpGlobals->time + 5.0; for (i = 1; i <= gpGlobals->maxClients; i++) { edict_t *pPlayer = INDEXENT(i); if (!FNullEnt(pPlayer) && !pPlayer->free && (pPlayer->v.flags & (FL_CLIENT | FL_FAKECLIENT))) count++; } // if there are currently less than the maximum number of "players" // then add another bot using the default skill level... if (count < max_bots && max_bots != -1) BotCreate( NULL, NULL, NULL ); } previous_time = gpGlobals->time; } (*other_gFunctionTable.pfnStartFrame)(); } void ParmsNewLevel( void ) { (*other_gFunctionTable.pfnParmsNewLevel)(); } void ParmsChangeLevel( void ) { (*other_gFunctionTable.pfnParmsChangeLevel)(); } const char *GetGameDescription( void ) { return (*other_gFunctionTable.pfnGetGameDescription)(); } void PlayerCustomization( edict_t *pEntity, customization_t *pCust ) { (*other_gFunctionTable.pfnPlayerCustomization)(pEntity, pCust); } void SpectatorConnect( edict_t *pEntity ) { (*other_gFunctionTable.pfnSpectatorConnect)(pEntity); } void SpectatorDisconnect( edict_t *pEntity ) { (*other_gFunctionTable.pfnSpectatorDisconnect)(pEntity); } void SpectatorThink( edict_t *pEntity ) { (*other_gFunctionTable.pfnSpectatorThink)(pEntity); } void Sys_Error( const char *error_string ) { (*other_gFunctionTable.pfnSys_Error)(error_string); } void PM_Move ( struct playermove_s *ppmove, int server ) { (*other_gFunctionTable.pfnPM_Move)(ppmove, server); } void PM_Init ( struct playermove_s *ppmove ) { (*other_gFunctionTable.pfnPM_Init)(ppmove); } char PM_FindTextureType( char *name ) { return (*other_gFunctionTable.pfnPM_FindTextureType)(name); } void SetupVisibility( edict_t *pViewEntity, edict_t *pClient, unsigned char **pvs, unsigned char **pas ) { (*other_gFunctionTable.pfnSetupVisibility)(pViewEntity, pClient, pvs, pas); } void UpdateClientData ( const struct edict_s *ent, int sendweapons, struct clientdata_s *cd ) { (*other_gFunctionTable.pfnUpdateClientData)(ent, sendweapons, cd); } int AddToFullPack( struct entity_state_s *state, int e, edict_t *ent, edict_t *host, int hostflags, int player, unsigned char *pSet ) { return (*other_gFunctionTable.pfnAddToFullPack)(state, e, ent, host, hostflags, player, pSet); } void CreateBaseline( int player, int eindex, struct entity_state_s *baseline, struct edict_s *entity, int playermodelindex, vec3_t player_mins, vec3_t player_maxs ) { (*other_gFunctionTable.pfnCreateBaseline)(player, eindex, baseline, entity, playermodelindex, player_mins, player_maxs); } void RegisterEncoders( void ) { (*other_gFunctionTable.pfnRegisterEncoders)(); } int GetWeaponData( struct edict_s *player, struct weapon_data_s *info ) { return (*other_gFunctionTable.pfnGetWeaponData)(player, info); } void CmdStart( const edict_t *player, const struct usercmd_s *cmd, unsigned int random_seed ) { (*other_gFunctionTable.pfnCmdStart)(player, cmd, random_seed); } void CmdEnd ( const edict_t *player ) { (*other_gFunctionTable.pfnCmdEnd)(player); } int ConnectionlessPacket( const struct netadr_s *net_from, const char *args, char *response_buffer, int *response_buffer_size ) { return (*other_gFunctionTable.pfnConnectionlessPacket)(net_from, args, response_buffer, response_buffer_size); } int GetHullBounds( int hullnumber, float *mins, float *maxs ) { return (*other_gFunctionTable.pfnGetHullBounds)(hullnumber, mins, maxs); } void CreateInstancedBaselines( void ) { (*other_gFunctionTable.pfnCreateInstancedBaselines)(); } int InconsistentFile( const edict_t *player, const char *filename, char *disconnect_message ) { return (*other_gFunctionTable.pfnInconsistentFile)(player, filename, disconnect_message); } int AllowLagCompensation( void ) { return (*other_gFunctionTable.pfnAllowLagCompensation)(); } DLL_FUNCTIONS gFunctionTable = { GameDLLInit, //pfnGameInit DispatchSpawn, //pfnSpawn DispatchThink, //pfnThink DispatchUse, //pfnUse DispatchTouch, //pfnTouch DispatchBlocked, //pfnBlocked DispatchKeyValue, //pfnKeyValue DispatchSave, //pfnSave DispatchRestore, //pfnRestore DispatchObjectCollsionBox, //pfnAbsBox SaveWriteFields, //pfnSaveWriteFields SaveReadFields, //pfnSaveReadFields SaveGlobalState, //pfnSaveGlobalState RestoreGlobalState, //pfnRestoreGlobalState ResetGlobalState, //pfnResetGlobalState ClientConnect, //pfnClientConnect ClientDisconnect, //pfnClientDisconnect ClientKill, //pfnClientKill ClientPutInServer, //pfnClientPutInServer ClientCommand, //pfnClientCommand ClientUserInfoChanged, //pfnClientUserInfoChanged ServerActivate, //pfnServerActivate ServerDeactivate, //pfnServerDeactivate PlayerPreThink, //pfnPlayerPreThink PlayerPostThink, //pfnPlayerPostThink StartFrame, //pfnStartFrame ParmsNewLevel, //pfnParmsNewLevel ParmsChangeLevel, //pfnParmsChangeLevel GetGameDescription, //pfnGetGameDescription Returns string describing current .dll game. PlayerCustomization, //pfnPlayerCustomization Notifies .dll of new customization for player. SpectatorConnect, //pfnSpectatorConnect Called when spectator joins server SpectatorDisconnect, //pfnSpectatorDisconnect Called when spectator leaves the server SpectatorThink, //pfnSpectatorThink Called when spectator sends a command packet (usercmd_t) Sys_Error, //pfnSys_Error Called when engine has encountered an error PM_Move, //pfnPM_Move PM_Init, //pfnPM_Init Server version of player movement initialization PM_FindTextureType, //pfnPM_FindTextureType SetupVisibility, //pfnSetupVisibility Set up PVS and PAS for networking for this client UpdateClientData, //pfnUpdateClientData Set up data sent only to specific client AddToFullPack, //pfnAddToFullPack CreateBaseline, //pfnCreateBaseline Tweak entity baseline for network encoding, allows setup of player baselines, too. RegisterEncoders, //pfnRegisterEncoders Callbacks for network encoding GetWeaponData, //pfnGetWeaponData CmdStart, //pfnCmdStart CmdEnd, //pfnCmdEnd ConnectionlessPacket, //pfnConnectionlessPacket GetHullBounds, //pfnGetHullBounds CreateInstancedBaselines, //pfnCreateInstancedBaselines InconsistentFile, //pfnInconsistentFile AllowLagCompensation, //pfnAllowLagCompensation }; C_DLLEXPORT int GetEntityAPI( DLL_FUNCTIONS *pFunctionTable, int interfaceVersion ) { // check if engine's pointer is valid and version is correct... if ( !pFunctionTable || interfaceVersion != INTERFACE_VERSION ) return FALSE; // pass engine callback function table to engine... memcpy( pFunctionTable, &gFunctionTable, sizeof( DLL_FUNCTIONS ) ); // pass other DLLs engine callbacks to function table... if (!(*other_GetEntityAPI)(&other_gFunctionTable, INTERFACE_VERSION)) return FALSE; // error initializing function table!!! return TRUE; } C_DLLEXPORT int GetNewDLLFunctions( NEW_DLL_FUNCTIONS *pFunctionTable, int *interfaceVersion ) { if (other_GetNewDLLFunctions == NULL) return FALSE; // pass other DLLs engine callbacks to function table... if (!(*other_GetNewDLLFunctions)(pFunctionTable, interfaceVersion)) return FALSE; // error initializing function table!!! return TRUE; } void ProcessBotCfgFile(void) { int ch; char cmd_line[256]; int cmd_index; static char server_cmd[80]; char *cmd, *arg1, *arg2; char msg[80]; if (bot_cfg_pause_time > gpGlobals->time) return; if (bot_cfg_fp == NULL) return; cmd_index = 0; cmd_line[cmd_index] = 0; ch = fgetc(bot_cfg_fp); // skip any leading blanks while (ch == ' ') ch = fgetc(bot_cfg_fp); while ((ch != EOF) && (ch != '\r') && (ch != '\n')) { if (ch == '\t') // convert tabs to spaces ch = ' '; cmd_line[cmd_index] = ch; ch = fgetc(bot_cfg_fp); // skip multiple spaces in input file while ((cmd_line[cmd_index] == ' ') && (ch == ' ')) ch = fgetc(bot_cfg_fp); cmd_index++; } if (ch == '\r') // is it a carriage return? { ch = fgetc(bot_cfg_fp); // skip the linefeed } // if reached end of file, then close it if (ch == EOF) { fclose(bot_cfg_fp); bot_cfg_fp = NULL; bot_cfg_pause_time = 0.0; } cmd_line[cmd_index] = 0; // terminate the command line // copy the command line to a server command buffer... strcpy(server_cmd, cmd_line); strcat(server_cmd, "\n"); cmd_index = 0; cmd = cmd_line; arg1 = arg2 = NULL; // skip to blank or end of string... while ((cmd_line[cmd_index] != ' ') && (cmd_line[cmd_index] != 0)) cmd_index++; if (cmd_line[cmd_index] == ' ') { cmd_line[cmd_index++] = 0; arg1 = &cmd_line[cmd_index]; // skip to blank or end of string... while ((cmd_line[cmd_index] != ' ') && (cmd_line[cmd_index] != 0)) cmd_index++; if (cmd_line[cmd_index] == ' ') { cmd_line[cmd_index++] = 0; arg2 = &cmd_line[cmd_index]; } } if (cmd_line[0] == '#' || cmd_line[0] == 0) return; // return if comment or blank line if (strcmp(cmd, "addbot") == 0) { BotCreate( NULL, arg1, arg2 ); // have to delay here or engine gives "Tried to write to // uninitialized sizebuf_t" error and crashes... bot_cfg_pause_time = gpGlobals->time + 2.0; bot_check_time = gpGlobals->time + 5.0; return; } if (strcmp(cmd, "botskill") == 0) { int temp = atoi(arg1); if ((temp >= 1) && (temp <= 5)) default_bot_skill = atoi( arg1 ); // set default bot skill level return; } if (strcmp(cmd, "observer") == 0) { int temp = atoi(arg1); if (temp) b_observer_mode = TRUE; else b_observer_mode = FALSE; return; } if (strcmp(cmd, "botdontshoot") == 0) { int temp = atoi(arg1); if (temp) b_botdontshoot = TRUE; else b_botdontshoot = FALSE; return; } if (strcmp(cmd, "min_bots") == 0) { min_bots = atoi( arg1 ); if ((min_bots < 0) || (min_bots > 31)) min_bots = 1; if (IS_DEDICATED_SERVER()) { sprintf(msg, "min_bots set to %d\n", min_bots); printf(msg); } return; } if (strcmp(cmd, "max_bots") == 0) { max_bots = atoi( arg1 ); if ((max_bots < 0) || (max_bots > 31)) max_bots = 1; if (IS_DEDICATED_SERVER()) { sprintf(msg, "max_bots set to %d\n", max_bots); printf(msg); } return; } if (strcmp(cmd, "pause") == 0) { bot_cfg_pause_time = gpGlobals->time + atoi( arg1 ); return; } if (strcmp(cmd, "bot_chat_percent") == 0) { int temp = atoi(arg1); if ((temp >= 0) && (temp <= 100)) bot_chat_percent = atoi( arg1 ); // set bot chat percent return; } SERVER_COMMAND(server_cmd); }
27.818095
164
0.604197
[ "vector" ]
328bd504bb706776a39786a5a1e918fde799a945
4,309
cpp
C++
src/menuoptions.cpp
projectivemotion/sdlgame1
9e126b6ef096605008dfc5db8e9264b68582b38a
[ "MIT" ]
null
null
null
src/menuoptions.cpp
projectivemotion/sdlgame1
9e126b6ef096605008dfc5db8e9264b68582b38a
[ "MIT" ]
null
null
null
src/menuoptions.cpp
projectivemotion/sdlgame1
9e126b6ef096605008dfc5db8e9264b68582b38a
[ "MIT" ]
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: menuoptions.cpp * Author: eye * * Created on September 24, 2019, 1:49 AM */ #include "menuoptions.h" #include "FontSurface.h" #include "app/AppClass.h" //typedef enum { // OPT1, // OPT2, // OPT3, // TOPTS //} opts; //void menuoptions::addOption(sceneid scenev, const char *pt, const SDL_Color& col, int x, int y){ void menuoptions::initOptions(){ // auto letters = app->getAssetManager().getFont("assets/unispace.ttf", 33); auto letters = app->getAssetManager().openFont(ASSET_FONT, 33); auto add = [this, letters](sceneid scenev, const char *pt, const SDL_Color& col, int x, int y){ int iheight = 50; int width = 200; opt mopt = {pt, letters->render(pt, col), {x,y,width,iheight}, 0, scenev}; opts.push_front(mopt); }; add(SCENE_BACKGROUND, "4 Balls", {0,0,255,128}, 100,100); add(SCENE_5BALLS, "5 Balls", {255, 255, 255, 255}, 100, 200); add(SCENE_SPRITETEST, "Sprite Test", {255, 0, 255, 255}, 100, 300); add(SCENE_MINES, "Mines", {255, 0, 255, 255}, 100, 400); } bool menuoptions::init(){ selectedOpt = nullptr; textx = nullptr; rect.w = 640; rect.h = 480; rect.x = 0; rect.y = 0; changed = true; initOptions(); sound = app->getAssetManager().getSound("assets/guncock.wav"); return true; } SDL_Texture *menuoptions::getTexture(){ if(textx == nullptr) return buildTexture(); return textx; } opt *menuoptions::getSelection(){ return selectedOpt; } // //void menuoptions::setOptionHandler(std::function<void(void)> h){ // handler = h; //} bool menuoptions::setChanged(bool nv){ bool ov = changed; changed = nv; clean(); // handler(); if(selectedOpt != nullptr) { sound->play(); // Mix_PlayChannel( -1, s1, 0 ); } return changed; } bool menuoptions::handleMouseEv(SDL_Event *e){ auto* prevSelection = selectedOpt; selectedOpt = nullptr; switch(e->type){ case SDL_MOUSEMOTION: int x = e->motion.x; int y = e->motion.y; // printf("Mouse %d %d\n", x, y); for(auto& opt : opts){ bool hover = (x > opt.rec.x && x < opt.rec.x+opt.rec.w && y > opt.rec.y && y < opt.rec.y + opt.rec.h ); int newstate = hover ? 1 : 0; if(hover){ // printf("Hit: %s %d %d %d %d\n", opt.t, opt.rec.x, opt.rec.y, // opt.rec.w, opt.rec.h); selectedOpt = &opt; } opt.state = hover ? 1 : 0; } break; } if(prevSelection != selectedOpt) { setChanged(true); } return true; } void menuoptions::clean(){ if(textx == nullptr) return; SDL_DestroyTexture(textx); textx = nullptr; } SDL_Texture *menuoptions::buildTexture(){ SDL_Texture *mTexture = nullptr; SDL_Surface *surface = nullptr; surface = SDL_CreateRGBSurface(0, 640, 480, 32, 0, 0, 0, 0); // fill auto blue = SDL_MapRGB(surface->format, 0, 0, 99); auto black = SDL_MapRGB(surface->format, 0, 0, 0); auto red = SDL_MapRGB(surface->format, 255, 0, 0); SDL_FillRect(surface, NULL, blue);// // draw for(auto& opt : opts){ // printf("%d %d %d %d\n", opt.rec.x, opt.rec.y, opt.rec.w, opt.rec.h); SDL_FillRect(surface, &opt.rec, opt.state == 1 ? red : black);// SDL_BlitSurface(opt.ren, nullptr, surface, &opt.rec); // printf("%d %d %d %d\n", opt.rec.x, opt.rec.y, opt.rec.w, opt.rec.h); } // textx = SDL_CreateTextureFromSurface( app->ren, surface ); SDL_FreeSurface(surface); // setChanged(false); return textx; } SDL_Rect *menuoptions::getrect(){ return &rect; } menuoptions::~menuoptions() { clean(); // @todo clear opt surfaces }
23.546448
103
0.540497
[ "render" ]
3290c52034a07ba30c2f9b5624732d675118d75d
7,176
cpp
C++
examples/car/carAbst_dba4.cpp
yinanl/rocs
bf2483903e39f4c0ea254a9ef56720a1259955ad
[ "BSD-3-Clause" ]
null
null
null
examples/car/carAbst_dba4.cpp
yinanl/rocs
bf2483903e39f4c0ea254a9ef56720a1259955ad
[ "BSD-3-Clause" ]
null
null
null
examples/car/carAbst_dba4.cpp
yinanl/rocs
bf2483903e39f4c0ea254a9ef56720a1259955ad
[ "BSD-3-Clause" ]
null
null
null
/** * carAbst_dba4.cpp * * Abstraction-based control for vehicle motion planning. * A different workspace setting from carAbst.cpp. * * Created by Yinan Li on Aug 10, 2020. * Hybrid Systems Group, University of Waterloo. */ #include <iostream> #include <fstream> #include <sstream> #include <iomanip> #include <cstdlib> #include <boost/algorithm/string.hpp> #include "src/abstraction.hpp" #include "src/DBAparser.h" #include "src/bsolver.hpp" #include "src/hdf5io.h" #include "car.hpp" int main(int argc, char *argv[]) { /** * Default values **/ std::string specfile; double eta[]{0.2, 0.2, 0.2}; /* partition precision */ bool preprocess = false; /* Input arguments: * carAbst dbafile precision(e.g. 0.2 0.2 0.2) -preprocess */ if (argc < 2 || argc > 6) { std::cout << "Improper number of arguments.\n"; std::exit(1); } specfile = std::string(argv[1]); if (argc > 2 && argc < 5) { std::cout << "Input precision should be of 3-dim, e.g. 0.2 0.2 0.2.\n"; std::exit(1); } if (argc >= 5) { for(int i = 2; i < 5; ++i) eta[i-2] = std::atof(argv[i]); if (argc > 5) { std::string param = std::string(argv[5]); if (param == "-preprocess") preprocess = true; else { std::cout << "Wrong argument for preprocessing.\n"; std::exit(1); } } } std::cout << "Partition precision: " << eta[0] << ' ' << eta[1] << ' ' << eta[2] << '\n'; clock_t tb, te; /* set the state space */ const double theta = 3.5; double xlb[] = {0, 0, -theta}; double xub[] = {10, 10, theta}; /* set the control values */ double ulb[] = {-1.0, -1.0}; double uub[] = {1.0, 1.0}; double mu[] = {0.3, 0.3}; /* define the control system */ rocs::DTCntlSys<carde> car("reach goal", h, carde::n, carde::m); car.init_workspace(xlb, xub); car.init_inputset(mu, ulb, uub); /** * Construct and save abstraction */ // const double eta[] = {0.2, 0.2, 0.2}; /* set precision */ rocs::abstraction<rocs::DTCntlSys<carde>> abst(&car); abst.init_state(eta, xlb, xub); std::cout << "The number of abstraction states: " << abst._x._nv << '\n'; /* Assign the label of avoid area to -1 */ rocs::UintSmall nAvoid = 3; double obs[3][4] = { {0.0, 3.2, 4.0, 5.0}, {5.4, 6.0, 5.0, 10.0}, {4.5, 5.2, 0.0, 2.5} }; auto label_avoid = [&obs, &nAvoid, &abst, &eta](size_t i) { std::vector<double> x(abst._x._dim); abst._x.id_to_val(x, i); double c1= eta[0]/2.0+1e-10; double c2= eta[1]/2.0+1e-10; for(size_t i = 0; i < nAvoid; ++i) { if ((obs[i][0]-c1) <= x[0] && x[0] <= (obs[i][1]+c1) && (obs[i][2]-c2) <= x[1] && x[1] <= (obs[i][3]+c2)) return -1; } return 0; }; abst.assign_labels(label_avoid); std::vector<size_t> obstacles; for (size_t i = 0; i < abst._x._nv; ++i) { if (abst._labels[i] < 0) obstacles.push_back(i); } /* Compute abstraction */ /* Robustness margins */ double e1[] = {0,0,0}; double e2[] = {0,0,0}; tb = clock(); abst.assign_transitions(e1, e2); // abst.assign_transitions(); te = clock(); float tabst = (float)(te - tb)/CLOCKS_PER_SEC; std::cout << "Time of computing abstraction: " << tabst << '\n'; std::cout << "# of transitions: " << abst._ts._ntrans << '\n'; /* Write abstraction to file */ // std::string nts_file_name = std::string("nts") + std::to_string(0.2) + std::string(".txt"); // rocs::txtWriter wtr(nts_file_name.c_str()); // wtr.write_fts_info(abst._ts); // wtr.write_pre_transitions(abst._ts, abst._x, xlb, xub); // wtr.open(); // wtr.close(); /** * Read DBA from dba*.txt file */ std::cout << "Reading the specification...\n"; rocs::UintSmall nAP = 0, nNodes = 0, q0 = 0; std::vector<rocs::UintSmall> acc; std::vector<std::vector<rocs::UintSmall>> arrayM; if (!rocs::read_spec(specfile, nNodes, nAP, q0, arrayM, acc)) std::exit(1); /* * Assign labels to states: has to be consistent with the dba file. */ double goal[6][4] = {{1.0, 2.0, 0.5, 2.0}, {7.1, 9.1, 1.9, 2.9}, {0.0, 4.0, 6.0, 10.0}, {6.0, 10.0, 0.0, 4.0}, {0.5, 2.5, 7.5, 8.5}, {3.8, 4.6, 3.1, 4.5}}; rocs::UintSmall nGoal = 6; auto label_target = [&goal, &nGoal, &abst, &eta](size_t i) { std::vector<double> x(abst._x._dim); abst._x.id_to_val(x, i); double c1= eta[0]/2.0; //+1e-10; double c2= eta[1]/2.0; //+1e-10; boost::dynamic_bitset<> label(nGoal, false); // n is the number of goals for(rocs::UintSmall i = 0; i < nGoal; ++i) { label[nGoal-1-i] = (goal[i][0] <= (x[0]-c1) && (x[0]+c1) <= goal[i][1] && goal[i][2] <= (x[1]-c2) && (x[1]+c2) <= goal[i][3]) ? true: false; } return label.to_ulong(); // label[0] is the least significant digit }; abst.assign_labels(label_target); std::cout << "Specification assignment is done.\n"; /** * Solve a Buchi game on the product of NTS and DBA. */ // std::cout << "Start solving a Buchi game on the product of the abstraction and DBA...\n"; // rocs::HEAD psolver; // memories will be allocated for psolver // rocs::initialization(&psolver); // rocs::construct_dba(&psolver, (int)nAP, (int)nNodes, (int)q0, acc, arrayM); // tb = clock(); // rocs::solve_buchigame_on_product(&psolver, abst); // te = clock(); // float tsyn = (float)(te - tb)/CLOCKS_PER_SEC; // std::cout << "Time of synthesizing controller: " << tsyn << '\n'; std::cout << "Start solving a Buchi game on the product of the abstraction and DBA...\n"; rocs::BSolver solver; solver.construct_dba((int)nAP, (int)nNodes, (int)q0, acc, arrayM); tb = clock(); solver.load_abstraction(abst); solver.generate_product(abst); solver.solve_buchigame_on_product(); te = clock(); float tsyn = (float)(te - tb)/CLOCKS_PER_SEC; std::cout << "Time of synthesizing controller: " << tsyn << '\n'; /** * Display and save memoryless controllers. */ std::vector<std::string> tokens; boost::split(tokens, specfile, boost::is_any_of(".")); std::string datafile = "controller_" + tokens[0] + "_"; for(int i = 0; i < 3; ++i) { std::stringstream ss; ss << std::setprecision(1); ss << eta[i]; datafile += ss.str(); if (i < 2) datafile += "-"; } datafile += ".h5"; std::cout << "Writing the controller...\n"; // solver.write_controller_to_txt(const_cast<char*>(datafile.c_str())); rocs::h5FileHandler ctlrWtr(datafile, H5F_ACC_TRUNC); ctlrWtr.write_problem_setting< rocs::DTCntlSys<carde> >(car); ctlrWtr.write_array<double>(eta, carde::n, "eta"); ctlrWtr.write_2d_array<double>(abst._x._data, "xgrid"); ctlrWtr.write_discrete_controller(&(solver._sol)); std::cout << "Controller writing is done.\n"; std::cout << "Total time of used (abstraction+synthesis): " << tabst+tsyn << '\n'; return 0; }
32.035714
98
0.561315
[ "vector" ]
32926db239c78fb31e46d26f97b6517349093927
375
cpp
C++
CppPrimer/CppPrimer-Exercises/CppPrimer-Ch03/Exercise3.12.cpp
alaxion/Learning
4b12b1603419252103cd933fdbfc4b2faffb6d00
[ "MIT" ]
null
null
null
CppPrimer/CppPrimer-Exercises/CppPrimer-Ch03/Exercise3.12.cpp
alaxion/Learning
4b12b1603419252103cd933fdbfc4b2faffb6d00
[ "MIT" ]
null
null
null
CppPrimer/CppPrimer-Exercises/CppPrimer-Ch03/Exercise3.12.cpp
alaxion/Learning
4b12b1603419252103cd933fdbfc4b2faffb6d00
[ "MIT" ]
null
null
null
// Exercise3.12.cpp // Ad // Which of the following vector definitions are in error? #include <iostream> #include <vector> using std::cin; using std::cout; using std::endl; using std::vector; using std::string; int main() { vector<vector<int>> ivec; vector<string> svec1 = ivec; vector<string> svec2(10, "null"); // Pause cin.get(); return 0; }
17.045455
59
0.642667
[ "vector" ]
329710343e58ea5cd36ab833be8bb5e1cf7e7fa7
28,173
cc
C++
google/cloud/securitycenter/internal/security_center_connection_impl.cc
sydney-munro/google-cloud-cpp
374b52e5cec78962358bdd5913d4118a47af1952
[ "Apache-2.0" ]
null
null
null
google/cloud/securitycenter/internal/security_center_connection_impl.cc
sydney-munro/google-cloud-cpp
374b52e5cec78962358bdd5913d4118a47af1952
[ "Apache-2.0" ]
null
null
null
google/cloud/securitycenter/internal/security_center_connection_impl.cc
sydney-munro/google-cloud-cpp
374b52e5cec78962358bdd5913d4118a47af1952
[ "Apache-2.0" ]
null
null
null
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated by the Codegen C++ plugin. // If you make any local changes, they will be lost. // source: google/cloud/securitycenter/v1/securitycenter_service.proto #include "google/cloud/securitycenter/internal/security_center_connection_impl.h" #include "google/cloud/securitycenter/internal/security_center_option_defaults.h" #include "google/cloud/background_threads.h" #include "google/cloud/common_options.h" #include "google/cloud/grpc_options.h" #include "google/cloud/internal/async_long_running_operation.h" #include "google/cloud/internal/pagination_range.h" #include "google/cloud/internal/retry_loop.h" #include <memory> namespace google { namespace cloud { namespace securitycenter_internal { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN SecurityCenterConnectionImpl::SecurityCenterConnectionImpl( std::unique_ptr<google::cloud::BackgroundThreads> background, std::shared_ptr<securitycenter_internal::SecurityCenterStub> stub, Options options) : background_(std::move(background)), stub_(std::move(stub)), options_(internal::MergeOptions( std::move(options), securitycenter_internal::SecurityCenterDefaultOptions( SecurityCenterConnection::options()))) {} future<StatusOr<google::cloud::securitycenter::v1::BulkMuteFindingsResponse>> SecurityCenterConnectionImpl::BulkMuteFindings( google::cloud::securitycenter::v1::BulkMuteFindingsRequest const& request) { auto stub = stub_; return google::cloud::internal::AsyncLongRunningOperation< google::cloud::securitycenter::v1::BulkMuteFindingsResponse>( background_->cq(), request, [stub](google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::cloud::securitycenter::v1::BulkMuteFindingsRequest const& request) { return stub->AsyncBulkMuteFindings(cq, std::move(context), request); }, [stub](google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::longrunning::GetOperationRequest const& request) { return stub->AsyncGetOperation(cq, std::move(context), request); }, [stub](google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::longrunning::CancelOperationRequest const& request) { return stub->AsyncCancelOperation(cq, std::move(context), request); }, &google::cloud::internal::ExtractLongRunningResultResponse< google::cloud::securitycenter::v1::BulkMuteFindingsResponse>, retry_policy(), backoff_policy(), idempotency_policy()->BulkMuteFindings(request), polling_policy(), __func__); } StatusOr<google::cloud::securitycenter::v1::Source> SecurityCenterConnectionImpl::CreateSource( google::cloud::securitycenter::v1::CreateSourceRequest const& request) { return google::cloud::internal::RetryLoop( retry_policy(), backoff_policy(), idempotency_policy()->CreateSource(request), [this](grpc::ClientContext& context, google::cloud::securitycenter::v1::CreateSourceRequest const& request) { return stub_->CreateSource(context, request); }, request, __func__); } StatusOr<google::cloud::securitycenter::v1::Finding> SecurityCenterConnectionImpl::CreateFinding( google::cloud::securitycenter::v1::CreateFindingRequest const& request) { return google::cloud::internal::RetryLoop( retry_policy(), backoff_policy(), idempotency_policy()->CreateFinding(request), [this](grpc::ClientContext& context, google::cloud::securitycenter::v1::CreateFindingRequest const& request) { return stub_->CreateFinding(context, request); }, request, __func__); } StatusOr<google::cloud::securitycenter::v1::MuteConfig> SecurityCenterConnectionImpl::CreateMuteConfig( google::cloud::securitycenter::v1::CreateMuteConfigRequest const& request) { return google::cloud::internal::RetryLoop( retry_policy(), backoff_policy(), idempotency_policy()->CreateMuteConfig(request), [this](grpc::ClientContext& context, google::cloud::securitycenter::v1::CreateMuteConfigRequest const& request) { return stub_->CreateMuteConfig(context, request); }, request, __func__); } StatusOr<google::cloud::securitycenter::v1::NotificationConfig> SecurityCenterConnectionImpl::CreateNotificationConfig( google::cloud::securitycenter::v1::CreateNotificationConfigRequest const& request) { return google::cloud::internal::RetryLoop( retry_policy(), backoff_policy(), idempotency_policy()->CreateNotificationConfig(request), [this](grpc::ClientContext& context, google::cloud::securitycenter::v1:: CreateNotificationConfigRequest const& request) { return stub_->CreateNotificationConfig(context, request); }, request, __func__); } Status SecurityCenterConnectionImpl::DeleteMuteConfig( google::cloud::securitycenter::v1::DeleteMuteConfigRequest const& request) { return google::cloud::internal::RetryLoop( retry_policy(), backoff_policy(), idempotency_policy()->DeleteMuteConfig(request), [this](grpc::ClientContext& context, google::cloud::securitycenter::v1::DeleteMuteConfigRequest const& request) { return stub_->DeleteMuteConfig(context, request); }, request, __func__); } Status SecurityCenterConnectionImpl::DeleteNotificationConfig( google::cloud::securitycenter::v1::DeleteNotificationConfigRequest const& request) { return google::cloud::internal::RetryLoop( retry_policy(), backoff_policy(), idempotency_policy()->DeleteNotificationConfig(request), [this](grpc::ClientContext& context, google::cloud::securitycenter::v1:: DeleteNotificationConfigRequest const& request) { return stub_->DeleteNotificationConfig(context, request); }, request, __func__); } StatusOr<google::iam::v1::Policy> SecurityCenterConnectionImpl::GetIamPolicy( google::iam::v1::GetIamPolicyRequest const& request) { return google::cloud::internal::RetryLoop( retry_policy(), backoff_policy(), idempotency_policy()->GetIamPolicy(request), [this](grpc::ClientContext& context, google::iam::v1::GetIamPolicyRequest const& request) { return stub_->GetIamPolicy(context, request); }, request, __func__); } StatusOr<google::cloud::securitycenter::v1::MuteConfig> SecurityCenterConnectionImpl::GetMuteConfig( google::cloud::securitycenter::v1::GetMuteConfigRequest const& request) { return google::cloud::internal::RetryLoop( retry_policy(), backoff_policy(), idempotency_policy()->GetMuteConfig(request), [this](grpc::ClientContext& context, google::cloud::securitycenter::v1::GetMuteConfigRequest const& request) { return stub_->GetMuteConfig(context, request); }, request, __func__); } StatusOr<google::cloud::securitycenter::v1::NotificationConfig> SecurityCenterConnectionImpl::GetNotificationConfig( google::cloud::securitycenter::v1::GetNotificationConfigRequest const& request) { return google::cloud::internal::RetryLoop( retry_policy(), backoff_policy(), idempotency_policy()->GetNotificationConfig(request), [this]( grpc::ClientContext& context, google::cloud::securitycenter::v1::GetNotificationConfigRequest const& request) { return stub_->GetNotificationConfig(context, request); }, request, __func__); } StatusOr<google::cloud::securitycenter::v1::OrganizationSettings> SecurityCenterConnectionImpl::GetOrganizationSettings( google::cloud::securitycenter::v1::GetOrganizationSettingsRequest const& request) { return google::cloud::internal::RetryLoop( retry_policy(), backoff_policy(), idempotency_policy()->GetOrganizationSettings(request), [this](grpc::ClientContext& context, google::cloud::securitycenter::v1:: GetOrganizationSettingsRequest const& request) { return stub_->GetOrganizationSettings(context, request); }, request, __func__); } StatusOr<google::cloud::securitycenter::v1::Source> SecurityCenterConnectionImpl::GetSource( google::cloud::securitycenter::v1::GetSourceRequest const& request) { return google::cloud::internal::RetryLoop( retry_policy(), backoff_policy(), idempotency_policy()->GetSource(request), [this]( grpc::ClientContext& context, google::cloud::securitycenter::v1::GetSourceRequest const& request) { return stub_->GetSource(context, request); }, request, __func__); } StreamRange<google::cloud::securitycenter::v1::GroupResult> SecurityCenterConnectionImpl::GroupAssets( google::cloud::securitycenter::v1::GroupAssetsRequest request) { request.clear_page_token(); auto stub = stub_; auto retry = std::shared_ptr<securitycenter::SecurityCenterRetryPolicy const>( retry_policy()); auto backoff = std::shared_ptr<BackoffPolicy const>(backoff_policy()); auto idempotency = idempotency_policy()->GroupAssets(request); char const* function_name = __func__; return google::cloud::internal::MakePaginationRange< StreamRange<google::cloud::securitycenter::v1::GroupResult>>( std::move(request), [stub, retry, backoff, idempotency, function_name]( google::cloud::securitycenter::v1::GroupAssetsRequest const& r) { return google::cloud::internal::RetryLoop( retry->clone(), backoff->clone(), idempotency, [stub](grpc::ClientContext& context, google::cloud::securitycenter::v1::GroupAssetsRequest const& request) { return stub->GroupAssets(context, request); }, r, function_name); }, [](google::cloud::securitycenter::v1::GroupAssetsResponse r) { std::vector<google::cloud::securitycenter::v1::GroupResult> result( r.group_by_results().size()); auto& messages = *r.mutable_group_by_results(); std::move(messages.begin(), messages.end(), result.begin()); return result; }); } StreamRange<google::cloud::securitycenter::v1::GroupResult> SecurityCenterConnectionImpl::GroupFindings( google::cloud::securitycenter::v1::GroupFindingsRequest request) { request.clear_page_token(); auto stub = stub_; auto retry = std::shared_ptr<securitycenter::SecurityCenterRetryPolicy const>( retry_policy()); auto backoff = std::shared_ptr<BackoffPolicy const>(backoff_policy()); auto idempotency = idempotency_policy()->GroupFindings(request); char const* function_name = __func__; return google::cloud::internal::MakePaginationRange< StreamRange<google::cloud::securitycenter::v1::GroupResult>>( std::move(request), [stub, retry, backoff, idempotency, function_name]( google::cloud::securitycenter::v1::GroupFindingsRequest const& r) { return google::cloud::internal::RetryLoop( retry->clone(), backoff->clone(), idempotency, [stub]( grpc::ClientContext& context, google::cloud::securitycenter::v1::GroupFindingsRequest const& request) { return stub->GroupFindings(context, request); }, r, function_name); }, [](google::cloud::securitycenter::v1::GroupFindingsResponse r) { std::vector<google::cloud::securitycenter::v1::GroupResult> result( r.group_by_results().size()); auto& messages = *r.mutable_group_by_results(); std::move(messages.begin(), messages.end(), result.begin()); return result; }); } StreamRange< google::cloud::securitycenter::v1::ListAssetsResponse::ListAssetsResult> SecurityCenterConnectionImpl::ListAssets( google::cloud::securitycenter::v1::ListAssetsRequest request) { request.clear_page_token(); auto stub = stub_; auto retry = std::shared_ptr<securitycenter::SecurityCenterRetryPolicy const>( retry_policy()); auto backoff = std::shared_ptr<BackoffPolicy const>(backoff_policy()); auto idempotency = idempotency_policy()->ListAssets(request); char const* function_name = __func__; return google::cloud::internal::MakePaginationRange<StreamRange< google::cloud::securitycenter::v1::ListAssetsResponse::ListAssetsResult>>( std::move(request), [stub, retry, backoff, idempotency, function_name]( google::cloud::securitycenter::v1::ListAssetsRequest const& r) { return google::cloud::internal::RetryLoop( retry->clone(), backoff->clone(), idempotency, [stub](grpc::ClientContext& context, google::cloud::securitycenter::v1::ListAssetsRequest const& request) { return stub->ListAssets(context, request); }, r, function_name); }, [](google::cloud::securitycenter::v1::ListAssetsResponse r) { std::vector<google::cloud::securitycenter::v1::ListAssetsResponse:: ListAssetsResult> result(r.list_assets_results().size()); auto& messages = *r.mutable_list_assets_results(); std::move(messages.begin(), messages.end(), result.begin()); return result; }); } StreamRange< google::cloud::securitycenter::v1::ListFindingsResponse::ListFindingsResult> SecurityCenterConnectionImpl::ListFindings( google::cloud::securitycenter::v1::ListFindingsRequest request) { request.clear_page_token(); auto stub = stub_; auto retry = std::shared_ptr<securitycenter::SecurityCenterRetryPolicy const>( retry_policy()); auto backoff = std::shared_ptr<BackoffPolicy const>(backoff_policy()); auto idempotency = idempotency_policy()->ListFindings(request); char const* function_name = __func__; return google::cloud::internal::MakePaginationRange< StreamRange<google::cloud::securitycenter::v1::ListFindingsResponse:: ListFindingsResult>>( std::move(request), [stub, retry, backoff, idempotency, function_name]( google::cloud::securitycenter::v1::ListFindingsRequest const& r) { return google::cloud::internal::RetryLoop( retry->clone(), backoff->clone(), idempotency, [stub](grpc::ClientContext& context, google::cloud::securitycenter::v1::ListFindingsRequest const& request) { return stub->ListFindings(context, request); }, r, function_name); }, [](google::cloud::securitycenter::v1::ListFindingsResponse r) { std::vector<google::cloud::securitycenter::v1::ListFindingsResponse:: ListFindingsResult> result(r.list_findings_results().size()); auto& messages = *r.mutable_list_findings_results(); std::move(messages.begin(), messages.end(), result.begin()); return result; }); } StreamRange<google::cloud::securitycenter::v1::MuteConfig> SecurityCenterConnectionImpl::ListMuteConfigs( google::cloud::securitycenter::v1::ListMuteConfigsRequest request) { request.clear_page_token(); auto stub = stub_; auto retry = std::shared_ptr<securitycenter::SecurityCenterRetryPolicy const>( retry_policy()); auto backoff = std::shared_ptr<BackoffPolicy const>(backoff_policy()); auto idempotency = idempotency_policy()->ListMuteConfigs(request); char const* function_name = __func__; return google::cloud::internal::MakePaginationRange< StreamRange<google::cloud::securitycenter::v1::MuteConfig>>( std::move(request), [stub, retry, backoff, idempotency, function_name]( google::cloud::securitycenter::v1::ListMuteConfigsRequest const& r) { return google::cloud::internal::RetryLoop( retry->clone(), backoff->clone(), idempotency, [stub]( grpc::ClientContext& context, google::cloud::securitycenter::v1::ListMuteConfigsRequest const& request) { return stub->ListMuteConfigs(context, request); }, r, function_name); }, [](google::cloud::securitycenter::v1::ListMuteConfigsResponse r) { std::vector<google::cloud::securitycenter::v1::MuteConfig> result( r.mute_configs().size()); auto& messages = *r.mutable_mute_configs(); std::move(messages.begin(), messages.end(), result.begin()); return result; }); } StreamRange<google::cloud::securitycenter::v1::NotificationConfig> SecurityCenterConnectionImpl::ListNotificationConfigs( google::cloud::securitycenter::v1::ListNotificationConfigsRequest request) { request.clear_page_token(); auto stub = stub_; auto retry = std::shared_ptr<securitycenter::SecurityCenterRetryPolicy const>( retry_policy()); auto backoff = std::shared_ptr<BackoffPolicy const>(backoff_policy()); auto idempotency = idempotency_policy()->ListNotificationConfigs(request); char const* function_name = __func__; return google::cloud::internal::MakePaginationRange< StreamRange<google::cloud::securitycenter::v1::NotificationConfig>>( std::move(request), [stub, retry, backoff, idempotency, function_name](google::cloud::securitycenter::v1:: ListNotificationConfigsRequest const& r) { return google::cloud::internal::RetryLoop( retry->clone(), backoff->clone(), idempotency, [stub](grpc::ClientContext& context, google::cloud::securitycenter::v1:: ListNotificationConfigsRequest const& request) { return stub->ListNotificationConfigs(context, request); }, r, function_name); }, [](google::cloud::securitycenter::v1::ListNotificationConfigsResponse r) { std::vector<google::cloud::securitycenter::v1::NotificationConfig> result(r.notification_configs().size()); auto& messages = *r.mutable_notification_configs(); std::move(messages.begin(), messages.end(), result.begin()); return result; }); } StreamRange<google::cloud::securitycenter::v1::Source> SecurityCenterConnectionImpl::ListSources( google::cloud::securitycenter::v1::ListSourcesRequest request) { request.clear_page_token(); auto stub = stub_; auto retry = std::shared_ptr<securitycenter::SecurityCenterRetryPolicy const>( retry_policy()); auto backoff = std::shared_ptr<BackoffPolicy const>(backoff_policy()); auto idempotency = idempotency_policy()->ListSources(request); char const* function_name = __func__; return google::cloud::internal::MakePaginationRange< StreamRange<google::cloud::securitycenter::v1::Source>>( std::move(request), [stub, retry, backoff, idempotency, function_name]( google::cloud::securitycenter::v1::ListSourcesRequest const& r) { return google::cloud::internal::RetryLoop( retry->clone(), backoff->clone(), idempotency, [stub](grpc::ClientContext& context, google::cloud::securitycenter::v1::ListSourcesRequest const& request) { return stub->ListSources(context, request); }, r, function_name); }, [](google::cloud::securitycenter::v1::ListSourcesResponse r) { std::vector<google::cloud::securitycenter::v1::Source> result( r.sources().size()); auto& messages = *r.mutable_sources(); std::move(messages.begin(), messages.end(), result.begin()); return result; }); } future<StatusOr<google::cloud::securitycenter::v1::RunAssetDiscoveryResponse>> SecurityCenterConnectionImpl::RunAssetDiscovery( google::cloud::securitycenter::v1::RunAssetDiscoveryRequest const& request) { auto stub = stub_; return google::cloud::internal::AsyncLongRunningOperation< google::cloud::securitycenter::v1::RunAssetDiscoveryResponse>( background_->cq(), request, [stub](google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::cloud::securitycenter::v1::RunAssetDiscoveryRequest const& request) { return stub->AsyncRunAssetDiscovery(cq, std::move(context), request); }, [stub](google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::longrunning::GetOperationRequest const& request) { return stub->AsyncGetOperation(cq, std::move(context), request); }, [stub](google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::longrunning::CancelOperationRequest const& request) { return stub->AsyncCancelOperation(cq, std::move(context), request); }, &google::cloud::internal::ExtractLongRunningResultResponse< google::cloud::securitycenter::v1::RunAssetDiscoveryResponse>, retry_policy(), backoff_policy(), idempotency_policy()->RunAssetDiscovery(request), polling_policy(), __func__); } StatusOr<google::cloud::securitycenter::v1::Finding> SecurityCenterConnectionImpl::SetFindingState( google::cloud::securitycenter::v1::SetFindingStateRequest const& request) { return google::cloud::internal::RetryLoop( retry_policy(), backoff_policy(), idempotency_policy()->SetFindingState(request), [this](grpc::ClientContext& context, google::cloud::securitycenter::v1::SetFindingStateRequest const& request) { return stub_->SetFindingState(context, request); }, request, __func__); } StatusOr<google::cloud::securitycenter::v1::Finding> SecurityCenterConnectionImpl::SetMute( google::cloud::securitycenter::v1::SetMuteRequest const& request) { return google::cloud::internal::RetryLoop( retry_policy(), backoff_policy(), idempotency_policy()->SetMute(request), [this](grpc::ClientContext& context, google::cloud::securitycenter::v1::SetMuteRequest const& request) { return stub_->SetMute(context, request); }, request, __func__); } StatusOr<google::iam::v1::Policy> SecurityCenterConnectionImpl::SetIamPolicy( google::iam::v1::SetIamPolicyRequest const& request) { return google::cloud::internal::RetryLoop( retry_policy(), backoff_policy(), idempotency_policy()->SetIamPolicy(request), [this](grpc::ClientContext& context, google::iam::v1::SetIamPolicyRequest const& request) { return stub_->SetIamPolicy(context, request); }, request, __func__); } StatusOr<google::iam::v1::TestIamPermissionsResponse> SecurityCenterConnectionImpl::TestIamPermissions( google::iam::v1::TestIamPermissionsRequest const& request) { return google::cloud::internal::RetryLoop( retry_policy(), backoff_policy(), idempotency_policy()->TestIamPermissions(request), [this](grpc::ClientContext& context, google::iam::v1::TestIamPermissionsRequest const& request) { return stub_->TestIamPermissions(context, request); }, request, __func__); } StatusOr<google::cloud::securitycenter::v1::ExternalSystem> SecurityCenterConnectionImpl::UpdateExternalSystem( google::cloud::securitycenter::v1::UpdateExternalSystemRequest const& request) { return google::cloud::internal::RetryLoop( retry_policy(), backoff_policy(), idempotency_policy()->UpdateExternalSystem(request), [this]( grpc::ClientContext& context, google::cloud::securitycenter::v1::UpdateExternalSystemRequest const& request) { return stub_->UpdateExternalSystem(context, request); }, request, __func__); } StatusOr<google::cloud::securitycenter::v1::Finding> SecurityCenterConnectionImpl::UpdateFinding( google::cloud::securitycenter::v1::UpdateFindingRequest const& request) { return google::cloud::internal::RetryLoop( retry_policy(), backoff_policy(), idempotency_policy()->UpdateFinding(request), [this](grpc::ClientContext& context, google::cloud::securitycenter::v1::UpdateFindingRequest const& request) { return stub_->UpdateFinding(context, request); }, request, __func__); } StatusOr<google::cloud::securitycenter::v1::MuteConfig> SecurityCenterConnectionImpl::UpdateMuteConfig( google::cloud::securitycenter::v1::UpdateMuteConfigRequest const& request) { return google::cloud::internal::RetryLoop( retry_policy(), backoff_policy(), idempotency_policy()->UpdateMuteConfig(request), [this](grpc::ClientContext& context, google::cloud::securitycenter::v1::UpdateMuteConfigRequest const& request) { return stub_->UpdateMuteConfig(context, request); }, request, __func__); } StatusOr<google::cloud::securitycenter::v1::NotificationConfig> SecurityCenterConnectionImpl::UpdateNotificationConfig( google::cloud::securitycenter::v1::UpdateNotificationConfigRequest const& request) { return google::cloud::internal::RetryLoop( retry_policy(), backoff_policy(), idempotency_policy()->UpdateNotificationConfig(request), [this](grpc::ClientContext& context, google::cloud::securitycenter::v1:: UpdateNotificationConfigRequest const& request) { return stub_->UpdateNotificationConfig(context, request); }, request, __func__); } StatusOr<google::cloud::securitycenter::v1::OrganizationSettings> SecurityCenterConnectionImpl::UpdateOrganizationSettings( google::cloud::securitycenter::v1::UpdateOrganizationSettingsRequest const& request) { return google::cloud::internal::RetryLoop( retry_policy(), backoff_policy(), idempotency_policy()->UpdateOrganizationSettings(request), [this](grpc::ClientContext& context, google::cloud::securitycenter::v1:: UpdateOrganizationSettingsRequest const& request) { return stub_->UpdateOrganizationSettings(context, request); }, request, __func__); } StatusOr<google::cloud::securitycenter::v1::Source> SecurityCenterConnectionImpl::UpdateSource( google::cloud::securitycenter::v1::UpdateSourceRequest const& request) { return google::cloud::internal::RetryLoop( retry_policy(), backoff_policy(), idempotency_policy()->UpdateSource(request), [this](grpc::ClientContext& context, google::cloud::securitycenter::v1::UpdateSourceRequest const& request) { return stub_->UpdateSource(context, request); }, request, __func__); } StatusOr<google::cloud::securitycenter::v1::SecurityMarks> SecurityCenterConnectionImpl::UpdateSecurityMarks( google::cloud::securitycenter::v1::UpdateSecurityMarksRequest const& request) { return google::cloud::internal::RetryLoop( retry_policy(), backoff_policy(), idempotency_policy()->UpdateSecurityMarks(request), [this]( grpc::ClientContext& context, google::cloud::securitycenter::v1::UpdateSecurityMarksRequest const& request) { return stub_->UpdateSecurityMarks(context, request); }, request, __func__); } GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace securitycenter_internal } // namespace cloud } // namespace google
44.648177
81
0.691371
[ "vector" ]
3299835ae69d9c50ae43d7ddc25219e3aaf4e1e0
23,303
tpp
C++
src/hypro/algorithms/eigendecomposition/Transformation.tpp
hypro/hypro
52ae4ffe0a8427977fce8d7979fffb82a1bc28f6
[ "MIT" ]
22
2016-10-05T12:19:01.000Z
2022-01-23T09:14:41.000Z
src/hypro/algorithms/eigendecomposition/Transformation.tpp
hypro/hypro
52ae4ffe0a8427977fce8d7979fffb82a1bc28f6
[ "MIT" ]
23
2017-05-08T15:02:39.000Z
2021-11-03T16:43:39.000Z
src/hypro/algorithms/eigendecomposition/Transformation.tpp
hypro/hypro
52ae4ffe0a8427977fce8d7979fffb82a1bc28f6
[ "MIT" ]
12
2017-06-07T23:51:09.000Z
2022-01-04T13:06:21.000Z
/** * @file Transformation.tpp * @author Jan Philipp Hafer */ #include "Transformation.h" namespace hypro { template <typename Number> Transformation<Number>::Transformation( const HybridAutomaton<Number>& _hybrid ) { const size_t CONDITION_LIMIT = 100; Matrix<Number> matrix_in_parser; size_t m_size, i; Matrix<Number> V_EVD; DiagonalMatrix<Number> D_EVD; Matrix<Number> Vinv_EVD; Matrix<Number> V; Matrix<Number> Vinv; Matrix<Number> A_in; Vector<Number> b_tr; //later transformed (b + taking linear terms into account) Matrix<Number> A_nonlinear; Vector<Number> b_nonlinear; LocationManager<Number>& locationManager = LocationManager<Number>::getInstance(); typename HybridAutomaton<Number>::Locations locations; Location<Number>* PtrtoNewLoc; mTransformedHA = HybridAutomaton<Number>(); //LOCATIONS for ( Location<Number>* LocPtr : _hybrid.getLocations() ) { matrix_in_parser = LocPtr->getFlow(); //copy for calculation; TODO many flows? -> lots of duplicate code/management m_size = matrix_in_parser.cols(); //rows assert( m_size >= 1 ); //exit if location size < 1 ==>> underflow error m_size -= 1; //Due to parsing: for representation zero row is added for constant coefficients we do not need STallValues<Number> mSTallvalues; mSTallvalues.mSTindependentFunct.expFunctionType.resize( m_size ); for ( i = 0; i < m_size; ++i ) { mSTallvalues.mSTindependentFunct.expFunctionType[i] = EXP_FUNCT_TYPE::INITIALIZED; assert( mSTallvalues.mSTindependentFunct.expFunctionType[i] == EXP_FUNCT_TYPE::INITIALIZED ); } assert( mSTallvalues.mSTindependentFunct.expFunctionType.capacity() == mSTallvalues.mSTindependentFunct.expFunctionType.size() ); declare_structures( mSTallvalues, m_size ); b_tr = Vector<Number>( m_size ); A_in = Matrix<Number>( m_size, m_size ); //no change due to being lookup V = Matrix<Number>( m_size, m_size ); //mSTallvalues gets V as well Vinv = Matrix<Number>( m_size, m_size ); b_tr = matrix_in_parser.topRightCorner( m_size, 1 ); A_in = matrix_in_parser.topLeftCorner( m_size, m_size ); mSTallvalues.mSTflowpipeSegment.trafoInput.setIdentity( m_size, m_size ); //x'=Ax with A=identity and crossed out influence of linear terms std::cout << "inital A:\n" << A_in; size_t numberLinear = countLinearAndRemember( A_in, m_size, mSTallvalues ); std::cout << "Number of Linear Terms: " << numberLinear << "\n"; //LINEARONLY if ( numberLinear == m_size ) { std::cout << "linear FLOW only\n"; Vinv.setIdentity( m_size, m_size ); V.setIdentity( m_size, m_size ); mSTallvalues.mSTindependentFunct.D.diagonal().setZero( m_size ); mSTallvalues.mSTflowpipeSegment.Vinv = Vinv; mSTallvalues.mSTflowpipeSegment.V = V; for ( i = 0; i < m_size; ++i ) { mSTallvalues.mSTindependentFunct.expFunctionType[i] = EXP_FUNCT_TYPE::CONSTANT; } } else { //LINEAR TERMS INSIDE matrix A -> size adaption for transformation if ( numberLinear > 0 ) { std::cout << "flow has linear terms\n"; size_t nonLinearsize = m_size - numberLinear; A_nonlinear = Matrix<Number>( nonLinearsize, nonLinearsize ); b_nonlinear = Vector<Number>( nonLinearsize ); V_EVD = Matrix<Number>( nonLinearsize, nonLinearsize ); D_EVD = DiagonalMatrix<Number>( nonLinearsize ); Vinv_EVD = Matrix<Number>( nonLinearsize, nonLinearsize ); std::cout << "nonLinearsize: " << nonLinearsize << "\n"; //ADAPTION of size and remember linear terms(in mSTallvalues) insertNonLinearAndClassify( A_in, b_tr, m_size, A_nonlinear, b_nonlinear, mSTallvalues ); std::cout << "A_nonlinear\n" << A_nonlinear; EigenvalueDecomposition( A_nonlinear, nonLinearsize, CONDITION_LIMIT, V_EVD, D_EVD, Vinv_EVD ); //convert the linear terms to change convergence point adjustLinearAndEVDcomponents( V_EVD, D_EVD, Vinv_EVD, A_in, b_nonlinear, m_size, V, Vinv, b_tr, mSTallvalues ); } else { //NO LINEAR TERMS std::cout << "no linear terms\n"; EigenvalueDecomposition( A_in, m_size, CONDITION_LIMIT, V, mSTallvalues.mSTindependentFunct.D, Vinv ); mSTallvalues.mSTflowpipeSegment.Vinv = Vinv; mSTallvalues.mSTflowpipeSegment.V = V; } //TRAFO of b_tr to Eigenspace b_tr = Vinv * b_tr; analyzeExponentialTerms( m_size, mSTallvalues ); } std::unique_ptr<Location<Number>> PtrtoNewLoc = std::make_unique<Location<Number>>( matrix_in_parser ); mLocationPtrsMap.insert( std::make_pair( LocPtr, PtrtoNewLoc.get() ) ); //SAVING STRUCT TRACE( "hypro.eigendecomposition", "D exact:\n" << mSTallvalues.mSTindependentFunct.D.diagonal() ); TRACE( "hypro.eigendecomposition", "b_tr :\n" << b_tr ); for ( i = 0; i < m_size; ++i ) { //SCALING dependents on linear terms if ( ( mSTallvalues.mSTindependentFunct.expFunctionType[i] == EXP_FUNCT_TYPE::CONVERGENT ) || ( mSTallvalues.mSTindependentFunct.expFunctionType[i] == EXP_FUNCT_TYPE::DIVERGENT ) ) { mSTallvalues.mSTindependentFunct.xinhom( i ) = b_tr( i ) / mSTallvalues.mSTindependentFunct.D.diagonal()( i ); continue; } if ( mSTallvalues.mSTindependentFunct.expFunctionType[i] == EXP_FUNCT_TYPE::LINEAR ) { mSTallvalues.mSTindependentFunct.xinhom( i ) = b_tr( i ); continue; } if ( mSTallvalues.mSTindependentFunct.expFunctionType[i] == EXP_FUNCT_TYPE::CONSTANT ) { mSTallvalues.mSTindependentFunct.xinhom( i ) = 0; continue; } FATAL( "hypro.eigendecomposition", "INVALID FUNCTION TYPE RECOGNIZED" ); std::exit( EXIT_FAILURE ); } TRACE( "hypro.eigendecomposition", "xinhom :\n" << mSTallvalues.mSTindependentFunct.xinhom ); mLocPtrtoComputationvaluesMap.insert( std::make_pair( PtrtoNewLoc.get(), mSTallvalues ) ); //std::cout << "old loc: "<<LocPtr<<"\n"; //std::cout << "new loc: "<<PtrtoNewLoc<<"\n"; //INVARIANTS(TYPE CONDITION) const Condition<Number>& invar1 = LocPtr->getInvariant(); Condition<Number> invar1NEW; //Condition(Ax<=b): A*Vsource*xeigen <= b; for ( i = 0; i < invar1.size(); ++i ) { invar1NEW.setMatrix( invar1.getMatrix( i ) * V, i ); invar1NEW.setVector( invar1.getVector( i ), i ); } PtrtoNewLoc->setInvariant( invar1NEW ); locations.emplace( std::move( PtrtoNewLoc ) ); } mTransformedHA.setLocations( std::move( locations ) ); //TRANSITIONS typename HybridAutomaton<Number>::transitionVector transitions; for ( Transition<Number>* TransPtr : _hybrid.getTransitions() ) { std::unique_ptr<Transition<Number>> NewTransPtr = std::make_unique<Transition<Number>>( *TransPtr ); //TODO transitionManager? transitions not freed, shared_ptr too costly in multithreaded context //POINTER Location<Number>* NewSourceLocPtr = mLocationPtrsMap[TransPtr->getSource()]; Location<Number>* NewTargetLocPtr = mLocationPtrsMap[TransPtr->getTarget()]; const Matrix<Number>& VSource = mLocPtrtoComputationvaluesMap[NewSourceLocPtr].mSTflowpipeSegment.V; const Matrix<Number>& VinvTarget = mLocPtrtoComputationvaluesMap[NewTargetLocPtr].mSTflowpipeSegment.Vinv; const Matrix<Number>& trafoInputTarget = mLocPtrtoComputationvaluesMap[NewTargetLocPtr].mSTflowpipeSegment.trafoInput; NewTransPtr->setSource( NewSourceLocPtr ); NewTransPtr->setTarget( NewTargetLocPtr ); //GUARD ( when transition can be made ) const Condition<Number>& guard1 = TransPtr->getGuard(); Condition<Number> guard1NEW; // = NewTransPtr->getGuard(); //Condition(Ax<=b): A*Vsource*xeigen <= b; for ( i = 0; i < guard1.size(); ++i ) { guard1NEW.setMatrix( guard1.getMatrix( i ) * VSource, i ); guard1NEW.setVector( guard1.getVector( i ), i ); } NewTransPtr->setGuard( guard1NEW ); //RESET ( reset into new location ) note: s:=source, t:=target, inv:=^(-1) const Reset<Number>& reset1 = TransPtr->getReset(); Reset<Number> reset1NEW; // = NewTransPtr->getReset(); //reset(into Eigenspace of new location): Vtarget^(-1)x'= //Vtinv*removelinearTerms*A*Vsource*xeigen[Vsource^(-1)x] + Vtarget^(-1)b for ( i = 0; i < reset1.size(); ++i ) { reset1NEW.setMatrix( VinvTarget * trafoInputTarget * reset1.getMatrix( i ) * VSource, i ); reset1NEW.setVector( VinvTarget * reset1.getVector( i ), i ); } NewTransPtr->setReset( reset1NEW ); NewTargetLocPtr->addTransition( NewTransPtr.get() ); transitions.emplace( std::move( NewTransPtr ) ); } mTransformedHA.setTransitions( std::move( transitions ) ); //INITIAL STATES (transformed into Eigenspace later on reachability analysis) locationStateMap initialStates; for ( typename locationStateMap::const_iterator it = _hybrid.getInitialStates().begin(); it != _hybrid.getInitialStates().end(); ++it ) { Location<Number>* NewLocPtr = mLocationPtrsMap[it->first]; State_t<Number> state1NEW = State_t<Number>( it->second ); state1NEW.setTimestamp( carl::Interval<Number>( 0 ) ); state1NEW.setLocation( NewLocPtr ); mTransformedHA.addInitialState( state1NEW ); } //LOCAL BAD STATES (condition [matrix,vector] matrix=matrix*V for ( typename HybridAutomaton<Number>::locationConditionMap::const_iterator it = _hybrid.getLocalBadStates().begin(); it != _hybrid.getLocalBadStates().end(); ++it ) { Location<Number>* NewLocPtr = mLocationPtrsMap[it->first]; TRACE( "hypro.eigendecomposition", "OldLocPtr" << it->first ); TRACE( "hypro.eigendecomposition", "NewLocPtr" << NewLocPtr ); const Condition<Number>& badState = it->second; TRACE( "hypro.eigendecomposition", "BadState" << badState ); Condition<Number> badStateNEW; const Matrix<Number>& V = mLocPtrtoComputationvaluesMap[NewLocPtr].mSTflowpipeSegment.V; for ( i = 0; i < badState.size(); ++i ) { //Condition(Ax<=b): A*Vsource*xeigen <= b; badStateNEW.setMatrix( badState.getMatrix( i ) * V, i ); badStateNEW.setVector( badState.getVector( i ), i ); } TRACE( "hypro.eigendecomposition", "transformed localBadState: " << badStateNEW ); mTransformedHA.addLocalBadState( NewLocPtr, badStateNEW ); } //for (const auto & locBadState : mTransformedHA.getLocalBadStates() ) { // TRACE("hypro.eigendecomposition","in location: " << locBadState.first) // TRACE("hypro.eigendecomposition","after trafo State:" << locBadState.second); //} //eigen decompositions from eigen with complex eigenvalues seem to result in wrong results (V even not invertible) //LOOP through all locations checking V,D,Vinv for NaN, Inf, -Inf (implicitly also sNan, qNaN) //bool outOfRange = false; //for (typename locationVector::const_iterator locIt=mTransformedHA.getLocations().begin(); // locIt!=mTransformedHA.getLocations().end(); ++locIt) { // STflowpipeSegment<Number>& segmentinfo = mLocPtrtoComputationvaluesMap[*locIt].mSTflowpipeSegment; // STindependentFunct<Number>& indepentinfo = mLocPtrtoComputationvaluesMap[*locIt].mSTindependentFunct; // if( (segmentinfo.Vinv.array().isNaN() == 1).any() || (segmentinfo.Vinv.array().isNaN() == 1).any() ) // outOfRange = true; // if( (segmentinfo.V.array().isNaN() == 1).any() || (segmentinfo.V.array().isNaN() == 1).any() ) // outOfRange = true; // if( (indepentinfo.D.diagonal().array().isNaN() == 1).any() || (indepentinfo.D.diagonal().array().isNaN() == 1).any() ) // outOfRange = true; //} //if (outOfRange) { // FATAL("hypro.eigendecomposition","OUT OF BOUNDS on EVD computation, please check the results in DEBUG mode"); // std::exit(EXIT_FAILURE); //} } template <typename Number> void Transformation<Number>::addGlobalBadStates( const HybridAutomaton<Number>& _hybrid, const bool transform ) { //CHECK MATCH OF LOCATION PTRS assert( _hybrid.getLocations().size() == mLocationPtrsMap.size() ); typename locationPtrMap::const_iterator locIt = mLocationPtrsMap.begin(); typename locationPtrMap::const_iterator endLocIt = mLocationPtrsMap.end(); for ( typename locationVector::iterator origIt = _hybrid.getLocations().begin(); origIt != _hybrid.getLocations().end(); ++origIt ) { //locations is set -> value is ptrs to origLoc, in map key is ptrs to origLoc assert( *origIt == locIt->first ); if ( locIt != endLocIt ) ++locIt; } assert( locIt == endLocIt ); //TRANSFORMATION -> for each globalBadState : set localBadState A*Vx <= b for according V of location //1. loop through global states //2. loop through ptr to location map and create new localBadState if ( transform ) { assert( !globalBadStatesTransformed ); //TODO MEMORY ASSERTION? size_t i; for ( typename conditionVector::const_iterator it = _hybrid.getGlobalBadStates().begin(); it != _hybrid.getGlobalBadStates().end(); ++it ) { for ( typename locationPtrMap::iterator locMapIt = mLocationPtrsMap.begin(); locMapIt != mLocationPtrsMap.end(); ++locMapIt ) { Condition<Number> badStateNEW; const Matrix<Number>& V = mLocPtrtoComputationvaluesMap[locMapIt->second].mSTflowpipeSegment.V; for ( i = 0; i < it->size(); ++i ) { badStateNEW.setMatrix( it->getMatrix( i ) * V, i ); badStateNEW.setVector( it->getVector( i ), i ); } mTransformedHA.addLocalBadState( locMapIt->second, badStateNEW ); } } globalBadStatesTransformed = true; } else { //NO TRANSFORMATION -> add to globalBadStates size_t i; for ( typename conditionVector::const_iterator it = _hybrid.getGlobalBadStates().begin(); it != _hybrid.getGlobalBadStates().end(); ++it ) { //loop through global states + copy to other HybridAutomaton for ( typename locationPtrMap::iterator locMapIt = mLocationPtrsMap.begin(); locMapIt != mLocationPtrsMap.end(); ++locMapIt ) { Condition<Number> globalbadStateNEW; for ( i = 0; i < it->size(); ++i ) { globalbadStateNEW.setMatrix( it->getMatrix( i ), i ); globalbadStateNEW.setVector( it->getVector( i ), i ); } mTransformedHA.addGlobalBadState( globalbadStateNEW ); } } } } template <typename Number> void Transformation<Number>::declare_structures( STallValues<Number>& mSTallValues, const int n ) { mSTallValues.mSTindependentFunct.D = DiagonalMatrix<Number>( n ); mSTallValues.mSTindependentFunct.xinhom = Vector<Number>( n ); mSTallValues.mSTflowpipeSegment.V = Matrix<Number>( n, n ); mSTallValues.mSTflowpipeSegment.Vinv = Matrix<Number>( n, n ); mSTallValues.mSTflowpipeSegment.trafoInput = Matrix<Number>( n, n ); } //count linear and remember in according std::vector template <typename Number> size_t Transformation<Number>::countLinearAndRemember( const Matrix<Number>& A_in, const size_t dimension, STallValues<Number>& mSTallvalues ) { //std::cout << "starting linear counting\n"; //dimension = dimension of A_in size_t count_linearVariables = 0; size_t nrow, ncol; bool linear; for ( nrow = 0; nrow < dimension; ++nrow ) { linear = true; for ( ncol = 0; ncol < dimension; ++ncol ) { if ( A_in( nrow, ncol ) != 0 ) { linear = false; break; } } if ( linear == true ) { ++count_linearVariables; mSTallvalues.mSTindependentFunct.expFunctionType[nrow] = EXP_FUNCT_TYPE::LINEAR; } else { assert( A_in( nrow, nrow ) != 0 ); //diagonal of nonlinear-term has to be defined } } return count_linearVariables; } //having linear terms, we grep nonlinear terms to apply EVD on template <typename Number> void Transformation<Number>::insertNonLinearAndClassify( const Matrix<Number>& A_in, const Vector<Number>& b_in, const size_t dimension, Matrix<Number>& A_nonlinear, Vector<Number>& b_nonlinear, STallValues<Number>& mSTallvalues ) { size_t ncol, nrow; size_t count_linVar_row = 0; size_t count_linVar_col = 0; //CHECK if according vector contains linear behavior -> skip columns //for rows: count the according occurences of linear terms to access correct element for ( ncol = 0; ncol < dimension; ++ncol ) { if ( mSTallvalues.mSTindependentFunct.expFunctionType[ncol] == EXP_FUNCT_TYPE::LINEAR ) { ++count_linVar_col; continue; } count_linVar_row = 0; for ( nrow = 0; nrow < dimension; ++nrow ) { if ( mSTallvalues.mSTindependentFunct.expFunctionType[nrow] == EXP_FUNCT_TYPE::LINEAR ) { ++count_linVar_row; } else { //std::cout << "A_nonlinear: \n" << A_nonlinear << "\n"; A_nonlinear( nrow - count_linVar_row, ncol - count_linVar_col ) = A_in( nrow, ncol ); //std::cout << "A_nonlinear: \n" << A_nonlinear << "\n"; } } } count_linVar_col = 0; for ( ncol = 0; ncol < dimension; ++ncol ) { if ( mSTallvalues.mSTindependentFunct.expFunctionType[ncol] == EXP_FUNCT_TYPE::LINEAR ) { ++count_linVar_col; if ( b_in( ncol ) == 0 ) { mSTallvalues.mSTindependentFunct.expFunctionType[ncol] = EXP_FUNCT_TYPE::CONSTANT; } } else { b_nonlinear( ncol - count_linVar_col ) = b_in( ncol ); } } std::cout << "A_nonlinear after reduction\n" << A_nonlinear; } template <typename Number> void Transformation<Number>::EigenvalueDecomposition( const Matrix<Number>& A_nonlinear, const size_t dimensionNonLinear, const size_t CONDITION_LIMIT, Matrix<Number>& V_EVD, DiagonalMatrix<Number>& D_EVD, Matrix<Number>& Vinv_EVD ) { //ONE DIMENSION -> set values(to save time) if ( dimensionNonLinear == 1 ) { std::cout << "dimension == 1\n"; V_EVD( 0, 0 ) = 1; Vinv_EVD( 0, 0 ) = 1; D_EVD.diagonal()( 0 ) = A_nonlinear( 0, 0 ); std::cout << "D_EVD:\n" << A_nonlinear << "\n"; return; } DiagonalMatrixdouble Ddouble = DiagonalMatrixdouble( dimensionNonLinear ); //formulation in .h Matrix<double> Vdouble = Matrix<double>( dimensionNonLinear, dimensionNonLinear ); Matrix<double> Vinvdouble = Matrix<double>( dimensionNonLinear, dimensionNonLinear ); Matrix<double> matrixCalcDouble = Matrix<double>( dimensionNonLinear, dimensionNonLinear ); matrixCalcDouble = convert<Number, double>( A_nonlinear ); Eigen::EigenSolver<Matrix<double>> es( matrixCalcDouble ); Vdouble << es.eigenvectors().real(); Ddouble.diagonal() << es.eigenvalues().real(); Vinvdouble = Vdouble.inverse(); //ASSERTION CONDITION TODO making this faster for big/sparse matrices Eigen::JacobiSVD<Matrix<double>> svd( Vinvdouble ); double cond = svd.singularValues()( 0 ) / svd.singularValues()( svd.singularValues().size() - 1 ); if ( std::abs( cond ) > CONDITION_LIMIT ) { FATAL( "hypro.eigendecomposition", "condition is higher than CONDITION_LIMIT" ); } std::cout << "A_nonlinear\n" << A_nonlinear; //CHECKUP for invalid results bool outOfRange = false; if ( ( Vinvdouble.array().isNaN() == 1 ).any() || ( Vinvdouble.array().isInf() == 1 ).any() ) outOfRange = true; if ( ( Vdouble.array().isNaN() == 1 ).any() || ( Vdouble.array().isInf() == 1 ).any() ) outOfRange = true; if ( ( Ddouble.diagonal().array().isNaN() == 1 ).any() || ( Ddouble.diagonal().array().isInf() == 1 ).any() ) outOfRange = true; //CONVERSION TO RATIONAL V_EVD = convert<double, Number>( Vdouble ); D_EVD = convert<double, Number>( Ddouble ); Vinv_EVD = convert<double, Number>( Vinvdouble ); std::cout << "Vinv_EVD(condition): (" << cond << ")\n" << Vinv_EVD; std::cout << "V_EVD:\n" << V_EVD; std::cout << "D_EVD:\n" << D_EVD.diagonal(); TRACE( "hypro.eigendecomposition", "V\n" << V_EVD ); TRACE( "hypro.eigendecompositoin", "Vinv\n" << Vinv_EVD ); //exit after output of EVD for quick feedback if ( outOfRange ) { FATAL( "hypro.eigendecomposition", "OUT OF BOUNDS on EVD computation, please check the results in DEBUG mode" ); std::exit( EXIT_FAILURE ); } } template <typename Number> void Transformation<Number>::adjustLinearAndEVDcomponents( const Matrix<Number>& V_EVD, const DiagonalMatrix<Number>& D_EVD, const Matrix<Number>& Vinv_EVD, const Matrix<Number>& A_in, const Vector<Number>& b_nonlinear, const size_t dimension, Matrix<Number>& V, Matrix<Number>& Vinv, Vector<Number>& b_tr, STallValues<Number>& mSTallvalues ) { //1.setting V,Vinv,D, b_tr V.setIdentity( dimension, dimension ); Vinv.setIdentity( dimension, dimension ); mSTallvalues.mSTindependentFunct.D.diagonal().setZero( dimension ); size_t nrow, ncol; size_t count_linVar_row = 0; size_t count_linVar_col = 0; for ( ncol = 0; ncol < dimension; ++ncol ) { if ( mSTallvalues.mSTindependentFunct.expFunctionType[ncol] == EXP_FUNCT_TYPE::LINEAR ) { ++count_linVar_col; continue; } count_linVar_row = 0; for ( nrow = 0; nrow < dimension; ++nrow ) { if ( mSTallvalues.mSTindependentFunct.expFunctionType[nrow] == EXP_FUNCT_TYPE::LINEAR ) { ++count_linVar_row; continue; } else { V( nrow, ncol ) = V_EVD( nrow - count_linVar_row, ncol - count_linVar_col ); Vinv( nrow, ncol ) = Vinv_EVD( nrow - count_linVar_row, ncol - count_linVar_col ); mSTallvalues.mSTindependentFunct.D.diagonal()( ncol ) = D_EVD.diagonal()( ncol - count_linVar_col ); } } //ASSIGN b_tr b_tr( ncol ) = b_nonlinear( ncol - count_linVar_col ); } mSTallvalues.mSTflowpipeSegment.V = V; mSTallvalues.mSTflowpipeSegment.Vinv = Vinv; //2.ADJUSTING b_tr (b_nonlinear was assigned) std::cout << "A_in\n" << A_in; std::cout << b_tr; for ( nrow = 0; nrow < dimension; ++nrow ) { if ( mSTallvalues.mSTindependentFunct.expFunctionType[nrow] == EXP_FUNCT_TYPE::LINEAR ) { for ( ncol = 0; ncol < dimension; ++ncol ) { b_tr( ncol ) += A_in( nrow, ncol ) * b_tr( nrow ); } } } //3.ADJUSTING trafoMatrix for x for ( ncol = 0; ncol < dimension; ++ncol ) { if ( mSTallvalues.mSTindependentFunct.expFunctionType[nrow] == EXP_FUNCT_TYPE::LINEAR ) { for ( nrow = 0; nrow < dimension; ++nrow ) { if ( nrow != ncol ) { mSTallvalues.mSTflowpipeSegment.trafoInput( nrow, ncol ) = A_in( nrow, ncol ); } } } } //std::cout << "D[" << nrow <<"]: " << mSTallvalues.mSTindependentFunct.D.diagonal()(nrow) << "\n"; DEBUG( "hypro.eigendecomposition", "A_in\n" << A_in ); DEBUG( "hypro.eigendecomposition", "b_tr\n" << b_tr ); DEBUG( "hypro.eigendecomposition", "Vinv\n" << Vinv ); DEBUG( "hypro.eigendecomposition", "V\n" << V ); DEBUG( "hypro.eigendecomposition", "D\n" << mSTallvalues.mSTindependentFunct.D.diagonal() ); DEBUG( "hypro.eigendecomposition", "trafoInput\n" << mSTallvalues.mSTflowpipeSegment.trafoInput ); } template <typename Number> void Transformation<Number>::analyzeExponentialTerms( const size_t dimension, STallValues<Number>& mSTallvalues ) { size_t nrow; //TODO COMPARISON ALMOST EQUAL 0 [else div by 0] (D.diagonal()(i) == 0 theoretically possible) for ( nrow = 0; nrow < dimension; ++nrow ) { if ( mSTallvalues.mSTindependentFunct.expFunctionType[nrow] == EXP_FUNCT_TYPE::INITIALIZED ) { assert( mSTallvalues.mSTindependentFunct.D.diagonal()( nrow ) != 0 ); if ( mSTallvalues.mSTindependentFunct.D.diagonal()( nrow ) > 0 ) { mSTallvalues.mSTindependentFunct.expFunctionType[nrow] = CONVERGENT; } else { mSTallvalues.mSTindependentFunct.expFunctionType[nrow] = DIVERGENT; } } assert( mSTallvalues.mSTindependentFunct.expFunctionType[nrow] != EXP_FUNCT_TYPE::INITIALIZED ); } } template <typename Number> void Transformation<Number>::output_HybridAutomaton() { std::cout << "\n-------------- STARTOF transformed AUTOMATA ------------------" << std::endl; std::cout << mTransformedHA << "\n-------------- ENDOF transformed AUTOMATA ------------------" << std::endl; } } //namespace hypro
46.420319
142
0.69682
[ "vector", "transform" ]
32a6ba86258783c3f89832dfecf6f3972e19cf48
257
cxx
C++
Basic Programs/Some CP Problems/DivisibilityProblem1328A.cxx
PrajaktaSathe/HacktoberFest2020
e84fc7a513afe3dd75c7c28db1866d7f5e6a8147
[ "MIT" ]
null
null
null
Basic Programs/Some CP Problems/DivisibilityProblem1328A.cxx
PrajaktaSathe/HacktoberFest2020
e84fc7a513afe3dd75c7c28db1866d7f5e6a8147
[ "MIT" ]
null
null
null
Basic Programs/Some CP Problems/DivisibilityProblem1328A.cxx
PrajaktaSathe/HacktoberFest2020
e84fc7a513afe3dd75c7c28db1866d7f5e6a8147
[ "MIT" ]
null
null
null
#include <algorithm> #include <vector> #include <iostream> using namespace std; int main(){ int t; cin >> t; for(int i=0;i<t;i++){ int a,b,k,l; cin >> a >> b; if(a%b==0) cout<<0<<'\n'; else { k=a%b; l=b-k; cout << l<<'\n'; } } return 0; }
12.238095
26
0.51751
[ "vector" ]
32b481c9d1f4f5d4b9513f74d1f912dbc351389f
923
hpp
C++
bundle.hpp
jameskingstonclarke/pit
6a548a6ba8893b6e4373c630dd67e6f220ac502c
[ "MIT" ]
1
2020-08-26T21:50:27.000Z
2020-08-26T21:50:27.000Z
bundle.hpp
jameskingstonclarke/pit
6a548a6ba8893b6e4373c630dd67e6f220ac502c
[ "MIT" ]
null
null
null
bundle.hpp
jameskingstonclarke/pit
6a548a6ba8893b6e4373c630dd67e6f220ac502c
[ "MIT" ]
null
null
null
#pragma once #include <string> #include <iostream> #include <vector> #include <stack> #include "value.hpp" #include "instruction.hpp" /* a bundle represents a compiled pit program/module. the bundle can be written to a file or passed to the runtime. */ namespace pit { class Bundle { public: Bundle(); Bundle(std::string file); void write_instr(uint8_t instr, uint32_t line); void write_constant(Value value); void to_file(std::string filename); void disassemble(); uint32_t disassemble_instruction(uint32_t offset); // constants std::vector<Value> constant_pool; // locals std::vector<Value> locals; // code std::vector<uint8_t> code; // lines corresponding to bytecode std::vector<uint32_t> lines; private: inline int no_arg(std::string instr, uint32_t offset); inline int one_arg(std::string instr, uint32_t offset); inline int two_args(std::string instr, uint32_t offset); }; }
24.945946
61
0.729144
[ "vector" ]
32b50b76729a4d14dd6c71abc1a51717b4d9bdf7
1,270
hpp
C++
source/lix/exec/stack.hpp
vector-of-bool/lix
b4f590abbdc9aedc92347d3b7a33854c05f7066e
[ "MIT" ]
2
2018-09-15T10:17:32.000Z
2022-01-29T04:01:02.000Z
source/lix/exec/stack.hpp
vector-of-bool/lix
b4f590abbdc9aedc92347d3b7a33854c05f7066e
[ "MIT" ]
null
null
null
source/lix/exec/stack.hpp
vector-of-bool/lix
b4f590abbdc9aedc92347d3b7a33854c05f7066e
[ "MIT" ]
null
null
null
#ifndef LIX_EXEC_STACK_HPP_INCLUDED #define LIX_EXEC_STACK_HPP_INCLUDED #include <lix/code/types.hpp> #include <lix/value.hpp> #include <lix/exec/closure.hpp> #include <lix/exec/fn.hpp> #include <cassert> #include <deque> #include <variant> #include <vector> namespace lix::exec { using lix::code::inst_offset_t; using lix::code::slot_ref_t; class stack { std::deque<lix::value> _items; public: using iterator = std::deque<lix::value>::const_iterator; using const_iterator = iterator; using size_type = std::deque<lix::value>::size_type; size_type size() const { return _items.size(); } const lix::value& nth(slot_ref_t off) const { // assert(off < size()); // return _items[off]; return _items.at(off.index); } lix::value& nth_mut(slot_ref_t off) { return _items.at(off.index); } void push(lix::value&& el) { _items.push_back(std::move(el)); } void push(const lix::value& el) { _items.push_back(el); } void rewind(slot_ref_t new_top) { assert(new_top.index <= size()); auto new_end = _items.begin() + new_top.index; _items.erase(new_end, _items.end()); } }; } // namespace lix::exec #endif // LIX_EXEC_STACK_HPP_INCLUDED
27.021277
74
0.645669
[ "vector" ]
32b915287f1c5ffd12e1e8c11c867ae6db0c07d3
10,149
cpp
C++
Source/UnrealSandboxTerrain/Private/TerrainZoneComponent.cpp
Mu-L/UnrealSandboxTerrain
2c38082f5726d0613c874646d5b214e416de8cf3
[ "MIT" ]
null
null
null
Source/UnrealSandboxTerrain/Private/TerrainZoneComponent.cpp
Mu-L/UnrealSandboxTerrain
2c38082f5726d0613c874646d5b214e416de8cf3
[ "MIT" ]
null
null
null
Source/UnrealSandboxTerrain/Private/TerrainZoneComponent.cpp
Mu-L/UnrealSandboxTerrain
2c38082f5726d0613c874646d5b214e416de8cf3
[ "MIT" ]
null
null
null
// Copyright blackw 2015-2020 #include "UnrealSandboxTerrainPrivatePCH.h" #include "TerrainZoneComponent.h" #include "SandboxTerrainController.h" #include "SandboxVoxeldata.h" #include "VoxelIndex.h" #include "serialization.hpp" #include "DrawDebugHelpers.h" TValueDataPtr SerializeMeshData(TMeshDataPtr MeshDataPtr); UTerrainFoliageMesh::UTerrainFoliageMesh(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { } UTerrainZoneComponent::UTerrainZoneComponent(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { PrimaryComponentTick.bCanEverTick = false; CurrentTerrainLodMask = 0xff; bIsObjectsNeedSave = false; } void UTerrainZoneComponent::ApplyTerrainMesh(TMeshDataPtr MeshDataPtr, const TTerrainLodMask TerrainLodMask) { const std::lock_guard<std::mutex> lock(TerrainMeshMutex); double start = FPlatformTime::Seconds(); TMeshData* MeshData = MeshDataPtr.get(); if (GetTerrainController()->bShowApplyZone) { DrawDebugBox(GetWorld(), GetComponentLocation(), FVector(USBT_ZONE_SIZE / 2), FColor(255, 255, 255, 0), false, 5); } if (MeshData == nullptr) { return; } if (MeshDataTimeStamp > MeshDataPtr->TimeStamp) { UE_LOG(LogSandboxTerrain, Log, TEXT("ASandboxTerrainZone::applyTerrainMesh skip late thread -> %f"), MeshDataPtr->TimeStamp); } MeshDataTimeStamp = MeshDataPtr->TimeStamp; // do not reduce lod mask TTerrainLodMask TargetTerrainLodMask = 0; if(TerrainLodMask < CurrentTerrainLodMask){ TargetTerrainLodMask = TerrainLodMask; CurrentTerrainLodMask = TerrainLodMask; } else { TargetTerrainLodMask = CurrentTerrainLodMask; } //MainTerrainMesh->SetMobility(EComponentMobility::Movable); //MainTerrainMesh->AddLocalRotation(FRotator(0.0f, 0.01, 0.0f)); // workaround //MainTerrainMesh->AddLocalRotation(FRotator(0.0f, -0.01, 0.0f)); // workaround //MainTerrainMesh->bLodFlag = GetTerrainController()->bEnableLOD; MainTerrainMesh->SetMeshData(MeshDataPtr, TargetTerrainLodMask); //MainTerrainMesh->SetMobility(EComponentMobility::Stationary); MainTerrainMesh->bCastShadowAsTwoSided = true; MainTerrainMesh->SetCastShadow(true); MainTerrainMesh->bCastHiddenShadow = true; MainTerrainMesh->SetVisibility(true); MainTerrainMesh->SetCollisionMeshData(MeshDataPtr); MainTerrainMesh->SetCollisionProfileName(TEXT("BlockAll")); double end = FPlatformTime::Seconds(); double time = (end - start) * 1000; //UE_LOG(LogSandboxTerrain, Log, TEXT("ASandboxTerrainZone::applyTerrainMesh ---------> %f %f %f --> %f ms"), GetComponentLocation().X, GetComponentLocation().Y, GetComponentLocation().Z, time); } typedef struct TInstantMeshData { float X; float Y; float Z; float Roll; float Pitch; float Yaw; float ScaleX; float ScaleY; float ScaleZ; } TInstantMeshData; TValueDataPtr UTerrainZoneComponent::SerializeAndResetObjectData(){ const std::lock_guard<std::mutex> lock(InstancedMeshMutex); TValueDataPtr Data = SerializeInstancedMeshes(); bIsObjectsNeedSave = false; return Data; } TValueDataPtr UTerrainZoneComponent::SerializeInstancedMesh(const TInstanceMeshTypeMap& InstanceObjectMap) { usbt::TFastUnsafeSerializer Serializer; int32 MeshCount = InstanceObjectMap.Num(); Serializer << MeshCount; for (auto& Elem : InstanceObjectMap) { const TInstanceMeshArray& InstancedObjectArray = Elem.Value; union { uint32 A[2]; uint64 B; }; B = Elem.Key; uint32 MeshTypeId = A[0]; uint32 MeshVariantId = A[1]; int32 MeshInstanceCount = InstancedObjectArray.TransformArray.Num(); Serializer << MeshTypeId << MeshVariantId << MeshInstanceCount; for (int32 InstanceIdx = 0; InstanceIdx < MeshInstanceCount; InstanceIdx++) { TInstantMeshData P; const FTransform& InstanceTransform = InstancedObjectArray.TransformArray[InstanceIdx]; P.X = InstanceTransform.GetLocation().X; P.Y = InstanceTransform.GetLocation().Y; P.Z = InstanceTransform.GetLocation().Z; P.Roll = InstanceTransform.Rotator().Roll; P.Pitch = InstanceTransform.Rotator().Pitch; P.Yaw = InstanceTransform.Rotator().Yaw; P.ScaleX = InstanceTransform.GetScale3D().X; P.ScaleY = InstanceTransform.GetScale3D().Y; P.ScaleZ = InstanceTransform.GetScale3D().Z; Serializer << P; } } return Serializer.data(); } std::shared_ptr<std::vector<uint8>> UTerrainZoneComponent::SerializeInstancedMeshes() { usbt::TFastUnsafeSerializer Serializer; int32 MeshCount = InstancedMeshMap.Num(); Serializer << MeshCount; for (auto& Elem : InstancedMeshMap) { UTerrainFoliageMesh* InstancedStaticMeshComponent = Elem.Value; union { uint32 A[2]; uint64 B; }; B = Elem.Key; uint32 MeshTypeId = A[0]; uint32 MeshVariantId = A[1]; int32 MeshInstanceCount = InstancedStaticMeshComponent->GetInstanceCount(); Serializer << MeshTypeId << MeshVariantId << MeshInstanceCount; for (int32 InstanceIdx = 0; InstanceIdx < MeshInstanceCount; InstanceIdx++) { TInstantMeshData P; FTransform InstanceTransform; InstancedStaticMeshComponent->GetInstanceTransform(InstanceIdx, InstanceTransform, true); const FVector LocalPos = InstanceTransform.GetLocation() - GetComponentLocation(); P.X = LocalPos.X; P.Y = LocalPos.Y; P.Z = LocalPos.Z; P.Roll = InstanceTransform.Rotator().Roll; P.Pitch = InstanceTransform.Rotator().Pitch; P.Yaw = InstanceTransform.Rotator().Yaw; P.ScaleX = InstanceTransform.GetScale3D().X; P.ScaleY = InstanceTransform.GetScale3D().Y; P.ScaleZ = InstanceTransform.GetScale3D().Z; Serializer << P; } } return Serializer.data(); } void UTerrainZoneComponent::DeserializeInstancedMeshes(std::vector<uint8>& Data, TInstanceMeshTypeMap& ZoneInstMeshMap) { usbt::TFastUnsafeDeserializer Deserializer(Data.data()); int32 MeshCount; Deserializer >> MeshCount; for (int Idx = 0; Idx < MeshCount; Idx++) { uint32 MeshTypeId; uint32 MeshVariantId; int32 MeshInstanceCount; Deserializer >> MeshTypeId; Deserializer >> MeshVariantId; Deserializer >> MeshInstanceCount; FTerrainInstancedMeshType MeshType; if (GetTerrainController()->FoliageMap.Contains(MeshTypeId)) { FSandboxFoliage FoliageType = GetTerrainController()->FoliageMap[MeshTypeId]; if ((uint32)FoliageType.MeshVariants.Num() > MeshVariantId) { MeshType.Mesh = FoliageType.MeshVariants[MeshVariantId]; MeshType.MeshTypeId = MeshTypeId; MeshType.MeshVariantId = MeshVariantId; MeshType.StartCullDistance = FoliageType.StartCullDistance; MeshType.EndCullDistance = FoliageType.EndCullDistance; } } TInstanceMeshArray& InstMeshArray = ZoneInstMeshMap.FindOrAdd(MeshType.GetMeshTypeCode()); InstMeshArray.MeshType = MeshType; InstMeshArray.TransformArray.Reserve(MeshInstanceCount); for (int32 InstanceIdx = 0; InstanceIdx < MeshInstanceCount; InstanceIdx++) { TInstantMeshData P; Deserializer >> P; FTransform Transform(FRotator(P.Pitch, P.Yaw, P.Roll), FVector(P.X, P.Y, P.Z), FVector(P.ScaleX, P.ScaleY, P.ScaleZ)); if (MeshType.Mesh != nullptr) { InstMeshArray.TransformArray.Add(Transform); } } } } void UTerrainZoneComponent::SpawnAll(const TInstanceMeshTypeMap& InstanceMeshMap) { for (const auto& Elem : InstanceMeshMap) { const TInstanceMeshArray& InstMeshTransArray = Elem.Value; SpawnInstancedMesh(InstMeshTransArray.MeshType, InstMeshTransArray); } } void UTerrainZoneComponent::SpawnInstancedMesh(const FTerrainInstancedMeshType& MeshType, const TInstanceMeshArray& InstMeshTransArray) { const std::lock_guard<std::mutex> lock(InstancedMeshMutex); UTerrainFoliageMesh* InstancedStaticMeshComponent = nullptr; uint64 MeshCode = MeshType.GetMeshTypeCode(); if (InstancedMeshMap.Contains(MeshCode)) { InstancedStaticMeshComponent = InstancedMeshMap[MeshCode]; } if (InstancedStaticMeshComponent == nullptr) { //UE_LOG(LogSandboxTerrain, Log, TEXT("SpawnInstancedMesh -> %d %d"), MeshType.MeshVariantId, MeshType.MeshTypeId); FString InstancedStaticMeshCompName = FString::Printf(TEXT("InstancedStaticMesh - [%d, %d]-> [%.0f, %.0f, %.0f]"), MeshType.MeshTypeId, MeshType.MeshVariantId, GetComponentLocation().X, GetComponentLocation().Y, GetComponentLocation().Z); InstancedStaticMeshComponent = NewObject<UTerrainFoliageMesh>(this, FName(*InstancedStaticMeshCompName)); InstancedStaticMeshComponent->RegisterComponent(); InstancedStaticMeshComponent->AttachToComponent(this, FAttachmentTransformRules::KeepRelativeTransform, NAME_None); InstancedStaticMeshComponent->SetStaticMesh(MeshType.Mesh); InstancedStaticMeshComponent->SetCullDistances(MeshType.StartCullDistance, MeshType.EndCullDistance); InstancedStaticMeshComponent->SetMobility(EComponentMobility::Static); InstancedStaticMeshComponent->SetSimulatePhysics(false); auto FoliageType = GetTerrainController()->FoliageMap[MeshType.MeshTypeId]; if (FoliageType.Type == ESandboxFoliageType::Tree) { InstancedStaticMeshComponent->SetCollisionEnabled(ECollisionEnabled::QueryAndPhysics); } else { InstancedStaticMeshComponent->SetCollisionEnabled(ECollisionEnabled::QueryOnly); InstancedStaticMeshComponent->SetCollisionProfileName(TEXT("OverlapAll")); } InstancedStaticMeshComponent->MeshTypeId = MeshType.MeshTypeId; InstancedStaticMeshComponent->MeshVariantId = MeshType.MeshVariantId; InstancedMeshMap.Add(MeshCode, InstancedStaticMeshComponent); } InstancedStaticMeshComponent->AddInstances(InstMeshTransArray.TransformArray, false); } void UTerrainZoneComponent::SetNeedSave() { bIsObjectsNeedSave = true; } bool UTerrainZoneComponent::IsNeedSave() { return bIsObjectsNeedSave; } TTerrainLodMask UTerrainZoneComponent::GetTerrainLodMask() { return CurrentTerrainLodMask; } ASandboxTerrainController* UTerrainZoneComponent::GetTerrainController() { return (ASandboxTerrainController*)GetAttachmentRootActor(); };
35.735915
241
0.750025
[ "mesh", "vector", "transform" ]
32ba0cc85968daf846e9bca8cfa7507772c25ef7
2,185
cpp
C++
codenation-contest/R-3-TinTin-CapTechHiring.cpp
sounishnath003/practice-180D-strategy
2778c861407a2be04168d5dfa6135a4b624029fc
[ "Apache-2.0" ]
null
null
null
codenation-contest/R-3-TinTin-CapTechHiring.cpp
sounishnath003/practice-180D-strategy
2778c861407a2be04168d5dfa6135a4b624029fc
[ "Apache-2.0" ]
null
null
null
codenation-contest/R-3-TinTin-CapTechHiring.cpp
sounishnath003/practice-180D-strategy
2778c861407a2be04168d5dfa6135a4b624029fc
[ "Apache-2.0" ]
1
2020-10-07T15:02:09.000Z
2020-10-07T15:02:09.000Z
#include <bits/stdc++.h> #pragma GCC optimize("Ofast") #pragma GCC target("avx,avx2,fma") using namespace std ; #define sim template < class c #define ris return * this #define dor > debug & operator << #define eni(x) sim > typename enable_if<sizeof dud<c>(0) x 1, debug&>::type operator<<(c i) { template < class c > struct rge { c b, e; }; template < class c > rge<c> range(c i, c j) { return rge<c>{i, j}; } template < class c > auto dud(c* x) -> decltype(cerr << *x, 0); template < class c > char dud(...); struct debug { ~debug() { cerr << endl; } template < class c > typename \ enable_if<sizeof dud<c>(0) != 1, debug&>::type operator<<(c i) { cerr << boolalpha << i; return * this; } template < class c > typename \ enable_if<sizeof dud<c>(0) == 1, debug&>::type operator<<(c i) {return * this << range(begin(i), end(i)); } template < class c, class b > debug & operator << (pair < b, c > d) { return * this << "(" << d.first << ", " << d.second << ")";} template < class c > debug & operator <<(rge<c> d) { *this << "["; for (auto it = d.b; it != d.e; ++it) *this << ", " + 2 * (it == d.b) << *it; return * this << "]";} }; #define imie(...) " [" << #__VA_ARGS__ ": " << (__VA_ARGS__) << "] " typedef long long ll; #define fo(i, k, n) for(int i = k; i < n; i++) const int inf = 0x3f3f3f3f; using longint = long long int; void solve() { int v,m,x; cin >> v >> m >> x; auto go = [&](int n, int k) -> int { vector<vector<int> > dp(n+1,vector<int>(k+1)); fo(i,0,n+1) { fo(j,0,min(i,k)+1) { dp[i][j] = (j==0 or j==i) ? 1 : dp[i-1][j-1] + dp[i-1][j]; } } return dp[n][k] ; }; vector<int> fibbs(x+2,1); adjacent_difference(fibbs.begin(), prev(fibbs.end()), next(fibbs.begin()), plus<int>{} ); fibbs.erase(fibbs.begin()), fibbs.erase(fibbs.begin()); vector<int> choices ; for(int i = m-1; i < x; i++) { choices.push_back(go(fibbs[i], v)); } int answer = accumulate(choices.begin(), choices.end(),0); debug () << imie (answer); } int main() { srand(time(NULL)) ; ios::sync_with_stdio(0), cin.tie(0), cout.tie(0); solve(); }
35.819672
167
0.540961
[ "vector" ]
32bcf3df50e00bc934d66e48c10b3430a8501ded
341,672
cpp
C++
src/main_9400.cpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
src/main_9400.cpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
src/main_9400.cpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
// Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes // Including type: UnityEngine.DrivenTransformProperties #include "UnityEngine/DrivenTransformProperties.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated static field getter // Get static field: static public UnityEngine.DrivenTransformProperties None UnityEngine::DrivenTransformProperties UnityEngine::DrivenTransformProperties::_get_None() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::DrivenTransformProperties::_get_None"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<UnityEngine::DrivenTransformProperties>("UnityEngine", "DrivenTransformProperties", "None")); } // Autogenerated static field setter // Set static field: static public UnityEngine.DrivenTransformProperties None void UnityEngine::DrivenTransformProperties::_set_None(UnityEngine::DrivenTransformProperties value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::DrivenTransformProperties::_set_None"); THROW_UNLESS(il2cpp_utils::SetFieldValue("UnityEngine", "DrivenTransformProperties", "None", value)); } // Autogenerated static field getter // Get static field: static public UnityEngine.DrivenTransformProperties All UnityEngine::DrivenTransformProperties UnityEngine::DrivenTransformProperties::_get_All() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::DrivenTransformProperties::_get_All"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<UnityEngine::DrivenTransformProperties>("UnityEngine", "DrivenTransformProperties", "All")); } // Autogenerated static field setter // Set static field: static public UnityEngine.DrivenTransformProperties All void UnityEngine::DrivenTransformProperties::_set_All(UnityEngine::DrivenTransformProperties value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::DrivenTransformProperties::_set_All"); THROW_UNLESS(il2cpp_utils::SetFieldValue("UnityEngine", "DrivenTransformProperties", "All", value)); } // Autogenerated static field getter // Get static field: static public UnityEngine.DrivenTransformProperties AnchoredPositionX UnityEngine::DrivenTransformProperties UnityEngine::DrivenTransformProperties::_get_AnchoredPositionX() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::DrivenTransformProperties::_get_AnchoredPositionX"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<UnityEngine::DrivenTransformProperties>("UnityEngine", "DrivenTransformProperties", "AnchoredPositionX")); } // Autogenerated static field setter // Set static field: static public UnityEngine.DrivenTransformProperties AnchoredPositionX void UnityEngine::DrivenTransformProperties::_set_AnchoredPositionX(UnityEngine::DrivenTransformProperties value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::DrivenTransformProperties::_set_AnchoredPositionX"); THROW_UNLESS(il2cpp_utils::SetFieldValue("UnityEngine", "DrivenTransformProperties", "AnchoredPositionX", value)); } // Autogenerated static field getter // Get static field: static public UnityEngine.DrivenTransformProperties AnchoredPositionY UnityEngine::DrivenTransformProperties UnityEngine::DrivenTransformProperties::_get_AnchoredPositionY() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::DrivenTransformProperties::_get_AnchoredPositionY"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<UnityEngine::DrivenTransformProperties>("UnityEngine", "DrivenTransformProperties", "AnchoredPositionY")); } // Autogenerated static field setter // Set static field: static public UnityEngine.DrivenTransformProperties AnchoredPositionY void UnityEngine::DrivenTransformProperties::_set_AnchoredPositionY(UnityEngine::DrivenTransformProperties value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::DrivenTransformProperties::_set_AnchoredPositionY"); THROW_UNLESS(il2cpp_utils::SetFieldValue("UnityEngine", "DrivenTransformProperties", "AnchoredPositionY", value)); } // Autogenerated static field getter // Get static field: static public UnityEngine.DrivenTransformProperties AnchoredPositionZ UnityEngine::DrivenTransformProperties UnityEngine::DrivenTransformProperties::_get_AnchoredPositionZ() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::DrivenTransformProperties::_get_AnchoredPositionZ"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<UnityEngine::DrivenTransformProperties>("UnityEngine", "DrivenTransformProperties", "AnchoredPositionZ")); } // Autogenerated static field setter // Set static field: static public UnityEngine.DrivenTransformProperties AnchoredPositionZ void UnityEngine::DrivenTransformProperties::_set_AnchoredPositionZ(UnityEngine::DrivenTransformProperties value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::DrivenTransformProperties::_set_AnchoredPositionZ"); THROW_UNLESS(il2cpp_utils::SetFieldValue("UnityEngine", "DrivenTransformProperties", "AnchoredPositionZ", value)); } // Autogenerated static field getter // Get static field: static public UnityEngine.DrivenTransformProperties Rotation UnityEngine::DrivenTransformProperties UnityEngine::DrivenTransformProperties::_get_Rotation() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::DrivenTransformProperties::_get_Rotation"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<UnityEngine::DrivenTransformProperties>("UnityEngine", "DrivenTransformProperties", "Rotation")); } // Autogenerated static field setter // Set static field: static public UnityEngine.DrivenTransformProperties Rotation void UnityEngine::DrivenTransformProperties::_set_Rotation(UnityEngine::DrivenTransformProperties value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::DrivenTransformProperties::_set_Rotation"); THROW_UNLESS(il2cpp_utils::SetFieldValue("UnityEngine", "DrivenTransformProperties", "Rotation", value)); } // Autogenerated static field getter // Get static field: static public UnityEngine.DrivenTransformProperties ScaleX UnityEngine::DrivenTransformProperties UnityEngine::DrivenTransformProperties::_get_ScaleX() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::DrivenTransformProperties::_get_ScaleX"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<UnityEngine::DrivenTransformProperties>("UnityEngine", "DrivenTransformProperties", "ScaleX")); } // Autogenerated static field setter // Set static field: static public UnityEngine.DrivenTransformProperties ScaleX void UnityEngine::DrivenTransformProperties::_set_ScaleX(UnityEngine::DrivenTransformProperties value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::DrivenTransformProperties::_set_ScaleX"); THROW_UNLESS(il2cpp_utils::SetFieldValue("UnityEngine", "DrivenTransformProperties", "ScaleX", value)); } // Autogenerated static field getter // Get static field: static public UnityEngine.DrivenTransformProperties ScaleY UnityEngine::DrivenTransformProperties UnityEngine::DrivenTransformProperties::_get_ScaleY() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::DrivenTransformProperties::_get_ScaleY"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<UnityEngine::DrivenTransformProperties>("UnityEngine", "DrivenTransformProperties", "ScaleY")); } // Autogenerated static field setter // Set static field: static public UnityEngine.DrivenTransformProperties ScaleY void UnityEngine::DrivenTransformProperties::_set_ScaleY(UnityEngine::DrivenTransformProperties value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::DrivenTransformProperties::_set_ScaleY"); THROW_UNLESS(il2cpp_utils::SetFieldValue("UnityEngine", "DrivenTransformProperties", "ScaleY", value)); } // Autogenerated static field getter // Get static field: static public UnityEngine.DrivenTransformProperties ScaleZ UnityEngine::DrivenTransformProperties UnityEngine::DrivenTransformProperties::_get_ScaleZ() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::DrivenTransformProperties::_get_ScaleZ"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<UnityEngine::DrivenTransformProperties>("UnityEngine", "DrivenTransformProperties", "ScaleZ")); } // Autogenerated static field setter // Set static field: static public UnityEngine.DrivenTransformProperties ScaleZ void UnityEngine::DrivenTransformProperties::_set_ScaleZ(UnityEngine::DrivenTransformProperties value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::DrivenTransformProperties::_set_ScaleZ"); THROW_UNLESS(il2cpp_utils::SetFieldValue("UnityEngine", "DrivenTransformProperties", "ScaleZ", value)); } // Autogenerated static field getter // Get static field: static public UnityEngine.DrivenTransformProperties AnchorMinX UnityEngine::DrivenTransformProperties UnityEngine::DrivenTransformProperties::_get_AnchorMinX() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::DrivenTransformProperties::_get_AnchorMinX"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<UnityEngine::DrivenTransformProperties>("UnityEngine", "DrivenTransformProperties", "AnchorMinX")); } // Autogenerated static field setter // Set static field: static public UnityEngine.DrivenTransformProperties AnchorMinX void UnityEngine::DrivenTransformProperties::_set_AnchorMinX(UnityEngine::DrivenTransformProperties value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::DrivenTransformProperties::_set_AnchorMinX"); THROW_UNLESS(il2cpp_utils::SetFieldValue("UnityEngine", "DrivenTransformProperties", "AnchorMinX", value)); } // Autogenerated static field getter // Get static field: static public UnityEngine.DrivenTransformProperties AnchorMinY UnityEngine::DrivenTransformProperties UnityEngine::DrivenTransformProperties::_get_AnchorMinY() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::DrivenTransformProperties::_get_AnchorMinY"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<UnityEngine::DrivenTransformProperties>("UnityEngine", "DrivenTransformProperties", "AnchorMinY")); } // Autogenerated static field setter // Set static field: static public UnityEngine.DrivenTransformProperties AnchorMinY void UnityEngine::DrivenTransformProperties::_set_AnchorMinY(UnityEngine::DrivenTransformProperties value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::DrivenTransformProperties::_set_AnchorMinY"); THROW_UNLESS(il2cpp_utils::SetFieldValue("UnityEngine", "DrivenTransformProperties", "AnchorMinY", value)); } // Autogenerated static field getter // Get static field: static public UnityEngine.DrivenTransformProperties AnchorMaxX UnityEngine::DrivenTransformProperties UnityEngine::DrivenTransformProperties::_get_AnchorMaxX() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::DrivenTransformProperties::_get_AnchorMaxX"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<UnityEngine::DrivenTransformProperties>("UnityEngine", "DrivenTransformProperties", "AnchorMaxX")); } // Autogenerated static field setter // Set static field: static public UnityEngine.DrivenTransformProperties AnchorMaxX void UnityEngine::DrivenTransformProperties::_set_AnchorMaxX(UnityEngine::DrivenTransformProperties value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::DrivenTransformProperties::_set_AnchorMaxX"); THROW_UNLESS(il2cpp_utils::SetFieldValue("UnityEngine", "DrivenTransformProperties", "AnchorMaxX", value)); } // Autogenerated static field getter // Get static field: static public UnityEngine.DrivenTransformProperties AnchorMaxY UnityEngine::DrivenTransformProperties UnityEngine::DrivenTransformProperties::_get_AnchorMaxY() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::DrivenTransformProperties::_get_AnchorMaxY"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<UnityEngine::DrivenTransformProperties>("UnityEngine", "DrivenTransformProperties", "AnchorMaxY")); } // Autogenerated static field setter // Set static field: static public UnityEngine.DrivenTransformProperties AnchorMaxY void UnityEngine::DrivenTransformProperties::_set_AnchorMaxY(UnityEngine::DrivenTransformProperties value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::DrivenTransformProperties::_set_AnchorMaxY"); THROW_UNLESS(il2cpp_utils::SetFieldValue("UnityEngine", "DrivenTransformProperties", "AnchorMaxY", value)); } // Autogenerated static field getter // Get static field: static public UnityEngine.DrivenTransformProperties SizeDeltaX UnityEngine::DrivenTransformProperties UnityEngine::DrivenTransformProperties::_get_SizeDeltaX() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::DrivenTransformProperties::_get_SizeDeltaX"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<UnityEngine::DrivenTransformProperties>("UnityEngine", "DrivenTransformProperties", "SizeDeltaX")); } // Autogenerated static field setter // Set static field: static public UnityEngine.DrivenTransformProperties SizeDeltaX void UnityEngine::DrivenTransformProperties::_set_SizeDeltaX(UnityEngine::DrivenTransformProperties value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::DrivenTransformProperties::_set_SizeDeltaX"); THROW_UNLESS(il2cpp_utils::SetFieldValue("UnityEngine", "DrivenTransformProperties", "SizeDeltaX", value)); } // Autogenerated static field getter // Get static field: static public UnityEngine.DrivenTransformProperties SizeDeltaY UnityEngine::DrivenTransformProperties UnityEngine::DrivenTransformProperties::_get_SizeDeltaY() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::DrivenTransformProperties::_get_SizeDeltaY"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<UnityEngine::DrivenTransformProperties>("UnityEngine", "DrivenTransformProperties", "SizeDeltaY")); } // Autogenerated static field setter // Set static field: static public UnityEngine.DrivenTransformProperties SizeDeltaY void UnityEngine::DrivenTransformProperties::_set_SizeDeltaY(UnityEngine::DrivenTransformProperties value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::DrivenTransformProperties::_set_SizeDeltaY"); THROW_UNLESS(il2cpp_utils::SetFieldValue("UnityEngine", "DrivenTransformProperties", "SizeDeltaY", value)); } // Autogenerated static field getter // Get static field: static public UnityEngine.DrivenTransformProperties PivotX UnityEngine::DrivenTransformProperties UnityEngine::DrivenTransformProperties::_get_PivotX() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::DrivenTransformProperties::_get_PivotX"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<UnityEngine::DrivenTransformProperties>("UnityEngine", "DrivenTransformProperties", "PivotX")); } // Autogenerated static field setter // Set static field: static public UnityEngine.DrivenTransformProperties PivotX void UnityEngine::DrivenTransformProperties::_set_PivotX(UnityEngine::DrivenTransformProperties value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::DrivenTransformProperties::_set_PivotX"); THROW_UNLESS(il2cpp_utils::SetFieldValue("UnityEngine", "DrivenTransformProperties", "PivotX", value)); } // Autogenerated static field getter // Get static field: static public UnityEngine.DrivenTransformProperties PivotY UnityEngine::DrivenTransformProperties UnityEngine::DrivenTransformProperties::_get_PivotY() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::DrivenTransformProperties::_get_PivotY"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<UnityEngine::DrivenTransformProperties>("UnityEngine", "DrivenTransformProperties", "PivotY")); } // Autogenerated static field setter // Set static field: static public UnityEngine.DrivenTransformProperties PivotY void UnityEngine::DrivenTransformProperties::_set_PivotY(UnityEngine::DrivenTransformProperties value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::DrivenTransformProperties::_set_PivotY"); THROW_UNLESS(il2cpp_utils::SetFieldValue("UnityEngine", "DrivenTransformProperties", "PivotY", value)); } // Autogenerated static field getter // Get static field: static public UnityEngine.DrivenTransformProperties AnchoredPosition UnityEngine::DrivenTransformProperties UnityEngine::DrivenTransformProperties::_get_AnchoredPosition() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::DrivenTransformProperties::_get_AnchoredPosition"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<UnityEngine::DrivenTransformProperties>("UnityEngine", "DrivenTransformProperties", "AnchoredPosition")); } // Autogenerated static field setter // Set static field: static public UnityEngine.DrivenTransformProperties AnchoredPosition void UnityEngine::DrivenTransformProperties::_set_AnchoredPosition(UnityEngine::DrivenTransformProperties value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::DrivenTransformProperties::_set_AnchoredPosition"); THROW_UNLESS(il2cpp_utils::SetFieldValue("UnityEngine", "DrivenTransformProperties", "AnchoredPosition", value)); } // Autogenerated static field getter // Get static field: static public UnityEngine.DrivenTransformProperties AnchoredPosition3D UnityEngine::DrivenTransformProperties UnityEngine::DrivenTransformProperties::_get_AnchoredPosition3D() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::DrivenTransformProperties::_get_AnchoredPosition3D"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<UnityEngine::DrivenTransformProperties>("UnityEngine", "DrivenTransformProperties", "AnchoredPosition3D")); } // Autogenerated static field setter // Set static field: static public UnityEngine.DrivenTransformProperties AnchoredPosition3D void UnityEngine::DrivenTransformProperties::_set_AnchoredPosition3D(UnityEngine::DrivenTransformProperties value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::DrivenTransformProperties::_set_AnchoredPosition3D"); THROW_UNLESS(il2cpp_utils::SetFieldValue("UnityEngine", "DrivenTransformProperties", "AnchoredPosition3D", value)); } // Autogenerated static field getter // Get static field: static public UnityEngine.DrivenTransformProperties Scale UnityEngine::DrivenTransformProperties UnityEngine::DrivenTransformProperties::_get_Scale() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::DrivenTransformProperties::_get_Scale"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<UnityEngine::DrivenTransformProperties>("UnityEngine", "DrivenTransformProperties", "Scale")); } // Autogenerated static field setter // Set static field: static public UnityEngine.DrivenTransformProperties Scale void UnityEngine::DrivenTransformProperties::_set_Scale(UnityEngine::DrivenTransformProperties value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::DrivenTransformProperties::_set_Scale"); THROW_UNLESS(il2cpp_utils::SetFieldValue("UnityEngine", "DrivenTransformProperties", "Scale", value)); } // Autogenerated static field getter // Get static field: static public UnityEngine.DrivenTransformProperties AnchorMin UnityEngine::DrivenTransformProperties UnityEngine::DrivenTransformProperties::_get_AnchorMin() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::DrivenTransformProperties::_get_AnchorMin"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<UnityEngine::DrivenTransformProperties>("UnityEngine", "DrivenTransformProperties", "AnchorMin")); } // Autogenerated static field setter // Set static field: static public UnityEngine.DrivenTransformProperties AnchorMin void UnityEngine::DrivenTransformProperties::_set_AnchorMin(UnityEngine::DrivenTransformProperties value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::DrivenTransformProperties::_set_AnchorMin"); THROW_UNLESS(il2cpp_utils::SetFieldValue("UnityEngine", "DrivenTransformProperties", "AnchorMin", value)); } // Autogenerated static field getter // Get static field: static public UnityEngine.DrivenTransformProperties AnchorMax UnityEngine::DrivenTransformProperties UnityEngine::DrivenTransformProperties::_get_AnchorMax() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::DrivenTransformProperties::_get_AnchorMax"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<UnityEngine::DrivenTransformProperties>("UnityEngine", "DrivenTransformProperties", "AnchorMax")); } // Autogenerated static field setter // Set static field: static public UnityEngine.DrivenTransformProperties AnchorMax void UnityEngine::DrivenTransformProperties::_set_AnchorMax(UnityEngine::DrivenTransformProperties value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::DrivenTransformProperties::_set_AnchorMax"); THROW_UNLESS(il2cpp_utils::SetFieldValue("UnityEngine", "DrivenTransformProperties", "AnchorMax", value)); } // Autogenerated static field getter // Get static field: static public UnityEngine.DrivenTransformProperties Anchors UnityEngine::DrivenTransformProperties UnityEngine::DrivenTransformProperties::_get_Anchors() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::DrivenTransformProperties::_get_Anchors"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<UnityEngine::DrivenTransformProperties>("UnityEngine", "DrivenTransformProperties", "Anchors")); } // Autogenerated static field setter // Set static field: static public UnityEngine.DrivenTransformProperties Anchors void UnityEngine::DrivenTransformProperties::_set_Anchors(UnityEngine::DrivenTransformProperties value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::DrivenTransformProperties::_set_Anchors"); THROW_UNLESS(il2cpp_utils::SetFieldValue("UnityEngine", "DrivenTransformProperties", "Anchors", value)); } // Autogenerated static field getter // Get static field: static public UnityEngine.DrivenTransformProperties SizeDelta UnityEngine::DrivenTransformProperties UnityEngine::DrivenTransformProperties::_get_SizeDelta() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::DrivenTransformProperties::_get_SizeDelta"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<UnityEngine::DrivenTransformProperties>("UnityEngine", "DrivenTransformProperties", "SizeDelta")); } // Autogenerated static field setter // Set static field: static public UnityEngine.DrivenTransformProperties SizeDelta void UnityEngine::DrivenTransformProperties::_set_SizeDelta(UnityEngine::DrivenTransformProperties value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::DrivenTransformProperties::_set_SizeDelta"); THROW_UNLESS(il2cpp_utils::SetFieldValue("UnityEngine", "DrivenTransformProperties", "SizeDelta", value)); } // Autogenerated static field getter // Get static field: static public UnityEngine.DrivenTransformProperties Pivot UnityEngine::DrivenTransformProperties UnityEngine::DrivenTransformProperties::_get_Pivot() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::DrivenTransformProperties::_get_Pivot"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<UnityEngine::DrivenTransformProperties>("UnityEngine", "DrivenTransformProperties", "Pivot")); } // Autogenerated static field setter // Set static field: static public UnityEngine.DrivenTransformProperties Pivot void UnityEngine::DrivenTransformProperties::_set_Pivot(UnityEngine::DrivenTransformProperties value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::DrivenTransformProperties::_set_Pivot"); THROW_UNLESS(il2cpp_utils::SetFieldValue("UnityEngine", "DrivenTransformProperties", "Pivot", value)); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes // Including type: UnityEngine.DrivenRectTransformTracker #include "UnityEngine/DrivenRectTransformTracker.hpp" // Including type: UnityEngine.Object #include "UnityEngine/Object.hpp" // Including type: UnityEngine.RectTransform #include "UnityEngine/RectTransform.hpp" // Including type: UnityEngine.DrivenTransformProperties #include "UnityEngine/DrivenTransformProperties.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated method: UnityEngine.DrivenRectTransformTracker.Add void UnityEngine::DrivenRectTransformTracker::Add(UnityEngine::Object* driver, UnityEngine::RectTransform* rectTransform, UnityEngine::DrivenTransformProperties drivenProperties) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::DrivenRectTransformTracker::Add"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(*this, "Add", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(driver), ::il2cpp_utils::ExtractType(rectTransform), ::il2cpp_utils::ExtractType(drivenProperties)}))); ::il2cpp_utils::RunMethodThrow<void, false>(*this, ___internal__method, driver, rectTransform, drivenProperties); } // Autogenerated method: UnityEngine.DrivenRectTransformTracker.Clear void UnityEngine::DrivenRectTransformTracker::Clear() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::DrivenRectTransformTracker::Clear"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(*this, "Clear", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); ::il2cpp_utils::RunMethodThrow<void, false>(*this, ___internal__method); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: UnityEngine.RectTransform #include "UnityEngine/RectTransform.hpp" // Including type: UnityEngine.RectTransform/Axis #include "UnityEngine/RectTransform_Axis.hpp" // Including type: UnityEngine.RectTransform/ReapplyDrivenProperties #include "UnityEngine/RectTransform_ReapplyDrivenProperties.hpp" // Including type: UnityEngine.Rect #include "UnityEngine/Rect.hpp" // Including type: UnityEngine.Vector2 #include "UnityEngine/Vector2.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // [DebuggerBrowsableAttribute] Offset: 0xD93D10 // [CompilerGeneratedAttribute] Offset: 0xD93D10 // Autogenerated static field getter // Get static field: static private UnityEngine.RectTransform/ReapplyDrivenProperties reapplyDrivenProperties UnityEngine::RectTransform::ReapplyDrivenProperties* UnityEngine::RectTransform::_get_reapplyDrivenProperties() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::RectTransform::_get_reapplyDrivenProperties"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<UnityEngine::RectTransform::ReapplyDrivenProperties*>("UnityEngine", "RectTransform", "reapplyDrivenProperties")); } // Autogenerated static field setter // Set static field: static private UnityEngine.RectTransform/ReapplyDrivenProperties reapplyDrivenProperties void UnityEngine::RectTransform::_set_reapplyDrivenProperties(UnityEngine::RectTransform::ReapplyDrivenProperties* value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::RectTransform::_set_reapplyDrivenProperties"); THROW_UNLESS(il2cpp_utils::SetFieldValue("UnityEngine", "RectTransform", "reapplyDrivenProperties", value)); } // Autogenerated method: UnityEngine.RectTransform.add_reapplyDrivenProperties void UnityEngine::RectTransform::add_reapplyDrivenProperties(UnityEngine::RectTransform::ReapplyDrivenProperties* value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::RectTransform::add_reapplyDrivenProperties"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine", "RectTransform", "add_reapplyDrivenProperties", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)}))); ::il2cpp_utils::RunMethodThrow<void, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, value); } // Autogenerated method: UnityEngine.RectTransform.remove_reapplyDrivenProperties void UnityEngine::RectTransform::remove_reapplyDrivenProperties(UnityEngine::RectTransform::ReapplyDrivenProperties* value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::RectTransform::remove_reapplyDrivenProperties"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine", "RectTransform", "remove_reapplyDrivenProperties", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)}))); ::il2cpp_utils::RunMethodThrow<void, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, value); } // Autogenerated method: UnityEngine.RectTransform.get_rect UnityEngine::Rect UnityEngine::RectTransform::get_rect() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::RectTransform::get_rect"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_rect", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Rect, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.RectTransform.get_anchorMin UnityEngine::Vector2 UnityEngine::RectTransform::get_anchorMin() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::RectTransform::get_anchorMin"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_anchorMin", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Vector2, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.RectTransform.set_anchorMin void UnityEngine::RectTransform::set_anchorMin(UnityEngine::Vector2 value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::RectTransform::set_anchorMin"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "set_anchorMin", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, value); } // Autogenerated method: UnityEngine.RectTransform.get_anchorMax UnityEngine::Vector2 UnityEngine::RectTransform::get_anchorMax() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::RectTransform::get_anchorMax"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_anchorMax", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Vector2, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.RectTransform.set_anchorMax void UnityEngine::RectTransform::set_anchorMax(UnityEngine::Vector2 value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::RectTransform::set_anchorMax"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "set_anchorMax", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, value); } // Autogenerated method: UnityEngine.RectTransform.get_anchoredPosition UnityEngine::Vector2 UnityEngine::RectTransform::get_anchoredPosition() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::RectTransform::get_anchoredPosition"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_anchoredPosition", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Vector2, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.RectTransform.set_anchoredPosition void UnityEngine::RectTransform::set_anchoredPosition(UnityEngine::Vector2 value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::RectTransform::set_anchoredPosition"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "set_anchoredPosition", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, value); } // Autogenerated method: UnityEngine.RectTransform.get_sizeDelta UnityEngine::Vector2 UnityEngine::RectTransform::get_sizeDelta() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::RectTransform::get_sizeDelta"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_sizeDelta", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Vector2, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.RectTransform.set_sizeDelta void UnityEngine::RectTransform::set_sizeDelta(UnityEngine::Vector2 value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::RectTransform::set_sizeDelta"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "set_sizeDelta", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, value); } // Autogenerated method: UnityEngine.RectTransform.get_pivot UnityEngine::Vector2 UnityEngine::RectTransform::get_pivot() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::RectTransform::get_pivot"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_pivot", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Vector2, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.RectTransform.set_pivot void UnityEngine::RectTransform::set_pivot(UnityEngine::Vector2 value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::RectTransform::set_pivot"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "set_pivot", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, value); } // Autogenerated method: UnityEngine.RectTransform.set_anchoredPosition3D void UnityEngine::RectTransform::set_anchoredPosition3D(UnityEngine::Vector3 value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::RectTransform::set_anchoredPosition3D"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "set_anchoredPosition3D", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, value); } // Autogenerated method: UnityEngine.RectTransform.set_offsetMin void UnityEngine::RectTransform::set_offsetMin(UnityEngine::Vector2 value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::RectTransform::set_offsetMin"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "set_offsetMin", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, value); } // Autogenerated method: UnityEngine.RectTransform.set_offsetMax void UnityEngine::RectTransform::set_offsetMax(UnityEngine::Vector2 value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::RectTransform::set_offsetMax"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "set_offsetMax", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, value); } // Autogenerated method: UnityEngine.RectTransform.GetLocalCorners void UnityEngine::RectTransform::GetLocalCorners(::Array<UnityEngine::Vector3>* fourCornersArray) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::RectTransform::GetLocalCorners"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "GetLocalCorners", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(fourCornersArray)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, fourCornersArray); } // Autogenerated method: UnityEngine.RectTransform.GetWorldCorners void UnityEngine::RectTransform::GetWorldCorners(::Array<UnityEngine::Vector3>* fourCornersArray) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::RectTransform::GetWorldCorners"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "GetWorldCorners", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(fourCornersArray)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, fourCornersArray); } // Autogenerated method: UnityEngine.RectTransform.SetSizeWithCurrentAnchors void UnityEngine::RectTransform::SetSizeWithCurrentAnchors(UnityEngine::RectTransform::Axis axis, float size) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::RectTransform::SetSizeWithCurrentAnchors"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "SetSizeWithCurrentAnchors", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(axis), ::il2cpp_utils::ExtractType(size)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, axis, size); } // Autogenerated method: UnityEngine.RectTransform.SendReapplyDrivenProperties void UnityEngine::RectTransform::SendReapplyDrivenProperties(UnityEngine::RectTransform* driven) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::RectTransform::SendReapplyDrivenProperties"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine", "RectTransform", "SendReapplyDrivenProperties", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(driven)}))); ::il2cpp_utils::RunMethodThrow<void, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, driven); } // Autogenerated method: UnityEngine.RectTransform.GetParentSize UnityEngine::Vector2 UnityEngine::RectTransform::GetParentSize() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::RectTransform::GetParentSize"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "GetParentSize", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Vector2, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.RectTransform.get_rect_Injected void UnityEngine::RectTransform::get_rect_Injected(UnityEngine::Rect& ret) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::RectTransform::get_rect_Injected"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_rect_Injected", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractIndependentType<UnityEngine::Rect&>()}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, ret); } // Autogenerated method: UnityEngine.RectTransform.get_anchorMin_Injected void UnityEngine::RectTransform::get_anchorMin_Injected(UnityEngine::Vector2& ret) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::RectTransform::get_anchorMin_Injected"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_anchorMin_Injected", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractIndependentType<UnityEngine::Vector2&>()}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, ret); } // Autogenerated method: UnityEngine.RectTransform.set_anchorMin_Injected void UnityEngine::RectTransform::set_anchorMin_Injected(UnityEngine::Vector2& value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::RectTransform::set_anchorMin_Injected"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "set_anchorMin_Injected", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, value); } // Autogenerated method: UnityEngine.RectTransform.get_anchorMax_Injected void UnityEngine::RectTransform::get_anchorMax_Injected(UnityEngine::Vector2& ret) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::RectTransform::get_anchorMax_Injected"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_anchorMax_Injected", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractIndependentType<UnityEngine::Vector2&>()}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, ret); } // Autogenerated method: UnityEngine.RectTransform.set_anchorMax_Injected void UnityEngine::RectTransform::set_anchorMax_Injected(UnityEngine::Vector2& value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::RectTransform::set_anchorMax_Injected"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "set_anchorMax_Injected", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, value); } // Autogenerated method: UnityEngine.RectTransform.get_anchoredPosition_Injected void UnityEngine::RectTransform::get_anchoredPosition_Injected(UnityEngine::Vector2& ret) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::RectTransform::get_anchoredPosition_Injected"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_anchoredPosition_Injected", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractIndependentType<UnityEngine::Vector2&>()}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, ret); } // Autogenerated method: UnityEngine.RectTransform.set_anchoredPosition_Injected void UnityEngine::RectTransform::set_anchoredPosition_Injected(UnityEngine::Vector2& value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::RectTransform::set_anchoredPosition_Injected"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "set_anchoredPosition_Injected", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, value); } // Autogenerated method: UnityEngine.RectTransform.get_sizeDelta_Injected void UnityEngine::RectTransform::get_sizeDelta_Injected(UnityEngine::Vector2& ret) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::RectTransform::get_sizeDelta_Injected"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_sizeDelta_Injected", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractIndependentType<UnityEngine::Vector2&>()}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, ret); } // Autogenerated method: UnityEngine.RectTransform.set_sizeDelta_Injected void UnityEngine::RectTransform::set_sizeDelta_Injected(UnityEngine::Vector2& value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::RectTransform::set_sizeDelta_Injected"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "set_sizeDelta_Injected", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, value); } // Autogenerated method: UnityEngine.RectTransform.get_pivot_Injected void UnityEngine::RectTransform::get_pivot_Injected(UnityEngine::Vector2& ret) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::RectTransform::get_pivot_Injected"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_pivot_Injected", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractIndependentType<UnityEngine::Vector2&>()}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, ret); } // Autogenerated method: UnityEngine.RectTransform.set_pivot_Injected void UnityEngine::RectTransform::set_pivot_Injected(UnityEngine::Vector2& value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::RectTransform::set_pivot_Injected"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "set_pivot_Injected", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, value); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes // Including type: UnityEngine.RectTransform/Axis #include "UnityEngine/RectTransform_Axis.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated static field getter // Get static field: static public UnityEngine.RectTransform/Axis Horizontal UnityEngine::RectTransform::Axis UnityEngine::RectTransform::Axis::_get_Horizontal() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::RectTransform::Axis::_get_Horizontal"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<UnityEngine::RectTransform::Axis>("UnityEngine", "RectTransform/Axis", "Horizontal")); } // Autogenerated static field setter // Set static field: static public UnityEngine.RectTransform/Axis Horizontal void UnityEngine::RectTransform::Axis::_set_Horizontal(UnityEngine::RectTransform::Axis value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::RectTransform::Axis::_set_Horizontal"); THROW_UNLESS(il2cpp_utils::SetFieldValue("UnityEngine", "RectTransform/Axis", "Horizontal", value)); } // Autogenerated static field getter // Get static field: static public UnityEngine.RectTransform/Axis Vertical UnityEngine::RectTransform::Axis UnityEngine::RectTransform::Axis::_get_Vertical() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::RectTransform::Axis::_get_Vertical"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<UnityEngine::RectTransform::Axis>("UnityEngine", "RectTransform/Axis", "Vertical")); } // Autogenerated static field setter // Set static field: static public UnityEngine.RectTransform/Axis Vertical void UnityEngine::RectTransform::Axis::_set_Vertical(UnityEngine::RectTransform::Axis value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::RectTransform::Axis::_set_Vertical"); THROW_UNLESS(il2cpp_utils::SetFieldValue("UnityEngine", "RectTransform/Axis", "Vertical", value)); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: UnityEngine.RectTransform/ReapplyDrivenProperties #include "UnityEngine/RectTransform_ReapplyDrivenProperties.hpp" // Including type: System.IAsyncResult #include "System/IAsyncResult.hpp" // Including type: System.AsyncCallback #include "System/AsyncCallback.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated method: UnityEngine.RectTransform/ReapplyDrivenProperties.Invoke void UnityEngine::RectTransform::ReapplyDrivenProperties::Invoke(UnityEngine::RectTransform* driven) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::RectTransform::ReapplyDrivenProperties::Invoke"); auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Invoke", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(driven)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, driven); } // Autogenerated method: UnityEngine.RectTransform/ReapplyDrivenProperties.BeginInvoke System::IAsyncResult* UnityEngine::RectTransform::ReapplyDrivenProperties::BeginInvoke(UnityEngine::RectTransform* driven, System::AsyncCallback* callback, ::Il2CppObject* object) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::RectTransform::ReapplyDrivenProperties::BeginInvoke"); auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "BeginInvoke", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(driven), ::il2cpp_utils::ExtractType(callback), ::il2cpp_utils::ExtractType(object)}))); return ::il2cpp_utils::RunMethodThrow<System::IAsyncResult*, false>(this, ___internal__method, driven, callback, object); } // Autogenerated method: UnityEngine.RectTransform/ReapplyDrivenProperties.EndInvoke void UnityEngine::RectTransform::ReapplyDrivenProperties::EndInvoke(System::IAsyncResult* result) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::RectTransform::ReapplyDrivenProperties::EndInvoke"); auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "EndInvoke", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(result)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, result); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes // Including type: UnityEngine.RotationOrder #include "UnityEngine/RotationOrder.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated static field getter // Get static field: static public UnityEngine.RotationOrder OrderXYZ UnityEngine::RotationOrder UnityEngine::RotationOrder::_get_OrderXYZ() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::RotationOrder::_get_OrderXYZ"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<UnityEngine::RotationOrder>("UnityEngine", "RotationOrder", "OrderXYZ")); } // Autogenerated static field setter // Set static field: static public UnityEngine.RotationOrder OrderXYZ void UnityEngine::RotationOrder::_set_OrderXYZ(UnityEngine::RotationOrder value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::RotationOrder::_set_OrderXYZ"); THROW_UNLESS(il2cpp_utils::SetFieldValue("UnityEngine", "RotationOrder", "OrderXYZ", value)); } // Autogenerated static field getter // Get static field: static public UnityEngine.RotationOrder OrderXZY UnityEngine::RotationOrder UnityEngine::RotationOrder::_get_OrderXZY() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::RotationOrder::_get_OrderXZY"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<UnityEngine::RotationOrder>("UnityEngine", "RotationOrder", "OrderXZY")); } // Autogenerated static field setter // Set static field: static public UnityEngine.RotationOrder OrderXZY void UnityEngine::RotationOrder::_set_OrderXZY(UnityEngine::RotationOrder value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::RotationOrder::_set_OrderXZY"); THROW_UNLESS(il2cpp_utils::SetFieldValue("UnityEngine", "RotationOrder", "OrderXZY", value)); } // Autogenerated static field getter // Get static field: static public UnityEngine.RotationOrder OrderYZX UnityEngine::RotationOrder UnityEngine::RotationOrder::_get_OrderYZX() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::RotationOrder::_get_OrderYZX"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<UnityEngine::RotationOrder>("UnityEngine", "RotationOrder", "OrderYZX")); } // Autogenerated static field setter // Set static field: static public UnityEngine.RotationOrder OrderYZX void UnityEngine::RotationOrder::_set_OrderYZX(UnityEngine::RotationOrder value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::RotationOrder::_set_OrderYZX"); THROW_UNLESS(il2cpp_utils::SetFieldValue("UnityEngine", "RotationOrder", "OrderYZX", value)); } // Autogenerated static field getter // Get static field: static public UnityEngine.RotationOrder OrderYXZ UnityEngine::RotationOrder UnityEngine::RotationOrder::_get_OrderYXZ() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::RotationOrder::_get_OrderYXZ"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<UnityEngine::RotationOrder>("UnityEngine", "RotationOrder", "OrderYXZ")); } // Autogenerated static field setter // Set static field: static public UnityEngine.RotationOrder OrderYXZ void UnityEngine::RotationOrder::_set_OrderYXZ(UnityEngine::RotationOrder value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::RotationOrder::_set_OrderYXZ"); THROW_UNLESS(il2cpp_utils::SetFieldValue("UnityEngine", "RotationOrder", "OrderYXZ", value)); } // Autogenerated static field getter // Get static field: static public UnityEngine.RotationOrder OrderZXY UnityEngine::RotationOrder UnityEngine::RotationOrder::_get_OrderZXY() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::RotationOrder::_get_OrderZXY"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<UnityEngine::RotationOrder>("UnityEngine", "RotationOrder", "OrderZXY")); } // Autogenerated static field setter // Set static field: static public UnityEngine.RotationOrder OrderZXY void UnityEngine::RotationOrder::_set_OrderZXY(UnityEngine::RotationOrder value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::RotationOrder::_set_OrderZXY"); THROW_UNLESS(il2cpp_utils::SetFieldValue("UnityEngine", "RotationOrder", "OrderZXY", value)); } // Autogenerated static field getter // Get static field: static public UnityEngine.RotationOrder OrderZYX UnityEngine::RotationOrder UnityEngine::RotationOrder::_get_OrderZYX() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::RotationOrder::_get_OrderZYX"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<UnityEngine::RotationOrder>("UnityEngine", "RotationOrder", "OrderZYX")); } // Autogenerated static field setter // Set static field: static public UnityEngine.RotationOrder OrderZYX void UnityEngine::RotationOrder::_set_OrderZYX(UnityEngine::RotationOrder value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::RotationOrder::_set_OrderZYX"); THROW_UNLESS(il2cpp_utils::SetFieldValue("UnityEngine", "RotationOrder", "OrderZYX", value)); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: UnityEngine.Transform #include "UnityEngine/Transform.hpp" // Including type: UnityEngine.Transform/Enumerator #include "UnityEngine/Transform_Enumerator.hpp" // Including type: UnityEngine.Vector3 #include "UnityEngine/Vector3.hpp" // Including type: UnityEngine.RotationOrder #include "UnityEngine/RotationOrder.hpp" // Including type: UnityEngine.Quaternion #include "UnityEngine/Quaternion.hpp" // Including type: UnityEngine.Matrix4x4 #include "UnityEngine/Matrix4x4.hpp" // Including type: UnityEngine.Space #include "UnityEngine/Space.hpp" // Including type: System.Collections.IEnumerator #include "System/Collections/IEnumerator.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated method: UnityEngine.Transform.get_position UnityEngine::Vector3 UnityEngine::Transform::get_position() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::get_position"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_position", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Vector3, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Transform.set_position void UnityEngine::Transform::set_position(UnityEngine::Vector3 value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::set_position"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "set_position", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, value); } // Autogenerated method: UnityEngine.Transform.get_localPosition UnityEngine::Vector3 UnityEngine::Transform::get_localPosition() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::get_localPosition"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_localPosition", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Vector3, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Transform.set_localPosition void UnityEngine::Transform::set_localPosition(UnityEngine::Vector3 value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::set_localPosition"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "set_localPosition", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, value); } // Autogenerated method: UnityEngine.Transform.GetLocalEulerAngles UnityEngine::Vector3 UnityEngine::Transform::GetLocalEulerAngles(UnityEngine::RotationOrder order) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::GetLocalEulerAngles"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "GetLocalEulerAngles", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(order)}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Vector3, false>(this, ___internal__method, order); } // Autogenerated method: UnityEngine.Transform.SetLocalEulerAngles void UnityEngine::Transform::SetLocalEulerAngles(UnityEngine::Vector3 euler, UnityEngine::RotationOrder order) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::SetLocalEulerAngles"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "SetLocalEulerAngles", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(euler), ::il2cpp_utils::ExtractType(order)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, euler, order); } // Autogenerated method: UnityEngine.Transform.SetLocalEulerHint void UnityEngine::Transform::SetLocalEulerHint(UnityEngine::Vector3 euler) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::SetLocalEulerHint"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "SetLocalEulerHint", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(euler)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, euler); } // Autogenerated method: UnityEngine.Transform.get_eulerAngles UnityEngine::Vector3 UnityEngine::Transform::get_eulerAngles() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::get_eulerAngles"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_eulerAngles", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Vector3, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Transform.set_eulerAngles void UnityEngine::Transform::set_eulerAngles(UnityEngine::Vector3 value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::set_eulerAngles"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "set_eulerAngles", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, value); } // Autogenerated method: UnityEngine.Transform.get_localEulerAngles UnityEngine::Vector3 UnityEngine::Transform::get_localEulerAngles() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::get_localEulerAngles"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_localEulerAngles", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Vector3, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Transform.set_localEulerAngles void UnityEngine::Transform::set_localEulerAngles(UnityEngine::Vector3 value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::set_localEulerAngles"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "set_localEulerAngles", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, value); } // Autogenerated method: UnityEngine.Transform.get_right UnityEngine::Vector3 UnityEngine::Transform::get_right() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::get_right"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_right", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Vector3, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Transform.set_right void UnityEngine::Transform::set_right(UnityEngine::Vector3 value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::set_right"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "set_right", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, value); } // Autogenerated method: UnityEngine.Transform.get_up UnityEngine::Vector3 UnityEngine::Transform::get_up() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::get_up"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_up", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Vector3, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Transform.set_up void UnityEngine::Transform::set_up(UnityEngine::Vector3 value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::set_up"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "set_up", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, value); } // Autogenerated method: UnityEngine.Transform.get_forward UnityEngine::Vector3 UnityEngine::Transform::get_forward() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::get_forward"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_forward", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Vector3, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Transform.set_forward void UnityEngine::Transform::set_forward(UnityEngine::Vector3 value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::set_forward"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "set_forward", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, value); } // Autogenerated method: UnityEngine.Transform.get_rotation UnityEngine::Quaternion UnityEngine::Transform::get_rotation() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::get_rotation"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_rotation", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Quaternion, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Transform.set_rotation void UnityEngine::Transform::set_rotation(UnityEngine::Quaternion value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::set_rotation"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "set_rotation", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, value); } // Autogenerated method: UnityEngine.Transform.get_localRotation UnityEngine::Quaternion UnityEngine::Transform::get_localRotation() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::get_localRotation"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_localRotation", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Quaternion, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Transform.set_localRotation void UnityEngine::Transform::set_localRotation(UnityEngine::Quaternion value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::set_localRotation"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "set_localRotation", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, value); } // Autogenerated method: UnityEngine.Transform.get_rotationOrder UnityEngine::RotationOrder UnityEngine::Transform::get_rotationOrder() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::get_rotationOrder"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_rotationOrder", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::RotationOrder, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Transform.set_rotationOrder void UnityEngine::Transform::set_rotationOrder(UnityEngine::RotationOrder value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::set_rotationOrder"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "set_rotationOrder", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, value); } // Autogenerated method: UnityEngine.Transform.GetRotationOrderInternal int UnityEngine::Transform::GetRotationOrderInternal() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::GetRotationOrderInternal"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "GetRotationOrderInternal", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<int, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Transform.SetRotationOrderInternal void UnityEngine::Transform::SetRotationOrderInternal(UnityEngine::RotationOrder rotationOrder) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::SetRotationOrderInternal"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "SetRotationOrderInternal", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(rotationOrder)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, rotationOrder); } // Autogenerated method: UnityEngine.Transform.get_localScale UnityEngine::Vector3 UnityEngine::Transform::get_localScale() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::get_localScale"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_localScale", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Vector3, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Transform.set_localScale void UnityEngine::Transform::set_localScale(UnityEngine::Vector3 value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::set_localScale"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "set_localScale", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, value); } // Autogenerated method: UnityEngine.Transform.get_parent UnityEngine::Transform* UnityEngine::Transform::get_parent() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::get_parent"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_parent", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Transform*, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Transform.set_parent void UnityEngine::Transform::set_parent(UnityEngine::Transform* value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::set_parent"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "set_parent", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, value); } // Autogenerated method: UnityEngine.Transform.get_parentInternal UnityEngine::Transform* UnityEngine::Transform::get_parentInternal() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::get_parentInternal"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_parentInternal", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Transform*, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Transform.set_parentInternal void UnityEngine::Transform::set_parentInternal(UnityEngine::Transform* value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::set_parentInternal"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "set_parentInternal", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, value); } // Autogenerated method: UnityEngine.Transform.GetParent UnityEngine::Transform* UnityEngine::Transform::GetParent() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::GetParent"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "GetParent", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Transform*, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Transform.SetParent void UnityEngine::Transform::SetParent(UnityEngine::Transform* p) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::SetParent"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "SetParent", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(p)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, p); } // Autogenerated method: UnityEngine.Transform.SetParent void UnityEngine::Transform::SetParent(UnityEngine::Transform* parent, bool worldPositionStays) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::SetParent"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "SetParent", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(parent), ::il2cpp_utils::ExtractType(worldPositionStays)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, parent, worldPositionStays); } // Autogenerated method: UnityEngine.Transform.get_worldToLocalMatrix UnityEngine::Matrix4x4 UnityEngine::Transform::get_worldToLocalMatrix() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::get_worldToLocalMatrix"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_worldToLocalMatrix", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Matrix4x4, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Transform.get_localToWorldMatrix UnityEngine::Matrix4x4 UnityEngine::Transform::get_localToWorldMatrix() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::get_localToWorldMatrix"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_localToWorldMatrix", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Matrix4x4, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Transform.SetPositionAndRotation void UnityEngine::Transform::SetPositionAndRotation(UnityEngine::Vector3 position, UnityEngine::Quaternion rotation) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::SetPositionAndRotation"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "SetPositionAndRotation", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(position), ::il2cpp_utils::ExtractType(rotation)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, position, rotation); } // Autogenerated method: UnityEngine.Transform.Translate void UnityEngine::Transform::Translate(UnityEngine::Vector3 translation, UnityEngine::Space relativeTo) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::Translate"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Translate", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(translation), ::il2cpp_utils::ExtractType(relativeTo)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, translation, relativeTo); } // Autogenerated method: UnityEngine.Transform.Translate void UnityEngine::Transform::Translate(UnityEngine::Vector3 translation) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::Translate"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Translate", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(translation)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, translation); } // Autogenerated method: UnityEngine.Transform.Translate void UnityEngine::Transform::Translate(float x, float y, float z, UnityEngine::Space relativeTo) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::Translate"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Translate", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(x), ::il2cpp_utils::ExtractType(y), ::il2cpp_utils::ExtractType(z), ::il2cpp_utils::ExtractType(relativeTo)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, x, y, z, relativeTo); } // Autogenerated method: UnityEngine.Transform.Translate void UnityEngine::Transform::Translate(float x, float y, float z) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::Translate"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Translate", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(x), ::il2cpp_utils::ExtractType(y), ::il2cpp_utils::ExtractType(z)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, x, y, z); } // Autogenerated method: UnityEngine.Transform.Translate void UnityEngine::Transform::Translate(UnityEngine::Vector3 translation, UnityEngine::Transform* relativeTo) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::Translate"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Translate", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(translation), ::il2cpp_utils::ExtractType(relativeTo)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, translation, relativeTo); } // Autogenerated method: UnityEngine.Transform.Translate void UnityEngine::Transform::Translate(float x, float y, float z, UnityEngine::Transform* relativeTo) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::Translate"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Translate", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(x), ::il2cpp_utils::ExtractType(y), ::il2cpp_utils::ExtractType(z), ::il2cpp_utils::ExtractType(relativeTo)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, x, y, z, relativeTo); } // Autogenerated method: UnityEngine.Transform.Rotate void UnityEngine::Transform::Rotate(UnityEngine::Vector3 eulers, UnityEngine::Space relativeTo) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::Rotate"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Rotate", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(eulers), ::il2cpp_utils::ExtractType(relativeTo)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, eulers, relativeTo); } // Autogenerated method: UnityEngine.Transform.Rotate void UnityEngine::Transform::Rotate(UnityEngine::Vector3 eulers) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::Rotate"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Rotate", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(eulers)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, eulers); } // Autogenerated method: UnityEngine.Transform.Rotate void UnityEngine::Transform::Rotate(float xAngle, float yAngle, float zAngle, UnityEngine::Space relativeTo) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::Rotate"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Rotate", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(xAngle), ::il2cpp_utils::ExtractType(yAngle), ::il2cpp_utils::ExtractType(zAngle), ::il2cpp_utils::ExtractType(relativeTo)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, xAngle, yAngle, zAngle, relativeTo); } // Autogenerated method: UnityEngine.Transform.Rotate void UnityEngine::Transform::Rotate(float xAngle, float yAngle, float zAngle) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::Rotate"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Rotate", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(xAngle), ::il2cpp_utils::ExtractType(yAngle), ::il2cpp_utils::ExtractType(zAngle)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, xAngle, yAngle, zAngle); } // Autogenerated method: UnityEngine.Transform.RotateAroundInternal void UnityEngine::Transform::RotateAroundInternal(UnityEngine::Vector3 axis, float angle) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::RotateAroundInternal"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "RotateAroundInternal", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(axis), ::il2cpp_utils::ExtractType(angle)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, axis, angle); } // Autogenerated method: UnityEngine.Transform.Rotate void UnityEngine::Transform::Rotate(UnityEngine::Vector3 axis, float angle, UnityEngine::Space relativeTo) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::Rotate"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Rotate", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(axis), ::il2cpp_utils::ExtractType(angle), ::il2cpp_utils::ExtractType(relativeTo)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, axis, angle, relativeTo); } // Autogenerated method: UnityEngine.Transform.Rotate void UnityEngine::Transform::Rotate(UnityEngine::Vector3 axis, float angle) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::Rotate"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Rotate", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(axis), ::il2cpp_utils::ExtractType(angle)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, axis, angle); } // Autogenerated method: UnityEngine.Transform.RotateAround void UnityEngine::Transform::RotateAround(UnityEngine::Vector3 point, UnityEngine::Vector3 axis, float angle) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::RotateAround"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "RotateAround", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(point), ::il2cpp_utils::ExtractType(axis), ::il2cpp_utils::ExtractType(angle)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, point, axis, angle); } // Autogenerated method: UnityEngine.Transform.LookAt void UnityEngine::Transform::LookAt(UnityEngine::Transform* target, UnityEngine::Vector3 worldUp) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::LookAt"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "LookAt", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(target), ::il2cpp_utils::ExtractType(worldUp)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, target, worldUp); } // Autogenerated method: UnityEngine.Transform.LookAt void UnityEngine::Transform::LookAt(UnityEngine::Transform* target) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::LookAt"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "LookAt", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(target)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, target); } // Autogenerated method: UnityEngine.Transform.LookAt void UnityEngine::Transform::LookAt(UnityEngine::Vector3 worldPosition, UnityEngine::Vector3 worldUp) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::LookAt"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "LookAt", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(worldPosition), ::il2cpp_utils::ExtractType(worldUp)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, worldPosition, worldUp); } // Autogenerated method: UnityEngine.Transform.LookAt void UnityEngine::Transform::LookAt(UnityEngine::Vector3 worldPosition) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::LookAt"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "LookAt", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(worldPosition)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, worldPosition); } // Autogenerated method: UnityEngine.Transform.Internal_LookAt void UnityEngine::Transform::Internal_LookAt(UnityEngine::Vector3 worldPosition, UnityEngine::Vector3 worldUp) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::Internal_LookAt"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Internal_LookAt", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(worldPosition), ::il2cpp_utils::ExtractType(worldUp)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, worldPosition, worldUp); } // Autogenerated method: UnityEngine.Transform.TransformDirection UnityEngine::Vector3 UnityEngine::Transform::TransformDirection(UnityEngine::Vector3 direction) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::TransformDirection"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "TransformDirection", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(direction)}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Vector3, false>(this, ___internal__method, direction); } // Autogenerated method: UnityEngine.Transform.TransformDirection UnityEngine::Vector3 UnityEngine::Transform::TransformDirection(float x, float y, float z) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::TransformDirection"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "TransformDirection", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(x), ::il2cpp_utils::ExtractType(y), ::il2cpp_utils::ExtractType(z)}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Vector3, false>(this, ___internal__method, x, y, z); } // Autogenerated method: UnityEngine.Transform.InverseTransformDirection UnityEngine::Vector3 UnityEngine::Transform::InverseTransformDirection(UnityEngine::Vector3 direction) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::InverseTransformDirection"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "InverseTransformDirection", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(direction)}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Vector3, false>(this, ___internal__method, direction); } // Autogenerated method: UnityEngine.Transform.InverseTransformDirection UnityEngine::Vector3 UnityEngine::Transform::InverseTransformDirection(float x, float y, float z) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::InverseTransformDirection"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "InverseTransformDirection", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(x), ::il2cpp_utils::ExtractType(y), ::il2cpp_utils::ExtractType(z)}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Vector3, false>(this, ___internal__method, x, y, z); } // Autogenerated method: UnityEngine.Transform.TransformVector UnityEngine::Vector3 UnityEngine::Transform::TransformVector(UnityEngine::Vector3 vector) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::TransformVector"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "TransformVector", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(vector)}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Vector3, false>(this, ___internal__method, vector); } // Autogenerated method: UnityEngine.Transform.TransformVector UnityEngine::Vector3 UnityEngine::Transform::TransformVector(float x, float y, float z) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::TransformVector"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "TransformVector", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(x), ::il2cpp_utils::ExtractType(y), ::il2cpp_utils::ExtractType(z)}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Vector3, false>(this, ___internal__method, x, y, z); } // Autogenerated method: UnityEngine.Transform.InverseTransformVector UnityEngine::Vector3 UnityEngine::Transform::InverseTransformVector(UnityEngine::Vector3 vector) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::InverseTransformVector"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "InverseTransformVector", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(vector)}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Vector3, false>(this, ___internal__method, vector); } // Autogenerated method: UnityEngine.Transform.InverseTransformVector UnityEngine::Vector3 UnityEngine::Transform::InverseTransformVector(float x, float y, float z) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::InverseTransformVector"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "InverseTransformVector", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(x), ::il2cpp_utils::ExtractType(y), ::il2cpp_utils::ExtractType(z)}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Vector3, false>(this, ___internal__method, x, y, z); } // Autogenerated method: UnityEngine.Transform.TransformPoint UnityEngine::Vector3 UnityEngine::Transform::TransformPoint(UnityEngine::Vector3 position) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::TransformPoint"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "TransformPoint", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(position)}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Vector3, false>(this, ___internal__method, position); } // Autogenerated method: UnityEngine.Transform.TransformPoint UnityEngine::Vector3 UnityEngine::Transform::TransformPoint(float x, float y, float z) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::TransformPoint"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "TransformPoint", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(x), ::il2cpp_utils::ExtractType(y), ::il2cpp_utils::ExtractType(z)}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Vector3, false>(this, ___internal__method, x, y, z); } // Autogenerated method: UnityEngine.Transform.InverseTransformPoint UnityEngine::Vector3 UnityEngine::Transform::InverseTransformPoint(UnityEngine::Vector3 position) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::InverseTransformPoint"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "InverseTransformPoint", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(position)}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Vector3, false>(this, ___internal__method, position); } // Autogenerated method: UnityEngine.Transform.InverseTransformPoint UnityEngine::Vector3 UnityEngine::Transform::InverseTransformPoint(float x, float y, float z) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::InverseTransformPoint"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "InverseTransformPoint", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(x), ::il2cpp_utils::ExtractType(y), ::il2cpp_utils::ExtractType(z)}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Vector3, false>(this, ___internal__method, x, y, z); } // Autogenerated method: UnityEngine.Transform.get_root UnityEngine::Transform* UnityEngine::Transform::get_root() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::get_root"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_root", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Transform*, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Transform.GetRoot UnityEngine::Transform* UnityEngine::Transform::GetRoot() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::GetRoot"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "GetRoot", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Transform*, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Transform.get_childCount int UnityEngine::Transform::get_childCount() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::get_childCount"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_childCount", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<int, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Transform.DetachChildren void UnityEngine::Transform::DetachChildren() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::DetachChildren"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "DetachChildren", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Transform.SetAsFirstSibling void UnityEngine::Transform::SetAsFirstSibling() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::SetAsFirstSibling"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "SetAsFirstSibling", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Transform.SetAsLastSibling void UnityEngine::Transform::SetAsLastSibling() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::SetAsLastSibling"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "SetAsLastSibling", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Transform.SetSiblingIndex void UnityEngine::Transform::SetSiblingIndex(int index) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::SetSiblingIndex"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "SetSiblingIndex", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(index)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, index); } // Autogenerated method: UnityEngine.Transform.GetSiblingIndex int UnityEngine::Transform::GetSiblingIndex() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::GetSiblingIndex"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "GetSiblingIndex", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<int, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Transform.FindRelativeTransformWithPath UnityEngine::Transform* UnityEngine::Transform::FindRelativeTransformWithPath(UnityEngine::Transform* transform, ::Il2CppString* path, bool isActiveOnly) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::FindRelativeTransformWithPath"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine", "Transform", "FindRelativeTransformWithPath", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(transform), ::il2cpp_utils::ExtractType(path), ::il2cpp_utils::ExtractType(isActiveOnly)}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Transform*, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, transform, path, isActiveOnly); } // Autogenerated method: UnityEngine.Transform.Find UnityEngine::Transform* UnityEngine::Transform::Find(::Il2CppString* n) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::Find"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Find", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(n)}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Transform*, false>(this, ___internal__method, n); } // Autogenerated method: UnityEngine.Transform.SendTransformChangedScale void UnityEngine::Transform::SendTransformChangedScale() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::SendTransformChangedScale"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "SendTransformChangedScale", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Transform.get_lossyScale UnityEngine::Vector3 UnityEngine::Transform::get_lossyScale() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::get_lossyScale"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_lossyScale", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Vector3, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Transform.IsChildOf bool UnityEngine::Transform::IsChildOf(UnityEngine::Transform* parent) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::IsChildOf"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "IsChildOf", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(parent)}))); return ::il2cpp_utils::RunMethodThrow<bool, false>(this, ___internal__method, parent); } // Autogenerated method: UnityEngine.Transform.get_hasChanged bool UnityEngine::Transform::get_hasChanged() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::get_hasChanged"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_hasChanged", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<bool, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Transform.set_hasChanged void UnityEngine::Transform::set_hasChanged(bool value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::set_hasChanged"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "set_hasChanged", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, value); } // Autogenerated method: UnityEngine.Transform.FindChild UnityEngine::Transform* UnityEngine::Transform::FindChild(::Il2CppString* n) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::FindChild"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "FindChild", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(n)}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Transform*, false>(this, ___internal__method, n); } // Autogenerated method: UnityEngine.Transform.GetEnumerator System::Collections::IEnumerator* UnityEngine::Transform::GetEnumerator() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::GetEnumerator"); auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "GetEnumerator", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<System::Collections::IEnumerator*, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Transform.RotateAround void UnityEngine::Transform::RotateAround(UnityEngine::Vector3 axis, float angle) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::RotateAround"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "RotateAround", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(axis), ::il2cpp_utils::ExtractType(angle)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, axis, angle); } // Autogenerated method: UnityEngine.Transform.RotateAroundLocal void UnityEngine::Transform::RotateAroundLocal(UnityEngine::Vector3 axis, float angle) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::RotateAroundLocal"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "RotateAroundLocal", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(axis), ::il2cpp_utils::ExtractType(angle)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, axis, angle); } // Autogenerated method: UnityEngine.Transform.GetChild UnityEngine::Transform* UnityEngine::Transform::GetChild(int index) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::GetChild"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "GetChild", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(index)}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Transform*, false>(this, ___internal__method, index); } // Autogenerated method: UnityEngine.Transform.GetChildCount int UnityEngine::Transform::GetChildCount() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::GetChildCount"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "GetChildCount", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<int, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Transform.get_hierarchyCapacity int UnityEngine::Transform::get_hierarchyCapacity() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::get_hierarchyCapacity"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_hierarchyCapacity", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<int, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Transform.set_hierarchyCapacity void UnityEngine::Transform::set_hierarchyCapacity(int value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::set_hierarchyCapacity"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "set_hierarchyCapacity", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, value); } // Autogenerated method: UnityEngine.Transform.internal_getHierarchyCapacity int UnityEngine::Transform::internal_getHierarchyCapacity() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::internal_getHierarchyCapacity"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "internal_getHierarchyCapacity", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<int, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Transform.internal_setHierarchyCapacity void UnityEngine::Transform::internal_setHierarchyCapacity(int value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::internal_setHierarchyCapacity"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "internal_setHierarchyCapacity", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, value); } // Autogenerated method: UnityEngine.Transform.get_hierarchyCount int UnityEngine::Transform::get_hierarchyCount() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::get_hierarchyCount"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_hierarchyCount", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<int, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Transform.internal_getHierarchyCount int UnityEngine::Transform::internal_getHierarchyCount() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::internal_getHierarchyCount"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "internal_getHierarchyCount", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<int, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Transform.IsNonUniformScaleTransform bool UnityEngine::Transform::IsNonUniformScaleTransform() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::IsNonUniformScaleTransform"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "IsNonUniformScaleTransform", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<bool, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Transform.get_position_Injected void UnityEngine::Transform::get_position_Injected(UnityEngine::Vector3& ret) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::get_position_Injected"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_position_Injected", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractIndependentType<UnityEngine::Vector3&>()}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, ret); } // Autogenerated method: UnityEngine.Transform.set_position_Injected void UnityEngine::Transform::set_position_Injected(UnityEngine::Vector3& value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::set_position_Injected"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "set_position_Injected", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, value); } // Autogenerated method: UnityEngine.Transform.get_localPosition_Injected void UnityEngine::Transform::get_localPosition_Injected(UnityEngine::Vector3& ret) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::get_localPosition_Injected"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_localPosition_Injected", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractIndependentType<UnityEngine::Vector3&>()}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, ret); } // Autogenerated method: UnityEngine.Transform.set_localPosition_Injected void UnityEngine::Transform::set_localPosition_Injected(UnityEngine::Vector3& value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::set_localPosition_Injected"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "set_localPosition_Injected", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, value); } // Autogenerated method: UnityEngine.Transform.GetLocalEulerAngles_Injected void UnityEngine::Transform::GetLocalEulerAngles_Injected(UnityEngine::RotationOrder order, UnityEngine::Vector3& ret) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::GetLocalEulerAngles_Injected"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "GetLocalEulerAngles_Injected", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(order), ::il2cpp_utils::ExtractIndependentType<UnityEngine::Vector3&>()}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, order, ret); } // Autogenerated method: UnityEngine.Transform.SetLocalEulerAngles_Injected void UnityEngine::Transform::SetLocalEulerAngles_Injected(UnityEngine::Vector3& euler, UnityEngine::RotationOrder order) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::SetLocalEulerAngles_Injected"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "SetLocalEulerAngles_Injected", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(euler), ::il2cpp_utils::ExtractType(order)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, euler, order); } // Autogenerated method: UnityEngine.Transform.SetLocalEulerHint_Injected void UnityEngine::Transform::SetLocalEulerHint_Injected(UnityEngine::Vector3& euler) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::SetLocalEulerHint_Injected"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "SetLocalEulerHint_Injected", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(euler)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, euler); } // Autogenerated method: UnityEngine.Transform.get_rotation_Injected void UnityEngine::Transform::get_rotation_Injected(UnityEngine::Quaternion& ret) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::get_rotation_Injected"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_rotation_Injected", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractIndependentType<UnityEngine::Quaternion&>()}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, ret); } // Autogenerated method: UnityEngine.Transform.set_rotation_Injected void UnityEngine::Transform::set_rotation_Injected(UnityEngine::Quaternion& value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::set_rotation_Injected"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "set_rotation_Injected", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, value); } // Autogenerated method: UnityEngine.Transform.get_localRotation_Injected void UnityEngine::Transform::get_localRotation_Injected(UnityEngine::Quaternion& ret) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::get_localRotation_Injected"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_localRotation_Injected", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractIndependentType<UnityEngine::Quaternion&>()}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, ret); } // Autogenerated method: UnityEngine.Transform.set_localRotation_Injected void UnityEngine::Transform::set_localRotation_Injected(UnityEngine::Quaternion& value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::set_localRotation_Injected"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "set_localRotation_Injected", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, value); } // Autogenerated method: UnityEngine.Transform.get_localScale_Injected void UnityEngine::Transform::get_localScale_Injected(UnityEngine::Vector3& ret) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::get_localScale_Injected"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_localScale_Injected", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractIndependentType<UnityEngine::Vector3&>()}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, ret); } // Autogenerated method: UnityEngine.Transform.set_localScale_Injected void UnityEngine::Transform::set_localScale_Injected(UnityEngine::Vector3& value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::set_localScale_Injected"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "set_localScale_Injected", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, value); } // Autogenerated method: UnityEngine.Transform.get_worldToLocalMatrix_Injected void UnityEngine::Transform::get_worldToLocalMatrix_Injected(UnityEngine::Matrix4x4& ret) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::get_worldToLocalMatrix_Injected"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_worldToLocalMatrix_Injected", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractIndependentType<UnityEngine::Matrix4x4&>()}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, ret); } // Autogenerated method: UnityEngine.Transform.get_localToWorldMatrix_Injected void UnityEngine::Transform::get_localToWorldMatrix_Injected(UnityEngine::Matrix4x4& ret) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::get_localToWorldMatrix_Injected"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_localToWorldMatrix_Injected", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractIndependentType<UnityEngine::Matrix4x4&>()}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, ret); } // Autogenerated method: UnityEngine.Transform.SetPositionAndRotation_Injected void UnityEngine::Transform::SetPositionAndRotation_Injected(UnityEngine::Vector3& position, UnityEngine::Quaternion& rotation) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::SetPositionAndRotation_Injected"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "SetPositionAndRotation_Injected", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(position), ::il2cpp_utils::ExtractType(rotation)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, position, rotation); } // Autogenerated method: UnityEngine.Transform.RotateAroundInternal_Injected void UnityEngine::Transform::RotateAroundInternal_Injected(UnityEngine::Vector3& axis, float angle) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::RotateAroundInternal_Injected"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "RotateAroundInternal_Injected", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(axis), ::il2cpp_utils::ExtractType(angle)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, axis, angle); } // Autogenerated method: UnityEngine.Transform.Internal_LookAt_Injected void UnityEngine::Transform::Internal_LookAt_Injected(UnityEngine::Vector3& worldPosition, UnityEngine::Vector3& worldUp) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::Internal_LookAt_Injected"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Internal_LookAt_Injected", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(worldPosition), ::il2cpp_utils::ExtractType(worldUp)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, worldPosition, worldUp); } // Autogenerated method: UnityEngine.Transform.TransformDirection_Injected void UnityEngine::Transform::TransformDirection_Injected(UnityEngine::Vector3& direction, UnityEngine::Vector3& ret) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::TransformDirection_Injected"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "TransformDirection_Injected", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(direction), ::il2cpp_utils::ExtractIndependentType<UnityEngine::Vector3&>()}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, direction, ret); } // Autogenerated method: UnityEngine.Transform.InverseTransformDirection_Injected void UnityEngine::Transform::InverseTransformDirection_Injected(UnityEngine::Vector3& direction, UnityEngine::Vector3& ret) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::InverseTransformDirection_Injected"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "InverseTransformDirection_Injected", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(direction), ::il2cpp_utils::ExtractIndependentType<UnityEngine::Vector3&>()}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, direction, ret); } // Autogenerated method: UnityEngine.Transform.TransformVector_Injected void UnityEngine::Transform::TransformVector_Injected(UnityEngine::Vector3& vector, UnityEngine::Vector3& ret) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::TransformVector_Injected"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "TransformVector_Injected", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(vector), ::il2cpp_utils::ExtractIndependentType<UnityEngine::Vector3&>()}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, vector, ret); } // Autogenerated method: UnityEngine.Transform.InverseTransformVector_Injected void UnityEngine::Transform::InverseTransformVector_Injected(UnityEngine::Vector3& vector, UnityEngine::Vector3& ret) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::InverseTransformVector_Injected"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "InverseTransformVector_Injected", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(vector), ::il2cpp_utils::ExtractIndependentType<UnityEngine::Vector3&>()}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, vector, ret); } // Autogenerated method: UnityEngine.Transform.TransformPoint_Injected void UnityEngine::Transform::TransformPoint_Injected(UnityEngine::Vector3& position, UnityEngine::Vector3& ret) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::TransformPoint_Injected"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "TransformPoint_Injected", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(position), ::il2cpp_utils::ExtractIndependentType<UnityEngine::Vector3&>()}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, position, ret); } // Autogenerated method: UnityEngine.Transform.InverseTransformPoint_Injected void UnityEngine::Transform::InverseTransformPoint_Injected(UnityEngine::Vector3& position, UnityEngine::Vector3& ret) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::InverseTransformPoint_Injected"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "InverseTransformPoint_Injected", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(position), ::il2cpp_utils::ExtractIndependentType<UnityEngine::Vector3&>()}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, position, ret); } // Autogenerated method: UnityEngine.Transform.get_lossyScale_Injected void UnityEngine::Transform::get_lossyScale_Injected(UnityEngine::Vector3& ret) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::get_lossyScale_Injected"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_lossyScale_Injected", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractIndependentType<UnityEngine::Vector3&>()}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, ret); } // Autogenerated method: UnityEngine.Transform.RotateAround_Injected void UnityEngine::Transform::RotateAround_Injected(UnityEngine::Vector3& axis, float angle) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::RotateAround_Injected"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "RotateAround_Injected", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(axis), ::il2cpp_utils::ExtractType(angle)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, axis, angle); } // Autogenerated method: UnityEngine.Transform.RotateAroundLocal_Injected void UnityEngine::Transform::RotateAroundLocal_Injected(UnityEngine::Vector3& axis, float angle) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::RotateAroundLocal_Injected"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "RotateAroundLocal_Injected", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(axis), ::il2cpp_utils::ExtractType(angle)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, axis, angle); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: UnityEngine.Transform/Enumerator #include "UnityEngine/Transform_Enumerator.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated method: UnityEngine.Transform/Enumerator.get_Current ::Il2CppObject* UnityEngine::Transform::Enumerator::get_Current() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::Enumerator::get_Current"); auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_Current", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<::Il2CppObject*, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Transform/Enumerator.MoveNext bool UnityEngine::Transform::Enumerator::MoveNext() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::Enumerator::MoveNext"); auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "MoveNext", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<bool, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Transform/Enumerator.Reset void UnityEngine::Transform::Enumerator::Reset() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Transform::Enumerator::Reset"); auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Reset", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes // Including type: UnityEngine.SpriteRenderer #include "UnityEngine/SpriteRenderer.hpp" // Including type: UnityEngine.Sprite #include "UnityEngine/Sprite.hpp" // Including type: UnityEngine.Color #include "UnityEngine/Color.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated method: UnityEngine.SpriteRenderer.set_sprite void UnityEngine::SpriteRenderer::set_sprite(UnityEngine::Sprite* value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SpriteRenderer::set_sprite"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "set_sprite", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, value); } // Autogenerated method: UnityEngine.SpriteRenderer.get_color UnityEngine::Color UnityEngine::SpriteRenderer::get_color() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SpriteRenderer::get_color"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_color", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Color, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.SpriteRenderer.set_color void UnityEngine::SpriteRenderer::set_color(UnityEngine::Color value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SpriteRenderer::set_color"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "set_color", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, value); } // Autogenerated method: UnityEngine.SpriteRenderer.get_color_Injected void UnityEngine::SpriteRenderer::get_color_Injected(UnityEngine::Color& ret) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SpriteRenderer::get_color_Injected"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_color_Injected", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractIndependentType<UnityEngine::Color&>()}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, ret); } // Autogenerated method: UnityEngine.SpriteRenderer.set_color_Injected void UnityEngine::SpriteRenderer::set_color_Injected(UnityEngine::Color& value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SpriteRenderer::set_color_Injected"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "set_color_Injected", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, value); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes // Including type: UnityEngine.SpriteMeshType #include "UnityEngine/SpriteMeshType.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated static field getter // Get static field: static public UnityEngine.SpriteMeshType FullRect UnityEngine::SpriteMeshType UnityEngine::SpriteMeshType::_get_FullRect() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SpriteMeshType::_get_FullRect"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<UnityEngine::SpriteMeshType>("UnityEngine", "SpriteMeshType", "FullRect")); } // Autogenerated static field setter // Set static field: static public UnityEngine.SpriteMeshType FullRect void UnityEngine::SpriteMeshType::_set_FullRect(UnityEngine::SpriteMeshType value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SpriteMeshType::_set_FullRect"); THROW_UNLESS(il2cpp_utils::SetFieldValue("UnityEngine", "SpriteMeshType", "FullRect", value)); } // Autogenerated static field getter // Get static field: static public UnityEngine.SpriteMeshType Tight UnityEngine::SpriteMeshType UnityEngine::SpriteMeshType::_get_Tight() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SpriteMeshType::_get_Tight"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<UnityEngine::SpriteMeshType>("UnityEngine", "SpriteMeshType", "Tight")); } // Autogenerated static field setter // Set static field: static public UnityEngine.SpriteMeshType Tight void UnityEngine::SpriteMeshType::_set_Tight(UnityEngine::SpriteMeshType value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SpriteMeshType::_set_Tight"); THROW_UNLESS(il2cpp_utils::SetFieldValue("UnityEngine", "SpriteMeshType", "Tight", value)); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes // Including type: UnityEngine.SpritePackingMode #include "UnityEngine/SpritePackingMode.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated static field getter // Get static field: static public UnityEngine.SpritePackingMode Tight UnityEngine::SpritePackingMode UnityEngine::SpritePackingMode::_get_Tight() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SpritePackingMode::_get_Tight"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<UnityEngine::SpritePackingMode>("UnityEngine", "SpritePackingMode", "Tight")); } // Autogenerated static field setter // Set static field: static public UnityEngine.SpritePackingMode Tight void UnityEngine::SpritePackingMode::_set_Tight(UnityEngine::SpritePackingMode value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SpritePackingMode::_set_Tight"); THROW_UNLESS(il2cpp_utils::SetFieldValue("UnityEngine", "SpritePackingMode", "Tight", value)); } // Autogenerated static field getter // Get static field: static public UnityEngine.SpritePackingMode Rectangle UnityEngine::SpritePackingMode UnityEngine::SpritePackingMode::_get_Rectangle() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SpritePackingMode::_get_Rectangle"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<UnityEngine::SpritePackingMode>("UnityEngine", "SpritePackingMode", "Rectangle")); } // Autogenerated static field setter // Set static field: static public UnityEngine.SpritePackingMode Rectangle void UnityEngine::SpritePackingMode::_set_Rectangle(UnityEngine::SpritePackingMode value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SpritePackingMode::_set_Rectangle"); THROW_UNLESS(il2cpp_utils::SetFieldValue("UnityEngine", "SpritePackingMode", "Rectangle", value)); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: UnityEngine.Sprite #include "UnityEngine/Sprite.hpp" // Including type: UnityEngine.Rect #include "UnityEngine/Rect.hpp" // Including type: UnityEngine.Vector4 #include "UnityEngine/Vector4.hpp" // Including type: UnityEngine.Texture2D #include "UnityEngine/Texture2D.hpp" // Including type: UnityEngine.SpriteMeshType #include "UnityEngine/SpriteMeshType.hpp" // Including type: UnityEngine.Bounds #include "UnityEngine/Bounds.hpp" // Including type: UnityEngine.SpritePackingMode #include "UnityEngine/SpritePackingMode.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated method: UnityEngine.Sprite.GetPackingMode int UnityEngine::Sprite::GetPackingMode() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Sprite::GetPackingMode"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "GetPackingMode", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<int, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Sprite.GetPacked int UnityEngine::Sprite::GetPacked() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Sprite::GetPacked"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "GetPacked", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<int, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Sprite.GetTextureRect UnityEngine::Rect UnityEngine::Sprite::GetTextureRect() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Sprite::GetTextureRect"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "GetTextureRect", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Rect, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Sprite.GetInnerUVs UnityEngine::Vector4 UnityEngine::Sprite::GetInnerUVs() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Sprite::GetInnerUVs"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "GetInnerUVs", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Vector4, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Sprite.GetOuterUVs UnityEngine::Vector4 UnityEngine::Sprite::GetOuterUVs() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Sprite::GetOuterUVs"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "GetOuterUVs", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Vector4, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Sprite.GetPadding UnityEngine::Vector4 UnityEngine::Sprite::GetPadding() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Sprite::GetPadding"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "GetPadding", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Vector4, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Sprite.CreateSprite UnityEngine::Sprite* UnityEngine::Sprite::CreateSprite(UnityEngine::Texture2D* texture, UnityEngine::Rect rect, UnityEngine::Vector2 pivot, float pixelsPerUnit, uint extrude, UnityEngine::SpriteMeshType meshType, UnityEngine::Vector4 border, bool generateFallbackPhysicsShape) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Sprite::CreateSprite"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine", "Sprite", "CreateSprite", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(texture), ::il2cpp_utils::ExtractType(rect), ::il2cpp_utils::ExtractType(pivot), ::il2cpp_utils::ExtractType(pixelsPerUnit), ::il2cpp_utils::ExtractType(extrude), ::il2cpp_utils::ExtractType(meshType), ::il2cpp_utils::ExtractType(border), ::il2cpp_utils::ExtractType(generateFallbackPhysicsShape)}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Sprite*, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, texture, rect, pivot, pixelsPerUnit, extrude, meshType, border, generateFallbackPhysicsShape); } // Autogenerated method: UnityEngine.Sprite.get_bounds UnityEngine::Bounds UnityEngine::Sprite::get_bounds() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Sprite::get_bounds"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_bounds", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Bounds, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Sprite.get_rect UnityEngine::Rect UnityEngine::Sprite::get_rect() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Sprite::get_rect"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_rect", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Rect, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Sprite.get_border UnityEngine::Vector4 UnityEngine::Sprite::get_border() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Sprite::get_border"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_border", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Vector4, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Sprite.get_texture UnityEngine::Texture2D* UnityEngine::Sprite::get_texture() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Sprite::get_texture"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_texture", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Texture2D*, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Sprite.get_pixelsPerUnit float UnityEngine::Sprite::get_pixelsPerUnit() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Sprite::get_pixelsPerUnit"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_pixelsPerUnit", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<float, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Sprite.get_associatedAlphaSplitTexture UnityEngine::Texture2D* UnityEngine::Sprite::get_associatedAlphaSplitTexture() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Sprite::get_associatedAlphaSplitTexture"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_associatedAlphaSplitTexture", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Texture2D*, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Sprite.get_pivot UnityEngine::Vector2 UnityEngine::Sprite::get_pivot() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Sprite::get_pivot"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_pivot", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Vector2, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Sprite.get_packed bool UnityEngine::Sprite::get_packed() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Sprite::get_packed"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_packed", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<bool, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Sprite.get_packingMode UnityEngine::SpritePackingMode UnityEngine::Sprite::get_packingMode() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Sprite::get_packingMode"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_packingMode", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::SpritePackingMode, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Sprite.get_textureRect UnityEngine::Rect UnityEngine::Sprite::get_textureRect() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Sprite::get_textureRect"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_textureRect", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Rect, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Sprite.get_vertices ::Array<UnityEngine::Vector2>* UnityEngine::Sprite::get_vertices() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Sprite::get_vertices"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_vertices", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<::Array<UnityEngine::Vector2>*, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Sprite.get_triangles ::Array<uint16_t>* UnityEngine::Sprite::get_triangles() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Sprite::get_triangles"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_triangles", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<::Array<uint16_t>*, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Sprite.get_uv ::Array<UnityEngine::Vector2>* UnityEngine::Sprite::get_uv() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Sprite::get_uv"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_uv", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<::Array<UnityEngine::Vector2>*, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Sprite.Create UnityEngine::Sprite* UnityEngine::Sprite::Create(UnityEngine::Texture2D* texture, UnityEngine::Rect rect, UnityEngine::Vector2 pivot, float pixelsPerUnit, uint extrude, UnityEngine::SpriteMeshType meshType, UnityEngine::Vector4 border, bool generateFallbackPhysicsShape) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Sprite::Create"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine", "Sprite", "Create", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(texture), ::il2cpp_utils::ExtractType(rect), ::il2cpp_utils::ExtractType(pivot), ::il2cpp_utils::ExtractType(pixelsPerUnit), ::il2cpp_utils::ExtractType(extrude), ::il2cpp_utils::ExtractType(meshType), ::il2cpp_utils::ExtractType(border), ::il2cpp_utils::ExtractType(generateFallbackPhysicsShape)}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Sprite*, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, texture, rect, pivot, pixelsPerUnit, extrude, meshType, border, generateFallbackPhysicsShape); } // Autogenerated method: UnityEngine.Sprite.GetTextureRect_Injected void UnityEngine::Sprite::GetTextureRect_Injected(UnityEngine::Rect& ret) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Sprite::GetTextureRect_Injected"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "GetTextureRect_Injected", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractIndependentType<UnityEngine::Rect&>()}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, ret); } // Autogenerated method: UnityEngine.Sprite.GetInnerUVs_Injected void UnityEngine::Sprite::GetInnerUVs_Injected(UnityEngine::Vector4& ret) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Sprite::GetInnerUVs_Injected"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "GetInnerUVs_Injected", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractIndependentType<UnityEngine::Vector4&>()}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, ret); } // Autogenerated method: UnityEngine.Sprite.GetOuterUVs_Injected void UnityEngine::Sprite::GetOuterUVs_Injected(UnityEngine::Vector4& ret) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Sprite::GetOuterUVs_Injected"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "GetOuterUVs_Injected", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractIndependentType<UnityEngine::Vector4&>()}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, ret); } // Autogenerated method: UnityEngine.Sprite.GetPadding_Injected void UnityEngine::Sprite::GetPadding_Injected(UnityEngine::Vector4& ret) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Sprite::GetPadding_Injected"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "GetPadding_Injected", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractIndependentType<UnityEngine::Vector4&>()}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, ret); } // Autogenerated method: UnityEngine.Sprite.CreateSprite_Injected UnityEngine::Sprite* UnityEngine::Sprite::CreateSprite_Injected(UnityEngine::Texture2D* texture, UnityEngine::Rect& rect, UnityEngine::Vector2& pivot, float pixelsPerUnit, uint extrude, UnityEngine::SpriteMeshType meshType, UnityEngine::Vector4& border, bool generateFallbackPhysicsShape) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Sprite::CreateSprite_Injected"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine", "Sprite", "CreateSprite_Injected", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(texture), ::il2cpp_utils::ExtractType(rect), ::il2cpp_utils::ExtractType(pivot), ::il2cpp_utils::ExtractType(pixelsPerUnit), ::il2cpp_utils::ExtractType(extrude), ::il2cpp_utils::ExtractType(meshType), ::il2cpp_utils::ExtractType(border), ::il2cpp_utils::ExtractType(generateFallbackPhysicsShape)}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Sprite*, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, texture, rect, pivot, pixelsPerUnit, extrude, meshType, border, generateFallbackPhysicsShape); } // Autogenerated method: UnityEngine.Sprite.get_bounds_Injected void UnityEngine::Sprite::get_bounds_Injected(UnityEngine::Bounds& ret) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Sprite::get_bounds_Injected"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_bounds_Injected", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractIndependentType<UnityEngine::Bounds&>()}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, ret); } // Autogenerated method: UnityEngine.Sprite.get_rect_Injected void UnityEngine::Sprite::get_rect_Injected(UnityEngine::Rect& ret) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Sprite::get_rect_Injected"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_rect_Injected", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractIndependentType<UnityEngine::Rect&>()}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, ret); } // Autogenerated method: UnityEngine.Sprite.get_border_Injected void UnityEngine::Sprite::get_border_Injected(UnityEngine::Vector4& ret) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Sprite::get_border_Injected"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_border_Injected", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractIndependentType<UnityEngine::Vector4&>()}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, ret); } // Autogenerated method: UnityEngine.Sprite.get_pivot_Injected void UnityEngine::Sprite::get_pivot_Injected(UnityEngine::Vector2& ret) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Sprite::get_pivot_Injected"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_pivot_Injected", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractIndependentType<UnityEngine::Vector2&>()}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, ret); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: UnityEngine._Scripting.APIUpdating.APIUpdaterRuntimeHelpers #include "UnityEngine/_Scripting/APIUpdating/APIUpdaterRuntimeHelpers.hpp" // Including type: System.Type #include "System/Type.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated method: UnityEngine._Scripting.APIUpdating.APIUpdaterRuntimeHelpers.GetMovedFromAttributeDataForType bool UnityEngine::_Scripting::APIUpdating::APIUpdaterRuntimeHelpers::GetMovedFromAttributeDataForType(System::Type* sourceType, ::Il2CppString*& assembly, ::Il2CppString*& nsp, ::Il2CppString*& klass) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::_Scripting::APIUpdating::APIUpdaterRuntimeHelpers::GetMovedFromAttributeDataForType"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine._Scripting.APIUpdating", "APIUpdaterRuntimeHelpers", "GetMovedFromAttributeDataForType", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(sourceType), ::il2cpp_utils::ExtractIndependentType<::Il2CppString*&>(), ::il2cpp_utils::ExtractIndependentType<::Il2CppString*&>(), ::il2cpp_utils::ExtractIndependentType<::Il2CppString*&>()}))); return ::il2cpp_utils::RunMethodThrow<bool, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, sourceType, assembly, nsp, klass); } // Autogenerated method: UnityEngine._Scripting.APIUpdating.APIUpdaterRuntimeHelpers.GetObsoleteTypeRedirection bool UnityEngine::_Scripting::APIUpdating::APIUpdaterRuntimeHelpers::GetObsoleteTypeRedirection(System::Type* sourceType, ::Il2CppString*& assemblyName, ::Il2CppString*& nsp, ::Il2CppString*& className) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::_Scripting::APIUpdating::APIUpdaterRuntimeHelpers::GetObsoleteTypeRedirection"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine._Scripting.APIUpdating", "APIUpdaterRuntimeHelpers", "GetObsoleteTypeRedirection", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(sourceType), ::il2cpp_utils::ExtractIndependentType<::Il2CppString*&>(), ::il2cpp_utils::ExtractIndependentType<::Il2CppString*&>(), ::il2cpp_utils::ExtractIndependentType<::Il2CppString*&>()}))); return ::il2cpp_utils::RunMethodThrow<bool, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, sourceType, assemblyName, nsp, className); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes // Including type: UnityEngine.Sprites.DataUtility #include "UnityEngine/Sprites/DataUtility.hpp" // Including type: UnityEngine.Vector4 #include "UnityEngine/Vector4.hpp" // Including type: UnityEngine.Sprite #include "UnityEngine/Sprite.hpp" // Including type: UnityEngine.Vector2 #include "UnityEngine/Vector2.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated method: UnityEngine.Sprites.DataUtility.GetInnerUV UnityEngine::Vector4 UnityEngine::Sprites::DataUtility::GetInnerUV(UnityEngine::Sprite* sprite) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Sprites::DataUtility::GetInnerUV"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.Sprites", "DataUtility", "GetInnerUV", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(sprite)}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Vector4, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, sprite); } // Autogenerated method: UnityEngine.Sprites.DataUtility.GetOuterUV UnityEngine::Vector4 UnityEngine::Sprites::DataUtility::GetOuterUV(UnityEngine::Sprite* sprite) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Sprites::DataUtility::GetOuterUV"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.Sprites", "DataUtility", "GetOuterUV", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(sprite)}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Vector4, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, sprite); } // Autogenerated method: UnityEngine.Sprites.DataUtility.GetPadding UnityEngine::Vector4 UnityEngine::Sprites::DataUtility::GetPadding(UnityEngine::Sprite* sprite) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Sprites::DataUtility::GetPadding"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.Sprites", "DataUtility", "GetPadding", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(sprite)}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Vector4, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, sprite); } // Autogenerated method: UnityEngine.Sprites.DataUtility.GetMinSize UnityEngine::Vector2 UnityEngine::Sprites::DataUtility::GetMinSize(UnityEngine::Sprite* sprite) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Sprites::DataUtility::GetMinSize"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.Sprites", "DataUtility", "GetMinSize", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(sprite)}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Vector2, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, sprite); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: UnityEngine.U2D.SpriteAtlasManager #include "UnityEngine/U2D/SpriteAtlasManager.hpp" // Including type: System.Action`2 #include "System/Action_2.hpp" // Including type: System.Action`1 #include "System/Action_1.hpp" // Including type: UnityEngine.U2D.SpriteAtlas #include "UnityEngine/U2D/SpriteAtlas.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // [CompilerGeneratedAttribute] Offset: 0xD93EC8 // [DebuggerBrowsableAttribute] Offset: 0xD93EC8 // Autogenerated static field getter // Get static field: static private System.Action`2<System.String,System.Action`1<UnityEngine.U2D.SpriteAtlas>> atlasRequested System::Action_2<::Il2CppString*, System::Action_1<UnityEngine::U2D::SpriteAtlas*>*>* UnityEngine::U2D::SpriteAtlasManager::_get_atlasRequested() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::U2D::SpriteAtlasManager::_get_atlasRequested"); return THROW_UNLESS((il2cpp_utils::GetFieldValue<System::Action_2<::Il2CppString*, System::Action_1<UnityEngine::U2D::SpriteAtlas*>*>*>("UnityEngine.U2D", "SpriteAtlasManager", "atlasRequested"))); } // Autogenerated static field setter // Set static field: static private System.Action`2<System.String,System.Action`1<UnityEngine.U2D.SpriteAtlas>> atlasRequested void UnityEngine::U2D::SpriteAtlasManager::_set_atlasRequested(System::Action_2<::Il2CppString*, System::Action_1<UnityEngine::U2D::SpriteAtlas*>*>* value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::U2D::SpriteAtlasManager::_set_atlasRequested"); THROW_UNLESS(il2cpp_utils::SetFieldValue("UnityEngine.U2D", "SpriteAtlasManager", "atlasRequested", value)); } // [CompilerGeneratedAttribute] Offset: 0xD93F04 // [DebuggerBrowsableAttribute] Offset: 0xD93F04 // Autogenerated static field getter // Get static field: static private System.Action`1<UnityEngine.U2D.SpriteAtlas> atlasRegistered System::Action_1<UnityEngine::U2D::SpriteAtlas*>* UnityEngine::U2D::SpriteAtlasManager::_get_atlasRegistered() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::U2D::SpriteAtlasManager::_get_atlasRegistered"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<System::Action_1<UnityEngine::U2D::SpriteAtlas*>*>("UnityEngine.U2D", "SpriteAtlasManager", "atlasRegistered")); } // Autogenerated static field setter // Set static field: static private System.Action`1<UnityEngine.U2D.SpriteAtlas> atlasRegistered void UnityEngine::U2D::SpriteAtlasManager::_set_atlasRegistered(System::Action_1<UnityEngine::U2D::SpriteAtlas*>* value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::U2D::SpriteAtlasManager::_set_atlasRegistered"); THROW_UNLESS(il2cpp_utils::SetFieldValue("UnityEngine.U2D", "SpriteAtlasManager", "atlasRegistered", value)); } // Autogenerated method: UnityEngine.U2D.SpriteAtlasManager.RequestAtlas bool UnityEngine::U2D::SpriteAtlasManager::RequestAtlas(::Il2CppString* tag) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::U2D::SpriteAtlasManager::RequestAtlas"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.U2D", "SpriteAtlasManager", "RequestAtlas", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(tag)}))); return ::il2cpp_utils::RunMethodThrow<bool, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, tag); } // Autogenerated method: UnityEngine.U2D.SpriteAtlasManager.add_atlasRegistered void UnityEngine::U2D::SpriteAtlasManager::add_atlasRegistered(System::Action_1<UnityEngine::U2D::SpriteAtlas*>* value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::U2D::SpriteAtlasManager::add_atlasRegistered"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.U2D", "SpriteAtlasManager", "add_atlasRegistered", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)}))); ::il2cpp_utils::RunMethodThrow<void, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, value); } // Autogenerated method: UnityEngine.U2D.SpriteAtlasManager.remove_atlasRegistered void UnityEngine::U2D::SpriteAtlasManager::remove_atlasRegistered(System::Action_1<UnityEngine::U2D::SpriteAtlas*>* value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::U2D::SpriteAtlasManager::remove_atlasRegistered"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.U2D", "SpriteAtlasManager", "remove_atlasRegistered", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)}))); ::il2cpp_utils::RunMethodThrow<void, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, value); } // Autogenerated method: UnityEngine.U2D.SpriteAtlasManager.PostRegisteredAtlas void UnityEngine::U2D::SpriteAtlasManager::PostRegisteredAtlas(UnityEngine::U2D::SpriteAtlas* spriteAtlas) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::U2D::SpriteAtlasManager::PostRegisteredAtlas"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.U2D", "SpriteAtlasManager", "PostRegisteredAtlas", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(spriteAtlas)}))); ::il2cpp_utils::RunMethodThrow<void, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, spriteAtlas); } // Autogenerated method: UnityEngine.U2D.SpriteAtlasManager.Register void UnityEngine::U2D::SpriteAtlasManager::Register(UnityEngine::U2D::SpriteAtlas* spriteAtlas) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::U2D::SpriteAtlasManager::Register"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.U2D", "SpriteAtlasManager", "Register", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(spriteAtlas)}))); ::il2cpp_utils::RunMethodThrow<void, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, spriteAtlas); } // Autogenerated method: UnityEngine.U2D.SpriteAtlasManager..cctor void UnityEngine::U2D::SpriteAtlasManager::_cctor() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::U2D::SpriteAtlasManager::.cctor"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.U2D", "SpriteAtlasManager", ".cctor", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); ::il2cpp_utils::RunMethodThrow<void, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: UnityEngine.U2D.SpriteAtlas #include "UnityEngine/U2D/SpriteAtlas.hpp" // Including type: UnityEngine.Sprite #include "UnityEngine/Sprite.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated method: UnityEngine.U2D.SpriteAtlas.CanBindTo bool UnityEngine::U2D::SpriteAtlas::CanBindTo(UnityEngine::Sprite* sprite) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::U2D::SpriteAtlas::CanBindTo"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "CanBindTo", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(sprite)}))); return ::il2cpp_utils::RunMethodThrow<bool, false>(this, ___internal__method, sprite); } // Autogenerated method: UnityEngine.U2D.SpriteAtlas.GetSprite UnityEngine::Sprite* UnityEngine::U2D::SpriteAtlas::GetSprite(::Il2CppString* name) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::U2D::SpriteAtlas::GetSprite"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "GetSprite", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(name)}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Sprite*, false>(this, ___internal__method, name); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes // Including type: UnityEngine.Profiling.Profiler #include "UnityEngine/Profiling/Profiler.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated method: UnityEngine.Profiling.Profiler.GetMonoUsedSizeLong int64_t UnityEngine::Profiling::Profiler::GetMonoUsedSizeLong() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Profiling::Profiler::GetMonoUsedSizeLong"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.Profiling", "Profiler", "GetMonoUsedSizeLong", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<int64_t, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes // Including type: UnityEngine.Profiling.Experimental.DebugScreenCapture #include "UnityEngine/Profiling/Experimental/DebugScreenCapture.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated method: UnityEngine.Profiling.Experimental.DebugScreenCapture.set_rawImageDataReference void UnityEngine::Profiling::Experimental::DebugScreenCapture::set_rawImageDataReference(Unity::Collections::NativeArray_1<uint8_t> value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Profiling::Experimental::DebugScreenCapture::set_rawImageDataReference"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(*this, "set_rawImageDataReference", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)}))); ::il2cpp_utils::RunMethodThrow<void, false>(*this, ___internal__method, value); } // Autogenerated method: UnityEngine.Profiling.Experimental.DebugScreenCapture.set_imageFormat void UnityEngine::Profiling::Experimental::DebugScreenCapture::set_imageFormat(UnityEngine::TextureFormat value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Profiling::Experimental::DebugScreenCapture::set_imageFormat"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(*this, "set_imageFormat", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)}))); ::il2cpp_utils::RunMethodThrow<void, false>(*this, ___internal__method, value); } // Autogenerated method: UnityEngine.Profiling.Experimental.DebugScreenCapture.set_width void UnityEngine::Profiling::Experimental::DebugScreenCapture::set_width(int value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Profiling::Experimental::DebugScreenCapture::set_width"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(*this, "set_width", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)}))); ::il2cpp_utils::RunMethodThrow<void, false>(*this, ___internal__method, value); } // Autogenerated method: UnityEngine.Profiling.Experimental.DebugScreenCapture.set_height void UnityEngine::Profiling::Experimental::DebugScreenCapture::set_height(int value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Profiling::Experimental::DebugScreenCapture::set_height"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(*this, "set_height", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)}))); ::il2cpp_utils::RunMethodThrow<void, false>(*this, ___internal__method, value); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: UnityEngine.Profiling.Memory.Experimental.MetaData #include "UnityEngine/Profiling/Memory/Experimental/MetaData.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: UnityEngine.Profiling.Memory.Experimental.MemoryProfiler #include "UnityEngine/Profiling/Memory/Experimental/MemoryProfiler.hpp" // Including type: System.Action`2 #include "System/Action_2.hpp" // Including type: System.Action`3 #include "System/Action_3.hpp" // Including type: System.Action`1 #include "System/Action_1.hpp" // Including type: UnityEngine.Profiling.Memory.Experimental.MetaData #include "UnityEngine/Profiling/Memory/Experimental/MetaData.hpp" // Including type: System.IntPtr #include "System/IntPtr.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // [DebuggerBrowsableAttribute] Offset: 0xD94030 // [CompilerGeneratedAttribute] Offset: 0xD94030 // Autogenerated static field getter // Get static field: static private System.Action`2<System.String,System.Boolean> m_SnapshotFinished System::Action_2<::Il2CppString*, bool>* UnityEngine::Profiling::Memory::Experimental::MemoryProfiler::_get_m_SnapshotFinished() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Profiling::Memory::Experimental::MemoryProfiler::_get_m_SnapshotFinished"); return THROW_UNLESS((il2cpp_utils::GetFieldValue<System::Action_2<::Il2CppString*, bool>*>("UnityEngine.Profiling.Memory.Experimental", "MemoryProfiler", "m_SnapshotFinished"))); } // Autogenerated static field setter // Set static field: static private System.Action`2<System.String,System.Boolean> m_SnapshotFinished void UnityEngine::Profiling::Memory::Experimental::MemoryProfiler::_set_m_SnapshotFinished(System::Action_2<::Il2CppString*, bool>* value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Profiling::Memory::Experimental::MemoryProfiler::_set_m_SnapshotFinished"); THROW_UNLESS(il2cpp_utils::SetFieldValue("UnityEngine.Profiling.Memory.Experimental", "MemoryProfiler", "m_SnapshotFinished", value)); } // [CompilerGeneratedAttribute] Offset: 0xD9406C // [DebuggerBrowsableAttribute] Offset: 0xD9406C // Autogenerated static field getter // Get static field: static private System.Action`3<System.String,System.Boolean,UnityEngine.Profiling.Experimental.DebugScreenCapture> m_SaveScreenshotToDisk System::Action_3<::Il2CppString*, bool, UnityEngine::Profiling::Experimental::DebugScreenCapture>* UnityEngine::Profiling::Memory::Experimental::MemoryProfiler::_get_m_SaveScreenshotToDisk() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Profiling::Memory::Experimental::MemoryProfiler::_get_m_SaveScreenshotToDisk"); return THROW_UNLESS((il2cpp_utils::GetFieldValue<System::Action_3<::Il2CppString*, bool, UnityEngine::Profiling::Experimental::DebugScreenCapture>*>("UnityEngine.Profiling.Memory.Experimental", "MemoryProfiler", "m_SaveScreenshotToDisk"))); } // Autogenerated static field setter // Set static field: static private System.Action`3<System.String,System.Boolean,UnityEngine.Profiling.Experimental.DebugScreenCapture> m_SaveScreenshotToDisk void UnityEngine::Profiling::Memory::Experimental::MemoryProfiler::_set_m_SaveScreenshotToDisk(System::Action_3<::Il2CppString*, bool, UnityEngine::Profiling::Experimental::DebugScreenCapture>* value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Profiling::Memory::Experimental::MemoryProfiler::_set_m_SaveScreenshotToDisk"); THROW_UNLESS(il2cpp_utils::SetFieldValue("UnityEngine.Profiling.Memory.Experimental", "MemoryProfiler", "m_SaveScreenshotToDisk", value)); } // [CompilerGeneratedAttribute] Offset: 0xD940A8 // [DebuggerBrowsableAttribute] Offset: 0xD940A8 // Autogenerated static field getter // Get static field: static private System.Action`1<UnityEngine.Profiling.Memory.Experimental.MetaData> createMetaData System::Action_1<UnityEngine::Profiling::Memory::Experimental::MetaData*>* UnityEngine::Profiling::Memory::Experimental::MemoryProfiler::_get_createMetaData() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Profiling::Memory::Experimental::MemoryProfiler::_get_createMetaData"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<System::Action_1<UnityEngine::Profiling::Memory::Experimental::MetaData*>*>("UnityEngine.Profiling.Memory.Experimental", "MemoryProfiler", "createMetaData")); } // Autogenerated static field setter // Set static field: static private System.Action`1<UnityEngine.Profiling.Memory.Experimental.MetaData> createMetaData void UnityEngine::Profiling::Memory::Experimental::MemoryProfiler::_set_createMetaData(System::Action_1<UnityEngine::Profiling::Memory::Experimental::MetaData*>* value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Profiling::Memory::Experimental::MemoryProfiler::_set_createMetaData"); THROW_UNLESS(il2cpp_utils::SetFieldValue("UnityEngine.Profiling.Memory.Experimental", "MemoryProfiler", "createMetaData", value)); } // Autogenerated method: UnityEngine.Profiling.Memory.Experimental.MemoryProfiler.PrepareMetadata ::Array<uint8_t>* UnityEngine::Profiling::Memory::Experimental::MemoryProfiler::PrepareMetadata() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Profiling::Memory::Experimental::MemoryProfiler::PrepareMetadata"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.Profiling.Memory.Experimental", "MemoryProfiler", "PrepareMetadata", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<::Array<uint8_t>*, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method); } // Autogenerated method: UnityEngine.Profiling.Memory.Experimental.MemoryProfiler.WriteIntToByteArray int UnityEngine::Profiling::Memory::Experimental::MemoryProfiler::WriteIntToByteArray(::Array<uint8_t>* array, int offset, int value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Profiling::Memory::Experimental::MemoryProfiler::WriteIntToByteArray"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.Profiling.Memory.Experimental", "MemoryProfiler", "WriteIntToByteArray", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(array), ::il2cpp_utils::ExtractType(offset), ::il2cpp_utils::ExtractType(value)}))); return ::il2cpp_utils::RunMethodThrow<int, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, array, offset, value); } // Autogenerated method: UnityEngine.Profiling.Memory.Experimental.MemoryProfiler.WriteStringToByteArray int UnityEngine::Profiling::Memory::Experimental::MemoryProfiler::WriteStringToByteArray(::Array<uint8_t>* array, int offset, ::Il2CppString* value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Profiling::Memory::Experimental::MemoryProfiler::WriteStringToByteArray"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.Profiling.Memory.Experimental", "MemoryProfiler", "WriteStringToByteArray", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(array), ::il2cpp_utils::ExtractType(offset), ::il2cpp_utils::ExtractType(value)}))); return ::il2cpp_utils::RunMethodThrow<int, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, array, offset, value); } // Autogenerated method: UnityEngine.Profiling.Memory.Experimental.MemoryProfiler.FinalizeSnapshot void UnityEngine::Profiling::Memory::Experimental::MemoryProfiler::FinalizeSnapshot(::Il2CppString* path, bool result) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Profiling::Memory::Experimental::MemoryProfiler::FinalizeSnapshot"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.Profiling.Memory.Experimental", "MemoryProfiler", "FinalizeSnapshot", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(path), ::il2cpp_utils::ExtractType(result)}))); ::il2cpp_utils::RunMethodThrow<void, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, path, result); } // Autogenerated method: UnityEngine.Profiling.Memory.Experimental.MemoryProfiler.SaveScreenshotToDisk void UnityEngine::Profiling::Memory::Experimental::MemoryProfiler::SaveScreenshotToDisk(::Il2CppString* path, bool result, System::IntPtr pixelsPtr, int pixelsCount, UnityEngine::TextureFormat format, int width, int height) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Profiling::Memory::Experimental::MemoryProfiler::SaveScreenshotToDisk"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.Profiling.Memory.Experimental", "MemoryProfiler", "SaveScreenshotToDisk", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(path), ::il2cpp_utils::ExtractType(result), ::il2cpp_utils::ExtractType(pixelsPtr), ::il2cpp_utils::ExtractType(pixelsCount), ::il2cpp_utils::ExtractType(format), ::il2cpp_utils::ExtractType(width), ::il2cpp_utils::ExtractType(height)}))); ::il2cpp_utils::RunMethodThrow<void, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, path, result, pixelsPtr, pixelsCount, format, width, height); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes // Including type: UnityEngine.Events.PersistentListenerMode #include "UnityEngine/Events/PersistentListenerMode.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated static field getter // Get static field: static public UnityEngine.Events.PersistentListenerMode EventDefined UnityEngine::Events::PersistentListenerMode UnityEngine::Events::PersistentListenerMode::_get_EventDefined() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Events::PersistentListenerMode::_get_EventDefined"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<UnityEngine::Events::PersistentListenerMode>("UnityEngine.Events", "PersistentListenerMode", "EventDefined")); } // Autogenerated static field setter // Set static field: static public UnityEngine.Events.PersistentListenerMode EventDefined void UnityEngine::Events::PersistentListenerMode::_set_EventDefined(UnityEngine::Events::PersistentListenerMode value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Events::PersistentListenerMode::_set_EventDefined"); THROW_UNLESS(il2cpp_utils::SetFieldValue("UnityEngine.Events", "PersistentListenerMode", "EventDefined", value)); } // Autogenerated static field getter // Get static field: static public UnityEngine.Events.PersistentListenerMode Void UnityEngine::Events::PersistentListenerMode UnityEngine::Events::PersistentListenerMode::_get_Void() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Events::PersistentListenerMode::_get_Void"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<UnityEngine::Events::PersistentListenerMode>("UnityEngine.Events", "PersistentListenerMode", "Void")); } // Autogenerated static field setter // Set static field: static public UnityEngine.Events.PersistentListenerMode Void void UnityEngine::Events::PersistentListenerMode::_set_Void(UnityEngine::Events::PersistentListenerMode value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Events::PersistentListenerMode::_set_Void"); THROW_UNLESS(il2cpp_utils::SetFieldValue("UnityEngine.Events", "PersistentListenerMode", "Void", value)); } // Autogenerated static field getter // Get static field: static public UnityEngine.Events.PersistentListenerMode Object UnityEngine::Events::PersistentListenerMode UnityEngine::Events::PersistentListenerMode::_get_Object() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Events::PersistentListenerMode::_get_Object"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<UnityEngine::Events::PersistentListenerMode>("UnityEngine.Events", "PersistentListenerMode", "Object")); } // Autogenerated static field setter // Set static field: static public UnityEngine.Events.PersistentListenerMode Object void UnityEngine::Events::PersistentListenerMode::_set_Object(UnityEngine::Events::PersistentListenerMode value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Events::PersistentListenerMode::_set_Object"); THROW_UNLESS(il2cpp_utils::SetFieldValue("UnityEngine.Events", "PersistentListenerMode", "Object", value)); } // Autogenerated static field getter // Get static field: static public UnityEngine.Events.PersistentListenerMode Int UnityEngine::Events::PersistentListenerMode UnityEngine::Events::PersistentListenerMode::_get_Int() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Events::PersistentListenerMode::_get_Int"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<UnityEngine::Events::PersistentListenerMode>("UnityEngine.Events", "PersistentListenerMode", "Int")); } // Autogenerated static field setter // Set static field: static public UnityEngine.Events.PersistentListenerMode Int void UnityEngine::Events::PersistentListenerMode::_set_Int(UnityEngine::Events::PersistentListenerMode value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Events::PersistentListenerMode::_set_Int"); THROW_UNLESS(il2cpp_utils::SetFieldValue("UnityEngine.Events", "PersistentListenerMode", "Int", value)); } // Autogenerated static field getter // Get static field: static public UnityEngine.Events.PersistentListenerMode Float UnityEngine::Events::PersistentListenerMode UnityEngine::Events::PersistentListenerMode::_get_Float() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Events::PersistentListenerMode::_get_Float"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<UnityEngine::Events::PersistentListenerMode>("UnityEngine.Events", "PersistentListenerMode", "Float")); } // Autogenerated static field setter // Set static field: static public UnityEngine.Events.PersistentListenerMode Float void UnityEngine::Events::PersistentListenerMode::_set_Float(UnityEngine::Events::PersistentListenerMode value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Events::PersistentListenerMode::_set_Float"); THROW_UNLESS(il2cpp_utils::SetFieldValue("UnityEngine.Events", "PersistentListenerMode", "Float", value)); } // Autogenerated static field getter // Get static field: static public UnityEngine.Events.PersistentListenerMode String UnityEngine::Events::PersistentListenerMode UnityEngine::Events::PersistentListenerMode::_get_String() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Events::PersistentListenerMode::_get_String"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<UnityEngine::Events::PersistentListenerMode>("UnityEngine.Events", "PersistentListenerMode", "String")); } // Autogenerated static field setter // Set static field: static public UnityEngine.Events.PersistentListenerMode String void UnityEngine::Events::PersistentListenerMode::_set_String(UnityEngine::Events::PersistentListenerMode value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Events::PersistentListenerMode::_set_String"); THROW_UNLESS(il2cpp_utils::SetFieldValue("UnityEngine.Events", "PersistentListenerMode", "String", value)); } // Autogenerated static field getter // Get static field: static public UnityEngine.Events.PersistentListenerMode Bool UnityEngine::Events::PersistentListenerMode UnityEngine::Events::PersistentListenerMode::_get_Bool() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Events::PersistentListenerMode::_get_Bool"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<UnityEngine::Events::PersistentListenerMode>("UnityEngine.Events", "PersistentListenerMode", "Bool")); } // Autogenerated static field setter // Set static field: static public UnityEngine.Events.PersistentListenerMode Bool void UnityEngine::Events::PersistentListenerMode::_set_Bool(UnityEngine::Events::PersistentListenerMode value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Events::PersistentListenerMode::_set_Bool"); THROW_UNLESS(il2cpp_utils::SetFieldValue("UnityEngine.Events", "PersistentListenerMode", "Bool", value)); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: UnityEngine.Events.ArgumentCache #include "UnityEngine/Events/ArgumentCache.hpp" // Including type: UnityEngine.Object #include "UnityEngine/Object.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated method: UnityEngine.Events.ArgumentCache.get_unityObjectArgument UnityEngine::Object* UnityEngine::Events::ArgumentCache::get_unityObjectArgument() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Events::ArgumentCache::get_unityObjectArgument"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_unityObjectArgument", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Object*, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Events.ArgumentCache.get_unityObjectArgumentAssemblyTypeName ::Il2CppString* UnityEngine::Events::ArgumentCache::get_unityObjectArgumentAssemblyTypeName() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Events::ArgumentCache::get_unityObjectArgumentAssemblyTypeName"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_unityObjectArgumentAssemblyTypeName", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<::Il2CppString*, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Events.ArgumentCache.get_intArgument int UnityEngine::Events::ArgumentCache::get_intArgument() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Events::ArgumentCache::get_intArgument"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_intArgument", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<int, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Events.ArgumentCache.get_floatArgument float UnityEngine::Events::ArgumentCache::get_floatArgument() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Events::ArgumentCache::get_floatArgument"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_floatArgument", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<float, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Events.ArgumentCache.get_stringArgument ::Il2CppString* UnityEngine::Events::ArgumentCache::get_stringArgument() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Events::ArgumentCache::get_stringArgument"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_stringArgument", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<::Il2CppString*, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Events.ArgumentCache.get_boolArgument bool UnityEngine::Events::ArgumentCache::get_boolArgument() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Events::ArgumentCache::get_boolArgument"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_boolArgument", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<bool, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Events.ArgumentCache.TidyAssemblyTypeName void UnityEngine::Events::ArgumentCache::TidyAssemblyTypeName() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Events::ArgumentCache::TidyAssemblyTypeName"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "TidyAssemblyTypeName", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Events.ArgumentCache.OnBeforeSerialize void UnityEngine::Events::ArgumentCache::OnBeforeSerialize() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Events::ArgumentCache::OnBeforeSerialize"); auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "OnBeforeSerialize", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Events.ArgumentCache.OnAfterDeserialize void UnityEngine::Events::ArgumentCache::OnAfterDeserialize() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Events::ArgumentCache::OnAfterDeserialize"); auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "OnAfterDeserialize", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: UnityEngine.Events.BaseInvokableCall #include "UnityEngine/Events/BaseInvokableCall.hpp" // Including type: System.Reflection.MethodInfo #include "System/Reflection/MethodInfo.hpp" // Including type: System.Delegate #include "System/Delegate.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated method: UnityEngine.Events.BaseInvokableCall.Invoke void UnityEngine::Events::BaseInvokableCall::Invoke(::Array<::Il2CppObject*>* args) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Events::BaseInvokableCall::Invoke"); auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Invoke", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(args)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, args); } // Autogenerated method: UnityEngine.Events.BaseInvokableCall.AllowInvoke bool UnityEngine::Events::BaseInvokableCall::AllowInvoke(System::Delegate* delegate) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Events::BaseInvokableCall::AllowInvoke"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.Events", "BaseInvokableCall", "AllowInvoke", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(delegate)}))); return ::il2cpp_utils::RunMethodThrow<bool, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, delegate); } // Autogenerated method: UnityEngine.Events.BaseInvokableCall.Find bool UnityEngine::Events::BaseInvokableCall::Find(::Il2CppObject* targetObj, System::Reflection::MethodInfo* method) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Events::BaseInvokableCall::Find"); auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Find", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(targetObj), ::il2cpp_utils::ExtractType(method)}))); return ::il2cpp_utils::RunMethodThrow<bool, false>(this, ___internal__method, targetObj, method); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: UnityEngine.Events.InvokableCall #include "UnityEngine/Events/InvokableCall.hpp" // Including type: UnityEngine.Events.UnityAction #include "UnityEngine/Events/UnityAction.hpp" // Including type: System.Reflection.MethodInfo #include "System/Reflection/MethodInfo.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated method: UnityEngine.Events.InvokableCall.add_Delegate void UnityEngine::Events::InvokableCall::add_Delegate(UnityEngine::Events::UnityAction* value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Events::InvokableCall::add_Delegate"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "add_Delegate", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, value); } // Autogenerated method: UnityEngine.Events.InvokableCall.remove_Delegate void UnityEngine::Events::InvokableCall::remove_Delegate(UnityEngine::Events::UnityAction* value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Events::InvokableCall::remove_Delegate"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "remove_Delegate", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, value); } // Autogenerated method: UnityEngine.Events.InvokableCall.Invoke void UnityEngine::Events::InvokableCall::Invoke() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Events::InvokableCall::Invoke"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Invoke", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Events.InvokableCall.Invoke void UnityEngine::Events::InvokableCall::Invoke(::Array<::Il2CppObject*>* args) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Events::InvokableCall::Invoke"); auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Invoke", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(args)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, args); } // Autogenerated method: UnityEngine.Events.InvokableCall.Find bool UnityEngine::Events::InvokableCall::Find(::Il2CppObject* targetObj, System::Reflection::MethodInfo* method) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Events::InvokableCall::Find"); auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Find", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(targetObj), ::il2cpp_utils::ExtractType(method)}))); return ::il2cpp_utils::RunMethodThrow<bool, false>(this, ___internal__method, targetObj, method); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes // Including type: UnityEngine.Events.UnityEventCallState #include "UnityEngine/Events/UnityEventCallState.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated static field getter // Get static field: static public UnityEngine.Events.UnityEventCallState Off UnityEngine::Events::UnityEventCallState UnityEngine::Events::UnityEventCallState::_get_Off() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Events::UnityEventCallState::_get_Off"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<UnityEngine::Events::UnityEventCallState>("UnityEngine.Events", "UnityEventCallState", "Off")); } // Autogenerated static field setter // Set static field: static public UnityEngine.Events.UnityEventCallState Off void UnityEngine::Events::UnityEventCallState::_set_Off(UnityEngine::Events::UnityEventCallState value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Events::UnityEventCallState::_set_Off"); THROW_UNLESS(il2cpp_utils::SetFieldValue("UnityEngine.Events", "UnityEventCallState", "Off", value)); } // Autogenerated static field getter // Get static field: static public UnityEngine.Events.UnityEventCallState EditorAndRuntime UnityEngine::Events::UnityEventCallState UnityEngine::Events::UnityEventCallState::_get_EditorAndRuntime() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Events::UnityEventCallState::_get_EditorAndRuntime"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<UnityEngine::Events::UnityEventCallState>("UnityEngine.Events", "UnityEventCallState", "EditorAndRuntime")); } // Autogenerated static field setter // Set static field: static public UnityEngine.Events.UnityEventCallState EditorAndRuntime void UnityEngine::Events::UnityEventCallState::_set_EditorAndRuntime(UnityEngine::Events::UnityEventCallState value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Events::UnityEventCallState::_set_EditorAndRuntime"); THROW_UNLESS(il2cpp_utils::SetFieldValue("UnityEngine.Events", "UnityEventCallState", "EditorAndRuntime", value)); } // Autogenerated static field getter // Get static field: static public UnityEngine.Events.UnityEventCallState RuntimeOnly UnityEngine::Events::UnityEventCallState UnityEngine::Events::UnityEventCallState::_get_RuntimeOnly() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Events::UnityEventCallState::_get_RuntimeOnly"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<UnityEngine::Events::UnityEventCallState>("UnityEngine.Events", "UnityEventCallState", "RuntimeOnly")); } // Autogenerated static field setter // Set static field: static public UnityEngine.Events.UnityEventCallState RuntimeOnly void UnityEngine::Events::UnityEventCallState::_set_RuntimeOnly(UnityEngine::Events::UnityEventCallState value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Events::UnityEventCallState::_set_RuntimeOnly"); THROW_UNLESS(il2cpp_utils::SetFieldValue("UnityEngine.Events", "UnityEventCallState", "RuntimeOnly", value)); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: UnityEngine.Events.PersistentCall #include "UnityEngine/Events/PersistentCall.hpp" // Including type: UnityEngine.Object #include "UnityEngine/Object.hpp" // Including type: UnityEngine.Events.ArgumentCache #include "UnityEngine/Events/ArgumentCache.hpp" // Including type: UnityEngine.Events.BaseInvokableCall #include "UnityEngine/Events/BaseInvokableCall.hpp" // Including type: UnityEngine.Events.UnityEventBase #include "UnityEngine/Events/UnityEventBase.hpp" // Including type: System.Reflection.MethodInfo #include "System/Reflection/MethodInfo.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated method: UnityEngine.Events.PersistentCall.get_target UnityEngine::Object* UnityEngine::Events::PersistentCall::get_target() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Events::PersistentCall::get_target"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_target", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Object*, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Events.PersistentCall.get_methodName ::Il2CppString* UnityEngine::Events::PersistentCall::get_methodName() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Events::PersistentCall::get_methodName"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_methodName", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<::Il2CppString*, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Events.PersistentCall.get_mode UnityEngine::Events::PersistentListenerMode UnityEngine::Events::PersistentCall::get_mode() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Events::PersistentCall::get_mode"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_mode", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Events::PersistentListenerMode, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Events.PersistentCall.get_arguments UnityEngine::Events::ArgumentCache* UnityEngine::Events::PersistentCall::get_arguments() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Events::PersistentCall::get_arguments"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_arguments", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Events::ArgumentCache*, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Events.PersistentCall.IsValid bool UnityEngine::Events::PersistentCall::IsValid() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Events::PersistentCall::IsValid"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "IsValid", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<bool, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Events.PersistentCall.GetRuntimeCall UnityEngine::Events::BaseInvokableCall* UnityEngine::Events::PersistentCall::GetRuntimeCall(UnityEngine::Events::UnityEventBase* theEvent) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Events::PersistentCall::GetRuntimeCall"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "GetRuntimeCall", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(theEvent)}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Events::BaseInvokableCall*, false>(this, ___internal__method, theEvent); } // Autogenerated method: UnityEngine.Events.PersistentCall.GetObjectCall UnityEngine::Events::BaseInvokableCall* UnityEngine::Events::PersistentCall::GetObjectCall(UnityEngine::Object* target, System::Reflection::MethodInfo* method, UnityEngine::Events::ArgumentCache* arguments) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Events::PersistentCall::GetObjectCall"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.Events", "PersistentCall", "GetObjectCall", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(target), ::il2cpp_utils::ExtractType(method), ::il2cpp_utils::ExtractType(arguments)}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Events::BaseInvokableCall*, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, target, method, arguments); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes // Including type: UnityEngine.Events.PersistentCallGroup #include "UnityEngine/Events/PersistentCallGroup.hpp" // Including type: System.Collections.Generic.List`1 #include "System/Collections/Generic/List_1.hpp" // Including type: UnityEngine.Events.PersistentCall #include "UnityEngine/Events/PersistentCall.hpp" // Including type: UnityEngine.Events.InvokableCallList #include "UnityEngine/Events/InvokableCallList.hpp" // Including type: UnityEngine.Events.UnityEventBase #include "UnityEngine/Events/UnityEventBase.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated method: UnityEngine.Events.PersistentCallGroup.Initialize void UnityEngine::Events::PersistentCallGroup::Initialize(UnityEngine::Events::InvokableCallList* invokableList, UnityEngine::Events::UnityEventBase* unityEventBase) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Events::PersistentCallGroup::Initialize"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Initialize", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(invokableList), ::il2cpp_utils::ExtractType(unityEventBase)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, invokableList, unityEventBase); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: UnityEngine.Events.InvokableCallList #include "UnityEngine/Events/InvokableCallList.hpp" // Including type: System.Collections.Generic.List`1 #include "System/Collections/Generic/List_1.hpp" // Including type: UnityEngine.Events.BaseInvokableCall #include "UnityEngine/Events/BaseInvokableCall.hpp" // Including type: System.Reflection.MethodInfo #include "System/Reflection/MethodInfo.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated method: UnityEngine.Events.InvokableCallList.AddPersistentInvokableCall void UnityEngine::Events::InvokableCallList::AddPersistentInvokableCall(UnityEngine::Events::BaseInvokableCall* call) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Events::InvokableCallList::AddPersistentInvokableCall"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "AddPersistentInvokableCall", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(call)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, call); } // Autogenerated method: UnityEngine.Events.InvokableCallList.AddListener void UnityEngine::Events::InvokableCallList::AddListener(UnityEngine::Events::BaseInvokableCall* call) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Events::InvokableCallList::AddListener"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "AddListener", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(call)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, call); } // Autogenerated method: UnityEngine.Events.InvokableCallList.RemoveListener void UnityEngine::Events::InvokableCallList::RemoveListener(::Il2CppObject* targetObj, System::Reflection::MethodInfo* method) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Events::InvokableCallList::RemoveListener"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "RemoveListener", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(targetObj), ::il2cpp_utils::ExtractType(method)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, targetObj, method); } // Autogenerated method: UnityEngine.Events.InvokableCallList.ClearPersistent void UnityEngine::Events::InvokableCallList::ClearPersistent() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Events::InvokableCallList::ClearPersistent"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "ClearPersistent", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Events.InvokableCallList.PrepareInvoke System::Collections::Generic::List_1<UnityEngine::Events::BaseInvokableCall*>* UnityEngine::Events::InvokableCallList::PrepareInvoke() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Events::InvokableCallList::PrepareInvoke"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "PrepareInvoke", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<System::Collections::Generic::List_1<UnityEngine::Events::BaseInvokableCall*>*, false>(this, ___internal__method); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: UnityEngine.Events.UnityEventBase #include "UnityEngine/Events/UnityEventBase.hpp" // Including type: UnityEngine.Events.InvokableCallList #include "UnityEngine/Events/InvokableCallList.hpp" // Including type: UnityEngine.Events.PersistentCallGroup #include "UnityEngine/Events/PersistentCallGroup.hpp" // Including type: System.Reflection.MethodInfo #include "System/Reflection/MethodInfo.hpp" // Including type: UnityEngine.Events.BaseInvokableCall #include "UnityEngine/Events/BaseInvokableCall.hpp" // Including type: UnityEngine.Events.PersistentCall #include "UnityEngine/Events/PersistentCall.hpp" // Including type: UnityEngine.Events.PersistentListenerMode #include "UnityEngine/Events/PersistentListenerMode.hpp" // Including type: System.Type #include "System/Type.hpp" // Including type: System.Collections.Generic.List`1 #include "System/Collections/Generic/List_1.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated method: UnityEngine.Events.UnityEventBase.UnityEngine.ISerializationCallbackReceiver.OnBeforeSerialize void UnityEngine::Events::UnityEventBase::UnityEngine_ISerializationCallbackReceiver_OnBeforeSerialize() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Events::UnityEventBase::UnityEngine.ISerializationCallbackReceiver.OnBeforeSerialize"); auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "UnityEngine.ISerializationCallbackReceiver.OnBeforeSerialize", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Events.UnityEventBase.UnityEngine.ISerializationCallbackReceiver.OnAfterDeserialize void UnityEngine::Events::UnityEventBase::UnityEngine_ISerializationCallbackReceiver_OnAfterDeserialize() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Events::UnityEventBase::UnityEngine.ISerializationCallbackReceiver.OnAfterDeserialize"); auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "UnityEngine.ISerializationCallbackReceiver.OnAfterDeserialize", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Events.UnityEventBase.FindMethod_Impl System::Reflection::MethodInfo* UnityEngine::Events::UnityEventBase::FindMethod_Impl(::Il2CppString* name, ::Il2CppObject* targetObj) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Events::UnityEventBase::FindMethod_Impl"); auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "FindMethod_Impl", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(name), ::il2cpp_utils::ExtractType(targetObj)}))); return ::il2cpp_utils::RunMethodThrow<System::Reflection::MethodInfo*, false>(this, ___internal__method, name, targetObj); } // Autogenerated method: UnityEngine.Events.UnityEventBase.GetDelegate UnityEngine::Events::BaseInvokableCall* UnityEngine::Events::UnityEventBase::GetDelegate(::Il2CppObject* target, System::Reflection::MethodInfo* theFunction) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Events::UnityEventBase::GetDelegate"); auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "GetDelegate", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(target), ::il2cpp_utils::ExtractType(theFunction)}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Events::BaseInvokableCall*, false>(this, ___internal__method, target, theFunction); } // Autogenerated method: UnityEngine.Events.UnityEventBase.FindMethod System::Reflection::MethodInfo* UnityEngine::Events::UnityEventBase::FindMethod(UnityEngine::Events::PersistentCall* call) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Events::UnityEventBase::FindMethod"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "FindMethod", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(call)}))); return ::il2cpp_utils::RunMethodThrow<System::Reflection::MethodInfo*, false>(this, ___internal__method, call); } // Autogenerated method: UnityEngine.Events.UnityEventBase.FindMethod System::Reflection::MethodInfo* UnityEngine::Events::UnityEventBase::FindMethod(::Il2CppString* name, ::Il2CppObject* listener, UnityEngine::Events::PersistentListenerMode mode, System::Type* argumentType) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Events::UnityEventBase::FindMethod"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "FindMethod", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(name), ::il2cpp_utils::ExtractType(listener), ::il2cpp_utils::ExtractType(mode), ::il2cpp_utils::ExtractType(argumentType)}))); return ::il2cpp_utils::RunMethodThrow<System::Reflection::MethodInfo*, false>(this, ___internal__method, name, listener, mode, argumentType); } // Autogenerated method: UnityEngine.Events.UnityEventBase.DirtyPersistentCalls void UnityEngine::Events::UnityEventBase::DirtyPersistentCalls() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Events::UnityEventBase::DirtyPersistentCalls"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "DirtyPersistentCalls", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Events.UnityEventBase.RebuildPersistentCallsIfNeeded void UnityEngine::Events::UnityEventBase::RebuildPersistentCallsIfNeeded() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Events::UnityEventBase::RebuildPersistentCallsIfNeeded"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "RebuildPersistentCallsIfNeeded", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Events.UnityEventBase.AddCall void UnityEngine::Events::UnityEventBase::AddCall(UnityEngine::Events::BaseInvokableCall* call) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Events::UnityEventBase::AddCall"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "AddCall", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(call)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, call); } // Autogenerated method: UnityEngine.Events.UnityEventBase.RemoveListener void UnityEngine::Events::UnityEventBase::RemoveListener(::Il2CppObject* targetObj, System::Reflection::MethodInfo* method) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Events::UnityEventBase::RemoveListener"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "RemoveListener", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(targetObj), ::il2cpp_utils::ExtractType(method)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, targetObj, method); } // Autogenerated method: UnityEngine.Events.UnityEventBase.PrepareInvoke System::Collections::Generic::List_1<UnityEngine::Events::BaseInvokableCall*>* UnityEngine::Events::UnityEventBase::PrepareInvoke() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Events::UnityEventBase::PrepareInvoke"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "PrepareInvoke", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<System::Collections::Generic::List_1<UnityEngine::Events::BaseInvokableCall*>*, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Events.UnityEventBase.GetValidMethodInfo System::Reflection::MethodInfo* UnityEngine::Events::UnityEventBase::GetValidMethodInfo(::Il2CppObject* obj, ::Il2CppString* functionName, ::Array<System::Type*>* argumentTypes) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Events::UnityEventBase::GetValidMethodInfo"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.Events", "UnityEventBase", "GetValidMethodInfo", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(obj), ::il2cpp_utils::ExtractType(functionName), ::il2cpp_utils::ExtractType(argumentTypes)}))); return ::il2cpp_utils::RunMethodThrow<System::Reflection::MethodInfo*, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, obj, functionName, argumentTypes); } // Autogenerated method: UnityEngine.Events.UnityEventBase.ToString ::Il2CppString* UnityEngine::Events::UnityEventBase::ToString() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Events::UnityEventBase::ToString"); auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "ToString", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<::Il2CppString*, false>(this, ___internal__method); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: UnityEngine.Events.UnityAction #include "UnityEngine/Events/UnityAction.hpp" // Including type: System.IAsyncResult #include "System/IAsyncResult.hpp" // Including type: System.AsyncCallback #include "System/AsyncCallback.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated method: UnityEngine.Events.UnityAction.Invoke void UnityEngine::Events::UnityAction::Invoke() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Events::UnityAction::Invoke"); auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Invoke", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Events.UnityAction.BeginInvoke System::IAsyncResult* UnityEngine::Events::UnityAction::BeginInvoke(System::AsyncCallback* callback, ::Il2CppObject* object) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Events::UnityAction::BeginInvoke"); auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "BeginInvoke", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(callback), ::il2cpp_utils::ExtractType(object)}))); return ::il2cpp_utils::RunMethodThrow<System::IAsyncResult*, false>(this, ___internal__method, callback, object); } // Autogenerated method: UnityEngine.Events.UnityAction.EndInvoke void UnityEngine::Events::UnityAction::EndInvoke(System::IAsyncResult* result) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Events::UnityAction::EndInvoke"); auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "EndInvoke", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(result)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, result); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: UnityEngine.Events.UnityEvent #include "UnityEngine/Events/UnityEvent.hpp" // Including type: UnityEngine.Events.UnityAction #include "UnityEngine/Events/UnityAction.hpp" // Including type: UnityEngine.Events.BaseInvokableCall #include "UnityEngine/Events/BaseInvokableCall.hpp" // Including type: System.Reflection.MethodInfo #include "System/Reflection/MethodInfo.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated method: UnityEngine.Events.UnityEvent.AddListener void UnityEngine::Events::UnityEvent::AddListener(UnityEngine::Events::UnityAction* call) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Events::UnityEvent::AddListener"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "AddListener", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(call)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, call); } // Autogenerated method: UnityEngine.Events.UnityEvent.RemoveListener void UnityEngine::Events::UnityEvent::RemoveListener(UnityEngine::Events::UnityAction* call) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Events::UnityEvent::RemoveListener"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "RemoveListener", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(call)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, call); } // Autogenerated method: UnityEngine.Events.UnityEvent.GetDelegate UnityEngine::Events::BaseInvokableCall* UnityEngine::Events::UnityEvent::GetDelegate(UnityEngine::Events::UnityAction* action) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Events::UnityEvent::GetDelegate"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.Events", "UnityEvent", "GetDelegate", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(action)}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Events::BaseInvokableCall*, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, action); } // Autogenerated method: UnityEngine.Events.UnityEvent.Invoke void UnityEngine::Events::UnityEvent::Invoke() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Events::UnityEvent::Invoke"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Invoke", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Events.UnityEvent.FindMethod_Impl System::Reflection::MethodInfo* UnityEngine::Events::UnityEvent::FindMethod_Impl(::Il2CppString* name, ::Il2CppObject* targetObj) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Events::UnityEvent::FindMethod_Impl"); auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "FindMethod_Impl", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(name), ::il2cpp_utils::ExtractType(targetObj)}))); return ::il2cpp_utils::RunMethodThrow<System::Reflection::MethodInfo*, false>(this, ___internal__method, name, targetObj); } // Autogenerated method: UnityEngine.Events.UnityEvent.GetDelegate UnityEngine::Events::BaseInvokableCall* UnityEngine::Events::UnityEvent::GetDelegate(::Il2CppObject* target, System::Reflection::MethodInfo* theFunction) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Events::UnityEvent::GetDelegate"); auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "GetDelegate", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(target), ::il2cpp_utils::ExtractType(theFunction)}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Events::BaseInvokableCall*, false>(this, ___internal__method, target, theFunction); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: UnityEngine.Serialization.FormerlySerializedAsAttribute #include "UnityEngine/Serialization/FormerlySerializedAsAttribute.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes // Including type: UnityEngine.Scripting.GarbageCollector #include "UnityEngine/Scripting/GarbageCollector.hpp" // Including type: System.Action`1 #include "System/Action_1.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // [DebuggerBrowsableAttribute] Offset: 0xD945D4 // [CompilerGeneratedAttribute] Offset: 0xD945D4 // Autogenerated static field getter // Get static field: static private System.Action`1<UnityEngine.Scripting.GarbageCollector/Mode> GCModeChanged System::Action_1<UnityEngine::Scripting::GarbageCollector::Mode>* UnityEngine::Scripting::GarbageCollector::_get_GCModeChanged() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Scripting::GarbageCollector::_get_GCModeChanged"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<System::Action_1<UnityEngine::Scripting::GarbageCollector::Mode>*>("UnityEngine.Scripting", "GarbageCollector", "GCModeChanged")); } // Autogenerated static field setter // Set static field: static private System.Action`1<UnityEngine.Scripting.GarbageCollector/Mode> GCModeChanged void UnityEngine::Scripting::GarbageCollector::_set_GCModeChanged(System::Action_1<UnityEngine::Scripting::GarbageCollector::Mode>* value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Scripting::GarbageCollector::_set_GCModeChanged"); THROW_UNLESS(il2cpp_utils::SetFieldValue("UnityEngine.Scripting", "GarbageCollector", "GCModeChanged", value)); } // Autogenerated method: UnityEngine.Scripting.GarbageCollector.set_GCMode void UnityEngine::Scripting::GarbageCollector::set_GCMode(UnityEngine::Scripting::GarbageCollector::Mode value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Scripting::GarbageCollector::set_GCMode"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.Scripting", "GarbageCollector", "set_GCMode", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)}))); ::il2cpp_utils::RunMethodThrow<void, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, value); } // Autogenerated method: UnityEngine.Scripting.GarbageCollector.SetMode void UnityEngine::Scripting::GarbageCollector::SetMode(UnityEngine::Scripting::GarbageCollector::Mode mode) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Scripting::GarbageCollector::SetMode"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.Scripting", "GarbageCollector", "SetMode", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(mode)}))); ::il2cpp_utils::RunMethodThrow<void, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, mode); } // Autogenerated method: UnityEngine.Scripting.GarbageCollector.GetMode UnityEngine::Scripting::GarbageCollector::Mode UnityEngine::Scripting::GarbageCollector::GetMode() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Scripting::GarbageCollector::GetMode"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.Scripting", "GarbageCollector", "GetMode", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Scripting::GarbageCollector::Mode, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes // Including type: UnityEngine.Scripting.GarbageCollector/Mode #include "UnityEngine/Scripting/GarbageCollector.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated static field getter // Get static field: static public UnityEngine.Scripting.GarbageCollector/Mode Disabled UnityEngine::Scripting::GarbageCollector::Mode UnityEngine::Scripting::GarbageCollector::Mode::_get_Disabled() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Scripting::GarbageCollector::Mode::_get_Disabled"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<UnityEngine::Scripting::GarbageCollector::Mode>("UnityEngine.Scripting", "GarbageCollector/Mode", "Disabled")); } // Autogenerated static field setter // Set static field: static public UnityEngine.Scripting.GarbageCollector/Mode Disabled void UnityEngine::Scripting::GarbageCollector::Mode::_set_Disabled(UnityEngine::Scripting::GarbageCollector::Mode value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Scripting::GarbageCollector::Mode::_set_Disabled"); THROW_UNLESS(il2cpp_utils::SetFieldValue("UnityEngine.Scripting", "GarbageCollector/Mode", "Disabled", value)); } // Autogenerated static field getter // Get static field: static public UnityEngine.Scripting.GarbageCollector/Mode Enabled UnityEngine::Scripting::GarbageCollector::Mode UnityEngine::Scripting::GarbageCollector::Mode::_get_Enabled() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Scripting::GarbageCollector::Mode::_get_Enabled"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<UnityEngine::Scripting::GarbageCollector::Mode>("UnityEngine.Scripting", "GarbageCollector/Mode", "Enabled")); } // Autogenerated static field setter // Set static field: static public UnityEngine.Scripting.GarbageCollector/Mode Enabled void UnityEngine::Scripting::GarbageCollector::Mode::_set_Enabled(UnityEngine::Scripting::GarbageCollector::Mode value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Scripting::GarbageCollector::Mode::_set_Enabled"); THROW_UNLESS(il2cpp_utils::SetFieldValue("UnityEngine.Scripting", "GarbageCollector/Mode", "Enabled", value)); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes // Including type: UnityEngine.Scripting.PreserveAttribute #include "UnityEngine/Scripting/PreserveAttribute.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: UnityEngine.Scripting.APIUpdating.MovedFromAttributeData #include "UnityEngine/Scripting/APIUpdating/MovedFromAttributeData.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated method: UnityEngine.Scripting.APIUpdating.MovedFromAttributeData.Set void UnityEngine::Scripting::APIUpdating::MovedFromAttributeData::Set(bool autoUpdateAPI, ::Il2CppString* sourceNamespace, ::Il2CppString* sourceAssembly, ::Il2CppString* sourceClassName) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Scripting::APIUpdating::MovedFromAttributeData::Set"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(*this, "Set", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(autoUpdateAPI), ::il2cpp_utils::ExtractType(sourceNamespace), ::il2cpp_utils::ExtractType(sourceAssembly), ::il2cpp_utils::ExtractType(sourceClassName)}))); ::il2cpp_utils::RunMethodThrow<void, false>(*this, ___internal__method, autoUpdateAPI, sourceNamespace, sourceAssembly, sourceClassName); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: UnityEngine.Scripting.APIUpdating.MovedFromAttribute #include "UnityEngine/Scripting/APIUpdating/MovedFromAttribute.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: UnityEngine.SceneManagement.Scene #include "UnityEngine/SceneManagement/Scene.hpp" // Including type: UnityEngine.GameObject #include "UnityEngine/GameObject.hpp" // Including type: System.Collections.Generic.List`1 #include "System/Collections/Generic/List_1.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated method: UnityEngine.SceneManagement.Scene.IsValidInternal bool UnityEngine::SceneManagement::Scene::IsValidInternal(int sceneHandle) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::Scene::IsValidInternal"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.SceneManagement", "Scene", "IsValidInternal", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(sceneHandle)}))); return ::il2cpp_utils::RunMethodThrow<bool, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, sceneHandle); } // Autogenerated method: UnityEngine.SceneManagement.Scene.GetNameInternal ::Il2CppString* UnityEngine::SceneManagement::Scene::GetNameInternal(int sceneHandle) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::Scene::GetNameInternal"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.SceneManagement", "Scene", "GetNameInternal", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(sceneHandle)}))); return ::il2cpp_utils::RunMethodThrow<::Il2CppString*, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, sceneHandle); } // Autogenerated method: UnityEngine.SceneManagement.Scene.GetIsLoadedInternal bool UnityEngine::SceneManagement::Scene::GetIsLoadedInternal(int sceneHandle) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::Scene::GetIsLoadedInternal"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.SceneManagement", "Scene", "GetIsLoadedInternal", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(sceneHandle)}))); return ::il2cpp_utils::RunMethodThrow<bool, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, sceneHandle); } // Autogenerated method: UnityEngine.SceneManagement.Scene.GetRootCountInternal int UnityEngine::SceneManagement::Scene::GetRootCountInternal(int sceneHandle) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::Scene::GetRootCountInternal"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.SceneManagement", "Scene", "GetRootCountInternal", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(sceneHandle)}))); return ::il2cpp_utils::RunMethodThrow<int, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, sceneHandle); } // Autogenerated method: UnityEngine.SceneManagement.Scene.GetRootGameObjectsInternal void UnityEngine::SceneManagement::Scene::GetRootGameObjectsInternal(int sceneHandle, ::Il2CppObject* resultRootList) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::Scene::GetRootGameObjectsInternal"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.SceneManagement", "Scene", "GetRootGameObjectsInternal", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(sceneHandle), ::il2cpp_utils::ExtractType(resultRootList)}))); ::il2cpp_utils::RunMethodThrow<void, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, sceneHandle, resultRootList); } // Autogenerated method: UnityEngine.SceneManagement.Scene.get_handle int UnityEngine::SceneManagement::Scene::get_handle() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::Scene::get_handle"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(*this, "get_handle", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<int, false>(*this, ___internal__method); } // Autogenerated method: UnityEngine.SceneManagement.Scene.IsValid bool UnityEngine::SceneManagement::Scene::IsValid() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::Scene::IsValid"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(*this, "IsValid", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<bool, false>(*this, ___internal__method); } // Autogenerated method: UnityEngine.SceneManagement.Scene.get_name ::Il2CppString* UnityEngine::SceneManagement::Scene::get_name() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::Scene::get_name"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(*this, "get_name", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<::Il2CppString*, false>(*this, ___internal__method); } // Autogenerated method: UnityEngine.SceneManagement.Scene.get_isLoaded bool UnityEngine::SceneManagement::Scene::get_isLoaded() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::Scene::get_isLoaded"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(*this, "get_isLoaded", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<bool, false>(*this, ___internal__method); } // Autogenerated method: UnityEngine.SceneManagement.Scene.get_rootCount int UnityEngine::SceneManagement::Scene::get_rootCount() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::Scene::get_rootCount"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(*this, "get_rootCount", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<int, false>(*this, ___internal__method); } // Autogenerated method: UnityEngine.SceneManagement.Scene.GetRootGameObjects ::Array<UnityEngine::GameObject*>* UnityEngine::SceneManagement::Scene::GetRootGameObjects() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::Scene::GetRootGameObjects"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(*this, "GetRootGameObjects", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<::Array<UnityEngine::GameObject*>*, false>(*this, ___internal__method); } // Autogenerated method: UnityEngine.SceneManagement.Scene.GetRootGameObjects void UnityEngine::SceneManagement::Scene::GetRootGameObjects(System::Collections::Generic::List_1<UnityEngine::GameObject*>* rootGameObjects) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::Scene::GetRootGameObjects"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(*this, "GetRootGameObjects", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(rootGameObjects)}))); ::il2cpp_utils::RunMethodThrow<void, false>(*this, ___internal__method, rootGameObjects); } // Autogenerated method: UnityEngine.SceneManagement.Scene.GetHashCode int UnityEngine::SceneManagement::Scene::GetHashCode() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::Scene::GetHashCode"); auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(*this, "GetHashCode", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<int, false>(*this, ___internal__method); } // Autogenerated method: UnityEngine.SceneManagement.Scene.Equals bool UnityEngine::SceneManagement::Scene::Equals(::Il2CppObject* other) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::Scene::Equals"); auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(*this, "Equals", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(other)}))); return ::il2cpp_utils::RunMethodThrow<bool, false>(*this, ___internal__method, other); } // Autogenerated method: UnityEngine.SceneManagement.Scene.op_Equality bool UnityEngine::SceneManagement::operator ==(const UnityEngine::SceneManagement::Scene& lhs, const UnityEngine::SceneManagement::Scene& rhs) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::Scene::op_Equality"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.SceneManagement", "Scene", "op_Equality", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(lhs), ::il2cpp_utils::ExtractType(rhs)}))); return ::il2cpp_utils::RunMethodThrow<bool, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, lhs, rhs); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: UnityEngine.SceneManagement.SceneManagerAPIInternal #include "UnityEngine/SceneManagement/SceneManagerAPIInternal.hpp" // Including type: UnityEngine.AsyncOperation #include "UnityEngine/AsyncOperation.hpp" // Including type: UnityEngine.SceneManagement.LoadSceneParameters #include "UnityEngine/SceneManagement/LoadSceneParameters.hpp" // Including type: UnityEngine.SceneManagement.UnloadSceneOptions #include "UnityEngine/SceneManagement/UnloadSceneOptions.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated method: UnityEngine.SceneManagement.SceneManagerAPIInternal.LoadSceneAsyncNameIndexInternal UnityEngine::AsyncOperation* UnityEngine::SceneManagement::SceneManagerAPIInternal::LoadSceneAsyncNameIndexInternal(::Il2CppString* sceneName, int sceneBuildIndex, UnityEngine::SceneManagement::LoadSceneParameters parameters, bool mustCompleteNextFrame) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::SceneManagerAPIInternal::LoadSceneAsyncNameIndexInternal"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.SceneManagement", "SceneManagerAPIInternal", "LoadSceneAsyncNameIndexInternal", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(sceneName), ::il2cpp_utils::ExtractType(sceneBuildIndex), ::il2cpp_utils::ExtractType(parameters), ::il2cpp_utils::ExtractType(mustCompleteNextFrame)}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::AsyncOperation*, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, sceneName, sceneBuildIndex, parameters, mustCompleteNextFrame); } // Autogenerated method: UnityEngine.SceneManagement.SceneManagerAPIInternal.UnloadSceneNameIndexInternal UnityEngine::AsyncOperation* UnityEngine::SceneManagement::SceneManagerAPIInternal::UnloadSceneNameIndexInternal(::Il2CppString* sceneName, int sceneBuildIndex, bool immediately, UnityEngine::SceneManagement::UnloadSceneOptions options, bool& outSuccess) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::SceneManagerAPIInternal::UnloadSceneNameIndexInternal"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.SceneManagement", "SceneManagerAPIInternal", "UnloadSceneNameIndexInternal", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(sceneName), ::il2cpp_utils::ExtractType(sceneBuildIndex), ::il2cpp_utils::ExtractType(immediately), ::il2cpp_utils::ExtractType(options), ::il2cpp_utils::ExtractIndependentType<bool&>()}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::AsyncOperation*, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, sceneName, sceneBuildIndex, immediately, options, outSuccess); } // Autogenerated method: UnityEngine.SceneManagement.SceneManagerAPIInternal.LoadSceneAsyncNameIndexInternal_Injected UnityEngine::AsyncOperation* UnityEngine::SceneManagement::SceneManagerAPIInternal::LoadSceneAsyncNameIndexInternal_Injected(::Il2CppString* sceneName, int sceneBuildIndex, UnityEngine::SceneManagement::LoadSceneParameters& parameters, bool mustCompleteNextFrame) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::SceneManagerAPIInternal::LoadSceneAsyncNameIndexInternal_Injected"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.SceneManagement", "SceneManagerAPIInternal", "LoadSceneAsyncNameIndexInternal_Injected", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(sceneName), ::il2cpp_utils::ExtractType(sceneBuildIndex), ::il2cpp_utils::ExtractType(parameters), ::il2cpp_utils::ExtractType(mustCompleteNextFrame)}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::AsyncOperation*, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, sceneName, sceneBuildIndex, parameters, mustCompleteNextFrame); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: UnityEngine.SceneManagement.SceneManager #include "UnityEngine/SceneManagement/SceneManager.hpp" // Including type: UnityEngine.Events.UnityAction`2 #include "UnityEngine/Events/UnityAction_2.hpp" // Including type: UnityEngine.Events.UnityAction`1 #include "UnityEngine/Events/UnityAction_1.hpp" // Including type: UnityEngine.AsyncOperation #include "UnityEngine/AsyncOperation.hpp" // Including type: UnityEngine.SceneManagement.UnloadSceneOptions #include "UnityEngine/SceneManagement/UnloadSceneOptions.hpp" // Including type: UnityEngine.SceneManagement.LoadSceneParameters #include "UnityEngine/SceneManagement/LoadSceneParameters.hpp" // Including type: UnityEngine.GameObject #include "UnityEngine/GameObject.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated static field getter // Get static field: static System.Boolean s_AllowLoadScene bool UnityEngine::SceneManagement::SceneManager::_get_s_AllowLoadScene() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::SceneManager::_get_s_AllowLoadScene"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<bool>("UnityEngine.SceneManagement", "SceneManager", "s_AllowLoadScene")); } // Autogenerated static field setter // Set static field: static System.Boolean s_AllowLoadScene void UnityEngine::SceneManagement::SceneManager::_set_s_AllowLoadScene(bool value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::SceneManager::_set_s_AllowLoadScene"); THROW_UNLESS(il2cpp_utils::SetFieldValue("UnityEngine.SceneManagement", "SceneManager", "s_AllowLoadScene", value)); } // [DebuggerBrowsableAttribute] Offset: 0xD94620 // [CompilerGeneratedAttribute] Offset: 0xD94620 // Autogenerated static field getter // Get static field: static private UnityEngine.Events.UnityAction`2<UnityEngine.SceneManagement.Scene,UnityEngine.SceneManagement.LoadSceneMode> sceneLoaded UnityEngine::Events::UnityAction_2<UnityEngine::SceneManagement::Scene, UnityEngine::SceneManagement::LoadSceneMode>* UnityEngine::SceneManagement::SceneManager::_get_sceneLoaded() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::SceneManager::_get_sceneLoaded"); return THROW_UNLESS((il2cpp_utils::GetFieldValue<UnityEngine::Events::UnityAction_2<UnityEngine::SceneManagement::Scene, UnityEngine::SceneManagement::LoadSceneMode>*>("UnityEngine.SceneManagement", "SceneManager", "sceneLoaded"))); } // Autogenerated static field setter // Set static field: static private UnityEngine.Events.UnityAction`2<UnityEngine.SceneManagement.Scene,UnityEngine.SceneManagement.LoadSceneMode> sceneLoaded void UnityEngine::SceneManagement::SceneManager::_set_sceneLoaded(UnityEngine::Events::UnityAction_2<UnityEngine::SceneManagement::Scene, UnityEngine::SceneManagement::LoadSceneMode>* value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::SceneManager::_set_sceneLoaded"); THROW_UNLESS(il2cpp_utils::SetFieldValue("UnityEngine.SceneManagement", "SceneManager", "sceneLoaded", value)); } // [DebuggerBrowsableAttribute] Offset: 0xD9465C // [CompilerGeneratedAttribute] Offset: 0xD9465C // Autogenerated static field getter // Get static field: static private UnityEngine.Events.UnityAction`1<UnityEngine.SceneManagement.Scene> sceneUnloaded UnityEngine::Events::UnityAction_1<UnityEngine::SceneManagement::Scene>* UnityEngine::SceneManagement::SceneManager::_get_sceneUnloaded() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::SceneManager::_get_sceneUnloaded"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<UnityEngine::Events::UnityAction_1<UnityEngine::SceneManagement::Scene>*>("UnityEngine.SceneManagement", "SceneManager", "sceneUnloaded")); } // Autogenerated static field setter // Set static field: static private UnityEngine.Events.UnityAction`1<UnityEngine.SceneManagement.Scene> sceneUnloaded void UnityEngine::SceneManagement::SceneManager::_set_sceneUnloaded(UnityEngine::Events::UnityAction_1<UnityEngine::SceneManagement::Scene>* value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::SceneManager::_set_sceneUnloaded"); THROW_UNLESS(il2cpp_utils::SetFieldValue("UnityEngine.SceneManagement", "SceneManager", "sceneUnloaded", value)); } // [DebuggerBrowsableAttribute] Offset: 0xD94698 // [CompilerGeneratedAttribute] Offset: 0xD94698 // Autogenerated static field getter // Get static field: static private UnityEngine.Events.UnityAction`2<UnityEngine.SceneManagement.Scene,UnityEngine.SceneManagement.Scene> activeSceneChanged UnityEngine::Events::UnityAction_2<UnityEngine::SceneManagement::Scene, UnityEngine::SceneManagement::Scene>* UnityEngine::SceneManagement::SceneManager::_get_activeSceneChanged() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::SceneManager::_get_activeSceneChanged"); return THROW_UNLESS((il2cpp_utils::GetFieldValue<UnityEngine::Events::UnityAction_2<UnityEngine::SceneManagement::Scene, UnityEngine::SceneManagement::Scene>*>("UnityEngine.SceneManagement", "SceneManager", "activeSceneChanged"))); } // Autogenerated static field setter // Set static field: static private UnityEngine.Events.UnityAction`2<UnityEngine.SceneManagement.Scene,UnityEngine.SceneManagement.Scene> activeSceneChanged void UnityEngine::SceneManagement::SceneManager::_set_activeSceneChanged(UnityEngine::Events::UnityAction_2<UnityEngine::SceneManagement::Scene, UnityEngine::SceneManagement::Scene>* value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::SceneManager::_set_activeSceneChanged"); THROW_UNLESS(il2cpp_utils::SetFieldValue("UnityEngine.SceneManagement", "SceneManager", "activeSceneChanged", value)); } // Autogenerated method: UnityEngine.SceneManagement.SceneManager.get_sceneCount int UnityEngine::SceneManagement::SceneManager::get_sceneCount() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::SceneManager::get_sceneCount"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.SceneManagement", "SceneManager", "get_sceneCount", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<int, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method); } // Autogenerated method: UnityEngine.SceneManagement.SceneManager.get_sceneCountInBuildSettings int UnityEngine::SceneManagement::SceneManager::get_sceneCountInBuildSettings() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::SceneManager::get_sceneCountInBuildSettings"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.SceneManagement", "SceneManager", "get_sceneCountInBuildSettings", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<int, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method); } // Autogenerated method: UnityEngine.SceneManagement.SceneManager.GetActiveScene UnityEngine::SceneManagement::Scene UnityEngine::SceneManagement::SceneManager::GetActiveScene() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::SceneManager::GetActiveScene"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.SceneManagement", "SceneManager", "GetActiveScene", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::SceneManagement::Scene, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method); } // Autogenerated method: UnityEngine.SceneManagement.SceneManager.SetActiveScene bool UnityEngine::SceneManagement::SceneManager::SetActiveScene(UnityEngine::SceneManagement::Scene scene) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::SceneManager::SetActiveScene"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.SceneManagement", "SceneManager", "SetActiveScene", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(scene)}))); return ::il2cpp_utils::RunMethodThrow<bool, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, scene); } // Autogenerated method: UnityEngine.SceneManagement.SceneManager.GetSceneByName UnityEngine::SceneManagement::Scene UnityEngine::SceneManagement::SceneManager::GetSceneByName(::Il2CppString* name) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::SceneManager::GetSceneByName"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.SceneManagement", "SceneManager", "GetSceneByName", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(name)}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::SceneManagement::Scene, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, name); } // Autogenerated method: UnityEngine.SceneManagement.SceneManager.GetSceneAt UnityEngine::SceneManagement::Scene UnityEngine::SceneManagement::SceneManager::GetSceneAt(int index) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::SceneManager::GetSceneAt"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.SceneManagement", "SceneManager", "GetSceneAt", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(index)}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::SceneManagement::Scene, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, index); } // Autogenerated method: UnityEngine.SceneManagement.SceneManager.UnloadSceneAsyncInternal UnityEngine::AsyncOperation* UnityEngine::SceneManagement::SceneManager::UnloadSceneAsyncInternal(UnityEngine::SceneManagement::Scene scene, UnityEngine::SceneManagement::UnloadSceneOptions options) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::SceneManager::UnloadSceneAsyncInternal"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.SceneManagement", "SceneManager", "UnloadSceneAsyncInternal", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(scene), ::il2cpp_utils::ExtractType(options)}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::AsyncOperation*, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, scene, options); } // Autogenerated method: UnityEngine.SceneManagement.SceneManager.LoadSceneAsyncNameIndexInternal UnityEngine::AsyncOperation* UnityEngine::SceneManagement::SceneManager::LoadSceneAsyncNameIndexInternal(::Il2CppString* sceneName, int sceneBuildIndex, UnityEngine::SceneManagement::LoadSceneParameters parameters, bool mustCompleteNextFrame) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::SceneManager::LoadSceneAsyncNameIndexInternal"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.SceneManagement", "SceneManager", "LoadSceneAsyncNameIndexInternal", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(sceneName), ::il2cpp_utils::ExtractType(sceneBuildIndex), ::il2cpp_utils::ExtractType(parameters), ::il2cpp_utils::ExtractType(mustCompleteNextFrame)}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::AsyncOperation*, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, sceneName, sceneBuildIndex, parameters, mustCompleteNextFrame); } // Autogenerated method: UnityEngine.SceneManagement.SceneManager.UnloadSceneNameIndexInternal UnityEngine::AsyncOperation* UnityEngine::SceneManagement::SceneManager::UnloadSceneNameIndexInternal(::Il2CppString* sceneName, int sceneBuildIndex, bool immediately, UnityEngine::SceneManagement::UnloadSceneOptions options, bool& outSuccess) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::SceneManager::UnloadSceneNameIndexInternal"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.SceneManagement", "SceneManager", "UnloadSceneNameIndexInternal", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(sceneName), ::il2cpp_utils::ExtractType(sceneBuildIndex), ::il2cpp_utils::ExtractType(immediately), ::il2cpp_utils::ExtractType(options), ::il2cpp_utils::ExtractIndependentType<bool&>()}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::AsyncOperation*, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, sceneName, sceneBuildIndex, immediately, options, outSuccess); } // Autogenerated method: UnityEngine.SceneManagement.SceneManager.MoveGameObjectToScene void UnityEngine::SceneManagement::SceneManager::MoveGameObjectToScene(UnityEngine::GameObject* go, UnityEngine::SceneManagement::Scene scene) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::SceneManager::MoveGameObjectToScene"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.SceneManagement", "SceneManager", "MoveGameObjectToScene", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(go), ::il2cpp_utils::ExtractType(scene)}))); ::il2cpp_utils::RunMethodThrow<void, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, go, scene); } // Autogenerated method: UnityEngine.SceneManagement.SceneManager.add_sceneLoaded void UnityEngine::SceneManagement::SceneManager::add_sceneLoaded(UnityEngine::Events::UnityAction_2<UnityEngine::SceneManagement::Scene, UnityEngine::SceneManagement::LoadSceneMode>* value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::SceneManager::add_sceneLoaded"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.SceneManagement", "SceneManager", "add_sceneLoaded", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)}))); ::il2cpp_utils::RunMethodThrow<void, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, value); } // Autogenerated method: UnityEngine.SceneManagement.SceneManager.remove_sceneLoaded void UnityEngine::SceneManagement::SceneManager::remove_sceneLoaded(UnityEngine::Events::UnityAction_2<UnityEngine::SceneManagement::Scene, UnityEngine::SceneManagement::LoadSceneMode>* value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::SceneManager::remove_sceneLoaded"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.SceneManagement", "SceneManager", "remove_sceneLoaded", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)}))); ::il2cpp_utils::RunMethodThrow<void, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, value); } // Autogenerated method: UnityEngine.SceneManagement.SceneManager.add_sceneUnloaded void UnityEngine::SceneManagement::SceneManager::add_sceneUnloaded(UnityEngine::Events::UnityAction_1<UnityEngine::SceneManagement::Scene>* value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::SceneManager::add_sceneUnloaded"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.SceneManagement", "SceneManager", "add_sceneUnloaded", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)}))); ::il2cpp_utils::RunMethodThrow<void, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, value); } // Autogenerated method: UnityEngine.SceneManagement.SceneManager.remove_sceneUnloaded void UnityEngine::SceneManagement::SceneManager::remove_sceneUnloaded(UnityEngine::Events::UnityAction_1<UnityEngine::SceneManagement::Scene>* value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::SceneManager::remove_sceneUnloaded"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.SceneManagement", "SceneManager", "remove_sceneUnloaded", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)}))); ::il2cpp_utils::RunMethodThrow<void, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, value); } // Autogenerated method: UnityEngine.SceneManagement.SceneManager.LoadScene void UnityEngine::SceneManagement::SceneManager::LoadScene(::Il2CppString* sceneName, UnityEngine::SceneManagement::LoadSceneMode mode) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::SceneManager::LoadScene"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.SceneManagement", "SceneManager", "LoadScene", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(sceneName), ::il2cpp_utils::ExtractType(mode)}))); ::il2cpp_utils::RunMethodThrow<void, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, sceneName, mode); } // Autogenerated method: UnityEngine.SceneManagement.SceneManager.LoadScene void UnityEngine::SceneManagement::SceneManager::LoadScene(::Il2CppString* sceneName) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::SceneManager::LoadScene"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.SceneManagement", "SceneManager", "LoadScene", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(sceneName)}))); ::il2cpp_utils::RunMethodThrow<void, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, sceneName); } // Autogenerated method: UnityEngine.SceneManagement.SceneManager.LoadScene UnityEngine::SceneManagement::Scene UnityEngine::SceneManagement::SceneManager::LoadScene(::Il2CppString* sceneName, UnityEngine::SceneManagement::LoadSceneParameters parameters) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::SceneManager::LoadScene"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.SceneManagement", "SceneManager", "LoadScene", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(sceneName), ::il2cpp_utils::ExtractType(parameters)}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::SceneManagement::Scene, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, sceneName, parameters); } // Autogenerated method: UnityEngine.SceneManagement.SceneManager.LoadScene void UnityEngine::SceneManagement::SceneManager::LoadScene(int sceneBuildIndex, UnityEngine::SceneManagement::LoadSceneMode mode) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::SceneManager::LoadScene"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.SceneManagement", "SceneManager", "LoadScene", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(sceneBuildIndex), ::il2cpp_utils::ExtractType(mode)}))); ::il2cpp_utils::RunMethodThrow<void, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, sceneBuildIndex, mode); } // Autogenerated method: UnityEngine.SceneManagement.SceneManager.LoadScene UnityEngine::SceneManagement::Scene UnityEngine::SceneManagement::SceneManager::LoadScene(int sceneBuildIndex, UnityEngine::SceneManagement::LoadSceneParameters parameters) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::SceneManager::LoadScene"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.SceneManagement", "SceneManager", "LoadScene", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(sceneBuildIndex), ::il2cpp_utils::ExtractType(parameters)}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::SceneManagement::Scene, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, sceneBuildIndex, parameters); } // Autogenerated method: UnityEngine.SceneManagement.SceneManager.LoadSceneAsync UnityEngine::AsyncOperation* UnityEngine::SceneManagement::SceneManager::LoadSceneAsync(int sceneBuildIndex, UnityEngine::SceneManagement::LoadSceneMode mode) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::SceneManager::LoadSceneAsync"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.SceneManagement", "SceneManager", "LoadSceneAsync", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(sceneBuildIndex), ::il2cpp_utils::ExtractType(mode)}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::AsyncOperation*, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, sceneBuildIndex, mode); } // Autogenerated method: UnityEngine.SceneManagement.SceneManager.LoadSceneAsync UnityEngine::AsyncOperation* UnityEngine::SceneManagement::SceneManager::LoadSceneAsync(int sceneBuildIndex, UnityEngine::SceneManagement::LoadSceneParameters parameters) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::SceneManager::LoadSceneAsync"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.SceneManagement", "SceneManager", "LoadSceneAsync", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(sceneBuildIndex), ::il2cpp_utils::ExtractType(parameters)}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::AsyncOperation*, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, sceneBuildIndex, parameters); } // Autogenerated method: UnityEngine.SceneManagement.SceneManager.LoadSceneAsync UnityEngine::AsyncOperation* UnityEngine::SceneManagement::SceneManager::LoadSceneAsync(::Il2CppString* sceneName, UnityEngine::SceneManagement::LoadSceneMode mode) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::SceneManager::LoadSceneAsync"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.SceneManagement", "SceneManager", "LoadSceneAsync", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(sceneName), ::il2cpp_utils::ExtractType(mode)}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::AsyncOperation*, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, sceneName, mode); } // Autogenerated method: UnityEngine.SceneManagement.SceneManager.LoadSceneAsync UnityEngine::AsyncOperation* UnityEngine::SceneManagement::SceneManager::LoadSceneAsync(::Il2CppString* sceneName) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::SceneManager::LoadSceneAsync"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.SceneManagement", "SceneManager", "LoadSceneAsync", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(sceneName)}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::AsyncOperation*, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, sceneName); } // Autogenerated method: UnityEngine.SceneManagement.SceneManager.LoadSceneAsync UnityEngine::AsyncOperation* UnityEngine::SceneManagement::SceneManager::LoadSceneAsync(::Il2CppString* sceneName, UnityEngine::SceneManagement::LoadSceneParameters parameters) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::SceneManager::LoadSceneAsync"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.SceneManagement", "SceneManager", "LoadSceneAsync", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(sceneName), ::il2cpp_utils::ExtractType(parameters)}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::AsyncOperation*, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, sceneName, parameters); } // Autogenerated method: UnityEngine.SceneManagement.SceneManager.UnloadSceneAsync UnityEngine::AsyncOperation* UnityEngine::SceneManagement::SceneManager::UnloadSceneAsync(::Il2CppString* sceneName) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::SceneManager::UnloadSceneAsync"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.SceneManagement", "SceneManager", "UnloadSceneAsync", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(sceneName)}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::AsyncOperation*, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, sceneName); } // Autogenerated method: UnityEngine.SceneManagement.SceneManager.UnloadSceneAsync UnityEngine::AsyncOperation* UnityEngine::SceneManagement::SceneManager::UnloadSceneAsync(UnityEngine::SceneManagement::Scene scene) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::SceneManager::UnloadSceneAsync"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.SceneManagement", "SceneManager", "UnloadSceneAsync", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(scene)}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::AsyncOperation*, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, scene); } // Autogenerated method: UnityEngine.SceneManagement.SceneManager.Internal_SceneLoaded void UnityEngine::SceneManagement::SceneManager::Internal_SceneLoaded(UnityEngine::SceneManagement::Scene scene, UnityEngine::SceneManagement::LoadSceneMode mode) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::SceneManager::Internal_SceneLoaded"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.SceneManagement", "SceneManager", "Internal_SceneLoaded", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(scene), ::il2cpp_utils::ExtractType(mode)}))); ::il2cpp_utils::RunMethodThrow<void, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, scene, mode); } // Autogenerated method: UnityEngine.SceneManagement.SceneManager.Internal_SceneUnloaded void UnityEngine::SceneManagement::SceneManager::Internal_SceneUnloaded(UnityEngine::SceneManagement::Scene scene) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::SceneManager::Internal_SceneUnloaded"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.SceneManagement", "SceneManager", "Internal_SceneUnloaded", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(scene)}))); ::il2cpp_utils::RunMethodThrow<void, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, scene); } // Autogenerated method: UnityEngine.SceneManagement.SceneManager.Internal_ActiveSceneChanged void UnityEngine::SceneManagement::SceneManager::Internal_ActiveSceneChanged(UnityEngine::SceneManagement::Scene previousActiveScene, UnityEngine::SceneManagement::Scene newActiveScene) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::SceneManager::Internal_ActiveSceneChanged"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.SceneManagement", "SceneManager", "Internal_ActiveSceneChanged", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(previousActiveScene), ::il2cpp_utils::ExtractType(newActiveScene)}))); ::il2cpp_utils::RunMethodThrow<void, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, previousActiveScene, newActiveScene); } // Autogenerated method: UnityEngine.SceneManagement.SceneManager..cctor void UnityEngine::SceneManagement::SceneManager::_cctor() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::SceneManager::.cctor"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.SceneManagement", "SceneManager", ".cctor", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); ::il2cpp_utils::RunMethodThrow<void, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method); } // Autogenerated method: UnityEngine.SceneManagement.SceneManager.GetActiveScene_Injected void UnityEngine::SceneManagement::SceneManager::GetActiveScene_Injected(UnityEngine::SceneManagement::Scene& ret) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::SceneManager::GetActiveScene_Injected"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.SceneManagement", "SceneManager", "GetActiveScene_Injected", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractIndependentType<UnityEngine::SceneManagement::Scene&>()}))); ::il2cpp_utils::RunMethodThrow<void, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, ret); } // Autogenerated method: UnityEngine.SceneManagement.SceneManager.SetActiveScene_Injected bool UnityEngine::SceneManagement::SceneManager::SetActiveScene_Injected(UnityEngine::SceneManagement::Scene& scene) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::SceneManager::SetActiveScene_Injected"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.SceneManagement", "SceneManager", "SetActiveScene_Injected", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(scene)}))); return ::il2cpp_utils::RunMethodThrow<bool, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, scene); } // Autogenerated method: UnityEngine.SceneManagement.SceneManager.GetSceneByName_Injected void UnityEngine::SceneManagement::SceneManager::GetSceneByName_Injected(::Il2CppString* name, UnityEngine::SceneManagement::Scene& ret) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::SceneManager::GetSceneByName_Injected"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.SceneManagement", "SceneManager", "GetSceneByName_Injected", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(name), ::il2cpp_utils::ExtractIndependentType<UnityEngine::SceneManagement::Scene&>()}))); ::il2cpp_utils::RunMethodThrow<void, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, name, ret); } // Autogenerated method: UnityEngine.SceneManagement.SceneManager.GetSceneAt_Injected void UnityEngine::SceneManagement::SceneManager::GetSceneAt_Injected(int index, UnityEngine::SceneManagement::Scene& ret) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::SceneManager::GetSceneAt_Injected"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.SceneManagement", "SceneManager", "GetSceneAt_Injected", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(index), ::il2cpp_utils::ExtractIndependentType<UnityEngine::SceneManagement::Scene&>()}))); ::il2cpp_utils::RunMethodThrow<void, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, index, ret); } // Autogenerated method: UnityEngine.SceneManagement.SceneManager.UnloadSceneAsyncInternal_Injected UnityEngine::AsyncOperation* UnityEngine::SceneManagement::SceneManager::UnloadSceneAsyncInternal_Injected(UnityEngine::SceneManagement::Scene& scene, UnityEngine::SceneManagement::UnloadSceneOptions options) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::SceneManager::UnloadSceneAsyncInternal_Injected"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.SceneManagement", "SceneManager", "UnloadSceneAsyncInternal_Injected", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(scene), ::il2cpp_utils::ExtractType(options)}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::AsyncOperation*, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, scene, options); } // Autogenerated method: UnityEngine.SceneManagement.SceneManager.MoveGameObjectToScene_Injected void UnityEngine::SceneManagement::SceneManager::MoveGameObjectToScene_Injected(UnityEngine::GameObject* go, UnityEngine::SceneManagement::Scene& scene) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::SceneManager::MoveGameObjectToScene_Injected"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.SceneManagement", "SceneManager", "MoveGameObjectToScene_Injected", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(go), ::il2cpp_utils::ExtractType(scene)}))); ::il2cpp_utils::RunMethodThrow<void, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, go, scene); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes // Including type: UnityEngine.SceneManagement.LoadSceneMode #include "UnityEngine/SceneManagement/LoadSceneMode.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated static field getter // Get static field: static public UnityEngine.SceneManagement.LoadSceneMode Single UnityEngine::SceneManagement::LoadSceneMode UnityEngine::SceneManagement::LoadSceneMode::_get_Single() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::LoadSceneMode::_get_Single"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<UnityEngine::SceneManagement::LoadSceneMode>("UnityEngine.SceneManagement", "LoadSceneMode", "Single")); } // Autogenerated static field setter // Set static field: static public UnityEngine.SceneManagement.LoadSceneMode Single void UnityEngine::SceneManagement::LoadSceneMode::_set_Single(UnityEngine::SceneManagement::LoadSceneMode value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::LoadSceneMode::_set_Single"); THROW_UNLESS(il2cpp_utils::SetFieldValue("UnityEngine.SceneManagement", "LoadSceneMode", "Single", value)); } // Autogenerated static field getter // Get static field: static public UnityEngine.SceneManagement.LoadSceneMode Additive UnityEngine::SceneManagement::LoadSceneMode UnityEngine::SceneManagement::LoadSceneMode::_get_Additive() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::LoadSceneMode::_get_Additive"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<UnityEngine::SceneManagement::LoadSceneMode>("UnityEngine.SceneManagement", "LoadSceneMode", "Additive")); } // Autogenerated static field setter // Set static field: static public UnityEngine.SceneManagement.LoadSceneMode Additive void UnityEngine::SceneManagement::LoadSceneMode::_set_Additive(UnityEngine::SceneManagement::LoadSceneMode value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::LoadSceneMode::_set_Additive"); THROW_UNLESS(il2cpp_utils::SetFieldValue("UnityEngine.SceneManagement", "LoadSceneMode", "Additive", value)); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes // Including type: UnityEngine.SceneManagement.LocalPhysicsMode #include "UnityEngine/SceneManagement/LocalPhysicsMode.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated static field getter // Get static field: static public UnityEngine.SceneManagement.LocalPhysicsMode None UnityEngine::SceneManagement::LocalPhysicsMode UnityEngine::SceneManagement::LocalPhysicsMode::_get_None() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::LocalPhysicsMode::_get_None"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<UnityEngine::SceneManagement::LocalPhysicsMode>("UnityEngine.SceneManagement", "LocalPhysicsMode", "None")); } // Autogenerated static field setter // Set static field: static public UnityEngine.SceneManagement.LocalPhysicsMode None void UnityEngine::SceneManagement::LocalPhysicsMode::_set_None(UnityEngine::SceneManagement::LocalPhysicsMode value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::LocalPhysicsMode::_set_None"); THROW_UNLESS(il2cpp_utils::SetFieldValue("UnityEngine.SceneManagement", "LocalPhysicsMode", "None", value)); } // Autogenerated static field getter // Get static field: static public UnityEngine.SceneManagement.LocalPhysicsMode Physics2D UnityEngine::SceneManagement::LocalPhysicsMode UnityEngine::SceneManagement::LocalPhysicsMode::_get_Physics2D() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::LocalPhysicsMode::_get_Physics2D"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<UnityEngine::SceneManagement::LocalPhysicsMode>("UnityEngine.SceneManagement", "LocalPhysicsMode", "Physics2D")); } // Autogenerated static field setter // Set static field: static public UnityEngine.SceneManagement.LocalPhysicsMode Physics2D void UnityEngine::SceneManagement::LocalPhysicsMode::_set_Physics2D(UnityEngine::SceneManagement::LocalPhysicsMode value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::LocalPhysicsMode::_set_Physics2D"); THROW_UNLESS(il2cpp_utils::SetFieldValue("UnityEngine.SceneManagement", "LocalPhysicsMode", "Physics2D", value)); } // Autogenerated static field getter // Get static field: static public UnityEngine.SceneManagement.LocalPhysicsMode Physics3D UnityEngine::SceneManagement::LocalPhysicsMode UnityEngine::SceneManagement::LocalPhysicsMode::_get_Physics3D() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::LocalPhysicsMode::_get_Physics3D"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<UnityEngine::SceneManagement::LocalPhysicsMode>("UnityEngine.SceneManagement", "LocalPhysicsMode", "Physics3D")); } // Autogenerated static field setter // Set static field: static public UnityEngine.SceneManagement.LocalPhysicsMode Physics3D void UnityEngine::SceneManagement::LocalPhysicsMode::_set_Physics3D(UnityEngine::SceneManagement::LocalPhysicsMode value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::LocalPhysicsMode::_set_Physics3D"); THROW_UNLESS(il2cpp_utils::SetFieldValue("UnityEngine.SceneManagement", "LocalPhysicsMode", "Physics3D", value)); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes // Including type: UnityEngine.SceneManagement.LoadSceneParameters #include "UnityEngine/SceneManagement/LoadSceneParameters.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated method: UnityEngine.SceneManagement.LoadSceneParameters.set_loadSceneMode void UnityEngine::SceneManagement::LoadSceneParameters::set_loadSceneMode(UnityEngine::SceneManagement::LoadSceneMode value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::LoadSceneParameters::set_loadSceneMode"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(*this, "set_loadSceneMode", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)}))); ::il2cpp_utils::RunMethodThrow<void, false>(*this, ___internal__method, value); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes // Including type: UnityEngine.SceneManagement.UnloadSceneOptions #include "UnityEngine/SceneManagement/UnloadSceneOptions.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated static field getter // Get static field: static public UnityEngine.SceneManagement.UnloadSceneOptions None UnityEngine::SceneManagement::UnloadSceneOptions UnityEngine::SceneManagement::UnloadSceneOptions::_get_None() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::UnloadSceneOptions::_get_None"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<UnityEngine::SceneManagement::UnloadSceneOptions>("UnityEngine.SceneManagement", "UnloadSceneOptions", "None")); } // Autogenerated static field setter // Set static field: static public UnityEngine.SceneManagement.UnloadSceneOptions None void UnityEngine::SceneManagement::UnloadSceneOptions::_set_None(UnityEngine::SceneManagement::UnloadSceneOptions value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::UnloadSceneOptions::_set_None"); THROW_UNLESS(il2cpp_utils::SetFieldValue("UnityEngine.SceneManagement", "UnloadSceneOptions", "None", value)); } // Autogenerated static field getter // Get static field: static public UnityEngine.SceneManagement.UnloadSceneOptions UnloadAllEmbeddedSceneObjects UnityEngine::SceneManagement::UnloadSceneOptions UnityEngine::SceneManagement::UnloadSceneOptions::_get_UnloadAllEmbeddedSceneObjects() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::UnloadSceneOptions::_get_UnloadAllEmbeddedSceneObjects"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<UnityEngine::SceneManagement::UnloadSceneOptions>("UnityEngine.SceneManagement", "UnloadSceneOptions", "UnloadAllEmbeddedSceneObjects")); } // Autogenerated static field setter // Set static field: static public UnityEngine.SceneManagement.UnloadSceneOptions UnloadAllEmbeddedSceneObjects void UnityEngine::SceneManagement::UnloadSceneOptions::_set_UnloadAllEmbeddedSceneObjects(UnityEngine::SceneManagement::UnloadSceneOptions value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::SceneManagement::UnloadSceneOptions::_set_UnloadAllEmbeddedSceneObjects"); THROW_UNLESS(il2cpp_utils::SetFieldValue("UnityEngine.SceneManagement", "UnloadSceneOptions", "UnloadAllEmbeddedSceneObjects", value)); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: UnityEngine.LowLevel.PlayerLoopSystem/UpdateFunction #include "UnityEngine/LowLevel/PlayerLoopSystem_UpdateFunction.hpp" // Including type: System.IAsyncResult #include "System/IAsyncResult.hpp" // Including type: System.AsyncCallback #include "System/AsyncCallback.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated method: UnityEngine.LowLevel.PlayerLoopSystem/UpdateFunction.Invoke void UnityEngine::LowLevel::PlayerLoopSystem::UpdateFunction::Invoke() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::LowLevel::PlayerLoopSystem::UpdateFunction::Invoke"); auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Invoke", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.LowLevel.PlayerLoopSystem/UpdateFunction.BeginInvoke System::IAsyncResult* UnityEngine::LowLevel::PlayerLoopSystem::UpdateFunction::BeginInvoke(System::AsyncCallback* callback, ::Il2CppObject* object) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::LowLevel::PlayerLoopSystem::UpdateFunction::BeginInvoke"); auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "BeginInvoke", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(callback), ::il2cpp_utils::ExtractType(object)}))); return ::il2cpp_utils::RunMethodThrow<System::IAsyncResult*, false>(this, ___internal__method, callback, object); } // Autogenerated method: UnityEngine.LowLevel.PlayerLoopSystem/UpdateFunction.EndInvoke void UnityEngine::LowLevel::PlayerLoopSystem::UpdateFunction::EndInvoke(System::IAsyncResult* result) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::LowLevel::PlayerLoopSystem::UpdateFunction::EndInvoke"); auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "EndInvoke", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(result)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, result); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: UnityEngine.Networking.PlayerConnection.MessageEventArgs #include "UnityEngine/Networking/PlayerConnection/MessageEventArgs.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: UnityEngine.Networking.PlayerConnection.PlayerConnection #include "UnityEngine/Networking/PlayerConnection/PlayerConnection.hpp" // Including type: UnityEngine.Networking.PlayerConnection.PlayerConnection/<>c__DisplayClass12_0 #include "UnityEngine/Networking/PlayerConnection/PlayerConnection_--c__DisplayClass12_0.hpp" // Including type: UnityEngine.Networking.PlayerConnection.PlayerConnection/<>c__DisplayClass13_0 #include "UnityEngine/Networking/PlayerConnection/PlayerConnection_--c__DisplayClass13_0.hpp" // Including type: UnityEngine.Networking.PlayerConnection.PlayerConnection/<>c__DisplayClass20_0 #include "UnityEngine/Networking/PlayerConnection/PlayerConnection_--c__DisplayClass20_0.hpp" // Including type: UnityEngine.Networking.PlayerConnection.PlayerEditorConnectionEvents #include "UnityEngine/Networking/PlayerConnection/PlayerEditorConnectionEvents.hpp" // Including type: System.Collections.Generic.List`1 #include "System/Collections/Generic/List_1.hpp" // Including type: UnityEngine.IPlayerEditorConnectionNative #include "UnityEngine/IPlayerEditorConnectionNative.hpp" // Including type: System.Guid #include "System/Guid.hpp" // Including type: UnityEngine.Events.UnityAction`1 #include "UnityEngine/Events/UnityAction_1.hpp" // Including type: UnityEngine.Networking.PlayerConnection.MessageEventArgs #include "UnityEngine/Networking/PlayerConnection/MessageEventArgs.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated static field getter // Get static field: static UnityEngine.IPlayerEditorConnectionNative connectionNative UnityEngine::IPlayerEditorConnectionNative* UnityEngine::Networking::PlayerConnection::PlayerConnection::_get_connectionNative() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Networking::PlayerConnection::PlayerConnection::_get_connectionNative"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<UnityEngine::IPlayerEditorConnectionNative*>("UnityEngine.Networking.PlayerConnection", "PlayerConnection", "connectionNative")); } // Autogenerated static field setter // Set static field: static UnityEngine.IPlayerEditorConnectionNative connectionNative void UnityEngine::Networking::PlayerConnection::PlayerConnection::_set_connectionNative(UnityEngine::IPlayerEditorConnectionNative* value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Networking::PlayerConnection::PlayerConnection::_set_connectionNative"); THROW_UNLESS(il2cpp_utils::SetFieldValue("UnityEngine.Networking.PlayerConnection", "PlayerConnection", "connectionNative", value)); } // Autogenerated static field getter // Get static field: static private UnityEngine.Networking.PlayerConnection.PlayerConnection s_Instance UnityEngine::Networking::PlayerConnection::PlayerConnection* UnityEngine::Networking::PlayerConnection::PlayerConnection::_get_s_Instance() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Networking::PlayerConnection::PlayerConnection::_get_s_Instance"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<UnityEngine::Networking::PlayerConnection::PlayerConnection*>("UnityEngine.Networking.PlayerConnection", "PlayerConnection", "s_Instance")); } // Autogenerated static field setter // Set static field: static private UnityEngine.Networking.PlayerConnection.PlayerConnection s_Instance void UnityEngine::Networking::PlayerConnection::PlayerConnection::_set_s_Instance(UnityEngine::Networking::PlayerConnection::PlayerConnection* value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Networking::PlayerConnection::PlayerConnection::_set_s_Instance"); THROW_UNLESS(il2cpp_utils::SetFieldValue("UnityEngine.Networking.PlayerConnection", "PlayerConnection", "s_Instance", value)); } // Autogenerated method: UnityEngine.Networking.PlayerConnection.PlayerConnection.get_instance UnityEngine::Networking::PlayerConnection::PlayerConnection* UnityEngine::Networking::PlayerConnection::PlayerConnection::get_instance() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Networking::PlayerConnection::PlayerConnection::get_instance"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.Networking.PlayerConnection", "PlayerConnection", "get_instance", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Networking::PlayerConnection::PlayerConnection*, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method); } // Autogenerated method: UnityEngine.Networking.PlayerConnection.PlayerConnection.get_isConnected bool UnityEngine::Networking::PlayerConnection::PlayerConnection::get_isConnected() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Networking::PlayerConnection::PlayerConnection::get_isConnected"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_isConnected", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<bool, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Networking.PlayerConnection.PlayerConnection.CreateInstance UnityEngine::Networking::PlayerConnection::PlayerConnection* UnityEngine::Networking::PlayerConnection::PlayerConnection::CreateInstance() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Networking::PlayerConnection::PlayerConnection::CreateInstance"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.Networking.PlayerConnection", "PlayerConnection", "CreateInstance", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Networking::PlayerConnection::PlayerConnection*, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method); } // Autogenerated method: UnityEngine.Networking.PlayerConnection.PlayerConnection.OnEnable void UnityEngine::Networking::PlayerConnection::PlayerConnection::OnEnable() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Networking::PlayerConnection::PlayerConnection::OnEnable"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "OnEnable", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Networking.PlayerConnection.PlayerConnection.GetConnectionNativeApi UnityEngine::IPlayerEditorConnectionNative* UnityEngine::Networking::PlayerConnection::PlayerConnection::GetConnectionNativeApi() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Networking::PlayerConnection::PlayerConnection::GetConnectionNativeApi"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "GetConnectionNativeApi", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::IPlayerEditorConnectionNative*, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Networking.PlayerConnection.PlayerConnection.Register void UnityEngine::Networking::PlayerConnection::PlayerConnection::Register(System::Guid messageId, UnityEngine::Events::UnityAction_1<UnityEngine::Networking::PlayerConnection::MessageEventArgs*>* callback) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Networking::PlayerConnection::PlayerConnection::Register"); auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Register", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(messageId), ::il2cpp_utils::ExtractType(callback)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, messageId, callback); } // Autogenerated method: UnityEngine.Networking.PlayerConnection.PlayerConnection.Unregister void UnityEngine::Networking::PlayerConnection::PlayerConnection::Unregister(System::Guid messageId, UnityEngine::Events::UnityAction_1<UnityEngine::Networking::PlayerConnection::MessageEventArgs*>* callback) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Networking::PlayerConnection::PlayerConnection::Unregister"); auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Unregister", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(messageId), ::il2cpp_utils::ExtractType(callback)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, messageId, callback); } // Autogenerated method: UnityEngine.Networking.PlayerConnection.PlayerConnection.RegisterConnection void UnityEngine::Networking::PlayerConnection::PlayerConnection::RegisterConnection(UnityEngine::Events::UnityAction_1<int>* callback) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Networking::PlayerConnection::PlayerConnection::RegisterConnection"); auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "RegisterConnection", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(callback)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, callback); } // Autogenerated method: UnityEngine.Networking.PlayerConnection.PlayerConnection.RegisterDisconnection void UnityEngine::Networking::PlayerConnection::PlayerConnection::RegisterDisconnection(UnityEngine::Events::UnityAction_1<int>* callback) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Networking::PlayerConnection::PlayerConnection::RegisterDisconnection"); auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "RegisterDisconnection", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(callback)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, callback); } // Autogenerated method: UnityEngine.Networking.PlayerConnection.PlayerConnection.UnregisterConnection void UnityEngine::Networking::PlayerConnection::PlayerConnection::UnregisterConnection(UnityEngine::Events::UnityAction_1<int>* callback) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Networking::PlayerConnection::PlayerConnection::UnregisterConnection"); auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "UnregisterConnection", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(callback)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, callback); } // Autogenerated method: UnityEngine.Networking.PlayerConnection.PlayerConnection.UnregisterDisconnection void UnityEngine::Networking::PlayerConnection::PlayerConnection::UnregisterDisconnection(UnityEngine::Events::UnityAction_1<int>* callback) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Networking::PlayerConnection::PlayerConnection::UnregisterDisconnection"); auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "UnregisterDisconnection", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(callback)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, callback); } // Autogenerated method: UnityEngine.Networking.PlayerConnection.PlayerConnection.Send void UnityEngine::Networking::PlayerConnection::PlayerConnection::Send(System::Guid messageId, ::Array<uint8_t>* data) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Networking::PlayerConnection::PlayerConnection::Send"); auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Send", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(messageId), ::il2cpp_utils::ExtractType(data)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, messageId, data); } // Autogenerated method: UnityEngine.Networking.PlayerConnection.PlayerConnection.TrySend bool UnityEngine::Networking::PlayerConnection::PlayerConnection::TrySend(System::Guid messageId, ::Array<uint8_t>* data) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Networking::PlayerConnection::PlayerConnection::TrySend"); auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "TrySend", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(messageId), ::il2cpp_utils::ExtractType(data)}))); return ::il2cpp_utils::RunMethodThrow<bool, false>(this, ___internal__method, messageId, data); } // Autogenerated method: UnityEngine.Networking.PlayerConnection.PlayerConnection.BlockUntilRecvMsg bool UnityEngine::Networking::PlayerConnection::PlayerConnection::BlockUntilRecvMsg(System::Guid messageId, int timeout) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Networking::PlayerConnection::PlayerConnection::BlockUntilRecvMsg"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "BlockUntilRecvMsg", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(messageId), ::il2cpp_utils::ExtractType(timeout)}))); return ::il2cpp_utils::RunMethodThrow<bool, false>(this, ___internal__method, messageId, timeout); } // Autogenerated method: UnityEngine.Networking.PlayerConnection.PlayerConnection.DisconnectAll void UnityEngine::Networking::PlayerConnection::PlayerConnection::DisconnectAll() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Networking::PlayerConnection::PlayerConnection::DisconnectAll"); auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "DisconnectAll", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Networking.PlayerConnection.PlayerConnection.MessageCallbackInternal void UnityEngine::Networking::PlayerConnection::PlayerConnection::MessageCallbackInternal(System::IntPtr data, uint64_t size, uint64_t guid, ::Il2CppString* messageId) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Networking::PlayerConnection::PlayerConnection::MessageCallbackInternal"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.Networking.PlayerConnection", "PlayerConnection", "MessageCallbackInternal", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(data), ::il2cpp_utils::ExtractType(size), ::il2cpp_utils::ExtractType(guid), ::il2cpp_utils::ExtractType(messageId)}))); ::il2cpp_utils::RunMethodThrow<void, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, data, size, guid, messageId); } // Autogenerated method: UnityEngine.Networking.PlayerConnection.PlayerConnection.ConnectedCallbackInternal void UnityEngine::Networking::PlayerConnection::PlayerConnection::ConnectedCallbackInternal(int playerId) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Networking::PlayerConnection::PlayerConnection::ConnectedCallbackInternal"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.Networking.PlayerConnection", "PlayerConnection", "ConnectedCallbackInternal", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(playerId)}))); ::il2cpp_utils::RunMethodThrow<void, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, playerId); } // Autogenerated method: UnityEngine.Networking.PlayerConnection.PlayerConnection.DisconnectedCallback void UnityEngine::Networking::PlayerConnection::PlayerConnection::DisconnectedCallback(int playerId) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Networking::PlayerConnection::PlayerConnection::DisconnectedCallback"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("UnityEngine.Networking.PlayerConnection", "PlayerConnection", "DisconnectedCallback", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(playerId)}))); ::il2cpp_utils::RunMethodThrow<void, false>(static_cast<Il2CppClass*>(nullptr), ___internal__method, playerId); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes // Including type: UnityEngine.Networking.PlayerConnection.PlayerConnection/<>c__DisplayClass12_0 #include "UnityEngine/Networking/PlayerConnection/PlayerConnection_--c__DisplayClass12_0.hpp" // Including type: UnityEngine.Networking.PlayerConnection.PlayerEditorConnectionEvents/MessageTypeSubscribers #include "UnityEngine/Networking/PlayerConnection/PlayerEditorConnectionEvents_MessageTypeSubscribers.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated method: UnityEngine.Networking.PlayerConnection.PlayerConnection/<>c__DisplayClass12_0.<Register>b__0 bool UnityEngine::Networking::PlayerConnection::PlayerConnection::$$c__DisplayClass12_0::$Register$b__0(UnityEngine::Networking::PlayerConnection::PlayerEditorConnectionEvents::MessageTypeSubscribers* x) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Networking::PlayerConnection::PlayerConnection::$$c__DisplayClass12_0::<Register>b__0"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "<Register>b__0", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(x)}))); return ::il2cpp_utils::RunMethodThrow<bool, false>(this, ___internal__method, x); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes // Including type: UnityEngine.Networking.PlayerConnection.PlayerConnection/<>c__DisplayClass13_0 #include "UnityEngine/Networking/PlayerConnection/PlayerConnection_--c__DisplayClass13_0.hpp" // Including type: UnityEngine.Networking.PlayerConnection.PlayerEditorConnectionEvents/MessageTypeSubscribers #include "UnityEngine/Networking/PlayerConnection/PlayerEditorConnectionEvents_MessageTypeSubscribers.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated method: UnityEngine.Networking.PlayerConnection.PlayerConnection/<>c__DisplayClass13_0.<Unregister>b__0 bool UnityEngine::Networking::PlayerConnection::PlayerConnection::$$c__DisplayClass13_0::$Unregister$b__0(UnityEngine::Networking::PlayerConnection::PlayerEditorConnectionEvents::MessageTypeSubscribers* x) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Networking::PlayerConnection::PlayerConnection::$$c__DisplayClass13_0::<Unregister>b__0"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "<Unregister>b__0", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(x)}))); return ::il2cpp_utils::RunMethodThrow<bool, false>(this, ___internal__method, x); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes // Including type: UnityEngine.Networking.PlayerConnection.PlayerConnection/<>c__DisplayClass20_0 #include "UnityEngine/Networking/PlayerConnection/PlayerConnection_--c__DisplayClass20_0.hpp" // Including type: UnityEngine.Networking.PlayerConnection.MessageEventArgs #include "UnityEngine/Networking/PlayerConnection/MessageEventArgs.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated method: UnityEngine.Networking.PlayerConnection.PlayerConnection/<>c__DisplayClass20_0.<BlockUntilRecvMsg>b__0 void UnityEngine::Networking::PlayerConnection::PlayerConnection::$$c__DisplayClass20_0::$BlockUntilRecvMsg$b__0(UnityEngine::Networking::PlayerConnection::MessageEventArgs* args) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Networking::PlayerConnection::PlayerConnection::$$c__DisplayClass20_0::<BlockUntilRecvMsg>b__0"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "<BlockUntilRecvMsg>b__0", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(args)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, args); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: UnityEngine.Networking.PlayerConnection.PlayerEditorConnectionEvents #include "UnityEngine/Networking/PlayerConnection/PlayerEditorConnectionEvents.hpp" // Including type: UnityEngine.Networking.PlayerConnection.PlayerEditorConnectionEvents/MessageEvent #include "UnityEngine/Networking/PlayerConnection/PlayerEditorConnectionEvents_MessageEvent.hpp" // Including type: UnityEngine.Networking.PlayerConnection.PlayerEditorConnectionEvents/ConnectionChangeEvent #include "UnityEngine/Networking/PlayerConnection/PlayerEditorConnectionEvents_ConnectionChangeEvent.hpp" // Including type: UnityEngine.Networking.PlayerConnection.PlayerEditorConnectionEvents/MessageTypeSubscribers #include "UnityEngine/Networking/PlayerConnection/PlayerEditorConnectionEvents_MessageTypeSubscribers.hpp" // Including type: UnityEngine.Networking.PlayerConnection.PlayerEditorConnectionEvents/<>c__DisplayClass6_0 #include "UnityEngine/Networking/PlayerConnection/PlayerEditorConnectionEvents_--c__DisplayClass6_0.hpp" // Including type: UnityEngine.Networking.PlayerConnection.PlayerEditorConnectionEvents/<>c__DisplayClass7_0 #include "UnityEngine/Networking/PlayerConnection/PlayerEditorConnectionEvents_--c__DisplayClass7_0.hpp" // Including type: UnityEngine.Networking.PlayerConnection.PlayerEditorConnectionEvents/<>c__DisplayClass8_0 #include "UnityEngine/Networking/PlayerConnection/PlayerEditorConnectionEvents_--c__DisplayClass8_0.hpp" // Including type: System.Collections.Generic.List`1 #include "System/Collections/Generic/List_1.hpp" // Including type: System.Guid #include "System/Guid.hpp" // Including type: UnityEngine.Events.UnityEvent`1 #include "UnityEngine/Events/UnityEvent_1.hpp" // Including type: UnityEngine.Networking.PlayerConnection.MessageEventArgs #include "UnityEngine/Networking/PlayerConnection/MessageEventArgs.hpp" // Including type: UnityEngine.Events.UnityAction`1 #include "UnityEngine/Events/UnityAction_1.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated method: UnityEngine.Networking.PlayerConnection.PlayerEditorConnectionEvents.InvokeMessageIdSubscribers void UnityEngine::Networking::PlayerConnection::PlayerEditorConnectionEvents::InvokeMessageIdSubscribers(System::Guid messageId, ::Array<uint8_t>* data, int playerId) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Networking::PlayerConnection::PlayerEditorConnectionEvents::InvokeMessageIdSubscribers"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "InvokeMessageIdSubscribers", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(messageId), ::il2cpp_utils::ExtractType(data), ::il2cpp_utils::ExtractType(playerId)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, messageId, data, playerId); } // Autogenerated method: UnityEngine.Networking.PlayerConnection.PlayerEditorConnectionEvents.AddAndCreate UnityEngine::Events::UnityEvent_1<UnityEngine::Networking::PlayerConnection::MessageEventArgs*>* UnityEngine::Networking::PlayerConnection::PlayerEditorConnectionEvents::AddAndCreate(System::Guid messageId) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Networking::PlayerConnection::PlayerEditorConnectionEvents::AddAndCreate"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "AddAndCreate", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(messageId)}))); return ::il2cpp_utils::RunMethodThrow<UnityEngine::Events::UnityEvent_1<UnityEngine::Networking::PlayerConnection::MessageEventArgs*>*, false>(this, ___internal__method, messageId); } // Autogenerated method: UnityEngine.Networking.PlayerConnection.PlayerEditorConnectionEvents.UnregisterManagedCallback void UnityEngine::Networking::PlayerConnection::PlayerEditorConnectionEvents::UnregisterManagedCallback(System::Guid messageId, UnityEngine::Events::UnityAction_1<UnityEngine::Networking::PlayerConnection::MessageEventArgs*>* callback) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Networking::PlayerConnection::PlayerEditorConnectionEvents::UnregisterManagedCallback"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "UnregisterManagedCallback", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(messageId), ::il2cpp_utils::ExtractType(callback)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, messageId, callback); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes // Including type: UnityEngine.Networking.PlayerConnection.PlayerEditorConnectionEvents/MessageEvent #include "UnityEngine/Networking/PlayerConnection/PlayerEditorConnectionEvents_MessageEvent.hpp" // Including type: UnityEngine.Networking.PlayerConnection.MessageEventArgs #include "UnityEngine/Networking/PlayerConnection/MessageEventArgs.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes // Including type: UnityEngine.Networking.PlayerConnection.PlayerEditorConnectionEvents/ConnectionChangeEvent #include "UnityEngine/Networking/PlayerConnection/PlayerEditorConnectionEvents_ConnectionChangeEvent.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: UnityEngine.Networking.PlayerConnection.PlayerEditorConnectionEvents/MessageTypeSubscribers #include "UnityEngine/Networking/PlayerConnection/PlayerEditorConnectionEvents_MessageTypeSubscribers.hpp" // Including type: System.Guid #include "System/Guid.hpp" // Including type: UnityEngine.Networking.PlayerConnection.PlayerEditorConnectionEvents/MessageEvent #include "UnityEngine/Networking/PlayerConnection/PlayerEditorConnectionEvents_MessageEvent.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated method: UnityEngine.Networking.PlayerConnection.PlayerEditorConnectionEvents/MessageTypeSubscribers.get_MessageTypeId System::Guid UnityEngine::Networking::PlayerConnection::PlayerEditorConnectionEvents::MessageTypeSubscribers::get_MessageTypeId() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Networking::PlayerConnection::PlayerEditorConnectionEvents::MessageTypeSubscribers::get_MessageTypeId"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_MessageTypeId", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<System::Guid, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Networking.PlayerConnection.PlayerEditorConnectionEvents/MessageTypeSubscribers.set_MessageTypeId void UnityEngine::Networking::PlayerConnection::PlayerEditorConnectionEvents::MessageTypeSubscribers::set_MessageTypeId(System::Guid value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Networking::PlayerConnection::PlayerEditorConnectionEvents::MessageTypeSubscribers::set_MessageTypeId"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "set_MessageTypeId", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)}))); ::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, value); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes // Including type: UnityEngine.Networking.PlayerConnection.PlayerEditorConnectionEvents/<>c__DisplayClass6_0 #include "UnityEngine/Networking/PlayerConnection/PlayerEditorConnectionEvents_--c__DisplayClass6_0.hpp" // Including type: UnityEngine.Networking.PlayerConnection.PlayerEditorConnectionEvents/MessageTypeSubscribers #include "UnityEngine/Networking/PlayerConnection/PlayerEditorConnectionEvents_MessageTypeSubscribers.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated method: UnityEngine.Networking.PlayerConnection.PlayerEditorConnectionEvents/<>c__DisplayClass6_0.<InvokeMessageIdSubscribers>b__0 bool UnityEngine::Networking::PlayerConnection::PlayerEditorConnectionEvents::$$c__DisplayClass6_0::$InvokeMessageIdSubscribers$b__0(UnityEngine::Networking::PlayerConnection::PlayerEditorConnectionEvents::MessageTypeSubscribers* x) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Networking::PlayerConnection::PlayerEditorConnectionEvents::$$c__DisplayClass6_0::<InvokeMessageIdSubscribers>b__0"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "<InvokeMessageIdSubscribers>b__0", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(x)}))); return ::il2cpp_utils::RunMethodThrow<bool, false>(this, ___internal__method, x); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes // Including type: UnityEngine.Networking.PlayerConnection.PlayerEditorConnectionEvents/<>c__DisplayClass7_0 #include "UnityEngine/Networking/PlayerConnection/PlayerEditorConnectionEvents_--c__DisplayClass7_0.hpp" // Including type: UnityEngine.Networking.PlayerConnection.PlayerEditorConnectionEvents/MessageTypeSubscribers #include "UnityEngine/Networking/PlayerConnection/PlayerEditorConnectionEvents_MessageTypeSubscribers.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated method: UnityEngine.Networking.PlayerConnection.PlayerEditorConnectionEvents/<>c__DisplayClass7_0.<AddAndCreate>b__0 bool UnityEngine::Networking::PlayerConnection::PlayerEditorConnectionEvents::$$c__DisplayClass7_0::$AddAndCreate$b__0(UnityEngine::Networking::PlayerConnection::PlayerEditorConnectionEvents::MessageTypeSubscribers* x) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Networking::PlayerConnection::PlayerEditorConnectionEvents::$$c__DisplayClass7_0::<AddAndCreate>b__0"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "<AddAndCreate>b__0", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(x)}))); return ::il2cpp_utils::RunMethodThrow<bool, false>(this, ___internal__method, x); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes // Including type: UnityEngine.Networking.PlayerConnection.PlayerEditorConnectionEvents/<>c__DisplayClass8_0 #include "UnityEngine/Networking/PlayerConnection/PlayerEditorConnectionEvents_--c__DisplayClass8_0.hpp" // Including type: UnityEngine.Networking.PlayerConnection.PlayerEditorConnectionEvents/MessageTypeSubscribers #include "UnityEngine/Networking/PlayerConnection/PlayerEditorConnectionEvents_MessageTypeSubscribers.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated method: UnityEngine.Networking.PlayerConnection.PlayerEditorConnectionEvents/<>c__DisplayClass8_0.<UnregisterManagedCallback>b__0 bool UnityEngine::Networking::PlayerConnection::PlayerEditorConnectionEvents::$$c__DisplayClass8_0::$UnregisterManagedCallback$b__0(UnityEngine::Networking::PlayerConnection::PlayerEditorConnectionEvents::MessageTypeSubscribers* x) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Networking::PlayerConnection::PlayerEditorConnectionEvents::$$c__DisplayClass8_0::<UnregisterManagedCallback>b__0"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "<UnregisterManagedCallback>b__0", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(x)}))); return ::il2cpp_utils::RunMethodThrow<bool, false>(this, ___internal__method, x); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: UnityEngine.Internal.DefaultValueAttribute #include "UnityEngine/Internal/DefaultValueAttribute.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated method: UnityEngine.Internal.DefaultValueAttribute.get_Value ::Il2CppObject* UnityEngine::Internal::DefaultValueAttribute::get_Value() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Internal::DefaultValueAttribute::get_Value"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_Value", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<::Il2CppObject*, false>(this, ___internal__method); } // Autogenerated method: UnityEngine.Internal.DefaultValueAttribute.Equals bool UnityEngine::Internal::DefaultValueAttribute::Equals(::Il2CppObject* obj) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Internal::DefaultValueAttribute::Equals"); auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Equals", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(obj)}))); return ::il2cpp_utils::RunMethodThrow<bool, false>(this, ___internal__method, obj); } // Autogenerated method: UnityEngine.Internal.DefaultValueAttribute.GetHashCode int UnityEngine::Internal::DefaultValueAttribute::GetHashCode() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Internal::DefaultValueAttribute::GetHashCode"); auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "GetHashCode", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodThrow<int, false>(this, ___internal__method); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes // Including type: UnityEngine.Internal.ExcludeFromDocsAttribute #include "UnityEngine/Internal/ExcludeFromDocsAttribute.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes // Including type: UnityEngine.Rendering.ShaderHardwareTier #include "UnityEngine/Rendering/ShaderHardwareTier.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated static field getter // Get static field: static public UnityEngine.Rendering.ShaderHardwareTier Tier1 UnityEngine::Rendering::ShaderHardwareTier UnityEngine::Rendering::ShaderHardwareTier::_get_Tier1() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Rendering::ShaderHardwareTier::_get_Tier1"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<UnityEngine::Rendering::ShaderHardwareTier>("UnityEngine.Rendering", "ShaderHardwareTier", "Tier1")); } // Autogenerated static field setter // Set static field: static public UnityEngine.Rendering.ShaderHardwareTier Tier1 void UnityEngine::Rendering::ShaderHardwareTier::_set_Tier1(UnityEngine::Rendering::ShaderHardwareTier value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Rendering::ShaderHardwareTier::_set_Tier1"); THROW_UNLESS(il2cpp_utils::SetFieldValue("UnityEngine.Rendering", "ShaderHardwareTier", "Tier1", value)); } // Autogenerated static field getter // Get static field: static public UnityEngine.Rendering.ShaderHardwareTier Tier2 UnityEngine::Rendering::ShaderHardwareTier UnityEngine::Rendering::ShaderHardwareTier::_get_Tier2() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Rendering::ShaderHardwareTier::_get_Tier2"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<UnityEngine::Rendering::ShaderHardwareTier>("UnityEngine.Rendering", "ShaderHardwareTier", "Tier2")); } // Autogenerated static field setter // Set static field: static public UnityEngine.Rendering.ShaderHardwareTier Tier2 void UnityEngine::Rendering::ShaderHardwareTier::_set_Tier2(UnityEngine::Rendering::ShaderHardwareTier value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Rendering::ShaderHardwareTier::_set_Tier2"); THROW_UNLESS(il2cpp_utils::SetFieldValue("UnityEngine.Rendering", "ShaderHardwareTier", "Tier2", value)); } // Autogenerated static field getter // Get static field: static public UnityEngine.Rendering.ShaderHardwareTier Tier3 UnityEngine::Rendering::ShaderHardwareTier UnityEngine::Rendering::ShaderHardwareTier::_get_Tier3() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Rendering::ShaderHardwareTier::_get_Tier3"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<UnityEngine::Rendering::ShaderHardwareTier>("UnityEngine.Rendering", "ShaderHardwareTier", "Tier3")); } // Autogenerated static field setter // Set static field: static public UnityEngine.Rendering.ShaderHardwareTier Tier3 void UnityEngine::Rendering::ShaderHardwareTier::_set_Tier3(UnityEngine::Rendering::ShaderHardwareTier value) { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Rendering::ShaderHardwareTier::_set_Tier3"); THROW_UNLESS(il2cpp_utils::SetFieldValue("UnityEngine.Rendering", "ShaderHardwareTier", "Tier3", value)); }
87.991759
519
0.790114
[ "object", "vector", "transform" ]
32c60cc4ffa3c554c13f6741254fde6739ef362f
52,254
cpp
C++
src/BlueSCSI.cpp
mactcp/BlueSCSI
7b7f19413c08093cdb2664f90d8f78ad5499a0f5
[ "MIT" ]
null
null
null
src/BlueSCSI.cpp
mactcp/BlueSCSI
7b7f19413c08093cdb2664f90d8f78ad5499a0f5
[ "MIT" ]
null
null
null
src/BlueSCSI.cpp
mactcp/BlueSCSI
7b7f19413c08093cdb2664f90d8f78ad5499a0f5
[ "MIT" ]
null
null
null
/* * BlueSCSI * Copyright (c) 2021 Eric Helgeson, Androda * * This file is free software: you may copy, redistribute and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation, either version 2 of the License, or (at your * option) any later version. * * This file is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see https://github.com/erichelgeson/bluescsi. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright (c) 2019 komatsu * * Permission to use, copy, modify, and/or distribute this software * for any purpose with or without fee is hereby granted, provided * that the above copyright notice and this permission notice appear * in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL * WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE * AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <Arduino.h> // For Platform.IO #include <SdFat.h> #include <setjmp.h> #ifdef USE_STM32_DMA #warning "warning USE_STM32_DMA" #endif #define DEBUG 0 // 0:No debug information output // 1: Debug information output to USB Serial // 2: Debug information output to LOG.txt (slow) #define SCSI_SELECT 0 // 0 for STANDARD // 1 for SHARP X1turbo // 2 for NEC PC98 #define READ_SPEED_OPTIMIZE 1 // Faster reads #define WRITE_SPEED_OPTIMIZE 1 // Speeding up writes // SCSI config #define NUM_SCSIID 7 // Maximum number of supported SCSI-IDs (The minimum is 0) #define NUM_SCSILUN 2 // Maximum number of LUNs supported (The minimum is 0) #define READ_PARITY_CHECK 0 // Perform read parity check (unverified) // HDD format #define MAX_BLOCKSIZE 2048 // Maximum BLOCK size // SDFAT SdFs SD; #if DEBUG == 1 #define LOG(XX) Serial.print(XX) #define LOGHEX(XX) Serial.print(XX, HEX) #define LOGN(XX) Serial.println(XX) #define LOGHEXN(XX) Serial.println(XX, HEX) #elif DEBUG == 2 #define LOG(XX) LOG_FILE.print(XX); LOG_FILE.sync(); #define LOGHEX(XX) LOG_FILE.print(XX, HEX); LOG_FILE.sync(); #define LOGN(XX) LOG_FILE.println(XX); LOG_FILE.sync(); #define LOGHEXN(XX) LOG_FILE.println(XX, HEX); LOG_FILE.sync(); #else #define LOG(XX) //Serial.print(XX) #define LOGHEX(XX) //Serial.print(XX, HEX) #define LOGN(XX) //Serial.println(XX) #define LOGHEXN(XX) //Serial.println(XX, HEX) #endif #define active 1 #define inactive 0 #define high 0 #define low 1 #define isHigh(XX) ((XX) == high) #define isLow(XX) ((XX) != high) #define gpio_mode(pin,val) gpio_set_mode(PIN_MAP[pin].gpio_device, PIN_MAP[pin].gpio_bit, val); #define gpio_write(pin,val) gpio_write_bit(PIN_MAP[pin].gpio_device, PIN_MAP[pin].gpio_bit, val) #define gpio_read(pin) gpio_read_bit(PIN_MAP[pin].gpio_device, PIN_MAP[pin].gpio_bit) //#define DB0 PB8 // SCSI:DB0 //#define DB1 PB9 // SCSI:DB1 //#define DB2 PB10 // SCSI:DB2 //#define DB3 PB11 // SCSI:DB3 //#define DB4 PB12 // SCSI:DB4 //#define DB5 PB13 // SCSI:DB5 //#define DB6 PB14 // SCSI:DB6 //#define DB7 PB15 // SCSI:DB7 //#define DBP PB0 // SCSI:DBP #define ATN PA8 // SCSI:ATN #define BSY PA9 // SCSI:BSY #define ACK PA10 // SCSI:ACK #define RST PA15 // SCSI:RST #define MSG PB3 // SCSI:MSG #define SEL PB4 // SCSI:SEL #define CD PB5 // SCSI:C/D #define REQ PB6 // SCSI:REQ #define IO PB7 // SCSI:I/O #define LED2 PA0 // External LED #define SD_CS PA4 // SDCARD:CS #define LED PC13 // LED // Image Set Selector #ifdef XCVR #define IMAGE_SELECT1 PC14 #define IMAGE_SELECT2 PC15 #else #define IMAGE_SELECT1 PA1 #define IMAGE_SELECT2 PB1 #endif // GPIO register port #define PAREG GPIOA->regs #define PBREG GPIOB->regs // LED control #define LED_ON() gpio_write(LED, high); gpio_write(LED2, low); #define LED_OFF() gpio_write(LED, low); gpio_write(LED2, high); // Virtual pin (Arduio compatibility is slow, so make it MCU-dependent) #define PA(BIT) (BIT) #define PB(BIT) (BIT+16) // Virtual pin decoding #define GPIOREG(VPIN) ((VPIN)>=16?PBREG:PAREG) #define BITMASK(VPIN) (1<<((VPIN)&15)) #define vATN PA(8) // SCSI:ATN #define vBSY PA(9) // SCSI:BSY #define vACK PA(10) // SCSI:ACK #define vRST PA(15) // SCSI:RST #define vMSG PB(3) // SCSI:MSG #define vSEL PB(4) // SCSI:SEL #define vCD PB(5) // SCSI:C/D #define vREQ PB(6) // SCSI:REQ #define vIO PB(7) // SCSI:I/O #define vSD_CS PA(4) // SDCARD:CS // SCSI output pin control: opendrain active LOW (direct pin drive) #define SCSI_OUT(VPIN,ACTIVE) { GPIOREG(VPIN)->BSRR = BITMASK(VPIN)<<((ACTIVE)?16:0); } // SCSI input pin check (inactive=0,avtive=1) #define SCSI_IN(VPIN) ((~GPIOREG(VPIN)->IDR>>(VPIN&15))&1) // SCSI phase change as single write to port B #define SCSIPHASEMASK(MSGACTIVE, CDACTIVE, IOACTIVE) ((BITMASK(vMSG)<<((MSGACTIVE)?16:0)) | (BITMASK(vCD)<<((CDACTIVE)?16:0)) | (BITMASK(vIO)<<((IOACTIVE)?16:0))) #define SCSI_PHASE_DATAOUT SCSIPHASEMASK(inactive, inactive, inactive) #define SCSI_PHASE_DATAIN SCSIPHASEMASK(inactive, inactive, active) #define SCSI_PHASE_COMMAND SCSIPHASEMASK(inactive, active, inactive) #define SCSI_PHASE_STATUS SCSIPHASEMASK(inactive, active, active) #define SCSI_PHASE_MESSAGEOUT SCSIPHASEMASK(active, active, inactive) #define SCSI_PHASE_MESSAGEIN SCSIPHASEMASK(active, active, active) #define SCSI_PHASE_CHANGE(MASK) { PBREG->BSRR = (MASK); } #ifdef XCVR #define TR_TARGET PA1 // Target Transceiver Control Pin #define TR_DBP PA2 // Data Pins Transceiver Control Pin #define TR_INITIATOR PA3 // Initiator Transciever Control Pin #define vTR_TARGET PA(1) // Target Transceiver Control Pin #define vTR_DBP PA(2) // Data Pins Transceiver Control Pin #define vTR_INITIATOR PA(3) // Initiator Transciever Control Pin #define TR_INPUT 1 #define TR_OUTPUT 0 // Transceiver control definitions #define TRANSCEIVER_IO_SET(VPIN,TR_INPUT) { GPIOREG(VPIN)->BSRR = BITMASK(VPIN) << ((TR_INPUT) ? 16 : 0); } // Turn on the output only for BSY #define SCSI_BSY_ACTIVE() { gpio_mode(BSY, GPIO_OUTPUT_PP); SCSI_OUT(vBSY, active) } #define SCSI_TARGET_ACTIVE() { gpio_mode(REQ, GPIO_OUTPUT_PP); gpio_mode(MSG, GPIO_OUTPUT_PP); gpio_mode(CD, GPIO_OUTPUT_PP); gpio_mode(IO, GPIO_OUTPUT_PP); gpio_mode(BSY, GPIO_OUTPUT_PP); TRANSCEIVER_IO_SET(vTR_TARGET,TR_OUTPUT);} // BSY,REQ,MSG,CD,IO Turn off output, BSY is the last input #define SCSI_TARGET_INACTIVE() { pinMode(REQ, INPUT); pinMode(MSG, INPUT); pinMode(CD, INPUT); pinMode(IO, INPUT); pinMode(BSY, INPUT); TRANSCEIVER_IO_SET(vTR_TARGET,TR_INPUT); } #define DB_MODE_OUT 1 // push-pull mode #define DB_MODE_IN 4 // floating inputs #else // GPIO mode // IN , FLOAT : 4 // IN , PU/PD : 8 // OUT, PUSH/PULL : 3 // OUT, OD : 7 #define DB_MODE_OUT 3 //#define DB_MODE_OUT 7 #define DB_MODE_IN 8 // Turn on the output only for BSY #define SCSI_BSY_ACTIVE() { gpio_mode(BSY, GPIO_OUTPUT_OD); SCSI_OUT(vBSY, active) } // BSY,REQ,MSG,CD,IO Turn on the output (no change required for OD) #define SCSI_TARGET_ACTIVE() { if (DB_MODE_OUT != 7) gpio_mode(REQ, GPIO_OUTPUT_PP);} // BSY,REQ,MSG,CD,IO Turn off output, BSY is the last input #define SCSI_TARGET_INACTIVE() { if (DB_MODE_OUT == 7) SCSI_OUT(vREQ,inactive) else { if (DB_MODE_IN == 8) gpio_mode(REQ, GPIO_INPUT_PU) else gpio_mode(REQ, GPIO_INPUT_FLOATING)} SCSI_PHASE_CHANGE(SCSI_PHASE_DATAOUT); gpio_mode(BSY, GPIO_INPUT_PU); } #endif // Put DB and DP in output mode #define SCSI_DB_OUTPUT() { PBREG->CRL=(PBREG->CRL &0xfffffff0)|DB_MODE_OUT; PBREG->CRH = 0x11111111*DB_MODE_OUT; } // Put DB and DP in input mode #define SCSI_DB_INPUT() { PBREG->CRL=(PBREG->CRL &0xfffffff0)|DB_MODE_IN ; PBREG->CRH = 0x11111111*DB_MODE_IN; } // HDDiamge file #define HDIMG_ID_POS 2 // Position to embed ID number #define HDIMG_LUN_POS 3 // Position to embed LUN numbers #define HDIMG_BLK_POS 5 // Position to embed block size numbers #define MAX_FILE_PATH 32 // Maximum file name length // HDD image typedef struct hddimg_struct { FsFile m_file; // File object uint64_t m_fileSize; // File size size_t m_blocksize; // SCSI BLOCK size }HDDIMG; HDDIMG img[NUM_SCSIID][NUM_SCSILUN]; // Maximum number uint8_t m_senseKey = 0; // Sense key uint16_t m_addition_sense = 0; // Additional sense information volatile bool m_isBusReset = false; // Bus reset volatile bool m_resetJmp = false; // Call longjmp on reset jmp_buf m_resetJmpBuf; byte scsi_id_mask; // Mask list of responding SCSI IDs byte m_id; // Currently responding SCSI-ID byte m_lun; // Logical unit number currently responding byte m_sts; // Status byte byte m_msg; // Message bytes HDDIMG *m_img; // HDD image for current SCSI-ID, LUN byte m_buf[MAX_BLOCKSIZE]; // General purpose buffer byte m_msb[256]; // Command storage bytes /* * Data byte to BSRR register setting value and parity table */ // Parity bit generation #define PTY(V) (1^((V)^((V)>>1)^((V)>>2)^((V)>>3)^((V)>>4)^((V)>>5)^((V)>>6)^((V)>>7))&1) // Data byte to BSRR register setting value conversion table // BSRR[31:24] = DB[7:0] // BSRR[ 16] = PTY(DB) // BSRR[15: 8] = ~DB[7:0] // BSRR[ 0] = ~PTY(DB) // Set DBP, set REQ = inactive #define DBP(D) ((((((uint32_t)(D)<<8)|PTY(D))*0x00010001)^0x0000ff01)|BITMASK(vREQ)) // BSRR register control value that simultaneously performs DB set, DP set, and REQ = H (inactrive) uint32_t db_bsrr[256]; // Parity bit acquisition #define PARITY(DB) (db_bsrr[DB]&1) // Macro cleaning #undef DBP32 #undef DBP8 //#undef DBP //#undef PTY // Log File #define VERSION "1.1-SNAPSHOT-20220407" #define LOG_FILENAME "LOG.txt" FsFile LOG_FILE; // SCSI Drive Vendor information byte SCSI_INFO_BUF[36] = { 0x00, //device type 0x00, //RMB = 0 0x01, //ISO, ECMA, ANSI version 0x01, //Response data format 35 - 4, //Additional data length 0, 0, //Reserve 0x00, //Support function 'Q', 'U', 'A', 'N', 'T', 'U', 'M', ' ', // vendor 8 'F', 'I', 'R', 'E', 'B', 'A', 'L', 'L', '1', ' ', ' ',' ', ' ', ' ', ' ', ' ', // product 16 '1', '.', '0', ' ' // version 4 }; void onFalseInit(void); void noSDCardFound(void); void onBusReset(void); void initFileLog(int); void finalizeFileLog(void); void findDriveImages(FsFile root); /* * IO read. */ inline byte readIO(void) { // Port input data register uint32_t ret = GPIOB->regs->IDR; byte bret = (byte)(~(ret>>8)); #if READ_PARITY_CHECK if((db_bsrr[bret]^ret)&1) m_sts |= 0x01; // parity error #endif return bret; } // If config file exists, read the first three lines and copy the contents. // File must be well formed or you will get junk in the SCSI Vendor fields. void readSCSIDeviceConfig() { FsFile config_file = SD.open("scsi-config.txt", O_RDONLY); if (!config_file.isOpen()) { return; } char vendor[9]; memset(vendor, 0, sizeof(vendor)); config_file.readBytes(vendor, sizeof(vendor)); LOG_FILE.print("SCSI VENDOR: "); LOG_FILE.println(vendor); memcpy(&(SCSI_INFO_BUF[8]), vendor, 8); char product[17]; memset(product, 0, sizeof(product)); config_file.readBytes(product, sizeof(product)); LOG_FILE.print("SCSI PRODUCT: "); LOG_FILE.println(product); memcpy(&(SCSI_INFO_BUF[16]), product, 16); char version[5]; memset(version, 0, sizeof(version)); config_file.readBytes(version, sizeof(version)); LOG_FILE.print("SCSI VERSION: "); LOG_FILE.println(version); memcpy(&(SCSI_INFO_BUF[32]), version, 4); config_file.close(); } // read SD information and print to logfile void readSDCardInfo() { cid_t sd_cid; if(SD.card()->readCID(&sd_cid)) { LOG_FILE.print("Sd MID:"); LOG_FILE.print(sd_cid.mid, 16); LOG_FILE.print(" OID:"); LOG_FILE.print(sd_cid.oid[0]); LOG_FILE.println(sd_cid.oid[1]); LOG_FILE.print("Sd Name:"); LOG_FILE.print(sd_cid.pnm[0]); LOG_FILE.print(sd_cid.pnm[1]); LOG_FILE.print(sd_cid.pnm[2]); LOG_FILE.print(sd_cid.pnm[3]); LOG_FILE.println(sd_cid.pnm[4]); LOG_FILE.print("Sd Date:"); LOG_FILE.print(sd_cid.mdt_month); LOG_FILE.print("/20"); // CID year is 2000 + high/low LOG_FILE.print(sd_cid.mdt_year_high); LOG_FILE.println(sd_cid.mdt_year_low); LOG_FILE.print("Sd Serial:"); LOG_FILE.println(sd_cid.psn); LOG_FILE.sync(); } } /* * Open HDD image file */ bool hddimageOpen(HDDIMG *h, FsFile file,int id,int lun,int blocksize) { h->m_fileSize = 0; h->m_blocksize = blocksize; h->m_file = file; if(h->m_file.isOpen()) { h->m_fileSize = h->m_file.size(); if(h->m_fileSize>0) { // check blocksize dummy file LOG_FILE.print(" / "); LOG_FILE.print(h->m_fileSize); LOG_FILE.print("bytes / "); LOG_FILE.print(h->m_fileSize / 1024); LOG_FILE.print("KiB / "); LOG_FILE.print(h->m_fileSize / 1024 / 1024); LOG_FILE.println("MiB"); return true; // File opened } else { LOG_FILE.println(" - file is 0 bytes, can not use."); h->m_file.close(); h->m_fileSize = h->m_blocksize = 0; // no file } } return false; } /* * Initialization. * Initialize the bus and set the PIN orientation */ void setup() { // PA15 / PB3 / PB4 Cannot be used // JTAG Because it is used for debugging. disableDebugPorts(); // Setup BSRR table for (unsigned i = 0; i <= 255; i++) { db_bsrr[i] = DBP(i); } // Serial initialization #if DEBUG > 0 Serial.begin(9600); // If using a USB->TTL monitor instead of USB serial monitor - you can uncomment this. //while (!Serial); #endif // PIN initialization gpio_mode(LED2, GPIO_OUTPUT_PP); gpio_mode(LED, GPIO_OUTPUT_OD); // Image Set Select Init gpio_mode(IMAGE_SELECT1, GPIO_INPUT_PU); gpio_mode(IMAGE_SELECT2, GPIO_INPUT_PU); pinMode(IMAGE_SELECT1, INPUT); pinMode(IMAGE_SELECT2, INPUT); int image_file_set = ((digitalRead(IMAGE_SELECT1) == LOW) ? 1 : 0) | ((digitalRead(IMAGE_SELECT2) == LOW) ? 2 : 0); LED_OFF(); #ifdef XCVR // Transceiver Pin Initialization pinMode(TR_TARGET, OUTPUT); pinMode(TR_INITIATOR, OUTPUT); pinMode(TR_DBP, OUTPUT); TRANSCEIVER_IO_SET(vTR_INITIATOR,TR_INPUT); #endif //GPIO(SCSI BUS)Initialization //Port setting register (lower) // GPIOB->regs->CRL |= 0x000000008; // SET INPUT W/ PUPD on PAB-PB0 //Port setting register (upper) //GPIOB->regs->CRH = 0x88888888; // SET INPUT W/ PUPD on PB15-PB8 // GPIOB->regs->ODR = 0x0000FF00; // SET PULL-UPs on PB15-PB8 // DB and DP are input modes SCSI_DB_INPUT() #ifdef XCVR TRANSCEIVER_IO_SET(vTR_DBP,TR_INPUT); // Initiator port pinMode(ATN, INPUT); pinMode(BSY, INPUT); pinMode(ACK, INPUT); pinMode(RST, INPUT); pinMode(SEL, INPUT); TRANSCEIVER_IO_SET(vTR_INITIATOR,TR_INPUT); // Target port pinMode(MSG, INPUT); pinMode(CD, INPUT); pinMode(REQ, INPUT); pinMode(IO, INPUT); TRANSCEIVER_IO_SET(vTR_TARGET,TR_INPUT); #else // Input port gpio_mode(ATN, GPIO_INPUT_PU); gpio_mode(BSY, GPIO_INPUT_PU); gpio_mode(ACK, GPIO_INPUT_PU); gpio_mode(RST, GPIO_INPUT_PU); gpio_mode(SEL, GPIO_INPUT_PU); // Output port gpio_mode(MSG, GPIO_OUTPUT_OD); gpio_mode(CD, GPIO_OUTPUT_OD); gpio_mode(REQ, GPIO_OUTPUT_OD); gpio_mode(IO, GPIO_OUTPUT_OD); // Turn off the output port SCSI_TARGET_INACTIVE() #endif //Occurs when the RST pin state changes from HIGH to LOW //attachInterrupt(RST, onBusReset, FALLING); // Try different clock speeds till we find one that is stable. LED_ON(); int mhz = 50; bool sd_ready = false; while (mhz >= 32 && !sd_ready) { if(SD.begin(SdSpiConfig(PA4, DEDICATED_SPI, SD_SCK_MHZ(mhz), &SPI))) { sd_ready = true; } else { mhz--; } } LED_OFF(); if(!sd_ready) { #if DEBUG > 0 Serial.println("SD initialization failed!"); #endif noSDCardFound(); } initFileLog(mhz); readSCSIDeviceConfig(); readSDCardInfo(); //HD image file open scsi_id_mask = 0x00; // Iterate over the root path in the SD card looking for candidate image files. FsFile root; char image_set_dir_name[] = "/ImageSetX/"; image_set_dir_name[9] = char(image_file_set) + 0x30; root.open(image_set_dir_name); if (root.isDirectory()) { LOG_FILE.print("Looking for images in: "); LOG_FILE.println(image_set_dir_name); LOG_FILE.sync(); } else { root.close(); root.open("/"); } findDriveImages(root); root.close(); FsFile images_all_dir; images_all_dir.open("/ImageSetAll/"); if (images_all_dir.isDirectory()) { LOG_FILE.println("Looking for images in: /ImageSetAll/"); LOG_FILE.sync(); findDriveImages(images_all_dir); } images_all_dir.close(); // Error if there are 0 image files if(scsi_id_mask==0) { LOG_FILE.println("ERROR: No valid images found!"); onFalseInit(); } finalizeFileLog(); LED_OFF(); //Occurs when the RST pin state changes from HIGH to LOW attachInterrupt(RST, onBusReset, FALLING); } void findDriveImages(FsFile root) { bool image_ready; FsFile file; char path_name[MAX_FILE_PATH+1]; root.getName(path_name, sizeof(path_name)); SD.chdir(path_name); while (1) { // Directories can not be opened RDWR, so it will fail, but fails the same way with no file/dir, so we need to peek at the file first. FsFile file_test = root.openNextFile(O_RDONLY); char name[MAX_FILE_PATH+1]; file_test.getName(name, MAX_FILE_PATH+1); String file_name = String(name); // Skip directories and already open files. if(file_test.isDir() || file_name.startsWith("LOG.txt")) { file_test.close(); continue; } // If error there is no next file to open. if(file_test.getError() > 0) { file_test.close(); break; } // Valid file, open for reading/writing. file = SD.open(name, O_RDWR); if(file && file.isFile()) { file_name.toLowerCase(); if(file_name.startsWith("hd")) { // Defaults for Hard Disks int id = 1; // 0 and 3 are common in Macs for physical HD and CD, so avoid them. int lun = 0; int blk = 512; // Positionally read in and coerase the chars to integers. // We only require the minimum and read in the next if provided. int file_name_length = file_name.length(); if(file_name_length > 2) { // HD[N] int tmp_id = name[HDIMG_ID_POS] - '0'; // If valid id, set it, else use default if(tmp_id > -1 && tmp_id < 8) { id = tmp_id; } else { LOG_FILE.print(name); LOG_FILE.println(" - bad SCSI id in filename, Using default ID 1"); } } int blk1 = 0, blk2, blk3, blk4 = 0; if(file_name_length > 8) { // HD00_[111] blk1 = name[HDIMG_BLK_POS] - '0'; blk2 = name[HDIMG_BLK_POS+1] - '0'; blk3 = name[HDIMG_BLK_POS+2] - '0'; if(file_name_length > 9) // HD00_NNN[1] blk4 = name[HDIMG_BLK_POS+3] - '0'; } if(blk1 == 2 && blk2 == 5 && blk3 == 6) { blk = 256; } else if(blk1 == 1 && blk2 == 0 && blk3 == 2 && blk4 == 4) { blk = 1024; } else if(blk1 == 2 && blk2 == 0 && blk3 == 4 && blk4 == 8) { blk = 2048; } if(id < NUM_SCSIID && lun < NUM_SCSILUN) { HDDIMG *h = &img[id][lun]; LOG_FILE.print(" - "); LOG_FILE.print(name); image_ready = hddimageOpen(h, file, id, lun, blk); if(image_ready) { // Marked as a responsive ID scsi_id_mask |= 1<<id; } } } } else { file.close(); LOG_FILE.print("Not an image: "); LOG_FILE.println(name); } LOG_FILE.sync(); } // cd .. before going back. SD.chdir("/"); } /* * Setup initialization logfile */ void initFileLog(int success_mhz) { LOG_FILE = SD.open(LOG_FILENAME, O_WRONLY | O_CREAT | O_TRUNC); LOG_FILE.println("BlueSCSI <-> SD - https://github.com/erichelgeson/BlueSCSI"); LOG_FILE.print("VERSION: "); LOG_FILE.println(VERSION); LOG_FILE.print("DEBUG:"); LOG_FILE.print(DEBUG); LOG_FILE.print(" SCSI_SELECT:"); LOG_FILE.print(SCSI_SELECT); LOG_FILE.print(" SDFAT_FILE_TYPE:"); LOG_FILE.println(SDFAT_FILE_TYPE); LOG_FILE.print("SdFat version: "); LOG_FILE.println(SD_FAT_VERSION_STR); LOG_FILE.print("SPI speed: "); LOG_FILE.print(success_mhz); LOG_FILE.println("Mhz"); if(success_mhz < 40) { LOG_FILE.println("SPI under 40Mhz - read https://github.com/erichelgeson/BlueSCSI/wiki/Slow-SPI"); } LOG_FILE.print("SdFat Max FileName Length: "); LOG_FILE.println(MAX_FILE_PATH); LOG_FILE.println("Initialized SD Card - lets go!"); LOG_FILE.sync(); } /* * Finalize initialization logfile */ void finalizeFileLog() { // View support drive map LOG_FILE.print("ID"); for(int lun=0;lun<NUM_SCSILUN;lun++) { LOG_FILE.print(":LUN"); LOG_FILE.print(lun); } LOG_FILE.println(":"); // for(int id=0;id<NUM_SCSIID;id++) { LOG_FILE.print(" "); LOG_FILE.print(id); for(int lun=0;lun<NUM_SCSILUN;lun++) { HDDIMG *h = &img[id][lun]; if( (lun<NUM_SCSILUN) && (h->m_file)) { LOG_FILE.print((h->m_blocksize<1000) ? ": " : ":"); LOG_FILE.print(h->m_blocksize); } else LOG_FILE.print(":----"); } LOG_FILE.println(":"); } LOG_FILE.println("Finished initialization of SCSI Devices - Entering main loop."); LOG_FILE.sync(); LOG_FILE.close(); } /* * Initialization failed, blink 3x fast */ void onFalseInit(void) { LOG_FILE.sync(); while(true) { for(int i = 0; i < 3; i++) { LED_ON(); delay(250); LED_OFF(); delay(250); } delay(3000); } } /* * No SC Card found, blink 5x fast */ void noSDCardFound(void) { while(true) { for(int i = 0; i < 5; i++) { LED_ON(); delay(250); LED_OFF(); delay(250); } delay(3000); } } /* * Return from exception and call longjmp */ void __attribute__ ((noinline)) longjmpFromInterrupt(jmp_buf jmpb, int retval) __attribute__ ((noreturn)); void longjmpFromInterrupt(jmp_buf jmpb, int retval) { // Address of longjmp with the thumb bit cleared const uint32_t longjmpaddr = ((uint32_t)longjmp) & 0xfffffffe; const uint32_t zero = 0; // Default PSR value, function calls don't require any particular value const uint32_t PSR = 0x01000000; // For documentation on what this is doing, see: // https://developer.arm.com/documentation/dui0552/a/the-cortex-m3-processor/exception-model/exception-entry-and-return // Stack frame needs to have R0-R3, R12, LR, PC, PSR (from bottom to top) // This is being set up to have R0 and R1 contain the parameters passed to longjmp, and PC is the address of the longjmp function. // This is using existing stack space, rather than allocating more, as longjmp is just going to unroll the stack even further. // 0xfffffff9 is the EXC_RETURN value to return to thread mode. asm ( "str %0, [sp];\ str %1, [sp, #4];\ str %2, [sp, #8];\ str %2, [sp, #12];\ str %2, [sp, #16];\ str %2, [sp, #20];\ str %3, [sp, #24];\ str %4, [sp, #28];\ ldr lr, =0xfffffff9;\ bx lr" :: "r"(jmpb),"r"(retval),"r"(zero), "r"(longjmpaddr), "r"(PSR) ); } /* * Bus reset interrupt. */ void onBusReset(void) { #if SCSI_SELECT == 1 // SASI I / F for X1 turbo has RST pulse write cycle +2 clock == // I can't filter because it only activates about 1.25us {{ #else if(isHigh(gpio_read(RST))) { delayMicroseconds(20); if(isHigh(gpio_read(RST))) { #endif // BUS FREE is done in the main process // gpio_mode(MSG, GPIO_OUTPUT_OD); // gpio_mode(CD, GPIO_OUTPUT_OD); // gpio_mode(REQ, GPIO_OUTPUT_OD); // gpio_mode(IO, GPIO_OUTPUT_OD); // Should I enter DB and DBP once? SCSI_DB_INPUT() LOGN("BusReset!"); if (m_resetJmp) { m_resetJmp = false; // Jumping out of the interrupt handler, so need to clear the interupt source. uint8 exti = PIN_MAP[RST].gpio_bit; EXTI_BASE->PR = (1U << exti); longjmpFromInterrupt(m_resetJmpBuf, 1); } else { m_isBusReset = true; } } } } /* * Enable the reset longjmp, and check if reset fired while it was disabled. */ void enableResetJmp(void) { m_resetJmp = true; if (m_isBusReset) { longjmp(m_resetJmpBuf, 1); } } /* * Read by handshake. */ inline byte readHandshake(void) { SCSI_OUT(vREQ,active) //SCSI_DB_INPUT() while( ! SCSI_IN(vACK)); byte r = readIO(); SCSI_OUT(vREQ,inactive) while( SCSI_IN(vACK)); return r; } /* * Write with a handshake. */ inline void writeHandshake(byte d) { // This has a 400ns bus settle delay built in. Not optimal for multi-byte transfers. GPIOB->regs->BSRR = db_bsrr[d]; // setup DB,DBP (160ns) #ifdef XCVR TRANSCEIVER_IO_SET(vTR_DBP,TR_OUTPUT) #endif SCSI_DB_OUTPUT() // (180ns) // ACK.Fall to DB output delay 100ns(MAX) (DTC-510B) SCSI_OUT(vREQ,inactive) // setup wait (30ns) SCSI_OUT(vREQ,inactive) // setup wait (30ns) SCSI_OUT(vREQ,inactive) // setup wait (30ns) SCSI_OUT(vREQ,active) // (30ns) //while(!SCSI_IN(vACK)) { if(m_isBusReset){ SCSI_DB_INPUT() return; }} while(!SCSI_IN(vACK)); // ACK.Fall to REQ.Raise delay 500ns(typ.) (DTC-510B) GPIOB->regs->BSRR = DBP(0xff); // DB=0xFF , SCSI_OUT(vREQ,inactive) // REQ.Raise to DB hold time 0ns SCSI_DB_INPUT() // (150ns) #ifdef XCVR TRANSCEIVER_IO_SET(vTR_DBP,TR_INPUT) #endif while( SCSI_IN(vACK)); } #if READ_SPEED_OPTIMIZE #pragma GCC push_options #pragma GCC optimize ("-Os") /* * This loop is tuned to repeat the following pattern: * 1) Set REQ * 2) 5 cycles of work/delay * 3) Wait for ACK * Cycle time tunings are for 72MHz STM32F103 * Alignment matters. For the 3 instruction wait loops,it looks like crossing * an 8 byte prefetch buffer can add 2 cycles of wait every branch taken. */ void writeDataLoop(uint32_t blocksize, const byte* srcptr) __attribute__ ((aligned(8))); void writeDataLoop(uint32_t blocksize, const byte* srcptr) { #define REQ_ON() (port_b->BRR = req_bit); #define FETCH_BSRR_DB() (bsrr_val = bsrr_tbl[*srcptr++]) #define REQ_OFF_DB_SET(BSRR_VAL) port_b->BSRR = BSRR_VAL; #define WAIT_ACK_ACTIVE() while((*port_a_idr>>(vACK&15)&1)) #define WAIT_ACK_INACTIVE() while(!(*port_a_idr>>(vACK&15)&1)) register const byte *endptr= srcptr + blocksize; // End pointer register const uint32_t *bsrr_tbl = db_bsrr; // Table to convert to BSRR register uint32_t bsrr_val; // BSRR value to output (DB, DBP, REQ = ACTIVE) register uint32_t req_bit = BITMASK(vREQ); register gpio_reg_map *port_b = PBREG; register volatile uint32_t *port_a_idr = &(GPIOA->regs->IDR); // Start the first bus cycle. FETCH_BSRR_DB(); REQ_OFF_DB_SET(bsrr_val); #ifdef XCVR TRANSCEIVER_IO_SET(vTR_DBP,TR_OUTPUT) #endif REQ_ON(); FETCH_BSRR_DB(); WAIT_ACK_ACTIVE(); REQ_OFF_DB_SET(bsrr_val); // Align the starts of the do/while and WAIT loops to an 8 byte prefetch. asm("nop.w;nop"); do{ WAIT_ACK_INACTIVE(); REQ_ON(); // 4 cycles of work FETCH_BSRR_DB(); // Extra 1 cycle delay while keeping the loop within an 8 byte prefetch. asm("nop"); WAIT_ACK_ACTIVE(); REQ_OFF_DB_SET(bsrr_val); // Extra 1 cycle delay, plus 4 cycles for the branch taken with prefetch. asm("nop"); }while(srcptr < endptr); WAIT_ACK_INACTIVE(); // Finish the last bus cycle, byte is already on DB. REQ_ON(); WAIT_ACK_ACTIVE(); REQ_OFF_DB_SET(bsrr_val); WAIT_ACK_INACTIVE(); } #pragma GCC pop_options #endif /* * Data in phase. * Send len bytes of data array p. */ void writeDataPhase(int len, const byte* p) { LOGN("DATAIN PHASE"); SCSI_PHASE_CHANGE(SCSI_PHASE_DATAIN); #if READ_SPEED_OPTIMIZE // Bus settle delay 400ns. Following code was measured at 800ns before REQ asserted. STM32F103. SCSI_DB_OUTPUT() writeDataLoop(len, p); SCSI_DB_INPUT() #else for (int i = 0; i < len; i++) { writeHandshake(p[i]); } #endif } /* * Data in phase. * Send len block while reading from SD card. */ void writeDataPhaseSD(uint32_t adds, uint32_t len) { LOGN("DATAIN PHASE(SD)"); SCSI_PHASE_CHANGE(SCSI_PHASE_DATAIN); //Bus settle delay 400ns, file.seek() measured at over 1000ns. uint64_t pos = (uint64_t)adds * m_img->m_blocksize; m_img->m_file.seekSet(pos); SCSI_DB_OUTPUT() for(uint32_t i = 0; i < len; i++) { // Asynchronous reads will make it faster ... m_resetJmp = false; m_img->m_file.read(m_buf, m_img->m_blocksize); enableResetJmp(); #if READ_SPEED_OPTIMIZE writeDataLoop(m_img->m_blocksize, m_buf); #else for(int j = 0; j < m_img->m_blocksize; j++) { writeHandshake(m_buf[j]); } #endif } SCSI_DB_INPUT() #ifdef XCVR TRANSCEIVER_IO_SET(vTR_DBP,TR_INPUT) #endif } #if WRITE_SPEED_OPTIMIZE #pragma GCC push_options #pragma GCC optimize ("-Os") /* * See writeDataLoop for optimization info. */ void readDataLoop(uint32_t blockSize, byte* dstptr) __attribute__ ((aligned(16))); void readDataLoop(uint32_t blockSize, byte* dstptr) { register byte *endptr= dstptr + blockSize - 1; #define REQ_ON() (port_b->BRR = req_bit); #define REQ_OFF() (port_b->BSRR = req_bit); #define WAIT_ACK_ACTIVE() while((*port_a_idr>>(vACK&15)&1)) #define WAIT_ACK_INACTIVE() while(!(*port_a_idr>>(vACK&15)&1)) register uint32_t req_bit = BITMASK(vREQ); register gpio_reg_map *port_b = PBREG; register volatile uint32_t *port_a_idr = &(GPIOA->regs->IDR); REQ_ON(); // Fastest alignment obtained by trial and error. // Wait loop is within an 8 byte prefetch buffer. asm("nop"); do { WAIT_ACK_ACTIVE(); uint32_t ret = port_b->IDR; REQ_OFF(); *dstptr++ = ~(ret >> 8); // Move wait loop in to a single 8 byte prefetch buffer asm("nop;nop;nop"); WAIT_ACK_INACTIVE(); REQ_ON(); // Extra 1 cycle delay asm("nop"); } while(dstptr<endptr); WAIT_ACK_ACTIVE(); uint32_t ret = GPIOB->regs->IDR; REQ_OFF(); *dstptr = ~(ret >> 8); WAIT_ACK_INACTIVE(); } #pragma GCC pop_options #endif /* * Data out phase. * len block read */ void readDataPhase(int len, byte* p) { LOGN("DATAOUT PHASE"); SCSI_PHASE_CHANGE(SCSI_PHASE_DATAOUT); // Bus settle delay 400ns. The following code was measured at 450ns before REQ asserted. STM32F103. #if WRITE_SPEED_OPTIMIZE readDataLoop(len, p); #else for(uint32_t i = 0; i < len; i++) p[i] = readHandshake(); #endif } /* * Data out phase. * Write to SD card while reading len block. */ void readDataPhaseSD(uint32_t adds, uint32_t len) { LOGN("DATAOUT PHASE(SD)"); SCSI_PHASE_CHANGE(SCSI_PHASE_DATAOUT); //Bus settle delay 400ns, file.seek() measured at over 1000ns. uint64_t pos = (uint64_t)adds * m_img->m_blocksize; m_img->m_file.seekSet(pos); for(uint32_t i = 0; i < len; i++) { m_resetJmp = true; #if WRITE_SPEED_OPTIMIZE readDataLoop(m_img->m_blocksize, m_buf); #else for(int j = 0; j < m_img->m_blocksize; j++) { m_buf[j] = readHandshake(); } #endif m_resetJmp = false; m_img->m_file.write(m_buf, m_img->m_blocksize); // If a reset happened while writing, break and let the flush happen before it is handled. if (m_isBusReset) { break; } } m_img->m_file.flush(); enableResetJmp(); } /* * Data out phase. * Compare to SD card while reading len block. */ void verifyDataPhaseSD(uint32_t adds, uint32_t len) { LOGN("DATAOUT PHASE(SD)"); SCSI_PHASE_CHANGE(SCSI_PHASE_DATAOUT); //Bus settle delay 400ns, file.seek() measured at over 1000ns. uint64_t pos = (uint64_t)adds * m_img->m_blocksize; m_img->m_file.seekSet(pos); for(uint32_t i = 0; i < len; i++) { #if WRITE_SPEED_OPTIMIZE readDataLoop(m_img->m_blocksize, m_buf); #else for(int j = 0; j < m_img->m_blocksize; j++) { m_buf[j] = readHandshake(); } #endif // This has just gone through the transfer to make things work, a compare would go here. } } /* * INQUIRY command processing. */ #if SCSI_SELECT == 2 byte onInquiryCommand(byte len) { byte buf[36] = { 0x00, //Device type 0x00, //RMB = 0 0x01, //ISO,ECMA,ANSI version 0x01, //Response data format 35 - 4, //Additional data length 0, 0, //Reserve 0x00, //Support function 'N', 'E', 'C', 'I', 'T', 'S', 'U', ' ', 'A', 'r', 'd', 'S', 'C', 'S', 'i', 'n', 'o', ' ', ' ',' ', ' ', ' ', ' ', ' ', '0', '0', '1', '0', }; writeDataPhase(len < 36 ? len : 36, buf); return 0x00; } #else byte onInquiryCommand(byte len) { writeDataPhase(len < 36 ? len : 36, SCSI_INFO_BUF); return 0x00; } #endif /* * REQUEST SENSE command processing. */ void onRequestSenseCommand(byte len) { byte buf[18] = { 0x70, //CheckCondition 0, //Segment number m_senseKey, //Sense key 0, 0, 0, 0, //information 10, //Additional data length 0, 0, 0, 0, // command specific information bytes (byte)(m_addition_sense >> 8), (byte)m_addition_sense, 0, 0, 0, 0, }; m_senseKey = 0; m_addition_sense = 0; writeDataPhase(len < 18 ? len : 18, buf); } /* * READ CAPACITY command processing. */ byte onReadCapacityCommand(byte pmi) { if(!m_img) { m_senseKey = 2; // Not ready m_addition_sense = 0x0403; // Logical Unit Not Ready, Manual Intervention Required return 0x02; // Image file absent } uint32_t bl = m_img->m_blocksize; uint32_t bc = m_img->m_fileSize / bl - 1; // Points to last LBA uint8_t buf[8] = { bc >> 24, bc >> 16, bc >> 8, bc, bl >> 24, bl >> 16, bl >> 8, bl }; writeDataPhase(8, buf); return 0x00; } /* * Check that the image file is present and the block range is valid. */ byte checkBlockCommand(uint32_t adds, uint32_t len) { // Check that image file is present if(!m_img) { m_senseKey = 2; // Not ready m_addition_sense = 0x0403; // Logical Unit Not Ready, Manual Intervention Required return 0x02; } // Check block range is valid uint32_t bc = m_img->m_fileSize / m_img->m_blocksize; if (adds >= bc || (adds + len) > bc) { m_senseKey = 5; // Illegal request m_addition_sense = 0x2100; // Logical block address out of range return 0x02; } return 0x00; } /* * READ6 / 10 Command processing. */ byte onReadCommand(uint32_t adds, uint32_t len) { LOGN("-R"); LOGHEXN(adds); LOGHEXN(len); byte sts = checkBlockCommand(adds, len); if (sts) { return sts; } LED_ON(); writeDataPhaseSD(adds, len); LED_OFF(); return 0x00; //sts } /* * WRITE6 / 10 Command processing. */ byte onWriteCommand(uint32_t adds, uint32_t len) { LOGN("-W"); LOGHEXN(adds); LOGHEXN(len); byte sts = checkBlockCommand(adds, len); if (sts) { return sts; } LED_ON(); readDataPhaseSD(adds, len); LED_OFF(); return 0; //sts } /* * VERIFY10 Command processing. */ byte onVerifyCommand(byte flags, uint32_t adds, uint32_t len) { byte sts = checkBlockCommand(adds, len); if (sts) { return sts; } int bytchk = (flags >> 1) & 0x03; if (bytchk != 0) { if (bytchk == 3) { // Data-Out buffer is single logical block for repeated verification. len = m_img->m_blocksize; } LED_ON(); verifyDataPhaseSD(adds, len); LED_OFF(); } return 0x00; } /* * MODE SENSE command processing. */ #if SCSI_SELECT == 2 byte onModeSenseCommand(byte scsi_cmd, byte dbd, int cmd2, uint32_t len) { if(!m_img) { m_senseKey = 2; // Not ready m_addition_sense = 0x0403; // Logical Unit Not Ready, Manual Intervention Required return 0x02; // Image file absent } int pageCode = cmd2 & 0x3F; // Assuming sector size 512, number of sectors 25, number of heads 8 as default settings int size = m_img->m_fileSize; int cylinders = (int)(size >> 9); cylinders >>= 3; cylinders /= 25; int sectorsize = 512; int sectors = 25; int heads = 8; // Sector size int disksize = 0; for(disksize = 16; disksize > 0; --(disksize)) { if ((1 << disksize) == sectorsize) break; } // Number of blocks uint32_t diskblocks = (uint32_t)(size >> disksize); memset(m_buf, 0, sizeof(m_buf)); int a = 4; if(dbd == 0) { uint32_t bl = m_img->m_blocksize; uint32_t bc = m_img->m_fileSize / bl; byte c[8] = { 0,// Density code bc >> 16, bc >> 8, bc, 0, //Reserve bl >> 16, bl >> 8, bl }; memcpy(&m_buf[4], c, 8); a += 8; m_buf[3] = 0x08; } switch(pageCode) { case 0x3F: { m_buf[a + 0] = 0x01; m_buf[a + 1] = 0x06; a += 8; } case 0x03: // drive parameters { m_buf[a + 0] = 0x80 | 0x03; // Page code m_buf[a + 1] = 0x16; // Page length m_buf[a + 2] = (byte)(heads >> 8);// number of sectors / track m_buf[a + 3] = (byte)(heads);// number of sectors / track m_buf[a + 10] = (byte)(sectors >> 8);// number of sectors / track m_buf[a + 11] = (byte)(sectors);// number of sectors / track int size = 1 << disksize; m_buf[a + 12] = (byte)(size >> 8);// number of sectors / track m_buf[a + 13] = (byte)(size);// number of sectors / track a += 24; if(pageCode != 0x3F) { break; } } case 0x04: // drive parameters { LOGN("AddDrive"); m_buf[a + 0] = 0x04; // Page code m_buf[a + 1] = 0x12; // Page length m_buf[a + 2] = (cylinders >> 16);// Cylinder length m_buf[a + 3] = (cylinders >> 8); m_buf[a + 4] = cylinders; m_buf[a + 5] = heads; // Number of heads a += 20; if(pageCode != 0x3F) { break; } } default: break; } m_buf[0] = a - 1; writeDataPhase(len < a ? len : a, m_buf); return 0x00; } #else byte onModeSenseCommand(byte scsi_cmd, byte dbd, byte cmd2, uint32_t len) { if(!m_img) { m_senseKey = 2; // Not ready m_addition_sense = 0x0403; // Logical Unit Not Ready, Manual Intervention Required return 0x02; // No image file } uint32_t bl = m_img->m_blocksize; uint32_t bc = m_img->m_fileSize / bl; memset(m_buf, 0, sizeof(m_buf)); int pageCode = cmd2 & 0x3F; int pageControl = cmd2 >> 6; int a = 4; if(scsi_cmd == 0x5A) a = 8; if(dbd == 0) { byte c[8] = { 0,//Density code bc >> 16, bc >> 8, bc, 0, //Reserve bl >> 16, bl >> 8, bl }; memcpy(&m_buf[a], c, 8); a += 8; } switch(pageCode) { case 0x3F: case 0x01: // Read/Write Error Recovery m_buf[a + 0] = 0x01; m_buf[a + 1] = 0x0A; a += 0x0C; if(pageCode != 0x3F) break; case 0x02: // Disconnect-Reconnect page m_buf[a + 0] = 0x02; m_buf[a + 1] = 0x0A; a += 0x0C; if(pageCode != 0x3f) break; case 0x03: //Drive parameters m_buf[a + 0] = 0x03; //Page code m_buf[a + 1] = 0x16; // Page length if(pageControl != 1) { m_buf[a + 11] = 0x3F;//Number of sectors / track m_buf[a + 12] = (byte)(m_img->m_blocksize >> 8); m_buf[a + 13] = (byte)m_img->m_blocksize; m_buf[a + 15] = 0x1; // Interleave } a += 0x18; if(pageCode != 0x3F) break; case 0x04: //Drive parameters m_buf[a + 0] = 0x04; //Page code m_buf[a + 1] = 0x16; // Page length if(pageControl != 1) { unsigned cylinders = bc / (16 * 63); m_buf[a + 2] = (byte)(cylinders >> 16); // Cylinders m_buf[a + 3] = (byte)(cylinders >> 8); m_buf[a + 4] = (byte)cylinders; m_buf[a + 5] = 16; //Number of heads } a += 0x18; if(pageCode != 0x3F) break; case 0x30: { const byte page30[0x14] = {0x41, 0x50, 0x50, 0x4C, 0x45, 0x20, 0x43, 0x4F, 0x4D, 0x50, 0x55, 0x54, 0x45, 0x52, 0x2C, 0x20, 0x49, 0x4E, 0x43, 0x20}; m_buf[a + 0] = 0x30; // Page code m_buf[a + 1] = sizeof(page30); // Page length if(pageControl != 1) { memcpy(&m_buf[a + 2], page30, sizeof(page30)); } a += 2 + sizeof(page30); if(pageCode != 0x3F) break; } break; // Don't want 0x3F falling through to error condition default: m_senseKey = 5; // Illegal request m_addition_sense = 0x2400; // Invalid field in CDB return 0x02; break; } if(scsi_cmd == 0x5A) // MODE SENSE 10 { m_buf[1] = a - 2; m_buf[7] = 0x08; } else { m_buf[0] = a - 1; m_buf[3] = 0x08; } writeDataPhase(len < a ? len : a, m_buf); return 0x00; } #endif byte onModeSelectCommand(byte scsi_cmd, byte flags, uint32_t len) { if (len > MAX_BLOCKSIZE) { m_senseKey = 5; // Illegal request m_addition_sense = 0x2400; // Invalid field in CDB return 0x02; } readDataPhase(len, m_buf); //Apple HD SC Setup sends: //0 0 0 8 0 0 0 0 0 0 2 0 0 2 10 0 1 6 24 10 8 0 0 0 //I believe mode page 0 set to 10 00 is Disable Unit Attention //Mode page 1 set to 24 10 08 00 00 00 is TB and PER set, read retry count 16, correction span 8 for (unsigned i = 0; i < len; i++) { LOGHEX(m_buf[i]);LOG(" "); } LOGN(""); return 0x00; } #if SCSI_SELECT == 1 /* * dtc510b_setDriveparameter */ #define PACKED __attribute__((packed)) typedef struct PACKED dtc500_cmd_c2_param_struct { uint8_t StepPlusWidth; // Default is 13.6usec (11) uint8_t StepPeriod; // Default is 3 msec.(60) uint8_t StepMode; // Default is Bufferd (0) uint8_t MaximumHeadAdress; // Default is 4 heads (3) uint8_t HighCylinderAddressByte; // Default set to 0 (0) uint8_t LowCylinderAddressByte; // Default is 153 cylinders (152) uint8_t ReduceWrietCurrent; // Default is above Cylinder 128 (127) uint8_t DriveType_SeekCompleteOption;// (0) uint8_t Reserved8; // (0) uint8_t Reserved9; // (0) } DTC510_CMD_C2_PARAM; static void logStrHex(const char *msg,uint32_t num) { LOG(msg); LOGHEXN(num); } static byte dtc510b_setDriveparameter(void) { DTC510_CMD_C2_PARAM DriveParameter; uint16_t maxCylinder; uint16_t numLAD; //uint32_t stepPulseUsec; int StepPeriodMsec; // receive paramter writeDataPhase(sizeof(DriveParameter),(byte *)(&DriveParameter)); maxCylinder = (((uint16_t)DriveParameter.HighCylinderAddressByte)<<8) | (DriveParameter.LowCylinderAddressByte); numLAD = maxCylinder * (DriveParameter.MaximumHeadAdress+1); //stepPulseUsec = calcStepPulseUsec(DriveParameter.StepPlusWidth); StepPeriodMsec = DriveParameter.StepPeriod*50; logStrHex (" StepPlusWidth : ",DriveParameter.StepPlusWidth); logStrHex (" StepPeriod : ",DriveParameter.StepPeriod ); logStrHex (" StepMode : ",DriveParameter.StepMode ); logStrHex (" MaximumHeadAdress : ",DriveParameter.MaximumHeadAdress); logStrHex (" CylinderAddress : ",maxCylinder); logStrHex (" ReduceWrietCurrent : ",DriveParameter.ReduceWrietCurrent); logStrHex (" DriveType/SeekCompleteOption : ",DriveParameter.DriveType_SeekCompleteOption); logStrHex (" Maximum LAD : ",numLAD-1); return 0; // error result } #endif /* * MsgIn2. */ void MsgIn2(int msg) { LOGN("MsgIn2"); SCSI_PHASE_CHANGE(SCSI_PHASE_MESSAGEIN); // Bus settle delay 400ns built in to writeHandshake writeHandshake(msg); } /* * Main loop. */ void loop() { #ifdef XCVR // Reset all DB and Target pins, switch transceivers to input // Precaution against bugs or jumps which don't clean up properly SCSI_DB_INPUT(); TRANSCEIVER_IO_SET(vTR_DBP,TR_INPUT) SCSI_TARGET_INACTIVE(); TRANSCEIVER_IO_SET(vTR_INITIATOR,TR_INPUT) #endif //int msg = 0; m_msg = 0; // Wait until RST = H, BSY = H, SEL = L do {} while( SCSI_IN(vBSY) || !SCSI_IN(vSEL) || SCSI_IN(vRST)); // BSY+ SEL- // If the ID to respond is not driven, wait for the next //byte db = readIO(); //byte scsiid = db & scsi_id_mask; byte scsiid = readIO() & scsi_id_mask; if((scsiid) == 0) { delayMicroseconds(1); return; } LOGN("Selection"); m_isBusReset = false; if (setjmp(m_resetJmpBuf) == 1) { LOGN("Reset, going to BusFree"); goto BusFree; } enableResetJmp(); // Set BSY to-when selected SCSI_BSY_ACTIVE(); // Turn only BSY output ON, ACTIVE // Ask for a TARGET-ID to respond m_id = 31 - __builtin_clz(scsiid); // Wait until SEL becomes inactive while(isHigh(gpio_read(SEL)) && isLow(gpio_read(BSY))) { } #ifdef XCVR // Reconfigure target pins to output mode, after resetting their values GPIOB->regs->BSRR = 0x000000E8; // MSG, CD, REQ, IO // GPIOA->regs->BSRR = 0x00000200; // BSY #endif SCSI_TARGET_ACTIVE() // (BSY), REQ, MSG, CD, IO output turned on // if(isHigh(gpio_read(ATN))) { SCSI_PHASE_CHANGE(SCSI_PHASE_MESSAGEOUT); // Bus settle delay 400ns. Following code was measured at 350ns before REQ asserted. Added another 50ns. STM32F103. SCSI_PHASE_CHANGE(SCSI_PHASE_MESSAGEOUT);// 28ns delay STM32F103 SCSI_PHASE_CHANGE(SCSI_PHASE_MESSAGEOUT);// 28ns delay STM32F103 bool syncenable = false; int syncperiod = 50; int syncoffset = 0; int msc = 0; while(isHigh(gpio_read(ATN)) && msc < 255) { m_msb[msc++] = readHandshake(); } for(int i = 0; i < msc; i++) { // ABORT if (m_msb[i] == 0x06) { goto BusFree; } // BUS DEVICE RESET if (m_msb[i] == 0x0C) { syncoffset = 0; goto BusFree; } // IDENTIFY if (m_msb[i] >= 0x80) { } // Extended message if (m_msb[i] == 0x01) { // Check only when synchronous transfer is possible if (!syncenable || m_msb[i + 2] != 0x01) { MsgIn2(0x07); break; } // Transfer period factor(50 x 4 = Limited to 200ns) syncperiod = m_msb[i + 3]; if (syncperiod > 50) { syncperiod = 50; } // REQ/ACK offset(Limited to 16) syncoffset = m_msb[i + 4]; if (syncoffset > 16) { syncoffset = 16; } // STDR response message generation MsgIn2(0x01); MsgIn2(0x03); MsgIn2(0x01); MsgIn2(syncperiod); MsgIn2(syncoffset); break; } } } LOG("Command:"); SCSI_PHASE_CHANGE(SCSI_PHASE_COMMAND); // Bus settle delay 400ns. The following code was measured at 20ns before REQ asserted. Added another 380ns. STM32F103. asm("nop;nop;nop;nop;nop;nop;nop;nop");// This asm causes some code reodering, which adds 270ns, plus 8 nop cycles for an additional 110ns. STM32F103 int len; byte cmd[12]; cmd[0] = readHandshake(); LOGHEX(cmd[0]); // Command length selection, reception static const int cmd_class_len[8]={6,10,10,6,6,12,6,6}; len = cmd_class_len[cmd[0] >> 5]; cmd[1] = readHandshake(); LOG(":");LOGHEX(cmd[1]); cmd[2] = readHandshake(); LOG(":");LOGHEX(cmd[2]); cmd[3] = readHandshake(); LOG(":");LOGHEX(cmd[3]); cmd[4] = readHandshake(); LOG(":");LOGHEX(cmd[4]); cmd[5] = readHandshake(); LOG(":");LOGHEX(cmd[5]); // Receive the remaining commands for(int i = 6; i < len; i++ ) { cmd[i] = readHandshake(); LOG(":"); LOGHEX(cmd[i]); } // LUN confirmation m_sts = cmd[1]&0xe0; // Preset LUN in status byte m_lun = m_sts>>5; // HDD Image selection m_img = (HDDIMG *)0; // None if( (m_lun <= NUM_SCSILUN) ) { m_img = &(img[m_id][m_lun]); // There is an image if(!(m_img->m_file.isOpen())) m_img = (HDDIMG *)0; // Image absent } // if(!m_img) m_sts |= 0x02; // Missing image file for LUN //LOGHEX(((uint32_t)m_img)); LOG(":ID "); LOG(m_id); LOG(":LUN "); LOG(m_lun); LOGN(""); switch(cmd[0]) { case 0x00: LOGN("[Test Unit]"); break; case 0x01: LOGN("[Rezero Unit]"); break; case 0x03: LOGN("[RequestSense]"); onRequestSenseCommand(cmd[4]); break; case 0x04: LOGN("[FormatUnit]"); break; case 0x06: LOGN("[FormatUnit]"); break; case 0x07: LOGN("[ReassignBlocks]"); break; case 0x08: LOGN("[Read6]"); m_sts |= onReadCommand((((uint32_t)cmd[1] & 0x1F) << 16) | ((uint32_t)cmd[2] << 8) | cmd[3], (cmd[4] == 0) ? 0x100 : cmd[4]); break; case 0x0A: LOGN("[Write6]"); m_sts |= onWriteCommand((((uint32_t)cmd[1] & 0x1F) << 16) | ((uint32_t)cmd[2] << 8) | cmd[3], (cmd[4] == 0) ? 0x100 : cmd[4]); break; case 0x0B: LOGN("[Seek6]"); break; case 0x12: LOGN("[Inquiry]"); m_sts |= onInquiryCommand(cmd[4]); break; case 0x15: LOGN("[ModeSelect6]"); m_sts |= onModeSelectCommand(cmd[0], cmd[1], cmd[4]); break; case 0x1A: LOGN("[ModeSense6]"); m_sts |= onModeSenseCommand(cmd[0], cmd[1]&0x80, cmd[2], cmd[4]); break; case 0x1B: LOGN("[StartStopUnit]"); break; case 0x1E: LOGN("[PreAllowMed.Removal]"); break; case 0x25: LOGN("[ReadCapacity]"); m_sts |= onReadCapacityCommand(cmd[8]); break; case 0x28: LOGN("[Read10]"); m_sts |= onReadCommand(((uint32_t)cmd[2] << 24) | ((uint32_t)cmd[3] << 16) | ((uint32_t)cmd[4] << 8) | cmd[5], ((uint32_t)cmd[7] << 8) | cmd[8]); break; case 0x2A: LOGN("[Write10]"); m_sts |= onWriteCommand(((uint32_t)cmd[2] << 24) | ((uint32_t)cmd[3] << 16) | ((uint32_t)cmd[4] << 8) | cmd[5], ((uint32_t)cmd[7] << 8) | cmd[8]); break; case 0x2B: LOGN("[Seek10]"); break; case 0x2F: LOGN("[Verify10]"); m_sts |= onVerifyCommand(cmd[1], ((uint32_t)cmd[2] << 24) | ((uint32_t)cmd[3] << 16) | ((uint32_t)cmd[4] << 8) | cmd[5], ((uint32_t)cmd[7] << 8) | cmd[8]); break; case 0x35: LOGN("[SynchronizeCache10]"); break; case 0x55: LOGN("[ModeSelect10"); m_sts |= onModeSelectCommand(cmd[0], cmd[1], ((uint32_t)cmd[7] << 8) | cmd[8]); break; case 0x5A: LOGN("[ModeSense10]"); m_sts |= onModeSenseCommand(cmd[0], cmd[1] & 0x80, cmd[2], ((uint32_t)cmd[7] << 8) | cmd[8]); break; #if SCSI_SELECT == 1 case 0xc2: LOGN("[DTC510B setDriveParameter]"); m_sts |= dtc510b_setDriveparameter(); break; #endif default: LOGN("[*Unknown]"); m_sts |= 0x02; m_senseKey = 5; // Illegal request m_addition_sense = 0x2000; // Invalid Command Operation Code break; } LOGN("Sts"); SCSI_PHASE_CHANGE(SCSI_PHASE_STATUS); // Bus settle delay 400ns built in to writeHandshake writeHandshake(m_sts); LOGN("MsgIn"); SCSI_PHASE_CHANGE(SCSI_PHASE_MESSAGEIN); // Bus settle delay 400ns built in to writeHandshake writeHandshake(m_msg); BusFree: LOGN("BusFree"); m_isBusReset = false; //SCSI_OUT(vREQ,inactive) // gpio_write(REQ, low); //SCSI_OUT(vMSG,inactive) // gpio_write(MSG, low); //SCSI_OUT(vCD ,inactive) // gpio_write(CD, low); //SCSI_OUT(vIO ,inactive) // gpio_write(IO, low); //SCSI_OUT(vBSY,inactive) SCSI_TARGET_INACTIVE() // Turn off BSY, REQ, MSG, CD, IO output #ifdef XCVR TRANSCEIVER_IO_SET(vTR_TARGET,TR_INPUT); #endif }
28.99778
250
0.63176
[ "object", "model" ]
32c975733464f8b24521f3be98b8730d34919615
3,012
cpp
C++
lib/src/activepp.cpp
willhoyle/activepp
1edca9ecaa53fe45d540c8583d53a6b8a5c11cfd
[ "MIT" ]
2
2020-04-14T09:49:27.000Z
2021-05-08T18:47:17.000Z
lib/src/activepp.cpp
willhoyle/activepp
1edca9ecaa53fe45d540c8583d53a6b8a5c11cfd
[ "MIT" ]
null
null
null
lib/src/activepp.cpp
willhoyle/activepp
1edca9ecaa53fe45d540c8583d53a6b8a5c11cfd
[ "MIT" ]
1
2020-04-14T09:49:31.000Z
2020-04-14T09:49:31.000Z
#include "activepp.h" #include "calendar.h" #include "Helper.h" #include "Requestor.h" #include "Session.h" #include "Streamer.h" #include <iostream> #include <string> #include <fstream> #include <future> #include <tuple> #include <unistd.h> // usleep #include <vector> #include "ActiveTickServerAPI/ActiveTickServerAPI.h" activepp::activepp(const std::string& _dataFolder) { dataFolder = _dataFolder; } activepp::~activepp() { bool shut = ATShutdownAPI(); } bool activepp::login( const std::string& username, const std::string& password, const std::string& apiUserId ) { std::string serverIpAddress = "activetick1.activetick.com"; uint32_t serverPort = 443; ATGUID guidApiUserid = Helper::StringToATGuid(apiUserId); bool rc = m_session.Init(guidApiUserid, serverIpAddress, serverPort, &Helper::ConvertString(username).front(), &Helper::ConvertString(password).front()); return true; } bool activepp::download( std::string& symbol, std::string& dateRange, std::string& type, std::string& time ) { std::cout << dateRange << std::endl; auto dates = calendar::parseDateRange(dateRange); ATTIME atBeginTime = Helper::StringToATTime("20170922000000"); ATTIME atEndTime = Helper::StringToATTime("20170922235959"); ATSYMBOL atSymbol = Helper::StringToSymbol(symbol); { Requestor requestor(m_session, dataFolder); Streamer streamer(m_session); std::future<bool> future; bool success; requestor.setDate("20170922"); future = requestor._promise.get_future(); uint64_t request = requestor.SendATTickHistoryDbRequest(atSymbol, true, false, atBeginTime, atEndTime, 3000000); future.wait(); } // { // // Requestor requestor(m_session, dataFolder); // Streamer streamer(m_session); // // std::future<bool> future; // bool success; // requestor.setDate("20170921"); // future = requestor._promise.get_future(); // uint64_t request = requestor.SendATTickHistoryDbRequest(atSymbol, true, false, atBeginTime, atEndTime, 3000000); // future.wait(); // } return true; } void call(uint64_t origRequest, LPATSYMBOL pSymbols, uint32_t symbolsCount) { std::cout << symbolsCount << std::endl; } void callback(uint64_t origRequest, LPATSECTORLIST_RECORD pRecords, uint32_t recordsCount) { std::cout << sizeof(pRecords->sector) << " " << sizeof(pRecords->industry) << std::endl; } void timeout(uint64_t origRequest) { } bool activepp::constituent( ) { wchar16_t ye = 67; uint64_t request = ATCreateConstituentListRequest(m_session.GetSessionHandle(), ATConstituentListSector , &ye, call); ATSendRequest(m_session.GetSessionHandle(), request, DEFAULT_REQUEST_TIMEOUT, timeout); // uint64_t request = ATCreateSectorListRequest(m_session.GetSessionHandle(), callback); // ATSendRequest(m_session.GetSessionHandle(), request, DEFAULT_REQUEST_TIMEOUT, timeout); int seconds = 10; int microseconds = seconds * 1000000; usleep(microseconds); } bool activepp::download( std::string& symbol, std::string& date, std::string& type ) { }
29.242718
155
0.732404
[ "vector" ]
32cca6a405787160259d5da348fd47747e8e1792
3,185
hh
C++
ncrystal_core/include/NCrystal/internal/NCFileUtils.hh
mctools/ncrystal
33ec51187a3bef418046c30e591ff7d8f239d54f
[ "Apache-2.0" ]
22
2017-08-31T08:44:10.000Z
2022-03-21T08:18:26.000Z
ncrystal_core/include/NCrystal/internal/NCFileUtils.hh
XuShuqi7/ncrystal
acf26db3dfd5f0a95355c7c3bbfcbfee55040175
[ "Apache-2.0" ]
77
2018-01-23T10:19:45.000Z
2022-03-21T07:57:32.000Z
ncrystal_core/include/NCrystal/internal/NCFileUtils.hh
XuShuqi7/ncrystal
acf26db3dfd5f0a95355c7c3bbfcbfee55040175
[ "Apache-2.0" ]
11
2017-09-14T19:49:50.000Z
2022-02-28T11:07:00.000Z
#ifndef NCrystal_FileUtils_hh #define NCrystal_FileUtils_hh //////////////////////////////////////////////////////////////////////////////// // // // This file is part of NCrystal (see https://mctools.github.io/ncrystal/) // // // // Copyright 2015-2021 NCrystal developers // // // // Licensed under the Apache License, Version 2.0 (the "License"); // // you may not use this file except in compliance with the License. // // You may obtain a copy of the License at // // // // http://www.apache.org/licenses/LICENSE-2.0 // // // // Unless required by applicable law or agreed to in writing, software // // distributed under the License is distributed on an "AS IS" BASIS, // // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // // limitations under the License. // // // //////////////////////////////////////////////////////////////////////////////// // File system and path related utilities. We might one day make a path object, // or simple wait for the glorious future when std::filesystem support is // ubiquitous, but until then... #include "NCrystal/NCDefs.hh" namespace NCrystal { //Check if file exists and is readable: bool file_exists( const std::string& filename ); //Simple file globbing (sorts results before returning!): VectS ncglob( const std::string&); //Current working directory: std::string ncgetcwd(); //Get basename and extension from filename: std::string basename(const std::string& filename); std::string getfileext(const std::string& filename); //Determine if path is absolute: bool path_is_absolute( const std::string& ); //Join paths, trying to pick correct path separator: std::string path_join(const std::string&, const std::string&); // tryRealPath: Wrap posix "realpath" function in tryRealPath(..). On any // sort of error (including the error of not being unix), returns an empty // string. Hopefully this function should work for 99.9% of usecases on // linux/osx/bsd, and fail gracefully in the rest. std::string tryRealPath( const std::string& path ); //Read entire file into a string while protecting against someone mistakenly //trying to open a multi-gigabyte file and bringing their machine to a slow //halt. Will return NullOpt in case the file does not exists or is //unreadable. Calling on too large files will instead result in a //DataLoadError. Optional<std::string> readEntireFileToString( const std::string& path ); } #endif
47.537313
80
0.540345
[ "object" ]
32d31abd54d8995b6408bb742942f3a41143ea8b
7,074
cpp
C++
DeveloperExcusesScreensaver/DeveloperExcusesScreensaver.cpp
AntonShalgachev/developer-excuses-screensaver
7b872c17fdd7d752798c6fe9c8e407f18ce10bf5
[ "MIT" ]
null
null
null
DeveloperExcusesScreensaver/DeveloperExcusesScreensaver.cpp
AntonShalgachev/developer-excuses-screensaver
7b872c17fdd7d752798c6fe9c8e407f18ce10bf5
[ "MIT" ]
null
null
null
DeveloperExcusesScreensaver/DeveloperExcusesScreensaver.cpp
AntonShalgachev/developer-excuses-screensaver
7b872c17fdd7d752798c6fe9c8e407f18ce10bf5
[ "MIT" ]
null
null
null
// DeveloperExcusesScreensaver.cpp : Defines the entry point for the application. // #include "DeveloperExcusesScreensaver.h" #include "framework.h" #include "Drawer.h" #include "QuoteSource.h" #include "ConfigurationManager.h" #include "resource.h" #include "tstring.h" namespace { struct MonitorRects { std::vector<RECT> rects; static BOOL CALLBACK MonitorEnum(HMONITOR hMon, HDC hdc, LPRECT lprcMonitor, LPARAM pData) { auto pThis = reinterpret_cast<MonitorRects*>(pData); pThis->rects.push_back(*lprcMonitor); return TRUE; } MonitorRects() { EnumDisplayMonitors(0, 0, MonitorEnum, reinterpret_cast<LPARAM>(this)); } }; std::unique_ptr<QuoteSource> quoteSource = nullptr; std::vector<std::shared_ptr<Drawer>> drawers; constexpr auto defaultUpdatePeriod = 7000; constexpr auto defaultFontSize = 43; constexpr auto defaultFontName = TEXT("Courier New"); constexpr auto defaultSeparateQuote = true; constexpr int updateTimerId = 1; constexpr bool debugTextDraw = false; constexpr bool debugBehaveLikeWindow = false; std::vector<unsigned char> serializeFontDescription(const LOGFONT& logFont) { auto dataSize = sizeof(logFont); std::vector<unsigned char> fontData; fontData.resize(dataSize); CopyMemory(fontData.data(), &logFont, dataSize); return fontData; } LOGFONT deserializeFontDescription(const std::vector<unsigned char>& serializedFontDescription) { LOGFONT logFont; CopyMemory(&logFont, serializedFontDescription.data(), sizeof(logFont)); return logFont; } std::vector<unsigned char> getDefaultFontData() { LOGFONT logFont; ZeroMemory(&logFont, sizeof(logFont)); wcscpy_s(logFont.lfFaceName, defaultFontName); logFont.lfQuality = ANTIALIASED_QUALITY; logFont.lfHeight = defaultFontSize; return serializeFontDescription(logFont); } ConfigurationManager::Configuration getDefaultConfiguration() { return ConfigurationManager::Configuration{ defaultUpdatePeriod, getDefaultFontData(), defaultSeparateQuote }; } ConfigurationManager configManager{ getDefaultConfiguration() }; void fetchNewQuoteForAllDrawers() { quoteSource->fetchQuote([](const tstring& text) { for (const auto& drawer : drawers) drawer->setText(text); }); } void fetchNewQuoteForEachDrawer() { for (const auto& drawer : drawers) { quoteSource->fetchQuote([drawer](const tstring& text) { drawer->setText(text); }); } } void fetchNewQuote() { if (configManager.getConfiguration().separateQuote) fetchNewQuoteForEachDrawer(); else fetchNewQuoteForAllDrawers(); } const std::vector<RECT>& getMonitorRects() { static const MonitorRects monitorRects; return monitorRects.rects; } } LRESULT WINAPI ScreenSaverProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_CREATE: if constexpr (debugBehaveLikeWindow) { RECT r; GetWindowRect(hWnd, &r); auto width = r.right - r.left; auto height = r.bottom - r.top; // to make it non-topmost SetWindowPos(hWnd, HWND_NOTOPMOST, r.left, r.top, width, height, 0); // to make it visible in the taskbar auto exStyle = GetWindowLong(hWnd, GWL_EXSTYLE); SetWindowLong(hWnd, GWL_EXSTYLE, exStyle & ~WS_EX_TOOLWINDOW); } for (const auto& monitorRect : getMonitorRects()) { auto drawer = std::make_shared<Drawer>(hWnd, deserializeFontDescription(configManager.getConfiguration().fontData), monitorRect); drawer->setDebugDraw(debugTextDraw); drawers.push_back(std::move(drawer)); } quoteSource = std::make_unique<QuoteSource>(); SetTimer(hWnd, updateTimerId, configManager.getConfiguration().timerPeriod, nullptr); fetchNewQuote(); break; case WM_DESTROY: drawers.clear(); quoteSource = nullptr; KillTimer(hWnd, updateTimerId); break; case WM_PAINT: { PAINTSTRUCT ps; HDC hdc = BeginPaint(hWnd, &ps); for (const auto& drawer : drawers) drawer->paint(hdc); EndPaint(hWnd, &ps); break; } case WM_TIMER: if (wParam == updateTimerId) fetchNewQuote(); break; case WM_ACTIVATEAPP: case WM_MOUSEMOVE: case WM_LBUTTONDOWN: case WM_MBUTTONDOWN: case WM_RBUTTONDOWN: case WM_KEYDOWN: case WM_SYSKEYDOWN: if constexpr (debugBehaveLikeWindow) return DefWindowProc(hWnd, message, wParam, lParam); break; } return DefScreenSaverProc(hWnd, message, wParam, lParam); } BOOL WINAPI ScreenSaverConfigureDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_INITDIALOG: { auto timerPeriod = configManager.getConfiguration().timerPeriod; auto timerPeriodText = to_tstring(timerPeriod); // string is null-terminated in C++11 SetDlgItemText(hDlg, IDC_TIMER_PERIOD_EDIT, timerPeriodText.c_str()); auto separateQuote = configManager.getConfiguration().separateQuote; SendMessage(GetDlgItem(hDlg, IDC_CHECK_SEPARATE_QUOTE), BM_SETCHECK, separateQuote ? BST_CHECKED : BST_UNCHECKED, 0); return TRUE; } case WM_COMMAND: { switch (LOWORD(wParam)) { case IDOK: { auto timerPeriodEdit = GetDlgItem(hDlg, IDC_TIMER_PERIOD_EDIT); auto timerPeriodStringLength = GetWindowTextLength(timerPeriodEdit); auto timerPeriodString = std::vector<TCHAR>(timerPeriodStringLength + 1); GetWindowText(timerPeriodEdit, timerPeriodString.data(), static_cast<DWORD>(timerPeriodString.size())); auto timerPeriod = StrToInt(timerPeriodString.data()); auto separateQuote = SendMessage(GetDlgItem(hDlg, IDC_CHECK_SEPARATE_QUOTE), BM_GETCHECK, NULL, NULL) == BST_CHECKED; configManager.getConfiguration().timerPeriod = timerPeriod; configManager.getConfiguration().separateQuote = separateQuote; configManager.save(); EndDialog(hDlg, LOWORD(wParam)); return TRUE; } case IDCANCEL: { EndDialog(hDlg, LOWORD(wParam)); return TRUE; } case IDC_CHOOSE_FONT: { auto logFont = deserializeFontDescription(configManager.getConfiguration().fontData); CHOOSEFONT chooseFont; ZeroMemory(&chooseFont, sizeof(chooseFont)); chooseFont.lStructSize = sizeof(chooseFont); chooseFont.hwndOwner = hDlg; chooseFont.lpLogFont = &logFont; chooseFont.iPointSize = 120; chooseFont.Flags = CF_BOTH | CF_EFFECTS | CF_FORCEFONTEXIST | CF_INITTOLOGFONTSTRUCT; ChooseFont(&chooseFont); configManager.getConfiguration().fontData = serializeFontDescription(logFont); return TRUE; } } break; } case WM_CLOSE: { EndDialog(hDlg, FALSE); return TRUE; } } return FALSE; } BOOL WINAPI RegisterDialogClasses(HANDLE) { return TRUE; }
27
145
0.685044
[ "vector" ]
ae0bde6ffa57b45dd9ff01fae887757aa338d10d
24,333
cpp
C++
Apps/Samples/Asteroids/AsteroidsApp.cpp
navono/MethaneKit
5cf55dcbbc23392f5c06b178570c7c32b6368ca7
[ "Apache-2.0" ]
null
null
null
Apps/Samples/Asteroids/AsteroidsApp.cpp
navono/MethaneKit
5cf55dcbbc23392f5c06b178570c7c32b6368ca7
[ "Apache-2.0" ]
null
null
null
Apps/Samples/Asteroids/AsteroidsApp.cpp
navono/MethaneKit
5cf55dcbbc23392f5c06b178570c7c32b6368ca7
[ "Apache-2.0" ]
null
null
null
/****************************************************************************** Copyright 2019-2020 Evgeny Gorodetskiy Licensed under the Apache License, Version 2.0 (the "License"), you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ******************************************************************************* FILE: AsteroidsApp.cpp Sample demonstrating parallel rendering of the distinct asteroids massive ******************************************************************************/ #include "AsteroidsApp.h" #include "AsteroidsAppController.h" #include <Methane/Samples/AppSettings.hpp> #include <Methane/Graphics/AppCameraController.h> #include <Methane/Data/TimeAnimation.h> #include <Methane/Instrumentation.h> #include <memory> #include <thread> #include <array> #include <map> #include <magic_enum.hpp> namespace Methane::Samples { struct MutableParameters { uint32_t instances_count; uint32_t unique_mesh_count; uint32_t textures_count; float scale_ratio; }; constexpr uint32_t g_max_complexity = 9; static const std::array<MutableParameters, g_max_complexity+1> g_mutable_parameters{ { { 1000U, 35U, 10U, 0.6F }, // 0 { 2000U, 50U, 10U, 0.5F }, // 1 { 3000U, 75U, 20U, 0.45F }, // 2 { 4000U, 100U, 20U, 0.4F }, // 3 { 5000U, 200U, 30U, 0.33F }, // 4 { 10000U, 300U, 30U, 0.3F }, // 5 { 15000U, 400U, 40U, 0.27F }, // 6 { 20000U, 500U, 40U, 0.23F }, // 7 { 35000U, 750U, 50U, 0.2F }, // 8 { 50000U, 1000U, 50U, 0.17F }, // 9 } }; [[nodiscard]] inline uint32_t GetDefaultComplexity() { #ifdef _DEBUG return 1U; #else return std::thread::hardware_concurrency() / 2; #endif } [[nodiscard]] inline const MutableParameters& GetMutableParameters(uint32_t complexity) { return g_mutable_parameters[std::min(complexity, g_max_complexity)]; } [[nodiscard]] inline const MutableParameters& GetMutableParameters() { return GetMutableParameters(GetDefaultComplexity()); } static const std::map<pal::Keyboard::State, AsteroidsAppAction> g_asteroids_action_by_keyboard_state{ { { pal::Keyboard::Key::RightBracket }, AsteroidsAppAction::IncreaseComplexity }, { { pal::Keyboard::Key::LeftBracket }, AsteroidsAppAction::DecreaseComplexity }, { { pal::Keyboard::Key::P }, AsteroidsAppAction::SwitchParallelRendering }, { { pal::Keyboard::Key::L }, AsteroidsAppAction::SwitchMeshLodsColoring }, { { pal::Keyboard::Key::Apostrophe }, AsteroidsAppAction::IncreaseMeshLodComplexity }, { { pal::Keyboard::Key::Semicolon }, AsteroidsAppAction::DecreaseMeshLodComplexity }, }; void AsteroidsFrame::ReleaseScreenPassAttachmentTextures() { META_FUNCTION_TASK(); initial_screen_pass_ptr->ReleaseAttachmentTextures(); final_screen_pass_ptr->ReleaseAttachmentTextures(); AppFrame::ReleaseScreenPassAttachmentTextures(); } AsteroidsApp::AsteroidsApp() : UserInterfaceApp( Samples::GetGraphicsAppSettings("Methane Asteroids", Samples::AppOptions::Default, gfx::Context::Options::None, 0.F /* depth clear */, { /* color clearing disabled */ }), { HeadsUpDisplayMode::UserInterface, true }, "Methane Asteroids sample is demonstrating parallel rendering\nof massive asteroids field dynamic simulation.") , m_view_camera(GetAnimations(), gfx::ActionCamera::Pivot::Aim) , m_light_camera(m_view_camera, GetAnimations(), gfx::ActionCamera::Pivot::Aim) , m_asteroids_array_settings( // Asteroids array settings: { // ================ m_view_camera, // - view_camera m_scene_scale, // - scale GetMutableParameters().instances_count, // - instance_count GetMutableParameters().unique_mesh_count, // - unique_mesh_count 4U, // - subdivisions_count GetMutableParameters().textures_count, // - textures_count { 256U, 256U }, // - texture_dimensions 1123U, // - random_seed 13.F, // - orbit_radius_ratio 4.F, // - disc_radius_ratio 0.06F, // - mesh_lod_min_screen_size GetMutableParameters().scale_ratio / 10.F, // - min_asteroid_scale_ratio GetMutableParameters().scale_ratio, // - max_asteroid_scale_ratio true, // - textures_array_enabled true // - depth_reversed }) , m_asteroids_complexity(GetDefaultComplexity()) { META_FUNCTION_TASK(); // NOTE: Near and Far values are swapped in camera parameters (1st value is near = max depth, 2nd value is far = min depth) // for Reversed-Z buffer values range [ near: 1, far 0], instead of [ near 0, far 1] // which is used for "from near to far" drawing order for reducing pixels overdraw m_view_camera.ResetOrientation({ { -110.F, 75.F, 210.F }, { 0.F, -60.F, 25.F }, { 0.F, 1.F, 0.F } }); m_view_camera.SetParameters({ 600.F /* near = max depth */, 0.01F /*far = min depth*/, 90.F /* FOV */ }); m_view_camera.SetZoomDistanceRange({ 60.F , 400.F }); m_light_camera.ResetOrientation({ { -100.F, 120.F, 0.F }, { 0.F, 0.F, 0.F }, { 0.F, 1.F, 0.F } }); m_light_camera.SetProjection(gfx::Camera::Projection::Orthogonal); m_light_camera.SetParameters({ -300.F, 300.F, 90.F }); m_light_camera.Resize({ 120.F, 120.F }); AddInputControllers({ std::make_shared<AsteroidsAppController>(*this, g_asteroids_action_by_keyboard_state), std::make_shared<gfx::AppCameraController>(m_view_camera, "VIEW CAMERA"), std::make_shared<gfx::AppCameraController>(m_light_camera, "LIGHT SOURCE", gfx::AppCameraController::ActionByMouseButton { { pal::Mouse::Button::Right, gfx::ActionCamera::MouseAction::Rotate } }, gfx::AppCameraController::ActionByKeyboardState { { { pal::Keyboard::Key::LeftControl, pal::Keyboard::Key::L }, gfx::ActionCamera::KeyboardAction::Reset } }, gfx::AppCameraController::ActionByKeyboardKey { }), }); const std::string options_group = "Asteroids Options"; add_option_group(options_group); add_option("-c,--complexity", [this](const CLI::results_t& res) { if (uint32_t complexity = 0; CLI::detail::lexical_cast(res[0], complexity)) { SetAsteroidsComplexity(complexity); return true; } return false; }, "simulation complexity", true) ->default_val(m_asteroids_complexity) ->expected(0, static_cast<int>(g_max_complexity)) ->group(options_group); add_option("-s,--subdiv-count", m_asteroids_array_settings.subdivisions_count, "mesh subdivisions count", true)->group(options_group); add_option("-t,--texture-array", m_asteroids_array_settings.textures_array_enabled, "texture array enabled", true)->group(options_group); add_option("-r,--parallel-render", m_is_parallel_rendering_enabled, "parallel rendering enabled", true)->group(options_group); // Setup animations GetAnimations().push_back(std::make_shared<Data::TimeAnimation>(std::bind(&AsteroidsApp::Animate, this, std::placeholders::_1, std::placeholders::_2))); // Enable dry updates on pause to keep asteroids in sync with projection matrix dependent on window size which may change GetAnimations().SetDryUpdateOnPauseEnabled(true); ShowParameters(); } AsteroidsApp::~AsteroidsApp() { META_FUNCTION_TASK(); // Wait for GPU rendering is completed to release resources GetRenderContext().WaitForGpu(gfx::RenderContext::WaitFor::RenderComplete); } void AsteroidsApp::Init() { META_FUNCTION_TASK(); META_SCOPE_TIMER("AsteroidsApp::Init"); UserInterfaceApp::Init(); gfx::RenderContext& context = GetRenderContext(); const gfx::RenderContext::Settings& context_settings = context.GetSettings(); const Data::FloatSize float_rect_size(static_cast<float>(context_settings.frame_size.GetWidth()), static_cast<float>(context_settings.frame_size.GetHeight())); m_view_camera.Resize(float_rect_size); // Create sky-box using namespace magic_enum::bitwise_operators; m_sky_box_ptr = std::make_shared<gfx::SkyBox>(context, GetImageLoader(), gfx::SkyBox::Settings{ m_view_camera, { "Textures/SkyBox/Galaxy/PositiveX.jpg", "Textures/SkyBox/Galaxy/NegativeX.jpg", "Textures/SkyBox/Galaxy/PositiveY.jpg", "Textures/SkyBox/Galaxy/NegativeY.jpg", "Textures/SkyBox/Galaxy/PositiveZ.jpg", "Textures/SkyBox/Galaxy/NegativeZ.jpg" }, m_scene_scale * 100.F, gfx::ImageLoader::Options::Mipmapped, gfx::SkyBox::Options::DepthEnabled | gfx::SkyBox::Options::DepthReversed }); // Create planet m_planet_ptr = std::make_shared<Planet>(context, GetImageLoader(), Planet::Settings{ m_view_camera, m_light_camera, "Textures/Planet/Mars.jpg", // texture_path hlslpp::float3(0.F, 0.F, 0.F), // position m_scene_scale * 3.F, // scale 0.1F, // spin_velocity_rps true, // depth_reversed gfx::ImageLoader::Options::Mipmapped | // image_options gfx::ImageLoader::Options::SrgbColorSpace, -1.F, // lod_bias }); // Create asteroids array m_asteroids_array_ptr = m_asteroids_array_state_ptr ? std::make_unique<AsteroidsArray>(context, m_asteroids_array_settings, *m_asteroids_array_state_ptr) : std::make_unique<AsteroidsArray>(context, m_asteroids_array_settings); const Data::Size constants_data_size = gfx::Buffer::GetAlignedBufferSize(static_cast<Data::Size>(sizeof(Constants))); const Data::Size scene_uniforms_data_size = gfx::Buffer::GetAlignedBufferSize(static_cast<Data::Size>(sizeof(SceneUniforms))); const Data::Size asteroid_uniforms_data_size = m_asteroids_array_ptr->GetUniformsBufferSize(); // Create constants buffer for frame rendering m_const_buffer_ptr = gfx::Buffer::CreateConstantBuffer(context, constants_data_size); m_const_buffer_ptr->SetName("Constants Buffer"); m_const_buffer_ptr->SetData({ { reinterpret_cast<Data::ConstRawPtr>(&m_scene_constants), sizeof(m_scene_constants) } }); // ========= Per-Frame Data ========= for(AsteroidsFrame& frame : GetFrames()) { // Create initial screen pass for asteroids rendering gfx::RenderPass::Settings initial_screen_pass_settings = frame.screen_pass_ptr->GetSettings(); initial_screen_pass_settings.depth_attachment.store_action = gfx::RenderPass::Attachment::StoreAction::Store; frame.initial_screen_pass_ptr = gfx::RenderPass::Create(context, initial_screen_pass_settings); // Create final screen pass for sky-box and planet rendering gfx::RenderPass::Settings final_screen_pass_settings = frame.screen_pass_ptr->GetSettings(); final_screen_pass_settings.color_attachments[0].load_action = gfx::RenderPass::Attachment::LoadAction::Load; final_screen_pass_settings.depth_attachment.load_action = gfx::RenderPass::Attachment::LoadAction::Load; frame.final_screen_pass_ptr = gfx::RenderPass::Create(context, final_screen_pass_settings); // Create parallel command list for asteroids rendering frame.parallel_cmd_list_ptr = gfx::ParallelRenderCommandList::Create(context.GetRenderCommandKit().GetQueue(), *frame.initial_screen_pass_ptr); frame.parallel_cmd_list_ptr->SetParallelCommandListsCount(std::thread::hardware_concurrency()); frame.parallel_cmd_list_ptr->SetName(IndexedName("Parallel Rendering", frame.index)); frame.parallel_cmd_list_ptr->SetValidationEnabled(false); // Create serial command list for asteroids rendering frame.serial_cmd_list_ptr = gfx::RenderCommandList::Create(context.GetRenderCommandKit().GetQueue(), *frame.initial_screen_pass_ptr); frame.serial_cmd_list_ptr->SetName(IndexedName("Serial Rendering", frame.index)); frame.serial_cmd_list_ptr->SetValidationEnabled(false); // Create final command list for sky-box and planet rendering frame.final_cmd_list_ptr = gfx::RenderCommandList::Create(context.GetRenderCommandKit().GetQueue(), *frame.final_screen_pass_ptr); frame.final_cmd_list_ptr->SetName(IndexedName("Final Rendering", frame.index)); frame.final_cmd_list_ptr->SetValidationEnabled(false); // Rendering command lists sequence frame.execute_cmd_list_set_ptr = CreateExecuteCommandListSet(frame); // Create uniforms buffer with volatile parameters for the whole scene rendering frame.scene_uniforms_buffer_ptr = gfx::Buffer::CreateVolatileBuffer(context, scene_uniforms_data_size); frame.scene_uniforms_buffer_ptr->SetName(IndexedName("Scene Uniforms Buffer", frame.index)); // Create uniforms buffer for Sky-Box rendering frame.skybox.uniforms_buffer_ptr = gfx::Buffer::CreateVolatileBuffer(context, sizeof(gfx::SkyBox::Uniforms)); frame.skybox.uniforms_buffer_ptr->SetName(IndexedName("Sky-box Uniforms Buffer", frame.index)); // Create uniforms buffer for Planet rendering frame.planet.uniforms_buffer_ptr = gfx::Buffer::CreateVolatileBuffer(context, sizeof(Planet::Uniforms)); frame.planet.uniforms_buffer_ptr->SetName(IndexedName("Planet Uniforms Buffer", frame.index)); // Create uniforms buffer for Asteroids array rendering frame.asteroids.uniforms_buffer_ptr = gfx::Buffer::CreateVolatileBuffer(context, asteroid_uniforms_data_size, true); frame.asteroids.uniforms_buffer_ptr->SetName(IndexedName("Asteroids Array Uniforms Buffer", frame.index)); // Resource bindings for Sky-Box rendering frame.skybox.program_bindings_per_instance.resize(1); frame.skybox.program_bindings_per_instance[0] = m_sky_box_ptr->CreateProgramBindings(frame.skybox.uniforms_buffer_ptr, frame.index); // Resource bindings for Planet rendering frame.planet.program_bindings_per_instance.resize(1); frame.planet.program_bindings_per_instance[0] = m_planet_ptr->CreateProgramBindings(m_const_buffer_ptr, frame.planet.uniforms_buffer_ptr, frame.index); // Resource bindings for Asteroids rendering frame.asteroids.program_bindings_per_instance = m_asteroids_array_ptr->CreateProgramBindings(m_const_buffer_ptr, frame.scene_uniforms_buffer_ptr, frame.asteroids.uniforms_buffer_ptr, frame.index); } // Update initial resource states before asteroids drawing without applying barriers on GPU (automatic state propagation from Common state works), // which is required for correct automatic resource barriers to be set after asteroids drawing, on planet drawing m_asteroids_array_ptr->CreateBeginningResourceBarriers(*m_const_buffer_ptr)->UpdateResourceStates(); CompleteInitialization(); META_LOG(GetParametersString()); } bool AsteroidsApp::Resize(const gfx::FrameSize& frame_size, bool is_minimized) { META_FUNCTION_TASK(); // Resize screen color and depth textures if (!UserInterfaceApp::Resize(frame_size, is_minimized)) return false; // Update frame buffer and depth textures in initial & final render passes for (const AsteroidsFrame& frame : GetFrames()) { META_CHECK_ARG_NOT_NULL(frame.initial_screen_pass_ptr); gfx::RenderPass::Settings initial_pass_settings = frame.initial_screen_pass_ptr->GetSettings(); initial_pass_settings.color_attachments[0].texture_location = gfx::Texture::Location(frame.screen_texture_ptr); initial_pass_settings.depth_attachment.texture_location = gfx::Texture::Location(GetDepthTexturePtr()); frame.initial_screen_pass_ptr->Update(initial_pass_settings); META_CHECK_ARG_NOT_NULL(frame.final_screen_pass_ptr); gfx::RenderPass::Settings final_pass_settings = frame.final_screen_pass_ptr->GetSettings(); final_pass_settings.color_attachments[0].texture_location = gfx::Texture::Location(frame.screen_texture_ptr); final_pass_settings.depth_attachment.texture_location = gfx::Texture::Location(GetDepthTexturePtr()); frame.final_screen_pass_ptr->Update(final_pass_settings); } m_view_camera.Resize({ static_cast<float>(frame_size.GetWidth()), static_cast<float>(frame_size.GetHeight()) }); return true; } bool AsteroidsApp::Update() { META_FUNCTION_TASK(); META_SCOPE_TIMER("AsteroidsApp::Update"); if (!UserInterfaceApp::Update()) return false; // Update scene uniforms m_scene_uniforms.view_proj_matrix = hlslpp::transpose(m_view_camera.GetViewProjMatrix()); m_scene_uniforms.eye_position = m_view_camera.GetOrientation().eye; m_scene_uniforms.light_position = m_light_camera.GetOrientation().eye; m_sky_box_ptr->Update(); return true; } bool AsteroidsApp::Animate(double elapsed_seconds, double delta_seconds) const { META_FUNCTION_TASK(); bool update_result = m_planet_ptr->Update(elapsed_seconds, delta_seconds); update_result |= m_asteroids_array_ptr->Update(elapsed_seconds, delta_seconds); return update_result; } bool AsteroidsApp::Render() { META_FUNCTION_TASK(); META_SCOPE_TIMER("AsteroidsApp::Render"); if (!UserInterfaceApp::Render()) return false; // Upload uniform buffers to GPU AsteroidsFrame& frame = GetCurrentFrame(); frame.scene_uniforms_buffer_ptr->SetData(m_scene_uniforms_subresources); // Asteroids rendering in parallel or in main thread if (m_is_parallel_rendering_enabled) { GetAsteroidsArray().DrawParallel(*frame.parallel_cmd_list_ptr, frame.asteroids, GetViewState()); frame.parallel_cmd_list_ptr->Commit(); } else { GetAsteroidsArray().Draw(*frame.serial_cmd_list_ptr, frame.asteroids, GetViewState()); frame.serial_cmd_list_ptr->Commit(); } // Draw planet and sky-box after asteroids to minimize pixel overdraw m_planet_ptr->Draw(*frame.final_cmd_list_ptr, frame.planet, GetViewState()); m_sky_box_ptr->Draw(*frame.final_cmd_list_ptr, frame.skybox, GetViewState()); RenderOverlay(*frame.final_cmd_list_ptr); frame.final_cmd_list_ptr->Commit(); // Execute rendering commands and present frame to screen GetRenderContext().GetRenderCommandKit().GetQueue().Execute(*frame.execute_cmd_list_set_ptr); GetRenderContext().Present(); return true; } void AsteroidsApp::OnContextReleased(gfx::Context& context) { META_FUNCTION_TASK(); META_SCOPE_TIMERS_FLUSH(); if (m_asteroids_array_ptr) { m_asteroids_array_state_ptr = m_asteroids_array_ptr->GetState(); } m_sky_box_ptr.reset(); m_planet_ptr.reset(); m_asteroids_array_ptr.reset(); m_const_buffer_ptr.reset(); UserInterfaceApp::OnContextReleased(context); } void AsteroidsApp::SetAsteroidsComplexity(uint32_t asteroids_complexity) { META_FUNCTION_TASK(); asteroids_complexity = std::min(g_max_complexity, asteroids_complexity); if (m_asteroids_complexity == asteroids_complexity) return; if (IsRenderContextInitialized()) { GetRenderContext().WaitForGpu(gfx::RenderContext::WaitFor::RenderComplete); } m_asteroids_complexity = asteroids_complexity; const MutableParameters& mutable_parameters = GetMutableParameters(m_asteroids_complexity); m_asteroids_array_settings.instance_count = mutable_parameters.instances_count; m_asteroids_array_settings.unique_mesh_count = mutable_parameters.unique_mesh_count; m_asteroids_array_settings.textures_count = mutable_parameters.textures_count; m_asteroids_array_settings.min_asteroid_scale_ratio = mutable_parameters.scale_ratio / 10.F; m_asteroids_array_settings.max_asteroid_scale_ratio = mutable_parameters.scale_ratio; m_asteroids_array_ptr.reset(); m_asteroids_array_state_ptr.reset(); if (IsRenderContextInitialized()) GetRenderContext().Reset(); UpdateParametersText(); } void AsteroidsApp::SetParallelRenderingEnabled(bool is_parallel_rendering_enabled) { META_FUNCTION_TASK(); if (m_is_parallel_rendering_enabled == is_parallel_rendering_enabled) return; META_SCOPE_TIMERS_FLUSH(); m_is_parallel_rendering_enabled = is_parallel_rendering_enabled; for(AsteroidsFrame& frame : GetFrames()) { frame.execute_cmd_list_set_ptr = CreateExecuteCommandListSet(frame); } UpdateParametersText(); META_LOG(GetParametersString()); } AsteroidsArray& AsteroidsApp::GetAsteroidsArray() const { META_FUNCTION_TASK(); META_CHECK_ARG_NOT_NULL(m_asteroids_array_ptr); return *m_asteroids_array_ptr; } std::string AsteroidsApp::GetParametersString() { META_FUNCTION_TASK(); std::stringstream ss; ss << "Asteroids simulation parameters:" << std::endl << " - simulation complexity [0.." << g_max_complexity << "]: " << m_asteroids_complexity << std::endl << " - asteroid instances count: " << m_asteroids_array_settings.instance_count << std::endl << " - unique meshes count: " << m_asteroids_array_settings.unique_mesh_count << std::endl << " - mesh subdivisions count: " << m_asteroids_array_settings.subdivisions_count << std::endl << " - unique textures count: " << m_asteroids_array_settings.textures_count << " " << std::endl << " - asteroid textures size: " << static_cast<std::string>(m_asteroids_array_settings.texture_dimensions) << std::endl << " - textures array binding: " << (m_asteroids_array_settings.textures_array_enabled ? "ON" : "OFF") << std::endl << " - parallel rendering: " << (m_is_parallel_rendering_enabled ? "ON" : "OFF") << std::endl << " - asteroid animations: " << (!GetAnimations().IsPaused() ? "ON" : "OFF") << std::endl << " - CPU h/w thread count: " << std::thread::hardware_concurrency(); return ss.str(); } Ptr<gfx::CommandListSet> AsteroidsApp::CreateExecuteCommandListSet(const AsteroidsFrame& frame) const { return gfx::CommandListSet::Create({ m_is_parallel_rendering_enabled ? static_cast<gfx::CommandList&>(*frame.parallel_cmd_list_ptr) : static_cast<gfx::CommandList&>(*frame.serial_cmd_list_ptr), *frame.final_cmd_list_ptr }); } } // namespace Methane::Samples int main(int argc, const char* argv[]) { return Methane::Samples::AsteroidsApp().Run({ argc, argv }); }
47.248544
205
0.668064
[ "mesh", "render" ]
ae18f6318e9b92b92059cca56de43fcb0dd13f2c
4,501
hpp
C++
vts-libs/vts0/tileop.hpp
melowntech/vts-libs
ffbf889b6603a8f95d3c12a2602232ff9c5d2236
[ "BSD-2-Clause" ]
2
2020-04-20T01:44:46.000Z
2021-01-15T06:54:51.000Z
externals/browser/externals/browser/externals/vts-libs/vts-libs/vts0/tileop.hpp
HanochZhu/vts-browser-unity-plugin
32a22d41e21b95fb015326f95e401d87756d0374
[ "BSD-2-Clause" ]
2
2020-01-29T16:30:49.000Z
2020-06-03T15:21:29.000Z
externals/browser/externals/browser/externals/vts-libs/vts-libs/vts0/tileop.hpp
HanochZhu/vts-browser-unity-plugin
32a22d41e21b95fb015326f95e401d87756d0374
[ "BSD-2-Clause" ]
1
2019-09-25T05:10:07.000Z
2019-09-25T05:10:07.000Z
/** * Copyright (c) 2017 Melown Technologies SE * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef vtslibs_vts0_tileop_hpp_included_ #define vtslibs_vts0_tileop_hpp_included_ #include "../storage/filetypes.hpp" #include "basetypes.hpp" #include "properties.hpp" #include "types.hpp" namespace vtslibs { namespace vts0 { using storage::TileFile; using storage::File; TileId fromAlignment(const Properties &properties, const TileId &tileId); TileId parent(const TileId &tileId); Children children(const TileId &tileId); bool isMetatile(const LodLevels &levels, const TileId &tile); Lod deltaDown(const LodLevels &levels, Lod lod); /** Check whether super tile is above (or exactly the same tile) as tile. */ bool above(const TileId &tile, const TileId &super); int child(const TileId &tileId); bool in(const LodRange &range, const TileId &tileId); /** Calculates area of tile's mesh (m^2) and atlas (pixel^2). */ std::pair<double, double> area(const Tile &tile); std::string asFilename(const TileId &tileId, TileFile type); bool fromFilename(TileId &tileId, TileFile &type , const std::string &str , std::string::size_type offset = 0); TileId findMetatile(const LodLevels &metaLevels, TileId tileId); math::Size2f tileSize(const Properties &prop, Lod lod); math::Size2f tileSize(const math::Extents2 &rootExtents, Lod lod); std::size_t tileCount(Lod lod); TileId fromLl(const Properties &prop, Lod lod, const math::Point2 &ll); math::Extents2 aligned(const Properties &prop, Lod lod , math::Extents2 in); math::Extents2 extents(const Properties &prop, const TileId &tileId); // inline stuff inline TileId parent(const TileId &tileId) { return TileId(tileId.lod - 1, tileId.x >> 1, tileId.y >> 1); } inline Children children(const TileId &tileId) { TileId base(tileId.lod + 1, tileId.x << 1, tileId.y << 1); // children must be from lower-left due to adapter return {{ { base.lod, base.x, base.y + 1 } // lower-left , { base.lod, base.x + 1, base.y + 1 } // lower-right , base // upper-left , { base.lod, base.x + 1, base.y } // upper-right }}; } inline bool isMetatile(const LodLevels &levels, const TileId &tile) { return !(std::abs(tile.lod - levels.lod) % levels.delta); } inline Lod deltaDown(const LodLevels &levels, Lod lod) { Lod res(lod + 1); while (std::abs(res - levels.lod) % levels.delta) { ++res; } return res; } inline int child(const TileId &tileId) { return (tileId.x & 1l) + ((tileId.y & 1l) << 1); } inline bool in(const LodRange &range, const TileId &tileId) { return (tileId.lod >= range.min) && (tileId.lod <= range.max); } inline TileId findMetatile(const LodLevels &metaLevels, TileId tileId) { while ((tileId.lod > 0) && !isMetatile(metaLevels, tileId)) { tileId = parent(tileId); } return tileId; } inline math::Size2f tileSize(const Properties &prop, Lod lod) { return tileSize(prop.extents, lod); } inline std::size_t tileCount(Lod lod) { return std::size_t(1) << lod; } } } // namespace vtslibs::vts0 #endif // vtslibs_vts0_tileop_hpp_included_
30.208054
78
0.696956
[ "mesh" ]
ae2184f6a52af8539b23ef70c09e5cadcc357437
6,599
cpp
C++
mpi_communication_partition/mpi_communication_partition_pass.cpp
tudasc/CommPart
f5e6739d69d4ca8dd6528cb9657df398a9f0caa8
[ "Apache-2.0" ]
3
2021-04-04T01:12:47.000Z
2021-06-07T14:27:45.000Z
mpi_communication_partition/mpi_communication_partition_pass.cpp
tudasc/CommPart
f5e6739d69d4ca8dd6528cb9657df398a9f0caa8
[ "Apache-2.0" ]
null
null
null
mpi_communication_partition/mpi_communication_partition_pass.cpp
tudasc/CommPart
f5e6739d69d4ca8dd6528cb9657df398a9f0caa8
[ "Apache-2.0" ]
null
null
null
/* Copyright 2021 Tim Jammer Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ //TODO clean Includes #include "llvm/ADT/APInt.h" #include "llvm/ADT/StringRef.h" #include "llvm/IR/BasicBlock.h" #include "llvm/IR/Constants.h" #include "llvm/IR/DerivedTypes.h" #include "llvm/IR/Function.h" #include "llvm/IR/IRBuilder.h" #include "llvm/IR/InstrTypes.h" #include "llvm/IR/Instruction.h" #include "llvm/IR/LegacyPassManager.h" #include "llvm/IR/Module.h" #include "llvm/IR/Type.h" #include "llvm/Pass.h" #include "llvm/Analysis/CFG.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Transforms/IPO/PassManagerBuilder.h" #include "llvm/Transforms/Utils/BasicBlockUtils.h" #include "llvm/Analysis/AliasAnalysis.h" #include "llvm/Analysis/BasicAliasAnalysis.h" #include "llvm/Analysis/LoopInfo.h" #include "llvm/Analysis/ScalarEvolution.h" #include "llvm/Analysis/TargetLibraryInfo.h" #include "llvm/IR/Dominators.h" #include "llvm/Analysis/PostDominators.h" #include "llvm/IR/InstIterator.h" #include "llvm/Analysis/ScalarEvolutionExpressions.h" // AA implementations #include "llvm/Analysis/AliasAnalysis.h" #include "llvm/Analysis/BasicAliasAnalysis.h" #include "llvm/Analysis/CFLAndersAliasAnalysis.h" #include "llvm/Analysis/CFLSteensAliasAnalysis.h" #include "llvm/Analysis/CaptureTracking.h" #include "llvm/Analysis/GlobalsModRef.h" #include "llvm/Analysis/MemoryLocation.h" #include "llvm/Analysis/ObjCARCAliasAnalysis.h" #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h" #include "llvm/Analysis/ScopedNoAliasAA.h" #include "llvm/Analysis/TargetLibraryInfo.h" #include "llvm/Analysis/TypeBasedAliasAnalysis.h" #include "llvm/IR/Verifier.h" #include "llvm/Transforms/Utils/Cloning.h" #include <assert.h> //#include <mpi.h> #include <cstring> #include <utility> #include <vector> #include "analysis_results.h" #include "debug.h" #include "implementation_specific.h" #include "mpi_functions.h" #include "helper.h" #include "insert_changes.h" #include "Microtask.h" #include "sending_partitioning.h" using namespace llvm; // declare dso_local i32 @MPI_Recv(i8*, i32, i32, i32, i32, i32, // %struct.MPI_Status*) #1 RequiredAnalysisResults *analysis_results; MpiFunctions *mpi_func; ImplementationSpecifics *mpi_implementation_specifics; namespace { struct MSGOrderRelaxCheckerPass: public ModulePass { static char ID; MSGOrderRelaxCheckerPass() : ModulePass(ID) { } // register that we require this analysis void getAnalysisUsage(AnalysisUsage &AU) const { AU.addRequired<TargetLibraryInfoWrapperPass>(); AU.addRequiredTransitive<AAResultsWrapperPass>(); //AU.addRequired<AAResultsWrapperPass>(); AU.addRequired<LoopInfoWrapperPass>(); AU.addRequired<ScalarEvolutionWrapperPass>(); AU.addRequired<DominatorTreeWrapperPass>(); AU.addRequired<PostDominatorTreeWrapperPass>(); // various AA implementations /* AU.addRequired<ScopedNoAliasAAWrapperPass>(); AU.addRequired<TypeBasedAAWrapperPass>(); // USING THIS WILL RESULT IN A CRASH there my be a bug AU.addRequired<BasicAAWrapperPass>(); AU.addRequired<GlobalsAAWrapperPass>(); AU.addRequired<SCEVAAWrapperPass>(); // these also result in bug AU.addRequired<CFLAndersAAWrapperPass>(); AU.addRequired<CFLSteensAAWrapperPass>(); */ } /* void getAnalysisUsage(AnalysisUsage &AU) const { AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); AU.addRequiredTransitive<AAResultsWrapperPass>(); AU.addRequiredTransitive<LoopInfoWrapperPass>(); AU.addRequiredTransitive<ScalarEvolutionWrapperPass>(); } */ StringRef getPassName() const { return "MPI Communication Partition"; } // Pass starts here virtual bool runOnModule(Module &M) { //Debug(M.dump();); //M.print(errs(), nullptr); M.getFunction("main")->dump(); mpi_func = new MpiFunctions(M); if (!mpi_func->is_mpi_used()) { // nothing to do for non mpi applications delete mpi_func; return false; } bool modification = false; analysis_results = new RequiredAnalysisResults(this, &M); mpi_implementation_specifics = new ImplementationSpecifics(M); for (auto *send_function : mpi_func->get_used_send_functions()) { // this iterator might be invalidated if a send call gets removed // so we collect all instructions into a vector beforehand std::vector<User*>senders; std::copy(send_function->user_begin(), send_function->user_end(), std::back_inserter(senders)); for (auto *s : senders) { //TODO do wen need to make shure this send call is actually still valid? if (auto *send_call = dyn_cast<CallInst>(s)) { modification = modification | handle_send_call(send_call); } } } //M.dump(); // only need to dump the relevant part /* M.getFunction("main")->dump(); M.getFunction(".omp_outlined.")->dump(); M.getFunction("main")->dump(); if (M.getFunction(".omp_outlined._p") != nullptr) { M.getFunction(".omp_outlined._p")->dump(); }*/ bool broken_dbg_info; bool module_errors = verifyModule(M, &errs(), &broken_dbg_info); if (!module_errors) { errs() << "Successfully executed the pass\n\n"; } else { errs() << "Module Verification ERROR\n"; } delete mpi_func; delete mpi_implementation_specifics; delete analysis_results; return modification; } } ; // class MSGOrderRelaxCheckerPass }// namespace char MSGOrderRelaxCheckerPass::ID = 42; // Automatically enable the pass. // http://adriansampson.net/blog/clangpass.html static void registerExperimentPass(const PassManagerBuilder&, legacy::PassManagerBase &PM) { PM.add(new MSGOrderRelaxCheckerPass()); } // static RegisterStandardPasses // RegisterMyPass(PassManagerBuilder::EP_ModuleOptimizerEarly, // static RegisterStandardPasses RegisterMyPass( PassManagerBuilder::EP_VectorizerStart, registerExperimentPass); // before vectorization makes analysis way harder //This extension point allows adding optimization passes before the vectorizer and other highly target specific optimization passes are executed. static RegisterStandardPasses RegisterMyPass0( PassManagerBuilder::EP_EnabledOnOptLevel0, registerExperimentPass);
29.070485
145
0.757842
[ "vector" ]
ae2e14e96a8883eaf60da2d6646995c4c12a08be
124
cpp
C++
src/Target/index.cpp
YiraSan/llvm-bindings
9fdae3c836eb329d42f8253adadf09ecaa44e2ee
[ "MIT" ]
155
2021-03-25T09:21:47.000Z
2022-03-30T01:51:40.000Z
src/Target/index.cpp
YiraSan/llvm-bindings
9fdae3c836eb329d42f8253adadf09ecaa44e2ee
[ "MIT" ]
13
2021-03-31T01:54:34.000Z
2022-03-19T05:43:45.000Z
src/Target/index.cpp
YiraSan/llvm-bindings
9fdae3c836eb329d42f8253adadf09ecaa44e2ee
[ "MIT" ]
20
2021-04-11T05:27:43.000Z
2022-03-06T04:48:15.000Z
#include "Target/index.h" void InitTarget(Napi::Env env, Napi::Object &exports) { TargetMachine::Init(env, exports); }
20.666667
55
0.701613
[ "object" ]
ae328622bf568ff5168d99cf1584906bbf54d708
2,812
cpp
C++
code/tests/gfx/src/main.cpp
BrightComposite/RaptureStateToolkit
6eb3c831540ba6a9d29e903dd3c537aac2e7f91f
[ "MIT" ]
null
null
null
code/tests/gfx/src/main.cpp
BrightComposite/RaptureStateToolkit
6eb3c831540ba6a9d29e903dd3c537aac2e7f91f
[ "MIT" ]
null
null
null
code/tests/gfx/src/main.cpp
BrightComposite/RaptureStateToolkit
6eb3c831540ba6a9d29e903dd3c537aac2e7f91f
[ "MIT" ]
null
null
null
//--------------------------------------------------------------------------- #include <application/starter.h> #include <opengl_window/context.h> #include <opengl/mesh.h> #include <opengl/shader.h> #include <opengl/uniform.h> #include <math/vector.h> #include <math/quaternion.h> #include <iostream> #include <valarray> #include <benchmark> //--------------------------------------------------------------------------- namespace asd { struct COLOR_SHADER { using tag = opengl::shader_program; static auto key() { return "2d/color"; } }; int launch(window & w, opengl::context & context); static entrance open([]() { opengl::driver driver; try { window w("gfx:test", {50, 50, 400, 400}); auto & context = w.bind(driver); std::cout << "Press ESC to exit" << std::endl; w.show(); launch(w, context); } catch (const window_creation_exception & e) { std::cerr << "Window creation error: " << e.what() << std::endl; } catch (const graphics_exception & e) { std::cerr << "Error: " << e.what() << std::endl; } }); int launch(window & w, opengl::context & context) { benchmark raw("draw triangle opengl"); benchmark queued("draw triangle queued"); benchmark immediate("draw triangle immediately"); namespace uniform = gfx3d::uniform; auto & uniforms = get<uniform::component>(context); auto & color_uniform = uniforms.register_uniform("Color", { uniform::scheme::create<uniform::f32v4>("color") }); auto color_block = color_uniform.create_block(); color_block.set(0, gfx::colorf(1.0f, 0.5f, 0.5f, 1.0f)); auto & layout = opengl::vertex_layouts::p2::get(); gfx3d::vertex_data data({ -0.5f, -0.5f, 0.5f, -0.5f, 0.0f, 0.5f, }); auto mesh = opengl::mesh_builder::build(context, layout, data); opengl::shader_program program(context, opengl::shader_code::get(COLOR_SHADER::key())); return w.context([&]() { glClearColor(1.0, 0.0, 0.0, 1.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); color_block.set(0, gfx::colorf(1.0f, 0.5f, 0.5f, 1.0f)); color_uniform.update(); double r = raw([&]() { color_block.bind(); program.apply(); opengl::draw_mesh(context, *mesh); }); context.flush(); std::cout << r / 1'000'000 << "ms" << " " << std::endl; }); } } //---------------------------------------------------------------------------
30.236559
120
0.48542
[ "mesh", "vector" ]
ae3384aea4c30b8163c5ca63bb4b109292b5c001
23,333
cpp
C++
knowledgebase_creator/src/containers/ConceptNetCall.cpp
StephanOpfer/symrock
519f684374124707f684edceb9b53156fe3bafbc
[ "MIT" ]
1
2018-12-04T16:16:41.000Z
2018-12-04T16:16:41.000Z
knowledgebase_creator/src/containers/ConceptNetCall.cpp
carpe-noctem-cassel/symrock
519f684374124707f684edceb9b53156fe3bafbc
[ "MIT" ]
2
2019-02-28T10:44:06.000Z
2019-03-28T12:31:01.000Z
knowledgebase_creator/src/containers/ConceptNetCall.cpp
carpe-noctem-cassel/symrock
519f684374124707f684edceb9b53156fe3bafbc
[ "MIT" ]
null
null
null
#include <gui/KnowledgebaseCreator.h> #include "gui/ModelSettingDialog.h" #include "containers/ConceptNetCall.h" #include "containers/ConceptNetEdge.h" #include "containers/ConceptNetConcept.h" #include <sstream> namespace kbcr { ConceptNetCall::ConceptNetCall(KnowledgebaseCreator *gui, QString id, QString queryConcept) { this->gui = gui; this->id = id; this->nextEdgesPage = nextEdgesPage; this->collectSynonymConceptsNAM = new QNetworkAccessManager(this); this->collectAntonymConceptsNAM = new QNetworkAccessManager(this); this->collectUsedForConceptsNAM = new QNetworkAccessManager(this); this->queryConcept = queryConcept; this->connect(this->collectSynonymConceptsNAM, SIGNAL(finished(QNetworkReply * )), this, SLOT(collectConcepts(QNetworkReply * ))); this->connect(this->collectAntonymConceptsNAM, SIGNAL(finished(QNetworkReply * )), this, SLOT(mapAntonyms(QNetworkReply * ))); this->connect(this->collectUsedForConceptsNAM, SIGNAL(finished(QNetworkReply * )), this, SLOT(mapServices(QNetworkReply * ))); this->newConceptFound = false; } ConceptNetCall::~ConceptNetCall() { // delete this->collectAntonymConceptsNAM; // delete this->collectSynonymConceptsNAM; } std::string ConceptNetCall::toString() { std::stringstream ss; ss << "ConceptNetCall:" << std::endl; ss << "ID: " << this->id.toStdString() << std::endl; ss << "Edges:" << std::endl; for (auto edge : this->edges) { ss << edge->toString(); } ss << "NextEdgePage: " << this->nextEdgesPage.toStdString() << std::endl; ss << "Concepts: " << std::endl; for (auto concept : this->concepts) { ss << concept.toStdString() << " "; } ss << "Adjectives: " << std::endl; for (auto adjective : this->connectedConcepts) { ss << adjective.first.toStdString() << " "; } ss << std::endl; return ss.str(); } void ConceptNetCall::findServices() { if (this->queryConcept.compare("wildcard") == 0) { return; } std::cout << "ConceptNetCall: queryConcept " << this->queryConcept.toStdString() << std::endl; for (auto edge : this->edges) { if (edge->relation.compare("MotivatedByGoal") == 0) { if (edge->secondConcept->term.compare(this->queryConcept) == 0) { this->connectedConcepts.emplace(edge->firstConcept->term, edge); std::cout << "ConceptNetCall: edge " << edge->firstConcept->term.toStdString() << std::endl; } } } collectMotivatedByGoals(); for (auto pair : this->motivatedConceptMap) { std::cout << "MotivatedConcept: " << pair.first.toStdString() << std::endl; std::cout << "\t UsedFor: "; for (auto usedFor : pair.second) { std::cout << usedFor.toStdString() << " "; } std::cout << std::endl; } } void ConceptNetCall::collectMotivatedByGoals() { for (auto motivatedConcepts : this->connectedConcepts) { this->motivatedConceptMap.emplace(motivatedConcepts.first, std::vector<QString>()); this->currentMotivatedConcept = motivatedConcepts.first; QUrl url(KnowledgebaseCreator::CONCEPTNET_BASE_URL + KnowledgebaseCreator::CONCEPTNET_URL_QUERYEND + motivatedConcepts.first + "&rel=/r/UsedFor" + "&limit=1000"); QEventLoop loop; this->connect(this, SIGNAL(closeCollectLoop()), &loop, SLOT(quit())); this->callUrl(url, this->collectUsedForConceptsNAM); loop.exec(); } this->collectUsedForConceptsNAM->deleteLater(); } void ConceptNetCall::mapServices(QNetworkReply *reply) { //not current adjective and not already in QString data = reply->readAll(); //remove html part std::string fullData = data.toStdString(); auto start = fullData.find("{\"@context\":"); auto end = fullData.find("</script>"); fullData = fullData.substr(start, end - start); // parse json auto jsonString = QString(fullData.c_str()).toUtf8(); QJsonDocument jsonDoc(QJsonDocument::fromJson(jsonString)); QJsonArray edges = jsonDoc.object()["edges"].toArray(); for (int i = 0; i < std::min(edges.size(), 5); i++) { // best x edges only QJsonObject edge = edges[i].toObject(); double weight = edge["weight"].toDouble(); if (weight < this->gui->modelSettingsDialog->getMinCn5Weight()) { break; } //end of edge QJsonObject end = edge["end"].toObject(); QString endLanguage = end["language"].toString(); // skip non English if (endLanguage != "en") { continue; } QString endTerm = end["term"].toString(); endTerm = trimTerm(endTerm); if (endTerm.at(0).isDigit() || this->conceptContainsUTF8(endTerm)) { // std::cout << "ConceptNetCall: Skipping Antonym:" << endTerm.toStdString() << std::endl; continue; } //start of edge QJsonObject start = edge["start"].toObject(); QString startLanguage = start["language"].toString(); // skip non English if (startLanguage != "en") { continue; } QString startTerm = start["term"].toString(); startTerm = trimTerm(startTerm); if (startTerm.at(0).isDigit() || this->conceptContainsUTF8(startTerm)) { // std::cout << "ConceptNetCall: Skipping Antonym:" << startTerm.toStdString() << std::endl; continue; } auto tmp = this->motivatedConceptMap.at(currentMotivatedConcept); if (std::find(tmp.begin(), tmp.end(), startTerm) == tmp.end()) { this->motivatedConceptMap.at(currentMotivatedConcept).push_back(startTerm); } } if (this->motivatedConceptMap.at(currentMotivatedConcept).size() == 0) { this->motivatedConceptMap.erase(currentMotivatedConcept); } emit closeCollectLoop(); } void ConceptNetCall::findInconsistencies() { if (this->queryConcept.compare("wildcard") == 0) { return; } for (auto edge : this->edges) { if (edge->firstConcept->senseLabel.compare("a") == 0 && edge->firstConcept->term.compare(this->queryConcept) != 0) { if (this->connectedConcepts.find(edge->firstConcept->term) == this->connectedConcepts.end()) { this->connectedConcepts.emplace(edge->firstConcept->term, edge); } } if (edge->secondConcept->senseLabel.compare("a") == 0 && edge->secondConcept->term.compare(this->queryConcept) != 0) { if (this->connectedConcepts.find(edge->secondConcept->term) == this->connectedConcepts.end()) { this->connectedConcepts.emplace(edge->secondConcept->term, edge); } } } // std::cout << "ConceptNetCall: Adjectives size: " << this->connectedConcepts.size() << std::endl; collectAntonyms(); // std::cout << "ConceptNetCall: Finished collecting Antonyms." << std::endl; checkAdjectives(); // std::cout << "ConceptNetCall: Finished checking Antonyms among the connectedConcepts of the queried concept." // << std::endl; for (auto adj : this->connectedConcepts) { auto tmp = std::make_shared<std::vector<QString>>(); tmp->push_back(adj.first); this->gatherMap.emplace(adj.first, tmp); } gatherConcepts(this->connectedConcepts); // std::cout << "ConceptNetCall: Finished gathering related concepts. Number of found concepts: " // << gatheredConcepts.size() << std::endl; for (auto adj : this->connectedConcepts) { if (this->gatherMap.at(adj.first)->size() == 1) { this->gatherMap.erase(adj.first); } } checkGatheredConcepts(); // std::cout << "ConceptNetCall: Finished checking Antonyms among gathered concepts." << std::endl; } void ConceptNetCall::checkGatheredConcepts() { // for (auto i : this->gatherMap) // { // std::cout << i.first.toStdString() << ": "; // for (auto j : *i.second) // { // std::cout << j.toStdString() << " "; // } // std::cout << std::endl; // } std::map<QString, std::vector<QString>>::iterator it; bool conceptDeleted = false; for (it = this->adjectiveAntonymMap.begin(); it != this->adjectiveAntonymMap.end();) { if (this->adjectiveAntonymMap.find(it->first) == this->adjectiveAntonymMap.end()) { it++; continue; } for (auto gathered : this->gatherMap) { for (auto concept : *gathered.second) { if (std::find(it->second.begin(), it->second.end(), concept) != it->second.end()) { if (this->connectedConcepts.find(gathered.first) == this->connectedConcepts.end()) { continue; } if (this->connectedConcepts.at(it->first)->weight < this->connectedConcepts.at(gathered.first)->weight) { auto iterator = this->connectedConcepts.find(it->first); if (iterator != this->connectedConcepts.end()) { // std::cout << "ConceptNetCall: Antonym found: removing: " << it->first.toStdString() // << " keeping: " << gathered.first.toStdString() << std::endl; this->connectedConcepts.erase(it->first); this->adjectiveAntonymMap.erase(it->first); conceptDeleted = true; } } else { auto iterator = this->connectedConcepts.find(gathered.first); if (iterator != this->connectedConcepts.end()) { // std::cout << "ConceptNetCall: Antonym found: removing: " << gathered.first.toStdString() // << " keeping: " << it->first.toStdString() << std::endl; this->connectedConcepts.erase(gathered.first); this->adjectiveAntonymMap.erase(gathered.first); conceptDeleted = true; } } } } } if (!conceptDeleted) { it++; } else { conceptDeleted = false; } } } void ConceptNetCall::checkAdjectives(/*std::map<QString, std::shared_ptr<ConceptNetEdge>> toCheck*/) { std::map<QString, std::vector<QString>>::iterator it; bool conceptDeleted = false; for (it = this->adjectiveAntonymMap.begin(); it != this->adjectiveAntonymMap.end();) { if (this->adjectiveAntonymMap.find(it->first) == this->adjectiveAntonymMap.end()) { it++; continue; } for (auto antonym : it->second) { if (this->connectedConcepts.find(antonym) == this->connectedConcepts.end()) { continue; } if (this->connectedConcepts.at(it->first)->weight < this->connectedConcepts.at(antonym)->weight) { auto iterator = this->connectedConcepts.find(it->first); if (iterator != this->connectedConcepts.end()) { // std::cout << "ConceptNetCall: Antonym found: removing: " << it->first.toStdString() // << " keeping: " << antonym.toStdString() << std::endl; this->connectedConcepts.erase(it->first); this->adjectiveAntonymMap.erase(it->first); conceptDeleted = true; } } else { auto iterator = this->connectedConcepts.find(antonym); if (iterator != this->connectedConcepts.end()) { // std::cout << "ConceptNetCall: Antonym found: removing: " << antonym.toStdString() // << " keeping: " << it->first.toStdString() << std::endl; this->connectedConcepts.erase(antonym); this->adjectiveAntonymMap.erase(antonym); conceptDeleted = true; } } } if (!conceptDeleted) { it++; } else { conceptDeleted = false; } } } QString ConceptNetCall::trimTerm(QString term) { auto pos = term.lastIndexOf("/"); return term.right(term.length() - pos - 1); } void ConceptNetCall::gatherConcepts(std::map<QString, std::shared_ptr<ConceptNetEdge>> toCheck) { this->newConceptFound = false; for (auto adjective : toCheck) { this->currentConcept = adjective.first; QEventLoop loopIsA; this->connect(this, SIGNAL(closeLoopAdjectiveGathering()), &loopIsA, SLOT(quit())); QUrl urlIsA(KnowledgebaseCreator::CONCEPTNET_BASE_URL + KnowledgebaseCreator::CONCEPTNET_URL_QUERYSTART + adjective.first + "&rel=/r/IsA" + "&limit=1000"); this->callUrl(urlIsA, this->collectSynonymConceptsNAM); loopIsA.exec(); QEventLoop loopSynonym; this->connect(this, SIGNAL(closeLoopAdjectiveGathering()), &loopSynonym, SLOT(quit())); QUrl urlSynonym( KnowledgebaseCreator::CONCEPTNET_BASE_URL + KnowledgebaseCreator::CONCEPTNET_URL_QUERYSTART + adjective.first + "&rel=/r/Synonym" + "&limit=1000"); this->callUrl(urlSynonym, this->collectSynonymConceptsNAM); loopSynonym.exec(); QEventLoop loopDefinedAs; this->connect(this, SIGNAL(closeLoopAdjectiveGathering()), &loopDefinedAs, SLOT(quit())); QUrl urlDefinedAs( KnowledgebaseCreator::CONCEPTNET_BASE_URL + KnowledgebaseCreator::CONCEPTNET_URL_QUERYSTART + adjective.first + "&rel=/r/DefinedAs" + "&limit=1000"); this->callUrl(urlDefinedAs, this->collectSynonymConceptsNAM); loopDefinedAs.exec(); QEventLoop loopPartOf; this->connect(this, SIGNAL(closeLoopAdjectiveGathering()), &loopPartOf, SLOT(quit())); QUrl urlPartOf( KnowledgebaseCreator::CONCEPTNET_BASE_URL + KnowledgebaseCreator::CONCEPTNET_URL_QUERYSTART + adjective.first + "&rel=/r/PartOf" + "&limit=1000"); this->callUrl(urlPartOf, this->collectSynonymConceptsNAM); loopPartOf.exec(); this->conceptsToCheck.erase(adjective.first); } if (this->newConceptFound) { gatherConcepts(this->conceptsToCheck); } else { this->collectSynonymConceptsNAM->deleteLater(); } } void ConceptNetCall::collectConcepts(QNetworkReply *reply) { QString data = reply->readAll(); QJsonDocument jsonDoc(QJsonDocument::fromJson(data.toUtf8())); QJsonArray edges = jsonDoc.object()["edges"].toArray(); for (int i = 0; i < edges.size(); i++) { QJsonObject edge = edges[i].toObject(); auto cn5Edge = extractCNEdge(edge); if (cn5Edge == nullptr) { continue; } if (cn5Edge->id.compare("BREAK") == 0) { break; } QString endTerm = edge["end"].toObject()["term"].toString(); endTerm = trimTerm(endTerm); if (this->conceptsToCheck.find(endTerm) == this->conceptsToCheck.end() && this->gatheredConcepts.find(endTerm) == this->gatheredConcepts.end() && cn5Edge->secondConcept->senseLabel.compare("a") == 0) { this->conceptsToCheck.emplace(endTerm, cn5Edge); this->gatheredConcepts.emplace( endTerm, std::pair<QString, std::shared_ptr<ConceptNetEdge>>(this->currentConcept, cn5Edge)); this->newConceptFound = true; for (auto p : this->gatherMap) { if (std::find(p.second->begin(), p.second->end(), this->currentConcept) != p.second->end()) { p.second->push_back(endTerm); break; } } } } emit closeLoopAdjectiveGathering(); } bool ConceptNetCall::conceptContainsUTF8(QString concept) { for (int i = 0; i < concept.length(); i++) { if (concept.at(i).unicode() > 127) { return true; } } return false; } void ConceptNetCall::callUrl(QUrl url, QNetworkAccessManager *n) { QNetworkRequest request(url); request.setRawHeader("Accept", "application/json"); n->get(request); } std::shared_ptr<ConceptNetEdge> ConceptNetCall::extractCNEdge(QJsonObject edge) { QString edgeId = edge["@id"].toString(); double weight = edge["weight"].toDouble(); if (weight < this->gui->modelSettingsDialog->getMinCn5Weight()) { return std::make_shared<ConceptNetEdge>(QString("BREAK"), QString(""), nullptr, nullptr, QString(""), -1.0); } //end of edge QJsonObject end = edge["end"].toObject(); QString endLanguage = end["language"].toString(); // skip non English if (endLanguage != "en") { return nullptr; } QString endTerm = end["term"].toString(); endTerm = trimTerm(endTerm); if (endTerm.at(0).isDigit() || this->conceptContainsUTF8(endTerm)) { // std::cout << "ConceptNetCall: Skipping concept:" << endTerm.toStdString() << std::endl; return nullptr; } QString endSenseLabel = end["sense_label"].toString(); QString endID = end["@id"].toString(); //start of edge QJsonObject start = edge["start"].toObject(); QString startLanguage = start["language"].toString(); // skip non English if (startLanguage != "en") { return nullptr; } QString startTerm = start["term"].toString(); startTerm = trimTerm(startTerm); if (startTerm.at(0).isDigit() || this->conceptContainsUTF8(startTerm)) { // std::cout << "ConceptNetCall: Skipping Antonym:" << startTerm.toStdString() << std::endl; return nullptr; } QString startSenseLabel = start["sense_label"].toString(); QString startID = start["@id"].toString(); QString relation = edge["rel"].toObject()["@id"].toString(); relation = relation.right(relation.size() - relation.lastIndexOf('/') - 1); return std::make_shared<ConceptNetEdge>( edgeId, startLanguage, std::make_shared<ConceptNetConcept>(startTerm, startSenseLabel, startID), std::make_shared<ConceptNetConcept>(endTerm, endSenseLabel, endID), relation, weight); } void ConceptNetCall::mapAntonyms(QNetworkReply *reply) { //not current adjective and not already in QString data = reply->readAll(); //remove html part std::string fullData = data.toStdString(); auto start = fullData.find("{\"@context\":"); auto end = fullData.find("</script>"); fullData = fullData.substr(start, end - start); // parse json auto jsonString = QString(fullData.c_str()).toUtf8(); QJsonDocument jsonDoc(QJsonDocument::fromJson(jsonString)); QJsonArray edges = jsonDoc.object()["edges"].toArray(); for (int i = 0; i < edges.size(); i++) { QJsonObject edge = edges[i].toObject(); double weight = edge["weight"].toDouble(); if (weight < this->gui->modelSettingsDialog->getMinCn5Weight()) { break; } //end of edge QJsonObject end = edge["end"].toObject(); QString endLanguage = end["language"].toString(); // skip non English if (endLanguage != "en") { continue; } QString endTerm = end["term"].toString(); endTerm = trimTerm(endTerm); if (endTerm.at(0).isDigit() || this->conceptContainsUTF8(endTerm)) { // std::cout << "ConceptNetCall: Skipping Antonym:" << endTerm.toStdString() << std::endl; continue; } //start of edge QJsonObject start = edge["start"].toObject(); QString startLanguage = start["language"].toString(); // skip non English if (startLanguage != "en") { continue; } QString startTerm = start["term"].toString(); startTerm = trimTerm(startTerm); if (startTerm.at(0).isDigit() || this->conceptContainsUTF8(startTerm)) { // std::cout << "ConceptNetCall: Skipping Antonym:" << startTerm.toStdString() << std::endl; continue; } if (endTerm != currentAdjective) { auto tmp = this->adjectiveAntonymMap.at(currentAdjective); if (std::find(tmp.begin(), tmp.end(), endTerm) == tmp.end()) { this->adjectiveAntonymMap.at(currentAdjective).push_back(endTerm); } } if (startTerm != currentAdjective) { auto tmp = this->adjectiveAntonymMap.at(currentAdjective); if (std::find(tmp.begin(), tmp.end(), startTerm) == tmp.end()) { this->adjectiveAntonymMap.at(currentAdjective).push_back(startTerm); } } } if (this->adjectiveAntonymMap.at(currentAdjective).size() == 0) { this->adjectiveAntonymMap.erase(currentAdjective); } emit closeCollectLoop(); } void ConceptNetCall::collectAntonyms() { for (auto adjective : this->connectedConcepts) { this->adjectiveAntonymMap.emplace(adjective.first, std::vector<QString>()); this->currentAdjective = adjective.first; QUrl url(KnowledgebaseCreator::CONCEPTNET_BASE_URL + KnowledgebaseCreator::CONCEPTNET_URL_QUERYNODE + adjective.first + "&rel=/r/Antonym" + "&limit=1000"); QEventLoop loop; this->connect(this, SIGNAL(closeCollectLoop()), &loop, SLOT(quit())); this->callUrl(url, this->collectAntonymConceptsNAM); loop.exec(); } this->collectAntonymConceptsNAM->deleteLater(); // for (auto pair : this->adjectiveAntonymMap) // { // std::cout << "Adjective: " << pair.first.toStdString() << std::endl; // std::cout << "\t Antonyms: "; // for (auto antonym : pair.second) // { // std::cout << antonym.toStdString() << " "; // } // std::cout << std::endl; // } } } /* namespace kbcr */
45.483431
129
0.560708
[ "object", "vector" ]
ae39362b36593532a193ce1bb1b016bef720c8bc
3,802
cpp
C++
libraries/Dynamic/Dynamic.cpp
TeamMMF/Projekt
5efa4361f71cd9b0755cad92a91de10601100ced
[ "MIT" ]
null
null
null
libraries/Dynamic/Dynamic.cpp
TeamMMF/Projekt
5efa4361f71cd9b0755cad92a91de10601100ced
[ "MIT" ]
null
null
null
libraries/Dynamic/Dynamic.cpp
TeamMMF/Projekt
5efa4361f71cd9b0755cad92a91de10601100ced
[ "MIT" ]
null
null
null
// // Created by matep on 03/12/2017. // #include "Dynamic.h" #include "Common.hpp" #include <iostream> #include <iomanip> #include <cstring> #include <algorithm> using namespace std; // Binary search (note boundaries in the caller) int cell_index(std::vector<int> &v, int l, int r, int key) { while (r - l > 1) { int m = l + (r - l) / 2; if (v[m] >= key) r = m; else l = m; } return r; } /** * Finds the longest increasing subsequence in a vector of integers. * @param v A reference to a vector of integers. * @return The number of elements in the longest increasing subsequence. */ int lis(const std::vector<int> &v) { int v_size = v.size(); if (v_size == 0) return 0; std::vector<int> tail(v_size, 0); int length = 1; // always points empty slot in tail tail[0] = v[0]; for (size_t i = 1; i < v_size; i++) { if (v[i] < tail[0]) // new smallest value tail[0] = v[i]; else if (v[i] > tail[length - 1]) // v[i] extends largest subsequence tail[length++] = v[i]; else // v[i] will become end candidate of an existing subsequence or // Throw away larger elements in all LIS, to make room for upcoming grater elements than v[i] // (and also, v[i] would have already appeared in one of LIS, identify the location and replace it) tail[cell_index(tail, -1, length - 1, v[i])] = v[i]; } return length; } /** * Finds all overlaps of a given query sequence based on the longest increasing subsequence algorithm and a specified threshold. * @param query_id The id of the query sequence. * @param minimizers The query sequence's minimizers. * @param lookup_map A map providing all minimizers (collected from all seqeunces) for a given hash. * @param lis_threshold The LIS threshold which must be satisfied in order to classify two sequences as overlaps * @param occurrences A map mapping a minimizer hash to its number of occurences (in all sequences) * @return All overlaps of a given query seqeunce, denoted by the IDs of the found overlapping sequences as well as a boolean specifying the strand (true for same strand, false for different) */ vector<pair<int, bool>> find_overlaps_by_LIS(int query_id, vector<minim> &minimizers, unordered_map<uint64_t, vector<hashMinPair3>> &lookup_map, int lis_threshold, unordered_map<uint64_t, uint32_t> &occurrences) { unordered_map<uint64_t, vector<int>> same_strand; unordered_map<uint64_t, vector<int>> different_strand; for (auto min : minimizers) { if (occurrences[min.hash] > IGNORE_THRESHOLD) continue; auto matches = lookup_map.find(min.hash); if (matches == lookup_map.end()) continue; for (auto match : matches->second) { if (match.seq_id > query_id) { continue; } int final = abs(match.index); if (match.index * min.index < 0) { different_strand[match.seq_id].push_back(-final); } else { same_strand[match.seq_id].push_back(final); } } } vector<pair<int, bool>> overlaps; for (auto &entry : same_strand) { if (lis(entry.second) >= lis_threshold) { overlaps.emplace_back(entry.first, true); } } for (auto &entry : different_strand) { if (lis(entry.second) >= lis_threshold) { overlaps.emplace_back(make_pair(entry.first, false)); } } return overlaps; };
33.946429
191
0.589164
[ "vector" ]
ae3f5be9861e208d559aebb5bd8f282e33cb7cb6
6,119
cpp
C++
Libraries/OsgAnimatSim/OsgPrismaticLimit.cpp
NeuroRoboticTech/AnimatLabPublicSource
c5b23f8898513582afb7891eb994a7bd40a89f08
[ "BSD-3-Clause" ]
8
2015-01-09T21:59:50.000Z
2021-04-14T14:08:47.000Z
Libraries/OsgAnimatSim/OsgPrismaticLimit.cpp
NeuroRoboticTech/AnimatLabPublicSource
c5b23f8898513582afb7891eb994a7bd40a89f08
[ "BSD-3-Clause" ]
null
null
null
Libraries/OsgAnimatSim/OsgPrismaticLimit.cpp
NeuroRoboticTech/AnimatLabPublicSource
c5b23f8898513582afb7891eb994a7bd40a89f08
[ "BSD-3-Clause" ]
2
2018-12-21T02:58:30.000Z
2020-08-12T11:44:39.000Z
#include "StdAfx.h" #include "OsgMovableItem.h" #include "OsgBody.h" #include "OsgRigidBody.h" #include "OsgJoint.h" #include "OsgPrismaticLimit.h" #include "OsgStructure.h" #include "OsgUserData.h" #include "OsgUserDataVisitor.h" #include "OsgDragger.h" namespace OsgAnimatSim { namespace Environment { namespace Joints { OsgPrismaticLimit::OsgPrismaticLimit() { } OsgPrismaticLimit::~OsgPrismaticLimit() { } void OsgPrismaticLimit::LimitAlpha(float fltA) { if(m_osgBoxMat.valid() && m_osgBoxSS.valid()) { m_osgBoxMat->setAlpha(osg::Material::FRONT_AND_BACK, fltA); if(fltA < 1) m_osgBoxSS->setRenderingHint(osg::StateSet::TRANSPARENT_BIN); else m_osgBoxSS->setRenderingHint(osg::StateSet::OPAQUE_BIN); } if(m_osgCylinderMat.valid() && m_osgCylinderSS.valid()) { m_osgCylinderMat->setAlpha(osg::Material::FRONT_AND_BACK, fltA); if(fltA < 1) m_osgCylinderSS->setRenderingHint(osg::StateSet::TRANSPARENT_BIN); else m_osgCylinderSS->setRenderingHint(osg::StateSet::OPAQUE_BIN); } } osg::Geometry *OsgPrismaticLimit::BoxGeometry() {return m_osgBox.get();} osg::MatrixTransform *OsgPrismaticLimit::BoxMT() {return m_osgBoxMT.get();} osg::Material *OsgPrismaticLimit::BoxMat() {return m_osgBoxMat.get();} osg::StateSet *OsgPrismaticLimit::BoxSS() {return m_osgBoxSS.get();} osg::Geometry *OsgPrismaticLimit::CylinderGeometry() {return m_osgCylinder.get();} osg::MatrixTransform *OsgPrismaticLimit::CylinderMT() {return m_osgCylinderMT.get();} osg::Material *OsgPrismaticLimit::CylinderMat() {return m_osgCylinderMat.get();} osg::StateSet *OsgPrismaticLimit::CylinderSS() {return m_osgCylinderSS.get();} void OsgPrismaticLimit::SetLimitPos(float fltRadius) { CStdFPoint vPos(0, 0, 0), vRot(0, 0, 0); float fltLimitPos = m_lpThisLimit->LimitPos(); //Reset the position of the Box. if(m_osgBoxMT.valid()) { vPos.Set(0, 0, -fltLimitPos); vRot.Set(0, 0, 0); m_osgBoxMT->setMatrix(SetupMatrix(vPos, vRot)); } //Reset the position and size of the Cylinder. if(m_osgCylinderMT.valid() && m_osgCylinder.valid() && m_osgCylinderGeode.valid()) { //First delete the cylinder geometry that currently exists. if(m_osgCylinderGeode->containsDrawable(m_osgCylinder.get())) m_osgCylinderGeode->removeDrawable(m_osgCylinder.get()); m_osgCylinder.release(); //Now recreate the cylinder using the new limit position. m_osgCylinder = CreateConeGeometry(fabs(fltLimitPos), fltRadius, fltRadius, 10, true, true, true); m_osgCylinderGeode->addDrawable(m_osgCylinder.get()); vPos.Set(0, 0, (-fltLimitPos/2)); vRot.Set(osg::PI/2, 0, 0); m_osgCylinderMT->setMatrix(SetupMatrix(vPos, vRot)); } } void OsgPrismaticLimit::DeleteLimitGraphics() { m_osgBox.release(); m_osgBoxMT.release(); m_osgBoxMat.release(); m_osgBoxSS.release(); m_osgCylinder.release(); m_osgCylinderGeode.release(); m_osgCylinderMT.release(); m_osgCylinderMat.release(); m_osgCylinderSS.release(); } void OsgPrismaticLimit::SetupLimitGraphics(float fltBoxSize, float fltRadius) { float fltLimitPos = m_lpThisLimit->LimitPos(); CStdColor *vColor = m_lpThisLimit->Color(); //Create the LIMIT Box m_osgBox = CreateBoxGeometry(fltBoxSize, fltBoxSize, fltBoxSize, fltBoxSize, fltBoxSize, fltBoxSize); osg::ref_ptr<osg::Geode> osgBox = new osg::Geode; osgBox->addDrawable(m_osgBox.get()); CStdFPoint vPos(0, 0, 0), vRot(0, 0, 0); //Translate box vPos.Set(0, 0, -fltLimitPos); vRot.Set(0, 0, 0); m_osgBoxMT = new osg::MatrixTransform(); m_osgBoxMT->setMatrix(SetupMatrix(vPos, vRot)); m_osgBoxMT->addChild(osgBox.get()); //create a material to use with the pos Box if(!m_osgBoxMat.valid()) m_osgBoxMat = new osg::Material(); //create a stateset for this node m_osgBoxSS = m_osgBoxMT->getOrCreateStateSet(); //set the diffuse property of this node to the color of this body m_osgBoxMat->setAmbient(osg::Material::FRONT_AND_BACK, osg::Vec4(0.1, 0.1, 0.1, 1)); m_osgBoxMat->setDiffuse(osg::Material::FRONT_AND_BACK, osg::Vec4(vColor->r(), vColor->g(), vColor->b(), vColor->a())); m_osgBoxMat->setSpecular(osg::Material::FRONT_AND_BACK, osg::Vec4(0.25, 0.25, 0.25, 1)); m_osgBoxMat->setShininess(osg::Material::FRONT_AND_BACK, 64); m_osgBoxSS->setMode(GL_BLEND, osg::StateAttribute::OVERRIDE | osg::StateAttribute::ON); //apply the material m_osgBoxSS->setAttribute(m_osgBoxMat.get(), osg::StateAttribute::ON); //Create the cylinder for the Prismatic //If this is the limit for showing the position then we should not create a cylinder. We only do that for the // upper and lower limits. if(!m_lpThisLimit->IsShowPosition()) { m_osgCylinder = CreateConeGeometry(fabs(fltLimitPos), fltRadius, fltRadius, 10, true, true, true); m_osgCylinderGeode = new osg::Geode; m_osgCylinderGeode->addDrawable(m_osgCylinder.get()); CStdFPoint vPos(0, 0, (-fltLimitPos/2)), vRot(osg::PI/2, 0, 0); m_osgCylinderMT = new osg::MatrixTransform(); m_osgCylinderMT->setMatrix(SetupMatrix(vPos, vRot)); m_osgCylinderMT->addChild(m_osgCylinderGeode.get()); //create a material to use with the pos flap if(!m_osgCylinderMat.valid()) m_osgCylinderMat = new osg::Material(); //create a stateset for this node m_osgCylinderSS = m_osgCylinderMT->getOrCreateStateSet(); //set the diffuse property of this node to the color of this body m_osgCylinderMat->setAmbient(osg::Material::FRONT_AND_BACK, osg::Vec4(0.1, 0.1, 0.1, 1)); m_osgCylinderMat->setDiffuse(osg::Material::FRONT_AND_BACK, osg::Vec4(vColor->r(), vColor->g(), vColor->b(), vColor->a())); //m_osgCylinderMat->setDiffuse(osg::Material::FRONT_AND_BACK, osg::Vec4(1, 0.25, 1, 1)); m_osgCylinderMat->setSpecular(osg::Material::FRONT_AND_BACK, osg::Vec4(0.25, 0.25, 0.25, 1)); m_osgCylinderMat->setShininess(osg::Material::FRONT_AND_BACK, 64); m_osgCylinderSS->setMode(GL_BLEND, osg::StateAttribute::OVERRIDE | osg::StateAttribute::ON); //apply the material m_osgCylinderSS->setAttribute(m_osgCylinderMat.get(), osg::StateAttribute::ON); } } } // Joints } // Environment } //OsgAnimatSim
33.075676
125
0.730021
[ "geometry" ]
ae4187dfe01f68a9781460c9348d68b9210cdd0d
1,172
cpp
C++
libRay/Camera.cpp
RA-Kooi/Ray-Tracer
8a4f133c1a7cc479f9f33819eb200d5a3ffa48d0
[ "MIT" ]
3
2019-03-22T02:15:18.000Z
2019-11-12T08:12:57.000Z
libRay/Camera.cpp
RA-Kooi/Ray-Tracer
8a4f133c1a7cc479f9f33819eb200d5a3ffa48d0
[ "MIT" ]
null
null
null
libRay/Camera.cpp
RA-Kooi/Ray-Tracer
8a4f133c1a7cc479f9f33819eb200d5a3ffa48d0
[ "MIT" ]
null
null
null
#include "Camera.hpp" #include <cmath> namespace LibRay { using namespace Math; Camera::Frustum::Frustum( float fovY, float aspectRatio, float nearPlaneHeight, float nearPlaneDistance, float farPlaneHeight, float farPlaneDistance) : fovY(fovY) , aspectRatio(aspectRatio) , nearPlaneHeight(nearPlaneHeight) , nearPlaneDistance(nearPlaneDistance) , farPlaneHeight(farPlaneHeight) , farPlaneDistance(farPlaneDistance) { } Camera::Camera( class Transform const &transform, Vector2st const &screenSize, float fovY, float near, float far) : transform(transform) , screenSize(screenSize) , fovY(fovY) , nearPlane(near) , farPlane(far) { this->transform.RecalculateMatrix(); } Camera::Frustum Camera::SceneFrustum() const { float const near = std::tan(fovY * 0.5f) * 2.f; float const nearPlaneHeight = near * nearPlane; float const farPlaneHeight = near * farPlane; return Frustum( fovY, float(screenSize.x) / float(screenSize.y), nearPlaneHeight, nearPlane, farPlaneHeight, farPlane); } Vector2st const &Camera::ScreenSize() const { return screenSize; } Transform const &Camera::Transform() const { return transform; } } // namespace LibRay
18.030769
48
0.751706
[ "transform" ]
ae4a196bff9726f040ef6565bc58323d4198ecf1
15,091
cpp
C++
sedml/SedChange.cpp
gmarupilla/libSEDML
3a2a207d78afccefb4389b65fea9eeb7e446d09e
[ "BSD-2-Clause" ]
1
2020-10-21T01:41:14.000Z
2020-10-21T01:41:14.000Z
sedml/SedChange.cpp
gmarupilla/libSEDML
3a2a207d78afccefb4389b65fea9eeb7e446d09e
[ "BSD-2-Clause" ]
null
null
null
sedml/SedChange.cpp
gmarupilla/libSEDML
3a2a207d78afccefb4389b65fea9eeb7e446d09e
[ "BSD-2-Clause" ]
null
null
null
/** * @file: SedChange.cpp * @brief: Implementation of the SedChange class * @author: Frank T. Bergmann * * <!-------------------------------------------------------------------------- * This file is part of libSEDML. Please visit http://sed-ml.org for more * information about SED-ML. The latest version of libSEDML can be found on * github: https://github.com/fbergmann/libSEDML/ * * Copyright (c) 2013-2016, Frank T. Bergmann * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ------------------------------------------------------------------------ --> */ #include <sedml/SedChange.h> #include <sedml/SedTypes.h> #include <sbml/xml/XMLInputStream.h> using namespace std; LIBSEDML_CPP_NAMESPACE_BEGIN /* * Creates a new SedChange with the given level, version, and package version. */ SedChange::SedChange(unsigned int level, unsigned int version) : SedBase(level, version) , mTarget("") { // set an SedNamespaces derived object of this package setSedNamespacesAndOwn(new SedNamespaces(level, version)); } /* * Creates a new SedChange with the given SedNamespaces object. */ SedChange::SedChange(SedNamespaces* sedns) : SedBase(sedns) , mTarget("") { // set the element namespace of this object setElementNamespace(sedns->getURI()); } /* * Copy constructor for SedChange. */ SedChange::SedChange(const SedChange& orig) : SedBase(orig) { mTarget = orig.mTarget; } /* * Assignment for SedChange. */ SedChange& SedChange::operator=(const SedChange& rhs) { if (&rhs != this) { SedBase::operator=(rhs); mTarget = rhs.mTarget; } return *this; } /* * Clone for SedChange. */ SedChange* SedChange::clone() const { return new SedChange(*this); } /* * Destructor for SedChange. */ SedChange::~SedChange() { } /* * Returns the value of the "target" attribute of this SedChange. */ const std::string& SedChange::getTarget() const { return mTarget; } /* * Returns true/false if target is set. */ bool SedChange::isSetTarget() const { return (mTarget.empty() == false); } /* * Sets target and returns value indicating success. */ int SedChange::setTarget(const std::string& target) { { mTarget = target; return LIBSEDML_OPERATION_SUCCESS; } } /* * Unsets target and returns value indicating success. */ int SedChange::unsetTarget() { mTarget.erase(); if (mTarget.empty() == true) { return LIBSEDML_OPERATION_SUCCESS; } else { return LIBSEDML_OPERATION_FAILED; } } /* * Returns the XML element name of this object */ const std::string& SedChange::getElementName() const { static const string name = "change"; return name; } /* * Returns the libSEDML type code for this SEDML object. */ int SedChange::getTypeCode() const { return SEDML_CHANGE; } /* * check if all the required attributes are set */ bool SedChange::hasRequiredAttributes() const { bool allPresent = true; if (isSetTarget() == false) allPresent = false; return allPresent; } /** @cond doxygen-libsedml-internal */ /* * write contained elements */ void SedChange::writeElements(XMLOutputStream& stream) const { SedBase::writeElements(stream); } /** @endcond doxygen-libsedml-internal */ /** @cond doxygen-libsedml-internal */ /* * Accepts the given SedVisitor. */ bool SedChange::accept(SedVisitor& v) const { return false; } /** @endcond doxygen-libsedml-internal */ /** @cond doxygen-libsedml-internal */ /* * Sets the parent SedDocument. */ void SedChange::setSedDocument(SedDocument* d) { SedBase::setSedDocument(d); } /** @endcond doxygen-libsedml-internal */ /** @cond doxygen-libsedml-internal */ /* * Get the list of expected attributes for this element. */ void SedChange::addExpectedAttributes(ExpectedAttributes& attributes) { SedBase::addExpectedAttributes(attributes); attributes.add("target"); } /** @endcond doxygen-libsedml-internal */ /** @cond doxygen-libsedml-internal */ /* * Read values from the given XMLAttributes set into their specific fields. */ void SedChange::readAttributes(const XMLAttributes& attributes, const ExpectedAttributes& expectedAttributes) { SedBase::readAttributes(attributes, expectedAttributes); bool assigned = false; // // target string ( use = "required" ) // assigned = attributes.readInto("target", mTarget, getErrorLog(), true); if (assigned == true) { // check string is not empty if (mTarget.empty() == true) { logEmptyString(mTarget, getLevel(), getVersion(), "<SedChange>"); } } } /** @endcond doxygen-libsedml-internal */ /** @cond doxygen-libsedml-internal */ /* * Write values of XMLAttributes to the output stream. */ void SedChange::writeAttributes(XMLOutputStream& stream) const { SedBase::writeAttributes(stream); if (isSetTarget() == true) stream.writeAttribute("target", getPrefix(), mTarget); } /** @endcond doxygen-libsedml-internal */ /* * Constructor */ SedListOfChanges::SedListOfChanges(unsigned int level, unsigned int version) : SedListOf(level, version) { setSedNamespacesAndOwn(new SedNamespaces(level, version)); } /* * Constructor */ SedListOfChanges::SedListOfChanges(SedNamespaces* sedns) : SedListOf(sedns) { setElementNamespace(sedns->getURI()); } /* * Returns a deep copy of this SedListOfChanges */ SedListOfChanges* SedListOfChanges::clone() const { return new SedListOfChanges(*this); } /* * Get a Change from the SedListOfChanges by index. */ SedChange* SedListOfChanges::get(unsigned int n) { return static_cast<SedChange*>(SedListOf::get(n)); } /* * Get a Change from the SedListOfChanges by index. */ const SedChange* SedListOfChanges::get(unsigned int n) const { return static_cast<const SedChange*>(SedListOf::get(n)); } /* * Get a Change from the SedListOfChanges by id. */ SedChange* SedListOfChanges::get(const std::string& sid) { return const_cast<SedChange*>( static_cast<const SedListOfChanges&>(*this).get(sid)); } /* * Get a Change from the SedListOfChanges by id. */ const SedChange* SedListOfChanges::get(const std::string& sid) const { vector<SedBase*>::const_iterator result; result = find_if(mItems.begin(), mItems.end(), SedIdEq<SedChange>(sid)); return (result == mItems.end()) ? 0 : static_cast <SedChange*>(*result); } /** * Adds a copy the given "SedChange" to this SedListOfChanges. * * @param sc; the SedChange object to add * * @return integer value indicating success/failure of the * function. @if clike The value is drawn from the * enumeration #OperationReturnValues_t. @endif The possible values * returned by this function are: * @li LIBSEDML_OPERATION_SUCCESS * @li LIBSEDML_INVALID_ATTRIBUTE_VALUE */ int SedListOfChanges::addChange(const SedChange* sc) { if (sc == NULL) return LIBSEDML_INVALID_ATTRIBUTE_VALUE; append(sc); return LIBSEDML_OPERATION_SUCCESS; } /** * Get the number of SedChange objects in this SedListOfChanges. * * @return the number of SedChange objects in this SedListOfChanges */ unsigned int SedListOfChanges::getNumChanges() const { return size(); } /** * Creates a new SedAddXML object, adds it to this SedListOfChanges * addXML and returns the SedAddXML object created. * * @return a new SedAddXML object instance * * @see addAddXML(const SedChange* sc) */ SedAddXML* SedListOfChanges::createAddXML() { SedAddXML *temp = new SedAddXML(); if (temp != NULL) appendAndOwn(temp); return temp; } /** * Creates a new SedChangeXML object, adds it to this SedListOfChanges * changeXML and returns the SedChangeXML object created. * * @return a new SedChangeXML object instance * * @see addChangeXML(const SedChange* sc) */ SedChangeXML* SedListOfChanges::createChangeXML() { SedChangeXML *temp = new SedChangeXML(); if (temp != NULL) appendAndOwn(temp); return temp; } /** * Creates a new SedRemoveXML object, adds it to this SedListOfChanges * removeXML and returns the SedRemoveXML object created. * * @return a new SedRemoveXML object instance * * @see addRemoveXML(const SedChange* sc) */ SedRemoveXML* SedListOfChanges::createRemoveXML() { SedRemoveXML *temp = new SedRemoveXML(); if (temp != NULL) appendAndOwn(temp); return temp; } /** * Creates a new SedChangeAttribute object, adds it to this SedListOfChanges * changeAttribute and returns the SedChangeAttribute object created. * * @return a new SedChangeAttribute object instance * * @see addChangeAttribute(const SedChange* sc) */ SedChangeAttribute* SedListOfChanges::createChangeAttribute() { SedChangeAttribute *temp = new SedChangeAttribute(); if (temp != NULL) appendAndOwn(temp); return temp; } /** * Creates a new SedComputeChange object, adds it to this SedListOfChanges * computeChange and returns the SedComputeChange object created. * * @return a new SedComputeChange object instance * * @see addComputeChange(const SedChange* sc) */ SedComputeChange* SedListOfChanges::createComputeChange() { SedComputeChange *temp = new SedComputeChange(); if (temp != NULL) appendAndOwn(temp); return temp; } /* * Removes the nth Change from this SedListOfChanges */ SedChange* SedListOfChanges::remove(unsigned int n) { return static_cast<SedChange*>(SedListOf::remove(n)); } /* * Removes the Change from this SedListOfChanges with the given identifier */ SedChange* SedListOfChanges::remove(const std::string& sid) { SedBase* item = NULL; vector<SedBase*>::iterator result; result = find_if(mItems.begin(), mItems.end(), SedIdEq<SedChange>(sid)); if (result != mItems.end()) { item = *result; mItems.erase(result); } return static_cast <SedChange*>(item); } /* * Returns the XML element name of this object */ const std::string& SedListOfChanges::getElementName() const { static const string name = "listOfChanges"; return name; } /* * Returns the libSEDML type code for this SEDML object. */ int SedListOfChanges::getTypeCode() const { return SEDML_LIST_OF; } /* * Returns the libSEDML type code for the objects in this LIST_OF. */ int SedListOfChanges::getItemTypeCode() const { return SEDML_CHANGE; } /** @cond doxygen-libsedml-internal */ /* * Creates a new SedChange in this SedListOfChanges */ SedBase* SedListOfChanges::createObject(XMLInputStream& stream) { const std::string& name = stream.peek().getName(); SedBase* object = NULL; if (name == "addXML") { object = new SedAddXML(getSedNamespaces()); appendAndOwn(object); } if (name == "changeXML") { object = new SedChangeXML(getSedNamespaces()); appendAndOwn(object); } if (name == "removeXML") { object = new SedRemoveXML(getSedNamespaces()); appendAndOwn(object); } if (name == "changeAttribute") { object = new SedChangeAttribute(getSedNamespaces()); appendAndOwn(object); } if (name == "computeChange") { object = new SedComputeChange(getSedNamespaces()); appendAndOwn(object); } return object; } /** @endcond doxygen-libsedml-internal */ /** @cond doxygen-libsedml-internal */ /* * Write the namespace for the Sed package. */ void SedListOfChanges::writeXMLNS(XMLOutputStream& stream) const { XMLNamespaces xmlns; std::string prefix = getPrefix(); if (prefix.empty()) { if (getNamespaces() != NULL && !getNamespaces()->hasURI(SEDML_XMLNS_L1) && !getNamespaces()->hasURI(SEDML_XMLNS_L1V2) && !getNamespaces()->hasURI(SEDML_XMLNS_L1V3)) { if (getVersion() == 2) xmlns.add(SEDML_XMLNS_L1V2, prefix); else if (getVersion() == 3) xmlns.add(SEDML_XMLNS_L1V3, prefix); else xmlns.add(SEDML_XMLNS_L1V2, prefix); } } stream << xmlns; } /** @endcond doxygen-libsedml-internal */ /** * write comments */ LIBSEDML_EXTERN SedChange_t * SedChange_create(unsigned int level, unsigned int version) { return new SedChange(level, version); } /** * write comments */ LIBSEDML_EXTERN void SedChange_free(SedChange_t * sc) { if (sc != NULL) delete sc; } /** * write comments */ LIBSEDML_EXTERN SedChange_t * SedChange_clone(SedChange_t * sc) { if (sc != NULL) { return static_cast<SedChange_t*>(sc->clone()); } else { return NULL; } } /** * write comments */ LIBSEDML_EXTERN char * SedChange_getTarget(SedChange_t * sc) { if (sc == NULL) return NULL; return sc->getTarget().empty() ? NULL : safe_strdup(sc->getTarget().c_str()); } /** * write comments */ LIBSEDML_EXTERN int SedChange_isSetTarget(SedChange_t * sc) { return (sc != NULL) ? static_cast<int>(sc->isSetTarget()) : 0; } /** * write comments */ LIBSEDML_EXTERN int SedChange_setTarget(SedChange_t * sc, const char * target) { return (sc != NULL) ? sc->setTarget(target) : LIBSEDML_INVALID_OBJECT; } /** * write comments */ LIBSEDML_EXTERN int SedChange_unsetTarget(SedChange_t * sc) { return (sc != NULL) ? sc->unsetTarget() : LIBSEDML_INVALID_OBJECT; } /** * write comments */ LIBSEDML_EXTERN int SedChange_hasRequiredAttributes(SedChange_t * sc) { return (sc != NULL) ? static_cast<int>(sc->hasRequiredAttributes()) : 0; } /** * write comments */ LIBSEDML_EXTERN SedChange_t * SedListOfChanges_getById(SedListOf_t * lo, const char * sid) { if (lo == NULL) return NULL; return (sid != NULL) ? static_cast <SedListOfChanges *>(lo)->get(sid) : NULL; } /** * write comments */ LIBSEDML_EXTERN SedChange_t * SedListOfChanges_removeById(SedListOf_t * lo, const char * sid) { if (lo == NULL) return NULL; return (sid != NULL) ? static_cast <SedListOfChanges *>(lo)->remove(sid) : NULL; } LIBSEDML_CPP_NAMESPACE_END
19.078382
170
0.689086
[ "object", "vector" ]
ae5609e8c68461fbf3ea3411c8dbc543382f8ee1
369
cpp
C++
visual_studio/visual_studio/oxi/scene/object/mock_ground.cpp
collus-corn/oxi
93e00c51c00f78cb3d09aa9c890e98c1a572af3a
[ "MIT" ]
null
null
null
visual_studio/visual_studio/oxi/scene/object/mock_ground.cpp
collus-corn/oxi
93e00c51c00f78cb3d09aa9c890e98c1a572af3a
[ "MIT" ]
null
null
null
visual_studio/visual_studio/oxi/scene/object/mock_ground.cpp
collus-corn/oxi
93e00c51c00f78cb3d09aa9c890e98c1a572af3a
[ "MIT" ]
null
null
null
#include "mock_ground.hpp" #include "Dxlib.h" #include "../i_position.hpp" #include "object_kind.hpp" #include "image_resources.hpp" oxi::scene::object::MockGround::MockGround(std::shared_ptr<oxi::scene::IPosition> position) :position_(position), kind_(oxi::scene::object::ObjectKind::ground) { image_ = LoadGraph(oxi::scene::object::ImageResources::mock_ground); }
30.75
91
0.753388
[ "object" ]
ae76b4e8360afbc965209ea326b0591f8abd9cd6
2,806
cpp
C++
Quadtree/main.cpp
kgomathi2910/Quad-Trees
70059b66a93a9491f435c99d2cd811e0e0df3337
[ "MIT" ]
null
null
null
Quadtree/main.cpp
kgomathi2910/Quad-Trees
70059b66a93a9491f435c99d2cd811e0e0df3337
[ "MIT" ]
null
null
null
Quadtree/main.cpp
kgomathi2910/Quad-Trees
70059b66a93a9491f435c99d2cd811e0e0df3337
[ "MIT" ]
null
null
null
#include<iostream> #include <SFML/Graphics.hpp> #include"Point.h" #include"Quadtree.h" using namespace std; using namespace sf; //For SFML functions #define SCREEN_WIDTH 600 #define SCREEN_HEIGHT 600 #define MAXIMUM_CAPACITY 4 int main() { RenderWindow window(sf::VideoMode(SCREEN_WIDTH, SCREEN_HEIGHT), "Collision via Quad Trees"); //renderwindow class for 2D drawing - (Videomode, Windowname) //VideoMode class for VideoMode(width, height, bitsperpixel) QuadTree my_screen(Rectangle(SCREEN_WIDTH/2, SCREEN_HEIGHT/2, SCREEN_WIDTH/2, SCREEN_HEIGHT/2), MAXIMUM_CAPACITY, 0); //Rectangle initially has screen size - x = 300, y = 300, half sizes = 300, capacity = 2, level = 0 Point *PC; //point clicked vector<Point*> points; //A vector of points CircleShape shape; //represents a circle shape.setRadius(3); //radius of the circle shape.setOrigin(3, 3); //sets the origin location of the circle Rectangle area(200, 200, 100, 100); while(window.isOpen()) { Event E;//describes a system event - like mouse click while(window.pollEvent(E)) //get the recent event to process it, fails when no pending event - retrieve { if(E.type == Event::Closed) //type - public attribute of event - type enum, Closed - integral constant { window.close(); } else if(E.type == Event::MouseButtonPressed && E.mouseButton.button == Mouse::Left)//union datatype { //if user clicks a point on screen - store it PC = new Point(Mouse::getPosition(window).x, Mouse::getPosition(window).y); points.push_back(PC); my_screen.insert(PC);//insert into quad tree //my_screen.dothis(); - for debug } else if(E.type == Event::MouseMoved)//if mouse is moved { if(Mouse::isButtonPressed(Mouse::Right)) { area.x = Mouse::getPosition(window).x; area.y = Mouse::getPosition(window).y; } } } for(size_t i = 0; i < points.size(); ++i) { points[i]->lights_up = false; //all points are initially not highlighted } my_screen.query(area); //get all points found in the region window.clear(); //display points for(Point *P : points) //iterates over begin and end iterators on points vector - P = *it { shape.setPosition(P->x, P->y);//position of the obj shape.setFillColor(P->lights_up?Color::Green:Color::White);//fill color of the shape window.draw(shape); } my_screen.Draw(window); area.Draw(window); window.display(); } }
39.521127
121
0.597648
[ "shape", "vector" ]
ae8440323c86eeb8de455a8a0b28771d4bdf9877
8,187
cpp
C++
src/main.cpp
Technica-Corporation/Speech_Recognition-Maixduino
37dcc532fd6c855b92273f8713c3006116de39cc
[ "Apache-2.0" ]
15
2019-07-10T09:07:53.000Z
2022-02-08T18:41:06.000Z
src/main.cpp
Technica-Corporation/Speech_Recognition-Maixduino
37dcc532fd6c855b92273f8713c3006116de39cc
[ "Apache-2.0" ]
1
2021-04-26T17:57:21.000Z
2021-04-26T17:57:21.000Z
src/main.cpp
Technica-Corporation/Speech_Recognition-Maixduino
37dcc532fd6c855b92273f8713c3006116de39cc
[ "Apache-2.0" ]
6
2019-07-10T09:07:54.000Z
2021-09-14T22:48:24.000Z
#include <Arduino.h> #include <Sipeed_ST7789.h> /* I added input parameters to Maix_Speech_Recognition.h's begin(int pin0, int pin1, int, pin2) This allows you to specify the pins to use as I was trying to get the one dock's built-in mic to work Additionally, the default data0 pin in the code did not work for me with the mic array */ #include "Maix_Speech_Recognition_demo.h" #include "model_wake.h" #include "model_primaryc.h" #include "model_secondaryc.h" #include "model_invalidc.h" #include "mic_array.h" #define LABEL_TEXT_SIZE 2 // This is labeled as a red squiggle for some reason; it still compiles though... SPIClass spi_(SPI0); // MUST be SPI0 for Maix series on board LCD Sipeed_ST7789 lcd(320, 240, spi_, SIPEED_ST7789_DCX_PIN, SIPEED_ST7789_RST_PIN, DMAC_CHANNEL2); SpeechRecognizer rec; void printCenterOnLCD(Sipeed_ST7789 &lcd_, const char *msg, uint8_t textSize = LABEL_TEXT_SIZE) { lcd_.setCursor((lcd_.width() - (6 * textSize * strlen(msg))) / 2, (lcd_.height() - (8*textSize)) / 2); lcd_.print(msg); } void setup() { lcd.setTextSize(LABEL_TEXT_SIZE); lcd.setTextColor(COLOR_WHITE); /* Turn off/down Mic array lights If you just plug in the array and go, they lights blink very fast and are VERY bright */ lights_out(0, 3, 4, MIC_LED_DAT, SPI0_CS1); /* Pin inputs for Mic: rec.begin(I2S0_IN_D0, I2S0_SCLK, I2S0_WS) Mic Array data input pins: d0=23, d1=22, d2=20 d0 doesn't seem to work for me d2 kind of works, but not well for me d1 I have not tested Built-in mic pin inputs: rec.begin(31, 30, 32); I could not get the built-in mic to work with Maixduino It did work with just the standalone-sdk though */ rec.begin(23, 18, 19); delay(1000); Serial.begin(115200); if (!lcd.begin(15000000, COLOR_BLACK)) { Serial.println(""); while(1); } Serial.println("Initializing..."); printCenterOnLCD(lcd, "Initializing..."); // *Moving the mic array across a desk* rec.addVoiceModel(0, 0, move_0, fram_num_move_0); rec.addVoiceModel(0, 1, move_1, fram_num_move_1); rec.addVoiceModel(0, 2, move_2, fram_num_move_2); rec.addVoiceModel(0, 3, move_3, fram_num_move_3); // *clearing my throat* rec.addVoiceModel(1, 0, clearthroat_0, fram_num_clearthroat_0); rec.addVoiceModel(1, 1, clearthroat_1, fram_num_clearthroat_1); rec.addVoiceModel(1, 2, clearthroat_2, fram_num_clearthroat_2); rec.addVoiceModel(1, 3, clearthroat_3, fram_num_clearthroat_3); // *clap* and *clap clap* rec.addVoiceModel(2, 0, clap_0, fram_num_clap_0); rec.addVoiceModel(2, 1, clap_1, fram_num_clap_1); rec.addVoiceModel(2, 2, clap_2, fram_num_clap_2); rec.addVoiceModel(2, 3, clap_3, fram_num_clap_3); // "red" and "red on" rec.addVoiceModel(3, 0, red_0, fram_num_red_0); rec.addVoiceModel(3, 1, red_1, fram_num_red_1); rec.addVoiceModel(3, 2, red_2, fram_num_red_2); rec.addVoiceModel(3, 3, red_3, fram_num_red_3); // "green" and "green on" rec.addVoiceModel(4, 0, green_0, fram_num_green_0); rec.addVoiceModel(4, 1, green_1, fram_num_green_1); rec.addVoiceModel(4, 2, green_2, fram_num_green_2); rec.addVoiceModel(4, 3, green_3, fram_num_green_3); // "blue" and "blue on" rec.addVoiceModel(5, 0, blue_0, fram_num_blue_0); rec.addVoiceModel(5, 1, blue_1, fram_num_blue_1); rec.addVoiceModel(5, 2, blue_2, fram_num_blue_2); rec.addVoiceModel(5, 3, blue_3, fram_num_blue_3); // "cyan" and "cyan on" rec.addVoiceModel(6, 0, cyan_0, fram_num_cyan_0); rec.addVoiceModel(6, 1, cyan_1, fram_num_cyan_1); rec.addVoiceModel(6, 2, cyan_2, fram_num_cyan_2); rec.addVoiceModel(6, 3, cyan_3, fram_num_cyan_3); // "magenta" and "magenta on" rec.addVoiceModel(7, 0, magenta_0, fram_num_magenta_0); rec.addVoiceModel(7, 1, magenta_1, fram_num_magenta_1); rec.addVoiceModel(7, 2, magenta_2, fram_num_magenta_2); rec.addVoiceModel(7, 3, magenta_3, fram_num_magenta_3); // "yellow" and "yellow on" rec.addVoiceModel(8, 0, yellow_0, fram_num_yellow_0); rec.addVoiceModel(8, 1, yellow_1, fram_num_yellow_1); rec.addVoiceModel(8, 2, yellow_2, fram_num_yellow_2); rec.addVoiceModel(8, 3, yellow_3, fram_num_yellow_3); Serial.println("Model init OK!"); lcd.fillScreen(COLOR_BLACK); printCenterOnLCD(lcd, "Initialization complete!"); delay(1000); } int ON = 0; void loop() { int res; if (ON == 0){ lcd.fillScreen(COLOR_BLACK); printCenterOnLCD(lcd, "Waiting for Wake Up..."); res = rec.recognize(); lcd.fillScreen(COLOR_BLACK); Serial.printf("Result: %d --> ", res); if (res > 0){ switch (res) { case 1: printCenterOnLCD(lcd, "NOT AWAKE: MOVE"); break; case 2: printCenterOnLCD(lcd, "NOT AWAKE: Clear Throat"); break; case 3: printCenterOnLCD(lcd, "AWAKE!"); ON = 1; break; default: printCenterOnLCD(lcd, "Not a Wake Up!"); break; } } else { printCenterOnLCD(lcd, "Not a Wake Up!"); } delay(1000); // short delay here } if (ON == 1){ lcd.fillScreen(COLOR_BLACK); lcd.setTextColor(COLOR_WHITE); printCenterOnLCD(lcd, "Color Command..."); res = rec.recognize(); Serial.printf("Result: %d --> ", res); if (res > 0){ switch (res) { case 1: lcd.setTextColor(COLOR_WHITE); lcd.fillScreen(COLOR_BLACK); printCenterOnLCD(lcd, "MOVE"); break; case 2: lcd.setTextColor(COLOR_WHITE); lcd.fillScreen(COLOR_BLACK); printCenterOnLCD(lcd, "CLEAR THROAT"); break; case 3: lcd.setTextColor(COLOR_WHITE); lcd.fillScreen(COLOR_BLACK); printCenterOnLCD(lcd, "Going back to sleep..."); ON = 0; break; case 4: lcd.setTextColor(COLOR_BLACK); lcd.fillScreen(COLOR_RED); printCenterOnLCD(lcd, "RED"); break; case 5: lcd.setTextColor(COLOR_BLACK); lcd.fillScreen(COLOR_GREEN); printCenterOnLCD(lcd, "GREEN"); break; case 6: lcd.setTextColor(COLOR_BLACK); lcd.fillScreen(COLOR_BLUE); printCenterOnLCD(lcd, "BLUE"); break; case 7: lcd.setTextColor(COLOR_BLACK); lcd.fillScreen(COLOR_CYAN); printCenterOnLCD(lcd, "CYAN"); break; case 8: lcd.setTextColor(COLOR_BLACK); lcd.fillScreen(COLOR_MAGENTA); printCenterOnLCD(lcd, "MAGENTA"); break; case 9: lcd.setTextColor(COLOR_BLACK); lcd.fillScreen(COLOR_YELLOW); printCenterOnLCD(lcd, "YELLOW"); break; default: lcd.setTextColor(COLOR_BLACK); lcd.fillScreen(COLOR_LIGHTGREY); printCenterOnLCD(lcd, "INVALID COMMAND"); break; } } else { lcd.setTextColor(COLOR_BLACK); lcd.fillScreen(COLOR_LIGHTGREY); printCenterOnLCD(lcd, "INVALID COMMAND"); } delay(3000); // longer delay to display color longer } }
36.066079
107
0.567485
[ "model" ]
ae8e3fecfd0273a9c7000e4d1167099913fde0ea
1,789
hpp
C++
util/std.hpp
kindone/cppproptest
db3cace33af7914d6d2b65945baa5554da281725
[ "MIT" ]
1
2021-06-19T05:40:33.000Z
2021-06-19T05:40:33.000Z
util/std.hpp
kindone/cppproptest
db3cace33af7914d6d2b65945baa5554da281725
[ "MIT" ]
null
null
null
util/std.hpp
kindone/cppproptest
db3cace33af7914d6d2b65945baa5554da281725
[ "MIT" ]
null
null
null
#pragma once #include <list> #include <vector> #include <set> #include <map> #include <tuple> #include <type_traits> #include <initializer_list> #include <functional> #include <utility> #include <memory> #include <string> #include <iostream> #include <iomanip> #include <sstream> #include <exception> #include <stdexcept> #include <algorithm> #include <random> #include <limits> #include <chrono> namespace proptest { using std::vector; using std::list; using std::set; using std::map; using std::pair; using std::tuple; using std::tuple_size; using std::tuple_element; using std::tuple_element_t; using std::index_sequence; using std::initializer_list; using std::remove_reference; using std::remove_reference_t; using std::is_trivial; using std::declval; namespace util { using std::forward; using std::move; using std::make_pair; using std::make_tuple; using std::make_shared; using std::make_unique; using std::transform; using std::back_inserter; } using std::make_index_sequence; using std::get; using std::is_lvalue_reference; using std::is_pointer; using std::is_same; using std::decay_t; using std::result_of; using std::enable_if; using std::enable_if_t; using std::unique_ptr; using std::shared_ptr; using std::static_pointer_cast; using std::to_string; using std::numeric_limits; using std::function; using std::string; using std::ostream; using std::stringstream; using std::cerr; using std::cout; using std::endl; using std::ios; using std::setw; using std::setfill; using std::hex; using std::exception; using std::logic_error; using std::runtime_error; using std::invalid_argument; using std::error_code; using std::uniform_int_distribution; using std::boolalpha; using std::mt19937_64; using std::true_type; using std::false_type; } // namespace proptest
17.712871
36
0.761319
[ "vector", "transform" ]
ae8f57bb8eef8d4971e0bf6fed94a3f6ee5e1379
2,383
cpp
C++
examples/tigre/WaveFrontReader.cpp
amecky/diesel
23647464f3587fb60a5f504f7103da72f2cda3f6
[ "MIT" ]
1
2017-09-28T19:39:57.000Z
2017-09-28T19:39:57.000Z
examples/tigre/WaveFrontReader.cpp
amecky/diesel
23647464f3587fb60a5f504f7103da72f2cda3f6
[ "MIT" ]
null
null
null
examples/tigre/WaveFrontReader.cpp
amecky/diesel
23647464f3587fb60a5f504f7103da72f2cda3f6
[ "MIT" ]
null
null
null
#include "WaveFrontReader.h" #include <fstream> #include <vector> int WaveFrontReader::load(const char * fileName, const WaveFrontFormat& format, ds::vec3* positions, ds::vec2* uvs, ds::vec3* normals, ds::Color* colors,int max) { std::ifstream file(fileName); if (!file) { return -1; } char cmd[256] = { 0 }; std::vector<ds::vec3> vertices; std::vector<ds::vec2> textures; std::vector<ds::vec3> ns; ds::Color current = ds::Color(1.0f, 1.0f, 1.0f, 1.0f); int cnt = 0; for (;; ) { file >> cmd; if (!file) { break; } if (*cmd == '#') { } else if (strcmp(cmd, "v") == 0) { float x, y, z; file >> x >> y >> z; ds::vec3 v(x, y, z); vertices.push_back(v); } else if (strcmp(cmd, "vt") == 0) { float u,v; file >> u >> v; ds::vec2 uv(u, v); textures.push_back(uv); } else if (strcmp(cmd, "vn") == 0) { float x, y, z; file >> x >> y >> z; ds::vec3 v(x, y, z); ns.push_back(v); } else if (strcmp(cmd, "mtllib") == 0) { char name[128]; file >> name; readMaterials(name); } else if (strcmp(cmd, "usemtl") == 0) { char name[128]; file >> name; ds::StaticHash s(name); current = _colors[s]; } else if (strcmp(cmd, "f") == 0) { int nr = 3; if (format.topology == WFT_QUAD) { nr = 4; } for (int i = 0; i < nr; ++i) { int v, t, n; file >> v; file.ignore(); if ((format.formats & 1) == 1) { file >> t; } file.ignore(); if ((format.formats & 2) == 2) { file >> n; } if (cnt < max) { positions[cnt] = vertices[v - 1]; if ((format.formats & 1) == 1 && uvs != 0) { uvs[cnt] = textures[t - 1]; } if ((format.formats & 2) == 2 && normals != 0) { normals[cnt] = ns[n - 1]; } if (colors != 0) { colors[cnt] = current; } ++cnt; } } } } return cnt; } void WaveFrontReader::readMaterials(const char* fileName) { std::ifstream file(fileName); ds::StaticHash s; if (file) { char cmd[256] = { 0 }; int cnt = 0; for (;; ) { file >> cmd; if (!file) { break; } if (strcmp(cmd, "newmtl") == 0) { char name[64]; file >> name; s = ds::StaticHash(name); } else if (strcmp(cmd, "Kd") == 0) { float r, g, b; file >> r; file >> g; file >> b; ds::Color clr = ds::Color(r, g, b, 1.0f); _colors[s] = clr; } } } }
20.543103
163
0.49979
[ "vector" ]
ae9149ab5c2ee7d66811da21bc841ef1e9c56e60
1,946
cpp
C++
CacheFile.cpp
LaszloAshin/oneKpaq
93aaebfd7933a385f4f95d173ee7e03232c9a453
[ "BSD-2-Clause" ]
29
2018-01-05T22:14:27.000Z
2022-02-17T21:51:44.000Z
CacheFile.cpp
LaszloAshin/oneKpaq
93aaebfd7933a385f4f95d173ee7e03232c9a453
[ "BSD-2-Clause" ]
1
2021-03-21T15:03:38.000Z
2021-03-21T15:03:38.000Z
CacheFile.cpp
LaszloAshin/oneKpaq
93aaebfd7933a385f4f95d173ee7e03232c9a453
[ "BSD-2-Clause" ]
8
2018-08-16T04:32:12.000Z
2022-02-24T14:31:41.000Z
/* Copyright (C) Teemu Suutari */ #include "onekpaq_common.h" #include "CacheFile.hpp" void CacheFile::clear(uint numBlocks) { _numBlocks=numBlocks; _combine.clear(); _header.clear(); } bool CacheFile::readFile(const std::string &fileName) { bool ret=false; std::ifstream file(fileName.c_str(),std::ios::in|std::ios::binary); if (file.is_open()) { _shift=readUint(file); _numBlocks=readUint(file); uint numCombinedBlocks=readUint(file); _combine.clear(); _header.clear(); for (uint i=0;file&&i<numCombinedBlocks;i++) { _combine.push_back(readUint(file)); _header.push_back(readVector(file)); } ret=bool(file); file.close(); } return ret; } bool CacheFile::writeFile(const std::string &fileName) { bool ret=false; std::ofstream file(fileName.c_str(),std::ios::out|std::ios::binary|std::ios::trunc); if (file.is_open()) { writeUint(file,_shift); writeUint(file,_numBlocks); writeUint(file,uint(_header.size())); for (uint i=0;file&&i<_header.size();i++) { writeUint(file,_combine[i]); writeVector(file,_header[i]); } ret=bool(file); file.close(); } return ret; } uint CacheFile::readUint(std::ifstream &stream) { if (!stream) return 0; // x86 only u32 ret=0; stream.read(reinterpret_cast<char*>(&ret),sizeof(ret)); return ret; } std::vector<u8> CacheFile::readVector(std::ifstream &stream) { std::vector<u8> ret; uint length=readUint(stream); if (stream&&length) { ret.resize(length); stream.read(reinterpret_cast<char*>(ret.data()),length); } return ret; } void CacheFile::writeUint(std::ofstream &stream,uint value) { if (!stream) return; // x86 only u32 tmp=value; stream.write(reinterpret_cast<const char*>(&tmp),sizeof(tmp)); } void CacheFile::writeVector(std::ofstream &stream,const std::vector<u8> &vector) { writeUint(stream,uint(vector.size())); if (stream&&vector.size()) stream.write(reinterpret_cast<const char*>(vector.data()),vector.size()); }
22.367816
101
0.693217
[ "vector" ]
ae979dce54f0a7fa250f0a65216c88ffb7b17aba
655
cpp
C++
101/vectors/vector_find_first_item.cpp
hariharanragothaman/Learning-STL
7e5f58083212d04b93159d44e1812069171aa349
[ "MIT" ]
2
2021-04-21T07:59:45.000Z
2021-05-13T05:53:00.000Z
101/vectors/vector_find_first_item.cpp
hariharanragothaman/Learning-STL
7e5f58083212d04b93159d44e1812069171aa349
[ "MIT" ]
null
null
null
101/vectors/vector_find_first_item.cpp
hariharanragothaman/Learning-STL
7e5f58083212d04b93159d44e1812069171aa349
[ "MIT" ]
1
2021-04-17T15:32:18.000Z
2021-04-17T15:32:18.000Z
#include "../../headers.h" int main() { vector<int> temp {5, 3, 7, 9, 4}; // First item that satisfies the condition auto lambda = [](int i) {return i > 7;}; vector<int>::iterator it = find_if(temp.begin(), temp.end(), lambda); int first_element_satisfying_condition = *it; cout << "The result is:" << first_element_satisfying_condition << endl; // First item that doesn't satisfy the condition vector<int>::iterator it2 = find_if_not(temp.begin(), temp.end() ,lambda); int first_element_not_satisfying_condition = *it2; cout << "The value is:" << first_element_not_satisfying_condition << endl; return 0; }
34.473684
78
0.662595
[ "vector" ]
aea4a0043d7486d9494120b9872e180dc51e1696
8,529
cpp
C++
multiview/multiview_cpp/src/perceive/cost-functions/disparity/strategies/triclops_disp.cpp
prcvlabs/multiview
1a03e14855292967ffb0c0ec7fff855c5abbc9d2
[ "Apache-2.0" ]
5
2021-09-03T23:12:08.000Z
2022-03-04T21:43:32.000Z
multiview/multiview_cpp/src/perceive/cost-functions/disparity/strategies/triclops_disp.cpp
prcvlabs/multiview
1a03e14855292967ffb0c0ec7fff855c5abbc9d2
[ "Apache-2.0" ]
3
2021-09-08T02:57:46.000Z
2022-02-26T05:33:02.000Z
multiview/multiview_cpp/src/perceive/cost-functions/disparity/strategies/triclops_disp.cpp
prcvlabs/multiview
1a03e14855292967ffb0c0ec7fff855c5abbc9d2
[ "Apache-2.0" ]
2
2021-09-26T03:14:40.000Z
2022-01-26T06:42:52.000Z
#include "triclops_disp.hpp" #include "perceive/foundation.hpp" #include "perceive/utils/cuda-spec.hpp" #include "perceive/utils/threads.hpp" #include "perceive/utils/tick-tock.hpp" // -------------------------------------------------------------------- TRICLOPS #ifdef USE_TRICLOPS #include <unistd.h> #include "perceive/contrib/triclops/triclops-bumblebee2-config-string.hpp" #include <fc2triclops.h> #include <triclops.h> // aliases namespaces namespace FC2 = FlyCapture2; namespace FC2T = Fc2Triclops; inline void tricheck(TriclopsError err, const std::string& msg) { if(err != TriclopsErrorOk) { LOG_ERR(perceive::format("Triclops err code {}: {}", err, msg)); throw std::runtime_error(msg); } } #endif #define This TriclopsDisparity namespace perceive::disparity { constexpr float max_disparity = 150.0f; // ------------------------------------------------------------------- meta-data // const vector<MemberMetaData>& This::Params::meta_data() const noexcept { #define ThisParams This::Params auto make_meta = []() { vector<MemberMetaData> m; m.push_back(MAKE_META(ThisParams, BOOL, rectify, true)); m.push_back(MAKE_META(ThisParams, BOOL, lowpass, true)); m.push_back(MAKE_META(ThisParams, BOOL, subpixel, true)); m.push_back(MAKE_META(ThisParams, BOOL, subpixel_validation, true)); m.push_back(MAKE_META(ThisParams, BOOL, edge_correlation, true)); m.push_back(MAKE_META(ThisParams, INT, min_disp, true)); m.push_back(MAKE_META(ThisParams, INT, max_disp, true)); m.push_back(MAKE_META(ThisParams, INT, edge_mask, true)); m.push_back(MAKE_META(ThisParams, INT, stereo_mask, true)); m.push_back(MAKE_META(ThisParams, BOOL, texture_validation, true)); m.push_back(MAKE_META(ThisParams, BOOL, surface_validation, true)); m.push_back(MAKE_META(ThisParams, INT, surface_validation_size, true)); return m; }; static vector<MemberMetaData> meta_ = make_meta(); return meta_; #undef ThisParams } // ------------------------------------------------------------------- calculate // void This::calculate(const Params& p, const bool l_is_ref_image, const cv::Mat& image0, const cv::Mat& image1, cv::Mat& out_left) noexcept // A float matrix { auto is_grey = [&](const cv::Mat& im) { return im.type() == CV_8U || im.type() == CV_8UC1; }; if(image0.empty() or image1.empty()) FATAL(format("attempt to calculate disparity on empty image")); if(!is_grey(image0) or !is_grey(image1)) { LOG_ERR(format("expected a pair of grey images")); return; // outta here! } cv::Mat out_right; struct TLParams { bool first{true}; Params last_p; #ifdef USE_TRICLOPS TriclopsContext triclops; TriclopsInput triclops_input; TriclopsError err; TriclopsImage im_disparity; TriclopsImage16 im_disp16; #endif }; static thread_local TLParams tl; if(tl.first) { #ifdef USE_TRICLOPS tl.first = false; // Write triclops file string filename = format("/tmp/.bumblebee2.{}.{}.config", rand(), rand()); FILE* fp = fopen(filename.c_str(), "w"); if(fp == NULL) FATAL(format("Could not open '{}' for writing", filename)); fprintf(fp, "%s\n", triclops_bumblebee2_config_string().c_str()); fclose(fp); // Init triclops context char* buffer = (char*) alloca(filename.size() + 1); strcpy(buffer, filename.c_str()); tricheck(triclopsGetDefaultContextFromFile(&(tl.triclops), buffer), "Read triclops configuration file"); // Remove temporary file unlink(filename.c_str()); #endif } const auto w = image0.cols; const auto h = image0.rows; auto ensure_dimensions = [w, h](cv::Mat& m, const int type) { if(m.rows != h || m.cols != w || m.type() != type) m = cv::Mat(h, w, type); }; ensure_dimensions(out_left, CV_32FC1); #ifdef USE_TRICLOPS auto stereo_triclops_calculate = [&]() { tricheck(triclopsSetResolutionAndPrepare(tl.triclops, h, w, h, w), "Set resolution"); tricheck(triclopsSetRectify(tl.triclops, p.rectify), "Set rectify"); tricheck(triclopsSetLowpass(tl.triclops, p.lowpass), "Set lowpass"); tricheck(triclopsSetSubpixelInterpolation(tl.triclops, p.subpixel), "Set sub-pixel"); tricheck(triclopsSetStrictSubpixelValidation(tl.triclops, p.subpixel_validation), "Set strict sub-pixel validation"); tricheck(triclopsSetEdgeCorrelation(tl.triclops, p.edge_correlation), "Set edge-correlation"); tricheck(triclopsSetDisparity(tl.triclops, p.min_disp, p.max_disp), "Set disparity"); tricheck(triclopsSetEdgeMask(tl.triclops, p.edge_mask), "Set edge-mask"); tricheck(triclopsSetStereoMask(tl.triclops, p.stereo_mask), "Set stereo-mask"); tricheck(triclopsSetTextureValidation(tl.triclops, p.texture_validation), "Set texture-validation"); tricheck(triclopsSetSurfaceValidation(tl.triclops, p.surface_validation), "Set surface-validation"); tricheck(triclopsSetSurfaceValidationSize(tl.triclops, p.surface_validation_size), "Set surface-validation-size"); tricheck(triclopsSetDisparityMappingOn(tl.triclops, false), "Set disparity-mapping on"); // Setup triclops input... unsigned long seconds = 0; unsigned long micro_seconds = 0; auto ptr0 = (unsigned char*) image0.ptr<unsigned char>(0); auto ptr1 = (unsigned char*) image1.ptr<unsigned char>(0); tricheck(triclopsBuildRGBTriclopsInput(w, h, w, seconds, micro_seconds, ptr1, ptr0, ptr0, &tl.triclops_input), "triclopsBuildRGBTriclopsInput()"); // Preprocess and Stereo tricheck(triclopsPreprocess(tl.triclops, &tl.triclops_input), "Preprocess images"); // Generate disparity information tricheck(triclopsStereo(tl.triclops), "Stereo processing"); TriclopsBool on; tricheck(triclopsGetSubpixelInterpolation(tl.triclops, &on), "Get subpixel interpolation"); const bool is_subpixel = on; if(is_subpixel) { tricheck(triclopsGetImage16(tl.triclops, TriImg16_DISPARITY, TriCam_REFERENCE, &tl.im_disp16), "Get disparity 16"); // -- Write results to float image for(int y = 0; y < h; ++y) { const uint16_t* src_ptr = tl.im_disp16.data + y * w; float* dst_ptr = (float*) out_left.ptr(y); for(int x = 0; x < w; ++x) { auto val = float(*src_ptr++) / 256.0f; *dst_ptr++ = val > max_disparity ? 0.0f : val; } } } else { // Load disparity image directly tricheck(triclopsGetImage(tl.triclops, TriImg_DISPARITY, TriCam_REFERENCE, &tl.im_disparity), "Load disparity image"); // Set up floating-point disparity information for(int y = 0; y < h; ++y) { const uint8_t* src_ptr = tl.im_disparity.data + y * w; float* dst_ptr = (float*) out_left.ptr(y); for(int x = 0; x < w; ++x) { auto val = float(*src_ptr++); *dst_ptr++ = val > max_disparity ? 0.0f : val; } } } }; #else auto stereo_triclops_calculate = [&]() { LOG_ERR("Not compiled in"); }; #endif try { stereo_triclops_calculate(); } catch(std::exception& e) { LOG_ERR(format("Exception: {}", e.what())); return; } catch(...) { LOG_ERR("Unknown exception executing stereo-bm"); return; } } } // namespace perceive::disparity
35.836134
80
0.566889
[ "vector" ]
001464f3da8b3b7044c813c8d5e5609e89816fd7
6,990
hxx
C++
ARCHIVE/BRAINSSurfaceTools/BRAINSSurfaceCommon/itkResampleQuadEdgeMeshFilter.hxx
pnlbwh/BRAINSTools
a2fe63ab5b795f03da140a4081d1fef6314dab95
[ "Apache-2.0" ]
null
null
null
ARCHIVE/BRAINSSurfaceTools/BRAINSSurfaceCommon/itkResampleQuadEdgeMeshFilter.hxx
pnlbwh/BRAINSTools
a2fe63ab5b795f03da140a4081d1fef6314dab95
[ "Apache-2.0" ]
null
null
null
ARCHIVE/BRAINSSurfaceTools/BRAINSSurfaceCommon/itkResampleQuadEdgeMeshFilter.hxx
pnlbwh/BRAINSTools
a2fe63ab5b795f03da140a4081d1fef6314dab95
[ "Apache-2.0" ]
1
2022-02-08T05:39:46.000Z
2022-02-08T05:39:46.000Z
/*========================================================================= * * Copyright SINAPSE: Scalable Informatics for Neuroscience, Processing and Software Engineering * The University of Iowa * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef __itkResampleQuadEdgeMeshFilter_hxx #define __itkResampleQuadEdgeMeshFilter_hxx #include "itkResampleQuadEdgeMeshFilter.h" #include "itkProgressReporter.h" #include "itkVersor.h" #include "itkNumericTraitsVectorPixel.h" namespace itk { template <typename TInputMesh, typename TOutputMesh> ResampleQuadEdgeMeshFilter<TInputMesh, TOutputMesh>::ResampleQuadEdgeMeshFilter() {} template <typename TInputMesh, typename TOutputMesh> ResampleQuadEdgeMeshFilter<TInputMesh, TOutputMesh>::~ResampleQuadEdgeMeshFilter() {} template <typename TInputMesh, typename TOutputMesh> void ResampleQuadEdgeMeshFilter<TInputMesh, TOutputMesh>::SetReferenceMesh(const TOutputMesh * mesh) { itkDebugMacro("setting input ReferenceMesh to " << mesh); if (mesh != static_cast<const TOutputMesh *>(this->ProcessObject::GetInput(1))) { this->ProcessObject::SetNthInput(1, const_cast<TOutputMesh *>(mesh)); this->Modified(); } } template <typename TInputMesh, typename TOutputMesh> const typename ResampleQuadEdgeMeshFilter<TInputMesh, TOutputMesh>::OutputMeshType * ResampleQuadEdgeMeshFilter<TInputMesh, TOutputMesh>::GetReferenceMesh() const { Self * surrogate = const_cast<Self *>(this); const OutputMeshType * referenceMesh = static_cast<const OutputMeshType *>(surrogate->ProcessObject::GetInput(1)); return referenceMesh; } template <typename TInputMesh, typename TOutputMesh> void ResampleQuadEdgeMeshFilter<TInputMesh, TOutputMesh>::GenerateData() { // Copy the input mesh into the output mesh. this->CopyReferenceMeshToOutputMesh(); OutputMeshPointer outputMesh = this->GetOutput(); // // Visit all nodes of the Mesh // OutputPointsContainerPointer points = outputMesh->GetPoints(); if (points.IsNull()) { itkExceptionMacro("Mesh has NULL Points"); } const unsigned int numberOfPoints = outputMesh->GetNumberOfPoints(); ProgressReporter progress(this, 0, numberOfPoints); OutputPointDataContainerPointer pointData = outputMesh->GetPointData(); if (pointData.IsNull()) { pointData = OutputPointDataContainer::New(); outputMesh->SetPointData(pointData); } pointData->Reserve(numberOfPoints); // Initialize the internal point locator structure this->m_Interpolator->SetInputMesh(this->GetInput()); this->m_Interpolator->Initialize(); using PointIterator = typename OutputMeshType::PointsContainer::ConstIterator; using PointDataIterator = typename OutputMeshType::PointDataContainer::Iterator; PointIterator pointItr = points->Begin(); PointIterator pointEnd = points->End(); PointDataIterator pointDataItr = pointData->Begin(); PointDataIterator pointDataEnd = pointData->End(); using MappedPointType = typename TransformType::OutputPointType; OutputPointType inputPoint; OutputPointType pointToEvaluate; while (pointItr != pointEnd && pointDataItr != pointDataEnd) { inputPoint.CastFrom(pointItr.Value()); MappedPointType transformedPoint = this->m_Transform->TransformPoint(inputPoint); pointToEvaluate.CastFrom(transformedPoint); pointDataItr.Value() = this->m_Interpolator->Evaluate(pointToEvaluate); progress.CompletedPixel(); ++pointItr; ++pointDataItr; } } // --------------------------------------------------------------------- template <typename TInputMesh, typename TOutputMesh> void ResampleQuadEdgeMeshFilter<TInputMesh, TOutputMesh>::CopyReferenceMeshToOutputMesh() { this->CopyReferenceMeshToOutputMeshGeometry(); this->CopyReferenceMeshToOutputMeshFieldData(); } // --------------------------------------------------------------------- template <typename TInputMesh, typename TOutputMesh> void ResampleQuadEdgeMeshFilter<TInputMesh, TOutputMesh>::CopyReferenceMeshToOutputMeshGeometry() { this->CopyReferenceMeshToOutputMeshPoints(); this->CopyReferenceMeshToOutputMeshEdgeCells(); this->CopyReferenceMeshToOutputMeshCells(); } // --------------------------------------------------------------------- template <typename TInputMesh, typename TOutputMesh> void ResampleQuadEdgeMeshFilter<TInputMesh, TOutputMesh>::CopyReferenceMeshToOutputMeshFieldData() { this->CopyReferenceMeshToOutputMeshPointData(); this->CopyReferenceMeshToOutputMeshCellData(); } // --------------------------------------------------------------------- template <typename TInputMesh, typename TOutputMesh> void ResampleQuadEdgeMeshFilter<TInputMesh, TOutputMesh>::CopyReferenceMeshToOutputMeshPoints() { const OutputMeshType * in = this->GetReferenceMesh(); OutputMeshType * out = this->GetOutput(); CopyMeshToMeshPoints(in, out); } // --------------------------------------------------------------------- template <typename TInputMesh, typename TOutputMesh> void ResampleQuadEdgeMeshFilter<TInputMesh, TOutputMesh>::CopyReferenceMeshToOutputMeshEdgeCells() { const OutputMeshType * in = this->GetReferenceMesh(); OutputMeshType * out = this->GetOutput(); CopyMeshToMeshEdgeCells(in, out); } // --------------------------------------------------------------------- template <typename TInputMesh, typename TOutputMesh> void ResampleQuadEdgeMeshFilter<TInputMesh, TOutputMesh>::CopyReferenceMeshToOutputMeshCells() { const OutputMeshType * in = this->GetReferenceMesh(); OutputMeshType * out = this->GetOutput(); CopyMeshToMeshCells(in, out); } // --------------------------------------------------------------------- template <typename TInputMesh, typename TOutputMesh> void ResampleQuadEdgeMeshFilter<TInputMesh, TOutputMesh>::CopyReferenceMeshToOutputMeshPointData() { const OutputMeshType * in = this->GetReferenceMesh(); OutputMeshType * out = this->GetOutput(); CopyMeshToMeshPointData(in, out); } // --------------------------------------------------------------------- template <typename TInputMesh, typename TOutputMesh> void ResampleQuadEdgeMeshFilter<TInputMesh, TOutputMesh>::CopyReferenceMeshToOutputMeshCellData() { const OutputMeshType * in = this->GetReferenceMesh(); OutputMeshType * out = this->GetOutput(); CopyMeshToMeshCellData(in, out); } } // end namespace itk #endif
33.127962
116
0.693562
[ "mesh" ]
001df20690d70c30269175fe819c03aa010e5838
16,227
cc
C++
tests/test_interpreter.cc
unlink2/lasm
3cacf44c218854f402ce022b9e223f5671125dbe
[ "MIT" ]
1
2021-01-23T18:25:11.000Z
2021-01-23T18:25:11.000Z
tests/test_interpreter.cc
unlink2/lasm
3cacf44c218854f402ce022b9e223f5671125dbe
[ "MIT" ]
null
null
null
tests/test_interpreter.cc
unlink2/lasm
3cacf44c218854f402ce022b9e223f5671125dbe
[ "MIT" ]
null
null
null
#include "interpreter.h" #include "scanner.h" #include "parser.h" #include "instruction.h" #include "instruction6502.h" #include <memory> #include "macros.h" #include "test_interpreter.h" using namespace lasm; class TestCallback: public InterpreterCallback { public: virtual void onStatementExecuted(LasmObject *object) { this->object = std::make_shared<LasmObject>(LasmObject(object)); } std::shared_ptr<LasmObject> object = std::shared_ptr<LasmObject>(nullptr); }; #define assert_interpreter_success(code, stmtSize, objType, ...) {\ BaseError error;\ InstructionSet6502 is;\ TestCallback callback;\ Scanner scanner(error, is, code, "");\ auto tokens = scanner.scanTokens();\ Parser parser(error, tokens, is);\ auto stmts = parser.parse();\ assert_int_equal(error.getType(), NO_ERROR);\ assert_false(error.didError());\ assert_int_equal(stmts.size(), stmtSize);\ Interpreter interpreter(error, is, &callback);\ assert_false(error.didError());\ interpreter.interprete(stmts);\ assert_int_equal(error.getType(), NO_ERROR);\ assert_false(error.didError());\ assert_non_null(callback.object.get());\ assert_int_equal(callback.object->getType(), objType);\ __VA_ARGS__\ } #define assert_code6502(code, codeSize, address, ...) assert_code6502_a(code, codeSize, address, 0, __VA_ARGS__) #define assert_code6502_a(code, codeSize, address, resultIndex, ...) {\ BaseError error;\ InstructionSet6502 is;\ TestCallback callback;\ Scanner scanner(error, is, code, "");\ auto tokens = scanner.scanTokens();\ Parser parser(error, tokens, is);\ auto stmts = parser.parse();\ assert_int_equal(error.getType(), NO_ERROR);\ assert_false(error.didError());\ Interpreter interpreter(error, is, &callback);\ assert_false(error.didError());\ auto result = interpreter.interprete(stmts);\ assert_false(error.didError());\ assert_int_equal(error.getType(), NO_ERROR);\ assert_int_equal(result[resultIndex].getSize(), codeSize);\ assert_int_equal(result[resultIndex].getAddress(), address);\ char dataArray[] = __VA_ARGS__;\ assert_memory_equal(dataArray, result[resultIndex].getData().get(), codeSize);\ } #define assert_parser_error(code, errorType) {\ BaseError error;\ InstructionSet6502 is;\ TestCallback callback;\ Scanner scanner(error, is, code, "");\ auto tokens = scanner.scanTokens();\ Parser parser(error, tokens, is);\ auto stmts = parser.parse();\ assert_true(error.didError());\ assert_int_equal(error.getType(), errorType);\ } #define assert_interpreter_error(code, stmtSize, errorType) {\ BaseError error;\ InstructionSet6502 is;\ TestCallback callback;\ Scanner scanner(error, is, code, "");\ auto tokens = scanner.scanTokens();\ Parser parser(error, tokens, is);\ auto stmts = parser.parse();\ assert_false(error.didError());\ assert_int_equal(stmts.size(), stmtSize);\ Interpreter interpreter(error, is, &callback);\ assert_false(error.didError());\ interpreter.interprete(stmts);\ assert_true(error.didError());\ assert_int_equal(error.getType(), errorType);\ } void test_interpreter(void **state) { // test interpreter functionality assert_interpreter_success("(2 + 3) * 2;", 1, NUMBER_O, {assert_int_equal((int)callback.object->toNumber(), 10);}); assert_interpreter_success("(2.0 + 3) * 2.1;", 1, REAL_O, {assert_float_equal(callback.object->toReal(), 10.5, 0.001);}); assert_interpreter_success("\"Hello\" + \"World\";", 1, STRING_O, {assert_cc_string_equal(callback.object->toString(), std::string("HelloWorld"));}); assert_interpreter_success("(\"Hello\") == \"Hello\";", 1, BOOLEAN_O, {assert_true(callback.object->toBool());}); assert_interpreter_success("2 <= 3;", 1, BOOLEAN_O, {assert_true(callback.object->toBool());}); assert_interpreter_success("let a = 2; a+1;", 2, NUMBER_O, {assert_int_equal(callback.object->toNumber(), 3);}); assert_interpreter_success("let a = \"Hi\"+\"World\"; a;", 2, STRING_O, {assert_cc_string_equal(callback.object->toString(), std::string("HiWorld"));}); assert_interpreter_success("let a = \"Hi\"+\"World\"; a = 22;", 2, NUMBER_O, {assert_int_equal(callback.object->toNumber(), 22);}); assert_interpreter_success("let a = 1; { let a = 2; } a;", 3, NUMBER_O, {assert_int_equal(callback.object->toNumber(), 1);}); assert_interpreter_success("let a = 1; { a = 22; } a;", 3, NUMBER_O, {assert_int_equal(callback.object->toNumber(), 22);}); assert_interpreter_success("let a = 1; if (a == 1) {a = 2;}", 2, NUMBER_O, {assert_int_equal(callback.object->toNumber(), 2);}); assert_interpreter_success("let a = 1; if (a == 2) {a = 2;} else {a;}", 2, NUMBER_O, {assert_int_equal(callback.object->toNumber(), 1);}); assert_interpreter_success("let a = 1; if (a == 1 || false) {a = 2;} else {a;}", 2, NUMBER_O, {assert_int_equal(callback.object->toNumber(), 2);}); assert_interpreter_success("let a = 1; if (a == 1 && false) {a = 2;} else {a;}", 2, NUMBER_O, {assert_int_equal(callback.object->toNumber(), 1);}); assert_interpreter_success("let a = 10; while (a > 0) a = a -1;", 2, NUMBER_O, {assert_int_equal(callback.object->toNumber(), 0);}); assert_interpreter_success("let a = 10; for (;a > 0; a = a - 1) {} ", 2, NUMBER_O, {assert_int_equal(callback.object->toNumber(), 0);}); assert_interpreter_success("let a = 10; for (;a > 0;) {a = a - 1;} ", 2, NUMBER_O, {assert_int_equal(callback.object->toNumber(), 0);}); assert_interpreter_success("let a; for (a = 0;a > 0;a = a - 1) {} ", 2, NUMBER_O, {assert_int_equal(callback.object->toNumber(), 0);}); assert_interpreter_success("let b = 0; for (let a = 10;a > 0;a = a - 1) {b = b + 1;} b; ", 3, NUMBER_O, {assert_int_equal(callback.object->toNumber(), 10);}); assert_interpreter_success("lo(0xFF81); ", 1, NUMBER_O, {assert_int_equal(callback.object->toNumber(), 0x81);}); assert_interpreter_success("hi(0x81FF); ", 1, NUMBER_O, {assert_int_equal(callback.object->toNumber(), 0x81);}); assert_interpreter_success("fn x() {return 1+1;} x();", 2, NUMBER_O, {assert_int_equal(callback.object->toNumber(), 2);}); assert_interpreter_success("fn x(a, b) { if ((a + b) == 2) { return 2; } else {return 5;}} let a = x(1, 1); a;", 3, NUMBER_O, {assert_int_equal(callback.object->toNumber(), 2);}); assert_interpreter_success("fn x(a, b) { if ((a + b) == 2) { return 2; } else {return 5;}} let a = x(1, 2); a;", 3, NUMBER_O, {assert_int_equal(callback.object->toNumber(), 5);}); assert_interpreter_success("fn x() {} let a = x(); a;", 3, NIL_O, {assert_null(callback.object->toNil());}); assert_interpreter_success("fn x() {return;} let a = x(); a;", 3, NIL_O, {assert_null(callback.object->toNil());}); assert_interpreter_success("0x8283 & 0xFF;", 1, NUMBER_O, {assert_int_equal(callback.object->toNumber(), 0x8283 & 0xFF);}); assert_interpreter_success("0x8283 | 0xFF;", 1, NUMBER_O, {assert_int_equal(callback.object->toNumber(), 0x8283 | 0xFF);}); assert_interpreter_success("0x8283 ^ 0xFF;", 1, NUMBER_O, {assert_int_equal(callback.object->toNumber(), 0x8283 ^ 0xFF);}); assert_interpreter_success("~0x8283;", 1, NUMBER_O, {assert_int_equal(callback.object->toNumber(), ~0x8283);}); assert_interpreter_success("0x8283 >> 2;", 1, NUMBER_O, {assert_int_equal(callback.object->toNumber(), 0x8283 >> 2);}); assert_interpreter_success("0x8283 << 2;", 1, NUMBER_O, {assert_int_equal(callback.object->toNumber(), 0x8283 << 2);}); assert_code6502("adc #0xFF;", 2, 0, {(char)0x69, (char)0xFF}); assert_code6502("org 0x02; align 0x04, 0xFF;", 2, 2, {(char)0xFF, (char)0xFF}); assert_code6502("org 0x02; fill 0x06, 0xFF;", 4, 2, {(char)0xFF, (char)0xFF, (char)0xFF, (char)0xFF}); assert_code6502("db \"Hello\", 2, 3, true;", 6, 0, {'H', 'e', 'l', 'l', 'o', '\0', 0x02, 0x03, 1}); assert_code6502("dw 100, 100;", 4, 0, {0x64, 0, 0, 0, 0x64, 0, 0, 0}); assert_code6502("dh 100;", 2, 0, {0x64, 0}); assert_code6502("dd 100;", 8, 0, {0x64, 0, 0, 0, 0, 0, 0, 0, 0}); assert_code6502_a("bss 100 {test1 1, test2 2, test3 3} adc #test1; adc #test2; adc #test3;", 2, 0, 0, {0x69, 100, 0x69, 100+1, 0x69, 100+3}); assert_code6502_a("bss 100 {test1 1, test2 2, test3 3} adc #test1; adc #test2; adc #test3;", 2, 2, 1, {0x69, 100+1, 0x69, 100+3}); assert_code6502_a("bss 100 {test1 1, test2 2, test3 3} adc #test1; adc #test2; adc #test3;", 2, 4, 2, {0x69, 100+3}); // lists assert_code6502_a("let a = [[2, 3], 1, 2, 3]; let s = \"Hello\"; adc #a[0][1]; adc #a[1]; adc #a[2]; adc #s[1];", 2, 0, 0, {0x69, 3}); assert_code6502_a("let a = [[2, 3], 1, 2, 3]; let s = \"Hello\"; adc #a[0][1]; adc #a[1]; adc #a[2]; adc #s[1];", 2, 2, 1, {0x69, 1}); assert_code6502_a("let a = [[2, 3], 1, 2, 3]; let s = \"Hello\"; adc #a[0][1]; adc #a[1]; adc #a[2]; adc #s[1];", 2, 4, 2, {0x69, 2}); assert_code6502_a("let a = [[2, 3], 1, 2, 3]; let s = \"Hello\"; adc #a[0][1]; adc #a[1]; adc #a[2]; adc #s[1];", 2, 6, 3, {0x69, 'e'}); // list assign assert_code6502_a("let a = [[2, 3], 1, 2, 3]; a[1] = 4; a[0][1] = 100; adc #a[0][1]; adc #a[1]; adc #a[2];", 2, 0, 0, {0x69, 100}); assert_code6502_a("let a = [[2, 3], 1, 2, 3]; a[1] = 4; a[0][1] = 100; adc #a[0][1]; adc #a[1]; adc #a[2];", 2, 2, 1, {0x69, 4}); assert_code6502_a("let a = [[2, 3], 1, 2, 3]; a[1] = 4; a[0][1] = 100; adc #a[0][1]; adc #a[1]; adc #a[2];", 2, 4, 2, {0x69, 2}); // label resolve std::string labelResolveCode = "fn labels() { adc #test_label; test_label: } adc #1; labels(); labels(); global: adc #global;" "for (let i = 0; i < 2; i = i + 1) { adc #label; adc #global; adc #after; label: } after:"; assert_code6502_a(labelResolveCode, 2, 0, 0, {0x69, 0x01}); assert_code6502_a(labelResolveCode, 2, 2, 1, {0x69, 0x04}); assert_code6502_a(labelResolveCode, 2, 4, 2, {0x69, 0x06}); assert_code6502_a(labelResolveCode, 2, 6, 3, {0x69, 0x06}); assert_code6502_a(labelResolveCode, 2, 8, 4, {0x69, 0x0E}); assert_code6502_a(labelResolveCode, 2, 10, 5, {0x69, 0x06}); assert_code6502_a(labelResolveCode, 2, 12, 6, {0x69, 0x14}); assert_code6502_a(labelResolveCode, 2, 14, 7, {0x69, 0x14}); assert_code6502_a(labelResolveCode, 2, 16, 8, {0x69, 0x06}); assert_code6502_a(labelResolveCode, 2, 18, 9, {0x69, 0x14}); // test absolute assert_code6502_a("adc 0x4021;", 3, 0, 0, {0x6D, 0x21, 0x40}); // absolute, x assert_code6502_a("adc 0x4021, x;", 3, 0, 0, {0x7D, 0x21, 0x40}); // absolute, y assert_code6502_a("adc 0x4021, y;", 3, 0, 0, {0x79, 0x21, 0x40}); // zp assert_code6502_a("adc 0x21;", 2, 0, 0, {0x65, 0x21}); // zp, x assert_code6502_a("adc 0x21, x;", 2, 0, 0, {0x75, 0x21}); // zp, y -> does not exists so it will be absolute assert_code6502_a("adc 0x21, y;", 3, 0, 0, {0x79, 0x21, 0x00}); // indirect, x assert_code6502_a("adc (0x21, x);", 2, 0, 0, {0x61, 0x21}); // indirect, y assert_code6502_a("adc (0x21), y;", 2, 0, 0, {0x71, 0x21}); // indirect address assert_code6502_a("jmp (0x2122);", 3, 0, 0, {0x6C, 0x22, 0x21}); assert_code6502_a("jmp 0x2122;", 3, 0, 0, {0x4C, 0x22, 0x21}); // implicit assert_code6502_a("brk;", 1, 0, 0, {0x00}); assert_code6502_a("asl;", 1, 0, 0, {0x0A}); assert_code6502_a("asl a;", 1, 0, 0, {0x0A}); assert_code6502_a("asl 0x100;", 3, 0, 0, {0x0E, 0x00, 0x01}); // branch assert_code6502_a("org 0x8000; beq test; org 0x8010; test:", 2, 0x8000, 0, {char(0xF0), 0x0E}); assert_code6502_a("org 0x7F90; test: org 0x8000; beq test;", 2, 0x8000, 0, {char(0xF0), -114}); } void test_interpreter_errors(void **state) { assert_interpreter_error("\"Hi\" >= 3;", 1, TYPE_ERROR); assert_parser_error("\"Hi\" >= 3", MISSING_SEMICOLON); assert_interpreter_error("2 / 0;", 1, DIVISION_BY_ZERO); assert_interpreter_error("2 % 0;", 1, DIVISION_BY_ZERO); assert_interpreter_error("a + 1;", 1, UNDEFINED_REF); assert_interpreter_error("a=1;", 1, UNDEFINED_REF); assert_parser_error("let a = 1; a+1=2;", BAD_ASSIGNMENT); assert_parser_error("{ let a = 1;", BLOCK_NOT_CLOSED_ERROR); assert_parser_error("if (true { 1; }", EXPECTED_EXPRESSION); assert_parser_error("while (false { 1; }", EXPECTED_EXPRESSION); assert_parser_error("for (;false; { 1; }", EXPECTED_EXPRESSION); assert_parser_error("for () { 1; }", EXPECTED_EXPRESSION); assert_interpreter_error("fn x(a, b) {} let a = x(1);", 2, ARITY_ERROR); assert_interpreter_error("fn x(a, b) {} let a = x(1, 2, 3);", 2, ARITY_ERROR); assert_parser_error("fn x a, b) {} x(1, 2);", MISSING_LEFT_PAREN); assert_parser_error("org", EXPECTED_EXPRESSION); assert_parser_error("align", EXPECTED_EXPRESSION); assert_parser_error("align 0xFF", MISSING_COMMA); assert_parser_error("align 0xFF, ", EXPECTED_EXPRESSION); assert_interpreter_error("align 0xFF, 256;", 1, VALUE_OUT_OF_RANGE); assert_parser_error("fill", EXPECTED_EXPRESSION); assert_parser_error("fill 0xFF", MISSING_COMMA); assert_parser_error("fill 0xFF, ", EXPECTED_EXPRESSION); assert_interpreter_error("fill 0xFF, 256;", 1, VALUE_OUT_OF_RANGE); assert_parser_error("db 0xFF 0xFF;", MISSING_SEMICOLON); assert_parser_error("db;", EXPECTED_EXPRESSION); assert_interpreter_error("db hi;", 1, TYPE_ERROR); assert_parser_error("bss test 100", BLOCK_NOT_OPENED_ERROR); assert_parser_error("bss { test 100}", EXPECTED_EXPRESSION); assert_parser_error("bss 100 { test 100", MISSING_COMMA); assert_parser_error("bss 100 { 100 100}", MISSING_IDENTIFIER); assert_parser_error("bss 100 { 100 100, test 100}", MISSING_IDENTIFIER); assert_interpreter_error("bss 3.1 { test 100}", 1, TYPE_ERROR); assert_interpreter_error("bss 3 { test 3.1}", 1, TYPE_ERROR); // list errors assert_parser_error("let a = [;", EXPECTED_EXPRESSION); assert_parser_error("let a = [1 2];", MISSING_COMMA); assert_interpreter_error("let a = [1, 2, 3]; a[4];", 2, INDEX_OUT_OF_BOUNDS); assert_interpreter_error("let a = \"hi\"; a[4];", 2, INDEX_OUT_OF_BOUNDS); assert_interpreter_error("let a = [1, 2, 3]; a[\"hello\"];", 2, TYPE_ERROR); assert_interpreter_error("let a = 22; a[1];", 2, TYPE_ERROR); assert_interpreter_error("let a = [1, 2, 3]; a[4] = 4;", 2, INDEX_OUT_OF_BOUNDS); assert_interpreter_error("let a = [1, 2, 3]; a[\"hello\"] = 3;", 2, TYPE_ERROR); assert_interpreter_error("let a = 22; a[1] = 1;", 2, TYPE_ERROR); // asm syntax errors assert_interpreter_error("adc 0x4FFF1;", 1, VALUE_OUT_OF_RANGE); assert_parser_error("adc 0x4FFF1, b;", INVALID_INSTRUCTION); assert_interpreter_error("adc (0xFF+1, x);", 1, VALUE_OUT_OF_RANGE); assert_interpreter_error("adc (0xFF+1), y;", 1, VALUE_OUT_OF_RANGE); assert_interpreter_error("adc (0xFF+1), x;", 1, INVALID_INSTRUCTION); assert_interpreter_error("adc (0xFF+1, y);", 1, INVALID_INSTRUCTION); assert_interpreter_error("adc (0xFF+1, a);", 1, INVALID_INSTRUCTION); assert_interpreter_error("adc (0xFF+1,);", 1, INVALID_INSTRUCTION); assert_interpreter_error("adc (0xFF+1),;", 1, INVALID_INSTRUCTION); assert_interpreter_error("adc (0xFF+1), l;", 1, INVALID_INSTRUCTION); // nop does not allow accumulator mode assert_parser_error("nop a;", INVALID_INSTRUCTION); // out of range branch assert_interpreter_error("org 0x7990; test: org 0x8000; beq test;", 4, VALUE_OUT_OF_RANGE); assert_interpreter_error("org 0x8000; beq test; org 0x8990; test:", 4, VALUE_OUT_OF_RANGE); } void test_misc_interpreter(void **state) { InstructionInfo result(nullptr); result.addOpcode(0xF1, "test"); assert_true(result.hasOpcode("test")); assert_false(result.hasOpcode("not_included")); assert_int_equal(result.getOpcode("test"), 0xF1); }
49.172727
162
0.645098
[ "object" ]
001e40a39b8a5eb6be729c4ead9494cfd22b163f
5,981
cpp
C++
test/test_gpusim.cpp
Mariewelt/gpusimilarity
ff4fbf3ef0761d35510b148f07943d2958e6e7a5
[ "BSD-3-Clause" ]
61
2018-09-06T06:48:05.000Z
2022-03-25T15:40:02.000Z
test/test_gpusim.cpp
Mariewelt/gpusimilarity
ff4fbf3ef0761d35510b148f07943d2958e6e7a5
[ "BSD-3-Clause" ]
36
2018-05-22T12:55:31.000Z
2020-10-04T14:05:27.000Z
test/test_gpusim.cpp
Mariewelt/gpusimilarity
ff4fbf3ef0761d35510b148f07943d2958e6e7a5
[ "BSD-3-Clause" ]
18
2018-06-21T17:35:23.000Z
2022-03-28T09:24:52.000Z
#define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE gpusimilarity #include <cstdlib> #include <vector> #include <boost/test/unit_test.hpp> #include "calculation_functors.h" #include "fingerprintdb_cuda.h" #include "gpusim.h" using namespace gpusim; using std::vector; using gpusim::GPUSimServer; bool missing_cuda_skip() { static auto cuda_skip = std::getenv("SKIP_CUDA"); if (cuda_skip != nullptr) return true; if (gpusim::get_gpu_count() == 0) return true; return false; } BOOST_AUTO_TEST_CASE(CompareGPUtoCPU) { if (missing_cuda_skip()) return; // TODO: Replace Schrodinger function that is commented out here // Only run this if there's a GPU available // if(!schrodinger::gpgpu::is_any_gpu_available()) return; QStringList db_fnames; db_fnames << "small.fsim"; GPUSimServer server(db_fnames); // Fetch a fingerprint to search against, this should always // guarantee a 100% match const Fingerprint& fp = server.getFingerprint(std::rand() % 20, "small"); const vector<int> return_counts = {10, 15}; const float similarity_cutoff = 0; const QString dbkey = "pass"; // Passed to database during creation unsigned long approximate_result_count; for (auto return_count : return_counts) { std::vector<char*> gpu_smiles; std::vector<char*> gpu_ids; std::vector<float> gpu_scores; server.similaritySearch(fp, "small", dbkey, return_count, similarity_cutoff, CalcType::GPU, gpu_smiles, gpu_ids, gpu_scores, approximate_result_count); std::vector<char*> cpu_smiles; std::vector<char*> cpu_ids; std::vector<float> cpu_scores; server.similaritySearch(fp, "small", dbkey, return_count, similarity_cutoff, CalcType::CPU, cpu_smiles, cpu_ids, cpu_scores, approximate_result_count); BOOST_CHECK_EQUAL(gpu_smiles.size(), return_count); for (unsigned int i = 0; i < gpu_smiles.size(); i++) { BOOST_CHECK_EQUAL(gpu_smiles[i], cpu_smiles[i]); } } } BOOST_AUTO_TEST_CASE(TestSearchMultiple) { if (missing_cuda_skip()) return; QStringList db_fnames; db_fnames << "small.fsim"; db_fnames << "small_copy.fsim"; GPUSimServer server(db_fnames); // Fetch a fingerprint to search against, this should always // guarantee a 100% match const Fingerprint& fp = server.getFingerprint(std::rand() % 20, "small"); int return_count = 10; const float similarity_cutoff = 0; std::vector<char*> smiles; std::vector<char*> ids; std::vector<float> scores; std::map<QString, QString> dbname_to_key; dbname_to_key["small"] = "pass"; dbname_to_key["small_copy"] = "pass"; unsigned long approximate_result_count; server.searchDatabases(fp, return_count, similarity_cutoff, dbname_to_key, smiles, ids, scores, approximate_result_count); BOOST_REQUIRE_EQUAL(smiles.size(), return_count); // Results should have two copies of each ID, one from each DB loaded BOOST_REQUIRE_EQUAL(ids[0], "ZINC00000022;:;ZINC00000022"); } BOOST_AUTO_TEST_CASE(TestSimilarityCutoff) { if (missing_cuda_skip()) return; QStringList db_fnames; db_fnames << "small.fsim"; GPUSimServer server(db_fnames); const Fingerprint& fp = server.getFingerprint(0, "small"); int return_count = 10; const vector<float> similarity_cutoffs = {0, 0.1, 0.3, 0.4}; // Results returned for each cutoff range const vector<int> result_counts = {10, 10, 3, 1}; const vector<unsigned long> approximate_counts = {100, 86, 3, 1}; const QString dbkey = "pass"; // Passed to database during creation unsigned long approximate_result_count; for (unsigned int i = 0; i < similarity_cutoffs.size(); i++) { std::vector<char*> smiles; std::vector<char*> ids; std::vector<float> scores; server.similaritySearch(fp, "small", dbkey, return_count, similarity_cutoffs[i], CalcType::GPU, smiles, ids, scores, approximate_result_count); BOOST_CHECK_EQUAL(smiles.size(), result_counts[i]); BOOST_CHECK_EQUAL(approximate_result_count, approximate_counts[i]); } } /* * This tests our custom sort function, modified bubble sort to get * O(num_required * len(indices)) */ BOOST_AUTO_TEST_CASE(CPUSort) { vector<int> indices = {0, 1, 2, 3, 4, 5}; vector<float> scores = {1, 3, 2, 4, 0, 7}; top_results_bubble_sort(indices, scores, 3); // Verify that this pushed the top 3 values to the far right of arrays BOOST_CHECK_EQUAL(indices[0], 5); BOOST_CHECK_EQUAL(scores[0], 7); BOOST_CHECK_EQUAL(indices[2], 1); BOOST_CHECK_EQUAL(scores[2], 3); } BOOST_AUTO_TEST_CASE(FoldFingerprint) { int factor = 2; vector<int> fp = {32, 24, 11, 7}; vector<int> ref_answer = {43, 31}; vector<int> answer(fp.size() / factor); gpusim::FoldFingerprintFunctorCPU(factor, fp.size(), fp, answer)(0); for (unsigned int i = 0; i < ref_answer.size(); i++) { BOOST_CHECK_EQUAL(answer[i], ref_answer[i]); } factor = 4; answer.resize(1); answer[0] = 0; gpusim::FoldFingerprintFunctorCPU(factor, fp.size(), fp, answer)(0); BOOST_CHECK_EQUAL(answer.size(), 1); BOOST_CHECK_EQUAL(answer[0], 63); } BOOST_AUTO_TEST_CASE(getNextGPU) { if (missing_cuda_skip()) return; unsigned int gpucount = gpusim::get_gpu_count(); // Make sure first go around gets every valid GPU for (unsigned int i = 0; i < gpucount; i++) { BOOST_CHECK_EQUAL(i, gpusim::get_next_gpu(1)); } // Make sure second go around loops through them all again for (unsigned int i = 0; i < gpucount; i++) { BOOST_CHECK_EQUAL(i, gpusim::get_next_gpu(1)); } }
32.862637
79
0.652566
[ "vector" ]
00294e69e90d027c39ef025f846dffa7c23179b5
7,911
cpp
C++
project/doc/ant_simu_split.cpp
SummerOf15/maze_solver
39de3663c7749c5a1788175889edcf93c4e56abf
[ "MIT" ]
null
null
null
project/doc/ant_simu_split.cpp
SummerOf15/maze_solver
39de3663c7749c5a1788175889edcf93c4e56abf
[ "MIT" ]
null
null
null
project/doc/ant_simu_split.cpp
SummerOf15/maze_solver
39de3663c7749c5a1788175889edcf93c4e56abf
[ "MIT" ]
null
null
null
#include <vector> #include <iostream> #include <random> #include <stdio.h> #include "labyrinthe.hpp" #include "ant.hpp" #include "pheromone.hpp" # include "gui/context.hpp" # include "gui/colors.hpp" # include "gui/point.hpp" # include "gui/segment.hpp" # include "gui/triangle.hpp" # include "gui/quad.hpp" # include "gui/event_manager.hpp" # include "display.hpp" #include "mpi.h" using namespace std; # define send_data_tag 1 # define receive_data_tag 2 void decompose_domain(int domain_size, int world_rank, int world_size, int* subdomain_start, int* subdomain_size) { if (world_size > domain_size) { // Assume the domain size is greater than the world size MPI_Abort(MPI_COMM_WORLD, 1); } *subdomain_start = domain_size / world_size * world_rank; *subdomain_size = domain_size / world_size; if (world_rank == world_size - 1) { // give remainders to the last subdomain *subdomain_size += domain_size % world_size; } } void send_outgoing_ants(std::vector<ant>* upgoing_walkers, std::vector<ant>* downgoing_walkers, int world_rank, int world_size) { // send the data as an array of MPI_BYTES to the next process // the last process send the data to process 0 if(upgoing_walkers->size()>0) { MPI_Send(upgoing_walkers->data(), upgoing_walkers->size() * sizeof(ant), MPI_BYTE, (world_rank - 1) % world_size, 0, MPI_COMM_WORLD); printf("Process %d sending %d outgoing walkers to process %d\n", world_rank, upgoing_walkers->size(), (world_rank - 1) % world_size); upgoing_walkers->clear(); } if (downgoing_walkers->size()>0) { MPI_Send(downgoing_walkers->data(), downgoing_walkers->size() * sizeof(ant), MPI_BYTE, (world_rank + 1) % world_size, 0, MPI_COMM_WORLD); printf("Process %d sending %d outgoing walkers to process %d\n", world_rank, downgoing_walkers->size(), (world_rank + 1) % world_size); downgoing_walkers->clear(); } // clear the outgoing walkers list } void receive_incoming_walkers(std::vector<ant>* incoming_walkers, int world_rank, int world_size) { MPI_Status status; // receive from the data from bottom direction. // if current process is 0, then receive from the last process int incoming_walkers_size; int incoming_rank = world_rank+1; if (incoming_rank<world_size) { MPI_Probe(incoming_rank, 0, MPI_COMM_WORLD, &status); // allocate buffer for incoming message MPI_Get_count(&status, MPI_BYTE, &incoming_walkers_size); // retrive the first n walkers incoming_walkers->resize(incoming_walkers_size / sizeof(ant)); MPI_Recv(incoming_walkers->data(), incoming_walkers_size, MPI_BYTE, incoming_rank, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); } // receive data from top direction std::vector<ant> downcoming_walkers; incoming_rank = world_rank-1; if (incoming_rank>=0) { MPI_Probe(incoming_rank, 0, MPI_COMM_WORLD, &status); // allocate buffer for incoming message MPI_Get_count(&status, MPI_BYTE, &incoming_walkers_size); if(incoming_walkers_size>0) { // retrive the first n walkers downcoming_walkers.resize(incoming_walkers_size / sizeof(ant)); MPI_Recv(downcoming_walkers.data(), incoming_walkers_size, MPI_BYTE, incoming_rank, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); for(int i=0;i<incoming_walkers_size;i++) { incoming_walkers->push_back(downcoming_walkers[i]); } //incoming_walkers->insert(incoming_walkers->end(),downcoming_walkers->begin(),downcoming_walkers->end()); } } } void advance_time( const labyrinthe& land, pheromone& phen, const position_t& pos_nest, const position_t& pos_food, std::vector<ant>& ants, std::size_t& cpteur,int subdomain_start,int subdomain_size, int domain_size, std::vector<ant>* upgoing_ants, std::vector<ant>* downgoing_ants, int rank, int num_procs) { for (size_t i = 0; i < ants.size(); ++i) { ants[i].advance(phen, land, pos_food, pos_nest, cpteur); position_t last_pos = ants[i].get_position(); if (last_pos.first < subdomain_start) { upgoing_ants->push_back(ants[i]); } else if (last_pos.first >= subdomain_start + subdomain_size) { downgoing_ants->push_back(ants[i]); } } //printf("%d+%d",upgoing_ants->size(),downgoing_ants->size()); // send_outgoing_ants(upgoing_ants, downgoing_ants, rank, num_procs); phen.do_evaporation(); phen.update(); } int main(int nargs, char* argv[]) { int rank,num_procs; MPI_Init(&nargs,&argv); MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &num_procs); const dimension_t dims{ 64,64 };// Dimension du labyrinthe const std::size_t life = int(dims.first * dims.second); const int nb_ants = 2 * dims.first * dims.second; // Nombre de fourmis const double eps = 0.75; // Coefficient d'exploration const double alpha = 0.97; // Coefficient de chaos const double beta = 0.999; // Coefficient d'évaporation labyrinthe laby(dims); // Location du nid position_t pos_nest{dims.first/2,dims.second/2}; // Location de la nourriture position_t pos_food{dims.first-1,dims.second-1}; int subdomain_start, subdomain_size; std::vector<ant> upgoing_ants, downgoing_ants; // Définition du coefficient d'exploration de toutes les fourmis. ant::set_exploration_coef(eps); std::vector<ant> ants; if(rank == 1) { cout<<sizeof(ant)<<endl; // On va créer toutes les fourmis dans le nid : ants.reserve(nb_ants); for ( size_t i = 0; i < nb_ants; ++i ) ants.emplace_back(pos_nest, life); // On crée toutes les fourmis dans la fourmilière. pheromone phen(laby.dimensions(), pos_food, pos_nest, alpha, beta); gui::context graphic_context(nargs, argv); gui::window& win = graphic_context.new_window(h_scal*laby.dimensions().second,h_scal*laby.dimensions().first+266); display_t displayer( laby, phen, pos_nest, pos_food, ants, win ); size_t food_quantity = 0; gui::event_manager manager; manager.on_key_event(int('q'), [](int code) { exit(0); }); manager.on_display([&] { displayer.display(food_quantity); win.blit(); }); decompose_domain(dims.first, rank, num_procs, &subdomain_start, &subdomain_size); std::cout << "totally divided" << num_procs << " partitions" << std::endl; manager.on_idle([&]() { advance_time(laby, phen, pos_nest, pos_food, ants, food_quantity, subdomain_start, subdomain_size, dims.first, &upgoing_ants, &downgoing_ants, rank, num_procs); displayer.display(food_quantity); win.blit(); }); std::cout<<upgoing_ants.size()<<std::endl; manager.loop(); } else if (rank % 2 == 0) { std::cout<<"rank "<<rank<<std::endl; cout<<ants.size(); //send all outgoing walkers to the next process send_outgoing_ants(&upgoing_ants, &downgoing_ants, rank, num_procs); //receiving all the new incoming walkers receive_incoming_walkers(&ants, rank, num_procs); } else { std::cout<<"rank "<<rank<<std::endl; //receiving all the new incoming walkers receive_incoming_walkers(&ants, rank, num_procs); //send all outgoing walkers to the next process send_outgoing_ants(&upgoing_ants, &downgoing_ants, rank, num_procs); } printf("Process %d received %d incoming walkers\n", rank, ants.size()); MPI_Finalize(); return 0; }
37.671429
145
0.65036
[ "vector" ]
0038ffc73b1b49a9050714b8fc3b4d9121a47d04
9,681
cpp
C++
deprecate/tools/vpcachier/main.cpp
novatig/CubismUP_3D_old
47f7dd5941d81853cfe879385080c7c2c68a9b71
[ "MIT" ]
2
2020-06-12T10:06:59.000Z
2021-04-22T00:44:27.000Z
deprecate/tools/vpcachier/main.cpp
novatig/CubismUP_3D_old
47f7dd5941d81853cfe879385080c7c2c68a9b71
[ "MIT" ]
null
null
null
deprecate/tools/vpcachier/main.cpp
novatig/CubismUP_3D_old
47f7dd5941d81853cfe879385080c7c2c68a9b71
[ "MIT" ]
null
null
null
/* * main.cpp * * * Created by Diego Rossinelli on 3/27/13. * Copyright 2013 ETH Zurich. All rights reserved. * */ #include <iostream> #include <string> #include <mpi.h> #include <numeric> #include <ArgumentParser.h> #include "Reader_WaveletCompression.h" #include "WaveletTexture3D.h" int main(int argc, const char ** argv) { MPI::Init_thread(MPI_THREAD_SERIALIZED); //create my cartesian communicator MPI::Intracomm& mycomm = MPI::COMM_WORLD; const int myrank = mycomm.Get_rank(); const int pesize = mycomm.Get_size(); const bool isroot = !myrank; ArgumentParser argparser(argc, argv); if (isroot) argparser.loud(); else argparser.mute(); const string pathtovpfile = argparser("-vp").asString("ciccio-bello.vpcache"); const string pathtosimdata = argparser("-simdata").asString("data.channel0"); const double minval = argparser("-min").asDouble(0); const double maxval = argparser("-max").asDouble(1); const double wavelet_threshold = argparser("-eps").asDouble(0); const bool reading = argparser.check("-read"); const bool halffloat = argparser.check("-f16"); const bool swap = argparser.check("-swap"); const bool swapW = argparser.check("-swapW"); const int wtype_read = argparser("-wtype_read").asInt(1); const int wtype_write = argparser("-wtype_write").asInt(1); /* double minval = 0; double maxval = 1; char *s; s = getenv("MINVAL"); if (s != NULL) minval = atof(s); s = getenv("MAXVAL"); if (s != NULL) maxval = atof(s); */ //printf("minval = %f, maxval = %f\n", minval, maxval); //just a mini-test for reading if (reading) { if (isroot) { WaveletTexture3D_Collection texture_collection(pathtovpfile, wtype_read); //texture_collection.set_wtype_read(wtype_read); WaveletTexture3D * texture = new WaveletTexture3D; for(int iz = 0; iz < texture_collection.get_ztextures(); ++iz) for(int iy = 0; iy < texture_collection.get_ytextures(); ++iy) for(int ix = 0; ix < texture_collection.get_xtextures(); ++ix) texture_collection.read(ix, iy, iz, *texture); delete texture; printf("Bella li, tutto in regola. Sa vedum!\n"); } } else //ok we are ready to start { //input is the simulation data Reader_WaveletCompressionMPI myreader(mycomm, pathtosimdata, swap, wtype_read); myreader.load_file(); //figure out the amount of work per rank const int xblocks = myreader.xblocks(); const int yblocks = myreader.yblocks(); const int zblocks = myreader.zblocks(); const double gridspacing = 1. / max(max(xblocks, yblocks), zblocks) / _BLOCKSIZE_; MYASSERT(_BLOCKSIZE_ <= _VOXELS_, "_BLOCKSIZE_ = " << _BLOCKSIZE_ << " is bigger than _VOXELS_ =" << _VOXELS_ << "\n"); const int ghosts1side = 2; const int puredata1d = _VOXELS_ - 2 * ghosts1side; const int xtextures = (xblocks * _BLOCKSIZE_ - 2 * ghosts1side) / puredata1d; const int ytextures = (yblocks * _BLOCKSIZE_ - 2 * ghosts1side) / puredata1d; const int ztextures = (zblocks * _BLOCKSIZE_ - 2 * ghosts1side) / puredata1d; const int ntextures = xtextures * ytextures * ztextures; if (isroot) { double uncompressed_footprint = 4. * xtextures * ytextures * ztextures * powf(_VOXELS_, 3) / 1024. / 1024.; printf("I am going to create: %d %d %d textures. Uncompressed memory footprint will be %.2f MB.\n", xtextures, ytextures, ztextures, uncompressed_footprint); } MYASSERT(xtextures > 0 && ytextures > 0 && ztextures > 0, "NUMBER OF VP BLOCKS IS ZERO!"); const int rankwork = std::max(1, (int)std::ceil(ntextures / (double)pesize)); const int mystart = std::min(ntextures, rankwork * myrank); const int myend = std::min(ntextures, rankwork * (myrank + 1)); const int mytotalwork = myend - mystart; //printf("%d) my work is %d - %d\n", myrank, mystart, myend); //spit a warning in case we starve { int leastwork = -1; mycomm.Reduce(&mytotalwork, &leastwork, 1, MPI_INT, MPI::MIN, 0); assert(leastwork >= 0 || !isroot); if (isroot && leastwork == 0) printf("WARNING: watchout because some of the ranks have zero work.\n"); } //ok, lets collect some stats vector<Real> vmaxval, vminval, vavg; WaveletTexture3D_CollectionMPI texture_collection(mycomm, pathtovpfile, xtextures, ytextures, ztextures, wavelet_threshold, halffloat, swapW, wtype_read, wtype_write); for(int g = mystart; g < myend; ++g) { const int gx = g % xtextures; const int gy = (g / xtextures) % ytextures; const int gz = g / (xtextures * ytextures); assert(gx >= 0 && gx < xtextures); assert(gy >= 0 && gy < ytextures); assert(gz >= 0 && gz < ztextures); WaveletTexture3D * texture = new WaveletTexture3D; WaveletsOnInterval::FwtAp * const ptrtexdata = & texture->data()[0][0][0]; const int xdatastart = gx * puredata1d; const int ydatastart = gy * puredata1d; const int zdatastart = gz * puredata1d; const int xdataend = (gx + 1) * puredata1d + 2 * ghosts1side; const int ydataend = (gy + 1) * puredata1d + 2 * ghosts1side; const int zdataend = (gz + 1) * puredata1d + 2 * ghosts1side; texture->geometry.setup<0>(xdatastart, xdataend, ghosts1side, gridspacing); texture->geometry.setup<1>(ydatastart, ydataend, ghosts1side, gridspacing); texture->geometry.setup<2>(zdatastart, zdataend, ghosts1side, gridspacing); assert(xdataend - xdatastart == _VOXELS_); assert(ydataend - ydatastart == _VOXELS_); assert(zdataend - zdatastart == _VOXELS_); const int xblockstart = xdatastart / _BLOCKSIZE_; const int yblockstart = ydatastart / _BLOCKSIZE_; const int zblockstart = zdatastart / _BLOCKSIZE_; const int xblockend = (xdataend - 1) / _BLOCKSIZE_ + 1; const int yblockend = (ydataend - 1) / _BLOCKSIZE_ + 1; const int zblockend = (zdataend - 1) / _BLOCKSIZE_ + 1; for(int bz = zblockstart; bz < zblockend; ++bz) for(int by = yblockstart; by < yblockend; ++by) for(int bx = xblockstart; bx < xblockend; ++bx) { Real data[_BLOCKSIZE_][_BLOCKSIZE_][_BLOCKSIZE_]; assert(bx >= 0 && bx < xblocks); assert(by >= 0 && by < yblocks); assert(bz >= 0 && bz < zblocks); myreader.load_block(bx, by, bz, data); const int xdststart = std::max(xdatastart, bx * _BLOCKSIZE_) - xdatastart; const int ydststart = std::max(ydatastart, by * _BLOCKSIZE_) - ydatastart; const int zdststart = std::max(zdatastart, bz * _BLOCKSIZE_) - zdatastart; const int xdstend = std::min(xdataend, (bx + 1) * _BLOCKSIZE_) - xdatastart; const int ydstend = std::min(ydataend, (by + 1) * _BLOCKSIZE_) - ydatastart; const int zdstend = std::min(zdataend, (bz + 1) * _BLOCKSIZE_) - zdatastart; const int xsrcoffset = xdatastart - bx * _BLOCKSIZE_; const int ysrcoffset = ydatastart - by * _BLOCKSIZE_; const int zsrcoffset = zdatastart - bz * _BLOCKSIZE_; for(int dz = zdststart; dz < zdstend; ++dz) for(int dy = ydststart; dy < ydstend; ++dy) for(int dx = xdststart; dx < xdstend; ++dx) { assert(dx >= 0 && dx < _VOXELS_); assert(dy >= 0 && dy < _VOXELS_); assert(dz >= 0 && dz < _VOXELS_); assert(dx + xsrcoffset >= 0 && dx + xsrcoffset < _BLOCKSIZE_); assert(dy + ysrcoffset >= 0 && dy + ysrcoffset < _BLOCKSIZE_); assert(dz + zsrcoffset >= 0 && dz + zsrcoffset < _BLOCKSIZE_); ptrtexdata[dx + _VOXELS_ * (dy + _VOXELS_ * dz)] = data[dz + zsrcoffset][dy + ysrcoffset][dx + xsrcoffset]; } } //normalize the data { const Real a1 = 1 / (maxval - minval); const Real a0 = -minval * a1; Real mysum = 0, mymax = -HUGE_VAL, mymin = HUGE_VAL; for(int i = 0; i < _VOXELS_ * _VOXELS_ * _VOXELS_; ++i) { const float val = ptrtexdata[i]; ptrtexdata[i] = std::min(1.f, std::max(0.f, a0 + a1 * val)); assert(ptrtexdata[i] >= 0 && ptrtexdata[i] <= 1); mysum += val; mymin = min(mymin, (Real)val); mymax = max(mymax, (Real)val); } vmaxval.push_back(mymax); vminval.push_back(mymin); vavg.push_back(mysum / (_VOXELS_ * _VOXELS_ * _VOXELS_)); } assert(xblockstart >= 0 && xblockstart < xblocks); assert(yblockstart >= 0 && yblockstart < yblocks); assert(zblockstart >= 0 && zblockstart < zblocks); assert(xblockend > 0 && xblockend <= xblocks); assert(yblockend > 0 && yblockend <= yblocks); assert(zblockend > 0 && zblockend <= zblocks); texture_collection.write(gx, gy, gz, *texture); delete texture; } //spit some statistics { //in case we did not do anything, put some fake values in the stat to prevent sigfault if (mytotalwork == 0) { vmaxval.push_back(-HUGE_VAL); vminval.push_back(+HUGE_VAL); vavg.push_back(0); } float minval = *std::min_element(vminval.begin(), vminval.end()); float avgval = std::accumulate(vavg.begin(), vavg.end(), 0) / vavg.size(); float maxval = *std::max_element(vmaxval.begin(), vmaxval.end()); mycomm.Reduce(isroot ? MPI::IN_PLACE : &minval, &minval, 1, MPI_FLOAT, MPI::MIN, 0); mycomm.Reduce(isroot ? MPI::IN_PLACE : &avgval, &avgval, 1, MPI_FLOAT, MPI::SUM, 0); mycomm.Reduce(isroot ? MPI::IN_PLACE : &maxval, &maxval, 1, MPI_FLOAT, MPI::MAX, 0); avgval /= mycomm.Get_size(); if (isroot) printf("Ok we are done here. The min, avg, max values found are : %.2f %.2f %.2f\n", minval, avgval, maxval); } if (isroot) std::cout << "Also tchuess zaeme gal.\n"; } MPI::Finalize(); return 0; }
33.968421
169
0.641359
[ "geometry", "vector" ]
0039a27e7bbe289ca1a69201813743d8674f7283
536
hpp
C++
src/ogl4/OpenGL4Mesh.hpp
LorenzoDiStefano/RenderLib
72182ccb01edc0a0c5d7370e256f32aa5e1517d3
[ "MIT" ]
null
null
null
src/ogl4/OpenGL4Mesh.hpp
LorenzoDiStefano/RenderLib
72182ccb01edc0a0c5d7370e256f32aa5e1517d3
[ "MIT" ]
null
null
null
src/ogl4/OpenGL4Mesh.hpp
LorenzoDiStefano/RenderLib
72182ccb01edc0a0c5d7370e256f32aa5e1517d3
[ "MIT" ]
null
null
null
#ifndef RENDERLIB_OPENGL4_MESH #define RENDERLIB_OPENGL4_MESH #pragma once #include <RenderLib/IMesh.hpp> #include <string> #include "glad.h" namespace RenderLib { class OpenGL4Mesh : public IMesh { public: OpenGL4Mesh(); ~OpenGL4Mesh(); void AddElements(const std::vector<float>& data, const uint32_t size) override; void Bind() override; uint32_t GetNumberOfVertices() override { return number_of_vertices; }; private: GLuint vao; std::vector<GLuint> vbos; uint32_t number_of_vertices; }; } #endif
16.242424
81
0.731343
[ "vector" ]
003ac77e28ec2ca00c564e5056ef1567dae4358a
3,610
cpp
C++
A5/a5.cpp
isaacrez/CSE250
a27e1d56cae79b8af08d7d5837bcaa47281ebfe9
[ "MIT" ]
null
null
null
A5/a5.cpp
isaacrez/CSE250
a27e1d56cae79b8af08d7d5837bcaa47281ebfe9
[ "MIT" ]
null
null
null
A5/a5.cpp
isaacrez/CSE250
a27e1d56cae79b8af08d7d5837bcaa47281ebfe9
[ "MIT" ]
null
null
null
// File: a5.cpp // Isaac // Rezey // I AFFIRM THAT WHEN WORKING ON THIS ASSIGNMENT // I WILL FOLLOW UB STUDENT CODE OF CONDUCT, AND // I WILL NOT VIOLATE ACADEMIC INTEGRITY RULES #include <iostream> #include <fstream> #include <algorithm> #include <map> #include <vector> #include <string> std::string comp(std::string prosName, int prosCount, std::string currName, int &highCount); int main(int argc, char* argv[]) { // Correcting user's faulty inputs if (argc != 2){ std::cout << "Incorrect inputs. Use as ./a5 filename" << std::endl; return -1; } // Initialize dictionary / file reading std::map<std::string, int> dict; std::ifstream file(argv[1]); std::string textLine; // Populate the dictionary while (not file.eof()) { textLine = ""; std::getline(file, textLine); // Decouple the key / value for (unsigned i = 0; i < textLine.size(); i++){ // Find the space if (textLine[i] == ' '){ // Cut them key and value around it std::string key = textLine.substr(0, i); int value = stoi(textLine.substr(i+1)); dict[key] = value; break; } } } file.close(); // Process inputs int lowerBound = 0; std::string allNames; std::vector<std::string> nameVec; getline(std::cin, allNames); for (unsigned i = 0; i < allNames.size(); i++){ if (allNames[i] == ' '){ nameVec.push_back(allNames.substr(lowerBound, i-lowerBound)); i++; lowerBound = i; } } nameVec.push_back(allNames.substr(lowerBound)); // Spell-checking process char alpha[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; for (auto it = nameVec.begin(); it != nameVec.end(); it++){ // Check if name is in the dictionary auto exactMatch = dict.find(*it); if (exactMatch != dict.end()){ std::cout << *it << " " << exactMatch->second << std::endl; exactMatch->second++; } else { // Check if name is off by one int highCount = 0; std::string currName = *it; std::string predName; // Deletion: for (unsigned i = 0; i < currName.size(); i++){ currName.erase(i, 1); auto key = dict.find(currName); if (key != dict.end()){ predName = comp(key->first, key->second, predName, highCount); } currName = *it; } // Replacement: for (unsigned i = 0; i < currName.size(); i++){ for (int j = 0; j < 27; j++){ currName[i] = alpha[j]; auto key = dict.find(currName); if (key != dict.end()){ predName = comp(key->first, key->second, predName, highCount); } } currName = *it; } // Addition: for (unsigned i = 0; i < currName.size()+1; i++){ currName.insert(i, "A"); for (int j = 0; j < 27; j++){ currName[i] = alpha[j]; auto key = dict.find(currName); if (key != dict.end()){ predName = comp(key->first, key->second, predName, highCount); } } currName = *it; } if (highCount != 0){ std::cout << predName << " " << highCount << std::endl; } else { // It's a unique, unknown element - add it in! std::cout << "-" << std::endl; dict[*it] = 1; } } } // Output final dictionary std::cout << "-----" << std::endl; for (auto it = dict.begin(); it != dict.end(); it++){ std::cout << it->first << " " << it->second << std::endl; } } std::string comp(std::string prosName, int prosCount, std::string currName, int &highCount){ if (prosCount > highCount){ highCount = prosCount; return prosName; } else if (prosCount == highCount){ if (std::lexicographical_compare(prosName.begin(), prosName.end(), currName.begin(), currName.end())){ highCount = prosCount; return prosName; } } return currName; }
25.069444
104
0.599446
[ "vector" ]