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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
44fdd86087f3db554fd8ea3f45a7460826ad4048 | 11,529 | cpp | C++ | src/VertexBuffers.cpp | sdh4/GLSupport | ea10881c128f346b878eee258d3cfefda9f5f3d5 | [
"MIT"
] | null | null | null | src/VertexBuffers.cpp | sdh4/GLSupport | ea10881c128f346b878eee258d3cfefda9f5f3d5 | [
"MIT"
] | null | null | null | src/VertexBuffers.cpp | sdh4/GLSupport | ea10881c128f346b878eee258d3cfefda9f5f3d5 | [
"MIT"
] | null | null | null | #include "VertexBuffers.h"
/*
Create a vertex array object and vertex buffer object for vertices of size 3 (x, y, z) along with colors of size 3: (r, g, b)
@param vaoID - address to store the vertex array object
@param vboID - address to store the vertex buffer objects. Note, TWO spaces are required to create buffers of vertices and colors.
@param vertices - pointer to an array containing vertices as [x0, y0, z0, x1, y1, z1, ...]
@param colors - pointer to an array containning color as [r0, g0, b0, r1, g1, b1, .....]
@param N - the number of vertices and colors, NOT THE LENGTH OF THE ARRAY. Note that the vector sizes MUST match.
*/
bool cs557::CreateVertexObjects33(int* vaoID, int* vboID, float* vertices, float* colors, int N, int vertices_location , int normals_location )
{
if (vertices == NULL || colors == NULL)
{
std::cout << "[ERROR] - CreateVertexObjects33: No vertices or color information given." << std::endl;
return false;
}
glGenVertexArrays(1, (GLuint*)vaoID); // Create our Vertex Array Object
glBindVertexArray(*vaoID); // Bind our Vertex Array Object so we can use it
if (vaoID[0] == -1){
std::cout << "[ERROR] - Vertex array object was not generated." << std::endl;
return false;
}
glGenBuffers(2, (GLuint*)vboID); // Generate our Vertex Buffer Object
if (vboID[0] == -1 || vboID[1] == -1){
std::cout << "[ERROR] - One or both vertex buffer objects were not generated." << std::endl;
return false;
}
// vertices
glBindBuffer(GL_ARRAY_BUFFER, vboID[0]); // Bind our Vertex Buffer Object
glBufferData(GL_ARRAY_BUFFER, N * 3 * int(sizeof(GLfloat)), vertices, GL_STATIC_DRAW); // Set the size and data of our VBO and set it to STATIC_DRAW
glVertexAttribPointer((GLuint)vertices_location, 3, GL_FLOAT, GL_FALSE, 0, 0); // Set up our vertex attributes pointer
glEnableVertexAttribArray(vertices_location); // Disable our Vertex Array Object
//Color
glBindBuffer(GL_ARRAY_BUFFER, vboID[1]); // Bind our second Vertex Buffer Object
glBufferData(GL_ARRAY_BUFFER, N * 3 * int(sizeof(GLfloat)), colors, GL_STATIC_DRAW); // Set the size and data of our VBO and set it to STATIC_DRAW
glVertexAttribPointer((GLuint)normals_location, 3, GL_FLOAT, GL_FALSE, 0, 0); // Set up our vertex attributes pointer
glEnableVertexAttribArray(normals_location); // Enable the second vertex attribute array
glBindVertexArray(0); // Disable our Vertex Buffer Object
return true;
}
/*
Create vertex buffer object for points and normal vectors + an index list
@param vaoID - address to store the vertex array object
@param vboID - address to store the vertex buffer objects. Note, THREE spaces are required to create buffers of vertices and normals and texture coordinate.
@param iboID - address to store the index buffer object
@param vertices - pointer to an array containing vertices as [x0, y0, z0, x1, y1, z1, ...]
@param normals - pointer to an array containning color as [n0, n0, n0, n1, n1, n1, .....]
@param N - the number of vertices and colors, NOT THE LENGTH OF THE ARRAY. Note that the vector sizes MUST match.
@param indices - pointer to an array with indices
@param I - the number of indices
@param vertices_location - the GLSL vertices location
@param normals_location - the GLSL normal vectors locations
*/
bool cs557::CreateVertexObjectsIndexed33( int* vaoID, int* vboID, int* iboID, float* points, float* normals, int N, int* indices, int I,
int vertices_location, int normals_location)
{
if (points == NULL || normals == NULL)
{
std::cout << "[ERROR] - CreateVertexObjects33: No vertices or color information given." << std::endl;
return false;
}
glGenVertexArrays(1, (GLuint*)vaoID); // Create our Vertex Array Object
glBindVertexArray(*vaoID); // Bind our Vertex Array Object so we can use it
if (vaoID[0] == -1){
std::cout << "[ERROR] - Vertex array object was not generated." << std::endl;
return false;
}
glGenBuffers(2, (GLuint*)vboID); // Generate our Vertex Buffer Object
glGenBuffers(1, (GLuint*)iboID);
if (vboID[0] == -1 || vboID[1] == -1 || iboID[0] == -1){
std::cout << "[ERROR] - One or both vertex buffer objects were not generated." << std::endl;
return false;
}
// vertices
glBindBuffer(GL_ARRAY_BUFFER, vboID[0]); // Bind our Vertex Buffer Object
glBufferData(GL_ARRAY_BUFFER, N * int(3) * sizeof(GLfloat), points, GL_STATIC_DRAW); // Set the size and data of our VBO and set it to STATIC_DRAW
glVertexAttribPointer((GLuint)vertices_location, 3, GL_FLOAT, GL_FALSE, 0, 0); // Set up our vertex attributes pointer
glEnableVertexAttribArray(vertices_location); // Disable our Vertex Array Object
//Color
glBindBuffer(GL_ARRAY_BUFFER, vboID[1]); // Bind our second Vertex Buffer Object
glBufferData(GL_ARRAY_BUFFER, N * int(3) * sizeof(GLfloat), normals, GL_STATIC_DRAW); // Set the size and data of our VBO and set it to STATIC_DRAW
glVertexAttribPointer((GLuint)normals_location, 3, GL_FLOAT, GL_FALSE, 0, 0); // Set up our vertex attributes pointer
glEnableVertexAttribArray(normals_location); // Enable the second vertex attribute array
// Index buffer
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, iboID[0]);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, I * sizeof(unsigned int),
indices, GL_STATIC_DRAW);
glBindVertexArray(0); // Disable our Vertex Buffer Object
return true;
}
/*
Create vertex buffer object for points and normal vectors + an index list
@param vaoID - address to store the vertex array object
@param vboID - address to store the vertex buffer objects. Note, TWO array elements are required to create buffers of vertices and normals and texture coordinate.
@param iboID - address to store the index buffer object
@param vertices - pointer to an array containing vertices as [x0, y0, z0, x1, y1, z1, ...]
@param normals - pointer to an array containning color as [n0, n0, n0, n1, n1, n1, .....]
@param N - the number of vertices and colors, NOT THE LENGTH OF THE ARRAY. Note that the vector sizes MUST match.
@param indices - pointer to an array with indices
@param I - the number of indices
@param vertices_location - the GLSL vertices location
@param normals_location - the GLSL normal vectors locations
*/
bool cs557::CreateVertexObjectsIndexed53( int* vaoID, int* vboID, int* iboID, float* points, float* normals, int N, int* indices, int I,
int vertices_location, int tex_coord_location, int normals_location)
{
if (points == NULL || normals == NULL)
{
std::cout << "[ERROR] - CreateVertexObjectsIndexed323: No vertices or normal given." << std::endl;
return false;
}
glGenVertexArrays(1, (GLuint*)vaoID); // Create our Vertex Array Object
glBindVertexArray(*vaoID); // Bind our Vertex Array Object so we can use it
if (vaoID[0] == -1){
std::cout << "[ERROR] - Vertex array object was not generated." << std::endl;
return false;
}
glGenBuffers(2, (GLuint*)vboID); // Generate our Vertex Buffer Object for points, normals, and texture coordinates
glGenBuffers(1, (GLuint*)iboID);
if (vboID[0] == -1 || vboID[1] == -1 || iboID[0] == -1){
std::cout << "[ERROR] - One or both vertex buffer objects were not generated." << std::endl;
return false;
}
// vertices
glBindBuffer(GL_ARRAY_BUFFER, vboID[0]); // Bind our Vertex Buffer Object
glBufferData(GL_ARRAY_BUFFER, N * int(5) * sizeof(GLfloat), points, GL_STATIC_DRAW); // Set the size and data of our VBO and set it to STATIC_DRAW
glVertexAttribPointer((GLuint)vertices_location, 3, GL_FLOAT, GL_FALSE, 5*sizeof(GLfloat), 0); // Set up our vertex attributes pointer
glEnableVertexAttribArray(vertices_location); // Enable the Vertex Array Object
// Texture Coordinates
glVertexAttribPointer((GLuint)tex_coord_location, 2, GL_FLOAT, GL_FALSE, 5 *sizeof(GLfloat), (const GLvoid*)(3 * sizeof(GLfloat))); // Set up our texture attributes pointer
glEnableVertexAttribArray(tex_coord_location); // Enable the Vertex Array Object
//Normals
glBindBuffer(GL_ARRAY_BUFFER, vboID[1]); // Bind our second Vertex Buffer Object
glBufferData(GL_ARRAY_BUFFER, N * int(3)* sizeof(GLfloat), normals, GL_STATIC_DRAW); // Set the size and data of our VBO and set it to STATIC_DRAW
glVertexAttribPointer((GLuint)normals_location, 3, GL_FLOAT, GL_FALSE, 0, 0); // Set up our vertex attributes pointer
glEnableVertexAttribArray(normals_location); // Enable the second vertex attribute array
// Index buffer
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, iboID[0]);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, I * sizeof(unsigned int),
indices, GL_STATIC_DRAW);
glBindVertexArray(0); // Disable our Vertex Buffer Object
return true;
}
/*
Create a vertex array object and vertex buffer object for vertices and texture coordinages of size 5 (x, y, z, u, v)
along with normal vectors of size 3: (nx, ny, nz)
@param vaoID - address to store the vertex array object
@param vboID - address to store the vertex buffer objects. Note, TWO spaces are required to create buffers of vertices and colors.
@param vertices_texture_coord - pointer to an array containing vertices and texture coords as [x0, y0, z0, u0, v0, x1, y1, z1, u1, v1, ...]
@param normals - pointer to an array containning normal vectors as [nx0, ny0, nz0, nx1, ny1, nz1, .....]
@param N - the number of vertices and colors, NOT THE LENGTH OF THE ARRAY. Note that the vector sizes MUST match.
*/
bool cs557::CreateVertexObjects53(int* vaoID, int* vboID, float* vertices_texture_coord, float* normals, int N,
int vertices_location, int tex_coord_location, int normals_location)
{
if (vertices_texture_coord == NULL || normals == NULL)
{
std::cout << "[ERROR] - CreateVertexObjects53: No vertices or color information given." << std::endl;
return false;
}
glGenVertexArrays(1, (GLuint*)vaoID); // Create our Vertex Array Object
glBindVertexArray(*vaoID); // Bind our Vertex Array Object so we can use it
if (vaoID[0] == -1){
std::cout << "[ERROR] - Vertex array object was not generated." << std::endl;
return false;
}
glGenBuffers(2, (GLuint*)vboID); // Generate our Vertex Buffer Object
if (vboID[0] == -1 || vboID[1] == -1){
std::cout << "[ERROR] - One or both vertex buffer objects were not generated." << std::endl;
return false;
}
// vertices
glBindBuffer(GL_ARRAY_BUFFER, vboID[0]); // Bind our Vertex Buffer Object
glBufferData(GL_ARRAY_BUFFER, N * int(5) * sizeof(GLfloat), vertices_texture_coord, GL_STATIC_DRAW); // Set the size and data of our VBO and set it to STATIC_DRAW
glVertexAttribPointer((GLuint)vertices_location, 3, GL_FLOAT, GL_FALSE, 5*sizeof(GLfloat), 0); // Set up our vertex attributes pointer
glEnableVertexAttribArray(vertices_location); // Enable the Vertex Array Object
// Texture Coordinates
glVertexAttribPointer((GLuint)tex_coord_location, 2, GL_FLOAT, GL_FALSE, 5 *sizeof(GLfloat), (const GLvoid*)(3 * sizeof(GLfloat))); // Set up our texture attributes pointer
glEnableVertexAttribArray(tex_coord_location); // Enable the Vertex Array Object
// Normals
glBindBuffer(GL_ARRAY_BUFFER, vboID[1]); // Bind our second Vertex Buffer Object
glBufferData(GL_ARRAY_BUFFER, N * int(3)* sizeof(GLfloat), normals, GL_STATIC_DRAW); // Set the size and data of our VBO and set it to STATIC_DRAW
glVertexAttribPointer((GLuint)normals_location, 3, GL_FLOAT, GL_FALSE, 0, 0); // Set up our vertex attributes pointer
glEnableVertexAttribArray(normals_location); // Enable the second vertex attribute array
glBindVertexArray(0); // Disable our Vertex Buffer Object
return true;
}
| 41.923636 | 173 | 0.729812 | [
"object",
"vector"
] |
44fef48911dcaa2f6beb3508e45d9cb36682bbb8 | 17,234 | cc | C++ | chromium/ui/app_list/views/contents_view.cc | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | 27 | 2016-04-27T01:02:03.000Z | 2021-12-13T08:53:19.000Z | chromium/ui/app_list/views/contents_view.cc | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | 2 | 2017-03-09T09:00:50.000Z | 2017-09-21T15:48:20.000Z | chromium/ui/app_list/views/contents_view.cc | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | 17 | 2016-04-27T02:06:39.000Z | 2019-12-18T08:07:00.000Z | // Copyright (c) 2012 The Chromium 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 "ui/app_list/views/contents_view.h"
#include <algorithm>
#include <vector>
#include "base/logging.h"
#include "ui/app_list/app_list_constants.h"
#include "ui/app_list/app_list_switches.h"
#include "ui/app_list/app_list_view_delegate.h"
#include "ui/app_list/views/app_list_folder_view.h"
#include "ui/app_list/views/app_list_main_view.h"
#include "ui/app_list/views/apps_container_view.h"
#include "ui/app_list/views/apps_grid_view.h"
#include "ui/app_list/views/custom_launcher_page_view.h"
#include "ui/app_list/views/search_box_view.h"
#include "ui/app_list/views/search_result_list_view.h"
#include "ui/app_list/views/search_result_page_view.h"
#include "ui/app_list/views/search_result_tile_item_list_view.h"
#include "ui/app_list/views/start_page_view.h"
#include "ui/events/event.h"
#include "ui/resources/grit/ui_resources.h"
#include "ui/views/view_model.h"
#include "ui/views/widget/widget.h"
namespace app_list {
ContentsView::ContentsView(AppListMainView* app_list_main_view)
: apps_container_view_(nullptr),
search_results_page_view_(nullptr),
start_page_view_(nullptr),
custom_page_view_(nullptr),
app_list_main_view_(app_list_main_view),
page_before_search_(0) {
pagination_model_.SetTransitionDurations(kPageTransitionDurationInMs,
kOverscrollPageTransitionDurationMs);
pagination_model_.AddObserver(this);
}
ContentsView::~ContentsView() {
pagination_model_.RemoveObserver(this);
}
void ContentsView::Init(AppListModel* model) {
DCHECK(model);
AppListViewDelegate* view_delegate = app_list_main_view_->view_delegate();
if (app_list::switches::IsExperimentalAppListEnabled()) {
std::vector<views::View*> custom_page_views =
view_delegate->CreateCustomPageWebViews(GetLocalBounds().size());
// Only add the first custom page view as STATE_CUSTOM_LAUNCHER_PAGE. Ignore
// any subsequent custom pages.
if (!custom_page_views.empty()) {
custom_page_view_ = new CustomLauncherPageView(custom_page_views[0]);
AddLauncherPage(custom_page_view_,
AppListModel::STATE_CUSTOM_LAUNCHER_PAGE);
}
// Start page.
start_page_view_ = new StartPageView(app_list_main_view_, view_delegate);
AddLauncherPage(start_page_view_, AppListModel::STATE_START);
}
// Search results UI.
search_results_page_view_ = new SearchResultPageView();
AppListModel::SearchResults* results = view_delegate->GetModel()->results();
search_results_page_view_->AddSearchResultContainerView(
results, new SearchResultListView(app_list_main_view_, view_delegate));
if (app_list::switches::IsExperimentalAppListEnabled()) {
search_results_page_view_->AddSearchResultContainerView(
results, new SearchResultTileItemListView(
GetSearchBoxView()->search_box(), view_delegate));
}
AddLauncherPage(search_results_page_view_,
AppListModel::STATE_SEARCH_RESULTS);
apps_container_view_ = new AppsContainerView(app_list_main_view_, model);
AddLauncherPage(apps_container_view_, AppListModel::STATE_APPS);
int initial_page_index = app_list::switches::IsExperimentalAppListEnabled()
? GetPageIndexForState(AppListModel::STATE_START)
: GetPageIndexForState(AppListModel::STATE_APPS);
DCHECK_GE(initial_page_index, 0);
page_before_search_ = initial_page_index;
// Must only call SetTotalPages once all the launcher pages have been added
// (as it will trigger a SelectedPageChanged call).
pagination_model_.SetTotalPages(app_list_pages_.size());
// Page 0 is selected by SetTotalPages and needs to be 'hidden' when selecting
// the initial page.
app_list_pages_[GetActivePageIndex()]->OnWillBeHidden();
pagination_model_.SelectPage(initial_page_index, false);
ActivePageChanged();
}
void ContentsView::CancelDrag() {
if (apps_container_view_->apps_grid_view()->has_dragged_view())
apps_container_view_->apps_grid_view()->EndDrag(true);
if (apps_container_view_->app_list_folder_view()
->items_grid_view()
->has_dragged_view()) {
apps_container_view_->app_list_folder_view()->items_grid_view()->EndDrag(
true);
}
}
void ContentsView::SetDragAndDropHostOfCurrentAppList(
ApplicationDragAndDropHost* drag_and_drop_host) {
apps_container_view_->SetDragAndDropHostOfCurrentAppList(drag_and_drop_host);
}
void ContentsView::SetActiveState(AppListModel::State state) {
SetActiveState(state, true);
}
void ContentsView::SetActiveState(AppListModel::State state, bool animate) {
if (IsStateActive(state))
return;
SetActiveStateInternal(GetPageIndexForState(state), false, animate);
}
int ContentsView::GetActivePageIndex() const {
// The active page is changed at the beginning of an animation, not the end.
return pagination_model_.SelectedTargetPage();
}
AppListModel::State ContentsView::GetActiveState() const {
return GetStateForPageIndex(GetActivePageIndex());
}
bool ContentsView::IsStateActive(AppListModel::State state) const {
int active_page_index = GetActivePageIndex();
return active_page_index >= 0 &&
GetPageIndexForState(state) == active_page_index;
}
int ContentsView::GetPageIndexForState(AppListModel::State state) const {
// Find the index of the view corresponding to the given state.
std::map<AppListModel::State, int>::const_iterator it =
state_to_view_.find(state);
if (it == state_to_view_.end())
return -1;
return it->second;
}
AppListModel::State ContentsView::GetStateForPageIndex(int index) const {
std::map<int, AppListModel::State>::const_iterator it =
view_to_state_.find(index);
if (it == view_to_state_.end())
return AppListModel::INVALID_STATE;
return it->second;
}
int ContentsView::NumLauncherPages() const {
return pagination_model_.total_pages();
}
void ContentsView::SetActiveStateInternal(int page_index,
bool show_search_results,
bool animate) {
if (!GetPageView(page_index)->visible())
return;
if (!show_search_results)
page_before_search_ = page_index;
app_list_pages_[GetActivePageIndex()]->OnWillBeHidden();
// Start animating to the new page.
pagination_model_.SelectPage(page_index, animate);
ActivePageChanged();
if (!animate)
Layout();
}
void ContentsView::ActivePageChanged() {
AppListModel::State state = AppListModel::INVALID_STATE;
std::map<int, AppListModel::State>::const_iterator it =
view_to_state_.find(GetActivePageIndex());
if (it != view_to_state_.end())
state = it->second;
app_list_pages_[GetActivePageIndex()]->OnWillBeShown();
app_list_main_view_->model()->SetState(state);
if (switches::IsExperimentalAppListEnabled()) {
DCHECK(start_page_view_);
// Set the visibility of the search box's back button.
app_list_main_view_->search_box_view()->back_button()->SetVisible(
state != AppListModel::STATE_START);
app_list_main_view_->search_box_view()->Layout();
bool folder_active = (state == AppListModel::STATE_APPS)
? apps_container_view_->IsInFolderView() : false;
app_list_main_view_->search_box_view()->SetBackButtonLabel(folder_active);
// Whenever the page changes, the custom launcher page is considered to have
// been reset.
app_list_main_view_->model()->ClearCustomLauncherPageSubpages();
}
app_list_main_view_->search_box_view()->ResetTabFocus(false);
}
void ContentsView::ShowSearchResults(bool show) {
int search_page = GetPageIndexForState(AppListModel::STATE_SEARCH_RESULTS);
DCHECK_GE(search_page, 0);
search_results_page_view_->ClearSelectedIndex();
SetActiveStateInternal(show ? search_page : page_before_search_, show, true);
}
bool ContentsView::IsShowingSearchResults() const {
return IsStateActive(AppListModel::STATE_SEARCH_RESULTS);
}
void ContentsView::NotifyCustomLauncherPageAnimationChanged(double progress,
int current_page,
int target_page) {
int custom_launcher_page_index =
GetPageIndexForState(AppListModel::STATE_CUSTOM_LAUNCHER_PAGE);
if (custom_launcher_page_index == target_page) {
app_list_main_view_->view_delegate()->CustomLauncherPageAnimationChanged(
progress);
} else if (custom_launcher_page_index == current_page) {
app_list_main_view_->view_delegate()->CustomLauncherPageAnimationChanged(
1 - progress);
}
}
void ContentsView::UpdatePageBounds() {
// The bounds calculations will potentially be mid-transition (depending on
// the state of the PaginationModel).
int current_page = std::max(0, pagination_model_.selected_page());
int target_page = current_page;
double progress = 1;
if (pagination_model_.has_transition()) {
const PaginationModel::Transition& transition =
pagination_model_.transition();
if (pagination_model_.is_valid_page(transition.target_page)) {
target_page = transition.target_page;
progress = transition.progress;
}
}
NotifyCustomLauncherPageAnimationChanged(progress, current_page, target_page);
AppListModel::State current_state = GetStateForPageIndex(current_page);
AppListModel::State target_state = GetStateForPageIndex(target_page);
// Update app list pages.
for (AppListPage* page : app_list_pages_) {
gfx::Rect to_rect = page->GetPageBoundsForState(target_state);
gfx::Rect from_rect = page->GetPageBoundsForState(current_state);
if (from_rect == to_rect)
continue;
// Animate linearly (the PaginationModel handles easing).
gfx::Rect bounds(
gfx::Tween::RectValueBetween(progress, from_rect, to_rect));
page->SetBoundsRect(bounds);
page->OnAnimationUpdated(progress, current_state, target_state);
}
// Update the search box.
UpdateSearchBox(progress, current_state, target_state);
}
void ContentsView::UpdateSearchBox(double progress,
AppListModel::State current_state,
AppListModel::State target_state) {
AppListPage* from_page = GetPageView(GetPageIndexForState(current_state));
AppListPage* to_page = GetPageView(GetPageIndexForState(target_state));
SearchBoxView* search_box = GetSearchBoxView();
gfx::Rect search_box_from(from_page->GetSearchBoxBounds());
gfx::Rect search_box_to(to_page->GetSearchBoxBounds());
gfx::Rect search_box_rect =
gfx::Tween::RectValueBetween(progress, search_box_from, search_box_to);
int original_z_height = from_page->GetSearchBoxZHeight();
int target_z_height = to_page->GetSearchBoxZHeight();
if (original_z_height != target_z_height) {
gfx::ShadowValue original_shadow = GetShadowForZHeight(original_z_height);
gfx::ShadowValue target_shadow = GetShadowForZHeight(target_z_height);
gfx::Vector2d offset(gfx::Tween::LinearIntValueBetween(
progress, original_shadow.x(), target_shadow.x()),
gfx::Tween::LinearIntValueBetween(
progress, original_shadow.y(), target_shadow.y()));
search_box->SetShadow(gfx::ShadowValue(
offset, gfx::Tween::LinearIntValueBetween(
progress, original_shadow.blur(), target_shadow.blur()),
gfx::Tween::ColorValueBetween(progress, original_shadow.color(),
target_shadow.color())));
}
search_box->GetWidget()->SetBounds(
search_box->GetViewBoundsForSearchBoxContentsBounds(
ConvertRectToWidget(search_box_rect)));
}
PaginationModel* ContentsView::GetAppsPaginationModel() {
return apps_container_view_->apps_grid_view()->pagination_model();
}
void ContentsView::ShowFolderContent(AppListFolderItem* item) {
apps_container_view_->ShowActiveFolder(item);
}
void ContentsView::Prerender() {
apps_container_view_->apps_grid_view()->Prerender();
}
AppListPage* ContentsView::GetPageView(int index) const {
DCHECK_GT(static_cast<int>(app_list_pages_.size()), index);
return app_list_pages_[index];
}
SearchBoxView* ContentsView::GetSearchBoxView() const {
return app_list_main_view_->search_box_view();
}
int ContentsView::AddLauncherPage(AppListPage* view) {
view->set_contents_view(this);
AddChildView(view);
app_list_pages_.push_back(view);
return app_list_pages_.size() - 1;
}
int ContentsView::AddLauncherPage(AppListPage* view,
AppListModel::State state) {
int page_index = AddLauncherPage(view);
bool success =
state_to_view_.insert(std::make_pair(state, page_index)).second;
success = success &&
view_to_state_.insert(std::make_pair(page_index, state)).second;
// There shouldn't be duplicates in either map.
DCHECK(success);
return page_index;
}
gfx::Rect ContentsView::GetDefaultSearchBoxBounds() const {
gfx::Rect search_box_bounds(0, 0, GetDefaultContentsSize().width(),
GetSearchBoxView()->GetPreferredSize().height());
if (switches::IsExperimentalAppListEnabled()) {
search_box_bounds.set_y(kExperimentalSearchBoxPadding);
search_box_bounds.Inset(kExperimentalSearchBoxPadding, 0);
}
return search_box_bounds;
}
gfx::Rect ContentsView::GetSearchBoxBoundsForState(
AppListModel::State state) const {
AppListPage* page = GetPageView(GetPageIndexForState(state));
return page->GetSearchBoxBounds();
}
gfx::Rect ContentsView::GetDefaultContentsBounds() const {
gfx::Rect bounds(gfx::Point(0, GetDefaultSearchBoxBounds().bottom()),
GetDefaultContentsSize());
return bounds;
}
bool ContentsView::Back() {
AppListModel::State state = view_to_state_[GetActivePageIndex()];
switch (state) {
case AppListModel::STATE_START:
// Close the app list when Back() is called from the start page.
return false;
case AppListModel::STATE_CUSTOM_LAUNCHER_PAGE:
if (app_list_main_view_->model()->PopCustomLauncherPageSubpage())
app_list_main_view_->view_delegate()->CustomLauncherPagePopSubpage();
else
SetActiveState(AppListModel::STATE_START);
break;
case AppListModel::STATE_APPS:
if (apps_container_view_->IsInFolderView())
apps_container_view_->app_list_folder_view()->CloseFolderPage();
else
SetActiveState(AppListModel::STATE_START);
break;
case AppListModel::STATE_SEARCH_RESULTS:
GetSearchBoxView()->ClearSearch();
ShowSearchResults(false);
break;
case AppListModel::INVALID_STATE: // Falls through.
NOTREACHED();
break;
}
return true;
}
gfx::Size ContentsView::GetDefaultContentsSize() const {
return apps_container_view_->apps_grid_view()->GetPreferredSize();
}
gfx::Size ContentsView::GetPreferredSize() const {
gfx::Rect search_box_bounds = GetDefaultSearchBoxBounds();
gfx::Rect default_contents_bounds = GetDefaultContentsBounds();
gfx::Vector2d bottom_right =
search_box_bounds.bottom_right().OffsetFromOrigin();
bottom_right.SetToMax(
default_contents_bounds.bottom_right().OffsetFromOrigin());
return gfx::Size(bottom_right.x(), bottom_right.y());
}
void ContentsView::Layout() {
// Immediately finish all current animations.
pagination_model_.FinishAnimation();
double progress =
IsStateActive(AppListModel::STATE_CUSTOM_LAUNCHER_PAGE) ? 1 : 0;
// Notify the custom launcher page that the active page has changed.
app_list_main_view_->view_delegate()->CustomLauncherPageAnimationChanged(
progress);
if (GetContentsBounds().IsEmpty())
return;
for (AppListPage* page : app_list_pages_) {
page->SetBoundsRect(page->GetPageBoundsForState(GetActiveState()));
}
// The search box is contained in a widget so set the bounds of the widget
// rather than the SearchBoxView.
views::Widget* search_box_widget = GetSearchBoxView()->GetWidget();
if (search_box_widget && search_box_widget != GetWidget()) {
gfx::Rect search_box_bounds = GetSearchBoxBoundsForState(GetActiveState());
search_box_widget->SetBounds(ConvertRectToWidget(
GetSearchBoxView()->GetViewBoundsForSearchBoxContentsBounds(
search_box_bounds)));
}
}
bool ContentsView::OnKeyPressed(const ui::KeyEvent& event) {
bool handled = app_list_pages_[GetActivePageIndex()]->OnKeyPressed(event);
if (!handled) {
if (event.key_code() == ui::VKEY_TAB && event.IsShiftDown()) {
GetSearchBoxView()->MoveTabFocus(true);
handled = true;
}
}
return handled;
}
void ContentsView::TotalPagesChanged() {
}
void ContentsView::SelectedPageChanged(int old_selected, int new_selected) {
if (old_selected >= 0)
app_list_pages_[old_selected]->OnHidden();
if (new_selected >= 0)
app_list_pages_[new_selected]->OnShown();
}
void ContentsView::TransitionStarted() {
}
void ContentsView::TransitionChanged() {
UpdatePageBounds();
}
} // namespace app_list
| 35.171429 | 80 | 0.72914 | [
"vector",
"model"
] |
78009437c7182110a1460d974e58c5d81845d3ba | 4,785 | cc | C++ | xic/src/edit/undolist_setif.cc | wrcad/xictools | f46ba6d42801426739cc8b2940a809b74f1641e2 | [
"Apache-2.0"
] | 73 | 2017-10-26T12:40:24.000Z | 2022-03-02T16:59:43.000Z | xic/src/edit/undolist_setif.cc | chris-ayala/xictools | 4ea72c118679caed700dab3d49a8d36445acaec3 | [
"Apache-2.0"
] | 12 | 2017-11-01T10:18:22.000Z | 2022-03-20T19:35:36.000Z | xic/src/edit/undolist_setif.cc | chris-ayala/xictools | 4ea72c118679caed700dab3d49a8d36445acaec3 | [
"Apache-2.0"
] | 34 | 2017-10-06T17:04:21.000Z | 2022-02-18T16:22:03.000Z |
/*========================================================================*
* *
* Distributed by Whiteley Research Inc., Sunnyvale, California, USA *
* http://wrcad.com *
* Copyright (C) 2017 Whiteley Research Inc., all rights reserved. *
* Author: Stephen R. Whiteley, except as indicated. *
* *
* As fully as possible recognizing licensing terms and conditions *
* imposed by earlier work from which this work was derived, if any, *
* this work is released under the Apache License, Version 2.0 (the *
* "License"). You may not use this file except in compliance with *
* the License, and compliance with inherited licenses which are *
* specified in a sub-header below this one if applicable. A copy *
* of the License is provided with this distribution, or you may *
* obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* See the License for the specific language governing permissions *
* and limitations under the License. *
* *
* 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 NON- *
* INFRINGEMENT. IN NO EVENT SHALL WHITELEY RESEARCH INCORPORATED *
* OR STEPHEN R. WHITELEY 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. *
* *
*========================================================================*
* XicTools Integrated Circuit Design System *
* *
* Xic Integrated Circuit Layout and Schematic Editor *
* *
*========================================================================*
$Id:$
*========================================================================*/
#include "main.h"
#include "edit.h"
#include "undolist.h"
//-----------------------------------------------------------------------------
// CD configuration
namespace {
// If create is true, record the hypertext entry in the history list.
// If create is false, Remove all references to ent in the history
// list. Unlike objects and properties, hypertext entries are owned
// by CD and should not be freed by the application.
//
void
ifRecordHYent(hyEnt *ent, bool create)
{
Ulist()->RecordHYent(ent, create);
}
// An object (oldesc) is being deleted, and being replaced by newdesc.
// Either olddesc or newdesc can be null.
//
// This is called when the changes are to be recorded in a history
// (undo) list. It is up to the application to actually delete old
// objects.
//
void
ifRecordObjectChange(CDs *sdesc, CDo *olddesc, CDo *newdesc)
{
Ulist()->RecordObjectChange(sdesc, olddesc, newdesc);
}
// A property (oldp) is being deleted, and being replaced by newp.
// Either oldp or newp can be null. If odesc is not null, the
// properties apply to that object, otherwise they apply to sdesc.
//
// This is called when the changes are to be recorded in a history
// (undo) list. It is up to the application to actually delete old
// properties.
//
void
ifRecordPrptyChange(CDs *sdesc, CDo *odesc, CDp *oldp, CDp *newp)
{
Ulist()->RecordPrptyChange(sdesc, odesc, oldp, newp);
}
}
//-----------------------------------------------------------------------------
// GEO configuration
// use ifRecordObjectChange from above
void
cUndoList::setupInterface()
{
CD()->RegisterIfRecordHYent(ifRecordHYent);
CD()->RegisterIfRecordObjectChange(ifRecordObjectChange);
CD()->RegisterIfRecordPrptyChange(ifRecordPrptyChange);
GEO()->RegisterIfRecordObjectChange(ifRecordObjectChange);
}
| 45.141509 | 79 | 0.489655 | [
"object"
] |
78019a9d512ad9196473ccfb52a53f7f0a7a5b3e | 8,421 | cpp | C++ | code/Graphics/Modeling/WavefrontMaterial.cpp | jpike/SoftwareRenderer | 8c9becd44dbfccbdf48a49479f696a22ffbeb465 | [
"Unlicense"
] | null | null | null | code/Graphics/Modeling/WavefrontMaterial.cpp | jpike/SoftwareRenderer | 8c9becd44dbfccbdf48a49479f696a22ffbeb465 | [
"Unlicense"
] | null | null | null | code/Graphics/Modeling/WavefrontMaterial.cpp | jpike/SoftwareRenderer | 8c9becd44dbfccbdf48a49479f696a22ffbeb465 | [
"Unlicense"
] | null | null | null | #include <fstream>
#include <sstream>
#include <string>
#include "Graphics/Modeling/WavefrontMaterial.h"
namespace GRAPHICS::MODELING
{
/// Attempts to load the material from the specified .mtl file.
/// @param[in] mtl_filepath - The path of the .mtl file to load.
/// @return The material, if successfull loaded; null otherwise.
std::shared_ptr<Material> WavefrontMaterial::Load(const std::filesystem::path& mtl_filepath)
{
// OPEN THE FILE.
std::ifstream material_file(mtl_filepath);
bool material_file_opened = material_file.is_open();
if (!material_file_opened)
{
return nullptr;
}
// READ IN THE DATA FROM THE .OBJ FILE.
// Note that this reading may not yet be fully robust.
// It only handles the absolute minimum as currently needed for basic demos.
constexpr char SPACE_SEPARATOR = ' ';
/// @todo Handle multiple materials?
auto material = std::make_shared<Material>();
/// @todo Handle different shading models?
material->Shading = ShadingType::MATERIAL;
std::string line;
while (std::getline(material_file, line))
{
// SKIP OVER ANY BLANK LINES.
bool is_blank_line = line.empty();
if (is_blank_line)
{
continue;
}
// SKIP OVER ANY COMMENT LINES.
constexpr char MTL_COMMENT_CHARACTER = '#';
bool is_comment_line = line.starts_with(MTL_COMMENT_CHARACTER);
if (is_comment_line)
{
continue;
}
// CHECK IF A NEW MATERIAL IS BEING DEFINED.
/// @todo Should we track this?
const std::string NEW_MATERIAL_KEYWORD = "newmtl";
bool is_new_material_line = line.starts_with(NEW_MATERIAL_KEYWORD);
if (is_new_material_line)
{
continue;
}
// READ IN ANY SPECULAR EXPONENT.
const std::string SPECULAR_EXPONENT_INDICATOR = "Ns";
bool is_specular_exponent_line = line.starts_with(SPECULAR_EXPONENT_INDICATOR);
if (is_specular_exponent_line)
{
/// @todo Make this more efficient.
std::istringstream line_data(line);
// Skip past the data type indicator.
std::string data_type_indicator;
line_data >> data_type_indicator;
line_data >> material->SpecularPower;
continue;
}
// READ IN ANY AMBIENT COLOR.
const std::string AMBIENT_COLOR_INDICATOR = "Ka";
bool is_ambient_color_line = line.starts_with(AMBIENT_COLOR_INDICATOR);
if (is_ambient_color_line)
{
/// @todo Make this more efficient.
std::istringstream line_data(line);
// Skip past the color type indicator.
std::string color_type_indicator;
line_data >> color_type_indicator;
Color color = Color::BLACK;
line_data >> color.Red;
line_data >> color.Green;
line_data >> color.Blue;
material->AmbientColor = color;
continue;
}
// READ IN ANY DIFFUSE COLOR.
const std::string DIFFUSE_COLOR_INDICATOR = "Kd";
bool is_diffuse_color_line = line.starts_with(DIFFUSE_COLOR_INDICATOR);
if (is_diffuse_color_line)
{
/// @todo Make this more efficient.
std::istringstream line_data(line);
// Skip past the color type indicator.
std::string color_type_indicator;
line_data >> color_type_indicator;
Color color = Color::BLACK;
line_data >> color.Red;
line_data >> color.Green;
line_data >> color.Blue;
material->DiffuseColor = color;
#if 0
/// @todo Using this for the material color is just a hack for now.
/// Adding duplicates to handle triangles for some cases.
material->WireframeColor = color;
material->FaceColor = color;
material->VertexFaceColors.push_back(color);
material->VertexFaceColors.push_back(color);
material->VertexFaceColors.push_back(color);
material->VertexWireframeColors.push_back(color);
material->VertexWireframeColors.push_back(color);
material->VertexWireframeColors.push_back(color);
#endif
continue;
}
// READ IN ANY SPECULAR COLOR.
const std::string SPECULAR_COLOR_INDICATOR = "Ks";
bool is_specular_color_line = line.starts_with(SPECULAR_COLOR_INDICATOR);
if (is_specular_color_line)
{
/// @todo Make this more efficient.
std::istringstream line_data(line);
// Skip past the color type indicator.
std::string color_type_indicator;
line_data >> color_type_indicator;
Color color = Color::BLACK;
line_data >> color.Red;
line_data >> color.Green;
line_data >> color.Blue;
material->SpecularColor = color;
continue;
}
// READ IN ANY EMISSIVE COLOR.
const std::string EMISSIVE_COLOR_INDICATOR = "Ke";
bool is_emissive_color_line = line.starts_with(EMISSIVE_COLOR_INDICATOR);
if (is_emissive_color_line)
{
/// @todo Make this more efficient.
std::istringstream line_data(line);
// Skip past the color type indicator.
std::string color_type_indicator;
line_data >> color_type_indicator;
Color color = Color::BLACK;
line_data >> color.Red;
line_data >> color.Green;
line_data >> color.Blue;
material->EmissiveColor = color;
continue;
}
/// @todo Not sure what "Ni" means.
/// https://en.wikipedia.org/wiki/Wavefront_.obj_file#Material_template_library
/// says optical density (index of refraction).
// READ IN ANY OPAQUENESS LEVEL.
constexpr char DISSOLVED_LEVEL_INDICATOR = 'd';
bool is_dissolved_level_line = line.starts_with(DISSOLVED_LEVEL_INDICATOR);
if (is_dissolved_level_line)
{
/// @todo Make this more efficient.
std::istringstream line_data(line);
// Skip past the data type indicator.
std::string data_type_indicator;
line_data >> data_type_indicator;
// UPDATE THE ALPHA FOR ALL COLORS.
float alpha = Color::MAX_FLOAT_COLOR_COMPONENT;
line_data >> alpha;
/// @todo Using this for the material color is just a hack for now.
/// Adding duplicates to handle triangles for some cases.
material->WireframeColor.Alpha = alpha;
material->FaceColor.Alpha = alpha;
for (auto& color : material->VertexFaceColors)
{
color.Alpha = alpha;
}
for (auto& color : material->VertexWireframeColors)
{
color.Alpha = alpha;
}
material->AmbientColor.Alpha = alpha;
material->DiffuseColor.Alpha = alpha;
material->SpecularColor.Alpha = alpha;
material->EmissiveColor.Alpha = alpha;
continue;
}
// READ IN THE ILLUMINATION MODEL.
const std::string ILLUMINATION_MODEL_INDICATOR = "illum";
bool is_illumination_model_line = line.starts_with(ILLUMINATION_MODEL_INDICATOR);
if (is_illumination_model_line)
{
/// @todo
continue;
}
}
// RETURN THE MATERIAL.
return material;
}
}
| 38.104072 | 96 | 0.545778 | [
"model"
] |
78023bf6a7131362a05228278d74c3951a70320e | 35,323 | hpp | C++ | include/GlobalNamespace/AnnotatedBeatmapLevelCollectionsGridView.hpp | sc2ad/BeatSaber-Quest-Codegen | ba8acaae541cfe1161e05fbc3bf87f4bc46bc4ab | [
"Unlicense"
] | 23 | 2020-08-07T04:09:00.000Z | 2022-03-31T22:10:29.000Z | include/GlobalNamespace/AnnotatedBeatmapLevelCollectionsGridView.hpp | sc2ad/BeatSaber-Quest-Codegen | ba8acaae541cfe1161e05fbc3bf87f4bc46bc4ab | [
"Unlicense"
] | 6 | 2021-09-29T23:47:31.000Z | 2022-03-30T20:49:23.000Z | include/GlobalNamespace/AnnotatedBeatmapLevelCollectionsGridView.hpp | sc2ad/BeatSaber-Quest-Codegen | ba8acaae541cfe1161e05fbc3bf87f4bc46bc4ab | [
"Unlicense"
] | 17 | 2020-08-20T19:36:52.000Z | 2022-03-30T18:28:24.000Z | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
#include "extern/beatsaber-hook/shared/utils/byref.hpp"
// Including type: UnityEngine.MonoBehaviour
#include "UnityEngine/MonoBehaviour.hpp"
// Including type: UnityEngine.EventSystems.IPointerEnterHandler
#include "UnityEngine/EventSystems/IPointerEnterHandler.hpp"
// Including type: UnityEngine.EventSystems.IPointerExitHandler
#include "UnityEngine/EventSystems/IPointerExitHandler.hpp"
// Including type: GridView/IDataSource
#include "GlobalNamespace/GridView_IDataSource.hpp"
// Including type: HMUI.SelectableCell
#include "HMUI/SelectableCell.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"
#include "extern/beatsaber-hook/shared/utils/typedefs-array.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: GlobalNamespace
namespace GlobalNamespace {
// Skipping declaration: GridView because it is already included!
// Forward declaring type: PageControl
class PageControl;
// Forward declaring type: AnnotatedBeatmapLevelCollectionsGridViewAnimator
class AnnotatedBeatmapLevelCollectionsGridViewAnimator;
// Forward declaring type: AnnotatedBeatmapLevelCollectionCell
class AnnotatedBeatmapLevelCollectionCell;
// Forward declaring type: AdditionalContentModel
class AdditionalContentModel;
// Forward declaring type: IVRPlatformHelper
class IVRPlatformHelper;
// Forward declaring type: IAnnotatedBeatmapLevelCollection
class IAnnotatedBeatmapLevelCollection;
}
// Forward declaring namespace: System
namespace System {
// Forward declaring type: Action
class Action;
// Forward declaring type: Action`1<T>
template<typename T>
class Action_1;
}
// Forward declaring namespace: System::Collections::Generic
namespace System::Collections::Generic {
// Forward declaring type: HashSet`1<T>
template<typename T>
class HashSet_1;
// Forward declaring type: IReadOnlyList`1<T>
template<typename T>
class IReadOnlyList_1;
}
// Forward declaring namespace: UnityEngine::EventSystems
namespace UnityEngine::EventSystems {
// Forward declaring type: PointerEventData
class PointerEventData;
}
// Completed forward declares
// Type namespace:
namespace GlobalNamespace {
// Forward declaring type: AnnotatedBeatmapLevelCollectionsGridView
class AnnotatedBeatmapLevelCollectionsGridView;
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView);
DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView*, "", "AnnotatedBeatmapLevelCollectionsGridView");
// Type namespace:
namespace GlobalNamespace {
// Size: 0x8C
#pragma pack(push, 1)
// Autogenerated type: AnnotatedBeatmapLevelCollectionsGridView
// [TokenAttribute] Offset: FFFFFFFF
class AnnotatedBeatmapLevelCollectionsGridView : public UnityEngine::MonoBehaviour/*, public UnityEngine::EventSystems::IPointerEnterHandler, public UnityEngine::EventSystems::IPointerExitHandler, public GlobalNamespace::GridView::IDataSource*/ {
public:
#ifdef USE_CODEGEN_FIELDS
public:
#else
protected:
#endif
// private GridView _gridView
// Size: 0x8
// Offset: 0x18
GlobalNamespace::GridView* gridView;
// Field size check
static_assert(sizeof(GlobalNamespace::GridView*) == 0x8);
// private PageControl _pageControl
// Size: 0x8
// Offset: 0x20
GlobalNamespace::PageControl* pageControl;
// Field size check
static_assert(sizeof(GlobalNamespace::PageControl*) == 0x8);
// [SpaceAttribute] Offset: 0xF11CE0
// private AnnotatedBeatmapLevelCollectionsGridViewAnimator _animator
// Size: 0x8
// Offset: 0x28
GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridViewAnimator* animator;
// Field size check
static_assert(sizeof(GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridViewAnimator*) == 0x8);
// [SpaceAttribute] Offset: 0xF11D18
// private AnnotatedBeatmapLevelCollectionCell _cellPrefab
// Size: 0x8
// Offset: 0x30
GlobalNamespace::AnnotatedBeatmapLevelCollectionCell* cellPrefab;
// Field size check
static_assert(sizeof(GlobalNamespace::AnnotatedBeatmapLevelCollectionCell*) == 0x8);
// private System.Single _cellWidth
// Size: 0x4
// Offset: 0x38
float cellWidth;
// Field size check
static_assert(sizeof(float) == 0x4);
// private System.Single _cellHeight
// Size: 0x4
// Offset: 0x3C
float cellHeight;
// Field size check
static_assert(sizeof(float) == 0x4);
// [SpaceAttribute] Offset: 0xF11D70
// private System.String[] _promoPackIDStrings
// Size: 0x8
// Offset: 0x40
::ArrayW<::Il2CppString*> promoPackIDStrings;
// Field size check
static_assert(sizeof(::ArrayW<::Il2CppString*>) == 0x8);
// [InjectAttribute] Offset: 0xF11DA8
// private readonly AdditionalContentModel _additionalContentModel
// Size: 0x8
// Offset: 0x48
GlobalNamespace::AdditionalContentModel* additionalContentModel;
// Field size check
static_assert(sizeof(GlobalNamespace::AdditionalContentModel*) == 0x8);
// [InjectAttribute] Offset: 0xF11DB8
// private readonly IVRPlatformHelper _vrPlatformHelper
// Size: 0x8
// Offset: 0x50
GlobalNamespace::IVRPlatformHelper* vrPlatformHelper;
// Field size check
static_assert(sizeof(GlobalNamespace::IVRPlatformHelper*) == 0x8);
// private System.Action didOpenAnnotatedBeatmapLevelCollectionEvent
// Size: 0x8
// Offset: 0x58
System::Action* didOpenAnnotatedBeatmapLevelCollectionEvent;
// Field size check
static_assert(sizeof(System::Action*) == 0x8);
// private System.Action didCloseAnnotatedBeatmapLevelCollectionEvent
// Size: 0x8
// Offset: 0x60
System::Action* didCloseAnnotatedBeatmapLevelCollectionEvent;
// Field size check
static_assert(sizeof(System::Action*) == 0x8);
// private System.Action`1<IAnnotatedBeatmapLevelCollection> didSelectAnnotatedBeatmapLevelCollectionEvent
// Size: 0x8
// Offset: 0x68
System::Action_1<GlobalNamespace::IAnnotatedBeatmapLevelCollection*>* didSelectAnnotatedBeatmapLevelCollectionEvent;
// Field size check
static_assert(sizeof(System::Action_1<GlobalNamespace::IAnnotatedBeatmapLevelCollection*>*) == 0x8);
// private System.Boolean _isInitialized
// Size: 0x1
// Offset: 0x70
bool isInitialized;
// Field size check
static_assert(sizeof(bool) == 0x1);
// private System.Boolean _isHovering
// Size: 0x1
// Offset: 0x71
bool isHovering;
// Field size check
static_assert(sizeof(bool) == 0x1);
// Padding between fields: isHovering and: promoPackIDs
char __padding13[0x6] = {};
// private System.Collections.Generic.HashSet`1<System.String> _promoPackIDs
// Size: 0x8
// Offset: 0x78
System::Collections::Generic::HashSet_1<::Il2CppString*>* promoPackIDs;
// Field size check
static_assert(sizeof(System::Collections::Generic::HashSet_1<::Il2CppString*>*) == 0x8);
// private System.Collections.Generic.IReadOnlyList`1<IAnnotatedBeatmapLevelCollection> _annotatedBeatmapLevelCollections
// Size: 0x8
// Offset: 0x80
System::Collections::Generic::IReadOnlyList_1<GlobalNamespace::IAnnotatedBeatmapLevelCollection*>* annotatedBeatmapLevelCollections;
// Field size check
static_assert(sizeof(System::Collections::Generic::IReadOnlyList_1<GlobalNamespace::IAnnotatedBeatmapLevelCollection*>*) == 0x8);
// private System.Int32 _selectedCellIndex
// Size: 0x4
// Offset: 0x88
int selectedCellIndex;
// Field size check
static_assert(sizeof(int) == 0x4);
public:
// Creating interface conversion operator: operator UnityEngine::EventSystems::IPointerEnterHandler
operator UnityEngine::EventSystems::IPointerEnterHandler() noexcept {
return *reinterpret_cast<UnityEngine::EventSystems::IPointerEnterHandler*>(this);
}
// Creating interface conversion operator: operator UnityEngine::EventSystems::IPointerExitHandler
operator UnityEngine::EventSystems::IPointerExitHandler() noexcept {
return *reinterpret_cast<UnityEngine::EventSystems::IPointerExitHandler*>(this);
}
// Creating interface conversion operator: operator GlobalNamespace::GridView::IDataSource
operator GlobalNamespace::GridView::IDataSource() noexcept {
return *reinterpret_cast<GlobalNamespace::GridView::IDataSource*>(this);
}
// Deleting conversion operator: operator System::IntPtr
constexpr operator System::IntPtr() const noexcept = delete;
// Get instance field reference: private GridView _gridView
GlobalNamespace::GridView*& dyn__gridView();
// Get instance field reference: private PageControl _pageControl
GlobalNamespace::PageControl*& dyn__pageControl();
// Get instance field reference: private AnnotatedBeatmapLevelCollectionsGridViewAnimator _animator
GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridViewAnimator*& dyn__animator();
// Get instance field reference: private AnnotatedBeatmapLevelCollectionCell _cellPrefab
GlobalNamespace::AnnotatedBeatmapLevelCollectionCell*& dyn__cellPrefab();
// Get instance field reference: private System.Single _cellWidth
float& dyn__cellWidth();
// Get instance field reference: private System.Single _cellHeight
float& dyn__cellHeight();
// Get instance field reference: private System.String[] _promoPackIDStrings
::ArrayW<::Il2CppString*>& dyn__promoPackIDStrings();
// Get instance field reference: private readonly AdditionalContentModel _additionalContentModel
GlobalNamespace::AdditionalContentModel*& dyn__additionalContentModel();
// Get instance field reference: private readonly IVRPlatformHelper _vrPlatformHelper
GlobalNamespace::IVRPlatformHelper*& dyn__vrPlatformHelper();
// Get instance field reference: private System.Action didOpenAnnotatedBeatmapLevelCollectionEvent
System::Action*& dyn_didOpenAnnotatedBeatmapLevelCollectionEvent();
// Get instance field reference: private System.Action didCloseAnnotatedBeatmapLevelCollectionEvent
System::Action*& dyn_didCloseAnnotatedBeatmapLevelCollectionEvent();
// Get instance field reference: private System.Action`1<IAnnotatedBeatmapLevelCollection> didSelectAnnotatedBeatmapLevelCollectionEvent
System::Action_1<GlobalNamespace::IAnnotatedBeatmapLevelCollection*>*& dyn_didSelectAnnotatedBeatmapLevelCollectionEvent();
// Get instance field reference: private System.Boolean _isInitialized
bool& dyn__isInitialized();
// Get instance field reference: private System.Boolean _isHovering
bool& dyn__isHovering();
// Get instance field reference: private System.Collections.Generic.HashSet`1<System.String> _promoPackIDs
System::Collections::Generic::HashSet_1<::Il2CppString*>*& dyn__promoPackIDs();
// Get instance field reference: private System.Collections.Generic.IReadOnlyList`1<IAnnotatedBeatmapLevelCollection> _annotatedBeatmapLevelCollections
System::Collections::Generic::IReadOnlyList_1<GlobalNamespace::IAnnotatedBeatmapLevelCollection*>*& dyn__annotatedBeatmapLevelCollections();
// Get instance field reference: private System.Int32 _selectedCellIndex
int& dyn__selectedCellIndex();
// public System.Void add_didOpenAnnotatedBeatmapLevelCollectionEvent(System.Action value)
// Offset: 0x26175EC
void add_didOpenAnnotatedBeatmapLevelCollectionEvent(System::Action* value);
// public System.Void remove_didOpenAnnotatedBeatmapLevelCollectionEvent(System.Action value)
// Offset: 0x2617690
void remove_didOpenAnnotatedBeatmapLevelCollectionEvent(System::Action* value);
// public System.Void add_didCloseAnnotatedBeatmapLevelCollectionEvent(System.Action value)
// Offset: 0x2617734
void add_didCloseAnnotatedBeatmapLevelCollectionEvent(System::Action* value);
// public System.Void remove_didCloseAnnotatedBeatmapLevelCollectionEvent(System.Action value)
// Offset: 0x26177D8
void remove_didCloseAnnotatedBeatmapLevelCollectionEvent(System::Action* value);
// public System.Void add_didSelectAnnotatedBeatmapLevelCollectionEvent(System.Action`1<IAnnotatedBeatmapLevelCollection> value)
// Offset: 0x261787C
void add_didSelectAnnotatedBeatmapLevelCollectionEvent(System::Action_1<GlobalNamespace::IAnnotatedBeatmapLevelCollection*>* value);
// public System.Void remove_didSelectAnnotatedBeatmapLevelCollectionEvent(System.Action`1<IAnnotatedBeatmapLevelCollection> value)
// Offset: 0x2617920
void remove_didSelectAnnotatedBeatmapLevelCollectionEvent(System::Action_1<GlobalNamespace::IAnnotatedBeatmapLevelCollection*>* value);
// public System.Void SetData(System.Collections.Generic.IReadOnlyList`1<IAnnotatedBeatmapLevelCollection> annotatedBeatmapLevelCollections)
// Offset: 0x26179C4
void SetData(System::Collections::Generic::IReadOnlyList_1<GlobalNamespace::IAnnotatedBeatmapLevelCollection*>* annotatedBeatmapLevelCollections);
// private System.Void Init()
// Offset: 0x2617A64
void Init();
// protected System.Void OnEnable()
// Offset: 0x2617C0C
void OnEnable();
// protected System.Void OnDisable()
// Offset: 0x2617D2C
void OnDisable();
// public System.Void Show()
// Offset: 0x2617E50
void Show();
// public System.Void Hide()
// Offset: 0x2617E78
void Hide();
// public System.Void CancelAsyncOperations()
// Offset: 0x2617EA0
void CancelAsyncOperations();
// public System.Void RefreshAvailability()
// Offset: 0x2617FDC
void RefreshAvailability();
// public System.Void SelectAndScrollToCellWithIdx(System.Int32 idx)
// Offset: 0x2618220
void SelectAndScrollToCellWithIdx(int idx);
// public System.Void OnPointerEnter(UnityEngine.EventSystems.PointerEventData eventData)
// Offset: 0x261852C
void OnPointerEnter(UnityEngine::EventSystems::PointerEventData* eventData);
// public System.Void OnPointerExit(UnityEngine.EventSystems.PointerEventData eventData)
// Offset: 0x26188D4
void OnPointerExit(UnityEngine::EventSystems::PointerEventData* eventData);
// private System.Void HandleAdditionalContentModelDidInvalidateData()
// Offset: 0x2618C28
void HandleAdditionalContentModelDidInvalidateData();
// private System.Void HandleVRPlatformHelperInputFocusCaptured()
// Offset: 0x2618DA8
void HandleVRPlatformHelperInputFocusCaptured();
// private System.Void HandleCellSelectionDidChange(HMUI.SelectableCell selectableCell, HMUI.SelectableCell/HMUI.TransitionType transition, System.Object changeOwner)
// Offset: 0x2618DF8
void HandleCellSelectionDidChange(HMUI::SelectableCell* selectableCell, HMUI::SelectableCell::TransitionType transition, ::Il2CppObject* changeOwner);
// public System.Int32 GetNumberOfCells()
// Offset: 0x2618CEC
int GetNumberOfCells();
// public System.Single GetCellWidth()
// Offset: 0x2619204
float GetCellWidth();
// public System.Single GetCellHeight()
// Offset: 0x261920C
float GetCellHeight();
// public UnityEngine.MonoBehaviour CellForIdx(GridView gridView, System.Int32 idx)
// Offset: 0x2619214
UnityEngine::MonoBehaviour* CellForIdx(GlobalNamespace::GridView* gridView, int idx);
// public System.Void .ctor()
// Offset: 0x2619570
// 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 AnnotatedBeatmapLevelCollectionsGridView* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<AnnotatedBeatmapLevelCollectionsGridView*, creationType>()));
}
}; // AnnotatedBeatmapLevelCollectionsGridView
#pragma pack(pop)
static check_size<sizeof(AnnotatedBeatmapLevelCollectionsGridView), 136 + sizeof(int)> __GlobalNamespace_AnnotatedBeatmapLevelCollectionsGridViewSizeCheck;
static_assert(sizeof(AnnotatedBeatmapLevelCollectionsGridView) == 0x8C);
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::add_didOpenAnnotatedBeatmapLevelCollectionEvent
// Il2CppName: add_didOpenAnnotatedBeatmapLevelCollectionEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::*)(System::Action*)>(&GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::add_didOpenAnnotatedBeatmapLevelCollectionEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Action")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView*), "add_didOpenAnnotatedBeatmapLevelCollectionEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::remove_didOpenAnnotatedBeatmapLevelCollectionEvent
// Il2CppName: remove_didOpenAnnotatedBeatmapLevelCollectionEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::*)(System::Action*)>(&GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::remove_didOpenAnnotatedBeatmapLevelCollectionEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Action")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView*), "remove_didOpenAnnotatedBeatmapLevelCollectionEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::add_didCloseAnnotatedBeatmapLevelCollectionEvent
// Il2CppName: add_didCloseAnnotatedBeatmapLevelCollectionEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::*)(System::Action*)>(&GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::add_didCloseAnnotatedBeatmapLevelCollectionEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Action")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView*), "add_didCloseAnnotatedBeatmapLevelCollectionEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::remove_didCloseAnnotatedBeatmapLevelCollectionEvent
// Il2CppName: remove_didCloseAnnotatedBeatmapLevelCollectionEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::*)(System::Action*)>(&GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::remove_didCloseAnnotatedBeatmapLevelCollectionEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Action")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView*), "remove_didCloseAnnotatedBeatmapLevelCollectionEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::add_didSelectAnnotatedBeatmapLevelCollectionEvent
// Il2CppName: add_didSelectAnnotatedBeatmapLevelCollectionEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::*)(System::Action_1<GlobalNamespace::IAnnotatedBeatmapLevelCollection*>*)>(&GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::add_didSelectAnnotatedBeatmapLevelCollectionEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "IAnnotatedBeatmapLevelCollection")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView*), "add_didSelectAnnotatedBeatmapLevelCollectionEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::remove_didSelectAnnotatedBeatmapLevelCollectionEvent
// Il2CppName: remove_didSelectAnnotatedBeatmapLevelCollectionEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::*)(System::Action_1<GlobalNamespace::IAnnotatedBeatmapLevelCollection*>*)>(&GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::remove_didSelectAnnotatedBeatmapLevelCollectionEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "IAnnotatedBeatmapLevelCollection")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView*), "remove_didSelectAnnotatedBeatmapLevelCollectionEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::SetData
// Il2CppName: SetData
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::*)(System::Collections::Generic::IReadOnlyList_1<GlobalNamespace::IAnnotatedBeatmapLevelCollection*>*)>(&GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::SetData)> {
static const MethodInfo* get() {
static auto* annotatedBeatmapLevelCollections = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System.Collections.Generic", "IReadOnlyList`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "IAnnotatedBeatmapLevelCollection")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView*), "SetData", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{annotatedBeatmapLevelCollections});
}
};
// Writing MetadataGetter for method: GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::Init
// Il2CppName: Init
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::*)()>(&GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::Init)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView*), "Init", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::OnEnable
// Il2CppName: OnEnable
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::*)()>(&GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::OnEnable)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView*), "OnEnable", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::OnDisable
// Il2CppName: OnDisable
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::*)()>(&GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::OnDisable)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView*), "OnDisable", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::Show
// Il2CppName: Show
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::*)()>(&GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::Show)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView*), "Show", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::Hide
// Il2CppName: Hide
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::*)()>(&GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::Hide)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView*), "Hide", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::CancelAsyncOperations
// Il2CppName: CancelAsyncOperations
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::*)()>(&GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::CancelAsyncOperations)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView*), "CancelAsyncOperations", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::RefreshAvailability
// Il2CppName: RefreshAvailability
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::*)()>(&GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::RefreshAvailability)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView*), "RefreshAvailability", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::SelectAndScrollToCellWithIdx
// Il2CppName: SelectAndScrollToCellWithIdx
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::*)(int)>(&GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::SelectAndScrollToCellWithIdx)> {
static const MethodInfo* get() {
static auto* idx = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView*), "SelectAndScrollToCellWithIdx", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{idx});
}
};
// Writing MetadataGetter for method: GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::OnPointerEnter
// Il2CppName: OnPointerEnter
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::*)(UnityEngine::EventSystems::PointerEventData*)>(&GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::OnPointerEnter)> {
static const MethodInfo* get() {
static auto* eventData = &::il2cpp_utils::GetClassFromName("UnityEngine.EventSystems", "PointerEventData")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView*), "OnPointerEnter", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{eventData});
}
};
// Writing MetadataGetter for method: GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::OnPointerExit
// Il2CppName: OnPointerExit
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::*)(UnityEngine::EventSystems::PointerEventData*)>(&GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::OnPointerExit)> {
static const MethodInfo* get() {
static auto* eventData = &::il2cpp_utils::GetClassFromName("UnityEngine.EventSystems", "PointerEventData")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView*), "OnPointerExit", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{eventData});
}
};
// Writing MetadataGetter for method: GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::HandleAdditionalContentModelDidInvalidateData
// Il2CppName: HandleAdditionalContentModelDidInvalidateData
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::*)()>(&GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::HandleAdditionalContentModelDidInvalidateData)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView*), "HandleAdditionalContentModelDidInvalidateData", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::HandleVRPlatformHelperInputFocusCaptured
// Il2CppName: HandleVRPlatformHelperInputFocusCaptured
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::*)()>(&GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::HandleVRPlatformHelperInputFocusCaptured)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView*), "HandleVRPlatformHelperInputFocusCaptured", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::HandleCellSelectionDidChange
// Il2CppName: HandleCellSelectionDidChange
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::*)(HMUI::SelectableCell*, HMUI::SelectableCell::TransitionType, ::Il2CppObject*)>(&GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::HandleCellSelectionDidChange)> {
static const MethodInfo* get() {
static auto* selectableCell = &::il2cpp_utils::GetClassFromName("HMUI", "SelectableCell")->byval_arg;
static auto* transition = &::il2cpp_utils::GetClassFromName("HMUI", "SelectableCell/TransitionType")->byval_arg;
static auto* changeOwner = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView*), "HandleCellSelectionDidChange", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{selectableCell, transition, changeOwner});
}
};
// Writing MetadataGetter for method: GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::GetNumberOfCells
// Il2CppName: GetNumberOfCells
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::*)()>(&GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::GetNumberOfCells)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView*), "GetNumberOfCells", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::GetCellWidth
// Il2CppName: GetCellWidth
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<float (GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::*)()>(&GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::GetCellWidth)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView*), "GetCellWidth", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::GetCellHeight
// Il2CppName: GetCellHeight
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<float (GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::*)()>(&GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::GetCellHeight)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView*), "GetCellHeight", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::CellForIdx
// Il2CppName: CellForIdx
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<UnityEngine::MonoBehaviour* (GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::*)(GlobalNamespace::GridView*, int)>(&GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::CellForIdx)> {
static const MethodInfo* get() {
static auto* gridView = &::il2cpp_utils::GetClassFromName("", "GridView")->byval_arg;
static auto* idx = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView*), "CellForIdx", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{gridView, idx});
}
};
// Writing MetadataGetter for method: GlobalNamespace::AnnotatedBeatmapLevelCollectionsGridView::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
| 64.812844 | 325 | 0.793449 | [
"object",
"vector"
] |
7804513a73abb315a3c52706a4d6a7f3b1ccd39c | 14,620 | cpp | C++ | QuadGrav/src/checkDerivatives.cpp | lanl/Dendro-GRCA | 8a475b1abd8832c3dfc19d00cc0ec4b9e2789c8a | [
"BSD-3-Clause"
] | 1 | 2021-06-21T08:38:53.000Z | 2021-06-21T08:38:53.000Z | QuadGrav/src/checkDerivatives.cpp | lanl/Dendro-GRCA | 8a475b1abd8832c3dfc19d00cc0ec4b9e2789c8a | [
"BSD-3-Clause"
] | null | null | null | QuadGrav/src/checkDerivatives.cpp | lanl/Dendro-GRCA | 8a475b1abd8832c3dfc19d00cc0ec4b9e2789c8a | [
"BSD-3-Clause"
] | 1 | 2020-09-23T17:09:34.000Z | 2020-09-23T17:09:34.000Z | //
// Created by milinda on 10/5/17.
/**
*@author Milinda Fernando
*School of Computing, University of Utah
*@brief check all teh quadgrav derivs for user specified function.
*/
//
#ifndef SFCSORTBENCH_CHECKDERIVATIVES_H
#define SFCSORTBENCH_CHECKDERIVATIVES_H
#include "iostream"
#include "TreeNode.h"
#include "mesh.h"
#include "derivs.h"
#include <functional>
#include "octUtils.h"
#include "oct2vtk.h"
#define NUM_VARS 10
#define FX 0
#define Dx_FX 1
#define Dy_FX 2
#define Dz_FX 3
#define DxDx_FX 4
#define DxDy_FX 5
#define DxDz_FX 6
#define DyDy_FX 7
#define DyDz_FX 8
#define DzDz_FX 9
int main (int argc, char** argv)
{
MPI_Init(&argc, &argv);
MPI_Comm comm = MPI_COMM_WORLD;
int rank, npes;
MPI_Comm_rank(comm, &rank);
MPI_Comm_size(comm, &npes);
if(argc<4)
{
if(!rank) std::cout<<"Usage: "<<argv[0]<<" maxDepth wavelet_tol partition_tol eleOrder"<<std::endl;
return 0;
}
m_uiMaxDepth=atoi(argv[1]);
double wavelet_tol=atof(argv[2]);
double partition_tol=atof(argv[3]);
unsigned int eOrder=atoi(argv[4]);
if(!rank)
{
std::cout<<YLW<<"maxDepth: "<<m_uiMaxDepth<<NRM<<std::endl;
std::cout<<YLW<<"wavelet_tol: "<<wavelet_tol<<NRM<<std::endl;
std::cout<<YLW<<"partition_tol: "<<partition_tol<<NRM<<std::endl;
std::cout<<YLW<<"eleOrder: "<<eOrder<<NRM<<std::endl;
}
_InitializeHcurve(m_uiDim);
const double d_min=-0.5;
const double d_max=0.5;
std::function<double(double,double,double)> fx[NUM_VARS];
/*fx[FX]=[d_min,d_max](const double x,const double y,const double z){ return sin(2*M_PI*x)*sin(2*M_PI*y)*sin(2*M_PI*z);};
// 1st order derivatives
fx[Dx_FX]=[d_min,d_max](const double x,const double y,const double z){ return (2*M_PI*cos(2*M_PI*x)*sin(2*M_PI*y)*sin(2*M_PI*z));};
fx[Dy_FX]=[d_min,d_max](const double x,const double y,const double z){ return (2*M_PI*sin(2*M_PI*x)*cos(2*M_PI*y)*sin(2*M_PI*z));};
fx[Dz_FX]=[d_min,d_max](const double x,const double y,const double z){ return (2*M_PI*sin(2*M_PI*x)*sin(2*M_PI*y)*cos(2*M_PI*z));};
// 2nd order derivatives
fx[DxDx_FX]=[d_min,d_max](const double x,const double y,const double z){ return (-4*M_PI*M_PI*sin(2*M_PI*x)*sin(2*M_PI*y)*sin(2*M_PI*z));};
fx[DxDy_FX]=[d_min,d_max](const double x,const double y,const double z){ return ( 4*M_PI*M_PI*cos(2*M_PI*x)*cos(2*M_PI*y)*sin(2*M_PI*z));};
fx[DxDz_FX]=[d_min,d_max](const double x,const double y,const double z){ return ( 4*M_PI*M_PI*cos(2*M_PI*x)*sin(2*M_PI*y)*cos(2*M_PI*z));};
fx[DyDy_FX]=[d_min,d_max](const double x,const double y,const double z){ return (-4*M_PI*M_PI*sin(2*M_PI*x)*sin(2*M_PI*y)*sin(2*M_PI*z));};
fx[DxDz_FX]=[d_min,d_max](const double x,const double y,const double z){ return ( 4*M_PI*M_PI*sin(2*M_PI*x)*cos(2*M_PI*y)*cos(2*M_PI*z));};
fx[DzDz_FX]=[d_min,d_max](const double x,const double y,const double z){ return (-4*M_PI*M_PI*sin(2*M_PI*x)*sin(2*M_PI*y)*sin(2*M_PI*z));};*/
fx[FX]=[d_min,d_max](const double x,const double y,const double z){ return sin(2*M_PI*((x/(1u<<m_uiMaxDepth))*(d_max-d_min)+d_min))*sin(2*M_PI*((y/(1u<<m_uiMaxDepth))*(d_max-d_min)+d_min))*sin(2*M_PI*((z/(1u<<m_uiMaxDepth))*(d_max-d_min)+d_min));};
// 1st order derivatives
fx[Dx_FX]=[d_min,d_max](const double x,const double y,const double z){ return (2*M_PI*cos(2*M_PI*((x/(1u<<m_uiMaxDepth))*(d_max-d_min)+d_min))*sin(2*M_PI*((y/(1u<<m_uiMaxDepth))*(d_max-d_min)+d_min))*sin(2*M_PI*((z/(1u<<m_uiMaxDepth))*(d_max-d_min)+d_min)));};
fx[Dy_FX]=[d_min,d_max](const double x,const double y,const double z){ return (2*M_PI*sin(2*M_PI*((x/(1u<<m_uiMaxDepth))*(d_max-d_min)+d_min))*cos(2*M_PI*((y/(1u<<m_uiMaxDepth))*(d_max-d_min)+d_min))*sin(2*M_PI*((z/(1u<<m_uiMaxDepth))*(d_max-d_min)+d_min)));};
fx[Dz_FX]=[d_min,d_max](const double x,const double y,const double z){ return (2*M_PI*sin(2*M_PI*((x/(1u<<m_uiMaxDepth))*(d_max-d_min)+d_min))*sin(2*M_PI*((y/(1u<<m_uiMaxDepth))*(d_max-d_min)+d_min))*cos(2*M_PI*((z/(1u<<m_uiMaxDepth))*(d_max-d_min)+d_min)));};
// 2nd order derivatives
fx[DxDx_FX]=[d_min,d_max](const double x,const double y,const double z){ return (-4*M_PI*M_PI*sin(2*M_PI*((x/(1u<<m_uiMaxDepth))*(d_max-d_min)+d_min))*sin(2*M_PI*((y/(1u<<m_uiMaxDepth))*(d_max-d_min)+d_min))*sin(2*M_PI*((z/(1u<<m_uiMaxDepth))*(d_max-d_min)+d_min)));};
fx[DxDy_FX]=[d_min,d_max](const double x,const double y,const double z){ return ( 4*M_PI*M_PI*cos(2*M_PI*((x/(1u<<m_uiMaxDepth))*(d_max-d_min)+d_min))*cos(2*M_PI*((y/(1u<<m_uiMaxDepth))*(d_max-d_min)+d_min))*sin(2*M_PI*((z/(1u<<m_uiMaxDepth))*(d_max-d_min)+d_min)));};
fx[DxDz_FX]=[d_min,d_max](const double x,const double y,const double z){ return ( 4*M_PI*M_PI*cos(2*M_PI*((x/(1u<<m_uiMaxDepth))*(d_max-d_min)+d_min))*sin(2*M_PI*((y/(1u<<m_uiMaxDepth))*(d_max-d_min)+d_min))*cos(2*M_PI*((z/(1u<<m_uiMaxDepth))*(d_max-d_min)+d_min)));};
fx[DyDy_FX]=[d_min,d_max](const double x,const double y,const double z){ return (-4*M_PI*M_PI*sin(2*M_PI*((x/(1u<<m_uiMaxDepth))*(d_max-d_min)+d_min))*sin(2*M_PI*((y/(1u<<m_uiMaxDepth))*(d_max-d_min)+d_min))*sin(2*M_PI*((z/(1u<<m_uiMaxDepth))*(d_max-d_min)+d_min)));};
fx[DyDz_FX]=[d_min,d_max](const double x,const double y,const double z){ return ( 4*M_PI*M_PI*sin(2*M_PI*((x/(1u<<m_uiMaxDepth))*(d_max-d_min)+d_min))*cos(2*M_PI*((y/(1u<<m_uiMaxDepth))*(d_max-d_min)+d_min))*cos(2*M_PI*((z/(1u<<m_uiMaxDepth))*(d_max-d_min)+d_min)));};
fx[DzDz_FX]=[d_min,d_max](const double x,const double y,const double z){ return (-4*M_PI*M_PI*sin(2*M_PI*((x/(1u<<m_uiMaxDepth))*(d_max-d_min)+d_min))*sin(2*M_PI*((y/(1u<<m_uiMaxDepth))*(d_max-d_min)+d_min))*sin(2*M_PI*((z/(1u<<m_uiMaxDepth))*(d_max-d_min)+d_min)));};
/* std::function<double(double,double,double)> fx1[NUM_VARS];
fx1[FX]=[d_min,d_max](const double x,const double y,const double z){ return (sin(2*M_PI*((x/(1u<<m_uiMaxDepth))*(d_max-d_min)+d_min))*sin(2*M_PI*((y/(1u<<m_uiMaxDepth))*(d_max-d_min)+d_min))*sin(2*M_PI*((z/(1u<<m_uiMaxDepth))*(d_max-d_min)+d_min)));};
fx1[Dx_FX]=[d_min,d_max](const double x,const double y,const double z){ return (2*M_PI*(1.0/(1u<<m_uiMaxDepth)*(d_max-d_min)))*(cos(2*M_PI*((x/(1u<<m_uiMaxDepth))*(d_max-d_min)+d_min))*sin(2*M_PI*((y/(1u<<m_uiMaxDepth))*(d_max-d_min)+d_min))*sin(2*M_PI*((z/(1u<<m_uiMaxDepth))*(d_max-d_min)+d_min)));};
fx1[Dy_FX]=[d_min,d_max](const double x,const double y,const double z){ return (2*M_PI*(1.0/(1u<<m_uiMaxDepth)*(d_max-d_min)))*(sin(2*M_PI*((x/(1u<<m_uiMaxDepth))*(d_max-d_min)+d_min))*cos(2*M_PI*((y/(1u<<m_uiMaxDepth))*(d_max-d_min)+d_min))*sin(2*M_PI*((z/(1u<<m_uiMaxDepth))*(d_max-d_min)+d_min)));};
fx1[Dz_FX]=[d_min,d_max](const double x,const double y,const double z){ return (2*M_PI*(1.0/(1u<<m_uiMaxDepth)*(d_max-d_min)))*(sin(2*M_PI*((x/(1u<<m_uiMaxDepth))*(d_max-d_min)+d_min))*sin(2*M_PI*((y/(1u<<m_uiMaxDepth))*(d_max-d_min)+d_min))*cos(2*M_PI*((z/(1u<<m_uiMaxDepth))*(d_max-d_min)+d_min)));};
fx1[DxDx_FX]=[d_min,d_max](const double x,const double y,const double z){ return (-pow(2*M_PI*((1.0/(1u<<m_uiMaxDepth))*(d_max-d_min)),2)*(sin(2*M_PI*((x/(1u<<m_uiMaxDepth))*(d_max-d_min)+d_min))*sin(2*M_PI*((y/(1u<<m_uiMaxDepth))*(d_max-d_min)+d_min))*sin(2*M_PI*((z/(1u<<m_uiMaxDepth))*(d_max-d_min)+d_min))));};
fx1[DxDy_FX]=[d_min,d_max](const double x,const double y,const double z){ return ( pow(2*M_PI*((1.0/(1u<<m_uiMaxDepth))*(d_max-d_min)),2)*(cos(2*M_PI*((x/(1u<<m_uiMaxDepth))*(d_max-d_min)+d_min))*cos(2*M_PI*((y/(1u<<m_uiMaxDepth))*(d_max-d_min)+d_min))*sin(2*M_PI*((z/(1u<<m_uiMaxDepth))*(d_max-d_min)+d_min))));};
fx1[DxDz_FX]=[d_min,d_max](const double x,const double y,const double z){ return ( pow(2*M_PI*((1.0/(1u<<m_uiMaxDepth))*(d_max-d_min)),2)*(cos(2*M_PI*((x/(1u<<m_uiMaxDepth))*(d_max-d_min)+d_min))*sin(2*M_PI*((y/(1u<<m_uiMaxDepth))*(d_max-d_min)+d_min))*cos(2*M_PI*((z/(1u<<m_uiMaxDepth))*(d_max-d_min)+d_min))));};
fx1[DyDy_FX]=[d_min,d_max](const double x,const double y,const double z){ return (-pow(2*M_PI*((1.0/(1u<<m_uiMaxDepth))*(d_max-d_min)),2)*(sin(2*M_PI*((x/(1u<<m_uiMaxDepth))*(d_max-d_min)+d_min))*sin(2*M_PI*((y/(1u<<m_uiMaxDepth))*(d_max-d_min)+d_min))*sin(2*M_PI*((z/(1u<<m_uiMaxDepth))*(d_max-d_min)+d_min))));};
fx1[DyDz_FX]=[d_min,d_max](const double x,const double y,const double z){ return ( pow(2*M_PI*((1.0/(1u<<m_uiMaxDepth))*(d_max-d_min)),2)*(sin(2*M_PI*((x/(1u<<m_uiMaxDepth))*(d_max-d_min)+d_min))*cos(2*M_PI*((y/(1u<<m_uiMaxDepth))*(d_max-d_min)+d_min))*cos(2*M_PI*((z/(1u<<m_uiMaxDepth))*(d_max-d_min)+d_min))));};
fx1[DzDz_FX]=[d_min,d_max](const double x,const double y,const double z){ return (-pow(2*M_PI*((1.0/(1u<<m_uiMaxDepth))*(d_max-d_min)),2)*(sin(2*M_PI*((x/(1u<<m_uiMaxDepth))*(d_max-d_min)+d_min))*sin(2*M_PI*((y/(1u<<m_uiMaxDepth))*(d_max-d_min)+d_min))*sin(2*M_PI*((z/(1u<<m_uiMaxDepth))*(d_max-d_min)+d_min))));};*/
ot::TreeNode root(m_uiDim,m_uiMaxDepth);
std::vector<ot::TreeNode> grid;
function2Octree(fx[FX],grid,m_uiMaxDepth,wavelet_tol,eOrder,comm);
std::vector<ot::TreeNode> tmpOcts;
SFC::parSort::SFC_treeSort(grid,tmpOcts,tmpOcts,tmpOcts,partition_tol,m_uiMaxDepth,root,ROOT_ROTATION,1,TS_REMOVE_DUPLICATES,2,comm);
std::swap(tmpOcts,grid);
tmpOcts.clear();
SFC::parSort::SFC_treeSort(grid,tmpOcts,tmpOcts,tmpOcts,partition_tol,m_uiMaxDepth,root,ROOT_ROTATION,1,TS_CONSTRUCT_OCTREE,2,comm);
std::swap(tmpOcts,grid);
tmpOcts.clear();
SFC::parSort::SFC_treeSort(grid,tmpOcts,tmpOcts,tmpOcts,partition_tol,m_uiMaxDepth,root,ROOT_ROTATION,1,TS_BALANCE_OCTREE,2,comm);
std::swap(tmpOcts,grid);
tmpOcts.clear();
DendroIntL localSz;
DendroIntL globalSz;
localSz=grid.size();
par::Mpi_Reduce(&localSz,&globalSz,1,MPI_SUM,0,comm);
if(!rank) std::cout<<"Num balance octs: "<<globalSz<<std::endl;
ot::Mesh pMesh(grid,1,eOrder,comm);
localSz=pMesh.getNumLocalMeshNodes();
par::Mpi_Reduce(&localSz,&globalSz,1,MPI_SUM,0,comm);
if(!rank) std::cout<<"Num total vertices: "<<globalSz<<std::endl;
double ** varFx=new double* [NUM_VARS]; // original vars
double ** varSFx=new double* [NUM_VARS]; // stencil computed.
double ** varDiff=new double* [NUM_VARS]; // stencil computed.
double ** unzipVarSFx=new double* [NUM_VARS];
for(unsigned int i=0;i<NUM_VARS;i++)
{
varFx[i]=pMesh.createVector<double>(fx[i]);
varSFx[i]=pMesh.createVector<double>(0);
varDiff[i]=pMesh.createVector<double>(0);
unzipVarSFx[i]=pMesh.createUnZippedVector<double>();
}
for(unsigned int i=0;i<NUM_VARS;i++)
{
pMesh.performGhostExchange(varFx[i]);
}
pMesh.unzip(varFx[FX],unzipVarSFx[FX]);
const std::vector<ot::Block> blockList=pMesh.getLocalBlockList();
unsigned int offset;
unsigned int sz[3];
double h[3];
const Point p_min(d_min,d_min,d_min);
const Point p_max(d_max,d_max,d_max);
unsigned int bflag;
for(unsigned int blk=0;blk<blockList.size();blk++)
{
offset=blockList[blk].getOffset();
bflag=blockList[blk].getBlkNodeFlag();
sz[0]=blockList[blk].getAllocationSzX();
sz[1]=blockList[blk].getAllocationSzY();
sz[2]=blockList[blk].getAllocationSzZ();
h[0]=blockList[blk].computeDx(p_min,p_max);
h[1]=blockList[blk].computeDy(p_min,p_max);
h[2]=blockList[blk].computeDz(p_min,p_max);
/*h[0]=blockList[blk].computeGridDx();
h[1]=blockList[blk].computeGridDy();
h[2]=blockList[blk].computeGridDz();*/
deriv42_x(unzipVarSFx[Dx_FX]+offset,unzipVarSFx[FX]+offset,h[0],sz,bflag);
deriv42_y(unzipVarSFx[Dy_FX]+offset,unzipVarSFx[FX]+offset,h[1],sz,bflag);
deriv42_z(unzipVarSFx[Dz_FX]+offset,unzipVarSFx[FX]+offset,h[2],sz,bflag);
deriv42_xx(unzipVarSFx[DxDx_FX]+offset,unzipVarSFx[FX]+offset,h[0],sz,bflag);
deriv42_yy(unzipVarSFx[DyDy_FX]+offset,unzipVarSFx[FX]+offset,h[1],sz,bflag);
deriv42_zz(unzipVarSFx[DzDz_FX]+offset,unzipVarSFx[FX]+offset,h[2],sz,bflag);
}
for(unsigned int blk=0;blk<blockList.size();blk++)
{
offset=blockList[blk].getOffset();
bflag=blockList[blk].getBlkNodeFlag();
sz[0]=blockList[blk].getAllocationSzX();
sz[1]=blockList[blk].getAllocationSzY();
sz[2]=blockList[blk].getAllocationSzZ();
h[0]=blockList[blk].computeDx(p_min,p_max);
h[1]=blockList[blk].computeDy(p_min,p_max);
h[2]=blockList[blk].computeDz(p_min,p_max);
/*h[0]=blockList[blk].computeGridDx();
h[1]=blockList[blk].computeGridDy();
h[2]=blockList[blk].computeGridDz();*/
deriv42_y(unzipVarSFx[DxDy_FX]+offset,unzipVarSFx[Dx_FX]+offset,h[1],sz,bflag);
deriv42_z(unzipVarSFx[DxDz_FX]+offset,unzipVarSFx[Dx_FX]+offset,h[2],sz,bflag);
deriv42_z(unzipVarSFx[DyDz_FX]+offset,unzipVarSFx[Dy_FX]+offset,h[2],sz,bflag);
}
double norm_inf[NUM_VARS];
if(pMesh.isActive())
for(unsigned int i=0;i<NUM_VARS;i++)
{
pMesh.zip(unzipVarSFx[i],varSFx[i]);
norm_inf[i]=normLInfty(varFx[i]+pMesh.getNodeLocalBegin(),varSFx[i]+pMesh.getNodeLocalBegin(),(pMesh.getNodeLocalEnd()-pMesh.getNodeLocalBegin()),pMesh.getMPICommunicator());
if(!rank)
{
std::cout<<"var: "<<i<<" l_inf: "<<norm_inf[i]<<std::endl;
}
for(unsigned int node=pMesh.getNodeLocalBegin();node<pMesh.getNodeLocalEnd();node++)
{
varDiff[i][node]=varFx[i][node]-varSFx[i][node];
}
}
for(unsigned int i=0;i<NUM_VARS;i++)
{
pMesh.performGhostExchange(varFx[i]);
pMesh.performGhostExchange(varSFx[i]);
pMesh.performGhostExchange(varDiff[i]);
}
const char * pDataNames[]={"fx","dx_fx","dy_fx","dz_fx","dxdx_fx","dxdy_fx","dxdz_fx","dydy_fx","dydz_fx","dzdz_fx"};
io::vtk::mesh2vtuFine(&pMesh,"fx",0,NULL,NULL,NUM_VARS,pDataNames,(const double **)varFx);
io::vtk::mesh2vtuFine(&pMesh,"fx_s",0,NULL,NULL,NUM_VARS,pDataNames,(const double **)varSFx);
io::vtk::mesh2vtuFine(&pMesh,"fx_d",0,NULL,NULL,NUM_VARS,pDataNames,(const double **)varDiff);
for(unsigned int i=0;i<NUM_VARS;i++)
{
delete [] varFx[i];
delete [] varSFx[i];
delete [] varDiff[i];
delete [] unzipVarSFx[i];
}
delete [] varFx;
delete [] varSFx;
delete [] varDiff;
delete [] unzipVarSFx;
MPI_Finalize();
return 0;
}
#endif //SFCSORTBENCH_CHECKDERIVATIVES_H
| 48.250825 | 320 | 0.659097 | [
"mesh",
"vector"
] |
7807a99ad0bfb980fb631c3d47de206812401cee | 26,250 | cpp | C++ | Logic/Stage/ScriptEngine.cpp | Teles1/LuniaAsio | 62e404442cdb6e5523fc6e7a5b0f64a4471180ed | [
"MIT"
] | null | null | null | Logic/Stage/ScriptEngine.cpp | Teles1/LuniaAsio | 62e404442cdb6e5523fc6e7a5b0f64a4471180ed | [
"MIT"
] | null | null | null | Logic/Stage/ScriptEngine.cpp | Teles1/LuniaAsio | 62e404442cdb6e5523fc6e7a5b0f64a4471180ed | [
"MIT"
] | null | null | null | #include "ScriptEngine.h"
#include <Core/Utils/StringUtil/GenericConversion.h>
#include <Core/Resource/Resource.h>
#include "ScriptLoadThread.h"
#include <Core/DeltaTimer.h>
using namespace Lunia::StringUtil;
#include <iostream>
using namespace std;
#define PREPARE_CONTEXT(func) if (PrepareContext(asModule->GetFunctionByName(func), func, __FUNCTION__)==false)\
{\
LoggerInstance().Warn("{} could not be prepared",func);\
return;\
}
namespace Lunia
{
namespace XRated
{
namespace Logic
{
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ScriptEngine
ScriptEngine::ScriptEngine( IStageScript* initStageScript )//, const std::string& module, const std::string& filename)
: stageScript( initStageScript ), elapsedTime(0), engine(0), context(0), bLoading(false), refCount(1)
{
}
ScriptEngine::~ScriptEngine()
{
}
void ScriptEngine::Clear()
{
engine = NULL; // should not call release() because to make return to pool.
context = NULL;
ScriptLoaderInstance().ReleaseScriptEngine( ScriptLoader::Ticket(ScriptLoader::Ticket::TicketType::Release, this, moduleName, 0) );
}
bool ScriptEngine::IsLoading() const
{
return bLoading;
}
int ScriptEngine::LoadScript(const std::string& module, uint16 uniqueId)
{
Logger::GetInstance().Info( "requesting to load({0}) script(stageid:{1}) to listener(uniqueId:{2})", bLoading, module.c_str(), uniqueId );
bLoading = true;
Clear(); //clear engine
moduleName = module; //Set Module name
ScriptLoaderInstance().LoadScript( ScriptLoader::Ticket(ScriptLoader::Ticket::TicketType::Create, this, module, uniqueId) );
return 1;
}
int ScriptEngine::ExecuteScript(const string& script)
{
return 0;//engine->ExecuteString(0/*moduleName.c_str()*/, script.c_str());
}
////////////////////////////////////////////////////////////////////////////////////////
// ScriptLoadThread::IThreadListener implement ////////////////////////////////////////
void ScriptEngine::ScriptLoaded(uint16 uniqueId)
{
Logger::GetInstance().Info( "script loaded({0}). (stagename:{1}, hash:{2}, unique:{3})"
, bLoading, moduleName.c_str(), stageScript->GetStageId(), uniqueId);
PREPARE_CONTEXT("SetInstance");
context->SetArgObject(0, (void*)this);
int r = context->Execute();
if (r < 0) LoggerInstance().Exception("Could not execute SetInstance");
stageScript->Initialized(uniqueId);
bLoading = false;
return;
}
////////////////////////////////////////////////////////////////////////////////////////
// To Stage
bool ScriptEngine::IsPlayer(uint32 userSerial)
{
return stageScript->IsPlayer( userSerial );
}
int ScriptEngine::GetPlayerCnt()
{
return stageScript->GetPlayerCnt();
}
int ScriptEngine::GetActivePlayerCnt()
{
return stageScript->GetActivePlayerCnt();
}
uint8 ScriptEngine::GetPlayerTeam(uint32 hash)
{
return stageScript->GetPlayerTeam(hash);
}
int ScriptEngine::GetPlayerClass(uint32 hash)
{
return stageScript->GetPlayerClass(hash);
}
int ScriptEngine::GetRandomInt(int min, int max)
{
return stageScript->GetRandomInt(min, max);
}
void ScriptEngine::GetNPCPosition(Serial serial, float& x, float& y)
{
stageScript->GetNPCPosition(serial, x, y);
}
int ScriptEngine::GetPlayerLv(uint32 userSerial)
{
return stageScript->GetPlayerLv(userSerial);
}
void ScriptEngine::GetServerTime(int& month, int& day, int& hour, int& minute)
{
SYSTEMTIME time;
GetLocalTime(&time);
month = time.wMonth;
day = time.wDay;
hour = time.wHour;
minute = time.wMinute;
}
void ScriptEngine::ShowScriptMsg(const std::string& msg)
{
Logger::GetInstance().Info( "{0}.", msg.c_str() );
}
void ScriptEngine::Pause(float time)
{
stageScript->Pause(time);
}
void ScriptEngine::DropPvpItem()
{
stageScript->DropPvpItem();
}
void ScriptEngine::SetPvpItemInfo(uint32 hash)
{
stageScript->SetPvpItemInfo(hash);
}
void ScriptEngine::AddInterestLocation(int location, bool bAdd)
{
stageScript->AddInterestLocation(location, bAdd);
}
void ScriptEngine::AddInterestObjectLocation(uint32 npcSerial, float range, bool bAdd)
{
stageScript->AddInterestObjectLocation(npcSerial, range, bAdd);
}
bool ScriptEngine::IsFulfilledInterestLocation(int location)
{
return stageScript->IsFulfilledInterestLocation( location );
}
void ScriptEngine::AddInterestObjects(uint32 objectId, bool bAdd)
{
stageScript->AddInterestObjects( objectId, bAdd);
}
void ScriptEngine::AddInterestNPCPath(uint32 objectId, bool bAdd)
{
stageScript->AddInterestNPCPath( objectId, bAdd);
}
void ScriptEngine::AddSpecifiedObjects(uint32 serial)
{
stageScript->AddInterestObjects(serial);
}
void ScriptEngine::LocPlayers(bool lock)
{
stageScript->LocPlayers(lock);
}
void ScriptEngine::SetFloor( int floor )
{
stageScript->SetFloor( floor );
}
void ScriptEngine::TimerRun(int id, float time)
{
stageScript->TimerRun(id, time);
}
void ScriptEngine::TimerPause(int id)
{
stageScript->TimerPause(id);
}
void ScriptEngine::MissionClear(bool success, uint8 team)
{
stageScript->MissionClear(success, team);
}
void ScriptEngine::ActivateFastMatch()
{
stageScript->ActivateFastMatch();
}
void ScriptEngine::SecretFound()
{
stageScript->SecretFound();
}
///* object */
void ScriptEngine::ClearItem()
{
stageScript->ClearItem();
}
void ScriptEngine::CreateItemInLocation(uint32 id, int location, int cnt)
{
stageScript->CreateItem( id, location, cnt );
}
void ScriptEngine::CreateItemInPosition(uint32 id, float x, float z)
{
stageScript->CreateItem( id, float3(x, 0, z));
}
void ScriptEngine::createItemInLocationById(uint32 id, uint32 itemId, int location, int cnt)
{
stageScript->CreateItem( itemId, location, cnt, id);
}
void ScriptEngine::CreateItemInPositionById(uint32 id, uint32 itemId, float x, float z)
{
stageScript->CreateItem( itemId, float3(x, 0, z), id);
}
void ScriptEngine::CreatePrivateItemInPosition(uint32 id, float x, float z)
{
stageScript->CreateItem( id, float3(x, 0, z), 0, true);
}
bool ScriptEngine::RemoveItemFromPlayer(uint32 id, uint32 itemId, int cnt)
{
return stageScript->RemoveItem(id, itemId, cnt, false);
}
bool ScriptEngine::RemoveItemFromPlayerByTeam(uint32 id, uint32 itemId, int cnt)
{
return stageScript->RemoveItem(id, itemId, cnt, true);
}
bool ScriptEngine::AddItemToPlayer(uint32 id, uint32 itemId, int cnt)
{
return stageScript->AddItemToPlayer(id, itemId, cnt, false);
}
bool ScriptEngine::AddItemToPlayerByTeam(uint32 id, uint32 itemId, int cnt)
{
return stageScript->AddItemToPlayer(id, itemId, cnt, true);
}
bool ScriptEngine::AddItemsToPlayer(uint32 id, std::vector<int>* arrayId, std::vector<int>* arrayCnt)
{
int ids[5] = {0,};
int cnts[5] = {0,};
unsigned int cnt = arrayId->size();
if ( cnt > 5) {
Logger::GetInstance().Info( "Too many parameters. [{0}]", cnt);
return false;
}
if ( cnt != arrayCnt->size() ) {
Logger::GetInstance().Info( "parameter count mismatch [{0}/{1}]", cnt, arrayCnt->size());
return false;
}
while ( cnt-- ) {
ids[cnt] = arrayId->at(cnt);
cnts[cnt] = arrayCnt->at(cnt);
}
return stageScript->AddItemToPlayer(id, ids, cnts);
}
bool ScriptEngine::RemoveItemsFromPlayer(uint32 id, std::vector<int>* arrayId, std::vector<int>* arrayCnt)
{
int ids[5] = {0,};
int cnts[5] = {0,};
unsigned int cnt = arrayId->size();
if ( cnt > 5) {
Logger::GetInstance().Info( "Too many parameters. [{0}]", cnt);
return false;
}
if ( cnt != arrayCnt->size() ) {
Logger::GetInstance().Info( "parameter count mismatch [{0}/{1}]", cnt, arrayCnt->size());
return false;
}
while ( cnt-- ) {
ids[cnt] = arrayId->at(cnt);
cnts[cnt] = arrayCnt->at(cnt);
}
return stageScript->RemoveItem(id, ids, cnts);
}
bool ScriptEngine::ExamineItemSlotFromPlayer(uint32 serial, uint32 itemId, int cnt)
{
return stageScript->ExamineItemSlotFromPlayer(serial, itemId, cnt);
}
//Create object functions
uint32 ScriptEngine::CreateObjectByPosition(uint32 id, float pos_x, float pos_y, uint8 team)
{
return stageScript->CreateObject(id, float2(pos_x, pos_y), team);
}
void ScriptEngine::CreateObjectsByPosition(uint32 hash, std::vector<float>* arrayX, std::vector<float>* arrayY, uint8 team)
{
unsigned int cnt = arrayX->size();
float x, y;
while ( cnt ) {
--cnt;
x = arrayX->at(cnt);
y = arrayY->at(cnt);
stageScript->CreateObject(hash, float2(x, y), team);
}
}
uint32 ScriptEngine::CreateObjectByPositionD(uint32 id, float pos_x, float pos_y, float dirX, float dirY, uint8 team)
{
return stageScript->CreateObject(id, float2(pos_x, pos_y), float3(dirX, 0, dirY), team);
}
uint32 ScriptEngine::CreateNPCByPos(uint32 id, float x, float y,
uint8 team, int idleType, int pathGroupIndex, int defenceLocation, int transferType)
{
return stageScript->CreateNPC(id, float3(x, 0, y), team, (Database::Info::StageInfo::Npc::IdleStateType)idleType,
pathGroupIndex, defenceLocation, (Database::Info::StageInfo::Npc::TransferType)transferType);
}
void ScriptEngine::CreateNPCsByPos(uint32 hash, std::vector<float>* array1, std::vector<float>* array2, uint8 team, int idleType, int pathGroupIndex, int defenceLocation, int transferType)
{
unsigned int cnt = array1->size();
float x, y;
while ( cnt ) {
--cnt;
x = array1->at(cnt);
y = array2->at(cnt);
stageScript->CreateNPC(hash, float3(x, 0, y), team, (Database::Info::StageInfo::Npc::IdleStateType)idleType,
pathGroupIndex, defenceLocation, (Database::Info::StageInfo::Npc::TransferType)transferType);
}
}
uint32 ScriptEngine::CreateNPCByPosD(uint32 id, float x, float y, float dirX, float dirY,
uint8 team, int idleType, int pathGroupIndex, int defenceLocation, int transferType)
{
return stageScript->CreateNPC(id, float3(x, 0, y), float3(dirX, 0, dirY), team, (Database::Info::StageInfo::Npc::IdleStateType)idleType,
pathGroupIndex, defenceLocation, (Database::Info::StageInfo::Npc::TransferType)transferType);
}
void ScriptEngine::ChangePlayerStatusLimit(std::vector<uint32>* statuses, const std::vector<uint32>& limits)
{
stageScript->ChangePlayerStatusLimit( statuses, limits );
}
void ScriptEngine::ChangePlayerStatusRate(std::vector<uint32>* statusId, const std::vector<float>& rate)
{
stageScript->ChangePlayerStatusRate( statusId, rate );
}
void ScriptEngine::DestroyObject(uint32 id, bool silent)
{
stageScript->DestroyObject( id, silent );
}
void ScriptEngine::DestroyObjectFromLocationById(uint32 id, int location, bool silent)
{
stageScript->DestroyObject( location, id, silent);
}
void ScriptEngine::DestroyObjectFromLocationByTeam(uint8 team, int location, bool silent)
{
stageScript->DestroyObject( location, team, silent);
}
void ScriptEngine::DestroyNPCFromLocationById(uint32 id, int location, bool silent)
{
stageScript->DestroyNPC( location, id, silent);
}
void ScriptEngine::DestroyNPCFromLocationByTeam(uint8 team, int location, bool silent)
{
stageScript->DestroyNPC( location, team, silent);
}
void ScriptEngine::ChangePlayerTeam(uint32 userSerial, uint8 team)
{
stageScript->ChangePlayerTeam( userSerial, team);
}
void ScriptEngine::ChangeNPCTeam(uint32 serial, uint8 team)
{
stageScript->ChangeNpcTeam( serial, team);
}
//void ScriptEngine::EnableAI(bool enable); // pause or play NPC
void ScriptEngine::ChangeNPCAI(int location, uint32 id, int idleType, int value)
{
stageScript->ChangeNpcAI(location, id, idleType, value);
}
void ScriptEngine::ChangeNPCAIBySerial(uint32 serial, int idleType, int value)
{
stageScript->ChangeNpcAI(serial, idleType, value);
}
void ScriptEngine::MoveObjectFromLocation(int locationFrom, int locationTo, uint16 objectType)
{
stageScript->MoveObject(locationFrom, locationTo, objectType);
}
void ScriptEngine::MoveObjectFromLocationById(int locationFrom, int locationTo, uint32 id, uint16 objectType)
{
stageScript->MoveObject(locationFrom, locationTo, id, objectType);
}
void ScriptEngine::MovePlayer(uint32 userSerial, int location)
{
stageScript->MovePlayer( userSerial, location );
}
void ScriptEngine::MoveAllPlayer(int location)
{
stageScript->MovePlayer( location );
}
void ScriptEngine::ChangeNPCSight(uint32 serial, float range)
{
stageScript->ChangeNpcSight(serial, range);
}
///* object status - flexible */
void ScriptEngine::GiveExp(uint32 userSerial, uint16 level, uint32 exp)
{
stageScript->GiveExp( XRated::Constants::ExpAcquiredType::ExpScript, userSerial, level, exp);
}
void ScriptEngine::GiveExpToAllPlayer(uint16 level, uint32 exp)
{
stageScript->GiveExp( XRated::Constants::ExpAcquiredType::ExpScript, level, exp);
}
void ScriptEngine::GiveBattleEXPtoAllPlayer(uint8 team, uint32 warExp)
{
stageScript->GiveBattleEXPtoAllPlayer( XRated::Constants::ExpAcquiredType::ExpScript, team, warExp );
}
void ScriptEngine::AddHp(uint32 id, int delta)
{
stageScript->AddHp( id, delta);
}
void ScriptEngine::AddMp(uint32 id, int delta)
{
stageScript->AddMp( id, delta);
}
void ScriptEngine::DealDamageFromLocationByTeam(int location, uint8 team, float dmg, bool bRate)
{
stageScript->DealDamage(location, team, dmg, bRate);
}
void ScriptEngine::DealDamageFromLocationById(int location, uint32 hash, float dmg, bool bRate)
{
stageScript->DealDamage(location, hash, dmg, bRate);
}
void ScriptEngine::ChangeNPCAction(uint32 serial, uint32 action)
{
stageScript->ChangeNPCAction(serial, action);
}
void ScriptEngine::ChangeNPCActionInLocationById(int location, uint32 hash, uint32 action)
{
stageScript->ChangeNPCAction(location, hash, action);
}
void ScriptEngine::ChangeMISCStateById(uint32 id, uint32 type, bool bAdd)
{
stageScript->ChangeMISCState(id, type, bAdd);
}
void ScriptEngine::ChangeMISCStateInLocationById(uint32 id, int location, uint32 type, bool bAdd)
{
stageScript->ChangeMISCState(id, location, type, bAdd);
}
void ScriptEngine::ChangeNPCStateById(uint32 id, uint32 type, bool bAdd)
{
stageScript->ChangeNPCState(id, type, bAdd);
}
void ScriptEngine::ChangeNPCStateInLocationById(uint32 id, int location, uint32 type, bool bAdd)
{
stageScript->ChangeNPCState(id, location, type, bAdd);
}
void ScriptEngine::CheckStateBundleForAchievement( uint32 stateBundleHash )
{
stageScript->CheckStateBundleForAchievement( stateBundleHash );
}
uint32 ScriptEngine::CheckMinimumPlayerCount( )
{
return stageScript->CheckMinimumPlayerCount();
}
void ScriptEngine::GiveStateBundleToObject( uint32 objectSerial, uint32 id )
{
stageScript->GiveStateBundleToObject( objectSerial, id );
}
///* Quest */
uint8 ScriptEngine::GetQuestState(uint32 userSerial, uint32 questHash)
{
return stageScript->GetQuestState(userSerial, questHash);
}
uint8 ScriptEngine::SetQuestState(uint32 userSerial, uint32 questHash, uint8 newState)
{
return stageScript->SetQuestState(userSerial, questHash, newState);
}
uint32 ScriptEngine::GetQuestParameter(uint32 userSerial, uint32 questHash, uint8 paramIndex)
{
return stageScript->GetQuestParameter(userSerial, questHash, paramIndex);
}
uint32 ScriptEngine::SetQuestParameter(uint32 userSerial, uint32 questHash, uint8 paramIndex, uint32 newValue)
{
return stageScript->SetQuestParameter(userSerial, questHash, paramIndex, newValue);
}
///* output */
void ScriptEngine::DisplayTextEvent(uint8 displayTo, uint16 textId, float param)
{
stageScript->DisplayTextEvent((Constants::DisplayTextType)displayTo, textId, param);
}
void ScriptEngine::NoticeTextEvent(uint32 userSerial, uint8 displayTo, uint16 textId, float param)
{
stageScript->NoticeTextEvent(userSerial, (Constants::DisplayTextType)displayTo, textId, param);
}
void ScriptEngine::DisplayText(uint8 displayTo, const std::string& text)
{
stageScript->DisplayText((Constants::DisplayTextType)displayTo, ToUnicode<string>(text));
}
void ScriptEngine::NoticeText(uint32 userSerial, uint8 displayTo, const std::string& text)
{
stageScript->NoticeText(userSerial, (Constants::DisplayTextType)displayTo, ToUnicode<string>(text));
}
void ScriptEngine::DisplayTimer(int timer, uint32 type)
{
stageScript->DisplayTimer(timer, (Constants::DisplayTimerType)type);
}
void ScriptEngine::BroadcastEvent(int eventId)
{
stageScript->BroadcastEvent(eventId);
}
void ScriptEngine::NoticeEvent(uint32 userSerial, int eventId)
{
stageScript->NoticeEvent(userSerial, eventId);
}
void ScriptEngine::NoticeClientStageEvent( uint32 userSerial, int eventId, int eventParam )
{
stageScript->NoticeClientStageEvent( userSerial, eventId, eventParam );
}
void ScriptEngine::AddMinimapPing(int pingId, int x, int y, int type)
{
stageScript->AddMinimapPing(pingId, x, y, (Constants::MiniMapPingType)type);
}
void ScriptEngine::NoticeAddMinimapPing(int pingId, int x, int y, int type, uint32 userSerial)
{
stageScript->NoticeAddMinimapPing(pingId, x, y, (Constants::MiniMapPingType)type, userSerial);
}
void ScriptEngine::RemoveMinimapPing(int pingId)
{
stageScript->RemoveMinimapPing(pingId);
}
void ScriptEngine::GiveLicense(uint32 licenseGroup, uint32 accessLevel)
{
stageScript->GiveLicense(licenseGroup, accessLevel);
}
void ScriptEngine::GiveLicenseToPlayer(uint32 userSerial, uint32 licenseGroup, uint32 accessLevel)
{
stageScript->GiveLicenseToPlayer(userSerial, licenseGroup, accessLevel);
}
void ScriptEngine::GiveCharacterLicense(uint32 userSerial, uint32 characterId)
{
stageScript->GiveCharacterLicense(userSerial, characterId);
}
void ScriptEngine::NoticeStylePointState(XRated::StylePoint::State state)
{
stageScript->NoticeStylePointState(state);
}
void ScriptEngine::GambleGameEnd(std::vector<int>* rankList)
{
std::vector<uint8> ranks;
unsigned int cnt = rankList->size();
if ( cnt > XRated::Gamble::SlimeRace::MaxSlimeNumber) {
Logger::GetInstance().Error( "Too many parameters. [{0}]", cnt);
return;
}
while ( cnt-- ) {
ranks.push_back( (uint8)rankList->at(cnt) );
}
stageScript->GambleGameEnd(ranks);
}
int ScriptEngine::GetSlimeRaceIntervalInMin() const
{
return stageScript->GetSlimeRaceIntervalInMin();
}
void ScriptEngine::GambleNextGame(uint32 userSerial, float seconds)
{
stageScript->GambleNextGame(userSerial, seconds);
}
bool ScriptEngine::IsHolidayEventTime(uint32 eventId)
{
return stageScript->IsHolidayEventTime(eventId);
}
uint32 ScriptEngine::GetHolidayEventNpcHash(uint32 eventId, uint32 oldNpcHash)
{
return stageScript->GetHolidayEventNpcHash(eventId, oldNpcHash);
}
void ScriptEngine::ChangeWeatherToNone()
{
stageScript->ChangeWeatherToNone();
}
void ScriptEngine::ChangeWeatherToClear()
{
stageScript->ChangeWeatherToClear();
}
void ScriptEngine::ChangeWeatherToRain()
{
stageScript->ChangeWeatherToRain();
}
void ScriptEngine::ChangeWeatherToSnow()
{
stageScript->ChangeWeatherToSnow();
}
void ScriptEngine::ChangeWeatherToAqua()
{
stageScript->ChangeWeatherToAqua();
}
bool ScriptEngine::PrepareContext(asIScriptFunction* function, const char* funcName, const char* callerName)
{
int result = context->Prepare(function);
if( result < 0 )
{
switch( result )
{
case -6: // method not found in the script
case -2: // already active context that means, you cannot call a script function in the c++ function which is called by a script function
// skip known issues
break;
default:
Logger::GetInstance().Error("Invalid Script Context(id:{0}, result:{1}, script_func:{2}, caller:{3}", function->GetId(), result, funcName, callerName);
break;
}
return false;
}
return true;
}
////////////////////////////////////////////////////////////////////////////////////////
//IStageScript::IStageEventListener implementation
// To script
void ScriptEngine::InitializeScript()
{
PREPARE_CONTEXT("Initialize");
context->Execute();
}
/* general events */
#pragma warning(push)
#pragma warning(disable:4189)
void ScriptEngine::TimerAlarmed(int timer)
{
//volatile uint32 stageHash=stageScript->GetStageId(); // debugging buffer
PREPARE_CONTEXT("TimerAlarmed");
context->SetArgDWord(0, timer);
context->Execute();
}
#pragma warning(pop)
void ScriptEngine::PvpGameStart()
{
PREPARE_CONTEXT("PvpGameStart");
context->Execute();
}
void ScriptEngine::BattleGroundTimeover()
{
PREPARE_CONTEXT("BattleGroundTimeover");
context->Execute();
}
void ScriptEngine::MissionCleared(bool success, uint8 team)
{
PREPARE_CONTEXT("MissionCleared");
context->SetArgDWord(0, success?1:0);
context->SetArgDWord(1, (int)team);
context->Execute();
}
void ScriptEngine::NoticeHolidayEvent(uint32 eventId, bool start /*true = start, false = end*/)
{
PREPARE_CONTEXT("NoticeHolidayEvent");
context->SetArgDWord(0, eventId);
context->SetArgDWord(1, start?1:0);
context->Execute();
}
/* object related */
void ScriptEngine::ObjectEntered(Constants::ObjectType type, uint32 serial, int location, uint8 team)
{
volatile uint32 stageHash=stageScript->GetStageId(); // debugging buffer
PREPARE_CONTEXT("ObjectEntered");
context->SetArgDWord(0, (int)type);
context->SetArgDWord(1, (int)serial);
context->SetArgDWord(2, location);
context->SetArgDWord(3, (int)team);
context->Execute();
}
void ScriptEngine::NpcObjectEntered(Constants::ObjectType type, uint32 serial, int location, uint8 team)
{
volatile uint32 stageHash=stageScript->GetStageId(); // debugging buffer
PREPARE_CONTEXT("NpcObjectEntered");
context->SetArgDWord(0, (int)type);
context->SetArgDWord(1, (int)serial);
context->SetArgDWord(2, location);
context->SetArgDWord(3, (int)team);
context->Execute();
}
void ScriptEngine::ObjectLeft(Constants::ObjectType type, uint32 serial, int location, uint8 team)
{
PREPARE_CONTEXT("ObjectLeft");
context->SetArgDWord(0, (int)type);
context->SetArgDWord(1, (int)serial);
context->SetArgDWord(2, location);
context->SetArgDWord(3, (int)team);
context->Execute();
}
void ScriptEngine::NpcObjectLeft(Constants::ObjectType type, uint32 serial, int location, uint8 team)
{
PREPARE_CONTEXT("NpcObjectLeft");
context->SetArgDWord(0, (int)type);
context->SetArgDWord(1, (int)serial);
context->SetArgDWord(2, location);
context->SetArgDWord(3, (int)team);
context->Execute();
}
void ScriptEngine::ObjectEnteredObjectLocation(Constants::ObjectType type, uint32 serial, int location, uint8 team)
{
PREPARE_CONTEXT("ObjectEnteredObjectLocation");
context->SetArgDWord(0, (int)type);
context->SetArgDWord(1, (int)serial);
context->SetArgDWord(2, location);
context->SetArgDWord(3, (int)team);
context->Execute();
}
void ScriptEngine::ObjectLeftFromObjectLocation(Constants::ObjectType type, uint32 serial, int location, uint8 team)
{
PREPARE_CONTEXT("ObjectLeftFromObjectLocation");
context->SetArgDWord(0, (int)type);
context->SetArgDWord(1, (int)serial);
context->SetArgDWord(2, location);
context->SetArgDWord(3, (int)team);
context->Execute();
}
void ScriptEngine::ObjectDestroyed(uint32 hash, Constants::ObjectType type)
{
PREPARE_CONTEXT("ObjectDestroyed");
context->SetArgDWord(0, hash);
context->SetArgDWord(1, (int)type);
context->Execute();
}
void ScriptEngine::NPCArrived(uint32 hash, uint32 serial, int pathCnt, int posCnt)
{
PREPARE_CONTEXT("NPCArrived");
context->SetArgDWord(0, hash);
context->SetArgDWord(1, serial);
context->SetArgDWord(2, pathCnt);
context->SetArgDWord(3, posCnt);
context->Execute();
}
void ScriptEngine::InterestObjectDestroyed(Serial serial)
{
PREPARE_CONTEXT("InterestObjectDestroyed");
context->SetArgDWord(0, serial);
context->Execute();
}
void ScriptEngine::PlayerDied(uint32 serial, uint16 life)
{
PREPARE_CONTEXT("PlayerDied");
context->SetArgDWord(0, serial);
context->SetArgDWord(1, life);
context->Execute();
}
void ScriptEngine::PlayerEntered(uint32 serial, uint8 team)
{
PREPARE_CONTEXT("PlayerEntered");
context->SetArgDWord(0, serial);
context->SetArgDWord(1, team);
context->Execute();
}
void ScriptEngine::PlayerLeft(uint32 serial, uint8 team)
{
PREPARE_CONTEXT("PlayerLeft");
context->SetArgDWord(0, serial);
context->SetArgDWord(1, team);
context->Execute();
}
void ScriptEngine::CompletedQuest( uint32 serial, uint32 questHash )
{
PREPARE_CONTEXT("CompletedQuest");
context->SetArgDWord(0, serial);
context->SetArgDWord(1, questHash);
context->Execute();
}
void ScriptEngine::AcceptedQuest( uint32 serial, uint32 questHash )
{
PREPARE_CONTEXT("AcceptedQuest");
context->SetArgDWord(0, serial);
context->SetArgDWord(1, questHash);
context->Execute();
}
}
}
}
| 29.395297 | 191 | 0.681524 | [
"object",
"vector"
] |
780a89596cdc1d2cc223c4beb7001c2b782314f1 | 13,533 | cpp | C++ | shapeCommonOperatation/mainwindow.cpp | xiaozhuo1314/VTK-Qt | 7f04184bf9269bfebf51b8539501b241dd2ba5ca | [
"Apache-2.0"
] | 32 | 2019-01-18T15:30:20.000Z | 2022-03-18T07:38:52.000Z | shapeCommonOperatation/mainwindow.cpp | xiaozhuo1314/VTK-Qt | 7f04184bf9269bfebf51b8539501b241dd2ba5ca | [
"Apache-2.0"
] | null | null | null | shapeCommonOperatation/mainwindow.cpp | xiaozhuo1314/VTK-Qt | 7f04184bf9269bfebf51b8539501b241dd2ba5ca | [
"Apache-2.0"
] | 18 | 2019-02-25T09:12:23.000Z | 2022-03-10T09:04:25.000Z | #include "mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
//triangleSurfaceAndVolume(); //计算表面积和体积
//distanceOnSurface(); //计算测地距离
//boundingBox(); //包围盒
//normalVector(); //加入法向量后图形会更加平滑
curvatures(); //显示曲率
}
MainWindow::~MainWindow()
{
}
void MainWindow::triangleSurfaceAndVolume()
{
vtkSmartPointer<vtkCubeSource> cubeSource = vtkSmartPointer<vtkCubeSource>::New(); //vtkPolyData类型数据
cubeSource->SetXLength(10);
cubeSource->SetYLength(10);
cubeSource->SetZLength(10);
cubeSource->Update();
//其他网格类型转换成三角网格类型
vtkSmartPointer<vtkTriangleFilter> triFilter = vtkSmartPointer<vtkTriangleFilter>::New();
triFilter->SetInputData(cubeSource->GetOutput());
triFilter->Update();
//计算三角网格的基本属性 面积。体积等
vtkSmartPointer<vtkMassProperties> massProp = vtkSmartPointer<vtkMassProperties>::New();
massProp->SetInputData(triFilter->GetOutput());
double Volume = massProp->GetVolume(); //获得体积
double SurfaceArea = massProp->GetSurfaceArea(); //获得表面积
double maxArea = massProp->GetMaxCellArea(); //最大三角形网格面积
double minArea = massProp->GetMinCellArea(); //最小三角形网格面积
qDebug()<<"the Volume : " << Volume;
qDebug()<<"the SurfaceArea : " << SurfaceArea;
qDebug()<<"the MaxAreaofCell : " << maxArea;
qDebug()<<"the MinAreaofCell : " << minArea;
vtkSmartPointer<vtkPolyDataMapper> mapper = vtkSmartPointer<vtkPolyDataMapper>::New();
mapper->SetInputData(triFilter->GetOutput());
vtkSmartPointer<vtkActor> actor = vtkSmartPointer<vtkActor>::New();
actor->SetMapper(mapper);
actor->GetProperty()->SetColor(0, 0, 1);
actor->GetProperty()->SetEdgeColor(1, 0, 0);
actor->GetProperty()->SetEdgeVisibility(1);
vtkSmartPointer<vtkRenderer> render = vtkSmartPointer<vtkRenderer>::New();
render->AddActor(actor);
render->SetBackground(0, 0, 0);
vtkSmartPointer<vtkRenderWindow> rw = vtkSmartPointer<vtkRenderWindow>::New();
rw->AddRenderer(render);
rw->SetSize(480, 420);
rw->SetWindowName("Calculating Area and Volume of Triangle grid");
vtkSmartPointer<vtkRenderWindowInteractor> rwi = vtkSmartPointer<vtkRenderWindowInteractor>::New();
rwi->SetRenderWindow(rw);
vtkSmartPointer<vtkInteractorStyleTrackballCamera> style = vtkSmartPointer<vtkInteractorStyleTrackballCamera>::New();
rwi->SetInteractorStyle(style); //控制相机对物体旋转、放大、缩小等操作
rwi->Initialize();
rwi->Start();
}
void MainWindow::distanceOnSurface()
{
vtkSmartPointer<vtkSphereSource> sphereSource = vtkSmartPointer<vtkSphereSource>::New();
sphereSource->SetCenter(0.0, 0.0, 0.0);
sphereSource->SetRadius(5.0);
sphereSource->Update();
//计算测地距离
vtkSmartPointer<vtkDijkstraGraphGeodesicPath> dijstra = vtkSmartPointer<vtkDijkstraGraphGeodesicPath>::New();
dijstra->SetInputData(sphereSource->GetOutput());
dijstra->SetStartVertex(0); //开始点的索引号
dijstra->SetEndVertex(10); //结束点的索引号
dijstra->Update();
vtkSmartPointer<vtkPolyDataMapper> mapper = vtkSmartPointer<vtkPolyDataMapper>::New();
mapper->SetInputData(sphereSource->GetOutput());
vtkSmartPointer<vtkPolyDataMapper> pathMapper = vtkSmartPointer<vtkPolyDataMapper>::New();
pathMapper->SetInputData(dijstra->GetOutput());
vtkSmartPointer<vtkActor> actor = vtkSmartPointer<vtkActor>::New();
actor->SetMapper(mapper);
vtkSmartPointer<vtkActor> pathActor = vtkSmartPointer<vtkActor>::New();
pathActor->SetMapper(pathMapper);
pathActor->GetProperty()->SetColor(1, 0, 0);
pathActor->GetProperty()->SetLineWidth(5);
vtkSmartPointer<vtkRenderer> renderer = vtkSmartPointer<vtkRenderer>::New();
renderer->AddActor(actor);
renderer->AddActor(pathActor);
renderer->SetBackground(0, 0, 0);
vtkSmartPointer<vtkRenderWindow> rw = vtkSmartPointer<vtkRenderWindow>::New();
rw->AddRenderer(renderer);
rw->SetSize(640, 480);
rw->SetWindowName("Calculating Geodesic Path");
vtkSmartPointer<vtkRenderWindowInteractor> rwi = vtkSmartPointer<vtkRenderWindowInteractor>::New();
rwi->SetRenderWindow(rw);
vtkSmartPointer<vtkInteractorStyleTrackballCamera> style = vtkSmartPointer<vtkInteractorStyleTrackballCamera>::New();
rwi->SetInteractorStyle(style); //控制相机对物体旋转、放大、缩小等操作
rwi->Initialize();
rwi->Start();
}
void MainWindow::boundingBox()
{
vtkSmartPointer<vtkSphereSource> sphereSource = vtkSmartPointer<vtkSphereSource>::New();
sphereSource->SetCenter(0.0, 0.0, 0.0);
sphereSource->SetRadius(5.0);
sphereSource->Update();
vtkSmartPointer<vtkPolyData> sphere = sphereSource->GetOutput();
//生成包围盒
vtkSmartPointer<vtkOutlineFilter> outline = vtkSmartPointer<vtkOutlineFilter>::New();
outline->SetInputData(sphere);
outline->Update(); //算法执行完毕,必须更新!!!
vtkSmartPointer<vtkPolyDataMapper> mapper =vtkSmartPointer<vtkPolyDataMapper>::New();
mapper->SetInputData(sphere);
vtkSmartPointer<vtkPolyDataMapper> outlineMapper = vtkSmartPointer<vtkPolyDataMapper>::New();
outlineMapper->SetInputData(outline->GetOutput());
vtkSmartPointer<vtkActor> actor =vtkSmartPointer<vtkActor>::New();
actor->SetMapper(mapper); //一个actor一个模型,一个mapper
vtkSmartPointer<vtkActor> outlineActor = vtkSmartPointer<vtkActor>::New();
outlineActor->SetMapper(outlineMapper);
outlineActor->GetProperty()->SetColor(0, 1, 0);
outlineActor->GetProperty()->SetLineWidth(3);
vtkSmartPointer<vtkRenderer> renderer = vtkSmartPointer<vtkRenderer>::New();
renderer->AddActor(actor);
renderer->AddActor(outlineActor);
renderer->SetBackground(0, 0, 0);
vtkSmartPointer<vtkRenderWindow> rw = vtkSmartPointer<vtkRenderWindow>::New();
rw->AddRenderer(renderer);
rw->SetSize(640, 480);;
rw->SetWindowName("PolyData Bounding Box");
rw->Render();
vtkSmartPointer<vtkRenderWindowInteractor> rwi = vtkSmartPointer<vtkRenderWindowInteractor>::New();
rwi->SetRenderWindow(rw);
vtkSmartPointer<vtkInteractorStyleTrackballCamera> style = vtkSmartPointer<vtkInteractorStyleTrackballCamera>::New();
rwi->SetInteractorStyle(style); //控制相机对物体旋转、放大、缩小等操作
rwi->Initialize();
rwi->Start();
}
void MainWindow::normalVector()
{
//读取文件
vtkSmartPointer<vtkPolyDataReader> plyReader = vtkSmartPointer<vtkPolyDataReader>::New();
plyReader->SetFileName("/home/silence/Project/VTK-Qt/shapeCommonOperatation/fran_cut.vtk");
plyReader->Update();
//法向量
vtkSmartPointer<vtkPolyDataNormals> normFilter = vtkSmartPointer<vtkPolyDataNormals>::New();
normFilter->SetInputData(plyReader->GetOutput());
normFilter->SetComputePointNormals(1); //开启点法向量计算
normFilter->SetComputeCellNormals(0); //关闭单元法向量计算
normFilter->SetConsistency(1); //自动调整模型的单元法向量。
normFilter->SetAutoOrientNormals(1); //开启或关闭合适法向的自动检测,自动调整法线方向
normFilter->SetSplitting(0); //打开或关闭锐利边缘的拆分。如果检测到存在锐利边缘,则会将其分裂,则模型数据可能会变化
normFilter->Update();
//vtkMaskPoints采集数据,仅保留点数据和属性
vtkSmartPointer<vtkMaskPoints> mask = vtkSmartPointer<vtkMaskPoints>::New();
mask->SetInputData(normFilter->GetOutput());
mask->SetMaximumNumberOfPoints(300); //为了减少计算量,随机采样300个点
mask->RandomModeOn(); //随机采样
mask->Update();
//将圆柱体附加到圆锥体上形成箭头,就是箭头根部是圆柱体,前部是圆锥
vtkSmartPointer<vtkArrowSource> arrow = vtkSmartPointer<vtkArrowSource>::New();
arrow->Update(); //一定要更新 否则数据没有添加进来,程序会报错
//符号化技术,用图形将法向量图形化展示,所用的图形是上面生成的箭头
vtkSmartPointer<vtkGlyph3D> glyph = vtkSmartPointer<vtkGlyph3D>::New();
glyph->SetInputData(mask->GetOutput()); //设置模型
glyph->SetSourceData(arrow->GetOutput()); //设置图形化显示的图形源数据,用箭头代替
glyph->SetVectorModeToUseNormal();//设置向量显示模式和法向量一致,指定要使用法向量数据来控制Glyph图形方向
glyph->SetScaleFactor(0.01); //设置伸缩比例,控制Glyph图形的大小
glyph->Update();
//mapper
vtkSmartPointer<vtkPolyDataMapper> mapper = vtkSmartPointer<vtkPolyDataMapper>::New();
mapper->SetInputData(plyReader->GetOutput());
//法向量mapper
vtkSmartPointer<vtkPolyDataMapper> normMapper = vtkSmartPointer<vtkPolyDataMapper>::New();
normMapper->SetInputData(normFilter->GetOutput());
//法向量可视化mapper
vtkSmartPointer<vtkPolyDataMapper> glyphMapper = vtkSmartPointer<vtkPolyDataMapper>::New();
glyphMapper->SetInputData(glyph->GetOutput());
vtkSmartPointer<vtkActor> actor = vtkSmartPointer<vtkActor>::New();
actor->SetMapper(mapper);
vtkSmartPointer<vtkActor> normActor = vtkSmartPointer<vtkActor>::New();
normActor->SetMapper(normMapper);
vtkSmartPointer<vtkActor> glyphActor = vtkSmartPointer<vtkActor>::New();
glyphActor->SetMapper(glyphMapper);
glyphActor->GetProperty()->SetColor(1, 0, 0);
double origView[4] = { 0, 0, 0.33, 1 };
double normView[4] = { 0.33, 0, 0.66, 1 };
double glyphView[4] = { 0.66, 0, 1, 1 };
//render
vtkSmartPointer<vtkRenderer> origRender = vtkSmartPointer<vtkRenderer>::New();
origRender->SetViewport(origView);
origRender->AddActor(actor);
origRender->SetBackground(1, 0, 0);
vtkSmartPointer<vtkRenderer> normRender = vtkSmartPointer<vtkRenderer>::New();
normRender->SetViewport(normView);
normRender->AddActor(normActor);
normRender->SetBackground(0, 1, 0);
vtkSmartPointer<vtkRenderer> glyphRender = vtkSmartPointer<vtkRenderer>::New();
glyphRender->SetViewport(glyphView);
glyphRender->AddActor(glyphActor);
glyphRender->AddActor(normActor);
glyphRender->SetBackground(0, 0, 1);
//render window
vtkSmartPointer<vtkRenderWindow> rw = vtkSmartPointer<vtkRenderWindow>::New();
rw->AddRenderer(origRender);
rw->AddRenderer(normRender);
rw->AddRenderer(glyphRender);
rw->SetWindowName("Calculating Point Norm & Cell Norm");
rw->SetSize(960, 320);
rw->Render();
//render window interactor
vtkSmartPointer<vtkRenderWindowInteractor> rwi = vtkSmartPointer<vtkRenderWindowInteractor>::New();
rwi->SetRenderWindow(rw);
vtkSmartPointer<vtkInteractorStyleTrackballCamera> style = vtkSmartPointer<vtkInteractorStyleTrackballCamera>::New();
rwi->SetInteractorStyle(style);
rwi->Initialize();
rwi->Start();
//关于类vtkGlyph3D
//详细描述:为每个输入点拷贝相应方向和伸缩比例的轮廓几何体
//vtkGlyph3d是一个过滤器,当拷贝几何体到每个输入点时,它起到滤波作用.
//glyph从过滤输入源中以多边形数据形式定义,glyph根据输入的矢量和法向量来确定方向,根据伸缩数据和矢量大小来确定伸缩比例.
//当glyph较多时,可能通过对象源与其相应的定义信息来创建glyph表.
//glyph表可以通过伸缩值或矢量大小来索引相应的gpyph对象.
//要使用vtkGlyph3D对象,我们首先需要提供一个输入集和一个对象源来定义ghyph.
//然后决定是否对ghyph进行伸缩,以及怎样对其进行伸缩,接下来决定是否对glyph设置方向,以及如何根据矢量及法向量来设置它,最终决定我们是用glyph表还是仅仅是单一的ghyph.
//如果使用了glyph表,我们还需要考虑相应的索引值.
//vtkGlyph3D 实际上是一种符号化的算法工具,可以使用一个源(如球体)为输入数据集的每一个点生成一个符号,并且可以设置符号的方向以及缩放比例,简单点说就是对于你想关注的数据点添加符号标注,符号的样式由自己指定。
//比如你有一个曲面数据,希望将曲面数据的每个点都用锥体标注出来并且锥体的方向表示该点的法向量方向,这个时候就可以使用vtkGlyph3D。
}
void MainWindow::curvatures()
{
vtkSmartPointer<vtkPolyDataReader> reader = vtkSmartPointer<vtkPolyDataReader>::New();
reader->SetFileName("/home/silence/Project/VTK-Qt/shapeCommonOperatation/fran_cut.vtk");
reader->Update();
//计算曲率
vtkSmartPointer<vtkCurvatures> curvaturesFilter = vtkSmartPointer<vtkCurvatures>::New();
curvaturesFilter->SetInputConnection(reader->GetOutputPort());
//curvaturesFilter->SetCurvatureTypeToMinimum(); //最小曲率
curvaturesFilter->SetCurvatureTypeToMaximum(); //最大曲率
//curvaturesFilter->SetCurvatureTypeToGaussian();//高斯曲率
//curvaturesFilter->SetCurvatureTypeToMean(); //平均曲率
curvaturesFilter->Update();
//保存属性数据时,四种曲率数据分别对应属性名字为
//Minimum_Curvature/Maximum_Curvature/Gauss_Curvature/Mean_Curvature,
//因此可以通过属性名字获取相应的曲率数据。例如要获得高斯曲率数据,可调用:
//vtkDoubleArray *gauss = static_cast<vtkDoubleArray*>(curvaturesFilter->GetOutput()->GetpointData()->GetArray("Gauss_Curvature"));
double scalarRange[2];
curvaturesFilter->GetOutput()->GetScalarRange(scalarRange); //获得曲率标量数据的最大最小值
//建立查找表 做颜色映射
vtkSmartPointer<vtkLookupTable> lut = vtkSmartPointer<vtkLookupTable>::New();
lut->SetHueRange(0.0, 0.6);
lut->SetAlphaRange(1.0, 1.0);
lut->SetValueRange(1.0, 1.0);
lut->SetSaturationRange(1.0, 1.0);
lut->SetNumberOfTableValues(256); //表中有256个值
lut->SetRange(scalarRange); //设置颜色表最大最小值
lut->Build();
vtkSmartPointer<vtkPolyDataMapper> mapper = vtkSmartPointer<vtkPolyDataMapper>::New();
mapper->SetInputData(curvaturesFilter->GetOutput());
mapper->SetLookupTable(lut);
mapper->SetScalarRange(scalarRange);
vtkSmartPointer<vtkActor> actor = vtkSmartPointer<vtkActor>::New();
actor->SetMapper(mapper);
//设置标签
vtkSmartPointer<vtkScalarBarActor> scalarBar = vtkSmartPointer<vtkScalarBarActor>::New();
scalarBar->SetLookupTable(mapper->GetLookupTable());
scalarBar->SetTitle(curvaturesFilter->GetOutput()->GetPointData()->GetScalars()->GetName());
scalarBar->SetNumberOfLabels(5); //设置5个标签
vtkSmartPointer<vtkRenderer> render = vtkSmartPointer<vtkRenderer>::New();
render->AddActor(actor);
render->AddActor2D(scalarBar);
render->SetBackground(0, 0, 0);
vtkSmartPointer<vtkRenderWindow> rw = vtkSmartPointer<vtkRenderWindow>::New();
rw->AddRenderer(render);
rw->SetSize(640, 480);
rw->SetWindowName("Calculating PolyData Curvature");
vtkSmartPointer<vtkRenderWindowInteractor> rwi = vtkSmartPointer<vtkRenderWindowInteractor>::New();
rwi->SetRenderWindow(rw);
vtkSmartPointer<vtkInteractorStyleTrackballCamera> style = vtkSmartPointer<vtkInteractorStyleTrackballCamera>::New();
rwi->SetInteractorStyle(style);
rwi->Initialize();
rwi->Start();
}
| 40.15727 | 135 | 0.73487 | [
"render"
] |
780b0ab019756c911b5e11365958578989ae484a | 1,057 | hh | C++ | Spectra/CeMinusSpectrum.hh | brownd1978/TrackToy | e8839460693cd14caecbca0bef8259fe3e73413e | [
"Apache-2.0"
] | null | null | null | Spectra/CeMinusSpectrum.hh | brownd1978/TrackToy | e8839460693cd14caecbca0bef8259fe3e73413e | [
"Apache-2.0"
] | null | null | null | Spectra/CeMinusSpectrum.hh | brownd1978/TrackToy | e8839460693cd14caecbca0bef8259fe3e73413e | [
"Apache-2.0"
] | null | null | null | //
// Model of the CeMinus spectrum including radiative effects, see https://journals.aps.org/prd/abstract/10.1103/PhysRevD.94.051301
//
#ifndef TrackToy_Spectra_CeMinusSpectrum_hh
#define TrackToy_Spectra_CeMinusSpectrum_hh
#include "TrackToy/Spectra/Spectrum.hh"
#include <limits>
namespace TrackToy {
struct CeMinusSpectrumParams {
double EEnd_; // endpoint energy
CeMinusSpectrumParams(double emax) : EEnd_(emax) {}
};
class CeMinusSpectrum : public Spectrum {
public:
CeMinusSpectrum(CeMinusSpectrumParams const& params, double emin=0.0, double emax = std::numeric_limits<float>::max());
double rate(double energy) const override;
double integral(double elow, double ehigh, unsigned nstep=10000 ) const override;
double sample(double prob) const override;
auto const& params() const { return params_; }
private:
CeMinusSpectrumParams params_;
std::vector<double> cdf_; // CDF (for random sampling) (constant energy bins)
double eStep_; // energy step for the above
};
}
#endif
| 37.75 | 131 | 0.732261 | [
"vector",
"model"
] |
78109ef61c98b4dc57d3fb0851693c5c2705b5ab | 22,613 | cpp | C++ | src/ssGUI/Extensions/RoundedCorners.cpp | Neko-Box-Coder/ssGUI | 25e218fd79fea105a30737a63381cf8d0be943f6 | [
"Apache-2.0"
] | 15 | 2022-01-21T10:48:04.000Z | 2022-03-27T17:55:11.000Z | src/ssGUI/Extensions/RoundedCorners.cpp | Neko-Box-Coder/ssGUI | 25e218fd79fea105a30737a63381cf8d0be943f6 | [
"Apache-2.0"
] | null | null | null | src/ssGUI/Extensions/RoundedCorners.cpp | Neko-Box-Coder/ssGUI | 25e218fd79fea105a30737a63381cf8d0be943f6 | [
"Apache-2.0"
] | 4 | 2022-01-21T10:48:05.000Z | 2022-01-22T15:42:34.000Z | #include "ssGUI/Extensions/RoundedCorners.hpp"
#include "ssGUI/GUIObjectClasses/MainWindow.hpp" //For getting mouse position
namespace ssGUI::Extensions
{
RoundedCorners::RoundedCorners() : Container(nullptr), Enabled(true), RoundedCornersRadius(10), TargetShapes{0}, TargetVertices(), VerticesToRound(),
VerticesToRoundPrevVertices(), VerticesToRoundNextVertices()
{}
RoundedCorners::~RoundedCorners()
{}
RoundedCorners::RoundedCorners(RoundedCorners const& other)
{
Container = nullptr;
Enabled = other.IsEnabled();
RoundedCornersRadius = other.GetRoundedCornersRadius();
TargetShapes = other.TargetShapes;
TargetVertices = other.TargetVertices;
VerticesToRound = other.VerticesToRound;
VerticesToRoundPrevVertices = other.VerticesToRoundPrevVertices;
VerticesToRoundNextVertices = other.VerticesToRoundNextVertices;
}
double RoundedCorners::GetAngle(glm::vec2 a, glm::vec2 b)
{
glm::vec3 a3 = glm::vec3(a, 0);
glm::vec3 b3 = glm::vec3(b, 0);
return atan2(glm::cross(a3, b3).z, glm::dot(glm::vec2(a), glm::vec2(b)));
}
glm::vec3 RoundedCorners::Barycentric(glm::vec2 samplePoint, glm::vec2 a, glm::vec2 b, glm::vec2 c)
{
glm::vec2 v0 = b - a;
glm::vec2 v1 = c - a;
glm::vec2 v2 = samplePoint - a;
float d00 = glm::dot(v0, v0);
float d01 = glm::dot(v0, v1);
float d11 = glm::dot(v1, v1);
float d20 = glm::dot(v2, v0);
float d21 = glm::dot(v2, v1);
float denom = d00 * d11 - d01 * d01;
//All points are the same or not valid triangle
if(denom == 0)
return glm::vec3(0, 0, 0);
float v = (d11 * d20 - d01 * d21) / denom;
float w = (d00 * d21 - d01 * d20) / denom;
float u = 1.0 - v - w;
return glm::vec3(u, v, w);
}
void RoundedCorners::PlotArcPoints(glm::vec2 a, glm::vec2 b, glm::vec2 c, std::vector<glm::vec2>& plottedPoints)
{
//Let A be previous vertices and B be current and C be next
int roundRadius = RoundedCornersRadius;
//Check if the shortest side is lower than the rounded corner radius.
//If so, change the radius to that
double halfABLength = round(glm::distance(a, b) * 0.5);
double halfBCLength = round(glm::distance(c, b) * 0.5);
if(halfABLength < roundRadius)
roundRadius = halfABLength;
if(halfBCLength < roundRadius)
roundRadius = halfBCLength;
glm::vec2 ba = a-b;
glm::vec2 bc = c-b;
glm::vec2 nba = glm::normalize(ba);
glm::vec2 nbc = glm::normalize(bc);
//Vertices are either at the same place or on a line
if(nba + nbc == glm::vec2())
{
DEBUG_LINE("Vertices at same place or on a line");
return;
}
glm::vec2 midVec = glm::normalize(nba + nbc);
//Find the angle from ba to bc (https://stackoverflow.com/questions/21483999/using-atan2-to-find-angle-between-two-vectors/21486462#21486462)
//This is in radians
double angleABC = GetAngle(ba, bc);
angleABC = angleABC < 0 ? angleABC * -1 : angleABC;
//Find the rounded corner circle location, let that be CIR
//https://math.stackexchange.com/questions/797828/calculate-center-of-circle-tangent-to-two-lines-in-space
glm::dvec2 cird = glm::dvec2(b) + glm::dvec2(midVec) * (roundRadius / sin(angleABC * 0.5));
glm::vec2 cir = glm::vec2(cird);
//let that be t1(on ab) and t2(on bc)
//Find the tangent points by using cross porduct to find the perpendicular line on ab and ac
//and add it to the circle origin by radius to find t1 and t2.
glm::vec2 t1 = glm::normalize(glm::cross(glm::vec3(ba, 0), glm::vec3(0, 0, -1))) * (float)roundRadius + glm::vec3(cir, 0);
glm::vec2 t2 = glm::normalize(glm::cross(glm::vec3(bc, 0), glm::vec3(0, 0, 1))) * (float)roundRadius + glm::vec3(cir, 0);
//Find the angle between CIR --> t1 to CIR --> t2
glm::vec2 cirTot1 = t1 - cir;
glm::vec2 cirTot2 = t2 - cir;
double angleT1CirT2 = GetAngle(cirTot1, cirTot2);
bool invalidAngle = false;
if(angleT1CirT2 < 0)
{
DEBUG_LINE("anti-clockwise placements of vertices detected. Rounded corners failed.");
invalidAngle = true;
}
else if(angleT1CirT2 > pi())
{
DEBUG_LINE("Angle between 2 tangents should not be larger than 180 degrees. Rounded corners failed.");
invalidAngle = true;
}
if(invalidAngle)
{
DEBUG_LINE("angleT1CirT2: "<<angleT1CirT2);
DEBUG_LINE("a: "<<a.x<<", "<<a.y);
DEBUG_LINE("b: "<<b.x<<", "<<b.y);
DEBUG_LINE("c: "<<c.x<<", "<<c.y);
DEBUG_LINE("t1: "<<t1.x<<", "<<t1.y);
DEBUG_LINE("t2: "<<t2.x<<", "<<t2.y);
DEBUG_LINE("cir: "<<cir.x<<", "<<cir.y);
DEBUG_EXIT_PROGRAM();
return;
}
glm::vec2 cirOriginline = glm::vec2(1, 0);
double originLineToT1Angle = GetAngle(cirOriginline, cirTot1);
originLineToT1Angle = originLineToT1Angle < 0 ? 2 * pi() + originLineToT1Angle : originLineToT1Angle;
//https://stackoverflow.com/questions/15525941/find-points-on-circle
//Using the information with tangent points, angles between them and clockwise information
//Plot the arc
//std::vector<glm::ivec2> arcVertices = std::vector<glm::ivec2>();
// DEBUG_LINE("points: "<<((int)(roundRadius * angleT1CirT2 * 1) + 2));
int minSamples = 10;
int sampleCount = (int)(roundRadius * angleT1CirT2 * 1) + 2;
int finalSampleCount = sampleCount < 10 ? minSamples : sampleCount;
for(int i = 1; i < finalSampleCount; i++)
{
double currentAngle = originLineToT1Angle + angleT1CirT2 * ((double)i / (double)finalSampleCount);
glm::dvec2 plotPoint = glm::dvec2(cos(currentAngle), sin(currentAngle)) * (double)roundRadius;
plottedPoints.push_back(/*glm::ivec2(round(plotPoint.x), round(plotPoint.y))*/glm::vec2(plotPoint) + cir);
}
}
void RoundedCorners::GetStartEndVertexIndex(int currentIndex, int& startIndex, int& endIndex, std::vector<int> const & drawingCounts)
{
startIndex = 0;
endIndex = 0;
for(int i = 0; i < drawingCounts.size(); i++)
{
if(startIndex + drawingCounts[i] > currentIndex)
{
endIndex = startIndex + drawingCounts[i];
break;
}
startIndex += drawingCounts[i];
}
}
void RoundedCorners::UpdateVerticesForRounding()
{
FUNC_DEBUG_ENTRY();
VerticesToRound.clear();
VerticesToRoundPrevVertices.clear();
VerticesToRoundNextVertices.clear();
std::vector<glm::vec2>& drawingVertices = Container->Extension_GetDrawingVertices();
std::vector<int>& drawingCounts = Container->Extension_GetDrawingCounts();
int startIndex = 0;
int endIndex = drawingCounts[0];
if(!TargetVertices.empty())
{
for(int i = 0; i < TargetVertices.size(); i++)
{
int currentVertexIndex = TargetVertices[i] + Container->Extension_GetGUIObjectFirstVertexIndex();
//Invlaid index check
if(currentVertexIndex >= drawingVertices.size())
{
VerticesToRound.erase(VerticesToRound.begin() + i);
i--;
continue;
}
if(currentVertexIndex < startIndex || currentVertexIndex >= endIndex)
GetStartEndVertexIndex(currentVertexIndex, startIndex, endIndex, drawingCounts);
//Shape size check
if(endIndex - startIndex < 2)
continue;
VerticesToRound.push_back(currentVertexIndex);
int prevIndex = currentVertexIndex;
int loopCount = 0;
do
{
prevIndex = (prevIndex == startIndex ? endIndex - 1 : prevIndex - 1);
loopCount++;
if(loopCount > endIndex - startIndex + 1)
{
DEBUG_LINE("Failed to construct rounded corner");
VerticesToRound.clear();
VerticesToRoundPrevVertices.clear();
VerticesToRoundNextVertices.clear();
return;
}
}
while(drawingVertices[prevIndex] - drawingVertices[currentVertexIndex] == glm::vec2());
VerticesToRoundPrevVertices.push_back(prevIndex);
int nextIndex = currentVertexIndex;
loopCount = 0;
do
{
nextIndex = (nextIndex == endIndex - 1 ? startIndex : nextIndex + 1);
loopCount++;
if(loopCount > endIndex - startIndex + 1)
{
DEBUG_LINE("Failed to construct rounded corner");
VerticesToRound.clear();
VerticesToRoundPrevVertices.clear();
VerticesToRoundNextVertices.clear();
return;
}
}
while(drawingVertices[nextIndex] - drawingVertices[currentVertexIndex] == glm::vec2());
VerticesToRoundNextVertices.push_back(nextIndex);
}
}
else
{
for(int i = 0; i < TargetShapes.size(); i++)
{
//Invalid index check
if(TargetShapes[i] + Container->Extension_GetGUIObjectFirstShapeIndex() >= drawingCounts.size())
continue;
int curShape = TargetShapes[i] + Container->Extension_GetGUIObjectFirstShapeIndex();
//Shape size check
if(drawingCounts[curShape] < 3)
continue;
int startIndex = 0;
for(int j = 0; j < TargetShapes[i] + Container->Extension_GetGUIObjectFirstShapeIndex(); j++)
{
startIndex += drawingCounts[j];
}
if(drawingCounts[curShape] <= 2)
continue;
for(int j = startIndex; j < startIndex + drawingCounts[curShape]; j++)
{
VerticesToRound.push_back(j);
int prevIndex = j;
int loopCount = 0;
do
{
prevIndex = (prevIndex == startIndex ? startIndex + drawingCounts[curShape] - 1 : prevIndex - 1);
loopCount++;
if(loopCount > drawingCounts[curShape])
{
DEBUG_LINE("Failed to construct rounded corner");
VerticesToRound.clear();
VerticesToRoundPrevVertices.clear();
VerticesToRoundNextVertices.clear();
return;
}
}
while(drawingVertices[prevIndex] - drawingVertices[j] == glm::vec2());
VerticesToRoundPrevVertices.push_back(prevIndex);
int nextIndex = j;
loopCount = 0;
do
{
nextIndex = (nextIndex == startIndex + drawingCounts[curShape] - 1 ? startIndex : nextIndex + 1);
loopCount++;
if(loopCount > drawingCounts[curShape])
{
DEBUG_LINE("Failed to construct rounded corner");
VerticesToRound.clear();
VerticesToRoundPrevVertices.clear();
VerticesToRoundNextVertices.clear();
return;
}
}
while(drawingVertices[nextIndex] - drawingVertices[j] == glm::vec2());
VerticesToRoundNextVertices.push_back(nextIndex);
}
}
}
FUNC_DEBUG_EXIT();
}
void RoundedCorners::ConstructRenderInfo()
{
FUNC_DEBUG_ENTRY();
std::vector<glm::vec2>& drawingVertices = Container->Extension_GetDrawingVertices();
std::vector<glm::vec2>& drawingUVs = Container->Extension_GetDrawingUVs();
std::vector<glm::u8vec4>& drawingColors = Container->Extension_GetDrawingColours();
std::vector<int>& drawingCounts = Container->Extension_GetDrawingCounts();
std::vector<ssGUI::DrawingProperty>& drawingProperties = Container->Extension_GetDrawingProperties();
std::vector<glm::vec2> originalVertices = drawingVertices;
std::vector<glm::vec2> originalUVs = drawingUVs;
std::vector<glm::u8vec4> originalColors = drawingColors;
std::vector<int> originalCounts = drawingCounts;
std::vector<ssGUI::DrawingProperty> originalProperties = drawingProperties;
std::vector<glm::vec2> newVertices; //Lists of new vertices as arc
std::vector<glm::vec2> newUVs; //Associated UVs
std::vector<glm::u8vec4> newColors; //Associated colors
std::vector<int> newCounts; //The number vertices per arc
if(drawingCounts.empty())
{
FUNC_DEBUG_EXIT();
return;
}
UpdateVerticesForRounding();
//Iterate via each vertices
for(int i = 0; i < VerticesToRound.size(); i++)
{
//For each vertices, plot and save the arc to a list
int currentIndex = VerticesToRound[i];
int prevIndex = VerticesToRoundPrevVertices[i];
int nextIndex = VerticesToRoundNextVertices[i];
int prevNewVerticesCount = newVertices.size();
PlotArcPoints(drawingVertices[prevIndex], drawingVertices[currentIndex], drawingVertices[nextIndex], newVertices);
newCounts.push_back(newVertices.size() - prevNewVerticesCount);
//For each arc points, sample the UV and colors
for(int j = prevNewVerticesCount; j < newVertices.size(); j++)
{
glm::vec3 coord = Barycentric(newVertices[j], drawingVertices[prevIndex], drawingVertices[currentIndex], drawingVertices[nextIndex]);
newUVs.push_back((drawingUVs[prevIndex]) * coord.x +
(drawingUVs[currentIndex]) * coord.y +
(drawingUVs[nextIndex]) * coord.z);
newColors.push_back(glm::vec4(drawingColors[prevIndex]) * coord.x +
glm::vec4(drawingColors[currentIndex]) * coord.y +
glm::vec4(drawingColors[nextIndex]) * coord.z);
}
}
drawingVertices.clear();
drawingUVs.clear();
drawingColors.clear();
drawingCounts.clear();
drawingProperties.clear();
//Hashmap for holding the original vertex index as key and index in newVertices as value
std::map<int, int> verticesToRoundMap;
for(int i = 0; i < VerticesToRound.size(); i++)
verticesToRoundMap[VerticesToRound[i]] = i;
//Reconstruct vertices, uvs, etc.
int shapeIndex = 0;
int shapeStartIndex = 0;
int shapeEndIndex = originalCounts[0];
int currentDrawingCounts = 0;
for(int i = 0; i < originalVertices.size(); i++)
{
//Updates current shape index
if(i >= shapeEndIndex)
{
shapeStartIndex += originalCounts[shapeIndex];
shapeIndex++;
shapeEndIndex += originalCounts[shapeIndex];
currentDrawingCounts = 0;
}
//If adding original vertices
if(verticesToRoundMap.find(i) == verticesToRoundMap.end())
{
drawingVertices.push_back(originalVertices[i]);
drawingUVs.push_back(originalUVs[i]);
drawingColors.push_back(originalColors[i]);
currentDrawingCounts++;
}
//If adding arc vertices
else
{
int arcIndex = verticesToRoundMap[i];
int startIndex = 0;
for(int j = 0; j < arcIndex; j++)
startIndex += newCounts[j];
int endIndex = startIndex + newCounts[arcIndex];
for(int j = startIndex; j < endIndex; j++)
{
drawingVertices.push_back(newVertices[j]);
drawingUVs.push_back(newUVs[j]);
drawingColors.push_back(newColors[j]);
}
currentDrawingCounts += newCounts[arcIndex];
}
//Updates drawing counts
if(i+1 >= shapeEndIndex)
{
drawingCounts.push_back(currentDrawingCounts);
drawingProperties.push_back(originalProperties[shapeIndex]);
}
}
FUNC_DEBUG_EXIT();
}
void RoundedCorners::ConstructRenderInfo(ssGUI::Backend::BackendDrawingInterface* drawingInterface, ssGUI::GUIObject* mainWindow, glm::vec2 mainWindowPositionOffset)
{
ConstructRenderInfo();
}
const std::string RoundedCorners::EXTENSION_NAME = "Rounded Corners";
void RoundedCorners::SetRoundedCornersRadius(int radius)
{
RoundedCornersRadius = radius;
if(Container != nullptr)
Container->RedrawObject();
}
int RoundedCorners::GetRoundedCornersRadius() const
{
return RoundedCornersRadius;
}
void RoundedCorners::AddTargetShape(int shapeIndex)
{
TargetShapes.push_back(shapeIndex);
if(Container != nullptr)
Container->RedrawObject();
}
int RoundedCorners::GetTargetShape(int location) const
{
return TargetShapes[location];
}
void RoundedCorners::SetTargetShape(int location, int shapeIndex)
{
TargetShapes[location] = shapeIndex;
if(Container != nullptr)
Container->RedrawObject();
}
int RoundedCorners::GetTargetShapesCount() const
{
return TargetShapes.size();
}
void RoundedCorners::RemoveTargetShape(int location)
{
TargetShapes.erase(TargetShapes.begin() + location);
if(Container != nullptr)
Container->RedrawObject();
}
void RoundedCorners::ClearTargetShapes()
{
TargetShapes.clear();
if(Container != nullptr)
Container->RedrawObject();
}
void RoundedCorners::AddTargetVertex(int vertexIndex)
{
TargetVertices.push_back(vertexIndex);
if(Container != nullptr)
Container->RedrawObject();
}
int RoundedCorners::GetTargetVertex(int location) const
{
return TargetVertices[location];
}
void RoundedCorners::SetTargetVertex(int location, int vertexIndex)
{
TargetVertices[location] = vertexIndex;
if(Container != nullptr)
Container->RedrawObject();
}
int RoundedCorners::GetTargetVerticesCount() const
{
return TargetVertices.size();
}
void RoundedCorners::RemoveTargetVertex(int location)
{
TargetVertices.erase(TargetVertices.begin() + location);
if(Container != nullptr)
Container->RedrawObject();
}
void RoundedCorners::ClearTargetVertices()
{
TargetVertices.clear();
if(Container != nullptr)
Container->RedrawObject();
}
void RoundedCorners::SetEnabled(bool enabled)
{
Enabled = enabled;
Container->RedrawObject();
}
bool RoundedCorners::IsEnabled() const
{
return Enabled;
}
void RoundedCorners::Internal_Update(bool isPreUpdate, ssGUI::Backend::BackendSystemInputInterface* inputInterface, ssGUI::InputStatus& globalInputStatus, ssGUI::InputStatus& windowInputStatus, ssGUI::GUIObject* mainWindow)
{
FUNC_DEBUG_ENTRY();
if(!Enabled || Container == nullptr)
{
FUNC_DEBUG_EXIT();
return;
}
FUNC_DEBUG_EXIT();
}
void RoundedCorners::Internal_Draw(bool isPreRender, ssGUI::Backend::BackendDrawingInterface* drawingInterface, ssGUI::GUIObject* mainWindow, glm::vec2 mainWindowPositionOffset)
{
FUNC_DEBUG_ENTRY();
if(!Enabled || Container == nullptr || isPreRender)
{
FUNC_DEBUG_EXIT();
return;
}
if(Container->IsRedrawNeeded())
ConstructRenderInfo();
FUNC_DEBUG_EXIT();
}
std::string RoundedCorners::GetExtensionName()
{
return EXTENSION_NAME;
}
void RoundedCorners::BindToObject(ssGUI::GUIObject* bindObj)
{
Container = bindObj;
}
void RoundedCorners::Copy(ssGUI::Extensions::Extension* extension)
{
if(extension->GetExtensionName() != EXTENSION_NAME)
return;
ssGUI::Extensions::RoundedCorners* roundedCorners = static_cast<ssGUI::Extensions::RoundedCorners*>(extension);
Enabled = roundedCorners->IsEnabled();
RoundedCornersRadius = roundedCorners->GetRoundedCornersRadius();
TargetShapes = roundedCorners->TargetShapes;
TargetVertices = roundedCorners->TargetVertices;
VerticesToRound = roundedCorners->VerticesToRound;
VerticesToRoundPrevVertices = roundedCorners->VerticesToRoundPrevVertices;
VerticesToRoundNextVertices = roundedCorners->VerticesToRoundNextVertices;
}
ObjectsReferences* RoundedCorners::Internal_GetObjectsReferences()
{
return nullptr;
}
RoundedCorners* RoundedCorners::Clone(ssGUI::GUIObject* newContainer)
{
RoundedCorners* temp = new RoundedCorners(*this);
if(newContainer != nullptr)
newContainer->AddExtension(temp);
return temp;
}
} | 37.500829 | 227 | 0.565073 | [
"shape",
"vector"
] |
78134575ff7e1ef52eb06e7f26dcd486d70de0a0 | 397 | cpp | C++ | Codes/leetcode-with-errichto/april-challange/ContiguousArray-failed.cpp | fahimfarhan/legendary-coding-odyssey | 55289e05aa04f866201c607bed00c505cd9c4df9 | [
"MIT"
] | 3 | 2019-07-20T07:26:31.000Z | 2020-08-06T09:31:09.000Z | Codes/leetcode-with-errichto/april-challange/ContiguousArray-failed.cpp | fahimfarhan/legendary-coding-odyssey | 55289e05aa04f866201c607bed00c505cd9c4df9 | [
"MIT"
] | null | null | null | Codes/leetcode-with-errichto/april-challange/ContiguousArray-failed.cpp | fahimfarhan/legendary-coding-odyssey | 55289e05aa04f866201c607bed00c505cd9c4df9 | [
"MIT"
] | 4 | 2019-06-20T18:43:32.000Z | 2020-10-07T16:45:23.000Z | class Solution {
public:
int findMaxLength(vector<int>& nums) {
int zeroKount = 0, oneKount = 0, minimus = 0, maximus = 0;
for(int n : nums) {
if( (n&1) == 1) { oneKount++; }
else{ zeroKount++; }
}
minimus = min(zeroKount, oneKount);
maximus = minimus << 1; // x2
return maximus;
}
}; | 24.8125 | 70 | 0.453401 | [
"vector"
] |
7819f5d5cfebde6029608f854b33e682fdcb1c35 | 2,112 | cpp | C++ | test/unit/module/real/special/stirling.cpp | leha-bot/eve | 30e7a7f6bcc5cf524a6c2cc624234148eee847be | [
"MIT"
] | 340 | 2020-09-16T21:12:48.000Z | 2022-03-28T15:40:33.000Z | test/unit/module/real/special/stirling.cpp | leha-bot/eve | 30e7a7f6bcc5cf524a6c2cc624234148eee847be | [
"MIT"
] | 383 | 2020-09-17T06:56:35.000Z | 2022-03-13T15:58:53.000Z | test/unit/module/real/special/stirling.cpp | leha-bot/eve | 30e7a7f6bcc5cf524a6c2cc624234148eee847be | [
"MIT"
] | 28 | 2021-02-27T23:11:23.000Z | 2022-03-25T12:31:29.000Z | //==================================================================================================
/**
EVE - Expressive Vector Engine
Copyright : EVE Contributors & Maintainers
SPDX-License-Identifier: MIT
**/
//==================================================================================================
#include "test.hpp"
#include <eve/concept/value.hpp>
#include <eve/function/all.hpp>
#include <eve/function/stirling.hpp>
#include <type_traits>
#include <cmath>
#include <eve/constant/inf.hpp>
#include <eve/constant/minf.hpp>
#include <eve/constant/nan.hpp>
#include <eve/constant/zero.hpp>
#include <eve/constant/one.hpp>
#include <eve/platform.hpp>
//==================================================================================================
// Types tests
//==================================================================================================
EVE_TEST_TYPES( "Check return types of stirling"
, eve::test::simd::ieee_reals
)
<typename T>(eve::as<T>)
{
using v_t = eve::element_type_t<T>;
TTS_EXPR_IS( eve::stirling(T()) , T);
TTS_EXPR_IS( eve::stirling(v_t()), v_t);
};
//==================================================================================================
// stirling tests
//==================================================================================================
EVE_TEST_TYPES( "Check behavior of stirling on wide"
, eve::test::simd::ieee_reals
)
<typename T>(eve::as<T>)
{
using eve::stirling;
using eve::as;
if constexpr( eve::platform::supports_invalids )
{
TTS_ULP_EQUAL(stirling(eve::inf(eve::as<T>()) ) , eve::inf(eve::as<T>()), 0.5);
TTS_ULP_EQUAL(stirling(eve::minf(eve::as<T>()) ) , eve::nan(eve::as<T>()), 0.5);
TTS_ULP_EQUAL(stirling(eve::mone(eve::as<T>()) ) , eve::nan(eve::as<T>()), 0.5);
TTS_ULP_EQUAL(stirling(eve::nan(eve::as<T>()) ) , eve::nan(eve::as<T>()), 0.5);
}
TTS_ULP_EQUAL(eve::round(stirling(T(1))), T(1), 0.5);
TTS_ULP_EQUAL(eve::round(stirling(T(2))), T(1), 0.5);
TTS_ULP_EQUAL(eve::round(stirling(T(3))), T(2), 0.5);
};
| 36.413793 | 100 | 0.456913 | [
"vector"
] |
781b5b07e28f37b52a064df30607e3398f84f872 | 1,625 | cpp | C++ | iohandlers/SolutionHandler.cpp | jkerkela/best-sudoku-solver | fa850a6e3e8bbbb5bcb823ddafb9d264ac471311 | [
"MIT"
] | null | null | null | iohandlers/SolutionHandler.cpp | jkerkela/best-sudoku-solver | fa850a6e3e8bbbb5bcb823ddafb9d264ac471311 | [
"MIT"
] | 2 | 2019-07-20T19:16:22.000Z | 2019-07-20T19:16:23.000Z | iohandlers/SolutionHandler.cpp | jkerkela/best-sudoku-solver | fa850a6e3e8bbbb5bcb823ddafb9d264ac471311 | [
"MIT"
] | null | null | null | #include "SolutionHandler.h"
#include "../dlxnodes/DancingLinks.h"
#include "../Constants.h"
#include <iostream>
#include <list>
#include <vector>
#include <stdio.h>
using std::cout;
using std::endl;
using std::string;
using std::vector;
void SolutionHandler::handleSolution(vector<DancingLinkNode*> answer) {
int** sudokuGrid = parseBoard(answer);
printSolution(sudokuGrid);
}
int** SolutionHandler::parseBoard(vector<DancingLinkNode*> answer) {
//vector<vector<int>> result;
int** result = initializeSolutionArray();
for(DancingLinkNode* n : answer){
DancingLinkNode* node = n;
int min = stoi(node->C->name);
for (DancingLinkNode* tmp = n->R; tmp != n; tmp = tmp->R) {
int val = stoi(tmp->C->name);
if (val < min){
min = val;
node = tmp;
}
}
int ans1 = stoi(node->C->name);
int ans2 = stoi(node->R->C->name);
int r = ans1 / sudokuBoardSize;
int c = ans1 % sudokuBoardSize;
int num = (ans2 % sudokuBoardSize) + 1;
result[r][c] = num;
}
return result;
}
void SolutionHandler::printSolution(int** solutionGrid) {
for (int i = 0; i < sudokuBoardSize; i++) {
string ret = "";
for (int j = 0; j < sudokuBoardSize; j++) {
ret += std::to_string(solutionGrid[i][j]) + " ";
}
cout << ret << endl;
}
}
int** SolutionHandler::initializeSolutionArray() {
int** solutionGrid = new int*[9];
for (int i = 0; i < 9; i++) {
solutionGrid[i] = new int[9];
}
return solutionGrid;
}
| 27.083333 | 71 | 0.568 | [
"vector"
] |
781b804b9c5f3bee8c202748d9a31809ddab1a76 | 1,791 | cpp | C++ | PAT-Code/A1131. Subway Map.cpp | bailingnan/CodingHistory | 8ddd1c07fccb8ffb1a8065ab616367f68f075729 | [
"MIT"
] | null | null | null | PAT-Code/A1131. Subway Map.cpp | bailingnan/CodingHistory | 8ddd1c07fccb8ffb1a8065ab616367f68f075729 | [
"MIT"
] | null | null | null | PAT-Code/A1131. Subway Map.cpp | bailingnan/CodingHistory | 8ddd1c07fccb8ffb1a8065ab616367f68f075729 | [
"MIT"
] | null | null | null |
#include <iostream>
#include <vector>
using namespace std;
vector<vector<int>> v(10000);
int line[10000][10000], visit[10000], minCnt, minTransfer, start, end1;
vector<int> path, tempPath;
int transferCnt(vector<int> a) {
int cnt = -1, preLine = 0;
for (int i = 1; i < a.size(); i++) {
if (line[a[i - 1]][a[i]] != preLine) cnt++;
preLine = line[a[i - 1]][a[i]];
}
return cnt;
}
void dfs(int node, int cnt) {
if (node == end1 && (cnt < minCnt || (cnt == minCnt && transferCnt(tempPath) < minTransfer))) {
minCnt = cnt;
minTransfer = transferCnt(tempPath);
path = tempPath;
}
if (node == end1) return;
for (int i = 0; i < v[node].size(); i++) {
if (visit[v[node][i]] == 0) {
visit[v[node][i]] = 1;
tempPath.push_back(v[node][i]);
dfs(v[node][i], cnt + 1);
visit[v[node][i]] = 0;
tempPath.pop_back();
}
}
}
int main() {
int n, m, k, pre, temp;
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d%d", &m, &pre);
for (int j = 1; j < m; j++) {
scanf("%d", &temp);
v[pre].push_back(temp);
v[temp].push_back(pre);
line[pre][temp] = line[temp][pre] = i + 1;
pre = temp;
}
}
scanf("%d", &k);
for (int i = 0; i < k; i++) {
scanf("%d%d", &start, &end1);
minCnt = 99999, minTransfer = 99999;
tempPath.clear();
tempPath.push_back(start);
visit[start] = 1;
dfs(start, 0);
visit[start] = 0;
printf("%d\n", minCnt);
int preLine = 0, preTransfer = start;
for (int j = 1; j < path.size(); j++) {
if (line[path[j - 1]][path[j]] != preLine) {
if (preLine != 0) printf("Take Line#%d from %04d to %04d.\n", preLine, preTransfer, path[j - 1]);
preLine = line[path[j - 1]][path[j]];
preTransfer = path[j - 1];
}
}
printf("Take Line#%d from %04d to %04d.\n", preLine, preTransfer, end1);
}
return 0;
}
| 26.338235 | 101 | 0.556672 | [
"vector"
] |
781fc39db3439825056e7799d34673986a6d2410 | 1,453 | cc | C++ | base/win/i18n_unittest.cc | domenic/mojo | 53dda76fed90a47c35ed6e06baf833a0d44495b8 | [
"BSD-3-Clause"
] | 231 | 2015-01-08T09:04:44.000Z | 2021-12-30T03:03:10.000Z | base/win/i18n_unittest.cc | 1065672644894730302/Chromium | 239dd49e906be4909e293d8991e998c9816eaa35 | [
"BSD-3-Clause"
] | 5 | 2015-03-27T14:29:23.000Z | 2019-09-25T13:23:12.000Z | base/win/i18n_unittest.cc | 1065672644894730302/Chromium | 239dd49e906be4909e293d8991e998c9816eaa35 | [
"BSD-3-Clause"
] | 268 | 2015-01-21T05:53:28.000Z | 2022-03-25T22:09:01.000Z | // Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file contains unit tests for Windows internationalization funcs.
#include "testing/gtest/include/gtest/gtest.h"
#include "base/win/i18n.h"
#include "base/win/windows_version.h"
namespace base {
namespace win {
namespace i18n {
// Tests that at least one user preferred UI language can be obtained.
TEST(I18NTest, GetUserPreferredUILanguageList) {
std::vector<std::wstring> languages;
EXPECT_TRUE(GetUserPreferredUILanguageList(&languages));
EXPECT_NE(static_cast<std::vector<std::wstring>::size_type>(0),
languages.size());
for (std::vector<std::wstring>::const_iterator scan = languages.begin(),
end = languages.end(); scan != end; ++scan) {
EXPECT_FALSE((*scan).empty());
}
}
// Tests that at least one thread preferred UI language can be obtained.
TEST(I18NTest, GetThreadPreferredUILanguageList) {
std::vector<std::wstring> languages;
EXPECT_TRUE(GetThreadPreferredUILanguageList(&languages));
EXPECT_NE(static_cast<std::vector<std::wstring>::size_type>(0),
languages.size());
for (std::vector<std::wstring>::const_iterator scan = languages.begin(),
end = languages.end(); scan != end; ++scan) {
EXPECT_FALSE((*scan).empty());
}
}
} // namespace i18n
} // namespace win
} // namespace base
| 33.790698 | 74 | 0.708878 | [
"vector"
] |
78228a799acab65114bd38f5f2177ff72c7aeda3 | 14,544 | hpp | C++ | inference-engine/src/inference_engine/cpp_interfaces/impl/ie_infer_async_request_thread_safe_default.hpp | giulio1979/dldt | e7061922066ccefc54c8dae6e3215308ce9559e1 | [
"Apache-2.0"
] | 1 | 2021-07-30T17:03:50.000Z | 2021-07-30T17:03:50.000Z | inference-engine/src/inference_engine/cpp_interfaces/impl/ie_infer_async_request_thread_safe_default.hpp | Dipet/dldt | b2140c083a068a63591e8c2e9b5f6b240790519d | [
"Apache-2.0"
] | null | null | null | inference-engine/src/inference_engine/cpp_interfaces/impl/ie_infer_async_request_thread_safe_default.hpp | Dipet/dldt | b2140c083a068a63591e8c2e9b5f6b240790519d | [
"Apache-2.0"
] | null | null | null | // Copyright (C) 2018-2020 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#pragma once
#include <cpp_interfaces/exception2status.hpp>
#include <cpp_interfaces/ie_immediate_executor.hpp>
#include <cpp_interfaces/ie_task_executor.hpp>
#include <cpp_interfaces/interface/ie_iinfer_async_request_internal.hpp>
#include <exception>
#include <future>
#include <map>
#include <memory>
#include <mutex>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
#include "ie_infer_async_request_thread_safe_internal.hpp"
#include "ie_util_internal.hpp"
namespace InferenceEngine {
/**
* @class AsyncInferRequestThreadSafeDefault
* @brief Base class with default implementation of asynchronous multi staged inference request.
* To customize pipeline stages derived class should change the content
* of _pipeline member container. It consists of pairs of tasks and executors which will run the task.
* @note To synchronize derived context with stages
* derived class should call StopAndWait() function in destructor.
* @section Example
* Here is an example of asynchronous inference request implementation for some accelerator device.
* It uses 5 different executors to run different stages of synchronous inference request.
* @code
// Inherits from AsyncInferRequestThreadSafeDefault
class AcceleratorAsyncInferRequest : public AsyncInferRequestThreadSafeDefault {
// Store the pointer to the synchronous request and five executors
AcceleratorAsyncInferRequest(const AcceleratorSyncRequest::Ptr& syncRequest,
const ITaskExecutor::Ptr& preprocessExecutor,
const ITaskExecutor::Ptr& writeToDeviceExecutor,
const ITaskExecutor::Ptr& runOnDeviceExecutor,
const ITaskExecutor::Ptr& readFromDeviceExecutor,
const ITaskExecutor::Ptr& postProcessExecutor) :
_accSyncRequest{syncRequest},
_preprocessExecutor{preprocessExecutor},
_writeToDeviceExecutor{writeToDeviceExecutor},
_runOnDeviceExecutor{runOnDeviceExecutor},
_readFromDeviceExecutor{readFromDeviceExecutor},
_postProcessExecutor{postProcessExecutor}
{
// Five pipeline stages of synchronous infer request are run by different executors
_pipeline = {
{ _preprocessExecutor , [this] {
_accSyncRequest->Preprocess();
}},
{ _writeToDeviceExecutor , [this] {
_accSyncRequest->WriteToDevice();
}},
{ _runOnDeviceExecutor , [this] {
_accSyncRequest->RunOnDevice();
}},
{ _readFromDeviceExecutor , [this] {
_accSyncRequest->ReadFromDevice();
}},
{ _postProcessExecutor , [this] {
_accSyncRequest->PostProcess();
}},
};
}
// As all stages use _accSyncRequest member we should wait for all stages tasks before the destructor
destroy this member. ~AcceleratorAsyncInferRequest() { StopAndWait();
}
AcceleratorSyncRequest::Ptr _accSyncRequest;
ITaskExecutor::Ptr _preprocessExecutor, _writeToDeviceExecutor, _runOnDeviceExecutor,
_readFromDeviceExecutor, _postProcessExecutor;
};
* @endcode
*/
class AsyncInferRequestThreadSafeDefault : public AsyncInferRequestThreadSafeInternal {
public:
using Ptr = std::shared_ptr<AsyncInferRequestThreadSafeDefault>;
using AtomicCallback = std::atomic<IInferRequest::CompletionCallback>;
using Futures = std::vector<std::shared_future<void>>;
using Promise = std::shared_ptr<std::promise<void>>;
using Stage = std::pair<ITaskExecutor::Ptr, Task>;
using Pipeline = std::vector<Stage>;
enum Stage_e : std::uint8_t { executor, task };
explicit AsyncInferRequestThreadSafeDefault(const InferRequestInternal::Ptr& request,
const ITaskExecutor::Ptr& taskExecutor,
const ITaskExecutor::Ptr& callbackExecutor)
: _syncRequest {request},
_requestExecutor {taskExecutor},
_callbackExecutor {callbackExecutor},
_pipeline {{_requestExecutor, [this] {
_syncRequest->Infer();
}}} {}
~AsyncInferRequestThreadSafeDefault() {
StopAndWait();
}
/**
* @brief Waits for completion of all pipline stages
* Just use the last '_futures' member to wait pipeline completion
* If the pipeline raises an exception it will be rethrown here
*/
StatusCode Wait(int64_t millis_timeout) override {
if (millis_timeout < IInferRequest::WaitMode::RESULT_READY) {
THROW_IE_EXCEPTION << PARAMETER_MISMATCH_str + "Timeout can't be less "
<< IInferRequest::WaitMode::RESULT_READY << " for InferRequest::Wait\n";
}
auto status = std::future_status::deferred;
auto future = [&] {
std::lock_guard<std::mutex> lock {_mutex};
return _futures.empty() ? std::shared_future<void> {} : _futures.back();
}();
if (!future.valid()) {
return StatusCode::INFER_NOT_STARTED;
}
switch (millis_timeout) {
case IInferRequest::WaitMode::RESULT_READY: {
future.wait();
status = std::future_status::ready;
} break;
case IInferRequest::WaitMode::STATUS_ONLY: {
status = future.wait_for(std::chrono::milliseconds {0});
} break;
default: {
status = future.wait_for(std::chrono::milliseconds {millis_timeout});
} break;
}
if (std::future_status::ready == status) {
future.get();
return StatusCode::OK;
} else {
return StatusCode::RESULT_NOT_READY;
}
}
void StartAsync_ThreadUnsafe() override {
_syncRequest->checkBlobs();
RunFirstStage();
}
void Infer_ThreadUnsafe() override {
_syncRequest->checkBlobs();
_syncRequest->InferImpl();
}
void GetPerformanceCounts_ThreadUnsafe(std::map<std::string, InferenceEngineProfileInfo>& perfMap) const override {
_syncRequest->GetPerformanceCounts(perfMap);
}
void SetBlob_ThreadUnsafe(const char* name, const Blob::Ptr& data) override {
_syncRequest->SetBlob(name, data);
}
void SetBlob_ThreadUnsafe(const char* name, const Blob::Ptr& data, const PreProcessInfo& info) override {
_syncRequest->SetBlob(name, data, info);
}
void GetBlob_ThreadUnsafe(const char* name, Blob::Ptr& data) override {
_syncRequest->GetBlob(name, data);
}
void GetPreProcess_ThreadUnsafe(const char* name, const PreProcessInfo** info) const override {
_syncRequest->GetPreProcess(name, info);
}
void SetCompletionCallback_ThreadUnsafe(InferenceEngine::IInferRequest::CompletionCallback callback) override {
_callback = callback;
}
void GetUserData_ThreadUnsafe(void** data) override {
if (data == nullptr) THROW_IE_EXCEPTION << NOT_ALLOCATED_str;
*data = _userData;
}
void SetUserData_ThreadUnsafe(void* data) override {
_userData = data;
}
void SetBatch_ThreadUnsafe(int batch) override {
_syncRequest->SetBatch(batch);
}
void SetPointerToPublicInterface(InferenceEngine::IInferRequest::Ptr ptr) {
_publicInterface = std::shared_ptr<IInferRequest>(ptr.get(), [](IInferRequest*) {});
}
protected:
/**
* @brief Creates and run the first stage task. If destructor was not called add future to the futures list that
* would be used to wait pipeline finish
*/
void RunFirstStage() {
_itStage = _pipeline.begin();
_promise = {};
bool stop = [&] {
std::lock_guard<std::mutex> lock(_mutex);
if (!_stop) {
_futures.erase(std::remove_if(std::begin(_futures), std::end(_futures),
[](const std::shared_future<void>& future) {
if (future.valid()) {
return (std::future_status::ready ==
future.wait_for(std::chrono::milliseconds {0}));
} else {
return true;
}
}),
_futures.end());
_futures.emplace_back(_promise.get_future().share());
}
return _stop;
}();
if (!stop) {
try {
auto& firstStageExecutor = std::get<Stage_e::executor>(*_itStage);
IE_ASSERT(nullptr != firstStageExecutor);
firstStageExecutor->run(MakeNextStageTask());
} catch (...) {
_promise.set_exception(std::current_exception());
throw;
}
}
}
/**
* @brief Create a task whith next pipeline stage.
* Each call to MakeNextStageTask() generates `InferenceEngine::Task` objects for each stage.
* When stage task is called it incerements
* `_stage` counter, call `_pipeline` task for this stage and generates next stage task using
* MakeNextStageTask() and pass it to executor. On last stage or if the exception is raised from `_pipeline` task
* the last stage task is called or passed to callback executor if it is presented. The last stage task call the
* callback, if it is presented, capture the `_promise` member and use it to forward completion or exception to the
* one of `_futures` member
*/
Task MakeNextStageTask() {
return [this]() mutable {
StatusCode requestStatus = StatusCode::OK;
std::exception_ptr localCurrentException = nullptr;
auto& thisStage = *_itStage;
auto copyItStage = ++_itStage;
try {
auto& stageTask = std::get<Stage_e::task>(thisStage);
IE_ASSERT(nullptr != stageTask);
stageTask();
if (_pipeline.end() != _itStage) {
auto nextStage = *_itStage;
auto& nextStageExecutor = std::get<Stage_e::executor>(nextStage);
IE_ASSERT(nullptr != nextStageExecutor);
nextStageExecutor->run(MakeNextStageTask());
}
} catch (InferenceEngine::details::InferenceEngineException& ie_ex) {
requestStatus = ie_ex.hasStatus() ? ie_ex.getStatus() : StatusCode::GENERAL_ERROR;
localCurrentException = std::make_exception_ptr(ie_ex);
} catch (...) {
requestStatus = StatusCode::GENERAL_ERROR;
localCurrentException = std::current_exception();
}
if ((_pipeline.end() == copyItStage) || (nullptr != localCurrentException)) {
auto lastStageTask = [this, requestStatus, localCurrentException]() mutable {
auto promise = std::move(_promise);
auto callback = _callback.load();
if (setIsRequestBusy(false)) {
if (nullptr != callback) {
InferenceEngine::CurrentException() = localCurrentException;
try {
callback(_publicInterface, requestStatus);
} catch (...) {
localCurrentException = std::current_exception();
}
InferenceEngine::CurrentException() = nullptr;
}
if (nullptr == localCurrentException) {
promise.set_value();
} else {
promise.set_exception(localCurrentException);
}
}
};
if (nullptr == _callbackExecutor) {
lastStageTask();
} else {
_callbackExecutor->run(std::move(lastStageTask));
}
}
};
}
/**
* @brief Forbids pipeline start and wait for all started piplenes.
* @note Should be called in derived class destrutor to wait for completion of usage of derived context captured by
* pipline tasks
*/
void StopAndWait() {
_callback = nullptr;
{
std::lock_guard<std::mutex> lock(_mutex);
if (!_stop) {
_stop = true;
for (auto&& future : _futures) {
if (future.valid()) {
future.wait();
}
}
}
}
}
/**
* @brief Implements Infer() using StartAsync() and Wait()
*/
void InferUsingAsync() {
struct CallbackStorage {
explicit CallbackStorage(AtomicCallback& callback)
: _callbackRef(callback), _callback(callback.exchange(nullptr)) {}
~CallbackStorage() {
_callbackRef = _callback;
}
AtomicCallback& _callbackRef;
IInferRequest::CompletionCallback _callback;
} storage {_callback};
StartAsync_ThreadUnsafe();
Wait(InferenceEngine::IInferRequest::WaitMode::RESULT_READY);
}
InferRequestInternal::Ptr _syncRequest;
ITaskExecutor::Ptr _requestExecutor;
ITaskExecutor::Ptr _callbackExecutor;
void* _userData = nullptr;
AtomicCallback _callback = {nullptr};
IInferRequest::Ptr _publicInterface;
Pipeline _pipeline;
Pipeline::iterator _itStage;
std::promise<void> _promise;
mutable std::mutex _mutex;
Futures _futures;
bool _stop = false;
};
} // namespace InferenceEngine
| 40.853933 | 119 | 0.574395 | [
"vector"
] |
7823d9346a904692d1b6a7f9a059ab438c07a6f2 | 17,171 | cpp | C++ | _studio/mfx_lib/encode_hw/hevc/linux/g9/hevcehw_g9_fei_lin.cpp | asaechnx/MediaSDK | 8414944b895a2259f9f30cbe3ac975806a8d7bf3 | [
"MIT"
] | 1 | 2020-09-08T15:30:11.000Z | 2020-09-08T15:30:11.000Z | _studio/mfx_lib/encode_hw/hevc/linux/g9/hevcehw_g9_fei_lin.cpp | asaechnx/MediaSDK | 8414944b895a2259f9f30cbe3ac975806a8d7bf3 | [
"MIT"
] | null | null | null | _studio/mfx_lib/encode_hw/hevc/linux/g9/hevcehw_g9_fei_lin.cpp | asaechnx/MediaSDK | 8414944b895a2259f9f30cbe3ac975806a8d7bf3 | [
"MIT"
] | null | null | null | // Copyright (c) 2019 Intel Corporation
//
// 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 "mfx_common.h"
#if defined(MFX_ENABLE_H265_VIDEO_ENCODE) && defined (MFX_VA_LINUX)
#include "mfxfeihevc.h"
#include "hevcehw_g9_fei_lin.h"
#include "hevcehw_g9_va_lin.h"
#include "hevcehw_g9_va_packer_lin.h"
using namespace HEVCEHW;
using namespace HEVCEHW::Gen9;
using namespace HEVCEHW::Linux;
using namespace HEVCEHW::Linux::Gen9;
void FEI::Query1NoCaps(const FeatureBlocks& /*blocks*/, TPushQ1 Push)
{
Push(BLK_SetGuidMap
, [](const mfxVideoParam&, mfxVideoParam& /*out*/, StorageRW& strg) -> mfxStatus
{
auto& gmap = Glob::GuidToVa::GetOrConstruct(strg);
gmap[DXVA2_Intel_Encode_HEVC_Main] = VAGUID{ VAProfileHEVCMain, VAEntrypointFEI };
gmap[DXVA2_Intel_Encode_HEVC_Main10] = VAGUID{ VAProfileHEVCMain10, VAEntrypointFEI };
#if VA_CHECK_VERSION(1,2,0)
gmap[DXVA2_Intel_Encode_HEVC_Main422] = VAGUID{ VAProfileHEVCMain422_10, VAEntrypointFEI };
gmap[DXVA2_Intel_Encode_HEVC_Main422_10] = VAGUID{ VAProfileHEVCMain422_10, VAEntrypointFEI };
gmap[DXVA2_Intel_Encode_HEVC_Main444] = VAGUID{ VAProfileHEVCMain444, VAEntrypointFEI };
gmap[DXVA2_Intel_Encode_HEVC_Main444_10] = VAGUID{ VAProfileHEVCMain444_10, VAEntrypointFEI };
#endif
return MFX_ERR_NONE;
});
Push(BLK_SetVaCallChain
, [](const mfxVideoParam&, mfxVideoParam& /*out*/, StorageRW& strg) -> mfxStatus
{
auto& ddiExec = Glob::DDI_Execute::GetOrConstruct(strg);
ddiExec.Push([&](Glob::DDI_Execute::TRef::TExt prev, const DDIExecParam& ep)
{
MFX_CHECK(ep.Function == DDI_VA::VAFID_GetConfigAttributes, prev(ep));
using TArgs = decltype(TupleArgs(vaGetConfigAttributes));
ThrowAssert(!ep.In.pData || ep.In.Size != sizeof(TArgs), "Invalid arguments for VAFID_GetConfigAttributes");
TArgs& args = *(TArgs*)ep.In.pData;
auto& pAttr = std::get<3>(args);
auto& nAttr = std::get<4>(args);
auto pAttrInitial = pAttr;
auto nAttrInitial = nAttr;
std::vector<VAConfigAttrib> vAttr(pAttr, pAttr + nAttr);
vAttr.emplace_back(VAConfigAttrib{ VAConfigAttribFEIFunctionType, 0 });
pAttr = vAttr.data();
++nAttr;
auto sts = prev(ep);
MFX_CHECK_STS(sts);
MFX_CHECK(vAttr.back().value & VA_FEI_FUNCTION_ENC_PAK, MFX_ERR_DEVICE_FAILED);
std::copy_n(pAttr, nAttrInitial, pAttrInitial);
return sts;
});
return MFX_ERR_NONE;
});
}
void FEI::Query1WithCaps(const FeatureBlocks& /*blocks*/, TPushQ1 Push)
{
Push(BLK_CheckAndFix
, [](const mfxVideoParam&, mfxVideoParam& out, StorageW& /*strg*/) -> mfxStatus
{
mfxExtCodingOption3* pCO3 = ExtBuffer::Get(out);
MFX_CHECK(pCO3, MFX_ERR_NONE);
// HEVC FEI Encoder uses own controls to switch on LCU QP buffer
MFX_CHECK(!CheckOrZero(pCO3->EnableMBQP, mfxU16(MFX_CODINGOPTION_OFF), mfxU16(MFX_CODINGOPTION_UNKNOWN))
, MFX_WRN_INCOMPATIBLE_VIDEO_PARAM);
return MFX_ERR_NONE;
});
}
void FEI::Reset(const FeatureBlocks& /*blocks*/, TPushR Push)
{
Push(BLK_CancelTasks
, [](
const mfxVideoParam& /*par*/
, StorageRW& global
, StorageRW& /*local*/) -> mfxStatus
{
Glob::ResetHint::Get(global).Flags |= RF_CANCEL_TASKS;
return MFX_ERR_NONE;
});
}
void FEI::FrameSubmit(const FeatureBlocks& /*blocks*/, TPushFS Push)
{
Push(BLK_FrameCheck
, [this](
const mfxEncodeCtrl* pCtrl
, const mfxFrameSurface1* pSurf
, mfxBitstream& /*bs*/
, StorageW& global
, StorageRW& /*local*/) -> mfxStatus
{
MFX_CHECK(pSurf, MFX_ERR_NONE);// In case of frames draining in display order
MFX_CHECK(pCtrl, MFX_ERR_INVALID_VIDEO_PARAM);
eMFXHWType platform = Glob::VideoCore::Get(global).GetHWType();
bool isSKL = platform == MFX_HW_SCL
, isICLplus = platform >= MFX_HW_ICL;
// mfxExtFeiHevcEncFrameCtrl is a mandatory buffer
mfxExtFeiHevcEncFrameCtrl* EncFrameCtrl =
reinterpret_cast<mfxExtFeiHevcEncFrameCtrl*>(ExtBuffer::Get(*pCtrl, MFX_EXTBUFF_HEVCFEI_ENC_CTRL));
MFX_CHECK(EncFrameCtrl, MFX_ERR_INVALID_VIDEO_PARAM);
// Check HW limitations for mfxExtFeiHevcEncFrameCtrl parameters
MFX_CHECK(EncFrameCtrl->NumMvPredictors[0] <= 4, MFX_ERR_INVALID_VIDEO_PARAM);
MFX_CHECK(EncFrameCtrl->NumMvPredictors[1] <= 4, MFX_ERR_INVALID_VIDEO_PARAM);
MFX_CHECK(EncFrameCtrl->MultiPred[0] <= (isICLplus + 1), MFX_ERR_INVALID_VIDEO_PARAM);
MFX_CHECK(EncFrameCtrl->MultiPred[1] <= (isICLplus + 1), MFX_ERR_INVALID_VIDEO_PARAM);
MFX_CHECK(EncFrameCtrl->SubPelMode <= 3 && EncFrameCtrl->SubPelMode != 2, MFX_ERR_INVALID_VIDEO_PARAM);
MFX_CHECK(EncFrameCtrl->MVPredictor == 0
|| EncFrameCtrl->MVPredictor == 1
|| EncFrameCtrl->MVPredictor == 2
|| (EncFrameCtrl->MVPredictor == 3 && isICLplus)
|| EncFrameCtrl->MVPredictor == 7, MFX_ERR_INVALID_VIDEO_PARAM);
MFX_CHECK(EncFrameCtrl->ForceCtuSplit <= mfxU16(isSKL), MFX_ERR_INVALID_VIDEO_PARAM);
MFX_CHECK(EncFrameCtrl->FastIntraMode <= mfxU16(isSKL), MFX_ERR_INVALID_VIDEO_PARAM);
MFX_CHECK(!Check<mfxU16>(EncFrameCtrl->NumFramePartitions, (mfxU16)1, (mfxU16)2, (mfxU16)4, (mfxU16)8, (mfxU16)16), MFX_ERR_INVALID_VIDEO_PARAM);
MFX_CHECK(EncFrameCtrl->AdaptiveSearch <= 1, MFX_ERR_INVALID_VIDEO_PARAM);
if (EncFrameCtrl->SearchWindow)
{
MFX_CHECK(EncFrameCtrl->LenSP == 0
&& EncFrameCtrl->SearchPath == 0
&& EncFrameCtrl->RefWidth == 0
&& EncFrameCtrl->RefHeight == 0, MFX_ERR_INVALID_VIDEO_PARAM);
MFX_CHECK(EncFrameCtrl->SearchWindow <= 5, MFX_ERR_INVALID_VIDEO_PARAM);
}
else
{
MFX_CHECK(EncFrameCtrl->SearchPath <= 2, MFX_ERR_INVALID_VIDEO_PARAM);
MFX_CHECK(EncFrameCtrl->LenSP >= 1 && EncFrameCtrl->LenSP <= 63, MFX_ERR_INVALID_VIDEO_PARAM);
MFX_CHECK(!EncFrameCtrl->AdaptiveSearch || EncFrameCtrl->LenSP >= 2, MFX_ERR_INVALID_VIDEO_PARAM);
if (isSKL)
{
Defaults::Param ccpar(
Glob::VideoParam::Get(global)
, Glob::EncodeCaps::Get(global)
, platform
, Glob::Defaults::Get(global));
FrameBaseInfo fi;
auto sts = ccpar.base.GetPreReorderInfo(ccpar, fi, pSurf, pCtrl, m_lastIDR, m_prevIPoc, m_frameOrder);
MFX_CHECK_STS(sts);
SetIf(m_frameOrder, !!ccpar.mvp.mfx.EncodedOrder, pSurf->Data.FrameOrder);
SetIf(m_lastIDR, IsIdr(fi.FrameType), m_frameOrder);
SetIf(m_prevIPoc, IsI(fi.FrameType), fi.POC);
++m_frameOrder;
MFX_CHECK(EncFrameCtrl->RefWidth % 4 == 0
&& EncFrameCtrl->RefHeight % 4 == 0
&& EncFrameCtrl->RefWidth <= (32 * (2 - IsB(fi.FrameType)))
&& EncFrameCtrl->RefHeight <= (32 * (2 - IsB(fi.FrameType)))
&& EncFrameCtrl->RefWidth >= 20
&& EncFrameCtrl->RefHeight >= 20
&& EncFrameCtrl->RefWidth * EncFrameCtrl->RefHeight <= 2048,
// For B frames actual limit is RefWidth*RefHeight <= 1024.
// Is is already guranteed by limit of 32 pxls for RefWidth and RefHeight in case of B frame
MFX_ERR_INVALID_VIDEO_PARAM);
}
else
{
// ICL+
MFX_CHECK((EncFrameCtrl->RefWidth == 64 && EncFrameCtrl->RefHeight == 64)
|| (EncFrameCtrl->RefWidth == 48 && EncFrameCtrl->RefHeight == 40),
MFX_ERR_INVALID_VIDEO_PARAM);
}
}
// Check if requested buffers are provided
MFX_CHECK(
!EncFrameCtrl->MVPredictor
|| ExtBuffer::Get(*pCtrl, MFX_EXTBUFF_HEVCFEI_ENC_MV_PRED)
, MFX_ERR_INVALID_VIDEO_PARAM);
MFX_CHECK(!EncFrameCtrl->PerCuQp
|| ExtBuffer::Get(*pCtrl, MFX_EXTBUFF_HEVCFEI_ENC_QP)
, MFX_ERR_INVALID_VIDEO_PARAM);
MFX_CHECK(!EncFrameCtrl->PerCtuInput
|| ExtBuffer::Get(*pCtrl, MFX_EXTBUFF_HEVCFEI_ENC_CTU_CTRL)
, MFX_ERR_INVALID_VIDEO_PARAM);
// Check for mfxExtFeiHevcRepackCtrl
mfxExtFeiHevcRepackCtrl* repackctrl =
reinterpret_cast<mfxExtFeiHevcRepackCtrl*>(ExtBuffer::Get(*pCtrl, MFX_EXTBUFF_HEVCFEI_REPACK_CTRL));
MFX_CHECK(!repackctrl || !EncFrameCtrl->PerCuQp, MFX_ERR_INVALID_VIDEO_PARAM);
MFX_CHECK(!repackctrl || repackctrl->NumPasses <= 8, MFX_ERR_INVALID_VIDEO_PARAM);
return MFX_ERR_NONE;
});
}
void FEI::PostReorderTask(const FeatureBlocks& /*blocks*/, TPushPostRT Push)
{
Push(BLK_UpdatePPS
, [](StorageW& global, StorageW& s_task) -> mfxStatus
{
auto& task = Task::Common::Get(s_task);
auto& pps = Glob::PPS::Get(global);
mfxExtFeiHevcEncFrameCtrl* EncFrameCtrl =
reinterpret_cast<mfxExtFeiHevcEncFrameCtrl*>(ExtBuffer::Get(task.ctrl, MFX_EXTBUFF_HEVCFEI_ENC_CTRL));
mfxExtFeiHevcRepackCtrl* repackctrl =
reinterpret_cast<mfxExtFeiHevcRepackCtrl*>(ExtBuffer::Get(task.ctrl, MFX_EXTBUFF_HEVCFEI_REPACK_CTRL));
bool bRepackPPS = false;
// repackctrl or PerCuQp is disabled, so insert PPS and turn the flag off.
bRepackPPS |= pps.cu_qp_delta_enabled_flag && !repackctrl && !EncFrameCtrl->PerCuQp;
// repackctrl or PerCuQp is enabled, so insert PPS and turn the flag on.
bRepackPPS |= !pps.cu_qp_delta_enabled_flag && (repackctrl || EncFrameCtrl->PerCuQp);
MFX_CHECK(bRepackPPS, MFX_ERR_NONE);
pps.cu_qp_delta_enabled_flag = 1 - pps.cu_qp_delta_enabled_flag;
// If state of CTU QP buffer changes, PPS header update required
task.RepackHeaders |= INSERT_PPS;
task.InsertHeaders |= INSERT_PPS;
return MFX_ERR_NONE;
});
}
template<class TEB, class TBase>
inline mfxU32 GetVaBufferID(TBase* pBase, mfxU32 ID, bool bSearch = true)
{
if (!pBase || !bSearch)
return VA_INVALID_ID;
auto pEB = reinterpret_cast<TEB*>(ExtBuffer::Get(*pBase, ID));
if (!pEB)
return VA_INVALID_ID;
return pEB->VaBufferID;
}
void FEI::SubmitTask(const FeatureBlocks& /*blocks*/, TPushST Push)
{
Push(BLK_SetTaskVaParam
, [this](StorageW& global, StorageW& s_task) -> mfxStatus
{
auto& task = Task::Common::Get(s_task);
mfxExtFeiHevcEncFrameCtrl* EncFrameCtrl =
reinterpret_cast<mfxExtFeiHevcEncFrameCtrl*>(ExtBuffer::Get(task.ctrl, MFX_EXTBUFF_HEVCFEI_ENC_CTRL));
MFX_CHECK(EncFrameCtrl, MFX_ERR_UNDEFINED_BEHAVIOR);
m_pVaFrameCtrl->function = VA_FEI_FUNCTION_ENC_PAK;
m_pVaFrameCtrl->search_path = EncFrameCtrl->SearchPath;
m_pVaFrameCtrl->len_sp = EncFrameCtrl->LenSP;
m_pVaFrameCtrl->ref_width = EncFrameCtrl->RefWidth;
m_pVaFrameCtrl->ref_height = EncFrameCtrl->RefHeight;
m_pVaFrameCtrl->search_window = EncFrameCtrl->SearchWindow;
m_pVaFrameCtrl->num_mv_predictors_l0 = mfxU16(!!EncFrameCtrl->MVPredictor * EncFrameCtrl->NumMvPredictors[0]);
m_pVaFrameCtrl->num_mv_predictors_l1 = mfxU16(!!EncFrameCtrl->MVPredictor * EncFrameCtrl->NumMvPredictors[1]);
m_pVaFrameCtrl->multi_pred_l0 = EncFrameCtrl->MultiPred[0];
m_pVaFrameCtrl->multi_pred_l1 = EncFrameCtrl->MultiPred[1];
m_pVaFrameCtrl->sub_pel_mode = EncFrameCtrl->SubPelMode;
m_pVaFrameCtrl->adaptive_search = EncFrameCtrl->AdaptiveSearch;
m_pVaFrameCtrl->mv_predictor_input = EncFrameCtrl->MVPredictor;
m_pVaFrameCtrl->per_block_qp = EncFrameCtrl->PerCuQp;
m_pVaFrameCtrl->per_ctb_input = EncFrameCtrl->PerCtuInput;
m_pVaFrameCtrl->force_lcu_split = EncFrameCtrl->ForceCtuSplit;
m_pVaFrameCtrl->num_concurrent_enc_frame_partition = EncFrameCtrl->NumFramePartitions;
m_pVaFrameCtrl->fast_intra_mode = EncFrameCtrl->FastIntraMode;
// Input buffers
m_pVaFrameCtrl->mv_predictor =
GetVaBufferID<mfxExtFeiHevcEncMVPredictors>(&task.ctrl, MFX_EXTBUFF_HEVCFEI_ENC_MV_PRED, !!EncFrameCtrl->MVPredictor);
m_pVaFrameCtrl->qp =
GetVaBufferID<mfxExtFeiHevcEncQP>(&task.ctrl, MFX_EXTBUFF_HEVCFEI_ENC_QP, !!EncFrameCtrl->PerCuQp);
m_pVaFrameCtrl->ctb_ctrl =
GetVaBufferID<mfxExtFeiHevcEncCtuCtrl>(&task.ctrl, MFX_EXTBUFF_HEVCFEI_ENC_QP, !!EncFrameCtrl->PerCtuInput);
auto* repackctrl = reinterpret_cast<mfxExtFeiHevcRepackCtrl*>(ExtBuffer::Get(task.ctrl, MFX_EXTBUFF_HEVCFEI_REPACK_CTRL));
if (repackctrl)
{
m_pVaFrameCtrl->max_frame_size = repackctrl->MaxFrameSize;
m_pVaFrameCtrl->num_passes = repackctrl->NumPasses;
m_pVaFrameCtrl->delta_qp = repackctrl->DeltaQP;
}
// Output buffers
#if MFX_VERSION >= MFX_VERSION_NEXT
m_pVaFrameCtrl->ctb_cmd = GetVaBufferID<mfxExtFeiHevcPakCtuRecordV0>(task.pBsOut, MFX_EXTBUFF_HEVCFEI_PAK_CTU_REC);
m_pVaFrameCtrl->cu_record = GetVaBufferID<mfxExtFeiHevcPakCuRecordV0>(task.pBsOut, MFX_EXTBUFF_HEVCFEI_PAK_CU_REC);
m_pVaFrameCtrl->distortion = GetVaBufferID<mfxExtFeiHevcDistortion>(task.pBsOut, MFX_EXTBUFF_HEVCFEI_ENC_DIST);
#else
m_pVaFrameCtrl->ctb_cmd = VA_INVALID_ID;
m_pVaFrameCtrl->cu_record = VA_INVALID_ID;
m_pVaFrameCtrl->distortion = VA_INVALID_ID;
#endif
return MFX_ERR_NONE;
});
}
void FEI::InitAlloc(const FeatureBlocks& blocks, TPushIA Push)
{
Push(BLK_SetFeedbackCallChain
, [this](StorageRW& strg, StorageRW& /*local*/) -> mfxStatus
{
auto& cc = VAPacker::CC::Get(strg);
cc.ReadFeedback.Push([](
VAPacker::CallChains::TReadFeedback::TExt prev
, const StorageR& global
, StorageW& s_task
, const VACodedBufferSegment& fb)
{
auto& task = Task::Common::Get(s_task);
mfxExtFeiHevcRepackStat *repackStat = reinterpret_cast<mfxExtFeiHevcRepackStat *>
(ExtBuffer::Get(task.ctrl, MFX_EXTBUFF_HEVCFEI_REPACK_STAT));
if (repackStat)
{
repackStat->NumPasses = 0;
mfxExtFeiHevcRepackCtrl* repackctrl = reinterpret_cast<mfxExtFeiHevcRepackCtrl*>
(ExtBuffer::Get(task.ctrl, MFX_EXTBUFF_HEVCFEI_REPACK_CTRL));
if (repackctrl)
{
mfxU8 QP = fb.status & VA_CODED_BUF_STATUS_PICTURE_AVE_QP_MASK;
mfxU8 QPOption = task.QpY;
mfxU32 numPasses = 0;
while ((QPOption != QP) && (numPasses < repackctrl->NumPasses))
QPOption += repackctrl->DeltaQP[numPasses++];
if (QPOption == QP)
repackStat->NumPasses = numPasses + 1;
}
}
return prev(global, s_task, fb);
});
m_pVaFrameCtrl = &AddVaMisc<VAEncMiscParameterFEIFrameControlHEVC>(
VAEncMiscParameterTypeFEIFrameControl, m_vaMiscData);
return MFX_ERR_NONE;
});
}
#endif //defined(MFX_ENABLE_H265_VIDEO_ENCODE)
| 43.251889 | 153 | 0.639741 | [
"vector"
] |
78240f6aaeb9897306c6aa738b8795bb71189cfd | 24,520 | cpp | C++ | install/TexGen/GUI/ControlsWindow.cpp | dalexa10/puma | ca02309c9f5c71e2e80ad8d64155dd6ca936c667 | [
"NASA-1.3"
] | 14 | 2021-06-17T17:17:07.000Z | 2022-03-26T05:20:20.000Z | install/TexGen/GUI/ControlsWindow.cpp | dalexa10/puma | ca02309c9f5c71e2e80ad8d64155dd6ca936c667 | [
"NASA-1.3"
] | 6 | 2021-11-01T20:37:39.000Z | 2022-03-11T17:18:53.000Z | install/TexGen/GUI/ControlsWindow.cpp | dalexa10/puma | ca02309c9f5c71e2e80ad8d64155dd6ca936c667 | [
"NASA-1.3"
] | 8 | 2021-07-20T09:24:23.000Z | 2022-02-26T16:32:00.000Z | /*=============================================================================
TexGen: Geometric textile modeller.
Copyright (C) 2006 Martin Sherburn
This program is free software; you can redistribute it 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 program 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, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
=============================================================================*/
#include "PrecompiledHeaders.h"
#include "ControlsWindow.h"
#include "WindowIDs.h"
#include "Modeller.h"
#include "CustomWidget.h"
CControlsWindow::CControlsWindow(wxMenuBar* pMenuBar, wxWindow* parent, wxWindowID id)
: wxChoicebook(parent, id)
, m_pMenuBar(pMenuBar)
, m_bUpdatingPositionText(false)
{
BuildControls();
}
CControlsWindow::~CControlsWindow(void)
{
}
void CControlsWindow::BuildControls()
{
BuildTextilesPage();
BuildModellerPage();
BuildDomainsPage();
BuildRenderingPage();
BuildPythonPage();
BuildToolsPage();
BuildOptionsPage();
ResizePages();
}
void CControlsWindow::ResizePages()
{
size_t i;
wxSizer *pSizer;
int x = 0;
int y = 0;
for (i=0; i<GetPageCount(); ++i)
{
pSizer = GetPage(i)->GetSizer();
if (pSizer)
{
x = max(x, pSizer->GetMinSize().x);
y = max(y, pSizer->GetMinSize().y);
}
}
for (i=0; i<GetPageCount(); ++i)
{
pSizer = GetPage(i)->GetSizer();
if (pSizer)
{
pSizer->SetDimension(0, 0, x, y);
}
}
SetSize(x, y);
}
void CControlsWindow::BuildTextilesPage()
{
wxNotebookPage *pControls = new wxNotebookPage(this, wxID_ANY);
wxBoxSizer *pMainSizer = new wxBoxSizer(wxVERTICAL);
wxSizerFlags SizerFlags(0);
// SizerFlags.Border(wxALL, 1);
SizerFlags.Expand();
vector<wxSizer*> SubSizers;
wxSizer *pSubSizer;
pSubSizer = new wxStaticBoxSizer(wxVERTICAL, pControls, wxT("Create:"));
pSubSizer->Add(new wxButton(pControls, ID_CreateEmptyTextile, wxT("Empty"), wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT), SizerFlags);
pSubSizer->Add(new wxButton(pControls, ID_Create2DWeave, wxT("Weave"), wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT), SizerFlags);
pSubSizer->Add(new wxButton(pControls, ID_Create3DTextile, wxT("3D Weave"), wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT), SizerFlags);
pSubSizer->Add(new wxButton(pControls, ID_CreateLayeredTextile, wxT("Layered"), wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT), SizerFlags);
// pSubSizer->Add(new wxButton(pControls, wxID_ANY, "Braid", wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT), SizerFlags);
pMainSizer->Add(pSubSizer, SizerFlags);
SubSizers.push_back(pSubSizer);
// NOTE: TEMPORARILY DISABLED UNTIL A BETTER WAY TO DEAL WITH LONG RUNNING TASKS IS FOUND...
/* pSubSizer = new wxStaticBoxSizer(wxVERTICAL, pControls, wxT("Algorithms:"));
pSubSizer->Add(new wxButton(pControls, ID_GeometrySolve, wxT("Geometry Solve"), wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT), SizerFlags);
pMainSizer->Add(pSubSizer, SizerFlags);
SubSizers.push_back(pSubSizer);*/
pSubSizer = new wxStaticBoxSizer(wxVERTICAL, pControls, wxT("")/*"Existing:"*/);
pSubSizer->Add(new wxButton(pControls, ID_EditTextile, wxT("Edit"), wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT), SizerFlags);
pSubSizer->Add(new wxButton(pControls, ID_DeleteTextile, wxT("Delete"), wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT), SizerFlags);
pSubSizer->Add(new wxButton(pControls, ID_RotateTextile, wxT("Rotate"), wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT), SizerFlags);
pMainSizer->Add(pSubSizer, SizerFlags);
SubSizers.push_back(pSubSizer);
int i;
for (i=0; i<(int)SubSizers.size(); ++i)
{
SubSizers[i]->SetDimension(0, 0, pMainSizer->GetMinSize().x, SubSizers[i]->GetMinSize().y);
}
pControls->SetSizer(pMainSizer);
AddPage(pControls, wxT("Textiles"));
wxMenu *pMenu = new wxMenu;
pMenu->Append(ID_CreateEmptyTextile, wxT("Create Empty..."));
pMenu->Append(ID_Create2DWeave, wxT("Create Weave..."));
pMenu->Append(ID_Create3DTextile, wxT("Create 3D Weave..."));
pMenu->Append(ID_CreateLayeredTextile, wxT("Create Layered..."));
pMenu->Append(ID_SetLayerOffsets, wxT("Set Layer Offsets"));
//pMenu->Append(ID_NestLayers, wxT("&Nest Layers"));
{
wxMenu *pNestingSubMenu = new wxMenu;
{
pNestingSubMenu->Append(ID_NestLayers, wxT("Keep Offsets"));
pNestingSubMenu->Append(ID_MaxNestLayers, wxT("Maximum nesting"));
}
pMenu->Append(wxID_ANY, wxT("&Nest Layers"), pNestingSubMenu);
}
// pMenu->Append(wxID_ANY, "Create Braid...");
pMenu->AppendSeparator();
// NOTE: TEMPORARILY DISABLED UNTIL A BETTER WAY TO DEAL WITH LONG RUNNING TASKS IS FOUND...
/* pMenu->Append(ID_GeometrySolve, wxT("Geometry Solve..."));
pMenu->AppendSeparator();*/
pMenu->Append(ID_EditTextile, wxT("Edit Textile..."));
pMenu->Append(ID_DeleteTextile, wxT("Delete Textile"));
pMenu->Append(ID_RotateTextile, wxT("Rotate Textile"));
m_pMenuBar->Append(pMenu, wxT("&Textiles"));
}
void CControlsWindow::BuildModellerPage()
{
wxNotebookPage *pControls = new wxNotebookPage(this, wxID_ANY);
wxBoxSizer *pMainSizer = new wxBoxSizer(wxVERTICAL);
wxSizerFlags SizerFlags(0);
// SizerFlags.Border(wxALL, 1);
SizerFlags.Expand();
vector<wxSizer*> SubSizers;
wxSizer *pSubSizer;
{
pSubSizer = new wxStaticBoxSizer(wxVERTICAL, pControls, wxT("Create:"));
{
pSubSizer->Add(new wxButton(pControls, ID_CreateYarn, wxT("Yarn"), wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT), SizerFlags);
}
pMainSizer->Add(pSubSizer, SizerFlags);
SubSizers.push_back(pSubSizer);
pSubSizer = new wxStaticBoxSizer(wxVERTICAL, pControls, wxT("Assign:"));
{
pSubSizer->Add(new wxButton(pControls, ID_AssignSection, wxT("Section"), wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT), SizerFlags);
pSubSizer->Add(new wxButton(pControls, ID_AssignInterpolation, wxT("Interpolation"), wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT), SizerFlags);
pSubSizer->Add(new wxButton(pControls, ID_AssignRepeats, wxT("Repeats"), wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT), SizerFlags);
pSubSizer->Add(new wxButton(pControls, ID_AssignProperties, wxT("Yarn Properties"), wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT), SizerFlags);
pSubSizer->Add(new wxButton(pControls, ID_AssignMatrixProperties, wxT("Matrix Properties"), wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT), SizerFlags);
}
pMainSizer->Add(pSubSizer, SizerFlags);
SubSizers.push_back(pSubSizer);
/* pSubSizer = new wxStaticBoxSizer(wxVERTICAL, pControls, wxT("Dialogs:"));
{
pSubSizer->Add(new wxButton(pControls, ID_ShowOutliner, wxT("Outliner"), wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT), SizerFlags);
}
pMainSizer->Add(pSubSizer, SizerFlags);
SubSizers.push_back(pSubSizer);*/
wxSizer *pSubSubSizer;
wxTextCtrl *pTextCtrl;
pSubSizer = new wxStaticBoxSizer(wxVERTICAL, pControls, wxT("Position:"));
{
pSubSubSizer = new wxBoxSizer(wxHORIZONTAL);
pSubSubSizer->Add(new wxStaticText(pControls, wxID_ANY, wxT("X:")), wxSizerFlags(0).Centre());
pSubSubSizer->Add(pTextCtrl = new wxTextCtrl(pControls, ID_PositionX, wxT("0.0"), wxDefaultPosition, wxSize(50, -1)), wxSizerFlags(1).Centre());
pTextCtrl->SetValidator(wxTextValidator(wxFILTER_NUMERIC, &m_PositionX));
pSubSizer->Add(pSubSubSizer, SizerFlags);
}
{
pSubSubSizer = new wxBoxSizer(wxHORIZONTAL);
pSubSubSizer->Add(new wxStaticText(pControls, wxID_ANY, wxT("Y:")), wxSizerFlags(0).Centre());
pSubSubSizer->Add(pTextCtrl = new wxTextCtrl(pControls, ID_PositionY, wxT("0.0"), wxDefaultPosition, wxSize(50, -1)), wxSizerFlags(1).Centre());
pTextCtrl->SetValidator(wxTextValidator(wxFILTER_NUMERIC, &m_PositionY));
pSubSizer->Add(pSubSubSizer, SizerFlags);
}
{
pSubSubSizer = new wxBoxSizer(wxHORIZONTAL);
pSubSubSizer->Add(new wxStaticText(pControls, wxID_ANY, wxT("Z:")), wxSizerFlags(0).Centre());
pSubSubSizer->Add(pTextCtrl = new wxTextCtrl(pControls, ID_PositionZ, wxT("0.0"), wxDefaultPosition, wxSize(50, -1)), wxSizerFlags(1).Centre());
pTextCtrl->SetValidator(wxTextValidator(wxFILTER_NUMERIC, &m_PositionZ));
pSubSizer->Add(pSubSubSizer, SizerFlags);
}
pMainSizer->Add(pSubSizer, SizerFlags);
SubSizers.push_back(pSubSizer);
pSubSizer = new wxStaticBoxSizer(wxVERTICAL, pControls, wxT("Snapping:"));
{
pSubSizer->Add(new wxCheckBox(pControls, ID_Snap, wxT("Snap")), SizerFlags);
pSubSizer->Add(new wxCheckBox(pControls, ID_Relative, wxT("Relative")), SizerFlags);
{
pSubSubSizer = new wxBoxSizer(wxHORIZONTAL);
pSubSubSizer->Add(new wxStaticText(pControls, wxID_ANY, wxT("Size:")), wxSizerFlags(0).Centre());
pSubSubSizer->Add(pTextCtrl = new wxTextCtrl(pControls, ID_SnapSize, wxT("0.1"), wxDefaultPosition, wxSize(50, -1)), wxSizerFlags(1).Centre());
pTextCtrl->SetValidator(wxTextValidator(wxFILTER_NUMERIC, &m_SnapSize));
pSubSizer->Add(pSubSubSizer, SizerFlags);
}
}
pMainSizer->Add(pSubSizer, SizerFlags);
SubSizers.push_back(pSubSizer);
pSubSizer = new wxStaticBoxSizer(wxVERTICAL, pControls, wxT("Tool:"));
{
pSubSizer->Add(new wxRadioButton(pControls, ID_SelectTool, wxT("Select"), wxDefaultPosition, wxDefaultSize, wxRB_GROUP), SizerFlags);
pSubSizer->Add(new wxRadioButton(pControls, ID_MoveTool, wxT("Move"), wxDefaultPosition, wxDefaultSize), SizerFlags);
pSubSizer->Add(new wxRadioButton(pControls, ID_RotateTool, wxT("Rotate"), wxDefaultPosition, wxDefaultSize), SizerFlags);
pSubSizer->Add(new wxRadioButton(pControls, ID_ScaleTool, wxT("Scale"), wxDefaultPosition, wxDefaultSize), SizerFlags);
}
pMainSizer->Add(pSubSizer, SizerFlags);
SubSizers.push_back(pSubSizer);
pSubSizer = new wxStaticBoxSizer(wxVERTICAL, pControls, wxT("Selection Filter:"));
{
pSubSizer->Add(new wxCheckBox(pControls, ID_FilterNodes, wxT("Nodes")), SizerFlags);
pSubSizer->Add(new wxCheckBox(pControls, ID_FilterPath, wxT("Paths")), SizerFlags);
pSubSizer->Add(new wxCheckBox(pControls, ID_FilterSurface, wxT("Surfaces")), SizerFlags);
}
pMainSizer->Add(pSubSizer, SizerFlags);
SubSizers.push_back(pSubSizer);
}
int i;
for (i=0; i<(int)SubSizers.size(); ++i)
{
SubSizers[i]->SetDimension(0, 0, pMainSizer->GetMinSize().x, SubSizers[i]->GetMinSize().y);
}
pControls->SetSizer(pMainSizer);
AddPage(pControls, wxT("Modeller"));
wxMenu *pMenu = new wxMenu;
pMenu->Append(ID_CreateYarn, wxT("Create Yarn..."));
pMenu->AppendSeparator();
pMenu->Append(ID_AssignSection, wxT("Assign Section..."));
pMenu->Append(ID_AssignInterpolation, wxT("Assign Interpolation..."));
pMenu->Append(ID_AssignRepeats, wxT("Assign Repeats..."));
pMenu->Append(ID_AssignProperties, wxT("Assign Yarn Properties..."));
pMenu->Append(ID_AssignMatrixProperties, wxT("Assign Matrix Properties..."));
pMenu->AppendSeparator();
pMenu->Append(ID_Snap, wxT("Snap"), wxT(""), wxITEM_CHECK);
pMenu->Append(ID_Relative, wxT("Relative Snap"), wxT(""), wxITEM_CHECK);
pMenu->AppendSeparator();
pMenu->Append(ID_SelectTool, wxT("Select Tool"), wxT(""), wxITEM_CHECK);
pMenu->Append(ID_MoveTool, wxT("Move Tool"), wxT(""), wxITEM_CHECK);
pMenu->Append(ID_RotateTool, wxT("Rotate Tool"), wxT(""), wxITEM_CHECK);
pMenu->Append(ID_ScaleTool, wxT("Scale Tool"), wxT(""), wxITEM_CHECK);
pMenu->AppendSeparator();
pMenu->Append(ID_FilterNodes, wxT("Select Nodes"), wxT(""), wxITEM_CHECK);
pMenu->Append(ID_FilterPath, wxT("Select Paths"), wxT(""), wxITEM_CHECK);
pMenu->Append(ID_FilterSurface, wxT("Select Surfaces"), wxT(""), wxITEM_CHECK);
m_pMenuBar->Append(pMenu, wxT("&Modeller"));
}
void CControlsWindow::BuildRenderingPage()
{
wxNotebookPage *pControls = new wxNotebookPage(this, wxID_ANY);
wxBoxSizer *pMainSizer = new wxBoxSizer(wxVERTICAL);
wxSizerFlags SizerFlags(0);
// SizerFlags.Border(wxALL, 1);
SizerFlags.Expand();
vector<wxSizer*> SubSizers;
wxSizer *pSubSizer;
pSubSizer = new wxStaticBoxSizer(wxVERTICAL, pControls, wxT("Display:"));
pSubSizer->Add(new wxCheckBox(pControls, ID_RenderNodes, wxT("Nodes")), SizerFlags);
pSubSizer->Add(new wxCheckBox(pControls, ID_RenderPaths, wxT("Paths")), SizerFlags);
pSubSizer->Add(new wxCheckBox(pControls, ID_RenderSurface, wxT("Surface")), SizerFlags);
pSubSizer->Add(new wxCheckBox(pControls, ID_RenderVolume, wxT("Volume")), SizerFlags);
pSubSizer->Add(new wxCheckBox(pControls, ID_RenderInterference, wxT("Interference")), SizerFlags);
pSubSizer->Add(new wxCheckBox(pControls, ID_RenderInterferenceDepth, wxT("Interference Depth")), SizerFlags);
pSubSizer->Add(new wxCheckBox(pControls, ID_RenderOrientation, wxT("Orientation")), SizerFlags);
pMainSizer->Add(pSubSizer, SizerFlags);
SubSizers.push_back(pSubSizer);
pSubSizer = new wxStaticBoxSizer(wxVERTICAL, pControls, wxT(""));
pSubSizer->Add(new wxCheckBox(pControls, ID_RenderDomain, wxT("Domain")), SizerFlags);
pSubSizer->Add(new wxCheckBox(pControls, ID_RenderDomainAxes, wxT("Domain Axes")), SizerFlags);
pSubSizer->Add(new wxCheckBox(pControls, ID_RenderAxes, wxT("Axes")), SizerFlags);
pMainSizer->Add(pSubSizer, SizerFlags);
SubSizers.push_back(pSubSizer);
pSubSizer = new wxStaticBoxSizer(wxVERTICAL, pControls, wxT(""));
pSubSizer->Add(new wxCheckBox(pControls, ID_XRay, wxT("X-Ray")), SizerFlags);
pSubSizer->Add(new wxCheckBox(pControls, ID_ParallelProjection, wxT("Parallel Projection")), SizerFlags);
pSubSizer->Add(new wxCheckBox(pControls, ID_TrimtoDomain, wxT("Trim to domain")), SizerFlags);
pMainSizer->Add(pSubSizer, SizerFlags);
SubSizers.push_back(pSubSizer);
pSubSizer = new wxStaticBoxSizer(wxVERTICAL, pControls, wxT("Colors"));
pSubSizer->Add(new wxButton(pControls, ID_ChangeBackgroundColor, wxT("Background")), SizerFlags);
pSubSizer->Add(new wxButton(pControls, ID_ChangeSurfaceColor, wxT("Surface")), SizerFlags);
pSubSizer->Add(new wxButton(pControls, ID_RefreshView, wxT("Refresh View")), SizerFlags);
pMainSizer->Add(pSubSizer, SizerFlags);
SubSizers.push_back(pSubSizer);
int i;
for (i=0; i<(int)SubSizers.size(); ++i)
{
SubSizers[i]->SetDimension(0, 0, pMainSizer->GetMinSize().x, SubSizers[i]->GetMinSize().y);
}
pControls->SetSizer(pMainSizer);
AddPage(pControls, wxT("Rendering"));
wxMenu *pMenu = new wxMenu;
pMenu->Append(ID_RenderNodes, wxT("Render Textile Nodes"), wxT(""), wxITEM_CHECK);
pMenu->Append(ID_RenderPaths, wxT("Render Textile Paths"), wxT(""), wxITEM_CHECK);
pMenu->Append(ID_RenderSurface, wxT("Render Textile Surface"), wxT(""), wxITEM_CHECK);
pMenu->Append(ID_RenderVolume, wxT("Render Textile Volume"), wxT(""), wxITEM_CHECK);
pMenu->Append(ID_RenderInterference, wxT("Render Textile Interference"), wxT(""), wxITEM_CHECK);
pMenu->Append(ID_RenderInterferenceDepth, wxT("Render Textile Interference Depth"), wxT(""), wxITEM_CHECK);
pMenu->Append(ID_RenderOrientation, wxT("Render Fibre Orientation"), wxT(""), wxITEM_CHECK);
pMenu->AppendSeparator();
pMenu->Append(ID_RenderDomain, wxT("Render Domain"), wxT(""), wxITEM_CHECK);
pMenu->Append(ID_RenderDomainAxes, wxT("Render Domain Axes"), wxT(""), wxITEM_CHECK);
pMenu->Append(ID_RenderAxes, wxT("Render Axes"), wxT(""), wxITEM_CHECK);
pMenu->AppendSeparator();
pMenu->Append(ID_XRay, wxT("X-Ray"), wxT(""), wxITEM_CHECK);
pMenu->Append(ID_ParallelProjection, wxT("Parallel Projection"), wxT(""), wxITEM_CHECK);
pMenu->Append(ID_TrimtoDomain, wxT("Trim to Domain"), wxT(""), wxITEM_CHECK);
pMenu->AppendSeparator();
pMenu->Append(ID_ChangeBackgroundColor, wxT("Change Background Colour"));
pMenu->Append(ID_ChangeSurfaceColor, wxT("Change Surface Colour"));
pMenu->Append(ID_RefreshView, wxT("RefreshView"));
m_pMenuBar->Append(pMenu, wxT("&Rendering"));
}
void CControlsWindow::BuildDomainsPage()
{
wxNotebookPage *pControls = new wxNotebookPage(this, wxID_ANY);
wxBoxSizer *pMainSizer = new wxBoxSizer(wxVERTICAL);
wxSizerFlags SizerFlags(0);
// SizerFlags.Border(wxALL, 1);
SizerFlags.Expand();
vector<wxSizer*> SubSizers;
wxSizer *pSubSizer;
pSubSizer = new wxStaticBoxSizer(wxVERTICAL, pControls, wxT("Create:"));
pSubSizer->Add(new wxButton(pControls, ID_CreateDomainBox, wxT("Box"), wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT), SizerFlags);
pSubSizer->Add(new wxButton(pControls, ID_CreateDomainPlanes, wxT("Planes"), wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT), SizerFlags);
pMainSizer->Add(pSubSizer, SizerFlags);
SubSizers.push_back(pSubSizer);
pSubSizer = new wxStaticBoxSizer(wxVERTICAL, pControls, wxT("")/*"Existing:"*/);
pSubSizer->Add(new wxButton(pControls, ID_EditDomain, wxT("Edit"), wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT), SizerFlags);
pSubSizer->Add(new wxButton(pControls, ID_DeleteDomain, wxT("Delete"), wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT), SizerFlags);
pMainSizer->Add(pSubSizer, SizerFlags);
SubSizers.push_back(pSubSizer);
int i;
for (i=0; i<(int)SubSizers.size(); ++i)
{
SubSizers[i]->SetDimension(0, 0, pMainSizer->GetMinSize().x, SubSizers[i]->GetMinSize().y);
}
pControls->SetSizer(pMainSizer);
AddPage(pControls, wxT("Domain"));
wxMenu *pMenu = new wxMenu;
pMenu->Append(ID_CreateDomainBox, wxT("Create Box..."));
pMenu->Append(ID_CreateDomainPlanes, wxT("Create Planes..."));
pMenu->AppendSeparator();
pMenu->Append(ID_EditDomain, wxT("Edit Domain..."));
pMenu->Append(ID_DeleteDomain, wxT("Delete Domain"));
m_pMenuBar->Append(pMenu, wxT("&Domain"));
}
void CControlsWindow::BuildPythonPage()
{
wxNotebookPage *pControls = new wxNotebookPage(this, wxID_ANY);
wxBoxSizer *pMainSizer = new wxBoxSizer(wxVERTICAL);
wxSizerFlags SizerFlags(0);
// SizerFlags.Border(wxALL, 1);
SizerFlags.Expand();
vector<wxSizer*> SubSizers;
wxSizer *pSubSizer;
pSubSizer = new wxStaticBoxSizer(wxVERTICAL, pControls, wxT("Script:"));
pSubSizer->Add(new wxButton(pControls, ID_RunScript, wxT("Run"), wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT), SizerFlags);
pSubSizer->Add(new wxButton(pControls, ID_RecordMacro, wxT("Record"), wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT), SizerFlags);
pMainSizer->Add(pSubSizer, SizerFlags);
SubSizers.push_back(pSubSizer);
int i;
for (i=0; i<(int)SubSizers.size(); ++i)
{
SubSizers[i]->SetDimension(0, 0, pMainSizer->GetMinSize().x, SubSizers[i]->GetMinSize().y);
}
pControls->SetSizer(pMainSizer);
AddPage(pControls, wxT("Python"));
wxMenu *pMenu = new wxMenu;
pMenu->Append(ID_RunScript, wxT("Run Script..."));
pMenu->Append(ID_RecordMacro, wxT("Record Script..."));
m_pMenuBar->Append(pMenu, wxT("&Python"));
}
void CControlsWindow::UpdateModellingPage(const CModeller *pModeller)
{
wxRadioButton* pRadioButton = NULL;
bool bChecked = false;
int i;
int iID;
for (i=TOOL_SELECT; i<=TOOL_SCALE; ++i)
{
bChecked = (i == pModeller->GetActiveTool());
switch (i)
{
case TOOL_SELECT:
iID = ID_SelectTool;
break;
case TOOL_MOVE:
iID = ID_MoveTool;
break;
case TOOL_ROTATE:
iID = ID_RotateTool;
break;
case TOOL_SCALE:
iID = ID_ScaleTool;
break;
}
pRadioButton = (wxRadioButton*)FindWindowById(iID, this);
if (pRadioButton)
{
pRadioButton->SetValue(bChecked);
}
m_pMenuBar->Check(iID, bChecked);
}
UpdateCheckWidget(ID_FilterNodes, pModeller->GetSelectNodes());
UpdateCheckWidget(ID_FilterPath, pModeller->GetSelectPaths());
UpdateCheckWidget(ID_FilterSurface, pModeller->GetSelectSurfaces());
UpdateCheckWidget(ID_Snap, pModeller->GetWidget()->GetSnap());
UpdateCheckWidget(ID_Relative, pModeller->GetWidget()->GetRelativeSnap());
UpdatePositionText(pModeller);
UpdateSnapSize(pModeller);
}
void CControlsWindow::UpdatePositionText(const CModeller *pModeller)
{
m_bUpdatingPositionText = true;
XYZ Pos = pModeller->GetPosition();
if (abs(Pos.x) < 1e-6)
Pos.x = 0;
if (abs(Pos.y) < 1e-6)
Pos.y = 0;
if (abs(Pos.z) < 1e-6)
Pos.z = 0;
m_PositionX.clear();
m_PositionY.clear();
m_PositionZ.clear();
m_PositionX << Pos.x;
m_PositionY << Pos.y;
m_PositionZ << Pos.z;
int i;
for (i=ID_PositionX; i<=ID_PositionZ; ++i)
{
wxTextCtrl* pTextCtrl = dynamic_cast<wxTextCtrl*>(FindWindowById(i, this));
if (pTextCtrl)
{
wxValidator* pValidator = pTextCtrl->GetValidator();
pValidator->TransferToWindow();
}
}
m_bUpdatingPositionText = false;
}
void CControlsWindow::UpdateSnapSize(const CModeller *pModeller)
{
double dSnapSize = pModeller->GetWidget()->GetSnapSize();
m_SnapSize.clear();
m_SnapSize << dSnapSize;
wxTextCtrl* pTextCtrl = dynamic_cast<wxTextCtrl*>(FindWindowById(ID_SnapSize, this));
if (pTextCtrl)
{
wxValidator* pValidator = pTextCtrl->GetValidator();
pValidator->TransferToWindow();
}
}
void CControlsWindow::UpdateRenderingPage(const CTexGenRenderer *pRenderer)
{
UpdateRenderWidget(ID_RenderNodes, pRenderer, CTexGenRenderer::PROP_NODE);
UpdateRenderWidget(ID_RenderPaths, pRenderer, CTexGenRenderer::PROP_PATH);
UpdateRenderWidget(ID_RenderSurface, pRenderer, CTexGenRenderer::PROP_SURFACE);
UpdateRenderWidget(ID_RenderVolume, pRenderer, CTexGenRenderer::PROP_VOLUME);
UpdateRenderWidget(ID_RenderInterference, pRenderer, CTexGenRenderer::PROP_INTERFERENCE);
UpdateRenderWidget(ID_RenderInterferenceDepth, pRenderer, CTexGenRenderer::PROP_INTERFERENCE_DEPTH);
UpdateRenderWidget(ID_RenderOrientation, pRenderer, CTexGenRenderer::PROP_ORIENTATION);
UpdateRenderWidget(ID_RenderDomain, pRenderer, CTexGenRenderer::PROP_DOMAIN);
UpdateRenderWidget(ID_RenderDomainAxes, pRenderer, CTexGenRenderer::PROP_DOMAINAXES);
UpdateRenderWidget(ID_RenderAxes, pRenderer, CTexGenRenderer::PROP_AXES);
// Find out if the widget should be checked or not
bool bChecked = pRenderer->GetXRay();
wxCheckBox* pCheckBox = (wxCheckBox*)FindWindowById(ID_XRay, this);
if (pCheckBox)
{
pCheckBox->SetValue(bChecked);
}
m_pMenuBar->Check(ID_XRay, bChecked);
// Find out if the parallel projection widget should be checked or not
bChecked = pRenderer->GetParallelProjection();
pCheckBox = (wxCheckBox*)FindWindowById(ID_ParallelProjection, this);
if (pCheckBox)
{
pCheckBox->SetValue(bChecked);
}
m_pMenuBar->Check(ID_ParallelProjection, bChecked);
// Find out if the widget should be checked or not
bChecked = pRenderer->GetTrimToDomain();
pCheckBox = (wxCheckBox*)FindWindowById(ID_TrimtoDomain, this);
if (pCheckBox)
{
pCheckBox->SetValue(bChecked);
}
m_pMenuBar->Check(ID_TrimtoDomain, bChecked);
}
void CControlsWindow::UpdatePythonPage(bool bRecording)
{
wxButton* pButton = (wxButton*)FindWindowById(ID_RecordMacro, this);
if (pButton)
{
if (bRecording)
pButton->SetLabel(wxT("Stop Recording"));
else
pButton->SetLabel(wxT("Record"));
}
wxMenuItem* pMenuItem = m_pMenuBar->FindItem(ID_RecordMacro);
if (pMenuItem)
{
if (bRecording)
pMenuItem->SetText(wxT("Stop Recording"));
else
pMenuItem->SetText(wxT("Record Script..."));
}
}
void CControlsWindow::UpdateCheckWidget(int iID, bool bChecked)
{
wxCheckBox* pCheckBox;
pCheckBox = (wxCheckBox*)FindWindowById(iID, this);
if (pCheckBox)
{
pCheckBox->SetValue(bChecked);
}
m_pMenuBar->Check(iID, bChecked);
}
void CControlsWindow::UpdateRenderWidget(int iID, const CTexGenRenderer *pRenderer, CTexGenRenderer::PROP_TYPE Type)
{
// Find out if the widget should be checked or not
bool bChecked = (pRenderer->GetNumProps(Type) > 0);
// Check the checkbox on the controls list
wxCheckBox* pCheckBox = (wxCheckBox*)FindWindowById(iID, this);
if (pCheckBox)
{
pCheckBox->SetValue(bChecked);
}
// Check the drop down menu item
m_pMenuBar->Check(iID, bChecked);
}
void CControlsWindow::BuildToolsPage()
{
wxMenu *pMenu = new wxMenu;
pMenu->Append(ID_PatternDraft, wxT("Create Pattern Draft"));
pMenu->Append(ID_QuickDomainVolumeFraction, wxT("Quick Calculate Domain Volume Fraction"));
pMenu->Append(ID_DomainVolumeFraction, wxT("Calculate Domain Volume Fraction"));
pMenu->Append(ID_YarnFibreVolumeFraction, wxT("Yarn Fibre Volume Fraction"));
m_pMenuBar->Append(pMenu, wxT("&Tools"));
}
void CControlsWindow::BuildOptionsPage()
{
wxMenu *pMenu = new wxMenu;
pMenu->Append(ID_OutputMessages, wxT("Output Messages"), wxT(""), wxITEM_CHECK );
pMenu->Check(ID_OutputMessages, CTexGen::GetInstance().GetMessagesOn());
m_pMenuBar->Append(pMenu, wxT("&Options"));
}
| 40 | 157 | 0.74425 | [
"geometry",
"render",
"vector",
"3d"
] |
78253456c976fdabf2fa6d7fdd2095117281114a | 2,733 | hpp | C++ | include/metrics/IMetricFamily.hpp | Rechip/mqtt-exporter | ebb7e44d066242b874cc3a602e3b32e97685fa95 | [
"MIT"
] | null | null | null | include/metrics/IMetricFamily.hpp | Rechip/mqtt-exporter | ebb7e44d066242b874cc3a602e3b32e97685fa95 | [
"MIT"
] | null | null | null | include/metrics/IMetricFamily.hpp | Rechip/mqtt-exporter | ebb7e44d066242b874cc3a602e3b32e97685fa95 | [
"MIT"
] | null | null | null | #ifndef ME_METRICS_IMETRICFAMILY_HPP_
#define ME_METRICS_IMETRICFAMILY_HPP_
#pragma once
#include "IMetric.hpp"
#include "Label.hpp"
#include "Variable.hpp"
#include "VectorIterator.hpp"
#include <chrono>
#include <memory>
#include <simple-yaml/simple_yaml.hpp>
#include <string>
#include <string_view>
#include <vector>
struct OpenMetric : public simple_yaml::Simple {
using Simple::Simple;
enum class Type {
//Standard types
counter,
gauge,
histogram,
summary,
// Extension types
MatchGauge
};
std::string name = bound("name");
Type type = bound("type");
std::string help = bound("help", "");
std::string unit = bound("unit", "");
std::vector<Label> labels = bound("labels");
std::string payloadJsonPath = bound("payloadJsonPath", "");
std::string payloadRegex = bound("payloadRegex", "");
// Histogram specific
std::vector<double> buckets = bound("buckets", std::vector<double>{});
// Summary specific
std::vector<double> quantiles = bound("quantiles", std::vector<double>{});
std::chrono::seconds max_age = bound("max_age", std::chrono::seconds{60});
int age_buckets = bound("age_buckets", 5);
// MatchGauge specific
std::string matchRegex = bound("matchRegex", "");
};
class IMetricFamily {
public:
using iterator = VectorIterator<std::shared_ptr<IMetric>>;
using Clock = IMetric::Clock;
struct Configuration : public simple_yaml::Simple {
using Simple::Simple;
std::string topic = bound("topic");
OpenMetric openMetric = bound("openMetric");
std::vector<Variable> variables = bound("variables");
Clock::duration maxAge = bound("maxAge", std::chrono::duration_cast<Clock::duration>(std::chrono::days{1}));
};
IMetricFamily(Configuration config);
virtual ~IMetricFamily() = default;
static std::shared_ptr<IMetricFamily> create(Configuration config);
std::string stringify() const;
std::string getUnit() const;
std::string getHelp() const;
std::string getBaseName() const;
std::string getTopic() const;
std::string getFullname() const;
std::vector<Variable> getVariables() const;
LabelSet getConstantLabels() const;
LabelSet getVariableLabels() const;
std::string parsePayload(std::string payload) const;
virtual iterator begin() const = 0;
virtual iterator end() const = 0;
virtual void newSample(std::string_view payload, const LabelSet& labels) = 0;
virtual OpenMetric::Type getStandardType() const = 0;
virtual void routine();
Configuration _config;
};
#endif
| 29.387097 | 120 | 0.64764 | [
"vector"
] |
782a36203320e1448a6ffa2b5ca1e2282ac275af | 31,900 | cpp | C++ | test/odbc/test_resultset.cpp | faizol/babelfish_extensions | 3dab47c2a27a784906426c9401fc99c9519906d1 | [
"PostgreSQL",
"Apache-2.0",
"BSD-3-Clause"
] | 115 | 2021-10-29T18:17:24.000Z | 2022-03-28T01:05:20.000Z | test/odbc/test_resultset.cpp | faizol/babelfish_extensions | 3dab47c2a27a784906426c9401fc99c9519906d1 | [
"PostgreSQL",
"Apache-2.0",
"BSD-3-Clause"
] | 81 | 2021-10-29T19:22:51.000Z | 2022-03-31T19:31:12.000Z | test/odbc/test_resultset.cpp | faizol/babelfish_extensions | 3dab47c2a27a784906426c9401fc99c9519906d1 | [
"PostgreSQL",
"Apache-2.0",
"BSD-3-Clause"
] | 53 | 2021-10-30T01:26:50.000Z | 2022-03-22T00:12:47.000Z | #include "odbc_handler.h"
#include "database_objects.h"
#include "query_generator.h"
#include <gtest/gtest.h>
#include <sqlext.h>
using std::vector;
using std::pair;
using std::tuple;
// Read Only table
static const string RESULT_SET_RO_TABLE1 = "RESULT_SET_RO";
// Columns for the test table
static const vector<pair<string,string>> RO_TABLE_COLUMNS = {
{"id", "INT"},
{"info", "VARCHAR(256) NOT NULL"},
{"decivar", "NUMERIC(38,16)"}
};
static const vector<tuple<int, string, float>> RO_TABLE_VALUES = {
{1, "hello1", 1.1},
{2, "hello2", 2.2},
{3, "hello3", 3.3},
{4, "hello4", 4.4}
};
const string SELECT_RESULT_SET_RO_TABLE1 = SelectStatement(RESULT_SET_RO_TABLE1, { "*" }, {"id"}); // order by id
class Result_Set : public testing::Test {
protected:
static void SetUpTestSuite() {
OdbcHandler test_setup;
test_setup.ConnectAndExecQuery(DropObjectStatement("TABLE",RESULT_SET_RO_TABLE1));
test_setup.ExecQuery(CreateTableStatement(RESULT_SET_RO_TABLE1, RO_TABLE_COLUMNS));
test_setup.ExecQuery(InsertStatement(RESULT_SET_RO_TABLE1, "(1, 'hello1', 1.1), (2, 'hello2', 2.2), (3, 'hello3', 3.3), (4, 'hello4', 4.4)"));
}
static void TearDownTestSuite() {
OdbcHandler test_cleanup;
test_cleanup.ConnectAndExecQuery(DropObjectStatement("TABLE",RESULT_SET_RO_TABLE1));
}
};
// Setup function for SQLBindcol tests.
// Execute query on the read only table and calls BindCol with a given col num as the argument.
// It will also assert the given expected rcode and output the sql state.
void SQLBindColTestSetup(const int col_num, const RETCODE expected_rcode, string* sql_state) {
OdbcHandler odbcHandler;
RETCODE rcode;
SQLINTEGER id;
SQLLEN id_indicator;
odbcHandler.ConnectAndExecQuery(SELECT_RESULT_SET_RO_TABLE1);
rcode = SQLBindCol(odbcHandler.GetStatementHandle(), col_num, SQL_C_ULONG, &id, 0, &id_indicator);
ASSERT_EQ(rcode, expected_rcode);
*sql_state = odbcHandler.GetSqlState(SQL_HANDLE_STMT, odbcHandler.GetStatementHandle());
}
// Connects the odbcHandler, allocate the stmt handle, and set the stmt handle to be scrollable
void ConnectAndSetScrollable(OdbcHandler* odbcHandler) {
RETCODE rcode;
odbcHandler->Connect(true);
rcode = SQLSetStmtAttr(odbcHandler->GetStatementHandle(),
SQL_ATTR_CURSOR_SCROLLABLE,
(SQLPOINTER) SQL_SCROLLABLE,
0);
ASSERT_EQ(rcode, SQL_SUCCESS) << odbcHandler->GetErrorMessage(SQL_HANDLE_STMT, rcode);
}
void ConnectAndSetScrollableWithConcurLock(OdbcHandler* odbcHandler) {
RETCODE rcode;
ConnectAndSetScrollable(odbcHandler);
rcode = SQLSetStmtAttr(odbcHandler->GetStatementHandle(), SQL_ATTR_CONCURRENCY,
(SQLPOINTER)SQL_CONCUR_LOCK ,0);
ASSERT_EQ(rcode, SQL_SUCCESS) << odbcHandler->GetErrorMessage(SQL_HANDLE_STMT, rcode);
}
// Tests SQLBindCol on a succesful state.
TEST_F(Result_Set, SQLBindCol_Successful) {
string sql_state;
SQLBindColTestSetup(1, SQL_SUCCESS, &sql_state);
ASSERT_EQ(sql_state, "00000");
}
// Tests SQLBindCol when ColumnNumber is 0 and it is not a bookmark column
TEST_F(Result_Set, SQLBindCol_NotBookmark) {
string sql_state;
// Bind column and assert that it returns error 07006
SQLBindColTestSetup(0, SQL_ERROR, &sql_state);
ASSERT_EQ(sql_state, "07006");
}
// Tests SQLBindCol when ColumnNumber argument exceeds max number of columns in result set
TEST_F(Result_Set, SQLBindCol_ExceedMaxCol) {
string sql_state;
// Bind column and assert that it returns error 07009
SQLBindColTestSetup(10000, SQL_ERROR, &sql_state);
ASSERT_EQ(sql_state, "07009");
}
// Tests SQLFetch when it iterates through all results
TEST_F(Result_Set, SQLFetch_SuccessfulIteration) {
OdbcHandler odbcHandler;
RETCODE rcode;
string sql_state;
SQLINTEGER id;
SQLCHAR info[256];
SQLLEN info_indicator;
SQLLEN id_indicator;
vector<tuple<int, int, SQLPOINTER, int>> bind_columns = {
{1, SQL_C_ULONG, &id, 0},
{2, SQL_C_CHAR, &info, sizeof(info)}
};
ASSERT_NO_FATAL_FAILURE(odbcHandler.ConnectAndExecQuery(SELECT_RESULT_SET_RO_TABLE1));
ASSERT_NO_FATAL_FAILURE(odbcHandler.BindColumns(bind_columns));
for (auto row_values : RO_TABLE_VALUES) {
// Assert that it is able to fetch all rows with the correct values
rcode = SQLFetch(odbcHandler.GetStatementHandle());
ASSERT_EQ(rcode, SQL_SUCCESS) << odbcHandler.GetErrorMessage(SQL_HANDLE_STMT, rcode);
auto& [id_val, info_val, decivar_val] = row_values;
EXPECT_EQ(id, id_val);
EXPECT_EQ(string((char*) info),info_val);
}
// Assert that SQLFetch returns SQL_NO_DATA
rcode = SQLFetch(odbcHandler.GetStatementHandle());
ASSERT_EQ(rcode, SQL_NO_DATA);
}
// Tests SQLFetch when a varchar variable gets truncated
TEST_F(Result_Set, SQLFetch_TruncatedVarchar) {
OdbcHandler odbcHandler;
RETCODE rcode;
string sql_state;
SQLCHAR info[2];
SQLLEN info_indicator;
ASSERT_NO_FATAL_FAILURE(odbcHandler.ConnectAndExecQuery(SELECT_RESULT_SET_RO_TABLE1));
// Bind the columns to variables
rcode = SQLBindCol(odbcHandler.GetStatementHandle(), 2, SQL_C_CHAR, &info, sizeof(info), &info_indicator);
ASSERT_EQ(rcode, SQL_SUCCESS) << odbcHandler.GetErrorMessage(SQL_HANDLE_STMT, rcode);
// Assert that we get sql state 01004 when a varchar variable is truncated
rcode = SQLFetch(odbcHandler.GetStatementHandle());
ASSERT_EQ(rcode, SQL_SUCCESS_WITH_INFO) << odbcHandler.GetErrorMessage(SQL_HANDLE_STMT, rcode);
sql_state = odbcHandler.GetSqlState(SQL_HANDLE_STMT,odbcHandler.GetStatementHandle());
ASSERT_EQ(sql_state, "01004");
}
// Tests SQLFetch when a numeric datatype gets truncated
TEST_F(Result_Set, SQLFetch_TruncatedNumeric) {
OdbcHandler odbcHandler;
RETCODE rcode;
string sql_state;
SQLINTEGER decivar;
SQLLEN decivar_indicator;
ASSERT_NO_FATAL_FAILURE(odbcHandler.ConnectAndExecQuery(SELECT_RESULT_SET_RO_TABLE1));
// Bind the columns to variables
rcode = SQLBindCol(odbcHandler.GetStatementHandle(), 3, SQL_C_ULONG, &decivar, 0, &decivar_indicator);
ASSERT_EQ(rcode, SQL_SUCCESS) << odbcHandler.GetErrorMessage(SQL_HANDLE_STMT, rcode);
rcode = SQLFetch(odbcHandler.GetStatementHandle());
ASSERT_EQ(rcode, SQL_SUCCESS_WITH_INFO) << odbcHandler.GetErrorMessage(SQL_HANDLE_STMT, rcode);
// Assert that we get sql state 01S07 when a numeric datatype is truncated
sql_state = odbcHandler.GetSqlState(SQL_HANDLE_STMT,odbcHandler.GetStatementHandle());
ASSERT_EQ(sql_state, "01S07");
}
// Tests SQLFetch when there is an invalid cast during bindcol.
TEST_F(Result_Set, SQLFetch_InvalidCast) {
OdbcHandler odbcHandler;
RETCODE rcode;
string sql_state;
SQLINTEGER id;
SQLLEN id_indicator;
ASSERT_NO_FATAL_FAILURE(odbcHandler.ConnectAndExecQuery(SELECT_RESULT_SET_RO_TABLE1));
// Bind the columns to variables
rcode = SQLBindCol(odbcHandler.GetStatementHandle(), 2, SQL_C_ULONG, &id, 0, &id_indicator);
ASSERT_EQ(rcode, SQL_SUCCESS) << odbcHandler.GetErrorMessage(SQL_HANDLE_STMT, rcode);
// Assert that we get sql state 22018 when there is an invalid cast
rcode = SQLFetch(odbcHandler.GetStatementHandle());
ASSERT_EQ(rcode, SQL_ERROR);
sql_state = odbcHandler.GetSqlState(SQL_HANDLE_STMT,odbcHandler.GetStatementHandle());
ASSERT_EQ(sql_state, "22018");
}
// Tests SQLSetPos when SQL_ATTR_ROW_ARRAY_SIZE is set to 1.
// DISABLED: PLEASE SEE BABELFISH-97
TEST_F(Result_Set, DISABLED_SQLSetPos_ResultRowSize1) {
OdbcHandler odbcHandler;
RETCODE rcode;
string sql_state;
int id;
SQLLEN id_indicator;
// Setup, connect and set attributes for SQLSetPos
ASSERT_NO_FATAL_FAILURE(ConnectAndSetScrollable(&odbcHandler));
ASSERT_NO_FATAL_FAILURE(odbcHandler.ExecQuery(SELECT_RESULT_SET_RO_TABLE1));
// Assert that we can retrieve the first row of the results but not the second.
rcode = SQLFetch(odbcHandler.GetStatementHandle());
ASSERT_EQ(rcode, SQL_SUCCESS) << odbcHandler.GetErrorMessage(SQL_HANDLE_STMT, rcode);
rcode = SQLSetPos(odbcHandler.GetStatementHandle(), 1, SQL_POSITION, SQL_LOCK_NO_CHANGE);
ASSERT_EQ(rcode, SQL_SUCCESS) << odbcHandler.GetErrorMessage(SQL_HANDLE_STMT, rcode);
rcode = SQLGetData(odbcHandler.GetStatementHandle(), 1, SQL_C_ULONG, &id, 0, &id_indicator);
ASSERT_EQ(rcode, SQL_SUCCESS) << odbcHandler.GetErrorMessage(SQL_HANDLE_STMT, rcode);
ASSERT_EQ(id, 1);
rcode = SQLSetPos(odbcHandler.GetStatementHandle(), 2, SQL_POSITION, SQL_LOCK_NO_CHANGE);
ASSERT_EQ(rcode, SQL_ERROR);
sql_state = odbcHandler.GetSqlState(SQL_HANDLE_STMT, odbcHandler.GetStatementHandle());
ASSERT_EQ(sql_state, "HY107");
}
// Tests SQLSetPos when SQL_ATTR_ROW_ARRAY_SIZE is set to 2.
// DISABLED: PLEASE SEE BABELFISH-97
TEST_F(Result_Set, DISABLED_SQLSetPos_ResultRowSize2) {
OdbcHandler odbcHandler;
RETCODE rcode;
string sql_state;
int id;
SQLLEN id_indicator;
ASSERT_NO_FATAL_FAILURE(ConnectAndSetScrollable(&odbcHandler));
rcode = SQLSetStmtAttr(odbcHandler.GetStatementHandle(),
SQL_ATTR_ROW_ARRAY_SIZE,
(SQLPOINTER) 2,
SQL_IS_INTEGER);
ASSERT_EQ(rcode, SQL_SUCCESS) << odbcHandler.GetErrorMessage(SQL_HANDLE_STMT, rcode);
ASSERT_NO_FATAL_FAILURE(odbcHandler.ExecQuery(SELECT_RESULT_SET_RO_TABLE1));
rcode = SQLFetch(odbcHandler.GetStatementHandle());
ASSERT_EQ(rcode, SQL_SUCCESS) << odbcHandler.GetErrorMessage(SQL_HANDLE_STMT, rcode);
// Assert that we can retrieve the first and second row of the results but not the third.
rcode = SQLSetPos(odbcHandler.GetStatementHandle(), 1, SQL_POSITION, SQL_LOCK_NO_CHANGE);
ASSERT_EQ(rcode, SQL_SUCCESS) << odbcHandler.GetErrorMessage(SQL_HANDLE_STMT, rcode);
rcode = SQLSetPos(odbcHandler.GetStatementHandle(), 2, SQL_POSITION, SQL_LOCK_NO_CHANGE);
ASSERT_EQ(rcode, SQL_SUCCESS) << odbcHandler.GetErrorMessage(SQL_HANDLE_STMT, rcode);
rcode = SQLSetPos(odbcHandler.GetStatementHandle(), 3, SQL_POSITION, SQL_LOCK_NO_CHANGE);
ASSERT_EQ(rcode, SQL_ERROR);
sql_state = odbcHandler.GetSqlState(SQL_HANDLE_STMT, odbcHandler.GetStatementHandle());
ASSERT_EQ(sql_state, "HY107");
// Assert that we can get the last set of items by calling another SQLFetch
rcode = SQLFetch(odbcHandler.GetStatementHandle());
ASSERT_EQ(rcode, SQL_SUCCESS) << odbcHandler.GetErrorMessage(SQL_HANDLE_STMT, rcode);
rcode = SQLSetPos(odbcHandler.GetStatementHandle(), 1, SQL_POSITION, SQL_LOCK_NO_CHANGE);
ASSERT_EQ(rcode, SQL_SUCCESS) << odbcHandler.GetErrorMessage(SQL_HANDLE_STMT, rcode);
rcode = SQLGetData(odbcHandler.GetStatementHandle(), 1, SQL_C_ULONG, &id, 0, &id_indicator);
ASSERT_EQ(rcode, SQL_SUCCESS) << odbcHandler.GetErrorMessage(SQL_HANDLE_STMT, rcode);
ASSERT_EQ(id, 3);
}
// Tests that SQL_UPDATE OR SQL_DELETE option would not work when
// SQL_ATTR_CONCURRENCY is set to read only (which should be the default value)
// DISABLED: PLEASE SEE BABELFISH-97
TEST_F(Result_Set, DISABLED_SQLSetPos_ErrorSqlAttrConcurrencyReadOnly) {
OdbcHandler odbcHandler;
RETCODE rcode;
string sql_state;
// Setup statement attributes and run the initial query
ASSERT_NO_FATAL_FAILURE(ConnectAndSetScrollable(&odbcHandler));
ASSERT_NO_FATAL_FAILURE(odbcHandler.ExecQuery(SELECT_RESULT_SET_RO_TABLE1));
// Fetch result and assert that there is an error of state HY0902 when using SQL_UPDATE
rcode = SQLFetch(odbcHandler.GetStatementHandle());
ASSERT_EQ(rcode, SQL_SUCCESS) << odbcHandler.GetErrorMessage(SQL_HANDLE_STMT, rcode);
rcode = SQLSetPos(odbcHandler.GetStatementHandle(), 1, SQL_UPDATE, SQL_LOCK_NO_CHANGE);
ASSERT_EQ(rcode, SQL_ERROR);
sql_state = odbcHandler.GetSqlState(SQL_HANDLE_STMT, odbcHandler.GetStatementHandle());
ASSERT_EQ(sql_state, "HY092");
// Fetch result and assert that there is an error of state HY0902 when using SQL_DELETE
rcode = SQLSetPos(odbcHandler.GetStatementHandle(), 1, SQL_DELETE, SQL_LOCK_NO_CHANGE);
ASSERT_EQ(rcode, SQL_ERROR);
sql_state = odbcHandler.GetSqlState(SQL_HANDLE_STMT, odbcHandler.GetStatementHandle());
ASSERT_EQ(sql_state, "HY092");
}
// Tests that SQL_UPDATE option gives error 21S02
// DISABLED: PLEASE SEE BABELFISH-97
TEST_F(Result_Set, DISABLED_SQLSetPos_Sqlupdate21S02) {
const string TEST_TABLE = "RESULT_SET_UPDATE21S02";
const string TEST_SELECT = SelectStatement(TEST_TABLE, { "*" });
DatabaseObjects dbObjects;
ASSERT_NO_FATAL_FAILURE(dbObjects.CreateTable(TEST_TABLE, {{"id", "INT"}}));
ASSERT_NO_FATAL_FAILURE(dbObjects.Insert(TEST_TABLE,"(1), (2), (3), (4)"));
OdbcHandler odbcHandler;
RETCODE rcode;
string sql_state;
// Setup attributes and initial query
ASSERT_NO_FATAL_FAILURE(ConnectAndSetScrollableWithConcurLock(&odbcHandler));
ASSERT_NO_FATAL_FAILURE(odbcHandler.ExecQuery(TEST_SELECT));
// Fetch results and assert that a state of 21S02 is returned due to no variables being bounded
rcode = SQLFetch(odbcHandler.GetStatementHandle());
ASSERT_EQ(rcode, SQL_SUCCESS) << odbcHandler.GetErrorMessage(SQL_HANDLE_STMT, rcode);
rcode = SQLSetPos(odbcHandler.GetStatementHandle(), 1, SQL_UPDATE, SQL_LOCK_NO_CHANGE);
ASSERT_EQ(rcode, SQL_ERROR);
sql_state = odbcHandler.GetSqlState(SQL_HANDLE_STMT, odbcHandler.GetStatementHandle());
ASSERT_EQ(sql_state, "21S02");
odbcHandler.FreeAllHandles(); // This is to release the concurrent lock. Otherwise dbObjects trying to drop the test table may block.
}
// Tests that SQL_UPDATE option works correctly
// DISABLED: PLEASE SEE BABELFISH-97
TEST_F(Result_Set, DISABLED_SQLSetPos_SqlupdateSuccessful) {
const string TEST_TABLE = "RESULT_SET_UPDATE";
const string TEST_SELECT = SelectStatement(TEST_TABLE, { "*" });
DatabaseObjects dbObjects;
ASSERT_NO_FATAL_FAILURE(dbObjects.CreateTable(TEST_TABLE, {{"id", "INT"}}));
ASSERT_NO_FATAL_FAILURE(dbObjects.Insert(TEST_TABLE,"(1), (2), (3), (4)"));
OdbcHandler odbcHandler;
RETCODE rcode;
SQLINTEGER id = 10;
SQLLEN id_indicator;
// Setup
ASSERT_NO_FATAL_FAILURE(ConnectAndSetScrollableWithConcurLock(&odbcHandler));
ASSERT_NO_FATAL_FAILURE(odbcHandler.ExecQuery(TEST_SELECT));
// Fetch and bind column to id and call SQLSetPos with SQL_UPDATE option
rcode = SQLFetch(odbcHandler.GetStatementHandle());
ASSERT_EQ(rcode, SQL_SUCCESS) << odbcHandler.GetErrorMessage(SQL_HANDLE_STMT, rcode);
rcode = SQLBindCol(odbcHandler.GetStatementHandle(), 1, SQL_C_ULONG, &id, 0, &id_indicator);
ASSERT_EQ(rcode, SQL_SUCCESS) << odbcHandler.GetErrorMessage(SQL_HANDLE_STMT, rcode);
rcode = SQLSetPos(odbcHandler.GetStatementHandle(), 1, SQL_UPDATE, SQL_LOCK_NO_CHANGE);
ASSERT_EQ(rcode, SQL_SUCCESS) << odbcHandler.GetErrorMessage(SQL_HANDLE_STMT, rcode);
ASSERT_NO_FATAL_FAILURE(odbcHandler.FreeAllHandles());
// Assert that the first item has changed to 10
ASSERT_NO_FATAL_FAILURE(odbcHandler.ConnectAndExecQuery(TEST_SELECT));
rcode = SQLBindCol(odbcHandler.GetStatementHandle(), 1, SQL_C_ULONG, &id, 0, &id_indicator);
ASSERT_EQ(rcode, SQL_SUCCESS) << odbcHandler.GetErrorMessage(SQL_HANDLE_STMT, rcode);
rcode = SQLFetch(odbcHandler.GetStatementHandle());
ASSERT_EQ(rcode, SQL_SUCCESS) << odbcHandler.GetErrorMessage(SQL_HANDLE_STMT, rcode);
ASSERT_EQ(id, 10);
}
// Ensures that SQL_DELETE works correctly
// DISABLED: PLEASE SEE BABELFISH-97
TEST_F(Result_Set, DISABLED_SQLSetPos_SqldeleteSuccessful) {
OdbcHandler odbcHandler;
RETCODE rcode;
SQLINTEGER id;
SQLLEN id_indicator;
int num_rows_before = 0;
int num_rows_after = 0;
const string TEST_TABLE = "RESULT_SET_DELETE";
const string TEST_SELECT = SelectStatement(TEST_TABLE, { "*" });
DatabaseObjects dbObjects;
ASSERT_NO_FATAL_FAILURE(dbObjects.CreateTable(TEST_TABLE, {{"id", "INT"}}));
ASSERT_NO_FATAL_FAILURE(dbObjects.Insert(TEST_TABLE,"(1), (2), (3), (4)"));
// Setup num_rows_before
ASSERT_NO_FATAL_FAILURE(odbcHandler.Connect(true));
ASSERT_NO_FATAL_FAILURE(odbcHandler.ExecQuery(TEST_SELECT));
// Count all the rows before delete for setup
while (SQLFetch(odbcHandler.GetStatementHandle()) != SQL_NO_DATA) {
num_rows_before++;
}
// Setup for SQLSetpos with SQL_Delete option
ASSERT_NO_FATAL_FAILURE(odbcHandler.FreeAllHandles());
ASSERT_NO_FATAL_FAILURE(ConnectAndSetScrollableWithConcurLock(&odbcHandler));
ASSERT_NO_FATAL_FAILURE(odbcHandler.ExecQuery(TEST_SELECT));
// Call SQLSetPos with SQL_DELETE option and ensure that it is succesful
rcode = SQLFetch(odbcHandler.GetStatementHandle());
ASSERT_EQ(rcode, SQL_SUCCESS) << odbcHandler.GetErrorMessage(SQL_HANDLE_STMT, rcode);
rcode = SQLSetPos(odbcHandler.GetStatementHandle(), 1, SQL_DELETE, SQL_LOCK_NO_CHANGE);
EXPECT_EQ(rcode, SQL_SUCCESS) << odbcHandler.GetErrorMessage(SQL_HANDLE_STMT, rcode);
ASSERT_NO_FATAL_FAILURE(odbcHandler.FreeAllHandles());
// Recount all rows and assert that there is one less than before
ASSERT_NO_FATAL_FAILURE(odbcHandler.ConnectAndExecQuery(TEST_SELECT));
while (SQLFetch(odbcHandler.GetStatementHandle()) != SQL_NO_DATA) {
num_rows_after++;
}
ASSERT_EQ(num_rows_after, num_rows_before -1);
}
// Ensures that SQLGetData works correctly
TEST_F(Result_Set, SQLGetData_Successful) {
OdbcHandler odbcHandler;
RETCODE rcode;
SQLINTEGER id;
SQLLEN id_indicator;
// Setup
ASSERT_NO_FATAL_FAILURE(odbcHandler.ConnectAndExecQuery(SELECT_RESULT_SET_RO_TABLE1));
rcode = SQLFetch(odbcHandler.GetStatementHandle());
ASSERT_EQ(rcode, SQL_SUCCESS) << odbcHandler.GetErrorMessage(SQL_HANDLE_STMT, rcode);
// Assert that SQLGetData retrieves the correct value
rcode = SQLGetData(odbcHandler.GetStatementHandle(), 1, SQL_C_ULONG, &id, 0, &id_indicator);
ASSERT_EQ(rcode, SQL_SUCCESS) << odbcHandler.GetErrorMessage(SQL_HANDLE_STMT, rcode);
ASSERT_EQ(id, 1);
}
// Tests SQLGetData when a varchar variable gets truncated
TEST_F(Result_Set, SQLGetData_TruncatedVarchar) {
OdbcHandler odbcHandler;
RETCODE rcode;
string sql_state;
SQLCHAR info[2];
SQLLEN info_indicator;
// Setup
ASSERT_NO_FATAL_FAILURE(odbcHandler.ConnectAndExecQuery(SELECT_RESULT_SET_RO_TABLE1));
rcode = SQLFetch(odbcHandler.GetStatementHandle());
ASSERT_EQ(rcode, SQL_SUCCESS) << odbcHandler.GetErrorMessage(SQL_HANDLE_STMT, rcode);
// Assert that we get sql state 01004 when a varchar variable is truncated
rcode = SQLGetData(odbcHandler.GetStatementHandle(), 2, SQL_C_CHAR, &info, sizeof(info), &info_indicator);
ASSERT_EQ(rcode, SQL_SUCCESS_WITH_INFO) << odbcHandler.GetErrorMessage(SQL_HANDLE_STMT, rcode);
sql_state = odbcHandler.GetSqlState(SQL_HANDLE_STMT,odbcHandler.GetStatementHandle());
ASSERT_EQ(sql_state, "01004");
}
// Tests SQLGetData when a numeric datatype gets truncated
TEST_F(Result_Set, SQLGetData_TruncatedNumeric) {
OdbcHandler odbcHandler;
RETCODE rcode;
string sql_state;
SQLINTEGER decivar;
SQLLEN decivar_indicator;
// Setup
ASSERT_NO_FATAL_FAILURE(odbcHandler.ConnectAndExecQuery(SELECT_RESULT_SET_RO_TABLE1));
rcode = SQLFetch(odbcHandler.GetStatementHandle());
ASSERT_EQ(rcode, SQL_SUCCESS) << odbcHandler.GetErrorMessage(SQL_HANDLE_STMT, rcode);
// Assert that we get sql state 01004 when a numeric datatype is truncated
rcode = SQLGetData(odbcHandler.GetStatementHandle(), 3, SQL_C_ULONG, &decivar, 0, &decivar_indicator);
ASSERT_EQ(rcode, SQL_SUCCESS_WITH_INFO) << odbcHandler.GetErrorMessage(SQL_HANDLE_STMT, rcode);
sql_state = odbcHandler.GetSqlState(SQL_HANDLE_STMT,odbcHandler.GetStatementHandle());
ASSERT_EQ(sql_state, "01S07");
}
// Tests SQLGetData when there is an invalid cast during bindcol.
TEST_F(Result_Set, SQLGetData_InvalidCast) {
OdbcHandler odbcHandler;
RETCODE rcode;
string sql_state;
SQLINTEGER id;
SQLLEN id_indicator;
ASSERT_NO_FATAL_FAILURE(odbcHandler.ConnectAndExecQuery(SELECT_RESULT_SET_RO_TABLE1));
// Assert that we get sql state 22018 when there is an invalid cast
rcode = SQLFetch(odbcHandler.GetStatementHandle());
ASSERT_EQ(rcode, SQL_SUCCESS) << odbcHandler.GetErrorMessage(SQL_HANDLE_STMT, rcode);
rcode = SQLGetData(odbcHandler.GetStatementHandle(), 2, SQL_C_ULONG, &id, 0, &id_indicator);
ASSERT_EQ(rcode, SQL_ERROR);
sql_state = odbcHandler.GetSqlState(SQL_HANDLE_STMT,odbcHandler.GetStatementHandle());
ASSERT_EQ(sql_state, "22018");
}
// Test SQLFetchScroll with Fetch First and Fetch Last options
// DISABLED: PLEASE SEE BABELFISH-98
TEST_F(Result_Set, DISABLED_SQLFetchScroll_FetchFirstAndFetchLast) {
OdbcHandler odbcHandler;
RETCODE rcode;
string sql_state;
SQLINTEGER id;
SQLLEN id_indicator;
int firstValue = std::get<0>(RO_TABLE_VALUES[0]);
int lastValue = std::get<0>(RO_TABLE_VALUES[RO_TABLE_VALUES.size()-1]);
// Setup
ASSERT_NO_FATAL_FAILURE(ConnectAndSetScrollable(&odbcHandler));
ASSERT_NO_FATAL_FAILURE(odbcHandler.ExecQuery(SELECT_RESULT_SET_RO_TABLE1));
// Call SQLFetchScroll with SQL_FETCH_FIRST option and assert that the correct value is being returned
rcode = SQLFetchScroll(odbcHandler.GetStatementHandle(), SQL_FETCH_FIRST, 0);
ASSERT_EQ(rcode, SQL_SUCCESS) << odbcHandler.GetErrorMessage(SQL_HANDLE_STMT, rcode);
rcode = SQLGetData(odbcHandler.GetStatementHandle(), 1, SQL_C_ULONG, &id, 0, &id_indicator);
ASSERT_EQ(rcode, SQL_SUCCESS) << odbcHandler.GetErrorMessage(SQL_HANDLE_STMT, rcode);
ASSERT_EQ(id, firstValue);
// Call SQLFetchScroll with SQL_FETCH_LAST option and assert that the correct value is being returned
rcode = SQLFetchScroll(odbcHandler.GetStatementHandle(), SQL_FETCH_LAST, 0);
ASSERT_EQ(rcode, SQL_SUCCESS) << odbcHandler.GetErrorMessage(SQL_HANDLE_STMT, rcode);
rcode = SQLGetData(odbcHandler.GetStatementHandle(), 1, SQL_C_ULONG, &id, 0, &id_indicator);
ASSERT_EQ(rcode, SQL_SUCCESS) << odbcHandler.GetErrorMessage(SQL_HANDLE_STMT, rcode);
ASSERT_EQ(id, lastValue);
}
// Test SQLFetchScroll with SQL_FETCH_NEXT and SQL_FETCH_PRIOR
// DISABLED: PLEASE SEE BABELFISH-98
TEST_F(Result_Set, DISABLED_SQLFetchScroll_FetchNextAndFetchPrior) {
OdbcHandler odbcHandler;
RETCODE rcode;
string sql_state;
SQLINTEGER id;
SQLLEN id_indicator;
// setup
ASSERT_NO_FATAL_FAILURE(ConnectAndSetScrollable(&odbcHandler));
ASSERT_NO_FATAL_FAILURE(odbcHandler.ExecQuery(SELECT_RESULT_SET_RO_TABLE1));
int num_results = RO_TABLE_VALUES.size();
// Move the cursor forward through all the results and assert the values retrieved are correct
for (int i = 1; i <= num_results; i++) {
rcode = SQLFetchScroll(odbcHandler.GetStatementHandle(), SQL_FETCH_NEXT, 0);
ASSERT_EQ(rcode, SQL_SUCCESS) << odbcHandler.GetErrorMessage(SQL_HANDLE_STMT, rcode);
rcode = SQLGetData(odbcHandler.GetStatementHandle(), 1, SQL_C_ULONG, &id, 0, &id_indicator);
ASSERT_EQ(rcode, SQL_SUCCESS) << odbcHandler.GetErrorMessage(SQL_HANDLE_STMT, rcode);
ASSERT_EQ(id, std::get<0>(RO_TABLE_VALUES[i-1]));
}
// Assert that there is no more data past the end
rcode = SQLFetchScroll(odbcHandler.GetStatementHandle(), SQL_FETCH_NEXT, 0);
ASSERT_EQ(rcode, SQL_NO_DATA);
// Move the cursor backwards through all the results and assert the values retrieved are correct
for (int i = num_results; i > 0; i--) {
rcode = SQLFetchScroll(odbcHandler.GetStatementHandle(), SQL_FETCH_PRIOR, 0);
ASSERT_EQ(rcode, SQL_SUCCESS) << odbcHandler.GetErrorMessage(SQL_HANDLE_STMT, rcode);
rcode = SQLGetData(odbcHandler.GetStatementHandle(), 1, SQL_C_ULONG, &id, 0, &id_indicator);
ASSERT_EQ(rcode, SQL_SUCCESS) << odbcHandler.GetErrorMessage(SQL_HANDLE_STMT, rcode);
ASSERT_EQ(id, std::get<0>(RO_TABLE_VALUES[i-1]));
}
// Assert that there is no more data before the beginning of the result set
rcode = SQLFetchScroll(odbcHandler.GetStatementHandle(), SQL_FETCH_PRIOR, 0);
ASSERT_EQ(rcode, SQL_NO_DATA);
}
// Test SQLFetchScroll with SQL_FETCH_ABSOLUTE
// DISABLED: PLEASE SEE BABELFISH-98
TEST_F(Result_Set, DISABLED_SQLFetchScroll_FetchAbsolute) {
OdbcHandler odbcHandler;
RETCODE rcode;
SQLINTEGER id;
SQLLEN id_indicator;
// Setup connection
ASSERT_NO_FATAL_FAILURE(ConnectAndSetScrollable(&odbcHandler));
ASSERT_NO_FATAL_FAILURE(odbcHandler.ExecQuery(SELECT_RESULT_SET_RO_TABLE1));
int num_results = RO_TABLE_VALUES.size();
// Go through the whole table and assert that the correct values are retrieved
for (int i = 1; i <= num_results; i++) {
rcode = SQLFetchScroll(odbcHandler.GetStatementHandle(), SQL_FETCH_ABSOLUTE, i);
ASSERT_EQ(rcode, SQL_SUCCESS) << odbcHandler.GetErrorMessage(SQL_HANDLE_STMT, rcode);
rcode = SQLGetData(odbcHandler.GetStatementHandle(), 1, SQL_C_ULONG, &id, 0, &id_indicator);
ASSERT_EQ(rcode, SQL_SUCCESS) << odbcHandler.GetErrorMessage(SQL_HANDLE_STMT, rcode);
ASSERT_EQ(id, std::get<0>(RO_TABLE_VALUES[i-1]));
}
// Assert that we will move to row 2 and that the value of id is correct
rcode = SQLFetchScroll(odbcHandler.GetStatementHandle(), SQL_FETCH_ABSOLUTE, 2);
ASSERT_EQ(rcode, SQL_SUCCESS) << odbcHandler.GetErrorMessage(SQL_HANDLE_STMT, rcode);
rcode = SQLGetData(odbcHandler.GetStatementHandle(), 1, SQL_C_ULONG, &id, 0, &id_indicator);
ASSERT_EQ(rcode, SQL_SUCCESS) << odbcHandler.GetErrorMessage(SQL_HANDLE_STMT, rcode);
ASSERT_EQ(id, std::get<0>(RO_TABLE_VALUES[1]));
}
// Test SQLFetchScroll with SQL_FETCH_RELATIVE
// DISABLED: PLEASE SEE BABELFISH-98
TEST_F(Result_Set, DISABLED_SQLFetchScroll_FetchRelative) {
OdbcHandler odbcHandler;
RETCODE rcode;
SQLINTEGER id;
SQLLEN id_indicator;
// Setup
ASSERT_NO_FATAL_FAILURE(ConnectAndSetScrollable(&odbcHandler));
ASSERT_NO_FATAL_FAILURE(odbcHandler.ExecQuery(SELECT_RESULT_SET_RO_TABLE1));
int num_results = RO_TABLE_VALUES.size();
// Go through all the results and assert that the correct value for id is fetched
for (int i = 1; i <= num_results; i++) {
rcode = SQLFetchScroll(odbcHandler.GetStatementHandle(), SQL_FETCH_RELATIVE, 1);
ASSERT_EQ(rcode, SQL_SUCCESS) << odbcHandler.GetErrorMessage(SQL_HANDLE_STMT, rcode);
rcode = SQLGetData(odbcHandler.GetStatementHandle(), 1, SQL_C_ULONG, &id, 0, &id_indicator);
ASSERT_EQ(rcode, SQL_SUCCESS) << odbcHandler.GetErrorMessage(SQL_HANDLE_STMT, rcode);
ASSERT_EQ(id, std::get<0>(RO_TABLE_VALUES[i-1]));
}
// Move the cursor back by 2 rows and assert that the correct result is fetched
rcode = SQLFetchScroll(odbcHandler.GetStatementHandle(), SQL_FETCH_RELATIVE, -2);
ASSERT_EQ(rcode, SQL_SUCCESS) << odbcHandler.GetErrorMessage(SQL_HANDLE_STMT, rcode);
rcode = SQLGetData(odbcHandler.GetStatementHandle(), 1, SQL_C_ULONG, &id, 0, &id_indicator);
ASSERT_EQ(rcode, SQL_SUCCESS) << odbcHandler.GetErrorMessage(SQL_HANDLE_STMT, rcode);
ASSERT_EQ(id, std::get<0>(RO_TABLE_VALUES[1]));
// Assert that SQL_NO_DATA is returned when the cursor is moved past before the beginning
rcode = SQLFetchScroll(odbcHandler.GetStatementHandle(), SQL_FETCH_RELATIVE, -2);
ASSERT_EQ(rcode, SQL_NO_DATA);
}
// Tests SQLNumResultCols
TEST_F(Result_Set, SQLNumResultCols) {
OdbcHandler odbcHandler;
RETCODE rcode;
string sql_state;
SQLSMALLINT num_cols;
ASSERT_NO_FATAL_FAILURE(odbcHandler.ConnectAndExecQuery(SELECT_RESULT_SET_RO_TABLE1));
rcode = SQLNumResultCols(odbcHandler.GetStatementHandle(), &num_cols);
ASSERT_EQ(rcode, SQL_SUCCESS) << odbcHandler.GetErrorMessage(SQL_HANDLE_STMT, rcode);
ASSERT_EQ(num_cols, RO_TABLE_COLUMNS.size());
}
// Tests SQLCloseCursor
// DISABLED: PLEASE SEE BABELFISH-99
TEST_F(Result_Set, DISABLED_SQLCloseCursor) {
OdbcHandler odbcHandler;
RETCODE rcode;
string sql_state;
SQLINTEGER id;
SQLLEN id_indicator;
// setup
ASSERT_NO_FATAL_FAILURE(ConnectAndSetScrollable(&odbcHandler));
ASSERT_NO_FATAL_FAILURE(odbcHandler.ExecQuery(SELECT_RESULT_SET_RO_TABLE1));
// Assert that it is unable the fetch after closing the cursor and that the correct sql state
// has been produced
rcode = SQLFetchScroll(odbcHandler.GetStatementHandle(), SQL_FETCH_ABSOLUTE, 1);
ASSERT_EQ(rcode, SQL_SUCCESS) << odbcHandler.GetErrorMessage(SQL_HANDLE_STMT, rcode);
rcode = SQLCloseCursor(odbcHandler.GetStatementHandle());
ASSERT_EQ(rcode, SQL_SUCCESS) << odbcHandler.GetErrorMessage(SQL_HANDLE_STMT, rcode);
rcode = SQLFetchScroll(odbcHandler.GetStatementHandle(), SQL_FETCH_ABSOLUTE, 2);
ASSERT_EQ(rcode, SQL_ERROR);
sql_state = odbcHandler.GetSqlState(SQL_HANDLE_STMT, odbcHandler.GetStatementHandle());
ASSERT_EQ(sql_state, "HY010");
}
// Test SQLDescribeCol
// DISABLED: PLEASE SEE BABELFISH-100
TEST_F(Result_Set, DISABLED_SQLDescribeCol) {
OdbcHandler odbcHandler;
SQLCHAR col_name[256];
SQLSMALLINT name_length;
SQLSMALLINT data_type;
SQLULEN col_size;
SQLSMALLINT dec_digits;
SQLSMALLINT nullable_ptr;
RETCODE rcode;
// Setup
ASSERT_NO_FATAL_FAILURE(odbcHandler.ConnectAndExecQuery(SELECT_RESULT_SET_RO_TABLE1));
rcode = SQLFetch(odbcHandler.GetStatementHandle());
ASSERT_EQ(rcode, SQL_SUCCESS) << odbcHandler.GetErrorMessage(SQL_HANDLE_STMT, rcode);
// The expected values would need to be updated if the RO_TABLE_COLUMNS change.
vector<tuple<string,int, int, int, int, int>> expected_values = {
{"id", 2, SQL_INTEGER, 10, 0, SQL_NULLABLE},
{"info", 4, SQL_VARCHAR, 256, 0, SQL_NO_NULLS},
{"decivar", 7, SQL_NUMERIC, 38, 16, SQL_NULLABLE}
};
int ordinal {0};
for (auto column_info : expected_values) {
++ordinal;
rcode = SQLDescribeCol(odbcHandler.GetStatementHandle(),
ordinal,
col_name,
sizeof(col_name),
&name_length,
&data_type,
&col_size,
&dec_digits,
&nullable_ptr);
ASSERT_EQ(rcode, SQL_SUCCESS) << odbcHandler.GetErrorMessage(SQL_HANDLE_STMT, rcode);
auto& [name, name_len, sql_type, size, digits, nullable] = column_info;
EXPECT_EQ(string( (char*) col_name), name);
EXPECT_EQ(name_length, name_len);
EXPECT_EQ(data_type,sql_type );
EXPECT_EQ(col_size, size);
EXPECT_EQ(dec_digits,digits);
EXPECT_EQ(nullable_ptr,nullable);
}
}
TEST_F(Result_Set, SQLMoreResults_BatchedQueries) {
OdbcHandler odbcHandler;
RETCODE rcode;
SQLLEN id_indciator = 0;
string sql_state;
int id = 0;
string batch_query = SelectStatement(RESULT_SET_RO_TABLE1, { "*" }, {}, "id = 1") + " ; " +
SelectStatement(RESULT_SET_RO_TABLE1, { "*" }, {}, "id = 2");
ASSERT_NO_FATAL_FAILURE(odbcHandler.Connect(true));
rcode = SQLPrepare(odbcHandler.GetStatementHandle(),(SQLCHAR*) batch_query.c_str(), SQL_NTS);
ASSERT_EQ(rcode, SQL_SUCCESS) << odbcHandler.GetErrorMessage(SQL_HANDLE_STMT, rcode);
rcode = SQLExecute(odbcHandler.GetStatementHandle());
ASSERT_EQ(rcode, SQL_SUCCESS) << odbcHandler.GetErrorMessage(SQL_HANDLE_STMT, rcode);
rcode = SQLFetch(odbcHandler.GetStatementHandle());
ASSERT_EQ(rcode, SQL_SUCCESS) << odbcHandler.GetErrorMessage(SQL_HANDLE_STMT, rcode);
rcode = SQLGetData(odbcHandler.GetStatementHandle(), 1, SQL_C_ULONG, &id, 0, 0);
ASSERT_EQ(rcode, SQL_SUCCESS) << odbcHandler.GetErrorMessage(SQL_HANDLE_STMT, rcode);
ASSERT_EQ(id, 1);
rcode = SQLMoreResults(odbcHandler.GetStatementHandle());
ASSERT_EQ(rcode, SQL_SUCCESS) << odbcHandler.GetErrorMessage(SQL_HANDLE_STMT, rcode);
rcode = SQLFetch(odbcHandler.GetStatementHandle());
ASSERT_EQ(rcode, SQL_SUCCESS) << odbcHandler.GetErrorMessage(SQL_HANDLE_STMT, rcode);
rcode = SQLGetData(odbcHandler.GetStatementHandle(), 1, SQL_C_ULONG, &id, 0, 0);
ASSERT_EQ(rcode, SQL_SUCCESS) << odbcHandler.GetErrorMessage(SQL_HANDLE_STMT, rcode);
ASSERT_EQ(id, 2);
rcode = SQLMoreResults(odbcHandler.GetStatementHandle());
ASSERT_EQ(rcode, SQL_NO_DATA);
}
| 41.918528 | 148 | 0.762351 | [
"vector"
] |
7830699d7bf22dbe6d3de0b195b51c5a25c083a5 | 7,117 | hpp | C++ | cbits/memory.hpp | twesterhout/tcm-swarm | e632d493a9dc0b78c2634c2ac6311abc5f99168a | [
"BSD-3-Clause"
] | null | null | null | cbits/memory.hpp | twesterhout/tcm-swarm | e632d493a9dc0b78c2634c2ac6311abc5f99168a | [
"BSD-3-Clause"
] | null | null | null | cbits/memory.hpp | twesterhout/tcm-swarm | e632d493a9dc0b78c2634c2ac6311abc5f99168a | [
"BSD-3-Clause"
] | null | null | null | // Copyright Tom Westerhout (c) 2018
//
// 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 Tom Westerhout nor the names of other
// 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.
#pragma once
#include "detail/config.hpp"
#include "detail/errors.hpp"
#include "logging.hpp"
#include <boost/core/demangle.hpp>
#include <Vc/Vc>
#include <memory>
TCM_SWARM_BEGIN_NAMESPACE
struct FreeDeleter {
template <class T>
auto operator()(T* p) const noexcept -> void
{
std::free(p);
}
};
namespace detail {
template <class Int, class = std::enable_if_t<std::is_integral_v<Int>>>
inline constexpr auto is_power_of_2(Int const n) noexcept -> bool
{
return n > 0 && (n & (n - 1)) == 0;
}
/// \brief Determines which alignment to use for internal vectors (biases and
/// weights).
template <class T, class Abi = Vc::simd_abi::native<T>>
constexpr auto alignment() noexcept -> std::size_t
{
// Intel MKL suggests to use buffers aligned to at least 64 bytes for
// optimal performance.
return std::max<std::size_t>(Vc::memory_alignment_v<Vc::simd<T, Abi>>, 64u);
}
/// \brief Rounds `n` up to a multiple of `Alignment`.
template <std::size_t Alignment>
constexpr auto round_up_to(std::size_t const n) noexcept -> std::size_t
{
static_assert(Alignment > 0 && (Alignment & (Alignment - 1)) == 0,
"Alignment must be a power of 2.");
return (n + Alignment - 1) & ~(Alignment - 1);
}
template <class T>
[[noreturn]] auto integer_overflow_in_allocation(
std::size_t dim, std::size_t count, std::size_t max_size) -> void
{
std::string msg =
format(fmt("Integer overflow encountered when trying to allocate "
"space for a vector of {} elements. The length was "
"rounded up to {} which exceeds {}, the maximal allowed "
"length for a buffer of {}."),
dim, count, max_size, boost::core::demangle(typeid(T).name()));
global_logger()->critical(msg);
throw_with_trace(std::length_error{"Integer overflow."});
}
// clang-format off
template <class T, std::size_t Alignment, std::size_t VectorSize>
TCM_SWARM_FORCEINLINE
auto allocate_aligned_buffer(std::size_t const dim)
-> std::tuple<std::unique_ptr<T[], FreeDeleter>, std::size_t>
// clang-format on
{
if (dim == 0) return {nullptr, 0};
auto const count = detail::round_up_to<VectorSize>(dim);
constexpr auto max_size =
std::numeric_limits<std::size_t>::max() / sizeof(T);
if (count > max_size) {
integer_overflow_in_allocation<T>(dim, count, max_size);
}
static_assert(VectorSize * sizeof(T) % Alignment == 0);
auto* raw =
reinterpret_cast<T*>(std::aligned_alloc(Alignment, count * sizeof(T)));
if (raw == nullptr) { throw_with_trace(std::bad_alloc{}); }
std::unique_ptr<T[], FreeDeleter> pointer{raw};
// TODO(twesterhout): Measure whether this matters and should be removed.
for (std::size_t j = dim; j < count; ++j) {
::new (raw + j) T;
}
return {std::move(pointer), count};
}
// clang-format off
template <class T, std::size_t Alignment, std::size_t VectorSize>
TCM_SWARM_FORCEINLINE
auto allocate_aligned_buffer(std::size_t const dim1, std::size_t const dim2)
-> std::tuple<std::unique_ptr<T[], FreeDeleter>, std::size_t, std::size_t>
// clang-format on
{
if (dim1 == 0 || dim2 == 0) return {nullptr, 0, 0};
auto const stride = detail::round_up_to<VectorSize>(dim2);
constexpr auto max_size =
std::numeric_limits<std::size_t>::max() / sizeof(T);
if (stride > max_size / dim1) {
// TODO(twesterhout): Strictly speaking, these multiplications may
// result in overflow, so the log message will be incorrect.
integer_overflow_in_allocation<T>(dim1 * dim2, dim1 * stride, max_size);
}
static_assert(VectorSize * sizeof(T) % Alignment == 0);
auto* raw = reinterpret_cast<T*>(
std::aligned_alloc(Alignment, dim1 * stride * sizeof(T)));
if (raw == nullptr) { throw_with_trace(std::bad_alloc{}); }
std::unique_ptr<T[], FreeDeleter> pointer{raw};
// TODO(twesterhout): Measure whether this matters and should be removed.
for (std::size_t i = 0; i < dim1; ++i) {
for (std::size_t j = dim2; j < stride; ++j) {
::new (raw + i * stride + j) T;
}
}
return {std::move(pointer), dim1, stride};
}
} // namespace detail
/// \brief Allocates a new buffer for a vector of dimension `dim`.
///
/// The returned vector has size of ``dim`` rounded up to a multiple of
/// ``Vc::simd<T, Abi>::size()`` and is aligned to at least
/// ``Vc::memory_alignment_v<Vc::simd<T, Abi>>``.
template <class T, class Abi, class... Size_t>
auto allocate_aligned_buffer(Size_t... dimensions)
{
static_assert(Vc::is_abi_tag_v<Abi>, "Abi must be a valid ABI tag.");
if constexpr (detail::is_complex_v<T>) {
using R = typename T::value_type;
static_assert(std::is_floating_point_v<R>,
"Only std::complex<R> where R is a floating point is supported.");
constexpr auto vector_size = Vc::simd<R, Abi>::size();
constexpr auto alignment = detail::alignment<R, Abi>();
return detail::allocate_aligned_buffer<T, alignment, vector_size>(dimensions...);
}
else {
static_assert(std::is_floating_point_v<T> || std::is_integral_v<T>,
"Only floating point and integral types are supported.");
constexpr auto vector_size = Vc::simd<T, Abi>::size();
constexpr auto alignment = detail::alignment<T, Abi>();
return detail::allocate_aligned_buffer<T, alignment, vector_size>(dimensions...);
}
}
TCM_SWARM_END_NAMESPACE
| 39.759777 | 89 | 0.672755 | [
"vector"
] |
783271ce8d4b1caf720b5d3c51a63bfe666da7ca | 56,073 | cpp | C++ | src/prod/src/ServiceModel/transport/SecuritySettings.cpp | vishnuk007/service-fabric | d0afdea185ae932cc3c9eacf179692e6fddbc630 | [
"MIT"
] | 1 | 2020-06-15T04:33:36.000Z | 2020-06-15T04:33:36.000Z | src/prod/src/ServiceModel/transport/SecuritySettings.cpp | vishnuk007/service-fabric | d0afdea185ae932cc3c9eacf179692e6fddbc630 | [
"MIT"
] | null | null | null | src/prod/src/ServiceModel/transport/SecuritySettings.cpp | vishnuk007/service-fabric | d0afdea185ae932cc3c9eacf179692e6fddbc630 | [
"MIT"
] | null | null | null | // ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#include "stdafx.h"
using namespace Transport;
using namespace Common;
using namespace std;
static StringLiteral const TraceType = "SecuritySettings";
//Specifies settings with no security
SecuritySettings::SecuritySettings()
: x509StoreLocation_(X509Default::StoreLocation())
{
}
_Use_decl_annotations_
ErrorCode SecuritySettings::CreateNegotiateServer(wstring const & clientIdentity, SecuritySettings & object)
{
object = SecuritySettings();
object.securityProvider_ = SecurityProvider::Negotiate;
if (!clientIdentity.empty())
{
object.remoteIdentities_.insert(clientIdentity);
}
// Need to turn on protection to mitigate "forwarding attacks", details described in bug 931057
object.protectionLevel_ = ProtectionLevel::Sign;
return ErrorCode::Success();
}
_Use_decl_annotations_
ErrorCode SecuritySettings::CreateNegotiateClient(wstring const & serverIdentity, SecuritySettings & object)
{
object = SecuritySettings();
object.securityProvider_ = SecurityProvider::Negotiate;
object.remoteSpn_ = serverIdentity;
// Need to turn on protection to mitigate "forwarding attacks", details described in bug 931057
object.protectionLevel_ = ProtectionLevel::Sign;
return ErrorCode::Success();
}
_Use_decl_annotations_
ErrorCode SecuritySettings::CreateNegotiate(
wstring const & serverIdentity,
wstring const & clientIdentities,
wstring const & protectionLevel,
SecuritySettings & object)
{
object = SecuritySettings();
object.securityProvider_ = SecurityProvider::Negotiate;
object.remoteSpn_ = serverIdentity;
vector<wstring> remoteIdentities;
StringUtility::Split<wstring>(clientIdentities, remoteIdentities, L",", true);
object.remoteIdentities_.insert(remoteIdentities.cbegin(), remoteIdentities.cend());
return ProtectionLevel::Parse(protectionLevel, object.protectionLevel_);
}
_Use_decl_annotations_
ErrorCode SecuritySettings::GenerateClientCert(SecureString & certKey, CertContextUPtr & cert) const
{
#ifndef PLATFORM_UNIX
wstring commonName = Guid::NewGuid().ToString();
auto error = CryptoUtility::GenerateExportableKey(
L"CN=" + commonName,
certKey);
if (!error.IsSuccess()) { return error; }
error = CryptoUtility::CreateSelfSignedCertificate(
L"CN=" + commonName,
L"CN=" + commonName,
cert);
if (!error.IsSuccess()) { return error; }
Thumbprint thumbprint;
error = thumbprint.Initialize(cert.get());
if (!error.IsSuccess()) { return error; }
remoteCertThumbprints_.Add(thumbprint);
#endif
return ErrorCode::Success();
}
_Use_decl_annotations_
ErrorCode SecuritySettings::CreateSelfGeneratedCertSslServer(SecuritySettings & object)
{
object = SecuritySettings();
#ifdef PLATFORM_UNIX
object.securityProvider_ = SecurityProvider::None;
#else
wstring commonName = Guid::NewGuid().ToString();
CertContextUPtr cert;
auto error = CryptoUtility::CreateSelfSignedCertificate(
L"CN=" + commonName,
L"CN=" + commonName,
cert);
object.certContext_ = make_shared<CertContextUPtr>(move(cert));
if (!error.IsSuccess()) { return error; }
object.isSelfGeneratedCert_ = true;
object.securityProvider_ = SecurityProvider::Ssl;
Thumbprint thumbprint;
error = thumbprint.Initialize(object.certContext_->get());
if (!error.IsSuccess()) { return error; }
// Need to turn on protection to mitigate "forwarding attacks", details described in bug 931057
object.protectionLevel_ = ProtectionLevel::EncryptAndSign;
#endif
return ErrorCode::Success();
}
_Use_decl_annotations_
ErrorCode SecuritySettings::CreateSslClient(
Common::CertContextUPtr & certContext,
wstring const & serverThumbprint,
SecuritySettings & object)
{
object = SecuritySettings();
#ifdef PLATFORM_UNIX
object.securityProvider_ = SecurityProvider::None;
#else
object.isSelfGeneratedCert_ = true;
object.securityProvider_ = SecurityProvider::Ssl;
object.certContext_ = make_shared<CertContextUPtr>(move(certContext));
object.SetRemoteCertThumbprints(serverThumbprint);
// Need to turn on protection to mitigate "forwarding attacks", details described in bug 931057
object.protectionLevel_ = ProtectionLevel::EncryptAndSign;
#endif
return ErrorCode::Success();
}
ErrorCode SecuritySettings::CreateSslClient(
wstring const & serverThumbprint,
_Out_ SecuritySettings & object)
{
object = SecuritySettings();
object.securityProvider_ = SecurityProvider::Ssl;
object.isSelfGeneratedCert_ = false;
object.protectionLevel_ = ProtectionLevel::EncryptAndSign;
object.x509StoreLocation_ = X509StoreLocation::CurrentUser;
object.x509StoreName_ = L"MY";
X509FindValue::Create(X509FindType::FindByThumbprint, serverThumbprint, object.x509FindValue_);
return object.remoteCertThumbprints_.Add(serverThumbprint);
}
_Use_decl_annotations_
ErrorCode SecuritySettings::CreateKerberos(
wstring const & remoteSpn,
wstring const & clientIdentities,
wstring const & protectionLevel,
SecuritySettings & object)
{
object = SecuritySettings();
object.securityProvider_ = SecurityProvider::Kerberos;
object.remoteSpn_ = remoteSpn;
vector<wstring> remoteIdentities;
StringUtility::Split<wstring>(clientIdentities, remoteIdentities, L",", true);
object.remoteIdentities_.insert(remoteIdentities.cbegin(), remoteIdentities.cend());
return ProtectionLevel::Parse(protectionLevel, object.protectionLevel_);
}
_Use_decl_annotations_ ErrorCode SecuritySettings::FromConfiguration(
wstring const & credentialType,
wstring const & x509StoreName,
wstring const & x509StoreLocation,
wstring const & x509FindType,
wstring const & x509FindValue,
wstring const & x509FindValueSecondary,
wstring const & protectionLevel,
wstring const & remoteCertThumbprints,
SecurityConfig::X509NameMap const & remoteX509Names,
SecurityConfig::IssuerStoreKeyValueMap const & remoteCertIssuers,
wstring const & remoteCertCommonNames,
wstring const & defaultRemoteCertIssuers,
wstring const & remoteSpn,
wstring const & clientIdentities,
SecuritySettings & object)
{
object = SecuritySettings();
auto error = SecurityProvider::FromCredentialType(credentialType, object.securityProvider_);
if (!error.IsSuccess()) { return error; }
if (object.securityProvider_ == SecurityProvider::None)
{
return ErrorCode::Success();
}
error = ProtectionLevel::Parse(protectionLevel, object.protectionLevel_);
if (!error.IsSuccess()) { return error; }
if (object.securityProvider_ == SecurityProvider::Negotiate)
{
return CreateNegotiate(remoteSpn, clientIdentities, protectionLevel, object);
}
if (object.securityProvider_ == SecurityProvider::Kerberos)
{
return CreateKerberos(remoteSpn, clientIdentities, protectionLevel, object);
}
if (object.securityProvider_ == SecurityProvider::Claims)
{
// Claims type is only allowed on public API
return ErrorCodeValue::InvalidCredentialType;
}
ASSERT_IFNOT(
object.securityProvider_ == SecurityProvider::Ssl,
"Unexpected security provider type at FromConfiguration: {0}",
object.securityProvider_);
error = object.remoteCertThumbprints_.Set(remoteCertThumbprints);
if (!error.IsSuccess()) return error;
if (!remoteX509Names.ParseError().IsSuccess())
{
WriteError(TraceType, "remoteX509Names.Error: {0}", remoteX509Names.ParseError());
return remoteX509Names.ParseError();
}
object.remoteX509Names_ = (remoteX509Names);
error = object.defaultX509IssuerThumbprints_.SetToThumbprints(defaultRemoteCertIssuers);
if (!error.IsSuccess()) return error;
if (!object.defaultX509IssuerThumbprints_.IsEmpty() && !object.remoteX509Names_.IsEmpty())
{
WriteError(TraceType, "Default issuer list '{0}' cannot be used together with X509Names '{1}'", object.defaultX509IssuerThumbprints_, object.remoteX509Names_);
return ErrorCodeValue::InvalidX509NameList;
}
vector<wstring> remoteNamesIssuersUnspecified;
StringUtility::Split<wstring>(remoteCertCommonNames, remoteNamesIssuersUnspecified, L",", true);
for (auto const & name : remoteNamesIssuersUnspecified)
{
object.remoteX509Names_.Add(name, object.defaultX509IssuerThumbprints_);
}
object.remoteCertIssuers_ = remoteCertIssuers;
if (!object.defaultX509IssuerThumbprints_.IsEmpty() && !object.remoteCertIssuers_.IsEmpty())
{
WriteError(TraceType, "Default issuer list '{0}' cannot be used together with RemoteCertIssuers '{1}'", object.defaultX509IssuerThumbprints_, object.remoteCertIssuers_);
return ErrorCodeValue::InvalidX509NameList;
}
if (!object.remoteX509Names_.GetAllIssuers().IsEmpty() && !object.remoteCertIssuers_.IsEmpty())
{
WriteError(TraceType, "X509Names '{0}' with issuer pinning cannot be used together with RemoteCertIssuers '{1}'", object.remoteX509Names_, object.remoteCertIssuers_);
return ErrorCodeValue::InvalidX509NameList;
}
error = UpdateRemoteIssuersIfNeeded(object);
if (!error.IsSuccess())
{
WriteError(TraceType, "FromConfiguration: UpdateRemoteIssuersIfNeeded failed: {0}", error);
return error;
}
object.x509StoreName_ = x509StoreName;
#ifndef PLATFORM_UNIX
if (object.x509StoreName_.empty()) { return ErrorCode(ErrorCodeValue::InvalidX509StoreName); }
#endif
if (x509StoreLocation.empty()) { return Common::ErrorCodeValue::InvalidX509StoreLocation; }
error = X509StoreLocation::Parse(x509StoreLocation, object.x509StoreLocation_);
if (!error.IsSuccess()) { return error; }
return X509FindValue::Create(x509FindType, x509FindValue, x509FindValueSecondary, object.x509FindValue_);
}
_Use_decl_annotations_
ErrorCode SecuritySettings::CreateClaimTokenClient(
wstring const & localClaimToken,
wstring const & serverCertThumbpints,
wstring const & serverCertCommonNames,
wstring const & serverCertIssuers,
wstring const & protectionLevel,
SecuritySettings & object)
{
object = SecuritySettings();
object.securityProvider_ = SecurityProvider::Claims;
object.localClaimToken_ = localClaimToken;
StringUtility::TrimWhitespaces(object.localClaimToken_);
if (object.localClaimToken_.empty())
{
return ErrorCodeValue::InvalidArgument;
}
auto error = object.remoteCertThumbprints_.Set(serverCertThumbpints);
if (!error.IsSuccess()) return error;
error = object.defaultX509IssuerThumbprints_.SetToThumbprints(serverCertIssuers);
if (!error.IsSuccess()) return error;
vector<wstring> svrNames;
StringUtility::Split<wstring>(serverCertCommonNames, svrNames, L",", true);
for (auto const & name : svrNames)
{
object.remoteX509Names_.Add(name, object.defaultX509IssuerThumbprints_);
}
return ProtectionLevel::Parse(protectionLevel, object.protectionLevel_);
}
bool SecuritySettings::operator == (SecuritySettings const & rhs) const
{
if (securityProvider_ != rhs.securityProvider_)
{
WriteInfo(TraceType, "securityProvider_: '{0}' != '{1}'", securityProvider_, rhs.securityProvider_);
return false;
}
if (this->securityProvider_ == SecurityProvider::None)
{
// No other validation is needed
return true;
}
if (protectionLevel_ != rhs.protectionLevel_)
{
WriteInfo(TraceType, "protectionLevel_: '{0}' != '{1}'", protectionLevel_, rhs.protectionLevel_);
return false;
}
if (remoteIdentities_ != rhs.remoteIdentities_)
{
WriteInfo(TraceType, "remoteIdentities_: '{0}' != '{1}'", remoteIdentities_, rhs.remoteIdentities_);
return false;
}
if (adminClientIdentities_ != rhs.adminClientIdentities_)
{
WriteInfo(TraceType, "adminClientIdentities_: '{0}' != '{1}'", adminClientIdentities_, rhs.adminClientIdentities_);
return false;
}
if (adminClientX509Names_ != rhs.adminClientX509Names_)
{
WriteInfo(TraceType, "adminClientX509Names_: '{0}' != '{1}'", adminClientX509Names_, rhs.adminClientX509Names_);
return false;
}
if (isClientRoleInEffect_ != rhs.isClientRoleInEffect_)
{
WriteInfo(TraceType, "isClientRoleInEffect_: '{0}' != '{1}'", isClientRoleInEffect_, rhs.isClientRoleInEffect_);
return false;
}
if (remoteCertThumbprints_ != rhs.remoteCertThumbprints_)
{
WriteInfo(TraceType, "remoteCertThumbprints_: '{0}' != '{1}'", remoteCertThumbprints_, rhs.remoteCertThumbprints_);
return false;
}
if (remoteX509Names_ != rhs.remoteX509Names_)
{
WriteInfo(TraceType, "remoteX509Names_: '{0}' != '{1}'", remoteX509Names_, rhs.remoteX509Names_);
return false;
}
if (remoteCertIssuers_ != rhs.remoteCertIssuers_)
{
WriteInfo(TraceType, "remoteCertIssuers_: '{0}' != '{1}'", remoteCertIssuers_, rhs.remoteCertIssuers_);
return false;
}
if (securityProvider_ == SecurityProvider::Ssl)
{
if (x509StoreLocation_ != rhs.x509StoreLocation_)
{
WriteInfo(TraceType, "x509StoreLocation_: '{0}' != '{1}'", x509StoreLocation_, rhs.x509StoreLocation_);
return false;
}
if (x509StoreName_ != rhs.x509StoreName_)
{
WriteInfo(TraceType, "x509StoreName_: '{0}' != '{1}'", x509StoreName_, rhs.x509StoreName_);
return false;
}
if ((x509FindValue_ && !rhs.x509FindValue_) || (!x509FindValue_ && rhs.x509FindValue_))
{
WriteInfo(TraceType, "x509FindValue_: {0} != {1}", TextTracePtr(x509FindValue_.get()), TextTracePtr(rhs.x509FindValue_.get()));
return false;
}
if ((x509FindValue_ != rhs.x509FindValue_) && (*x509FindValue_ != *(rhs.x509FindValue_)))
{
WriteInfo(TraceType, "x509FindValue_: {0} != {1}", x509FindValue_, rhs.x509FindValue_);
return false;
}
if (claimBasedClientAuthEnabled_ != rhs.claimBasedClientAuthEnabled_)
{
WriteInfo(TraceType, "claimBasedClientAuthEnabled_: '{0}' != '{1}'", claimBasedClientAuthEnabled_, rhs.claimBasedClientAuthEnabled_);
return false;
}
if (clientClaims_ != rhs.clientClaims_)
{
WriteInfo(TraceType, "clientClaims_: '{0}' != '{1}'", clientClaims_, rhs.clientClaims_);
return false;
}
if (adminClientClaims_ != rhs.adminClientClaims_)
{
WriteInfo(TraceType, "adminClientClaims_: '{0}' != '{1}'", adminClientClaims_, rhs.adminClientClaims_);
return false;
}
}
else if (SecurityProvider::IsWindowsProvider(securityProvider_))
{
if (!StringUtility::AreEqualCaseInsensitive(remoteSpn_, rhs.remoteSpn_))
{
WriteInfo(TraceType, "remoteSpn_: '{0}' != '{1}'", remoteSpn_, rhs.remoteSpn_);
return false;
}
}
else if (securityProvider_ == SecurityProvider::Claims)
{
if (localClaimToken_ != rhs.localClaimToken_) // not doing case-insensive comparison, because token string could be encrypted
{
WriteInfo(TraceType, "localClaimToken_: '{0}' != '{1}'", localClaimToken_, rhs.localClaimToken_);
return false;
}
}
return true;
}
bool SecuritySettings::operator != (SecuritySettings const & rhs) const
{
return !(*this == rhs);
}
_Use_decl_annotations_
ErrorCode SecuritySettings::FromPublicApi(
FABRIC_SECURITY_CREDENTIALS const& securityCredentials,
SecuritySettings & object)
{
object = SecuritySettings();
object.credTypeFromPublicApi_ = securityCredentials.Kind;
auto error = SecurityProvider::FromPublic(securityCredentials.Kind, object.securityProvider_);
if (!error.IsSuccess()) { return error; }
if (object.securityProvider_ == SecurityProvider::None)
{
return ErrorCodeValue::Success;
}
if (SecurityProvider::IsWindowsProvider(object.securityProvider_))
{
auto windowsCredentials = reinterpret_cast<FABRIC_WINDOWS_CREDENTIALS*>(securityCredentials.Value);
object.remoteSpn_ = windowsCredentials->RemoteSpn;
for (ULONG i = 0; i < windowsCredentials->RemoteIdentityCount; ++i)
{
object.remoteIdentities_.insert(windowsCredentials->RemoteIdentities[i]);
}
return ProtectionLevel::FromPublic(windowsCredentials->ProtectionLevel, object.protectionLevel_);
}
if (object.securityProvider_ == SecurityProvider::Claims)
{
auto claimCredentials = reinterpret_cast<FABRIC_CLAIMS_CREDENTIALS*>(securityCredentials.Value);
for (ULONG i = 0; i < claimCredentials->IssuerThumbprintCount; ++i)
{
LPCWSTR const& issuerThumbprint = claimCredentials->IssuerThumbprints[i];
error = object.defaultX509IssuerThumbprints_.AddThumbprint(issuerThumbprint);
if (!error.IsSuccess())
{
return error;
}
}
// Public API only support client side settings, thus we do not have to worry about RBAC
for (ULONG i = 0; i < claimCredentials->ServerCommonNameCount; i++)
{
if (claimCredentials->ServerCommonNames[i] == nullptr)
{
return ErrorCodeValue::InvalidAllowedCommonNameList;
}
object.remoteX509Names_.Add(claimCredentials->ServerCommonNames[i], object.defaultX509IssuerThumbprints_);
}
object.localClaimToken_ = claimCredentials->LocalClaims;
if (claimCredentials->Reserved != nullptr)
{
auto claimCredentialsEx1 = reinterpret_cast<FABRIC_CLAIMS_CREDENTIALS_EX1*>(claimCredentials->Reserved);
for (ULONG i = 0; i < claimCredentialsEx1->ServerThumbprintCount; i++)
{
if (claimCredentialsEx1->ServerThumbprints[i] == nullptr)
{
return ErrorCodeValue::InvalidAllowedCommonNameList;
}
error = object.remoteCertThumbprints_.Add(claimCredentialsEx1->ServerThumbprints[i]);
if (!error.IsSuccess())
{
WriteError(TraceType, "FromPublicApi: remoteCertThumbprints_.Add failed: {0}", error);
return error;
}
}
}
//
// Claims token is allowed to be empty. For AAD, it can be retrieved at runtime
// when SecurityContextSsl fires ClaimsHandlerFunc()
//
return ProtectionLevel::FromPublic(claimCredentials->ProtectionLevel, object.protectionLevel_);
}
ASSERT_IFNOT(
object.securityProvider_ == SecurityProvider::Ssl,
"Unexpected security provider type at FromPublicApi: {0}",
object.securityProvider_);
if (object.credTypeFromPublicApi_ == FABRIC_SECURITY_CREDENTIAL_KIND_X509_2)
{
#ifndef PLATFORM_UNIX
WriteError(TraceType, "FromPublicApi: FABRIC_SECURITY_CREDENTIAL_KIND_X509_2 not supported");
return ErrorCodeValue::InvalidCredentials;
#else
auto x509SCredentials = reinterpret_cast<FABRIC_X509_CREDENTIALS2*>(securityCredentials.Value);
if (x509SCredentials == NULL) { return ErrorCode(ErrorCodeValue::InvalidCredentials); }
error = ProtectionLevel::FromPublic(x509SCredentials->ProtectionLevel, object.protectionLevel_);
if (!error.IsSuccess()) { return error; }
object.x509StoreLocation_ = X509Default::StoreLocation();
object.x509StoreName_ = wstring(x509SCredentials->CertLoadPath);
// x509FindValue_ is left empty
for (ULONG i = 0; i < x509SCredentials->RemoteCertThumbprintCount; ++i)
{
LPCWSTR remoteCertThumbprint = x509SCredentials->RemoteCertThumbprints[i];
error = object.remoteCertThumbprints_.Add(remoteCertThumbprint);
if (!error.IsSuccess())
{
WriteError(TraceType, "FromPublicApi: remoteCertThumbprints_.Add failed: {0}", error);
return error;
}
}
error = object.remoteX509Names_.AddNames(x509SCredentials->RemoteX509Names, x509SCredentials->RemoteX509NameCount);
if (!error.IsSuccess())
{
WriteError(TraceType, "FromPublicApi: remoteX509Names_.AddNames failed: {0}", error);
return error;
}
if (x509SCredentials->Reserved == nullptr)
{
return error;
}
FABRIC_X509_CREDENTIALS_EX3 const * x509Ex3 = (FABRIC_X509_CREDENTIALS_EX3 const *)(x509SCredentials->Reserved);
object.remoteCertIssuers_.AddIssuerEntries(x509Ex3->RemoteCertIssuers, x509Ex3->RemoteCertIssuerCount);
if (!object.defaultX509IssuerThumbprints_.IsEmpty() && !object.remoteCertIssuers_.IsEmpty())
{
WriteError(TraceType, "FromPublicApi: Default issuer list '{0}' cannot be used together with RemoteCertIssuers '{1}'", object.defaultX509IssuerThumbprints_, object.remoteCertIssuers_);
return ErrorCodeValue::InvalidX509NameList;
}
if (!object.remoteX509Names_.GetAllIssuers().IsEmpty() && !object.remoteCertIssuers_.IsEmpty())
{
WriteError(TraceType, "FromPublicApi: X509Names '{0}' with issuer pinning cannot be used together with RemoteCertIssuers '{1}'", object.remoteX509Names_, object.remoteCertIssuers_);
return ErrorCodeValue::InvalidX509NameList;
}
error = UpdateRemoteIssuersIfNeeded(object);
if (!error.IsSuccess())
{
WriteError(TraceType, "FromPublicApi: UpdateRemoteIssuersIfNeeded failed: {0}", error);
return error;
}
return error;
#endif
}
auto x509SCredentials = reinterpret_cast<FABRIC_X509_CREDENTIALS*>(securityCredentials.Value);
if (x509SCredentials == NULL) { return ErrorCode(ErrorCodeValue::InvalidCredentials); }
error = ProtectionLevel::FromPublic(x509SCredentials->ProtectionLevel, object.protectionLevel_);
if (!error.IsSuccess()) { return error; }
error = X509StoreLocation::FromPublic(x509SCredentials->StoreLocation, object.x509StoreLocation_);
if (!error.IsSuccess()) { return error; }
object.x509StoreName_ = wstring(x509SCredentials->StoreName);
#ifndef PLATFORM_UNIX
if (object.x509StoreName_.empty()) { return ErrorCode(ErrorCodeValue::InvalidX509StoreName); }
#endif
for (ULONG i = 0; i < x509SCredentials->AllowedCommonNameCount; i++)
{
if (x509SCredentials->AllowedCommonNames[i] == nullptr)
{
return ErrorCodeValue::InvalidAllowedCommonNameList;
}
object.remoteX509Names_.Add(x509SCredentials->AllowedCommonNames[i]);
}
if (x509SCredentials->Reserved == nullptr)
{
error = X509FindValue::Create(x509SCredentials->FindType, (LPCWSTR)x509SCredentials->FindValue, nullptr, object.x509FindValue_);
if (!error.IsSuccess()) WriteError(TraceType, "FromPublicApi: X509FindValue::Create(primary) failed: {0}", error);
return error;
}
FABRIC_X509_CREDENTIALS_EX1 const * x509Ex1 = (FABRIC_X509_CREDENTIALS_EX1 const *)(x509SCredentials->Reserved);
for (ULONG i = 0; i < x509Ex1->IssuerThumbprintCount; ++i)
{
LPCWSTR issuerThumbprint = x509Ex1->IssuerThumbprints[i];
error = object.defaultX509IssuerThumbprints_.AddThumbprint(issuerThumbprint);
if (!error.IsSuccess())
{
WriteError(TraceType, "FromPublicApi: defaultX509IssuerThumbprints_.Add failed: {0}", error);
return error;
}
}
if (!object.defaultX509IssuerThumbprints_.IsEmpty())
{
error = object.remoteX509Names_.SetDefaultIssuers(object.defaultX509IssuerThumbprints_);
if (!error.IsSuccess())
{
WriteError(TraceType, "FromPublicApi: remoteX509Names_.SetDefaultIssuers failed: {0}", error);
return error;
}
}
if (x509Ex1->Reserved == nullptr)
{
error = X509FindValue::Create(x509SCredentials->FindType, (LPCWSTR)x509SCredentials->FindValue, nullptr, object.x509FindValue_);
if (!error.IsSuccess()) WriteError(TraceType, "FromPublicApi: X509FindValue::Create(primary) failed: {0}", error);
return error;
}
FABRIC_X509_CREDENTIALS_EX2 const * x509Ex2 = (FABRIC_X509_CREDENTIALS_EX2 const *)(x509Ex1->Reserved);
for (ULONG i = 0; i < x509Ex2->RemoteCertThumbprintCount; ++i)
{
LPCWSTR remoteCertThumbprint = x509Ex2->RemoteCertThumbprints[i];
error = object.remoteCertThumbprints_.Add(remoteCertThumbprint);
if (!error.IsSuccess())
{
WriteError(TraceType, "FromPublicApi: remoteCertThumbprints_.Add failed: {0}", error);
return error;
}
}
if (!object.defaultX509IssuerThumbprints_.IsEmpty() && (x509Ex2->RemoteX509NameCount > 0))
{
WriteError(TraceType, "FromPublicApi: Default issuer list '{0}' cannot be used together with X509Names '{1}'", object.defaultX509IssuerThumbprints_, x509Ex2->RemoteX509NameCount);
return ErrorCodeValue::InvalidX509NameList;
}
error = object.remoteX509Names_.AddNames(x509Ex2->RemoteX509Names, x509Ex2->RemoteX509NameCount);
if (!error.IsSuccess())
{
WriteError(TraceType, "FromPublicApi: remoteX509Names_.AddNames failed: {0}", error);
return error;
}
error = X509FindValue::Create(x509SCredentials->FindType, x509SCredentials->FindValue, x509Ex2->FindValueSecondary, object.x509FindValue_);
if (!error.IsSuccess())
{
WriteError(TraceType, "FromPublicApi: X509FindValue::Create(primary, secondary) failed: {0}", error);
return error;
}
if (x509Ex2->Reserved == nullptr)
{
return error;
}
FABRIC_X509_CREDENTIALS_EX3 const * x509Ex3 = (FABRIC_X509_CREDENTIALS_EX3 const *)(x509Ex2->Reserved);
object.remoteCertIssuers_.AddIssuerEntries(x509Ex3->RemoteCertIssuers, x509Ex3->RemoteCertIssuerCount);
if (!object.defaultX509IssuerThumbprints_.IsEmpty() && !object.remoteCertIssuers_.IsEmpty())
{
WriteError(TraceType, "FromPublicApi: Default issuer list '{0}' cannot be used together with RemoteCertIssuers '{1}'", object.defaultX509IssuerThumbprints_, object.remoteCertIssuers_);
return ErrorCodeValue::InvalidX509NameList;
}
if (!object.remoteX509Names_.GetAllIssuers().IsEmpty() && !object.remoteCertIssuers_.IsEmpty())
{
WriteError(TraceType, "FromPublicApi: X509Names '{0}' with issuer pinning cannot be used together with RemoteCertIssuers '{1}'", object.remoteX509Names_, object.remoteCertIssuers_);
return ErrorCodeValue::InvalidX509NameList;
}
error = UpdateRemoteIssuersIfNeeded(object);
if (!error.IsSuccess())
{
WriteError(TraceType, "FromPublicApi: UpdateRemoteIssuersIfNeeded failed: {0}", error);
return error;
}
return error;
}
_Use_decl_annotations_
void SecuritySettings::ToPublicApi(Common::ScopedHeap & heap, FABRIC_SECURITY_CREDENTIALS & securityCredentials) const
{
if (securityProvider_ == SecurityProvider::Ssl)
{
securityCredentials.Kind = SecurityProvider::ToPublic(securityProvider_, credTypeFromPublicApi_);
if (securityCredentials.Kind == FABRIC_SECURITY_CREDENTIAL_KIND_X509_2)
{
auto x509SCredentials = heap.AddItem<FABRIC_X509_CREDENTIALS2>();
securityCredentials.Value = x509SCredentials.GetRawPointer();
x509SCredentials->ProtectionLevel = ProtectionLevel::ToPublic(protectionLevel_);
x509SCredentials->CertLoadPath = heap.AddString(x509StoreName_);
x509SCredentials->RemoteCertThumbprintCount = (ULONG)remoteCertThumbprints_.Value().size();
auto remoteCertThumbprints = heap.AddArray<LPCWSTR>(remoteCertThumbprints_.Value().size());
ULONG index = 0;
for (auto const & thumbprint : remoteCertThumbprints_.Value())
{
remoteCertThumbprints[index++] = heap.AddString(thumbprint.PrimaryToString());
}
x509SCredentials->RemoteCertThumbprints = remoteCertThumbprints.GetRawArray();
auto nameList = remoteX509Names_.ToVector();
x509SCredentials->RemoteX509NameCount = (ULONG)nameList.size();
auto remoteX509NameArray = heap.AddArray<FABRIC_X509_NAME>(nameList.size());
for (ULONG i = 0; i < x509SCredentials->RemoteX509NameCount; ++i)
{
remoteX509NameArray[i].Name = heap.AddString(nameList[i].first, true);
remoteX509NameArray[i].IssuerCertThumbprint = heap.AddString(nameList[i].second, true);
}
x509SCredentials->RemoteX509Names = remoteX509NameArray.GetRawArray();
ReferencePointer<FABRIC_X509_CREDENTIALS_EX3> x509Ex3RPtr = heap.AddItem<FABRIC_X509_CREDENTIALS_EX3>(); //allocate and zero memory
x509SCredentials->Reserved = x509Ex3RPtr.GetRawPointer();
remoteCertIssuers_.ToPublicApi(heap, *x509Ex3RPtr);
return;
}
auto x509SCredentials = heap.AddItem<FABRIC_X509_CREDENTIALS>();
securityCredentials.Value = x509SCredentials.GetRawPointer();
x509SCredentials->FindType = X509FindType::ToPublic(x509FindValue_->Type());
x509SCredentials->FindValue = x509FindValue_->PrimaryValueToPublicPtr(heap);
x509SCredentials->ProtectionLevel = ProtectionLevel::ToPublic(protectionLevel_);
x509SCredentials->StoreLocation = X509StoreLocation::ToPublic(x509StoreLocation_);
x509SCredentials->StoreName = heap.AddString(x509StoreName_);
// defaultX509IssuerThumbprints_ is skipped as it is covered by remoteX509Names_
if (remoteCertThumbprints_.Value().empty() &&
!x509FindValue_->Secondary() &&
remoteX509Names_.IsEmpty())
return;
ReferencePointer<FABRIC_X509_CREDENTIALS_EX1> x509Ex1RPtr = heap.AddItem<FABRIC_X509_CREDENTIALS_EX1>(); //allocate and zero memory
x509SCredentials->Reserved = x509Ex1RPtr.GetRawPointer();
FABRIC_X509_CREDENTIALS_EX1 & x509Ex1 = *x509Ex1RPtr;
ReferencePointer<FABRIC_X509_CREDENTIALS_EX2> x509Ex2RPtr = heap.AddItem<FABRIC_X509_CREDENTIALS_EX2>(); //allocate and zero memory
x509Ex1.Reserved = x509Ex2RPtr.GetRawPointer();
FABRIC_X509_CREDENTIALS_EX2 & x509Ex2 = *x509Ex2RPtr;
ReferencePointer<FABRIC_X509_CREDENTIALS_EX3> x509Ex3RPtr = heap.AddItem<FABRIC_X509_CREDENTIALS_EX3>(); //allocate and zero memory
x509Ex2.Reserved = x509Ex3RPtr.GetRawPointer();
x509Ex2.RemoteCertThumbprintCount = (ULONG)remoteCertThumbprints_.Value().size();
auto remoteCertThumbprints = heap.AddArray<LPCWSTR>(remoteCertThumbprints_.Value().size());
ULONG index = 0;
for (auto const & thumbprint : remoteCertThumbprints_.Value())
{
remoteCertThumbprints[index++] = heap.AddString(thumbprint.PrimaryToString());
}
x509Ex2.RemoteCertThumbprints = remoteCertThumbprints.GetRawArray();
if (x509FindValue_->Secondary())
{
x509Ex2.FindValueSecondary = x509FindValue_->Secondary()->PrimaryValueToPublicPtr(heap);
}
auto nameList = remoteX509Names_.ToVector();
x509Ex2.RemoteX509NameCount = (ULONG)nameList.size();
auto remoteX509NameArray = heap.AddArray<FABRIC_X509_NAME>(nameList.size());
for (ULONG i = 0; i < x509Ex2.RemoteX509NameCount; ++i)
{
remoteX509NameArray[i].Name = heap.AddString(nameList[i].first, true);
remoteX509NameArray[i].IssuerCertThumbprint = heap.AddString(nameList[i].second, true);
}
x509Ex2.RemoteX509Names = remoteX509NameArray.GetRawArray();
remoteCertIssuers_.ToPublicApi(heap, *x509Ex3RPtr);
return;
}
if (SecurityProvider::IsWindowsProvider(securityProvider_))
{
securityCredentials.Kind = FABRIC_SECURITY_CREDENTIAL_KIND_WINDOWS;
auto windowsCredentials = heap.AddItem<FABRIC_WINDOWS_CREDENTIALS>();
windowsCredentials->Reserved = nullptr;
securityCredentials.Value = windowsCredentials.GetRawPointer();
windowsCredentials->RemoteSpn = heap.AddString(remoteSpn_);
windowsCredentials->RemoteIdentityCount = (ULONG)(remoteIdentities_.size());
auto remoteIdentities = heap.AddArray<LPCWSTR>(remoteIdentities_.size());
ULONG i = 0;
for (auto iter = remoteIdentities_.cbegin(); iter != remoteIdentities_.cend(); ++iter, ++i)
{
remoteIdentities[i] = heap.AddString(*iter);
}
windowsCredentials->RemoteIdentities = remoteIdentities.GetRawArray();
windowsCredentials->ProtectionLevel = ProtectionLevel::ToPublic(protectionLevel_);
return;
}
ASSERT_IFNOT(securityProvider_ == SecurityProvider::None, "Unexpected security CredentialType at ToPublicApi: {0}", securityProvider_);
// Set credentials to null
securityCredentials.Kind = FABRIC_SECURITY_CREDENTIAL_KIND_NONE;
securityCredentials.Value = NULL;
}
void SecuritySettings::WriteTo(TextWriter & w, FormatOptions const &) const
{
if (securityProvider_ == SecurityProvider::None)
{
w.WriteChar('{');
w.Write("{0}", securityProvider_);
w.WriteChar('}');
return;
}
w.WriteChar('{');
w.Write(" provider={0} protection={1} ", securityProvider_, protectionLevel_);
if (SecurityProvider::IsWindowsProvider(securityProvider_))
{
w.Write("remoteSpn='{0}' ", remoteSpn_);
if (!remoteIdentities_.empty())
{
w.Write("remote='{0}' ", remoteIdentities_);
}
}
if (securityProvider_ == SecurityProvider::Ssl)
{
w.Write("certType = '{0}' store='{1}/{2}' findValue='{3}' ", x509CertType_, x509StoreLocation_, x509StoreName_, x509FindValue_);
if (!remoteCertThumbprints_.Value().empty())
{
w.Write("remoteCertThumbprints='{0}' ", remoteCertThumbprints_);
}
if (!remoteX509Names_.IsEmpty())
{
w.Write("remoteX509Names={0} ", remoteX509Names_);
}
if (!remoteCertIssuers_.IsEmpty())
{
w.Write("RemoteCertIssuers={0} ", remoteCertIssuers_);
}
if (!defaultX509IssuerThumbprints_.IsEmpty())
{
w.Write("certIssuers='{0}' ", defaultX509IssuerThumbprints_);
}
w.Write("certChainFlags={0:x} ", X509CertChainFlags());
}
w.Write("isClientRoleInEffect={0} ", isClientRoleInEffect_);
if (isClientRoleInEffect_)
{
if (!adminClientIdentities_.empty())
{
w.Write("adminClientIdentities='{0}' ", adminClientIdentities_);
}
if (!adminClientX509Names_.IsEmpty())
{
w.Write("adminClientX509Names='{0}' ", adminClientX509Names_);
}
if (!adminClientCertThumbprints_.Value().empty())
{
w.Write("adminClientCertThumbprints='{0}' ", adminClientCertThumbprints_);
}
}
if (securityProvider_ == SecurityProvider::Claims)
{
w.Write("localClaimToken='{0}' ", localClaimToken_);
}
w.Write("claimBasedClientAuthEnabled={0} ", claimBasedClientAuthEnabled_);
if (claimBasedClientAuthEnabled_)
{
w.Write("clientClaims='{0}' adminClientClaims='{1}' ", clientClaims_, adminClientClaims_);
}
w.WriteChar('}');
}
void SecuritySettings::Test_SetRawValues(SecurityProvider::Enum provider, ProtectionLevel::Enum protectionLevel)
{
this->securityProvider_ = provider;
this->protectionLevel_ = protectionLevel;
}
wstring SecuritySettings::ToString() const
{
wstring result;
StringWriter(result).Write(*this);
return result;
}
bool SecuritySettings::IsClientRoleInEffect() const
{
return isClientRoleInEffect_ || claimBasedClientAuthEnabled_;
}
RoleMask::Enum SecuritySettings::DefaultRemoteRole(bool inbound) const
{
if (!inbound || IsRemotePeer()) return RoleMask::All;
if (IsClientRoleInEffect()) return RoleMask::User;
return defaultRemoteRole_;
}
SecuritySettings::IdentitySet const & SecuritySettings::AdminClientIdentities() const
{
return adminClientIdentities_;
}
void SecuritySettings::EnableAdminRole(wstring const & adminClientIdList)
{
isClientRoleInEffect_ = true;
vector<wstring> adminClientIdentities;
StringUtility::Split<wstring>(adminClientIdList, adminClientIdentities, L",", true);
adminClientIdentities_.insert(adminClientIdentities.cbegin(), adminClientIdentities.cend());
remoteIdentities_.insert(adminClientIdentities.cbegin(), adminClientIdentities.cend());
}
ErrorCode SecuritySettings::EnableAdminRole(
wstring const & adminClientCertThumbprints,
SecurityConfig::X509NameMap const & adminClientX509Names,
wstring const & adminClientList)
{
isClientRoleInEffect_ = true;
auto error = adminClientCertThumbprints_.Set(adminClientCertThumbprints);
if (!error.IsSuccess()) return error;
remoteCertThumbprints_.Add(adminClientCertThumbprints_);
if (!defaultX509IssuerThumbprints_.IsEmpty() && !adminClientX509Names.IsEmpty())
{
WriteError(TraceType, "EnableAdminRole: default issuer list '{0}' cannot be used together with X509Names '{1}'", defaultX509IssuerThumbprints_, adminClientX509Names);
return ErrorCodeValue::InvalidX509NameList;
}
adminClientX509Names_ = adminClientX509Names;
vector<wstring> adminClientCNs;
StringUtility::Split<wstring>(adminClientList, adminClientCNs, L",", true);
for (auto const & name : adminClientCNs)
{
adminClientX509Names_.Add(name, defaultX509IssuerThumbprints_);
}
// If issuer store is specified, overwrite all issuer whitelist values in adminClientX509Names_ with public keys obtained from the store
if (!remoteCertIssuers_.IsEmpty())
{
X509IdentitySet clientIssuerPublicKeys;
error = remoteCertIssuers_.GetPublicKeys(clientIssuerPublicKeys);
if (!error.IsSuccess()) { return error; }
adminClientX509Names_.OverwriteIssuers(clientIssuerPublicKeys);
}
remoteX509Names_.Add(adminClientX509Names_);
return error;
}
void SecuritySettings::AddClientToAdminRole(std::wstring const & clientIdentity)
{
isClientRoleInEffect_ = true;
if (SecurityProvider::IsWindowsProvider(securityProvider_))
{
adminClientIdentities_.insert(clientIdentity);
remoteIdentities_.insert(clientIdentity);
return;
}
// SecurityProvider::Claims is not supported on server side
KInvariant(securityProvider_ == SecurityProvider::Ssl);
adminClientX509Names_.Add(clientIdentity, defaultX509IssuerThumbprints_);
remoteX509Names_.Add(clientIdentity, defaultX509IssuerThumbprints_);
}
void SecuritySettings::AddAdminClientX509Names(SecurityConfig::X509NameMap const & names)
{
adminClientX509Names_.Add(names);
remoteX509Names_.Add(names);
WriteInfo(
TraceType,
"AddAdminClientX509Names: after: adminClientX509Names_: {0}; remoteX509Names_: {1}",
adminClientX509Names_, remoteX509Names_);
}
void SecuritySettings::AddAdminClientIdentities(IdentitySet const & identities)
{
adminClientIdentities_.insert(identities.cbegin(), identities.cend());
remoteIdentities_.insert(identities.cbegin(), identities.cend());
WriteInfo(
TraceType,
"AddAdminClientIdentities: after: adminClientIdentities_: {0}; remoteIdentities_: {1}",
adminClientIdentities_, remoteIdentities_);
}
SecuritySettings::IdentitySet const & SecuritySettings::RemoteIdentities() const
{
return remoteIdentities_;
}
void SecuritySettings::AddRemoteIdentity(std::wstring const & value)
{
remoteIdentities_.insert(value);
}
X509FindType::Enum SecuritySettings::X509FindType() const
{
return x509FindValue_->Type();
}
SecurityProvider::Enum SecuritySettings::SecurityProvider() const
{
return securityProvider_;
}
X509StoreLocation::Enum SecuritySettings::X509StoreLocation() const
{
return x509StoreLocation_;
}
wstring const& SecuritySettings::X509StoreName() const
{
return x509StoreName_;
}
X509FindValue::SPtr const& SecuritySettings::X509FindValue() const
{
return x509FindValue_;
}
ProtectionLevel::Enum SecuritySettings::ProtectionLevel() const
{
return protectionLevel_;
}
wstring const& SecuritySettings::RemoteSpn() const
{
return remoteSpn_;
}
void SecuritySettings::SetRemoteSpn(std::wstring const & remoteSpn)
{
remoteSpn_ = remoteSpn;
}
wstring const & SecuritySettings::LocalClaimToken() const
{
return localClaimToken_;
}
ErrorCode SecuritySettings::StringToRoleClaims(std::wstring const & inputString, RoleClaims & roleClaims)
{
// split "Claim && Claim && Claim ..."
vector<wstring> claimVector;
StringUtility::Split<wstring>(inputString, claimVector, L"&&", true);
if (claimVector.empty())
{
return ErrorCodeValue::InvalidArgument;
}
for (wstring const & claim : claimVector)
{
if (!roleClaims.AddClaim(claim))
{
return ErrorCodeValue::InvalidArgument;
}
}
return ErrorCode::Success();
}
bool SecuritySettings::ClaimListToRoleClaim(vector<ServiceModel::Claim> const& claimList, _Out_ RoleClaims &roleClaims)
{
for (ServiceModel::Claim const& claim : claimList)
{
if (!roleClaims.AddClaim(claim.ClaimType, claim.Value))
{
return false;
}
}
return true;
}
ErrorCode SecuritySettings::StringToRoleClaimsOrList(std::wstring const & inputString, RoleClaimsOrList & roleClaimsOrList)
{
wstring inputCopy = inputString;
StringUtility::TrimWhitespaces(inputCopy);
if (inputCopy.empty())
{
return ErrorCode();
}
// split "RoleClaims || RoleClaims || RoleClaims ..."
vector<wstring> roleClaimsVector;
StringUtility::Split<wstring>(inputCopy, roleClaimsVector, L"||", true);
if (roleClaimsVector.empty())
{
return ErrorCodeValue::InvalidArgument;
}
for (wstring const & roleClaimsEntry : roleClaimsVector)
{
RoleClaims newRoleClaimsEntry;
auto error = StringToRoleClaims(roleClaimsEntry, newRoleClaimsEntry);
if (!error.IsSuccess())
{
return error;
}
roleClaimsOrList.AddRoleClaims(newRoleClaimsEntry);
}
return ErrorCode();
}
ErrorCode SecuritySettings::EnableClaimBasedAuthOnClients(wstring const & clientClaimList, wstring const & adminClientClaimList)
{
if (securityProvider_ != SecurityProvider::Ssl)
{
WriteError(TraceType, "SSL is required for claim-based client authorization: {0}", securityProvider_);
// Claim based auth on clients requires SSL on server side
return ErrorCodeValue::InvalidArgument;
}
auto error = StringToRoleClaimsOrList(clientClaimList, clientClaims_);
if (!error.IsSuccess())
{
return error;
}
error = StringToRoleClaimsOrList(adminClientClaimList, adminClientClaims_);
if (!error.IsSuccess())
{
return error;
}
// Add admin client claims to client claims, so that callers do not have to add the same claim to both list
error = StringToRoleClaimsOrList(adminClientClaimList, clientClaims_);
if (!error.IsSuccess())
{
return error;
}
claimBasedClientAuthEnabled_ = true;
isClientRoleInEffect_ = true;
return error;
}
bool SecuritySettings::ClaimBasedClientAuthEnabled() const
{
return claimBasedClientAuthEnabled_;
}
bool SecuritySettings::IdentitySet::operator == (IdentitySet const & rhs) const
{
if (this->size() != rhs.size())
{
return false;
}
for (IdentitySet::const_iterator iter1 = cbegin(), iter2 = rhs.cbegin(); iter1 != cend(); ++iter1, ++iter2)
{
if (!StringUtility::AreEqualCaseInsensitive(*iter1, *iter2))
{
return false;
}
}
return true;
}
bool SecuritySettings::IdentitySet::operator != (IdentitySet const & rhs) const
{
return !(*this == rhs);
}
void SecuritySettings::IdentitySet::WriteTo(Common::TextWriter & w, Common::FormatOptions const &) const
{
bool outputGenerated = false;
for (auto const & identity : *this)
{
if (outputGenerated)
{
w.Write(", {0}", identity);
}
else
{
w.Write("{0}", identity);
outputGenerated = true;
}
}
}
wstring SecuritySettings::IdentitySet::ToString() const
{
wstring result;
StringWriter(result).Write(*this);
return result;
}
SecuritySettings::RoleClaimsOrList const & SecuritySettings::ClientClaims() const
{
return clientClaims_;
}
SecuritySettings::RoleClaimsOrList const & SecuritySettings::AdminClientClaims() const
{
return adminClientClaims_;
}
bool SecuritySettings::RoleClaims::AddClaim(wstring const & claim)
{
// split "ClaimType=ClaimValue"
vector<wstring> claimParts;
StringUtility::Split<wstring>(claim, claimParts, L"=", true);
if (claimParts.size() != 2)
{
return false;
}
return AddClaim(claimParts.front(), claimParts.back());
}
bool SecuritySettings::RoleClaims::AddClaim(wstring const & claimType, wstring const & claimValue)
{
wstring type = claimType;
StringUtility::TrimWhitespaces(type);
wstring value = claimValue;
StringUtility::TrimWhitespaces(value);
if (type.empty() || value.empty())
{
return false;
}
auto iter = value_.find(type);
if ((iter == value_.cend()) || !StringUtility::AreEqualCaseInsensitive(iter->second, value))
{
value_.emplace(pair<wstring, wstring>(move(type), move(value)));
}
return true;
}
bool SecuritySettings::RoleClaims::operator < (RoleClaims const & rhs) const
{
return value_ < rhs.value_;
}
bool SecuritySettings::RoleClaims::operator == (RoleClaims const & rhs) const
{
return (value_.size() == rhs.value_.size()) && this->Contains(rhs) && rhs.Contains(*this);
}
bool SecuritySettings::RoleClaims::operator != (RoleClaims const & rhs) const
{
return !(*this == rhs);
}
bool SecuritySettings::RoleClaims::Contains(std::wstring const & claimType, std::wstring const & claimValue) const
{
for (auto iter = value_.lower_bound(claimType); iter != value_.upper_bound(claimType); ++iter)
{
if (StringUtility::AreEqualCaseInsensitive(claimType, iter->first) &&
StringUtility::AreEqualCaseInsensitive(claimValue, iter->second))
{
return true;
}
}
return false;
}
bool SecuritySettings::RoleClaims::Contains(RoleClaims const & other) const
{
for (auto const & claim : other.value_)
{
if (!Contains(claim.first, claim.second))
{
return false;
}
}
return true;
}
bool SecuritySettings::RoleClaims::IsInRole(RoleClaimsOrList const & roleClaimsOrList) const
{
for (auto const & requirement : roleClaimsOrList.Value())
{
if (this->Contains(requirement))
{
return true;
}
}
return false;
}
multimap<wstring, wstring, IsLessCaseInsensitiveComparer<wstring>> const & SecuritySettings::RoleClaims::Value() const
{
return value_;
}
void SecuritySettings::RoleClaims::WriteTo(Common::TextWriter & w, Common::FormatOptions const &) const
{
bool outputGenerated = false;
for (auto const & claim : value_)
{
if (outputGenerated)
{
w.Write(L" && ");
}
w.Write("{0}={1}", claim.first, claim.second);
outputGenerated = true;
}
}
wstring SecuritySettings::RoleClaims::ToString() const
{
wstring result;
StringWriter(result).Write(*this);
return result;
}
void SecuritySettings::RoleClaimsOrList::AddRoleClaims(RoleClaims const & roleClaims)
{
bool shouldAdd = true;
for (auto existing = value_.cbegin(); existing != value_.cend();)
{
if (existing->Contains(roleClaims))
{
// the existing RoleClaims entry is more restrictive, thus should be replaced
auto toDelete = existing++;
value_.erase(toDelete);
continue;
}
if (roleClaims.Contains(*existing))
{
// new entry is more restrictive, already covered by the existing entry
shouldAdd = false;
}
++existing;
}
if (shouldAdd)
{
value_.insert(roleClaims);
}
}
bool SecuritySettings::RoleClaimsOrList::operator == (RoleClaimsOrList const & rhs) const
{
return (value_.size() == rhs.value_.size()) && this->Contains(rhs) && rhs.Contains(*this);
}
bool SecuritySettings::RoleClaimsOrList::operator != (RoleClaimsOrList const & rhs) const
{
return !(*this == rhs);
}
bool SecuritySettings::RoleClaimsOrList::Contains(RoleClaims const & roleClaimsEntry) const
{
for (auto const & entry : value_)
{
if (entry == roleClaimsEntry)
{
return true;
}
}
return false;
}
bool SecuritySettings::RoleClaimsOrList::Contains(RoleClaimsOrList const & other) const
{
for (auto const & otherEntry : other.value_)
{
if (!Contains(otherEntry))
{
return false;
}
}
return true;
}
set<SecuritySettings::RoleClaims> const & SecuritySettings::RoleClaimsOrList::Value() const
{
return value_;
}
void SecuritySettings::RoleClaimsOrList::WriteTo(TextWriter & w, FormatOptions const &) const
{
bool outputGenerated = false;
for (auto const & roleClaims : value_)
{
if (outputGenerated)
{
w.Write(" || {0}", roleClaims);
}
else
{
w.Write("{0}", roleClaims);
outputGenerated = true;
}
}
}
wstring SecuritySettings::RoleClaimsOrList::ToString() const
{
wstring result;
StringWriter(result).Write(*this);
return result;
}
ThumbprintSet const & SecuritySettings::RemoteCertThumbprints() const
{
return remoteCertThumbprints_;
}
ErrorCode SecuritySettings::SetRemoteCertThumbprints(std::wstring const & thumbprints)
{
if ((securityProvider_ != SecurityProvider::Ssl) && (securityProvider_ != SecurityProvider::Claims))
{
WriteError("SetRemoteCertThumbprints", "thumbprint is not supported for {0}", securityProvider_);
return ErrorCodeValue::InvalidOperation;
}
return remoteCertThumbprints_.Set(thumbprints);
}
ThumbprintSet const & SecuritySettings::AdminClientCertThumbprints() const
{
return adminClientCertThumbprints_;
}
SecurityConfig::X509NameMap const & SecuritySettings::RemoteX509Names() const
{
return remoteX509Names_;
}
SecurityConfig::IssuerStoreKeyValueMap const & SecuritySettings::RemoteCertIssuers() const
{
return remoteCertIssuers_;
}
ErrorCode SecuritySettings::SetRemoteCertIssuerPublicKeys(Common::X509IdentitySet issuerPublicKeys)
{
remoteX509Names_.OverwriteIssuers(issuerPublicKeys);
return ErrorCodeValue::Success;
}
ErrorCode SecuritySettings::SetAdminClientCertIssuerPublicKeys(Common::X509IdentitySet issuerPublicKeys)
{
adminClientX509Names_.OverwriteIssuers(issuerPublicKeys);
return ErrorCodeValue::Success;
}
SecurityConfig::X509NameMap const & SecuritySettings::AdminClientX509Names() const
{
return adminClientX509Names_;
}
DWORD SecuritySettings::X509CertChainFlags() const
{
return x509CertChainFlagCallback_ ? x509CertChainFlagCallback_() : SecurityConfig::GetConfig().CrlCheckingFlag;
}
void SecuritySettings::SetX509CertChainFlagCallback(X509CertChainFlagCallback const& callback)
{
// if X509 cert chain flag can be passed from public API, we can simply add a callback to return the flag passed in
Invariant(!x509CertChainFlagCallback_);
x509CertChainFlagCallback_ = callback;
}
bool SecuritySettings::FramingProtectionEnabled() const
{
#ifdef PLATFORM_UNIX
return true;
#else
return
framingProtectionEnabledCallback_ ?
framingProtectionEnabledCallback_() :
(isRemotePeer_ ?
SecurityConfig::GetConfig().FramingProtectionEnabledInPeerToPeerMode :
SecurityConfig::GetConfig().FramingProtectionEnabled);
#endif
}
void SecuritySettings::SetFramingProtectionEnabledCallback(BooleanFlagCallback const & callback)
{
#ifdef PLATFORM_UNIX
Assert::CodingError("not allowed");
#else
framingProtectionEnabledCallback_ = callback;
#endif
}
bool SecuritySettings::ReadyNewSessionBeforeExpiration() const
{
return
readyNewSessionBeforeExpirationCallback_ ?
readyNewSessionBeforeExpirationCallback_() : SecurityConfig::GetConfig().ReadyNewSessionBeforeExpiration;
}
void SecuritySettings::SetReadyNewSessionBeforeExpirationCallback(BooleanFlagCallback const & callback)
{
readyNewSessionBeforeExpirationCallback_ = callback;
}
bool SecuritySettings::ShouldIgnoreCrlOfflineError(bool inbound) const
{
if (crlOfflineIgnoreCallback_) return crlOfflineIgnoreCallback_(inbound);
return inbound ? SecurityConfig::GetConfig().IgnoreCrlOfflineError : SecurityConfig::GetConfig().IgnoreSvrCrlOfflineError;
}
void SecuritySettings::SetCrlOfflineIgnoreCallback(CrlOfflineIgnoreCallback const & callback)
{
Invariant(callback);
crlOfflineIgnoreCallback_ = callback;
}
TimeSpan SecuritySettings::SessionDuration() const
{
return sessionDurationCallback_? sessionDurationCallback_() : SecurityConfig::GetConfig().SessionExpiration;
}
ErrorCode SecuritySettings::UpdateRemoteIssuersIfNeeded(SecuritySettings &object)
{
ErrorCode error(ErrorCodeValue::Success);
if (!object.remoteCertIssuers_.IsEmpty())
{
X509IdentitySet remoteCertIssuerPublicKeys;
error = object.RemoteCertIssuers().GetPublicKeys(remoteCertIssuerPublicKeys);
if (!error.IsSuccess())
{
WriteError(TraceType, "UpdateRemoteIssuersIfNeeded: remoteCertIssuers_.GetPublicKeys failed: {0}", error);
return error;
}
object.SetRemoteCertIssuerPublicKeys(remoteCertIssuerPublicKeys);
}
return error;
}
#ifndef PLATFORM_UNIX
ErrorCode SecuritySettings::AddRemoteX509Name(PCCERT_CONTEXT certContext)
{
wstring commonName;
auto err = CryptoUtility::GetCertificateCommonName(certContext, commonName);
if (!err.IsSuccess()) return err;
X509PubKey::SPtr issuerPubKey;
err = CryptoUtility::GetCertificateIssuerPubKey(certContext, issuerPubKey);
if (!err.IsSuccess()) return err;
remoteX509Names_.Add(commonName, issuerPubKey);
return err;
}
ErrorCode SecuritySettings::AddAdminClientX509Name(PCCERT_CONTEXT certContext)
{
wstring commonName;
auto err = CryptoUtility::GetCertificateCommonName(certContext, commonName);
if (!err.IsSuccess()) return err;
X509PubKey::SPtr issuerPubKey;
err = CryptoUtility::GetCertificateIssuerPubKey(certContext, issuerPubKey);
if (!err.IsSuccess()) return err;
adminClientX509Names_.Add(commonName, issuerPubKey);
if (!remoteCertIssuers_.IsEmpty())
{
X509IdentitySet clientIssuerPublicKeys;
err = remoteCertIssuers_.GetPublicKeys(clientIssuerPublicKeys);
if (!err.IsSuccess()) { return err; }
adminClientX509Names_.Add(commonName, clientIssuerPublicKeys);
}
remoteX509Names_.Add(adminClientX509Names_);
return err;
}
#endif
| 33.556553 | 196 | 0.694416 | [
"object",
"vector"
] |
783558f587ddc138ad85f2724232907e5fdbd730 | 5,658 | cxx | C++ | panda/src/downloader/multiplexStreamBuf.cxx | sean5470/panda3d | ea2d4fecd4af1d4064c5fe2ae2a902ef4c9b903d | [
"PHP-3.0",
"PHP-3.01"
] | null | null | null | panda/src/downloader/multiplexStreamBuf.cxx | sean5470/panda3d | ea2d4fecd4af1d4064c5fe2ae2a902ef4c9b903d | [
"PHP-3.0",
"PHP-3.01"
] | null | null | null | panda/src/downloader/multiplexStreamBuf.cxx | sean5470/panda3d | ea2d4fecd4af1d4064c5fe2ae2a902ef4c9b903d | [
"PHP-3.0",
"PHP-3.01"
] | null | null | null | /**
* PANDA 3D SOFTWARE
* Copyright (c) Carnegie Mellon University. All rights reserved.
*
* All use of this software is subject to the terms of the revised BSD
* license. You should have received a copy of this license along
* with this source code in a file named "LICENSE."
*
* @file multiplexStreamBuf.cxx
* @author drose
* @date 2000-11-27
*/
#include "multiplexStreamBuf.h"
#if defined(WIN32_VC) || defined(WIN64_VC)
#define WINDOWS_LEAN_AND_MEAN
#include <windows.h>
#undef WINDOWS_LEAN_AND_MEAN
#endif
// We use real assert() instead of nassert(), because we're likely to be
// invoked directly by pnotify.here, and we don't want to risk infinite
// recursion.
#include <assert.h>
#ifndef HAVE_STREAMSIZE
// Some compilers--notably SGI--don't define this for us.
typedef int streamsize;
#endif
/**
* Closes or deletes the relevant pointers, if _owns_obj is true.
*/
void MultiplexStreamBuf::Output::
close() {
if (_owns_obj) {
switch (_output_type) {
case OT_ostream:
assert(_out != (ostream *)NULL);
delete _out;
break;
case OT_stdio:
assert(_fout != (FILE *)NULL);
fclose(_fout);
break;
default:
break;
}
}
}
/**
* Dumps the indicated string to the appropriate place.
*/
void MultiplexStreamBuf::Output::
write_string(const string &str) {
switch (_output_type) {
case OT_ostream:
assert(_out != (ostream *)NULL);
_out->write(str.data(), str.length());
_out->flush();
break;
case OT_stdio:
assert(_fout != (FILE *)NULL);
fwrite(str.data(), str.length(), 1, _fout);
fflush(_fout);
break;
case OT_system_debug:
#if defined(WIN32_VC) || defined(WIN64_VC)
OutputDebugString(str.c_str());
#endif
break;
}
}
/**
*
*/
MultiplexStreamBuf::
MultiplexStreamBuf() {
#ifndef PHAVE_IOSTREAM
// Older iostream implementations required this.
allocate();
setp(base(), ebuf());
#endif
}
/**
*
*/
MultiplexStreamBuf::
~MultiplexStreamBuf() {
sync();
// Make sure all of our owned pointers are freed.
Outputs::iterator oi;
for (oi = _outputs.begin(); oi != _outputs.end(); ++oi) {
Output &out = (*oi);
out.close();
}
}
/**
* Adds the indicated output destinition to the set of things that will be
* written to when characters are output to the MultiplexStream.
*/
void MultiplexStreamBuf::
add_output(MultiplexStreamBuf::BufferType buffer_type,
MultiplexStreamBuf::OutputType output_type,
ostream *out, FILE *fout, bool owns_obj) {
Output o;
o._buffer_type = buffer_type;
o._output_type = output_type;
o._out = out;
o._fout = fout;
o._owns_obj = owns_obj;
// Ensure that we have the mutex while we fiddle with the list of outputs.
_lock.lock();
_outputs.push_back(o);
_lock.unlock();
}
/**
* Forces out all output that hasn't yet been written.
*/
void MultiplexStreamBuf::
flush() {
_lock.lock();
write_chars("", 0, true);
_lock.unlock();
}
/**
* Called by the system ostream implementation when its internal buffer is
* filled, plus one character.
*/
int MultiplexStreamBuf::
overflow(int ch) {
_lock.lock();
streamsize n = pptr() - pbase();
if (n != 0) {
write_chars(pbase(), n, false);
pbump(-n); // Reset pptr().
}
if (ch != EOF) {
// Write one more character.
char c = ch;
write_chars(&c, 1, false);
}
_lock.unlock();
return 0;
}
/**
* Called by the system ostream implementation when the buffer should be
* flushed to output (for instance, on destruction).
*/
int MultiplexStreamBuf::
sync() {
_lock.lock();
streamsize n = pptr() - pbase();
// We pass in false for the flush value, even though our transmitting
// ostream said to sync. This allows us to get better line buffering, since
// our transmitting ostream is often set unitbuf, and might call sync
// multiple times in one line. We still have an explicit flush() call to
// force the issue.
write_chars(pbase(), n, false);
pbump(-n);
_lock.unlock();
return 0; // Return 0 for success, EOF to indicate write full.
}
/**
* An internal function called by sync() and overflow() to store one or more
* characters written to the stream into the memory buffer.
*
* It is assumed that there is only one thread at a time running this code; it
* is the responsibility of the caller to grab the _lock mutex before calling
* this.
*/
void MultiplexStreamBuf::
write_chars(const char *start, int length, bool flush) {
size_t orig = _line_buffer.length();
string latest;
if (length != 0) {
latest = string(start, length);
}
string line;
if (flush) {
// If we're to flush the stream now, we dump the whole thing regardless of
// whether we have reached end-of-line.
line = _line_buffer + latest;
_line_buffer = "";
} else {
// Otherwise, we check for the end-of-line character, for our ostreams
// that only want a complete line at a time.
_line_buffer += latest;
size_t eol = _line_buffer.rfind('\n', orig);
if (eol != string::npos) {
line = _line_buffer.substr(0, eol + 1);
_line_buffer = _line_buffer.substr(eol + 1);
}
}
Outputs::iterator oi;
for (oi = _outputs.begin(); oi != _outputs.end(); ++oi) {
Output &out = (*oi);
switch (out._buffer_type) {
case BT_none:
// No buffering: send all new characters directly to the ostream.
if (!latest.empty()) {
out.write_string(latest);
}
break;
case BT_line:
// Line buffering: send only when a complete line has been received.
if (!line.empty()) {
out.write_string(line);
}
break;
}
}
}
| 23.380165 | 78 | 0.656416 | [
"3d"
] |
7839d3cc94e65c877e8e53108550e234af676fc7 | 732 | cpp | C++ | codes/leetcode/BinarySearchTreeIterator.cpp | smmehrab/problem-solving | 4aeab1673f18d3270ee5fc9b64ed6805eacf4af5 | [
"MIT"
] | null | null | null | codes/leetcode/BinarySearchTreeIterator.cpp | smmehrab/problem-solving | 4aeab1673f18d3270ee5fc9b64ed6805eacf4af5 | [
"MIT"
] | null | null | null | codes/leetcode/BinarySearchTreeIterator.cpp | smmehrab/problem-solving | 4aeab1673f18d3270ee5fc9b64ed6805eacf4af5 | [
"MIT"
] | null | null | null | /*
************************************************
username : smmehrab
fullname : s.m.mehrabul islam
email : mehrab.24csedu.001@gmail.com
institute : university of dhaka, bangladesh
session : 2017-2018
************************************************
*/
class BSTIterator {
private:
vector<int> nodes;
int index = 0;
void traverse(TreeNode* root) {
if (!root) return;
traverse(root->left);
nodes.push_back(root->val);
traverse(root->right);
}
public:
BSTIterator(TreeNode* root) {
traverse(root);
}
int next() {
return nodes[index++];
}
bool hasNext() {
return (index<nodes.size());
}
}; | 21.529412 | 48 | 0.478142 | [
"vector"
] |
783a65b789e01c6a062b7a9533d7e32833243a96 | 5,431 | cpp | C++ | VisionSystem/src/ExplainYOLOImageGenerator.cpp | Jespjon/VisionSystemForAnAutonomousRailwayMaintenanceVehicle | d25895bcb42d730578aae583150be5783034d75c | [
"MIT"
] | 5 | 2021-05-28T14:24:26.000Z | 2021-11-08T13:14:02.000Z | VisionSystem/src/ExplainYOLOImageGenerator.cpp | Jespjon/VisionSystemForAnAutonomousRailwayMaintenanceVehicle | d25895bcb42d730578aae583150be5783034d75c | [
"MIT"
] | null | null | null | VisionSystem/src/ExplainYOLOImageGenerator.cpp | Jespjon/VisionSystemForAnAutonomousRailwayMaintenanceVehicle | d25895bcb42d730578aae583150be5783034d75c | [
"MIT"
] | 1 | 2021-07-04T03:39:51.000Z | 2021-07-04T03:39:51.000Z | // About
/*
* Generate images explaining how YOLO detects.
* Uses Darknet.
*
* Set the number of horizontal and vertical lines in Grid() manually.
*/
#include <opencv2/opencv.hpp>
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <fstream>
#define OPENCV
#include "yolo_v2_class.hpp" // imported functions from DLL
#include "SharedParameters.h"
using std::cout;
using std::endl;
using std::string;
std::string namesFile = "../../../../../darknet/data/yolo-tiny-authours-VOC-COCO-poles/obj.names";
std::string cfgFile = "../../../../../darknet/cfg/yolo-tiny-obj-authours-VOC-COCO-poles.cfg";
std::string weightsFile = "../../../../../darknet/backup/yolo-tiny-obj-authours-VOC-COCO-poles_best.weights";
std::vector<std::string> ObjectNames;
Detector* detector;
float detectedObjectThreshold;
int imageWidth = 1280;
int imageHeight = 720;
cv::Size imageSize(imageWidth, imageHeight);
cv::Mat frameImage;
cv::Mat outputImage;
std::vector<bbox_t> resultVector;
std::string windowName = "Image Window";
// Set the names of the input and output image
std::string imageFolderPath = pathToVisionSystem + "../Images/";
std::string inputImageName = "TestImage.png";
std::string outputFileName = "yolo";
void DrawBoxes(cv::Mat image) {
//Purple, Red, Yellow, Green, Cyan, Blue
int const colors[6][3] = { { 1,0,1 },{ 0,0,1 },{ 0,1,1 },{ 0,1,0 },{ 1,1,0 },{ 1,0,0 } };
//Car, person, sign_speed, sign_v, sign_triangle_warning, sign_speed_down, sign_speed_up, signal_forsignal, signal_1, signal_2-5, train, signal_triangle, bus, barrier, truck, motorcycle, crossing, bicycle
int classColorIndices[18] = { 1, 2, 2, 2, 2, 2, 2, 2, 4, 4, 3, 3, 1, 5, 1, 1, 5, 1 };
int detectedSpeedSignIndex = 0;
int detectedSignalIndex = 0;
for (auto& i : resultVector) {
cv::Scalar color(colors[classColorIndices[i.obj_id]][0], colors[classColorIndices[i.obj_id]][1], colors[classColorIndices[i.obj_id]][2]);
color *= 255;
if (detectedObjectThreshold < 0.1) {
color = cv::Scalar(0, 0, 0);
cv::rectangle(image, cv::Rect(i.x, i.y, i.w, i.h), color, i.prob * 20);
} else
cv::rectangle(image, cv::Rect(i.x, i.y, i.w, i.h), color, 5);
}
}
void DetectObjects(cv::Mat frameImage) {
// detection by Yolo
std::shared_ptr<image_t> det_image = detector->mat_to_image_resize(frameImage); // resize
resultVector = detector->detect_resized(*det_image, imageSize.width, imageSize.height, detectedObjectThreshold, true);
}
std::vector<std::string> GetObjectsNamesFromFile(std::string const filename) {
std::ifstream file(filename);
std::vector<std::string> file_lines;
if (!file.is_open()) return file_lines;
for (std::string line; getline(file, line);) file_lines.push_back(line);
return file_lines;
}
void SetupYoloNetwork() {
detector = new Detector(cfgFile, weightsFile);
ObjectNames = GetObjectsNamesFromFile(namesFile);
}
void DrawEdge(cv::Mat frameImage) {
int ramLineWidth = 10;
cv::line(frameImage, cv::Point(0, 0), cv::Point(0, imageSize.height), cv::Scalar(0, 0, 0), ramLineWidth);
cv::line(frameImage, cv::Point(imageSize.width - 1, 0), cv::Point(imageSize.width - 1, imageSize.height), cv::Scalar(0, 0, 0), ramLineWidth);
cv::line(frameImage, cv::Point(0, 0), cv::Point(imageSize.width, 0), cv::Scalar(0, 0, 0), ramLineWidth);
cv::line(frameImage, cv::Point(0, imageSize.height - 1), cv::Point(imageSize.width, imageSize.height - 1), cv::Scalar(0, 0, 0), ramLineWidth);
}
void YOLONonFiltered() {
detectedObjectThreshold = 0.000001;
frameImage.copyTo(outputImage);
DetectObjects(outputImage);
DrawBoxes(outputImage);
DrawEdge(outputImage);
cv::imshow(windowName, outputImage);
cv::waitKey(0);
string fileName = outputFileName + "_bounding_boxes.jpg";
cv::imwrite(imageFolderPath + fileName, outputImage);
}
void YOLOFiltered() {
detectedObjectThreshold = 0.2;
frameImage.copyTo(outputImage);
DetectObjects(outputImage);
DrawBoxes(outputImage);
DrawEdge(outputImage);
cv::imshow(windowName, outputImage);
cv::waitKey(0);
string fileName = outputFileName + "_filtered.jpg";
cv::imwrite(imageFolderPath + fileName, outputImage);
}
void Grid() {
frameImage.copyTo(outputImage);
int gridLineWidth = 2;
int nVerticalLines = 23;
for (int i = 0; i < nVerticalLines; i++) {
cv::line(outputImage, cv::Point(i * imageSize.width / (float)nVerticalLines, 0), cv::Point(i * imageSize.width / (float)nVerticalLines, imageSize.height), cv::Scalar(0, 0, 0), gridLineWidth);
}
int nHorizontalLines = 15;
for (int i = 0; i < nHorizontalLines; i++) {
cv::line(outputImage, cv::Point(0, i * imageSize.height / (float)nHorizontalLines), cv::Point(imageSize.width, i * imageSize.height / (float)nHorizontalLines), cv::Scalar(0, 0, 0), gridLineWidth);
}
DrawEdge(outputImage);
cv::imshow(windowName, outputImage);
cv::waitKey(0);
string fileName = outputFileName + "_grid.jpg";
cv::imwrite(imageFolderPath + fileName, outputImage);
}
int main(int argc, char** argv)
{
// Setup
SetupYoloNetwork();
cv::namedWindow(windowName);
frameImage = cv::imread(imageFolderPath + inputImageName);
imageSize = frameImage.size();
// Create images
Grid();
YOLONonFiltered();
YOLOFiltered();
return 0;
} | 36.695946 | 208 | 0.678144 | [
"vector"
] |
783c5544c00563c20224c0d06e5f6f77c27a353b | 1,248 | cpp | C++ | Source_Files/OOP-Project-CardGames.cpp | Michael432125/Card-Games-Polymorphic-OOP | ebaab8c04fbd1327bd8fbbda8ca83a19fa194e3c | [
"MIT"
] | null | null | null | Source_Files/OOP-Project-CardGames.cpp | Michael432125/Card-Games-Polymorphic-OOP | ebaab8c04fbd1327bd8fbbda8ca83a19fa194e3c | [
"MIT"
] | null | null | null | Source_Files/OOP-Project-CardGames.cpp | Michael432125/Card-Games-Polymorphic-OOP | ebaab8c04fbd1327bd8fbbda8ca83a19fa194e3c | [
"MIT"
] | null | null | null |
#include <iostream>
#include <iomanip>
#include<string>
#include<vector>
#include "Card.h"
#include "Deck.h"
#include "GGPlayer.h"
#include "BlackJackPlayer.h"
#include "CardGuessingGame.h"
#include "BlackJack.h"
using namespace std;
void virtualViaPointer(BaseGame*); //prototype
int main()
{
vector<BaseGame*> games(2);
//Card Guessing Game
vector<size_t> g{ 0 };
string name = "";
GGPlayer p(g, name);
Card temp(Suit::Clubs, Face::_3, false);
Deck deck;
size_t t = 0;
CardGuessingGame n = CardGuessingGame(deck, temp, &p, t);
//Blackjack
vector<bool> boolVec{};
Hand h;
BlackJackPlayer player(name, h, boolVec);
BlackJackPlayer house(name, h, boolVec);
BlackJack bj = BlackJack(deck, &player, &house);
games[0] = &n;
games[1] = &bj;
cout << "\nThe Casino";
cout << "Card Guessing Game[1], BlackJack [2]: ";
string input = "";
cin >> input;
cin.ignore();
if (input == "1") {
virtualViaPointer(games[0]);
}
else if (input == "2") {
virtualViaPointer(games[1]);
}
else {
cout << "\nNot a valid input";
}
}
void virtualViaPointer(BaseGame* baseClassPtr) {
baseClassPtr->gameLogic();
}
| 16.207792 | 61 | 0.602564 | [
"vector"
] |
783d211c006478c63cb7740463d652a09618372f | 11,529 | cpp | C++ | src/pke/unittest/UnitTestAutomorphism.cpp | yamanalab/PALISADE | b476d46170da62d7235d55d9a20497778e96a724 | [
"BSD-2-Clause"
] | null | null | null | src/pke/unittest/UnitTestAutomorphism.cpp | yamanalab/PALISADE | b476d46170da62d7235d55d9a20497778e96a724 | [
"BSD-2-Clause"
] | null | null | null | src/pke/unittest/UnitTestAutomorphism.cpp | yamanalab/PALISADE | b476d46170da62d7235d55d9a20497778e96a724 | [
"BSD-2-Clause"
] | null | null | null | /*
* @file UnitTestAutomorphism for all transform testing
* @author TPOC: contact@palisade-crypto.org
*
* @copyright Copyright (c) 2019, New Jersey Institute of Technology (NJIT)
* 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 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.
*
*/
#include "include/gtest/gtest.h"
#include <iostream>
#include <vector>
#include <algorithm>
#include "cryptocontext.h"
#include "encoding/encodings.h"
#include "utils/debug.h"
using namespace std;
using namespace lbcrypto;
class UTAUTOMORPHISM : public ::testing::Test {
protected:
void SetUp() {}
void TearDown() {
CryptoContextFactory<Poly>::ReleaseAllContexts();
CryptoContextFactory<DCRTPoly>::ReleaseAllContexts();
}
public:
};
// declaration for Automorphism Test on BGV scheme with polynomial operation in
// arbitrary cyclotomics.
std::vector<int64_t> ArbBGVAutomorphismPackedArray(usint i);
// declaration for Automorphism Test on Null scheme with polynomial operation in
// power of 2 cyclotomics.
std::vector<int64_t> NullAutomorphismPackedArray(usint i);
// declaration for Automorphism Test on BGV scheme with polynomial operation in
// powerof 2 cyclotomics.
std::vector<int64_t> BGVAutomorphismPackedArray(usint i);
// declaration for Automorphism Test on BFV scheme with polynomial operation in
// power of 2 cyclotomics.
std::vector<int64_t> BFVAutomorphismPackedArray(usint i);
// declaration for Automorphism Test on BFVrns scheme with polynomial operation
// in power of 2 cyclotomics.
std::vector<int64_t> BFVrnsAutomorphismPackedArray(usint i);
// Helper to function to produce a output of the input vector by i to the
// left(cyclic rotation).
std::vector<int64_t> Rotate(const std::vector<int64_t>& input, usint i);
// Helper to function to check if the elements in perm are the same in the init
// vector.
bool CheckAutomorphism(const std::vector<int64_t>& perm,
const std::vector<int64_t>& init);
TEST_F(UTAUTOMORPHISM, Test_Null_Automorphism_PowerOf2) {
PackedEncoding::Destroy();
std::vector<int64_t> initVector = {1, 2, 3, 4, 5, 6, 7, 8};
for (usint index = 3; index < 16; index = index + 2) {
auto morphedVector = NullAutomorphismPackedArray(index);
EXPECT_TRUE(CheckAutomorphism(morphedVector, initVector));
}
}
TEST_F(UTAUTOMORPHISM, Test_BGV_Automorphism_PowerOf2) {
PackedEncoding::Destroy();
std::vector<int64_t> initVector = {1, 2, 3, 4, 5, 6, 7, 8};
for (usint index = 3; index < 16; index = index + 2) {
auto morphedVector = BGVAutomorphismPackedArray(index);
EXPECT_TRUE(CheckAutomorphism(morphedVector, initVector));
}
}
TEST_F(UTAUTOMORPHISM, Test_BFV_Automorphism_PowerOf2) {
PackedEncoding::Destroy();
std::vector<int64_t> initVector = {1, 2, 3, 4, 5, 6, 7, 8};
for (usint index = 3; index < 16; index = index + 2) {
auto morphedVector = BFVAutomorphismPackedArray(index);
EXPECT_TRUE(CheckAutomorphism(morphedVector, initVector));
}
}
TEST_F(UTAUTOMORPHISM, Test_BFVrns_Automorphism_PowerOf2) {
PackedEncoding::Destroy();
std::vector<int64_t> initVector = {1, 2, 3, 4, 5, 6, 7, 8};
for (usint index = 3; index < 16; index = index + 2) {
auto morphedVector = BFVrnsAutomorphismPackedArray(index);
EXPECT_TRUE(CheckAutomorphism(morphedVector, initVector));
}
}
TEST_F(UTAUTOMORPHISM, Test_BGV_Automorphism_Arb) {
PackedEncoding::Destroy();
usint m = 22;
auto totientList = GetTotientList(m);
std::vector<int64_t> initVector = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
for (usint index = 1; index < 10; index++) {
auto morphedVector = ArbBGVAutomorphismPackedArray(totientList[index]);
EXPECT_TRUE(CheckAutomorphism(morphedVector, initVector));
}
}
TEST_F(UTAUTOMORPHISM, Test_BFV_Automorphism_Arb) { EXPECT_EQ(1, 1); }
std::vector<int64_t> ArbBGVAutomorphismPackedArray(usint i) {
usint m = 22;
usint p = 2333;
BigInteger modulusP(p);
BigInteger modulusQ("955263939794561");
BigInteger squareRootOfRoot("941018665059848");
// usint n = GetTotient(m);
BigInteger bigmodulus("80899135611688102162227204937217");
BigInteger bigroot("77936753846653065954043047918387");
auto cycloPoly = GetCyclotomicPolynomial<BigVector>(m, modulusQ);
ChineseRemainderTransformArb<BigVector>::SetCylotomicPolynomial(cycloPoly,
modulusQ);
float stdDev = 4;
shared_ptr<ILParams> params(
new ILParams(m, modulusQ, squareRootOfRoot, bigmodulus, bigroot));
CryptoContext<Poly> cc =
CryptoContextFactory<Poly>::genCryptoContextBGV(params, p, 8, stdDev);
cc->Enable(ENCRYPTION);
cc->Enable(SHE);
// Initialize the public key containers.
LPKeyPair<Poly> kp = cc->KeyGen();
Ciphertext<Poly> ciphertext;
std::vector<int64_t> vectorOfInts = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
Plaintext intArray = cc->MakePackedPlaintext(vectorOfInts);
ciphertext = cc->Encrypt(kp.publicKey, intArray);
std::vector<usint> indexList = GetTotientList(m);
indexList.erase(indexList.begin());
auto evalKeys = cc->EvalAutomorphismKeyGen(kp.secretKey, indexList);
Ciphertext<Poly> p1;
p1 = cc->EvalAutomorphism(ciphertext, i, *evalKeys);
Plaintext intArrayNew;
cc->Decrypt(kp.secretKey, p1, &intArrayNew);
return intArrayNew->GetPackedValue();
}
std::vector<int64_t> NullAutomorphismPackedArray(usint i) {
usint m = 16;
BigInteger q("67108913");
// BigInteger rootOfUnity("61564");
usint plaintextModulus = 17;
// float stdDev = 4;
// shared_ptr<ILParams> params(new ILParams(m, q, rootOfUnity));
CryptoContext<Poly> cc =
CryptoContextFactory<Poly>::genCryptoContextNull(m, plaintextModulus);
cc->Enable(ENCRYPTION);
cc->Enable(SHE);
// Initialize the public key containers.
LPKeyPair<Poly> kp = cc->KeyGen();
Ciphertext<Poly> ciphertext;
std::vector<int64_t> vectorOfInts = {1, 2, 3, 4, 5, 6, 7, 8};
Plaintext intArray = cc->MakePackedPlaintext(vectorOfInts);
ciphertext = cc->Encrypt(kp.publicKey, intArray);
std::vector<usint> indexList = {3, 5, 7, 9, 11, 13, 15};
auto evalKeys =
cc->EvalAutomorphismKeyGen(kp.publicKey, kp.secretKey, indexList);
Ciphertext<Poly> p1;
p1 = cc->EvalAutomorphism(ciphertext, i, *evalKeys);
Plaintext intArrayNew;
cc->Decrypt(kp.secretKey, p1, &intArrayNew);
return intArrayNew->GetPackedValue();
}
std::vector<int64_t> BGVAutomorphismPackedArray(usint i) {
usint m = 16;
BigInteger q("67108913");
BigInteger rootOfUnity("61564");
usint plaintextModulus = 17;
float stdDev = 4;
shared_ptr<ILParams> params(new ILParams(m, q, rootOfUnity));
CryptoContext<Poly> cc = CryptoContextFactory<Poly>::genCryptoContextBGV(
params, plaintextModulus, 1, stdDev);
cc->Enable(ENCRYPTION);
cc->Enable(SHE);
// Initialize the public key containers.
LPKeyPair<Poly> kp = cc->KeyGen();
Ciphertext<Poly> ciphertext;
std::vector<int64_t> vectorOfInts = {1, 2, 3, 4, 5, 6, 7, 8};
Plaintext intArray = cc->MakePackedPlaintext(vectorOfInts);
ciphertext = cc->Encrypt(kp.publicKey, intArray);
std::vector<usint> indexList = {3, 5, 7, 9, 11, 13, 15};
auto evalKeys = cc->EvalAutomorphismKeyGen(kp.secretKey, indexList);
Ciphertext<Poly> p1;
p1 = cc->EvalAutomorphism(ciphertext, i, *evalKeys);
Plaintext intArrayNew;
cc->Decrypt(kp.secretKey, p1, &intArrayNew);
return intArrayNew->GetPackedValue();
}
std::vector<int64_t> BFVAutomorphismPackedArray(usint i) {
usint m = 16;
BigInteger q("67108913");
BigInteger rootOfUnity("61564");
usint plaintextModulus = 17;
usint relWindow = 1;
float stdDev = 4;
BigInteger BBIPlaintextModulus(plaintextModulus);
BigInteger delta(q.DividedBy(BBIPlaintextModulus));
shared_ptr<ILParams> params(new ILParams(m, q, rootOfUnity));
CryptoContext<Poly> cc = CryptoContextFactory<Poly>::genCryptoContextBFV(
params, plaintextModulus, relWindow, stdDev, delta.ToString());
cc->Enable(ENCRYPTION);
cc->Enable(SHE);
// Initialize the public key containers.
LPKeyPair<Poly> kp = cc->KeyGen();
Ciphertext<Poly> ciphertext;
std::vector<int64_t> vectorOfInts = {1, 2, 3, 4, 5, 6, 7, 8};
Plaintext intArray = cc->MakePackedPlaintext(vectorOfInts);
ciphertext = cc->Encrypt(kp.publicKey, intArray);
std::vector<usint> indexList = {3, 5, 7, 9, 11, 13, 15};
auto evalKeys = cc->EvalAutomorphismKeyGen(kp.secretKey, indexList);
Ciphertext<Poly> p1;
p1 = cc->EvalAutomorphism(ciphertext, i, *evalKeys);
Plaintext intArrayNew;
cc->Decrypt(kp.secretKey, p1, &intArrayNew);
return intArrayNew->GetPackedValue();
}
std::vector<int64_t> BFVrnsAutomorphismPackedArray(usint i) {
PlaintextModulus p = 65537;
double sigma = 4;
double rootHermiteFactor = 1.006;
EncodingParams encodingParams(new EncodingParamsImpl(p));
// Set Crypto Parameters
CryptoContext<DCRTPoly> cc =
CryptoContextFactory<DCRTPoly>::genCryptoContextBFVrns(
encodingParams, rootHermiteFactor, sigma, 0, 1, 0, OPTIMIZED, 2);
cc->Enable(ENCRYPTION);
cc->Enable(SHE);
// Initialize the public key containers.
LPKeyPair<DCRTPoly> kp = cc->KeyGen();
Ciphertext<DCRTPoly> ciphertext;
std::vector<int64_t> vectorOfInts = {1, 2, 3, 4, 5, 6, 7, 8};
Plaintext intArray = cc->MakePackedPlaintext(vectorOfInts);
ciphertext = cc->Encrypt(kp.publicKey, intArray);
std::vector<usint> indexList = {3, 5, 7, 9, 11, 13, 15};
auto evalKeys = cc->EvalAutomorphismKeyGen(kp.secretKey, indexList);
Ciphertext<DCRTPoly> p1;
p1 = cc->EvalAutomorphism(ciphertext, i, *evalKeys);
Plaintext intArrayNew;
cc->Decrypt(kp.secretKey, p1, &intArrayNew);
return intArrayNew->GetPackedValue();
}
std::vector<int64_t> Rotate(const std::vector<int64_t>& input, usint i) {
usint n = input.size();
std::vector<int64_t> result(n, 0);
for (usint j = 0; j < n; j++) {
usint newIndex = (n + j - i) % n;
result[newIndex] = input[j];
}
return result;
}
bool CheckAutomorphism(const std::vector<int64_t>& perm,
const std::vector<int64_t>& init) {
bool result = true;
for (usint i = 0; i < init.size(); i++) {
usint val = init.at(i);
if (!(std::find(perm.begin(), perm.end(), val) != perm.end())) {
result = false;
break;
}
}
return result;
}
| 30.339474 | 80 | 0.715066 | [
"vector",
"transform"
] |
784330ff9bd3bb0a0b054cb6d98a623438af68f7 | 26,621 | cpp | C++ | src/brpc/span.cpp | wu-hanqing/incubator-brpc | 7de0d7eaf6fca2b73b9f6018eb1b9128ce0a8f21 | [
"Apache-2.0"
] | 2 | 2020-07-19T13:24:11.000Z | 2020-07-19T13:24:18.000Z | src/brpc/span.cpp | RichPure/incubator-brpc | 846f7998799dd3c9103ef743fecc3c75d6dcb7ef | [
"BSL-1.0",
"Apache-2.0"
] | 2 | 2020-05-24T17:49:57.000Z | 2020-09-26T06:29:01.000Z | src/brpc/span.cpp | RichPure/incubator-brpc | 846f7998799dd3c9103ef743fecc3c75d6dcb7ef | [
"BSL-1.0",
"Apache-2.0"
] | 1 | 2022-03-17T09:58:18.000Z | 2022-03-17T09:58:18.000Z | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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 <netinet/in.h>
#include <gflags/gflags.h>
#include <leveldb/db.h>
#include <leveldb/comparator.h>
#include "bthread/bthread.h"
#include "butil/scoped_lock.h"
#include "butil/thread_local.h"
#include "butil/string_printf.h"
#include "butil/time.h"
#include "butil/logging.h"
#include "butil/object_pool.h"
#include "butil/fast_rand.h"
#include "butil/file_util.h"
#include "brpc/shared_object.h"
#include "brpc/reloadable_flags.h"
#include "brpc/span.h"
#define BRPC_SPAN_INFO_SEP "\1"
namespace brpc {
const int64_t SPAN_DELETE_INTERVAL_US = 10000000L/*10s*/;
DEFINE_string(rpcz_database_dir, "./rpc_data/rpcz",
"For storing requests/contexts collected by rpcz.");
// TODO: collected per second is customizable.
// const int32_t MAX_RPCZ_MAX_SPAN_PER_SECOND = 10000;
// DEFINE_int32(rpcz_max_span_per_second, MAX_RPCZ_MAX_SPAN_PER_SECOND,
// "Index so many spans per second at most");
// static bool validate_rpcz_max_span_per_second(const char*, int32_t val) {
// return (val >= 1 && val <= MAX_RPCZ_MAX_SPAN_PER_SECOND);
// }
// BRPC_VALIDATE_GFLAG(rpcz_max_span_per_second,
// validate_rpcz_max_span_per_second);
DEFINE_int32(rpcz_keep_span_seconds, 3600,
"Keep spans for at most so many seconds");
BRPC_VALIDATE_GFLAG(rpcz_keep_span_seconds, PositiveInteger);
DEFINE_bool(rpcz_keep_span_db, false, "Don't remove DB of rpcz at program's exit");
struct IdGen {
bool init;
uint16_t seq;
uint64_t current_random;
butil::FastRandSeed seed;
};
static __thread IdGen tls_trace_id_gen = { false, 0, 0, { { 0, 0 } } };
static __thread IdGen tls_span_id_gen = { false, 0, 0, { { 0, 0 } } };
inline uint64_t UpdateTLSRandom64(IdGen* g) {
if (!g->init) {
g->init = true;
init_fast_rand_seed(&g->seed);
}
const uint64_t val = fast_rand(&g->seed);
g->current_random = val;
return val;
}
inline uint64_t GenerateSpanId() {
// 0 is an invalid Id
IdGen* g = &tls_trace_id_gen;
if (g->seq == 0) {
UpdateTLSRandom64(g);
g->seq = 1;
}
return (g->current_random & 0xFFFFFFFFFFFF0000ULL) | g->seq++;
}
inline uint64_t GenerateTraceId() {
// 0 is an invalid Id
IdGen* g = &tls_span_id_gen;
if (g->seq == 0) {
UpdateTLSRandom64(g);
g->seq = 1;
}
return (g->current_random & 0xFFFFFFFFFFFF0000ULL) | g->seq++;
}
Span* Span::CreateClientSpan(const std::string& full_method_name,
int64_t base_real_us) {
Span* span = butil::get_object<Span>(Forbidden());
if (__builtin_expect(span == NULL, 0)) {
return NULL;
}
span->_log_id = 0;
span->_base_cid = INVALID_BTHREAD_ID;
span->_ending_cid = INVALID_BTHREAD_ID;
span->_type = SPAN_TYPE_CLIENT;
span->_async = false;
span->_protocol = PROTOCOL_UNKNOWN;
span->_error_code = 0;
span->_request_size = 0;
span->_response_size = 0;
span->_base_real_us = base_real_us;
span->_received_real_us = 0;
span->_start_parse_real_us = 0;
span->_start_callback_real_us = 0;
span->_start_send_real_us = 0;
span->_sent_real_us = 0;
span->_next_client = NULL;
span->_tls_next = NULL;
span->_full_method_name = full_method_name;
span->_info.clear();
Span* parent = (Span*)bthread::tls_bls.rpcz_parent_span;
if (parent) {
span->_trace_id = parent->trace_id();
span->_parent_span_id = parent->span_id();
span->_local_parent = parent;
span->_next_client = parent->_next_client;
parent->_next_client = span;
} else {
span->_trace_id = GenerateTraceId();
span->_parent_span_id = 0;
span->_local_parent = NULL;
}
span->_span_id = GenerateSpanId();
return span;
}
inline const std::string& unknown_span_name() {
// thread-safe in gcc.
static std::string s_unknown_method_name = "unknown_method";
return s_unknown_method_name;
}
Span* Span::CreateServerSpan(
const std::string& full_method_name,
uint64_t trace_id, uint64_t span_id, uint64_t parent_span_id,
int64_t base_real_us) {
Span* span = butil::get_object<Span>(Forbidden());
if (__builtin_expect(span == NULL, 0)) {
return NULL;
}
span->_trace_id = (trace_id ? trace_id : GenerateTraceId());
span->_span_id = (span_id ? span_id : GenerateSpanId());
span->_parent_span_id = parent_span_id;
span->_log_id = 0;
span->_base_cid = INVALID_BTHREAD_ID;
span->_ending_cid = INVALID_BTHREAD_ID;
span->_type = SPAN_TYPE_SERVER;
span->_async = false;
span->_protocol = PROTOCOL_UNKNOWN;
span->_error_code = 0;
span->_request_size = 0;
span->_response_size = 0;
span->_base_real_us = base_real_us;
span->_received_real_us = 0;
span->_start_parse_real_us = 0;
span->_start_callback_real_us = 0;
span->_start_send_real_us = 0;
span->_sent_real_us = 0;
span->_next_client = NULL;
span->_tls_next = NULL;
span->_full_method_name = (!full_method_name.empty() ?
full_method_name : unknown_span_name());
span->_info.clear();
span->_local_parent = NULL;
return span;
}
Span* Span::CreateServerSpan(
uint64_t trace_id, uint64_t span_id, uint64_t parent_span_id,
int64_t base_real_us) {
return CreateServerSpan(unknown_span_name(), trace_id, span_id,
parent_span_id, base_real_us);
}
void Span::ResetServerSpanName(const std::string& full_method_name) {
_full_method_name = (!full_method_name.empty() ?
full_method_name : unknown_span_name());
}
void Span::destroy() {
EndAsParent();
Span* p = _next_client;
while (p) {
Span* p_next = p->_next_client;
p->_info.clear();
butil::return_object(p);
p = p_next;
}
_info.clear();
butil::return_object(this);
}
void Span::Annotate(const char* fmt, ...) {
const int64_t anno_time = butil::cpuwide_time_us() + _base_real_us;
butil::string_appendf(&_info, BRPC_SPAN_INFO_SEP "%lld ",
(long long)anno_time);
va_list ap;
va_start(ap, fmt);
butil::string_vappendf(&_info, fmt, ap);
va_end(ap);
}
void Span::Annotate(const char* fmt, va_list args) {
const int64_t anno_time = butil::cpuwide_time_us() + _base_real_us;
butil::string_appendf(&_info, BRPC_SPAN_INFO_SEP "%lld ",
(long long)anno_time);
butil::string_vappendf(&_info, fmt, args);
}
void Span::Annotate(const std::string& info) {
const int64_t anno_time = butil::cpuwide_time_us() + _base_real_us;
butil::string_appendf(&_info, BRPC_SPAN_INFO_SEP "%lld ",
(long long)anno_time);
_info.append(info);
}
void Span::AnnotateCStr(const char* info, size_t length) {
const int64_t anno_time = butil::cpuwide_time_us() + _base_real_us;
butil::string_appendf(&_info, BRPC_SPAN_INFO_SEP "%lld ",
(long long)anno_time);
if (length <= 0) {
_info.append(info);
} else {
_info.append(info, length);
}
}
size_t Span::CountClientSpans() const {
size_t n = 0;
for (Span* p = _next_client; p; p = p->_next_client, ++n);
return n;
}
int64_t Span::GetStartRealTimeUs() const {
return _type == SPAN_TYPE_SERVER ? _received_real_us : _start_send_real_us;
}
int64_t Span::GetEndRealTimeUs() const {
int64_t result = 0;
result = std::max(result, _received_real_us);
result = std::max(result, _start_parse_real_us);
result = std::max(result, _start_callback_real_us);
result = std::max(result, _start_send_real_us);
result = std::max(result, _sent_real_us);
return result;
}
SpanInfoExtractor::SpanInfoExtractor(const char* info)
: _sp(info, *BRPC_SPAN_INFO_SEP) {
}
bool SpanInfoExtractor::PopAnnotation(
int64_t before_this_time, int64_t* time, std::string* annotation) {
for (; _sp != NULL; ++_sp) {
butil::StringSplitter sp_time(_sp.field(), _sp.field() + _sp.length(), ' ');
if (sp_time) {
char* endptr;
const int64_t anno_time = strtoll(sp_time.field(), &endptr, 10);
if (*endptr == ' ') {
if (before_this_time <= anno_time) {
return false;
}
*time = anno_time;
++sp_time;
annotation->assign(
sp_time.field(),
_sp.field() + _sp.length() - sp_time.field());
++_sp;
return true;
}
}
LOG(ERROR) << "Unknown annotation: "
<< std::string(_sp.field(), _sp.length());
}
return false;
}
bool CanAnnotateSpan() {
return bthread::tls_bls.rpcz_parent_span;
}
void AnnotateSpan(const char* fmt, ...) {
Span* span = (Span*)bthread::tls_bls.rpcz_parent_span;
va_list ap;
va_start(ap, fmt);
span->Annotate(fmt, ap);
va_end(ap);
}
class SpanDB : public SharedObject {
public:
leveldb::DB* id_db;
leveldb::DB* time_db;
std::string id_db_name;
std::string time_db_name;
SpanDB() : id_db(NULL), time_db(NULL) { }
static SpanDB* Open();
leveldb::Status Index(const Span* span, std::string* value_buf);
leveldb::Status RemoveSpansBefore(int64_t tm);
private:
static void Swap(SpanDB& db1, SpanDB& db2) {
std::swap(db1.id_db, db2.id_db);
std::swap(db1.id_db_name, db2.id_db_name);
std::swap(db1.time_db, db2.time_db);
std::swap(db1.time_db_name, db2.time_db_name);
}
~SpanDB() {
if (id_db == NULL && time_db == NULL) {
return;
}
delete id_db;
delete time_db;
if (!FLAGS_rpcz_keep_span_db) {
std::string cmd = butil::string_printf("rm -rf %s %s",
id_db_name.c_str(),
time_db_name.c_str());
butil::ignore_result(system(cmd.c_str()));
}
}
};
static bool started_span_indexing = false;
static pthread_once_t start_span_indexing_once = PTHREAD_ONCE_INIT;
static int64_t g_last_time_key = 0;
static int64_t g_last_delete_tm = 0;
// Following variables are monitored by builtin services, thus non-static.
static pthread_mutex_t g_span_db_mutex = PTHREAD_MUTEX_INITIALIZER;
static bool g_span_ending = false; // don't open span again if this var is true.
// Can't use intrusive_ptr which has ctor/dtor issues.
static SpanDB* g_span_db = NULL;
bool has_span_db() { return !!g_span_db; }
bvar::CollectorSpeedLimit g_span_sl = BVAR_COLLECTOR_SPEED_LIMIT_INITIALIZER;
static bvar::DisplaySamplingRatio s_display_sampling_ratio(
"rpcz_sampling_ratio", &g_span_sl);
struct SpanEarlier {
bool operator()(bvar::Collected* c1, bvar::Collected* c2) const {
return ((Span*)c1)->GetStartRealTimeUs() < ((Span*)c2)->GetStartRealTimeUs();
}
};
class SpanPreprocessor : public bvar::CollectorPreprocessor {
public:
void process(std::vector<bvar::Collected*> & list) {
// Sort spans by their starting time so that the code on making
// time monotonic in Span::Index works better.
std::sort(list.begin(), list.end(), SpanEarlier());
}
};
static SpanPreprocessor* g_span_prep = NULL;
bvar::CollectorSpeedLimit* Span::speed_limit() {
return &g_span_sl;
}
bvar::CollectorPreprocessor* Span::preprocessor() {
return g_span_prep;
}
static void ResetSpanDB(SpanDB* db) {
SpanDB* old_db = NULL;
{
BAIDU_SCOPED_LOCK(g_span_db_mutex);
old_db = g_span_db;
g_span_db = db;
if (g_span_db) {
g_span_db->AddRefManually();
}
}
if (old_db) {
old_db->RemoveRefManually();
}
}
static void RemoveSpanDB() {
g_span_ending = true;
ResetSpanDB(NULL);
}
static void StartSpanIndexing() {
atexit(RemoveSpanDB);
g_span_prep = new SpanPreprocessor;
started_span_indexing = true;
}
static int StartIndexingIfNeeded() {
if (pthread_once(&start_span_indexing_once, StartSpanIndexing) != 0) {
return -1;
}
return started_span_indexing ? 0 : -1;
}
inline int GetSpanDB(butil::intrusive_ptr<SpanDB>* db) {
BAIDU_SCOPED_LOCK(g_span_db_mutex);
if (g_span_db != NULL) {
*db = g_span_db;
return 0;
}
return -1;
}
void Span::Submit(Span* span, int64_t cpuwide_time_us) {
if (span->local_parent() == NULL) {
span->submit(cpuwide_time_us);
}
}
static void Span2Proto(const Span* span, RpczSpan* out) {
out->set_trace_id(span->trace_id());
out->set_span_id(span->span_id());
out->set_parent_span_id(span->parent_span_id());
out->set_log_id(span->log_id());
out->set_base_cid(span->base_cid().value);
out->set_ending_cid(span->ending_cid().value);
out->set_remote_ip(butil::ip2int(span->remote_side().ip));
out->set_remote_port(span->remote_side().port);
out->set_type(span->type());
out->set_async(span->async());
out->set_protocol(span->protocol());
out->set_request_size(span->request_size());
out->set_response_size(span->response_size());
out->set_received_real_us(span->received_real_us());
out->set_start_parse_real_us(span->start_parse_real_us());
out->set_start_callback_real_us(span->start_callback_real_us());
out->set_start_send_real_us(span->start_send_real_us());
out->set_sent_real_us(span->sent_real_us());
out->set_full_method_name(span->full_method_name());
out->set_info(span->info());
out->set_error_code(span->error_code());
}
inline void ToBigEndian(uint64_t n, uint32_t* buf) {
buf[0] = htonl(n >> 32);
buf[1] = htonl(n & 0xFFFFFFFFUL);
}
inline uint64_t ToLittleEndian(const uint32_t* buf) {
return (((uint64_t)ntohl(buf[0])) << 32) | ntohl(buf[1]);
}
SpanDB* SpanDB::Open() {
SpanDB local;
leveldb::Status st;
char prefix[64];
time_t rawtime;
time(&rawtime);
struct tm lt_buf;
struct tm* timeinfo = localtime_r(&rawtime, <_buf);
const size_t nw = strftime(prefix, sizeof(prefix),
"/%Y%m%d.%H%M%S", timeinfo);
const int nw2 = snprintf(prefix + nw, sizeof(prefix) - nw, ".%d",
getpid());
leveldb::Options options;
options.create_if_missing = true;
options.error_if_exists = true;
local.id_db_name.append(FLAGS_rpcz_database_dir);
local.id_db_name.append(prefix, nw + nw2);
// Create the dir first otherwise leveldb fails.
butil::File::Error error;
const butil::FilePath dir(local.id_db_name);
if (!butil::CreateDirectoryAndGetError(dir, &error)) {
LOG(ERROR) << "Fail to create directory=`" << dir.value() << ", "
<< error;
return NULL;
}
local.id_db_name.append("/id.db");
st = leveldb::DB::Open(options, local.id_db_name.c_str(), &local.id_db);
if (!st.ok()) {
LOG(ERROR) << "Fail to open id_db: " << st.ToString();
return NULL;
}
local.time_db_name.append(FLAGS_rpcz_database_dir);
local.time_db_name.append(prefix, nw + nw2);
local.time_db_name.append("/time.db");
st = leveldb::DB::Open(options, local.time_db_name.c_str(), &local.time_db);
if (!st.ok()) {
LOG(ERROR) << "Fail to open time_db: " << st.ToString();
return NULL;
}
SpanDB* db = new (std::nothrow) SpanDB;
if (NULL == db) {
return NULL;
}
LOG(INFO) << "Opened " << local.id_db_name << " and "
<< local.time_db_name;
Swap(local, *db);
return db;
}
leveldb::Status SpanDB::Index(const Span* span, std::string* value_buf) {
leveldb::WriteOptions options;
options.sync = false;
leveldb::Status st;
// NOTE: Writing into time_db before id_db so that if the second write
// fails, the entry in time_db will be finally removed when it's out
// of time window.
const int64_t start_time = span->GetStartRealTimeUs();
BriefSpan brief;
brief.set_trace_id(span->trace_id());
brief.set_span_id(span->span_id());
brief.set_log_id(span->log_id());
brief.set_type(span->type());
brief.set_error_code(span->error_code());
brief.set_request_size(span->request_size());
brief.set_response_size(span->response_size());
brief.set_start_real_us(start_time);
brief.set_latency_us(span->GetEndRealTimeUs() - start_time);
brief.set_full_method_name(span->full_method_name());
if (!brief.SerializeToString(value_buf)) {
return leveldb::Status::InvalidArgument(
leveldb::Slice("Fail to serialize BriefSpan"));
}
// We need to make the time monotonic otherwise if older entries are
// overwritten by newer ones, entries in id_db associated with the older
// entries are not evicted. Surely we can call DB::Get() before Put(), but
// that would be too slow due to the storage model of leveldb. One feasible
// method is to maintain recent window of keys to time_db, when there's a
// conflict before Put(), try key+1us until an unused time is found. The
// window could be 5~10s. However this method needs a std::map(slow) or
// hashmap+queue(more memory: remember that we're just a framework), and
// this method can't guarantee no duplication when real time goes back
// significantly.
// Since the time to this method is ALMOST in ascending order, we use a
// very simple strategy: if the time is not greater than last-time, set
// it to be last-time + 1us. This works when time goes back because the
// real time is at least 1000000 / FLAGS_rpcz_max_span_per_second times faster
// and it will finally catch up with our time key. (provided the flag
// is less than 1000000).
int64_t time_key = start_time;
if (time_key <= g_last_time_key) {
time_key = g_last_time_key + 1;
}
g_last_time_key = time_key;
uint32_t time_data[2];
ToBigEndian(time_key, time_data);
st = time_db->Put(options,
leveldb::Slice((char*)time_data, sizeof(time_data)),
leveldb::Slice(value_buf->data(), value_buf->size()));
if (!st.ok()) {
return st;
}
uint32_t key_data[4];
ToBigEndian(span->trace_id(), key_data);
ToBigEndian(span->span_id(), key_data + 2);
leveldb::Slice key((char*)key_data, sizeof(key_data));
RpczSpan value_proto;
Span2Proto(span, &value_proto);
// client spans should be reversed.
size_t client_span_count = span->CountClientSpans();
for (size_t i = 0; i < client_span_count; ++i) {
value_proto.add_client_spans();
}
size_t i = 0;
for (const Span* p = span->_next_client; p; p = p->_next_client, ++i) {
Span2Proto(p, value_proto.mutable_client_spans(client_span_count - i - 1));
}
if (!value_proto.SerializeToString(value_buf)) {
return leveldb::Status::InvalidArgument(
leveldb::Slice("Fail to serialize RpczSpan"));
}
leveldb::Slice value(value_buf->data(), value_buf->size());
st = id_db->Put(options, key, value);
return st;
}
// NOTE: may take more than 100ms
leveldb::Status SpanDB::RemoveSpansBefore(int64_t tm) {
if (id_db == NULL || time_db == NULL) {
return leveldb::Status::InvalidArgument(leveldb::Slice("NULL param"));
}
leveldb::Status rc;
leveldb::WriteOptions options;
options.sync = false;
leveldb::Iterator* it = time_db->NewIterator(leveldb::ReadOptions());
for (it->SeekToFirst(); it->Valid(); it->Next()) {
if (it->key().size() != 8) {
LOG(ERROR) << "Invalid key size: " << it->key().size();
continue;
}
const int64_t realtime =
ToLittleEndian((const uint32_t*)it->key().data());
if (realtime >= tm) { // removal is done.
break;
}
BriefSpan brief;
if (brief.ParseFromArray(it->value().data(), it->value().size())) {
uint32_t key_data[4];
ToBigEndian(brief.trace_id(), key_data);
ToBigEndian(brief.span_id(), key_data + 2);
leveldb::Slice key((char*)key_data, sizeof(key_data));
rc = id_db->Delete(options, key);
if (!rc.ok()) {
LOG(ERROR) << "Fail to delete from id_db";
break;
}
} else {
LOG(ERROR) << "Fail to parse from value";
}
rc = time_db->Delete(options, it->key());
if (!rc.ok()) {
LOG(ERROR) << "Fail to delete from time_db";
break;
}
}
delete it;
return rc;
}
// Write span into leveldb.
void Span::dump_and_destroy(size_t /*round*/) {
StartIndexingIfNeeded();
std::string value_buf;
butil::intrusive_ptr<SpanDB> db;
if (GetSpanDB(&db) != 0) {
if (g_span_ending) {
destroy();
return;
}
SpanDB* db2 = SpanDB::Open();
if (db2 == NULL) {
LOG(WARNING) << "Fail to open SpanDB";
destroy();
return;
}
ResetSpanDB(db2);
db.reset(db2);
}
leveldb::Status st = db->Index(this, &value_buf);
destroy();
if (!st.ok()) {
LOG(WARNING) << st.ToString();
if (st.IsNotFound() || st.IsIOError() || st.IsCorruption()) {
ResetSpanDB(NULL);
return;
}
}
// Remove old spans
const int64_t now = butil::gettimeofday_us();
if (now > g_last_delete_tm + SPAN_DELETE_INTERVAL_US) {
g_last_delete_tm = now;
leveldb::Status st = db->RemoveSpansBefore(
now - FLAGS_rpcz_keep_span_seconds * 1000000L);
if (!st.ok()) {
LOG(ERROR) << st.ToString();
if (st.IsNotFound() || st.IsIOError() || st.IsCorruption()) {
ResetSpanDB(NULL);
return;
}
}
}
}
int FindSpan(uint64_t trace_id, uint64_t span_id, RpczSpan* response) {
butil::intrusive_ptr<SpanDB> db;
if (GetSpanDB(&db) != 0) {
return -1;
}
uint32_t key_data[4];
ToBigEndian(trace_id, key_data);
ToBigEndian(span_id, key_data + 2);
leveldb::Slice key((char*)key_data, sizeof(key_data));
std::string value;
leveldb::Status st = db->id_db->Get(leveldb::ReadOptions(), key, &value);
if (!st.ok()) {
return -1;
}
if (!response->ParseFromString(value)) {
LOG(ERROR) << "Fail to parse from the value";
return -1;
}
return 0;
}
void FindSpans(uint64_t trace_id, std::deque<RpczSpan>* out) {
out->clear();
butil::intrusive_ptr<SpanDB> db;
if (GetSpanDB(&db) != 0) {
return;
}
leveldb::Iterator* it = db->id_db->NewIterator(leveldb::ReadOptions());
uint32_t key_data[4];
ToBigEndian(trace_id, key_data);
ToBigEndian(0, key_data + 2);
leveldb::Slice key((char*)key_data, sizeof(key_data));
for (it->Seek(key); it->Valid(); it->Next()) {
if (it->key().size() != sizeof(key_data)) {
LOG(ERROR) << "Invalid key size: " << it->key().size();
break;
}
const uint64_t stored_trace_id =
ToLittleEndian((const uint32_t*)it->key().data());
if (trace_id != stored_trace_id) {
break;
}
RpczSpan span;
if (span.ParseFromArray(it->value().data(), it->value().size())) {
out->push_back(span);
} else {
LOG(ERROR) << "Fail to parse from value";
}
}
delete it;
}
void ListSpans(int64_t starting_realtime, size_t max_scan,
std::deque<BriefSpan>* out, SpanFilter* filter) {
out->clear();
butil::intrusive_ptr<SpanDB> db;
if (GetSpanDB(&db) != 0) {
return;
}
leveldb::Iterator* it = db->time_db->NewIterator(leveldb::ReadOptions());
uint32_t time_data[2];
ToBigEndian(starting_realtime, time_data);
leveldb::Slice key((char*)time_data, sizeof(time_data));
it->Seek(key);
if (!it->Valid()) {
it->SeekToLast();
}
BriefSpan brief;
size_t nscan = 0;
for (size_t i = 0; nscan < max_scan && it->Valid(); ++i, it->Prev()) {
const int64_t key_tm = ToLittleEndian((const uint32_t*)it->key().data());
// May have some bigger time at the beginning, because leveldb returns
// keys >= starting_realtime.
if (key_tm > starting_realtime) {
continue;
}
brief.Clear();
if (brief.ParseFromArray(it->value().data(), it->value().size())) {
if (NULL == filter || filter->Keep(brief)) {
out->push_back(brief);
}
// We increase the count no matter filter passed or not to avoid
// scaning too many entries.
++nscan;
} else {
LOG(ERROR) << "Fail to parse from value";
}
}
delete it;
}
void DescribeSpanDB(std::ostream& os) {
butil::intrusive_ptr<SpanDB> db;
if (GetSpanDB(&db) != 0) {
return;
}
if (db->id_db != NULL) {
std::string val;
if (db->id_db->GetProperty(leveldb::Slice("leveldb.stats"), &val)) {
os << "[ " << db->id_db_name << " ]\n" << val;
}
if (db->id_db->GetProperty(leveldb::Slice("leveldb.sstables"), &val)) {
os << '\n' << val;
}
}
os << '\n';
if (db->time_db != NULL) {
std::string val;
if (db->time_db->GetProperty(leveldb::Slice("leveldb.stats"), &val)) {
os << "[ " << db->time_db_name << " ]\n" << val;
}
if (db->time_db->GetProperty(leveldb::Slice("leveldb.sstables"), &val)) {
os << '\n' << val;
}
}
}
} // namespace brpc
| 33.193267 | 85 | 0.618947 | [
"vector",
"model"
] |
784faaef60aaa54dce6bce84b79c32da907c8b91 | 29,393 | cpp | C++ | modules/gles2/functional/es2fTextureFilteringTests.cpp | omegaphora/external_deqp | 8460b8642f48b81894c3cc6fc6d423811da60648 | [
"Apache-2.0"
] | 2 | 2016-12-27T00:57:00.000Z | 2020-07-13T13:02:45.000Z | modules/gles2/functional/es2fTextureFilteringTests.cpp | omegaphora/external_deqp | 8460b8642f48b81894c3cc6fc6d423811da60648 | [
"Apache-2.0"
] | null | null | null | modules/gles2/functional/es2fTextureFilteringTests.cpp | omegaphora/external_deqp | 8460b8642f48b81894c3cc6fc6d423811da60648 | [
"Apache-2.0"
] | 4 | 2016-04-27T21:12:29.000Z | 2020-07-13T13:02:48.000Z | /*-------------------------------------------------------------------------
* drawElements Quality Program OpenGL ES 2.0 Module
* -------------------------------------------------
*
* Copyright 2014 The Android Open Source Project
*
* 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
* \brief Texture filtering tests.
*//*--------------------------------------------------------------------*/
#include "es2fTextureFilteringTests.hpp"
#include "glsTextureTestUtil.hpp"
#include "gluTexture.hpp"
#include "gluStrUtil.hpp"
#include "gluTextureUtil.hpp"
#include "gluPixelTransfer.hpp"
#include "tcuTestLog.hpp"
#include "tcuTextureUtil.hpp"
#include "tcuTexLookupVerifier.hpp"
#include "tcuVectorUtil.hpp"
#include "deStringUtil.hpp"
#include "glwFunctions.hpp"
#include "glwEnums.hpp"
namespace deqp
{
namespace gles2
{
namespace Functional
{
using tcu::TestLog;
using std::vector;
using std::string;
using tcu::Sampler;
using namespace glu;
using namespace gls::TextureTestUtil;
enum
{
VIEWPORT_WIDTH = 64,
VIEWPORT_HEIGHT = 64,
MIN_VIEWPORT_WIDTH = 64,
MIN_VIEWPORT_HEIGHT = 64
};
class Texture2DFilteringCase : public tcu::TestCase
{
public:
Texture2DFilteringCase (tcu::TestContext& testCtx, glu::RenderContext& renderCtx, const glu::ContextInfo& ctxInfo, const char* name, const char* desc, deUint32 minFilter, deUint32 magFilter, deUint32 wrapS, deUint32 wrapT, deUint32 format, deUint32 dataType, int width, int height);
Texture2DFilteringCase (tcu::TestContext& testCtx, glu::RenderContext& renderCtx, const glu::ContextInfo& ctxInfo, const char* name, const char* desc, deUint32 minFilter, deUint32 magFilter, deUint32 wrapS, deUint32 wrapT, const std::vector<std::string>& filenames);
~Texture2DFilteringCase (void);
void init (void);
void deinit (void);
IterateResult iterate (void);
private:
Texture2DFilteringCase (const Texture2DFilteringCase& other);
Texture2DFilteringCase& operator= (const Texture2DFilteringCase& other);
glu::RenderContext& m_renderCtx;
const glu::ContextInfo& m_renderCtxInfo;
const deUint32 m_minFilter;
const deUint32 m_magFilter;
const deUint32 m_wrapS;
const deUint32 m_wrapT;
const deUint32 m_format;
const deUint32 m_dataType;
const int m_width;
const int m_height;
const std::vector<std::string> m_filenames;
struct FilterCase
{
const glu::Texture2D* texture;
tcu::Vec2 minCoord;
tcu::Vec2 maxCoord;
FilterCase (void)
: texture(DE_NULL)
{
}
FilterCase (const glu::Texture2D* tex_, const tcu::Vec2& minCoord_, const tcu::Vec2& maxCoord_)
: texture (tex_)
, minCoord (minCoord_)
, maxCoord (maxCoord_)
{
}
};
std::vector<glu::Texture2D*> m_textures;
std::vector<FilterCase> m_cases;
TextureRenderer m_renderer;
int m_caseNdx;
};
Texture2DFilteringCase::Texture2DFilteringCase (tcu::TestContext& testCtx, glu::RenderContext& renderCtx, const glu::ContextInfo& ctxInfo, const char* name, const char* desc, deUint32 minFilter, deUint32 magFilter, deUint32 wrapS, deUint32 wrapT, deUint32 format, deUint32 dataType, int width, int height)
: TestCase (testCtx, name, desc)
, m_renderCtx (renderCtx)
, m_renderCtxInfo (ctxInfo)
, m_minFilter (minFilter)
, m_magFilter (magFilter)
, m_wrapS (wrapS)
, m_wrapT (wrapT)
, m_format (format)
, m_dataType (dataType)
, m_width (width)
, m_height (height)
, m_renderer (renderCtx, testCtx, glu::GLSL_VERSION_100_ES, glu::PRECISION_MEDIUMP)
, m_caseNdx (0)
{
}
Texture2DFilteringCase::Texture2DFilteringCase (tcu::TestContext& testCtx, glu::RenderContext& renderCtx, const glu::ContextInfo& ctxInfo, const char* name, const char* desc, deUint32 minFilter, deUint32 magFilter, deUint32 wrapS, deUint32 wrapT, const std::vector<std::string>& filenames)
: TestCase (testCtx, name, desc)
, m_renderCtx (renderCtx)
, m_renderCtxInfo (ctxInfo)
, m_minFilter (minFilter)
, m_magFilter (magFilter)
, m_wrapS (wrapS)
, m_wrapT (wrapT)
, m_format (GL_NONE)
, m_dataType (GL_NONE)
, m_width (0)
, m_height (0)
, m_filenames (filenames)
, m_renderer (renderCtx, testCtx, glu::GLSL_VERSION_100_ES, glu::PRECISION_MEDIUMP)
, m_caseNdx (0)
{
}
Texture2DFilteringCase::~Texture2DFilteringCase (void)
{
deinit();
}
void Texture2DFilteringCase::init (void)
{
try
{
if (!m_filenames.empty())
{
m_textures.reserve(1);
m_textures.push_back(glu::Texture2D::create(m_renderCtx, m_renderCtxInfo, m_testCtx.getArchive(), (int)m_filenames.size(), m_filenames));
}
else
{
// Create 2 textures.
m_textures.reserve(2);
for (int ndx = 0; ndx < 2; ndx++)
m_textures.push_back(new glu::Texture2D(m_renderCtx, m_format, m_dataType, m_width, m_height));
bool mipmaps = deIsPowerOfTwo32(m_width) && deIsPowerOfTwo32(m_height);
int numLevels = mipmaps ? deLog2Floor32(de::max(m_width, m_height))+1 : 1;
tcu::TextureFormatInfo fmtInfo = tcu::getTextureFormatInfo(m_textures[0]->getRefTexture().getFormat());
tcu::Vec4 cBias = fmtInfo.valueMin;
tcu::Vec4 cScale = fmtInfo.valueMax-fmtInfo.valueMin;
// Fill first gradient texture.
for (int levelNdx = 0; levelNdx < numLevels; levelNdx++)
{
tcu::Vec4 gMin = tcu::Vec4(-0.5f, -0.5f, -0.5f, 2.0f)*cScale + cBias;
tcu::Vec4 gMax = tcu::Vec4( 1.0f, 1.0f, 1.0f, 0.0f)*cScale + cBias;
m_textures[0]->getRefTexture().allocLevel(levelNdx);
tcu::fillWithComponentGradients(m_textures[0]->getRefTexture().getLevel(levelNdx), gMin, gMax);
}
// Fill second with grid texture.
for (int levelNdx = 0; levelNdx < numLevels; levelNdx++)
{
deUint32 step = 0x00ffffff / numLevels;
deUint32 rgb = step*levelNdx;
deUint32 colorA = 0xff000000 | rgb;
deUint32 colorB = 0xff000000 | ~rgb;
m_textures[1]->getRefTexture().allocLevel(levelNdx);
tcu::fillWithGrid(m_textures[1]->getRefTexture().getLevel(levelNdx), 4, toVec4(tcu::RGBA(colorA))*cScale + cBias, toVec4(tcu::RGBA(colorB))*cScale + cBias);
}
// Upload.
for (std::vector<glu::Texture2D*>::iterator i = m_textures.begin(); i != m_textures.end(); i++)
(*i)->upload();
}
// Compute cases.
{
const struct
{
int texNdx;
float lodX;
float lodY;
float oX;
float oY;
} cases[] =
{
{ 0, 1.6f, 2.9f, -1.0f, -2.7f },
{ 0, -2.0f, -1.35f, -0.2f, 0.7f },
{ 1, 0.14f, 0.275f, -1.5f, -1.1f },
{ 1, -0.92f, -2.64f, 0.4f, -0.1f },
};
const float viewportW = (float)de::min<int>(VIEWPORT_WIDTH, m_renderCtx.getRenderTarget().getWidth());
const float viewportH = (float)de::min<int>(VIEWPORT_HEIGHT, m_renderCtx.getRenderTarget().getHeight());
for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); caseNdx++)
{
const int texNdx = de::clamp(cases[caseNdx].texNdx, 0, (int)m_textures.size()-1);
const float lodX = cases[caseNdx].lodX;
const float lodY = cases[caseNdx].lodY;
const float oX = cases[caseNdx].oX;
const float oY = cases[caseNdx].oY;
const float sX = deFloatExp2(lodX)*viewportW / float(m_textures[texNdx]->getRefTexture().getWidth());
const float sY = deFloatExp2(lodY)*viewportH / float(m_textures[texNdx]->getRefTexture().getHeight());
m_cases.push_back(FilterCase(m_textures[texNdx], tcu::Vec2(oX, oY), tcu::Vec2(oX+sX, oY+sY)));
}
}
m_caseNdx = 0;
m_testCtx.setTestResult(QP_TEST_RESULT_PASS, "Pass");
}
catch (...)
{
// Clean up to save memory.
Texture2DFilteringCase::deinit();
throw;
}
}
void Texture2DFilteringCase::deinit (void)
{
for (std::vector<glu::Texture2D*>::iterator i = m_textures.begin(); i != m_textures.end(); i++)
delete *i;
m_textures.clear();
m_renderer.clear();
m_cases.clear();
}
Texture2DFilteringCase::IterateResult Texture2DFilteringCase::iterate (void)
{
const glw::Functions& gl = m_renderCtx.getFunctions();
const RandomViewport viewport (m_renderCtx.getRenderTarget(), VIEWPORT_WIDTH, VIEWPORT_HEIGHT, deStringHash(getName()) ^ deInt32Hash(m_caseNdx));
const tcu::TextureFormat texFmt = m_textures[0]->getRefTexture().getFormat();
const tcu::TextureFormatInfo fmtInfo = tcu::getTextureFormatInfo(texFmt);
const FilterCase& curCase = m_cases[m_caseNdx];
const tcu::ScopedLogSection section (m_testCtx.getLog(), string("Test") + de::toString(m_caseNdx), string("Test ") + de::toString(m_caseNdx));
ReferenceParams refParams (TEXTURETYPE_2D);
tcu::Surface rendered (viewport.width, viewport.height);
vector<float> texCoord;
if (viewport.width < MIN_VIEWPORT_WIDTH || viewport.height < MIN_VIEWPORT_HEIGHT)
throw tcu::NotSupportedError("Too small viewport", "", __FILE__, __LINE__);
// Setup params for reference.
refParams.sampler = mapGLSampler(m_wrapS, m_wrapT, m_minFilter, m_magFilter);
refParams.samplerType = getSamplerType(texFmt);
refParams.lodMode = LODMODE_EXACT;
refParams.colorBias = fmtInfo.lookupBias;
refParams.colorScale = fmtInfo.lookupScale;
// Compute texture coordinates.
m_testCtx.getLog() << TestLog::Message << "Texture coordinates: " << curCase.minCoord << " -> " << curCase.maxCoord << TestLog::EndMessage;
computeQuadTexCoord2D(texCoord, curCase.minCoord, curCase.maxCoord);
gl.bindTexture (GL_TEXTURE_2D, curCase.texture->getGLTexture());
gl.texParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, m_minFilter);
gl.texParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, m_magFilter);
gl.texParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, m_wrapS);
gl.texParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, m_wrapT);
gl.viewport(viewport.x, viewport.y, viewport.width, viewport.height);
m_renderer.renderQuad(0, &texCoord[0], refParams);
glu::readPixels(m_renderCtx, viewport.x, viewport.y, rendered.getAccess());
{
const bool isNearestOnly = m_minFilter == GL_NEAREST && m_magFilter == GL_NEAREST;
const tcu::PixelFormat pixelFormat = m_renderCtx.getRenderTarget().getPixelFormat();
const tcu::IVec4 colorBits = max(getBitsVec(pixelFormat) - (isNearestOnly ? 1 : 2), tcu::IVec4(0)); // 1 inaccurate bit if nearest only, 2 otherwise
tcu::LodPrecision lodPrecision;
tcu::LookupPrecision lookupPrecision;
lodPrecision.derivateBits = 8;
lodPrecision.lodBits = 6;
lookupPrecision.colorThreshold = tcu::computeFixedPointThreshold(colorBits) / refParams.colorScale;
lookupPrecision.coordBits = tcu::IVec3(20,20,0);
lookupPrecision.uvwBits = tcu::IVec3(7,7,0);
lookupPrecision.colorMask = getCompareMask(pixelFormat);
const bool isOk = verifyTextureResult(m_testCtx, rendered.getAccess(), curCase.texture->getRefTexture(),
&texCoord[0], refParams, lookupPrecision, lodPrecision, pixelFormat);
if (!isOk)
m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Image verification failed");
}
m_caseNdx += 1;
return m_caseNdx < (int)m_cases.size() ? CONTINUE : STOP;
}
class TextureCubeFilteringCase : public tcu::TestCase
{
public:
TextureCubeFilteringCase (tcu::TestContext& testCtx, glu::RenderContext& renderCtx, const glu::ContextInfo& ctxInfo, const char* name, const char* desc, deUint32 minFilter, deUint32 magFilter, deUint32 wrapS, deUint32 wrapT, deUint32 format, deUint32 dataType, int width, int height);
TextureCubeFilteringCase (tcu::TestContext& testCtx, glu::RenderContext& renderCtx, const glu::ContextInfo& ctxInfo, const char* name, const char* desc, deUint32 minFilter, deUint32 magFilter, deUint32 wrapS, deUint32 wrapT, const std::vector<std::string>& filenames);
~TextureCubeFilteringCase (void);
void init (void);
void deinit (void);
IterateResult iterate (void);
private:
TextureCubeFilteringCase (const TextureCubeFilteringCase& other);
TextureCubeFilteringCase& operator= (const TextureCubeFilteringCase& other);
glu::RenderContext& m_renderCtx;
const glu::ContextInfo& m_renderCtxInfo;
const deUint32 m_minFilter;
const deUint32 m_magFilter;
const deUint32 m_wrapS;
const deUint32 m_wrapT;
const deUint32 m_format;
const deUint32 m_dataType;
const int m_width;
const int m_height;
const std::vector<std::string> m_filenames;
struct FilterCase
{
const glu::TextureCube* texture;
tcu::Vec2 bottomLeft;
tcu::Vec2 topRight;
FilterCase (void)
: texture(DE_NULL)
{
}
FilterCase (const glu::TextureCube* tex_, const tcu::Vec2& bottomLeft_, const tcu::Vec2& topRight_)
: texture (tex_)
, bottomLeft(bottomLeft_)
, topRight (topRight_)
{
}
};
std::vector<glu::TextureCube*> m_textures;
std::vector<FilterCase> m_cases;
TextureRenderer m_renderer;
int m_caseNdx;
};
TextureCubeFilteringCase::TextureCubeFilteringCase (tcu::TestContext& testCtx, glu::RenderContext& renderCtx, const glu::ContextInfo& ctxInfo, const char* name, const char* desc, deUint32 minFilter, deUint32 magFilter, deUint32 wrapS, deUint32 wrapT, deUint32 format, deUint32 dataType, int width, int height)
: TestCase (testCtx, name, desc)
, m_renderCtx (renderCtx)
, m_renderCtxInfo (ctxInfo)
, m_minFilter (minFilter)
, m_magFilter (magFilter)
, m_wrapS (wrapS)
, m_wrapT (wrapT)
, m_format (format)
, m_dataType (dataType)
, m_width (width)
, m_height (height)
, m_renderer (renderCtx, testCtx, glu::GLSL_VERSION_100_ES, glu::PRECISION_MEDIUMP)
, m_caseNdx (0)
{
}
TextureCubeFilteringCase::TextureCubeFilteringCase (tcu::TestContext& testCtx, glu::RenderContext& renderCtx, const glu::ContextInfo& ctxInfo, const char* name, const char* desc, deUint32 minFilter, deUint32 magFilter, deUint32 wrapS, deUint32 wrapT, const std::vector<std::string>& filenames)
: TestCase (testCtx, name, desc)
, m_renderCtx (renderCtx)
, m_renderCtxInfo (ctxInfo)
, m_minFilter (minFilter)
, m_magFilter (magFilter)
, m_wrapS (wrapS)
, m_wrapT (wrapT)
, m_format (GL_NONE)
, m_dataType (GL_NONE)
, m_width (0)
, m_height (0)
, m_filenames (filenames)
, m_renderer (renderCtx, testCtx, glu::GLSL_VERSION_100_ES, glu::PRECISION_MEDIUMP)
, m_caseNdx (0)
{
}
TextureCubeFilteringCase::~TextureCubeFilteringCase (void)
{
deinit();
}
void TextureCubeFilteringCase::init (void)
{
try
{
if (!m_filenames.empty())
{
m_textures.reserve(1);
m_textures.push_back(glu::TextureCube::create(m_renderCtx, m_renderCtxInfo, m_testCtx.getArchive(), (int)m_filenames.size() / 6, m_filenames));
}
else
{
DE_ASSERT(m_width == m_height);
m_textures.reserve(2);
for (int ndx = 0; ndx < 2; ndx++)
m_textures.push_back(new glu::TextureCube(m_renderCtx, m_format, m_dataType, m_width));
const bool mipmaps = deIsPowerOfTwo32(m_width) && deIsPowerOfTwo32(m_height);
const int numLevels = mipmaps ? deLog2Floor32(de::max(m_width, m_height))+1 : 1;
tcu::TextureFormatInfo fmtInfo = tcu::getTextureFormatInfo(m_textures[0]->getRefTexture().getFormat());
tcu::Vec4 cBias = fmtInfo.valueMin;
tcu::Vec4 cScale = fmtInfo.valueMax-fmtInfo.valueMin;
// Fill first with gradient texture.
static const tcu::Vec4 gradients[tcu::CUBEFACE_LAST][2] =
{
{ tcu::Vec4(0.0f, 0.0f, 0.0f, 1.0f), tcu::Vec4(1.0f, 1.0f, 1.0f, 0.0f) }, // negative x
{ tcu::Vec4(0.5f, 0.0f, 0.0f, 1.0f), tcu::Vec4(1.0f, 1.0f, 1.0f, 0.0f) }, // positive x
{ tcu::Vec4(0.0f, 0.5f, 0.0f, 1.0f), tcu::Vec4(1.0f, 1.0f, 1.0f, 0.0f) }, // negative y
{ tcu::Vec4(0.0f, 0.0f, 0.5f, 1.0f), tcu::Vec4(1.0f, 1.0f, 1.0f, 0.0f) }, // positive y
{ tcu::Vec4(0.0f, 0.0f, 0.0f, 0.5f), tcu::Vec4(1.0f, 1.0f, 1.0f, 1.0f) }, // negative z
{ tcu::Vec4(0.5f, 0.5f, 0.5f, 1.0f), tcu::Vec4(1.0f, 1.0f, 1.0f, 0.0f) } // positive z
};
for (int face = 0; face < tcu::CUBEFACE_LAST; face++)
{
for (int levelNdx = 0; levelNdx < numLevels; levelNdx++)
{
m_textures[0]->getRefTexture().allocLevel((tcu::CubeFace)face, levelNdx);
tcu::fillWithComponentGradients(m_textures[0]->getRefTexture().getLevelFace(levelNdx, (tcu::CubeFace)face), gradients[face][0]*cScale + cBias, gradients[face][1]*cScale + cBias);
}
}
// Fill second with grid texture.
for (int face = 0; face < tcu::CUBEFACE_LAST; face++)
{
for (int levelNdx = 0; levelNdx < numLevels; levelNdx++)
{
deUint32 step = 0x00ffffff / (numLevels*tcu::CUBEFACE_LAST);
deUint32 rgb = step*levelNdx*face;
deUint32 colorA = 0xff000000 | rgb;
deUint32 colorB = 0xff000000 | ~rgb;
m_textures[1]->getRefTexture().allocLevel((tcu::CubeFace)face, levelNdx);
tcu::fillWithGrid(m_textures[1]->getRefTexture().getLevelFace(levelNdx, (tcu::CubeFace)face), 4, toVec4(tcu::RGBA(colorA))*cScale + cBias, toVec4(tcu::RGBA(colorB))*cScale + cBias);
}
}
// Upload.
for (std::vector<glu::TextureCube*>::iterator i = m_textures.begin(); i != m_textures.end(); i++)
(*i)->upload();
}
// Compute cases
{
const glu::TextureCube* tex0 = m_textures[0];
const glu::TextureCube* tex1 = m_textures.size() > 1 ? m_textures[1] : tex0;
// \note Coordinates are chosen so that they only sample face interior. ES3 has changed edge sampling behavior
// and hw is not expected to implement both modes.
m_cases.push_back(FilterCase(tex0, tcu::Vec2(-0.8f, -0.8f), tcu::Vec2(0.8f, 0.8f))); // minification
m_cases.push_back(FilterCase(tex0, tcu::Vec2(0.5f, 0.65f), tcu::Vec2(0.8f, 0.8f))); // magnification
m_cases.push_back(FilterCase(tex1, tcu::Vec2(-0.8f, -0.8f), tcu::Vec2(0.8f, 0.8f))); // minification
m_cases.push_back(FilterCase(tex1, tcu::Vec2(0.2f, 0.2f), tcu::Vec2(0.6f, 0.5f))); // magnification
}
m_caseNdx = 0;
m_testCtx.setTestResult(QP_TEST_RESULT_PASS, "Pass");
}
catch (...)
{
// Clean up to save memory.
TextureCubeFilteringCase::deinit();
throw;
}
}
void TextureCubeFilteringCase::deinit (void)
{
for (std::vector<glu::TextureCube*>::iterator i = m_textures.begin(); i != m_textures.end(); i++)
delete *i;
m_textures.clear();
m_renderer.clear();
m_cases.clear();
}
static const char* getFaceDesc (const tcu::CubeFace face)
{
switch (face)
{
case tcu::CUBEFACE_NEGATIVE_X: return "-X";
case tcu::CUBEFACE_POSITIVE_X: return "+X";
case tcu::CUBEFACE_NEGATIVE_Y: return "-Y";
case tcu::CUBEFACE_POSITIVE_Y: return "+Y";
case tcu::CUBEFACE_NEGATIVE_Z: return "-Z";
case tcu::CUBEFACE_POSITIVE_Z: return "+Z";
default:
DE_ASSERT(false);
return DE_NULL;
}
}
TextureCubeFilteringCase::IterateResult TextureCubeFilteringCase::iterate (void)
{
const glw::Functions& gl = m_renderCtx.getFunctions();
const int viewportSize = 28;
const RandomViewport viewport (m_renderCtx.getRenderTarget(), viewportSize, viewportSize, deStringHash(getName()) ^ deInt32Hash(m_caseNdx));
const tcu::ScopedLogSection iterSection (m_testCtx.getLog(), string("Test") + de::toString(m_caseNdx), string("Test ") + de::toString(m_caseNdx));
const FilterCase& curCase = m_cases[m_caseNdx];
const tcu::TextureFormat& texFmt = curCase.texture->getRefTexture().getFormat();
const tcu::TextureFormatInfo fmtInfo = tcu::getTextureFormatInfo(texFmt);
ReferenceParams sampleParams (TEXTURETYPE_CUBE);
if (viewport.width < viewportSize || viewport.height < viewportSize)
throw tcu::NotSupportedError("Too small render target", DE_NULL, __FILE__, __LINE__);
// Setup texture
gl.bindTexture (GL_TEXTURE_CUBE_MAP, curCase.texture->getGLTexture());
gl.texParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, m_minFilter);
gl.texParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, m_magFilter);
gl.texParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, m_wrapS);
gl.texParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, m_wrapT);
// Other state
gl.viewport(viewport.x, viewport.y, viewport.width, viewport.height);
// Params for reference computation.
sampleParams.sampler = glu::mapGLSampler(m_wrapS, m_wrapT, m_minFilter, m_magFilter);
sampleParams.sampler.seamlessCubeMap = true;
sampleParams.samplerType = getSamplerType(texFmt);
sampleParams.colorBias = fmtInfo.lookupBias;
sampleParams.colorScale = fmtInfo.lookupScale;
sampleParams.lodMode = LODMODE_EXACT;
m_testCtx.getLog() << TestLog::Message << "Coordinates: " << curCase.bottomLeft << " -> " << curCase.topRight << TestLog::EndMessage;
for (int faceNdx = 0; faceNdx < tcu::CUBEFACE_LAST; faceNdx++)
{
const tcu::CubeFace face = tcu::CubeFace(faceNdx);
tcu::Surface result (viewport.width, viewport.height);
vector<float> texCoord;
computeQuadTexCoordCube(texCoord, face, curCase.bottomLeft, curCase.topRight);
m_testCtx.getLog() << TestLog::Message << "Face " << getFaceDesc(face) << TestLog::EndMessage;
// \todo Log texture coordinates.
m_renderer.renderQuad(0, &texCoord[0], sampleParams);
GLU_EXPECT_NO_ERROR(gl.getError(), "Draw");
glu::readPixels(m_renderCtx, viewport.x, viewport.y, result.getAccess());
GLU_EXPECT_NO_ERROR(gl.getError(), "Read pixels");
{
const bool isNearestOnly = m_minFilter == GL_NEAREST && m_magFilter == GL_NEAREST;
const tcu::PixelFormat pixelFormat = m_renderCtx.getRenderTarget().getPixelFormat();
const tcu::IVec4 colorBits = max(getBitsVec(pixelFormat) - (isNearestOnly ? 1 : 2), tcu::IVec4(0)); // 1 inaccurate bit if nearest only, 2 otherwise
tcu::LodPrecision lodPrecision;
tcu::LookupPrecision lookupPrecision;
lodPrecision.derivateBits = 5;
lodPrecision.lodBits = 3;
lookupPrecision.colorThreshold = tcu::computeFixedPointThreshold(colorBits) / sampleParams.colorScale;
lookupPrecision.coordBits = tcu::IVec3(10,10,10);
lookupPrecision.uvwBits = tcu::IVec3(6,6,0);
lookupPrecision.colorMask = getCompareMask(pixelFormat);
const bool isOk = verifyTextureResult(m_testCtx, result.getAccess(), curCase.texture->getRefTexture(),
&texCoord[0], sampleParams, lookupPrecision, lodPrecision, pixelFormat);
if (!isOk)
m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Image verification failed");
}
}
m_caseNdx += 1;
return m_caseNdx < (int)m_cases.size() ? CONTINUE : STOP;
}
TextureFilteringTests::TextureFilteringTests (Context& context)
: TestCaseGroup(context, "filtering", "Texture Filtering Tests")
{
}
TextureFilteringTests::~TextureFilteringTests (void)
{
}
void TextureFilteringTests::init (void)
{
tcu::TestCaseGroup* group2D = new tcu::TestCaseGroup(m_testCtx, "2d", "2D Texture Filtering");
tcu::TestCaseGroup* groupCube = new tcu::TestCaseGroup(m_testCtx, "cube", "Cube Map Filtering");
addChild(group2D);
addChild(groupCube);
static const struct
{
const char* name;
deUint32 mode;
} wrapModes[] =
{
{ "clamp", GL_CLAMP_TO_EDGE },
{ "repeat", GL_REPEAT },
{ "mirror", GL_MIRRORED_REPEAT }
};
static const struct
{
const char* name;
deUint32 mode;
} minFilterModes[] =
{
{ "nearest", GL_NEAREST },
{ "linear", GL_LINEAR },
{ "nearest_mipmap_nearest", GL_NEAREST_MIPMAP_NEAREST },
{ "linear_mipmap_nearest", GL_LINEAR_MIPMAP_NEAREST },
{ "nearest_mipmap_linear", GL_NEAREST_MIPMAP_LINEAR },
{ "linear_mipmap_linear", GL_LINEAR_MIPMAP_LINEAR }
};
static const struct
{
const char* name;
deUint32 mode;
} magFilterModes[] =
{
{ "nearest", GL_NEAREST },
{ "linear", GL_LINEAR }
};
static const struct
{
const char* name;
int width;
int height;
} sizes2D[] =
{
{ "pot", 32, 64 },
{ "npot", 31, 55 }
};
static const struct
{
const char* name;
int width;
int height;
} sizesCube[] =
{
{ "pot", 64, 64 },
{ "npot", 63, 63 }
};
static const struct
{
const char* name;
deUint32 format;
deUint32 dataType;
} formats[] =
{
{ "rgba8888", GL_RGBA, GL_UNSIGNED_BYTE },
{ "rgb888", GL_RGB, GL_UNSIGNED_BYTE },
{ "rgba4444", GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4 },
{ "l8", GL_LUMINANCE, GL_UNSIGNED_BYTE }
};
#define FOR_EACH(ITERATOR, ARRAY, BODY) \
for (int ITERATOR = 0; ITERATOR < DE_LENGTH_OF_ARRAY(ARRAY); ITERATOR++) \
BODY
// 2D cases.
FOR_EACH(minFilter, minFilterModes,
FOR_EACH(magFilter, magFilterModes,
FOR_EACH(wrapMode, wrapModes,
FOR_EACH(format, formats,
FOR_EACH(size, sizes2D,
{
bool isMipmap = minFilterModes[minFilter].mode != GL_NEAREST && minFilterModes[minFilter].mode != GL_LINEAR;
bool isClamp = wrapModes[wrapMode].mode == GL_CLAMP_TO_EDGE;
bool isRepeat = wrapModes[wrapMode].mode == GL_REPEAT;
bool isMagNearest = magFilterModes[magFilter].mode == GL_NEAREST;
bool isPotSize = deIsPowerOfTwo32(sizes2D[size].width) && deIsPowerOfTwo32(sizes2D[size].height);
if ((isMipmap || !isClamp) && !isPotSize)
continue; // Not supported.
if ((format != 0) && !(!isMipmap || (isRepeat && isMagNearest)))
continue; // Skip.
string name = string("") + minFilterModes[minFilter].name + "_" + magFilterModes[magFilter].name + "_" + wrapModes[wrapMode].name + "_" + formats[format].name;
if (!isMipmap)
name += string("_") + sizes2D[size].name;
group2D->addChild(new Texture2DFilteringCase(m_testCtx, m_context.getRenderContext(), m_context.getContextInfo(),
name.c_str(), "",
minFilterModes[minFilter].mode,
magFilterModes[magFilter].mode,
wrapModes[wrapMode].mode,
wrapModes[wrapMode].mode,
formats[format].format, formats[format].dataType,
sizes2D[size].width, sizes2D[size].height));
})))));
// 2D ETC1 texture cases.
{
std::vector<std::string> filenames;
for (int i = 0; i <= 7; i++)
filenames.push_back(string("data/etc1/photo_helsinki_mip_") + de::toString(i) + ".pkm");
FOR_EACH(minFilter, minFilterModes,
FOR_EACH(magFilter, magFilterModes,
FOR_EACH(wrapMode, wrapModes,
{
string name = string("") + minFilterModes[minFilter].name + "_" + magFilterModes[magFilter].name + "_" + wrapModes[wrapMode].name + "_etc1";
group2D->addChild(new Texture2DFilteringCase(m_testCtx, m_context.getRenderContext(), m_context.getContextInfo(),
name.c_str(), "",
minFilterModes[minFilter].mode,
magFilterModes[magFilter].mode,
wrapModes[wrapMode].mode,
wrapModes[wrapMode].mode,
filenames));
})));
}
// Cubemap cases.
FOR_EACH(minFilter, minFilterModes,
FOR_EACH(magFilter, magFilterModes,
FOR_EACH(wrapMode, wrapModes,
FOR_EACH(format, formats,
FOR_EACH(size, sizesCube,
{
bool isMipmap = minFilterModes[minFilter].mode != GL_NEAREST && minFilterModes[minFilter].mode != GL_LINEAR;
bool isClamp = wrapModes[wrapMode].mode == GL_CLAMP_TO_EDGE;
bool isRepeat = wrapModes[wrapMode].mode == GL_REPEAT;
bool isMagNearest = magFilterModes[magFilter].mode == GL_NEAREST;
bool isPotSize = deIsPowerOfTwo32(sizesCube[size].width) && deIsPowerOfTwo32(sizesCube[size].height);
if ((isMipmap || !isClamp) && !isPotSize)
continue; // Not supported.
if (format != 0 && !(!isMipmap || (isRepeat && isMagNearest)))
continue; // Skip.
string name = string("") + minFilterModes[minFilter].name + "_" + magFilterModes[magFilter].name + "_" + wrapModes[wrapMode].name + "_" + formats[format].name;
if (!isMipmap)
name += string("_") + sizesCube[size].name;
groupCube->addChild(new TextureCubeFilteringCase(m_testCtx, m_context.getRenderContext(), m_context.getContextInfo(),
name.c_str(), "",
minFilterModes[minFilter].mode,
magFilterModes[magFilter].mode,
wrapModes[wrapMode].mode,
wrapModes[wrapMode].mode,
formats[format].format, formats[format].dataType,
sizesCube[size].width, sizesCube[size].height));
})))));
// Cubemap ETC1 cases
{
static const char* faceExt[] = { "neg_x", "pos_x", "neg_y", "pos_y", "neg_z", "pos_z" };
const int numLevels = 7;
vector<string> filenames;
for (int level = 0; level < numLevels; level++)
for (int face = 0; face < tcu::CUBEFACE_LAST; face++)
filenames.push_back(string("data/etc1/skybox_") + faceExt[face] + "_mip_" + de::toString(level) + ".pkm");
FOR_EACH(minFilter, minFilterModes,
FOR_EACH(magFilter, magFilterModes,
{
string name = string("") + minFilterModes[minFilter].name + "_" + magFilterModes[magFilter].name + "_clamp_etc1";
groupCube->addChild(new TextureCubeFilteringCase(m_testCtx, m_context.getRenderContext(), m_context.getContextInfo(),
name.c_str(), "",
minFilterModes[minFilter].mode,
magFilterModes[magFilter].mode,
GL_CLAMP_TO_EDGE,
GL_CLAMP_TO_EDGE,
filenames));
}));
}
}
} // Functional
} // gles2
} // deqp
| 35.932763 | 309 | 0.688225 | [
"render",
"vector"
] |
7853c7dca899b6c4e363141907ad7a3902e55b59 | 10,953 | cc | C++ | code/Geometry.cc | Alex7Li/ICPCNotebook | c6ff4abace39913ff49b4c683a79adbcf008abf7 | [
"MIT"
] | null | null | null | code/Geometry.cc | Alex7Li/ICPCNotebook | c6ff4abace39913ff49b4c683a79adbcf008abf7 | [
"MIT"
] | null | null | null | code/Geometry.cc | Alex7Li/ICPCNotebook | c6ff4abace39913ff49b4c683a79adbcf008abf7 | [
"MIT"
] | 1 | 2021-12-09T22:25:27.000Z | 2021-12-09T22:25:27.000Z | // C++ routines for computational geometry.
#include <iostream>
#include <vector>
#include <cmath>
#include <cassert>
using namespace std;
double INF = 1e100;
double EPS = 1e-12;
struct PT {
double x, y;
PT() {}
PT(double x, double y) : x(x), y(y) {}
PT(const PT &p) : x(p.x), y(p.y) {}
PT operator+(const PT &p) const { return PT(x + p.x, y + p.y); }
PT operator-(const PT &p) const { return PT(x - p.x, y - p.y); }
PT operator*(double c) const { return PT(x * c, y * c); }
PT operator/(double c) const { return PT(x / c, y / c); }
};
double dot(PT p, PT q) { return p.x * q.x + p.y * q.y; }
double dist2(PT p, PT q) { return dot(p - q, p - q); }
double cross(PT p, PT q) { return p.x * q.y - p.y * q.x; }
ostream &operator<<(ostream &os, const PT &p) {
return os << "(" << p.x << "," << p.y << ")";
}
// rotate a point CCW or CW around the origin
PT RotateCCW90(PT p) { return PT(-p.y, p.x); }
PT RotateCW90(PT p) { return PT(p.y, -p.x); }
PT RotateCCW(PT p, double t) {
return PT(p.x * cos(t) - p.y * sin(t), p.x * sin(t) + p.y * cos(t));
}
// project point c onto line through a and b
// assuming a != b
PT ProjectPointLine(PT a, PT b, PT c) {
return a + (b - a) * dot(c - a, b - a) / dot(b - a, b - a);
}
// project point c onto line segment through a and b
PT ProjectPointSegment(PT a, PT b, PT c) {
double r = dot(b - a, b - a);
if (fabs(r) < EPS) return a;
r = dot(c - a, b - a) / r;
if (r < 0) return a;
if (r > 1) return b;
return a + (b - a) * r;
}
// compute distance from c to segment between a and b
double DistancePointSegment(PT a, PT b, PT c) {
return sqrt(dist2(c, ProjectPointSegment(a, b, c)));
}
// compute distance between point (x,y,z) and plane ax+by+cz=d
double DistancePointPlane(double x, double y, double z,
double a, double b, double c, double d) {
return fabs(a * x + b * y + c * z - d) / sqrt(a * a + b * b + c * c);
}
// determine if lines from a to b and c to d are parallel or collinear
bool LinesParallel(PT a, PT b, PT c, PT d) {
return fabs(cross(b - a, c - d)) < EPS;
}
bool LinesCollinear(PT a, PT b, PT c, PT d) {
return LinesParallel(a, b, c, d)
&& fabs(cross(a - b, a - c)) < EPS
&& fabs(cross(c - d, c - a)) < EPS;
}
// determine if line segment from a to b intersects with
// line segment from c to d
bool SegmentsIntersect(PT a, PT b, PT c, PT d) {
if (LinesCollinear(a, b, c, d)) {
if (dist2(a, c) < EPS || dist2(a, d) < EPS ||
dist2(b, c) < EPS || dist2(b, d) < EPS)
return true;
if (dot(c - a, c - b) > 0 && dot(d - a, d - b) > 0 && dot(c - b, d - b) > 0)
return false;
return true;
}
if (cross(d - a, b - a) * cross(c - a, b - a) > 0) return false;
if (cross(a - c, d - c) * cross(b - c, d - c) > 0) return false;
return true;
}
// compute intersection of line passing through a and b
// with line passing through c and d, assuming that unique
// intersection exists; for segment intersection, check if
// segments intersect first
PT ComputeLineIntersection(PT a, PT b, PT c, PT d) {
b = b - a;
d = c - d;
c = c - a;
assert(dot(b, b) > EPS && dot(d, d) > EPS);
return a + b * cross(c, d) / cross(b, d);
}
// compute center of circle given three points
PT ComputeCircleCenter(PT a, PT b, PT c) {
b = (a + b) / 2;
c = (a + c) / 2;
return ComputeLineIntersection(b, b + RotateCW90(a - b), c, c + RotateCW90(a - c));
}
// determine if point is in a possibly non-convex polygon (by William
// Randolph Franklin); returns 1 for strictly interior points, 0 for
// strictly exterior points, and 0 or 1 for the remaining points.
// Note that it is possible to convert this into an *exact* test using
// integer arithmetic by taking care of the division appropriately
// (making sure to deal with signs properly) and then by writing exact
// tests for checking point on polygon boundary
bool PointInPolygon(const vector<PT> &p, PT q) {
bool c = 0;
for (int i = 0; i < p.size(); i++) {
int j = (i + 1) % p.size();
if ((p[i].y <= q.y && q.y < p[j].y ||
p[j].y <= q.y && q.y < p[i].y) &&
q.x < p[i].x + (p[j].x - p[i].x) * (q.y - p[i].y) / (p[j].y - p[i].y))
c = !c;
}
return c;
}
// determine if point is on the boundary of a polygon
bool PointOnPolygon(const vector<PT> &p, PT q) {
for (int i = 0; i < p.size(); i++)
if (dist2(ProjectPointSegment(p[i], p[(i + 1) % p.size()], q), q) < EPS)
return true;
return false;
}
// compute intersection of line through points a and b with
// circle centered at c with radius r > 0
vector<PT> CircleLineIntersection(PT a, PT b, PT c, double r) {
vector<PT> ret;
b = b - a;
a = a - c;
double A = dot(b, b);
double B = dot(a, b);
double C = dot(a, a) - r * r;
double D = B * B - A * C;
if (D < -EPS) return ret;
ret.push_back(c + a + b * (-B + sqrt(D + EPS)) / A);
if (D > EPS)
ret.push_back(c + a + b * (-B - sqrt(D)) / A);
return ret;
}
// compute intersection of circle centered at a with radius r
// with circle centered at b with radius R
vector<PT> CircleCircleIntersection(PT a, PT b, double r, double R) {
vector<PT> ret;
double d = sqrt(dist2(a, b));
if (d > r + R || d + min(r, R) < max(r, R)) return ret;
double x = (d * d - R * R + r * r) / (2 * d);
double y = sqrt(r * r - x * x);
PT v = (b - a) / d;
ret.push_back(a + v * x + RotateCCW90(v) * y);
if (y > 0)
ret.push_back(a + v * x - RotateCCW90(v) * y);
return ret;
}
// This code computes the area or centroid of a (possibly nonconvex)
// polygon, assuming that the coordinates are listed in a clockwise or
// counterclockwise fashion. Note that the centroid is often known as
// the "center of gravity" or "center of mass".
double ComputeSignedArea(const vector<PT> &p) {
double area = 0;
for (int i = 0; i < p.size(); i++) {
int j = (i + 1) % p.size();
area += p[i].x * p[j].y - p[j].x * p[i].y;
}
return area / 2.0;
}
double ComputeArea(const vector<PT> &p) {
return fabs(ComputeSignedArea(p));
}
PT ComputeCentroid(const vector<PT> &p) {
PT c(0, 0);
double scale = 6.0 * ComputeSignedArea(p);
for (int i = 0; i < p.size(); i++) {
int j = (i + 1) % p.size();
c = c + (p[i] + p[j]) * (p[i].x * p[j].y - p[j].x * p[i].y);
}
return c / scale;
}
// tests whether or not a given polygon (in CW or CCW order) is simple
bool IsSimple(const vector<PT> &p) {
for (int i = 0; i < p.size(); i++) {
for (int k = i + 1; k < p.size(); k++) {
int j = (i + 1) % p.size();
int l = (k + 1) % p.size();
if (i == l || j == k) continue;
if (SegmentsIntersect(p[i], p[j], p[k], p[l]))
return false;
}
}
return true;
}
int main() {
// expected: (-5,2)
cerr << RotateCCW90(PT(2, 5)) << endl;
// expected: (5,-2)
cerr << RotateCW90(PT(2, 5)) << endl;
// expected: (-5,2)
cerr << RotateCCW(PT(2, 5), M_PI / 2) << endl;
// expected: (5,2)
cerr << ProjectPointLine(PT(-5, -2), PT(10, 4), PT(3, 7)) << endl;
// expected: (5,2) (7.5,3) (2.5,1)
cerr << ProjectPointSegment(PT(-5, -2), PT(10, 4), PT(3, 7)) << " "
<< ProjectPointSegment(PT(7.5, 3), PT(10, 4), PT(3, 7)) << " "
<< ProjectPointSegment(PT(-5, -2), PT(2.5, 1), PT(3, 7)) << endl;
// expected: 6.78903
cerr << DistancePointPlane(4, -4, 3, 2, -2, 5, -8) << endl;
// expected: 1 0 1
cerr << LinesParallel(PT(1, 1), PT(3, 5), PT(2, 1), PT(4, 5)) << " "
<< LinesParallel(PT(1, 1), PT(3, 5), PT(2, 0), PT(4, 5)) << " "
<< LinesParallel(PT(1, 1), PT(3, 5), PT(5, 9), PT(7, 13)) << endl;
// expected: 0 0 1
cerr << LinesCollinear(PT(1, 1), PT(3, 5), PT(2, 1), PT(4, 5)) << " "
<< LinesCollinear(PT(1, 1), PT(3, 5), PT(2, 0), PT(4, 5)) << " "
<< LinesCollinear(PT(1, 1), PT(3, 5), PT(5, 9), PT(7, 13)) << endl;
// expected: 1 1 1 0
cerr << SegmentsIntersect(PT(0, 0), PT(2, 4), PT(3, 1), PT(-1, 3)) << " "
<< SegmentsIntersect(PT(0, 0), PT(2, 4), PT(4, 3), PT(0, 5)) << " "
<< SegmentsIntersect(PT(0, 0), PT(2, 4), PT(2, -1), PT(-2, 1)) << " "
<< SegmentsIntersect(PT(0, 0), PT(2, 4), PT(5, 5), PT(1, 7)) << endl;
// expected: (1,2)
cerr << ComputeLineIntersection(PT(0, 0), PT(2, 4), PT(3, 1), PT(-1, 3)) << endl;
// expected: (1,1)
cerr << ComputeCircleCenter(PT(-3, 4), PT(6, 1), PT(4, 5)) << endl;
vector<PT> v;
v.push_back(PT(0, 0));
v.push_back(PT(5, 0));
v.push_back(PT(5, 5));
v.push_back(PT(0, 5));
// expected: 1 1 1 0 0
cerr << PointInPolygon(v, PT(2, 2)) << " "
<< PointInPolygon(v, PT(2, 0)) << " "
<< PointInPolygon(v, PT(0, 2)) << " "
<< PointInPolygon(v, PT(5, 2)) << " "
<< PointInPolygon(v, PT(2, 5)) << endl;
// expected: 0 1 1 1 1
cerr << PointOnPolygon(v, PT(2, 2)) << " "
<< PointOnPolygon(v, PT(2, 0)) << " "
<< PointOnPolygon(v, PT(0, 2)) << " "
<< PointOnPolygon(v, PT(5, 2)) << " "
<< PointOnPolygon(v, PT(2, 5)) << endl;
// expected: (1,6)
// (5,4) (4,5)
// blank line
// (4,5) (5,4)
// blank line
// (4,5) (5,4)
vector<PT> u = CircleLineIntersection(PT(0, 6), PT(2, 6), PT(1, 1), 5);
for (int i = 0; i < u.size(); i++) cerr << u[i] << " ";
cerr << endl;
u = CircleLineIntersection(PT(0, 9), PT(9, 0), PT(1, 1), 5);
for (int i = 0; i < u.size(); i++) cerr << u[i] << " ";
cerr << endl;
u = CircleCircleIntersection(PT(1, 1), PT(10, 10), 5, 5);
for (int i = 0; i < u.size(); i++) cerr << u[i] << " ";
cerr << endl;
u = CircleCircleIntersection(PT(1, 1), PT(8, 8), 5, 5);
for (int i = 0; i < u.size(); i++) cerr << u[i] << " ";
cerr << endl;
u = CircleCircleIntersection(PT(1, 1), PT(4.5, 4.5), 10, sqrt(2.0) / 2.0);
for (int i = 0; i < u.size(); i++) cerr << u[i] << " ";
cerr << endl;
u = CircleCircleIntersection(PT(1, 1), PT(4.5, 4.5), 5, sqrt(2.0) / 2.0);
for (int i = 0; i < u.size(); i++) cerr << u[i] << " ";
cerr << endl;
// area should be 5.0
// centroid should be (1.1666666, 1.166666)
PT pa[] = {PT(0, 0), PT(5, 0), PT(1, 1), PT(0, 5)};
vector<PT> p(pa, pa + 4);
PT c = ComputeCentroid(p);
cerr << "Area: " << ComputeArea(p) << endl;
cerr << "Centroid: " << c << endl;
return 0;
}
| 37.639175 | 88 | 0.503241 | [
"geometry",
"vector"
] |
78560815c5cd7df0a0a2d6fe57f34fdbb7aea109 | 3,878 | cpp | C++ | test/UnitTests/Mesh/BlockMeshTest.cpp | cselab/CubismNova | cbd6876ae9b5864f82f3470b564132c92e0f2e00 | [
"BSD-2-Clause"
] | 9 | 2020-01-27T01:17:19.000Z | 2022-02-26T12:20:17.000Z | test/UnitTests/Mesh/BlockMeshTest.cpp | cselab/CubismNova | cbd6876ae9b5864f82f3470b564132c92e0f2e00 | [
"BSD-2-Clause"
] | null | null | null | test/UnitTests/Mesh/BlockMeshTest.cpp | cselab/CubismNova | cbd6876ae9b5864f82f3470b564132c92e0f2e00 | [
"BSD-2-Clause"
] | 1 | 2021-04-01T07:48:39.000Z | 2021-04-01T07:48:39.000Z | // File : BlockMeshTest.cpp
// Created : Sun Jan 05 2020 11:36:50 AM (+0100)
// Author : Fabian Wermelinger
// Description: Block mesh / sub-mesh tests
// Copyright 2020 ETH Zurich. All Rights Reserved.
#include "Cubism/Alloc/AlignedBlockAllocator.h"
#include "Cubism/Block/Field.h"
#include "Cubism/Core/Index.h"
#include "Cubism/Mesh/StructuredUniform.h"
#include "gtest/gtest.h"
#include <vector>
namespace
{
using namespace Cubism;
TEST(BlockMesh, Field)
{
using IRange = Core::IndexRange<3>;
using MIndex = typename IRange::MultiIndex;
using Mesh = Mesh::StructuredUniform<double, IRange::Dim>;
using MeshIntegrity = typename Mesh::MeshIntegrity;
using PointType = typename Mesh::PointType;
using Entity = typename Mesh::EntityType;
using Range = typename Mesh::RangeType;
const MIndex block_cells(8);
const MIndex nblocks(2);
// global mesh
const PointType end(1);
const MIndex cells = nblocks * block_cells;
Mesh m(end, cells, MeshIntegrity::FullMesh);
// custom field state
struct MyFieldState {
MIndex block_index;
Mesh *mesh;
};
using CellField = Block::CellField<double, Mesh::Dim, MyFieldState>;
using FC = Block::FieldContainer<CellField>;
const PointType block_extent = m.getExtent() / PointType(nblocks);
FC fields;
std::vector<Mesh *> mfields;
std::vector<IRange> vfaces(Mesh::Dim);
for (int bz = 0; bz < nblocks[2]; ++bz) {
for (int by = 0; by < nblocks[1]; ++by) {
for (int bx = 0; bx < nblocks[0]; ++bx) {
const MIndex bi{bx, by, bz};
const PointType bstart =
m.getBegin() + PointType(bi) * block_extent;
const PointType bend = bstart + block_extent;
const MIndex cells = block_cells;
MIndex nodes = cells;
for (size_t i = 0; i < Mesh::Dim; ++i) {
MIndex faces(cells);
if (bi[i] == nblocks[i] - 1) {
++nodes[i];
++faces[i];
}
vfaces[i] = IRange(faces);
}
MyFieldState fs = {};
mfields.push_back(new Mesh(m.getGlobalRange(),
Range(bstart, bend),
IRange(cells),
IRange(nodes),
vfaces,
MeshIntegrity::SubMesh));
fs.block_index = bi;
fs.mesh = mfields.back();
fields.pushBack(new CellField(IRange(cells), fs));
}
}
}
size_t sum_cells = 0;
size_t sum_nodes = 0;
size_t sum_faces_x = 0;
size_t sum_faces_y = 0;
size_t sum_faces_z = 0;
for (const auto f : fields) {
const MyFieldState &fs = f->getState();
const MIndex bi = fs.block_index;
const Mesh &fm = *fs.mesh;
const PointType morigin = m.getBegin() + PointType(bi) * block_extent;
const PointType gorigin = m.getGlobalBegin();
EXPECT_EQ(fm.getBegin(), morigin);
EXPECT_EQ(fm.getGlobalBegin(), gorigin);
sum_cells += fm.size(Entity::Cell);
sum_nodes += fm.size(Entity::Node);
sum_faces_x += fm.size(Entity::Face, Dir::X);
sum_faces_y += fm.size(Entity::Face, Dir::Y);
sum_faces_z += fm.size(Entity::Face, Dir::Z);
}
EXPECT_EQ(m.size(Entity::Cell), sum_cells);
EXPECT_EQ(m.size(Entity::Node), sum_nodes);
EXPECT_EQ(m.size(Entity::Face, Dir::X), sum_faces_x);
EXPECT_EQ(m.size(Entity::Face, Dir::Y), sum_faces_y);
EXPECT_EQ(m.size(Entity::Face, Dir::Z), sum_faces_z);
for (auto m : mfields) {
delete m;
}
}
} // namespace
| 35.254545 | 78 | 0.55312 | [
"mesh",
"vector"
] |
7857bfd244a6da1a596b94792876691b7a90c03b | 956 | cc | C++ | content/public/browser/background_fetch_description.cc | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | content/public/browser/background_fetch_description.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | content/public/browser/background_fetch_description.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // Copyright 2018 The Chromium 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 "content/public/browser/background_fetch_description.h"
namespace content {
BackgroundFetchDescription::BackgroundFetchDescription(
std::string job_unique_id,
std::string title,
url::Origin origin,
SkBitmap icon,
int completed_parts,
int total_parts,
int completed_parts_size,
int total_parts_size,
std::vector<std::string> current_guids)
: job_unique_id(job_unique_id),
title(title),
origin(origin),
icon(icon),
completed_parts(completed_parts),
total_parts(total_parts),
completed_parts_size(completed_parts_size),
total_parts_size(total_parts_size),
current_guids(std::move(current_guids)) {}
BackgroundFetchDescription::~BackgroundFetchDescription() = default;
} // namespace content
| 29.875 | 73 | 0.737448 | [
"vector"
] |
785db589ea3814441d1fcdb501118db05aa99e83 | 972 | hpp | C++ | source/backend/cuda/execution/PReLUExecution.hpp | xhuan28/MNN | 81df3a48d79cbc0b75251d12934345948866f7be | [
"Apache-2.0"
] | 6,958 | 2019-05-06T02:38:02.000Z | 2022-03-31T18:08:48.000Z | source/backend/cuda/execution/PReLUExecution.hpp | xhuan28/MNN | 81df3a48d79cbc0b75251d12934345948866f7be | [
"Apache-2.0"
] | 1,775 | 2019-05-06T04:40:19.000Z | 2022-03-30T15:39:24.000Z | source/backend/cuda/execution/PReLUExecution.hpp | xhuan28/MNN | 81df3a48d79cbc0b75251d12934345948866f7be | [
"Apache-2.0"
] | 1,511 | 2019-05-06T02:38:05.000Z | 2022-03-31T16:59:39.000Z | //
// PReLUExecution.hpp
// MNN
//
// Created by MNN on 2019/01/31.
// Copyright © 2018, Alibaba Group Holding Limited
//
#ifndef PReLUExecution_hpp
#define PReLUExecution_hpp
#include "core/Execution.hpp"
#include <vector>
#include "backend/cuda/core/CUDABackend.hpp"
namespace MNN {
namespace CUDA {
class PReLUExecution : public Execution {
public:
PReLUExecution(const PRelu* prelu, Backend *backend);
virtual ~PReLUExecution();
virtual ErrorCode onResize(const std::vector<Tensor *> &inputs, const std::vector<Tensor *> &outputs) override;
virtual ErrorCode onExecute(const std::vector<Tensor *> &inputs, const std::vector<Tensor *> &outputs) override;
private:
CUDARuntime *mRuntime;
void *mDeviceSlope = nullptr;
int mCount;
int mBatch;
int mChannel;
int mArea;
std::shared_ptr<Tensor> preluTensor;
bool mIsChannelShared = false;
};
} // namespace CUDA
} // namespace MNN
#endif /* PReLUExecution_hpp */
| 22.604651 | 116 | 0.709877 | [
"vector"
] |
786180a92ee27c8c7290ebbb5baf0b4f7c2f78bb | 4,578 | hpp | C++ | esl/computation/environment.hpp | rht/ESL | f883155a167d3c48e5ecdca91c8302fefc901c22 | [
"Apache-2.0"
] | null | null | null | esl/computation/environment.hpp | rht/ESL | f883155a167d3c48e5ecdca91c8302fefc901c22 | [
"Apache-2.0"
] | null | null | null | esl/computation/environment.hpp | rht/ESL | f883155a167d3c48e5ecdca91c8302fefc901c22 | [
"Apache-2.0"
] | 1 | 2021-01-27T12:11:48.000Z | 2021-01-27T12:11:48.000Z | /// \file environment.hpp
///
/// \brief An environment manages computing resources when running a simulation
/// model.
///
/// \authors Maarten P. Scholl
/// \date 2018-11-24
/// \copyright Copyright 2017-2019 The Institute for New Economic Thinking,
/// Oxford Martin School, University of Oxford
///
/// 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.
///
/// You may obtain instructions to fulfill the attribution
/// requirements in CITATION.cff
///
#ifndef ESL_COMPUTATION_ENVIRONMENT_HPP
#define ESL_COMPUTATION_ENVIRONMENT_HPP
#include <unordered_map>
#include <vector>
#include <esl/simulation/identity.hpp>
namespace esl {
class agent;
namespace simulation {
class model;
class agent_collection;
} // namespace simulation
namespace computation {
///
/// \brief The basic computational environment computes models in a
/// single process.
///
class environment
{
protected:
// std::unordered_map<identity<agent>, timer<mean>>
// agent_action_time_;
///
/// \brief Keeps track of agents that were newly created, so that
/// all accounting can be done after the current timestep.
///
///
std::vector<identity<agent>> activated_;
///
/// \brief keeps track of agents that were recently deactivated, so
/// that accounting and storing outputs can be handled after
/// the current timestep has completed.
///
std::vector<identity<agent>> deactivated_;
public:
///
///
///
environment();
///
///
///
virtual ~environment() = default;
///
/// \brief Progresses the model one timestep
///
/// \details One time step of the model (depending on its design)
/// comprise one or more rounds of agent interactions.
///
///
virtual void step(simulation::model &);
///
/// \brief Simulates the model until completion, meaning the
/// simulation time reaches the specified end or an exit
/// condition is met.
///
virtual void run(simulation::model &simulation);
protected:
// allows the model to call send_messages
friend class esl::simulation::model;
// allows the agent collection to activate/deactive agents
friend class esl::simulation::agent_collection;
///
/// \brief Activates all queued agents.
///
/// \return number of activated agents
virtual size_t activate();
///
/// \return
virtual size_t deactivate();
///
/// \brief tasks that are to be executed before simulation::step
///
virtual void before_step();
///
/// \brief tasks that are to be executed after each
/// simulation::step
///
virtual void after_step(simulation::model &simulation);
virtual void after_run(simulation::model &simulation);
///
/// \param a
virtual void activate_agent(const identity<agent> &a);
///
///
/// \param a
virtual void deactivate_agent(const identity<agent> &a);
///
/// \param simulation
/// \return
virtual size_t send_messages(simulation::model &simulation);
};
} // namespace computation
} // namespace esl
#endif // ESL_COMPUTATION_ENVIRONMENT_HPP
| 31.356164 | 80 | 0.53626 | [
"vector",
"model"
] |
7861c91f113c62bcce3813d82a43d640b800db4e | 2,606 | cc | C++ | dali/operators/reader/caffe2_reader_op.cc | ancientmooner/DALI | 355e8db8130cee0d20e9ae3d698f195278544995 | [
"ECL-2.0",
"Apache-2.0"
] | 11 | 2021-03-16T05:09:16.000Z | 2022-03-29T12:48:44.000Z | dali/operators/reader/caffe2_reader_op.cc | ancientmooner/DALI | 355e8db8130cee0d20e9ae3d698f195278544995 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | dali/operators/reader/caffe2_reader_op.cc | ancientmooner/DALI | 355e8db8130cee0d20e9ae3d698f195278544995 | [
"ECL-2.0",
"Apache-2.0"
] | 3 | 2021-05-08T16:51:55.000Z | 2021-07-22T09:02:44.000Z | // Copyright (c) 2017-2018, NVIDIA CORPORATION. All rights reserved.
//
// 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 "dali/operators/reader/caffe2_reader_op.h"
namespace dali {
DALI_REGISTER_OPERATOR(Caffe2Reader, Caffe2Reader, CPU);
DALI_SCHEMA(Caffe2Reader)
.DocStr("Read sample data from a Caffe2 Lightning Memory-Mapped Database (LMDB).")
.NumInput(0)
.OutputFn([](const OpSpec& spec) {
int img_idx = spec.GetArgument<bool>("image_available") ? 1 : 0;
auto label_type = static_cast<LabelType>(spec.GetArgument<int>("label_type"));
int num_label_outputs = (label_type == NO_LABEL) ? 0 : 1;
num_label_outputs += (label_type == MULTI_LABEL_SPARSE ||
label_type == MULTI_LABEL_WEIGHTED_SPARSE) ? 1 : 0;
int additional_inputs = spec.GetArgument<int>("additional_inputs");
int has_bbox = static_cast<int>(spec.GetArgument<bool>("bbox"));
return img_idx + num_label_outputs + additional_inputs + has_bbox;
})
.AddArg("path",
R"code(List of paths to Caffe2 LMDB directories.)code",
DALI_STRING_VEC)
.AddOptionalArg("num_labels",
R"code(Number of classes in dataset. Required when sparse labels are used.)code", 1)
.AddOptionalArg("label_type",
R"code(Type of label stored in dataset.
* 0 = SINGLE_LABEL : single integer label for multi-class classification
* 1 = MULTI_LABEL_SPARSE : sparse active label indices for multi-label classification
* 2 = MULTI_LABEL_DENSE : dense label embedding vector for label embedding regression
* 3 = MULTI_LABEL_WEIGHTED_SPARSE : sparse active label indices with per-label weights for multi-label classification.
* 4 = NO_LABEL : no label is available.
)code", 0)
.AddOptionalArg("image_available",
R"code(If image is available at all in this LMDB.)code", true)
.AddOptionalArg("additional_inputs",
R"code(Additional auxiliary data tensors provided for each sample.)code", 0)
.AddOptionalArg("bbox",
R"code(Denotes if bounding-box information is present.)code", false)
.AddParent("LoaderBase");
} // namespace dali
| 44.169492 | 118 | 0.726401 | [
"vector"
] |
786348d7fc2f0694f0c3cec1afc25583235c3b12 | 1,745 | cc | C++ | src/vector.cc | klantz81/ocean-simulation | b09bc3e9358ee23769f7a840c125f031f4ff7fe7 | [
"MIT"
] | 44 | 2016-04-01T05:15:18.000Z | 2021-09-14T04:09:35.000Z | src/vector.cc | klantz81/ocean-simulation | b09bc3e9358ee23769f7a840c125f031f4ff7fe7 | [
"MIT"
] | 3 | 2016-04-11T16:36:41.000Z | 2019-09-16T01:31:32.000Z | src/vector.cc | klantz81/ocean-simulation | b09bc3e9358ee23769f7a840c125f031f4ff7fe7 | [
"MIT"
] | 3 | 2016-04-01T07:13:18.000Z | 2019-07-18T02:22:02.000Z | #include "vector.h"
vector3::vector3() : x(0.0f), y(0.0f), z(0.0f) { }
vector3::vector3(float x, float y, float z) : x(x), y(y), z(z) { }
float vector3::operator*(const vector3& v) {
return this->x*v.x + this->y*v.y + this->z*v.z;
}
vector3 vector3::cross(const vector3& v) {
return vector3(this->y*v.z - this->z*v.y, this->z*v.x - this->x*v.z, this->x*v.y - this->y*v.z);
}
vector3 vector3::operator+(const vector3& v) {
return vector3(this->x + v.x, this->y + v.y, this->z + v.z);
}
vector3 vector3::operator-(const vector3& v) {
return vector3(this->x - v.x, this->y - v.y, this->z - v.z);
}
vector3 vector3::operator*(const float s) {
return vector3(this->x*s, this->y*s, this->z*s);
}
vector3& vector3::operator=(const vector3& v) {
this->x = v.x; this->y = v.y; this->z = v.z;
return *this;
}
float vector3::length() {
return sqrt(this->x*this->x + this->y*this->y + this->z*this->z);
}
vector3 vector3::unit() {
float l = this->length();
return vector3(this->x/l, this->y/l, this->z/l);
}
vector2::vector2() : x(0.0f), y(0.0f) { }
vector2::vector2(float x, float y) : x(x), y(y) { }
float vector2::operator*(const vector2& v) {
return this->x*v.x + this->y*v.y;
}
vector2 vector2::operator+(const vector2& v) {
return vector2(this->x + v.x, this->y + v.y);
}
vector2 vector2::operator-(const vector2& v) {
return vector2(this->x - v.x, this->y - v.y);
}
vector2 vector2::operator*(const float s) {
return vector2(this->x*s, this->y*s);
}
vector2& vector2::operator=(const vector2& v) {
this->x = v.x; this->y = v.y;
return *this;
}
float vector2::length() {
return sqrt(this->x*this->x + this->y*this->y);
}
vector2 vector2::unit() {
float l = this->length();
return vector2(this->x/l, this->y/l);
}
| 23.581081 | 97 | 0.612607 | [
"vector"
] |
78656d9502b0af2394ea48eb973ae5f5bd0cf120 | 1,521 | cpp | C++ | .LHP/He10/T.Van/HeB4/TAITRONG/TAITRONG/TAITRONG.cpp | sxweetlollipop2912/MaCode | 661d77a2096e4d772fda2b6a7f80c84113b2cde9 | [
"MIT"
] | null | null | null | .LHP/He10/T.Van/HeB4/TAITRONG/TAITRONG/TAITRONG.cpp | sxweetlollipop2912/MaCode | 661d77a2096e4d772fda2b6a7f80c84113b2cde9 | [
"MIT"
] | null | null | null | .LHP/He10/T.Van/HeB4/TAITRONG/TAITRONG/TAITRONG.cpp | sxweetlollipop2912/MaCode | 661d77a2096e4d772fda2b6a7f80c84113b2cde9 | [
"MIT"
] | null | null | null | #include "pch.h"
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <vector>
#define maxN 1001
#define maxM 10001
#define maxA 10001
#define des first
#define cost second
typedef int maxn, maxm, maxa;
typedef std::pair <maxn, maxa> info;
maxn n, S, T;
maxm m;
maxa cmin[maxN];
bool done[maxN];
std::vector <info> ad[maxN];
void Prepare() {
std::cin >> n >> m >> S >> T;
--S; --T;
for (maxm i = 0; i < m; i++) {
maxn u, v;
maxa c;
std::cin >> u >> v >> c;
--u; --v;
ad[u].push_back(std::make_pair(v, c));
ad[v].push_back(std::make_pair(u, c));
}
}
class cmp {
public:
bool operator() (const info &x, const info &y) {
return x.cost < y.cost;
}
};
std::priority_queue <info, std::vector <info>, cmp > pq;
void Fill(const maxn &u) {
for (maxn i = 0; i < ad[u].size(); i++) {
maxn v = ad[u][i].des;
maxa c = std::min(cmin[u], ad[u][i].cost);
if (c <= cmin[v]) continue;
cmin[v] = c;
pq.push(std::make_pair(v, cmin[v]));
}
}
maxn Find() {
while (!pq.empty() && done[pq.top().des]) pq.pop();
if (pq.empty()) return -1;
maxn re = pq.top().des;
pq.pop();
return re;
}
void Dijkstra() {
maxn cur = S;
cmin[cur] = maxA;
while (cur != -1 && cur != T) {
done[cur] = 1;
Fill(cur);
cur = Find();
}
}
void Process() {
Dijkstra();
std::cout << cmin[T];
}
int main() {
//freopen("taitrong.inp", "r", stdin);
//freopen("taitrong.out", "w", stdout);
std::ios_base::sync_with_stdio(0);
std::cin.tie(0);
Prepare();
Process();
} | 15.363636 | 56 | 0.571335 | [
"vector"
] |
786833f2d6a195d8d4854385be2f62443cc6dda6 | 23,898 | cc | C++ | tensorflow/core/framework/graph_to_functiondef.cc | TOT0RoKR/tensorflow | 12c2babf7dccc00c13d6e297c0f792f89f7408aa | [
"Apache-2.0"
] | 74 | 2020-07-06T17:11:39.000Z | 2022-01-28T06:31:28.000Z | tensorflow/core/framework/graph_to_functiondef.cc | sseung0703/tensorflow | be084bd7a4dd241eb781fc704f57bcacc5c9b6dd | [
"Apache-2.0"
] | 1,056 | 2019-12-15T01:20:31.000Z | 2022-02-10T02:06:28.000Z | tensorflow/core/framework/graph_to_functiondef.cc | sseung0703/tensorflow | be084bd7a4dd241eb781fc704f57bcacc5c9b6dd | [
"Apache-2.0"
] | 12 | 2020-07-08T07:27:17.000Z | 2021-12-27T08:54:27.000Z | /* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
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 "tensorflow/core/framework/graph_to_functiondef.h"
#include <unordered_map>
#include <unordered_set>
#include "tensorflow/core/framework/attr_value_util.h"
#include "tensorflow/core/framework/function.pb.h"
#include "tensorflow/core/framework/node_def.pb.h"
#include "tensorflow/core/framework/node_def_util.h"
#include "tensorflow/core/framework/tensor.pb.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/graph/graph.h"
#include "tensorflow/core/graph/graph_node_util.h"
#include "tensorflow/core/graph/tensor_id.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/strings/base64.h"
#include "tensorflow/core/lib/strings/str_util.h"
#include "tensorflow/core/lib/strings/strcat.h"
namespace tensorflow {
namespace {
// Class that maintains a one-to-one original node name -> new node name
// mapping. We normalize the names used as input and output arguments to match
// regexp "[a-z][a-z0-9_]*" specified in definition of ArgDef.name.
// Once we rename them, we risk creating a name collision with the other
// node names, so if necessary we add a suffix to make
// names unique. If we have an input named "A" and a node in the function
// body named "a", they will be renamed to "a" and "a_0".
class NodeNameMapping {
public:
NodeNameMapping() = default;
// Normalize the input name and make it unique. This is the same as the
// function for output, expect that it adds a name mapping for the name.
string GetInputName(const string& name);
// Normalize the output name and make it unique.
string GetOutputName(const string& name);
// Make the node name unique.
string Uniquify(const string& name);
// Records name as a used name. If this name is already used,
// returns an error status.
Status UseOutputName(const string& name);
// Look up how a node name was previously normalized/uniquified.
// Returns empty if name was never seen.
string Lookup(const string& name) const;
private:
string UniquifyHelper(const string& name);
static string Normalize(string name);
// The normalized/uniquified names already used as
// input names (in signature), output names (in signature), and node names
// (in node_def).
// This is a superset of values in name_mapping_.
std::unordered_map<string, uint64> used_names_;
// Mapping from original node name from the graph to the normalized
// and uniquified version of it.
std::unordered_map<string, string> name_mapping_;
};
string NodeNameMapping::Normalize(string name) {
// Convert letters to lowercase and non-alphanumeric characters to '_'.
if (name.empty()) return "unknown";
const int n = name.size();
for (int i = 0; i < n; ++i) {
char c = name[i];
if (isalnum(c)) {
if (isupper(c)) {
name[i] = tolower(c);
}
} else {
name[i] = '_';
}
}
// Find the first letter and start with it.
int i = 0;
for (; i < n; ++i) {
if (isalpha(name[i])) break;
}
// Return "unknown" if none of the name's chars were letters.
return i == n ? "unknown" : name.substr(i);
}
string NodeNameMapping::UniquifyHelper(const string& name) {
auto it = used_names_.emplace(name, 0);
// If the name hasn't been used yet, use it as-is.
if (it.second) return name;
// Add a suffix to name to make it unique.
while (true) {
const string candidate = strings::StrCat(name, "_", it.first->second);
it.first->second++;
if (used_names_.emplace(candidate, 0).second) return candidate;
}
}
string NodeNameMapping::GetInputName(const string& name) {
const string& input_name = UniquifyHelper(Normalize(name));
name_mapping_[name] = input_name;
return input_name;
}
string NodeNameMapping::GetOutputName(const string& name) {
const string& input_name = UniquifyHelper(Normalize(name));
// Don't add it to name_mapping_ since this name is not for a node.
return input_name;
}
string NodeNameMapping::Uniquify(const string& name) {
const string uniqued = UniquifyHelper(name);
name_mapping_[name] = uniqued;
return uniqued;
}
Status NodeNameMapping::UseOutputName(const string& name) {
const auto& iter = used_names_.find(name);
if (iter != used_names_.end()) {
return errors::InvalidArgument(
"Cannot have duplicate output names. Name '", name,
"' appears more than once in 'output_names' array.");
}
used_names_.emplace(name, 0);
return Status::OK();
}
string NodeNameMapping::Lookup(const string& name) const {
const auto iter = name_mapping_.find(name);
if (iter == name_mapping_.end()) return string();
return iter->second;
}
Status FillFunctionBody(
const string& fn_name, const NodeNameMapping& node_names,
const std::vector<const Node*>& body_nodes,
const std::unordered_map<string, string>& tensor_renaming,
bool set_stateful_from_nodes, bool copy_placeholder_attrs_from_nodes,
FunctionDef* fdef) {
std::unordered_set<string> func_attr_names;
for (const auto& func_attr : fdef->signature().attr()) {
func_attr_names.insert(func_attr.name());
}
std::vector<const Edge*> in_edges;
std::vector<const Edge*> control_edges;
for (const Node* node : body_nodes) {
NodeDef* node_def = fdef->add_node_def();
// First, copy the node_def as is. We will patch it next.
*node_def = node->def();
if (!node->assigned_device_name().empty()) {
node_def->set_device(node->assigned_device_name());
}
node_def->set_name(node_names.Lookup(node->name()));
MergeDebugInfo(NodeDebugInfo(node->def()), node_def);
// Input names must be set based on nested names in tensor_renaming.
// Clear the flat input names we got from the original node_def
// from the graph.
node_def->clear_input();
// Collect regular and control inputs. Regular inputs are indexed
// by the index at which they come into the `node`. Control inputs
// don't follow any order, and we sort control inputs to make sure generated
// NodeDef is deterministic.
in_edges.clear();
in_edges.resize(node->num_inputs(), nullptr);
control_edges.clear();
for (const Edge* edge : node->in_edges()) {
if (edge->src()->IsSource()) continue;
if (edge->IsControlEdge()) {
control_edges.push_back(edge);
} else {
in_edges[edge->dst_input()] = edge;
}
}
std::sort(control_edges.begin(), control_edges.end(),
[](const Edge* a, const Edge* b) {
return a->src()->name() < b->src()->name();
});
// Add regular inputs.
for (size_t i = 0; i < in_edges.size(); ++i) {
const Edge* edge = in_edges[i];
string original_input_name;
if (edge == nullptr) {
// A backedge might not appear as a regular Edge, but be only present
// in the node_def. Such edges are referred to as requested_inputs().
if (i >= node->requested_inputs().size()) {
return errors::InvalidArgument(
"Graph to be converted to function appears to be malformed. ",
"Node ", node->name(), " is missing input edge ", i);
}
original_input_name =
ParseTensorName(node->requested_inputs()[i]).ToString();
} else {
original_input_name =
strings::StrCat(edge->src()->name(), ":", edge->src_output());
}
const auto iter = tensor_renaming.find(original_input_name);
if (iter == tensor_renaming.end()) {
return errors::InvalidArgument(
"Input ", i, ", '", original_input_name, "', of node '",
node->name(), "' in function '", fn_name,
"' is not available. You might need to include it in inputs "
"or include its source node in the body");
}
node_def->add_input(iter->second);
}
// Add control inputs.
for (const Edge* edge : control_edges) {
// Add this control input only if the src node is in the body or a part of
// the inputs.
const string normalized = node_names.Lookup(edge->src()->name());
// If we did not find a name for the source of control edge, this
// source must be outside of the body, and not an input. Raise an error.
if (normalized.empty()) {
return errors::InvalidArgument(
"The source of control edge ", edge->DebugString(),
" is not in the body. Encountered while creating function '",
fn_name, "'");
}
node_def->add_input(strings::StrCat("^", normalized));
}
// A function is stateful if any of its nodes are stateful.
if (set_stateful_from_nodes && node->op_def().is_stateful()) {
fdef->mutable_signature()->set_is_stateful(true);
}
// If this node has any attributes with placeholder value, add the
// attribute to FunctionDef signature.
if (!copy_placeholder_attrs_from_nodes) {
continue;
}
for (const auto& iter : node->attrs()) {
if (iter.second.placeholder().empty()) {
continue;
}
// If we already added the attribute, skip it.
string func_attr_name = iter.second.placeholder();
if (func_attr_names.find(func_attr_name) != func_attr_names.end()) {
continue;
}
// This node's attribute is a placeholder value, so it does not have type
// information. We check node's OpDef for attribute type.
string node_attr_name = iter.first;
const OpDef::AttrDef* node_attr_def = nullptr;
for (const auto& node_attr : node->op_def().attr()) {
if (node_attr.name() == node_attr_name) {
node_attr_def = &node_attr;
}
}
if (!node_attr_def) {
return errors::Unimplemented(
"Placeholder value is not supported for attributes not in OpDef. "
"Attribute: ",
node_attr_name, ", OpDef: ", node->op_def().DebugString());
}
OpDef::AttrDef* attr_def = fdef->mutable_signature()->add_attr();
attr_def->set_name(func_attr_name);
attr_def->set_type(node_attr_def->type());
func_attr_names.insert(func_attr_name);
}
}
return Status::OK();
}
Status GraphToFunctionDefHelper(
const Graph& graph, const string& name,
const std::function<absl::optional<string>(const Node*)>& control_ret,
const std::vector<string>& output_names, FunctionDef* fdef) {
auto add_arg_or_retval = [](Node* node,
std::vector<OutputTensor>* args_or_retvals) {
int index;
TF_RETURN_IF_ERROR(GetNodeAttr(node->attrs(), "index", &index));
if (index >= args_or_retvals->size()) {
args_or_retvals->resize(index + 1);
}
if ((*args_or_retvals)[index].node == nullptr) {
(*args_or_retvals)[index].node = node;
} else {
return errors::InvalidArgument("Multiple '", node->type_string(),
"' nodes found with index ", index);
}
return Status::OK();
};
std::vector<const Node*> body_nodes;
std::vector<OutputTensor> inputs;
std::vector<OutputTensor> outputs;
std::vector<const Node*> control_outputs;
std::vector<string> control_output_names;
for (Node* node : graph.op_nodes()) {
if (node->IsArg()) {
TF_RETURN_IF_ERROR(add_arg_or_retval(node, &inputs));
continue;
}
if (node->IsRetval()) {
TF_RETURN_IF_ERROR(add_arg_or_retval(node, &outputs));
continue;
}
if (control_ret) {
auto control_ret_name = control_ret(node);
if (control_ret_name.has_value()) {
control_outputs.push_back(node);
control_output_names.push_back(control_ret_name.value());
}
}
body_nodes.push_back(node);
}
auto validate_args_retvals =
[](const std::vector<OutputTensor>& args_or_retvals,
const string& op_type) {
for (int i = 0, e = args_or_retvals.size(); i < e; ++i) {
if (args_or_retvals[i].node == nullptr) {
return errors::InvalidArgument("Missing '", op_type,
"' node at index ", i);
}
}
return Status::OK();
};
TF_RETURN_IF_ERROR(validate_args_retvals(inputs, "_Arg"));
TF_RETURN_IF_ERROR(validate_args_retvals(outputs, "_Retval"));
return GraphToFunctionDef(graph, name, /*append_hash_to_fn_name=*/false,
/*set_stateful_from_nodes=*/false,
/*copy_placeholder_attrs_from_nodes=*/false,
body_nodes, inputs, outputs, output_names,
control_outputs, control_output_names,
/*description=*/nullptr, fdef);
}
} // anonymous namespace
Status GraphToFunctionDef(const Graph& fn_body, const string& fn_name,
bool append_hash_to_fn_name,
bool set_stateful_from_nodes,
bool copy_placeholder_attrs_from_nodes,
const std::vector<const Node*>& body_nodes,
const std::vector<OutputTensor>& inputs,
const std::vector<OutputTensor>& outputs,
const std::vector<string>& output_names,
const std::vector<const Node*>& control_outputs,
const std::vector<string>& control_output_names,
const char* description, FunctionDef* fdef) {
if (!output_names.empty()) {
DCHECK_EQ(output_names.size(), outputs.size());
}
if (description != nullptr) {
fdef->mutable_signature()->set_description(description);
}
// Keep track of names we used and how we normalized them.
NodeNameMapping node_names;
// Mapping from original names of tensors (i.e. "<node_name>:<idx>") to the
// name we used in the function:
// - For input tensors:
// {flat_tensor_name -> normalized_name_of_src_node}
// e.g. {In:3 -> in}
// - For tensors produced by nodes in function's body:
// {flat_tensor_name -> nested_tensor_name}
// e.g. {Add:3 -> add_0:z:1}
std::unordered_map<string, string> tensor_renaming;
// Fill outputs in function's signature.
// We fill the outputs first to prevent output_names from colliding
// with the input names we pick below. With this order, no names are used in
// node_names yet, and output_names won't collide with anything (except
// potentially with themselves).
for (size_t i = 0; i < outputs.size(); ++i) {
const Node* node = outputs[i].node;
int idx = outputs[i].index;
OpDef::ArgDef* argdef = fdef->mutable_signature()->add_output_arg();
if (node->IsRetval()) {
argdef->set_type(node->input_type(idx));
} else {
argdef->set_type(node->output_type(idx));
}
if (!output_names.empty()) {
TF_RETURN_IF_ERROR(node_names.UseOutputName(output_names[i]));
argdef->set_name(output_names[i]);
} else {
argdef->set_name(node_names.GetOutputName(node->name()));
}
}
// Fill inputs in function's signature.
for (size_t i = 0; i < inputs.size(); ++i) {
const Node* node = inputs[i].node;
int idx = inputs[i].index;
OpDef::ArgDef* argdef = fdef->mutable_signature()->add_input_arg();
argdef->set_type(node->output_type(idx));
const string& input_name = node_names.GetInputName(node->name());
argdef->set_name(input_name);
FunctionDef::ArgAttrs arg_attrs;
int64 resource_arg_unique_id = -1;
for (const auto& attr : node->attrs()) {
// Only copy internal attributes. These attributes will be applied to
// _Arg/Placeholder nodes when this FunctionDef is converted to graph,
// and normal attributes for nodes cannot be applied to those
// _Arg/Placeholder nodes.
if (absl::StartsWith(attr.first, "_")) {
arg_attrs.mutable_attr()->insert(attr);
} else if (attr.first == "shape" && argdef->type() != DT_RESOURCE) {
// Preserve known shapes by moving them to the _output_shapes list.
// The _Arg shape function knows how to extract them from there.
// Don't preserve the shape of a resource arg node, which is a scalar
// resource handle.
AttrValue value;
*(value.mutable_list()->add_shape()) = attr.second.shape();
arg_attrs.mutable_attr()->insert({"_output_shapes", value});
} else if (attr.first == "value" && node->type_string() == "Const") {
// Small eager tensors are captured as const ops rather than
// Placeholders. Add a _output_shapes arg_attr with the shape of the
// const tensor.
AttrValue value;
*(value.mutable_list()->add_shape()) =
attr.second.tensor().tensor_shape();
arg_attrs.mutable_attr()->insert({"_output_shapes", value});
}
if (attr.first == "_resource_arg_unique_id") {
resource_arg_unique_id = attr.second.i();
}
}
if (arg_attrs.attr_size() > 0) {
(*fdef->mutable_arg_attr())[i] = std::move(arg_attrs);
}
if (resource_arg_unique_id >= 0) {
(*fdef->mutable_resource_arg_unique_id())[idx] = resource_arg_unique_id;
}
tensor_renaming[strings::StrCat(node->name(), ":", idx)] = input_name;
}
// Populate tensor_renaming and node_names.
// Generate the new output names for every node in the function.
// The NodeDefs in FunctionDefs use a different naming scheme for
// their inputs than the NodeDefs in a graph (see the comment for
// FunctionDef.node_def in function.proto). We do the
// graph tensor name -> function tensor name conversion for every
// possible input (i.e. every node's outputs) and store the result
// in tensor_renaming.
for (const Node* node : body_nodes) {
// Make sure node_name does not collide with an input or output name.
const string& node_name = node_names.Uniquify(node->name());
// For each output_arg in the op_def, the output_ranges
// map will have [start, end] range of indices that this arg produces
// among all the output tensors of this op.
NameRangeMap output_ranges;
TF_RETURN_IF_ERROR(
NameRangesForNode(*node, node->op_def(), nullptr, &output_ranges));
for (const auto& output : output_ranges) {
const StringPiece& output_name = output.first;
int index_start = output.second.first;
int index_end = output.second.second;
for (int i = index_start; i < index_end; ++i) {
const string& original_name = strings::StrCat(node->name(), ":", i);
const string& new_name =
strings::StrCat(node_name, ":", output_name, ":", i - index_start);
// Record the mapping if this tensor is not already mapped.
// Tensor can be already mapped if it is used as an input.
if (tensor_renaming.find(original_name) == tensor_renaming.end()) {
tensor_renaming[original_name] = new_name;
}
}
}
}
TF_RETURN_IF_ERROR(FillFunctionBody(fn_name, node_names, body_nodes,
tensor_renaming, set_stateful_from_nodes,
copy_placeholder_attrs_from_nodes, fdef));
// Remap return values.
for (int r = 0; r < fdef->signature().output_arg_size(); ++r) {
const string& ret_name = fdef->signature().output_arg(r).name();
// We convert this flat tensor name to the nested value
// (e.g. `add:z:1`) that we stored in tensor_renaming.
string return_value;
if (outputs[r].node->IsRetval()) {
Edge const* edge;
TF_RETURN_IF_ERROR(outputs[r].node->input_edge(0, &edge));
return_value =
strings::StrCat(edge->src()->name(), ":", edge->src_output());
} else {
return_value =
strings::StrCat(outputs[r].node->name(), ":", outputs[r].index);
}
const auto iter = tensor_renaming.find(return_value);
if (iter == tensor_renaming.end()) {
return errors::InvalidArgument(
"TF_Output ", return_value, " is neither in the function body ",
"nor among function inputs. Encountered while creating function '",
fn_name, "'");
}
(*fdef->mutable_ret())[ret_name] = iter->second;
}
if (append_hash_to_fn_name) {
const uint64 hash = FunctionDefHash(*fdef);
string encoded;
TF_RETURN_IF_ERROR(Base64Encode(
StringPiece(reinterpret_cast<const char*>(&hash), sizeof(hash)),
&encoded));
// Besides letters and digits our Base64 encoding uses '_' and '-'.
// Dash is invalid in operation names and multiple underscores in random
// places look strange. Since we never need to decode the hash back,
// replace these chars with 'a' and 'A'. Replacing with different letters
// keeps more entropy.
std::replace(encoded.begin(), encoded.end(), '-', 'a');
std::replace(encoded.begin(), encoded.end(), '_', 'A');
fdef->mutable_signature()->set_name(strings::StrCat(fn_name, "_", encoded));
} else {
fdef->mutable_signature()->set_name(fn_name);
}
if (!control_output_names.empty() &&
(control_outputs.size() != control_output_names.size())) {
return errors::InvalidArgument(
"Expected number of control outputs (", control_outputs.size(),
") and the number of control output names (",
control_output_names.size(), ") to match but they do not.");
}
std::set<string> control_output_names_set;
for (int i = 0; i < control_outputs.size(); ++i) {
string signature_name;
if (!control_output_names.empty()) {
signature_name = control_output_names[i];
} else {
signature_name = control_outputs[i]->name();
}
if (signature_name.empty()) {
return errors::InvalidArgument("Control output name must be not empty");
}
if (!control_output_names_set.insert(signature_name).second) {
return errors::InvalidArgument("Repeated control output name: ",
signature_name);
}
const string control_output_node =
node_names.Lookup(control_outputs[i]->name());
if (control_output_node.empty()) {
return errors::InvalidArgument(
"Control output node name must be not empty");
}
(*fdef->mutable_control_ret())[signature_name] = control_output_node;
}
for (const string& control_output : control_output_names_set) {
fdef->mutable_signature()->add_control_output(control_output);
}
return Status::OK();
}
Status GraphToFunctionDef(
const Graph& graph, const string& name,
const std::function<absl::optional<string>(const Node*)>& control_ret,
FunctionDef* fdef) {
return GraphToFunctionDefHelper(graph, name, control_ret,
/*output_names=*/{}, fdef);
}
Status GraphToFunctionDef(const Graph& graph, const string& name,
FunctionDef* fdef) {
return GraphToFunctionDef(graph, name, /*control_ret=*/nullptr, fdef);
}
Status GraphToFunctionDef(const Graph& graph, const string& name,
const std::vector<std::string>& output_names,
FunctionDef* fdef) {
return GraphToFunctionDefHelper(graph, name, /*control_ret=*/nullptr,
output_names, fdef);
}
} // namespace tensorflow
| 39.370675 | 80 | 0.646958 | [
"shape",
"vector"
] |
786a1c4c4a3d3aedc80d2909e7de1f89d5964a86 | 49,580 | cpp | C++ | decompiler/VuDisasm/VuDisassembler.cpp | charliebruce/jak-project | 44459757b593508870c2816061c7fbcac73597ee | [
"ISC"
] | null | null | null | decompiler/VuDisasm/VuDisassembler.cpp | charliebruce/jak-project | 44459757b593508870c2816061c7fbcac73597ee | [
"ISC"
] | null | null | null | decompiler/VuDisasm/VuDisassembler.cpp | charliebruce/jak-project | 44459757b593508870c2816061c7fbcac73597ee | [
"ISC"
] | null | null | null | #include <cstring>
#include <algorithm>
#include "VuDisassembler.h"
#include "third-party/fmt/core.h"
#include "common/util/print_float.h"
#include "common/util/Assert.h"
namespace decompiler {
namespace {
int upper_op6(u32 in) {
return in & 0b111111;
}
int upper_op11(u32 in) {
return in & 0b11111111111;
}
int upper_dest_mask(u32 in) {
return 0b1111 & (in >> 21);
}
int upper_ft(u32 in) {
return 0b11111 & (in >> 16);
}
int upper_fs(u32 in) {
return 0b11111 & (in >> 11);
}
int upper_fd(u32 in) {
return 0b11111 & (in >> 6);
}
int upper_bc(u32 in) {
return 0b11 & in;
}
int lower_op(u32 in) {
return (in >> 25);
}
int upper_imm15_unsigned(u32 in) {
u32 p1 = (in & 0b11111111111);
u32 p2 = (in >> 21) & 0b1111;
return p1 | (p2 << 11);
}
} // namespace
VuDisassembler::VuDisassembler(VuKind kind) : m_kind(kind) {
// build the decode tables
m_upper_op6_table[0b000000].set(VuInstrK::ADDbc); // 0
m_upper_op6_table[0b000001].set(VuInstrK::ADDbc); // 1
m_upper_op6_table[0b000010].set(VuInstrK::ADDbc); // 2
m_upper_op6_table[0b000011].set(VuInstrK::ADDbc); // 3
m_upper_op6_table[0b000100].set(VuInstrK::SUBbc); // 4
m_upper_op6_table[0b000101].set(VuInstrK::SUBbc); // 5
m_upper_op6_table[0b000110].set(VuInstrK::SUBbc); // 6
m_upper_op6_table[0b000111].set(VuInstrK::SUBbc); // 7
m_upper_op6_table[0b001000].set(VuInstrK::MADDbc); // 8
m_upper_op6_table[0b001001].set(VuInstrK::MADDbc); // 9
m_upper_op6_table[0b001010].set(VuInstrK::MADDbc); // 10
m_upper_op6_table[0b001011].set(VuInstrK::MADDbc); // 11
m_upper_op6_table[0b001100].set(VuInstrK::MSUBbc); // 12
m_upper_op6_table[0b001101].set(VuInstrK::MSUBbc); // 13
m_upper_op6_table[0b001110].set(VuInstrK::MSUBbc); // 14
m_upper_op6_table[0b001111].set(VuInstrK::MSUBbc); // 15
m_upper_op6_table[0b010000].set(VuInstrK::MAXbc); // 16
m_upper_op6_table[0b010001].set(VuInstrK::MAXbc); // 17
m_upper_op6_table[0b010010].set(VuInstrK::MAXbc); // 18
m_upper_op6_table[0b010011].set(VuInstrK::MAXbc); // 19
m_upper_op6_table[0b010100].set(VuInstrK::MINIbc); // 20
m_upper_op6_table[0b010101].set(VuInstrK::MINIbc); // 21
m_upper_op6_table[0b010110].set(VuInstrK::MINIbc); // 22
m_upper_op6_table[0b010111].set(VuInstrK::MINIbc); // 23
m_upper_op6_table[0b011000].set(VuInstrK::MULbc); // 24
m_upper_op6_table[0b011001].set(VuInstrK::MULbc); // 25
m_upper_op6_table[0b011010].set(VuInstrK::MULbc); // 26
m_upper_op6_table[0b011011].set(VuInstrK::MULbc); // 27
m_upper_op6_table[0b011100].set(VuInstrK::MULq); // 28
m_upper_op6_table[0b011101].set(VuInstrK::MAXi); // 29
m_upper_op6_table[0b011110].set(VuInstrK::MULi); // 30
m_upper_op6_table[0b011111].set(VuInstrK::MINIi); // 31
m_upper_op6_table[0b100000].set(VuInstrK::ADDq); // 32
// m_upper_op6_table[0b100001].set(VuInstrK::MADDq); // 33
m_upper_op6_table[0b100010].set(VuInstrK::ADDi); // 34
// m_upper_op6_table[0b100011].set(VuInstrK::MADDi); // 35
// m_upper_op6_table[0b100100].set(VuInstrK::SUBq); // 36
// m_upper_op6_table[0b100101].set(VuInstrK::MSUBq); // 37
// m_upper_op6_table[0b100110].set(VuInstrK::SUBi); // 38
// m_upper_op6_table[0b100111].set(VuInstrK::MSUBi); // 39
m_upper_op6_table[0b101000].set(VuInstrK::ADD); // 40
m_upper_op6_table[0b101001].set(VuInstrK::MADD); // 41
m_upper_op6_table[0b101010].set(VuInstrK::MUL); // 42
m_upper_op6_table[0b101011].set(VuInstrK::MAX); // 43
m_upper_op6_table[0b101100].set(VuInstrK::SUB); // 44
// m_upper_op6_table[0b101101].set(VuInstrK::MSUB); // 45
m_upper_op6_table[0b101110].set(VuInstrK::OPMSUB); // 46
m_upper_op6_table[0b101111].set(VuInstrK::MINI); // 47
// ???
m_upper_op6_table[0b111100].set_11(); // 60
m_upper_op6_table[0b111101].set_11(); // 61
m_upper_op6_table[0b111110].set_11(); // 62
m_upper_op6_table[0b111111].set_11(); // 63
add_op(VuInstrK::NOP, "nop").iemdt();
add_op(VuInstrK::LOWER_NOP, "nop");
add_op(VuInstrK::FTOI4, "ftoi4").iemdt().dst_mask().dst_vf_ft().src_vf_fs();
add_op(VuInstrK::FTOI0, "ftoi0").iemdt().dst_mask().dst_vf_ft().src_vf_fs();
add_op(VuInstrK::ITOF0, "itof0").iemdt().dst_mask().dst_vf_ft().src_vf_fs();
add_op(VuInstrK::ITOF12, "itof12").iemdt().dst_mask().dst_vf_ft().src_vf_fs();
add_op(VuInstrK::ITOF15, "itof15").iemdt().dst_mask().dst_vf_ft().src_vf_fs();
add_op(VuInstrK::FTOI12, "ftoi12").iemdt().dst_mask().dst_vf_ft().src_vf_fs();
add_op(VuInstrK::ADD, "add").iemdt().dst_mask().dss_fd_fs_ft();
add_op(VuInstrK::MULbc, "mul").iemdt().dst_mask().bc().dss_fd_fs_ft();
add_op(VuInstrK::ADDbc, "add").iemdt().dst_mask().dss_fd_fs_ft().bc();
add_op(VuInstrK::MAXbc, "max").iemdt().dst_mask().dss_fd_fs_ft().bc();
add_op(VuInstrK::MULAbc, "mula").iemdt().bc().dst_mask().dst_acc().src_vfs().src_vft();
add_op(VuInstrK::MADDAbc, "madda").iemdt().bc().dst_mask().dst_acc().src_vfs().src_vft();
add_op(VuInstrK::MSUBAbc, "msuba").iemdt().bc().dst_mask().dst_acc().src_vfs().src_vft();
add_op(VuInstrK::MADDbc, "madd").iemdt().dst_mask().dss_fd_fs_ft().bc();
add_op(VuInstrK::SUBbc, "sub").iemdt().dst_mask().dss_fd_fs_ft().bc();
add_op(VuInstrK::OPMULA, "opmula").iemdt().dst_mask().dst_acc().src_vfs().src_vft();
add_op(VuInstrK::OPMSUB, "opmsub").iemdt().dst_mask().dss_fd_fs_ft();
add_op(VuInstrK::MUL, "mul").iemdt().dst_mask().dss_fd_fs_ft();
add_op(VuInstrK::MULq, "mul").iemdt().dst_mask().dst_vfd().src_vfs().src_q().vft_zero();
add_op(VuInstrK::SUB, "sub").iemdt().dst_mask().dss_fd_fs_ft();
add_op(VuInstrK::MSUBbc, "msub").iemdt().dst_mask().dss_fd_fs_ft().bc();
add_op(VuInstrK::MADDA, "madda").iemdt().dst_mask().dst_acc().src_vfs().src_vft();
add_op(VuInstrK::MULA, "mula").iemdt().dst_mask().dst_acc().src_vfs().src_vft();
add_op(VuInstrK::MINIbc, "mini").iemdt().dst_mask().bc().dss_fd_fs_ft();
add_op(VuInstrK::MAXi, "maxi").iemdt().dst_mask().dst_vfd().src_vfs().vft_zero().src_i();
add_op(VuInstrK::MINIi, "minii").iemdt().dst_mask().dst_vfd().src_vfs().vft_zero().src_i();
add_op(VuInstrK::ADDAbc, "adda").iemdt().dst_mask().bc().dst_vfs().src_vft();
add_op(VuInstrK::CLIP, "clip").iemdt().dst_mask().bc().src_vfs().src_vft();
add_op(VuInstrK::MINI, "mini").iemdt().dst_mask().dss_fd_fs_ft();
add_op(VuInstrK::MAX, "max").iemdt().dst_mask().dss_fd_fs_ft();
add_op(VuInstrK::ADDA, "adda").iemdt().dst_mask().dst_acc().src_vfs().src_vft();
add_op(VuInstrK::MADD, "madd").iemdt().dst_mask().dss_fd_fs_ft();
add_op(VuInstrK::ADDq, "addq").iemdt().dst_mask().vft_zero().dst_vfd().src_vfs().src_q();
add_op(VuInstrK::MULi, "muli").iemdt().dst_mask().vft_zero().dst_vfd().src_vfs().src_i();
add_op(VuInstrK::ADDi, "addi").iemdt().dst_mask().vft_zero().dst_vfd().src_vfs().src_i();
add_op(VuInstrK::MULAq, "mula").iemdt().dst_mask().dst_acc().vft_zero().src_vfs().src_q();
m_lower_op6_table[0b000000].set(VuInstrK::LQ);
m_lower_op6_table[0b000001].set(VuInstrK::SQ);
m_lower_op6_table[0b000100].set(VuInstrK::ILW);
m_lower_op6_table[0b000101].set(VuInstrK::ISW);
m_lower_op6_table[0b001000].set(VuInstrK::IADDIU);
m_lower_op6_table[0b001001].set(VuInstrK::ISUBIU);
// m_lower_op6_table[0b010000].set(VuInstrK::FCEQ);
m_lower_op6_table[0b010001].set(VuInstrK::FCSET);
m_lower_op6_table[0b010010].set(VuInstrK::FCAND);
m_lower_op6_table[0b010011].set(VuInstrK::FCOR);
// m_lower_op6_table[0b010100].set(VuInstrK::FSEQ);
// m_lower_op6_table[0b010101].set(VuInstrK::FSSET);
m_lower_op6_table[0b010110].set(VuInstrK::FSAND);
// m_lower_op6_table[0b010111].set(VuInstrK::FSOR);
// m_lower_op6_table[0b011000].set(VuInstrK::FMEQ);
// ??
m_lower_op6_table[0b011010].set(VuInstrK::FMAND);
// m_lower_op6_table[0b011011].set(VuInstrK::FMOR);
m_lower_op6_table[0b011100].set(VuInstrK::FCGET);
// ??
m_lower_op6_table[0b100000].set(VuInstrK::B);
m_lower_op6_table[0b100001].set(VuInstrK::BAL);
m_lower_op6_table[0b100100].set(VuInstrK::JR);
m_lower_op6_table[0b100101].set(VuInstrK::JALR);
m_lower_op6_table[0b101000].set(VuInstrK::IBEQ);
m_lower_op6_table[0b101001].set(VuInstrK::IBNE);
m_lower_op6_table[0b101100].set(VuInstrK::IBLTZ);
m_lower_op6_table[0b101101].set(VuInstrK::IBGTZ);
m_lower_op6_table[0b101110].set(VuInstrK::IBLEZ);
m_lower_op6_table[0b101111].set(VuInstrK::IBGEZ);
add_op(VuInstrK::IBNE, "ibne").dst_mask_zero().src_vit().src_vis().rel_branch11();
add_op(VuInstrK::LQ, "lq").dst_mask().dst_vft().src_imm11_load_store().src_vis();
add_op(VuInstrK::ILW, "ilw").dst_mask().dst_vit().src_imm11_load_store().src_vis();
add_op(VuInstrK::IADDIU, "iaddiu").dst_vit().src_vis().src_imm15_unsigned();
add_op(VuInstrK::IADDI, "iaddi").dst_vit().src_vis().src_imm5_signed().dst_mask_zero();
add_op(VuInstrK::IOR, "ior").dst_vid().src_vis().src_vit().dst_mask_zero();
add_op(VuInstrK::SQI, "sqi").dst_vfs().src_vit().dst_mask();
add_op(VuInstrK::ISW, "isw").src_vit().src_imm11_load_store().src_vis().dst_mask();
add_op(VuInstrK::LQI, "lqi").dst_mask().dst_vft().src_vis();
add_op(VuInstrK::IADD, "iadd").dst_mask_zero().dst_vid().src_vis().src_vit();
add_op(VuInstrK::XGKICK, "xgkick").dst_mask_zero().vft_zero().src_vis();
add_op(VuInstrK::ISUB, "isub").dst_mask_zero().dst_vid().src_vis().src_vit();
add_op(VuInstrK::SQ, "sq").dst_mask().dst_vfs().src_imm11_load_store().src_vit();
add_op(VuInstrK::FMAND, "fmand").imm15_zero().dst_vit().src_vis();
add_op(VuInstrK::DIV, "div").ftf_1().fsf_0().dst_q().src_vfs().src_vft();
add_op(VuInstrK::MOVE, "move").dst_mask().dst_vft().src_vfs();
add_op(VuInstrK::MR32, "mr32").dst_mask().dst_vft().src_vfs();
add_op(VuInstrK::RSQRT, "rsqrt").ftf_1().fsf_0().dst_q().src_vfs().src_vft();
add_op(VuInstrK::ILWR, "ilwr").dst_mask().dst_vit().src_vis();
add_op(VuInstrK::MTIR, "mtir").ftf_zero().fsf_0().dst_vit().src_vfs();
add_op(VuInstrK::JR, "jr").dst_mask_zero().vit_zero().src_vis().imm11_zero();
add_op(VuInstrK::IAND, "iand").dst_mask_zero().dst_vid().src_vis().src_vit();
add_op(VuInstrK::IBEQ, "ibeq").src_vit().src_vis().dst_mask_zero().rel_branch11();
add_op(VuInstrK::B, "b").dst_mask_zero().vit_zero().vis_zero().rel_branch11();
// add_op(VuInstrK::XITOP, "xitop").dst_mask_zero().vis_zero().src_vit();
add_op(VuInstrK::XTOP, "xtop").dst_mask_zero().vis_zero().src_vit();
add_op(VuInstrK::BAL, "bal").dst_mask_zero().vis_zero().dst_vit().rel_branch11();
add_op(VuInstrK::MFIR, "mfir").dst_mask().dst_vft().src_vis();
add_op(VuInstrK::IBGTZ, "ibgtz").dst_mask_zero().vit_zero().src_vis().rel_branch11();
add_op(VuInstrK::FCGET, "fcget").imm15_zero().vis_zero().dst_vit();
add_op(VuInstrK::ISUBIU, "isubiu").dst_vit().src_vis().imm15_unsigned();
add_op(VuInstrK::FSAND, "fsand").dst_vit().imm15_unsigned().vis_zero(); // really imm12.
add_op(VuInstrK::IBLTZ, "ibltz").dst_mask_zero().vit_zero().src_vis().rel_branch11();
add_op(VuInstrK::FCSET, "fcset").src_imm24_unsigned();
add_op(VuInstrK::FCAND, "fcand vi01,").src_imm24_unsigned();
add_op(VuInstrK::FCOR, "fcor vi01,").src_imm24_unsigned();
add_op(VuInstrK::IBGEZ, "ibgez").dst_mask_zero().vit_zero().src_vis().rel_branch11();
add_op(VuInstrK::ISWR, "iswr").dst_mask().src_vit().src_vis();
add_op(VuInstrK::JALR, "jalr").dst_mask_zero().dst_vit().src_vis().imm11_zero();
add_op(VuInstrK::WAITP, "waitp").dst_mask_zero().vft_zero().vfs_zero();
add_op(VuInstrK::WAITQ, "waitq").dst_mask_zero().vft_zero().vfs_zero();
add_op(VuInstrK::IBLEZ, "iblez").dst_mask_zero().vit_zero().src_vis().rel_branch11();
add_op(VuInstrK::SQRT, "sqrt").fsf_zero().ftf_0().vis_zero().dst_q().src_vft();
add_op(VuInstrK::SQD, "sqd").dst_mask().src_vfs().src_vit();
add_op(VuInstrK::ERLENG, "erleng").dst_mask().vft_zero().src_vfs().dst_p();
add_op(VuInstrK::ELENG, "eleng").dst_mask().vft_zero().src_vfs().dst_p();
add_op(VuInstrK::MFP, "mfp").dst_mask().dst_vft().src_p();
}
/*!
* Add a VU operation to the decode table
*/
VuDisassembler::OpInfo& VuDisassembler::add_op(VuInstrK kind, const std::string& name) {
ASSERT((int)kind < (int)VuInstrK::INVALID);
auto& elt = m_op_info[(int)kind];
elt.name = name;
elt.known = true;
return elt;
}
/*!
* Decode a lower instruction kind
*/
VuInstrK VuDisassembler::lower_kind(u32 in) {
auto op = lower_op(in);
if (in == 0b10000000000000000000000000110000) {
return VuInstrK::LOWER_NOP;
}
if (op == 0b1000000) {
switch (in & 0b111111) {
case 0b110010:
return VuInstrK::IADDI;
case 0b110101:
return VuInstrK::IOR;
case 0b110000:
return VuInstrK::IADD;
case 0b110001:
return VuInstrK::ISUB;
case 0b110100:
return VuInstrK::IAND;
}
switch (in & 0b11111111111) {
case 0b01100'1111'00:
return VuInstrK::MOVE;
case 0b01100'1111'01:
return VuInstrK::MR32;
case 0b01101'1111'00:
return VuInstrK::LQI;
case 0b01101'1111'01:
return VuInstrK::SQI;
case 0b01101'1111'11:
return VuInstrK::SQD;
case 0b01110'1111'00:
return VuInstrK::DIV;
case 0b01110'1111'01:
return VuInstrK::SQRT;
case 0b01110'1111'10:
return VuInstrK::RSQRT;
case 0b01110'1111'11:
return VuInstrK::WAITQ;
case 0b01111'1111'00:
return VuInstrK::MTIR;
case 0b01111'1111'01:
return VuInstrK::MFIR;
case 0b01111'1111'10:
return VuInstrK::ILWR;
case 0b01111'1111'11:
return VuInstrK::ISWR;
case 0b11001'1111'00:
return VuInstrK::MFP;
case 0b11010'1111'00:
return VuInstrK::XTOP;
case 0b11011'1111'00:
return VuInstrK::XGKICK;
case 0b11100'1111'10:
return VuInstrK::ELENG;
case 0b11100'1111'11:
return VuInstrK::ERLENG;
case 0b11110'1111'11:
return VuInstrK::WAITP;
}
fmt::print("Unknown lower special: 0b{:b}\n", in);
ASSERT(false);
} else {
ASSERT((op & 0b1000000) == 0);
ASSERT(op < 64);
auto elt = m_lower_op6_table[(int)op];
if (!elt.known) {
fmt::print("Invalid lower op6: 0b{:b} 0b{:b} 0x{:x}\n", op, in, in);
ASSERT(false);
}
return elt.kind;
}
}
/*!
* Decode an upper instruction kind
*/
VuInstrK VuDisassembler::upper_kind(u32 in) {
auto& upper_info = m_upper_op6_table[upper_op6(in)];
if (upper_info.goto_11) {
switch (upper_op11(in)) {
case 0b00000'1111'00:
case 0b00000'1111'01:
case 0b00000'1111'10:
case 0b00000'1111'11:
return VuInstrK::ADDAbc;
case 0b00010'1111'00:
case 0b00010'1111'01:
case 0b00010'1111'10:
case 0b00010'1111'11:
return VuInstrK::MADDAbc;
case 0b00011'1111'00:
case 0b00011'1111'01:
case 0b00011'1111'10:
case 0b00011'1111'11:
return VuInstrK::MSUBAbc;
case 0b00100'1111'00:
return VuInstrK::ITOF0;
case 0b00100'1111'10:
return VuInstrK::ITOF12;
case 0b00100'1111'11:
return VuInstrK::ITOF15;
case 0b00101'1111'00:
return VuInstrK::FTOI0;
case 0b00101'1111'01:
return VuInstrK::FTOI4;
case 0b00101'1111'10:
return VuInstrK::FTOI12;
case 0b00110'1111'00:
case 0b00110'1111'01:
case 0b00110'1111'10:
case 0b00110'1111'11:
return VuInstrK::MULAbc;
case 0b00111'1111'00:
return VuInstrK::MULAq;
case 0b00111'1111'11:
return VuInstrK::CLIP;
case 0b01010'1111'00:
return VuInstrK::ADDA;
case 0b01010'1111'01:
return VuInstrK::MADDA;
case 0b01010'1111'10:
return VuInstrK::MULA;
case 0b01011'1111'10:
return VuInstrK::OPMULA;
case 0b01011'1111'11:
ASSERT(upper_dest_mask(in) == 0);
ASSERT(upper_fs(in) == 0);
ASSERT(upper_ft(in) == 0);
return VuInstrK::NOP;
break;
default:
fmt::print("Invalid op11: 0b{:b}\n", upper_op11(in));
ASSERT(false);
}
}
if (!upper_info.known) {
fmt::print("Invalid upper op6: 0b{:b}\n", upper_op6(in));
ASSERT(false);
}
return upper_info.kind;
}
/*!
* Get the mask applied to instruction offsets.
*/
s32 VuDisassembler::get_instruction_index_mask() {
switch (m_kind) {
case VU0:
return (4096 / 8) - 1;
case VU1:
return (16384 / 8) - 1;
default:
ASSERT(false);
}
}
VuProgram VuDisassembler::disassemble(void* data, int size_bytes, bool debug_print) {
auto bytes = (u8*)data;
// should be 8 byte aligned size.
ASSERT((size_bytes & 0x7) == 0);
VuProgram prog;
int instruction_count = size_bytes / 8;
for (int i = 0; i < instruction_count; i++) {
u32 lower, upper;
memcpy(&lower, bytes + i * 8, 4);
memcpy(&upper, bytes + i * 8 + 4, 4);
// decode
auto upper_instr = decode(upper_kind(upper), upper, i);
auto lower_instr = upper_instr.i_bit() ? VuInstruction::make_fp_constant(lower)
: decode(lower_kind(lower), lower, i);
prog.add_instruction(upper_instr, lower_instr);
// debug
if (debug_print) {
fmt::print("{}\n", to_string(VuInstructionPair{upper_instr, lower_instr}));
}
}
name_labels();
if (debug_print) {
fmt::print("----------------------------------\n");
fmt::print("{}\n", to_string(prog));
}
return prog;
}
VuInstruction VuDisassembler::decode(VuInstrK kind, u32 data, int instr_idx) {
VuInstruction instr;
instr.kind = kind;
auto& inst = info(kind);
if (!inst.known) {
fmt::print("instr idx {} is unknown\n", (int)kind);
ASSERT(false);
}
for (auto& step : inst.decode) {
s64 value = -1;
switch (step.field) {
case VuDecodeStep::FieldK::IEMDT:
value = data >> 25;
ASSERT((value & 3) == 0);
break;
case VuDecodeStep::FieldK::DST_MASK:
value = upper_dest_mask(data);
break;
case VuDecodeStep::FieldK::FS:
value = upper_fs(data);
break;
case VuDecodeStep::FieldK::FT:
value = upper_ft(data);
break;
case VuDecodeStep::FieldK::FD:
value = upper_fd(data);
break;
case VuDecodeStep::FieldK::BC:
value = upper_bc(data);
break;
case VuDecodeStep::FieldK::NONE:
break;
case VuDecodeStep::FieldK::IMM11_BRANCH: {
s32 signed_11 = upper_op11(data) << 21;
signed_11 >>= 21;
s32 offset = signed_11 + instr_idx + 1;
offset &= 2047;
value = add_label(offset);
} break;
case VuDecodeStep::FieldK::IMM11_SIGNED: {
s32 signed_value = (data << 21);
signed_value = (signed_value >> 21);
value = signed_value;
} break;
case VuDecodeStep::FieldK::IMM15_UNSIGNED:
value = upper_imm15_unsigned(data);
break;
case VuDecodeStep::FieldK::IMM5_SIGNED: {
s32 signed_value = (data << 21);
value = (signed_value >> 27);
break;
}
case VuDecodeStep::FieldK::FTF:
value = (data >> 23) & 0b11;
break;
case VuDecodeStep::FieldK::FSF:
value = (data >> 21) & 0b11;
break;
case VuDecodeStep::FieldK::IMM24_UNSIGNED:
value = (data & 0b1111'1111'1111'1111'1111'1111);
break;
default:
ASSERT(false);
}
switch (step.atom) {
case VuDecodeStep::AtomK::IEMDT:
instr.iemdt = value;
break;
case VuDecodeStep::AtomK::DST_MASK:
instr.mask = value;
break;
case VuDecodeStep::AtomK::DST_VF:
ASSERT(!instr.dst);
instr.dst = VuInstructionAtom::make_vf(value);
break;
case VuDecodeStep::AtomK::DST_VI:
ASSERT(!instr.dst);
instr.dst = VuInstructionAtom::make_vi(value);
break;
case VuDecodeStep::AtomK::SRC_VF:
instr.src.push_back(VuInstructionAtom::make_vf(value));
break;
case VuDecodeStep::AtomK::BC:
ASSERT(!instr.bc);
instr.bc = value;
break;
case VuDecodeStep::AtomK::ASSERT_ZERO:
ASSERT(value == 0);
break;
case VuDecodeStep::AtomK::SRC_VI:
instr.src.push_back(VuInstructionAtom::make_vi(value));
break;
case VuDecodeStep::AtomK::BRANCH_TARGET:
instr.src.push_back(VuInstructionAtom::make_label(value));
break;
case VuDecodeStep::AtomK::LOAD_STORE_OFFSET:
instr.src.push_back(VuInstructionAtom::make_load_store_imm(value));
break;
case VuDecodeStep::AtomK::SRC_IMM:
instr.src.push_back(VuInstructionAtom::make_imm(value));
break;
case VuDecodeStep::AtomK::DST_ACC:
ASSERT(!instr.dst);
instr.dst = VuInstructionAtom::make_acc();
break;
case VuDecodeStep::AtomK::DST_Q:
ASSERT(!instr.dst);
instr.dst = VuInstructionAtom::make_q();
break;
case VuDecodeStep::AtomK::DST_P:
ASSERT(!instr.dst);
instr.dst = VuInstructionAtom::make_p();
break;
case VuDecodeStep::AtomK::SRC_Q:
instr.src.push_back(VuInstructionAtom::make_q());
break;
case VuDecodeStep::AtomK::SRC_I:
instr.src.push_back(VuInstructionAtom::make_i());
break;
case VuDecodeStep::AtomK::SRC_P:
instr.src.push_back(VuInstructionAtom::make_p());
break;
case VuDecodeStep::AtomK::SECOND_SOURCE_FIELD:
instr.second_src_field = value;
break;
case VuDecodeStep::AtomK::FIRST_SOURCE_FIELD:
instr.first_src_field = value;
break;
default:
ASSERT(false);
}
}
return instr;
}
namespace {
char bc_to_part(int x) {
switch (x) {
case 0:
return 'x';
case 1:
return 'y';
case 2:
return 'z';
case 3:
return 'w';
default:
return '?';
}
}
std::string mask_to_string(u8 val) {
std::string result;
if (val & 8) {
result += 'x';
}
if (val & 4) {
result += 'y';
}
if (val & 2) {
result += 'z';
}
if (val & 1) {
result += 'w';
}
return result;
}
std::string vf_src(const std::string& name, bool mips2c_format) {
if (mips2c_format) {
return fmt::format("c->vf_src({}).vf", name);
} else {
return fmt::format("vu.{}", name);
}
}
std::string vf_dst(const std::string& name, bool mips2c_format) {
if (mips2c_format) {
return fmt::format("c->vfs[{}].vf", name);
} else {
return fmt::format("vu.{}", name);
}
}
std::string vi_src(const std::string& name, bool mips2c_format) {
if (mips2c_format) {
return fmt::format("vis[{}]", name);
} else {
return fmt::format("vu.{}", name);
}
}
} // namespace
int unk = 0;
std::string VuDisassembler::to_cpp(const VuInstruction& instr, bool mips2c_format) const {
switch (instr.kind) {
case VuInstrK::NOP:
case VuInstrK::LOWER_NOP:
return "/* nop */";
case VuInstrK::LQ:
if (instr.src.at(1).is_int_reg(0)) {
return fmt::format("lq_buffer(Mask::{}, vu.{}, {});", mask_to_string(*instr.mask),
instr.dst->to_string(m_label_names),
instr.src.at(0).to_string(m_label_names));
} else if (instr.src.at(0).value() == 0) {
return fmt::format(mips2c_format ? "lq_buffer(Mask::{}, c->vfs[{}].vf, vis[{}]);"
: "lq_buffer(Mask::{}, vu.{}, vu.{});",
mask_to_string(*instr.mask), instr.dst->to_string(m_label_names),
instr.src.at(1).to_string(m_label_names));
} else {
return fmt::format(mips2c_format ? "lq_buffer(Mask::{}, c->vfs[{}].vf, vis[{}] + {});"
: "lq_buffer(Mask::{}, vu.{}, vu.{} + {});",
mask_to_string(*instr.mask), instr.dst->to_string(m_label_names),
instr.src.at(1).to_string(m_label_names),
instr.src.at(0).to_string(m_label_names));
}
goto unknown;
case VuInstrK::LQI:
ASSERT(!instr.src.at(0).is_int_reg(0));
return fmt::format(mips2c_format ? "lq_buffer(Mask::{}, c->vfs[{}].vf, vis[{}]++);"
: "lq_buffer(Mask::{}, vu.{}, vu.{}++);",
mask_to_string(*instr.mask), instr.dst->to_string(m_label_names),
instr.src.at(0).to_string(m_label_names));
case VuInstrK::SQI:
ASSERT(!instr.src.at(0).is_int_reg(0));
if (mips2c_format) {
return fmt::format("sq_buffer(Mask::{}, {}, vis[{}]++);", mask_to_string(*instr.mask),
vf_src(instr.dst->to_string(m_label_names), mips2c_format),
instr.src.at(0).to_string(m_label_names));
} else {
return fmt::format("sq_buffer(Mask::{}, vu.{}, vu.{}++);", mask_to_string(*instr.mask),
instr.dst->to_string(m_label_names),
instr.src.at(0).to_string(m_label_names));
}
case VuInstrK::SQ:
if (instr.src.at(1).is_int_reg(0)) {
return fmt::format("sq_buffer(Mask::{}, vu.{}, {});", mask_to_string(*instr.mask),
instr.dst->to_string(m_label_names),
instr.src.at(0).to_string(m_label_names));
} else if (instr.src.at(0).value() == 0) {
return fmt::format(mips2c_format ? "sq_buffer(Mask::{}, c->vf_src({}).vf, vis[{}]);"
: "sq_buffer(Mask::{}, vu.{}, vu.{});",
mask_to_string(*instr.mask), instr.dst->to_string(m_label_names),
instr.src.at(1).to_string(m_label_names));
} else {
return fmt::format(mips2c_format ? "sq_buffer(Mask::{}, c->vf_src({}).vf, vis[{}] + {});"
: "sq_buffer(Mask::{}, vu.{}, vu.{} + {});",
mask_to_string(*instr.mask), instr.dst->to_string(m_label_names),
instr.src.at(1).to_string(m_label_names),
instr.src.at(0).to_string(m_label_names));
}
goto unknown;
case VuInstrK::IADDI:
if (instr.src.at(0).is_int_reg(0)) {
return fmt::format("vu.{} = {};", instr.dst->to_string(m_label_names),
(s16)instr.src.at(1).value());
} else {
return fmt::format("vu.{} = vu.{} + {};", instr.dst->to_string(m_label_names),
instr.src.at(0).to_string(m_label_names), (s16)instr.src.at(1).value());
}
case VuInstrK::IADDIU:
ASSERT(!instr.dst->is_int_reg(0));
if (instr.src.at(0).is_int_reg(0)) {
if (mips2c_format) {
return fmt::format("vis[{}] = 0x{:x}; /* {} */", instr.dst->to_string(m_label_names),
(u16)instr.src.at(1).value(), instr.src.at(1).value());
} else {
return fmt::format("vu.{} = 0x{:x}; /* {} */", instr.dst->to_string(m_label_names),
(u16)instr.src.at(1).value(), instr.src.at(1).value());
}
} else {
if (mips2c_format) {
return fmt::format("vis[{}] = vis[{}] + 0x{:x}; /* {} */",
instr.dst->to_string(m_label_names),
instr.src.at(0).to_string(m_label_names), (u16)instr.src.at(1).value(),
instr.src.at(1).value());
} else {
return fmt::format("vu.{} = vu.{} + 0x{:x}; /* {} */",
instr.dst->to_string(m_label_names),
instr.src.at(0).to_string(m_label_names), (u16)instr.src.at(1).value(),
instr.src.at(1).value());
}
}
case VuInstrK::ISW:
if (instr.src.at(2).is_int_reg(0)) {
return fmt::format("isw_buffer(Mask::{}, vu.{}, {});", mask_to_string(*instr.mask),
instr.src.at(0).to_string(m_label_names),
instr.src.at(1).to_string(m_label_names));
} else {
return fmt::format("isw_buffer(Mask::{}, vu.{}, vu.{} + {});", mask_to_string(*instr.mask),
instr.src.at(0).to_string(m_label_names),
instr.src.at(2).to_string(m_label_names),
instr.src.at(1).to_string(m_label_names));
}
goto unknown;
case VuInstrK::ISWR:
return fmt::format("isw_buffer(Mask::{}, vu.{}, vu.{});", mask_to_string(*instr.mask),
instr.src.at(0).to_string(m_label_names),
instr.src.at(1).to_string(m_label_names));
case VuInstrK::ILWR:
return fmt::format("ilw_buffer(Mask::{}, vu.{}, vu.{});", mask_to_string(*instr.mask),
instr.dst->to_string(m_label_names),
instr.src.at(0).to_string(m_label_names));
case VuInstrK::ILW:
if (instr.src.at(1).is_int_reg(0)) {
return fmt::format("ilw_buffer(Mask::{}, vu.{}, {});", mask_to_string(*instr.mask),
instr.dst->to_string(m_label_names),
instr.src.at(0).to_string(m_label_names));
} else {
return fmt::format("ilw_buffer(Mask::{}, vu.{}, vu.{} + {});", mask_to_string(*instr.mask),
instr.dst->to_string(m_label_names),
instr.src.at(1).to_string(m_label_names),
instr.src.at(0).to_string(m_label_names));
}
case VuInstrK::ISUBIU:
if (instr.src.at(0).is_int_reg(0)) {
return fmt::format("vu.{} = -{};", instr.dst->to_string(m_label_names),
instr.src.at(1).value());
} else {
return fmt::format("vu.{} = vu.{} - 0x{:x}; /* {} */", instr.dst->to_string(m_label_names),
instr.src.at(0).to_string(m_label_names), (u16)instr.src.at(1).value(),
instr.src.at(1).value());
}
case VuInstrK::MTIR:
return fmt::format(
mips2c_format ? "vis[{}] = c->vf_src({}).vf.{}_as_u16();" : "vu.{} = vu.{}.{}_as_u16();",
instr.dst->to_string(m_label_names), instr.src.at(0).to_string(m_label_names),
bc_to_part(*instr.first_src_field));
case VuInstrK::MFIR:
return fmt::format("vu.{}.mfir(Mask::{}, vu.{});", instr.dst->to_string(m_label_names),
mask_to_string(*instr.mask), instr.src.at(0).to_string(m_label_names));
case VuInstrK::B:
return fmt::format("bc = true;", instr.src.at(0).to_string(m_label_names));
case VuInstrK::IBGTZ:
return fmt::format("bc = ((s16)vu.{}) > 0;", instr.src.at(0).to_string(m_label_names));
case VuInstrK::IBLTZ:
return fmt::format("bc = ((s16)vu.{}) < 0;", instr.src.at(0).to_string(m_label_names));
case VuInstrK::IBLEZ:
return fmt::format("bc = ((s16)vu.{}) <= 0;", instr.src.at(0).to_string(m_label_names));
case VuInstrK::IBGEZ:
return fmt::format("bc = ((s16)vu.{}) >= 0;", instr.src.at(0).to_string(m_label_names));
case VuInstrK::IBEQ:
ASSERT(!instr.src.at(1).is_int_reg(0));
if (instr.src.at(0).is_int_reg(0)) {
return fmt::format("bc = ({} == 0);",
vi_src(instr.src.at(1).to_string(m_label_names), mips2c_format));
} else {
return fmt::format("bc = ({} == {});",
vi_src(instr.src.at(0).to_string(m_label_names), mips2c_format),
vi_src(instr.src.at(1).to_string(m_label_names), mips2c_format));
}
case VuInstrK::IBNE:
ASSERT(!instr.src.at(1).is_int_reg(0));
if (instr.src.at(0).is_int_reg(0)) {
return fmt::format("bc = ({} != 0);",
vi_src(instr.src.at(1).to_string(m_label_names), mips2c_format));
} else {
return fmt::format("bc = ({} != {});",
vi_src(instr.src.at(0).to_string(m_label_names), mips2c_format),
vi_src(instr.src.at(1).to_string(m_label_names), mips2c_format));
}
case VuInstrK::IADD:
ASSERT(!instr.src.at(1).is_int_reg(0));
ASSERT(!instr.src.at(0).is_int_reg(0));
ASSERT(!instr.dst->is_int_reg(0));
return fmt::format(mips2c_format ? "vis[{}] = vis[{}] + vis[{}];" : "vu.{} = vu.{} + vu.{};",
instr.dst->to_string(m_label_names),
instr.src.at(0).to_string(m_label_names),
instr.src.at(1).to_string(m_label_names));
case VuInstrK::ISUB:
return fmt::format("vu.{} = vu.{} - vu.{};", instr.dst->to_string(m_label_names),
instr.src.at(0).to_string(m_label_names),
instr.src.at(1).to_string(m_label_names));
case VuInstrK::IAND:
ASSERT(!instr.src.at(1).is_int_reg(0));
ASSERT(!instr.src.at(0).is_int_reg(0));
ASSERT(!instr.dst->is_int_reg(0));
return fmt::format("{} = {} & {};",
vi_src(instr.dst->to_string(m_label_names), mips2c_format),
vi_src(instr.src.at(0).to_string(m_label_names), mips2c_format),
vi_src(instr.src.at(1).to_string(m_label_names), mips2c_format));
case VuInstrK::IOR:
if (instr.src.at(1).is_int_reg(0)) {
if (instr.src.at(0).is_int_reg(0) && instr.src.at(1).is_int_reg(0)) {
return fmt::format("vu.{} = 0;", instr.dst->to_string(m_label_names));
} else {
ASSERT(!instr.dst->is_int_reg(0));
ASSERT(!instr.src.at(0).is_int_reg(0));
if (mips2c_format) {
return fmt::format("vis[{}] = vis[{}];", instr.dst->to_string(m_label_names),
instr.src.at(0).to_string(m_label_names));
} else {
return fmt::format("vu.{} = vu.{};", instr.dst->to_string(m_label_names),
instr.src.at(0).to_string(m_label_names));
}
}
} else {
return fmt::format("vu.{} = vu.{} | vu.{};", instr.dst->to_string(m_label_names),
instr.src.at(0).to_string(m_label_names),
instr.src.at(1).to_string(m_label_names));
}
case VuInstrK::MFP:
return fmt::format("vu.{}.mfp(Mask::{}, vu.P);", instr.dst->to_string(m_label_names),
mask_to_string(*instr.mask));
case VuInstrK::MULq:
return fmt::format(mips2c_format ? "c->vfs[{}].vf.mul(Mask::{}, c->vf_src({}).vf, c->Q);"
: "vu.{}.mul(Mask::{}, vu.{}, vu.Q);",
instr.dst->to_string(m_label_names), mask_to_string(*instr.mask),
instr.src.at(0).to_string(m_label_names));
case VuInstrK::MULi:
return fmt::format(mips2c_format ? "c->vfs[{}].vf.mul(Mask::{}, c->vf_src({}).vf, c->I);"
: "vu.{}.mul(Mask::{}, vu.{}, vu.I);",
instr.dst->to_string(m_label_names), mask_to_string(*instr.mask),
instr.src.at(0).to_string(m_label_names));
case VuInstrK::DIV:
return fmt::format(
"vu.Q = vu.{}.{}() / vu.{}.{}();", instr.src.at(0).to_string(m_label_names),
bc_to_part(*instr.first_src_field), instr.src.at(1).to_string(m_label_names),
bc_to_part(*instr.second_src_field));
case VuInstrK::ERLENG:
return fmt::format("vu.P = erleng(vu.{});", instr.src.at(0).to_string(m_label_names));
case VuInstrK::ELENG:
return fmt::format("vu.P = eleng(vu.{});", instr.src.at(0).to_string(m_label_names));
case VuInstrK::RSQRT:
return fmt::format(
"c->Q = c->vf_src({}).vf.{}() / std::sqrt(c->vf_src({}).vf.{}());",
instr.src.at(0).to_string(m_label_names), bc_to_part(*instr.first_src_field),
instr.src.at(1).to_string(m_label_names), bc_to_part(*instr.second_src_field));
case VuInstrK::MR32:
case VuInstrK::MOVE:
case VuInstrK::ITOF0:
case VuInstrK::ITOF12:
case VuInstrK::ITOF15:
case VuInstrK::FTOI0:
case VuInstrK::FTOI4:
case VuInstrK::FTOI12:
return fmt::format("{}.{}(Mask::{}, {});",
vf_dst(instr.dst->to_string(m_label_names), mips2c_format),
info(instr.kind).name, mask_to_string(*instr.mask),
vf_src(instr.src.at(0).to_string(m_label_names), mips2c_format));
case VuInstrK::CLIP:
return fmt::format("ASSERT(false); cf = clip({}, {}.w(), cf);",
vf_src(instr.src.at(0).to_string(m_label_names), mips2c_format),
vf_src(instr.src.at(1).to_string(m_label_names), mips2c_format));
case VuInstrK::FCAND:
return fmt::format("fcand(vu.vi01, 0x{:x}, cf);\n", instr.src.at(0).value());
case VuInstrK::FCOR:
return fmt::format("fcor(vu.vi01, 0x{:x}, cf);\n", instr.src.at(0).value());
case VuInstrK::FCSET:
return fmt::format("cf = 0x{:x};\n", instr.src.at(0).value());
case VuInstrK::ADDbc:
case VuInstrK::SUBbc:
case VuInstrK::MULbc:
case VuInstrK::MINIbc:
case VuInstrK::MAXbc:
return fmt::format("{}.{}(Mask::{}, {}, {}.{}());",
vf_dst(instr.dst->to_string(m_label_names), mips2c_format),
info(instr.kind).name, mask_to_string(*instr.mask),
vf_src(instr.src.at(0).to_string(m_label_names), mips2c_format),
vf_src(instr.src.at(1).to_string(m_label_names), mips2c_format),
bc_to_part(*instr.bc));
case VuInstrK::FP_CONSTANT:
if (mips2c_format) {
return fmt::format("c->I = {};", float_to_string(instr.fp));
} else {
return fmt::format("vu.I = {};", float_to_string(instr.fp));
}
case VuInstrK::MINIi:
case VuInstrK::MAXi:
return fmt::format("{}.{}(Mask::{}, {}, {});",
vf_dst(instr.dst->to_string(m_label_names), mips2c_format),
info(instr.kind).name, mask_to_string(*instr.mask),
vf_src(instr.src.at(0).to_string(m_label_names), mips2c_format),
mips2c_format ? "c->I" : "vu.I");
case VuInstrK::SUB:
if (instr.dst.value().value() == instr.src.at(0).value() &&
instr.src.at(0).value() == instr.src.at(1).value() && instr.mask.value() == 0b1111) {
return fmt::format("vu.{}.set_zero();", instr.src.at(0).to_string(m_label_names));
} else {
return fmt::format("{}.{}(Mask::{}, {}, {});",
vf_dst(instr.dst->to_string(m_label_names), mips2c_format),
info(instr.kind).name, mask_to_string(*instr.mask),
vf_src(instr.src.at(0).to_string(m_label_names), mips2c_format),
vf_src(instr.src.at(1).to_string(m_label_names), mips2c_format));
}
break;
case VuInstrK::MUL:
case VuInstrK::ADD:
case VuInstrK::MAX:
case VuInstrK::MINI:
return fmt::format("{}.{}(Mask::{}, {}, {});",
vf_dst(instr.dst->to_string(m_label_names), mips2c_format),
info(instr.kind).name, mask_to_string(*instr.mask),
vf_src(instr.src.at(0).to_string(m_label_names), mips2c_format),
vf_src(instr.src.at(1).to_string(m_label_names), mips2c_format));
case VuInstrK::ADDAbc:
return fmt::format(mips2c_format
? "c->acc.vf.adda(Mask::{}, c->vfs[{}].vf, c->vfs[{}].vf.{}());"
: "vu.acc.adda(Mask::{}, vu.{}, vu.{}.{}());",
mask_to_string(*instr.mask), instr.dst->to_string(m_label_names),
instr.src.at(0).to_string(m_label_names), bc_to_part(*instr.bc));
case VuInstrK::MADDA:
return fmt::format("vu.acc.madda(Mask::{}, vu.{}, vu.{});", mask_to_string(*instr.mask),
instr.src.at(0).to_string(m_label_names),
instr.src.at(1).to_string(m_label_names));
case VuInstrK::MADDAbc:
return fmt::format(mips2c_format
? "c->acc.vf.madda(Mask::{}, c->vfs[{}].vf, c->vfs[{}].vf.{}());"
: "vu.acc.madda(Mask::{}, vu.{}, vu.{}.{}());",
mask_to_string(*instr.mask), instr.src.at(0).to_string(m_label_names),
instr.src.at(1).to_string(m_label_names), bc_to_part(*instr.bc));
case VuInstrK::MADDbc:
return fmt::format(
mips2c_format
? "c->acc.vf.madd(Mask::{}, c->vfs[{}].vf, c->vf_src({}).vf, c->vf_src({}).vf.{}());"
: "vu.acc.madd(Mask::{}, vu.{}, vu.{}, vu.{}.{}());",
mask_to_string(*instr.mask), instr.dst->to_string(m_label_names),
instr.src.at(0).to_string(m_label_names), instr.src.at(1).to_string(m_label_names),
bc_to_part(*instr.bc));
case VuInstrK::MSUBbc:
return fmt::format(
mips2c_format
? "c->acc.vf.msub(Mask::{}, c->vfs[{}].vf, c->vf_src({}).vf, c->vf_src({}).vf.{}());"
: "vu.acc.msub(Mask::{}, vu.{}, vu.{}, vu.{}.{}());",
mask_to_string(*instr.mask), instr.dst->to_string(m_label_names),
instr.src.at(0).to_string(m_label_names), instr.src.at(1).to_string(m_label_names),
bc_to_part(*instr.bc));
case VuInstrK::MULA:
return fmt::format("vu.acc.mula(Mask::{}, vu.{}, vu.{});", mask_to_string(*instr.mask),
instr.src.at(0).to_string(m_label_names),
instr.src.at(1).to_string(m_label_names));
case VuInstrK::MULAq:
return fmt::format("vu.acc.mula(Mask::{}, vu.{}, vu.Q);", mask_to_string(*instr.mask),
instr.src.at(0).to_string(m_label_names));
case VuInstrK::MULAbc:
return fmt::format(mips2c_format
? "c->acc.vf.mula(Mask::{}, c->vf_src({}).vf, c->vf_src({}).vf.{}());"
: "vu.acc.mula(Mask::{}, vu.{}, vu.{}.{}());",
mask_to_string(*instr.mask), instr.src.at(0).to_string(m_label_names),
instr.src.at(1).to_string(m_label_names), bc_to_part(*instr.bc));
case VuInstrK::XGKICK:
return fmt::format("xgkick(vu.{});", instr.src.at(0).to_string(m_label_names));
case VuInstrK::XTOP:
return fmt::format("vu.{} = xtop();", instr.src.at(0).to_string(m_label_names));
default:
unk++;
fmt::print("unknown 0 is {}\n", to_string(instr));
return "ASSERT(false);"; //"???";
}
unknown:
unk++;
fmt::print("unknown 1 is {}\n", to_string(instr));
return "ASSERT(false);";
}
std::string VuDisassembler::to_string(const VuInstruction& instr) const {
if (instr.kind == VuInstrK::FP_CONSTANT) {
return float_to_string(instr.fp);
}
auto& in = info(instr.kind);
if (!in.known) {
ASSERT(false);
}
std::string result;
result += in.name;
if (instr.bc) {
result += bc_to_part(*instr.bc);
}
if (instr.mask) {
u8 val = *instr.mask;
result += '.';
if (val & 8) {
result += 'x';
}
if (val & 4) {
result += 'y';
}
if (val & 2) {
result += 'z';
}
if (val & 1) {
result += 'w';
}
}
bool comma = false;
if (instr.dst) {
result += " ";
result += instr.dst->to_string(m_label_names);
result += ',';
comma = true;
}
bool close = false;
int idx = 0;
for (auto& src : instr.src) {
if (close) {
} else {
result += " ";
}
result += src.to_string(m_label_names);
if (idx == 0 && instr.first_src_field) {
result += '.';
result += bc_to_part(*instr.first_src_field);
}
if (idx == 1 && instr.second_src_field) {
result += '.';
result += bc_to_part(*instr.second_src_field);
}
if (src.kind() == VuInstructionAtom::Kind::LOAD_STORE_IMM) {
result += '(';
close = true;
} else {
if (close) {
result += ")";
close = false;
comma = false;
} else {
result += ',';
comma = true;
}
}
idx++;
}
ASSERT(!close);
if (comma) {
result.pop_back();
}
if (instr.iemdt) {
u8 val = *instr.iemdt;
if (val & 0b100) {
result += " :t";
}
if (val & 0b1000) {
result += " :d";
}
if (val & 0b10000) {
result += " :m";
}
if (val & 0b100000) {
result += " :e";
}
if (val & 0b1000000) {
result += " :i";
}
}
return result;
}
std::string VuDisassembler::to_string(const VuInstructionPair& pair) const {
return fmt::format(" {:25s} | {:25s}", to_string(pair.lower), to_string(pair.upper));
}
std::string VuDisassembler::to_string(const VuProgram& prog) const {
std::string result;
for (int i = 0; i < (int)prog.instructions().size(); i++) {
auto lab = m_labels.find(i);
if (lab != m_labels.end()) {
result += m_label_names.at(lab->second);
result += ':';
result += '\n';
}
// result += fmt::format("{} ;; 0x{:x}", to_string(prog.instructions().at(i)), i);
result += to_string(prog.instructions().at(i));
result += '\n';
}
return result;
}
int VuDisassembler::add_label(int instr) {
auto existing = m_labels.find(instr);
if (existing == m_labels.end()) {
int new_idx = m_labels.size();
m_labels[instr] = new_idx;
return new_idx;
} else {
return existing->second;
}
}
void VuDisassembler::add_label_with_name(int instr, const std::string& name) {
add_label(instr);
m_user_named_instructions[instr] = name;
}
void VuDisassembler::name_labels() {
std::vector<int> instrs_with_labels;
for (auto [instr, label_idx] : m_labels) {
instrs_with_labels.push_back(instr);
}
m_label_names.resize(instrs_with_labels.size());
std::sort(instrs_with_labels.begin(), instrs_with_labels.end());
int idx = 1;
for (auto& instr : instrs_with_labels) {
auto label_idx = m_labels.at(instr);
m_label_names.at(label_idx) = fmt::format("L{}", idx++);
}
for (auto& kv : m_user_named_instructions) {
m_label_names.at(m_labels.at(kv.first)) = kv.second;
}
}
bool has_branch_delay(const VuInstructionPair& pair) {
switch (pair.lower.kind) {
case VuInstrK::JALR:
// case VuInstrK::JR: it does, but it's not supported
case VuInstrK::IBGTZ:
case VuInstrK::IBNE:
case VuInstrK::IBEQ:
case VuInstrK::B:
case VuInstrK::BAL:
case VuInstrK::IBLTZ:
case VuInstrK::IBLEZ:
case VuInstrK::IBGEZ:
return true;
default:
return false;
}
}
std::string get_label_name(const VuInstructionPair& pair,
const std::vector<std::string>& label_names) {
for (auto& arg : pair.lower.src) {
if (arg.kind() == VuInstructionAtom::Kind::LABEL) {
return arg.to_string(label_names);
}
}
ASSERT(false);
}
std::string VuDisassembler::to_string_with_cpp(const VuProgram& prog, bool mips2c_format) const {
std::string result;
for (int i = 0; i < (int)prog.instructions().size(); i++) {
auto lab = m_labels.find(i);
if (lab != m_labels.end()) {
result += m_label_names.at(lab->second);
result += ':';
result += '\n';
}
auto& pair = prog.instructions().at(i);
if (has_branch_delay(pair) && pair.lower.kind != VuInstrK::JALR) {
result += " // BRANCH!\n";
// set bc
result += to_string_with_cpp(prog.instructions().at(i), mips2c_format, i);
result += "\n";
result += to_string_with_cpp(prog.instructions().at(i + 1), mips2c_format, i + 1);
result += "\n";
result += fmt::format(" if (bc) {{ goto {}; }}", get_label_name(pair, m_label_names));
result += "\n\n";
i++;
} else {
result += to_string_with_cpp(prog.instructions().at(i), mips2c_format, i);
result += '\n';
}
if (i > 0) {
const auto& prev = prog.instructions().at(i - 1);
bool has_ebit = false;
if (prev.lower.iemdt && (*prev.lower.iemdt & 0b100000)) {
has_ebit = true;
}
if (prev.upper.iemdt && (*prev.upper.iemdt & 0b100000)) {
has_ebit = true;
}
if (has_ebit) {
result += "return;\n\n";
}
}
}
fmt::print("TOTAL unk: {}\n", unk);
return result;
}
namespace {
bool is_nop(const VuInstruction& i) {
return i.kind == VuInstrK::NOP || i.kind == VuInstrK::LOWER_NOP;
}
} // namespace
std::string VuDisassembler::to_string_with_cpp(const VuInstructionPair& pair,
bool mips2c_format,
int idx) const {
std::string result;
result +=
fmt::format(" // {:25s} | {:30s} {}\n", to_string(pair.lower), to_string(pair.upper), idx);
if (!is_nop(pair.lower) && !is_nop(pair.upper) && pair.lower.kind == VuInstrK::FP_CONSTANT) {
result += fmt::format(" {:25s}", to_cpp(pair.upper, mips2c_format));
result += fmt::format(" {:25s}", to_cpp(pair.lower, mips2c_format));
} else {
if (!is_nop(pair.upper)) {
result += fmt::format(" {:25s}", to_cpp(pair.upper, mips2c_format));
}
if (!is_nop(pair.lower)) {
result += fmt::format(" {:25s}", to_cpp(pair.lower, mips2c_format));
}
}
return result;
}
} // namespace decompiler
| 38.374613 | 100 | 0.584812 | [
"vector"
] |
786a8fae0e8bfa293a5373606e4af84d1c439680 | 8,693 | cpp | C++ | src/scripting/GameOptions.cpp | prospectdwell/CyberEngineTweaks | cfdfaef15f92512733d39336855281b78e9b3a14 | [
"MIT",
"Unlicense"
] | 2,521 | 2020-12-13T12:46:26.000Z | 2020-12-21T11:12:09.000Z | src/scripting/GameOptions.cpp | prospectdwell/CyberEngineTweaks | cfdfaef15f92512733d39336855281b78e9b3a14 | [
"MIT",
"Unlicense"
] | 203 | 2020-12-13T12:43:46.000Z | 2020-12-21T11:13:09.000Z | src/scripting/GameOptions.cpp | prospectdwell/CyberEngineTweaks | cfdfaef15f92512733d39336855281b78e9b3a14 | [
"MIT",
"Unlicense"
] | 100 | 2020-12-13T23:45:57.000Z | 2020-12-21T11:07:59.000Z | #include <stdafx.h>
#include "GameOptions.h"
static TiltedPhoques::Vector<GameOption*> s_gameOptions;
std::string GameOption::GetInfo()
{
std::stringstream ret;
if (pCategory)
ret << pCategory << "/";
if (pName)
ret << pName;
ret << " = ";
ret << GetString();
return ret.str();
}
std::string GameOption::GetString()
{
std::stringstream ret;
if (GetType() == kBoolean)
{
ret << (Boolean ? "true" : "false");
}
else if (GetType() == kInteger)
{
ret << Integer.Value;
}
else if (GetType() == kFloat)
{
ret << std::to_string(Float.Value);
}
else if(GetType() == kString)
{
ret << "\"" << String.c_str() << "\"";
}
else if(GetType() == kColor)
{
ret << "0x" << std::hex << Integer.Value << std::dec;
}
return ret.str();
}
bool GameOption::GetBool(bool& retval)
{
return Get(&retval, kBoolean);
}
bool GameOption::GetInt(int& retval)
{
return Get(&retval, kInteger);
}
bool GameOption::GetFloat(float& retval)
{
return Get(&retval, kFloat);
}
bool GameOption::GetColor(int& retval)
{
return Get(&retval, kColor);
}
bool GameOption::Set(const std::string& value)
{
if (GetType() == kBoolean)
{
return SetBool(stricmp(value.c_str(), "true") == 0 || stricmp(value.c_str(), "1") == 0);
}
if (GetType() == kInteger)
{
return SetInt(std::stoi(value, nullptr, 0));
}
if (GetType() == kFloat)
{
return SetFloat(std::stof(value, nullptr));
}
if (GetType() == kString)
{
return SetString(value);
}
if (GetType() == kColor)
{
return SetColor(std::stoi(value, nullptr, 0));
}
return false;
}
bool GameOption::SetBool(bool value)
{
return Set(&value, kBoolean);
}
bool GameOption::SetInt(int value)
{
return Set(&value, kInteger);
}
bool GameOption::SetFloat(float value)
{
return Set(&value, kFloat);
}
bool GameOption::SetString(const std::string& value)
{
RED4ext::CString str(value.c_str());
return Set(&str, kString);
}
bool GameOption::SetColor(int value)
{
return Set(&value, kColor);
}
bool GameOption::Toggle()
{
if (GetType() != kBoolean)
return false;
Boolean = !Boolean;
return true;
}
GameOption* GameOptions::Find(const std::string& category, const std::string& name)
{
auto option = std::find_if(
s_gameOptions.begin(), s_gameOptions.end(),
[&category, &name](GameOption* x)
{
return stricmp(x->pCategory, category.c_str()) == 0 && stricmp(x->pName, name.c_str()) == 0;
});
if (option == s_gameOptions.end())
{
spdlog::get("scripting")->info("Failed to find game option '{}/{}'!", category, name);
return nullptr;;
}
return *option;
}
void GameOptions::Print(const std::string& category, const std::string& name)
{
auto* option = Find(category, name);
if (!option)
return;
spdlog::get("scripting")->info(option->GetInfo());
}
std::string GameOptions::Get(const std::string& category, const std::string& name)
{
auto* option = Find(category, name);
if (!option)
return "";
return option->GetString();
}
bool GameOptions::GetBool(const std::string& category, const std::string& name)
{
auto* option = Find(category, name);
if (!option)
return false;
bool value = false;
bool result = option->GetBool(value);
if (!result)
{
spdlog::get("scripting")->info("Failed to read game option '{}/{}', not a boolean?", category, name);
return false;
}
return value;
}
int GameOptions::GetInt(const std::string& category, const std::string& name)
{
auto* option = Find(category, name);
if (!option)
return false;
int value = false;
bool result = option->GetInt(value);
if (!result)
{
spdlog::get("scripting")->info("Failed to read game option '{}/{}', not an integer/color?", category, name);
return 0;
}
return value;
}
float GameOptions::GetFloat(const std::string& category, const std::string& name)
{
auto* option = Find(category, name);
if (!option)
return false;
float value = false;
bool result = option->GetFloat(value);
if (!result)
{
spdlog::get("scripting")->info("Failed to read game option '{}/{}', not a float?", category, name);
return 0.f;
}
return value;
}
void GameOptions::Set(const std::string& category, const std::string& name, const std::string& value)
{
auto* option = Find(category, name);
if (!option)
return;
auto consoleLogger = spdlog::get("scripting");
if (option->Set(value))
consoleLogger->info(option->GetInfo());
else
{
if (option->GetType() == GameOption::kString)
consoleLogger->error("Failed to set game option '{}/{}', can't set string options right now.", category, name);
else
consoleLogger->error("Failed to set game option '{}/{}' due to an error (missing pointer?).", category, name);
}
}
void GameOptions::SetBool(const std::string& category, const std::string& name, bool value)
{
auto* option = Find(category, name);
if (!option)
return;
auto consoleLogger = spdlog::get("scripting");
if (option->SetBool(value))
consoleLogger->info(option->GetInfo());
else
{
if (option->GetType() != GameOption::kBoolean)
consoleLogger->error("Failed to set game option '{}/{}', not a boolean.", category, name);
else
consoleLogger->error("Failed to set game option '{}/{}' due to an error (missing pointer?).", category, name);
}
}
void GameOptions::SetInt(const std::string& category, const std::string& name, int value)
{
auto* option = Find(category, name);
if (!option)
return;
auto consoleLogger = spdlog::get("scripting");
if (option->SetInt(value))
consoleLogger->info(option->GetInfo());
else
{
if (option->GetType() != GameOption::kInteger && option->GetType() != GameOption::kColor)
consoleLogger->error("Failed to set game option '{}/{}', not an integer.", category, name);
else
consoleLogger->error("Failed to set game option '{}/{}' due to an error (missing pointer?).", category, name);
}
}
void GameOptions::SetFloat(const std::string& category, const std::string& name, float value)
{
auto* option = Find(category, name);
if (!option)
return;
auto consoleLogger = spdlog::get("scripting");
if (option->SetFloat(value))
consoleLogger->info(option->GetInfo());
else
{
if (option->GetType() != GameOption::kFloat)
consoleLogger->error("Failed to set game option '{}/{}', not a float.", category, name);
else
consoleLogger->error("Failed to set game option '{}/{}' due to an error (missing pointer?).", category, name);
}
}
void GameOptions::Toggle(const std::string& category, const std::string& name)
{
auto* option = Find(category, name);
if (!option)
return;
auto consoleLogger = spdlog::get("scripting");
if (option->Toggle())
consoleLogger->info(option->GetInfo());
else
{
if (option->GetType() != GameOption::kBoolean)
consoleLogger->error("Failed to set game option '{}/{}', not a boolean.", category, name);
else
consoleLogger->error("Failed to set game option '{}/{}' due to an error (missing pointer?).", category, name);
}
}
void GameOptions::Dump()
{
for (auto option : s_gameOptions)
Log::Info(option->GetInfo());
spdlog::get("scripting")->info("Dumped {} options to cyber_engine_tweaks.log", s_gameOptions.size());
}
void GameOptions::List(const std::string& category)
{
auto consoleLogger = spdlog::get("scripting");
int count = 0;
auto iter = s_gameOptions.begin();
while (iter != s_gameOptions.end())
{
iter = std::find_if(
iter, s_gameOptions.end(),
[&category](GameOption* x)
{
if (!category.length() || category.at(0) == '*')
return true;
return stricmp(x->pCategory, category.c_str()) == 0;
});
if (iter != s_gameOptions.end())
{
consoleLogger->info((*iter)->GetInfo());
iter++;
count++;
}
}
consoleLogger->info("Found {} options", count);
}
TiltedPhoques::Vector<GameOption*>& GameOptions::GetList()
{
return s_gameOptions;
}
| 24.766382 | 123 | 0.585989 | [
"vector"
] |
786b735594fbe4a51d1f3c0febc044d59daa160c | 1,971 | cpp | C++ | test/net/unit/ip6_packet_test.cpp | paulyc/IncludeOS | 5c82bad4a22838bc2219fbadef57d94f006b4760 | [
"Apache-2.0"
] | 5 | 2016-10-01T11:50:51.000Z | 2019-10-24T12:54:36.000Z | test/net/unit/ip6_packet_test.cpp | paulyc/IncludeOS | 5c82bad4a22838bc2219fbadef57d94f006b4760 | [
"Apache-2.0"
] | 1 | 2016-11-25T22:37:41.000Z | 2016-11-25T22:37:41.000Z | test/net/unit/ip6_packet_test.cpp | AndreasAakesson/IncludeOS | 891b960a0a7473c08cd0d93a2bba7569c6d88b48 | [
"Apache-2.0"
] | 3 | 2016-09-28T18:15:50.000Z | 2017-07-18T17:02:25.000Z | // This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2017 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// 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 <packet_factory.hpp>
#include <common.cxx>
#include <net/ip6/addr.hpp>
using namespace net;
CASE("IP6 Packet HOPLIMIT")
{
const ip6::Addr src{0xfe80, 0, 0, 0, 0xe823, 0xfcff, 0xfef4, 0x85bd};
const ip6::Addr dst{ 0xfe80, 0, 0, 0, 0xe823, 0xfcff, 0xfef4, 0x83e7 };
auto ip6 = create_ip6_packet_init(src, dst);
const uint8_t DEFAULT_HOPLIMIT = 128;
ip6->set_ip_hop_limit(DEFAULT_HOPLIMIT);
EXPECT(ip6->hop_limit() == DEFAULT_HOPLIMIT);
for(uint8_t i = DEFAULT_HOPLIMIT; i > 0; i--) {
ip6->decrement_hop_limit();
EXPECT(ip6->hop_limit() == i-1);
}
}
CASE("IP6 Packet HOPLIMIT - multiple packets")
{
std::vector<ip6::Addr> addrs{
{0xfe80, 0, 0, 0, 0xe823, 0xfcff, 0xfef4, 0x85bd},
{0xfe80, 0, 0, 0, 0xe823, 0xfcff, 0xfef4, 0x83e7},
ip6::Addr{0,0,0,1},
{0xfe80, 0, 0, 0, 0x0202, 0xb3ff, 0xff1e, 0x8329},
};
for(int i = 0; i < addrs.size()-1; i++)
{
auto ip6 = create_ip6_packet_init(addrs[i], addrs[i+1]);
const uint8_t DEFAULT_HOPLIMIT = 64;
ip6->set_ip_hop_limit(DEFAULT_HOPLIMIT);
EXPECT(ip6->hop_limit() == DEFAULT_HOPLIMIT);
for(uint8_t i = DEFAULT_HOPLIMIT; i > 0; i--)
ip6->decrement_hop_limit();
EXPECT(ip6->hop_limit() == 0);
}
}
| 29.41791 | 75 | 0.684424 | [
"vector"
] |
78793f7e61984e4107fbe085e72aa71666b081a6 | 1,537 | hpp | C++ | include/bohrium/bh_pprint.hpp | bh107/bohrium | 5b83e7117285fefc7779ed0e9acb0f8e74c7e068 | [
"Apache-2.0"
] | 236 | 2015-03-31T15:39:30.000Z | 2022-03-24T01:43:14.000Z | include/bohrium/bh_pprint.hpp | bh107/bohrium | 5b83e7117285fefc7779ed0e9acb0f8e74c7e068 | [
"Apache-2.0"
] | 324 | 2015-05-27T10:35:38.000Z | 2021-12-10T07:34:10.000Z | include/bohrium/bh_pprint.hpp | bh107/bohrium | 5b83e7117285fefc7779ed0e9acb0f8e74c7e068 | [
"Apache-2.0"
] | 41 | 2015-05-26T12:38:42.000Z | 2022-01-10T15:16:37.000Z | /*
This file is part of Bohrium and copyright (c) 2012 the Bohrium
team <http://www.bh107.org>.
Bohrium is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3
of the License, or (at your option) any later version.
Bohrium 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 Lesser General Public License along with Bohrium.
If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <iostream>
#include <vector>
#include <bohrium/bh_opcode.h>
#include <bohrium/bh_view.hpp>
#include <bohrium/bh_ir.hpp>
#include <bohrium/bh_type.hpp>
// Pretty print a C array
template<typename T>
std::string pprint_carray(const T *ary, uint64_t size) {
std::stringstream ss;
ss << "[";
for (uint64_t i=0; i<size; ++i) {
ss << ary[i];
if (i+1 < size) {
ss << ", ";
}
}
ss << "]";
return ss.str();
}
// Pretty print a std::vector
template<typename T>
std::ostream& operator<<(std::ostream& out, const std::vector<T>& v)
{
out << "[";
for (typename std::vector<T>::const_iterator i = v.cbegin();;)
{
out << *i;
if (++i == v.cend())
break;
out << ", ";
}
out << "]";
return out;
}
| 25.196721 | 68 | 0.647365 | [
"vector"
] |
787a17f23b9a791a6adbafb23287bc7232876b51 | 9,751 | cpp | C++ | mob_manipulator_controller/src/Stack_Tasks.cpp | jmfajardod/osf_wbc_bsc_thesis | ff6abdba73ed1822e8d03e7d8f5919dc60f4810a | [
"Apache-2.0"
] | 2 | 2021-04-06T20:42:02.000Z | 2021-04-06T21:07:01.000Z | mob_manipulator_controller/src/Stack_Tasks.cpp | jmfajardod/osf_wbc_bsc_thesis | ff6abdba73ed1822e8d03e7d8f5919dc60f4810a | [
"Apache-2.0"
] | null | null | null | mob_manipulator_controller/src/Stack_Tasks.cpp | jmfajardod/osf_wbc_bsc_thesis | ff6abdba73ed1822e8d03e7d8f5919dc60f4810a | [
"Apache-2.0"
] | null | null | null | /*******************************************************************************
* Copyright 2020 Jose Manuel Fajardo
*
* 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 <mob_manipulator_controller/Mob_Manipulator_Controller.hpp>
namespace mob_manipulator_controller {
using namespace dart::common;
using namespace dart::dynamics;
using namespace dart::math;
using namespace osc_controller;
////////////////////////////////////////////////////////////////////////////////
// Function where the stack of tasks is defined
void MobManipulatorController::StackTasks(Eigen::MatrixXd *Null_space, Eigen::VectorXd *torque_ns, int cycle){
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //
// Init definition of Stack of Tasks
// Uncomment or write the tasks to add to the stack
// The task first defined has more priority
/*****************************************************/
// Controller using pos XY with mobile robot and Z with mobile manipulator
//---osc_controller_.AchieveCartesianMobilRob(targetCartPos, targetCartVel, targetCartAccel, &min_sv_pos, M, C_k, g_k, dart_robotSkeleton, mEndEffector_, &tau_result, Null_space);
//osc_controller_.AchieveCartesianMobilRobConstVel(targetCartPos, &min_sv_pos, M, C_k, g_k, dart_robotSkeleton, mEndEffector_, &tau_result, Null_space);
//---osc_controller_.AchievePosZ(targetCartPos, targetCartVel, targetCartAccel, &min_sv_pos, cycle, M, C_k, g_k, dart_robotSkeleton, mEndEffector_, &tau_result, torque_ns, Null_space);
//osc_controller_.AchievePosZConstVel(targetCartPos, &min_sv_pos, cycle, M, C_k, g_k, dart_robotSkeleton, mEndEffector_, &tau_result, torque_ns, Null_space);
/*****************************************************/
// Controller using pos XYZ with manipulator
//---osc_controller_.AchieveCartesianManipulator(targetCartPos, targetCartVel, targetCartAccel, &min_sv_pos, cycle, M, C_k, g_k, dart_robotSkeleton, mEndEffector_, &tau_result, torque_ns, Null_space);
//osc_controller_.AchieveCartManipulatorConstVel(targetCartPos, &min_sv_pos, cycle, M, C_k, g_k, dart_robotSkeleton, mEndEffector_, &tau_result, torque_ns, Null_space);
/*****************************************************/
// Controller using pos XYZ with mobile manipulator
//---osc_controller_.AchieveCartesianManipulator(targetCartPos, targetCartVel, targetCartAccel, &min_sv_pos, cycle, M, C_k, g_k, dart_robotSkeleton, mEndEffector_, &tau_result, torque_ns, Null_space);
//osc_controller_.AchieveCartesianConstVel(targetCartPos, &min_sv_pos, cycle, M, C_k, g_k, dart_robotSkeleton, mEndEffector_, &tau_result, torque_ns, Null_space);
/*****************************************************/
// Orientation tasks with mobile manipulator
//---osc_controller_.AchieveOrientation(targetOrientPos, targetOrientVel, targetOrientAccel, &min_sv_ori, cycle, M, C_k, g_k, dart_robotSkeleton, mEndEffector_, &tau_result, torque_ns, Null_space);
//osc_controller_.AchieveOrientationConstVel(targetOrientPos, &min_sv_ori, cycle, M, C_k, g_k, dart_robotSkeleton, mEndEffector_, &tau_result, torque_ns, Null_space);
//---osc_controller_.OrientationImpedance(targetOrientPos, targetOrientVel, targetOrientAccel, &min_sv_ori, cycle, tau_ext, M, C_k, g_k, dart_robotSkeleton, mEndEffector_, &tau_result, torque_ns, Null_space);
/*****************************************************/
// Orientation tasks with manipulator
//---osc_controller_.AchieveOriManipulator(targetOrientPos, targetOrientVel, targetOrientAccel, &min_sv_ori, cycle, M, C_k, g_k, dart_robotSkeleton, mEndEffector_, &tau_result, torque_ns, Null_space);
osc_controller_.AchieveOriManipulatorConstVel(targetOrientPos, &min_sv_ori, cycle, M, C_k, g_k, dart_robotSkeleton, mEndEffector_, &tau_result, torque_ns, Null_space);
/*****************************************************/
// Controller using pos XYZ with manipulator - To test singularities
//---osc_controller_.AchieveCartesianManipulator(targetCartPos, targetCartVel, targetCartAccel, &min_sv_pos, cycle, M, C_k, g_k, dart_robotSkeleton, mEndEffector_, &tau_result, torque_ns, Null_space);
osc_controller_.AchieveCartManipulatorConstVel(targetCartPos, &min_sv_pos, cycle, M, C_k, g_k, dart_robotSkeleton, mEndEffector_, &tau_result, torque_ns, Null_space);
/*****************************************************/
// Joint tasks
if(cycle==1){
osc_controller_.AchieveJointConf(q_desired, M, C_k, g_k, dart_robotSkeleton, mEndEffector_, &tau_result, Null_space);
}
}
////////////////////////////////////////////////////////////////////////////////
// Function to calculate torque due to tasks define in the stack of tasks
void MobManipulatorController::calcTorqueDueTasks(){
/*********************************************************************************/
// Stack of tasks Definition
Eigen::MatrixXd Null_space;
Eigen::VectorXd tau_ns;
//--- Number of cycles of algorithm due to singularity handling method
int cycles_algorithm = 1;
if(osc_controller_.singularity_handling_method == 2){
cycles_algorithm = 2;
}
//--- Compute the constraints of the saturation
if(osc_controller_.joint_limit_handling_method==3){
time_actual_sjs = ros::Time::now().toSec();
double current_sampling_time = time_actual_sjs-time_previous_sjs;
if(current_sampling_time<=10e-6){
current_sampling_time = 1.0/500.0;
}
osc_controller_.updateSJSConstraints(dart_robotSkeleton, current_sampling_time);
time_previous_sjs = ros::Time::now().toSec();
}
//--- SJS variables
bool flag_sjs = true;
Eigen::MatrixXd Jacobian_constraints = Eigen::MatrixXd::Zero(1, robot_dofs);
Eigen::VectorXd Desired_accel_constraints = Eigen::VectorXd::Zero(1);
bool task_limited = false;
//--- SJS main cycle
while(flag_sjs){
//--- Init non-singular torque
tau_ns = Eigen::VectorXd::Zero(robot_dofs);
//-- Loop for third singularity handling method
for (size_t cycle = 1; cycle <= cycles_algorithm; cycle++){
Null_space = Eigen::MatrixXd::Identity(robot_dofs,robot_dofs);
tau_result = Eigen::VectorXd::Zero(robot_dofs);
/*****************************************************/
// Avoid Joint Limits task
if(cycle==1){
if(osc_controller_.joint_limit_handling_method==0){
osc_controller_.AvoidJointLimitsPotentials(M, C_k, g_k, dart_robotSkeleton, mEndEffector_, &tau_result, &Null_space);
}
if(osc_controller_.joint_limit_handling_method==1){
osc_controller_.AvoidJointLimitsIntermValue(M, C_k, g_k, dart_robotSkeleton, mEndEffector_, &tau_result, &Null_space);
}
if(osc_controller_.joint_limit_handling_method==3 && task_limited){
osc_controller_.SaturationJointSpace( Jacobian_constraints, Desired_accel_constraints, M, C_k, g_k, dart_robotSkeleton, mEndEffector_, &tau_result, &Null_space);
}
}
/*****************************************************/
// Calc torques due task in stack
StackTasks(&Null_space, &tau_ns, cycle);
/*****************************************************/
// Take torque at the end of first cycle as non-singular torque
tau_ns = tau_result;
}
/*****************************************************/
// Compensation of non-linear effects in joint space
if(osc_controller_.compensate_jtspace){
tau_result = tau_result + C_k + g_k;
}
flag_sjs = false; // Clean SJS flag
/*****************************************************/
// IF SJS is selected check the constraints
if(osc_controller_.joint_limit_handling_method==3){
Eigen::VectorXd current_joint_accel = M.inverse() * (tau_result - C_k - g_k);
//--- Check constraints
int critical_joint = -1;
osc_controller_.checkSJSConstraints(current_joint_accel, mEndEffector_, &flag_sjs);
//--- If constraints are exceeded
if(flag_sjs){
task_limited = true;
Eigen::MatrixXd prev_jacob = Jacobian_constraints;
//--- Update Jacobian and task vector
osc_controller_.updateSJSConstraintTask(current_joint_accel, &flag_sjs, &Jacobian_constraints, &Desired_accel_constraints);
if(prev_jacob.rows()==Jacobian_constraints.rows()){
if(prev_jacob.isApprox(Jacobian_constraints)){
ROS_INFO("Repeated saturations in SJS");
flag_sjs = false;
}
}
}
}
}// End SJS cycle
}
} /* namespace */ | 49.247475 | 213 | 0.606502 | [
"vector"
] |
787d18411cc62f3287e1db54b64aa0ec5c208219 | 1,077 | cpp | C++ | src/utils/pipelinecontainer.cpp | chili-epfl/qml-ar | e48e67d28b3b8556787df65b50bb196ff2a169db | [
"MIT"
] | 32 | 2018-01-31T13:07:36.000Z | 2021-12-21T14:33:59.000Z | src/utils/pipelinecontainer.cpp | chili-epfl/qml-ar | e48e67d28b3b8556787df65b50bb196ff2a169db | [
"MIT"
] | 1 | 2021-05-10T15:11:52.000Z | 2021-05-10T15:11:52.000Z | src/utils/pipelinecontainer.cpp | chili-epfl/qml-ar | e48e67d28b3b8556787df65b50bb196ff2a169db | [
"MIT"
] | 6 | 2018-02-19T02:19:02.000Z | 2021-04-07T11:20:18.000Z | /**
* @file pipelinecontainer.cpp
* @brief This template class wraps an object
* adding additional information: id, timestamp
* @author Sergei Volodin
* @version 1.0
* @date 2018-07-25
*/
#ifndef PIPELINECONTAINER_CPP
#define PIPELINECONTAINER_CPP
#include <QtCore>
#include "pipelinecontainer.h"
template<class T>
PipelineContainer<T>::PipelineContainer(T object, PipelineContainerInfo info)
{
this->object = object;
this->info_ = info;
}
template<class T>
PipelineContainer<T>::PipelineContainer(T object)
{
this->object = object;
}
template<class T>
PipelineContainer<T>::PipelineContainer()
{
}
template<class T>
void PipelineContainer<T>::setInfo(PipelineContainerInfo info)
{
this->info_ = info;
}
template<class T>
PipelineContainerInfo PipelineContainer<T>::info()
{
return info_;
}
template<class T>
PipelineContainer<T>::operator PipelineContainerInfo()
{
return info();
}
template<class T>
PipelineContainer<T>::operator T &()
{
return o();
}
template<class T>
T &PipelineContainer<T>::o()
{
return object;
}
#endif
| 16.569231 | 77 | 0.723305 | [
"object"
] |
787d8f68d8b90716596d7c5b92f36c3107645a69 | 19,226 | cpp | C++ | lib/Dialect/XTen/Transforms/XTenDataflowUtils.cpp | denolf/mlir-xten | c3986f6a0e9411b32127c27eebaa30decc922c87 | [
"Apache-2.0"
] | 10 | 2021-11-05T00:08:47.000Z | 2022-02-09T20:12:56.000Z | lib/Dialect/XTen/Transforms/XTenDataflowUtils.cpp | denolf/mlir-xten | c3986f6a0e9411b32127c27eebaa30decc922c87 | [
"Apache-2.0"
] | 1 | 2022-01-27T17:21:14.000Z | 2022-01-27T17:22:41.000Z | lib/Dialect/XTen/Transforms/XTenDataflowUtils.cpp | denolf/mlir-xten | c3986f6a0e9411b32127c27eebaa30decc922c87 | [
"Apache-2.0"
] | 6 | 2021-11-10T06:49:47.000Z | 2021-12-22T19:02:48.000Z | //===- XTenDataflowUtils.cpp ------------------------------------*- C++ -*-===//
//
// This file is licensed under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
// (c) Copyright 2021 Xilinx Inc.
//
//===----------------------------------------------------------------------===//
#include "mlir/Dialect/Func/IR/FuncOps.h"
#include "mlir/IR/BuiltinOps.h"
#include "mlir/IR/OperationSupport.h"
#include "torch-mlir/Dialect/Torch/IR/TorchTypes.h"
#include "xten/Dialect/XTen/XTenDataflowUtils.h"
#include "xten/Dialect/XTen/XTenDataflowConsts.h"
#define DEBUG_TYPE "xten-dataflow-utils"
using namespace mlir;
namespace xilinx {
namespace xten {
mlir::torch::Torch::BaseTensorType baseShapeManupulation(mlir::torch::Torch::BaseTensorType initShape, unsigned int at, unsigned int into, bool manipulationType) {
auto shape = initShape.getSizes();
std::vector<long> newShape = std::vector<long>(shape);
if(manipulationType) {
newShape[at] = newShape[at] / into;
} else {
newShape[at] = newShape[at] * into;
}
shape = initShape.getSizes();
for(uint64_t i = 0; i < newShape.size(); i++) {
assert(newShape[at] > 0);
}
ArrayRef<long> nShape = ArrayRef<long>(newShape);
//ShapedType ttype = RankedTensorType::get(nShape, initShape.getElementType());
auto tmpType = initShape.getWithSizesAndDtype(nShape,initShape.getDtype()); // NOLF NEED CHECK
auto ttype = tmpType.dyn_cast<mlir::torch::Torch::BaseTensorType>(); // NOLF NEED CHECK
return ttype;
}
mlir::torch::Torch::BaseTensorType breakShapeInto(mlir::torch::Torch::BaseTensorType initShape, unsigned int at, unsigned int into) {
return baseShapeManupulation(initShape, at, into, true);
}
mlir::torch::Torch::BaseTensorType mergeShapeInto(mlir::torch::Torch::BaseTensorType initShape, unsigned int at, unsigned int into) {
return baseShapeManupulation(initShape, at, into, false);
}
// TODO most likely factor some code here
void splitConstantActivationsInto(mlir::arith::ConstantOp op, std::vector<Value> &ops, OpBuilder &builder, unsigned int loc,
DenseElementsAttr at, unsigned int into) {
mlir::torch::Torch::BaseTensorType initialShape = at.getType().dyn_cast<mlir::torch::Torch::BaseTensorType>(); // NOLF NEED CHECK
ArrayRef<int64_t> s = initialShape.getSizes();
uint64_t C = s[CIN_LOC];
uint64_t N = s[N_LOC];
uint64_t M = s[M_LOC];
uint64_t C_switch = C;
uint64_t N_switch = N;
uint64_t M_switch = M;
if(loc == 0) {
C_switch = C / into;
} else if(loc == 1) {
N_switch = N / into;
} else if(loc == 2) {
M_switch = M / into;
}
//if(initialShape.getElementType().isF32()) { // TODO more types
if(initialShape.getDtype().isF32()) { // TODO more types NOLF NEED CHECK
std::vector<std::vector<APFloat>> vects;
for(unsigned int i = 0; i < into; i++) {
vects.push_back(std::vector<APFloat>());
}
uint64_t i = 0;
for(auto it = at.value_begin<APFloat>(); it != at.value_end<APFloat>(); it++) {
//llvm::outs() << "Got this value: ";
//(*it).print(llvm::outs());
uint64_t loc_c = i / (M * N);
uint64_t loc_N = (i / M) % N;
uint64_t loc_M = i % M;
uint64_t vectsId = std::max(std::max(loc_c / C_switch, loc_N / N_switch),
loc_M / M_switch);
vects.at(vectsId).push_back(*it);
i++;
}
for(uint64_t i = 0; i < into; i++) {
assert(vects.at(i).size() == (size_t)(at.getType().getNumElements() / into));
}
mlir::torch::Torch::BaseTensorType ttype = breakShapeInto(initialShape, loc, into);
for(uint64_t i = 0; i < into; i++) {
DenseElementsAttr attr = DenseElementsAttr::get(ttype, vects.at(i));
Operation* cst = builder.create<mlir::arith::ConstantOp>(builder.getUnknownLoc(), ttype, attr);
ops.push_back(cst->getResult(0));
}
}
}
// Splits weights into according to dim given by loc
void splitConstantWeightsInto(mlir::arith::ConstantOp op, std::vector<Value> &ops, OpBuilder &builder, unsigned int loc,
DenseElementsAttr at, unsigned int into) {
mlir::torch::Torch::BaseTensorType initialShape = at.getType().dyn_cast<mlir::torch::Torch::BaseTensorType>(); // NOLF NEED CHECK
ArrayRef<int64_t> s = initialShape.getSizes();
uint64_t COut = s[COUT_LOC];
uint64_t CIn = s[CIN_LOC];
uint64_t F0 = s[F0_LOC];
uint64_t F1 = s[F1_LOC];
uint64_t COut_switch = COut;
uint64_t CIn_switch = CIn;
uint64_t F0_switch = F0;
uint64_t F1_switch = F1;
if(loc == 0) {
COut_switch = COut / into;
} else if(loc == 1) {
CIn_switch = CIn / into;
} else if(loc == 2) {
F0_switch = F0 / into;
} else if(loc == 3) {
F1_switch = F1 / into;
}
//if(initialShape.getElementType().isF32()) { // TODO is this the only choice?
if(initialShape.getDtype().isF32()) { // TODO more types NOLF NEED CHECK
std::vector<std::vector<APFloat>> vects;
for(unsigned int i = 0; i < into; i++) {
vects.push_back(std::vector<APFloat>());
}
uint64_t i = 0;
for(auto it = at.value_begin<APFloat>(); it != at.value_end<APFloat>(); it++) {
//llvm::outs() << "Got this value: ";
//(*it).print(llvm::outs());
uint64_t loc_cout = i / (F0 * F1 * CIn);
uint64_t loc_cin = (i / (F0 * F1)) % CIn;
uint64_t loc_F0 = (i / F1) % F0;
uint64_t loc_F1 = i % F1;
uint64_t vectsId = std::max(std::max(loc_cout / COut_switch, loc_cin / CIn_switch),
std::max(loc_F0 / F0_switch, loc_F1 / F1_switch));
vects.at(vectsId).push_back(*it);
i++;
}
for(uint64_t i = 0; i < into; i++) {
assert(vects.at(i).size() == (size_t)(at.getType().getNumElements() / into));
}
mlir::torch::Torch::BaseTensorType ttype = breakShapeInto(initialShape, loc, into);
for(uint64_t i = 0; i < into; i++) {
DenseElementsAttr attr = DenseElementsAttr::get(ttype, vects.at(i));
Operation* cst = builder.create<mlir::arith::ConstantOp>(builder.getUnknownLoc(), ttype, attr);
ops.push_back(cst->getResult(0));
}
}
}
// loc = 0 split
// loc > 0 generate some other 0 biases
void splitConstantBiasInto(mlir::arith::ConstantOp op, std::vector<Value> &ops, OpBuilder &builder, unsigned int loc, DenseElementsAttr at, unsigned int into) {
mlir::torch::Torch::BaseTensorType initialShape = at.getType().dyn_cast<mlir::torch::Torch::BaseTensorType>(); // NOLF NEED CHECK
//if(initialShape.getElementType().isF32()) { // TODO extend to more types
if(initialShape.getDtype().isF32()) {
std::vector<std::vector<APFloat>> vects;
for(unsigned int i = 0; i < into; i++) {
vects.push_back(std::vector<APFloat>());
}
uint64_t i = 0;
for(auto it = at.value_begin<APFloat>(); it != at.value_end<APFloat>(); it++) {
if(loc == 0) {
unsigned int index = i / (at.getType().getNumElements() / into);
vects.at(index).push_back(*it);
} else {
vects.at(0).push_back(*it);
// NOTE assume that same kernel with 0 bias from the compiler point of view
// NOTE create duplicate constants here
for(unsigned int j = 1; j < into; j++) {
vects.at(j).push_back(APFloat((float)0));
}
}
i++;
}
for(uint64_t i = 0; i < vects.size(); i++) {
assert(vects.at(i).size() == (size_t)((loc == 0) ? at.getType().getNumElements() / into : at.getType().getNumElements()));
}
// now splitted the dense in into parts, need to regenerate it
mlir::torch::Torch::BaseTensorType ttype;
if(loc == 0) {
ttype = breakShapeInto(initialShape, 0, into);
} else {
ttype = initialShape;
}
for(uint64_t i = 0; i < into; i++) {
DenseElementsAttr attr = DenseElementsAttr::get(ttype, vects.at(i));
Operation* cst = builder.create<mlir::arith::ConstantOp>(builder.getUnknownLoc(), ttype, attr);
ops.push_back(cst->getResult(0));
}
}
}
// TODO support WSplit
// TODO remove the unecessary indirection here, this should belong to the Pattern themselves
unsigned int splitToDim(Split split, SplitType t) {
if(t == bSplitType) {
if(split == PSplit) {
return 0;
} else {
return 1;
}
} else if(t == aSplitType) {
if(split == CaSplit) {
return 0;
} else {
return (unsigned int )-1;
}
} else if(t == wSplitType) {
if(split == PSplit) {
return 0;
} else if(split == CaSplit) {
return 1;
} else if(split == LSplit) {
return 2;
}
}
return (unsigned int )-1;
}
void splitConstantInto(mlir::arith::ConstantOp op, std::vector<Value> &ops, OpBuilder &builder, Split split, SplitType t, unsigned int into) {
for(NamedAttribute attr: op->getAttrs()) {
// We Look for the Dense Attribute
auto at = attr.getValue().dyn_cast<DenseElementsAttr>();
if(at) {
if(t == bSplitType) {
unsigned int splitDim = splitToDim(split, t);
splitConstantBiasInto(op, ops, builder, splitDim, at, into);
} else if(t == aSplitType) {
unsigned int splitDim = splitToDim(split, t);
if(splitDim == (unsigned int)-1) {
// TODO maybe fail silently if top level is fine with that
llvm::outs() << "Only Ca split is supported to split activation tensors";
exit(1);
} else {
splitConstantActivationsInto(op, ops, builder, splitDim, at, into);
}
} else {
unsigned int splitDim = splitToDim(split, t);
splitConstantWeightsInto(op, ops, builder, splitDim, at, into);
}
}
}
}
void deleteOpsFrom(std::vector<Operation*> &ops) {
for(unsigned int i = 0; i < ops.size(); i++) {
llvm::outs() << "Deleting.. " << i << "\n";
ops.at(i)->erase();
}
ops.clear();
}
void deleteOpsFrom(std::vector<AbsOpWrapper*> &ops) {
for(unsigned int i = 0; i < ops.size(); i++) {
ops.at(i)->getUnderlyingOperation()->erase();
delete ops.at(i);
}
ops.clear();
}
// TODO double check shape propagation here
Operation* insertConcat(OpBuilder &builder, Value prevRes, std::vector<Value> &values, unsigned int dim, bool clearPrev) {
mlir::torch::Torch::BaseTensorType prevResType = prevRes.getType().dyn_cast<mlir::torch::Torch::BaseTensorType>();
ArrayRef<Value> valuesRef = ArrayRef<Value>(values);
ValueRange valuesRange(valuesRef);
Operation* cstDim = builder.create<mlir::arith::ConstantIntOp>(builder.getUnknownLoc(), dim, 32);
Operation* res = builder.create<xilinx::xten::ConcatOp>(builder.getUnknownLoc(), prevResType, valuesRange, cstDim->getResult(0));
if(clearPrev) {
// Replace output of old convolution usage by concat value
prevRes.replaceAllUsesWith(res->getResult(0));
}
return res;
}
void insertSplit(OpBuilder &builder, Value prevInput, std::vector<Value> &nInputs, unsigned int dim, unsigned int into) {
mlir::torch::Torch::BaseTensorType nShape = breakShapeInto(prevInput.getType().dyn_cast<mlir::torch::Torch::BaseTensorType>(), dim, into);
std::vector<Type> shapes = std::vector<Type>(into, nShape);
ArrayRef<Type> tShapes = ArrayRef<Type>(shapes);
Operation* cstDim = builder.create<mlir::arith::ConstantIntOp>(builder.getUnknownLoc(), dim, 32);
Operation* splitOp = builder.create<SplitOp>(builder.getUnknownLoc(), TypeRange(tShapes), prevInput, cstDim->getResult(0));
for(auto indexedResult: llvm::enumerate(splitOp->getResults())) {
nInputs.push_back(indexedResult.value());
}
}
void replaceSplit(OpBuilder &builder, xilinx::xten::SplitOp split, std::vector<Value> &values,
std::vector<Operation*> &toDelete, unsigned int dim) {
unsigned int into = values.size();
llvm::outs() << "Split number of operands: " << split.getNumOperands() << "\n";
if(split.getNumResults() == into) {
for(unsigned int i = 0; i < into; i++) {
split.getResult(i).replaceAllUsesWith(values.at(i));
}
// Delete split
toDelete.push_back(split);
} else {
unsigned int splitResults = split.getNumResults();
unsigned int resPerConv = splitResults / into;
unsigned int rem = splitResults % into;
unsigned int consumed = 0;
for(unsigned int i = 0; i < into; i++) {
unsigned int shouldHandle = resPerConv + ((i > rem ) ? 1 : 0);
if(shouldHandle == 1) {
split.getResult(consumed).replaceAllUsesWith(values.at(i));
consumed++;
} else {
ArrayRef<Value> af = ArrayRef<Value>(values);
Operation* cstDim = builder.create<mlir::arith::ConstantIntOp>(builder.getUnknownLoc(), dim, 32);
Operation* splitOp = builder.create<xilinx::xten::SplitOp>(builder.getUnknownLoc(), TypeRange(af), values.at(i), cstDim->getResult(0));
for(unsigned int j = 0; j < shouldHandle; j++) {
split.getResult(consumed).replaceAllUsesWith(splitOp->getResult(j));
consumed++;
}
}
}
toDelete.push_back(split);
}
}
void replaceConcat(OpBuilder &builder, xilinx::xten::ConcatOp concat, std::vector<Value> &nInputs,
std::vector<Operation*> &toDelete, unsigned int dim, unsigned int into) {
if(into == (concat.getNumOperands() - 1)) { // because there is the dim argument as well
for(unsigned int i = 0; i < into; i++) {
nInputs.push_back(concat.getOperand(i));
}
toDelete.push_back(concat);
} else {
unsigned int concatOperands = concat.getNumOperands();
unsigned int operandsPerConv = concatOperands / into;
unsigned int rem = concatOperands % into;
unsigned int consumed = 0;
for(unsigned int i = 0; i < into; i++) {
unsigned int shouldHandle = operandsPerConv + ((i > rem) ? 1 : 0);
if(shouldHandle == 1) {
nInputs.push_back(concat.getOperand(consumed));
consumed++;
} else {
mlir::torch::Torch::BaseTensorType opShape = concat.getOperand(consumed).getType().dyn_cast<mlir::torch::Torch::BaseTensorType>();
Type nShape = mergeShapeInto(opShape, 0, shouldHandle);
std::vector<Value> values;
for(unsigned int j = 0; j < shouldHandle; j++) {
values.push_back(concat.getOperand(consumed));
consumed++;
}
ArrayRef<Value> af = ArrayRef<Value>(values);
Operation* cstDim = builder.create<mlir::arith::ConstantIntOp>(builder.getUnknownLoc(), dim, 32);
Operation* res = builder.create<xilinx::xten::ConcatOp>(builder.getUnknownLoc(), nShape, ValueRange(af), cstDim->getResult(0));
nInputs.push_back(res->getResult(0));
}
}
}
}
unsigned int getAttrOrDefault(Operation* op, std::string attrName, unsigned int defVal) {
if(op->getAttr(attrName) != nullptr) {
return op->getAttr(attrName).dyn_cast<IntegerAttr>().getValue().getZExtValue();
} else {
return defVal;
}
}
void printOperationLoc(Operation* op) {
unsigned int locCa = getAttrOrDefault(op, "locCa", 0);
unsigned int locL = getAttrOrDefault(op, "locL", 0);
unsigned int locW = getAttrOrDefault(op, "locW", 0);
unsigned int locP = getAttrOrDefault(op, "locP", 0);
llvm::outs() << "Op is at: P: " << locP << ", Ca: " << locCa << ", W: " << locW << ", L: " << locL << "\n";
}
}
}
| 45.885442 | 171 | 0.504993 | [
"shape",
"vector"
] |
788487128939a919027e808dbd4e61ae9a602096 | 1,067 | cpp | C++ | src/ciCMS/cfg/components/Camera.cpp | markkorput/ciCMS | a0ec32761ce712e78e31fe15e64ee9bd79c9bd51 | [
"MIT"
] | null | null | null | src/ciCMS/cfg/components/Camera.cpp | markkorput/ciCMS | a0ec32761ce712e78e31fe15e64ee9bd79c9bd51 | [
"MIT"
] | null | null | null | src/ciCMS/cfg/components/Camera.cpp | markkorput/ciCMS | a0ec32761ce712e78e31fe15e64ee9bd79c9bd51 | [
"MIT"
] | null | null | null | #include "Camera.h"
#include "cinder/gl/gl.h"
using namespace cms::cfg::components;
void Camera::cfg(cms::cfg::Cfg& cfg) {
cfg
.connectAttr<void()>("on", [this](){ this->render(); })
.connectAttr<void(ci::quat&)>("orientationOn", [this](ci::quat& orientation){
this->cam.setOrientation(orientation); })
.withSignalByAttr<void()>("emit", [this](ci::signals::Signal<void()>& sig) {
this->drawSignal = &sig;
})
.reader()
->withVec3("pos", [this](const glm::vec3& val){ this->cam.setEyePoint(val); })
.withVec3("lookAt", [this](const glm::vec3& val){ this->cam.lookAt(val); });
if (cfg.reader()->getBool("ui", false)) {
camUi = ci::CameraUi( &cam, ci::app::getWindow() );
camUi.connect(ci::app::getWindow() );
camUi.enable();
} else {
camUi.disable();
}
}
void Camera::render() {
// TODO; push matrix?
if (drawSignal) {
ci::gl::pushViewMatrix();
ci::gl::pushProjectionMatrix();
ci::gl::setMatrices(cam);
drawSignal->emit();
ci::gl::popViewMatrix();
ci::gl::popProjectionMatrix();
}
}
| 26.02439 | 82 | 0.606373 | [
"render"
] |
788c6c3e1dd9664e5c0c82104004de42856d3e65 | 7,458 | cc | C++ | tensorflow/core/kernels/stack_ops.cc | ryan-collins-forks/tensorflow | 080a1f6c64976b11437d2dc4ef4178e4ca1205b7 | [
"Apache-2.0"
] | null | null | null | tensorflow/core/kernels/stack_ops.cc | ryan-collins-forks/tensorflow | 080a1f6c64976b11437d2dc4ef4178e4ca1205b7 | [
"Apache-2.0"
] | null | null | null | tensorflow/core/kernels/stack_ops.cc | ryan-collins-forks/tensorflow | 080a1f6c64976b11437d2dc4ef4178e4ca1205b7 | [
"Apache-2.0"
] | null | null | null | /* Copyright 2015 Google Inc. All Rights Reserved.
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.
==============================================================================*/
// See docs in ../ops/data_flow_ops.cc.
#include <limits.h>
#include <vector>
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/framework/resource_mgr.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/gtl/map_util.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/macros.h"
#include "tensorflow/core/platform/mutex.h"
#include "tensorflow/core/platform/port.h"
#include "tensorflow/core/platform/thread_annotations.h"
#include "tensorflow/core/public/tensor.h"
#include "tensorflow/core/public/tensor_shape.h"
namespace tensorflow {
class Stack : public ResourceBase {
public:
Stack(const DataType& elem_type, const Tensor& handle)
: elem_type_(elem_type), handle_(handle) {}
void Push(const PersistentTensor& value) {
mutex_lock l(mu_);
stack_.push_back(value);
}
bool Pop(PersistentTensor* value) {
mutex_lock l(mu_);
if (!stack_.empty()) {
*value = stack_.back();
stack_.pop_back();
return true;
}
return false;
}
DataType ElemType() { return elem_type_; }
string DebugString() override {
mutex_lock l(mu_);
return strings::StrCat("#elem:", stack_.size());
}
private:
friend class StackOp;
mutex* mu() { return &mu_; }
Tensor* handle() { return &handle_; }
mutex mu_;
DataType elem_type_;
Tensor handle_;
std::vector<PersistentTensor> stack_ GUARDED_BY(mu_);
};
// A per-run local stack. The stack uses a "per-step" resource manager which
// ensures that correct garbage collection on error or successful completion.
class StackOp : public OpKernel {
public:
explicit StackOp(OpKernelConstruction* context) : OpKernel(context) {
OP_REQUIRES_OK(context, context->GetAttr("elem_type", &elem_type_));
OP_REQUIRES_OK(context, context->GetAttr("stack_name", &stack_name_));
if (stack_name_ == "") stack_name_ = name();
}
void Compute(OpKernelContext* ctx) override {
// Create the stack handle.
Tensor stack_handle;
AllocatorAttributes alloc_attr;
alloc_attr.set_on_host(true);
OP_REQUIRES_OK(ctx, ctx->allocate_temp(tensorflow::DT_STRING,
tensorflow::TensorShape({2}),
&stack_handle, alloc_attr));
auto handle = stack_handle.flat<string>();
handle(0) = "_stacks";
handle(1) = stack_name_;
// Store the handle in a container of the per-step RM.
ResourceMgr* rm = ctx->step_resource_manager();
OP_REQUIRES(ctx, rm != nullptr,
errors::Internal("No per-step resource manager."));
Stack* stack = new Stack(elem_type_, stack_handle);
OP_REQUIRES_OK(ctx, rm->Create(handle(0), stack_name_, stack));
ctx->set_output_ref(0, stack->mu(), stack->handle());
}
private:
DataType elem_type_;
string stack_name_;
TF_DISALLOW_COPY_AND_ASSIGN(StackOp);
};
REGISTER_KERNEL_BUILDER(Name("Stack").Device(DEVICE_CPU), StackOp);
REGISTER_KERNEL_BUILDER(Name("Stack").Device(DEVICE_GPU).HostMemory("handle"),
StackOp);
class StackPushOp : public OpKernel {
public:
explicit StackPushOp(OpKernelConstruction* context) : OpKernel(context) {}
void Compute(OpKernelContext* ctx) override {
Tensor Tstack_handle = ctx->mutable_input(0, false);
OP_REQUIRES(ctx, Tstack_handle.NumElements() == 2,
errors::InvalidArgument(
"Stack handle must have two elements, but had shape: ",
Tstack_handle.shape().DebugString()));
const string& container = Tstack_handle.flat<string>()(0);
const string& stack_name = Tstack_handle.flat<string>()(1);
ResourceMgr* rm = ctx->step_resource_manager();
OP_REQUIRES(ctx, rm != nullptr,
errors::Internal("No per-step resource manager."));
Stack* stack = nullptr;
OP_REQUIRES_OK(ctx, rm->Lookup(container, stack_name, &stack));
OP_REQUIRES(ctx, ctx->input_dtype(1) == stack->ElemType(),
errors::InvalidArgument("Must have type ", stack->ElemType(),
" but got ", ctx->input_dtype(1)));
stack->Push(PersistentTensor(ctx->input(1)));
ctx->set_output(0, ctx->input(1));
}
};
REGISTER_KERNEL_BUILDER(Name("StackPush").Device(DEVICE_CPU), StackPushOp);
REGISTER_KERNEL_BUILDER(
Name("StackPush").Device(DEVICE_GPU).HostMemory("handle"), StackPushOp);
class StackPopOp : public OpKernel {
public:
explicit StackPopOp(OpKernelConstruction* context) : OpKernel(context) {}
void Compute(OpKernelContext* ctx) override {
Tensor Tstack_handle = ctx->mutable_input(0, false);
OP_REQUIRES(ctx, Tstack_handle.NumElements() == 2,
errors::InvalidArgument(
"Stack handle must have two elements, but had shape: ",
Tstack_handle.shape().DebugString()));
const string& container = Tstack_handle.flat<string>()(0);
const string& stack_name = Tstack_handle.flat<string>()(1);
ResourceMgr* rm = ctx->step_resource_manager();
OP_REQUIRES(ctx, rm != nullptr,
errors::Internal("No per-step resource manager."));
Stack* stack = nullptr;
OP_REQUIRES_OK(ctx, rm->Lookup(container, stack_name, &stack));
PersistentTensor value;
bool has_value = stack->Pop(&value);
if (!has_value) {
errors::InvalidArgument("Calling Pop() when the stack is empty.");
}
ctx->set_output(0, *value.AccessTensor(ctx));
}
};
REGISTER_KERNEL_BUILDER(Name("StackPop").Device(DEVICE_CPU), StackPopOp);
REGISTER_KERNEL_BUILDER(
Name("StackPop").Device(DEVICE_GPU).HostMemory("handle"), StackPopOp);
class StackCloseOp : public OpKernel {
public:
explicit StackCloseOp(OpKernelConstruction* context) : OpKernel(context) {}
void Compute(OpKernelContext* ctx) override {
Tensor Tstack_handle = ctx->mutable_input(0, false);
OP_REQUIRES(ctx, Tstack_handle.NumElements() == 2,
errors::InvalidArgument(
"Stack handle must have two elements, but had shape: ",
Tstack_handle.shape().DebugString()));
const string& container = Tstack_handle.flat<string>()(0);
const string& stack_name = Tstack_handle.flat<string>()(1);
ResourceMgr* rm = ctx->step_resource_manager();
OP_REQUIRES(ctx, rm != nullptr,
errors::Internal("No per-step resource manager."));
OP_REQUIRES_OK(ctx, rm->Delete<Stack>(container, stack_name));
}
};
REGISTER_KERNEL_BUILDER(Name("StackClose").Device(DEVICE_CPU), StackCloseOp);
REGISTER_KERNEL_BUILDER(
Name("StackClose").Device(DEVICE_GPU).HostMemory("handle"), StackCloseOp);
} // namespace tensorflow
| 37.477387 | 80 | 0.680343 | [
"shape",
"vector"
] |
788dd7ffe35c2e4f58fda11d54ce19b0a35be408 | 5,101 | cc | C++ | ext.cc | MadPidgeon/Graph-Isomorphism | 30fb35a6faad8bda0663d49aff2fca1f2f69c56d | [
"MIT"
] | null | null | null | ext.cc | MadPidgeon/Graph-Isomorphism | 30fb35a6faad8bda0663d49aff2fca1f2f69c56d | [
"MIT"
] | null | null | null | ext.cc | MadPidgeon/Graph-Isomorphism | 30fb35a6faad8bda0663d49aff2fca1f2f69c56d | [
"MIT"
] | null | null | null | #include <iostream>
#include "ext.h"
std::ostream& operator<<( std::ostream& os, Empty ) {
return os << "Ø";
}
range::iterator::iterator( int i ) : _i( i ) {
}
range::iterator::iterator( const self_type& other ) {
_i = other._i;
}
range::iterator::self_type range::iterator::operator++(int) {
self_type r = *this;
++(*this);
return r;
}
range::iterator::self_type& range::iterator::operator++() {
++_i;
return *this;
}
range::iterator::reference range::iterator::operator*() {
return _i;
}
range::iterator::pointer range::iterator::operator->() {
return &_i;
}
bool range::iterator::operator==(const self_type& rhs) {
return _i == rhs._i;
}
bool range::iterator::operator!=(const self_type& rhs) {
return _i != rhs._i;
}
size_t range::size() const {
return _m-_n;
}
range::iterator range::begin() {
return iterator( _n );
}
range::iterator range::end() {
return iterator( _m );
}
range::operator std::deque<int>() const {
std::deque<int> S( _n );
std::iota( S.begin(), S.end(), 0 );
return S;
}
range::range( int n, int m ) : _n(n), _m(m) {}
all_tuples::iterator::iterator( int n, int r ) : _n(n), _r(r), _tuple( _r, 0 ) {
}
all_tuples::iterator::iterator( const self_type& other ) {
_n = other._n;
_r = other._r;
_tuple = other._tuple;
}
size_t all_tuples::size() const {
return pow( _n, _r );
}
all_tuples::iterator::self_type all_tuples::iterator::operator++(int) {
self_type i = *this;
++(*this);
return i;
}
all_tuples::iterator::self_type& all_tuples::iterator::operator++() {
for( int i = _r-1; i >= 0; i-- ) {
_tuple[i] += 1;
if( _tuple[i] == _n )
_tuple[i] = 0;
else
return *this;
}
_n = -1;
return *this;
}
all_tuples::iterator::reference all_tuples::iterator::operator*() {
return _tuple;
}
all_tuples::iterator::pointer all_tuples::iterator::operator->() {
return &_tuple;
}
bool all_tuples::iterator::operator==(const self_type& rhs) {
return _n == rhs._n && _tuple == rhs._tuple;;
}
bool all_tuples::iterator::operator!=(const self_type& rhs) {
return _n != rhs._n || _tuple != rhs._tuple;
}
all_tuples::iterator all_tuples::begin() const {
return iterator( _n, _r );
}
all_tuples::iterator all_tuples::end() const {
return iterator( -1, _r );
}
all_tuples::all_tuples( int n, int r ) : _n(n), _r(r) {}
all_ordered_tuples::iterator::iterator( int n, int r ) : _n(n), _r(r), _tuple( _r ) {
for( int i = 0; i < _r; i++ )
_tuple[i] = i;
}
all_ordered_tuples::iterator::iterator( const self_type& other ) {
_n = other._n;
_r = other._r;
_tuple = other._tuple;
}
all_ordered_tuples::iterator::self_type all_ordered_tuples::iterator::operator++(int) {
self_type i = *this;
++(*this);
return i;
}
all_ordered_tuples::iterator::self_type& all_ordered_tuples::iterator::operator++() {
if( _tuple[_r-1] < _n-1 )
_tuple[_r-1]++;
else {
int i = _r-1;
while( i --> 0 )
if( _tuple[i+1] != _tuple[i]+1 )
break;
if( i == -1 )
_n = -1;
else {
_tuple[i]++;
for( int j = i+1; j < _r; j++ )
_tuple[j] = _tuple[j-1]+1;
}
}
return *this;
}
all_ordered_tuples::iterator::reference all_ordered_tuples::iterator::operator*() {
return _tuple;
}
all_ordered_tuples::iterator::pointer all_ordered_tuples::iterator::operator->() {
return &_tuple;
}
bool all_ordered_tuples::iterator::operator==(const self_type& rhs) {
return _n == rhs._n && ( _n == -1 || _tuple == rhs._tuple );
}
bool all_ordered_tuples::iterator::operator!=(const self_type& rhs) {
return _n != rhs._n || ( _n != -1 && _tuple != rhs._tuple );
}
all_ordered_tuples::iterator all_ordered_tuples::begin() const {
return iterator( _n, _r );
}
all_ordered_tuples::iterator all_ordered_tuples::end() const {
return iterator( -1, _r );
}
size_t all_ordered_tuples::size() const {
return binom( _n, _r );
}
range all_ordered_tuples::parent_set() const {
return range( 0, _n );
}
all_ordered_tuples::all_ordered_tuples( int n, int r ) : _n(n), _r(r) {}
int pow( int n, int k ) {
int r = 1;
while( k --> 0 )
r *= n;
return r;
}
std::vector<int> inverse_mapping( const std::vector<int>& d ) {
std::vector<int> r( d.size(), 0 );
for( size_t i = 0; i < d.size(); i++ )
r[d[i]] = i;
return r;
}
uint binom( int n, int k ) {
uint ans = 1;
k = std::max( k, n-k );
for( int j = 1; j <= k; j++, n-- ) {
if( n%j==0 )
ans *= n/j;
else if( ans%j == 0 )
ans = ans/j*n;
else
ans = (ans*n)/j;
}
return ans;
}
bool bipartiteMatching_Subroutine( const matrix<bool>& M, int p, std::vector<bool>& seen, std::vector<int>& match ) {
for( int q : range( 0, M.height() ) ) {
if( M.at(p,q) and not seen.at(q) ) {
seen.at(q) = true;
if( match.at(q) < 0 or bipartiteMatching_Subroutine( M, match.at(q), seen, match ) ) {
match.at(q) = p;
return true;
}
}
}
return false;
}
std::vector<int> bipartiteMatching( const matrix<bool>& M ) {
std::vector<int> match( M.width(), -1 );
for( int p : range( 0, M.height() ) ) {
std::vector<bool> seen( M.width(), false );
bipartiteMatching_Subroutine( M, p, seen, match );
}
return match;
} | 21.343096 | 117 | 0.619878 | [
"vector"
] |
788f0f2f1150827d98473c0b538afce06c4ff7bf | 6,778 | cpp | C++ | src/UriHandler.cpp | spjuanjoc/uri_parser_cpp | 83c67bf29b12f3eee55c78661aad8495f08f73b3 | [
"MIT"
] | null | null | null | src/UriHandler.cpp | spjuanjoc/uri_parser_cpp | 83c67bf29b12f3eee55c78661aad8495f08f73b3 | [
"MIT"
] | null | null | null | src/UriHandler.cpp | spjuanjoc/uri_parser_cpp | 83c67bf29b12f3eee55c78661aad8495f08f73b3 | [
"MIT"
] | null | null | null | #include "UriHandler.h"
#include <algorithm>
#include <cctype>
#include <iostream>
#include <sstream>
#include <utility>
#include <vector>
using std::stringstream;
using std::uint32_t;
using std::vector;
constexpr auto MIN_PORT = 0;
constexpr auto MAX_PORT = 65535;
namespace urii
{
UriHandler::UriHandler(std::string uri) : m_uri{std::move(uri)}
{
parseUri(m_uri);
}
bool UriHandler::hasPort() const
{
return m_has_port;
}
bool UriHandler::isValidUri() const
{
return m_is_valid_uri;
}
bool UriHandler::isValidIPv4(const std::string& host)
{
std::string sIP{host};
std::replace_if(
sIP.begin(),
sIP.end(),
[](const char c) { return c == '.'; },
' ');
std::stringstream ss;
ss << sIP;
bool allDigits = true;
while (!ss.eof())
{
std::string tmp;
ss >> tmp;
for (unsigned char c : tmp)
{
allDigits &= (isdigit(c) != 0);
}
}
return allDigits;
}
bool UriHandler::isValidHextet(const std::string& hextet)
{
std::stringstream ss;
int outHex = 0x0;
ss << hextet;
ss >> std::hex >> outHex;
ss.str("");
ss.clear();
ss << outHex;
return (ss.str() == hextet);
}
bool UriHandler::isValidIPv6(const std::string& host)
{
const uint32_t MAX_NUM_OF_HEXETS = 8;
bool valid = true;
std::string result = cropIPv6(host);
std::string section{result};
std::replace_if(
section.begin(),
section.end(),
[](char c) { return c == ':'; },
' ');
std::stringstream ss;
ss << section;
uint32_t counter = 0;
while (!ss.eof())
{
std::string hexet;
ss >> hexet;
valid &= isValidHextet(hexet);
++counter;
}
if (counter > MAX_NUM_OF_HEXETS)
{
valid = false;
}
return valid;
}
bool UriHandler::isValidRegName(const std::string& host)
{
return true; /// \todo implement
}
std::string UriHandler::cropIPv6(const std::string& ip)
{
std::string result{ip};
auto pos1 = result.find(']');
if (pos1 != std::string::npos)
{
result = result.substr(0, pos1 + 1);
}
result.erase(std::remove_if(result.begin(), result.end(), [](char c) { return (c == '[' || c == ']'); }),
result.end());
auto pos = result.find('%');
if (pos != std::string::npos)
{
result = result.substr(0, pos);
}
return result;
}
std::string UriHandler::getAuthority() const
{
return m_authority;
}
std::string UriHandler::getFragment() const
{
return m_fragment;
}
std::string UriHandler::getHost() const
{
return m_full_authority.m_host;
}
std::string UriHandler::getPath() const
{
return m_path;
}
std::string UriHandler::getPort() const
{
return m_full_authority.m_port;
}
std::string UriHandler::getQuery() const
{
return m_query;
}
std::string UriHandler::getScheme() const
{
return m_scheme;
}
std::string UriHandler::getUserInfo() const
{
return m_full_authority.m_user_info;
}
void UriHandler::parseAuthority(const std::string& authority)
{
const auto& itIpVersion = authority.find(']');
if (itIpVersion != std::string::npos)
{
std::string port = authority.substr(itIpVersion);
const auto& itPort = port.find(':');
if (itPort != std::string::npos)
{
m_has_port = true;
parsePort(port, itPort);
}
if (isValidIPv6(authority))
{
m_host_type = HostType::IPv6;
m_is_valid_uri = true;
m_full_authority.m_host = authority.substr(0, itIpVersion + 1);
}
else
{
m_is_valid_uri = false;
m_host_type = HostType::Unknown;
}
}
else
{
std::string host = authority;
const auto& itPort = authority.find(':');
if (itPort != std::string::npos)
{
std::string tempPort = authority;
tempPort = tempPort.substr(itPort + 1);
const auto& itValid = tempPort.find(':');
if (itValid != std::string::npos)
{
m_is_valid_uri = false;
return;
//ipv6 with no []
}
m_has_port = true;
host = host.substr(0, itPort);
parsePort(authority, itPort);
}
if (isValidIPv4(host))
{
m_host_type = HostType::IPv4;
m_is_valid_uri = true;
m_full_authority.m_host = host;
}
else if (isValidRegName(host))
{
m_host_type = HostType::RegName;
m_is_valid_uri = true;
m_full_authority.m_host = host;
}
else
{
m_is_valid_uri = false;
m_host_type = HostType::Unknown;
}
}
parseUserInfo();
}
void UriHandler::parsePort(const std::string& port, const unsigned& position)
{
m_full_authority.m_port = port.substr(position);
m_full_authority.m_port.erase(std::remove_if(m_full_authority.m_port.begin(),
m_full_authority.m_port.end(),
[](unsigned char c) { return isdigit(c) == 0; }),
m_full_authority.m_port.end());
auto uPort = std::stoi(m_full_authority.m_port);
// port range: 0 to 65535
if (uPort < MIN_PORT || uPort > MAX_PORT)
{
m_full_authority.m_port = "";
m_is_valid_uri = false;
}
}
void UriHandler::parseUserInfo()
{
auto it = m_full_authority.m_host.find('@');
if (it != std::string::npos)
{
m_full_authority.m_user_info = m_full_authority.m_host.substr(0, it);
m_full_authority.m_host = m_full_authority.m_host.substr(it + 1);
}
}
void UriHandler::parseUri(const std::string& uri)
{
std::string sUri{uri};
std::replace_if(
sUri.begin(),
sUri.end(),
[](const char c) { return c == '/'; },
' ');
std::stringstream ss;
ss << sUri;
vector<std::string> uriVec;
while (!ss.eof())
{
std::string tmp;
ss >> tmp;
uriVec.emplace_back(tmp);
}
size_t vecSize = uriVec.size();
if (vecSize >= 2)
{
m_scheme = uriVec.at(0);
m_scheme.erase(std::remove_if(m_scheme.begin(), m_scheme.end(), [](unsigned char c) { return !isalpha(c); }),
m_scheme.end());
m_authority = uriVec.at(1);
parseAuthority(m_authority);
}
if (vecSize >= 3)
{
auto itPath = uriVec.begin();
std::advance(itPath, 2);
for (auto it = itPath; it < uriVec.end(); ++it)
{
m_path.append("/");
m_path.append(*it);
}
parsePath();
}
if (vecSize < 2)
{
m_is_valid_uri = false;
}
}
void UriHandler::parsePath()
{
std::string tmp = m_path;
auto it = tmp.find('#');
if (it != std::string::npos)
{
m_fragment = tmp.substr(it + 1);
m_path = tmp.substr(0, it);
}
auto it2 = m_path.find('?');
if (it2 != std::string::npos)
{
m_query = m_path.substr(it2 + 1);
m_path = tmp.substr(0, it2);
}
}
} // namespace urii
| 21.18125 | 113 | 0.586899 | [
"vector"
] |
7897e606f5ff5801ce3f842ac56246b129dd7928 | 5,769 | cpp | C++ | ngraph/core/src/node_input.cpp | alvoron/openvino | 862176d1d4ab407c99445efa1cf5c4e277fd23e3 | [
"Apache-2.0"
] | null | null | null | ngraph/core/src/node_input.cpp | alvoron/openvino | 862176d1d4ab407c99445efa1cf5c4e277fd23e3 | [
"Apache-2.0"
] | 29 | 2020-11-23T14:25:43.000Z | 2022-02-21T13:03:30.000Z | ngraph/core/src/node_input.cpp | v-Golubev/openvino | 26936d1fbb025c503ee43fe74593ee9d7862ab15 | [
"Apache-2.0"
] | null | null | null | // Copyright (C) 2018-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include "ngraph/node_input.hpp"
#include "ngraph/node.hpp"
namespace ngraph
{
Input<Node>::Input(Node* node, size_t index)
: m_node(node)
, m_index(index)
{
}
Node* Input<Node>::get_node() const { return m_node; }
size_t Input<Node>::get_index() const { return m_index; }
const element::Type& Input<Node>::get_element_type() const
{
return m_node->get_input_element_type(m_index);
}
const Shape& Input<Node>::get_shape() const { return m_node->get_input_shape(m_index); }
const PartialShape& Input<Node>::get_partial_shape() const
{
return m_node->get_input_partial_shape(m_index);
}
Output<Node> Input<Node>::get_source_output() const
{
auto& output_descriptor = m_node->m_inputs.at(m_index).get_output();
return Output<Node>(output_descriptor.get_node(), output_descriptor.get_index());
}
descriptor::Tensor& Input<Node>::get_tensor() const
{
return m_node->m_inputs.at(m_index).get_output().get_tensor();
}
std::shared_ptr<descriptor::Tensor> Input<Node>::get_tensor_ptr() const
{
return m_node->m_inputs.at(m_index).get_output().get_tensor_ptr();
}
bool Input<Node>::get_is_relevant_to_shapes() const
{
return m_node->m_inputs.at(m_index).get_is_relevant_to_shape();
}
bool Input<Node>::get_is_relevant_to_values() const
{
return m_node->m_inputs.at(m_index).get_is_relevant_to_value();
}
void Input<Node>::replace_source_output(const Output<Node>& new_source_output) const
{
m_node->m_inputs.at(m_index).replace_output(new_source_output.get_node_shared_ptr(),
new_source_output.get_index());
}
bool Input<Node>::operator==(const Input& other) const
{
return m_node == other.m_node && m_index == other.m_index;
}
bool Input<Node>::operator!=(const Input& other) const { return !(*this == other); }
bool Input<Node>::operator<(const Input& other) const
{
return m_node < other.m_node || (m_node == other.m_node && m_index < other.m_index);
}
bool Input<Node>::operator>(const Input& other) const
{
return m_node > other.m_node || (m_node == other.m_node && m_index > other.m_index);
}
bool Input<Node>::operator<=(const Input& other) const { return !(*this > other); }
bool Input<Node>::operator>=(const Input& other) const { return !(*this < other); }
Input<const Node>::Input(const Node* node, size_t index)
: m_node(node)
, m_index(index)
{
}
RTMap& Input<Node>::get_rt_info() { return m_node->m_inputs.at(m_index).get_rt_info(); }
const RTMap& Input<Node>::get_rt_info() const
{
return m_node->m_inputs.at(m_index).get_rt_info();
}
const RTMap& Input<const Node>::get_rt_info() const
{
return m_node->m_inputs.at(m_index).get_rt_info();
}
const Node* Input<const Node>::get_node() const { return m_node; }
size_t Input<const Node>::get_index() const { return m_index; }
const element::Type& Input<const Node>::get_element_type() const
{
return m_node->get_input_element_type(m_index);
}
const Shape& Input<const Node>::get_shape() const { return m_node->get_input_shape(m_index); }
const PartialShape& Input<const Node>::get_partial_shape() const
{
return m_node->get_input_partial_shape(m_index);
}
Output<Node> Input<const Node>::get_source_output() const
{
auto& output_descriptor = m_node->m_inputs.at(m_index).get_output();
return Output<Node>(output_descriptor.get_node(), output_descriptor.get_index());
}
descriptor::Tensor& Input<const Node>::get_tensor() const
{
return m_node->m_inputs.at(m_index).get_output().get_tensor();
}
std::shared_ptr<descriptor::Tensor> Input<const Node>::get_tensor_ptr() const
{
return m_node->m_inputs.at(m_index).get_output().get_tensor_ptr();
}
bool Input<const Node>::get_is_relevant_to_shapes() const
{
return m_node->m_inputs.at(m_index).get_is_relevant_to_shape();
}
bool Input<const Node>::get_is_relevant_to_values() const
{
return m_node->m_inputs.at(m_index).get_is_relevant_to_value();
}
bool Input<const Node>::operator==(const Input& other) const
{
return m_node == other.m_node && m_index == other.m_index;
}
bool Input<const Node>::operator!=(const Input& other) const { return !(*this == other); }
bool Input<const Node>::operator<(const Input& other) const
{
return m_node < other.m_node || (m_node == other.m_node && m_index < other.m_index);
}
bool Input<const Node>::operator>(const Input& other) const
{
return m_node > other.m_node || (m_node == other.m_node && m_index > other.m_index);
}
bool Input<const Node>::operator<=(const Input& other) const { return !(*this > other); }
bool Input<const Node>::operator>=(const Input& other) const { return !(*this < other); }
std::ostream& operator<<(std::ostream& out, const Input<Node>& input)
{
return input.get_node()->write_description(out, 0)
<< ".input(" << input.get_index() << "):" << input.get_element_type()
<< input.get_partial_shape();
}
std::ostream& operator<<(std::ostream& out, const Input<const Node>& input)
{
return input.get_node()->write_description(out, 0)
<< ".input(" << input.get_index() << "):" << input.get_element_type()
<< input.get_partial_shape();
}
} // namespace ngraph
| 34.54491 | 98 | 0.641186 | [
"shape"
] |
789aff5f007aff7f5c758f41b710ae9116866cfb | 5,647 | cc | C++ | hessian2/basic_codec/map_codec_unittests.cc | yun1129/hessian2-codec | 8e61255ebe0b257173da7d5f78950f6d776c5c3d | [
"Apache-2.0"
] | 1 | 2021-01-07T13:24:34.000Z | 2021-01-07T13:24:34.000Z | hessian2/basic_codec/map_codec_unittests.cc | yun1129/hessian2-codec | 8e61255ebe0b257173da7d5f78950f6d776c5c3d | [
"Apache-2.0"
] | null | null | null | hessian2/basic_codec/map_codec_unittests.cc | yun1129/hessian2-codec | 8e61255ebe0b257173da7d5f78950f6d776c5c3d | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <type_traits>
#include "gtest/gtest.h"
#include "hessian2/basic_codec/object_codec.hpp"
#include "hessian2/basic_codec/list_codec.hpp"
#include "hessian2/basic_codec/map_codec.hpp"
#include "hessian2/test_framework/decoder_test_framework.h"
#include "hessian2/test_framework/encoder_test_framework.h"
namespace hessian2 {
TEST_F(TestDecoderFramework, DecoderJavaTestCaseForMap) {
{
Object::UntypedMap o;
UntypedMapObject obj(std::move(o));
EXPECT_TRUE(Decode<UntypedMapObject>("replyUntypedMap_0", obj));
}
{
Object::UntypedMap o;
o.emplace(std::make_unique<StringObject>(absl::string_view("a")),
std::make_unique<IntegerObject>(0));
UntypedMapObject obj(std::move(o));
EXPECT_TRUE(Decode<UntypedMapObject>("replyUntypedMap_1", obj));
}
{
Object::UntypedMap o;
o.emplace(std::make_unique<IntegerObject>(0),
std::make_unique<StringObject>(absl::string_view("a")));
o.emplace(std::make_unique<IntegerObject>(1),
std::make_unique<StringObject>(absl::string_view("b")));
UntypedMapObject obj(std::move(o));
EXPECT_TRUE(Decode<UntypedMapObject>("replyUntypedMap_2", obj));
}
{
Object::UntypedMap o;
Object::UntypedList o_list;
o_list.emplace_back(std::make_unique<StringObject>(absl::string_view("a")));
o.emplace(std::make_unique<UntypedListObject>(std::move(o_list)),
std::make_unique<IntegerObject>(0));
UntypedMapObject obj(std::move(o));
EXPECT_TRUE(Decode<UntypedMapObject>("replyUntypedMap_3", obj));
}
{
Object::TypedMap o;
o.type_name_ = "java.util.Hashtable";
TypedMapObject obj(std::move(o));
EXPECT_TRUE(Decode<TypedMapObject>("replyTypedMap_0", obj));
}
{
Object::TypedMap o;
o.type_name_ = "java.util.Hashtable";
o.field_name_and_value_.emplace(
std::make_unique<StringObject>(absl::string_view("a")),
std::make_unique<IntegerObject>(0));
TypedMapObject obj(std::move(o));
EXPECT_TRUE(Decode<TypedMapObject>("replyTypedMap_1", obj));
}
{
Object::TypedMap o;
o.type_name_ = "java.util.Hashtable";
o.field_name_and_value_.emplace(
std::make_unique<IntegerObject>(0),
std::make_unique<StringObject>(absl::string_view("a")));
o.field_name_and_value_.emplace(
std::make_unique<IntegerObject>(1),
std::make_unique<StringObject>(absl::string_view("b")));
TypedMapObject obj(std::move(o));
EXPECT_TRUE(Decode<TypedMapObject>("replyTypedMap_2", obj));
}
{
Object::TypedMap o;
Object::UntypedList o_list;
o_list.emplace_back(std::make_unique<StringObject>(absl::string_view("a")));
o.type_name_ = "java.util.Hashtable";
o.field_name_and_value_.emplace(
std::make_unique<UntypedListObject>(std::move(o_list)),
std::make_unique<IntegerObject>(0));
TypedMapObject obj(std::move(o));
EXPECT_TRUE(Decode<TypedMapObject>("replyTypedMap_3", obj));
}
}
TEST_F(TestEncoderFramework, EncoderJavaTestCaseForMap) {
{
Object::UntypedMap o;
UntypedMapObject obj(std::move(o));
EXPECT_TRUE(Encode<UntypedMapObject>("argUntypedMap_0", obj));
}
{
Object::UntypedMap o;
o.emplace(std::make_unique<StringObject>(absl::string_view("a")),
std::make_unique<IntegerObject>(0));
UntypedMapObject obj(std::move(o));
EXPECT_TRUE(Encode<UntypedMapObject>("argUntypedMap_1", obj));
}
{
Object::UntypedMap o;
o.emplace(std::make_unique<IntegerObject>(0),
std::make_unique<StringObject>(absl::string_view("a")));
o.emplace(std::make_unique<IntegerObject>(1),
std::make_unique<StringObject>(absl::string_view("b")));
UntypedMapObject obj(std::move(o));
EXPECT_TRUE(Encode<UntypedMapObject>("argUntypedMap_2", obj));
}
{
Object::UntypedMap o;
Object::UntypedList o_list;
o_list.emplace_back(std::make_unique<StringObject>(absl::string_view("a")));
o.emplace(std::make_unique<UntypedListObject>(std::move(o_list)),
std::make_unique<IntegerObject>(0));
UntypedMapObject obj(std::move(o));
EXPECT_TRUE(Encode<UntypedMapObject>("argUntypedMap_3", obj));
}
{
Object::TypedMap o;
o.type_name_ = "java.util.Hashtable";
TypedMapObject obj(std::move(o));
EXPECT_TRUE(Encode<TypedMapObject>("argTypedMap_0", obj));
}
{
Object::TypedMap o;
o.type_name_ = "java.util.Hashtable";
o.field_name_and_value_.emplace(
std::make_unique<StringObject>(absl::string_view("a")),
std::make_unique<IntegerObject>(0));
TypedMapObject obj(std::move(o));
EXPECT_TRUE(Encode<TypedMapObject>("argTypedMap_1", obj));
}
{
Object::TypedMap o;
o.type_name_ = "java.util.Hashtable";
o.field_name_and_value_.emplace(
std::make_unique<IntegerObject>(0),
std::make_unique<StringObject>(absl::string_view("a")));
o.field_name_and_value_.emplace(
std::make_unique<IntegerObject>(1),
std::make_unique<StringObject>(absl::string_view("b")));
TypedMapObject obj(std::move(o));
EXPECT_TRUE(Encode<TypedMapObject>("argTypedMap_2", obj));
}
{
Object::TypedMap o;
Object::UntypedList o_list;
o_list.emplace_back(std::make_unique<StringObject>(absl::string_view("a")));
o.type_name_ = "java.util.Hashtable";
o.field_name_and_value_.emplace(
std::make_unique<UntypedListObject>(std::move(o_list)),
std::make_unique<IntegerObject>(0));
TypedMapObject obj(std::move(o));
EXPECT_TRUE(Encode<TypedMapObject>("argTypedMap_3", obj));
}
}
} // namespace hessian2
| 33.217647 | 80 | 0.683726 | [
"object"
] |
789eb51cac632eb92ae526227bddff658dad1a76 | 4,308 | hpp | C++ | stan/math/opencl/prim/frechet_lccdf.hpp | LaudateCorpus1/math | 990a66b3cccd27a5fd48626360bb91093a48278b | [
"BSD-3-Clause"
] | null | null | null | stan/math/opencl/prim/frechet_lccdf.hpp | LaudateCorpus1/math | 990a66b3cccd27a5fd48626360bb91093a48278b | [
"BSD-3-Clause"
] | null | null | null | stan/math/opencl/prim/frechet_lccdf.hpp | LaudateCorpus1/math | 990a66b3cccd27a5fd48626360bb91093a48278b | [
"BSD-3-Clause"
] | null | null | null | #ifndef STAN_MATH_OPENCL_PRIM_FRECHET_LCCDF_HPP
#define STAN_MATH_OPENCL_PRIM_FRECHET_LCCDF_HPP
#ifdef STAN_OPENCL
#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/err.hpp>
#include <stan/math/prim/fun/constants.hpp>
#include <stan/math/prim/fun/elt_divide.hpp>
#include <stan/math/prim/fun/elt_multiply.hpp>
#include <stan/math/opencl/kernel_generator.hpp>
#include <stan/math/prim/functor/operands_and_partials.hpp>
namespace stan {
namespace math {
/** \ingroup opencl
* Returns the frechet log complementary cumulative distribution function for
* the given location, and scale. If given containers of matching sizes returns
* the product of probabilities.
*
* @tparam T_y_cl type of scalar outcome
* @tparam T_shape_cl type of location
* @tparam T_scale_cl type of scale
* @param y (Sequence of) scalar(s).
* @param alpha (Sequence of) location(s).
* @param sigma (Sequence of) scale(s).
* @return The log of the product of densities.
*/
template <
typename T_y_cl, typename T_shape_cl, typename T_scale_cl,
require_all_prim_or_rev_kernel_expression_t<T_y_cl, T_shape_cl,
T_scale_cl>* = nullptr,
require_any_not_stan_scalar_t<T_y_cl, T_shape_cl, T_scale_cl>* = nullptr>
return_type_t<T_y_cl, T_shape_cl, T_scale_cl> frechet_lccdf(
const T_y_cl& y, const T_shape_cl& alpha, const T_scale_cl& sigma) {
static const char* function = "frechet_lccdf(OpenCL)";
using T_partials_return = partials_return_t<T_y_cl, T_shape_cl, T_scale_cl>;
using std::isfinite;
using std::isnan;
check_consistent_sizes(function, "Random variable", y, "Shape parameter",
alpha, "Scale parameter", sigma);
const size_t N = max_size(y, alpha, sigma);
if (N == 0) {
return 1.0;
}
const auto& y_col = as_column_vector_or_scalar(y);
const auto& alpha_col = as_column_vector_or_scalar(alpha);
const auto& sigma_col = as_column_vector_or_scalar(sigma);
const auto& y_val = value_of(y_col);
const auto& alpha_val = value_of(alpha_col);
const auto& sigma_val = value_of(sigma_col);
auto check_y_positive
= check_cl(function, "Random variable", y_val, "positive");
auto y_positive = y_val > 0;
auto check_alpha_positive_finite
= check_cl(function, "Shape parameter", alpha_val, "positive finite");
auto alpha_positive_finite_expr = alpha_val > 0 && isfinite(alpha_val);
auto check_sigma_positive_finite
= check_cl(function, "Scale parameter", sigma_val, "positive finite");
auto sigma_positive_finite_expr = 0 < sigma_val && isfinite(sigma_val);
auto pow_n = pow(elt_divide(sigma_val, y_val), alpha_val);
auto exp_n = exp(-pow_n);
auto lccdf_expr = colwise_sum(log1m(exp_n));
auto rep_deriv = elt_divide(pow_n, elt_divide(1.0, exp_n) - 1.0);
auto y_deriv = elt_multiply(elt_divide(-alpha_val, y_val), rep_deriv);
auto alpha_deriv
= elt_multiply(-log(elt_divide(y_val, sigma_val)), rep_deriv);
auto sigma_deriv = elt_multiply(elt_divide(alpha_val, sigma_val), rep_deriv);
matrix_cl<double> lccdf_cl;
matrix_cl<double> y_deriv_cl;
matrix_cl<double> alpha_deriv_cl;
matrix_cl<double> sigma_deriv_cl;
results(check_y_positive, check_alpha_positive_finite,
check_sigma_positive_finite, lccdf_cl, y_deriv_cl, alpha_deriv_cl,
sigma_deriv_cl)
= expressions(y_positive, alpha_positive_finite_expr,
sigma_positive_finite_expr, lccdf_expr,
calc_if<!is_constant<T_y_cl>::value>(y_deriv),
calc_if<!is_constant<T_shape_cl>::value>(alpha_deriv),
calc_if<!is_constant<T_scale_cl>::value>(sigma_deriv));
T_partials_return lccdf = (from_matrix_cl(lccdf_cl)).sum();
operands_and_partials<decltype(y_col), decltype(alpha_col),
decltype(sigma_col)>
ops_partials(y_col, alpha_col, sigma_col);
if (!is_constant<T_y_cl>::value) {
ops_partials.edge1_.partials_ = std::move(y_deriv_cl);
}
if (!is_constant<T_shape_cl>::value) {
ops_partials.edge2_.partials_ = std::move(alpha_deriv_cl);
}
if (!is_constant<T_scale_cl>::value) {
ops_partials.edge3_.partials_ = std::move(sigma_deriv_cl);
}
return ops_partials.build(lccdf);
}
} // namespace math
} // namespace stan
#endif
#endif
| 38.464286 | 79 | 0.721216 | [
"shape"
] |
a19345a6609e882025ed5aef18e761447d6755b3 | 8,753 | cc | C++ | remoting/host/chromoting_param_traits.cc | Wzzzx/chromium-crosswalk | 768dde8efa71169f1c1113ca6ef322f1e8c9e7de | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2019-01-28T08:09:58.000Z | 2021-11-15T15:32:10.000Z | remoting/host/chromoting_param_traits.cc | maidiHaitai/haitaibrowser | a232a56bcfb177913a14210e7733e0ea83a6b18d | [
"BSD-3-Clause"
] | null | null | null | remoting/host/chromoting_param_traits.cc | maidiHaitai/haitaibrowser | a232a56bcfb177913a14210e7733e0ea83a6b18d | [
"BSD-3-Clause"
] | 6 | 2020-09-23T08:56:12.000Z | 2021-11-18T03:40:49.000Z | // Copyright 2013 The Chromium 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 "remoting/host/chromoting_param_traits.h"
#include <stdint.h>
#include "base/strings/stringprintf.h"
#include "ipc/ipc_message_utils.h"
#include "third_party/webrtc/modules/desktop_capture/desktop_frame.h"
namespace IPC {
// static
void ParamTraits<webrtc::DesktopVector>::GetSize(base::PickleSizer* s,
const param_type& p) {
GetParamSize(s, p.x());
GetParamSize(s, p.y());
}
// static
void ParamTraits<webrtc::DesktopVector>::Write(base::Pickle* m,
const webrtc::DesktopVector& p) {
m->WriteInt(p.x());
m->WriteInt(p.y());
}
// static
bool ParamTraits<webrtc::DesktopVector>::Read(const base::Pickle* m,
base::PickleIterator* iter,
webrtc::DesktopVector* r) {
int x, y;
if (!iter->ReadInt(&x) || !iter->ReadInt(&y))
return false;
*r = webrtc::DesktopVector(x, y);
return true;
}
// static
void ParamTraits<webrtc::DesktopVector>::Log(const webrtc::DesktopVector& p,
std::string* l) {
l->append(base::StringPrintf("webrtc::DesktopVector(%d, %d)",
p.x(), p.y()));
}
// static
void ParamTraits<webrtc::DesktopSize>::GetSize(base::PickleSizer* s,
const param_type& p) {
GetParamSize(s, p.width());
GetParamSize(s, p.height());
}
// static
void ParamTraits<webrtc::DesktopSize>::Write(base::Pickle* m,
const webrtc::DesktopSize& p) {
m->WriteInt(p.width());
m->WriteInt(p.height());
}
// static
bool ParamTraits<webrtc::DesktopSize>::Read(const base::Pickle* m,
base::PickleIterator* iter,
webrtc::DesktopSize* r) {
int width, height;
if (!iter->ReadInt(&width) || !iter->ReadInt(&height))
return false;
*r = webrtc::DesktopSize(width, height);
return true;
}
// static
void ParamTraits<webrtc::DesktopSize>::Log(const webrtc::DesktopSize& p,
std::string* l) {
l->append(base::StringPrintf("webrtc::DesktopSize(%d, %d)",
p.width(), p.height()));
}
// static
void ParamTraits<webrtc::DesktopRect>::GetSize(base::PickleSizer* s,
const param_type& p) {
GetParamSize(s, p.left());
GetParamSize(s, p.top());
GetParamSize(s, p.right());
GetParamSize(s, p.bottom());
}
// static
void ParamTraits<webrtc::DesktopRect>::Write(base::Pickle* m,
const webrtc::DesktopRect& p) {
m->WriteInt(p.left());
m->WriteInt(p.top());
m->WriteInt(p.right());
m->WriteInt(p.bottom());
}
// static
bool ParamTraits<webrtc::DesktopRect>::Read(const base::Pickle* m,
base::PickleIterator* iter,
webrtc::DesktopRect* r) {
int left, right, top, bottom;
if (!iter->ReadInt(&left) || !iter->ReadInt(&top) ||
!iter->ReadInt(&right) || !iter->ReadInt(&bottom)) {
return false;
}
*r = webrtc::DesktopRect::MakeLTRB(left, top, right, bottom);
return true;
}
// static
void ParamTraits<webrtc::DesktopRect>::Log(const webrtc::DesktopRect& p,
std::string* l) {
l->append(base::StringPrintf("webrtc::DesktopRect(%d, %d, %d, %d)",
p.left(), p.top(), p.right(), p.bottom()));
}
// static
void ParamTraits<webrtc::MouseCursor>::Write(base::Pickle* m,
const webrtc::MouseCursor& p) {
ParamTraits<webrtc::DesktopSize>::Write(m, p.image()->size());
// Data is serialized in such a way that size is exactly width * height *
// |kBytesPerPixel|.
std::string data;
uint8_t* current_row = p.image()->data();
for (int y = 0; y < p.image()->size().height(); ++y) {
data.append(current_row,
current_row + p.image()->size().width() *
webrtc::DesktopFrame::kBytesPerPixel);
current_row += p.image()->stride();
}
m->WriteData(reinterpret_cast<const char*>(p.image()->data()), data.size());
ParamTraits<webrtc::DesktopVector>::Write(m, p.hotspot());
}
// static
bool ParamTraits<webrtc::MouseCursor>::Read(const base::Pickle* m,
base::PickleIterator* iter,
webrtc::MouseCursor* r) {
webrtc::DesktopSize size;
if (!ParamTraits<webrtc::DesktopSize>::Read(m, iter, &size) ||
size.width() <= 0 || size.width() > (SHRT_MAX / 2) ||
size.height() <= 0 || size.height() > (SHRT_MAX / 2)) {
return false;
}
const int expected_length =
size.width() * size.height() * webrtc::DesktopFrame::kBytesPerPixel;
const char* data;
int data_length;
if (!iter->ReadData(&data, &data_length) || data_length != expected_length)
return false;
webrtc::DesktopVector hotspot;
if (!ParamTraits<webrtc::DesktopVector>::Read(m, iter, &hotspot))
return false;
webrtc::BasicDesktopFrame* image = new webrtc::BasicDesktopFrame(size);
memcpy(image->data(), data, data_length);
r->set_image(image);
r->set_hotspot(hotspot);
return true;
}
// static
void ParamTraits<webrtc::MouseCursor>::Log(
const webrtc::MouseCursor& p,
std::string* l) {
l->append(base::StringPrintf(
"webrtc::DesktopRect{image(%d, %d), hotspot(%d, %d)}",
p.image()->size().width(), p.image()->size().height(),
p.hotspot().x(), p.hotspot().y()));
}
// static
void ParamTraits<remoting::ScreenResolution>::Write(
base::Pickle* m,
const remoting::ScreenResolution& p) {
ParamTraits<webrtc::DesktopSize>::Write(m, p.dimensions());
ParamTraits<webrtc::DesktopVector>::Write(m, p.dpi());
}
// static
bool ParamTraits<remoting::ScreenResolution>::Read(
const base::Pickle* m,
base::PickleIterator* iter,
remoting::ScreenResolution* r) {
webrtc::DesktopSize size;
webrtc::DesktopVector dpi;
if (!ParamTraits<webrtc::DesktopSize>::Read(m, iter, &size) ||
!ParamTraits<webrtc::DesktopVector>::Read(m, iter, &dpi)) {
return false;
}
if (size.width() < 0 || size.height() < 0 ||
dpi.x() < 0 || dpi.y() < 0) {
return false;
}
*r = remoting::ScreenResolution(size, dpi);
return true;
}
// static
void ParamTraits<remoting::ScreenResolution>::Log(
const remoting::ScreenResolution& p,
std::string* l) {
l->append(base::StringPrintf("webrtc::ScreenResolution(%d, %d, %d, %d)",
p.dimensions().width(), p.dimensions().height(),
p.dpi().x(), p.dpi().y()));
}
// static
void ParamTraits<net::IPAddress>::GetSize(base::PickleSizer* s,
const param_type& p) {
GetParamSize(s, p.bytes());
}
// static
void ParamTraits<net::IPAddress>::Write(base::Pickle* m, const param_type& p) {
WriteParam(m, p.bytes());
}
// static
bool ParamTraits<net::IPAddress>::Read(const base::Pickle* m,
base::PickleIterator* iter,
param_type* p) {
std::vector<uint8_t> bytes;
if (!ReadParam(m, iter, &bytes))
return false;
net::IPAddress address(bytes);
if (address.empty() || address.IsValid()) {
*p = address;
return true;
}
return false;
}
// static
void ParamTraits<net::IPAddress>::Log(const param_type& p, std::string* l) {
l->append("IPAddress:" + (p.empty() ? "(empty)" : p.ToString()));
}
// static
void ParamTraits<net::IPEndPoint>::GetSize(base::PickleSizer* s,
const param_type& p) {
GetParamSize(s, p.address());
GetParamSize(s, p.port());
}
// static
void ParamTraits<net::IPEndPoint>::Write(base::Pickle* m, const param_type& p) {
WriteParam(m, p.address());
WriteParam(m, p.port());
}
// static
bool ParamTraits<net::IPEndPoint>::Read(const base::Pickle* m,
base::PickleIterator* iter,
param_type* p) {
net::IPAddress address;
uint16_t port;
if (!ReadParam(m, iter, &address) || !ReadParam(m, iter, &port))
return false;
*p = net::IPEndPoint(address, port);
return true;
}
// static
void ParamTraits<net::IPEndPoint>::Log(const param_type& p, std::string* l) {
l->append("IPEndPoint: " + p.ToString());
}
} // namespace IPC
| 31.260714 | 80 | 0.571575 | [
"vector"
] |
a199a63e582cb047761f6c54a58c535ff32edcfb | 2,006 | cpp | C++ | 103. Binary Tree Zigzag Level Order Traversal.cpp | zjuxiaoleiliu/leetcode | c81aa9dc2f1e64287206bc9d5437ebb2782f32f6 | [
"MIT"
] | null | null | null | 103. Binary Tree Zigzag Level Order Traversal.cpp | zjuxiaoleiliu/leetcode | c81aa9dc2f1e64287206bc9d5437ebb2782f32f6 | [
"MIT"
] | null | null | null | 103. Binary Tree Zigzag Level Order Traversal.cpp | zjuxiaoleiliu/leetcode | c81aa9dc2f1e64287206bc9d5437ebb2782f32f6 | [
"MIT"
] | null | null | null | 题目描述:
Given a binary tree, return the zigzag level order traversal of its nodes values.
(ie, from left to right, then right to left for the next level and alternate between).
For example:
Given binary tree{3,9,20,#,#,15,7},
3
/ \
9 20
/ \
15 7
return its zigzag level order traversal as:
[
[3],
[20,9],
[15,7]
]
confused what"{1,#,2,3}"means? > read more on how binary tree is serialized on OJ.
OJ's Binary Tree Serialization:
The serialization of a binary tree follows a level order traversal,
where '#' signifies a path terminator where no node exists below.
Here's an example:
1
/ \
2 3
/
4
\
5
The above binary tree is serialized as"{1,2,3,#,#,4,#,#,5}".
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int> > zigzagLevelOrder(TreeNode *root) {
vector<vector<int>> ret;
if(root == nullptr)
return ret;
stack<TreeNode*> s[2];
s[0].push(root);
int flag = 0;
vector<int> temp;
int size = 1;
while(!s[flag].empty())
{
TreeNode * cur = s[flag].top();
temp.push_back(cur->val);
if(flag==0)
{
if(cur->left!=nullptr)
s[1-flag].push(cur->left);
if(cur->right!=nullptr)
s[1-flag].push(cur->right);
}
else
{
if(cur->right!=nullptr)
s[1-flag].push(cur->right);
if(cur->left!=nullptr)
s[1-flag].push(cur->left);
}
s[flag].pop();
size--;
if(size==0)
{
ret.push_back(temp);
flag = 1-flag;
size = s[flag].size();
temp.clear();
}
}
return ret;
}
};
| 20.469388 | 88 | 0.497507 | [
"vector"
] |
a19a73d3b8a2cac09041320eb702efa0799a2838 | 8,416 | cpp | C++ | src/main_monitor.cpp | MilanMichael/robot_diagnostic | f67188015791b0ffdc6e0b1241321f8908d694ff | [
"BSD-2-Clause"
] | 1 | 2020-12-27T08:07:21.000Z | 2020-12-27T08:07:21.000Z | src/main_monitor.cpp | MilanMichael/robot_diagnostic | f67188015791b0ffdc6e0b1241321f8908d694ff | [
"BSD-2-Clause"
] | null | null | null | src/main_monitor.cpp | MilanMichael/robot_diagnostic | f67188015791b0ffdc6e0b1241321f8908d694ff | [
"BSD-2-Clause"
] | null | null | null | /*********************************************************************
*
* Software License Agreement (BSD License)
*
* Copyright (c) 2020,
* 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 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.
*
* Author: Milan Michael
*
*********************************************************************/
#include <robot_diagnostic/main_monitor.h>
MainMonitor::MainMonitor(ros::NodeHandle *nh)
{
nh_ = nh;
GetTopicParams();
diagnotics_sub = nh->subscribe("/diagnostics", 1, &MainMonitor::DiagnosticsMessageCB, this);
topic_monitor = new TopicMonitor(*nh_);
topic_monitor->AddTopic(*nh_, all_topics.topic_name, all_topics.min_freq, all_topics.max_freq, all_topics.min_timestamp_diff,
all_topics.max_timestamp_diff, all_topics.is_header, all_topics.just_monitor);
system_state_timer = nh->createTimer(ros::Duration(0.1), &MainMonitor::SystemState, this);
system_status_pub = nh->advertise<robot_diagnostic::SystemStatus>("/system_status", 1);
}
void MainMonitor::SystemState(const ros::TimerEvent &event)
{
robot_diagnostic::SystemStatus state_status;
robot_diagnostic::IndividualState indicidual_state;
for (int i = 0; i < all_topics.topic_name.size(); i++)
{
indicidual_state.node_name = all_topics.node_name[i];
indicidual_state.topic_name = all_topics.topic_name[i];
indicidual_state.health_status = all_topics.current_status[i] == diagnostic_msgs::DiagnosticStatus::OK ? "GOOD" :
(all_topics.current_status[i] == diagnostic_msgs::DiagnosticStatus::WARN ?
"WARNING" : (all_topics.current_status[i] == diagnostic_msgs::DiagnosticStatus::ERROR ? "ERROR" : "Initialized"));
indicidual_state.message = all_topics.current_message[i];
switch (all_topics.current_status[i])
{
case 0:
state_status.good_state.push_back(indicidual_state);
break;
case 1:
state_status.warning_state.push_back(indicidual_state);
break;
case 2:
state_status.error_state.push_back(indicidual_state);
break;
default:
state_status.error_state.push_back(indicidual_state);
break;
}
}
state_status.system_level = state_status.error_state.size() > 0 ? diagnostic_msgs::DiagnosticStatus::ERROR :
(state_status.warning_state.size() > 0 ? diagnostic_msgs::DiagnosticStatus::WARN : diagnostic_msgs::DiagnosticStatus::OK);
state_status.system_state = state_status.system_level == 0 ? "System is Fine" : (state_status.system_level == 1 ? "System in Warning" : "System in Error");
system_status_pub.publish(state_status);
}
void MainMonitor::DiagnosticsMessageCB(const diagnostic_msgs::DiagnosticArray::ConstPtr &msg)
{
diagnostic_msgs::DiagnosticArray Message = *msg;
std::vector<std::string>::iterator it;
for (int i = 0; i < Message.status.size(); i++)
{
if (Message.status[i].level == diagnostic_msgs::DiagnosticStatus::OK)
{
std::string ok_topic_name = Utility::WordFromString(Message.status[i].name, 2);
it = std::find(all_topics.topic_name.begin(), all_topics.topic_name.end(), ok_topic_name);
if (it != all_topics.topic_name.end())
{
if (all_topics.current_status[it - all_topics.topic_name.begin()] != diagnostic_msgs::DiagnosticStatus::OK)
{
all_topics.current_status[it - all_topics.topic_name.begin()] = diagnostic_msgs::DiagnosticStatus::OK;
all_topics.current_message[it - all_topics.topic_name.begin()] = "ALL OK";
}
}
}
else if (Message.status[i].level == diagnostic_msgs::DiagnosticStatus::WARN)
{
std::string warn_topic_name = Utility::WordFromString(Message.status[i].name, 2);
it = std::find(all_topics.topic_name.begin(), all_topics.topic_name.end(), warn_topic_name);
if (it != all_topics.topic_name.end())
{
if (all_topics.current_status[it - all_topics.topic_name.begin()] != diagnostic_msgs::DiagnosticStatus::WARN)
{
all_topics.current_status[it - all_topics.topic_name.begin()] = diagnostic_msgs::DiagnosticStatus::WARN;
all_topics.current_message[it - all_topics.topic_name.begin()] = all_topics.warning_message[it - all_topics.topic_name.begin()];
}
}
}
else if (Message.status[i].level == diagnostic_msgs::DiagnosticStatus::ERROR)
{
std::string error_topic_name = Utility::WordFromString(Message.status[i].name, 2);
it = std::find(all_topics.topic_name.begin(), all_topics.topic_name.end(), error_topic_name);
if (it != all_topics.topic_name.end())
{
if (all_topics.current_status[it - all_topics.topic_name.begin()] != diagnostic_msgs::DiagnosticStatus::ERROR)
{
all_topics.current_status[it - all_topics.topic_name.begin()] = diagnostic_msgs::DiagnosticStatus::ERROR;
all_topics.current_message[it - all_topics.topic_name.begin()] = all_topics.error_message[it - all_topics.topic_name.begin()];
}
}
}
}
}
void MainMonitor::GetTopicParams()
{
XmlRpc::XmlRpcValue topicList;
if (nh_->getParam("/Diagnostic_topics", topicList))
{
std::map<std::string, XmlRpc::XmlRpcValue>::iterator i;
for (i = topicList.begin(); i != topicList.end(); i++)
{
all_topics.topic_name.push_back(i->second["name"]);
all_topics.is_header.push_back(i->second["isheader"]);
all_topics.max_freq.push_back(i->second["maxfreq"]);
all_topics.min_freq.push_back(i->second["minfreq"]);
all_topics.min_timestamp_diff.push_back(i->second["mintimestamp_diff"]);
all_topics.max_timestamp_diff.push_back(i->second["maxtimestamp_diff"]);
all_topics.node_name.push_back(i->second["nodename"]);
all_topics.warning_message.push_back(i->second["warning_message"]);
all_topics.error_message.push_back(i->second["error_message"]);
all_topics.just_monitor.push_back(i->second["just_monitor"]);
all_topics.current_status.push_back(3);
all_topics.current_message.push_back("Topic Initialized , No new message from diagnostics");
}
}
}
int main(int argc, char *argv[])
{
ros::init(argc, argv, "robot_diagnostic");
ros::NodeHandle nh("~");
MainMonitor *main_monitor;
main_monitor = new MainMonitor(&nh);
double rate = 50;
ros::Rate loop_rate(rate);
while (ros::ok())
{
loop_rate.sleep();
ros::spin();
}
return 0;
}
| 45.989071 | 159 | 0.64817 | [
"vector"
] |
a1a0548cbee645bf116e893283397ed59312d6e2 | 8,034 | cc | C++ | tensorflow/core/ir/importexport/tests/roundtrip/roundtrip.cc | yf225/tensorflow-alpa | 0196bd11c737e0a89b142affe401d233326f14b0 | [
"Apache-2.0"
] | 3 | 2022-03-09T01:39:56.000Z | 2022-03-30T23:17:58.000Z | tensorflow/core/ir/importexport/tests/roundtrip/roundtrip.cc | yf225/tensorflow-alpa | 0196bd11c737e0a89b142affe401d233326f14b0 | [
"Apache-2.0"
] | 1 | 2020-08-01T05:40:12.000Z | 2020-08-01T05:40:12.000Z | tensorflow/core/ir/importexport/tests/roundtrip/roundtrip.cc | yf225/tensorflow-alpa | 0196bd11c737e0a89b142affe401d233326f14b0 | [
"Apache-2.0"
] | 1 | 2022-03-22T00:45:15.000Z | 2022-03-22T00:45:15.000Z | /* Copyright 2021 The TensorFlow Authors. All Rights Reserved.
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 "tensorflow/core/ir/importexport/tests/roundtrip/roundtrip.h"
#include "absl/strings/str_cat.h"
#include "llvm/ADT/SmallVector.h"
#include "mlir/IR/MLIRContext.h" // from @llvm-project
#include "tensorflow/core/common_runtime/graph_constructor.h"
#include "tensorflow/core/framework/attr_value.pb.h"
#include "tensorflow/core/framework/function.h"
#include "tensorflow/core/framework/function.pb.h"
#include "tensorflow/core/framework/graph.pb.h"
#include "tensorflow/core/framework/node_def.pb.h"
#include "tensorflow/core/framework/tensor_util.h"
#include "tensorflow/core/graph/tensor_id.h"
#include "tensorflow/core/ir/importexport/export.h"
#include "tensorflow/core/ir/importexport/import.h"
#include "tensorflow/core/platform/errors.h"
#include "tensorflow/core/platform/protobuf.h"
using mlir::MLIRContext;
namespace tensorflow {
// Applies various normalization to a NodeDef to make it possible to perform
// textual comparison (for example splat constant are detected, NaN are removed,
// control input are alphabetically sorted, etc).
void NormalizeNode(NodeDef* node, bool add_fulltype) {
for (auto& named_attr : (*node->mutable_attr())) {
AttrValue& attr_val = named_attr.second;
if (attr_val.has_tensor()) {
auto* tensor = attr_val.mutable_tensor();
switch (tensor->dtype()) {
// There is no compression or canonicalization for DT_STRING, let's
// just strip it entirely for now so it is ignored from the comparison.
case DT_STRING: {
const TensorShape shape(tensor->tensor_shape());
if (!tensor->tensor_content().empty()) {
tensor->mutable_tensor_content()->clear();
} else {
tensor->mutable_string_val()->Clear();
}
break;
}
case DT_FLOAT:
tensor::CompressTensorProtoInPlace(1, 1.0, tensor);
for (float& val : *tensor->mutable_float_val())
if (std::isnan(val)) val = -42.;
break;
case DT_DOUBLE:
tensor::CompressTensorProtoInPlace(1, 1.0, tensor);
for (double& val : *tensor->mutable_double_val())
if (std::isnan(val)) val = -42.;
break;
case DT_COMPLEX64:
tensor::CompressTensorProtoInPlace(1, 1.0, tensor);
for (float& val : *tensor->mutable_scomplex_val())
if (std::isnan(val)) val = -42.;
break;
case DT_COMPLEX128:
tensor::CompressTensorProtoInPlace(1, 1.0, tensor);
for (double& val : *tensor->mutable_dcomplex_val())
if (std::isnan(val)) val = -42.;
break;
case DT_VARIANT: {
Tensor t;
if (t.FromProto(*tensor)) t.AsProtoField(tensor);
break;
}
default:
tensor::CompressTensorProtoInPlace(1, 1.0, tensor);
}
}
}
// Sort control inputs alphabetically.
for (auto it = node->mutable_input()->begin(),
end = node->mutable_input()->end();
it != end; ++it) {
if (it->empty() || it->front() != '^') continue;
std::sort(it, end);
}
const OpDef* op_def = nullptr;
(void)tensorflow::OpRegistry::Global()->LookUpOpDef(node->op(), &op_def);
// Following logic in Graph::AddNode to avoid false positives due to
// type refinement.
if (add_fulltype) {
if (node->has_experimental_type()) {
VLOG(3) << "node has type set, skipping type constructor "
<< node->name();
} else {
const OpRegistrationData* op_reg_data;
(void)tensorflow::OpRegistry::Global()->LookUp(node->op(), &op_reg_data);
if (op_reg_data && op_reg_data->type_ctor != nullptr) {
VLOG(3) << "found type constructor for " << node->name();
(void)full_type::SpecializeType(AttrSlice(*node), op_reg_data->op_def,
*(node->mutable_experimental_type()));
} else {
VLOG(3) << "no type constructor for " << node->name();
}
}
}
if (op_def) StripDefaultsFromNodeDef(*op_def, node);
}
void NormalizeTensorData(GraphDef& graphdef, bool add_fulltype) {
FunctionDefLibrary* library = graphdef.mutable_library();
llvm::sort(*library->mutable_function(),
[](FunctionDef& lhs, FunctionDef& rhs) {
return lhs.signature().name() < rhs.signature().name();
});
for (int i = 0; i < graphdef.node_size(); ++i)
NormalizeNode(graphdef.mutable_node(i), add_fulltype);
llvm::sort(*graphdef.mutable_node(),
[](const NodeDef& lhs, const NodeDef& rhs) {
return lhs.name() < rhs.name();
});
for (int func_id = 0; func_id < library->function_size(); ++func_id) {
FunctionDef* func = library->mutable_function(func_id);
llvm::sort(*func->mutable_node_def(), [](NodeDef& lhs, NodeDef& rhs) {
return lhs.name() < rhs.name();
});
for (int node_id = 0; node_id < func->node_def_size(); ++node_id) {
NodeDef* node = func->mutable_node_def(node_id);
NormalizeNode(node, add_fulltype);
}
for (const auto& it : *func->mutable_ret()) {
func->mutable_ret()->at(it.first) = it.second;
// Eliminate empty arg_attr entries.
llvm::SmallVector<int> to_erase;
for (auto& arg_attr : *func->mutable_arg_attr()) {
if (arg_attr.second.attr().empty()) {
to_erase.push_back(arg_attr.first);
}
}
for (int idx : to_erase) func->mutable_arg_attr()->erase(idx);
for (int i = 0; i < func->node_def_size(); ++i)
NormalizeNode(func->mutable_node_def(i), add_fulltype);
}
}
}
Status TestRoundTrip(GraphDef& graphdef) {
MLIRContext context;
GraphDebugInfo debug_info;
auto errorOrModule =
mlir::tfg::ImportGraphDefToMlir(&context, debug_info, graphdef);
if (!errorOrModule.ok()) {
LOG(ERROR) << errorOrModule.status();
llvm::errs()
<< "\n\n=========\n=========\n=========\n=========\n=========\n"
<< graphdef.DebugString()
<< "=========\n=========\n=========\n=========\n";
return errorOrModule.status();
}
GraphDef new_graph;
auto module = errorOrModule.ValueOrDie().get();
Status status = tensorflow::ExportMlirToGraphdef(module, &new_graph);
if (!status.ok()) {
LOG(ERROR) << "Error exporting MLIR module to GraphDef: " << status;
return status;
}
GraphDef original_graph;
{
GraphConstructorOptions options;
options.allow_internal_ops = true;
options.add_default_attributes = true;
Graph graph(OpRegistry::Global());
GraphDef preprocessed_graphdef(graphdef);
TF_RETURN_IF_ERROR(ConvertGraphDefToGraph(
options, std::move(preprocessed_graphdef), &graph));
graph.ToGraphDef(&original_graph);
}
NormalizeTensorData(new_graph, /*add_fulltype=*/false);
NormalizeTensorData(original_graph, /*add_fulltype=*/true);
tensorflow::protobuf::util::MessageDifferencer differencer;
if (!differencer.Equivalent(original_graph, new_graph)) {
LOG(ERROR) << "GraphDef didn't Roundtrip:";
llvm::errs()
<< "\n=========\n\n"
<< module
<< "\n\n=========\n=========\n=========\n=========\n=========\n"
<< graphdef.DebugString()
<< "=========\n=========\n=========\n=========\n";
return errors::InvalidArgument("GraphDef didn't roundtrip");
}
return {};
}
} // namespace tensorflow
| 38.625 | 80 | 0.625218 | [
"shape"
] |
a1a30a528724e18dff25cda982c5ef8e1ffcaf52 | 4,518 | cc | C++ | ui/gfx/image/image_util.cc | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 575 | 2015-06-18T23:58:20.000Z | 2022-03-23T09:32:39.000Z | ui/gfx/image/image_util.cc | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | ui/gfx/image/image_util.cc | iridium-browser/iridium-browser | 907e31cf5ce5ad14d832796e3a7c11e496828959 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 52 | 2015-07-14T10:40:50.000Z | 2022-03-15T01:11:49.000Z | // Copyright (c) 2012 The Chromium 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 "ui/gfx/image/image_util.h"
#include <stdint.h>
#include <algorithm>
#include <memory>
#include "build/build_config.h"
#include "skia/ext/image_operations.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/gfx/codec/jpeg_codec.h"
#include "ui/gfx/image/image.h"
#include "ui/gfx/image/image_skia.h"
#include "ui/gfx/image/resize_image_dimensions.h"
namespace {
// Returns whether column |x| of |bitmap| has any "visible pixels", where
// "visible" is defined as having an opactiy greater than an arbitrary small
// value.
bool ColumnHasVisiblePixels(const SkBitmap& bitmap, int x) {
const SkAlpha kMinimumVisibleOpacity = 12;
for (int y = 0; y < bitmap.height(); ++y) {
if (SkColorGetA(bitmap.getColor(x, y)) > kMinimumVisibleOpacity)
return true;
}
return false;
}
} // namespace
namespace gfx {
// The iOS implementations of the JPEG functions are in image_util_ios.mm.
#if !defined(OS_IOS)
Image ImageFrom1xJPEGEncodedData(const unsigned char* input,
size_t input_size) {
std::unique_ptr<SkBitmap> bitmap(gfx::JPEGCodec::Decode(input, input_size));
if (bitmap.get())
return Image::CreateFrom1xBitmap(*bitmap);
return Image();
}
Image ResizedImageForSearchByImage(const Image& image) {
return ResizedImageForSearchByImageSkiaRepresentation(image);
}
// The MacOS implementation of this function is in image_utils_mac.mm.
#if !defined(OS_APPLE)
bool JPEG1xEncodedDataFromImage(const Image& image,
int quality,
std::vector<unsigned char>* dst) {
return JPEG1xEncodedDataFromSkiaRepresentation(image, quality, dst);
}
#endif // !defined(OS_APPLE)
bool JPEG1xEncodedDataFromSkiaRepresentation(const Image& image,
int quality,
std::vector<unsigned char>* dst) {
const gfx::ImageSkiaRep& image_skia_rep =
image.AsImageSkia().GetRepresentation(1.0f);
if (image_skia_rep.scale() != 1.0f)
return false;
const SkBitmap& bitmap = image_skia_rep.GetBitmap();
if (!bitmap.readyToDraw())
return false;
return gfx::JPEGCodec::Encode(bitmap, quality, dst);
}
Image ResizedImageForSearchByImageSkiaRepresentation(const Image& image) {
const gfx::ImageSkiaRep& image_skia_rep =
image.AsImageSkia().GetRepresentation(1.0f);
if (image_skia_rep.scale() != 1.0f)
return image;
const SkBitmap& bitmap = image_skia_rep.GetBitmap();
if (bitmap.height() * bitmap.width() > kSearchByImageMaxImageArea &&
(bitmap.width() > kSearchByImageMaxImageWidth ||
bitmap.height() > kSearchByImageMaxImageHeight)) {
double scale = std::min(
static_cast<double>(kSearchByImageMaxImageWidth) / bitmap.width(),
static_cast<double>(kSearchByImageMaxImageHeight) / bitmap.height());
int width = base::ClampToRange<int>(scale * bitmap.width(), 1,
kSearchByImageMaxImageWidth);
int height = base::ClampToRange<int>(scale * bitmap.height(), 1,
kSearchByImageMaxImageHeight);
SkBitmap new_bitmap = skia::ImageOperations::Resize(
bitmap, skia::ImageOperations::RESIZE_GOOD, width, height);
return Image(ImageSkia(ImageSkiaRep(new_bitmap, 0.0f)));
}
return image;
}
#endif // !defined(OS_IOS)
void GetVisibleMargins(const ImageSkia& image, int* left, int* right) {
*left = 0;
*right = 0;
if (!image.HasRepresentation(1.f))
return;
const SkBitmap& bitmap = image.GetRepresentation(1.f).GetBitmap();
if (bitmap.drawsNothing() || bitmap.isOpaque())
return;
int x = 0;
for (; x < bitmap.width(); ++x) {
if (ColumnHasVisiblePixels(bitmap, x)) {
*left = x;
break;
}
}
if (x == bitmap.width()) {
// Image is fully transparent. Divide the width in half, giving the leading
// region the extra pixel for odd widths.
*left = (bitmap.width() + 1) / 2;
*right = bitmap.width() - *left;
return;
}
// Since we already know column *left is non-transparent, we can avoid
// rechecking that column; hence the '>' here.
for (x = bitmap.width() - 1; x > *left; --x) {
if (ColumnHasVisiblePixels(bitmap, x))
break;
}
*right = bitmap.width() - 1 - x;
}
} // namespace gfx
| 32.503597 | 80 | 0.664675 | [
"vector"
] |
a1a62518ef3bef0b306002245086cabae202f6bb | 51,239 | cpp | C++ | main_d1/editor/seguvs.cpp | ziplantil/CacaoticusDescent | b4299442bc43310690a666e181dd983c1491dce1 | [
"MIT"
] | 22 | 2019-08-19T21:09:29.000Z | 2022-03-25T23:19:15.000Z | main_d1/editor/seguvs.cpp | ziplantil/CacaoticusDescent | b4299442bc43310690a666e181dd983c1491dce1 | [
"MIT"
] | 6 | 2019-11-08T22:17:03.000Z | 2022-03-10T05:02:59.000Z | main_d1/editor/seguvs.cpp | ziplantil/CacaoticusDescent | b4299442bc43310690a666e181dd983c1491dce1 | [
"MIT"
] | 6 | 2019-08-24T08:03:14.000Z | 2022-02-04T15:04:52.000Z | /*
THE COMPUTER CODE CONTAINED HEREIN IS THE SOLE PROPERTY OF PARALLAX
SOFTWARE CORPORATION ("PARALLAX"). PARALLAX, IN DISTRIBUTING THE CODE TO
END-USERS, AND SUBJECT TO ALL OF THE TERMS AND CONDITIONS HEREIN, GRANTS A
ROYALTY-FREE, PERPETUAL LICENSE TO SUCH END-USERS FOR USE BY SUCH END-USERS
IN USING, DISPLAYING, AND CREATING DERIVATIVE WORKS THEREOF, SO LONG AS
SUCH USE, DISPLAY OR CREATION IS FOR NON-COMMERCIAL, ROYALTY OR REVENUE
FREE PURPOSES. IN NO EVENT SHALL THE END-USER USE THE COMPUTER CODE
CONTAINED HEREIN FOR REVENUE-BEARING PURPOSES. THE END-USER UNDERSTANDS
AND AGREES TO THE TERMS HEREIN AND ACCEPTS THE SAME BY USE OF THIS FILE.
COPYRIGHT 1993-1998 PARALLAX SOFTWARE CORPORATION. ALL RIGHTS RESERVED.
*/
#ifdef EDITOR
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <math.h>
#include <string.h>
#include "main_d1/inferno.h"
#include "main_d1/segment.h"
#include "editor.h"
#include "main_d1/gameseg.h"
#include "fix/fix.h"
#include "platform/mono.h"
#include "misc/error.h"
#include "main_d1/wall.h"
#include "kdefs.h"
#include "main_d1/bm.h" // Needed for TmapInfo
#include "main_d1/effects.h" // Needed for effects_bm_num
#include "main_d1/fvi.h"
void cast_all_light_in_mine(int quick_flag);
//--rotate_uvs-- vms_vector Rightvec;
// ---------------------------------------------------------------------------------------------
// Returns approximate area of a side
fix area_on_side(side *sidep)
{
fix du,dv,width,height;
du = sidep->uvls[1].u - sidep->uvls[0].u;
dv = sidep->uvls[1].v - sidep->uvls[0].v;
width = fix_sqrt(fixmul(du,du) + fixmul(dv,dv));
du = sidep->uvls[3].u - sidep->uvls[0].u;
dv = sidep->uvls[3].v - sidep->uvls[0].v;
height = fix_sqrt(fixmul(du,du) + fixmul(dv,dv));
return fixmul(width, height);
}
// -------------------------------------------------------------------------------------------
// DEBUG function -- callable from debugger.
// Returns approximate area of all sides which get mapped (ie, are not a connection).
// I wrote this because I was curious how much memory would be required to texture map all
// sides individually with custom artwork. For demo1.min on 2/18/94, it would be about 5 meg.
int area_on_all_sides(void)
{
int i,s;
int total_area = 0;
for (i=0; i<=Highest_segment_index; i++)
{
segment *segp = &Segments[i];
for (s=0; s<MAX_SIDES_PER_SEGMENT; s++)
if (!IS_CHILD(segp->children[s]))
total_area += f2i(area_on_side(&segp->sides[s]));
}
return total_area;
}
fix average_connectivity(void)
{
int i,s;
int total_sides = 0, total_mapped_sides = 0;
for (i=0; i<=Highest_segment_index; i++) {
segment *segp = &Segments[i];
for (s=0; s<MAX_SIDES_PER_SEGMENT; s++) {
if (!IS_CHILD(segp->children[s]))
total_mapped_sides++;
total_sides++;
}
}
return 6 * fixdiv(total_mapped_sides, total_sides);
}
#define MAX_LIGHT_SEGS 16
// ---------------------------------------------------------------------------------------------
// Scan all polys in all segments, return average light value for vnum.
// segs = output array for segments containing vertex, terminated by -1.
fix get_average_light_at_vertex(int vnum, short *segs)
{
int segnum, relvnum, sidenum;
fix total_light;
int num_occurrences;
// #ifndef NDEBUG //Removed this ifdef because the version of Assert that I used to get it to compile doesn't work without this symbol. -KRB
short *original_segs = segs;
// #endif
num_occurrences = 0;
total_light = 0;
for (segnum=0; segnum<=Highest_segment_index; segnum++)
{
segment *segp = &Segments[segnum];
short *vp = segp->verts;
for (relvnum=0; relvnum<MAX_VERTICES_PER_SEGMENT; relvnum++)
if (*vp++ == vnum)
break;
if (relvnum < MAX_VERTICES_PER_SEGMENT)
{
*segs++ = segnum;
Assert(segs - original_segs < MAX_LIGHT_SEGS);
for (sidenum=0; sidenum < MAX_SIDES_PER_SEGMENT; sidenum++)
{
if (!IS_CHILD(segp->children[sidenum]))
{
side *sidep = &segp->sides[sidenum];
int8_t *vp = Side_to_verts[sidenum];
int v;
for (v=0; v<4; v++)
if (*vp++ == relvnum)
{
total_light += sidep->uvls[v].l;
num_occurrences++;
}
} // end if
} // end sidenum
}
} // end segnum
*segs = -1;
if (num_occurrences)
return total_light/num_occurrences;
else
return 0;
}
void set_average_light_at_vertex(int vnum)
{
int relvnum, sidenum;
short Segment_indices[MAX_LIGHT_SEGS];
int segind;
fix average_light;
average_light = get_average_light_at_vertex(vnum, Segment_indices);
if (!average_light)
return;
segind = 0;
while (Segment_indices[segind] != -1)
{
int segnum = Segment_indices[segind++];
segment *segp = &Segments[segnum];
for (relvnum=0; relvnum<MAX_VERTICES_PER_SEGMENT; relvnum++)
if (segp->verts[relvnum] == vnum)
break;
if (relvnum < MAX_VERTICES_PER_SEGMENT)
{
for (sidenum=0; sidenum < MAX_SIDES_PER_SEGMENT; sidenum++)
{
if (!IS_CHILD(segp->children[sidenum]))
{
side *sidep = &segp->sides[sidenum];
int8_t *vp = Side_to_verts[sidenum];
int v;
for (v=0; v<4; v++)
if (*vp++ == relvnum)
sidep->uvls[v].l = average_light;
} // end if
} // end sidenum
} // end if
} // end while
Update_flags |= UF_WORLD_CHANGED;
}
void set_average_light_on_side(segment *segp, int sidenum)
{
int v;
if (!IS_CHILD(segp->children[sidenum]))
for (v=0; v<4; v++)
{
// mprintf((0,"Vertex %i\n", segp->verts[Side_to_verts[side][v]]));
set_average_light_at_vertex(segp->verts[Side_to_verts[sidenum][v]]);
}
}
int set_average_light_on_curside(void)
{
set_average_light_on_side(Cursegp, Curside);
return 0;
}
// -----------------------------------------------------------------------------------------
void set_average_light_on_all_fast(void)
{
int s,v,relvnum;
fix al;
int alc;
int seglist[MAX_LIGHT_SEGS];
int *segptr;
set_vertex_counts();
// Set total light value for all vertices in array average_light.
for (v=0; v<=Highest_vertex_index; v++)
{
al = 0;
alc = 0;
if (Vertex_active[v])
{
segptr = seglist;
for (s=0; s<=Highest_segment_index; s++)
{
segment *segp = &Segments[s];
for (relvnum=0; relvnum<MAX_VERTICES_PER_SEGMENT; relvnum++)
if (segp->verts[relvnum] == v)
break;
if (relvnum != MAX_VERTICES_PER_SEGMENT)
{
int si;
*segptr++ = s; // Note this segment in list, so we can process it below.
Assert(segptr - seglist < MAX_LIGHT_SEGS);
for (si=0; si<MAX_SIDES_PER_SEGMENT; si++)
{
if (!IS_CHILD(segp->children[si]))
{
side *sidep = &segp->sides[si];
int8_t *vp = Side_to_verts[si];
int vv;
for (vv=0; vv<4; vv++)
if (*vp++ == relvnum)
{
al += sidep->uvls[vv].l;
alc++;
}
} // if (segp->children[si == -1) {
} // for (si=0...
} // if (relvnum != ...
} // for (s=0; ...
*segptr = -1;
// Now, divide average_light by number of number of occurrences for each vertex
if (alc)
al /= alc;
else
al = 0;
segptr = seglist;
while (*segptr != -1)
{
int segnum = *segptr++;
segment *segp = &Segments[segnum];
int sidenum;
for (relvnum=0; relvnum<MAX_VERTICES_PER_SEGMENT; relvnum++)
if (segp->verts[relvnum] == v)
break;
Assert(relvnum < MAX_VERTICES_PER_SEGMENT); // IMPOSSIBLE! This segment is in seglist, but vertex v does not occur!
for (sidenum=0; sidenum < MAX_SIDES_PER_SEGMENT; sidenum++)
{
int wid_result;
wid_result = WALL_IS_DOORWAY(segp, sidenum);
if ((wid_result != WID_FLY_FLAG) && (wid_result != WID_NO_WALL))
{
side *sidep = &segp->sides[sidenum];
int8_t *vp = Side_to_verts[sidenum];
int v;
for (v=0; v<4; v++)
if (*vp++ == relvnum)
sidep->uvls[v].l = al;
} // end if
} // end sidenum
} // end while
} // if (Vertex_active[v]...
} // for (v=0...
}
extern int Doing_lighting_hack_flag; // If set, don't mprintf warning messages in gameseg.c/find_point_seg
int set_average_light_on_all(void)
{
// set_average_light_on_all_fast();
Doing_lighting_hack_flag = 1;
cast_all_light_in_mine(0);
Doing_lighting_hack_flag = 0;
Update_flags |= UF_WORLD_CHANGED;
// int seg, side;
// for (seg=0; seg<=Highest_segment_index; seg++)
// for (side=0; side<MAX_SIDES_PER_SEGMENT; side++)
// if (Segments[seg].segnum != -1)
// set_average_light_on_side(&Segments[seg], side);
return 0;
}
int set_average_light_on_all_quick(void)
{
cast_all_light_in_mine(1);
Update_flags |= UF_WORLD_CHANGED;
return 0;
}
// ---------------------------------------------------------------------------------------------
fix compute_uv_dist(uvl *uv0, uvl *uv1)
{
vms_vector v0,v1;
v0.x = uv0->u;
v0.y = 0;
v0.z = uv0->v;
v1.x = uv1->u;
v1.y = 0;
v1.z = uv1->v;
return vm_vec_dist(&v0,&v1);
}
// ---------------------------------------------------------------------------------------------
// Given a polygon, compress the uv coordinates so that they are as close to 0 as possible.
// Do this by adding a constant u and v to each uv pair.
void compress_uv_coordinates(side *sidep)
{
int v;
fix uc, vc;
uc = 0;
vc = 0;
for (v=0; v<4; v++)
{
uc += sidep->uvls[v].u;
vc += sidep->uvls[v].v;
}
uc /= 4;
vc /= 4;
uc = uc & 0xffff0000;
vc = vc & 0xffff0000;
for (v=0; v<4; v++)
{
sidep->uvls[v].u -= uc;
sidep->uvls[v].v -= vc;
}
}
// ---------------------------------------------------------------------------------------------
void compress_uv_coordinates_on_side(side *sidep)
{
compress_uv_coordinates(sidep);
}
// ---------------------------------------------------------------------------------------------
void validate_uv_coordinates_on_side(segment *segp, int sidenum)
{
// int v;
// fix uv_dist,threed_dist;
// vms_vector tvec;
// fix dist_ratios[MAX_VERTICES_PER_POLY];
side *sidep = &segp->sides[sidenum];
// int8_t *vp = Side_to_verts[sidenum];
// This next hunk doesn't seem to affect anything. @mk, 02/13/94
// for (v=1; v<4; v++) {
// uv_dist = compute_uv_dist(&sidep->uvls[v],&sidep->uvls[0]);
// threed_dist = vm_vec_mag(vm_vec_sub(&tvec,&Vertices[segp->verts[vp[v]],&Vertices[vp[0]]));
// dist_ratios[v-1] = fixdiv(uv_dist,threed_dist);
// }
compress_uv_coordinates_on_side(sidep);
}
void compress_uv_coordinates_in_segment(segment *segp)
{
int side;
for (side=0; side<MAX_SIDES_PER_SEGMENT; side++)
compress_uv_coordinates_on_side(&segp->sides[side]);
}
void compress_uv_coordinates_all(void)
{
int seg;
for (seg=0; seg<=Highest_segment_index; seg++)
if (Segments[seg].segnum != -1)
compress_uv_coordinates_in_segment(&Segments[seg]);
}
void check_lighting_side(segment *sp, int sidenum)
{
int v;
side *sidep = &sp->sides[sidenum];
for (v=0; v<4; v++)
if ((sidep->uvls[v].l > F1_0*16) || (sidep->uvls[v].l < 0))
Int3(); //mprintf(0,"Bogus lighting value in segment %i, side %i, vert %i = %x\n",sp-Segments, side, v, sidep->uvls[v].l);
}
void check_lighting_segment(segment *segp)
{
int side;
for (side=0; side<MAX_SIDES_PER_SEGMENT; side++)
check_lighting_side(segp, side);
}
// Flag bogus lighting values.
void check_lighting_all(void)
{
int seg;
for (seg=0; seg<=Highest_segment_index; seg++)
if (Segments[seg].segnum != -1)
check_lighting_segment(&Segments[seg]);
}
void assign_default_lighting_on_side(segment *segp, int sidenum)
{
int v;
side *sidep = &segp->sides[sidenum];
for (v=0; v<4; v++)
sidep->uvls[v].l = DEFAULT_LIGHTING;
}
void assign_default_lighting(segment *segp)
{
int sidenum;
for (sidenum=0; sidenum<MAX_SIDES_PER_SEGMENT; sidenum++)
assign_default_lighting_on_side(segp, sidenum);
}
void assign_default_lighting_all(void)
{
int seg;
for (seg=0; seg<=Highest_segment_index; seg++)
if (Segments[seg].segnum != -1)
assign_default_lighting(&Segments[seg]);
}
// ---------------------------------------------------------------------------------------------
void validate_uv_coordinates(segment *segp)
{
int s;
for (s=0; s<MAX_SIDES_PER_SEGMENT; s++)
validate_uv_coordinates_on_side(segp,s);
}
// ---------------------------------------------------------------------------------------------
// For all faces in side, copy uv coordinates from uvs array to face.
void copy_uvs_from_side_to_faces(segment *segp, int sidenum, uvl uvls[])
{
int v;
side *sidep = &segp->sides[sidenum];
for (v=0; v<4; v++)
sidep->uvls[v] = uvls[v];
}
fix zhypot(fix a, fix b)
{
int64_t val = ((int64_t)a * (int64_t)a) + ((int64_t)b * (int64_t)b);
return quad_sqrt(val);
}
/*#pragma aux zhypot parm [eax] [ebx] value [eax] modify [eax ebx ecx edx] = \
"imul eax" \
"xchg eax,ebx" \
"mov ecx,edx" \
"imul eax" \
"add eax,ebx" \
"adc edx,ecx" \
"call quad_sqrt";*/
// ---------------------------------------------------------------------------------------------
// Assign lighting value to side, a function of the normal vector.
void assign_light_to_side(segment *sp, int sidenum)
{
int v;
side *sidep = &sp->sides[sidenum];
for (v=0; v<4; v++)
sidep->uvls[v].l = DEFAULT_LIGHTING;
}
fix Stretch_scale_x = F1_0;
fix Stretch_scale_y = F1_0;
// ---------------------------------------------------------------------------------------------
// Given u,v coordinates at two vertices, assign u,v coordinates to other two vertices on a side.
// (Actually, assign them to the coordinates in the faces.)
// va, vb = face-relative vertex indices corresponding to uva, uvb. Ie, they are always in 0..3 and should be looked up in
// Side_to_verts[side] to get the segment relative index.
void assign_uvs_to_side(segment *segp, int sidenum, uvl *uva, uvl *uvb, int va, int vb)
{
int vlo,vhi,v0,v1,v2,v3;
vms_vector fvec,rvec,tvec;
vms_matrix rotmat;
uvl uvls[4],ruvmag,fuvmag,uvlo,uvhi;
fix fmag,mag01;
int8_t *vp;
Assert( (va<4) && (vb<4) );
Assert((abs(va - vb) == 1) || (abs(va - vb) == 3)); // make sure the verticies specify an edge
vp = &Side_to_verts[sidenum][0];
// We want vlo precedes vhi, ie vlo < vhi, or vlo = 3, vhi = 0
if (va == ((vb + 1) % 4)) // va = vb + 1
{
vlo = vb;
vhi = va;
uvlo = *uvb;
uvhi = *uva;
}
else
{
vlo = va;
vhi = vb;
uvlo = *uva;
uvhi = *uvb;
}
Assert(((vlo+1) % 4) == vhi); // If we are on an edge, then uvhi is one more than uvlo (mod 4)
uvls[vlo] = uvlo;
uvls[vhi] = uvhi;
// Now we have vlo precedes vhi, compute vertices ((vhi+1) % 4) and ((vhi+2) % 4)
// Assign u,v scale to a unit length right vector.
fmag = zhypot(uvhi.v - uvlo.v,uvhi.u - uvlo.u);
if (fmag < 64) // this is a fix, so 64 = 1/1024
{
mprintf((0,"Warning: fmag = %7.3f, using approximate u,v values\n",f2fl(fmag)));
ruvmag.u = F1_0*256;
ruvmag.v = F1_0*256;
fuvmag.u = F1_0*256;
fuvmag.v = F1_0*256;
} else
{
ruvmag.u = uvhi.v - uvlo.v;
ruvmag.v = uvlo.u - uvhi.u;
fuvmag.u = uvhi.u - uvlo.u;
fuvmag.v = uvhi.v - uvlo.v;
}
v0 = segp->verts[vp[vlo]];
v1 = segp->verts[vp[vhi]];
v2 = segp->verts[vp[(vhi+1)%4]];
v3 = segp->verts[vp[(vhi+2)%4]];
// Compute right vector by computing orientation matrix from:
// forward vector = vlo:vhi
// right vector = vlo:(vhi+2) % 4
vm_vec_sub(&fvec,&Vertices[v1],&Vertices[v0]);
vm_vec_sub(&rvec,&Vertices[v3],&Vertices[v0]);
if (((fvec.x == 0) && (fvec.y == 0) && (fvec.z == 0)) || ((rvec.x == 0) && (rvec.y == 0) && (rvec.z == 0)))
{
mprintf((1, "Trapped null vector in assign_uvs_to_side, using identity matrix.\n"));
rotmat = vmd_identity_matrix;
}
else
vm_vector_2_matrix(&rotmat,&fvec,0,&rvec);
rvec = rotmat.rvec; vm_vec_negate(&rvec);
fvec = rotmat.fvec;
// mprintf((0, "va = %i, vb = %i\n", va, vb));
mag01 = vm_vec_dist(&Vertices[v1],&Vertices[v0]);
if ((va == 0) || (va == 2))
mag01 = fixmul(mag01, Stretch_scale_x);
else
mag01 = fixmul(mag01, Stretch_scale_y);
if (mag01 < F1_0/1024 )
editor_status("U, V bogosity in segment #%i, probably on side #%i. CLEAN UP YOUR MESS!", segp-Segments, sidenum);
else
{
vm_vec_sub(&tvec,&Vertices[v2],&Vertices[v1]);
uvls[(vhi+1)%4].u = uvhi.u +
fixdiv(fixmul(ruvmag.u,vm_vec_dotprod(&rvec,&tvec)),mag01) +
fixdiv(fixmul(fuvmag.u,vm_vec_dotprod(&fvec,&tvec)),mag01);
uvls[(vhi+1)%4].v = uvhi.v +
fixdiv(fixmul(ruvmag.v,vm_vec_dotprod(&rvec,&tvec)),mag01) +
fixdiv(fixmul(fuvmag.v,vm_vec_dotprod(&fvec,&tvec)),mag01);
vm_vec_sub(&tvec,&Vertices[v3],&Vertices[v0]);
uvls[(vhi+2)%4].u = uvlo.u +
fixdiv(fixmul(ruvmag.u,vm_vec_dotprod(&rvec,&tvec)),mag01) +
fixdiv(fixmul(fuvmag.u,vm_vec_dotprod(&fvec,&tvec)),mag01);
uvls[(vhi+2)%4].v = uvlo.v +
fixdiv(fixmul(ruvmag.v,vm_vec_dotprod(&rvec,&tvec)),mag01) +
fixdiv(fixmul(fuvmag.v,vm_vec_dotprod(&fvec,&tvec)),mag01);
uvls[(vhi+1)%4].l = uvhi.l;
uvls[(vhi+2)%4].l = uvlo.l;
copy_uvs_from_side_to_faces(segp, sidenum, uvls);
}
}
int Vmag = VMAG;
// -----------------------------------------------------------------------------------------------------------
// Assign default uvs to side.
// This means:
// v0 = 0,0
// v1 = k,0 where k is 3d size dependent
// v2, v3 assigned by assign_uvs_to_side
void assign_default_uvs_to_side(segment *segp,int side)
{
uvl uv0,uv1;
int8_t *vp;
uv0.u = 0;
uv0.v = 0;
vp = Side_to_verts[side];
uv1.u = 0;
uv1.v = Num_tilings * fixmul(Vmag, vm_vec_dist(&Vertices[segp->verts[vp[1]]],&Vertices[segp->verts[vp[0]]]));
assign_uvs_to_side(segp, side, &uv0, &uv1, 0, 1);
}
// -----------------------------------------------------------------------------------------------------------
// Assign default uvs to side.
// This means:
// v0 = 0,0
// v1 = k,0 where k is 3d size dependent
// v2, v3 assigned by assign_uvs_to_side
void stretch_uvs_from_curedge(segment *segp, int side)
{
uvl uv0,uv1;
int v0, v1;
v0 = Curedge;
v1 = (v0 + 1) % 4;
uv0.u = segp->sides[side].uvls[v0].u;
uv0.v = segp->sides[side].uvls[v0].v;
uv1.u = segp->sides[side].uvls[v1].u;
uv1.v = segp->sides[side].uvls[v1].v;
assign_uvs_to_side(segp, side, &uv0, &uv1, v0, v1);
}
// --------------------------------------------------------------------------------------------------------------
// Assign default uvs to a segment.
void assign_default_uvs_to_segment(segment *segp)
{
int s;
for (s=0; s<MAX_SIDES_PER_SEGMENT; s++)
{
assign_default_uvs_to_side(segp,s);
assign_light_to_side(segp, s);
}
}
// -- mk021394 -- // --------------------------------------------------------------------------------------------------------------
// -- mk021394 -- // Find the face:poly:vertex index in base_seg:base_common_side which is segment relative vertex v1
// -- mk021394 -- // This very specific routine is subsidiary to med_assign_uvs_to_side.
// -- mk021394 -- void get_face_and_vert(segment *base_seg, int base_common_side, int v1, int *ff, int *vv, int *pi)
// -- mk021394 -- {
// -- mk021394 -- int p,f,v;
// -- mk021394 --
// -- mk021394 -- for (f=0; f<base_seg->sides[base_common_side].num_faces; f++) {
// -- mk021394 -- face *fp = &base_seg->sides[base_common_side].faces[f];
// -- mk021394 -- for (p=0; p<fp->num_polys; p++) {
// -- mk021394 -- poly *pp = &fp->polys[p];
// -- mk021394 -- for (v=0; v<pp->num_vertices; v++)
// -- mk021394 -- if (pp->verts[v] == v1) {
// -- mk021394 -- *ff = f;
// -- mk021394 -- *vv = v;
// -- mk021394 -- *pi = p;
// -- mk021394 -- return;
// -- mk021394 -- }
// -- mk021394 -- }
// -- mk021394 -- }
// -- mk021394 --
// -- mk021394 -- Assert(0); // Error -- Couldn't find face:vertex which matched vertex v1 on base_seg:base_common_side
// -- mk021394 -- }
// -- mk021394 -- // --------------------------------------------------------------------------------------------------------------
// -- mk021394 -- // Find the vertex index in base_seg:base_common_side which is segment relative vertex v1
// -- mk021394 -- // This very specific routine is subsidiary to med_assign_uvs_to_side.
// -- mk021394 -- void get_side_vert(segment *base_seg,int base_common_side,int v1,int *vv)
// -- mk021394 -- {
// -- mk021394 -- int p,f,v;
// -- mk021394 --
// -- mk021394 -- Assert((base_seg->sides[base_common_side].tri_edge == 0) || (base_seg->sides[base_common_side].tri_edge == 1));
// -- mk021394 -- Assert(base_seg->sides[base_common_side].num_faces <= 2);
// -- mk021394 --
// -- mk021394 -- for (f=0; f<base_seg->sides[base_common_side].num_faces; f++) {
// -- mk021394 -- face *fp = &base_seg->sides[base_common_side].faces[f];
// -- mk021394 -- for (p=0; p<fp->num_polys; p++) {
// -- mk021394 -- poly *pp = &fp->polys[p];
// -- mk021394 -- for (v=0; v<pp->num_vertices; v++)
// -- mk021394 -- if (pp->verts[v] == v1) {
// -- mk021394 -- if (pp->num_vertices == 4) {
// -- mk021394 -- *vv = v;
// -- mk021394 -- return;
// -- mk021394 -- }
// -- mk021394 --
// -- mk021394 -- if (base_seg->sides[base_common_side].tri_edge == 0) { // triangulated 012, 023, so if f==0, *vv = v, if f==1, *vv = v if v=0, else v+1
// -- mk021394 -- if ((f == 1) && (v > 0))
// -- mk021394 -- v++;
// -- mk021394 -- *vv = v;
// -- mk021394 -- return;
// -- mk021394 -- } else { // triangulated 013, 123
// -- mk021394 -- if (f == 0) {
// -- mk021394 -- if (v == 2)
// -- mk021394 -- v++;
// -- mk021394 -- } else
// -- mk021394 -- v++;
// -- mk021394 -- *vv = v;
// -- mk021394 -- return;
// -- mk021394 -- }
// -- mk021394 -- }
// -- mk021394 -- }
// -- mk021394 -- }
// -- mk021394 --
// -- mk021394 -- Assert(0); // Error -- Couldn't find face:vertex which matched vertex v1 on base_seg:base_common_side
// -- mk021394 -- }
//--rotate_uvs-- // --------------------------------------------------------------------------------------------------------------
//--rotate_uvs-- // Rotate uvl coordinates uva, uvb about their center point by heading
//--rotate_uvs-- void rotate_uvs(uvl *uva, uvl *uvb, vms_vector *rvec)
//--rotate_uvs-- {
//--rotate_uvs-- uvl uvc, uva1, uvb1;
//--rotate_uvs--
//--rotate_uvs-- uvc.u = (uva->u + uvb->u)/2;
//--rotate_uvs-- uvc.v = (uva->v + uvb->v)/2;
//--rotate_uvs--
//--rotate_uvs-- uva1.u = fixmul(uva->u - uvc.u, rvec->x) - fixmul(uva->v - uvc.v, rvec->z);
//--rotate_uvs-- uva1.v = fixmul(uva->u - uvc.u, rvec->z) + fixmul(uva->v - uvc.v, rvec->x);
//--rotate_uvs--
//--rotate_uvs-- uva->u = uva1.u + uvc.u;
//--rotate_uvs-- uva->v = uva1.v + uvc.v;
//--rotate_uvs--
//--rotate_uvs-- uvb1.u = fixmul(uvb->u - uvc.u, rvec->x) - fixmul(uvb->v - uvc.v, rvec->z);
//--rotate_uvs-- uvb1.v = fixmul(uvb->u - uvc.u, rvec->z) + fixmul(uvb->v - uvc.v, rvec->x);
//--rotate_uvs--
//--rotate_uvs-- uvb->u = uvb1.u + uvc.u;
//--rotate_uvs-- uvb->v = uvb1.v + uvc.v;
//--rotate_uvs-- }
// --------------------------------------------------------------------------------------------------------------
void med_assign_uvs_to_side(segment *con_seg, int con_common_side, segment *base_seg, int base_common_side, int abs_id1, int abs_id2)
{
uvl uv1,uv2;
int v,bv1,bv2,cv1,cv2, vv1, vv2;
//[ISB]fix some runtime errors
memset(&uv1, 0, sizeof(uvl));
memset(&uv2, 0, sizeof(uvl));
bv1 = -1; bv2 = -1;
// Find which vertices in segment match abs_id1, abs_id2
for (v=0; v<MAX_VERTICES_PER_SEGMENT; v++)
{
if (base_seg->verts[v] == abs_id1)
bv1 = v;
if (base_seg->verts[v] == abs_id2)
bv2 = v;
if (con_seg->verts[v] == abs_id1)
cv1 = v;
if (con_seg->verts[v] == abs_id2)
cv2 = v;
}
// Now, bv1, bv2 are segment relative vertices in base segment which are the same as absolute vertices abs_id1, abs_id2
// cv1, cv2 are segment relative vertices in conn segment which are the same as absolute vertices abs_id1, abs_id2
Assert((bv1 != -1) && (bv2 != -1) && (cv1 != -1) && (cv2 != -1));
//Assert((uv1.u != uv2.u) || (uv1.v != uv2.v)); //[ISB] what is this supposed to accomplish?
// Now, scan 4 vertices in base side and 4 vertices in connected side.
// Set uv1, uv2 to uv coordinates from base side which correspond to vertices bv1, bv2.
// Set vv1, vv2 to relative vertex ids (in 0..3) in connecting side which correspond to cv1, cv2
vv1 = -1; vv2 = -1;
for (v=0; v<4; v++)
{
if (bv1 == Side_to_verts[base_common_side][v])
uv1 = base_seg->sides[base_common_side].uvls[v];
if (bv2 == Side_to_verts[base_common_side][v])
uv2 = base_seg->sides[base_common_side].uvls[v];
if (cv1 == Side_to_verts[con_common_side][v])
vv1 = v;
if (cv2 == Side_to_verts[con_common_side][v])
vv2 = v;
}
Assert( (vv1 != -1) && (vv2 != -1) );
assign_uvs_to_side(con_seg, con_common_side, &uv1, &uv2, vv1, vv2);
}
// -----------------------------------------------------------------------------
// Given a base and a connecting segment, a side on each of those segments and two global vertex ids,
// determine which side in each of the segments shares those two vertices.
// This is used to propagate a texture map id to a connecting segment in an expected and desired way.
// Since we can attach any side of a segment to any side of another segment, and do so in each case in
// four different rotations (for a total of 6*6*4 = 144 ways), not having this nifty function will cause
// great confusion.
void get_side_ids(segment *base_seg, segment *con_seg, int base_side, int con_side, int abs_id1, int abs_id2, int *base_common_side, int *con_common_side)
{
int8_t *base_vp,*con_vp;
int v0,side;
*base_common_side = -1;
// Find side in base segment which contains the two global vertex ids.
for (side=0; side<MAX_SIDES_PER_SEGMENT; side++)
{
if (side != base_side)
{
base_vp = Side_to_verts[side];
for (v0=0; v0<4; v0++)
if (((base_seg->verts[base_vp[v0]] == abs_id1) && (base_seg->verts[base_vp[ (v0+1) % 4]] == abs_id2)) || ((base_seg->verts[base_vp[v0]] == abs_id2) && (base_seg->verts[base_vp[ (v0+1) % 4]] == abs_id1)))
{
Assert(*base_common_side == -1); // This means two different sides shared the same edge with base_side == impossible!
*base_common_side = side;
}
}
}
// Note: For connecting segment, process vertices in reversed order.
*con_common_side = -1;
// Find side in connecting segment which contains the two global vertex ids.
for (side=0; side<MAX_SIDES_PER_SEGMENT; side++)
{
if (side != con_side)
{
con_vp = Side_to_verts[side];
for (v0=0; v0<4; v0++)
if (((con_seg->verts[con_vp[(v0 + 1) % 4]] == abs_id1) && (con_seg->verts[con_vp[v0]] == abs_id2)) || ((con_seg->verts[con_vp[(v0 + 1) % 4]] == abs_id2) && (con_seg->verts[con_vp[v0]] == abs_id1)))
{
Assert(*con_common_side == -1); // This means two different sides shared the same edge with con_side == impossible!
*con_common_side = side;
}
}
}
// mprintf((0,"side %3i adjacent to side %3i\n",*base_common_side,*con_common_side));
Assert((*base_common_side != -1) && (*con_common_side != -1));
}
// -----------------------------------------------------------------------------
// Propagate texture map u,v coordinates from base_seg:base_side to con_seg:con_side.
// The two vertices abs_id1 and abs_id2 are the only two vertices common to the two sides.
// If uv_only_flag is 1, then don't assign texture map ids, only update the uv coordinates
// If uv_only_flag is -1, then ONLY assign texture map ids, don't update the uv coordinates
void propagate_tmaps_to_segment_side(segment *base_seg, int base_side, segment *con_seg, int con_side, int abs_id1, int abs_id2, int uv_only_flag)
{
int base_common_side,con_common_side;
int tmap_num;
Assert ((uv_only_flag == -1) || (uv_only_flag == 0) || (uv_only_flag == 1));
// Set base_common_side = side in base_seg which contains edge abs_id1:abs_id2
// Set con_common_side = side in con_seg which contains edge abs_id1:abs_id2
if (base_seg != con_seg)
get_side_ids(base_seg, con_seg, base_side, con_side, abs_id1, abs_id2, &base_common_side, &con_common_side);
else
{
base_common_side = base_side;
con_common_side = con_side;
}
// Now, all faces in con_seg which are on side con_common_side get their tmap_num set to whatever tmap is assigned
// to whatever face I find which is on side base_common_side.
// First, find tmap_num for base_common_side. If it doesn't exist (ie, there is a connection there), look at the segment
// that is connected through it.
if (!IS_CHILD(con_seg->children[con_common_side]))
{
if (!IS_CHILD(base_seg->children[base_common_side]))
{
// There is at least one face here, so get the tmap_num from there.
tmap_num = base_seg->sides[base_common_side].tmap_num;
// Now assign all faces in the connecting segment on side con_common_side to tmap_num.
if ((uv_only_flag == -1) || (uv_only_flag == 0))
con_seg->sides[con_common_side].tmap_num = tmap_num;
if (uv_only_flag != -1)
med_assign_uvs_to_side(con_seg, con_common_side, base_seg, base_common_side, abs_id1, abs_id2);
}
else // There are no faces here, there is a connection, trace through the connection.
{
int cside;
cside = find_connect_side(base_seg, &Segments[base_seg->children[base_common_side]]);
propagate_tmaps_to_segment_side(&Segments[base_seg->children[base_common_side]], cside, con_seg, con_side, abs_id1, abs_id2, uv_only_flag);
}
}
}
int8_t Edge_between_sides[MAX_SIDES_PER_SEGMENT][MAX_SIDES_PER_SEGMENT][2] = {
// left top right bottom back front
{ {-1,-1}, { 3, 7}, {-1,-1}, { 2, 6}, { 6, 7}, { 2, 3} }, // left
{ { 3, 7}, {-1,-1}, { 0, 4}, {-1,-1}, { 4, 7}, { 0, 3} }, // top
{ {-1,-1}, { 0, 4}, {-1,-1}, { 1, 5}, { 4, 5}, { 0, 1} }, // right
{ { 2, 6}, {-1,-1}, { 1, 5}, {-1,-1}, { 5, 6}, { 1, 2} }, // bottom
{ { 6, 7}, { 4, 7}, { 4, 5}, { 5, 6}, {-1,-1}, {-1,-1} }, // back
{ { 2, 3}, { 0, 3}, { 0, 1}, { 1, 2}, {-1,-1}, {-1,-1} }}; // front
// -----------------------------------------------------------------------------
// Propagate texture map u,v coordinates to base_seg:back_side from base_seg:some-other-side
// There is no easy way to figure out which side is adjacent to another side along some edge, so we do a bit of searching.
void med_propagate_tmaps_to_back_side(segment *base_seg, int back_side, int uv_only_flag)
{
int v1,v2;
int s,ss,tmap_num,back_side_tmap;
if (IS_CHILD(base_seg->children[back_side]))
return; // connection, so no sides here.
// Scan all sides, look for an occupied side which is not back_side or Side_opposite[back_side]
for (s=0; s<MAX_SIDES_PER_SEGMENT; s++)
if ((s != back_side) && (s != Side_opposite[back_side]))
{
v1 = Edge_between_sides[s][back_side][0];
v2 = Edge_between_sides[s][back_side][1];
goto found1;
}
Assert(0); // Error -- couldn't find edge != back_side and Side_opposite[back_side]
found1: ;
Assert( (v1 != -1) && (v2 != -1)); // This means there was no shared edge between the two sides.
propagate_tmaps_to_segment_side(base_seg, s, base_seg, back_side, base_seg->verts[v1], base_seg->verts[v2], uv_only_flag);
// Assign an unused tmap id to the back side.
// Note that this can get undone by the caller if this was not part of a new attach, but a rotation or a scale (which
// both do attaches).
// First see if tmap on back side is anywhere else.
if (!uv_only_flag)
{
back_side_tmap = base_seg->sides[back_side].tmap_num;
for (s=0; s<MAX_SIDES_PER_SEGMENT; s++)
{
if (s != back_side)
if (base_seg->sides[s].tmap_num == back_side_tmap)
{
for (tmap_num=0; tmap_num < MAX_SIDES_PER_SEGMENT; tmap_num++)
{
for (ss=0; ss<MAX_SIDES_PER_SEGMENT; ss++)
if (ss != back_side)
if (base_seg->sides[ss].tmap_num == New_segment.sides[tmap_num].tmap_num)
goto found2; // current texture map (tmap_num) is used on current (ss) side, so try next one
// Current texture map (tmap_num) has not been used, assign to all faces on back_side.
base_seg->sides[back_side].tmap_num = New_segment.sides[tmap_num].tmap_num;
goto done1;
found2: ;
}
}
}
done1: ;
}
}
int fix_bogus_uvs_on_side(void)
{
med_propagate_tmaps_to_back_side(Cursegp, Curside, 1);
return 0;
}
void fix_bogus_uvs_on_side1(segment *sp, int sidenum, int uvonly_flag)
{
side *sidep = &sp->sides[sidenum];
if ((sidep->uvls[0].u == 0) && (sidep->uvls[1].u == 0) && (sidep->uvls[2].u == 0))
{
mprintf((0,"Found bogus segment %i, side %i\n", sp-Segments, sidenum));
med_propagate_tmaps_to_back_side(sp, sidenum, uvonly_flag);
}
}
void fix_bogus_uvs_seg(segment *segp)
{
int s;
for (s=0; s<MAX_SIDES_PER_SEGMENT; s++)
{
if (!IS_CHILD(segp->children[s]))
fix_bogus_uvs_on_side1(segp, s, 1);
}
}
int fix_bogus_uvs_all(void)
{
int seg;
for (seg=0; seg<=Highest_segment_index; seg++)
if (Segments[seg].segnum != -1)
fix_bogus_uvs_seg(&Segments[seg]);
return 0;
}
// -----------------------------------------------------------------------------
// Propagate texture map u,v coordinates to base_seg:back_side from base_seg:some-other-side
// There is no easy way to figure out which side is adjacent to another side along some edge, so we do a bit of searching.
void med_propagate_tmaps_to_any_side(segment *base_seg, int back_side, int tmap_num, int uv_only_flag)
{
int v1,v2;
int s;
// Scan all sides, look for an occupied side which is not back_side or Side_opposite[back_side]
for (s=0; s<MAX_SIDES_PER_SEGMENT; s++)
if ((s != back_side) && (s != Side_opposite[back_side]))
{
v1 = Edge_between_sides[s][back_side][0];
v2 = Edge_between_sides[s][back_side][1];
goto found1;
}
Assert(0); // Error -- couldn't find edge != back_side and Side_opposite[back_side]
found1: ;
Assert( (v1 != -1) && (v2 != -1)); // This means there was no shared edge between the two sides.
propagate_tmaps_to_segment_side(base_seg, s, base_seg, back_side, base_seg->verts[v1], base_seg->verts[v2], uv_only_flag);
base_seg->sides[back_side].tmap_num = tmap_num;
}
// -----------------------------------------------------------------------------
// Segment base_seg is connected through side base_side to segment con_seg on con_side.
// For all walls in con_seg, find the wall in base_seg which shares an edge. Copy tmap_num
// from that side in base_seg to the wall in con_seg. If the wall in base_seg is not present
// (ie, there is another segment connected through it), follow the connection through that
// segment to get the wall in the connected segment which shares the edge, and get tmap_num from there.
void propagate_tmaps_to_segment_sides(segment *base_seg, int base_side, segment *con_seg, int con_side, int uv_only_flag)
{
int8_t *base_vp,*con_vp;
short abs_id1,abs_id2;
int v;
base_vp = Side_to_verts[base_side];
con_vp = Side_to_verts[con_side];
// Do for each edge on connecting face.
for (v=0; v<4; v++)
{
abs_id1 = base_seg->verts[base_vp[v]];
abs_id2 = base_seg->verts[base_vp[(v+1) % 4]];
propagate_tmaps_to_segment_side(base_seg, base_side, con_seg, con_side, abs_id1, abs_id2, uv_only_flag);
}
}
// -----------------------------------------------------------------------------
// Propagate texture maps in base_seg to con_seg.
// For each wall in con_seg, find the wall in base_seg which shared an edge. Copy tmap_num from that
// wall in base_seg to the wall in con_seg. If the wall in base_seg is not present, then look at the
// segment connected through base_seg through the wall. The wall with a common edge is the new wall
// of interest. Continue searching in this way until a wall of interest is present.
void med_propagate_tmaps_to_segments(segment *base_seg,segment *con_seg, int uv_only_flag)
{
int s;
// mprintf((0,"Propagating segments from %i to %i\n",base_seg-Segments,con_seg-Segments));
for (s=0; s<MAX_SIDES_PER_SEGMENT; s++)
if (base_seg->children[s] == con_seg-Segments)
propagate_tmaps_to_segment_sides(base_seg, s, con_seg, find_connect_side(base_seg, con_seg), uv_only_flag);
con_seg->static_light = base_seg->static_light;
validate_uv_coordinates(con_seg);
}
// -------------------------------------------------------------------------------
// Copy texture map uvs from srcseg to destseg.
// If two segments have different face structure (eg, destseg has two faces on side 3, srcseg has only 1)
// then assign uvs according to side vertex id, not face vertex id.
void copy_uvs_seg_to_seg(segment *destseg,segment *srcseg)
{
int s;
for (s=0; s<MAX_SIDES_PER_SEGMENT; s++)
{
destseg->sides[s].tmap_num = srcseg->sides[s].tmap_num;
destseg->sides[s].tmap_num2 = srcseg->sides[s].tmap_num2;
}
destseg->static_light = srcseg->static_light;
}
// _________________________________________________________________________________________________________________________
// Maximum distance between a segment containing light to a segment to receive light.
#define LIGHT_DISTANCE_THRESHOLD (F1_0*80)
fix Magical_light_constant = (F1_0*16);
// int Seg0, Seg1;
//int Bugseg = 27;
typedef struct {
int8_t flag, hit_type;
vms_vector vector;
} hash_info;
#define FVI_HASH_SIZE 8
#define FVI_HASH_AND_MASK (FVI_HASH_SIZE - 1)
// Note: This should be malloced.
// Also, the vector should not be 12 bytes, you should only care about some smaller portion of it.
hash_info fvi_cache[FVI_HASH_SIZE];
int Hash_hits=0, Hash_retries=0, Hash_calcs=0;
// -----------------------------------------------------------------------------------------
// Set light from a light source.
// Light incident on a surface is defined by the light incident at its points.
// Light at a point = K * (V . N) / d
// where:
// K = some magical constant to make everything look good
// V = normalized vector from light source to point
// N = surface normal at point
// d = distance from light source to point
// (Note that the above equation can be simplified to K * (VV . N) / d^2 where VV = non-normalized V)
// Light intensity emitted from a light source is defined to be cast from four points.
// These four points are 1/64 of the way from the corners of the light source to the center
// of its segment. By assuming light is cast from these points, rather than from on the
// light surface itself, light will be properly cast on the light surface. Otherwise, the
// vector V would be the null vector.
// If quick_light set, then don't use find_vector_intersection
void cast_light_from_side(segment *segp, int light_side, fix light_intensity, int quick_light)
{
vms_vector segment_center;
int segnum,sidenum,vertnum, lightnum;
compute_segment_center(&segment_center, segp);
//mprintf((0, "From [%i %i %7.3f]: ", segp-Segments, light_side, f2fl(light_intensity)));
// Do for four lights, one just inside each corner of side containing light.
for (lightnum=0; lightnum<4; lightnum++)
{
int light_vertex_num, i;
vms_vector vector_to_center;
vms_vector light_location;
// fix inverse_segment_magnitude;
light_vertex_num = segp->verts[Side_to_verts[light_side][lightnum]];
light_location = Vertices[light_vertex_num];
// New way, 5/8/95: Move towards center irrespective of size of segment.
vm_vec_sub(&vector_to_center, &segment_center, &light_location);
vm_vec_normalize_quick(&vector_to_center);
vm_vec_add2(&light_location, &vector_to_center);
// -- Old way, before 5/8/95 -- // -- This way was kind of dumb. In larger segments, you move LESS towards the center.
// -- Old way, before 5/8/95 -- // Main problem, though, is vertices don't illuminate themselves well in oblong segments because the dot product is small.
// -- Old way, before 5/8/95 -- vm_vec_sub(&vector_to_center, &segment_center, &light_location);
// -- Old way, before 5/8/95 -- inverse_segment_magnitude = fixdiv(F1_0/5, vm_vec_mag(&vector_to_center));
// -- Old way, before 5/8/95 -- vm_vec_scale_add(&light_location, &light_location, &vector_to_center, inverse_segment_magnitude);
for (segnum=0; segnum<=Highest_segment_index; segnum++)
{
segment *rsegp = &Segments[segnum];
vms_vector r_segment_center;
fix dist_to_rseg;
for (i=0; i<FVI_HASH_SIZE; i++)
fvi_cache[i].flag = 0;
// efficiency hack (I hope!), for faraway segments, don't check each point.
compute_segment_center(&r_segment_center, rsegp);
dist_to_rseg = vm_vec_dist_quick(&r_segment_center, &segment_center);
if (dist_to_rseg <= LIGHT_DISTANCE_THRESHOLD)
{
for (sidenum=0; sidenum<MAX_SIDES_PER_SEGMENT; sidenum++)
{
if (WALL_IS_DOORWAY(rsegp, sidenum) != WID_NO_WALL)
{
side *rsidep = &rsegp->sides[sidenum];
vms_vector *side_normalp = &rsidep->normals[0]; // kinda stupid? always use vector 0.
//mprintf((0, "[%i %i], ", rsegp-Segments, sidenum));
for (vertnum=0; vertnum<4; vertnum++)
{
fix distance_to_point, light_at_point, light_dot;
vms_vector vert_location, vector_to_light;
int abs_vertnum;
abs_vertnum = rsegp->verts[Side_to_verts[sidenum][vertnum]];
vert_location = Vertices[abs_vertnum];
distance_to_point = vm_vec_dist_quick(&vert_location, &light_location);
vm_vec_sub(&vector_to_light, &light_location, &vert_location);
vm_vec_normalize(&vector_to_light);
// Hack: In oblong segments, it's possible to get a very small dot product
// but the light source is very nearby (eg, illuminating light itself!).
light_dot = vm_vec_dot(&vector_to_light, side_normalp);
if (distance_to_point < F1_0)
if (light_dot > 0)
light_dot = (light_dot + F1_0)/2;
if (light_dot > 0)
{
light_at_point = fixdiv(fixmul(light_dot, light_dot), distance_to_point);
light_at_point = fixmul(light_at_point, Magical_light_constant);
if (light_at_point >= 0)
{
fvi_info hit_data;
int hit_type;
vms_vector vert_location_1, r_vector_to_center;
fix inverse_segment_magnitude;
vm_vec_sub(&r_vector_to_center, &r_segment_center, &vert_location);
inverse_segment_magnitude = fixdiv(F1_0/3, vm_vec_mag(&r_vector_to_center));
vm_vec_scale_add(&vert_location_1, &vert_location, &r_vector_to_center, inverse_segment_magnitude);
vert_location = vert_location_1;
//if ((segp-Segments == 199) && (rsegp-Segments==199))
// Int3();
// Seg0 = segp-Segments;
// Seg1 = rsegp-Segments;
if (!quick_light)
{
int hash_value = Side_to_verts[sidenum][vertnum];
hash_info *hashp = &fvi_cache[hash_value];
while (1)
{
if (hashp->flag)
{
if ((hashp->vector.x == vector_to_light.x) && (hashp->vector.y == vector_to_light.y) && (hashp->vector.z == vector_to_light.z)) {
//mprintf((0, "{CACHE %4x} ", hash_value));
hit_type = hashp->hit_type;
Hash_hits++;
break;
}
else
{
Int3(); // How is this possible? Should be no hits!
Hash_retries++;
hash_value = (hash_value+1) & FVI_HASH_AND_MASK;
hashp = &fvi_cache[hash_value];
}
}
else
{
//mprintf((0, "\nH:%04x ", hash_value));
fvi_query fq;
Hash_calcs++;
hashp->vector = vector_to_light;
hashp->flag = 1;
fq.p0 = &light_location;
fq.startseg = segp-Segments;
fq.p1 = &vert_location;
fq.rad = 0;
fq.thisobjnum = -1;
fq.ignore_obj_list = NULL;
fq.flags = 0;
hit_type = find_vector_intersection(&fq,&hit_data);
hashp->hit_type = hit_type;
break;
}
}
}
else
hit_type = HIT_NONE;
//mprintf((0, "hit=%i ", hit_type));
switch (hit_type)
{
case HIT_NONE:
light_at_point = fixmul(light_at_point, light_intensity);
rsidep->uvls[vertnum].l += light_at_point;
//mprintf((0, "(%5.2f) ", f2fl(light_at_point)));
if (rsidep->uvls[vertnum].l > F1_0)
rsidep->uvls[vertnum].l = F1_0;
break;
case HIT_WALL:
break;
case HIT_OBJECT:
Int3(); // Hit object, should be ignoring objects!
break;
case HIT_BAD_P0:
Int3(); // Ugh, this thing again, what happened, what does it mean?
break;
}
} // end if (light_at_point...
} // end if (light_dot >...
} // end for (vertnum=0...
} // end if (rsegp...
} // end for (sidenum=0...
} // end if (dist_to_rseg...
} // end for (segnum=0...
} // end for (lightnum=0...
//mprintf((0, "\n"));
}
// ------------------------------------------------------------------------------------------
// Zero all lighting values.
void calim_zero_light_values(void)
{
int segnum, sidenum, vertnum;
for (segnum=0; segnum<=Highest_segment_index; segnum++)
{
segment *segp = &Segments[segnum];
for (sidenum=0; sidenum<MAX_SIDES_PER_SEGMENT; sidenum++)
{
side *sidep = &segp->sides[sidenum];
for (vertnum=0; vertnum<4; vertnum++)
sidep->uvls[vertnum].l = F1_0/64; // Put a tiny bit of light here.
}
Segments[segnum].static_light = F1_0/64;
}
}
// ------------------------------------------------------------------------------------------
// Used in setting average light value in a segment, cast light from a side to the center
// of all segments.
void cast_light_from_side_to_center(segment *segp, int light_side, fix light_intensity, int quick_light)
{
vms_vector segment_center;
int segnum, lightnum;
compute_segment_center(&segment_center, segp);
// Do for four lights, one just inside each corner of side containing light.
for (lightnum=0; lightnum<4; lightnum++)
{
int light_vertex_num;
vms_vector vector_to_center;
vms_vector light_location;
light_vertex_num = segp->verts[Side_to_verts[light_side][lightnum]];
light_location = Vertices[light_vertex_num];
vm_vec_sub(&vector_to_center, &segment_center, &light_location);
vm_vec_scale_add(&light_location, &light_location, &vector_to_center, F1_0/64);
for (segnum=0; segnum<=Highest_segment_index; segnum++)
{
segment *rsegp = &Segments[segnum];
vms_vector r_segment_center;
fix dist_to_rseg;
//if ((segp == &Segments[Bugseg]) && (rsegp == &Segments[Bugseg]))
// Int3();
compute_segment_center(&r_segment_center, rsegp);
dist_to_rseg = vm_vec_dist_quick(&r_segment_center, &segment_center);
if (dist_to_rseg <= LIGHT_DISTANCE_THRESHOLD)
{
fix light_at_point;
if (dist_to_rseg > F1_0)
light_at_point = fixdiv(Magical_light_constant, dist_to_rseg);
else
light_at_point = Magical_light_constant;
if (light_at_point >= 0)
{
int hit_type;
if (!quick_light)
{
fvi_query fq;
fvi_info hit_data;
fq.p0 = &light_location;
fq.startseg = segp-Segments;
fq.p1 = &r_segment_center;
fq.rad = 0;
fq.thisobjnum = -1;
fq.ignore_obj_list = NULL;
fq.flags = 0;
hit_type = find_vector_intersection(&fq,&hit_data);
}
else
hit_type = HIT_NONE;
switch (hit_type) {
case HIT_NONE:
light_at_point = fixmul(light_at_point, light_intensity);
if (light_at_point >= F1_0)
light_at_point = F1_0-1;
rsegp->static_light += light_at_point;
if (segp->static_light < 0) // if it went negative, saturate
segp->static_light = 0;
break;
case HIT_WALL:
break;
case HIT_OBJECT:
Int3(); // Hit object, should be ignoring objects!
break;
case HIT_BAD_P0:
Int3(); // Ugh, this thing again, what happened, what does it mean?
break;
}
} // end if (light_at_point...
} // end if (dist_to_rseg...
} // end for (segnum=0...
} // end for (lightnum=0...
}
// ------------------------------------------------------------------------------------------
// Process all lights.
void calim_process_all_lights(int quick_light)
{
int segnum, sidenum;
for (segnum=0; segnum<=Highest_segment_index; segnum++) {
segment *segp = &Segments[segnum];
mprintf((0, "."));
for (sidenum=0; sidenum<MAX_SIDES_PER_SEGMENT; sidenum++) {
// if (!IS_CHILD(segp->children[sidenum])) {
if (WALL_IS_DOORWAY(segp, sidenum) != WID_NO_WALL) {
side *sidep = &segp->sides[sidenum];
fix light_intensity;
light_intensity = TmapInfo[sidep->tmap_num].lighting + TmapInfo[sidep->tmap_num2 & 0x3fff].lighting;
// if (segp->sides[sidenum].wall_num != -1) {
// int wall_num, bitmap_num, effect_num;
// wall_num = segp->sides[sidenum].wall_num;
// effect_num = Walls[wall_num].type;
// bitmap_num = effects_bm_num[effect_num];
//
// light_intensity += TmapInfo[bitmap_num].lighting;
// }
if (light_intensity) {
light_intensity /= 4; // casting light from four spots, so divide by 4.
cast_light_from_side(segp, sidenum, light_intensity, quick_light);
cast_light_from_side_to_center(segp, sidenum, light_intensity, quick_light);
}
}
}
}
}
// ------------------------------------------------------------------------------------------
// Apply static light in mine.
// First, zero all light values.
// Then, for all light sources, cast their light.
void cast_all_light_in_mine(int quick_flag)
{
validate_segment_all();
calim_zero_light_values();
calim_process_all_lights(quick_flag);
}
// int Fvit_num = 1000;
//
// fix find_vector_intersection_test(void)
// {
// int i;
// fvi_info hit_data;
// int p0_seg, p1_seg, this_objnum, ignore_obj, check_obj_flag;
// fix rad;
// int start_time = timer_get_milliseconds();;
// vms_vector p0,p1;
//
// ignore_obj = 1;
// check_obj_flag = 0;
// this_objnum = -1;
// rad = F1_0/4;
//
// for (i=0; i<Fvit_num; i++) {
// p0_seg = rand()*(Highest_segment_index+1)/32768;
// compute_segment_center(&p0, &Segments[p0_seg]);
//
// p1_seg = rand()*(Highest_segment_index+1)/32768;
// compute_segment_center(&p1, &Segments[p1_seg]);
//
// find_vector_intersection(&hit_data, &p0, p0_seg, &p1, rad, this_objnum, ignore_obj, check_obj_flag);
// }
//
// return timer_get_milliseconds() - start_time;
// }
vms_vector Normals[MAX_SEGMENTS*12];
int Normal_nearness = 4;
int normal_near(vms_vector *v1, vms_vector *v2)
{
if (abs(v1->x - v2->x) < Normal_nearness)
if (abs(v1->y - v2->y) < Normal_nearness)
if (abs(v1->z - v2->z) < Normal_nearness)
return 1;
return 0;
}
int Total_normals=0;
int Diff_normals=0;
void print_normals(void)
{
int i,j,s,n,nn;
// vms_vector *normal;
int num_normals=0;
Total_normals = 0;
Diff_normals = 0;
for (i=0; i<=Highest_segment_index; i++)
for (s=0; s<6; s++) {
if (Segments[i].sides[s].type == SIDE_IS_QUAD)
nn=1;
else
nn=2;
for (n=0; n<nn; n++) {
for (j=0; j<num_normals; j++)
if (normal_near(&Segments[i].sides[s].normals[n],&Normals[j]))
break;
if (j == num_normals) {
Normals[num_normals++] = Segments[i].sides[s].normals[n];
Diff_normals++;
}
Total_normals++;
}
}
}
#endif
| 31.964442 | 208 | 0.616854 | [
"object",
"vector",
"3d"
] |
a1a80149104261ee794eb2d3802982f361341a2f | 2,268 | cpp | C++ | fem/nonlinearform_ext.cpp | ianabel/mfem | d8c0e3a1914719a4e67a9f1b02ae4c6b5d9e7f0b | [
"BSD-3-Clause"
] | null | null | null | fem/nonlinearform_ext.cpp | ianabel/mfem | d8c0e3a1914719a4e67a9f1b02ae4c6b5d9e7f0b | [
"BSD-3-Clause"
] | null | null | null | fem/nonlinearform_ext.cpp | ianabel/mfem | d8c0e3a1914719a4e67a9f1b02ae4c6b5d9e7f0b | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
// Implementations of classes FABilinearFormExtension, EABilinearFormExtension,
// PABilinearFormExtension and MFBilinearFormExtension.
#include "nonlinearform.hpp"
namespace mfem
{
NonlinearFormExtension::NonlinearFormExtension(NonlinearForm *form)
: Operator(form->FESpace()->GetTrueVSize()), n(form)
{
// empty
}
PANonlinearFormExtension::PANonlinearFormExtension(NonlinearForm *form):
NonlinearFormExtension(form), fes(*form->FESpace())
{
const ElementDofOrdering ordering = ElementDofOrdering::LEXICOGRAPHIC;
elem_restrict_lex = fes.GetElementRestriction(ordering);
if (elem_restrict_lex)
{
localX.SetSize(elem_restrict_lex->Height(), Device::GetMemoryType());
localY.SetSize(elem_restrict_lex->Height(), Device::GetMemoryType());
localY.UseDevice(true); // ensure 'localY = 0.0' is done on device
}
}
void PANonlinearFormExtension::AssemblePA()
{
Array<NonlinearFormIntegrator*> &integrators = *n->GetDNFI();
const int Ni = integrators.Size();
for (int i = 0; i < Ni; ++i)
{
integrators[i]->AssemblePA(*n->FESpace());
}
}
void PANonlinearFormExtension::Mult(const Vector &x, Vector &y) const
{
Array<NonlinearFormIntegrator*> &integrators = *n->GetDNFI();
const int iSz = integrators.Size();
if (elem_restrict_lex)
{
elem_restrict_lex->Mult(x, localX);
localY = 0.0;
for (int i = 0; i < iSz; ++i)
{
integrators[i]->AddMultPA(localX, localY);
}
elem_restrict_lex->MultTranspose(localY, y);
}
else
{
y.UseDevice(true); // typically this is a large vector, so store on device
y = 0.0;
for (int i = 0; i < iSz; ++i)
{
integrators[i]->AddMultPA(x, y);
}
}
}
}
| 30.24 | 80 | 0.691358 | [
"vector"
] |
a1a867998ca21a8f91d31dc05c5f7ddf72a80d3a | 2,036 | cpp | C++ | hackerrank/Data Structures/Stacks/Largest_rectangle.cpp | GSri30/Competetive_programming | 0dc1681500a80b6f0979d0dc9f749357ee07bcb8 | [
"MIT"
] | 22 | 2020-01-03T17:32:00.000Z | 2021-11-07T09:31:44.000Z | hackerrank/Data Structures/Stacks/Largest_rectangle.cpp | GSri30/Competetive_programming | 0dc1681500a80b6f0979d0dc9f749357ee07bcb8 | [
"MIT"
] | 10 | 2020-09-30T09:41:18.000Z | 2020-10-11T11:25:09.000Z | hackerrank/Data Structures/Stacks/Largest_rectangle.cpp | GSri30/Competetive_programming | 0dc1681500a80b6f0979d0dc9f749357ee07bcb8 | [
"MIT"
] | 25 | 2019-10-14T19:25:01.000Z | 2021-05-26T08:12:20.000Z | #include <bits/stdc++.h>
using namespace std;
vector<string> split_string(string);
// Complete the largestRectangle function below.
long largestRectangle(vector<int> h)
{
stack <int> s;
int maxarea = 0;
int tp ;
int areawithtop = 0;
int n = h.size();
int i = 0;
while(i < n)
{
if(s.empty() || h[s.top()] <= h[i])
{
s.push(i++);
}
else
{
tp = s.top();
s.pop();
areawithtop = h[tp] * (s.empty() ? i : i - s.top() - 1);
if (maxarea < areawithtop)
{
maxarea = areawithtop;
}
}
}
while(!s.empty())
{
tp = s.top();
s.pop();
areawithtop = h[tp] * (s.empty() ? i : i - s.top() - 1);
if (maxarea < areawithtop)
{
maxarea = areawithtop;
}
}
return maxarea;
}
int main()
{
ofstream fout(getenv("OUTPUT_PATH"));
int n;
cin >> n;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
string h_temp_temp;
getline(cin, h_temp_temp);
vector<string> h_temp = split_string(h_temp_temp);
vector<int> h(n);
for (int i = 0; i < n; i++) {
int h_item = stoi(h_temp[i]);
h[i] = h_item;
}
long result = largestRectangle(h);
fout << result << "\n";
fout.close();
return 0;
}
vector<string> split_string(string input_string) {
string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) {
return x == y and x == ' ';
});
input_string.erase(new_end, input_string.end());
while (input_string[input_string.length() - 1] == ' ') {
input_string.pop_back();
}
vector<string> splits;
char delimiter = ' ';
size_t i = 0;
size_t pos = input_string.find(delimiter);
while (pos != string::npos) {
splits.push_back(input_string.substr(i, pos - i));
i = pos + 1;
pos = input_string.find(delimiter, i);
}
splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1));
return splits;
}
| 18.851852 | 115 | 0.550098 | [
"vector"
] |
a1a8890941ab29060bf84b9a7b84c115f3c65f50 | 2,148 | hpp | C++ | src/graph/prim.hpp | today2098/algorithm | b180355635d3d1ea0a8c3dff40ae1c9bac636f95 | [
"MIT"
] | null | null | null | src/graph/prim.hpp | today2098/algorithm | b180355635d3d1ea0a8c3dff40ae1c9bac636f95 | [
"MIT"
] | null | null | null | src/graph/prim.hpp | today2098/algorithm | b180355635d3d1ea0a8c3dff40ae1c9bac636f95 | [
"MIT"
] | null | null | null | #ifndef ALGORITHM_PRIM_HPP
#define ALGORITHM_PRIM_HPP 1
#include <algorithm>
#include <cassert>
#include <utility>
#include <vector>
namespace algorithm {
template <typename T>
class Prim {
struct Edge {
int to;
T cost;
};
int vn, n; // vn:=(ノード数), n:=(葉の数).
std::vector<std::vector<Edge> > g; // g[v][]:=(ノードvがもつ辺のリスト).
std::vector<T> tree; // tree[]:=(完全二分木). 1-based index.
T inf;
void shiht_up(int k) {
assert(n <= k and k < 2 * n);
k >>= 1;
while(k > 0) {
tree[k] = std::min(tree[2 * k], tree[2 * k + 1]);
k >>= 1;
}
}
void tree_push(T cost, int k) {
assert(0 <= k and k < vn);
k += n;
if(cost >= tree[k]) return;
tree[k] = cost;
shiht_up(k);
}
std::pair<T, int> tree_pop() {
int k = 1;
while(k < n) k = (tree[2 * k] < tree[2 * k + 1] ? 2 * k : 2 * k + 1);
auto &&res = std::pair<T, int>(tree[k], k - n);
tree[k] = inf;
shiht_up(k);
return res;
}
public:
// constructor.
Prim() : Prim(0) {}
explicit Prim(std::size_t vn_, T inf_ = 1e9) : vn(vn_), g(vn_), inf(inf_) {
n = 1;
while(n < vn) n <<= 1;
tree.assign(2 * n, inf);
}
int size() const { return vn; } // ノード数を返す.
void add_edge(int u, int v, T cost) { // 重み付き無向辺を張る.
assert(0 <= u and u < vn);
assert(0 <= v and v < vn);
g[u].push_back((Edge){v, cost});
g[v].push_back((Edge){u, cost});
}
T prim(int v = 0) { // ノードvを含む最小全域木のコストを求める. O(|E|*log|V|).
assert(0 <= v and v < vn);
T res = 0;
bool seen[vn] = {};
tree_push(0, v);
while(1) {
auto &&[cost, u] = tree_pop();
if(cost == inf) break;
if(seen[u]) continue;
res += cost, seen[u] = true;
for(const Edge &e : g[u]) {
if(!seen[e.to]) tree_push(e.cost, e.to);
}
}
return res;
}
};
} // namespace algorithm
#endif // ALGORITHM_PRIM_HPP
| 25.571429 | 79 | 0.449721 | [
"vector"
] |
a1aa8960342b3e54ee98759a69a3acef6ba178d5 | 5,847 | hpp | C++ | include/BuildingManager.hpp | sarahkittyy/MinerGame | 94b0398044e8bc1a0f84c80955a335a74febb025 | [
"MIT"
] | 1 | 2019-02-10T19:01:54.000Z | 2019-02-10T19:01:54.000Z | include/BuildingManager.hpp | sarahkittyy/MinerGame | 94b0398044e8bc1a0f84c80955a335a74febb025 | [
"MIT"
] | null | null | null | include/BuildingManager.hpp | sarahkittyy/MinerGame | 94b0398044e8bc1a0f84c80955a335a74febb025 | [
"MIT"
] | null | null | null | #pragma once
////////TODO///////
// Refactor ;-;
///////////////////
#include <imgui-sfml/imgui-SFML.h>
#include <imgui/imgui.h>
#include <SFML/Graphics.hpp>
#include <algorithm>
#include <exception>
#include <fstream>
#include <vector>
#include "KeyManager.hpp"
#include "MaterialManager.hpp"
#include "Tilemap.hpp"
#include "nlohmann/json.hpp"
/**
* @brief Class that loads & stores building information, and
* that updates GUI & states to allow for constructing buildings to the map.
*
* @remarks I'm sorry.
*
*/
class BuildingManager : public sf::Drawable
{
public:
/**
* @brief Declare the upgrade manager as a friend class.
*
*/
friend class UpgradeManager;
/**
* @brief Default constructor.
*
* @see initBuildings()
*/
BuildingManager(Tilemap *map);
/**
* @brief Simple typedef to make building usage easier.
*
*/
typedef nlohmann::json Building;
/**
* @brief Placed building data.
*
*/
struct BuildingEntityData
{
sf::Sprite spr;
Building *building_data;
};
/**
* @brief Get the main object data json object.
*
* @return nlohmann::json& A reference to the loaded object_data.json.
*/
nlohmann::json &getObjectData();
/**
* @brief Return the internal material manager.
*
* @return MaterialManager* A pointer to the main game material manager.
*/
MaterialManager *getMaterialManager();
/**
* @brief Renders the necessary gui components.
*
* @remarks REQUIRES ImGui::Begin() to have been called!
* @remarks CALL ImGui::End() AFTER.
*
* @see ImGui::Begin()
*/
void renderGuiBuildings();
/**
* @brief Renders the resources to the active ImGui context.
*
* @remarks CALL ImGui::Begin() BEFOREHAND.
*
*/
void renderGuiResources();
/**
* @brief Renders the tooltip for building information.
*
*/
void renderGuiTooltip();
/**
* @brief Updates the actively placed buildings & "build mode".
*
* @remarks Counts ticks & updates resources/tick.
*/
void update();
private:
/**
* @brief SFML draw() override.
*
*/
virtual void draw(sf::RenderTarget &target, sf::RenderStates states) const;
/**
* @brief The internal material manager.
*
*/
MaterialManager mMaterials;
/**
* @brief Internal clock to time the ticks per second.
*
*/
sf::Clock mTickClock;
/**
* @brief Clock that's never reset, logging the total game time elapsed.
*
*/
sf::Clock mGlobalClock;
/**
* @brief The whole object_data json file.
*
*/
nlohmann::json mObjectData;
/**
* @brief The ticks per second.
*
*/
float mTPS;
/**
* @brief Internal reference to the tilemap, to retrieve tile properties.
*
*/
Tilemap *mMap;
/**
* @brief The internal vector of buildings & their data.
*
*/
std::vector<Building> mBuildings;
/**
* @brief Vector of placed building data, for the actual rendered buildings.
*
*/
std::vector<BuildingEntityData> mBuilt;
/**
* @brief Renders the tooltip for the given building to GUI.
*
* @param building The building to render the tooltip for.
*/
void renderGuiBuilding(Building &building, bool isHighlightedOnMap = false);
/**
* @brief Initializes the material manager & the mBuildings vector.
*
* @return true If successful.
*/
bool initBuildings();
/**
* @brief Updates a single game tick.
*
*/
void updateTick();
/**
* @brief Returns the amount of buildings of the specified name are built.
*
* @param building_name The name of the building.
* @return int The built count.
*/
int getBuildingCount(std::string building_name);
/**
* @brief Returns a pointer to the building with the given name.
*
* @return Building*
*/
Building *getBuilding(std::string building_name);
/**
* @brief Map of building names to their textures.
*
*/
std::unordered_map<std::string, sf::Texture> mBuildingTextures;
/**
* @brief Get the texture of the given building.
*
* @param building_name The name of the building.
* @return sf::Texture* A pointer to the required texture.
*/
sf::Texture *getBuildingTexture(std::string building_name);
/**
* @brief Get the texture of the given building.
*
* @param building The building.
* @return sf::Texture* A pointer to the building's texture.
*/
sf::Texture *getBuildingTexture(Building &building);
/**
* @brief True if currently in "build mode" -- dragging tower for placement.
*
*/
bool mBuildMode;
/**
* @brief Build mode's internal reference to the currently selected
* building.
*
*/
Building *mBuildingBuilding;
/**
* @brief Enable buildmode & start moving the sprite.
*
* @param building
*/
void placeBuilding(Building *building);
/**
* @brief Called by update(), updates the building sprite & places the
* building if necessary & in buildmode.
*
*/
void updateBuilding();
/**
* @brief Releases the held building, ending build mode.
*
*/
void releaseBuilding();
/**
* @brief The sprite rendered when dragging & dropping the building.
*
*/
sf::Sprite mBuildingSprite;
/**
* @brief A rectangle rendered ontop of the map, to indicate placeable/unplaceable, and/or which tile is being hovered over.
*
*/
sf::RectangleShape mHighlightRect;
/**
* @brief A constant map of names to colors, for the different colors the
* map cursor can take on.
*
*/
const std::unordered_map<std::string, sf::Color> HIGHLIGHT = {
{"DEFAULT",
sf::Color(255, 255, 255, 130)},
{"INVALID",
sf::Color(255, 65, 65, 130)}};
/**
* @brief True if the HighlightRect should be drawn.
*
*/
bool mDrawHighlight;
/**
* @brief True if one of the buttons are being hovered over.
*
* @remarks Updated in renderGuiBuildings().
*
*/
bool mBuildingButtonHovered;
/**
* @brief Pointer to the building being hovered over.
*
*/
Building *mBuildingHovered;
}; | 20.162069 | 125 | 0.660852 | [
"render",
"object",
"vector"
] |
a1ac149ff025183ee3b3449df680d0a172787e9b | 4,582 | cpp | C++ | fuego-0.4/gouct/GoUctDefaultRootFilter.cpp | MisterTea/HyperNEAT | 516fef725621991ee709eb9b4afe40e0ce82640d | [
"BSD-3-Clause"
] | 85 | 2015-02-08T20:36:17.000Z | 2021-11-14T20:38:31.000Z | fuego-0.4/gouct/GoUctDefaultRootFilter.cpp | afcarl/HyperNEAT | 516fef725621991ee709eb9b4afe40e0ce82640d | [
"BSD-3-Clause"
] | 9 | 2015-01-28T16:33:19.000Z | 2020-04-12T23:03:28.000Z | fuego-0.4/gouct/GoUctDefaultRootFilter.cpp | afcarl/HyperNEAT | 516fef725621991ee709eb9b4afe40e0ce82640d | [
"BSD-3-Clause"
] | 27 | 2015-01-28T16:33:30.000Z | 2021-08-12T05:04:39.000Z | //----------------------------------------------------------------------------
/** @file GoUctDefaultRootFilter.cpp
See GoUctDefaultRootFilter.h
*/
//----------------------------------------------------------------------------
#include "SgSystem.h"
#include "GoUctDefaultRootFilter.h"
#include "GoBensonSolver.h"
#include "GoBoard.h"
#include "GoBoardUtil.h"
#include "GoModBoard.h"
#include "GoSafetySolver.h"
#include "SgWrite.h"
using namespace std;
//----------------------------------------------------------------------------
/** Return true, if point is on edge line and no stone is within a
Manhattan distance of 4.
*/
bool IsEmptyEdge(const GoBoard& bd, SgPoint p)
{
if (bd.Occupied(p))
return false;
int size = bd.Size();
int col = SgPointUtil::Col(p);
int row = SgPointUtil::Row(p);
if (! (col == 1 || col == size || row == 1 || row == size))
return false;
for (int deltaCol = -4; deltaCol <= 4; ++deltaCol)
for (int deltaRow = -4; deltaRow <= 4; ++deltaRow)
{
if (col + deltaCol < 1 || col + deltaCol > size
|| row + deltaRow < 1 || row + deltaRow > size
|| abs(deltaCol) + abs(deltaRow) > 4)
continue;
if (bd.Occupied(SgPointUtil::Pt(col + deltaCol,
row + deltaRow)))
return false;
}
return true;
}
//----------------------------------------------------------------------------
GoUctDefaultRootFilter::GoUctDefaultRootFilter(const GoBoard& bd)
: m_bd(bd),
m_checkLadders(true),
m_minLadderLength(6)
{
}
vector<SgPoint> GoUctDefaultRootFilter::Get()
{
vector<SgPoint> rootFilter;
SgBlackWhite toPlay = m_bd.ToPlay();
SgBlackWhite opp = SgOppBW(toPlay);
// Safe territory
GoModBoard modBoard(m_bd);
GoBoard& bd = modBoard.Board();
SgBWSet alternateSafe;
bool isAllAlternateSafe = false;
// Alternate safety is used to prune moves only in opponent territory
// and only if everything is alive under alternate play. This ensures that
// capturing moves that are not liberties of dead blocks and ko threats
// will not be pruned. This alternate safety pruning is not going to
// improve or worsen playing strength, but may cause earlier passes,
// which is nice in games against humans
GoSafetySolver safetySolver(bd);
safetySolver.FindSafePoints(&alternateSafe);
isAllAlternateSafe = (alternateSafe.Both() == bd.AllPoints());
// Benson solver guarantees that capturing moves of dead blocks are
// liberties of the dead blocks and that no move in Benson safe territory
// is a ko threat
GoBensonSolver bensonSolver(bd);
SgBWSet unconditionalSafe;
bensonSolver.FindSafePoints(&unconditionalSafe);
for (GoBoard::Iterator it(bd); it; ++it)
{
SgPoint p = *it;
if (m_bd.IsLegal(p))
{
bool isUnconditionalSafe = unconditionalSafe[toPlay].Contains(p);
bool isUnconditionalSafeOpp = unconditionalSafe[opp].Contains(p);
bool isAlternateSafeOpp = alternateSafe[opp].Contains(p);
bool hasOppNeighbors = bd.HasNeighbors(p, opp);
// Always generate capturing moves in own safe territory, even
// if current rules do no use CaptureDead(), because the UCT
// player always scores with Tromp-Taylor after two passes in the
// in-tree phase
if ((isAllAlternateSafe && isAlternateSafeOpp)
|| isUnconditionalSafeOpp
|| (isUnconditionalSafe && ! hasOppNeighbors))
rootFilter.push_back(p);
}
}
// Loosing ladder defense moves
if (m_checkLadders)
for (GoBlockIterator it(m_bd); it; ++it)
{
SgPoint p = *it;
if (m_bd.GetStone(p) == toPlay && m_bd.InAtari(p))
{
if (m_ladder.Ladder(m_bd, p, toPlay, &m_ladderSequence,
false/*twoLibIsEscape*/) < 0)
{
if (m_ladderSequence.Length() >= m_minLadderLength)
rootFilter.push_back(m_bd.TheLiberty(p));
}
}
}
// Moves on edge line, if no stone is near
for (GoBoard::Iterator it(m_bd); it; ++it)
{
SgPoint p = *it;
if (IsEmptyEdge(m_bd, p))
rootFilter.push_back(p);
}
return rootFilter;
}
//----------------------------------------------------------------------------
| 33.940741 | 78 | 0.549542 | [
"vector"
] |
a1ae48a41a0e52c3a64862d87f7266b0a69ff286 | 1,803 | cpp | C++ | Modules/Classification/CLVigraRandomForest/src/IO/mitkDummyLsetReader.cpp | zhaomengxiao/MITK | a09fd849a4328276806008bfa92487f83a9e2437 | [
"BSD-3-Clause"
] | 1 | 2022-03-03T12:03:32.000Z | 2022-03-03T12:03:32.000Z | Modules/Classification/CLVigraRandomForest/src/IO/mitkDummyLsetReader.cpp | zhaomengxiao/MITK | a09fd849a4328276806008bfa92487f83a9e2437 | [
"BSD-3-Clause"
] | 1 | 2021-12-22T10:19:02.000Z | 2021-12-22T10:19:02.000Z | Modules/Classification/CLVigraRandomForest/src/IO/mitkDummyLsetReader.cpp | zhaomengxiao/MITK_lancet | a09fd849a4328276806008bfa92487f83a9e2437 | [
"BSD-3-Clause"
] | 1 | 2020-11-27T09:41:18.000Z | 2020-11-27T09:41:18.000Z | /*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
#include <mitkDummyLsetReader.h>
#include <itksys/SystemTools.hxx>
#include <itkImageFileReader.h>
#include <itkNrrdImageIO.h>
#include <mitkImageCast.h>
#include <mitkCustomMimeType.h>
typedef itk::Image<unsigned char, 3> ImageType;
std::vector<itk::SmartPointer<mitk::BaseData> > mitk::DummyLsetFileReader::DoRead()
{
std::vector<itk::SmartPointer<mitk::BaseData> > result;
typedef itk::ImageFileReader<ImageType> FileReaderType;
FileReaderType::Pointer reader = FileReaderType::New();
reader->SetFileName(this->GetInputLocation());
itk::NrrdImageIO::Pointer io = itk::NrrdImageIO::New();
reader->SetImageIO(io);
reader->Update();
mitk::Image::Pointer img;
mitk::CastToMitkImage(reader->GetOutput(),img);
result.push_back(img.GetPointer());
return result;
}
mitk::DummyLsetFileReader::DummyLsetFileReader(const DummyLsetFileReader & other)
: AbstractFileReader(other)
{
}
mitk::DummyLsetFileReader* mitk::DummyLsetFileReader::Clone() const
{
return new DummyLsetFileReader(*this);
}
mitk::DummyLsetFileReader::~DummyLsetFileReader()
{}
mitk::DummyLsetFileReader::DummyLsetFileReader()
{
CustomMimeType mimeType(this->GetMimeTypePrefix() + "lset");
mimeType.AddExtension("lset");
mimeType.SetCategory("Images");
mimeType.SetComment("Experimental MBI LabelSetImage");
this->SetMimeType(mimeType);
this->SetDescription("MBI LabelSetImage");
this->RegisterService();
}
| 26.910448 | 83 | 0.691625 | [
"vector"
] |
a1b1cd0c427c0f0620f90cd11c1d3f241cb227e8 | 804 | cpp | C++ | watchman/tests/log.cpp | chadaustin/watchman | b01a841f3eca5ebaf5ce4a62e1937c95851f450e | [
"MIT"
] | 9,308 | 2015-01-03T13:33:47.000Z | 2022-03-31T06:45:26.000Z | watchman/test/log.cpp | 00mjk/watchman | eb22a60e74f04065e24eb51ba1dd1342d66f2ad6 | [
"MIT"
] | 878 | 2015-01-07T15:28:33.000Z | 2022-03-30T09:30:10.000Z | watchman/test/log.cpp | 00mjk/watchman | eb22a60e74f04065e24eb51ba1dd1342d66f2ad6 | [
"MIT"
] | 932 | 2015-01-05T08:25:00.000Z | 2022-03-25T11:11:42.000Z | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <folly/portability/GTest.h>
#include "watchman/Logging.h"
using namespace watchman;
void w_request_shutdown(void) {}
TEST(Log, logging) {
char huge[8192];
bool logged = false;
auto sub = watchman::getLog().subscribe(
watchman::DBG, [&logged]() { logged = true; });
memset(huge, 'X', sizeof(huge));
huge[sizeof(huge) - 1] = '\0';
logf(DBG, "test {}", huge);
std::vector<std::shared_ptr<const watchman::Publisher::Item>> pending;
sub->getPending(pending);
EXPECT_FALSE(pending.empty()) << "got an item from our subscription";
EXPECT_TRUE(logged);
}
/* vim:ts=2:sw=2:et:
*/
| 22.971429 | 72 | 0.670398 | [
"vector"
] |
a1b3439ca94bd5f1ded367bc0de684243e008fd9 | 14,971 | cpp | C++ | src/Module_trigSeq.cpp | j4s0n-c/trowaSoft-VCV | 9cd0d05607c88e95200472725df1d032b42130cd | [
"MIT"
] | 91 | 2017-11-28T07:23:09.000Z | 2022-03-28T08:31:51.000Z | src/Module_trigSeq.cpp | j4s0n-c/trowaSoft-VCV | 9cd0d05607c88e95200472725df1d032b42130cd | [
"MIT"
] | 59 | 2017-11-28T06:12:18.000Z | 2022-03-18T09:00:59.000Z | src/Module_trigSeq.cpp | j4s0n-c/trowaSoft-VCV | 9cd0d05607c88e95200472725df1d032b42130cd | [
"MIT"
] | 15 | 2017-11-28T13:42:35.000Z | 2021-12-26T08:03:37.000Z | #include <string.h>
#include <stdio.h>
#include <exception>
#include "TSSequencerModuleBase.hpp"
#include "trowaSoft.hpp"
//#include "dsp/digital.hpp"
#include "trowaSoftComponents.hpp"
#include "trowaSoftUtilities.hpp"
#include "Module_trigSeq.hpp"
#include "TSOSCSequencerOutputMessages.hpp"
#include "TSOSCCommon.hpp"
#include "TSSequencerWidgetBase.hpp"
Model* modelTrigSeq = createModel<trigSeq, trigSeqWidget>(/*slug*/ "trigSeq");
Model* modelTrigSeq64 = createModel<trigSeq64, trigSeq64Widget>(/*slug*/ "trigSeq64");
trigSeq::trigSeq(int numSteps, int numRows, int numCols) : TSSequencerModuleBase(numSteps, numRows, numCols, false, TSSequencerModuleBase::ValueMode::VALUE_TRIGGER)
{
// [v1.0.4] Set the value modes we support:
numValueModesSupported = 3;
valueModesSupported = new ValueMode[numValueModesSupported] { ValueMode::VALUE_TRIGGER, ValueMode::VALUE_RETRIGGER, ValueMode::VALUE_CONTINUOUS };
selectedOutputValueMode = defaultChannelValueMode;
selectedOutputValueModeIx = getSupportedValueModeIndex(selectedOutputValueMode);
lastOutputValueMode = selectedOutputValueMode;
gateTriggers = new dsp::SchmittTrigger[numSteps]; // maxSteps
// Configure Parameters:
for (int s = 0; s < maxSteps; s++)
{
configSwitch(TSSequencerModuleBase::CHANNEL_PARAM + s, 0, 1, defaultStateValue, "Step " + std::to_string(s+1), {"Off", "On"});;
//configParam(TSSequencerModuleBase::CHANNEL_PARAM + s, 0.0, 1.0, defaultStateValue, /*label*/ "Step " + std::to_string(s+1));
}
this->reconfigureValueModeParamQty();
return;
}
//-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
// trigSeq::randomize()
// Only randomize the current gate/trigger steps.
//-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
void trigSeq::onRandomize()
{
for (int s = 0; s < maxSteps; s++)
{
triggerState[currentPatternEditingIx][currentChannelEditingIx][s] = (random::uniform() > 0.5);
}
reloadEditMatrix = true;
return;
} // end randomize()
//-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
// Toggle the single step value
// (i.e. this command probably comes from an external source)
// @step : (IN) The step number to edit (0 to maxSteps).
// @val : (IN) The step value.
// @channel : (IN) The channel to edit (0 to TROWA_SEQ_NUM_CHNLS - 1).
// @pattern: (IN) The pattern to edit (0 to TROWA_SEQ_NUM_PATTERNS - 1).
//-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
float trigSeq::getToggleStepValue(int step, float val, int channel, int pattern)
{
return !(bool)(triggerState[pattern][channel][step]);
} // end getToggleStepValue()
//-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
// Calculate a representation of all channels for this step
//-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
float trigSeq::getPlayingStepValue(int step, int pattern)
{
/// TODO: REMOVE THIS, NOT USED ANYMORE
int count = 0;
for (int c = 0; c < TROWA_SEQ_NUM_CHNLS; c++)
{
count += (bool)(this->triggerState[pattern][c][step]);
} // end for
return (float)(count) / (float)(TROWA_SEQ_NUM_CHNLS);
} // end getPlayingStepValue()
//-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
// process()
// [Previously step(void)]
//-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
void trigSeq::process(const ProcessArgs &args)
{
if (!initialized)
return;
// Now calculate some base items all the time:
float clockTime = 0.0f;
bool nextStep = isNewStep(args.sampleRate, &clockTime);
#if TROWA_SEQ_USE_INTERNAL_DIVISOR
if (nextStep)
{
idleCounter = 0;
}
else
{
// Skip evaluations if needed
idleCounter = (idleCounter + 1) % IDLETHRESHOLD;
if (idleCounter != 0)
{
return;
}
}
#endif
bool gOn = true;
bool pulse = false;
bool reloadMatrix = false;
bool valueModeChanged = false;
bool sendOSC = useOSC && oscInitialized;
int r = 0;
int c = 0;
//------------------------------------------------------------
// Get our common sequencer inputs
//------------------------------------------------------------
TSSequencerModuleBase::getStepInputs(args, &pulse, &reloadMatrix, &valueModeChanged, nextStep, clockTime);
if (valueModeChanged)
{
// v1.0.4 - This should be OK for trigSeq (he uses the first 3 ValueModes).
// Gate Mode has changed
gateMode = static_cast<GateMode>((short)(selectedOutputValueMode));
modeString = modeStrings[selectedOutputValueMode];
channelValueModes[currentChannelEditingIx] = selectedOutputValueMode;
}
// Only send OSC if it is enabled, initialized, and we are in EDIT mode.
sendOSC = useOSC && oscInitialized; //&& currentCtlMode == ExternalControllerMode::EditMode
char addrBuff[TROWA_SEQ_BUFF_SIZE] = { 0 };
//-- * Load the trigger we are editing into our button matrix for display:
// This is what we are showing not what we playing
int gridRow, gridCol; // for touchOSC grids
if (reloadMatrix)
{
reloadEditMatrix = false;
oscMutex.lock();
osc::OutboundPacketStream oscStream(oscBuffer, OSC_OUTPUT_BUFFER_SIZE);
if (sendOSC && oscInitialized)
{
#if TROWA_DEBUG_MSGS >= TROWA_DEBUG_LVL_MED
DEBUG("Sending reload matrix: %s.", oscAddrBuffer[SeqOSCOutputMsg::EditStep]);
#endif
oscStream << osc::BeginBundleImmediate;
}
oscMutex.unlock();
// Load this gate and/or pattern into our 4x4 matrix
this->currentStepMatrixColor = voiceColors[currentChannelEditingIx];
for (int s = 0; s < maxSteps; s++)
{
r = s / this->numCols; // TROWA_SEQ_STEP_NUM_COLS;
c = s % this->numCols; // TROWA_SEQ_STEP_NUM_COLS;
//padLightPtrs[r][c]->setColor(voiceColors[currentChannelEditingIx]);
if (triggerState[currentPatternEditingIx][currentChannelEditingIx][s])
{
gateLights[r][c] = 1.0f - stepLights[r][c];
gateTriggers[s].state = TriggerSignal::HIGH;
paramQuantities[ParamIds::CHANNEL_PARAM + s]->setValue(1.0f);// Not momentary anymore
}
else
{
gateLights[r][c] = 0.0f; // Turn light off
gateTriggers[s].state = TriggerSignal::LOW;
paramQuantities[ParamIds::CHANNEL_PARAM + s]->setValue(0.0f);// Not momentary anymore
}
oscMutex.lock();
if (sendOSC && oscInitialized)
{
if (s > 0 && s % 16 == 0) // There is a limit to client buffer size, so let's not make the bundles too large. Hopefully they can take 16-steps at a time.
{
// Send this bundle and then start a new one
oscStream << osc::EndBundle;
oscTxSocket->Send(oscStream.Data(), oscStream.Size());
oscStream.Clear();
// Start new bundle:
oscStream << osc::BeginBundleImmediate;
}
if (this->oscCurrentClient == OSCClient::touchOSCClient)
{
// LED Color (current step LED):
sprintf(addrBuff, oscAddrBuffer[SeqOSCOutputMsg::PlayStepLed], s + 1);
sprintf(addrBuff, OSC_TOUCH_OSC_CHANGE_COLOR_FS, addrBuff);
oscStream << osc::BeginMessage(addrBuff)
<< touchOSC::ChannelColors[currentChannelEditingIx]
<< osc::EndMessage;
// Step:
touchOSC::stepIndex_to_mcRowCol(s, numRows, numCols, &gridRow, &gridCol);
sprintf(addrBuff, oscAddrBuffer[SeqOSCOutputMsg::EditTOSC_GridStep], gridRow, gridCol); // Grid's /<row>/<col> to accomodate touchOSC's lack of multi-parameter support.
}
else
{
// Step
sprintf(addrBuff, oscAddrBuffer[SeqOSCOutputMsg::EditStep], s + 1); // Changed to /<step> to accomodate touchOSC's lack of multi-parameter support.
}
oscStream << osc::BeginMessage(addrBuff)
<< triggerState[currentPatternEditingIx][currentChannelEditingIx][s]
<< osc::EndMessage;
}
oscMutex.unlock();
} // end for
oscMutex.lock();
if (sendOSC && oscInitialized)
{
// Send color of grid:
if (this->oscCurrentClient == OSCClient::touchOSCClient)
{
oscStream << osc::BeginMessage(oscAddrBuffer[SeqOSCOutputMsg::EditStepGridColor])
<< touchOSC::ChannelColors[currentChannelEditingIx]
<< osc::EndMessage;
// Also change color on the Channel control:
sprintf(addrBuff, OSC_TOUCH_OSC_CHANGE_COLOR_FS, oscAddrBuffer[SeqOSCOutputMsg::EditChannel]);
oscStream << osc::BeginMessage(addrBuff)
<< touchOSC::ChannelColors[currentChannelEditingIx]
<< osc::EndMessage;
}
// End last bundle and send:
oscStream << osc::EndBundle;
oscTxSocket->Send(oscStream.Data(), oscStream.Size());
}
oscMutex.unlock();
}
//-- * Read the buttons
else if (!valuesChanging) // Only read in if another thread isn't changing the values
{
oscMutex.lock();
osc::OutboundPacketStream oscStream(oscBuffer, OSC_OUTPUT_BUFFER_SIZE);
if (sendOSC && oscInitialized)
{
oscStream << osc::BeginBundleImmediate;
}
oscMutex.unlock();
int numChanged = 0;
// Step buttons/pads (for this one Channel/gate) - Read Inputs
for (int s = 0; s < maxSteps; s++)
{
bool sendLightVal = false;
//if (gateTriggers[s].process(params[ParamIds::CHANNEL_PARAM + s].getValue()))
// Now normal switches:
if (triggerState[currentPatternEditingIx][currentChannelEditingIx][s] != (params[ParamIds::CHANNEL_PARAM + s].getValue() > 0))
{
triggerState[currentPatternEditingIx][currentChannelEditingIx][s] = !triggerState[currentPatternEditingIx][currentChannelEditingIx][s];
sendLightVal = sendOSC; // Value has changed.
}
r = s / this->numCols; // TROWA_SEQ_STEP_NUM_COLS;
c = s % this->numCols; // TROWA_SEQ_STEP_NUM_COLS;
stepLights[r][c] -= stepLights[r][c] / lightLambda / args.sampleRate;
gateLights[r][c] = (triggerState[currentPatternEditingIx][currentChannelEditingIx][s]) ? 1.0 - stepLights[r][c] : stepLights[r][c];
lights[PAD_LIGHTS + s].value = gateLights[r][c];
oscMutex.lock();
// This step has changed and we are doing OSC
if (sendLightVal && oscInitialized)
{
// Send the step value
if (this->oscCurrentClient == OSCClient::touchOSCClient)
{
touchOSC::stepIndex_to_mcRowCol(s, numRows, numCols, &gridRow, &gridCol);
sprintf(addrBuff, oscAddrBuffer[SeqOSCOutputMsg::EditTOSC_GridStep], gridRow, gridCol); // Grid's /<row>/<col> to accomodate touchOSC's lack of multi-parameter support.
}
else
{
sprintf(addrBuff, oscAddrBuffer[SeqOSCOutputMsg::EditStep], s + 1); // Changed to /<step> to accomodate touchOSC's lack of multi-parameter support.
}
#if TROWA_DEBUG_MSGS >= TROWA_DEBUG_LVL_MED
DEBUG("Step changed %d (new val is %.2f), sending OSC %s", s, triggerState[currentPatternEditingIx][currentChannelEditingIx][s], addrBuff);
#endif
oscStream << osc::BeginMessage(addrBuff)
<< triggerState[currentPatternEditingIx][currentChannelEditingIx][s]
<< osc::EndMessage;
numChanged++;
} // end if send the value over OSC
oscMutex.unlock();
} // end loop through step buttons
oscMutex.lock();
if (sendOSC && oscInitialized && numChanged > 0)
{
oscStream << osc::EndBundle;
oscTxSocket->Send(oscStream.Data(), oscStream.Size());
}
oscMutex.unlock();
} // end else (read buttons)
// Set Outputs (16 Channels)
// gOn = true;
// if (gateMode == TRIGGER)
// gOn = pulse; // gateOn = gateOn && pulse;
// else if (gateMode == RETRIGGER)
// gOn = !pulse; // gateOn = gateOn && !pulse;
for (int g = 0; g < TROWA_SEQ_NUM_CHNLS; g++)
{
switch (channelValueModes[g]) // [v1.1] Each channel can have its own output mode (trigger/retrigger/gate).
{
case VALUE_TRIGGER:
gOn = pulse;
break;
case VALUE_RETRIGGER:
gOn = !pulse;
break;
default:
gOn = true;
break;
}
float gate = (running && gOn && (triggerState[currentPatternPlayingIx][g][index])) ? trigSeq_GATE_ON_OUTPUT : trigSeq_GATE_OFF_OUTPUT;
outputs[CHANNELS_OUTPUT + g].value= gate;
// Output lights (around output jacks for each gate/trigger):
lights[CHANNEL_LIGHTS + g].value = (running && triggerState[currentPatternPlayingIx][g][index]) ? 1.0 : 0;
}
// Now we have to keep track of this for OSC...
prevIndex = index;
return;
} // end step()
//-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
// trigSeqWidget()
// Widget for the trowaSoft 16-step pad / trigger sequencer.
// @seqModule : (IN) Pointer to the sequencer module.
//-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
trigSeqWidget::trigSeqWidget(trigSeq* seqModule) : TSSequencerWidgetBase(seqModule)
{
// [02/24/2018] Adjusted for 0.60 differences. Main issue is possiblity of NULL module...
bool isPreview = this->module == NULL; // If this is null, then this isn't a real module instance but a 'Preview'?
if (!isPreview && seqModule == NULL)
{
seqModule = dynamic_cast<trigSeq*>(this->module);
}
//////////////////////////////////////////////
// Background
//////////////////////////////////////////////
{
SvgPanel *panel = new SvgPanel();
panel->box.size = box.size;
panel->setBackground(APP->window->loadSvg(asset::plugin(pluginInstance, "res/trigSeq.svg")));
addChild(panel);
}
this->TSSequencerWidgetBase::addBaseControls(false);
// (User) Input Pads ==================================================
int y = 115;
int x = 79;
int dx = 3;
Vec lSize = Vec(50 - 2*dx, 50 - 2*dx);
NVGcolor lightColor = TSColors::COLOR_TS_RED;
numCols = TROWA_SEQ_STEP_NUM_COLS;
numRows = TROWA_SEQ_STEP_NUM_ROWS;
int groupId = 0;
if (!isPreview)
{
numCols = seqModule->numCols;
numRows = seqModule->numRows;
lightColor = seqModule->voiceColors[seqModule->currentChannelEditingIx];
groupId = seqModule->oscId; // Use this id for now since this is unique to each module instance.
}
int id = 0;
padLightPtrs = new ColorValueLight**[numRows];
for (int r = 0; r < numRows; r++) //---------THE PADS
{
padLightPtrs[r] = new ColorValueLight*[numCols];
for (int c = 0; c < numCols; c++)
{
// Pad buttons:
TS_PadSquare* padBtn = dynamic_cast<TS_PadSquare*>(createParam<TS_PadSquare>(Vec(x, y), seqModule, TSSequencerModuleBase::CHANNEL_PARAM + id));//, 0.0, 1.0, 0.0));
padBtn->groupId = groupId;
padBtn->btnId = id;
addParam(padBtn);
// Lights:
TS_LightSquare* padLight = dynamic_cast<TS_LightSquare*>(TS_createColorValueLight<TS_LightSquare>(/*pos */ Vec(x + dx, y + dx),
/*seqModule*/ seqModule,
/*lightId*/ TSSequencerModuleBase::PAD_LIGHTS + id, // r * numCols + c
/* size */ lSize, /* color */ lightColor));
addChild(padLight);
padLight->cornerRadius = 5.0f;
padLightPtrs[r][c] = padLight;
// if (seqModule != NULL)
// {
// // Keep a reference to our pad lights so we can change the colors
// seqModule->padLightPtrs[r][c] = padLight;
// }
x+= 59;
id++;
}
y += 59; // Next row
x = 79;
} // end loop through MxN grid
if (seqModule != NULL)
{
seqModule->modeString = seqModule->modeStrings[seqModule->selectedOutputValueMode];
seqModule->initialized = true;
}
return;
} // end trigSeqWidget()
| 36.783784 | 173 | 0.643578 | [
"model"
] |
a1b771adbe191013082371cf07dba90392fdf8f3 | 1,270 | cpp | C++ | DSA Crack Sheet/solutions/Middle of the Linked List.cpp | Akshad7829/DataStructures-Algorithms | 439822c6a374672d1734e2389d3fce581a35007d | [
"MIT"
] | 5 | 2021-08-10T18:47:49.000Z | 2021-08-21T15:42:58.000Z | DSA Crack Sheet/solutions/Middle of the Linked List.cpp | Akshad7829/DataStructures-Algorithms | 439822c6a374672d1734e2389d3fce581a35007d | [
"MIT"
] | 2 | 2022-02-25T13:36:46.000Z | 2022-02-25T14:06:44.000Z | DSA Crack Sheet/solutions/Middle of the Linked List.cpp | Akshad7829/DataStructures-Algorithms | 439822c6a374672d1734e2389d3fce581a35007d | [
"MIT"
] | 1 | 2021-08-11T06:36:42.000Z | 2021-08-11T06:36:42.000Z | /*
Middle of the Linked List
=========================
Given a non-empty, singly linked list with head node head, return a middle node of linked list.
If there are two middle nodes, return the second middle node.
Example 1:
Input: [1,2,3,4,5]
Output: Node 3 from this list (Serialization: [3,4,5])
The returned node has value 3. (The judge's serialization of this node is [3,4,5]).
Note that we returned a ListNode object ans, such that:
ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, and ans.next.next.next = NULL.
Example 2:
Input: [1,2,3,4,5,6]
Output: Node 4 from this list (Serialization: [4,5,6])
Since the list has two middle nodes with values 3 and 4, we return the second one.
Note:
The number of nodes in the given list will be between 1 and 100.
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution
{
public:
ListNode *middleNode(ListNode *head)
{
auto fast = head, slow = head;
while (fast && fast->next)
{
fast = fast->next->next;
slow = slow->next;
}
return slow;
}
}; | 25.918367 | 95 | 0.637008 | [
"object"
] |
a1b7ab596b8362c2511ebe3c391bdd1166b31614 | 15,285 | hpp | C++ | boost/lib/include/boost/asio/execution/set_value.hpp | mamil/demo | 32240d95b80175549e6a1904699363ce672a1591 | [
"MIT"
] | 177 | 2021-02-19T02:01:04.000Z | 2022-03-30T07:31:21.000Z | boost/lib/include/boost/asio/execution/set_value.hpp | mamil/demo | 32240d95b80175549e6a1904699363ce672a1591 | [
"MIT"
] | 188 | 2021-02-19T04:15:55.000Z | 2022-03-26T09:42:15.000Z | boost/lib/include/boost/asio/execution/set_value.hpp | mamil/demo | 32240d95b80175549e6a1904699363ce672a1591 | [
"MIT"
] | 78 | 2021-03-05T03:01:13.000Z | 2022-03-29T07:10:01.000Z | //
// execution/set_value.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef BOOST_ASIO_EXECUTION_SET_VALUE_HPP
#define BOOST_ASIO_EXECUTION_SET_VALUE_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <boost/asio/detail/config.hpp>
#include <boost/asio/detail/type_traits.hpp>
#include <boost/asio/detail/variadic_templates.hpp>
#include <boost/asio/traits/set_value_member.hpp>
#include <boost/asio/traits/set_value_free.hpp>
#include <boost/asio/detail/push_options.hpp>
#if defined(GENERATING_DOCUMENTATION)
namespace boost {
namespace asio {
namespace execution {
/// A customisation point that delivers a value to a receiver.
/**
* The name <tt>execution::set_value</tt> denotes a customisation point object.
* The expression <tt>execution::set_value(R, Vs...)</tt> for some
* subexpressions <tt>R</tt> and <tt>Vs...</tt> is expression-equivalent to:
*
* @li <tt>R.set_value(Vs...)</tt>, if that expression is valid. If the
* function selected does not send the value(s) <tt>Vs...</tt> to the receiver
* <tt>R</tt>'s value channel, the program is ill-formed with no diagnostic
* required.
*
* @li Otherwise, <tt>set_value(R, Vs...)</tt>, if that expression is valid,
* with overload resolution performed in a context that includes the
* declaration <tt>void set_value();</tt> and that does not include a
* declaration of <tt>execution::set_value</tt>. If the function selected by
* overload resolution does not send the value(s) <tt>Vs...</tt> to the
* receiver <tt>R</tt>'s value channel, the program is ill-formed with no
* diagnostic required.
*
* @li Otherwise, <tt>execution::set_value(R, Vs...)</tt> is ill-formed.
*/
inline constexpr unspecified set_value = unspecified;
/// A type trait that determines whether a @c set_value expression is
/// well-formed.
/**
* Class template @c can_set_value is a trait that is derived from
* @c true_type if the expression <tt>execution::set_value(std::declval<R>(),
* std::declval<Vs>()...)</tt> is well formed; otherwise @c false_type.
*/
template <typename R, typename... Vs>
struct can_set_value :
integral_constant<bool, automatically_determined>
{
};
} // namespace execution
} // namespace asio
} // namespace boost
#else // defined(GENERATING_DOCUMENTATION)
namespace asio_execution_set_value_fn {
using boost::asio::decay;
using boost::asio::declval;
using boost::asio::enable_if;
using boost::asio::traits::set_value_free;
using boost::asio::traits::set_value_member;
void set_value();
enum overload_type
{
call_member,
call_free,
ill_formed
};
template <typename R, typename Vs, typename = void>
struct call_traits
{
BOOST_ASIO_STATIC_CONSTEXPR(overload_type, overload = ill_formed);
BOOST_ASIO_STATIC_CONSTEXPR(bool, is_noexcept = false);
typedef void result_type;
};
template <typename R, typename Vs>
struct call_traits<R, Vs,
typename enable_if<
(
set_value_member<R, Vs>::is_valid
)
>::type> :
set_value_member<R, Vs>
{
BOOST_ASIO_STATIC_CONSTEXPR(overload_type, overload = call_member);
};
template <typename R, typename Vs>
struct call_traits<R, Vs,
typename enable_if<
(
!set_value_member<R, Vs>::is_valid
&&
set_value_free<R, Vs>::is_valid
)
>::type> :
set_value_free<R, Vs>
{
BOOST_ASIO_STATIC_CONSTEXPR(overload_type, overload = call_free);
};
struct impl
{
#if defined(BOOST_ASIO_HAS_MOVE)
#if defined(BOOST_ASIO_HAS_VARIADIC_TEMPLATES)
template <typename R, typename... Vs>
BOOST_ASIO_CONSTEXPR typename enable_if<
call_traits<R, void(Vs...)>::overload == call_member,
typename call_traits<R, void(Vs...)>::result_type
>::type
operator()(R&& r, Vs&&... v) const
BOOST_ASIO_NOEXCEPT_IF((
call_traits<R, void(Vs...)>::is_noexcept))
{
return BOOST_ASIO_MOVE_CAST(R)(r).set_value(BOOST_ASIO_MOVE_CAST(Vs)(v)...);
}
template <typename R, typename... Vs>
BOOST_ASIO_CONSTEXPR typename enable_if<
call_traits<R, void(Vs...)>::overload == call_free,
typename call_traits<R, void(Vs...)>::result_type
>::type
operator()(R&& r, Vs&&... v) const
BOOST_ASIO_NOEXCEPT_IF((
call_traits<R, void(Vs...)>::is_noexcept))
{
return set_value(BOOST_ASIO_MOVE_CAST(R)(r),
BOOST_ASIO_MOVE_CAST(Vs)(v)...);
}
#else // defined(BOOST_ASIO_HAS_VARIADIC_TEMPLATES)
template <typename R>
BOOST_ASIO_CONSTEXPR typename enable_if<
call_traits<R, void()>::overload == call_member,
typename call_traits<R, void()>::result_type
>::type
operator()(R&& r) const
BOOST_ASIO_NOEXCEPT_IF((
call_traits<R, void()>::is_noexcept))
{
return BOOST_ASIO_MOVE_CAST(R)(r).set_value();
}
template <typename R>
BOOST_ASIO_CONSTEXPR typename enable_if<
call_traits<R, void()>::overload == call_free,
typename call_traits<R, void()>::result_type
>::type
operator()(R&& r) const
BOOST_ASIO_NOEXCEPT_IF((
call_traits<R, void()>::is_noexcept))
{
return set_value(BOOST_ASIO_MOVE_CAST(R)(r));
}
#define BOOST_ASIO_PRIVATE_SET_VALUE_CALL_DEF(n) \
template <typename R, BOOST_ASIO_VARIADIC_TPARAMS(n)> \
BOOST_ASIO_CONSTEXPR typename enable_if< \
call_traits<R, \
void(BOOST_ASIO_VARIADIC_TARGS(n))>::overload == call_member, \
typename call_traits<R, void(BOOST_ASIO_VARIADIC_TARGS(n))>::result_type \
>::type \
operator()(R&& r, BOOST_ASIO_VARIADIC_MOVE_PARAMS(n)) const \
BOOST_ASIO_NOEXCEPT_IF(( \
call_traits<R, void(BOOST_ASIO_VARIADIC_TARGS(n))>::is_noexcept)) \
{ \
return BOOST_ASIO_MOVE_CAST(R)(r).set_value( \
BOOST_ASIO_VARIADIC_MOVE_ARGS(n)); \
} \
\
template <typename R, BOOST_ASIO_VARIADIC_TPARAMS(n)> \
BOOST_ASIO_CONSTEXPR typename enable_if< \
call_traits<R, void(BOOST_ASIO_VARIADIC_TARGS(n))>::overload == call_free, \
typename call_traits<R, void(BOOST_ASIO_VARIADIC_TARGS(n))>::result_type \
>::type \
operator()(R&& r, BOOST_ASIO_VARIADIC_MOVE_PARAMS(n)) const \
BOOST_ASIO_NOEXCEPT_IF(( \
call_traits<R, void(BOOST_ASIO_VARIADIC_TARGS(n))>::is_noexcept)) \
{ \
return set_value(BOOST_ASIO_MOVE_CAST(R)(r), \
BOOST_ASIO_VARIADIC_MOVE_ARGS(n)); \
} \
/**/
BOOST_ASIO_VARIADIC_GENERATE(BOOST_ASIO_PRIVATE_SET_VALUE_CALL_DEF)
#undef BOOST_ASIO_PRIVATE_SET_VALUE_CALL_DEF
#endif // defined(BOOST_ASIO_HAS_VARIADIC_TEMPLATES)
#else // defined(BOOST_ASIO_HAS_MOVE)
#if defined(BOOST_ASIO_HAS_VARIADIC_TEMPLATES)
template <typename R, typename... Vs>
BOOST_ASIO_CONSTEXPR typename enable_if<
call_traits<R&, void(const Vs&...)>::overload == call_member,
typename call_traits<R&, void(const Vs&...)>::result_type
>::type
operator()(R& r, const Vs&... v) const
BOOST_ASIO_NOEXCEPT_IF((
call_traits<R&, void(const Vs&...)>::is_noexcept))
{
return r.set_value(v...);
}
template <typename R, typename... Vs>
BOOST_ASIO_CONSTEXPR typename enable_if<
call_traits<const R&, void(const Vs&...)>::overload == call_member,
typename call_traits<const R&, void(const Vs&...)>::result_type
>::type
operator()(const R& r, const Vs&... v) const
BOOST_ASIO_NOEXCEPT_IF((
call_traits<const R&, void(const Vs&...)>::is_noexcept))
{
return r.set_value(v...);
}
template <typename R, typename... Vs>
BOOST_ASIO_CONSTEXPR typename enable_if<
call_traits<R&, void(const Vs&...)>::overload == call_free,
typename call_traits<R&, void(const Vs&...)>::result_type
>::type
operator()(R& r, const Vs&... v) const
BOOST_ASIO_NOEXCEPT_IF((
call_traits<R&, void(const Vs&...)>::is_noexcept))
{
return set_value(r, v...);
}
template <typename R, typename... Vs>
BOOST_ASIO_CONSTEXPR typename enable_if<
call_traits<const R&, void(const Vs&...)>::overload == call_free,
typename call_traits<const R&, void(const Vs&...)>::result_type
>::type
operator()(const R& r, const Vs&... v) const
BOOST_ASIO_NOEXCEPT_IF((
call_traits<const R&, void(const Vs&...)>::is_noexcept))
{
return set_value(r, v...);
}
#else // defined(BOOST_ASIO_HAS_VARIADIC_TEMPLATES)
template <typename R>
BOOST_ASIO_CONSTEXPR typename enable_if<
call_traits<R&, void()>::overload == call_member,
typename call_traits<R&, void()>::result_type
>::type
operator()(R& r) const
BOOST_ASIO_NOEXCEPT_IF((
call_traits<R&, void()>::is_noexcept))
{
return r.set_value();
}
template <typename R>
BOOST_ASIO_CONSTEXPR typename enable_if<
call_traits<const R&, void()>::overload == call_member,
typename call_traits<const R&, void()>::result_type
>::type
operator()(const R& r) const
BOOST_ASIO_NOEXCEPT_IF((
call_traits<const R&, void()>::is_noexcept))
{
return r.set_value();
}
template <typename R>
BOOST_ASIO_CONSTEXPR typename enable_if<
call_traits<R&, void()>::overload == call_free,
typename call_traits<R&, void()>::result_type
>::type
operator()(R& r) const
BOOST_ASIO_NOEXCEPT_IF((
call_traits<R&, void()>::is_noexcept))
{
return set_value(r);
}
template <typename R>
BOOST_ASIO_CONSTEXPR typename enable_if<
call_traits<const R&, void()>::overload == call_free,
typename call_traits<const R&, void()>::result_type
>::type
operator()(const R& r) const
BOOST_ASIO_NOEXCEPT_IF((
call_traits<const R&, void()>::is_noexcept))
{
return set_value(r);
}
#define BOOST_ASIO_PRIVATE_SET_VALUE_CALL_DEF(n) \
template <typename R, BOOST_ASIO_VARIADIC_TPARAMS(n)> \
BOOST_ASIO_CONSTEXPR typename enable_if< \
call_traits<R&, \
void(BOOST_ASIO_VARIADIC_TARGS(n))>::overload == call_member, \
typename call_traits<R&, void(BOOST_ASIO_VARIADIC_TARGS(n))>::result_type \
>::type \
operator()(R& r, BOOST_ASIO_VARIADIC_MOVE_PARAMS(n)) const \
BOOST_ASIO_NOEXCEPT_IF(( \
call_traits<R&, void(BOOST_ASIO_VARIADIC_TARGS(n))>::is_noexcept)) \
{ \
return r.set_value(BOOST_ASIO_VARIADIC_MOVE_ARGS(n)); \
} \
\
template <typename R, BOOST_ASIO_VARIADIC_TPARAMS(n)> \
BOOST_ASIO_CONSTEXPR typename enable_if< \
call_traits<const R&, \
void(BOOST_ASIO_VARIADIC_TARGS(n))>::overload == call_member, \
typename call_traits<const R&, \
void(BOOST_ASIO_VARIADIC_TARGS(n))>::result_type \
>::type \
operator()(const R& r, BOOST_ASIO_VARIADIC_MOVE_PARAMS(n)) const \
BOOST_ASIO_NOEXCEPT_IF(( \
call_traits<const R&, void(BOOST_ASIO_VARIADIC_TARGS(n))>::is_noexcept)) \
{ \
return r.set_value(BOOST_ASIO_VARIADIC_MOVE_ARGS(n)); \
} \
\
template <typename R, BOOST_ASIO_VARIADIC_TPARAMS(n)> \
BOOST_ASIO_CONSTEXPR typename enable_if< \
call_traits<R&, \
void(BOOST_ASIO_VARIADIC_TARGS(n))>::overload == call_free, \
typename call_traits<R&, void(BOOST_ASIO_VARIADIC_TARGS(n))>::result_type \
>::type \
operator()(R& r, BOOST_ASIO_VARIADIC_MOVE_PARAMS(n)) const \
BOOST_ASIO_NOEXCEPT_IF(( \
call_traits<R&, void(BOOST_ASIO_VARIADIC_TARGS(n))>::is_noexcept)) \
{ \
return set_value(r, BOOST_ASIO_VARIADIC_MOVE_ARGS(n)); \
} \
\
template <typename R, BOOST_ASIO_VARIADIC_TPARAMS(n)> \
BOOST_ASIO_CONSTEXPR typename enable_if< \
call_traits<const R&, \
void(BOOST_ASIO_VARIADIC_TARGS(n))>::overload == call_free, \
typename call_traits<const R&, \
void(BOOST_ASIO_VARIADIC_TARGS(n))>::result_type \
>::type \
operator()(const R& r, BOOST_ASIO_VARIADIC_MOVE_PARAMS(n)) const \
BOOST_ASIO_NOEXCEPT_IF(( \
call_traits<const R&, void(BOOST_ASIO_VARIADIC_TARGS(n))>::is_noexcept)) \
{ \
return set_value(r, BOOST_ASIO_VARIADIC_MOVE_ARGS(n)); \
} \
/**/
BOOST_ASIO_VARIADIC_GENERATE(BOOST_ASIO_PRIVATE_SET_VALUE_CALL_DEF)
#undef BOOST_ASIO_PRIVATE_SET_VALUE_CALL_DEF
#endif // defined(BOOST_ASIO_HAS_VARIADIC_TEMPLATES)
#endif // defined(BOOST_ASIO_HAS_MOVE)
};
template <typename T = impl>
struct static_instance
{
static const T instance;
};
template <typename T>
const T static_instance<T>::instance = {};
} // namespace asio_execution_set_value_fn
namespace boost {
namespace asio {
namespace execution {
namespace {
static BOOST_ASIO_CONSTEXPR const asio_execution_set_value_fn::impl&
set_value = asio_execution_set_value_fn::static_instance<>::instance;
} // namespace
#if defined(BOOST_ASIO_HAS_VARIADIC_TEMPLATES)
template <typename R, typename... Vs>
struct can_set_value :
integral_constant<bool,
asio_execution_set_value_fn::call_traits<R, void(Vs...)>::overload !=
asio_execution_set_value_fn::ill_formed>
{
};
#if defined(BOOST_ASIO_HAS_VARIABLE_TEMPLATES)
template <typename R, typename... Vs>
constexpr bool can_set_value_v = can_set_value<R, Vs...>::value;
#endif // defined(BOOST_ASIO_HAS_VARIABLE_TEMPLATES)
template <typename R, typename... Vs>
struct is_nothrow_set_value :
integral_constant<bool,
asio_execution_set_value_fn::call_traits<R, void(Vs...)>::is_noexcept>
{
};
#if defined(BOOST_ASIO_HAS_VARIABLE_TEMPLATES)
template <typename R, typename... Vs>
constexpr bool is_nothrow_set_value_v
= is_nothrow_set_value<R, Vs...>::value;
#endif // defined(BOOST_ASIO_HAS_VARIABLE_TEMPLATES)
#else // defined(BOOST_ASIO_HAS_VARIADIC_TEMPLATES)
template <typename R, typename = void,
typename = void, typename = void, typename = void, typename = void,
typename = void, typename = void, typename = void, typename = void>
struct can_set_value;
template <typename R, typename = void,
typename = void, typename = void, typename = void, typename = void,
typename = void, typename = void, typename = void, typename = void>
struct is_nothrow_set_value;
template <typename R>
struct can_set_value<R> :
integral_constant<bool,
asio_execution_set_value_fn::call_traits<R, void()>::overload !=
asio_execution_set_value_fn::ill_formed>
{
};
template <typename R>
struct is_nothrow_set_value<R> :
integral_constant<bool,
asio_execution_set_value_fn::call_traits<R, void()>::is_noexcept>
{
};
#define BOOST_ASIO_PRIVATE_SET_VALUE_TRAITS_DEF(n) \
template <typename R, BOOST_ASIO_VARIADIC_TPARAMS(n)> \
struct can_set_value<R, BOOST_ASIO_VARIADIC_TARGS(n)> : \
integral_constant<bool, \
asio_execution_set_value_fn::call_traits<R, \
void(BOOST_ASIO_VARIADIC_TARGS(n))>::overload != \
asio_execution_set_value_fn::ill_formed> \
{ \
}; \
\
template <typename R, BOOST_ASIO_VARIADIC_TPARAMS(n)> \
struct is_nothrow_set_value<R, BOOST_ASIO_VARIADIC_TARGS(n)> : \
integral_constant<bool, \
asio_execution_set_value_fn::call_traits<R, \
void(BOOST_ASIO_VARIADIC_TARGS(n))>::is_noexcept> \
{ \
}; \
/**/
BOOST_ASIO_VARIADIC_GENERATE(BOOST_ASIO_PRIVATE_SET_VALUE_TRAITS_DEF)
#undef BOOST_ASIO_PRIVATE_SET_VALUE_TRAITS_DEF
#endif // defined(BOOST_ASIO_HAS_VARIADIC_TEMPLATES)
} // namespace execution
} // namespace asio
} // namespace boost
#endif // defined(GENERATING_DOCUMENTATION)
#include <boost/asio/detail/pop_options.hpp>
#endif // BOOST_ASIO_EXECUTION_SET_VALUE_HPP
| 31.130346 | 80 | 0.712529 | [
"object"
] |
a1b8125121f37e61f1775274dfee38d49bb5625a | 80,788 | cpp | C++ | src/qt/qtbase/src/corelib/kernel/qmetaobjectbuilder.cpp | zwollerob/PhantomJS_AMR6VL | 71c126e98a8c32950158d04d0bd75823cd008b99 | [
"BSD-3-Clause"
] | null | null | null | src/qt/qtbase/src/corelib/kernel/qmetaobjectbuilder.cpp | zwollerob/PhantomJS_AMR6VL | 71c126e98a8c32950158d04d0bd75823cd008b99 | [
"BSD-3-Clause"
] | null | null | null | src/qt/qtbase/src/corelib/kernel/qmetaobjectbuilder.cpp | zwollerob/PhantomJS_AMR6VL | 71c126e98a8c32950158d04d0bd75823cd008b99 | [
"BSD-3-Clause"
] | null | null | null | /****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the QtCore module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** As a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qmetaobjectbuilder_p.h"
#include "qobject_p.h"
#include "qmetaobject_p.h"
#include <stdlib.h>
QT_BEGIN_NAMESPACE
/*!
\class QMetaObjectBuilder
\inmodule QtCore
\internal
\brief The QMetaObjectBuilder class supports building QMetaObject objects at runtime.
*/
/*!
\enum QMetaObjectBuilder::AddMember
This enum defines which members of QMetaObject should be copied by QMetaObjectBuilder::addMetaObject()
\value ClassName Add the class name.
\value SuperClass Add the super class.
\value Methods Add methods that aren't signals or slots.
\value Signals Add signals.
\value Slots Add slots.
\value Constructors Add constructors.
\value Properties Add properties.
\value Enumerators Add enumerators.
\value ClassInfos Add items of class information.
\value RelatedMetaObjects Add related meta objects.
\value StaticMetacall Add the static metacall function.
\value PublicMethods Add public methods (ignored for signals).
\value ProtectedMethods Add protected methods (ignored for signals).
\value PrivateMethods All private methods (ignored for signals).
\value AllMembers Add all members.
\value AllPrimaryMembers Add everything except the class name, super class, and static metacall function.
*/
// copied from moc's generator.cpp
namespace QtPrivate {
Q_CORE_EXPORT bool isBuiltinType(const QByteArray &type)
{
int id = QMetaType::type(type);
if (!id && !type.isEmpty() && type != "void")
return false;
return (id < QMetaType::User);
}
} // namespace QtPrivate
// copied from qmetaobject.cpp
static inline Q_DECL_UNUSED const QMetaObjectPrivate *priv(const uint* data)
{ return reinterpret_cast<const QMetaObjectPrivate*>(data); }
class QMetaMethodBuilderPrivate
{
public:
QMetaMethodBuilderPrivate
(QMetaMethod::MethodType _methodType,
const QByteArray& _signature,
const QByteArray& _returnType = QByteArray("void"),
QMetaMethod::Access _access = QMetaMethod::Public,
int _revision = 0)
: signature(QMetaObject::normalizedSignature(_signature.constData())),
returnType(QMetaObject::normalizedType(_returnType)),
attributes(((int)_access) | (((int)_methodType) << 2)),
revision(_revision)
{
Q_ASSERT((_methodType == QMetaMethod::Constructor) == returnType.isNull());
}
QByteArray signature;
QByteArray returnType;
QList<QByteArray> parameterNames;
QByteArray tag;
int attributes;
int revision;
QMetaMethod::MethodType methodType() const
{
return (QMetaMethod::MethodType)((attributes & MethodTypeMask) >> 2);
}
QMetaMethod::Access access() const
{
return (QMetaMethod::Access)(attributes & AccessMask);
}
void setAccess(QMetaMethod::Access value)
{
attributes = ((attributes & ~AccessMask) | (int)value);
}
QList<QByteArray> parameterTypes() const
{
return QMetaObjectPrivate::parameterTypeNamesFromSignature(signature);
}
int parameterCount() const
{
return parameterTypes().size();
}
QByteArray name() const
{
return signature.left(qMax(signature.indexOf('('), 0));
}
};
class QMetaPropertyBuilderPrivate
{
public:
QMetaPropertyBuilderPrivate
(const QByteArray& _name, const QByteArray& _type, int notifierIdx=-1,
int _revision = 0)
: name(_name),
type(QMetaObject::normalizedType(_type.constData())),
flags(Readable | Writable | Scriptable), notifySignal(-1),
revision(_revision)
{
if (notifierIdx >= 0) {
flags |= Notify;
notifySignal = notifierIdx;
}
}
QByteArray name;
QByteArray type;
int flags;
int notifySignal;
int revision;
bool flag(int f) const
{
return ((flags & f) != 0);
}
void setFlag(int f, bool value)
{
if (value)
flags |= f;
else
flags &= ~f;
}
};
class QMetaEnumBuilderPrivate
{
public:
QMetaEnumBuilderPrivate(const QByteArray& _name)
: name(_name), isFlag(false)
{
}
QByteArray name;
bool isFlag;
QList<QByteArray> keys;
QList<int> values;
};
class QMetaObjectBuilderPrivate
{
public:
QMetaObjectBuilderPrivate()
: flags(0)
{
superClass = &QObject::staticMetaObject;
staticMetacallFunction = 0;
}
bool hasRevisionedProperties() const;
bool hasRevisionedMethods() const;
QByteArray className;
const QMetaObject *superClass;
QMetaObjectBuilder::StaticMetacallFunction staticMetacallFunction;
QList<QMetaMethodBuilderPrivate> methods;
QList<QMetaMethodBuilderPrivate> constructors;
QList<QMetaPropertyBuilderPrivate> properties;
QList<QByteArray> classInfoNames;
QList<QByteArray> classInfoValues;
QList<QMetaEnumBuilderPrivate> enumerators;
QList<const QMetaObject *> relatedMetaObjects;
int flags;
};
bool QMetaObjectBuilderPrivate::hasRevisionedProperties() const
{
for (int i = 0; i < properties.size(); ++i) {
if (properties.at(i).revision)
return true;
}
return false;
}
bool QMetaObjectBuilderPrivate::hasRevisionedMethods() const
{
for (int i = 0; i < methods.size(); ++i) {
if (methods.at(i).revision)
return true;
}
return false;
}
/*!
Constructs a new QMetaObjectBuilder.
*/
QMetaObjectBuilder::QMetaObjectBuilder()
{
d = new QMetaObjectBuilderPrivate();
}
/*!
Constructs a new QMetaObjectBuilder which is a copy of the
meta object information in \a prototype. Note: the super class
contents for \a prototype are not copied, only the immediate
class that is defined by \a prototype.
The \a members parameter indicates which members of \a prototype
should be added. The default is AllMembers.
\sa addMetaObject()
*/
QMetaObjectBuilder::QMetaObjectBuilder
(const QMetaObject *prototype, QMetaObjectBuilder::AddMembers members)
{
d = new QMetaObjectBuilderPrivate();
addMetaObject(prototype, members);
}
/*!
Destroys this meta object builder.
*/
QMetaObjectBuilder::~QMetaObjectBuilder()
{
delete d;
}
/*!
Returns the name of the class being constructed by this
meta object builder. The default value is an empty QByteArray.
\sa setClassName(), superClass()
*/
QByteArray QMetaObjectBuilder::className() const
{
return d->className;
}
/*!
Sets the \a name of the class being constructed by this
meta object builder.
\sa className(), setSuperClass()
*/
void QMetaObjectBuilder::setClassName(const QByteArray& name)
{
d->className = name;
}
/*!
Returns the superclass meta object of the class being constructed
by this meta object builder. The default value is the meta object
for QObject.
\sa setSuperClass(), className()
*/
const QMetaObject *QMetaObjectBuilder::superClass() const
{
return d->superClass;
}
/*!
Sets the superclass meta object of the class being constructed
by this meta object builder to \a meta. The \a meta parameter
must not be null.
\sa superClass(), setClassName()
*/
void QMetaObjectBuilder::setSuperClass(const QMetaObject *meta)
{
Q_ASSERT(meta);
d->superClass = meta;
}
/*!
Returns the flags of the class being constructed by this meta object
builder.
\sa setFlags()
*/
QMetaObjectBuilder::MetaObjectFlags QMetaObjectBuilder::flags() const
{
return (QMetaObjectBuilder::MetaObjectFlags)d->flags;
}
/*!
Sets the \a flags of the class being constructed by this meta object
builder.
\sa flags()
*/
void QMetaObjectBuilder::setFlags(MetaObjectFlags flags)
{
d->flags = flags;
}
/*!
Returns the number of methods in this class, excluding the number
of methods in the base class. These include signals and slots
as well as normal member functions.
\sa addMethod(), method(), removeMethod(), indexOfMethod()
*/
int QMetaObjectBuilder::methodCount() const
{
return d->methods.size();
}
/*!
Returns the number of constructors in this class.
\sa addConstructor(), constructor(), removeConstructor(), indexOfConstructor()
*/
int QMetaObjectBuilder::constructorCount() const
{
return d->constructors.size();
}
/*!
Returns the number of properties in this class, excluding the number
of properties in the base class.
\sa addProperty(), property(), removeProperty(), indexOfProperty()
*/
int QMetaObjectBuilder::propertyCount() const
{
return d->properties.size();
}
/*!
Returns the number of enumerators in this class, excluding the
number of enumerators in the base class.
\sa addEnumerator(), enumerator(), removeEnumerator()
\sa indexOfEnumerator()
*/
int QMetaObjectBuilder::enumeratorCount() const
{
return d->enumerators.size();
}
/*!
Returns the number of items of class information in this class,
exclusing the number of items of class information in the base class.
\sa addClassInfo(), classInfoName(), classInfoValue(), removeClassInfo()
\sa indexOfClassInfo()
*/
int QMetaObjectBuilder::classInfoCount() const
{
return d->classInfoNames.size();
}
/*!
Returns the number of related meta objects that are associated
with this class.
Related meta objects are used when resolving the enumerated type
associated with a property, where the enumerated type is in a
different class from the property.
\sa addRelatedMetaObject(), relatedMetaObject()
\sa removeRelatedMetaObject()
*/
int QMetaObjectBuilder::relatedMetaObjectCount() const
{
return d->relatedMetaObjects.size();
}
/*!
Adds a new public method to this class with the specified \a signature.
Returns an object that can be used to adjust the other attributes
of the method. The \a signature will be normalized before it is
added to the class.
\sa method(), methodCount(), removeMethod(), indexOfMethod()
*/
QMetaMethodBuilder QMetaObjectBuilder::addMethod(const QByteArray& signature)
{
int index = d->methods.size();
d->methods.append(QMetaMethodBuilderPrivate(QMetaMethod::Method, signature));
return QMetaMethodBuilder(this, index);
}
/*!
Adds a new public method to this class with the specified
\a signature and \a returnType. Returns an object that can be
used to adjust the other attributes of the method. The \a signature
and \a returnType will be normalized before they are added to
the class.
\sa method(), methodCount(), removeMethod(), indexOfMethod()
*/
QMetaMethodBuilder QMetaObjectBuilder::addMethod
(const QByteArray& signature, const QByteArray& returnType)
{
int index = d->methods.size();
d->methods.append(QMetaMethodBuilderPrivate
(QMetaMethod::Method, signature, returnType));
return QMetaMethodBuilder(this, index);
}
/*!
Adds a new public method to this class that has the same information as
\a prototype. This is used to clone the methods of an existing
QMetaObject. Returns an object that can be used to adjust the
attributes of the method.
This function will detect if \a prototype is an ordinary method,
signal, slot, or constructor and act accordingly.
\sa method(), methodCount(), removeMethod(), indexOfMethod()
*/
QMetaMethodBuilder QMetaObjectBuilder::addMethod(const QMetaMethod& prototype)
{
QMetaMethodBuilder method;
if (prototype.methodType() == QMetaMethod::Method)
method = addMethod(prototype.methodSignature());
else if (prototype.methodType() == QMetaMethod::Signal)
method = addSignal(prototype.methodSignature());
else if (prototype.methodType() == QMetaMethod::Slot)
method = addSlot(prototype.methodSignature());
else if (prototype.methodType() == QMetaMethod::Constructor)
method = addConstructor(prototype.methodSignature());
method.setReturnType(prototype.typeName());
method.setParameterNames(prototype.parameterNames());
method.setTag(prototype.tag());
method.setAccess(prototype.access());
method.setAttributes(prototype.attributes());
method.setRevision(prototype.revision());
return method;
}
/*!
Adds a new public slot to this class with the specified \a signature.
Returns an object that can be used to adjust the other attributes
of the slot. The \a signature will be normalized before it is
added to the class.
\sa addMethod(), addSignal(), indexOfSlot()
*/
QMetaMethodBuilder QMetaObjectBuilder::addSlot(const QByteArray& signature)
{
int index = d->methods.size();
d->methods.append(QMetaMethodBuilderPrivate(QMetaMethod::Slot, signature));
return QMetaMethodBuilder(this, index);
}
/*!
Adds a new signal to this class with the specified \a signature.
Returns an object that can be used to adjust the other attributes
of the signal. The \a signature will be normalized before it is
added to the class.
\sa addMethod(), addSlot(), indexOfSignal()
*/
QMetaMethodBuilder QMetaObjectBuilder::addSignal(const QByteArray& signature)
{
int index = d->methods.size();
d->methods.append(QMetaMethodBuilderPrivate
(QMetaMethod::Signal, signature, QByteArray("void"), QMetaMethod::Public));
return QMetaMethodBuilder(this, index);
}
/*!
Adds a new constructor to this class with the specified \a signature.
Returns an object that can be used to adjust the other attributes
of the constructor. The \a signature will be normalized before it is
added to the class.
\sa constructor(), constructorCount(), removeConstructor()
\sa indexOfConstructor()
*/
QMetaMethodBuilder QMetaObjectBuilder::addConstructor(const QByteArray& signature)
{
int index = d->constructors.size();
d->constructors.append(QMetaMethodBuilderPrivate(QMetaMethod::Constructor, signature,
/*returnType=*/QByteArray()));
return QMetaMethodBuilder(this, -(index + 1));
}
/*!
Adds a new constructor to this class that has the same information as
\a prototype. This is used to clone the constructors of an existing
QMetaObject. Returns an object that can be used to adjust the
attributes of the constructor.
This function requires that \a prototype be a constructor.
\sa constructor(), constructorCount(), removeConstructor()
\sa indexOfConstructor()
*/
QMetaMethodBuilder QMetaObjectBuilder::addConstructor(const QMetaMethod& prototype)
{
Q_ASSERT(prototype.methodType() == QMetaMethod::Constructor);
QMetaMethodBuilder ctor = addConstructor(prototype.methodSignature());
ctor.setReturnType(prototype.typeName());
ctor.setParameterNames(prototype.parameterNames());
ctor.setTag(prototype.tag());
ctor.setAccess(prototype.access());
ctor.setAttributes(prototype.attributes());
return ctor;
}
/*!
Adds a new readable/writable property to this class with the
specified \a name and \a type. Returns an object that can be used
to adjust the other attributes of the property. The \a type will
be normalized before it is added to the class. \a notifierId will
be registered as the property's \e notify signal.
\sa property(), propertyCount(), removeProperty(), indexOfProperty()
*/
QMetaPropertyBuilder QMetaObjectBuilder::addProperty
(const QByteArray& name, const QByteArray& type, int notifierId)
{
int index = d->properties.size();
d->properties.append(QMetaPropertyBuilderPrivate(name, type, notifierId));
return QMetaPropertyBuilder(this, index);
}
/*!
Adds a new property to this class that has the same information as
\a prototype. This is used to clone the properties of an existing
QMetaObject. Returns an object that can be used to adjust the
attributes of the property.
\sa property(), propertyCount(), removeProperty(), indexOfProperty()
*/
QMetaPropertyBuilder QMetaObjectBuilder::addProperty(const QMetaProperty& prototype)
{
QMetaPropertyBuilder property = addProperty(prototype.name(), prototype.typeName());
property.setReadable(prototype.isReadable());
property.setWritable(prototype.isWritable());
property.setResettable(prototype.isResettable());
property.setDesignable(prototype.isDesignable());
property.setScriptable(prototype.isScriptable());
property.setStored(prototype.isStored());
property.setEditable(prototype.isEditable());
property.setUser(prototype.isUser());
property.setStdCppSet(prototype.hasStdCppSet());
property.setEnumOrFlag(prototype.isEnumType());
property.setConstant(prototype.isConstant());
property.setFinal(prototype.isFinal());
property.setRevision(prototype.revision());
if (prototype.hasNotifySignal()) {
// Find an existing method for the notify signal, or add a new one.
QMetaMethod method = prototype.notifySignal();
int index = indexOfMethod(method.methodSignature());
if (index == -1)
index = addMethod(method).index();
d->properties[property._index].notifySignal = index;
d->properties[property._index].setFlag(Notify, true);
}
return property;
}
/*!
Adds a new enumerator to this class with the specified
\a name. Returns an object that can be used to adjust
the other attributes of the enumerator.
\sa enumerator(), enumeratorCount(), removeEnumerator()
\sa indexOfEnumerator()
*/
QMetaEnumBuilder QMetaObjectBuilder::addEnumerator(const QByteArray& name)
{
int index = d->enumerators.size();
d->enumerators.append(QMetaEnumBuilderPrivate(name));
return QMetaEnumBuilder(this, index);
}
/*!
Adds a new enumerator to this class that has the same information as
\a prototype. This is used to clone the enumerators of an existing
QMetaObject. Returns an object that can be used to adjust the
attributes of the enumerator.
\sa enumerator(), enumeratorCount(), removeEnumerator()
\sa indexOfEnumerator()
*/
QMetaEnumBuilder QMetaObjectBuilder::addEnumerator(const QMetaEnum& prototype)
{
QMetaEnumBuilder en = addEnumerator(prototype.name());
en.setIsFlag(prototype.isFlag());
int count = prototype.keyCount();
for (int index = 0; index < count; ++index)
en.addKey(prototype.key(index), prototype.value(index));
return en;
}
/*!
Adds \a name and \a value as an item of class information to this class.
Returns the index of the new item of class information.
\sa classInfoCount(), classInfoName(), classInfoValue(), removeClassInfo()
\sa indexOfClassInfo()
*/
int QMetaObjectBuilder::addClassInfo(const QByteArray& name, const QByteArray& value)
{
int index = d->classInfoNames.size();
d->classInfoNames += name;
d->classInfoValues += value;
return index;
}
/*!
Adds \a meta to this class as a related meta object. Returns
the index of the new related meta object entry.
Related meta objects are used when resolving the enumerated type
associated with a property, where the enumerated type is in a
different class from the property.
\sa relatedMetaObjectCount(), relatedMetaObject()
\sa removeRelatedMetaObject()
*/
int QMetaObjectBuilder::addRelatedMetaObject(const QMetaObject *meta)
{
Q_ASSERT(meta);
int index = d->relatedMetaObjects.size();
d->relatedMetaObjects.append(meta);
return index;
}
/*!
Adds the contents of \a prototype to this meta object builder.
This function is useful for cloning the contents of an existing QMetaObject.
The \a members parameter indicates which members of \a prototype
should be added. The default is AllMembers.
*/
void QMetaObjectBuilder::addMetaObject
(const QMetaObject *prototype, QMetaObjectBuilder::AddMembers members)
{
Q_ASSERT(prototype);
int index;
if ((members & ClassName) != 0)
d->className = prototype->className();
if ((members & SuperClass) != 0)
d->superClass = prototype->superClass();
if ((members & (Methods | Signals | Slots)) != 0) {
for (index = prototype->methodOffset(); index < prototype->methodCount(); ++index) {
QMetaMethod method = prototype->method(index);
if (method.methodType() != QMetaMethod::Signal) {
if (method.access() == QMetaMethod::Public && (members & PublicMethods) == 0)
continue;
if (method.access() == QMetaMethod::Private && (members & PrivateMethods) == 0)
continue;
if (method.access() == QMetaMethod::Protected && (members & ProtectedMethods) == 0)
continue;
}
if (method.methodType() == QMetaMethod::Method && (members & Methods) != 0) {
addMethod(method);
} else if (method.methodType() == QMetaMethod::Signal &&
(members & Signals) != 0) {
addMethod(method);
} else if (method.methodType() == QMetaMethod::Slot &&
(members & Slots) != 0) {
addMethod(method);
}
}
}
if ((members & Constructors) != 0) {
for (index = 0; index < prototype->constructorCount(); ++index)
addConstructor(prototype->constructor(index));
}
if ((members & Properties) != 0) {
for (index = prototype->propertyOffset(); index < prototype->propertyCount(); ++index)
addProperty(prototype->property(index));
}
if ((members & Enumerators) != 0) {
for (index = prototype->enumeratorOffset(); index < prototype->enumeratorCount(); ++index)
addEnumerator(prototype->enumerator(index));
}
if ((members & ClassInfos) != 0) {
for (index = prototype->classInfoOffset(); index < prototype->classInfoCount(); ++index) {
QMetaClassInfo ci = prototype->classInfo(index);
addClassInfo(ci.name(), ci.value());
}
}
if ((members & RelatedMetaObjects) != 0) {
Q_ASSERT(priv(prototype->d.data)->revision >= 2);
const QMetaObject * const *objects = prototype->d.relatedMetaObjects;
if (objects) {
while (*objects != 0) {
addRelatedMetaObject(*objects);
++objects;
}
}
}
if ((members & StaticMetacall) != 0) {
Q_ASSERT(priv(prototype->d.data)->revision >= 6);
if (prototype->d.static_metacall)
setStaticMetacallFunction(prototype->d.static_metacall);
}
}
/*!
Returns the method at \a index in this class.
\sa methodCount(), addMethod(), removeMethod(), indexOfMethod()
*/
QMetaMethodBuilder QMetaObjectBuilder::method(int index) const
{
if (index >= 0 && index < d->methods.size())
return QMetaMethodBuilder(this, index);
else
return QMetaMethodBuilder();
}
/*!
Returns the constructor at \a index in this class.
\sa methodCount(), addMethod(), removeMethod(), indexOfConstructor()
*/
QMetaMethodBuilder QMetaObjectBuilder::constructor(int index) const
{
if (index >= 0 && index < d->constructors.size())
return QMetaMethodBuilder(this, -(index + 1));
else
return QMetaMethodBuilder();
}
/*!
Returns the property at \a index in this class.
\sa methodCount(), addMethod(), removeMethod(), indexOfProperty()
*/
QMetaPropertyBuilder QMetaObjectBuilder::property(int index) const
{
if (index >= 0 && index < d->properties.size())
return QMetaPropertyBuilder(this, index);
else
return QMetaPropertyBuilder();
}
/*!
Returns the enumerator at \a index in this class.
\sa enumeratorCount(), addEnumerator(), removeEnumerator()
\sa indexOfEnumerator()
*/
QMetaEnumBuilder QMetaObjectBuilder::enumerator(int index) const
{
if (index >= 0 && index < d->enumerators.size())
return QMetaEnumBuilder(this, index);
else
return QMetaEnumBuilder();
}
/*!
Returns the related meta object at \a index in this class.
Related meta objects are used when resolving the enumerated type
associated with a property, where the enumerated type is in a
different class from the property.
\sa relatedMetaObjectCount(), addRelatedMetaObject()
\sa removeRelatedMetaObject()
*/
const QMetaObject *QMetaObjectBuilder::relatedMetaObject(int index) const
{
if (index >= 0 && index < d->relatedMetaObjects.size())
return d->relatedMetaObjects[index];
else
return 0;
}
/*!
Returns the name of the item of class information at \a index
in this class.
\sa classInfoCount(), addClassInfo(), classInfoValue(), removeClassInfo()
\sa indexOfClassInfo()
*/
QByteArray QMetaObjectBuilder::classInfoName(int index) const
{
if (index >= 0 && index < d->classInfoNames.size())
return d->classInfoNames[index];
else
return QByteArray();
}
/*!
Returns the value of the item of class information at \a index
in this class.
\sa classInfoCount(), addClassInfo(), classInfoName(), removeClassInfo()
\sa indexOfClassInfo()
*/
QByteArray QMetaObjectBuilder::classInfoValue(int index) const
{
if (index >= 0 && index < d->classInfoValues.size())
return d->classInfoValues[index];
else
return QByteArray();
}
/*!
Removes the method at \a index from this class. The indices of
all following methods will be adjusted downwards by 1. If the
method is registered as a notify signal on a property, then the
notify signal will be removed from the property.
\sa methodCount(), addMethod(), method(), indexOfMethod()
*/
void QMetaObjectBuilder::removeMethod(int index)
{
if (index >= 0 && index < d->methods.size()) {
d->methods.removeAt(index);
for (int prop = 0; prop < d->properties.size(); ++prop) {
// Adjust the indices of property notify signal references.
if (d->properties[prop].notifySignal == index) {
d->properties[prop].notifySignal = -1;
d->properties[prop].setFlag(Notify, false);
} else if (d->properties[prop].notifySignal > index)
(d->properties[prop].notifySignal)--;
}
}
}
/*!
Removes the constructor at \a index from this class. The indices of
all following constructors will be adjusted downwards by 1.
\sa constructorCount(), addConstructor(), constructor()
\sa indexOfConstructor()
*/
void QMetaObjectBuilder::removeConstructor(int index)
{
if (index >= 0 && index < d->constructors.size())
d->constructors.removeAt(index);
}
/*!
Removes the property at \a index from this class. The indices of
all following properties will be adjusted downwards by 1.
\sa propertyCount(), addProperty(), property(), indexOfProperty()
*/
void QMetaObjectBuilder::removeProperty(int index)
{
if (index >= 0 && index < d->properties.size())
d->properties.removeAt(index);
}
/*!
Removes the enumerator at \a index from this class. The indices of
all following enumerators will be adjusted downwards by 1.
\sa enumertorCount(), addEnumerator(), enumerator()
\sa indexOfEnumerator()
*/
void QMetaObjectBuilder::removeEnumerator(int index)
{
if (index >= 0 && index < d->enumerators.size())
d->enumerators.removeAt(index);
}
/*!
Removes the item of class information at \a index from this class.
The indices of all following items will be adjusted downwards by 1.
\sa classInfoCount(), addClassInfo(), classInfoName(), classInfoValue()
\sa indexOfClassInfo()
*/
void QMetaObjectBuilder::removeClassInfo(int index)
{
if (index >= 0 && index < d->classInfoNames.size()) {
d->classInfoNames.removeAt(index);
d->classInfoValues.removeAt(index);
}
}
/*!
Removes the related meta object at \a index from this class.
The indices of all following related meta objects will be adjusted
downwards by 1.
Related meta objects are used when resolving the enumerated type
associated with a property, where the enumerated type is in a
different class from the property.
\sa relatedMetaObjectCount(), addRelatedMetaObject()
\sa relatedMetaObject()
*/
void QMetaObjectBuilder::removeRelatedMetaObject(int index)
{
if (index >= 0 && index < d->relatedMetaObjects.size())
d->relatedMetaObjects.removeAt(index);
}
/*!
Finds a method with the specified \a signature and returns its index;
otherwise returns -1. The \a signature will be normalized by this method.
\sa method(), methodCount(), addMethod(), removeMethod()
*/
int QMetaObjectBuilder::indexOfMethod(const QByteArray& signature)
{
QByteArray sig = QMetaObject::normalizedSignature(signature);
for (int index = 0; index < d->methods.size(); ++index) {
if (sig == d->methods[index].signature)
return index;
}
return -1;
}
/*!
Finds a signal with the specified \a signature and returns its index;
otherwise returns -1. The \a signature will be normalized by this method.
\sa indexOfMethod(), indexOfSlot()
*/
int QMetaObjectBuilder::indexOfSignal(const QByteArray& signature)
{
QByteArray sig = QMetaObject::normalizedSignature(signature);
for (int index = 0; index < d->methods.size(); ++index) {
if (sig == d->methods[index].signature &&
d->methods[index].methodType() == QMetaMethod::Signal)
return index;
}
return -1;
}
/*!
Finds a slot with the specified \a signature and returns its index;
otherwise returns -1. The \a signature will be normalized by this method.
\sa indexOfMethod(), indexOfSignal()
*/
int QMetaObjectBuilder::indexOfSlot(const QByteArray& signature)
{
QByteArray sig = QMetaObject::normalizedSignature(signature);
for (int index = 0; index < d->methods.size(); ++index) {
if (sig == d->methods[index].signature &&
d->methods[index].methodType() == QMetaMethod::Slot)
return index;
}
return -1;
}
/*!
Finds a constructor with the specified \a signature and returns its index;
otherwise returns -1. The \a signature will be normalized by this method.
\sa constructor(), constructorCount(), addConstructor(), removeConstructor()
*/
int QMetaObjectBuilder::indexOfConstructor(const QByteArray& signature)
{
QByteArray sig = QMetaObject::normalizedSignature(signature);
for (int index = 0; index < d->constructors.size(); ++index) {
if (sig == d->constructors[index].signature)
return index;
}
return -1;
}
/*!
Finds a property with the specified \a name and returns its index;
otherwise returns -1.
\sa property(), propertyCount(), addProperty(), removeProperty()
*/
int QMetaObjectBuilder::indexOfProperty(const QByteArray& name)
{
for (int index = 0; index < d->properties.size(); ++index) {
if (name == d->properties[index].name)
return index;
}
return -1;
}
/*!
Finds an enumerator with the specified \a name and returns its index;
otherwise returns -1.
\sa enumertor(), enumeratorCount(), addEnumerator(), removeEnumerator()
*/
int QMetaObjectBuilder::indexOfEnumerator(const QByteArray& name)
{
for (int index = 0; index < d->enumerators.size(); ++index) {
if (name == d->enumerators[index].name)
return index;
}
return -1;
}
/*!
Finds an item of class information with the specified \a name and
returns its index; otherwise returns -1.
\sa classInfoName(), classInfoValue(), classInfoCount(), addClassInfo()
\sa removeClassInfo()
*/
int QMetaObjectBuilder::indexOfClassInfo(const QByteArray& name)
{
for (int index = 0; index < d->classInfoNames.size(); ++index) {
if (name == d->classInfoNames[index])
return index;
}
return -1;
}
// Align on a specific type boundary.
#define ALIGN(size,type) \
(size) = ((size) + sizeof(type) - 1) & ~(sizeof(type) - 1)
/*!
\class QMetaStringTable
\inmodule QtCore
\internal
\brief The QMetaStringTable class can generate a meta-object string table at runtime.
*/
QMetaStringTable::QMetaStringTable(const QByteArray &className)
: m_index(0)
, m_className(className)
{
const int index = enter(m_className);
Q_ASSERT(index == 0);
Q_UNUSED(index);
}
// Enters the given value into the string table (if it hasn't already been
// entered). Returns the index of the string.
int QMetaStringTable::enter(const QByteArray &value)
{
Entries::iterator it = m_entries.find(value);
if (it != m_entries.end())
return it.value();
int pos = m_index;
m_entries.insert(value, pos);
++m_index;
return pos;
}
int QMetaStringTable::preferredAlignment()
{
return Q_ALIGNOF(QByteArrayData);
}
// Returns the size (in bytes) required for serializing this string table.
int QMetaStringTable::blobSize() const
{
int size = m_entries.size() * sizeof(QByteArrayData);
Entries::const_iterator it;
for (it = m_entries.constBegin(); it != m_entries.constEnd(); ++it)
size += it.key().size() + 1;
return size;
}
static void writeString(char *out, int i, const QByteArray &str,
const int offsetOfStringdataMember, int &stringdataOffset)
{
int size = str.size();
qptrdiff offset = offsetOfStringdataMember + stringdataOffset
- i * sizeof(QByteArrayData);
const QByteArrayData data =
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(size, offset);
memcpy(out + i * sizeof(QByteArrayData), &data, sizeof(QByteArrayData));
memcpy(out + offsetOfStringdataMember + stringdataOffset, str.constData(), size);
out[offsetOfStringdataMember + stringdataOffset + size] = '\0';
stringdataOffset += size + 1;
}
// Writes strings to string data struct.
// The struct consists of an array of QByteArrayData, followed by a char array
// containing the actual strings. This format must match the one produced by
// moc (see generator.cpp).
void QMetaStringTable::writeBlob(char *out) const
{
Q_ASSERT(!(reinterpret_cast<quintptr>(out) & (preferredAlignment()-1)));
int offsetOfStringdataMember = m_entries.size() * sizeof(QByteArrayData);
int stringdataOffset = 0;
// qt_metacast expects the first string in the string table to be the class name.
writeString(out, /*index*/0, m_className, offsetOfStringdataMember, stringdataOffset);
for (Entries::ConstIterator it = m_entries.constBegin(), end = m_entries.constEnd();
it != end; ++it) {
const int i = it.value();
if (i == 0)
continue;
const QByteArray &str = it.key();
writeString(out, i, str, offsetOfStringdataMember, stringdataOffset);
}
}
// Returns the sum of all parameters (including return type) for the given
// \a methods. This is needed for calculating the size of the methods'
// parameter type/name meta-data.
static int aggregateParameterCount(const QList<QMetaMethodBuilderPrivate> &methods)
{
int sum = 0;
for (int i = 0; i < methods.size(); ++i)
sum += methods.at(i).parameterCount() + 1; // +1 for return type
return sum;
}
// Build a QMetaObject in "buf" based on the information in "d".
// If "buf" is null, then return the number of bytes needed to
// build the QMetaObject. Returns -1 if the metaobject if
// relocatable is set, but the metaobject contains relatedMetaObjects.
static int buildMetaObject(QMetaObjectBuilderPrivate *d, char *buf,
int expectedSize, bool relocatable)
{
Q_UNUSED(expectedSize); // Avoid warning in release mode
int size = 0;
int dataIndex;
int paramsIndex;
int enumIndex;
int index;
bool hasRevisionedMethods = d->hasRevisionedMethods();
bool hasRevisionedProperties = d->hasRevisionedProperties();
bool hasNotifySignals = false;
if (relocatable &&
(d->relatedMetaObjects.size() > 0 || d->staticMetacallFunction))
return -1;
// Create the main QMetaObject structure at the start of the buffer.
QMetaObject *meta = reinterpret_cast<QMetaObject *>(buf);
size += sizeof(QMetaObject);
ALIGN(size, int);
if (buf) {
if (!relocatable) meta->d.superdata = d->superClass;
meta->d.relatedMetaObjects = 0;
meta->d.extradata = 0;
meta->d.static_metacall = d->staticMetacallFunction;
}
// Populate the QMetaObjectPrivate structure.
QMetaObjectPrivate *pmeta
= reinterpret_cast<QMetaObjectPrivate *>(buf + size);
int pmetaSize = size;
dataIndex = MetaObjectPrivateFieldCount;
for (index = 0; index < d->properties.size(); ++index) {
if (d->properties[index].notifySignal != -1) {
hasNotifySignals = true;
break;
}
}
int methodParametersDataSize =
((aggregateParameterCount(d->methods)
+ aggregateParameterCount(d->constructors)) * 2) // types and parameter names
- d->methods.size() // return "parameters" don't have names
- d->constructors.size(); // "this" parameters don't have names
if (buf) {
Q_STATIC_ASSERT_X(QMetaObjectPrivate::OutputRevision == 7, "QMetaObjectBuilder should generate the same version as moc");
pmeta->revision = QMetaObjectPrivate::OutputRevision;
pmeta->flags = d->flags;
pmeta->className = 0; // Class name is always the first string.
//pmeta->signalCount is handled in the "output method loop" as an optimization.
pmeta->classInfoCount = d->classInfoNames.size();
pmeta->classInfoData = dataIndex;
dataIndex += 2 * d->classInfoNames.size();
pmeta->methodCount = d->methods.size();
pmeta->methodData = dataIndex;
dataIndex += 5 * d->methods.size();
if (hasRevisionedMethods)
dataIndex += d->methods.size();
paramsIndex = dataIndex;
dataIndex += methodParametersDataSize;
pmeta->propertyCount = d->properties.size();
pmeta->propertyData = dataIndex;
dataIndex += 3 * d->properties.size();
if (hasNotifySignals)
dataIndex += d->properties.size();
if (hasRevisionedProperties)
dataIndex += d->properties.size();
pmeta->enumeratorCount = d->enumerators.size();
pmeta->enumeratorData = dataIndex;
dataIndex += 4 * d->enumerators.size();
pmeta->constructorCount = d->constructors.size();
pmeta->constructorData = dataIndex;
dataIndex += 5 * d->constructors.size();
} else {
dataIndex += 2 * d->classInfoNames.size();
dataIndex += 5 * d->methods.size();
if (hasRevisionedMethods)
dataIndex += d->methods.size();
paramsIndex = dataIndex;
dataIndex += methodParametersDataSize;
dataIndex += 3 * d->properties.size();
if (hasNotifySignals)
dataIndex += d->properties.size();
if (hasRevisionedProperties)
dataIndex += d->properties.size();
dataIndex += 4 * d->enumerators.size();
dataIndex += 5 * d->constructors.size();
}
// Allocate space for the enumerator key names and values.
enumIndex = dataIndex;
for (index = 0; index < d->enumerators.size(); ++index) {
QMetaEnumBuilderPrivate *enumerator = &(d->enumerators[index]);
dataIndex += 2 * enumerator->keys.size();
}
// Zero terminator at the end of the data offset table.
++dataIndex;
// Find the start of the data and string tables.
int *data = reinterpret_cast<int *>(pmeta);
size += dataIndex * sizeof(int);
ALIGN(size, void *);
char *str = reinterpret_cast<char *>(buf + size);
if (buf) {
if (relocatable) {
meta->d.stringdata = reinterpret_cast<const QByteArrayData *>((quintptr)size);
meta->d.data = reinterpret_cast<uint *>((quintptr)pmetaSize);
} else {
meta->d.stringdata = reinterpret_cast<const QByteArrayData *>(str);
meta->d.data = reinterpret_cast<uint *>(data);
}
}
// Reset the current data position to just past the QMetaObjectPrivate.
dataIndex = MetaObjectPrivateFieldCount;
QMetaStringTable strings(d->className);
// Output the class infos,
Q_ASSERT(!buf || dataIndex == pmeta->classInfoData);
for (index = 0; index < d->classInfoNames.size(); ++index) {
int name = strings.enter(d->classInfoNames[index]);
int value = strings.enter(d->classInfoValues[index]);
if (buf) {
data[dataIndex] = name;
data[dataIndex + 1] = value;
}
dataIndex += 2;
}
// Output the methods in the class.
Q_ASSERT(!buf || dataIndex == pmeta->methodData);
for (index = 0; index < d->methods.size(); ++index) {
QMetaMethodBuilderPrivate *method = &(d->methods[index]);
int name = strings.enter(method->name());
int argc = method->parameterCount();
int tag = strings.enter(method->tag);
int attrs = method->attributes;
if (buf) {
data[dataIndex] = name;
data[dataIndex + 1] = argc;
data[dataIndex + 2] = paramsIndex;
data[dataIndex + 3] = tag;
data[dataIndex + 4] = attrs;
if (method->methodType() == QMetaMethod::Signal)
pmeta->signalCount++;
}
dataIndex += 5;
paramsIndex += 1 + argc * 2;
}
if (hasRevisionedMethods) {
for (index = 0; index < d->methods.size(); ++index) {
QMetaMethodBuilderPrivate *method = &(d->methods[index]);
if (buf)
data[dataIndex] = method->revision;
++dataIndex;
}
}
// Output the method parameters in the class.
Q_ASSERT(!buf || dataIndex == pmeta->methodData + d->methods.size() * 5
+ (hasRevisionedMethods ? d->methods.size() : 0));
for (int x = 0; x < 2; ++x) {
QList<QMetaMethodBuilderPrivate> &methods = (x == 0) ? d->methods : d->constructors;
for (index = 0; index < methods.size(); ++index) {
QMetaMethodBuilderPrivate *method = &(methods[index]);
QList<QByteArray> paramTypeNames = method->parameterTypes();
int paramCount = paramTypeNames.size();
for (int i = -1; i < paramCount; ++i) {
const QByteArray &typeName = (i < 0) ? method->returnType : paramTypeNames.at(i);
int typeInfo;
if (QtPrivate::isBuiltinType(typeName))
typeInfo = QMetaType::type(typeName);
else
typeInfo = IsUnresolvedType | strings.enter(typeName);
if (buf)
data[dataIndex] = typeInfo;
++dataIndex;
}
QList<QByteArray> paramNames = method->parameterNames;
while (paramNames.size() < paramCount)
paramNames.append(QByteArray());
for (int i = 0; i < paramCount; ++i) {
int stringIndex = strings.enter(paramNames.at(i));
if (buf)
data[dataIndex] = stringIndex;
++dataIndex;
}
}
}
// Output the properties in the class.
Q_ASSERT(!buf || dataIndex == pmeta->propertyData);
for (index = 0; index < d->properties.size(); ++index) {
QMetaPropertyBuilderPrivate *prop = &(d->properties[index]);
int name = strings.enter(prop->name);
int typeInfo;
if (QtPrivate::isBuiltinType(prop->type))
typeInfo = QMetaType::type(prop->type);
else
typeInfo = IsUnresolvedType | strings.enter(prop->type);
int flags = prop->flags;
if (!QtPrivate::isBuiltinType(prop->type))
flags |= EnumOrFlag;
if (buf) {
data[dataIndex] = name;
data[dataIndex + 1] = typeInfo;
data[dataIndex + 2] = flags;
}
dataIndex += 3;
}
if (hasNotifySignals) {
for (index = 0; index < d->properties.size(); ++index) {
QMetaPropertyBuilderPrivate *prop = &(d->properties[index]);
if (buf) {
if (prop->notifySignal != -1)
data[dataIndex] = prop->notifySignal;
else
data[dataIndex] = 0;
}
++dataIndex;
}
}
if (hasRevisionedProperties) {
for (index = 0; index < d->properties.size(); ++index) {
QMetaPropertyBuilderPrivate *prop = &(d->properties[index]);
if (buf)
data[dataIndex] = prop->revision;
++dataIndex;
}
}
// Output the enumerators in the class.
Q_ASSERT(!buf || dataIndex == pmeta->enumeratorData);
for (index = 0; index < d->enumerators.size(); ++index) {
QMetaEnumBuilderPrivate *enumerator = &(d->enumerators[index]);
int name = strings.enter(enumerator->name);
int isFlag = (int)(enumerator->isFlag);
int count = enumerator->keys.size();
int enumOffset = enumIndex;
if (buf) {
data[dataIndex] = name;
data[dataIndex + 1] = isFlag;
data[dataIndex + 2] = count;
data[dataIndex + 3] = enumOffset;
}
for (int key = 0; key < count; ++key) {
int keyIndex = strings.enter(enumerator->keys[key]);
if (buf) {
data[enumOffset++] = keyIndex;
data[enumOffset++] = enumerator->values[key];
}
}
dataIndex += 4;
enumIndex += 2 * count;
}
// Output the constructors in the class.
Q_ASSERT(!buf || dataIndex == pmeta->constructorData);
for (index = 0; index < d->constructors.size(); ++index) {
QMetaMethodBuilderPrivate *method = &(d->constructors[index]);
int name = strings.enter(method->name());
int argc = method->parameterCount();
int tag = strings.enter(method->tag);
int attrs = method->attributes;
if (buf) {
data[dataIndex] = name;
data[dataIndex + 1] = argc;
data[dataIndex + 2] = paramsIndex;
data[dataIndex + 3] = tag;
data[dataIndex + 4] = attrs;
}
dataIndex += 5;
paramsIndex += 1 + argc * 2;
}
size += strings.blobSize();
if (buf)
strings.writeBlob(str);
// Output the zero terminator in the data array.
if (buf)
data[enumIndex] = 0;
// Create the relatedMetaObjects block if we need one.
if (d->relatedMetaObjects.size() > 0) {
ALIGN(size, QMetaObject *);
const QMetaObject **objects =
reinterpret_cast<const QMetaObject **>(buf + size);
if (buf) {
meta->d.relatedMetaObjects = objects;
for (index = 0; index < d->relatedMetaObjects.size(); ++index)
objects[index] = d->relatedMetaObjects[index];
objects[index] = 0;
}
size += sizeof(QMetaObject *) * (d->relatedMetaObjects.size() + 1);
}
// Align the final size and return it.
ALIGN(size, void *);
Q_ASSERT(!buf || size == expectedSize);
return size;
}
/*!
Converts this meta object builder into a concrete QMetaObject.
The return value should be deallocated using free() once it
is no longer needed.
The returned meta object is a snapshot of the state of the
QMetaObjectBuilder. Any further modifications to the QMetaObjectBuilder
will not be reflected in previous meta objects returned by
this method.
*/
QMetaObject *QMetaObjectBuilder::toMetaObject() const
{
int size = buildMetaObject(d, 0, 0, false);
char *buf = reinterpret_cast<char *>(malloc(size));
memset(buf, 0, size);
buildMetaObject(d, buf, size, false);
return reinterpret_cast<QMetaObject *>(buf);
}
/*
\internal
Converts this meta object builder into relocatable data. This data can
be stored, copied and later passed to fromRelocatableData() to create a
concrete QMetaObject.
The data is specific to the architecture on which it was created, but is not
specific to the process that created it. Not all meta object builder's can
be converted to data in this way. If \a ok is provided, it will be set to
true if the conversion succeeds, and false otherwise. If a
staticMetacallFunction() or any relatedMetaObject()'s are specified the
conversion to relocatable data will fail.
*/
QByteArray QMetaObjectBuilder::toRelocatableData(bool *ok) const
{
int size = buildMetaObject(d, 0, 0, true);
if (size == -1) {
if (ok) *ok = false;
return QByteArray();
}
QByteArray data;
data.resize(size);
char *buf = data.data();
memset(buf, 0, size);
buildMetaObject(d, buf, size, true);
if (ok) *ok = true;
return data;
}
/*
\internal
Sets the \a data returned from toRelocatableData() onto a concrete
QMetaObject instance, \a output. As the meta object's super class is not
saved in the relocatable data, it must be passed as \a superClass.
*/
void QMetaObjectBuilder::fromRelocatableData(QMetaObject *output,
const QMetaObject *superclass,
const QByteArray &data)
{
if (!output)
return;
const char *buf = data.constData();
const QMetaObject *dataMo = reinterpret_cast<const QMetaObject *>(buf);
quintptr stringdataOffset = (quintptr)dataMo->d.stringdata;
quintptr dataOffset = (quintptr)dataMo->d.data;
output->d.superdata = superclass;
output->d.stringdata = reinterpret_cast<const QByteArrayData *>(buf + stringdataOffset);
output->d.data = reinterpret_cast<const uint *>(buf + dataOffset);
output->d.extradata = 0;
output->d.relatedMetaObjects = 0;
output->d.static_metacall = 0;
}
/*!
\typedef QMetaObjectBuilder::StaticMetacallFunction
Typedef for static metacall functions. The three parameters are
the call type value, the constructor index, and the
array of parameters.
*/
/*!
Returns the static metacall function to use to construct objects
of this class. The default value is null.
\sa setStaticMetacallFunction()
*/
QMetaObjectBuilder::StaticMetacallFunction QMetaObjectBuilder::staticMetacallFunction() const
{
return d->staticMetacallFunction;
}
/*!
Sets the static metacall function to use to construct objects
of this class to \a value. The default value is null.
\sa staticMetacallFunction()
*/
void QMetaObjectBuilder::setStaticMetacallFunction
(QMetaObjectBuilder::StaticMetacallFunction value)
{
d->staticMetacallFunction = value;
}
#ifndef QT_NO_DATASTREAM
/*!
Serializes the contents of the meta object builder onto \a stream.
\sa deserialize()
*/
void QMetaObjectBuilder::serialize(QDataStream& stream) const
{
int index;
// Write the class and super class names.
stream << d->className;
if (d->superClass)
stream << QByteArray(d->superClass->className());
else
stream << QByteArray();
// Write the counts for each type of class member.
stream << d->classInfoNames.size();
stream << d->methods.size();
stream << d->properties.size();
stream << d->enumerators.size();
stream << d->constructors.size();
stream << d->relatedMetaObjects.size();
// Write the items of class information.
for (index = 0; index < d->classInfoNames.size(); ++index) {
stream << d->classInfoNames[index];
stream << d->classInfoValues[index];
}
// Write the methods.
for (index = 0; index < d->methods.size(); ++index) {
const QMetaMethodBuilderPrivate *method = &(d->methods[index]);
stream << method->signature;
stream << method->returnType;
stream << method->parameterNames;
stream << method->tag;
stream << method->attributes;
if (method->revision)
stream << method->revision;
}
// Write the properties.
for (index = 0; index < d->properties.size(); ++index) {
const QMetaPropertyBuilderPrivate *property = &(d->properties[index]);
stream << property->name;
stream << property->type;
stream << property->flags;
stream << property->notifySignal;
if (property->revision)
stream << property->revision;
}
// Write the enumerators.
for (index = 0; index < d->enumerators.size(); ++index) {
const QMetaEnumBuilderPrivate *enumerator = &(d->enumerators[index]);
stream << enumerator->name;
stream << enumerator->isFlag;
stream << enumerator->keys;
stream << enumerator->values;
}
// Write the constructors.
for (index = 0; index < d->constructors.size(); ++index) {
const QMetaMethodBuilderPrivate *method = &(d->constructors[index]);
stream << method->signature;
stream << method->returnType;
stream << method->parameterNames;
stream << method->tag;
stream << method->attributes;
}
// Write the related meta objects.
for (index = 0; index < d->relatedMetaObjects.size(); ++index) {
const QMetaObject *meta = d->relatedMetaObjects[index];
stream << QByteArray(meta->className());
}
// Add an extra empty QByteArray for additional data in future versions.
// This should help maintain backwards compatibility, allowing older
// versions to read newer data.
stream << QByteArray();
}
// Resolve a class name using the name reference map.
static const QMetaObject *resolveClassName
(const QMap<QByteArray, const QMetaObject *>& references,
const QByteArray& name)
{
if (name == QByteArray("QObject"))
return &QObject::staticMetaObject;
else
return references.value(name, 0);
}
/*!
Deserializes a meta object builder from \a stream into
this meta object builder.
The \a references parameter specifies a mapping from class names
to QMetaObject instances for resolving the super class name and
related meta objects in the object that is deserialized.
The meta object for QObject is implicitly added to \a references
and does not need to be supplied.
The QDataStream::status() value on \a stream will be set to
QDataStream::ReadCorruptData if the input data is corrupt.
The status will be set to QDataStream::ReadPastEnd if the
input was exhausted before the full meta object was read.
\sa serialize()
*/
void QMetaObjectBuilder::deserialize
(QDataStream& stream,
const QMap<QByteArray, const QMetaObject *>& references)
{
QByteArray name;
const QMetaObject *cl;
int index;
// Clear all members in the builder to their default states.
d->className.clear();
d->superClass = &QObject::staticMetaObject;
d->classInfoNames.clear();
d->classInfoValues.clear();
d->methods.clear();
d->properties.clear();
d->enumerators.clear();
d->constructors.clear();
d->relatedMetaObjects.clear();
d->staticMetacallFunction = 0;
// Read the class and super class names.
stream >> d->className;
stream >> name;
if (name.isEmpty()) {
d->superClass = 0;
} else if ((cl = resolveClassName(references, name)) != 0) {
d->superClass = cl;
} else {
stream.setStatus(QDataStream::ReadCorruptData);
return;
}
// Read the counts for each type of class member.
int classInfoCount, methodCount, propertyCount;
int enumeratorCount, constructorCount, relatedMetaObjectCount;
stream >> classInfoCount;
stream >> methodCount;
stream >> propertyCount;
stream >> enumeratorCount;
stream >> constructorCount;
stream >> relatedMetaObjectCount;
if (classInfoCount < 0 || methodCount < 0 ||
propertyCount < 0 || enumeratorCount < 0 ||
constructorCount < 0 || relatedMetaObjectCount < 0) {
stream.setStatus(QDataStream::ReadCorruptData);
return;
}
// Read the items of class information.
for (index = 0; index < classInfoCount; ++index) {
if (stream.status() != QDataStream::Ok)
return;
QByteArray value;
stream >> name;
stream >> value;
addClassInfo(name, value);
}
// Read the member methods.
for (index = 0; index < methodCount; ++index) {
if (stream.status() != QDataStream::Ok)
return;
stream >> name;
addMethod(name);
QMetaMethodBuilderPrivate *method = &(d->methods[index]);
stream >> method->returnType;
stream >> method->parameterNames;
stream >> method->tag;
stream >> method->attributes;
if (method->attributes & MethodRevisioned)
stream >> method->revision;
if (method->methodType() == QMetaMethod::Constructor) {
// Cannot add a constructor in this set of methods.
stream.setStatus(QDataStream::ReadCorruptData);
return;
}
}
// Read the properties.
for (index = 0; index < propertyCount; ++index) {
if (stream.status() != QDataStream::Ok)
return;
QByteArray type;
stream >> name;
stream >> type;
addProperty(name, type);
QMetaPropertyBuilderPrivate *property = &(d->properties[index]);
stream >> property->flags;
stream >> property->notifySignal;
if (property->notifySignal < -1 ||
property->notifySignal >= d->methods.size()) {
// Notify signal method index is out of range.
stream.setStatus(QDataStream::ReadCorruptData);
return;
}
if (property->notifySignal >= 0 &&
d->methods[property->notifySignal].methodType() != QMetaMethod::Signal) {
// Notify signal method index does not refer to a signal.
stream.setStatus(QDataStream::ReadCorruptData);
return;
}
if (property->flags & Revisioned)
stream >> property->revision;
}
// Read the enumerators.
for (index = 0; index < enumeratorCount; ++index) {
if (stream.status() != QDataStream::Ok)
return;
stream >> name;
addEnumerator(name);
QMetaEnumBuilderPrivate *enumerator = &(d->enumerators[index]);
stream >> enumerator->isFlag;
stream >> enumerator->keys;
stream >> enumerator->values;
if (enumerator->keys.size() != enumerator->values.size()) {
// Mismatch between number of keys and number of values.
stream.setStatus(QDataStream::ReadCorruptData);
return;
}
}
// Read the constructor methods.
for (index = 0; index < constructorCount; ++index) {
if (stream.status() != QDataStream::Ok)
return;
stream >> name;
addConstructor(name);
QMetaMethodBuilderPrivate *method = &(d->constructors[index]);
stream >> method->returnType;
stream >> method->parameterNames;
stream >> method->tag;
stream >> method->attributes;
if (method->methodType() != QMetaMethod::Constructor) {
// The type must be Constructor.
stream.setStatus(QDataStream::ReadCorruptData);
return;
}
}
// Read the related meta objects.
for (index = 0; index < relatedMetaObjectCount; ++index) {
if (stream.status() != QDataStream::Ok)
return;
stream >> name;
cl = resolveClassName(references, name);
if (!cl) {
stream.setStatus(QDataStream::ReadCorruptData);
return;
}
addRelatedMetaObject(cl);
}
// Read the extra data block, which is reserved for future use.
stream >> name;
}
#endif // !QT_NO_DATASTREAM
/*!
\class QMetaMethodBuilder
\inmodule QtCore
\internal
\brief The QMetaMethodBuilder class enables modifications to a method definition on a meta object builder.
*/
QMetaMethodBuilderPrivate *QMetaMethodBuilder::d_func() const
{
// Positive indices indicate methods, negative indices indicate constructors.
if (_mobj && _index >= 0 && _index < _mobj->d->methods.size())
return &(_mobj->d->methods[_index]);
else if (_mobj && -_index >= 1 && -_index <= _mobj->d->constructors.size())
return &(_mobj->d->constructors[(-_index) - 1]);
else
return 0;
}
/*!
\fn QMetaMethodBuilder::QMetaMethodBuilder()
\internal
*/
/*!
Returns the index of this method within its QMetaObjectBuilder.
*/
int QMetaMethodBuilder::index() const
{
if (_index >= 0)
return _index; // Method, signal, or slot
else
return (-_index) - 1; // Constructor
}
/*!
Returns the type of this method (signal, slot, method, or constructor).
*/
QMetaMethod::MethodType QMetaMethodBuilder::methodType() const
{
QMetaMethodBuilderPrivate *d = d_func();
if (d)
return d->methodType();
else
return QMetaMethod::Method;
}
/*!
Returns the signature of this method.
\sa parameterNames(), returnType()
*/
QByteArray QMetaMethodBuilder::signature() const
{
QMetaMethodBuilderPrivate *d = d_func();
if (d)
return d->signature;
else
return QByteArray();
}
/*!
Returns the return type for this method; empty if the method's
return type is \c{void}.
\sa setReturnType(), signature()
*/
QByteArray QMetaMethodBuilder::returnType() const
{
QMetaMethodBuilderPrivate *d = d_func();
if (d)
return d->returnType;
else
return QByteArray();
}
/*!
Sets the return type for this method to \a value. If \a value
is empty, then the method's return type is \c{void}. The \a value
will be normalized before it is added to the method.
\sa returnType(), parameterTypes(), signature()
*/
void QMetaMethodBuilder::setReturnType(const QByteArray& value)
{
QMetaMethodBuilderPrivate *d = d_func();
if (d)
d->returnType = QMetaObject::normalizedType(value);
}
/*!
Returns the list of parameter types for this method.
\sa returnType(), parameterNames()
*/
QList<QByteArray> QMetaMethodBuilder::parameterTypes() const
{
QMetaMethodBuilderPrivate *d = d_func();
if (d)
return d->parameterTypes();
else
return QList<QByteArray>();
}
/*!
Returns the list of parameter names for this method.
\sa setParameterNames()
*/
QList<QByteArray> QMetaMethodBuilder::parameterNames() const
{
QMetaMethodBuilderPrivate *d = d_func();
if (d)
return d->parameterNames;
else
return QList<QByteArray>();
}
/*!
Sets the list of parameter names for this method to \a value.
\sa parameterNames()
*/
void QMetaMethodBuilder::setParameterNames(const QList<QByteArray>& value)
{
QMetaMethodBuilderPrivate *d = d_func();
if (d)
d->parameterNames = value;
}
/*!
Returns the tag associated with this method.
\sa setTag()
*/
QByteArray QMetaMethodBuilder::tag() const
{
QMetaMethodBuilderPrivate *d = d_func();
if (d)
return d->tag;
else
return QByteArray();
}
/*!
Sets the tag associated with this method to \a value.
\sa setTag()
*/
void QMetaMethodBuilder::setTag(const QByteArray& value)
{
QMetaMethodBuilderPrivate *d = d_func();
if (d)
d->tag = value;
}
/*!
Returns the access specification of this method (private, protected,
or public). The default value is QMetaMethod::Public for methods,
slots, signals and constructors.
\sa setAccess()
*/
QMetaMethod::Access QMetaMethodBuilder::access() const
{
QMetaMethodBuilderPrivate *d = d_func();
if (d)
return d->access();
else
return QMetaMethod::Public;
}
/*!
Sets the access specification of this method (private, protected,
or public) to \a value. If the method is a signal, this function
will be ignored.
\sa access()
*/
void QMetaMethodBuilder::setAccess(QMetaMethod::Access value)
{
QMetaMethodBuilderPrivate *d = d_func();
if (d && d->methodType() != QMetaMethod::Signal)
d->setAccess(value);
}
/*!
Returns the additional attributes for this method.
\sa setAttributes()
*/
int QMetaMethodBuilder::attributes() const
{
QMetaMethodBuilderPrivate *d = d_func();
if (d)
return (d->attributes >> 4);
else
return 0;
}
/*!
Sets the additional attributes for this method to \a value.
\sa attributes()
*/
void QMetaMethodBuilder::setAttributes(int value)
{
QMetaMethodBuilderPrivate *d = d_func();
if (d)
d->attributes = ((d->attributes & 0x0f) | (value << 4));
}
/*!
Returns the revision of this method.
\sa setRevision()
*/
int QMetaMethodBuilder::revision() const
{
QMetaMethodBuilderPrivate *d = d_func();
if (d)
return d->revision;
return 0;
}
/*!
Sets the \a revision of this method.
\sa revision()
*/
void QMetaMethodBuilder::setRevision(int revision)
{
QMetaMethodBuilderPrivate *d = d_func();
if (d) {
d->revision = revision;
if (revision)
d->attributes |= MethodRevisioned;
else
d->attributes &= ~MethodRevisioned;
}
}
/*!
\class QMetaPropertyBuilder
\inmodule QtCore
\internal
\brief The QMetaPropertyBuilder class enables modifications to a property definition on a meta object builder.
*/
QMetaPropertyBuilderPrivate *QMetaPropertyBuilder::d_func() const
{
if (_mobj && _index >= 0 && _index < _mobj->d->properties.size())
return &(_mobj->d->properties[_index]);
else
return 0;
}
/*!
\fn QMetaPropertyBuilder::QMetaPropertyBuilder()
\internal
*/
/*!
\fn int QMetaPropertyBuilder::index() const
Returns the index of this property within its QMetaObjectBuilder.
*/
/*!
Returns the name associated with this property.
\sa type()
*/
QByteArray QMetaPropertyBuilder::name() const
{
QMetaPropertyBuilderPrivate *d = d_func();
if (d)
return d->name;
else
return QByteArray();
}
/*!
Returns the type associated with this property.
\sa name()
*/
QByteArray QMetaPropertyBuilder::type() const
{
QMetaPropertyBuilderPrivate *d = d_func();
if (d)
return d->type;
else
return QByteArray();
}
/*!
Returns \c true if this property has a notify signal; false otherwise.
\sa notifySignal(), setNotifySignal(), removeNotifySignal()
*/
bool QMetaPropertyBuilder::hasNotifySignal() const
{
QMetaPropertyBuilderPrivate *d = d_func();
if (d)
return d->flag(Notify);
else
return false;
}
/*!
Returns the notify signal associated with this property.
\sa hasNotifySignal(), setNotifySignal(), removeNotifySignal()
*/
QMetaMethodBuilder QMetaPropertyBuilder::notifySignal() const
{
QMetaPropertyBuilderPrivate *d = d_func();
if (d && d->notifySignal >= 0)
return QMetaMethodBuilder(_mobj, d->notifySignal);
else
return QMetaMethodBuilder();
}
/*!
Sets the notify signal associated with this property to \a value.
\sa hasNotifySignal(), notifySignal(), removeNotifySignal()
*/
void QMetaPropertyBuilder::setNotifySignal(const QMetaMethodBuilder& value)
{
QMetaPropertyBuilderPrivate *d = d_func();
if (d) {
if (value._mobj) {
d->notifySignal = value._index;
d->setFlag(Notify, true);
} else {
d->notifySignal = -1;
d->setFlag(Notify, false);
}
}
}
/*!
Removes the notify signal from this property.
\sa hasNotifySignal(), notifySignal(), setNotifySignal()
*/
void QMetaPropertyBuilder::removeNotifySignal()
{
QMetaPropertyBuilderPrivate *d = d_func();
if (d) {
d->notifySignal = -1;
d->setFlag(Notify, false);
}
}
/*!
Returns \c true if this property is readable; otherwise returns \c false.
The default value is true.
\sa setReadable(), isWritable()
*/
bool QMetaPropertyBuilder::isReadable() const
{
QMetaPropertyBuilderPrivate *d = d_func();
if (d)
return d->flag(Readable);
else
return false;
}
/*!
Returns \c true if this property is writable; otherwise returns \c false.
The default value is true.
\sa setWritable(), isReadable()
*/
bool QMetaPropertyBuilder::isWritable() const
{
QMetaPropertyBuilderPrivate *d = d_func();
if (d)
return d->flag(Writable);
else
return false;
}
/*!
Returns \c true if this property can be reset to a default value; otherwise
returns \c false. The default value is false.
\sa setResettable()
*/
bool QMetaPropertyBuilder::isResettable() const
{
QMetaPropertyBuilderPrivate *d = d_func();
if (d)
return d->flag(Resettable);
else
return false;
}
/*!
Returns \c true if this property is designable; otherwise returns \c false.
This default value is false.
\sa setDesignable(), isScriptable(), isStored()
*/
bool QMetaPropertyBuilder::isDesignable() const
{
QMetaPropertyBuilderPrivate *d = d_func();
if (d)
return d->flag(Designable);
else
return false;
}
/*!
Returns \c true if the property is scriptable; otherwise returns \c false.
This default value is true.
\sa setScriptable(), isDesignable(), isStored()
*/
bool QMetaPropertyBuilder::isScriptable() const
{
QMetaPropertyBuilderPrivate *d = d_func();
if (d)
return d->flag(Scriptable);
else
return false;
}
/*!
Returns \c true if the property is stored; otherwise returns \c false.
This default value is false.
\sa setStored(), isDesignable(), isScriptable()
*/
bool QMetaPropertyBuilder::isStored() const
{
QMetaPropertyBuilderPrivate *d = d_func();
if (d)
return d->flag(Stored);
else
return false;
}
/*!
Returns \c true if the property is editable; otherwise returns \c false.
This default value is false.
\sa setEditable(), isDesignable(), isScriptable(), isStored()
*/
bool QMetaPropertyBuilder::isEditable() const
{
QMetaPropertyBuilderPrivate *d = d_func();
if (d)
return d->flag(Editable);
else
return false;
}
/*!
Returns \c true if this property is designated as the \c USER
property, i.e., the one that the user can edit or that is
significant in some other way. Otherwise it returns
false. This default value is false.
\sa setUser(), isDesignable(), isScriptable()
*/
bool QMetaPropertyBuilder::isUser() const
{
QMetaPropertyBuilderPrivate *d = d_func();
if (d)
return d->flag(User);
else
return false;
}
/*!
Returns \c true if the property has a C++ setter function that
follows Qt's standard "name" / "setName" pattern. Designer and uic
query hasStdCppSet() in order to avoid expensive
QObject::setProperty() calls. All properties in Qt [should] follow
this pattern. The default value is false.
\sa setStdCppSet()
*/
bool QMetaPropertyBuilder::hasStdCppSet() const
{
QMetaPropertyBuilderPrivate *d = d_func();
if (d)
return d->flag(StdCppSet);
else
return false;
}
/*!
Returns \c true if the property is an enumerator or flag type;
otherwise returns \c false. This default value is false.
\sa setEnumOrFlag()
*/
bool QMetaPropertyBuilder::isEnumOrFlag() const
{
QMetaPropertyBuilderPrivate *d = d_func();
if (d)
return d->flag(EnumOrFlag);
else
return false;
}
/*!
Returns \c true if the property is constant; otherwise returns \c false.
The default value is false.
*/
bool QMetaPropertyBuilder::isConstant() const
{
QMetaPropertyBuilderPrivate *d = d_func();
if (d)
return d->flag(Constant);
else
return false;
}
/*!
Returns \c true if the property is final; otherwise returns \c false.
The default value is false.
*/
bool QMetaPropertyBuilder::isFinal() const
{
QMetaPropertyBuilderPrivate *d = d_func();
if (d)
return d->flag(Final);
else
return false;
}
/*!
Sets this property to readable if \a value is true.
\sa isReadable(), setWritable()
*/
void QMetaPropertyBuilder::setReadable(bool value)
{
QMetaPropertyBuilderPrivate *d = d_func();
if (d)
d->setFlag(Readable, value);
}
/*!
Sets this property to writable if \a value is true.
\sa isWritable(), setReadable()
*/
void QMetaPropertyBuilder::setWritable(bool value)
{
QMetaPropertyBuilderPrivate *d = d_func();
if (d)
d->setFlag(Writable, value);
}
/*!
Sets this property to resettable if \a value is true.
\sa isResettable()
*/
void QMetaPropertyBuilder::setResettable(bool value)
{
QMetaPropertyBuilderPrivate *d = d_func();
if (d)
d->setFlag(Resettable, value);
}
/*!
Sets this property to designable if \a value is true.
\sa isDesignable(), setScriptable(), setStored()
*/
void QMetaPropertyBuilder::setDesignable(bool value)
{
QMetaPropertyBuilderPrivate *d = d_func();
if (d)
d->setFlag(Designable, value);
}
/*!
Sets this property to scriptable if \a value is true.
\sa isScriptable(), setDesignable(), setStored()
*/
void QMetaPropertyBuilder::setScriptable(bool value)
{
QMetaPropertyBuilderPrivate *d = d_func();
if (d)
d->setFlag(Scriptable, value);
}
/*!
Sets this property to storable if \a value is true.
\sa isStored(), setDesignable(), setScriptable()
*/
void QMetaPropertyBuilder::setStored(bool value)
{
QMetaPropertyBuilderPrivate *d = d_func();
if (d)
d->setFlag(Stored, value);
}
/*!
Sets this property to editable if \a value is true.
\sa isEditable(), setDesignable(), setScriptable(), setStored()
*/
void QMetaPropertyBuilder::setEditable(bool value)
{
QMetaPropertyBuilderPrivate *d = d_func();
if (d)
d->setFlag(Editable, value);
}
/*!
Sets the \c USER flag on this property to \a value.
\sa isUser(), setDesignable(), setScriptable()
*/
void QMetaPropertyBuilder::setUser(bool value)
{
QMetaPropertyBuilderPrivate *d = d_func();
if (d)
d->setFlag(User, value);
}
/*!
Sets the C++ setter flag on this property to \a value, which is
true if the property has a C++ setter function that follows Qt's
standard "name" / "setName" pattern.
\sa hasStdCppSet()
*/
void QMetaPropertyBuilder::setStdCppSet(bool value)
{
QMetaPropertyBuilderPrivate *d = d_func();
if (d)
d->setFlag(StdCppSet, value);
}
/*!
Sets this property to be of an enumerator or flag type if
\a value is true.
\sa isEnumOrFlag()
*/
void QMetaPropertyBuilder::setEnumOrFlag(bool value)
{
QMetaPropertyBuilderPrivate *d = d_func();
if (d)
d->setFlag(EnumOrFlag, value);
}
/*!
Sets the \c CONSTANT flag on this property to \a value.
\sa isConstant()
*/
void QMetaPropertyBuilder::setConstant(bool value)
{
QMetaPropertyBuilderPrivate *d = d_func();
if (d)
d->setFlag(Constant, value);
}
/*!
Sets the \c FINAL flag on this property to \a value.
\sa isFinal()
*/
void QMetaPropertyBuilder::setFinal(bool value)
{
QMetaPropertyBuilderPrivate *d = d_func();
if (d)
d->setFlag(Final, value);
}
/*!
Returns the revision of this property.
\sa setRevision()
*/
int QMetaPropertyBuilder::revision() const
{
QMetaPropertyBuilderPrivate *d = d_func();
if (d)
return d->revision;
return 0;
}
/*!
Sets the \a revision of this property.
\sa revision()
*/
void QMetaPropertyBuilder::setRevision(int revision)
{
QMetaPropertyBuilderPrivate *d = d_func();
if (d) {
d->revision = revision;
d->setFlag(Revisioned, revision != 0);
}
}
/*!
\class QMetaEnumBuilder
\inmodule QtCore
\internal
\brief The QMetaEnumBuilder class enables modifications to an enumerator definition on a meta object builder.
*/
QMetaEnumBuilderPrivate *QMetaEnumBuilder::d_func() const
{
if (_mobj && _index >= 0 && _index < _mobj->d->enumerators.size())
return &(_mobj->d->enumerators[_index]);
else
return 0;
}
/*!
\fn QMetaEnumBuilder::QMetaEnumBuilder()
\internal
*/
/*!
\fn int QMetaEnumBuilder::index() const
Returns the index of this enumerator within its QMetaObjectBuilder.
*/
/*!
Returns the name of the enumerator (without the scope).
*/
QByteArray QMetaEnumBuilder::name() const
{
QMetaEnumBuilderPrivate *d = d_func();
if (d)
return d->name;
else
return QByteArray();
}
/*!
Returns \c true if this enumerator is used as a flag; otherwise returns
false.
\sa setIsFlag()
*/
bool QMetaEnumBuilder::isFlag() const
{
QMetaEnumBuilderPrivate *d = d_func();
if (d)
return d->isFlag;
else
return false;
}
/*!
Sets this enumerator to be used as a flag if \a value is true.
\sa isFlag()
*/
void QMetaEnumBuilder::setIsFlag(bool value)
{
QMetaEnumBuilderPrivate *d = d_func();
if (d)
d->isFlag = value;
}
/*!
Returns the number of keys.
\sa key(), addKey()
*/
int QMetaEnumBuilder::keyCount() const
{
QMetaEnumBuilderPrivate *d = d_func();
if (d)
return d->keys.size();
else
return 0;
}
/*!
Returns the key with the given \a index, or an empty QByteArray
if no such key exists.
\sa keyCount(), addKey(), value()
*/
QByteArray QMetaEnumBuilder::key(int index) const
{
QMetaEnumBuilderPrivate *d = d_func();
if (d && index >= 0 && index < d->keys.size())
return d->keys[index];
else
return QByteArray();
}
/*!
Returns the value with the given \a index; or returns -1 if there
is no such value.
\sa keyCount(), addKey(), key()
*/
int QMetaEnumBuilder::value(int index) const
{
QMetaEnumBuilderPrivate *d = d_func();
if (d && index >= 0 && index < d->keys.size())
return d->values[index];
else
return -1;
}
/*!
Adds a new key called \a name to this enumerator, associated
with \a value. Returns the index of the new key.
\sa keyCount(), key(), value(), removeKey()
*/
int QMetaEnumBuilder::addKey(const QByteArray& name, int value)
{
QMetaEnumBuilderPrivate *d = d_func();
if (d) {
int index = d->keys.size();
d->keys += name;
d->values += value;
return index;
} else {
return -1;
}
}
/*!
Removes the key at \a index from this enumerator.
\sa addKey()
*/
void QMetaEnumBuilder::removeKey(int index)
{
QMetaEnumBuilderPrivate *d = d_func();
if (d && index >= 0 && index < d->keys.size()) {
d->keys.removeAt(index);
d->values.removeAt(index);
}
}
QT_END_NAMESPACE
| 29.712394 | 129 | 0.648029 | [
"object"
] |
a1bc873d31ea4e1bd2fc4b9d52a2f4a2fb17ab1f | 36,277 | cpp | C++ | src/projects/geomechanics/test_GEO_direct_shear2.cpp | rserban/chrono | bee5e30b2ce3b4ac62324799d1366b6db295830e | [
"BSD-3-Clause"
] | 1 | 2020-03-05T13:00:41.000Z | 2020-03-05T13:00:41.000Z | src/projects/geomechanics/test_GEO_direct_shear2.cpp | rserban/chrono | bee5e30b2ce3b4ac62324799d1366b6db295830e | [
"BSD-3-Clause"
] | null | null | null | src/projects/geomechanics/test_GEO_direct_shear2.cpp | rserban/chrono | bee5e30b2ce3b4ac62324799d1366b6db295830e | [
"BSD-3-Clause"
] | 1 | 2022-03-27T15:12:24.000Z | 2022-03-27T15:12:24.000Z | // =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All right reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Author: Daniel Melanz, Radu Serban
// =============================================================================
//
// Chrono::Multicore demo program for shearing studies.
//
// The system contains a shearing box composed of three bodies: (1) a containing
// bin, (2) a shearing plate, and (3) a load body. Granular material sits inside
// of the containing bin and shearing plate and is compressed from the top by
// the load body. During the shearing mode, the shear plate is translated in the
// x-direction at a specified velocity.
//
// The global reference frame has Z up.
// All units SI (CGS, i.e., centimeter - gram - second)
// =============================================================================
#include <cmath>
#include <iostream>
#include <sstream>
#include <string>
#include <valarray>
#include <vector>
#include "chrono/ChConfig.h"
#include "chrono/core/ChStream.h"
#include "chrono/utils/ChUtilsCreators.h"
#include "chrono/utils/ChUtilsGenerators.h"
#include "chrono/utils/ChUtilsInputOutput.h"
#include "chrono_multicore/physics/ChSystemMulticore.h"
#include "chrono_multicore/solver/ChSystemDescriptorMulticore.h"
#include "chrono_thirdparty/filesystem/path.h"
// Control use of OpenGL run-time rendering
// Note: CHRONO_OPENGL is defined in ChConfig.h
//#undef CHRONO_OPENGL
#ifdef CHRONO_OPENGL
#include "chrono_opengl/ChOpenGLWindow.h"
#endif
#include "utils.h"
using namespace chrono;
using namespace chrono::collision;
using std::cout;
using std::endl;
using std::flush;
// -----------------------------------------------------------------------------
// Problem definitions
// -----------------------------------------------------------------------------
// Comment the following line to use NSC contact
//#define USE_SMC
enum ProblemType { SETTLING, PRESSING, SHEARING, TESTING };
ProblemType problem = SETTLING;
// -----------------------------------------------------------------------------
// Conversion factors
// -----------------------------------------------------------------------------
// Conversion for Young's modulus and pressure
// [Y] = Pa = N / m^2 = kg / m / s^2
double Pa2cgs = 10;
// -----------------------------------------------------------------------------
// Global problem definitions
// -----------------------------------------------------------------------------
// Desired number of OpenMP threads (will be clamped to maximum available)
int threads = 20;
// Perform dynamic tuning of number of threads?
bool thread_tuning = false;
// Perform shearing action via a linear actuator or kinematically?
bool use_actuator = true;
// Save PovRay post-processing data?
bool write_povray_data = true;
// Simulation times
double time_settling_min = 0.1;
double time_settling_max = 1.0;
double time_pressing_min = 0.1;
double time_pressing_max = 1.0;
double time_shearing = 5;
double time_testing = 2;
// Stopping criteria for settling (as fraction of particle radius)
double settling_tol = 0.2;
// Solver settings
#ifdef USE_SMC
double time_step = 1e-5;
int max_iteration_bilateral = 100;
#else
double time_step = 1e-4;
int max_iteration_normal = 0;
int max_iteration_sliding = 10000;
int max_iteration_spinning = 0;
int max_iteration_bilateral = 100;
double contact_recovery_speed = 10e30;
#endif
bool clamp_bilaterals = false;
double bilateral_clamp_speed = 10e30;
double tolerance = 1;
// Contact force model
#ifdef USE_SMC
ChSystemSMC::ContactForceModel contact_force_model = ChSystemSMC::ContactForceModel::Hertz;
ChSystemSMC::TangentialDisplacementModel tangential_displ_mode = ChSystemSMC::TangentialDisplacementModel::MultiStep;
#endif
// Output
#ifdef USE_SMC
const std::string out_dir = "../DIRECTSHEAR_SMC";
#else
const std::string out_dir = "../DIRECTSHEAR_NSC";
#endif
const std::string pov_dir = out_dir + "/POVRAY";
const std::string shear_file = out_dir + "/shear.dat";
const std::string stats_file = out_dir + "/stats.dat";
const std::string settled_ckpnt_file = out_dir + "/settled.dat";
const std::string pressed_ckpnt_file = out_dir + "/pressed.dat";
// Frequency for visualization output
int out_fps_settling = 120;
int out_fps_pressing = 120;
int out_fps_shearing = 60;
int out_fps_testing = 60;
// Frequency for writing results to output file (SHEARING only)
int write_fps = 1000;
// Simulation frame at which detailed timing information is printed
int timing_frame = -1;
// Gravitational acceleration [cm/s^2]
double gravity = 981;
// Parameters for the mechanism
int Id_ground = -1; // body ID for the ground (containing bin)
int Id_box = -2; // body ID for the shear box
int Id_plate = -3; // body ID for the load plate
double hdimX = 12.0 / 2; // [cm] bin half-length in x direction
double hdimY = 12.0 / 2; // [cm] bin half-depth in y direction
double hdimZ = 3.0 / 2; // [cm] bin half-height in z direction
double hthick = 1.0 / 2; // [cm] bin half-thickness of the walls
double h_scaling = 5; // ratio of shear box height to bin height
float Y_walls = (float)(Pa2cgs * 1e7);
float cr_walls = 0.6f;
float nu_walls = 0.3f;
float mu_walls = 0.08f;
int ground_coll_fam = 1; // collision family for bin contact shapes
int box_coll_fam = 2; // collision family for shear box contact shapes
int plate_coll_fam = 3; // collision family for load plate contact shapes
// Applied normal pressure
double normalPressure = Pa2cgs * 3.1e3; // 3.1 kPa // 6.4 kPa // 12.5 kPa // 24.2 kPa
// Desired shearing velocity [cm/s]
double desiredVelocity = 0.166; // 10 cm/min (about 100 times faster than experiment)
// Parameters for the granular material
int Id_g = 1; // start body ID for particles
double r_g = 0.3; // [cm] radius of granular spheres
double rho_g = 2.550; // [g/cm^3] density of granules
double desiredBulkDensity = 1.5; // [g/cm^3] desired bulk density
float Y_g = (float)(Pa2cgs * 4e7); // (1,000 times softer than experiment on glass beads)
float cr_g = 0.87f;
float nu_g = 0.22f;
float mu_g = 0.18f;
// Parameters of the testing ball
int Id_ball = -4;
double mass_ball = 200; // [g] mass of testing ball
double radius_ball = 0.9 * hdimX; // [cm] radius of testing ball
// =============================================================================
// Create the containing bin (the ground), the shear box, and the load plate.
//
// Both the shear box and load plate are constructed fixed to the ground.
// No joints between bodies are defined at this time.
// =============================================================================
void CreateMechanismBodies(ChSystemMulticore* system) {
// -------------------------------
// Create a material for the walls
// -------------------------------
#ifdef USE_SMC
auto mat_walls = chrono_types::make_shared<ChMaterialSurfaceSMC>();
mat_walls->SetYoungModulus(Y_walls);
mat_walls->SetFriction(mu_walls);
mat_walls->SetRestitution(cr_walls);
mat_walls->SetPoissonRatio(nu_walls);
#else
auto mat_walls = chrono_types::make_shared<ChMaterialSurfaceNSC>();
mat_walls->SetFriction(mu_walls);
#endif
// ----------------------
// Create the ground body -- always FIRST body in system
// ----------------------
auto ground = chrono_types::make_shared<ChBody>(ChCollisionSystemType::CHRONO);
ground->SetIdentifier(Id_ground);
ground->SetBodyFixed(true);
ground->SetCollide(true);
// Attach geometry of the containing bin. Disable contact ground-shearBox
// and ground-loadPlate.
ground->GetCollisionModel()->ClearModel();
utils::AddBoxGeometry(ground.get(), mat_walls, ChVector<>(hdimX, hdimY, hthick), ChVector<>(0, 0, -hthick));
utils::AddBoxGeometry(ground.get(), mat_walls, ChVector<>(hthick, hdimY, hdimZ), ChVector<>(-hdimX - hthick, 0, hdimZ));
utils::AddBoxGeometry(ground.get(), mat_walls, ChVector<>(hthick, hdimY, hdimZ), ChVector<>(hdimX + hthick, 0, hdimZ));
utils::AddBoxGeometry(ground.get(), mat_walls, ChVector<>(hdimX, hthick, hdimZ), ChVector<>(0, -hdimY - hthick, hdimZ));
utils::AddBoxGeometry(ground.get(), mat_walls, ChVector<>(hdimX, hthick, hdimZ), ChVector<>(0, hdimY + hthick, hdimZ));
ground->GetCollisionModel()->SetFamily(ground_coll_fam);
ground->GetCollisionModel()->SetFamilyMaskNoCollisionWithFamily(box_coll_fam);
ground->GetCollisionModel()->SetFamilyMaskNoCollisionWithFamily(plate_coll_fam);
ground->GetCollisionModel()->BuildModel();
system->AddBody(ground);
// --------------------
// Create the shear box -- always SECOND body in system
// --------------------
// Initially, the shear box is fixed to ground.
// During the shearing phase it may be released (if using an actuator)
auto box = chrono_types::make_shared<ChBody>(ChCollisionSystemType::CHRONO);
box->SetIdentifier(Id_box);
box->SetPos(ChVector<>(0, 0, 2 * hdimZ + r_g));
box->SetCollide(true);
box->SetBodyFixed(true);
// Add geometry of the shear box. Disable contact with the load plate.
box->GetCollisionModel()->ClearModel();
utils::AddBoxGeometry(box.get(), mat_walls, ChVector<>(hthick, hdimY, h_scaling * hdimZ),
ChVector<>(-hdimX - hthick, 0, h_scaling * hdimZ));
utils::AddBoxGeometry(box.get(), mat_walls, ChVector<>(hthick, hdimY, h_scaling * hdimZ),
ChVector<>(hdimX + hthick, 0, h_scaling * hdimZ));
utils::AddBoxGeometry(box.get(), mat_walls, ChVector<>(hdimX, hthick, h_scaling * hdimZ),
ChVector<>(0, -hdimY - hthick, h_scaling * hdimZ));
utils::AddBoxGeometry(box.get(), mat_walls, ChVector<>(hdimX, hthick, h_scaling * hdimZ),
ChVector<>(0, hdimY + hthick, h_scaling * hdimZ));
box->GetCollisionModel()->SetFamily(box_coll_fam);
box->GetCollisionModel()->SetFamilyMaskNoCollisionWithFamily(plate_coll_fam);
box->GetCollisionModel()->BuildModel();
system->AddBody(box);
// ---------------------
// Create the plate body -- always THIRD body in the system
// ---------------------
// Initially, the load plate is fixed to ground.
// It is released after the settling phase.
// Set plate dimensions, increasing the X dimension to accommodate the
// shearing phase (use 3 times as much as needed)
double hdimX_p = hdimX + 3 * time_shearing * desiredVelocity;
// Estimate plate mass from desired applied normal pressure
double area = 4 * hdimX * hdimY;
double mass = normalPressure * area / gravity;
auto plate = chrono_types::make_shared<ChBody>(ChCollisionSystemType::CHRONO);
plate->SetIdentifier(Id_plate);
plate->SetMass(mass);
plate->SetPos(ChVector<>(0, 0, (1 + 2 * h_scaling) * hdimZ));
plate->SetCollide(true);
plate->SetBodyFixed(true);
// Add geometry of the load plate.
plate->GetCollisionModel()->ClearModel();
utils::AddBoxGeometry(plate.get(), mat_walls, ChVector<>(hdimX_p, hdimY, hdimZ), ChVector<>(0, 0, hdimZ));
plate->GetCollisionModel()->SetFamily(plate_coll_fam);
plate->GetCollisionModel()->BuildModel();
system->AddBody(plate);
}
// =============================================================================
// Connect the shear box to the containing bin (ground) through a translational
// joint and create a linear actuator.
// =============================================================================
void ConnectShearBox(ChSystemMulticore* system, std::shared_ptr<ChBody> ground, std::shared_ptr<ChBody> box) {
auto prismatic = chrono_types::make_shared<ChLinkLockPrismatic>();
prismatic->Initialize(ground, box, ChCoordsys<>(ChVector<>(0, 0, 2 * hdimZ), Q_from_AngY(CH_C_PI_2)));
prismatic->SetName("prismatic_box_ground");
system->AddLink(prismatic);
auto actuator_fun = chrono_types::make_shared<ChFunction_Ramp>(0.0, desiredVelocity);
auto actuator = chrono_types::make_shared<ChLinkLinActuator>();
ChVector<> pt1(0, 0, 2 * hdimZ);
ChVector<> pt2(1, 0, 2 * hdimZ);
actuator->Initialize(ground, box, false, ChCoordsys<>(pt1, QUNIT), ChCoordsys<>(pt2, QUNIT));
actuator->SetName("actuator");
actuator->Set_lin_offset(1);
actuator->Set_dist_funct(actuator_fun);
system->AddLink(actuator);
}
// =============================================================================
// Connect the load plate to the bin (ground) through a vertical translational
// joint.
// =============================================================================
void ConnectLoadPlate(ChSystemMulticore* system, std::shared_ptr<ChBody> ground, std::shared_ptr<ChBody> plate) {
auto prismatic = chrono_types::make_shared<ChLinkLockPrismatic>();
prismatic->Initialize(ground, plate, ChCoordsys<>(ChVector<>(0, 0, 2 * hdimZ), QUNIT));
prismatic->SetName("prismatic_plate_ground");
system->AddLink(prismatic);
}
// =============================================================================
// Create the granular material
//
// Granular material consisting of identical spheres with specified radius and
// material properties; the spheres are generated in a number of vertical
// layers with locations within each layer obtained using Poisson Disk sampling,
// thus ensuring that no two spheres are closer than twice the radius.
// =============================================================================
int CreateGranularMaterial(ChSystemMulticore* system) {
// -------------------------------------------
// Create a material for the granular material
// -------------------------------------------
#ifdef USE_SMC
auto mat_g = chrono_types::make_shared<ChMaterialSurfaceSMC>();
mat_g->SetYoungModulus(Y_g);
mat_g->SetFriction(mu_g);
mat_g->SetRestitution(cr_g);
mat_g->SetPoissonRatio(nu_g);
#else
auto mat_g = chrono_types::make_shared<ChMaterialSurfaceNSC>();
mat_g->SetFriction(mu_g);
#endif
// ---------------------------------------------
// Create a mixture entirely made out of spheres
// ---------------------------------------------
// Create the particle generator with a mixture of 100% spheres
double r = 1.01 * r_g;
utils::PDSampler<double> sampler(2 * r);
utils::Generator gen(system);
std::shared_ptr<utils::MixtureIngredient> m1 = gen.AddMixtureIngredient(utils::MixtureType::SPHERE, 1.0);
m1->setDefaultMaterial(mat_g);
m1->setDefaultDensity(rho_g);
m1->setDefaultSize(r_g);
// Ensure that all generated particle bodies will have positive IDs.
gen.setBodyIdentifier(Id_g);
// ----------------------
// Generate the particles
// ----------------------
ChVector<> hdims(hdimX - r, hdimY - r, 0);
ChVector<> center(0, 0, 2 * r);
while (center.z() < 2 * h_scaling * hdimZ) {
gen.CreateObjectsBox(sampler, center, hdims);
center.z() += 2 * r;
}
// Return the number of generated particles.
return gen.getTotalNumBodies();
}
// =============================================================================
// Create a single large sphere (for use in TESTING)
// =============================================================================
void CreateBall(ChSystemMulticore* system) {
// ------------------------------
// Create a material for the ball
// ------------------------------
#ifdef USE_SMC
auto mat_g = chrono_types::make_shared<ChMaterialSurfaceSMC>();
mat_g->SetYoungModulus(Y_g);
mat_g->SetFriction(mu_g);
mat_g->SetRestitution(cr_g);
mat_g->SetPoissonRatio(nu_g);
#else
auto mat_g = chrono_types::make_shared<ChMaterialSurfaceNSC>();
mat_g->SetFriction(mu_g);
#endif
// ---------------
// Create the ball
// ---------------
auto ball = chrono_types::make_shared<ChBody>(ChCollisionSystemType::CHRONO);
ball->SetIdentifier(Id_ball);
ball->SetMass(mass_ball);
ball->SetPos(ChVector<>(0, 0, 1.01 * radius_ball));
ball->SetCollide(true);
ball->SetBodyFixed(false);
ball->GetCollisionModel()->ClearModel();
utils::AddSphereGeometry(ball.get(), mat_g, radius_ball);
ball->GetCollisionModel()->BuildModel();
system->AddBody(ball);
}
// =============================================================================
// Find the height of the highest and lowest sphere in the granular mix. We only
// look at bodies whith positive identifiers (to exclude all other bodies).
// =============================================================================
void FindHeightRange(ChSystemMulticore* sys, double& lowest, double& highest) {
highest = -1000;
lowest = 1000;
for (auto body : sys->Get_bodylist()) {
if (body->GetIdentifier() <= 0)
continue;
double h = body->GetPos().z();
if (h < lowest)
lowest = h;
else if (h > highest)
highest = h;
}
}
// =============================================================================
//
//// TODO: cannot do this with SMC!!!!!
//
// =============================================================================
void setBulkDensity(ChSystem* sys, double bulkDensity) {
double vol_g = (4.0 / 3) * CH_C_PI * r_g * r_g * r_g;
double normalPlateHeight = sys->Get_bodylist().at(1)->GetPos().z() - hdimZ;
double bottomHeight = 0;
double boxVolume = hdimX * 2 * hdimX * 2 * (normalPlateHeight - bottomHeight);
double granularVolume = (sys->Get_bodylist().size() - 3) * vol_g;
double reqDensity = bulkDensity * boxVolume / granularVolume;
for (auto body : sys->Get_bodylist()) {
if (body->GetIdentifier() > 1) {
body->SetMass(reqDensity * vol_g);
}
}
cout << "N Bodies: " << sys->Get_bodylist().size() << endl;
cout << "Box Volume: " << boxVolume << endl;
cout << "Granular Volume: " << granularVolume << endl;
cout << "Desired bulk density = " << bulkDensity << ", Required Body Density = " << reqDensity << endl;
}
// =============================================================================
int main(int argc, char* argv[]) {
// Create output directories.
if (!filesystem::create_directory(filesystem::path(out_dir))) {
cout << "Error creating directory " << out_dir << endl;
return 1;
}
if (!filesystem::create_directory(filesystem::path(pov_dir))) {
cout << "Error creating directory " << pov_dir << endl;
return 1;
}
// -------------
// Create system
// -------------
#ifdef USE_SMC
cout << "Create SMC system" << endl;
ChSystemMulticoreSMC* msystem = new ChSystemMulticoreSMC();
#else
cout << "Create NSC system" << endl;
ChSystemMulticoreNSC* msystem = new ChSystemMulticoreNSC();
#endif
msystem->Set_G_acc(ChVector<>(0, 0, -gravity));
// Set number of threads.
int max_threads = omp_get_num_procs();
if (threads > max_threads)
threads = max_threads;
if (thread_tuning)
msystem->SetNumThreads(1, 1, threads);
else
msystem->SetNumThreads(threads);
// Edit system settings
msystem->GetSettings()->solver.use_full_inertia_tensor = false;
msystem->GetSettings()->solver.tolerance = tolerance;
msystem->GetSettings()->solver.max_iteration_bilateral = max_iteration_bilateral;
msystem->GetSettings()->solver.clamp_bilaterals = clamp_bilaterals;
msystem->GetSettings()->solver.bilateral_clamp_speed = bilateral_clamp_speed;
#ifdef USE_SMC
msystem->GetSettings()->collision.narrowphase_algorithm = ChNarrowphase::Algorithm::PRIMS;
msystem->GetSettings()->solver.contact_force_model = contact_force_model;
msystem->GetSettings()->solver.tangential_displ_mode = tangential_displ_mode;
#else
msystem->GetSettings()->solver.solver_mode = SolverMode::SLIDING;
msystem->GetSettings()->solver.max_iteration_normal = max_iteration_normal;
msystem->GetSettings()->solver.max_iteration_sliding = max_iteration_sliding;
msystem->GetSettings()->solver.max_iteration_spinning = max_iteration_spinning;
msystem->GetSettings()->solver.alpha = 0;
msystem->GetSettings()->solver.contact_recovery_speed = contact_recovery_speed;
msystem->SetMaxPenetrationRecoverySpeed(contact_recovery_speed);
msystem->ChangeSolverType(SolverType::APGDREF);
msystem->GetSettings()->collision.collision_envelope = 0.05 * r_g;
#endif
msystem->GetSettings()->collision.bins_per_axis = vec3(10, 10, 10);
// --------------
// Problem set up
// --------------
// Depending on problem type:
// - Select end simulation time
// - Select output FPS
// - Create / load objects
double time_min = 0;
double time_end = 0;
int out_fps = 0;
std::shared_ptr<ChBody> ground;
std::shared_ptr<ChBody> shearBox;
std::shared_ptr<ChBody> loadPlate;
std::shared_ptr<ChLinkLockPrismatic> prismatic_box_ground;
std::shared_ptr<ChLinkLockPrismatic> prismatic_plate_ground;
std::shared_ptr<ChLinkLinActuator> actuator;
switch (problem) {
case SETTLING: {
time_min = time_settling_min;
time_end = time_settling_max;
out_fps = out_fps_settling;
// Create the mechanism bodies (all fixed).
CreateMechanismBodies(msystem);
// Grab handles to mechanism bodies (must increase ref counts)
ground = msystem->Get_bodylist().at(0);
shearBox = msystem->Get_bodylist().at(1);
loadPlate = msystem->Get_bodylist().at(2);
// Create granular material.
int num_particles = CreateGranularMaterial(msystem);
cout << "Granular material: " << num_particles << " particles" << endl;
break;
}
case PRESSING: {
time_min = time_pressing_min;
time_end = time_pressing_max;
out_fps = out_fps_pressing;
// Create bodies from checkpoint file.
cout << "Read checkpoint data from " << settled_ckpnt_file;
utils::ReadCheckpoint(msystem, settled_ckpnt_file);
cout << " done. Read " << msystem->Get_bodylist().size() << " bodies." << endl;
// Grab handles to mechanism bodies (must increase ref counts)
ground = msystem->Get_bodylist().at(0);
shearBox = msystem->Get_bodylist().at(1);
loadPlate = msystem->Get_bodylist().at(2);
// Move the load plate just above the granular material.
double highest, lowest;
FindHeightRange(msystem, lowest, highest);
ChVector<> pos = loadPlate->GetPos();
double z_new = highest + 2 * r_g;
loadPlate->SetPos(ChVector<>(pos.x(), pos.y(), z_new));
// Connect the load plate to the shear box.
ConnectLoadPlate(msystem, ground, loadPlate);
prismatic_plate_ground =
std::static_pointer_cast<ChLinkLockPrismatic>(msystem->SearchLink("prismatic_plate_ground"));
// Release the load plate.
loadPlate->SetBodyFixed(false);
// Set plate mass from desired applied normal pressure
double area = 4 * hdimX * hdimY;
double mass = normalPressure * area / gravity;
loadPlate->SetMass(mass);
break;
}
case SHEARING: {
time_end = time_shearing;
out_fps = out_fps_shearing;
// Create bodies from checkpoint file.
cout << "Read checkpoint data from " << pressed_ckpnt_file;
utils::ReadCheckpoint(msystem, pressed_ckpnt_file);
cout << " done. Read " << msystem->Get_bodylist().size() << " bodies." << endl;
// Grab handles to mechanism bodies (must increase ref counts)
ground = msystem->Get_bodylist().at(0);
shearBox = msystem->Get_bodylist().at(1);
loadPlate = msystem->Get_bodylist().at(2);
// If using an actuator, connect the shear box and get a handle to the actuator.
if (use_actuator) {
ConnectShearBox(msystem, ground, shearBox);
prismatic_box_ground =
std::static_pointer_cast<ChLinkLockPrismatic>(msystem->SearchLink("prismatic_box_ground"));
actuator = std::static_pointer_cast<ChLinkLinActuator>(msystem->SearchLink("actuator"));
}
// Release the shear box when using an actuator.
shearBox->SetBodyFixed(!use_actuator);
// Connect the load plate to the shear box.
ConnectLoadPlate(msystem, ground, loadPlate);
prismatic_plate_ground =
std::static_pointer_cast<ChLinkLockPrismatic>(msystem->SearchLink("prismatic_plate_ground"));
// Release the load plate.
loadPlate->SetBodyFixed(false);
// setBulkDensity(msystem, desiredBulkDensity);
// Set plate mass from desired applied normal pressure
double area = 4 * hdimX * hdimY;
double mass = normalPressure * area / gravity;
loadPlate->SetMass(mass);
break;
}
case TESTING: {
time_end = time_testing;
out_fps = out_fps_testing;
// For TESTING only, increase shearing velocity.
desiredVelocity = 0.5;
// Create the mechanism bodies (all fixed).
CreateMechanismBodies(msystem);
// Create the test ball.
CreateBall(msystem);
// Grab handles to mechanism bodies (must increase ref counts)
ground = msystem->Get_bodylist().at(0);
shearBox = msystem->Get_bodylist().at(1);
loadPlate = msystem->Get_bodylist().at(2);
// Move the load plate just above the test ball.
ChVector<> pos = loadPlate->GetPos();
double z_new = 2.1 * radius_ball;
loadPlate->SetPos(ChVector<>(pos.x(), pos.y(), z_new));
// If using an actuator, connect the shear box and get a handle to the actuator.
if (use_actuator) {
ConnectShearBox(msystem, ground, shearBox);
prismatic_box_ground =
std::static_pointer_cast<ChLinkLockPrismatic>(msystem->SearchLink("prismatic_box_ground"));
actuator = std::static_pointer_cast<ChLinkLinActuator>(msystem->SearchLink("actuator"));
}
// Release the shear box when using an actuator.
shearBox->SetBodyFixed(!use_actuator);
// Connect the load plate to the shear box.
ConnectLoadPlate(msystem, ground, loadPlate);
prismatic_plate_ground =
std::static_pointer_cast<ChLinkLockPrismatic>(msystem->SearchLink("prismatic_plate_ground"));
// Release the load plate.
loadPlate->SetBodyFixed(false);
// Set plate mass from desired applied normal pressure
double area = 4 * hdimX * hdimY;
double mass = normalPressure * area / gravity;
loadPlate->SetMass(mass);
break;
}
}
// ----------------------
// Perform the simulation
// ----------------------
// Set number of simulation steps and steps between successive output
int out_steps = (int)std::ceil((1.0 / time_step) / out_fps);
int write_steps = (int)std::ceil((1.0 / time_step) / write_fps);
// Initialize counters
double time = 0;
int sim_frame = 0;
int out_frame = 0;
int next_out_frame = 0;
double exec_time = 0;
int num_contacts = 0;
double max_cnstr_viol[3] = {0, 0, 0};
// Circular buffer with highest particle location
// (only used for SETTLING or PRESSING)
int buffer_size = (int)std::ceil(time_min / time_step);
std::valarray<double> hdata(0.0, buffer_size);
// Create output files
ChStreamOutAsciiFile statsStream(stats_file.c_str());
ChStreamOutAsciiFile shearStream(shear_file.c_str());
shearStream.SetNumFormat("%16.4e");
#ifdef CHRONO_OPENGL
opengl::ChOpenGLWindow& gl_window = opengl::ChOpenGLWindow::getInstance();
gl_window.Initialize(1280, 720, "Direct Shear Test", msystem);
gl_window.SetCamera(ChVector<>(0, -10 * hdimY, hdimZ), ChVector<>(0, 0, hdimZ), ChVector<>(0, 0, 1));
gl_window.SetRenderMode(opengl::WIREFRAME);
#endif
// Loop until reaching the end time...
while (time < time_end) {
// Current position and velocity of the shear box
ChVector<> pos_old = shearBox->GetPos();
ChVector<> vel_old = shearBox->GetPos_dt();
// Calculate minimum and maximum particle heights
double highest, lowest;
FindHeightRange(msystem, lowest, highest);
// If at an output frame, write PovRay file and print info
if (sim_frame == next_out_frame) {
cout << "------------ Output frame: " << out_frame + 1 << endl;
cout << " Sim frame: " << sim_frame << endl;
cout << " Time: " << time << endl;
cout << " Shear box pos: " << pos_old.x() << endl;
cout << " vel: " << vel_old.x() << endl;
cout << " Particle lowest: " << lowest << endl;
cout << " highest: " << highest << endl;
cout << " Execution time: " << exec_time << endl;
// Save PovRay post-processing data.
if (write_povray_data) {
char filename[100];
sprintf(filename, "%s/data_%03d.dat", pov_dir.c_str(), out_frame + 1);
utils::WriteVisualizationAssets(msystem, filename, false);
}
// Create a checkpoint from the current state.
if (problem == SETTLING || problem == PRESSING) {
cout << " Write checkpoint data " << flush;
if (problem == SETTLING)
utils::WriteCheckpoint(msystem, settled_ckpnt_file);
else
utils::WriteCheckpoint(msystem, pressed_ckpnt_file);
cout << msystem->Get_bodylist().size() << " bodies" << endl;
}
// Increment counters
out_frame++;
next_out_frame += out_steps;
}
// Check for early termination of a settling phase.
if (problem == SETTLING || problem == PRESSING) {
// Store maximum particle height in circular buffer
hdata[sim_frame % buffer_size] = highest;
// Check variance of data in circular buffer
if (time > time_min) {
double mean_height = hdata.sum() / buffer_size;
std::valarray<double> x = hdata - mean_height;
double var = std::sqrt((x * x).sum() / buffer_size);
// Consider the material settled when the variance is below the
// specified fraction of a particle radius
if (var < settling_tol * r_g) {
cout << "Granular material settled... time = " << time << endl;
break;
}
}
}
// Advance simulation by one step
#ifdef CHRONO_OPENGL
if (gl_window.Active()) {
gl_window.DoStepDynamics(time_step);
gl_window.Render();
} else
break;
#else
msystem->DoStepDynamics(time_step);
#endif
////progressbar(out_steps + sim_frame - next_out_frame + 1, out_steps);
TimingOutput(msystem);
// Record stats about the simulation
if (sim_frame % write_steps == 0) {
// write stat info
size_t numIters = msystem->data_manager->measures.solver.maxd_hist.size();
double residual = 0;
if (numIters != 0)
residual = msystem->data_manager->measures.solver.residual;
statsStream << time << ", " << exec_time << ", " << num_contacts / write_steps << ", " << numIters << ", "
<< residual << ", " << max_cnstr_viol[0] << ", " << max_cnstr_viol[1] << ", "
<< max_cnstr_viol[2] << ", \n";
statsStream.GetFstream().flush();
num_contacts = 0;
max_cnstr_viol[0] = 0;
max_cnstr_viol[1] = 0;
max_cnstr_viol[2] = 0;
}
if (problem == SHEARING || problem == TESTING) {
// Get the current reaction force or impose shear box position
ChVector<> rforcePbg(0, 0, 0);
ChVector<> rtorquePbg(0, 0, 0);
ChVector<> rforcePpb(0, 0, 0);
ChVector<> rtorquePpb(0, 0, 0);
ChVector<> rforceA(0, 0, 0);
ChVector<> rtorqueA(0, 0, 0);
if (use_actuator) {
rforcePbg = prismatic_box_ground->Get_react_force();
rtorquePbg = prismatic_box_ground->Get_react_torque();
rforcePpb = prismatic_plate_ground->Get_react_force();
rtorquePpb = prismatic_plate_ground->Get_react_torque();
rforceA = actuator->Get_react_force();
rtorqueA = actuator->Get_react_torque();
} else {
double xpos_new = pos_old.x() + desiredVelocity * time_step;
shearBox->SetPos(ChVector<>(xpos_new, pos_old.y(), pos_old.z()));
shearBox->SetPos_dt(ChVector<>(desiredVelocity, 0, 0));
}
if (sim_frame % write_steps == 0) {
////cout << "X pos: " << xpos_new << " X react: " << cnstr_force << endl;
shearStream << time << " " << shearBox->GetPos().x() << " ";
shearStream << rforceA.x() << " " << rforceA.y() << " " << rforceA.z() << " ";
shearStream << rtorqueA.x() << " " << rtorqueA.y() << " " << rtorqueA.z() << "\n";
shearStream.GetFstream().flush();
}
}
// Find maximum constraint violation
if (prismatic_box_ground) {
auto C = prismatic_box_ground->GetConstraintViolation();
for (int i = 0; i < 5; i++)
max_cnstr_viol[0] = std::max(max_cnstr_viol[0], std::abs(C(i)));
}
if (prismatic_plate_ground) {
auto C = prismatic_plate_ground->GetConstraintViolation();
for (int i = 0; i < 5; i++)
max_cnstr_viol[1] = std::max(max_cnstr_viol[1], std::abs(C(i)));
}
if (actuator) {
auto C = actuator->GetConstraintViolation();
max_cnstr_viol[2] = std::max(max_cnstr_viol[2], std::abs(C(0)));
}
// Increment counters
time += time_step;
sim_frame++;
exec_time += msystem->GetTimerStep();
num_contacts += msystem->GetNcontacts();
// If requested, output detailed timing information for this step
if (sim_frame == timing_frame)
msystem->PrintStepStats();
}
// ----------------
// Final processing
// ----------------
// Create a checkpoint from the last state
if (problem == SETTLING || problem == PRESSING) {
cout << " Write checkpoint data " << flush;
if (problem == SETTLING)
utils::WriteCheckpoint(msystem, settled_ckpnt_file);
else
utils::WriteCheckpoint(msystem, pressed_ckpnt_file);
cout << msystem->Get_bodylist().size() << " bodies" << endl;
}
// Final stats
cout << "==================================" << endl;
cout << "Number of bodies: " << msystem->Get_bodylist().size() << endl;
cout << "Simulation time: " << exec_time << endl;
cout << "Number of threads: " << threads << endl;
return 0;
}
| 38.551541 | 124 | 0.588417 | [
"geometry",
"render",
"vector",
"model"
] |
a1c47ea4c9d2c83278c8c73e529ff4b01c048bca | 16,796 | cpp | C++ | src/maple_be/src/cg/schedule.cpp | harmonyos-mirror/OpenArkCompiler-test | 1755550ea22eb185cbef8cc5864fa273caebf95a | [
"MulanPSL-1.0"
] | 796 | 2019-08-30T16:20:33.000Z | 2021-12-25T14:45:06.000Z | src/maple_be/src/cg/schedule.cpp | harmonyos-mirror/OpenArkCompiler-test | 1755550ea22eb185cbef8cc5864fa273caebf95a | [
"MulanPSL-1.0"
] | 16 | 2019-08-30T18:04:08.000Z | 2021-09-19T05:02:58.000Z | src/maple_be/src/cg/schedule.cpp | harmonyos-mirror/OpenArkCompiler-test | 1755550ea22eb185cbef8cc5864fa273caebf95a | [
"MulanPSL-1.0"
] | 326 | 2019-08-30T16:11:29.000Z | 2021-11-26T12:31:17.000Z | /*
* Copyright (c) [2020] Huawei Technologies Co.,Ltd.All rights reserved.
*
* OpenArkCompiler is licensed under the Mulan PSL v1.
* You can use this software according to the terms and conditions of the Mulan PSL v1.
* You may obtain a copy of Mulan PSL v1 at:
*
* http://license.coscl.org.cn/MulanPSL
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR
* FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v1 for more details.
*/
#if TARGAARCH64
#include "aarch64_schedule.h"
#endif
#if TARGARM32
#include "arm32_schedule.h"
#endif
#include "cg.h"
#include "optimize_common.h"
#undef PRESCHED_DEBUG
namespace maplebe {
/* ---- RegPressureSchedule function ---- */
void RegPressureSchedule::InitBBInfo(BB &b, MemPool &memPool, const MapleVector<DepNode*> &nodes) {
bb = &b;
liveReg.clear();
scheduledNode.clear();
readyList.clear();
maxPriority = 0;
maxPressure = memPool.NewArray<int32>(RegPressure::GetMaxRegClassNum());
curPressure = memPool.NewArray<int32>(RegPressure::GetMaxRegClassNum());
physicalRegNum = memPool.NewArray<int32>(RegPressure::GetMaxRegClassNum());
for (auto node : nodes) {
node->SetState(kNormal);
}
}
/* return register type according to register number */
RegType RegPressureSchedule::GetRegisterType(regno_t reg) const {
return cgFunc.GetRegisterType(reg);
}
/* Get amount of every physical register */
void RegPressureSchedule::BuildPhyRegInfo(const std::vector<int32> ®NumVec) {
FOR_ALL_REGCLASS(i) {
physicalRegNum[i] = regNumVec[i];
}
}
/* initialize register pressure information according to bb's live-in data.
* initialize node's valid preds size.
*/
void RegPressureSchedule::Init(const MapleVector<DepNode*> &nodes) {
FOR_ALL_REGCLASS(i) {
curPressure[i] = 0;
maxPressure[i] = 0;
}
for (auto *node : nodes) {
/* calculate the node uses'register pressure */
for (auto &useReg : node->GetUseRegnos()) {
CalculatePressure(*node, useReg, false);
}
/* calculate the node defs'register pressure */
size_t i = 0;
for (auto &defReg : node->GetDefRegnos()) {
CalculatePressure(*node, defReg, true);
RegType regType = GetRegisterType(defReg);
/* if no use list, a register is only defined, not be used */
if (node->GetRegDefs(i) == nullptr) {
node->IncDeadDefByIndex(regType);
}
++i;
}
node->SetValidPredsSize(node->GetPreds().size());
}
DepNode *firstNode = nodes.front();
readyList.emplace_back(firstNode);
firstNode->SetState(kReady);
scheduledNode.reserve(nodes.size());
constexpr size_t readyListSize = 10;
readyList.reserve(readyListSize);
}
void RegPressureSchedule::SortReadyList() {
std::sort(readyList.begin(), readyList.end(), DepNodePriorityCmp);
}
/* return true if nodes1 first. */
bool RegPressureSchedule::DepNodePriorityCmp(const DepNode *node1, const DepNode *node2) {
CHECK_NULL_FATAL(node1);
CHECK_NULL_FATAL(node2);
int32 priority1 = node1->GetPriority();
int32 priority2 = node2->GetPriority();
if (priority1 != priority2) {
return priority1 > priority2;
}
int32 numCall1 = node1->GetNumCall();
int32 numCall2 = node2->GetNumCall();
if (node1->GetIncPressure() == true && node2->GetIncPressure() == true) {
if (numCall1 != numCall2) {
return numCall1 > numCall2;
}
}
int32 near1 = node1->GetNear();
int32 near2 = node1->GetNear();
int32 depthS1 = node1->GetMaxDepth() + near1;
int32 depthS2 = node2->GetMaxDepth() + near2;
if (depthS1 != depthS2) {
return depthS1 > depthS2;
}
if (near1 != near2) {
return near1 > near2;
}
if (numCall1 != numCall2) {
return numCall1 > numCall2;
}
size_t succsSize1 = node1->GetSuccs().size();
size_t succsSize2 = node1->GetSuccs().size();
if (succsSize1 != succsSize2) {
return succsSize1 < succsSize2;
}
if (node1->GetHasPreg() != node2->GetHasPreg()) {
return node1->GetHasPreg();
}
return node1->GetInsn()->GetId() < node2->GetInsn()->GetId();
}
/* set a node's incPressure is true, when a class register inscrease */
void RegPressureSchedule::ReCalculateDepNodePressure(DepNode &node) {
/* if there is a type of register pressure increases, set incPressure as true. */
auto &pressures = node.GetPressure();
node.SetIncPressure(pressures[kRegisterInt] > 0);
}
/* calculate the maxDepth of every node in nodes. */
void RegPressureSchedule::CalculateMaxDepth(const MapleVector<DepNode*> &nodes) {
/* from the last node to first node. */
for (auto it = nodes.rbegin(); it != nodes.rend(); ++it) {
/* init call count */
if ((*it)->GetInsn()->IsCall()) {
(*it)->SetNumCall(1);
}
/* traversing each successor of it. */
for (auto succ : (*it)->GetSuccs()) {
DepNode &to = succ->GetTo();
if ((*it)->GetMaxDepth() < (to.GetMaxDepth() + 1)) {
(*it)->SetMaxDepth(to.GetMaxDepth() + 1);
}
if (to.GetInsn()->IsCall() && ((*it)->GetNumCall() < to.GetNumCall() + 1)) {
(*it)->SetNumCall(to.GetNumCall() + 1);
} else if ((*it)->GetNumCall() < to.GetNumCall()) {
(*it)->SetNumCall(to.GetNumCall());
}
}
}
}
/* calculate the near of every successor of the node. */
void RegPressureSchedule::CalculateNear(const DepNode &node) {
for (auto succ : node.GetSuccs()) {
DepNode &to = succ->GetTo();
if (succ->GetDepType() == kDependenceTypeTrue && to.GetNear() < node.GetNear() + 1) {
to.SetNear(node.GetNear() + 1);
}
}
}
/* return true if it is last time using the regNO. */
bool RegPressureSchedule::IsLastUse(const DepNode &node, regno_t regNO) const {
size_t i = 0;
for (auto reg : node.GetUseRegnos()) {
if (reg == regNO) {
break;
}
++i;
}
RegList *regList = node.GetRegUses(i);
/*
* except the node, if there are insn that has no scheduled in regNO'sregList,
* then it is not the last time using the regNO, return false.
*/
while (regList != nullptr) {
CHECK_NULL_FATAL(regList->insn);
DepNode *useNode = regList->insn->GetDepNode();
ASSERT(useNode != nullptr, "get depend node failed in RegPressureSchedule::IsLastUse");
if ((regList->insn != node.GetInsn()) && (useNode->GetState() != kScheduled)) {
return false;
}
regList = regList->next;
}
return true;
}
void RegPressureSchedule::CalculatePressure(DepNode &node, regno_t reg, bool def) {
RegType regType = GetRegisterType(reg);
/* if def a register, register pressure increase. */
if (def) {
node.IncPressureByIndex(regType);
} else {
/* if it is the last time using the reg, register pressure decrease. */
if (IsLastUse(node, reg)) {
node.DecPressureByIndex(regType);
}
}
}
/* update live reg information. */
void RegPressureSchedule::UpdateLiveReg(const DepNode &node, regno_t reg, bool def) {
if (def) {
if (liveReg.find(reg) == liveReg.end()) {
(void)liveReg.insert(reg);
}
/* if no use list, a register is only defined, not be used */
size_t i = 0;
for (auto defReg : node.GetDefRegnos()) {
if (defReg == reg) {
break;
}
++i;
}
if (node.GetRegDefs(i) == nullptr) {
liveReg.erase(reg);
}
} else {
if (IsLastUse(node, reg)) {
if (liveReg.find(reg) != liveReg.end()) {
liveReg.erase(reg);
}
}
}
}
/* update register pressure information. */
void RegPressureSchedule::UpdateBBPressure(const DepNode &node) {
size_t idx = 0;
for (auto ® : node.GetUseRegnos()) {
#ifdef PRESCHED_DEBUG
UpdateLiveReg(node, reg, false);
if (liveReg.find(reg) == liveReg.end()) {
++idx;
continue;
}
#endif
/* find all insn that use the reg, if a insn use the reg lastly, insn'pressure - 1 */
RegList *regList = node.GetRegUses(idx);
while (regList != nullptr) {
CHECK_NULL_FATAL(regList->insn);
DepNode *useNode = regList->insn->GetDepNode();
if (useNode->GetState() == kScheduled) {
regList = regList->next;
continue;
}
if (IsLastUse(*useNode, reg)) {
RegType regType = GetRegisterType(reg);
useNode->DecPressureByIndex(regType);
}
break;
}
++idx;
}
#ifdef PRESCHED_DEBUG
for (auto &defReg : node.GetDefRegnos()) {
UpdateLiveReg(node, defReg, true);
}
#endif
const auto &pressures = node.GetPressure();
const auto &deadDefNum = node.GetDeadDefNum();
#ifdef PRESCHED_DEBUG
LogInfo::MapleLogger() << "node's pressure: ";
for (auto pressure : pressures) {
LogInfo::MapleLogger() << pressure << " ";
}
LogInfo::MapleLogger() << "\n";
#endif
FOR_ALL_REGCLASS(i) {
curPressure[i] += pressures[i];
if (curPressure[i] > maxPressure[i]) {
maxPressure[i] = curPressure[i];
}
curPressure[i] -= deadDefNum[i];
}
}
/* update node priority and try to update the priority of all node's ancestor. */
void RegPressureSchedule::UpdatePriority(DepNode &node) {
std::vector<DepNode*> workQueue;
workQueue.emplace_back(&node);
node.SetPriority(maxPriority++);
do {
DepNode *nowNode = workQueue.front();
(void)workQueue.erase(workQueue.begin());
for (auto pred : nowNode->GetPreds()) {
DepNode &from = pred->GetFrom();
if (from.GetState() != kScheduled && from.GetPriority() < maxPriority) {
from.SetPriority(maxPriority);
workQueue.emplace_back(&from);
}
}
} while (!workQueue.empty());
}
/* return true if all node's pred has been scheduled. */
bool RegPressureSchedule::CanSchedule(const DepNode &node) const {
return node.GetValidPredsSize() == 0;
}
/*
* delete node from readylist and
* add the successor of node to readyList when
* 1. successor has no been scheduled;
* 2. successor's has been scheduled or the dependence between node and successor is true-dependence.
*/
void RegPressureSchedule::UpdateReadyList(const DepNode &node) {
/* delete node from readylist */
for (auto it = readyList.begin(); it != readyList.end(); ++it) {
if (*it == &node) {
readyList.erase(it);
break;
}
}
for (auto *succ : node.GetSuccs()) {
DepNode &succNode = succ->GetTo();
succNode.DescreaseValidPredsSize();
if (((succ->GetDepType() == kDependenceTypeTrue) || CanSchedule(succNode)) && (succNode.GetState() == kNormal)) {
readyList.emplace_back(&succNode);
succNode.SetState(kReady);
}
}
}
/* choose a node to schedule */
DepNode *RegPressureSchedule::ChooseNode() {
DepNode *node = nullptr;
for (auto *it : readyList) {
if (!it->GetIncPressure() && !it->GetHasNativeCallRegister()) {
if (CanSchedule(*it)) {
return it;
} else if (node == nullptr) {
node = it;
}
}
}
if (node == nullptr) {
node = readyList.front();
}
return node;
}
void RegPressureSchedule::DumpBBLiveInfo() const {
LogInfo::MapleLogger() << "Live In: ";
for (auto reg : bb->GetLiveInRegNO()) {
LogInfo::MapleLogger() << "R" <<reg << " ";
}
LogInfo::MapleLogger() << "\n";
LogInfo::MapleLogger() << "Live Out: ";
for (auto reg : bb->GetLiveOutRegNO()) {
LogInfo::MapleLogger() << "R" << reg << " ";
}
LogInfo::MapleLogger() << "\n";
}
void RegPressureSchedule::DumpReadyList() const {
LogInfo::MapleLogger() << "readyList: " << "\n";
for (DepNode *it : readyList) {
if (CanSchedule(*it)) {
LogInfo::MapleLogger() << it->GetInsn()->GetId() << "CS ";
} else {
LogInfo::MapleLogger() << it->GetInsn()->GetId() << "NO ";
}
}
LogInfo::MapleLogger() << "\n";
}
void RegPressureSchedule::DumpSelectInfo(const DepNode &node) const {
LogInfo::MapleLogger() << "select a node: " << "\n";
node.DumpSchedInfo();
node.DumpRegPressure();
node.GetInsn()->Dump();
LogInfo::MapleLogger() << "liveReg: ";
for (auto reg : liveReg) {
LogInfo::MapleLogger() << "R" << reg << " ";
}
LogInfo::MapleLogger() << "\n";
LogInfo::MapleLogger() << "\n";
}
void RegPressureSchedule::DumpBBPressureInfo() const {
LogInfo::MapleLogger() << "curPressure: ";
FOR_ALL_REGCLASS(i) {
LogInfo::MapleLogger() << curPressure[i] << " ";
}
LogInfo::MapleLogger() << "\n";
LogInfo::MapleLogger() << "maxPressure: ";
FOR_ALL_REGCLASS(i) {
LogInfo::MapleLogger() << maxPressure[i] << " ";
}
LogInfo::MapleLogger() << "\n";
}
void RegPressureSchedule::DoScheduling(MapleVector<DepNode*> &nodes) {
#ifdef PRESCHED_DEBUG
LogInfo::MapleLogger() << "--------------- bb " << bb->GetId() <<" begin scheduling -------------" << "\n";
DumpBBLiveInfo();
#endif
/* initialize register pressure information and readylist. */
Init(nodes);
CalculateMaxDepth(nodes);
while (!readyList.empty()) {
/* calculate register pressure */
for (DepNode *it : readyList) {
ReCalculateDepNodePressure(*it);
}
if (readyList.size() > 1) {
SortReadyList();
}
/* choose a node can be scheduled currently. */
DepNode *node = ChooseNode();
#ifdef PRESCHED_DEBUG
DumpBBPressureInfo();
DumpReadyList();
LogInfo::MapleLogger() << "first tmp select node: " << node->GetInsn()->GetId() << "\n";
#endif
while (!CanSchedule(*node)) {
UpdatePriority(*node);
SortReadyList();
node = readyList.front();
#ifdef PRESCHED_DEBUG
LogInfo::MapleLogger() << "update ready list: " << "\n";
DumpReadyList();
#endif
}
scheduledNode.emplace_back(node);
/* mark node has scheduled */
node->SetState(kScheduled);
UpdateBBPressure(*node);
CalculateNear(*node);
UpdateReadyList(*node);
#ifdef PRESCHED_DEBUG
DumpSelectInfo(*node);
#endif
}
#ifdef PRESCHED_DEBUG
LogInfo::MapleLogger() << "---------------------------------- end --------------------------------" << "\n";
#endif
/* update nodes according to scheduledNode. */
nodes.clear();
for (auto node : scheduledNode) {
nodes.emplace_back(node);
}
}
/*
* ------------- Schedule function ----------
* calculate and mark each insn id, each BB's firstLoc and lastLoc.
*/
void Schedule::InitIDAndLoc() {
uint32 id = 0;
FOR_ALL_BB(bb, &cgFunc) {
bb->SetLastLoc(bb->GetPrev() ? bb->GetPrev()->GetLastLoc() : nullptr);
FOR_BB_INSNS(insn, bb) {
insn->SetId(id++);
#if DEBUG
insn->AppendComment(" Insn id: " + std::to_string(insn->GetId()));
#endif
if (insn->IsImmaterialInsn() && !insn->IsComment()) {
bb->SetLastLoc(insn);
} else if (!bb->GetFirstLoc() && insn->IsMachineInstruction()) {
bb->SetFirstLoc(*bb->GetLastLoc());
}
}
}
}
AnalysisResult* CgDoPreScheduling::Run(CGFunc *cgFunc, CgFuncResultMgr *cgFuncResMgr) {
ASSERT(cgFunc != nullptr, "expect a cgfunc in CgDoPreScheduling");
CHECK_NULL_FATAL(cgFuncResMgr);
if (LIST_SCHED_DUMP) {
LogInfo::MapleLogger() << "Before CgDoPreScheduling : " << cgFunc->GetName() << "\n";
DotGenerator::GenerateDot("preschedule", *cgFunc, cgFunc->GetMirModule(), true);
}
auto *live = static_cast<LiveAnalysis*>(cgFuncResMgr->GetAnalysisResult(kCGFuncPhaseLIVE, cgFunc));
/* revert liveanalysis result container. */
ASSERT(live != nullptr, "nullptr check");
live->ResetLiveSet();
MemPool *scheduleMp = NewMemPool();
Schedule *schedule = nullptr;
#if TARGAARCH64
schedule = scheduleMp->New<AArch64Schedule>(*cgFunc, *scheduleMp, *live, PhaseName());
#endif
#if TARGARM32
schedule = scheduleMp->New<Arm32Schedule>(*cgFunc, *scheduleMp, *live, PhaseName());
#endif
schedule->ListScheduling(true);
live->ClearInOutDataInfo();
cgFuncResMgr->InvalidAnalysisResult(kCGFuncPhaseLIVE, cgFunc);
return nullptr;
}
AnalysisResult* CgDoScheduling::Run(CGFunc *cgFunc, CgFuncResultMgr *cgFuncResMgr) {
ASSERT(cgFunc != nullptr, "expect a cgfunc in CgDoScheduling");
CHECK_NULL_FATAL(cgFuncResMgr);
if (LIST_SCHED_DUMP) {
LogInfo::MapleLogger() << "Before CgDoScheduling : " << cgFunc->GetName() << "\n";
DotGenerator::GenerateDot("scheduling", *cgFunc, cgFunc->GetMirModule(), true);
}
auto *live = static_cast<LiveAnalysis*>(cgFuncResMgr->GetAnalysisResult(kCGFuncPhaseLIVE, cgFunc));
/* revert liveanalysis result container. */
ASSERT(live != nullptr, "nullptr check");
live->ResetLiveSet();
MemPool *scheduleMp = NewMemPool();
Schedule *schedule = nullptr;
#if TARGAARCH64
schedule = scheduleMp->New<AArch64Schedule>(*cgFunc, *scheduleMp, *live, PhaseName());
#endif
#if TARGARM32
schedule = scheduleMp->New<Arm32Schedule>(*cgFunc, *scheduleMp, *live, PhaseName());
#endif
schedule->ListScheduling(false);
live->ClearInOutDataInfo();
cgFuncResMgr->InvalidAnalysisResult(kCGFuncPhaseLIVE, cgFunc);
return nullptr;
}
} /* namespace maplebe */
| 29.780142 | 117 | 0.646761 | [
"vector"
] |
a1c4a7a78bff5fbbcf641efeeca80dac967608d7 | 6,673 | cc | C++ | sdc-plugin/clocks.cc | SymbiFlow/yosys-f4pga-plugins | d11a5751998cec71c003b612d35e45e648fc46a1 | [
"ISC"
] | 5 | 2022-02-19T07:54:56.000Z | 2022-03-15T16:38:09.000Z | sdc-plugin/clocks.cc | SymbiFlow/yosys-f4pga-plugins | d11a5751998cec71c003b612d35e45e648fc46a1 | [
"ISC"
] | 21 | 2022-02-21T13:05:24.000Z | 2022-03-30T08:34:14.000Z | sdc-plugin/clocks.cc | SymbiFlow/yosys-f4pga-plugins | d11a5751998cec71c003b612d35e45e648fc46a1 | [
"ISC"
] | 3 | 2022-02-23T03:50:55.000Z | 2022-03-09T16:32:18.000Z | /*
* Copyright 2020-2022 F4PGA Authors
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
*/
#include "clocks.h"
#include "kernel/register.h"
#include "propagation.h"
#include <cassert>
#include <cmath>
#include <regex>
void Clock::Add(const std::string &name, RTLIL::Wire *wire, float period, float rising_edge, float falling_edge, ClockType type)
{
wire->set_string_attribute(RTLIL::escape_id("CLOCK_SIGNAL"), "yes");
wire->set_bool_attribute(RTLIL::escape_id("IS_GENERATED"), type == GENERATED);
wire->set_bool_attribute(RTLIL::escape_id("IS_EXPLICIT"), type == EXPLICIT);
wire->set_bool_attribute(RTLIL::escape_id("IS_PROPAGATED"), type == PROPAGATED);
wire->set_string_attribute(RTLIL::escape_id("CLASS"), "clock");
wire->set_string_attribute(RTLIL::escape_id("NAME"), name);
wire->set_string_attribute(RTLIL::escape_id("SOURCE_WIRES"), Clock::WireName(wire));
wire->set_string_attribute(RTLIL::escape_id("PERIOD"), std::to_string(period));
std::string waveform(std::to_string(rising_edge) + " " + std::to_string(falling_edge));
wire->set_string_attribute(RTLIL::escape_id("WAVEFORM"), waveform);
}
void Clock::Add(const std::string &name, std::vector<RTLIL::Wire *> wires, float period, float rising_edge, float falling_edge, ClockType type)
{
std::for_each(wires.begin(), wires.end(), [&](RTLIL::Wire *wire) { Add(name, wire, period, rising_edge, falling_edge, type); });
}
void Clock::Add(RTLIL::Wire *wire, float period, float rising_edge, float falling_edge, ClockType type)
{
Add(Clock::WireName(wire), wire, period, rising_edge, falling_edge, type);
}
float Clock::Period(RTLIL::Wire *clock_wire)
{
if (!clock_wire->has_attribute(RTLIL::escape_id("PERIOD"))) {
log_cmd_error("PERIOD has not been specified on wire '%s'.\n", WireName(clock_wire).c_str());
}
float period(0);
std::string period_str;
try {
period_str = clock_wire->get_string_attribute(RTLIL::escape_id("PERIOD"));
period = std::stof(period_str);
} catch (const std::invalid_argument &e) {
log_cmd_error("Incorrect value '%s' specifed on PERIOD attribute for wire "
"'%s'.\nPERIOD needs to be a float value.\n",
period_str.c_str(), WireName(clock_wire).c_str());
}
return period;
}
std::pair<float, float> Clock::Waveform(RTLIL::Wire *clock_wire)
{
if (!clock_wire->has_attribute(RTLIL::escape_id("WAVEFORM"))) {
float period(Period(clock_wire));
if (!period) {
log_cmd_error("Neither PERIOD nor WAVEFORM has been specified for wire %s\n", WireName(clock_wire).c_str());
return std::make_pair(0, 0);
}
float falling_edge = period / 2;
log_warning("Waveform has not been specified on wire '%s'.\nDefault value {0 %f} "
"will be used\n",
WireName(clock_wire).c_str(), falling_edge);
return std::make_pair(0, falling_edge);
}
float rising_edge(0);
float falling_edge(0);
std::string waveform(clock_wire->get_string_attribute(RTLIL::escape_id("WAVEFORM")));
if (std::sscanf(waveform.c_str(), "%f %f", &rising_edge, &falling_edge) != 2) {
log_cmd_error("Incorrect value '%s' specifed on WAVEFORM attribute for wire "
"'%s'.\nWAVEFORM needs to be specified in form of '<rising_edge> "
"<falling_edge>' where the edge values are floats.\n",
waveform.c_str(), WireName(clock_wire).c_str());
}
return std::make_pair(rising_edge, falling_edge);
}
float Clock::RisingEdge(RTLIL::Wire *clock_wire) { return Waveform(clock_wire).first; }
float Clock::FallingEdge(RTLIL::Wire *clock_wire) { return Waveform(clock_wire).second; }
std::string Clock::Name(RTLIL::Wire *clock_wire)
{
if (clock_wire->has_attribute(RTLIL::escape_id("NAME"))) {
return clock_wire->get_string_attribute(RTLIL::escape_id("NAME"));
}
return WireName(clock_wire);
}
std::string Clock::WireName(RTLIL::Wire *clock_wire)
{
if (!clock_wire) {
return std::string();
}
return AddEscaping(RTLIL::unescape_id(clock_wire->name));
}
std::string Clock::SourceWireName(RTLIL::Wire *clock_wire)
{
if (clock_wire->has_attribute(RTLIL::escape_id("SOURCE_WIRES"))) {
return clock_wire->get_string_attribute(RTLIL::escape_id("SOURCE_WIRES"));
}
return Name(clock_wire);
}
bool Clock::GetClockWireBoolAttribute(RTLIL::Wire *wire, const std::string &attribute_name)
{
if (wire->has_attribute(RTLIL::escape_id(attribute_name))) {
return wire->get_bool_attribute(RTLIL::escape_id(attribute_name));
}
return false;
}
const std::map<std::string, RTLIL::Wire *> Clocks::GetClocks(RTLIL::Design *design)
{
std::map<std::string, RTLIL::Wire *> clock_wires;
RTLIL::Module *top_module = design->top_module();
for (auto &wire_obj : top_module->wires_) {
auto &wire = wire_obj.second;
if (wire->has_attribute(RTLIL::escape_id("CLOCK_SIGNAL"))) {
if (wire->get_string_attribute(RTLIL::escape_id("CLOCK_SIGNAL")) == "yes") {
clock_wires.insert(std::make_pair(Clock::WireName(wire), wire));
}
}
}
return clock_wires;
}
void Clocks::UpdateAbc9DelayTarget(RTLIL::Design *design)
{
std::map<std::string, RTLIL::Wire *> clock_wires = Clocks::GetClocks(design);
for (auto &clock_wire : clock_wires) {
auto &wire = clock_wire.second;
float period = Clock::Period(wire);
// Set the ABC9 delay to the shortest clock period in the design.
//
// By convention, delays in Yosys are in picoseconds, but ABC9 has
// no information on interconnect delay, so target half the specified
// clock period to give timing slack; otherwise ABC9 may produce a
// mapping that cannot meet the specified clock.
int abc9_delay = design->scratchpad_get_int("abc9.D", INT32_MAX);
int period_ps = period * 1000.0 / 2.0;
design->scratchpad_set_int("abc9.D", std::min(abc9_delay, period_ps));
}
}
| 40.93865 | 143 | 0.671812 | [
"vector"
] |
a1c61c4b5a2566f87f8f3752077720269c1e5271 | 161 | cpp | C++ | src/csapex_core/src/model/graph_facade.cpp | ICRA-2018/csapex | 8ee83b9166d0281a4923184cce67b4a55f273ea2 | [
"BSD-3-Clause"
] | 21 | 2016-09-02T15:33:25.000Z | 2021-06-10T06:34:39.000Z | src/csapex_core/src/model/graph_facade.cpp | ICRA-2018/csapex | 8ee83b9166d0281a4923184cce67b4a55f273ea2 | [
"BSD-3-Clause"
] | null | null | null | src/csapex_core/src/model/graph_facade.cpp | ICRA-2018/csapex | 8ee83b9166d0281a4923184cce67b4a55f273ea2 | [
"BSD-3-Clause"
] | 10 | 2016-10-12T00:55:17.000Z | 2020-04-24T19:59:02.000Z | /// HEADER
#include <csapex/model/graph_facade.h>
using namespace csapex;
GraphFacade::GraphFacade()
{
}
GraphFacade::~GraphFacade()
{
stopObserving();
}
| 11.5 | 38 | 0.708075 | [
"model"
] |
a1c6ca8ec91d00ddb48844195a773924c14f973e | 8,493 | cpp | C++ | src/04-cross-platform-hello-triangle/src/OpenGLRenderer.cpp | alaingalvan/CrossWindow-Demos | dd5f9d752ebe460f5daa10b3a8b63ff7a43a81c5 | [
"MIT"
] | 41 | 2018-10-08T20:40:56.000Z | 2022-03-18T00:36:27.000Z | src/04-cross-platform-hello-triangle/src/OpenGLRenderer.cpp | alaingalvan/CrossWindow-Demos | dd5f9d752ebe460f5daa10b3a8b63ff7a43a81c5 | [
"MIT"
] | null | null | null | src/04-cross-platform-hello-triangle/src/OpenGLRenderer.cpp | alaingalvan/CrossWindow-Demos | dd5f9d752ebe460f5daa10b3a8b63ff7a43a81c5 | [
"MIT"
] | 3 | 2019-07-30T07:24:08.000Z | 2021-11-22T06:26:50.000Z | #include <glad/glad.h>
#include "Renderer.h"
Renderer::Renderer(xwin::Window& window)
{
xwin::WindowDesc desc = window.getDesc();
mWidth = clamp(desc.width, 1u, 0xffffu);
mHeight = clamp(desc.height, 1u, 0xffffu);
initializeAPI(window);
initializeResources();
setupCommands();
tStart = std::chrono::high_resolution_clock::now();
}
Renderer::~Renderer()
{
destroyFrameBuffer();
destroyResources();
destroyAPI();
}
void Renderer::initializeAPI(xwin::Window& window)
{
xgfx::OpenGLDesc ogldesc;
mOGLState = xgfx::createContext(&window, ogldesc);
xgfx::setContext(mOGLState);
if (!gladLoadGL())
{
// Failed
std::cout << "Failed to load OpenGL.";
return;
}
#if defined(_DEBUG)
GLenum err = glGetError();
if (err != GL_NO_ERROR)
{
std::cout << "Error loading OpenGL.";
}
#endif
}
void Renderer::destroyAPI()
{
xgfx::unsetContext(mOGLState);
xgfx::destroyContext(mOGLState);
}
void Renderer::initializeResources()
{
// OpenGL global setup
glClearColor(0.2f, 0.2f, 0.2f, 1.0f);
glEnable(GL_DEPTH_TEST);
glGenVertexArrays(1, &mVertexArray);
glBindVertexArray(mVertexArray);
glEnableVertexAttribArray(0);
auto checkShaderCompilation = [&](GLuint shader)
{
#if defined(_DEBUG)
GLint isCompiled = 0;
glGetShaderiv(shader, GL_COMPILE_STATUS, &isCompiled);
if (isCompiled == GL_FALSE)
{
GLint maxLength = 0;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &maxLength);
std::vector<char> errorLog(maxLength);
glGetShaderInfoLog(shader, maxLength, &maxLength, &errorLog[0]);
glDeleteShader(shader);
std::cout << errorLog.data();
return false;
}
#endif
return true;
};
std::vector<char> vertShaderCode = readFile("assets/shaders/triangle.vert.glsl");
GLchar* vertStr = vertShaderCode.data();
GLint vertLen = static_cast<GLint>(vertShaderCode.size());
std::vector<char> fragShaderCode = readFile("assets/shaders/triangle.frag.glsl");
GLchar* fragStr = fragShaderCode.data();
GLint fragLen = static_cast<GLint>(fragShaderCode.size());
mVertexShader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(mVertexShader, 1, &vertStr, &vertLen);
glCompileShader(mVertexShader);
if (!checkShaderCompilation(mVertexShader)) return;
mFragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(mFragmentShader, 1, &fragStr, &fragLen);
glCompileShader(mFragmentShader);
if (!checkShaderCompilation(mFragmentShader)) return;
mProgram = glCreateProgram();
glAttachShader(mProgram, mVertexShader);
glAttachShader(mProgram, mFragmentShader);
glLinkProgram(mProgram);
GLint result = 0;
glGetProgramiv(mProgram, GL_LINK_STATUS, &result);
#if defined(_DEBUG)
if (result != GL_TRUE) {
std::cout << "Program failed to link.";
return;
}
#endif
glUseProgram(mProgram);
glGenBuffers(1, &mVertexBuffer);
glGenBuffers(1, &mIndexBuffer);
glBindBuffer(GL_ARRAY_BUFFER, mVertexBuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mIndexBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(Vertex) * 3, mVertexBufferData, GL_STATIC_DRAW);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned int) * 3, mIndexBufferData, GL_STATIC_DRAW);
mPositionAttrib = glGetAttribLocation(mProgram, "inPos");
mColorAttrib = glGetAttribLocation(mProgram, "inColor");
glEnableVertexAttribArray(mPositionAttrib);
glEnableVertexAttribArray(mColorAttrib);
glVertexAttribPointer(mPositionAttrib, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, position));
glVertexAttribPointer(mColorAttrib, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, color));
GLuint matrixBlockIndex = glGetUniformBlockIndex(mProgram, "UBO");
glUniformBlockBinding(mProgram, matrixBlockIndex, 0);
glGenBuffers(1, &mUniformUBO);
glBindBuffer(GL_UNIFORM_BUFFER, mUniformUBO);
glBufferData(GL_UNIFORM_BUFFER, sizeof(uboVS), &uboVS, GL_DYNAMIC_DRAW);
glBindBufferRange(GL_UNIFORM_BUFFER, 0, mUniformUBO, 0, sizeof(uboVS));
// Update Uniforms
uboVS.projectionMatrix = Matrix4::perspective(45.0f, (float)1280 / (float)720, 0.01f, 1024.0f);
uboVS.viewMatrix = Matrix4::translation(Vector3(0.0f, 0.0f, -2.5f)) * Matrix4::rotationZ(3.14f);
uboVS.modelMatrix = Matrix4::identity();
GLvoid* p = glMapBuffer(GL_UNIFORM_BUFFER, GL_WRITE_ONLY);
memcpy(p, &uboVS, sizeof(uboVS));
glUnmapBuffer(GL_UNIFORM_BUFFER);
}
void Renderer::destroyResources()
{
glDisableVertexAttribArray(mPositionAttrib);
glDisableVertexAttribArray(mColorAttrib);
glDeleteShader(mVertexShader);
glDeleteShader(mFragmentShader);
glDeleteProgram(mProgram);
glDeleteVertexArrays(1, &mVertexArray);
glDeleteBuffers(1, &mVertexBuffer);
glDeleteBuffers(1, &mIndexBuffer);
glDeleteBuffers(1, &mUniformUBO);
}
void Renderer::render()
{
// Framelimit set to 60 fps
tEnd = std::chrono::high_resolution_clock::now();
float time = std::chrono::duration<float, std::milli>(tEnd - tStart).count();
if (time < (1000.0f / 60.0f))
{
return;
}
tStart = std::chrono::high_resolution_clock::now();
xgfx::swapBuffers(mOGLState);
// Update Uniforms
mElapsedTime += 0.001f * time;
mElapsedTime = fmodf(mElapsedTime, 6.283185307179586f);
uboVS.modelMatrix = Matrix4::rotationY(mElapsedTime);
GLvoid* p = glMapBuffer(GL_UNIFORM_BUFFER, GL_WRITE_ONLY);
memcpy(p, &uboVS, sizeof(uboVS));
glUnmapBuffer(GL_UNIFORM_BUFFER);
// Draw
glBindFramebuffer(GL_FRAMEBUFFER, mFrameBuffer);
glViewport(0, 0, mWidth, mHeight);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glDrawElements(GL_TRIANGLES, 3, GL_UNSIGNED_INT, 0);
// Blit framebuffer to window
glBindFramebuffer(GL_READ_FRAMEBUFFER, mFrameBuffer);
glReadBuffer(GL_COLOR_ATTACHMENT0);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
glViewport(0, 0, mWidth, mHeight);
glBlitFramebuffer(0, 0, mWidth, mHeight, 0, 0, mWidth, mHeight, GL_COLOR_BUFFER_BIT, GL_NEAREST);
}
void Renderer::resize(unsigned width, unsigned height)
{
mWidth = clamp(width, 1u, 0xffffu);
mHeight = clamp(height, 1u, 0xffffu);
// Update Unforms
uboVS.projectionMatrix = Matrix4::perspective(45.0f, static_cast<float>(mWidth) / static_cast<float>(mHeight), 0.01f, 1024.0f);
GLvoid* p = glMapBuffer(GL_UNIFORM_BUFFER, GL_WRITE_ONLY);
memcpy(p, &uboVS, sizeof(uboVS));
glUnmapBuffer(GL_UNIFORM_BUFFER);
destroyFrameBuffer();
initFrameBuffer();
}
void Renderer::initFrameBuffer()
{
glGenTextures(1, &mFrameBufferTex);
glBindTexture(GL_TEXTURE_2D, mFrameBufferTex);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, mWidth, mHeight, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL);
glBindTexture(GL_TEXTURE_2D, 0);
glGenRenderbuffers(1, &mRenderBufferDepth);
glBindRenderbuffer(GL_RENDERBUFFER, mRenderBufferDepth);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, mWidth, mHeight);
glGenFramebuffers(1, &mFrameBuffer);
glBindFramebuffer(GL_FRAMEBUFFER, mFrameBuffer);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, mFrameBufferTex, 0);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, mRenderBufferDepth);
GLenum DrawBuffers[1] = { GL_COLOR_ATTACHMENT0 };
glDrawBuffers(1, DrawBuffers);
#if defined(_DEBUG)
GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
if (status != GL_FRAMEBUFFER_COMPLETE)
{
std::cout << "Frame Buffer Failed to be Created!";
}
#endif
glBindFramebuffer(GL_FRAMEBUFFER, mFrameBuffer);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
void Renderer::destroyFrameBuffer()
{
glDeleteTextures(1, &mFrameBufferTex);
glDeleteRenderbuffers(1, &mRenderBufferDepth);
glDeleteFramebuffers(1, &mFrameBuffer);
}
/**
* While most modern graphics APIs have a swapchains, command queue, sync, and render passes, OpenGL does not.
* OpenGL does have frame buffers, but it creates one by default.
* So these functions are just stubs:
*/
void Renderer::setupSwapchain(unsigned width, unsigned height)
{
// Driver sets up swapchain
}
void Renderer::createCommands()
{
// Driver creates commands in OpenGL, you just set state
}
void Renderer::setupCommands()
{
// Driver creates commands in OpenGL, you just set state
}
void Renderer::destroyCommands()
{
// Driver destroys commands
}
void Renderer::createRenderPass()
{
// Render passes exist at the driver level
}
void Renderer::createSynchronization()
{
// Driver handles sync
}
| 29.489583 | 128 | 0.765572 | [
"render",
"vector"
] |
a1d5b7f6bd22bc074eabaeb9a6d5a4ecdd59f0bc | 2,062 | cxx | C++ | templates/ws/src/clan/utils.cxx | roadnarrows-robotics/rnmake | 6446cda6b36d66f6ee945db128a052caaf9c89ee | [
"MIT"
] | null | null | null | templates/ws/src/clan/utils.cxx | roadnarrows-robotics/rnmake | 6446cda6b36d66f6ee945db128a052caaf9c89ee | [
"MIT"
] | null | null | null | templates/ws/src/clan/utils.cxx | roadnarrows-robotics/rnmake | 6446cda6b36d66f6ee945db128a052caaf9c89ee | [
"MIT"
] | null | null | null |
/*! \file
*
* \brief Languages spoken back in the day.
*
* \pkgfile{@FILENAME@}
* \pkgcomponent{Application,clan}
* \author @PKG_AUTHOR@
*
* \LegalBegin
* @PKG_LICENSE@
* \LegalEnd
*/
#include <string>
#include <vector>
#include <chrono>
#include <iostream>
#include <iomanip>
#include "utils.h"
namespace clan
{
static const std::string WHITESPACE = " \n\r\t\f\v";
std::string ltrim(const std::string& s)
{
size_t start = s.find_first_not_of(WHITESPACE);
return (start == std::string::npos) ? "" : s.substr(start);
}
std::string rtrim(const std::string& s)
{
size_t end = s.find_last_not_of(WHITESPACE);
return (end == std::string::npos) ? "" : s.substr(0, end + 1);
}
std::string trim(const std::string& s)
{
return rtrim(ltrim(s));
}
void print_vec(const StrVec &vec, int indent0, int indent1, int elems)
{
int indent = indent0;
int rem;
int eol = elems - 1;
for(size_t i=0; i<vec.size(); ++i)
{
rem = i % elems;
if( rem == 0 )
{
std::cout << std::setw(indent) << "" << std::setw(0);
}
std::cout << "'" << vec[i] << "' ";
if( rem == eol )
{
std::cout << std::endl;
indent = indent1;
}
}
if( rem != eol )
{
std::cout << std::endl;
}
}
void print_vec(const IntVec &vec, int indent0, int indent1, int elems)
{
int indent = indent0;
int rem;
int eol = elems - 1;
for(size_t i=0; i<vec.size(); ++i)
{
rem = i % elems;
if( rem == 0 )
{
std::cout << std::setw(indent) << "" << std::setw(0);
}
std::cout << vec[i] << " ";
if( rem == eol )
{
std::cout << std::endl;
indent = indent1;
}
}
if( rem != eol )
{
std::cout << std::endl;
}
}
unsigned rng_seed()
{
std::chrono::system_clock::time_point tp = std::chrono::system_clock::now();
std::chrono::system_clock::duration tse = tp.time_since_epoch();
return (unsigned)tse.count();
}
} // namespace clan
| 19.826923 | 80 | 0.532493 | [
"vector"
] |
a1d64d09c65f29824adcbe4bcc979e5d25a98a4c | 3,528 | hpp | C++ | include/mtx/requests.hpp | christarazi/matrix-structs | a84b37215ead77620dcddc0789c4b9b443757a17 | [
"Unlicense"
] | null | null | null | include/mtx/requests.hpp | christarazi/matrix-structs | a84b37215ead77620dcddc0789c4b9b443757a17 | [
"Unlicense"
] | null | null | null | include/mtx/requests.hpp | christarazi/matrix-structs | a84b37215ead77620dcddc0789c4b9b443757a17 | [
"Unlicense"
] | null | null | null | #pragma once
#include <string>
#include <json.hpp>
using json = nlohmann::json;
namespace mtx {
namespace requests {
//! Whether or not the room will be visible by non members.
enum class Visibility
{
//! A private visibility will hide the room from the published room list.
Private,
//! Indicates that the room will be shown in the published room list
Public,
};
//! Convenience parameter for setting various default state events based on a preset.
enum class Preset
{
//! `join_rules` is set to `invite`. `history_visibility` is set to `shared`.
PrivateChat,
//! `join_rules` is set to `public`. `history_visibility` is set to `shared`.
PublicChat,
//! `join_rules` is set to `invite`. `history_visibility` is set to `shared`.
//! All invitees are given the same power level as the room creator.
TrustedPrivateChat,
};
//! Request payload for the `POST /_matrix/client/r0/createRoom` endpoint.
struct CreateRoom
{
//! If this is included, an `m.room.name` event will
//! be sent into the room to indicate the name of the room.
std::string name;
//! If this is included, an `m.room.topic` event will be sent
//! into the room to indicate the topic for the room.
std::string topic;
//! The desired room alias local part. e.g `#foo:example.com`.
std::string room_alias_name;
//! A list of user IDs to invite to the room.
std::vector<std::string> invite;
//! This flag makes the server set the is_direct flag on the
//! `m.room.member` events sent to the users in @p invite and @p invite_3pid.
bool is_direct = false;
//! Convenience parameter for setting various default state events.
Preset preset = Preset::PrivateChat;
//! Whether or not the room will be visible by non members.
Visibility visibility = Visibility::Private;
};
void
to_json(json &obj, const CreateRoom &request);
//! Request payload for the `POST /_matrix/client/r0/login` endpoint.
struct Login
{
//! The login type being used. One of ["m.login.password", "m.login.token"]
std::string type = "m.login.password";
//! The fully qualified user ID or just local part of the user ID, to log in.
std::string user;
//! When logging in using a third party identifier, the medium of the identifier.
//! Must be 'email'.
std::string medium;
//! Third party identifier for the user.
std::string address;
//! Required when type is m.login.token. The login token.
std::string token;
//! Required when type is m.login.password. The user's password.
std::string password;
//! ID of the client device. If this does not correspond to a known client device,
//! a new device will be created.
//! The server will auto-generate a device_id if this is not specified.
std::string device_id;
//! A display name to assign to the newly-created device.
//! Ignored if device_id corresponds to a known device.
std::string initial_device_display_name;
};
void
to_json(json &obj, const Login &request);
//! Request payload for the `POST /_matrix/client/r0/profile/{userId}/displayname` endpoint.
struct DisplayName
{
std::string displayname;
};
void
to_json(json &obj, const DisplayName &request);
struct Empty
{};
void
to_json(json &obj, const Empty &);
using Logout = Empty;
}
}
| 33.923077 | 92 | 0.652494 | [
"vector"
] |
a1dc96d94e1aab1118e1028f949190f1bdf95e4c | 634 | cpp | C++ | ctest/grid.cpp | TenniS-Open/omega | 4d8b26250def9ef3f9191c0b401b35c0b7d83b82 | [
"BSD-2-Clause"
] | null | null | null | ctest/grid.cpp | TenniS-Open/omega | 4d8b26250def9ef3f9191c0b401b35c0b7d83b82 | [
"BSD-2-Clause"
] | null | null | null | ctest/grid.cpp | TenniS-Open/omega | 4d8b26250def9ef3f9191c0b401b35c0b7d83b82 | [
"BSD-2-Clause"
] | null | null | null | //
// Created by kier on 2020/7/23.
//
#include "ohm/grid.h"
#include "ohm/range.h"
#include "ohm/print.h"
#include "ohm/type.h"
#include <vector>
#include <string>
#include <map>
int main() {
using namespace ohm;
auto a = range(4);
std::vector<std::string> b = {"a", "b", "c"};
std::map<float, std::string> c = {{1.f, "1"}, {2.f, "2"}};
println(classname<decltype(grid(a, b, c))::value_type>());
println(classname<decltype(grided(a, b, c))::value_type>());
for (auto i : grid(a, b, c)) {
println(i);
}
for (auto i : grided(a, b, c)) {
println(i);
}
println();
}
| 17.135135 | 64 | 0.541009 | [
"vector"
] |
a1de03686dcebbde7bd801e76efc77ef75bb9df8 | 1,064 | cpp | C++ | backup/2/leetcode/c++/container-with-most-water.cpp | yangyanzhan/code-camp | 4272564e916fc230a4a488f92ae32c07d355dee0 | [
"Apache-2.0"
] | 21 | 2019-11-16T19:08:35.000Z | 2021-11-12T12:26:01.000Z | backup/2/leetcode/c++/container-with-most-water.cpp | yangyanzhan/code-camp | 4272564e916fc230a4a488f92ae32c07d355dee0 | [
"Apache-2.0"
] | 1 | 2022-02-04T16:02:53.000Z | 2022-02-04T16:02:53.000Z | backup/2/leetcode/c++/container-with-most-water.cpp | yangyanzhan/code-camp | 4272564e916fc230a4a488f92ae32c07d355dee0 | [
"Apache-2.0"
] | 4 | 2020-05-15T19:39:41.000Z | 2021-10-30T06:40:31.000Z | // Hi, I'm Yanzhan. For more algothmic problems, visit my Youtube Channel (Yanzhan Yang's Youtube Channel) : https://www.youtube.com/channel/UCDkz-__gl3frqLexukpG0DA?view_as=subscriber or my Twitter Account (Yanzhan Yang's Twitter) : https://twitter.com/YangYanzhan or my GitHub HomePage (Yanzhan Yang's GitHub HomePage) : https://yanzhan.site .
// For this specific algothmic problem, visit my Youtube Video : .
// It's fascinating to solve algothmic problems, follow Yanzhan to learn more!
// Blog URL for this problem: https://yanzhan.site/leetcode/container-with-most-water.html .
using namespace std;
class Solution {
public:
int maxArea(vector<int> &height) {
int start = 0, end = height.size() - 1;
int res = 0;
while (start < end) {
int h1 = height[start], h2 = height[end];
int area = (end - start) * min(h1, h2);
res = max(res, area);
if (h1 <= h2) {
start++;
} else {
end--;
}
}
return res;
}
};
| 40.923077 | 345 | 0.607143 | [
"vector"
] |
a1e30460f7265e846fd76ca1f0c4f12c76e51b38 | 4,579 | cpp | C++ | ProcessLib/LocalAssemblerInterface.cpp | lkqhvac/ogs6 | f47008c5955fb445d6a7d8bcfdaebe66566b3819 | [
"BSD-3-Clause"
] | 1 | 2021-01-13T01:58:38.000Z | 2021-01-13T01:58:38.000Z | ProcessLib/LocalAssemblerInterface.cpp | lkqhvac/ogs6 | f47008c5955fb445d6a7d8bcfdaebe66566b3819 | [
"BSD-3-Clause"
] | null | null | null | ProcessLib/LocalAssemblerInterface.cpp | lkqhvac/ogs6 | f47008c5955fb445d6a7d8bcfdaebe66566b3819 | [
"BSD-3-Clause"
] | 1 | 2021-04-08T08:14:08.000Z | 2021-04-08T08:14:08.000Z | /**
* \file
* \copyright
* Copyright (c) 2012-2020, OpenGeoSys Community (http://www.opengeosys.org)
* Distributed under a Modified BSD License.
* See accompanying file LICENSE.txt or
* http://www.opengeosys.org/project/license
*
*/
#include "LocalAssemblerInterface.h"
#include <cassert>
#include "NumLib/DOF/DOFTableUtil.h"
#include "CoupledSolutionsForStaggeredScheme.h"
namespace ProcessLib
{
void LocalAssemblerInterface::assemble(
double const /*t*/,
double const /*dt*/,
std::vector<double> const& /*local_x*/,
std::vector<double> const& /*local_xdot*/,
std::vector<double>& /*local_M_data*/,
std::vector<double>& /*local_K_data*/,
std::vector<double>& /*local_b_data*/)
{
OGS_FATAL(
"The assemble() function is not implemented in the local assembler.");
}
void LocalAssemblerInterface::assembleForStaggeredScheme(
double const /*t*/, double const /*dt*/, Eigen::VectorXd const& /*local_x*/,
Eigen::VectorXd const& /*local_xdot*/, int const /*process_id*/,
std::vector<double>& /*local_M_data*/,
std::vector<double>& /*local_K_data*/,
std::vector<double>& /*local_b_data*/)
{
OGS_FATAL(
"The assembleForStaggeredScheme() function is not implemented in the "
"local assembler.");
}
void LocalAssemblerInterface::assembleWithJacobian(
double const /*t*/, double const /*dt*/,
std::vector<double> const& /*local_x*/,
std::vector<double> const& /*local_xdot*/, const double /*dxdot_dx*/,
const double /*dx_dx*/, std::vector<double>& /*local_M_data*/,
std::vector<double>& /*local_K_data*/,
std::vector<double>& /*local_b_data*/,
std::vector<double>& /*local_Jac_data*/)
{
OGS_FATAL(
"The assembleWithJacobian() function is not implemented in the local "
"assembler.");
}
void LocalAssemblerInterface::assembleWithJacobianForStaggeredScheme(
double const /*t*/, double const /*dt*/, Eigen::VectorXd const& /*local_x*/,
Eigen::VectorXd const& /*local_xdot*/, const double /*dxdot_dx*/,
const double /*dx_dx*/, int const /*process_id*/,
std::vector<double>& /*local_M_data*/,
std::vector<double>& /*local_K_data*/,
std::vector<double>& /*local_b_data*/,
std::vector<double>& /*local_Jac_data*/)
{
OGS_FATAL(
"The assembleWithJacobianForStaggeredScheme() function is not implemented in"
" the local assembler.");
}
void LocalAssemblerInterface::computeSecondaryVariable(
std::size_t const mesh_item_id,
NumLib::LocalToGlobalIndexMap const& dof_table, double const t,
double const dt, GlobalVector const& x, GlobalVector const& x_dot)
{
auto const indices = NumLib::getIndices(mesh_item_id, dof_table);
auto const local_x = x.get(indices);
auto const local_x_dot = x_dot.get(indices);
computeSecondaryVariableConcrete(t, dt, local_x, local_x_dot);
}
void LocalAssemblerInterface::setInitialConditions(
std::size_t const mesh_item_id,
NumLib::LocalToGlobalIndexMap const& dof_table, GlobalVector const& x,
double const t)
{
auto const indices = NumLib::getIndices(mesh_item_id, dof_table);
auto const local_x = x.get(indices);
setInitialConditionsConcrete(local_x, t);
}
void LocalAssemblerInterface::initialize(
std::size_t const /*mesh_item_id*/,
NumLib::LocalToGlobalIndexMap const& /*dof_table*/)
{
initializeConcrete();
}
void LocalAssemblerInterface::preTimestep(
std::size_t const mesh_item_id,
NumLib::LocalToGlobalIndexMap const& dof_table, GlobalVector const& x,
double const t, double const delta_t)
{
auto const indices = NumLib::getIndices(mesh_item_id, dof_table);
auto const local_x = x.get(indices);
preTimestepConcrete(local_x, t, delta_t);
}
void LocalAssemblerInterface::postTimestep(
std::size_t const mesh_item_id,
NumLib::LocalToGlobalIndexMap const& dof_table, GlobalVector const& x,
double const t, double const dt)
{
auto const indices = NumLib::getIndices(mesh_item_id, dof_table);
auto const local_x = x.get(indices);
postTimestepConcrete(local_x, t, dt);
}
void LocalAssemblerInterface::postNonLinearSolver(
std::size_t const mesh_item_id,
NumLib::LocalToGlobalIndexMap const& dof_table, GlobalVector const& x,
double const t, double const dt, bool const use_monolithic_scheme)
{
auto const indices = NumLib::getIndices(mesh_item_id, dof_table);
auto const local_x = x.get(indices);
postNonLinearSolverConcrete(local_x, t, dt, use_monolithic_scheme);
}
} // namespace ProcessLib
| 33.918519 | 85 | 0.704739 | [
"vector"
] |
a1e952740ea17b03f6484eeddb4d0cffb010b086 | 825 | cpp | C++ | test/containers/sequences/vector.bool/construct_size.pass.cpp | caiohamamura/libcxx | 27c836ff3a9c505deb9fd1616012924de8ff9279 | [
"MIT"
] | 187 | 2015-02-28T11:50:45.000Z | 2022-02-20T12:51:00.000Z | test/containers/sequences/vector.bool/construct_size.pass.cpp | caiohamamura/libcxx | 27c836ff3a9c505deb9fd1616012924de8ff9279 | [
"MIT"
] | 2 | 2019-06-24T20:44:59.000Z | 2020-06-17T18:41:35.000Z | test/containers/sequences/vector.bool/construct_size.pass.cpp | caiohamamura/libcxx | 27c836ff3a9c505deb9fd1616012924de8ff9279 | [
"MIT"
] | 80 | 2015-01-02T12:44:41.000Z | 2022-01-20T15:37:54.000Z | //===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// <vector>
// vector<bool>
// explicit vector(size_type n);
#include <vector>
#include <cassert>
template <class C>
void
test(typename C::size_type n)
{
C c(n);
assert(c.__invariants());
assert(c.size() == n);
assert(c.get_allocator() == typename C::allocator_type());
for (typename C::const_iterator i = c.cbegin(), e = c.cend(); i != e; ++i)
assert(*i == typename C::value_type());
}
int main()
{
test<std::vector<bool> >(50);
}
| 24.264706 | 80 | 0.495758 | [
"vector"
] |
a1fb86eb149c68d2a64403389fbb1a2f90f32db2 | 15,432 | cpp | C++ | src/OdometerMain.cpp | morynicz/vision-of-movement | c413f956a181253da98da31f8f60fdb3f2ddd51f | [
"MIT"
] | 5 | 2015-09-28T22:21:59.000Z | 2021-01-19T16:16:51.000Z | src/OdometerMain.cpp | morynicz/vision-of-movement | c413f956a181253da98da31f8f60fdb3f2ddd51f | [
"MIT"
] | null | null | null | src/OdometerMain.cpp | morynicz/vision-of-movement | c413f956a181253da98da31f8f60fdb3f2ddd51f | [
"MIT"
] | 3 | 2015-07-14T18:29:10.000Z | 2022-03-14T06:36:49.000Z | /**
* \author Michał Orynicz
*/
#include "VisualOdometer.hpp"
#include "BirdsEyeTranslationReader.hpp"
#include "TangentRotationReader.hpp"
#include "SmoothFilter.hpp"
#include "TrimHistoryFilter.hpp"
#include "LucasKanadePyramidTracker.hpp"
#include "ShiThomasiFeatureExtractor.hpp"
#include "PreparationFunctions.hpp"
#include "ConvenienceFunctions.hpp"
#include "ErrorCodes.hpp"
#include "DrawingFunctions.hpp"
#include "Catcher.hpp"
#include "CvTypesIo.hpp"
#include "CommandlineParameters.hpp"
#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/calib3d/calib3d.hpp"
#include <boost/program_options.hpp>
#include <boost/date_time.hpp>
#include <string>
#include <vector>
#include <ctime>
using std::cerr;
using std::endl;
void processInput(const cv::Mat &input,
const std::vector<cv::Mat> &rectifyMaps,
std::list<cv::Point3f> &positions, VisualOdometer &odo,
std::list<long long int> ×tamps,
const boost::posix_time::ptime &milenium,
const int &verbosity, const CameraSpatialParameters &spatial,
const cv::Size &imageSize, const std::string &mainWindowName,
const std::string &mapWindowName);
VisualOdometer getVisualOdometer(cv::VideoCapture &capture,
const ShiThomasiParameters &shiThomasi,
const LucasKanadeParameters &lucasKanade,
const ChessboardParameters &chessboard,
CameraSpatialParameters &spatial,
const std::string &cameraParametersFilename,
const std::string &cameraSpatialFilename,
const int &maxHistoryLength, const int &maxDeviation,
const int &maxDeviants, const int &minLength,
const int &maxLength, const int &upperMargin,
const int &lowerMargin, const int & maxFeaturesUpper,
const int & maxFeaturesLower,
std::vector<cv::Mat> &rectifyMaps, cv::Size &imageSize,
std::list<cv::Point3f> &positions,
const cv::Mat &cameraMatrix,
const cv::Mat &distortionCoefficients,
void (*parametersCalibration)(cv::VideoCapture &capture,
std::vector<cv::Mat> rectifyMaps, int &horizon,
int &deadZone, const cv::Size &imageSize));
void printTrajectory(const std::string &matlabFilename,
const std::list<long long int> ×tamps,
const std::list<cv::Point3f> &positions);
int main(int argc, char **argv) {
ShiThomasiParameters shiThomasi;
LucasKanadeParameters lucasKanade;
ChessboardParameters chessboard;
CameraSpatialParameters spatial;
int maxFeaturesUpper = 100;
int maxFeaturesLower = 100;
int maxHistoryLength = 8;
double maxDeviation = CV_PI / 16;
double maxDeviants = 0.9;
double minLength = 10;
double maxLength = 50;
double upperMargin = 30;
double lowerMargin = 30;
spatial.horizon = -1;
spatial.deadZone = -1;
int captureDeviceNumber = 1;
int verbosity = 0;
std::string cameraParametersFilename;
std::string matlabFilename, cameraSpatialFilename;
std::vector<cv::Mat> rectifyMaps;
cv::Size imageSize;
std::list<cv::Point3f> positions;
std::list<long long int> timestamps;
cv::Point3f currentPosition(0, 0, 0);
Catcher capture;
cv::Mat cameraMatrix, distortionCoefficients;
try {
readParametersCommandLine(argc, argv, shiThomasi, lucasKanade,
chessboard, spatial, maxFeaturesUpper,
maxFeaturesLower, maxHistoryLength, upperMargin,
lowerMargin, captureDeviceNumber, verbosity,
cameraParametersFilename, matlabFilename,
cameraSpatialFilename);
capture.open(captureDeviceNumber);
getCameraParameters(cameraParametersFilename, rectifyMaps,
cameraMatrix, distortionCoefficients, imageSize);
capture.set(CV_CAP_PROP_FRAME_WIDTH, imageSize.width);
capture.set(CV_CAP_PROP_FRAME_HEIGHT, imageSize.height);
std::cerr << imageSize << std::endl;
} catch (cv::Exception &ex) {
if (USER_TRIGGERED_EXIT == ex.code) {
return 0;
} else {
std::cerr << "EXCEPTION!!!!!!!!!!!" << std::endl
<< ex.what() << std::endl;
return 1;
}
}
try {
VisualOdometer odo = getVisualOdometer(capture, shiThomasi,
lucasKanade, chessboard, spatial,
cameraParametersFilename, cameraSpatialFilename,
maxHistoryLength, maxDeviation, maxDeviants,
minLength, maxLength, upperMargin, lowerMargin,
maxFeaturesUpper, maxFeaturesLower, rectifyMaps,
imageSize, positions, cameraMatrix,
distortionCoefficients, calibrateParameters);
char control = ' ';
cv::Mat input;
cv::Mat undistorted;
cv::Mat grey;
cv::Mat map;
if (verbosity > 1) {
cv::namedWindow("main", CV_WINDOW_KEEPRATIO);
}
if (verbosity > 0) {
cv::namedWindow("map", CV_WINDOW_KEEPRATIO);
}
if (0 == verbosity) {
cv::namedWindow("kill switch", CV_WINDOW_NORMAL);
}
std::vector<std::list<cv::Point2f> > featuresRot;
std::vector<std::list<cv::Point2f> > featuresGround;
boost::posix_time::ptime milenium(
boost::gregorian::date(1970, 1, 1));
for (int i = 0; i < 5; ++i) { //a couple of dry cycles to warm up
cv::Point3f displacement;
capture >> input;
if (input.empty()) {
continue;
}
cv::remap(input, undistorted, rectifyMaps[0],
rectifyMaps[1], cv::INTER_LINEAR);
cv::cvtColor(undistorted, grey, CV_RGB2GRAY);
displacement = odo.calculateDisplacement(grey);
}
do {
cv::Point3f displacement;
capture >> input;
if (input.empty()) {
continue;
}
processInput(input, rectifyMaps, positions, odo,
timestamps, milenium, verbosity, spatial,
imageSize, "main", "map");
if (1 < verbosity && 'p' == control) {
std::string fileName;
std::stringstream buff;
buff << "screen" << timestamps.front() << ".png";
buff >> fileName;
cv::imwrite(fileName, undistorted);
}
control = cv::waitKey(1);
} while ('q' != control);
cv::waitKey(0);
printTrajectory(matlabFilename, timestamps, positions);
} catch (cv::Exception &ex) {
if (USER_TRIGGERED_EXIT == ex.code) {
return 0;
} else {
std::cerr << "EXCEPTION!!!!!!!!!!!" << std::endl
<< ex.what() << std::endl;
return 1;
}
}
return 0;
}
void printTrajectory(const std::string &matlabFilename,
const std::list<long long int> ×tamps,
const std::list<cv::Point3f> &positions) {
std::list<long long int>::const_iterator iTime =
timestamps.begin();
std::ofstream out;
if (!matlabFilename.empty()) {
out.open(matlabFilename.c_str(), std::ofstream::out);
if (!out.is_open()) {
std::cerr << "WARNING: could not open file "
<< matlabFilename << " for write" << std::endl;
} else {
out << "t=[" << std::endl;
}
}
for (std::list<cv::Point3f>::const_iterator iPos =
positions.begin();
positions.end() != iPos && timestamps.end() != iTime;
++iPos, ++iTime) {
std::cerr << *iPos << " " << *iTime << std::endl;
if (!matlabFilename.empty()) {
out << iPos->x << "," << iPos->y << "," << iPos->z << ","
<< *iTime << std::endl;
}
}
out << "];" << std::endl;
out.close();
}
void processInput(const cv::Mat &input,
const std::vector<cv::Mat> &rectifyMaps,
std::list<cv::Point3f> &positions, VisualOdometer &odo,
std::list<long long int> ×tamps,
const boost::posix_time::ptime &milenium,
const int &verbosity, const CameraSpatialParameters &spatial,
const cv::Size &imageSize, const std::string &mainWindowName,
const std::string &mapWindowName) {
cv::Mat undistorted;
cv::Mat grey;
cv::Point3d currentPosition = positions.back();
cv::Point3d displacement;
cv::Mat map;
try {
cv::remap(input, undistorted, rectifyMaps[0], rectifyMaps[1],
cv::INTER_LINEAR);
cv::cvtColor(undistorted, grey, CV_RGB2GRAY);
displacement = odo.calculateDisplacement(grey);
cv::Point3d globalDisplacement(
displacement.x
* cos(currentPosition.z + displacement.z)
+ displacement.y
* sin(
currentPosition.z
+ displacement.z),
displacement.x
* sin(currentPosition.z + displacement.z)
+ displacement.y
* cos(
currentPosition.z
+ displacement.z),
displacement.z);
currentPosition = currentPosition + globalDisplacement;
positions.push_back(currentPosition);
boost::posix_time::ptime pTime =
boost::posix_time::microsec_clock::universal_time();
boost::posix_time::time_duration duration(pTime - milenium);
long long int miliseconds = duration.total_milliseconds();
timestamps.push_back(miliseconds);
if (verbosity > 0) {
map = drawTraveledRoute(positions);
cv::imshow(mapWindowName, map);
}
if (verbosity > 1) {
std::vector<std::list<cv::Point2f> > featuresRot =
odo.getRotationFeatures();
std::vector<std::list<cv::Point2f> > featuresGround =
odo.getTranslationFeatures();
drawFeaturesUpperAndLower(undistorted, featuresRot,
cv::Mat(), featuresGround, spatial.homography,
spatial.horizon, spatial.deadZone);
cv::line(undistorted, cv::Point(imageSize.width / 2, 0),
cv::Point(imageSize.width / 2, imageSize.height),
CV_RGB(255,0,0), 1, 8, 0);
drawDeadZoneHorizon(undistorted, spatial.horizon,
spatial.deadZone);
cv::imshow(mainWindowName, undistorted);
}
} catch (const cv::Exception &ex) {
std::cerr << "EXCEPTION!!!!!!!!!!!" << std::endl << ex.what()
<< std::endl;
cv::Exception newEx(ex.code, "Exception caught", __func__,
__FILE__, __LINE__);
throw newEx;
}
}
VisualOdometer getVisualOdometer(cv::VideoCapture &capture,
const ShiThomasiParameters &shiThomasi,
const LucasKanadeParameters &lucasKanade,
const ChessboardParameters &chessboard,
CameraSpatialParameters &spatial,
const std::string &cameraParametersFilename,
const std::string &cameraSpatialFilename,
const int &maxHistoryLength, const int &maxDeviation,
const int &maxDeviants, const int &minLength,
const int &maxLength, const int &upperMargin,
const int &lowerMargin, const int & maxFeaturesUpper,
const int & maxFeaturesLower,
std::vector<cv::Mat> &rectifyMaps, cv::Size &imageSize,
std::list<cv::Point3f> &positions,
const cv::Mat &cameraMatrix,
const cv::Mat &distortionCoefficients,
void (*parametersCalibration)(cv::VideoCapture &capture,
std::vector<cv::Mat> rectifyMaps, int &horizon,
int &deadZone, const cv::Size &imageSize)) {
ShiThomasiFeatureExtractor extractor(shiThomasi.qualityLevel,
shiThomasi.minDistance, shiThomasi.blockSize,
shiThomasi.winSize, shiThomasi.zeroZone,
shiThomasi.termCrit);
LucasKanadePyramidTracker tracker(lucasKanade.winSize,
lucasKanade.maxLevel, lucasKanade.flags,
lucasKanade.termCrit, lucasKanade.minEigenvalueThresh,
lucasKanade.maxErrorValue);
try {
std::list<FeatureFilter*> filters;
filters.push_back(new TrimHistoryFilter(maxHistoryLength));
filters.push_back(
new SmoothFilter(maxDeviation, maxDeviants, minLength,
maxLength));
cv::Point3f currentPosition(0, 0, 0);
positions.push_back(currentPosition);
if (0 >= spatial.horizon || 0 > spatial.deadZone) {
spatial.horizon = imageSize.height / 2;
spatial.deadZone = 0;
parametersCalibration(capture, rectifyMaps,
spatial.horizon, spatial.deadZone, imageSize);
std::vector<cv::Point2f> corners = getChessboardCorners(
capture, rectifyMaps, spatial.horizon,
spatial.deadZone, chessboard.size, imageSize,
chessboard.winSize, chessboard.zeroZone,
chessboard.termCrit);
cerr << "got corners" << endl;
getHomographyRtMatrixAndRotationCenter(corners, imageSize,
chessboard.size, chessboard.squareSize,
spatial.horizon, spatial.deadZone, cameraMatrix,
distortionCoefficients, chessboard.height,
spatial.homography, spatial.rotationCenter,
spatial.rtMatrix);
if (!cameraSpatialFilename.empty()) {
cv::FileStorage fs(cameraSpatialFilename,
cv::FileStorage::WRITE);
if (!fs.isOpened()) {
cv::Exception ex(-1, "Could not open FileStorage",
__func__, __FILE__, __LINE__);
throw ex;
}
fs << "cameraSpatialParameters" << spatial;
fs.release();
}
}
TangentRotationReader rotationReader(tracker, extractor,
filters, maxFeaturesUpper,
cameraMatrix.at<double>(0, 0),
cv::Size(imageSize.width,
spatial.horizon - spatial.deadZone),
upperMargin);
BirdsEyeTranslationReader transReader(spatial.homography,
extractor, tracker, maxFeaturesLower, filters,
spatial.rotationCenter,
cv::Size(imageSize.width,
imageSize.height - spatial.horizon
- spatial.deadZone), lowerMargin);
VisualOdometer odo(rotationReader, transReader,
spatial.horizon, spatial.deadZone);
return odo;
} catch (const cv::Exception &ex) {
if (USER_TRIGGERED_EXIT != ex.code) {
std::cerr << "EXCEPTION!!!!!!!!!!!" << std::endl
<< ex.what() << std::endl;
}
cv::Exception newEx(ex.code, "Exception caught", __func__,
__FILE__, __LINE__);
throw newEx;
}
}
| 38.292804 | 73 | 0.580741 | [
"vector"
] |
a1fde143f00f0f0d9b5765307764e8f1ada17071 | 8,767 | cpp | C++ | Pocket Cube/2016.11.19.3.cpp | 1980744819/ACM-code | a697242bc963e682e552e655e3d78527e044e854 | [
"Apache-2.0"
] | null | null | null | Pocket Cube/2016.11.19.3.cpp | 1980744819/ACM-code | a697242bc963e682e552e655e3d78527e044e854 | [
"Apache-2.0"
] | null | null | null | Pocket Cube/2016.11.19.3.cpp | 1980744819/ACM-code | a697242bc963e682e552e655e3d78527e044e854 | [
"Apache-2.0"
] | null | null | null | #include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<vector>
#include<set>
#include<map>
#include<queue>
#include<stack>
#include<algorithm>
using namespace std;
int Map[8][6];
int Map_t[8][6];
int judge(){
int i,j;
int flag;
int t;
for(i=0;i<6;i++){
flag=0;
switch(i){
case 0:{
t=Map_t[0][0];
if(t!=Map_t[0][1]||t!=Map_t[1][0]||t!=Map_t[1][1])
flag=1;
}break;
case 1:{
t=Map_t[0][2];
if(t!=Map_t[0][3]||t!=Map_t[1][2]||t!=Map_t[1][3])
flag=1;
}break;
case 2:{
t=Map_t[0][4];
if(t!=Map_t[0][5]||t!=Map_t[1][4]||t!=Map_t[1][5])
flag=1;
}break;
case 3:{
t=Map_t[2][2];
if(t!=Map_t[2][3]||t!=Map_t[3][2]||t!=Map_t[3][3])
flag=1;
}break;
case 4:{
t=Map_t[4][2];
if(t!=Map_t[4][3]||t!=Map_t[5][2]||t!=Map_t[5][3])
flag=1;
}break;
case 5:{
t=Map_t[6][2];
if(t!=Map_t[6][3]||t!=Map_t[7][2]||t!=Map_t[7][3])
flag=1;
}break;
}
if(flag)
break;
}
if(flag)
return 0;
else
return 1;
}
void Copy(){
int i,j;
for(i=0;i<8;i++){
for(j=0;j<6;j++){
Map_t[i][j]=Map[i][j];
}
}
}
int main(){
int i,j,k;
int n;
scanf("%d",&n);
int flag;
int t1,t2;
while(n--){
scanf("%d %d %d %d",&Map[0][2],&Map[0][3],&Map[1][2],&Map[1][3]);
scanf("%d %d %d %d",&Map[2][2],&Map[2][3],&Map[3][2],&Map[3][3]);
scanf("%d %d %d %d",&Map[4][2],&Map[4][3],&Map[5][2],&Map[5][3]);
scanf("%d %d %d %d",&Map[6][2],&Map[6][3],&Map[7][2],&Map[7][3]);
scanf("%d %d %d %d",&Map[0][0],&Map[0][1],&Map[1][0],&Map[1][1]);
scanf("%d %d %d %d",&Map[0][4],&Map[0][5],&Map[1][4],&Map[1][5]);
/*for(i=0;i<8;i++){
for(j=0;j<6;j++){
printf("%d",Map[i][j]);
}
printf("\n");
}*/
Copy();
if(judge()){
printf("YES\n");
continue;
}
for(i=0;i<12;i++){
Copy();
flag=0;
switch(i){
case 0:{
t1=Map_t[0][0];
t2=Map_t[0][1];
Map_t[0][0]=Map_t[0][2];
Map_t[0][1]=Map_t[0][3];
Map_t[0][2]=Map_t[0][4];
Map_t[0][3]=Map_t[0][5];
Map_t[0][4]=Map_t[5][3];
Map_t[0][5]=Map_t[5][2];
Map_t[5][3]=t1;
Map_t[5][2]=t2;
flag=judge();
}break;
case 1:{
t1=Map_t[0][0];
t2=Map_t[0][1];
Map_t[0][0]=Map_t[5][3];
Map_t[0][1]=Map_t[5][2];
Map_t[5][3]=Map_t[0][4];
Map_t[5][2]=Map_t[0][5];
Map_t[0][4]=Map_t[0][2];
Map_t[0][5]=Map_t[0][3];
Map_t[0][2]=t1;
Map_t[0][3]=t2;
flag=judge();
}break;
case 2:{
t1=Map_t[1][0];
t2=Map_t[1][1];
Map_t[1][0]=Map_t[1][2];
Map_t[1][1]=Map_t[1][3];
Map_t[1][2]=Map_t[1][4];
Map_t[1][3]=Map_t[1][5];
Map_t[1][4]=Map_t[4][3];
Map_t[1][5]=Map_t[4][2];
Map_t[4][3]=t1;
Map_t[4][2]=t2;
flag=judge();
}break;
case 3:{
t1=Map_t[1][0];
t2=Map_t[1][1];
Map_t[1][0]=Map_t[4][3];
Map_t[1][1]=Map_t[4][2];
Map_t[4][3]=Map_t[1][4];
Map_t[4][2]=Map_t[1][5];
Map_t[1][4]=Map_t[1][2];
Map_t[1][5]=Map_t[1][3];
Map_t[1][2]=t1;
Map_t[1][3]=t2;
flag=judge();
}break;
case 4:{
t1=Map_t[0][2];
t2=Map_t[1][2];
Map_t[0][2]=Map_t[2][2];
Map_t[1][2]=Map_t[3][2];
Map_t[2][2]=Map_t[4][2];
Map_t[3][2]=Map_t[5][2];
Map_t[4][2]=Map_t[6][2];
Map_t[5][2]=Map_t[7][2];
Map_t[6][2]=t1;
Map_t[7][2]=t2;
flag=judge();
}break;
case 5:{
t1=Map_t[0][2];
t2=Map_t[1][2];
Map_t[0][2]=Map_t[6][2];
Map_t[1][2]=Map_t[7][2];
Map_t[6][2]=Map_t[4][2];
Map_t[7][2]=Map_t[5][2];
Map_t[4][2]=Map_t[2][2];
Map_t[5][2]=Map_t[3][2];
Map_t[2][2]=t1;
Map_t[3][2]=t2;
flag=judge();
}break;
case 6:{
t1=Map_t[0][3];
t2=Map_t[1][3];
Map_t[0][3]=Map_t[2][3];
Map_t[1][3]=Map_t[3][3];
Map_t[2][3]=Map_t[4][3];
Map_t[3][3]=Map_t[5][3];
Map_t[4][3]=Map_t[6][3];
Map_t[5][3]=Map_t[7][3];
Map_t[6][3]=t1;
Map_t[7][3]=t2;
flag=judge();
}break;
case 7:{
t1=Map_t[0][3];
t2=Map_t[1][3];
Map_t[0][3]=Map_t[6][3];
Map_t[1][3]=Map_t[7][3];
Map_t[6][3]=Map_t[4][3];
Map_t[7][3]=Map_t[5][3];
Map_t[4][3]=Map_t[2][3];
Map_t[5][3]=Map_t[3][3];
Map_t[2][3]=t1;
Map_t[3][3]=t2;
flag=judge();
}break;
case 8:{
t1=Map_t[2][2];
t2=Map_t[2][3];
Map_t[2][2]=Map_t[1][4];
Map_t[2][3]=Map_t[0][4];
Map_t[1][4]=Map_t[7][3];
Map_t[0][4]=Map_t[7][2];
Map_t[7][3]=Map_t[0][1];
Map_t[7][2]=Map_t[1][1];
Map_t[0][1]=t1;
Map_t[1][1]=t2;
flag=judge();
}
break;
case 9:{
t1=Map_t[2][2];
t2=Map_t[2][3];
Map_t[2][2]=Map_t[0][1];
Map_t[2][3]=Map_t[1][1];
Map_t[0][1]=Map_t[7][3];
Map_t[1][1]=Map_t[7][2];
Map_t[7][3]=Map_t[1][4];
Map_t[7][2]=Map_t[0][4];
Map_t[1][4]=t1;
Map_t[0][4]=t2;
flag=judge();
}
break;
case 10:{
t1=Map_t[3][2];
t2=Map_t[3][3];
Map_t[3][2]=Map_t[1][5];
Map_t[3][3]=Map_t[0][5];
Map_t[1][5]=Map_t[6][3];
Map_t[0][5]=Map_t[6][2];
Map_t[6][3]=Map_t[0][0];
Map_t[6][2]=Map_t[1][0];
Map_t[0][0]=t1;
Map_t[1][0]=t2;
flag=judge();
}
break;
case 11:{
t1=Map_t[3][2];
t2=Map_t[3][3];
Map_t[3][2]=Map_t[0][0];
Map_t[3][3]=Map_t[1][0];
Map_t[0][0]=Map_t[6][3];
Map_t[1][0]=Map_t[6][2];
Map_t[6][3]=Map_t[1][5];
Map_t[6][2]=Map_t[0][5];
Map_t[1][5]=t1;
Map_t[0][5]=t2;
flag=judge();
}
break;
}
if(flag){
printf("YES\n");
break;
}
}
if(!flag)
printf("NO\n");
memset(Map_t,0,sizeof(Map_t));
memset(Map,0,sizeof(Map));
}
return 0;
}
| 32.113553 | 73 | 0.302498 | [
"vector"
] |
a1ff137c7a79655028eec6e445e877a449eb62b5 | 15,736 | cpp | C++ | dot_game_engine/Screen.cpp | prdepinho/dot_game_engine | 97fd5ebdad9d669aa1bacafd9e56f6bf37b4cde6 | [
"MIT"
] | null | null | null | dot_game_engine/Screen.cpp | prdepinho/dot_game_engine | 97fd5ebdad9d669aa1bacafd9e56f6bf37b4cde6 | [
"MIT"
] | null | null | null | dot_game_engine/Screen.cpp | prdepinho/dot_game_engine | 97fd5ebdad9d669aa1bacafd9e56f6bf37b4cde6 | [
"MIT"
] | null | null | null | #include "Screen.h"
#include "Game.h"
#include <iostream>
#include <cstdlib>
#include "Resources.h"
Screen::Screen(sf::RenderWindow *window) : window(window), created(false) {
}
Screen::~Screen() {
if (created)
destroy();
}
void Screen::destroy() { }
void Screen::create() {
created = true;
game_view.setSize(sf::Vector2f((float) Game::get_screen_width(), (float) Game::get_screen_height()));
game_view.setCenter(sf::Vector2f((float) Game::get_screen_width() / 2.f, (float) Game::get_screen_height() / 2.f));
gui_view.setSize(sf::Vector2f((float) Game::get_screen_width(), (float) Game::get_screen_height()));
gui_view.setCenter((float)Game::get_screen_width() / 2.f, (float) Game::get_screen_height() / 2.f);
}
void Screen::update(float elapsed_time) {
window->setView(game_view);
for (auto map : game_entities) {
for (auto entity : map) {
entity.second->update(elapsed_time);
}
}
window->setView(gui_view);
for (auto map : gui_entities) {
for (auto entity : map) {
entity.second->update(elapsed_time);
}
}
for (std::string &id : delete_buffer)
delete_entity(id);
delete_buffer.clear();
for (std::string &id : erase_buffer)
erase_entity(id);
erase_buffer.clear();
}
void Screen::draw() {
window->setView(game_view);
for (int layer = 0; layer < game_entities.size(); layer++) {
auto &map = game_entities[layer];
if (layers_to_order_by_position[layer]) {
std::vector<Entity *> ordered_entities = order_by_position(layer);
for (auto entity : ordered_entities) {
window->draw(*entity);
}
}
else {
for (auto entity : map) {
window->draw(*entity.second);
}
}
}
window->setView(gui_view);
for (auto map : gui_entities) {
for (auto entity : map) {
window->draw(*entity.second);
}
}
}
void Screen::poll_events(float elapsed_time) {
sf::Event event;
while (window->pollEvent(event)) {
if (window->hasFocus()) {
std::string event_type = "";
int key = event.key.code;
int button = event.mouseButton.button;
int x = event.mouseMove.x;
int y = event.mouseMove.y;
float delta = event.mouseWheelScroll.delta;
switch (event.type) {
case sf::Event::Closed:
window->close();
break;
case sf::Event::KeyPressed:
event_type = "key_down";
break;
case sf::Event::KeyReleased:
event_type = "key_up";
break;
case sf::Event::MouseButtonPressed:
event_type = "mouse_button_down";
break;
case sf::Event::MouseButtonReleased:
event_type = "mouse_button_up";
break;
case sf::Event::MouseMoved:
event_type = "mouse_moved";
break;
case sf::Event::MouseWheelScrolled:
if (event.mouseWheelScroll.wheel == sf::Mouse::VerticalWheel)
event_type = "mouse_scrolled";
break;
}
// callback entity input events if mouse is over it, gui first, higher layers first, only one callback
// also check cursor enter and cursor exit
if (event_type != "") {
bool rval = false;
for (auto it = gui_entities.rbegin(); it != gui_entities.rend(); ++it) {
for (auto that : *it) {
ScreenEntity &entity = entity_map[that.first];
if (is_mouse_over_entity(that.second, ScreenView::GUI_VIEW)) {
if (!rval) {
rval = entity.callback.entity_input_callback(event_type, elapsed_time, key, button, x, y, delta);
if (!entity.cursor_in)
rval = entity.callback.entity_input_callback("mouse_cursor_enter", elapsed_time, key, button, x, y, delta);
entity.cursor_in = true;
}
}
else {
if (entity.cursor_in)
rval = entity.callback.entity_input_callback("mouse_cursor_exit", elapsed_time, key, button, x, y, delta);
entity.cursor_in = false;
}
}
}
for (auto it = game_entities.rbegin(); it != game_entities.rend(); ++it) {
for (auto that : *it) {
ScreenEntity &entity = entity_map[that.first];
if (is_mouse_over_entity(that.second, ScreenView::GAME_VIEW)) {
if (!rval) {
rval = entity.callback.entity_input_callback(event_type, elapsed_time, key, button, x, y, delta);
if (!entity.cursor_in)
rval = entity.callback.entity_input_callback("mouse_cursor_enter", elapsed_time, key, button, x, y, delta);
entity.cursor_in = true;
}
}
else {
if (entity.cursor_in)
rval = entity.callback.entity_input_callback("mouse_cursor_exit", elapsed_time, key, button, x, y, delta);
entity.cursor_in = false;
}
}
}
// callback on_input
if (!rval)
Lua::get().run_on_input(event_type, elapsed_time, key, button, x, y, delta);
}
}
}
}
void Screen::add_panel(
std::string id,
ScreenView view,
int layer,
int x,
int y,
int width,
int height,
int texture_x,
int texture_y,
int texture_width,
int texture_height,
std::string texture
) {
Panel *panel = new Panel(x, y, width, height, texture_x, texture_y, texture_width, texture_height, texture);
entity_map[id].entity = panel;
entity_map[id].type = EntityType::PANEL;
entity_map[id].view = view;
entity_map[id].layer = layer;
panel->build();
add_entity(entity_map[id].entity, id, view, layer);
}
void Screen::add_segmented_panel(
std::string id,
ScreenView view,
int layer,
int x,
int y,
int width,
int height,
int texture_x,
int texture_y,
int border_size,
int interior_width,
int interior_height,
std::string texture
) {
SegmentedPanel *seg_panel = new SegmentedPanel(x, y, width, height, texture_x, texture_y, border_size, interior_width, interior_height, texture);
entity_map[id].entity = seg_panel;
entity_map[id].type = EntityType::SEGMENTED_PANEL;
entity_map[id].view = view;
entity_map[id].layer = layer;
seg_panel->build();
add_entity(entity_map[id].entity, id, view, layer);
}
void Screen::add_text_line(
std::string id,
ScreenView view,
int layer,
int x,
int y,
std::string text,
std::string font,
sf::Color color
) {
Text *text_obj = new Text(font);
entity_map[id].entity = text_obj;
entity_map[id].type = EntityType::TEXT;
entity_map[id].view = view;
entity_map[id].layer = layer;
text_obj->build();
text_obj->write_line(x, y, text, color);
add_entity(entity_map[id].entity, id, view, layer);
}
void Screen::add_text_block(
std::string id,
ScreenView view,
int layer,
int x,
int y,
int line_length,
std::string text,
std::string font,
sf::Color color
) {
Text *text_obj = new Text(font);
entity_map[id].entity = text_obj;
entity_map[id].type = EntityType::TEXT;
entity_map[id].view = view;
entity_map[id].layer = layer;
text_obj->build();
text_obj->write_block(x, y, line_length, text, color);
add_entity(entity_map[id].entity, id, view, layer);
}
void Screen::add_sprite(
std::string id,
ScreenView view,
int layer,
int x,
int y,
int width,
int height,
AnimationResources resources)
{
Sprite *sprite = new Sprite(id, x, y, width, height, resources);
entity_map[id].entity = sprite;
entity_map[id].type = EntityType::SPRITE;
entity_map[id].view = view;
entity_map[id].layer = layer;
sprite->build();
add_entity(entity_map[id].entity, id, view, layer);
}
void Screen::add_tile_layer(
std::string id,
ScreenView view,
int layer,
int x,
int y,
int tile_width,
int tile_height,
int rows,
int columns,
std::vector<TileLayer::Tile> tiles,
std::string texture,
std::map<int, TileLayer::Animation> animations
) {
TileLayer *tile_layer = new TileLayer(x, y, tile_width, tile_height, rows, columns, tiles, texture, animations);
entity_map[id].entity = tile_layer;
entity_map[id].type = EntityType::TILE_LAYER;
entity_map[id].view = view;
entity_map[id].layer = layer;
tile_layer->build();
add_entity(entity_map[id].entity, id, view, layer);
}
void Screen::load_tilemap(std::string map_name, int x, int y) {
if (tilemap.name == map_name)
return;
remove_tilemap();
MapLoader::load(tilemap, map_name, x, y);
}
void Screen::remove_tilemap() {
for (const std::string &tile_layer_id : tilemap.tile_layer_ids) {
remove_entity(tile_layer_id);
}
tilemap = TileMap();
}
void Screen::set_tile(
std::string id,
int tile_x,
int tile_y,
int texture_x,
int texture_y
) {
if (entity_map[id].type == EntityType::TILE_LAYER)
dynamic_cast<TileLayer *>(entity_map[id].entity)->set_tile(tile_x, tile_y, texture_x, texture_y);
}
void Screen::set_panel_texture(
std::string id,
int texture_x,
int texture_y,
int texture_width,
int texture_height,
std::string texture
) {
dynamic_cast<Panel *>(entity_map[id].entity)->change_skin(texture_x, texture_y, texture_width, texture_height, texture);
}
void Screen::set_segmented_panel_texture(
std::string id,
int texture_x,
int texture_y,
int border_size,
int interior_width,
int interior_height,
std::string texture
) {
dynamic_cast<SegmentedPanel *>(entity_map[id].entity)->change_skin(texture_x, texture_y, border_size, interior_width, interior_height, texture);
}
void Screen::add_entity(Entity *entity, std::string id, ScreenView view, int layer) {
switch (view) {
case ScreenView::GAME_VIEW:
if (game_entities.size() <= layer)
game_entities.resize(layer + 1);
game_entities[layer][id] = entity;
break;
case ScreenView::GUI_VIEW:
if (gui_entities.size() <= layer)
gui_entities.resize(layer + 1);
gui_entities[layer][id] = entity;
break;
}
}
void Screen::move_entity(std::string id, float delta_x, float delta_y) {
get_entity(id)->move({ delta_x, delta_y });
}
void Screen::resize_entity(std::string id, float delta_x, float delta_y) {
Entity *entity = get_entity(id);
entity->set_dimensions((int) (entity->get_width() + delta_x), (int) (entity->get_height() + delta_y));
entity->build();
}
std::string Screen::get_text(std::string id) {
ScreenEntity &screen_entity = entity_map[id];
if (screen_entity.type == EntityType::TEXT)
return dynamic_cast<Text *>(screen_entity.entity)->get_text();
return "";
}
void Screen::set_text(std::string id, std::string text) {
ScreenEntity &screen_entity = entity_map[id];
if (screen_entity.type == EntityType::TEXT)
dynamic_cast<Text *>(screen_entity.entity)->set_text(text);
}
void Screen::remove_entity(std::string id) {
delete_buffer.push_back(id);
}
void Screen::set_entity_visibility(std::string id, bool visible) {
if (visible) {
ScreenEntity &entity = entity_map[id];
switch (entity.view) {
case ScreenView::GAME_VIEW:
if (game_entities.size() <= entity.layer)
game_entities.resize(entity.layer + 1);
game_entities[entity.layer][id] = entity.entity;
break;
case ScreenView::GUI_VIEW:
if (gui_entities.size() <= entity.layer)
gui_entities.resize(entity.layer + 1);
gui_entities[entity.layer][id] = entity.entity;
break;
}
}
else {
erase_buffer.push_back(id);
}
}
Entity *Screen::get_entity(std::string id) {
return entity_map[id].entity;
}
ScreenEntity &Screen::get_screen_entity(std::string id) {
return entity_map[id];
}
Sprite *Screen::get_sprite(std::string id) {
if (entity_map[id].type == EntityType::SPRITE)
return dynamic_cast<Sprite *>(entity_map[id].entity);
return nullptr;
}
void Screen::set_show_outline(std::string id, bool show, sf::Color color) {
Entity *entity = get_entity(id);
if (entity) {
if (show)
entity->show_outline(1, 0, color);
else
entity->hide_outline();
}
}
void Screen::set_show_origin(std::string id, bool show, sf::Color color) {
Entity *entity = get_entity(id);
if (entity) {
if (show)
entity->show_origin(1, color);
else
entity->hide_origin();
}
}
bool Screen::is_mouse_over_entity(Entity *entity, ScreenView view) {
switch (view) {
case ScreenView::GAME_VIEW:
{
auto mouse = get_mouse_game_position();
return entity->in_bounds((int)mouse.x, (int)mouse.y);
}
break;
case ScreenView::GUI_VIEW:
{
auto mouse = get_mouse_gui_position();
return entity->in_bounds((int)mouse.x, (int)mouse.y);
}
break;
}
return false;
}
void Screen::set_entity_callback(std::string id, LuaObject callback) {
if (get_entity(id)) {
entity_map[id].callback.delete_functions();
entity_map[id].callback = callback;
}
}
#if 0
void change_callback(LuaObject callback) {
this->callback.delete_functions();
this->callback = callback;
}
#endif
void Screen::set_position(std::string id, int x, int y) {
Entity *entity = get_entity(id);
if (entity)
entity->set_position(x, y);
}
void Screen::set_dimensions(std::string id, int w, int h) {
Entity *entity = get_entity(id);
if (entity) {
entity->set_dimensions(w, h);
entity->build();
}
}
void Screen::start_animation(std::string id, std::string key, bool loop) {
if (get_entity(id)) {
if (loop)
dynamic_cast<Sprite *>(entity_map[id].entity)->loop_animation(key);
else
dynamic_cast<Sprite *>(entity_map[id].entity)->start_animation(key);
}
}
void Screen::stop_animation(std::string id) {
if (get_entity(id))
dynamic_cast<Sprite *>(entity_map[id].entity)->stop_animation();
}
sf::Vector2f Screen::get_mouse_gui_position() {
window->setView(gui_view);
return window->mapPixelToCoords(sf::Mouse::getPosition(*window));
}
sf::Vector2f Screen::get_mouse_game_position() {
window->setView(game_view);
return window->mapPixelToCoords(sf::Mouse::getPosition(*window));
}
void Screen::pan_game_view(sf::Vector2f v) {
game_view.move(v);
}
sf::Vector2i Screen::get_tile_coords_under_cursor(std::string id) {
ScreenEntity &entity = entity_map[id];
int tile_x = 0;
int tile_y = 0;
if (entity.type == EntityType::TILE_LAYER) {
sf::Vector2f cursor;
switch (entity.view) {
case ScreenView::GAME_VIEW:
cursor = get_mouse_game_position();
break;
case ScreenView::GUI_VIEW:
cursor = get_mouse_gui_position();
break;
}
TileLayer *tile_layer = dynamic_cast<TileLayer *>(entity.entity);
tile_x = (int)((cursor.x - tile_layer->get_x()) / tile_layer->get_tile_width());
tile_y = (int)((cursor.y - tile_layer->get_y()) / tile_layer->get_tile_height());
}
return { tile_x, tile_y };
}
// Returns the gui position of coordinates in the game map. TODO: take zoom into account.
sf::Vector2f Screen::get_gui_position_over_game(float x, float y) {
auto gui_center = gui_view.getCenter();
auto gui_size = gui_view.getSize();
sf::Vector2f gui_origin = {gui_center.x - gui_size.x / 2, gui_center.y - gui_size.y / 2};
auto game_center = game_view.getCenter();
auto game_size = game_view.getSize();
sf::Vector2f game_origin = {game_center.x - game_size.x / 2, game_center.y - game_size.y / 2};
sf::Vector2f diff = { gui_origin.x - game_origin.x, gui_origin.y - game_origin.y };
return sf::Vector2f{ x + diff.x, y + diff.y };
}
void Screen::erase_entity(std::string id) {
ScreenEntity &entity = entity_map[id];
switch (entity.view) {
case ScreenView::GAME_VIEW:
game_entities[entity.layer].erase(id);
break;
case ScreenView::GUI_VIEW:
gui_entities[entity.layer].erase(id);
break;
}
}
void Screen::delete_entity(std::string id) {
ScreenEntity &entity = entity_map[id];
switch (entity.view) {
case ScreenView::GAME_VIEW:
game_entities[entity.layer].erase(id);
break;
case ScreenView::GUI_VIEW:
gui_entities[entity.layer].erase(id);
break;
}
entity_map.erase(id);
}
static bool compare_entityes_by_position(Entity *a, Entity *b) {
// print from top right to bottom left
return (b->get_x() + a->get_y() * 1000) < (a->get_x() + b->get_y() * 1000);
}
std::vector<Entity *> Screen::order_by_position(int layer) {
std::vector<Entity *> ordered_entities;
for (auto &pair : game_entities[layer]) {
Entity *entity = pair.second;
ordered_entities.push_back(entity);
}
std::sort(ordered_entities.begin(), ordered_entities.end(), compare_entityes_by_position);
return ordered_entities;
}
void Screen::set_draw_in_position_order(int layer, bool order) {
layers_to_order_by_position[layer] = order;
}
| 26.807496 | 146 | 0.696492 | [
"vector"
] |
b8062955e49132af677751314634994898190185 | 8,029 | cpp | C++ | Hardware/SIAM/ShiftAdd.cpp | gkrish19/SIAM | 1e530d4c070054045fc2e8e7fe4ce82a54755132 | [
"MIT"
] | 4 | 2021-02-02T06:50:43.000Z | 2022-01-29T12:25:32.000Z | Hardware/SIAM/ShiftAdd.cpp | gkrish19/SIAM | 1e530d4c070054045fc2e8e7fe4ce82a54755132 | [
"MIT"
] | null | null | null | Hardware/SIAM/ShiftAdd.cpp | gkrish19/SIAM | 1e530d4c070054045fc2e8e7fe4ce82a54755132 | [
"MIT"
] | 2 | 2021-07-07T19:58:40.000Z | 2022-01-27T22:51:20.000Z | /*******************************************************************************
* Copyright (c) 2017-2020
* School of Electrical, Computer and Energy Engineering, Arizona State University
* PI: Prof. Yu Cao
* All rights reserved.
*
* This source code is part of NeuroSim - a device-circuit-algorithm framework to benchmark
* neuro-inspired architectures with synaptic devices(e.g., SRAM and emerging non-volatile memory).
* Copyright of the model is maintained by the developers, and the model is distributed under
* the terms of the Creative Commons Attribution-NonCommercial 4.0 International Public License
* http://creativecommons.org/licenses/by-nc/4.0/legalcode.
* The source code is free and you can redistribute and/or modify it
* by providing 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 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.
*
* Developer list:
* Gokul Krishnan Email: gkrish19@asu.edu
* Credits: Prof.Shimeng Yu and his research group for NeuroSim
********************************************************************************/
#include <cmath>
#include <iostream>
#include "constant.h"
#include "formula.h"
#include "ShiftAdd.h"
using namespace std;
ShiftAdd::ShiftAdd(const InputParameter& _inputParameter, const Technology& _tech, const MemCell& _cell): inputParameter(_inputParameter), tech(_tech), cell(_cell), adder(_inputParameter, _tech, _cell), dff(_inputParameter, _tech, _cell), FunctionUnit() {
initialized = false;
}
void ShiftAdd::Initialize(int _numUnit, int _numAdderBit, double _clkFreq, SpikingMode _spikingMode, int _numReadPulse) {
if (initialized)
cout << "[ShiftAdd] Warning: Already initialized!" << endl;
numUnit = _numUnit;
numAdderBit = _numAdderBit;
numAdder = numUnit;
clkFreq = _clkFreq;
spikingMode = _spikingMode;
numReadPulse = _numReadPulse;
if (spikingMode == NONSPIKING) { // NONSPIKING: binary format
numDff = (numAdderBit+1 + numReadPulse-1) * numUnit; // numAdderBit+1 because the adder output is 1 bit more than the input, and numReadPulse-1 is for shift-and-add extension (shift register)
dff.Initialize(numDff, clkFreq);
adder.Initialize(numAdderBit, numAdder);
} else { // SPIKING: count spikes
numBitPerDff = pow(2, numAdderBit);
numDff = numBitPerDff * numUnit; // numUnit shift registers in total
dff.Initialize(numDff, clkFreq);
}
/* Currently ignore INV and NAND in shift-add circuit */
// PISO shift register (https://en.wikipedia.org/wiki/Shift_register)
// INV
widthInvN = MIN_NMOS_SIZE * tech.featureSize;
widthInvP = tech.pnSizeRatio * MIN_NMOS_SIZE * tech.featureSize;
numInv = numUnit;
// NAND2
widthNandN = 2 * MIN_NMOS_SIZE * tech.featureSize;
widthNandP = tech.pnSizeRatio * MIN_NMOS_SIZE * tech.featureSize;
numNand = 3 * (numDff/numUnit-1) * numUnit; // numDff/numUnit means the number of DFF for each shift register
initialized = true;
}
void ShiftAdd::CalculateArea(double _newHeight, double _newWidth, AreaModify _option) {
if (!initialized) {
cout << "[ShiftAdd] Error: Require initialization first!" << endl;
} else {
double hInv, wInv, hNand, wNand;
// Adder
if (_newWidth && _option==NONE) {
if (spikingMode == NONSPIKING) { // NONSPIKING: binary format
adder.CalculateArea(NULL, _newWidth, NONE);
dff.CalculateArea(NULL, _newWidth, NONE);
} else { // SPIKING: count spikes
dff.CalculateArea(NULL, _newWidth, NONE);
}
} else {
cout << "[ShiftAdd] Error: No width assigned for the shift-and-add circuit" << endl;
exit(-1);
}
// Assume the INV and NAND2 are on the same row and the total width of them is smaller than the adder or DFF
if (spikingMode == NONSPIKING) { // NONSPIKING: binary format
height = adder.height + tech.featureSize*MAX_TRANSISTOR_HEIGHT /* INV and NAND2 */ + dff.height;
width = _newWidth;
} else { // SPIKING: count spikes
height = tech.featureSize*MAX_TRANSISTOR_HEIGHT /* INV and NAND2 */ + dff.height;
width = _newWidth;
}
area = height * width;
// Modify layout
newHeight = _newHeight;
newWidth = _newWidth;
switch (_option) {
case MAGIC:
MagicLayout();
break;
case OVERRIDE:
OverrideLayout();
break;
default: // NONE
break;
}
}
}
void ShiftAdd::CalculateLatency(double numRead) {
if (!initialized) {
cout << "[ShiftAdd] Error: Require initialization first!" << endl;
} else {
readLatency = 0;
// Assume the delay of INV and NAND2 are negligible
if (spikingMode == NONSPIKING) { // NONSPIKING: binary format
// We can shift and add the weighted sum data in the next vector pulse integration cycle
// Thus the shift-and-add time can be partially hidden by the vector pulse integration time at the next cycle
// But there is at least one time of shift-and-add, which is at the last vector pulse cycle
adder.CalculateLatency(1e20, dff.capTgDrain, 1);
dff.CalculateLatency(1e20, 1);
double shiftAddLatency = adder.readLatency + dff.readLatency;
if (shiftAddLatency > cell.readPulseWidth) // Completely hidden in the vector pulse cycle if smaller
readLatency += (shiftAddLatency - cell.readPulseWidth) * (numRead - 1);
readLatency += shiftAddLatency; // At least need one time of shift-and-add
} else { // SPIKING: count spikes
// We can shift out the weighted sum data in the next vector pulse integration cycle
// Thus the shiftout time can be partially hidden by the vector pulse integration time at the next cycle
// But there is at least one time of shiftout, which is at the last vector pulse cycle
dff.CalculateLatency(1e20, numBitPerDff); // Need numBitPerDff cycles to shift out the weighted sum data
double shiftLatency = dff.readLatency;
if (shiftLatency > cell.readPulseWidth) // Completely hidden in the vector pulse cycle if smaller
readLatency += (shiftLatency - cell.readPulseWidth) * (numRead - 1);
readLatency += shiftLatency; // At least need one time of shiftout
}
}
}
void ShiftAdd::CalculatePower(double numRead) {
if (!initialized) {
cout << "[ShiftAdd] Error: Require initialization first!" << endl;
} else {
leakage = 0;
readDynamicEnergy = 0;
if (spikingMode == NONSPIKING) { // NONSPIKING: binary format
adder.CalculatePower(numRead, numAdder);
dff.CalculatePower(numRead, numDff);
readDynamicEnergy += adder.readDynamicEnergy;
readDynamicEnergy += dff.readDynamicEnergy;
leakage += adder.leakage;
leakage += dff.leakage;
} else { // SPIKING: count spikes
dff.CalculatePower(numRead, numDff);
readDynamicEnergy += dff.readDynamicEnergy;
leakage += dff.leakage;
}
}
}
void ShiftAdd::PrintProperty(const char* str) {
FunctionUnit::PrintProperty(str);
}
void ShiftAdd::SaveOutput(const char* str) {
FunctionUnit::SaveOutput(str);
}
| 42.257895 | 256 | 0.702205 | [
"vector",
"model"
] |
b809022104d1d2241d94879b2a962ea7e1f1a88a | 3,957 | hpp | C++ | src/util/thread_pool.hpp | LaisoEmilio/WispRenderer | 8186856a7b3e1f0a19f6f6c8a9b99d8ccff38572 | [
"Apache-2.0"
] | 203 | 2019-04-26T10:52:22.000Z | 2022-03-15T17:42:44.000Z | src/util/thread_pool.hpp | LaisoEmilio/WispRenderer | 8186856a7b3e1f0a19f6f6c8a9b99d8ccff38572 | [
"Apache-2.0"
] | 90 | 2018-11-23T09:07:05.000Z | 2019-04-13T10:44:03.000Z | src/util/thread_pool.hpp | LaisoEmilio/WispRenderer | 8186856a7b3e1f0a19f6f6c8a9b99d8ccff38572 | [
"Apache-2.0"
] | 14 | 2019-06-19T00:52:00.000Z | 2021-02-19T13:44:01.000Z | /*!
* Copyright 2019 Breda University of Applied Sciences and Team Wisp (Viktor Zoutman, Emilio Laiso, Jens Hagen, Meine Zeinstra, Tahar Meijs, Koen Buitenhuis, Niels Brunekreef, Darius Bouma, Florian Schut)
*
* 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.
*/
/*
This thread pool is a modified version of https://github.com/progschj/ThreadPool.
It is adjusted to fit our project structure better.
Original licesne:
Copyright (c) 2012 Jakob Progsch, Václav Zeman
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#pragma once
#include <vector>
#include <queue>
#include <memory>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <future>
#include <functional>
#include <stdexcept>
#include "delegate.hpp"
namespace util
{
class ThreadPool
{
public:
ThreadPool(size_t);
template<class F, class... Args>
decltype(auto) Enqueue(F&& f, Args&&... args);
~ThreadPool();
private:
// need to keep track of threads so we can join them
std::vector<std::thread> m_workers;
// the task queue
std::queue<Delegate<void()>> m_tasks;
// synchronization
std::mutex m_queue_mutex;
std::condition_variable m_condition;
bool m_stop;
};
// the constructor just launches some amount of workers
inline ThreadPool::ThreadPool(std::size_t threads)
: m_stop(false)
{
for (decltype(threads) i = 0; i < threads; ++i)
m_workers.emplace_back(
[this]
{
for (;;)
{
Delegate<void()> task;
{
std::unique_lock<std::mutex> lock(m_queue_mutex);
m_condition.wait(lock,
[this] { return m_stop || !m_tasks.empty(); });
if (m_stop && m_tasks.empty())
return;
task = std::move(m_tasks.front());
m_tasks.pop();
}
task();
}
}
);
}
// add new work item to the pool
template<class F, class... Args>
decltype(auto) ThreadPool::Enqueue(F&& f, Args&&... args)
{
using return_type = typename std::result_of<F(Args...)>::type;
auto task = std::make_shared< std::packaged_task<return_type()> >(
std::bind(std::forward<F>(f), std::forward<Args>(args)...)
);
std::future<return_type> res = task->get_future();
{
std::unique_lock<std::mutex> lock(m_queue_mutex);
// don't allow enqueueing after stopping the pool
if (m_stop)
throw std::runtime_error("enqueue on stopped ThreadPool");
m_tasks.emplace([task]() { (*task)(); });
}
m_condition.notify_one();
return res;
}
// the destructor joins all threads
inline ThreadPool::~ThreadPool()
{
{
std::unique_lock<std::mutex> lock(m_queue_mutex);
m_stop = true;
}
m_condition.notify_all();
for (std::thread& worker : m_workers)
{
worker.join();
}
}
} | 26.736486 | 204 | 0.701289 | [
"vector"
] |
b809f4c6efae05620ddd3d7ee9add2f77897ce9d | 9,293 | cc | C++ | chrome/browser/sync/test/integration/sync_arc_package_helper.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/sync/test/integration/sync_arc_package_helper.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/sync/test/integration/sync_arc_package_helper.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2021-01-05T23:43:46.000Z | 2021-01-07T23:36:34.000Z | // Copyright 2016 The Chromium 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 "chrome/browser/sync/test/integration/sync_arc_package_helper.h"
#include <vector>
#include "base/command_line.h"
#include "base/run_loop.h"
#include "base/strings/string_number_conversions.h"
#include "chrome/browser/chromeos/arc/arc_util.h"
#include "chrome/browser/chromeos/arc/session/arc_session_manager.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/sync/test/integration/sync_datatype_helper.h"
#include "chrome/browser/sync/test/integration/sync_test.h"
#include "chrome/browser/ui/app_list/arc/arc_app_list_prefs.h"
#include "chrome/browser/ui/app_list/arc/arc_package_syncable_service.h"
#include "chromeos/constants/chromeos_switches.h"
#include "components/arc/session/connection_holder.h"
#include "components/arc/test/connection_holder_util.h"
#include "components/arc/test/fake_app_instance.h"
namespace arc {
namespace {
std::string GetTestPackageName(size_t id) {
return "testarcpackage" + base::NumberToString(id);
}
} // namespace
// static
SyncArcPackageHelper* SyncArcPackageHelper::GetInstance() {
SyncArcPackageHelper* instance = base::Singleton<SyncArcPackageHelper>::get();
DCHECK(sync_datatype_helper::test());
instance->SetupTest(sync_datatype_helper::test());
return instance;
}
// static
sync_pb::EntitySpecifics SyncArcPackageHelper::GetTestSpecifics(size_t id) {
sync_pb::EntitySpecifics specifics;
sync_pb::ArcPackageSpecifics* arc_specifics = specifics.mutable_arc_package();
arc_specifics->set_package_name(GetTestPackageName(id));
arc_specifics->set_package_version(id);
arc_specifics->set_last_backup_android_id(id);
arc_specifics->set_last_backup_time(id);
return specifics;
}
SyncArcPackageHelper::SyncArcPackageHelper()
: test_(nullptr), setup_completed_(false) {}
SyncArcPackageHelper::~SyncArcPackageHelper() {}
void SyncArcPackageHelper::SetupTest(SyncTest* test) {
if (setup_completed_) {
DCHECK_EQ(test, test_);
return;
}
test_ = test;
for (auto* profile : test_->GetAllProfiles()) {
EnableArcService(profile);
SendRefreshPackageList(profile);
}
setup_completed_ = true;
}
void SyncArcPackageHelper::InstallPackageWithIndex(Profile* profile,
size_t id) {
std::string package_name = GetTestPackageName(id);
mojom::ArcPackageInfo package;
package.package_name = package_name;
package.package_version = id;
package.last_backup_android_id = id;
package.last_backup_time = id;
package.sync = true;
InstallPackage(profile, package);
}
void SyncArcPackageHelper::UninstallPackageWithIndex(Profile* profile,
size_t id) {
std::string package_name = GetTestPackageName(id);
UninstallPackage(profile, package_name);
}
void SyncArcPackageHelper::ClearPackages(Profile* profile) {
const ArcAppListPrefs* prefs = ArcAppListPrefs::Get(profile);
DCHECK(prefs);
const std::vector<std::string> pref_packages = prefs->GetPackagesFromPrefs();
for (const auto& package : pref_packages) {
UninstallPackage(profile, package);
}
}
bool SyncArcPackageHelper::AllProfilesHaveSamePackages() {
const auto& profiles = test_->GetAllProfiles();
for (auto* profile : profiles) {
if (profile != profiles.front() &&
!ArcPackagesMatch(profiles.front(), profile)) {
DVLOG(1) << "Packages match failed!";
return false;
}
}
return true;
}
bool SyncArcPackageHelper::AllProfilesHaveSamePackageDetails() {
if (!AllProfilesHaveSamePackages()) {
DVLOG(1) << "Packages match failed, skip packages detail match.";
return false;
}
const auto& profiles = test_->GetAllProfiles();
for (auto* profile : profiles) {
if (profile != profiles.front() &&
!ArcPackageDetailsMatch(profiles.front(), profile)) {
DVLOG(1) << "Profile1: " << ArcPackageSyncableService::Get(profile);
DVLOG(1) << "Profile2: "
<< ArcPackageSyncableService::Get(profiles.front());
return false;
}
}
return true;
}
void SyncArcPackageHelper::EnableArcService(Profile* profile) {
DCHECK(profile);
DCHECK(!instance_map_[profile]);
arc::SetArcPlayStoreEnabledForProfile(profile, true);
// Usually ArcPlayStoreEnabledPreferenceHandler would take care of propagating
// prefs changes to observers, but that's not the case in integration tests.
arc::ArcSessionManager::Get()->NotifyArcPlayStoreEnabledChanged(true);
ArcAppListPrefs* arc_app_list_prefs = ArcAppListPrefs::Get(profile);
DCHECK(arc_app_list_prefs);
base::RunLoop run_loop;
arc_app_list_prefs->SetDefaultAppsReadyCallback(run_loop.QuitClosure());
run_loop.Run();
instance_map_[profile] =
std::make_unique<FakeAppInstance>(arc_app_list_prefs);
DCHECK(instance_map_[profile].get());
arc_app_list_prefs->app_connection_holder()->SetInstance(
instance_map_[profile].get());
WaitForInstanceReady(arc_app_list_prefs->app_connection_holder());
}
void SyncArcPackageHelper::SendRefreshPackageList(Profile* profile) {
// OnPackageListRefreshed will be called when AppInstance is ready.
// For fakeAppInstance we use SendRefreshPackageList to make sure that
// OnPackageListRefreshed will be called.
instance_map_[profile]->SendRefreshPackageList({});
}
void SyncArcPackageHelper::DisableArcService(Profile* profile) {
DCHECK(profile);
DCHECK(instance_map_[profile]);
arc::SetArcPlayStoreEnabledForProfile(profile, false);
// Usually ArcPlayStoreEnabledPreferenceHandler would take care of propagating
// prefs changes to observers, but that's not the case in integration tests.
arc::ArcSessionManager::Get()->NotifyArcPlayStoreEnabledChanged(false);
ArcAppListPrefs* arc_app_list_prefs = ArcAppListPrefs::Get(profile);
DCHECK(arc_app_list_prefs);
arc_app_list_prefs->app_connection_holder()->CloseInstance(
instance_map_[profile].get());
instance_map_.erase(profile);
arc::ArcSessionManager::Get()->Shutdown();
}
void SyncArcPackageHelper::InstallPackage(
Profile* profile,
const mojom::ArcPackageInfo& package) {
ArcAppListPrefs* arc_app_list_prefs = ArcAppListPrefs::Get(profile);
DCHECK(arc_app_list_prefs);
mojom::AppInstance* app_instance = ARC_GET_INSTANCE_FOR_METHOD(
arc_app_list_prefs->app_connection_holder(), InstallPackage);
DCHECK(app_instance);
// After this function, new package should be added to local sync service
// and install event should be sent to sync server.
app_instance->InstallPackage(package.Clone());
}
void SyncArcPackageHelper::UninstallPackage(Profile* profile,
const std::string& package_name) {
ArcAppListPrefs* arc_app_list_prefs = ArcAppListPrefs::Get(profile);
DCHECK(arc_app_list_prefs);
mojom::AppInstance* app_instance = ARC_GET_INSTANCE_FOR_METHOD(
arc_app_list_prefs->app_connection_holder(), UninstallPackage);
DCHECK(app_instance);
// After this function, package should be removed from local sync service
// and uninstall event should be sent to sync server.
app_instance->UninstallPackage(package_name);
}
// Packages from local pref are used for these test functions. Packages in local
// pref should be indentical to syncservice after syncservice is launched.
// Packagd update behavior is not synced by design.
bool SyncArcPackageHelper::ArcPackagesMatch(Profile* profile1,
Profile* profile2) {
const ArcAppListPrefs* prefs1 = ArcAppListPrefs::Get(profile1);
const ArcAppListPrefs* prefs2 = ArcAppListPrefs::Get(profile2);
DCHECK(prefs1);
DCHECK(prefs2);
const std::vector<std::string> pref1_packages =
prefs1->GetPackagesFromPrefs();
const std::vector<std::string> pref2_packages =
prefs2->GetPackagesFromPrefs();
if (pref1_packages.size() != pref2_packages.size())
return false;
for (const auto& package : pref1_packages) {
std::unique_ptr<ArcAppListPrefs::PackageInfo> package_info =
prefs2->GetPackage(package);
if (!package_info.get())
return false;
}
return true;
}
bool SyncArcPackageHelper::ArcPackageDetailsMatch(Profile* profile1,
Profile* profile2) {
const ArcAppListPrefs* prefs1 = ArcAppListPrefs::Get(profile1);
const ArcAppListPrefs* prefs2 = ArcAppListPrefs::Get(profile2);
DCHECK(prefs1);
DCHECK(prefs2);
const std::vector<std::string> pref1_packages =
prefs1->GetPackagesFromPrefs();
for (const auto& package : pref1_packages) {
std::unique_ptr<ArcAppListPrefs::PackageInfo> package1_info =
prefs1->GetPackage(package);
std::unique_ptr<ArcAppListPrefs::PackageInfo> package2_info =
prefs2->GetPackage(package);
if (!package2_info.get())
return false;
if (package1_info->package_version != package2_info->package_version)
return false;
if (package1_info->last_backup_android_id !=
package2_info->last_backup_android_id)
return false;
if (package1_info->last_backup_time != package2_info->last_backup_time)
return false;
}
return true;
}
} // namespace arc
| 35.742308 | 80 | 0.737544 | [
"vector"
] |
b80aa6684d71aad4d9bafc011f2b80240be5e3f8 | 2,433 | cc | C++ | tst/parser_ut.cc | quittle/ahoy | e71f1f2c8a648c94f85db252100c77b495adec54 | [
"Apache-2.0"
] | 2 | 2016-08-02T15:12:26.000Z | 2016-11-06T06:55:38.000Z | tst/parser_ut.cc | quittle/ahoy | e71f1f2c8a648c94f85db252100c77b495adec54 | [
"Apache-2.0"
] | 8 | 2018-02-11T21:28:30.000Z | 2021-10-02T13:36:16.000Z | tst/parser_ut.cc | quittle/ahoy | e71f1f2c8a648c94f85db252100c77b495adec54 | [
"Apache-2.0"
] | null | null | null | // Copyright (c) 2016 Dustin Toff
// Licensed under Apache License v2.0
#include "ahoy/parser.h"
#include <memory>
#include <vector>
#include <gtest/gtest.h>
namespace {
const char kProgram[] = "./program";
const char kValue[] = "value";
const char kValue2[] = "value 2";
bool parse(const ahoy::Parser& parser, const std::vector<std::string>& args) {
const uint arg_len = args.size() + 1;
const std::unique_ptr<const char*[]> array(new const char*[arg_len]);
array[0] = kProgram;
for (uint i = 0; i < arg_len - 1; i++) {
array[i + 1] = args[i].c_str();
}
return parser.Parse(arg_len, array.get());
}
} // namespace
namespace ahoy {
TEST(Parser, Empty) {
const Parser p;
EXPECT_TRUE(parse(p, {}));
EXPECT_FALSE(parse(p, { kValue }));
}
TEST(Parser, SingleOption) {
std::string param;
const Parser p = Parser().withOptions(Parameter(¶m));
EXPECT_TRUE(parse(p, {}));
EXPECT_TRUE(parse(p, { kValue }));
EXPECT_FALSE(parse(p, { kValue, kValue }));
EXPECT_EQ(kValue, param);
}
TEST(Parser, SingleNext) {
std::string param;
const Parser p = Parser().then(Parameter(¶m));
EXPECT_TRUE(parse(p, {}));
EXPECT_TRUE(parse(p, { kValue }));
EXPECT_FALSE(parse(p, { kValue, kValue }));
EXPECT_EQ(kValue, param);
}
TEST(Parser, OptionAndNext) {
std::string option;
std::string then;
const Parser p = Parser().withOptions(Parameter(&option)).then(Parameter(&then));
EXPECT_TRUE(parse(p, {}));
EXPECT_TRUE(parse(p, { kValue }));
EXPECT_EQ(kValue, option);
EXPECT_EQ("", then);
EXPECT_TRUE(parse(p, { kValue, kValue2 }));
EXPECT_EQ(kValue, option);
EXPECT_EQ(kValue2, then);
}
TEST(Parser, ProgramName) {
std::string program_name;
char const * const args[] = { kProgram };
EXPECT_TRUE(Parser().Parse(1, args, &program_name));
EXPECT_EQ(kProgram, program_name);
}
TEST(Parser, GetCurrentOptions) {
Parser parser;
ASSERT_EQ(0, parser.current_options().size());
parser.withOptions({});
ASSERT_EQ(0, parser.current_options().size());
Parameter parameter((bool*) nullptr);
parser.withOptions(parameter);
const std::vector<Parameter>& parameters = parser.current_options();
ASSERT_EQ(1, parameters.size());
ASSERT_EQ(parameter, parameters[0]);
ASSERT_EQ(std::vector<Parameter>({parameter}), parser.current_options());
}
} // namespace ahoy
| 25.082474 | 85 | 0.647349 | [
"vector"
] |
b80b349bb8d38820d43812a25b7f4b72713abda3 | 2,438 | cc | C++ | modules/planning/common/indexed_list_test.cc | seeclong/apollo | 99c8afb5ebcae2a3c9359a156a957ff03944b27b | [
"Apache-2.0"
] | 47 | 2019-09-11T01:33:22.000Z | 2022-02-28T08:02:23.000Z | modules/planning/common/indexed_list_test.cc | seeclong/apollo | 99c8afb5ebcae2a3c9359a156a957ff03944b27b | [
"Apache-2.0"
] | 7 | 2021-03-10T18:14:25.000Z | 2022-02-27T04:46:46.000Z | modules/planning/common/indexed_list_test.cc | seeclong/apollo | 99c8afb5ebcae2a3c9359a156a957ff03944b27b | [
"Apache-2.0"
] | 57 | 2019-11-22T05:56:22.000Z | 2019-12-28T08:51:10.000Z | /******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* 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
**/
#include "gtest/gtest.h"
#include "modules/common/util/util.h"
#include "modules/planning/common/indexed_list.h"
namespace apollo {
namespace planning {
using StringIndexedList = IndexedList<int, std::string>;
TEST(IndexedList, Add_ConstRef) {
StringIndexedList object;
{
ASSERT_NE(nullptr, object.Add(1, "one"));
ASSERT_NE(nullptr, object.Find(1));
ASSERT_NE(nullptr, object.Add(1, "one"));
const auto& items = object.Items();
ASSERT_EQ(nullptr, object.Find(2));
ASSERT_EQ(1, items.size());
ASSERT_EQ("one", *items[0]);
}
{
ASSERT_NE(nullptr, object.Add(2, "two"));
ASSERT_NE(nullptr, object.Add(2, "two"));
ASSERT_NE(nullptr, object.Find(1));
ASSERT_NE(nullptr, object.Find(2));
const auto& items = object.Items();
ASSERT_EQ(2, items.size());
ASSERT_EQ("one", *items[0]);
ASSERT_EQ("two", *items[1]);
}
}
TEST(IndexedList, Find) {
StringIndexedList object;
object.Add(1, "one");
auto* one = object.Find(1);
ASSERT_EQ(*one, "one");
ASSERT_NE(nullptr, one);
*one = "one_again";
const auto* one_again = object.Find(1);
ASSERT_NE(nullptr, one_again);
ASSERT_EQ("one_again", *one_again);
ASSERT_EQ(nullptr, object.Find(2));
}
TEST(IndexedList, Copy) {
StringIndexedList b_object;
b_object.Add(1, "one");
b_object.Add(2, "two");
StringIndexedList a_object;
a_object.Add(3, "three");
a_object.Add(4, "four");
a_object = b_object;
ASSERT_NE(nullptr, a_object.Find(1));
ASSERT_NE(nullptr, a_object.Find(2));
ASSERT_EQ(nullptr, a_object.Find(3));
ASSERT_EQ(nullptr, a_object.Find(4));
}
} // namespace planning
} // namespace apollo
| 29.731707 | 79 | 0.64397 | [
"object"
] |
b80f15b313f36272c24f8551ab0a738372070401 | 3,878 | hpp | C++ | python/plot/datalog.hpp | LevinJ/pypangolin | 3ac794aff96c3db103ec2bbc298ab013eaf6f6e8 | [
"MIT"
] | 221 | 2018-01-06T12:29:12.000Z | 2022-03-31T08:05:09.000Z | python/plot/datalog.hpp | LevinJ/pypangolin | 3ac794aff96c3db103ec2bbc298ab013eaf6f6e8 | [
"MIT"
] | 39 | 2018-01-11T19:51:48.000Z | 2022-03-24T00:48:12.000Z | python/plot/datalog.hpp | LevinJ/pypangolin | 3ac794aff96c3db103ec2bbc298ab013eaf6f6e8 | [
"MIT"
] | 78 | 2018-01-06T12:14:51.000Z | 2022-02-26T05:14:47.000Z | #include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <pangolin/plot/datalog.h>
namespace py = pybind11;
using namespace pybind11::literals;
namespace pangolin {
void declareDataLog(py::module & m) {
py::class_<DimensionStats>(m, "DimensionStats")
.def(py::init<>())
.def("Reset", &DimensionStats::Reset)
.def("Add", &DimensionStats::Add,
"v"_a) // (const float) -> void
.def_readwrite("isMonotonic", &DimensionStats::isMonotonic) // bool
.def_readwrite("sum", &DimensionStats::sum) // float
.def_readwrite("sum_sq", &DimensionStats::sum_sq) // float
.def_readwrite("min", &DimensionStats::min) // float
.def_readwrite("max", &DimensionStats::max) // float
;
py::class_<DataLogBlock>(m, "DataLogBlock")
.def(py::init<size_t, size_t, size_t>(),
"dim"_a, "max_samples"_a, "start_id"_a)
.def("Samples", &DataLogBlock::Samples) // -> size_t
.def("MaxSamples", &DataLogBlock::MaxSamples) // -> size_t
.def("SampleSpaceLeft", &DataLogBlock::SampleSpaceLeft) // -> size_t
.def("IsFull", &DataLogBlock::IsFull) // -> bool
.def("AddSamples", &DataLogBlock::AddSamples,
"num_samples"_a, "dimensions"_a, "data_dim_major"_a)
.def("ClearLinked", &DataLogBlock::ClearLinked)
.def("NextBlock", &DataLogBlock::NextBlock) // ->DataLogBlock*
.def("StartId", &DataLogBlock::StartId) // -> size_t
.def("DimData", &DataLogBlock::DimData,
"d"_a) // -> float*
.def("Dimensions", &DataLogBlock::Dimensions) // -> size_t
.def("Sample", &DataLogBlock::Sample,
"n"_a) // -> const float*
;
py::class_<DataLog>(m, "DataLog")
.def(py::init<unsigned int>(),
"block_samples_alloc"_a=10000)
.def("SetLabels", &DataLog::SetLabels,
"labels"_a) // (const std::vector<std::string> &) -> void
.def("Labels", &DataLog::Labels) // () -> const std::vector<std::string> &
.def("Log", (void (DataLog::*) (size_t, const float *, unsigned int)) &DataLog::Log,
"dimension"_a, "vals"_a, "samples"_a=1)
.def("Log", (void (DataLog::*) (float)) &DataLog::Log)
.def("Log", (void (DataLog::*) (float, float)) &DataLog::Log)
.def("Log", (void (DataLog::*) (float, float, float)) &DataLog::Log)
.def("Log", (void (DataLog::*) (float, float, float, float)) &DataLog::Log)
.def("Log", (void (DataLog::*) (float, float, float, float, float)) &DataLog::Log)
.def("Log", (void (DataLog::*) (float, float, float, float, float, float)) &DataLog::Log)
.def("Log", (void (DataLog::*) (float, float, float, float, float, float, float)) &DataLog::Log)
.def("Log", (void (DataLog::*) (float, float, float, float, float, float, float, float)) &DataLog::Log)
.def("Log", (void (DataLog::*) (float, float, float, float, float, float, float, float, float)) &DataLog::Log)
.def("Log", (void (DataLog::*) (float, float, float, float, float, float, float, float, float, float)) &DataLog::Log)
.def("Log", (void (DataLog::*) (const std::vector<float> &)) &DataLog::Log)
.def("Clear", &DataLog::Clear)
.def("Save", &DataLog::Save,
"filename"_a) // std::string ->
.def("FirstBlock", &DataLog::FirstBlock) // () -> const DataLogBlock*
.def("LastBlock", &DataLog::LastBlock) // () -> const DataLogBlock*
.def("Samples", &DataLog::Samples) // () -> size_t
.def("Sample", &DataLog::Sample,
"n"_a) // (int) -> const float*
.def("Stats", &DataLog::Stats,
"dim"_a) // (size_t) -> const DimensionStats&
;
}
} | 42.615385 | 125 | 0.556988 | [
"vector"
] |
b810576f7df01abfef50ba127e4a93d3a58f0b10 | 9,725 | cpp | C++ | AD-Census/ADCensusStereo.cpp | the-sword/AD-Census | fb87e4a0d0d0e48aada627cef4e5975cb53458c0 | [
"MIT"
] | null | null | null | AD-Census/ADCensusStereo.cpp | the-sword/AD-Census | fb87e4a0d0d0e48aada627cef4e5975cb53458c0 | [
"MIT"
] | null | null | null | AD-Census/ADCensusStereo.cpp | the-sword/AD-Census | fb87e4a0d0d0e48aada627cef4e5975cb53458c0 | [
"MIT"
] | null | null | null | /* -*-c++-*- AD-Census - Copyright (C) 2020.
* Author : Yingsong Li(Ethan Li) <ethan.li.whu@gmail.com>
* https://github.com/ethan-li-coding/AD-Census
* Describe : implement of ad-census stereo class
*/
#include "ADCensusStereo.h"
#include <algorithm>
#include <chrono>
#include<iostream>
#include <cstring>
using namespace std::chrono;
ADCensusStereo::ADCensusStereo(): width_(0), height_(0), img_left_(nullptr), img_right_(nullptr),
disp_left_(nullptr), disp_right_(nullptr),
is_initialized_(false) { }
ADCensusStereo::~ADCensusStereo()
{
Release();
is_initialized_ = false;
}
bool ADCensusStereo::Initialize(const sint32& width, const sint32& height, const ADCensusOption& option)
{
// ··· 赋值
// 影像尺寸
width_ = width;
height_ = height;
// 算法参数
option_ = option;
if (width <= 0 || height <= 0) {
return false;
}
//··· 开辟内存空间
const sint32 img_size = width_ * height_;
const sint32 disp_range = option_.max_disparity - option_.min_disparity;
if (disp_range <= 0) {
return false;
}
// 视差图
disp_left_ = new float32[img_size];
disp_right_ = new float32[img_size];
// 初始化代价计算器
if(!cost_computer_.Initialize(width_,height_,option_.min_disparity,option_.max_disparity)) {
is_initialized_ = false;
return is_initialized_;
}
// 初始化代价聚合器
if(!aggregator_.Initialize(width_, height_,option_.min_disparity,option_.max_disparity)) {
is_initialized_ = false;
return is_initialized_;
}
// 初始化多步优化器
if (!refiner_.Initialize(width_, height_)) {
is_initialized_ = false;
return is_initialized_;
}
is_initialized_ = disp_left_ && disp_right_;
return is_initialized_;
}
bool ADCensusStereo::Match(const uint8* img_left, const uint8* img_right, float32* disp_left)
{
if (!is_initialized_) {
return false;
}
if (img_left == nullptr || img_right == nullptr || disp_left == nullptr) {
return false;
}
img_left_ = img_left;
img_right_ = img_right;
auto start = steady_clock::now();
// 代价计算
ComputeCost();
auto end = steady_clock::now();
auto tt = duration_cast<milliseconds>(end - start);
printf("computing cost! timing : %lf s\n", tt.count() / 1000.0);
start = steady_clock::now();
// 代价聚合
CostAggregation();
end = steady_clock::now();
tt = duration_cast<milliseconds>(end - start);
printf("cost aggregating! timing : %lf s\n", tt.count() / 1000.0);
start = steady_clock::now();
// 扫描线优化
ScanlineOptimize();
end = steady_clock::now();
tt = duration_cast<milliseconds>(end - start);
printf("scanline optimizing! timing : %lf s\n", tt.count() / 1000.0);
start = steady_clock::now();
// 计算左右视图视差
ComputeDisparity();
ComputeDisparityRight();
end = steady_clock::now();
tt = duration_cast<milliseconds>(end - start);
printf("computing disparities! timing : %lf s\n", tt.count() / 1000.0);
start = steady_clock::now();
// 多步骤视差优化
MultiStepRefine();
end = steady_clock::now();
tt = duration_cast<milliseconds>(end - start);
printf("multistep refining! timing : %lf s\n", tt.count() / 1000.0);
start = steady_clock::now();
// 输出视差图
memcpy(disp_left, disp_left_, height_ * width_ * sizeof(float32));
end = steady_clock::now();
tt = duration_cast<milliseconds>(end - start);
printf("output disparities! timing : %lf s\n", tt.count() / 1000.0);
return true;
}
bool ADCensusStereo::Reset(const uint32& width, const uint32& height, const ADCensusOption& option)
{
// 释放内存
Release();
// 重置初始化标记
is_initialized_ = false;
// 初始化
return Initialize(width, height, option);
}
void ADCensusStereo::ComputeCost()
{
// 设置代价计算器数据
cost_computer_.SetData(img_left_, img_right_);
// 设置代价计算器参数
cost_computer_.SetParams(option_.lambda_ad, option_.lambda_census);
// 计算代价
cost_computer_.Compute();
}
void ADCensusStereo::CostAggregation()
{
// 设置聚合器数据
aggregator_.SetData(img_left_, img_right_, cost_computer_.get_cost_ptr());
// 设置聚合器参数
aggregator_.SetParams(option_.cross_L1, option_.cross_L2, option_.cross_t1, option_.cross_t2);
// 代价聚合
aggregator_.Aggregate(4);
}
void ADCensusStereo::ScanlineOptimize()
{
// 设置优化器数据
scan_line_.SetData(img_left_, img_right_, cost_computer_.get_cost_ptr(), aggregator_.get_cost_ptr());
// 设置优化器参数
scan_line_.SetParam(width_, height_, option_.min_disparity, option_.max_disparity, option_.so_p1, option_.so_p2, option_.so_tso);
// 扫描线优化
scan_line_.Optimize();
}
void ADCensusStereo::MultiStepRefine()
{
// 设置多步优化器数据
refiner_.SetData(img_left_, aggregator_.get_cost_ptr(), aggregator_.get_arms_ptr(), disp_left_, disp_right_);
// 设置多步优化器参数
refiner_.SetParam(option_.min_disparity, option_.max_disparity, option_.irv_ts, option_.irv_th, option_.lrcheck_thres,
option_.do_lr_check,option_.do_filling,option_.do_filling, option_.do_discontinuity_adjustment);
// 多步优化
refiner_.Refine();
}
void ADCensusStereo::ComputeDisparity()
{
const sint32& min_disparity = option_.min_disparity;
const sint32& max_disparity = option_.max_disparity;
const sint32 disp_range = max_disparity - min_disparity;
if (disp_range <= 0) {
return;
}
// 左影像视差图
const auto disparity = disp_left_;
// 左影像聚合代价数组
const auto cost_ptr = aggregator_.get_cost_ptr();
const sint32 width = width_;
const sint32 height = height_;
// 为了加快读取效率,把单个像素的所有代价值存储到局部数组里
std::vector<float32> cost_local(disp_range);
// ---逐像素计算最优视差
for (sint32 i = 0; i < height; i++) {
for (sint32 j = 0; j < width; j++) {
float32 min_cost = Large_Float;
sint32 best_disparity = 0;
// ---遍历视差范围内的所有代价值,输出最小代价值及对应的视差值
for (sint32 d = min_disparity; d < max_disparity; d++) {
const sint32 d_idx = d - min_disparity;
const auto& cost = cost_local[d_idx] = cost_ptr[i * width * disp_range + j * disp_range + d_idx];
if (min_cost > cost) {
min_cost = cost;
best_disparity = d;
}
}
// ---子像素拟合
if (best_disparity == min_disparity || best_disparity == max_disparity - 1) {
disparity[i * width + j] = Invalid_Float;
continue;
}
// 最优视差前一个视差的代价值cost_1,后一个视差的代价值cost_2
const sint32 idx_1 = best_disparity - 1 - min_disparity;
const sint32 idx_2 = best_disparity + 1 - min_disparity;
const float32 cost_1 = cost_local[idx_1];
const float32 cost_2 = cost_local[idx_2];
// 解一元二次曲线极值
const float32 denom = cost_1 + cost_2 - 2 * min_cost;
if (denom != 0.0f) {
disparity[i * width + j] = static_cast<float32>(best_disparity) + (cost_1 - cost_2) / (denom * 2.0f);
}
else {
disparity[i * width + j] = static_cast<float32>(best_disparity);
}
}
}
}
void ADCensusStereo::ComputeDisparityRight()
{
const sint32& min_disparity = option_.min_disparity;
const sint32& max_disparity = option_.max_disparity;
const sint32 disp_range = max_disparity - min_disparity;
if (disp_range <= 0) {
return;
}
// 右影像视差图
const auto disparity = disp_right_;
// 左影像聚合代价数组
const auto cost_ptr = aggregator_.get_cost_ptr();
const sint32 width = width_;
const sint32 height = height_;
// 为了加快读取效率,把单个像素的所有代价值存储到局部数组里
std::vector<float32> cost_local(disp_range);
// ---逐像素计算最优视差
// 通过左影像的代价,获取右影像的代价
// 右cost(xr,yr,d) = 左cost(xr+d,yl,d)
for (sint32 i = 0; i < height; i++) {
for (sint32 j = 0; j < width; j++) {
float32 min_cost = Large_Float;
sint32 best_disparity = 0;
// ---统计候选视差下的代价值
for (sint32 d = min_disparity; d < max_disparity; d++) {
const sint32 d_idx = d - min_disparity;
const sint32 col_left = j + d;
if (col_left >= 0 && col_left < width) {
const auto& cost = cost_local[d_idx] = cost_ptr[i * width * disp_range + col_left * disp_range + d_idx];
if (min_cost > cost) {
min_cost = cost;
best_disparity = d;
}
}
else {
cost_local[d_idx] = Large_Float;
}
}
// ---子像素拟合
if (best_disparity == min_disparity || best_disparity == max_disparity - 1) {
disparity[i * width + j] = best_disparity;
continue;
}
// 最优视差前一个视差的代价值cost_1,后一个视差的代价值cost_2
const sint32 idx_1 = best_disparity - 1 - min_disparity;
const sint32 idx_2 = best_disparity + 1 - min_disparity;
const float32 cost_1 = cost_local[idx_1];
const float32 cost_2 = cost_local[idx_2];
// 解一元二次曲线极值
const float32 denom = cost_1 + cost_2 - 2 * min_cost;
if (denom != 0.0f) {
disparity[i * width + j] = static_cast<float32>(best_disparity) + (cost_1 - cost_2) / (denom * 2.0f);
}
else {
disparity[i * width + j] = static_cast<float32>(best_disparity);
}
}
}
}
void ADCensusStereo::Release()
{
SAFE_DELETE(disp_left_);
SAFE_DELETE(disp_right_);
}
| 30.390625 | 133 | 0.604524 | [
"vector"
] |
b8160a87358e2351701ba1d221ae2c7a86aab43a | 9,378 | cxx | C++ | cgv/media/mesh/obj_loader.cxx | MarioHenze/cgv | bacb2d270b1eecbea1e933b8caad8d7e11d807c2 | [
"BSD-3-Clause"
] | 11 | 2017-09-30T12:21:55.000Z | 2021-04-29T21:31:57.000Z | cgv/media/mesh/obj_loader.cxx | MarioHenze/cgv | bacb2d270b1eecbea1e933b8caad8d7e11d807c2 | [
"BSD-3-Clause"
] | 2 | 2017-07-11T11:20:08.000Z | 2018-03-27T12:09:02.000Z | cgv/media/mesh/obj_loader.cxx | MarioHenze/cgv | bacb2d270b1eecbea1e933b8caad8d7e11d807c2 | [
"BSD-3-Clause"
] | 24 | 2018-03-27T11:46:16.000Z | 2021-05-01T20:28:34.000Z | #include "obj_loader.h"
#include <cgv/utils/file.h>
#include <cgv/type/standard_types.h>
using namespace cgv::utils::file;
using namespace cgv::type;
using namespace cgv::media::illum;
#ifdef WIN32
#pragma warning (disable:4996)
#endif
namespace cgv {
namespace media {
namespace mesh {
face_info::face_info(unsigned _nr, unsigned _vi0, int _ti0, int _ni0, unsigned _gi, unsigned _mi)
: degree(_nr),
first_vertex_index(_vi0),
first_texcoord_index(_ti0),
first_normal_index(_ni0),
group_index(_gi),
material_index(_mi)
{
}
/// overide this function to process a vertex
template <typename T>
void obj_loader_generic<T>::process_vertex(const v3d_type& p)
{
vertices.push_back(p);
}
/// overide this function to process a texcoord
template <typename T>
void obj_loader_generic<T>::process_texcoord(const v2d_type& t)
{
texcoords.push_back(t);
}
/// overide this function to process a normal
template <typename T>
void obj_loader_generic<T>::process_normal(const v3d_type& n)
{
normals.push_back(n);
}
template <typename T>
void obj_loader_generic<T>::process_color(const color_type& c)
{
colors.push_back(c);
}
/// overide this function to process a face
template <typename T>
void obj_loader_generic<T>::process_face(unsigned vcount, int *vertices,
int *texcoords, int *normals)
{
this->convert_to_positive(vcount,vertices,texcoords,normals,
(unsigned)this->vertices.size(), (unsigned)this->normals.size(), (unsigned)this->texcoords.size());
faces.push_back(face_info(vcount,(unsigned)vertex_indices.size(),
texcoords == 0 ? -1 : (int)texcoord_indices.size(),
normals == 0 ? -1 : (int)normal_indices.size(),
this->get_current_group(),this->get_current_material()));
unsigned i;
for (i=0; i<vcount; ++i)
vertex_indices.push_back(vertices[i]);
if (normals)
for (i=0; i<vcount; ++i)
normal_indices.push_back(normals[i]);
if (texcoords)
for (i=0; i<vcount; ++i)
texcoord_indices.push_back(texcoords[i]);
}
/// overide this function to process a group given by name
template <typename T>
void obj_loader_generic<T>::process_group(const std::string& name, const std::string& parameters)
{
group_info gi;
gi.name = name;
gi.parameters = parameters;
groups.push_back(gi);
}
/// process a material definition
template <typename T>
void obj_loader_generic<T>::process_material(const obj_material& mtl, unsigned idx)
{
if (idx >= materials.size())
materials.push_back(mtl);
else
materials[idx] = mtl;
}
template <typename T>
const char* get_bin_extension()
{
return ".bin_obj";
}
template <>
const char* get_bin_extension<float>()
{
return ".bin_objf";
}
/// overloads reading to support binary file format
template <typename T>
bool obj_loader_generic<T>::read_obj(const std::string& file_name)
{
// check if binary file exists
std::string bin_fn = drop_extension(file_name) + get_bin_extension<T>();
if (exists(bin_fn) &&
get_last_write_time(bin_fn) > get_last_write_time(file_name) &&
read_obj_bin(bin_fn)) {
this->path_name = get_path(file_name);
if (!this->path_name.empty())
this->path_name += "/";
return true;
}
vertices.clear();
normals.clear();
texcoords.clear();
faces.clear();
colors.clear();
if (!obj_reader_generic<T>::read_obj(file_name))
return false;
// correct colors in case of 8bit colors
unsigned i;
bool do_correct = false;
for (i = 0; i < colors.size(); ++i) {
if (colors[i][0] > 5 ||colors[i][1] > 5 ||colors[i][2] > 5) {
do_correct = true;
break;
}
}
if (do_correct) {
for (i = 0; i < colors.size(); ++i) {
colors[i] *= 1.0f/255;
}
}
write_obj_bin(bin_fn);
return true;
}
template <typename T>
bool obj_loader_generic<T>::read_obj_bin(const std::string& file_name)
{
// open binary file
FILE* fp = fopen(file_name.c_str(), "rb");
if (!fp)
return false;
// read element count
uint32_type v, n, t, f, h, g, m;
if (1!=fread(&v, sizeof(uint32_type), 1, fp) ||
1!=fread(&n, sizeof(uint32_type), 1, fp) ||
1!=fread(&t, sizeof(uint32_type), 1, fp) ||
1!=fread(&f, sizeof(uint32_type), 1, fp) ||
1!=fread(&h, sizeof(uint32_type), 1, fp) ||
1!=fread(&g, sizeof(uint32_type), 1, fp) ||
1!=fread(&m, sizeof(uint32_type), 1, fp)) {
fclose(fp);
return false;
}
bool has_colors = false;
if (v > 0x7FFFFFFF) {
v = 0xFFFFFFFF - v;
has_colors = true;
}
// reserve space
vertices.resize(v);
if (has_colors)
colors.resize(v);
vertex_indices.resize(h);
if (v != fread(&vertices[0], sizeof(v3d_type), v, fp) ||
h > 0 && h != fread(&vertex_indices[0], sizeof(unsigned), h, fp) )
{
fclose(fp);
return false;
}
if (has_colors) {
if (v != fread(&colors[0], sizeof(color_type), v, fp))
{
fclose(fp);
return false;
}
}
if (n > 0) {
normals.resize(n);
normal_indices.resize(h);
if (n != fread(&normals[0], sizeof(v3d_type), n, fp) ||
h > 0 && h != fread(&normal_indices[0], sizeof(unsigned), h, fp) )
{
fclose(fp);
return false;
}
}
if (t > 0) {
texcoords.resize(t);
texcoord_indices.resize(h);
if (t != fread(&texcoords[0], sizeof(v2d_type), t, fp) ||
h > 0 && h != fread(&texcoord_indices[0], sizeof(unsigned), h, fp) )
{
fclose(fp);
return false;
}
}
faces.resize(f);
if (f > 0 && f != fread(&faces[0], sizeof(face_info), f, fp))
{
fclose(fp);
return false;
}
groups.resize(g);
for (unsigned gi=0; gi<g; ++gi) {
if (!read_string_bin(groups[gi].name, fp) ||
!read_string_bin(groups[gi].parameters, fp))
{
fclose(fp);
return false;
}
}
if (1 != fread(&this->have_default_material, sizeof(bool), 1, fp))
{
fclose(fp);
return false;
}
if (this->have_default_material)
materials.push_back(obj_material());
for (unsigned mi=0; mi<m; ++mi) {
std::string s;
if (!read_string_bin(s, fp)) {
fclose(fp);
return false;
}
obj_reader_generic<T>::read_mtl(s);
}
fclose(fp);
return true;
}
/// prepare for reading another file
template <typename T>
void obj_loader_generic<T>::clear()
{
obj_reader_generic<T>::clear();
vertices.clear();
normals.clear();
texcoords.clear();
vertex_indices.clear();
normal_indices.clear();
texcoord_indices.clear();
faces.clear();
groups.clear();
materials.clear();
}
template <typename T>
bool obj_loader_generic<T>::write_obj_bin(const std::string& file_name) const
{
// open binary file
FILE* fp = fopen(file_name.c_str(), "wb");
if (!fp)
return false;
// read element count
uint32_type v = (unsigned) vertices.size(),
n = (unsigned) normals.size(),
t = (unsigned) texcoords.size(),
f = (unsigned) faces.size(),
h = (unsigned) vertex_indices.size(),
g = (unsigned) groups.size(),
m = (unsigned) this->mtl_lib_files.size();
uint32_type v_write = v;
bool has_colors = (colors.size() == vertices.size());
if (has_colors)
v_write = 0xFFFFFFFF - v;
if (1!=fwrite(&v_write, sizeof(uint32_type), 1, fp) ||
1!=fwrite(&n, sizeof(uint32_type), 1, fp) ||
1!=fwrite(&t, sizeof(uint32_type), 1, fp) ||
1!=fwrite(&f, sizeof(uint32_type), 1, fp) ||
1!=fwrite(&h, sizeof(uint32_type), 1, fp) ||
1!=fwrite(&g, sizeof(uint32_type), 1, fp) ||
1!=fwrite(&m, sizeof(uint32_type), 1, fp)) {
fclose(fp);
return false;
}
if (v != fwrite(&vertices[0], sizeof(v3d_type), v, fp) ||
h > 0 && h != fwrite(&vertex_indices[0], sizeof(unsigned), h, fp) )
{
fclose(fp);
return false;
}
if (has_colors) {
if (v != fwrite(&colors[0], sizeof(color_type), v, fp) )
{
fclose(fp);
return false;
}
}
if (n > 0) {
if (n != fwrite(&normals[0], sizeof(v3d_type), n, fp) ||
h > 0 && h != fwrite(&normal_indices[0], sizeof(unsigned), h, fp) )
{
fclose(fp);
return false;
}
}
if (t > 0) {
if (t != fwrite(&texcoords[0], sizeof(v2d_type), t, fp) ||
h > 0 && h != fwrite(&texcoord_indices[0], sizeof(unsigned), h, fp) )
{
fclose(fp);
return false;
}
}
if (f > 0 && f != fwrite(&faces[0], sizeof(face_info), f, fp))
{
fclose(fp);
return false;
}
for (unsigned gi=0; gi<g; ++gi) {
if (!write_string_bin(groups[gi].name, fp) ||
!write_string_bin(groups[gi].parameters, fp))
{
fclose(fp);
return false;
}
}
if (1 != fwrite(&this->have_default_material, sizeof(bool), 1, fp))
{
fclose(fp);
return false;
}
std::set<std::string>::const_iterator mi = this->mtl_lib_files.begin();
for (; mi != this->mtl_lib_files.end(); ++mi) {
if (!write_string_bin(*mi, fp))
{
fclose(fp);
return false;
}
}
fclose(fp);
return true;
}
template <typename T>
void obj_loader_generic<T>::show_stats() const
{
std::cout << "num vertices "<<vertices.size()<<std::endl;
std::cout << "num normals "<<normals.size()<<std::endl;
std::cout << "num texcoords "<<texcoords.size()<<std::endl;
std::cout << "num faces "<<faces.size()<<std::endl;
std::cout << "num materials "<<materials.size()<<std::endl;
std::cout << "num groups "<<groups.size()<<std::endl;
}
template class obj_loader_generic < float >;
template class obj_loader_generic < double >;
}
}
} | 24.549738 | 102 | 0.62444 | [
"mesh"
] |
b81a164d7e6f7f5e862ec7db278406ff3b8e05b4 | 6,018 | cpp | C++ | Software_Final Version/Inertial_Navigation_with_QT/read_imr_file.cpp | GimHuang/inertial-navigation | 88c7aea844c26b5a2b7a2314ba4ca428c532d8f6 | [
"MIT"
] | 2 | 2021-05-30T18:17:17.000Z | 2021-11-24T07:16:49.000Z | Software_Final Version/Inertial_Navigation_with_QT/read_imr_file.cpp | jhuang-86/inertial-navigation | 88c7aea844c26b5a2b7a2314ba4ca428c532d8f6 | [
"MIT"
] | null | null | null | Software_Final Version/Inertial_Navigation_with_QT/read_imr_file.cpp | jhuang-86/inertial-navigation | 88c7aea844c26b5a2b7a2314ba4ca428c532d8f6 | [
"MIT"
] | 4 | 2021-04-16T08:51:59.000Z | 2021-12-31T01:13:08.000Z | #include"read_imr_file.h"
void imr_data::read_imr_header(fstream& imrfile, IMR_Header* imrheader)
{
/*
*************************************************************************************
*func: read_imr_header
*@Param: fstream &imrfile 文件类
*@Param: IMR_Header *imrheader 结构体指针,存放文件头数据
*@Return:
*@Note: 读取imr头文件
*creator:Jin Huang
*organization:sdust
*e-mail:kim.huang.j@qq.com
*************************************************************************************
*/
for (int i = 0; i < 8; i++)
{
imrfile.read((char*)&imrheader->szHeader[i], sizeof(char));
}
imrfile.read((char*)&imrheader->bIsIntelOrMotorola, sizeof(int8_t));
imrfile.read((char*)&imrheader->dVersionNumber, sizeof(double));
imrfile.read((char*)&imrheader->bDeltaTheta, sizeof(int32_t));
imrfile.read((char*)&imrheader->bDeltaVelocity, sizeof(int32_t));
imrfile.read((char*)&imrheader->dDataRateHz, sizeof(double));
imrfile.read((char*)&imrheader->dGyroScaleFactor, sizeof(double));
imrfile.read((char*)&imrheader->dAccelScaleFactor, sizeof(double));
imrfile.read((char*)&imrheader->iUtcOrGpsTime, sizeof(int32_t));
imrfile.read((char*)&imrheader->iRcvTimeOrCorrTime, sizeof(int32_t));
imrfile.read((char*)&imrheader->dTimeTagBias, sizeof(double));
for (int i = 0; i < 32; i++)
{
imrfile.read((char*)&imrheader->szImuName[i], sizeof(char));
}
for (int i = 0; i < 4; i++)
{
imrfile.read((char*)&imrheader->reserved1[i], sizeof(unit8_t));
}
for (int i = 0; i < 32; i++)
{
imrfile.read((char*)&imrheader->szProgramName[i], sizeof(char));
}
for (int i = 0; i < 12; i++)
{
imrfile.read((char*)&imrheader->tCreate[i], sizeof(char));
}
imrfile.read((char*)&imrheader->bLeverArmValid, sizeof(bool));
imrfile.read((char*)&imrheader->lXoffset, sizeof(int32_t));
imrfile.read((char*)&imrheader->lYoffset, sizeof(int32_t));
imrfile.read((char*)&imrheader->lZoffset, sizeof(int32_t));
for (int i = 0; i < 354; i++)
{
imrfile.read((char*)&imrheader->Reserved[i], sizeof(int8_t));
}
//imrfile.close();
}
void imr_data::read_imr_data(fstream& imrfile, vector<adj_IMR_Record>& adj_data, IMR_Header imr_header)
{
/*
*************************************************************************************
*func: read_imr_data
*@Param: fstream& imrfile 文件类
*@Param: vector<adj_IMR_Record> &adj_data 利用vector 存放的校正后imr数据的结构体数组
*@Param: IMR_Header imr_header imr数据文件头
*@Return:
*@Note: 读取imr数据部分,并通过imr_header 进行校正,通过vector<adj_IMR_Record> &adj_data 返回
*creator:Jin Huang
*organization:sdust
*e-mail:kim.huang.j@qq.com
*************************************************************************************
*/
imrfile.seekg(512, ios::beg); // 跳过文件头部分
IMR_Record* imr_data = new IMR_Record;
adj_IMR_Record* temp_data = new adj_IMR_Record;
while (!imrfile.eof())
{
imrfile.read((char*)imr_data, sizeof(IMR_Record));
temp_data->Time = imr_data->Time;
#ifdef IsCorrect
if (!imr_header.bDeltaTheta) // 对陀螺仪测的的陀螺量加以改正--->得到 度/s m/s^2
{
temp_data->gx = imr_data->gx * imr_header.dGyroScaleFactor;
temp_data->gy = imr_data->gy * imr_header.dGyroScaleFactor;
temp_data->gz = imr_data->gz * imr_header.dGyroScaleFactor;
}
else
{
temp_data->gx = imr_data->gx * imr_header.dGyroScaleFactor * imr_header.dDataRateHz;
temp_data->gy = imr_data->gy * imr_header.dGyroScaleFactor * imr_header.dDataRateHz;
temp_data->gz = imr_data->gz * imr_header.dGyroScaleFactor * imr_header.dDataRateHz;
}
if (!imr_header.bDeltaVelocity)
{
temp_data->ax = imr_data->ax * imr_header.dAccelScaleFactor;
temp_data->ay = imr_data->ay * imr_header.dAccelScaleFactor;
temp_data->az = imr_data->az * imr_header.dAccelScaleFactor;
}
else
{
temp_data->ax = imr_data->ax * imr_header.dAccelScaleFactor * imr_header.dDataRateHz;
temp_data->ay = imr_data->ay * imr_header.dAccelScaleFactor * imr_header.dDataRateHz;
temp_data->az = imr_data->az * imr_header.dAccelScaleFactor * imr_header.dDataRateHz;
}
#endif // IsCorrect
#ifndef IsCorrect // 对陀螺仪测的的陀螺量加以改正--->得到 度 m/s
if (!imr_header.bDeltaTheta)
{
temp_data->gx = (double)imr_data->gx;
temp_data->gy = (double)imr_data->gy;
temp_data->gz = (double)imr_data->gz;
}
else
{
temp_data->gx = imr_data->gx * imr_header.dGyroScaleFactor;
temp_data->gy = imr_data->gy * imr_header.dGyroScaleFactor;
temp_data->gz = imr_data->gz * imr_header.dGyroScaleFactor;
}
if (!imr_header.bDeltaVelocity)
{
temp_data->ax = (double)imr_data->ax;
temp_data->ay = (double)imr_data->ay;
temp_data->az = (double)imr_data->az;
}
else
{
temp_data->ax = imr_data->ax * imr_header.dAccelScaleFactor;
temp_data->ay = imr_data->ay * imr_header.dAccelScaleFactor;
temp_data->az = imr_data->az * imr_header.dAccelScaleFactor;
}
#endif // !IsCorrect
adj_data.push_back(*temp_data);
}
imrfile.close();
}
void imr_data::read_data(char* file_path)
{
file_header = new IMR_Header;
fstream imrfile(file_path, ios::in | ios::binary); // 打开文件
if (imrfile)
{
read_imr_header(imrfile, file_header); // 读取头文件
read_imr_data(imrfile, file_data, *file_header); // 读取数据文件
std::cout << "Finish Reading, The total data num is: " << file_data.size() << endl;
}
else
{
cerr << "Open file error!" << endl;
exit(0);
}
}
void imr_data::initial()
{
// 初始化、重置对象
file_header = new IMR_Header;
file_data.clear();
}
| 36.920245 | 103 | 0.584247 | [
"vector"
] |
b81c76371f5c56c41dc4db8cc87374b5e305535d | 18,625 | cpp | C++ | src/picross/src/work_grid.cpp | pierre-dejoue/picross-solver | c4d85d66b7537e4651d411cb6480a34bb4fcf51b | [
"MIT"
] | null | null | null | src/picross/src/work_grid.cpp | pierre-dejoue/picross-solver | c4d85d66b7537e4651d411cb6480a34bb4fcf51b | [
"MIT"
] | null | null | null | src/picross/src/work_grid.cpp | pierre-dejoue/picross-solver | c4d85d66b7537e4651d411cb6480a34bb4fcf51b | [
"MIT"
] | null | null | null | /*******************************************************************************
* PICROSS SOLVER
*
* Copyright (c) 2010-2021 Pierre DEJOUE
******************************************************************************/
#include "work_grid.h"
#include "line.h"
#include <picross/picross.h>
#include <algorithm>
#include <cassert>
namespace picross
{
constexpr unsigned int LineSelectionPolicy_RampUpMaxNbAlternatives::min_nb_alternatives;
constexpr unsigned int LineSelectionPolicy_RampUpMaxNbAlternatives::max_nb_alternatives;
namespace
{
std::vector<LineConstraint> row_constraints_from(const InputGrid& grid)
{
std::vector<LineConstraint> rows;
rows.reserve(grid.rows.size());
std::transform(grid.rows.cbegin(), grid.rows.cend(), std::back_inserter(rows), [](const InputGrid::Constraint& c) { return LineConstraint(Line::ROW, c); });
return rows;
}
std::vector<LineConstraint> column_constraints_from(const InputGrid& grid)
{
std::vector<LineConstraint> cols;
cols.reserve(grid.cols.size());
std::transform(grid.cols.cbegin(), grid.cols.cend(), std::back_inserter(cols), [](const InputGrid::Constraint& c) { return LineConstraint(Line::COL, c); });
return cols;
}
} // namespace
template <typename LineSelectionPolicy>
WorkGrid<LineSelectionPolicy>::WorkGrid(const InputGrid& grid, Solver::Solutions* solutions, GridStats* stats, Solver::Observer observer, Solver::Abort abort_function)
: OutputGrid(grid.cols.size(), grid.rows.size(), grid.name)
, rows(row_constraints_from(grid))
, cols(column_constraints_from(grid))
, saved_solutions(solutions)
, stats(stats)
, observer(std::move(observer))
, abort_function(std::move(abort_function))
, max_nb_alternatives(LineSelectionPolicy::initial_max_nb_alternatives())
, nested_level(0u)
, binomial(new BinomialCoefficientsCache())
{
assert(cols.size() == get_width());
assert(rows.size() == get_height());
assert(saved_solutions != nullptr);
// Other initializations
line_completed[Line::ROW].resize(get_height(), false);
line_completed[Line::COL].resize(get_width(), false);
line_to_be_reduced[Line::ROW].resize(get_height(), false);
line_to_be_reduced[Line::COL].resize(get_width(), false);
nb_alternatives[Line::ROW].resize(get_height(), 0u);
nb_alternatives[Line::COL].resize(get_width(), 0u);
}
// Shallow copy (does not copy the list of alternatives)
template <typename LineSelectionPolicy>
WorkGrid<LineSelectionPolicy>::WorkGrid(const WorkGrid& parent, unsigned int nested_level)
: OutputGrid(static_cast<const OutputGrid&>(parent))
, rows(parent.rows)
, cols(parent.cols)
, saved_solutions(parent.saved_solutions)
, stats(parent.stats)
, observer(parent.observer)
, abort_function(parent.abort_function)
, max_nb_alternatives(LineSelectionPolicy::initial_max_nb_alternatives())
, nested_level(nested_level)
, binomial(nullptr) // only used on the first pass on the grid threfore on nested_level == 0
{
assert(nested_level > 0u);
line_completed[Line::ROW] = parent.line_completed[Line::ROW];
line_completed[Line::COL] = parent.line_completed[Line::COL];
line_to_be_reduced[Line::ROW] = parent.line_to_be_reduced[Line::ROW];
line_to_be_reduced[Line::COL] = parent.line_to_be_reduced[Line::COL];
nb_alternatives[Line::ROW] = parent.nb_alternatives[Line::ROW];
nb_alternatives[Line::COL] = parent.nb_alternatives[Line::COL];
// Stats
if (stats != nullptr && nested_level > stats->max_nested_level)
{
stats->max_nested_level = nested_level;
}
// Solver::Observer
if (observer)
{
observer(Solver::Event::BRANCHING, nullptr, nested_level);
}
}
template <typename LineSelectionPolicy>
Solver::Status WorkGrid<LineSelectionPolicy>::solve(unsigned int max_nb_solutions)
{
auto status = full_grid_pass(nested_level == 0u); // If nested_level == 0, this is the first pass on the grid
if (status.contradictory)
return Solver::Status::CONTRADICTORY_GRID;
bool grid_completed = all_lines_completed();
// While the reduce method is making progress, call it!
while (!grid_completed)
{
status = full_grid_pass();
if (status.contradictory)
return Solver::Status::CONTRADICTORY_GRID;
grid_completed = all_lines_completed();
// Exit loop either if the grid has completed or if the condition to switch the branching search is met
if (LineSelectionPolicy::switch_to_branching(max_nb_alternatives, status.grid_changed, status.skipped_lines, nested_level))
break;
// Max number of alternatives for the next full grid pass
max_nb_alternatives = LineSelectionPolicy::get_max_nb_alternatives(max_nb_alternatives, status.grid_changed, status.skipped_lines, nested_level);
}
// Are we done?
if (grid_completed)
{
if (observer)
{
observer(Solver::Event::SOLVED_GRID, nullptr, nested_level);
}
save_solution();
return Solver::Status::OK;
}
// If we are not, we have to make an hypothesis and continue based on that
else
{
// Find the row or column not yet solved with the minimal alternative lines.
// That is the min of all alternatives greater or equal to 2.
unsigned int min_alt = 0u;
Line::Type found_line_type = Line::ROW;
unsigned int found_line_index = 0u;
for (const auto& type : { Line::ROW, Line::COL })
{
for (unsigned int idx = 0u; idx < nb_alternatives[type].size(); idx++)
{
const auto nb_alt = line_to_be_reduced[type][idx] ? 0u : nb_alternatives[type][idx];
if (nb_alt >= 2u && (min_alt < 2u || nb_alt < min_alt))
{
min_alt = nb_alt;
found_line_type = type;
found_line_index = idx;
}
}
}
if (min_alt == 0u)
{
Solver::Status::CONTRADICTORY_GRID;
}
// Select the row or column with the minimal number of alternatives
const LineConstraint& line_constraint = found_line_type == Line::ROW ? rows.at(found_line_index) : cols.at(found_line_index);
const Line known_tiles = get_line(found_line_type, found_line_index);
guess_list_of_all_alternatives = line_constraint.build_all_possible_lines(known_tiles);
assert(guess_list_of_all_alternatives.size() == min_alt);
// Guess!
return guess(max_nb_solutions);
}
}
template <typename LineSelectionPolicy>
bool WorkGrid<LineSelectionPolicy>::all_lines_completed() const
{
const bool all_rows = std::all_of(line_completed[Line::ROW].cbegin(), line_completed[Line::ROW].cend(), [](bool b) { return b; });
const bool all_cols = std::all_of(line_completed[Line::COL].cbegin(), line_completed[Line::COL].cend(), [](bool b) { return b; });
// The logical AND is important here: in the case an hypothesis is made on a row (resp. a column), it is marked as completed
// but the constraints on the columns (resp. the rows) may not be all satisfied.
return all_rows && all_cols;
}
template <typename LineSelectionPolicy>
bool WorkGrid<LineSelectionPolicy>::set_line(const Line& line)
{
bool line_changed = false;
const size_t line_index = line.get_index();
const Line origin_line = get_line(line.get_type(), line_index);
const auto width = static_cast<unsigned int>(get_width());
const auto height = static_cast<unsigned int>(get_height());
assert(line.size() == line.get_type() == Line::ROW ? width : height);
const Line::Container& tiles = line.get_tiles();
if (line.get_type() == Line::ROW)
{
for (unsigned int tile_index = 0u; tile_index < line.size(); tile_index++)
{
// modify grid
const bool tile_changed = set(tile_index, line_index, tiles[tile_index]);
if (tile_changed)
{
// mark the impacted column with flag "to be reduced"
line_to_be_reduced[Line::COL][tile_index] = true;
LineSelectionPolicy::estimate_nb_alternatives(nb_alternatives[Line::COL][tile_index]);
line_changed = true;
}
}
}
else
{
for (unsigned int tile_index = 0u; tile_index < line.size(); tile_index++)
{
// modify grid
const bool tile_changed = set(line_index, tile_index, tiles[tile_index]);
if (tile_changed)
{
// mark the impacted row with flag "to be reduced"
line_to_be_reduced[Line::ROW][tile_index] = true;
LineSelectionPolicy::estimate_nb_alternatives(nb_alternatives[Line::ROW][tile_index]);
line_changed = true;
}
}
}
if (observer && line_changed)
{
const Line delta = line_delta(origin_line, get_line(line.get_type(), line_index));
observer(Solver::Event::DELTA_LINE, &delta, nested_level);
}
return line_changed;
}
// On the first pass of the grid, assume that the color of every tile in the line is unknown
// and compute the trivial reduction and number of alternatives
template <typename LineSelectionPolicy>
typename WorkGrid<LineSelectionPolicy>::PassStatus WorkGrid<LineSelectionPolicy>::single_line_initial_pass(Line::Type type, unsigned int index)
{
PassStatus status;
const LineConstraint& constraint = type == Line::ROW ? rows.at(index) : cols.at(index);
const auto line_size = static_cast<unsigned int>(type == Line::ROW ? get_width() : get_height());
assert(binomial);
Line reduced_line(type, index, line_size); // All Tile::UNKNOWN
// Compute the trivial reduction if it exists and the number of alternatives
const auto pair = constraint.line_trivial_reduction(reduced_line, *binomial);
const auto nb_alt = pair.second;
assert(nb_alt > 0u);
if (stats != nullptr) { stats->max_initial_nb_alternatives = std::max(stats->max_initial_nb_alternatives, nb_alt); }
// If the reduced line is not compatible with the information already present in the grid
// then the row and column constraints are contradictory.
if (!get_line(type, index).compatible(reduced_line))
{
status.contradictory = true;
return status;
}
// Set line
status.grid_changed = set_line(reduced_line);
// Must be set after set_line (it modifies nb_alternatives)
nb_alternatives[type][index] = nb_alt;
if (nb_alt == 1u)
{
// Line is completed
line_completed[type][index] = true;
line_to_be_reduced[type][index] = false;
}
else
{
// During a normal pass line_to_be_reduced is set to false after a line reduction has been performed.
// Here since we are computing a trivial reduction assuming the initial line is completly unknown we
// are ignoring tiles that are possibly already set. In such a case, we need to redo a reduction
// on the next full grid pass.
const Line new_line = get_line(type, index);
if (reduced_line == new_line)
{
line_completed[type][index] = false;
line_to_be_reduced[type][index] = false;
}
else
{
line_completed[type][index] = is_fully_defined(new_line);
line_to_be_reduced[type][index] = !line_completed[type][index];
if (line_completed[type][index]) { nb_alternatives[type][index] = 1u; }
}
}
return status;
}
template <typename LineSelectionPolicy>
typename WorkGrid<LineSelectionPolicy>::PassStatus WorkGrid<LineSelectionPolicy>::single_line_pass(Line::Type type, unsigned int index)
{
assert(line_completed[type][index] == false);
assert(line_to_be_reduced[type][index] == true);
if (stats != nullptr) { stats->nb_single_line_pass_calls++; }
PassStatus status;
const LineConstraint& line_constraint = type == Line::ROW ? rows.at(index) : cols.at(index);
const Line known_tiles = get_line(type, index);
// Reduce all possible lines that match the data already present in the grid and the line constraint
const auto reduction = line_constraint.reduce_and_count_alternatives(known_tiles, stats);
const Line& reduced_line = reduction.first;
const auto nb_alt = reduction.second;
if (stats != nullptr) { stats->max_nb_alternatives = std::max(stats->max_nb_alternatives, nb_alt); }
// If the list of all lines is empty, it means the grid data is contradictory. Throw an exception.
if (nb_alt == 0)
{
status.contradictory = true;
return status;
}
// In any case, update the grid data with the reduced line resulting from list all_lines
status.grid_changed = set_line(reduced_line);
// Must be set after set_line (it modifies nb_alternatives)
nb_alternatives[type][index] = nb_alt;
// If the list comprises of only one element, it means we solved that line
if (nb_alt == 1) { line_completed[type][index] = true; }
if (stats != nullptr && status.grid_changed)
{
stats->nb_single_line_pass_calls_w_change++;
stats->max_nb_alternatives_w_change = std::max(stats->max_nb_alternatives_w_change, nb_alt);
}
// This line does not need to be reduced until one of the tiles is modified.
line_to_be_reduced[type][index] = false;
return status;
}
// Reduce all rows or all columns. Return false if no change was made on the grid.
template <typename LineSelectionPolicy>
typename WorkGrid<LineSelectionPolicy>::PassStatus WorkGrid<LineSelectionPolicy>::full_side_pass(Line::Type type, bool first_pass)
{
PassStatus status;
const auto length = type == Line::ROW ? get_height() : get_width();
if (first_pass)
{
for (unsigned int x = 0u; x < length; x++)
{
status += single_line_initial_pass(type, x);
if (status.contradictory)
break;
}
}
else
{
for (unsigned int x = 0u; x < length; x++)
{
if (line_to_be_reduced[type][x])
{
if (nb_alternatives[type][x] <= max_nb_alternatives)
{
status += single_line_pass(type, x);
if (status.contradictory)
break;
}
else
{
status.skipped_lines++;
}
}
if (abort_function && abort_function()) { throw PicrossSolverAborted(); }
}
}
return status;
}
// Reduce all columns and all rows. Return false if no change was made on the grid.
// Return true if the grid was changed during the full pass
template <typename LineSelectionPolicy>
typename WorkGrid<LineSelectionPolicy>::PassStatus WorkGrid<LineSelectionPolicy>::full_grid_pass(bool first_pass)
{
PassStatus status;
if (stats != nullptr) { stats->nb_full_grid_pass_calls++; }
// Pass on columns
status += full_side_pass(Line::COL, first_pass);
if (status.contradictory)
return status;
// Pass on rows
status += full_side_pass(Line::ROW, first_pass);
return status;
}
template <typename LineSelectionPolicy>
Solver::Status WorkGrid<LineSelectionPolicy>::guess(unsigned int max_nb_solutions) const
{
assert(guess_list_of_all_alternatives.size() > 0u);
/* This function will test a range of alternatives for one particular line of the grid, each time
* creating a new instance of the grid class on which the function WorkGrid::solve() is called.
*/
if (stats != nullptr)
{
stats->guess_total_calls++;
const auto nb_alternatives = static_cast<unsigned int>(guess_list_of_all_alternatives.size());
stats->guess_total_alternatives += nb_alternatives;
if (stats->guess_max_nb_alternatives_by_depth.size() < nested_level + 1)
stats->guess_max_nb_alternatives_by_depth.resize(nested_level + 1);
auto& max_nb_alternatives = stats->guess_max_nb_alternatives_by_depth[nested_level];
max_nb_alternatives = std::max(max_nb_alternatives, nb_alternatives);
}
const Line::Type guess_line_type = guess_list_of_all_alternatives.front().get_type();
const unsigned int guess_line_index = guess_list_of_all_alternatives.front().get_index();
bool flag_solution_found = false;
for (const Line& guess_line : guess_list_of_all_alternatives)
{
// Allocate a new work grid. Use the shallow copy.
WorkGrid new_grid(*this, nested_level + 1);
// Set one line in the new_grid according to the hypothesis we made. That line is then complete
const bool changed = new_grid.set_line(guess_line);
assert(changed);
assert(!new_grid.line_completed[guess_line_type][guess_line_index]);
new_grid.line_completed[guess_line_type][guess_line_index] = true;
new_grid.line_to_be_reduced[guess_line_type][guess_line_index] = false;
new_grid.nb_alternatives[guess_line_type][guess_line_index] = 1u;
if (max_nb_solutions > 0u && saved_solutions->size() >= max_nb_solutions)
break;
// Solve the new grid!
const auto status = new_grid.solve(max_nb_solutions);
flag_solution_found |= status == Solver::Status::OK;
}
return flag_solution_found ? Solver::Status::OK : Solver::Status::CONTRADICTORY_GRID;
}
template <typename LineSelectionPolicy>
bool WorkGrid<LineSelectionPolicy>::valid_solution() const
{
assert(is_solved());
bool valid = true;
for (unsigned int x = 0u; x < get_width(); x++) { valid &= cols.at(x).compatible(get_line<Line::COL>(x)); }
for (unsigned int y = 0u; y < get_height(); y++) { valid &= rows.at(y).compatible(get_line<Line::ROW>(y)); }
return valid;
}
template <typename LineSelectionPolicy>
void WorkGrid<LineSelectionPolicy>::save_solution() const
{
assert(valid_solution());
if (stats != nullptr) { stats->nb_solutions++; }
// Shallow copy of only the grid data
saved_solutions->emplace_back(static_cast<const OutputGrid&>(*this));
}
// Template explicit instantiations
template class WorkGrid<LineSelectionPolicy_Legacy>;
template class WorkGrid<LineSelectionPolicy_RampUpMaxNbAlternatives>;
template class WorkGrid<LineSelectionPolicy_RampUpMaxNbAlternatives_EstimateNbAlternatives>;
} // namespace picross
| 37.399598 | 167 | 0.665879 | [
"vector",
"transform"
] |
b820c2aabfc46e567f6eccb41d09c235e73e2508 | 71,303 | cpp | C++ | sources/thelib/src/protocols/wrtc/wrtcconnection.cpp | rdkcmf/rdkc-rms | 65ab1efcee9e3de46a888c125f591cd48b815601 | [
"Apache-2.0"
] | 3 | 2020-07-30T19:41:00.000Z | 2020-10-28T12:52:37.000Z | sources/thelib/src/protocols/wrtc/wrtcconnection.cpp | rdkcmf/rdkc-rms | 65ab1efcee9e3de46a888c125f591cd48b815601 | [
"Apache-2.0"
] | null | null | null | sources/thelib/src/protocols/wrtc/wrtcconnection.cpp | rdkcmf/rdkc-rms | 65ab1efcee9e3de46a888c125f591cd48b815601 | [
"Apache-2.0"
] | 2 | 2020-05-11T03:19:00.000Z | 2021-07-07T17:40:47.000Z | /**
##########################################################################
# If not stated otherwise in this file or this component's LICENSE
# file the following copyright and licenses apply:
#
# Copyright 2019 RDK Management
#
# 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.
##########################################################################
**/
/**
* wrtcconnection.cpp - create and funnel data through a WebRTC Connection
*
**/
#ifdef HAS_PROTOCOL_WEBRTC
#include "protocols/wrtc/wrtcsdp.h"
#include "protocols/rtp/sdp.h"
#include "protocols/wrtc/wrtcconnection.h"
#include "protocols/wrtc/wrtcsigprotocol.h"
#include "protocols/wrtc/candidate.h"
#include "protocols/wrtc/iceudpprotocol.h"
#include "protocols/wrtc/icetcpprotocol.h"
#include "protocols/rtp/connectivity/outboundconnectivity.h"
#include "protocols/rtp/streaming/outnetrtpudph264stream.h"
#include "protocols/rtp/connectivity/inboundconnectivity.h"
#include "protocols/ssl/inbounddtlsprotocol.h"
#include "protocols/ssl/outbounddtlsprotocol.h"
#include "application/baseclientapplication.h"
#include "streaming/baseinstream.h"
#include "streaming/streamstypes.h"
#include "streaming/codectypes.h"
#include "eventlogger/eventlogger.h"
#include "mediaformats/readers/streammetadataresolver.h"
#include "application/clientapplicationmanager.h"
#include "utils/misc/timeprobemanager.h"
#define PENDING_STREAM_REGISTERED 0x01
#define PENDING_HAS_VCODEC 0x02
#define PENDING_HAS_ACODEC 0x04
#define PENDING_COMPLETE 0x07
#define ENABLE_ICE_UDP
#define ENABLE_ICE_TCP
#define MAX_ZERO_SEND_THRESHOLD 5 // kludge for the sctp->sendData returning ZERO, and CHROME version >= 62
#define STUN_REFRESH_RATE_SEC 15 // refresh rate in seconds before new set of bind requests are sent out
#define WRTC_CAPAB_MAX_HEARTBEAT 10 // maximum value of heartbeats with no responses before considered stale
#define TOGGLE_COMMAND "TogglingAudio"
uint32_t WrtcConnection::_sessionCounter = 0;
X509Certificate* WrtcConnection::_pCertificate = NULL;
WrtcConnection::WrtcConnection()
: BaseRTSPProtocol(PT_WRTC_CNX) {
_sessionCounter++;
_pFastTimer = _pSlowTimer = NULL;
_bestStun = NULL;
_started = false;
_stopping = false;
_gotSDP = false;
_sentSDP = false;
_pSDP = NULL;
_pSDPInfo = NULL;
_pDtls = NULL;
_pSctp = NULL;
_pOutNetMP4Stream = NULL;
_dataChannelEstablished = false;
_fullMp4 = false;
_clientId = "";
_rmsClientId = "";
_cmdReceived = "Unknown";
_isStreamAttached = false;
_pOutboundConnectivity = NULL;
_pOutStream = NULL;
_commandChannelId = 0;
_pInboundConnectivity = NULL;
_pTalkDownStream = NULL;
_is2wayAudioSupported = false;
_mediaContext.hasAudio = false;
_mediaContext.hasVideo = false;
_isPlaylist = false;
_useSrtp = false;
_retryConnectionProcess = false;
_slowTimerCounter = 0;
_waiting = false;
_pendingFlag = 0;
_pPendingInStream = NULL;
SetControlled(); // default as controlled (let browser be pushy)
SpawnStunProtocols(); // get a BaseIceProtocol for each network interface
SetRmsCapabilities(); // set rms enabled capabilities
_ticks = 0;
_capabPeer.hasHeartbeat = false;
_capabRms.hasHeartbeat = false;
#ifdef WRTC_CAPAB_HAS_HEARTBEAT
_hbNoAckCounter = 0;
_capabRms.hasHeartbeat = true;
#endif // WRTC_CAPAB_HAS_HEARTBEAT
_checkHSState = false;
_dtlsState = -1;
RTCPReceiver::ResetNackStats();
}
//TODO: This will be removed later on
WrtcConnection::WrtcConnection(WrtcSigProtocol * pSig, Variant & settings)
: BaseRTSPProtocol(PT_WRTC_CNX) {
_sessionCounter++;
_pSig = pSig;
_pFastTimer = _pSlowTimer = NULL;
_bestStun = NULL;
_started = false;
_stopping = false;
_gotSDP = false;
_sentSDP = false;
_pSDP = NULL;
_pSDPInfo = NULL;
_pDtls = NULL;
_pSctp = NULL;
_pOutNetMP4Stream = NULL;
_dataChannelEstablished = false;
_fullMp4 = false;
_clientId = "";
_rmsClientId = "";
_cmdReceived = "Unknown";
_isStreamAttached = false;
_customParameters = settings;
_streamChannelId = 0xFFFFFFFF;
_pOutboundConnectivity = NULL;
_pOutStream = NULL;
_commandChannelId = 0;
_pInboundConnectivity = NULL;
_pTalkDownStream = NULL;
_is2wayAudioSupported = false;
_isPlaylist = false;
_useSrtp = false;
_retryConnectionProcess = false;
_slowTimerCounter = 0;
_waiting = false;
_pendingFlag = 0;
_pPendingInStream = NULL;
SetControlled(); // default as controlled (let browser be pushy)
SpawnStunProtocols(); // get a BaseIceProtocol for each network interface
SetRmsCapabilities(); // set rms enabled capabilities
_ticks = 0;
_capabPeer.hasHeartbeat = false;
_capabRms.hasHeartbeat = false;
#ifdef WRTC_CAPAB_HAS_HEARTBEAT
_hbNoAckCounter = 0;
_capabRms.hasHeartbeat = true;
_sctpAlive = false;
#endif // WRTC_CAPAB_HAS_HEARTBEAT
_checkHSState = false;
_dtlsState = -1;
RTCPReceiver::ResetNackStats();
if (!InitializeCertificate()) {
WARN("Failed to initialize certificates!");
}
}
uint32_t WrtcConnection::getSessionCounts()
{
return _sessionCounter;
}
WrtcConnection::~WrtcConnection() {
_sessionCounter--;
//Output the time we had streaming going to this client
std::stringstream sstrm;
sstrm << GetId();
string probSess("wrtcplayback");
probSess += sstrm.str();
uint64_t ts = PROBE_TRACK_TIME_MS(STR(probSess) );
string pauseProbSess(probSess);
string resumeProbSess(probSess);
string firstFramePostResumeProbSess(probSess);
// TS for client paused
pauseProbSess += "clientPaused";
uint64_t wconPauseTs = PROBE_GET_STORED_TIME(STR(pauseProbSess),true);
// TS for client resumed
resumeProbSess += "clientResumed";
uint64_t wconResumeTs = PROBE_GET_STORED_TIME(STR(resumeProbSess),true);
// TS for first frame sent post client resumed
firstFramePostResumeProbSess += "firstFramePostResume";
uint64_t wconFFPostResumeTs = PROBE_GET_STORED_TIME(STR(firstFramePostResumeProbSess),true);
//Retrieve the time to establish the wrtc connection and delete it after retrieval
probSess += "wrtcConn";
uint64_t wconTs = PROBE_GET_STORED_TIME(STR(probSess),true);
//Retrieve the time taken to send the first frame and delete it after retrieval
probSess += "firstFrame";
uint64_t wconFFTs = PROBE_GET_STORED_TIME(STR(probSess),true);
// Only print this if we have a session to report
if( ts > 0 ) {
INFO("RMS stopped streaming to client");
INFO("RMS stopped streaming event:%"PRId64",%"PRId32"", ts, GetId() );
// Log Peer/Ice states at the end of session
if (_pSig != NULL) {
INFO("The peer state is %s", STR(_pSig->GetPeerState()));
INFO("Peer State Transition: %s-closed", STR(_pSig->GetPeerState()));
_pSig->SetPeerState(WRTC_PEER_CLOSED);
INFO("The ice state is %s", STR(_pSig->GetIceState()));
INFO("Ice State Transition: %s-closed", STR(_pSig->GetIceState()));
_pSig->SetIceState(WRTC_ICE_CLOSED);
}
if(HasAudio()) {
INFO("RMS stopped live audio streaming to client");
}
// connection failure logging
if(!wconTs) {
if(ts < 2000) {
INFO("RMS unable to peer in less than 2 sec");
}
else if(ts < 2500) {
INFO("RMS unable to peer in less than 2.5 sec");
}
else if(ts < 3000) {
INFO("RMS unable to peer in less than 3 sec");
}
else if(ts < 6000) {
INFO("RMS unable to peer in less than 6 sec");
}
else if(ts < 10000) {
INFO("RMS unable to peer in less than 10 sec");
}
else {
INFO("RMS unable to peer in more than 10 sec");
}
}
// first frame failure logging
if(wconTs && !wconFFTs) {
if(ts < 2000) {
INFO("RMS unable to send frame in less than 2 sec");
}
else if(ts < 2500) {
INFO("RMS unable to send frame in less than 2.5 sec");
}
else if(ts < 3000) {
INFO("RMS unable to send frame in less than 3 sec");
}
else if(ts < 6000) {
INFO("RMS unable to send frame in less than 6 sec");
}
else if(ts < 10000) {
INFO("RMS unable to send frame in less than 10 sec");
}
else if(ts < 20000) {
INFO("RMS unable to send frame in less than 20 sec");
}
else {
INFO("RMS unable to send frame in more than 20 sec");
}
}
PROBE_CLEAR_TIME(STR(probSess));
/*
Session statistics Info : { RMS Session Statistics: <Player Client ID>, <Player IPVersion>, <Relay/Reflex>, <Received Command from Player>, <Session Total duration>, <Time the first frame send post Resume Command>, <Time the Resume Command Received>, <Time the Pause Command Received>, <Time taken to send First Frame>, <Time taken to connect Peer> }
RMS Session Candidate IPversion Type: { <RMS IPVersion> ,<Player IPVersion> }
*/
if(_bestStun) {
Candidate * pCan = _bestStun->GetBestCandidate();
if(pCan) {
INFO("RMS Session Statistics:%s,%s,%s,%s,%"PRIu64",%"PRIu64",%"PRIu64",%"PRIu64",%"PRIu64",%"PRIu64"",
STR(_clientId), (pCan->IsIpv6() ? STR("IPV6") : STR("IPV4")),
(pCan->IsRelay() ? STR("relay") : (pCan->IsReflex() ? STR("reflex") : STR("unknown"))), STR(_cmdReceived),
ts, wconFFPostResumeTs, wconResumeTs, wconPauseTs, wconFFTs, wconTs);
/* INFO("RMS Session Statistics: %s, %s, %s, %s, %"PRIu64", %"PRIu64", %"PRIu64", %s, %s",
STR(_rmsClientId), (_bestStun && _bestStun->IsIpv6() ? STR("IPV6") : STR("IPV4")),
STR(_clientId), (pCan->IsIpv6() ? STR("IPV6") : STR("IPV4")), ts, wconFFTs, wconTs,
(pCan->IsRelay() ? STR("relay") : (pCan->IsReflex() ? STR("reflex") : STR("unknown"))),
STR(_cmdReceived)); */
INFO("RMS Session Candidate IPversion Type:%s,%s", (_bestStun && _bestStun->IsIpv6() ? STR("IPV6") : STR("IPV4")),
(pCan->IsIpv6() ? STR("IPV6") : STR("IPV4")));
}
_cmdReceived = "Unknown";
}
// Stream info of the session
BaseOutStream * outStream = GetOutboundStream();
if (NULL != outStream) {
// get out stream stats
Variant stats;
outStream->GetStats(stats);
// video info of the session
uint64_t bytesCount = stats["video"]["bytesCount"];
uint64_t droppedBytesCount = stats["video"]["droppedBytesCount"];
uint64_t packetsCount = stats["video"]["packetsCount"];
uint64_t droppedPacketsCount = stats["video"]["droppedPacketsCount"];
uint8_t videoProfile = stats["video"]["profile"];
NackStats nackStats;
nackStats = RTCPReceiver::GetNackStats();
/* Video Session: { <Player Client ID>, <Profile>, <Bytes Sent>, <Bytes Dropped>, <Packets Sent>,
<Packets Dropped> } */
INFO("Video Session: %s, 0x%"
PRIx8", %"PRId64", %"PRId64", %"PRId64", %"PRId64", %"PRIu32", %"PRIu32"", STR(_clientId),
videoProfile, bytesCount, droppedBytesCount, packetsCount, droppedPacketsCount, nackStats.pRequested, nackStats.pTransmitted);
/* Nact stats */
INFO("Nack Stats: %"PRIu32",%"PRIu32"", nackStats.pRequested, nackStats.pTransmitted);
// Audio info of the session
bytesCount = stats["audio"]["bytesCount"];
droppedBytesCount = stats["audio"]["droppedBytesCount"];
packetsCount = stats["audio"]["packetsCount"];
droppedPacketsCount = stats["audio"]["droppedPacketsCount"];
/* Audio Session: { <Player Client ID>, <Bytes Sent>, <Bytes Dropped>, <Packets Sent>, <Packets Dropped> } */
INFO("Audio Session:%s,%"
PRId64",%"PRId64",%"PRId64",%"PRId64"", STR(_clientId), bytesCount, droppedBytesCount, packetsCount, droppedPacketsCount);
/* DTLS HS logging */
if(_dtlsState == 1) {
INFO("RMS DTLS handshake success");
INFO("DTLS stats: %"PRId8"", _dtlsState);
}
else if (_dtlsState != -1) {
INFO("RMS DTLS handshake failed");
INFO("DTLS stats: %"PRId8"", _dtlsState);
}
else if (_dtlsState == -1) {
INFO("RMS DTLS handshake not started");
INFO("DTLS stats: %"PRId8"", _dtlsState);
}
}
// Use the session counter to report the instances
if (_sessionCounter) {
INFO("Number of active client connections: %"PRIu32, (_sessionCounter - 1));
} else {
INFO("No active webrtc connections.");
}
}
//#ifdef WEBRTC_DEBUG
FINE("WrtcConnection deleted.");
//#endif
_stopping = true;
if(IsSctpAlive()) {
if (_pSctp != NULL ) {
delete _pSctp;
_pSctp = NULL;
}
_sctpAlive = false;
}
if (_pFastTimer != NULL) {
delete _pFastTimer;
_pFastTimer = NULL;
}
if (_pSlowTimer != NULL) {
delete _pSlowTimer;
_pSlowTimer = NULL;
}
// Connection was established, streaming has started, and everyone was happy
// We no longer wait for the connection to get stale or terminated by the
// other end, but rather close it to help prevent the "mem increase" scenario
// UPDATE: since we already have a mechanism to remove the ice protocols
// we can safely terminate the remaining ones on the list without having to
// check if the connection did properly establish or not
FOR_VECTOR(_stuns, i) {
_stuns[i]->Terminate();
}
_stuns.clear();
_bestStun = NULL;
if (_pSig != NULL) {
INFO("Closing Player Client ID:%s", STR(_clientId));
_pSig->UnlinkConnection(this);
}
_rtcpReceiver.SetOutNetRTPStream(NULL);
RTCPReceiver::ResetNackStats();
if (_pOutStream != NULL){
delete _pOutStream;
_pOutStream = NULL;
}
if (_pOutboundConnectivity != NULL) {
_pOutboundConnectivity->SetOutStream(NULL);
delete _pOutboundConnectivity;
_pOutboundConnectivity = NULL;
}
if (_pInboundConnectivity != NULL) {
delete _pInboundConnectivity;
_pInboundConnectivity = NULL;
}
if(_pTalkDownStream != NULL) {
delete _pTalkDownStream;
_pTalkDownStream = NULL;
}
if (_pSDP != NULL) {
delete _pSDP;
_pSDP = NULL;
}
if (_pSDPInfo != NULL) {
delete _pSDPInfo;
_pSDPInfo = NULL;
}
if (_pOutNetMP4Stream != NULL && _isStreamAttached) {
// Unregister from this stream
if (_fullMp4) {
((OutNetMP4Stream *)_pOutNetMP4Stream)->UnRegisterOutputProtocol(GetId());
} else {
((OutNetFMP4Stream *)_pOutNetMP4Stream)->UnRegisterOutputProtocol(GetId());
}
_pOutNetMP4Stream = NULL;
}
RemovePlaylist();
}
void WrtcConnection::RemovePlaylist() {
if (_isPlaylist && !_streamName.empty()) {
BaseClientApplication *pApp = GetLastKnownApplication();
if (pApp) {
Variant message;
message["header"] = "removeConfig";
message["payload"]["command"] = message["header"];
message["payload"]["localStreamName"] = _streamName;
pApp->SignalApplicationMessage(message);
}
}
}
bool WrtcConnection::Initialize(Variant ¶meters) {
_customParameters = parameters;
return true;
}
bool WrtcConnection::IsVod(string streamName) {
if (streamName.find_last_of(".") == string::npos) return false;
string extension = streamName.substr(streamName.find_last_of("."));
return extension == ".vod" || extension == ".lst";
}
bool WrtcConnection::IsLazyPull(string streamName) {
if (streamName.find_last_of(".") == string::npos) return false;
string extension = streamName.substr(streamName.find_last_of("."));
return extension == ".vod";
}
bool WrtcConnection::IsWaiting() {
return _waiting;
}
bool WrtcConnection::SetStreamName(string streamName, bool useSrtp) {
// This is a bit weird to have here, but since this object gets instantiated way before
// actual client join, this serves as a good proxy for the start of the peering connection
std::stringstream sstrm;
sstrm << GetId();
string probSess("wrtcplayback");
probSess += sstrm.str();
uint64_t ts = PROBE_TRACK_INIT_MS(STR(probSess) );
INFO("Starting to peer:%"PRId64"", ts);
_streamName = streamName;
_useSrtp = useSrtp;
if (!_useSrtp) {
// This is an fmp4
return SendStreamAsMp4(streamName);
}
BaseClientApplication *pApp = GetApplication();
if (pApp == NULL) {
FATAL("Unable to get application");
return false;
}
StreamsManager *pSM = pApp->GetStreamsManager();
if (pSM == NULL) {
FATAL("Unable to get Streams Manager");
return false;
}
if (IsVod(streamName)) {
if (IsLazyPull(streamName)) {
//check first if there is an existing lazypull stream
BaseInStream *pInStream = RetrieveInStream(streamName, pSM);
if (pInStream != NULL) {
DEBUG("creating out stream in SetStreamName lazypull");
return CreateOutStream(streamName, pInStream, pSM);
}
}
StreamMetadataResolver *pSMR = pApp->GetStreamMetadataResolver();
if (pSMR == NULL) {
FATAL("No stream metadata resolver found");
return false;
}
Metadata metadata;
metadata["callback"]["protocolID"] = GetId();
metadata["callback"]["streamName"] = streamName;
if (!pSMR->ResolveMetadata(streamName, metadata, true)) { // lazy pull should be executing here.
FATAL("Unable to obtain metadata for stream name %s", STR(streamName));
return false;
}
if (metadata.type() == MEDIA_TYPE_VOD) {
// _pendingInputStreamName = metadata.completeFileName();
_waiting = true;
return true;
}
else if (metadata.type() == MEDIA_TYPE_LST) {
metadata["_isVod"] = "1";
if (SetupPlaylist(streamName, metadata, true)) {
_waiting = true;
return true;
}
}
return false;
} else {
BaseInStream *pInStream = RetrieveInStream(streamName, pSM);
if (pInStream != NULL) {
DEBUG("creating out stream in SetStreamName");
return CreateOutStream(streamName, pInStream, pSM);
}
return false;
}
return true;
}
/** @description: Set the mobile client id
* @param[in] : string - client id
* @return: void
*/
void WrtcConnection::SetClientId( string clientId ) {
_clientId = clientId;
}
/** @description: Set the RMS client id
* @param[in] : string - rms client id
* @return: void
*/
void WrtcConnection::SetRMSClientId( string rmsClientId ) {
_rmsClientId = rmsClientId;
}
BaseInStream *WrtcConnection::RetrieveInStream(string streamName, StreamsManager *pSM) {
map<uint32_t, BaseStream *> streams = pSM->FindByTypeByName(ST_IN_NET,
streamName, true, false);
if (streams.size() == 0) {
FATAL("Unable to find stream %s", STR(streamName));
return NULL;
}
BaseInStream *pInStream = (BaseInStream *)MAP_VAL(streams.begin());
if (!pInStream->IsCompatibleWithType(ST_OUT_NET_RTP)) {
FATAL("Incompatible stream for SRTP");
return NULL;
}
return pInStream;
}
#ifdef PLAYBACK_SUPPORT
bool WrtcConnection::CreateInStream(string streamName, StreamsManager *pSM) {
if (!_is2wayAudioSupported) {
INFO("No talk down request from the client");
return false;
}
uint32_t bandwidthHint = 0;
uint8_t rtcpDetectionInterval = 15;
int16_t a = -1;
int16_t b = -1;
string talkdown = streamName;
talkdown.append("talkdown");
INFO("The talkdown stream name is %s", STR(talkdown));
if(NULL == _pInboundConnectivity) {
_pInboundConnectivity = new InboundConnectivity((BaseRTSPProtocol *)this, talkdown, bandwidthHint, rtcpDetectionInterval, a, b);
}
Variant audioTrack;
audioTrack["isTcp"] = true;
audioTrack["portsOrChannels"]["data"] = (uint16_t) 0;
audioTrack["portsOrChannels"]["rtcp"] = (uint16_t) 1;
if (!_pInboundConnectivity->AddTrack( audioTrack, true)) {
FATAL("Unable to add audio track");
return false;
}
Variant inboundParams;
inboundParams["hasAudio"] = true;
inboundParams["hasVideo"] = false;
/* We should avoid registering the stream expiry for talk down inbound stream
as the peer doesn't send audio packets to camera all the time and
we should not tear down the stream due to the absence of traffic in the
talkdown stream */
inboundParams["registerStreamExpiry"] = false;
if (!_pInboundConnectivity->Initialize(inboundParams)) {
FATAL("Unable to initialize inbound connectivity");
return false;
}
BaseInStream *pInStream =(BaseInStream *) _pInboundConnectivity->GetInStream();
if(pInStream) {
_pTalkDownStream = new OutDeviceTalkDownStream(this, streamName);
if (!_pTalkDownStream->SetStreamsManager(pSM)) {
FATAL("Unable to set the streams manager for talkdown");
delete _pTalkDownStream;
_pTalkDownStream = NULL;
return false;
}
if (!(pInStream)->Link(_pTalkDownStream)) {
FATAL("Unable to link streams for talkdown");
delete _pTalkDownStream;
_pTalkDownStream = NULL;
return false;
}
}
else {
FATAL("Unable to retrieve streams");
return false;
}
//INFO("Created talkdown stream for audio out 0x%x", _pTalkDownStream);
return true;
}
#else
bool WrtcConnection::CreateInStream(string streamName, StreamsManager *pSM) {
INFO("No Playback support available on the device");
return false;
}
#endif
bool WrtcConnection::CreateOutStream(string streamName, BaseInStream *pInStream, StreamsManager *pSM) {
PROBE_POINT("webrtc", "sess1", "create_out_stream", true);
_pOutStream = new OutNetRTPUDPH264Stream(this, streamName, false, true, true);
if (!_pOutStream->SetStreamsManager(pSM)) {
FATAL("Unable to set the streams manager");
delete _pOutStream;
_pOutStream = NULL;
return false;
}
_pOutStream->SetPayloadType(107, false);
_pOutStream->SetPayloadType(106, true);
_pOutboundConnectivity = new OutboundConnectivity(false, this);
if (!_pOutboundConnectivity->Initialize()) {
FATAL("Unable to initialize outbound connectivity");
return false;
}
_pOutStream->SetConnectivity(_pOutboundConnectivity);
_pOutboundConnectivity->SetOutStream(_pOutStream);
// TODO: Check SDP for video and audio
StreamCapabilities *pCaps = pInStream->GetCapabilities();
#ifdef HAS_G711
bool hasAudio = pCaps->GetAudioCodec() != NULL && (pCaps->GetAudioCodecType() == CODEC_AUDIO_AAC || (pCaps->GetAudioCodecType() & CODEC_AUDIO_G711) == CODEC_AUDIO_G711);
#else
bool hasAudio = pCaps->GetAudioCodec() != NULL && pCaps->GetAudioCodecType() == CODEC_AUDIO_AAC;
#endif /* HAS_G711 */
bool hasVideo = pCaps->GetVideoCodec() != NULL && pCaps->GetVideoCodecType() == CODEC_VIDEO_H264;
_pOutboundConnectivity->HasAudio(hasAudio);
_pOutboundConnectivity->HasVideo(hasVideo);
// update the media context
HasAudio(hasAudio);
HasVideo(hasVideo);
if (!pInStream->Link(_pOutStream)) {
FATAL("Unable to link streams");
delete _pOutStream;
_pOutStream = NULL;
return false;
}
// attach outstream to rtcpreceiver
_rtcpReceiver.SetOutNetRTPStream(_pOutStream);
return true;
}
void WrtcConnection::Start(bool hasNewCandidate) {
if (_started || _stopping || (hasNewCandidate && _started)) {
//#ifdef WEBRTC_DEBUG
DEBUG("Start() called AGAIN - ignoring...!");
//#endif
// Check, if this is a new candidate AND we already started
if (hasNewCandidate && _started) {
FINE("New candidate received...");
// New candidate received, and the process has already started, make
// the necessary adjustments.
// Only do this if we have not successfully established
// a connection yet. Unless we want to try if this candidate
// is more reliable/faster.
if (_bestStun && _bestStun->GetBestCandidate()) {
// At this point, we already have a connection
// TODO: do we retry still?
} else {
// No connection established yet, retry the candidates
StartFastTimer(); // restart the fast timer to try the new candidate
_retryConnectionProcess = true; // indicate that we want to restart
}
}
return;
}
// Sanity check...
if (!InitializeCertificate()) {
WARN("Failed to initialize certificates!");
return;
}
// Issue an SDP if we haven't received one yet
if (!_gotSDP) {
if (_sentSDP) {
//#ifdef WEBRTC_DEBUG
DEBUG("Would have sent SDP TWICE!!");
//#endif
} else {
_sentSDP = true; // b2: track this, sending twice is bad
// create a Controlling SDP
_isControlled = false;
_pSDP = new WrtcSDP(SDP_TYPE_CONTROLLING, _pCertificate);
_pSDP->SetSourceStream(_pOutStream);
string sdpStr = _pSDP->GenerateSDP(NULL, _useSrtp, _useSrtp, true);
INFO("SDP offer is %s", STR(sdpStr));
_pSig->SendSDP(sdpStr, true); // send offer
// manually setting hasAudio and hasVideo for now. should be dependent on sdp
GetCustomParameters()["hasAudio"] = false;
GetCustomParameters()["hasVideo"] = false;
}
} else if (_pSDP && _pSDPInfo) {
if (_sentSDP) {
//#ifdef WEBRTC_DEBUG
DEBUG("Would have sent SDP TWICE!!");
//#endif
} else {
_sentSDP = true; // b2: track this, sending twice is bad
string sdpStr = _pSDP->GenerateSDP(_pSDPInfo, _useSrtp, _useSrtp, true);
INFO("SDP answer is %s", STR(sdpStr));
_pSig->SendSDP(sdpStr, false); // send answer
}
}
if (!_pSDP) {
WARN("WebRTC didn't generate an SDP!");
return;
}
if (!_pSDPInfo) {
INFO("WebRTC didn't receive an SDP");
return;
}
// complete and start each STUN agent (BaseIceProtocol)
FOR_VECTOR(_stuns, i) {
// fill in the SDP exchanged User Info
_stuns[i]->SetIceUser(_pSDP->GetICEUsername(), _pSDP->GetICEPassword(),
_pSDPInfo->iceUsername, _pSDPInfo->icePassword);
_stuns[i]->SetIceFingerprints(_pSDP->GetFingerprint(), _pSDPInfo->fingerprint);
_stuns[i]->SetIceControlling(!_isControlled);
// now start the stun agent
_stuns[i]->Start(0);
_started = true;
}
FINE("WebRTC connection started...");
StartFastTimer();
}
bool WrtcConnection::SetSDP(string sdp, bool offer) {
_gotSDP = true;
FINE("Received SDP from the player is %s", STR(sdp));
string raw = sdp;
SDP peerSdp;
//3. Parse the SDP
if (!SDP::ParseSDP(peerSdp, raw, true)) {
FATAL("Unable to parse the peer SDP, so by default 2 way audio support is off");
//return false;
}
else {
Variant audioTrack = peerSdp.GetTrackLine(0, "audio");
_is2wayAudioSupported = (bool)audioTrack[SDP_A]["sendrecv"];
INFO("2 way audio support from the peer is %d", _is2wayAudioSupported);
if((bool)audioTrack[SDP_A]["sendrecv"]) {
// Get the application
BaseClientApplication *pApp = NULL;
if ((pApp = GetApplication()) == NULL) {
FATAL("Unable to get the application");
return false;
}
StreamsManager *pSM = pApp->GetStreamsManager();
if (pSM == NULL) {
FATAL("Unable to get Streams Manager");
return false;
}
bool ret = CreateInStream(_streamName, pSM);
if(ret) {
INFO("Successfully created the inbound stream for audio out");
}
else {
FATAL("Error while creating the inbound stream for audio out");
}
}
else {
INFO("No talk down request from the client");
}
}
_pSDPInfo = WrtcSDP::ParseSdpStr2(sdp);
if (_pSDPInfo == NULL) {
FATAL("Generated SDP info is null!");
return false;
}
INFO("Client Session Info: %s.", STR(_pSDPInfo->sessionInfo));
//#ifdef WEBRTC_DEBUG
DEBUG("Got SDP: %s", offer ? (char *)"offer" : (char *)"answer");
DEBUG("ParseSdpStr2 returned %s", _pSDPInfo ? "ok" : "NULL");
//#endif
if (offer) { // then peer expects an answer
// Sanity check...
if (!InitializeCertificate()) {
return false;
}
_pSDP = new WrtcSDP(SDP_TYPE_CONTROLLED, _pCertificate);
}
// Set the correct mid value regardless of offer or answer
_pSig->SetSdpMid(_pSDPInfo->mid);
return true;
}
bool WrtcConnection::Tick() {
if (_pFastTimer) {
// we are running the fast timer
if (!FastTick()) {
//#ifdef WEBRTC_DEBUG
DEBUG("$b2$ Switching to slow timer");
//#endif
StartSlowTimer();
}
}
else {
SlowTick();
}
return true;
}
bool WrtcConnection::FastTick() {
bool reset = false;
if (_retryConnectionProcess) {
// Check if there is a need to restart the connection process
reset = true;
_retryConnectionProcess = false;
}
bool more = false;
bool alreadyConnected = false;
FOR_VECTOR(_stuns, i) {
// Tick returns false if done (true if it wants more ticks)
more |= _stuns[i]->FastTick(reset, alreadyConnected);
if (alreadyConnected) {
// It has connected already, bail out!
more = false;
break;
}
}
// if done (!more), then find the best result
// and change to slow ticks
//
if (!more) {
FOR_VECTOR(_stuns, i) {
BaseIceProtocol * pStun = _stuns[i]; // do the index once
if (!pStun->IsDead()) {
pStun->Select(); // have the stun check himself
if (!_bestStun || (pStun->IsBetterThan(_bestStun))) {
_bestStun = pStun;
}
}
}
// panic stuff if we didn't find a connection!
if (!_bestStun) {
FATAL("No valid STUN interface found!");
// Shutdown signalling protocol, as well as this session if no interface found
// Doesn't happen today, but should be a good future proofing
_pSig->Shutdown(false, true);
} else {
Candidate * pCan = _bestStun->GetBestCandidate();
if (!pCan) {
if (_pSig != NULL) {
INFO("Ice State Transition: %s-failed", STR(_pSig->GetIceState()));
_pSig->SetIceState(WRTC_ICE_FAILED);
}
FATAL("STUN has no valid candidate! (%s [%s])", STR(_bestStun->GetHostIpStr()), (_bestStun->IsTcpType() ? STR("TCP") : STR("UDP")));
// The crash is probably caused by this, there is no peering
// connection but has still proceeded with the slow tick
// We should be scheduled for deletion
EnqueueForDelete();
} else {
if (_pSig != NULL) {
INFO("Ice State Transition: %s-connected", STR(_pSig->GetIceState()));
_pSig->SetIceState(WRTC_ICE_CONNECTED);
}
INFO("WebRTC connection established: STUN (%s [%s]), Candidate (%s).",
STR(_bestStun->GetHostIpStr()), (_bestStun->IsTcpType() ? STR("TCP") : STR("UDP")), STR(pCan->GetShortString()));
PROBE_POINT("webrtc", "sess1", "candidate_selected", false);
//Output the time it took to get to this point
std::stringstream sstrm;
sstrm << GetId();
string probSess("wrtcplayback");
probSess += sstrm.str();
uint64_t ts = PROBE_TRACK_TIME_MS(STR(probSess) );
INFO("WebRTC connection event:%"PRId64"", ts);
//we need to store this because comcast really wants to see this number again in a log later...
//adding token to identify this specific val
probSess += "wrtcConn";
PROBE_STORE_TIME(probSess,ts);
if (_sessionCounter) {
INFO("Number of active client connections: %"PRIu32, (_sessionCounter - 1));
} else {
INFO("No active webrtc connections.");
}
// Report STUN message to peer
// $ToDo$ should I only do this if I'm (!_isControlled)??
_bestStun->ReportBestCandidate();
// Now that we have a best candidate, setup the srtp or data channel
if (!InitializeDataChannel()) {
FATAL("Unable to start data channel!");
// We should be scheduled for deletion
EnqueueForDelete();
}
/*
if (_useSrtp) {
if (!InitializeSrtp()) {
FATAL("Unable to start SRTP!");
}
}
*/
// Commenting the below block to clean up the unused stuns as we think this would fix RDKC-4665(as per tiage/RM, RDKC-4665 occurs due to the fix provided for RDKC-4066)
#if 0
// At this point we have a connection path and are setting up protocol stacks. we should now
// cleanup the stuns that are not going to be used so that we dont have a bunch of extra processing
// and messages being sent.
INFO("Deleting unused stuns: %d", _stuns.size());
// Dont delete the TCP stun as it still has some asynchronous stuff going on. There is only one
// and it will cleanup separately.
BaseIceProtocol * tcpStun( NULL );
FOR_VECTOR(_stuns, i) {
if ( _bestStun != _stuns[i] && !_stuns[i]->IsTcpType() )
_stuns[i]->Terminate();
if ( _stuns[i]->IsTcpType() ) {
tcpStun = _stuns[i];
}
}
// Now that we've spun the unused to terminate/delete, clear the list and reinsert just the chosen one
_stuns.clear();
_stuns.push_back( _bestStun );
_stuns.push_back( tcpStun );
INFO("Stuns remaning after the cull: %d", _stuns.size());
#endif
}
}
return false; // cause switch to slow tick
}
return true; // continue the ticking!!
}
bool WrtcConnection::SlowTick() {
// Session might already have been scheduled for deletion
if (IsEnqueueForDelete()) {
return false;
}
if(_pDtls && _checkHSState) {
_dtlsState = _pDtls->GetHandshakeState();
INFO("The current state of DTLS handshake is %d", _dtlsState);
// No need to check the state once handshake has been successfully completed
if(_dtlsState == 1) {
_checkHSState = false;
}
}
// Increment the tick counter here so that we can use it for the channel
// validation as well
_ticks++;
// Check the validity of the channel first
if (IsSctpAlive()) {
// Channel is Invalid
if (!_pSctp->IsDataChannelValid(_commandChannelId)) {
// It would seem that when using a relay, there is a chance that the datachannel
// is not even ready yet. This issue got worse since we changed the slowtick
// from 15 seconds to 1 second
// We now give some allowance similar to the STUN refresh
if (_ticks < STUN_REFRESH_RATE_SEC) {
DEBUG("Datachannel not ready yet.");
return true;
}
// tear down the connection only if channel is not been connected at least once
if (_pSctp->IsDataChannelConnectedOnce(_commandChannelId)) {
FATAL("Datachannel no longer valid.");
EnqueueForDelete();
return false;
}
}
// Data channel is valid
else {
#ifdef WRTC_CAPAB_HAS_HEARTBEAT
// Send the heartbeat message
if (!SendHeartbeat()) {
if (_pSig != NULL) {
INFO("Ice State Transition: %s-disconnected", STR(_pSig->GetIceState()));
_pSig->SetIceState(WRTC_ICE_DISCONNECTED);
}
FATAL("Could not send heartbeat!");
EnqueueForDelete();
return false;
}
// Now check if we have response from client
if (_capabPeer.hasHeartbeat && (_hbNoAckCounter++ > WRTC_CAPAB_MAX_HEARTBEAT)) {
if (_pSig != NULL) {
INFO("Ice State Transition: %s-disconnected", STR(_pSig->GetIceState()));
_pSig->SetIceState(WRTC_ICE_DISCONNECTED);
}
FATAL("No heartbeat response from player!");
EnqueueForDelete();
return false;
}
#endif // WRTC_CAPAB_HAS_HEARTBEAT
}
}
// Only proceed below if it is time to send the bind request
// Which is every STUN_REFRESH_RATE_SEC (15s)
if ((_ticks % STUN_REFRESH_RATE_SEC)) {
return true;
}
if (_bestStun) {
_slowTimerCounter++;
if (!(_bestStun->SlowTick(false))) {
// There is no valid candidate (failure of connection establishment)
// there should be a number of retry on the slow timer and should not wait
// for RRS to disconnect the connection
if (_slowTimerCounter > 2 && _pSig != NULL ) {
// Delete this connection after 30s
_pSig->EnqueueForDelete();
}
}
}
return true;
}
void WrtcConnection::OverrideIceMaxRetries(int newMaxRetries) {
FOR_VECTOR(_stuns, i) {
_stuns[i]->SetMaxRetries (newMaxRetries);
}
}
//
// setters called from WrtcSigProtocol
// note: ipPort is a URL string: "x.y.z.z:pppp"
//
bool WrtcConnection::SetStunServer(string ipPortStr) {
//UPDATE: We should resolve any domains at this point to IP address
// Moved here so that we resolve only once
string resolvedIpPortStr;
if (!ResolveDomainName(ipPortStr, resolvedIpPortStr)) {
FATAL("Error setting STUN server!");
return false;
}
INFO("Resolved STUN: %s", STR(resolvedIpPortStr));
FOR_VECTOR(_stuns, i) {
_stuns[i]->SetStunServer(resolvedIpPortStr);
}
return true;
}
bool WrtcConnection::SetTurnServer(string username, string credential, string ipPort) {
//UPDATE: We should resolve any domains at this point to IP address
// Moved here so that we resolve only once
string resolvedIpPortStr;
if (!ResolveDomainName(ipPort, resolvedIpPortStr)) {
FATAL("Error setting STUN server!");
return false;
}
INFO("Resolved TURN: %s", STR(resolvedIpPortStr));
FOR_VECTOR(_stuns, i) {
_stuns[i]->SetTurnServer(username, credential, resolvedIpPortStr);
}
return true;
}
bool WrtcConnection::SetCandidate(Candidate * pCan) {
FOR_VECTOR(_stuns, i) {
// Add a reference to the STUNs
_stuns[i]->AddCandidate(pCan);
}
return true;
}
bool WrtcConnection::SetControlled(bool isControlled) {
_isControlled = isControlled;
return true;
}
bool WrtcConnection::SpawnStunProtocols() {
//First make sure the sig protocol is valid
if (_pSig == NULL) {
FATAL("Signaling protocol is NULL!");
return false;
}
// For UDP stuns, use all valid interfaces
#ifdef ENABLE_ICE_UDP
vector<string> ipAddrs;
if (!GetInterfaceIps(ipAddrs)) {
FATAL("Failed to get local IP list");
return false;
}
// loop through the addr vector creating Stuns
FOR_VECTOR(ipAddrs, i) {
// Spawn a UDP ICE instance
BaseIceProtocol *pStunUdp = new IceUdpProtocol();
pStunUdp->Initialize(ipAddrs[i], this, _pSig);
_stuns.push_back(pStunUdp);
}
#endif
// For TCP stuns, we can use our used public interface since we know we can make a tcp connection on it already
#ifdef ENABLE_ICE_TCP
// Get the IO Handler of the webRTC signaling protocol
IOHandler *pHandler = _pSig->GetIOHandler();
if (pHandler == NULL) {
FATAL("IO Handler is NULL!");
return false;
}
// Get the IP address of the interface used
string ip = ((TCPCarrier *) pHandler)->GetNearEndpointAddressIp();
// Spawn TCP ICE
BaseIceProtocol *pStunTcp = new IceTcpProtocol();
pStunTcp->Initialize(ip, this, _pSig);
_stuns.push_back(pStunTcp);
#endif
return true;
}
//
// GetInterfaceIps is used to find the network interfaces on this machine
// - we have a WIN32 version and an ELSE version
//
#ifdef WIN32
bool WrtcConnection::GetInterfaceIps(vector<string> & ips) {
// WINDOZE VERSION
FATAL("IPV4 ONLY FOR WINDOWS");
struct addrinfo hints, *res;
struct in_addr addr;
uint32_t err;
char hostname[64];
err = gethostname(hostname, 64);
if (err) {
FATAL("Network interface error: %"PRIu32, err);
return false;
}
//#ifdef WEBRTC_DEBUG
DEBUG("GetInterfaceIps: hostname = %s", hostname);
//#endif
memset(&hints, 0, sizeof(hints));
hints.ai_socktype = SOCK_DGRAM;
hints.ai_family = AF_INET; // just IPv4 for now!
if ((err = getaddrinfo(hostname, NULL, &hints, &res)) != 0) {
FATAL("Network interface error %"PRIu32, err);
return false;
}
// loop through all addresses returned
while (res) {
addr.S_un = ((struct sockaddr_in *)(res->ai_addr))->sin_addr.S_un;
char dst[32];
if (inet_ntop(AF_INET, (void *)&addr, dst, 32)) {
string newip = std::string(dst);
//#ifdef WEBRTC_DEBUG
DEBUG("GetInterfaceIps: Add Interface: %s", STR(newip));
//#endif
ips.push_back(newip);
}else {
WARN("Failed to add interface: 0x%x", (uint32_t)addr.s_addr);
}
res = res->ai_next;
}
freeaddrinfo(res);
return true;
}
#else
// LINUX VERSION
bool WrtcConnection::GetInterfaceIps(vector<string> & ips) {
// Reset ip cache
ips.clear();
struct ifaddrs *localIfList = NULL;
struct ifaddrs *currIface = NULL;
void *networkAdressSrc = NULL;
string address;
// Retrieve all available network addresses/interfaces
if (getifaddrs(&localIfList) == -1) {
FATAL("Network interface error: 0x%x", errno);
return false;
}
//Loop over the interfaces and pull out the valid local IP's (ipv4 and ipv6)
for (currIface = localIfList; currIface != NULL; currIface = currIface->ifa_next) {
// Skip the interface with null address
if (!currIface->ifa_addr) {
continue;
}
// examine for IPv4
if (currIface->ifa_addr->sa_family == AF_INET) {
// Hey this is a valid IPv4 Address
networkAdressSrc = &((struct sockaddr_in *)currIface->ifa_addr)->sin_addr;
char dst[INET_ADDRSTRLEN]; //Destination address buffer
inet_ntop(AF_INET, networkAdressSrc, dst, INET_ADDRSTRLEN);
address = dst;
}
// examine for IPv6
else if (currIface->ifa_addr->sa_family == AF_INET6) {
// Hey this is a valid IPv6 Address
networkAdressSrc = &((struct sockaddr_in6 *)currIface->ifa_addr)->sin6_addr;
char dst[INET6_ADDRSTRLEN];
inet_ntop(AF_INET6, networkAdressSrc, dst, INET6_ADDRSTRLEN);
address = dst;
}
// Only use non-loopback, non-local-link, and non-empty ip's
if ( ( currIface->ifa_name[0] == 'l' && currIface->ifa_name[1] == 'o' ) ||
( address.find( "fe80::" ) != std::string::npos ) ||
( address.size() == 0 )) {
INFO("Skipping: %s", STR(address));
continue;
} else {
INFO("VALID: %s", STR(address));
// Valid address, so construct a candidate with it
ips.push_back(address);
}
}
//Cleanup
if (localIfList != NULL) {
freeifaddrs(localIfList);
}
//remove duplicates
sort( ips.begin(), ips.end() );
ips.erase( unique( ips.begin(), ips.end() ), ips.end() );
INFO("Final list of IPs:");
for( size_t i = 0; i < ips.size(); i++ )
INFO(" %s", STR(ips[i]));
return true;
}
#endif
//
// Timer calls, (into Timer Class further below)
//
void WrtcConnection::StartFastTimer() {
if (_pSlowTimer) {
delete _pSlowTimer;
_pSlowTimer = NULL;
}
if (!_pFastTimer) {
_pFastTimer = WrtcTimer::CreateFastTimer(100, this);
}
}
void WrtcConnection::StartSlowTimer() {
if (_pFastTimer) {
delete _pFastTimer;
_pFastTimer = NULL;
}
if (!_pSlowTimer) {
// Slow tick is now once per second, but recognizes STUN_REFRESH_RATE_SEC
_pSlowTimer = WrtcTimer::CreateSlowTimer(1, this);
}
}
//
// Timer Class stuff
//
WrtcConnection::WrtcTimer
::WrtcTimer(WrtcConnection * pWrtc) {
_pWrtc = pWrtc;
}
WrtcConnection::WrtcTimer
::~WrtcTimer() {
}
WrtcConnection::WrtcTimer * WrtcConnection::WrtcTimer
::CreateFastTimer(uint32_t ms, WrtcConnection * pWrtc) {
WrtcTimer * pTimer = new WrtcTimer(pWrtc);
pTimer->EnqueueForHighGranularityTimeEvent(ms);
return pTimer;
}
WrtcConnection::WrtcTimer * WrtcConnection::WrtcTimer
::CreateSlowTimer(uint32_t secs, WrtcConnection * pWrtc) {
WrtcTimer * pTimer = new WrtcTimer(pWrtc);
pTimer->EnqueueForTimeEvent(secs);
return pTimer;
}
// the timer override
bool WrtcConnection::WrtcTimer::TimePeriodElapsed() {
return _pWrtc->Tick();
}
//
// BaseProtocolOverrides
//
bool WrtcConnection::AllowFarProtocol(uint64_t type) {
return true;
}
bool WrtcConnection::AllowNearProtocol(uint64_t type) {
FATAL("This protocol doesn't allow any near protocols");
return false;
}
bool WrtcConnection::SignalInputData(int32_t recvAmount) {
FATAL("OPERATION NOT SUPPORTED");
return false;
}
// SignalInputData
// - this call gets non-stun traffic from below
//
bool WrtcConnection::SignalInputData(IOBuffer &buffer, SocketAddress *pPeerAddress) {
// TODO: handle RTCP
// double-check RTCP packet
uint8_t pt = *(GETIBPOINTER(buffer) + 1);
if (pt == 0xC8 || pt == 0xC9) { // inbound SRTCP
_rtcpReceiver.ProcessRTCPPacket(buffer);
}
else { // inbound RTP
//INFO("Please Feed the data to the inbound connection size %d", GETAVAILABLEBYTESCOUNT(buffer));
#ifdef PLAYBACK_SUPPORT
if (NULL != _pInboundConnectivity) {
_pInboundConnectivity->FeedData(0, GETIBPOINTER(buffer), GETAVAILABLEBYTESCOUNT(buffer));
}
#endif
}
return true;
}
bool WrtcConnection::SignalInputData(IOBuffer &buffer) {
FATAL("OPERATION NOT SUPPORTED");
return true;
}
bool WrtcConnection::EnqueueForOutbound() {
if (_pDtls != NULL && (_pDtls->GetType() == PT_INBOUND_DTLS)) {
if (_useSrtp) {
InboundDTLSProtocol *pInboundDtls = (InboundDTLSProtocol *) _pDtls;
if (pInboundDtls->HasSRTP()) {
if (GETAVAILABLEBYTESCOUNT(_outputBuffer) > 0) {
uint8_t firstByte = GETIBPOINTER(_outputBuffer)[0];
if ((firstByte & 0x80) > 0) { // RTP/RTCP packet
return pInboundDtls->FeedData(_outputBuffer);
}
}
}
} else {
//int32_t ret = _pSctp->SendData(_streamChannelId, GETIBPOINTER(_outputBuffer),
// GETAVAILABLEBYTESCOUNT(_outputBuffer));
int32_t chunk = 15000;
int32_t buffSize = GETAVAILABLEBYTESCOUNT(_outputBuffer);
int32_t zeroSendCount = 0;
while (buffSize > 0) {
int32_t target = (buffSize > chunk) ? chunk : buffSize;
int32_t ret = 0;
if(IsSctpAlive()) {
ret = _pSctp->SendData(_streamChannelId, GETIBPOINTER(_outputBuffer), target);
}
// Check first the returned value
if (ret > 0) {
// Everything seems ok. Read the buffer, reset the zero count,
// and decrement th buffsize with the actual sent value
_outputBuffer.Ignore(ret);
zeroSendCount = 0;
buffSize -= ret;
} else if (ret == 0) {
// Value returned is zero, handle this by resending
if (zeroSendCount++ < MAX_ZERO_SEND_THRESHOLD) {
continue;
} else {
// zero send count has reached threshold
// Use buffsize as error indicator
WARN("SCTP 0 size sent.");
buffSize = 0;
break;
}
} else {
// There was an error in sending, break out
// Use buffsize as error indicator
WARN("SCTP send failure");
buffSize = -1;
break;
}
}
if (buffSize >= 0) {
// If there was no error, return
return true;
}
}
}
_outputBuffer.IgnoreAll();
if (_pDtls == NULL) {
// No outbound protocol yet, just return as true
return true;
} else {
WARN("Failure sending data!");
return false;
}
}
IOBuffer *WrtcConnection::GetOutputBuffer() {
return &_outputBuffer;
}
bool WrtcConnection::InitializeDataChannel() {
DEBUG("Initializing data channel...");
// Get the bind port and initial best remote port
uint8_t ipv6[16];
uint32_t ip;
uint16_t port;
Variant settings;
string localIpStr = _bestStun->GetHostIpStr();
if (IpPortStrIsV6(localIpStr)) {
SplitIpStrV6(localIpStr, ipv6, port);
} else {
SplitIpStrV4(localIpStr, ip, port);
}
settings["localPort"] = port;
string remoteIpStr = _bestStun->GetBestCanIpStr();
if (IpPortStrIsV6(remoteIpStr)) {
SplitIpStrV6(remoteIpStr, ipv6, port);
} else {
SplitIpStrV4(remoteIpStr, ip, port);
}
settings["remotePort"] = port;
settings["sctpPort"] = _pSDP->GetSCTPPort();
settings["sctpMaxChannels"] = _pSDP->GetSCTPMaxChannels();
settings[CONF_SSL_CERT] = _customParameters[CONF_SSL_CERT];
settings[CONF_SSL_KEY] = _customParameters[CONF_SSL_KEY];
settings[USE_PREBUILT_SSL_CERT] = _customParameters[USE_PREBUILT_SSL_CERT];
//TODO: We should be spawning dtls and sctp protocols using the factory
// But for now, let's just instantiate them ourselves
if (_isControlled) {
DEBUG("_isControlled enabled....creating outbound dtls");
_pDtls = new OutboundDTLSProtocol(_pCertificate);
settings["sctpClient"] = true;
} else {
DEBUG("_isControlled disabled....creating inbound dtls");
_pDtls = new InboundDTLSProtocol(_pCertificate,_useSrtp);
settings["sctpClient"] = false;
}
_pDtls->Initialize(settings);
_checkHSState = true;
if(NULL == _pSctp) {
_pSctp = new SCTPProtocol();
_sctpAlive = true;
_pSctp->Initialize(settings);
}
// Link the protocols together STUN -> DTLS -> SCTP -> WrtcConnection
_pDtls->SetFarProtocol(_bestStun);
if(IsSctpAlive()) {
_pSctp->SetFarProtocol(_pDtls);
this->SetFarProtocol(_pSctp);
//TODO: consider refactoring to prevent the need for this
// Start dtls and sctp
_pDtls->Start();
_pSctp->Start(this);
_dataChannelEstablished = true;
} else {
FATAL("Error in data channel initilaize : sctp is not alive : %d",_sctpAlive);
EnqueueForDelete();
}
return true;
}
//set sctp protocol tear down status
bool WrtcConnection::IsSctpAlive() {
//FINE("WrtcConnection::IsSctpAlive : %d",_sctpAlive);
return _sctpAlive;
}
void WrtcConnection::SetSctpAlive(bool sctpalive) {
INFO("WrtcConnection::SetSctpAlive : %d",sctpalive);
_sctpAlive = sctpalive;
}
// IAN TODO: start merging this to InitializeDataChannel
bool WrtcConnection::InitializeSrtp() {
DEBUG("Initializing SRTP...");
uint32_t ip;
uint16_t port;
Variant settings;
string localIpStr = _bestStun->GetHostIpStr();
SplitIpStrV4(localIpStr, ip, port);
settings["localPort"] = port;
string remoteIpStr = _bestStun->GetBestCanIpStr();
SplitIpStrV4(remoteIpStr, ip, port);
settings["remotePort"] = port;
settings[CONF_SSL_CERT] = _customParameters[CONF_SSL_CERT];
settings[CONF_SSL_KEY] = _customParameters[CONF_SSL_KEY];
// Should be spawning dtls protocol using the factory
// but time is of the essence... let's worry about that later... ian
_pDtls = new InboundDTLSProtocol(_pCertificate,true);
_pDtls->Initialize(settings);
// Link the protocols together STUN -> DTLS -> WrtcConnection
_pDtls->SetFarProtocol(_bestStun);
this->SetFarProtocol(_pDtls);
//TODO: consider refactoring to prevent the need for this
// Start dtls
_pDtls->Start();
// ((InboundDTLSProtocol *)_pDtls)->CreateOutSRTPStream(_streamName);
return true;
}
bool WrtcConnection::SignalDataChannelCreated(const string &name, uint32_t id) {
//#ifdef WEBRTC_DEBUG
DEBUG("DataChannel created: %s (%"PRIu32")", STR(name), id);
//#endif
if (name == SCTP_COMMAND_CHANNEL) {
PROBE_POINT("webrtc", "sess1", "sctp_cmd_channel_created", false);
// Any form of command or request/response is sent using the 'command' channel
_commandChannelId = id;
} else if (name == SCTP_STREAM_CHANNEL) {
PROBE_POINT("webrtc", "sess1", "sctp_strm_channel_created", false);
// The data is then sent through the 'stream' command
_streamChannelId = id;
} else {
WARN("Channel name does not match either command or stream channel names!");
}
return true;
}
bool WrtcConnection::SignalDataChannelInput(uint32_t id, const uint8_t *pBuffer, const uint32_t size) {
// Parse the message that was received on this channel and handle accordingly
if (_commandChannelId == id) {
//#ifdef WEBRTC_DEBUG
FINE("Message received: (%"PRIu32") %.*s", size, size, pBuffer);
//#endif
string msgString = string((char *) pBuffer, size);
Variant msg;
uint32_t start = 0;
if (!Variant::DeserializeFromJSON(msgString, msg, start)) {
FATAL("Unable to parse JSON string!");
return false;
}
return HandleDataChannelMessage(msg);
} else if (_streamChannelId == id) {
//TODO
FATAL("Inbound FMP4 data. Operation not yet supported!");
return false;
} else {
WARN("Unknown channel ID: %"PRIu32, id);
return false;
}
return true;
}
bool WrtcConnection::SignalDataChannelReady(uint32_t id) {
FINE("SignalDataChannelReady: %"PRIu32, id);
return true;
}
bool WrtcConnection::SignalDataChannelClosed(uint32_t id) {
//#ifdef WEBRTC_DEBUG
FINE("SignalDataChannelClosed: %"PRIu32, id);
//#endif
return true;
}
bool WrtcConnection::PushMetaData(Variant &metadata) {
Variant meta;
meta["type"] = "metadata";
meta["payload"]= metadata;
string data = "";
meta.SerializeToJSON(data, true);
return SendCommandData(data);
}
bool WrtcConnection::SetupPlaylist(string const &streamName) {
Variant message;
return SetupPlaylist(streamName, message);
}
bool WrtcConnection::SetupPlaylist(string const &streamName, Variant &config, bool appendRandomChars) {
Variant message;
message["header"] = "pullStream";
message["payload"]["command"] = message["header"];
//do not save to pushpull config
config["serializeToConfig"] = "0";
config["localStreamName"] = (appendRandomChars ? generateRandomString(8) + ";*" : "") + streamName;
config["keepAlive"] = "0";
config["uri"] =
format("rtmp://localhost/vod/%s", STR(streamName));
if (config.HasKeyChain(V_MAP, false, 1, "callback")) {
config["_callback"] = config["callback"];
config.RemoveKey("callback");
}
message["payload"]["parameters"] = config;
ClientApplicationManager::BroadcastMessageToAllApplications(message);
return (message.HasKeyChain(V_BOOL, true, 3, "payload", "parameters", "ok")
|| (bool)message["payload"]["parameters"]["ok"]);
}
bool WrtcConnection::SetupLazyPull(string const &streamName) {
BaseClientApplication *pApp = GetApplication();
if (pApp) {
StreamMetadataResolver *pSMR = pApp->GetStreamMetadataResolver();
if (pSMR) {
Metadata metadata;
return pSMR->ResolveMetadata(streamName, metadata, true);
}
}
return false;
}
bool WrtcConnection::HandleDataChannelMessage(Variant &msg) {
string errMsg = "";
string response = "";
// Check the message type
if (msg.HasKey("type")) {
if (msg["type"] == "fmp4Request") {
// Sanity check, make sure that no SRTP stream exists
if (_useSrtp) {
// Nothing to do here
return true;
}
// Prepare the response
msg["type"] = "fmp4Response";
// Check if this is a full MP4 for iOS devices instead
if (msg.HasKeyChain(V_BOOL, false, 2, "payload", "fullMp4")) {
_fullMp4 = (bool) msg["payload"]["fullMp4"];
}
if (msg.HasKeyChain(V_STRING, false, 2, "payload", "name")) {
// Get the requested stream name
string streamName = msg["payload"]["name"];
bool useSrtp = false;
if (msg.HasKeyChain(V_BOOL, false, 2, "payload", "useSrtp")) {
useSrtp = (bool) msg["payload"]["useSrtp"];
}
FINE("WebRTC request: %s", STR(streamName));
string rsn = lowerCase(streamName);
_isPlaylist = (rsn.rfind(".lst") == rsn.length() - 4);
bool isLazyPullVod = _isPlaylist ? false :
(rsn.rfind(".vod") == rsn.length() - 4);
bool streamCanBeSent = true;
uint8_t retries = 10;
if (_isPlaylist) {
if (!SetupPlaylist(streamName)) {
streamCanBeSent = false;
} else {
//wait until requested stream is set up
while (retries-- > 0 &&
!SetStreamName(streamName, useSrtp)) {
}
streamCanBeSent = (retries > 0);
}
} else if (isLazyPullVod) {
streamCanBeSent = false;
if (SetupLazyPull(streamName)) {
//wait until requested stream is set up
while (retries-- > 0 &&
!SetStreamName(streamName, useSrtp)) {
}
streamCanBeSent = (retries > 0);
}
} else {
streamCanBeSent = SendStreamAsMp4(streamName);
}
// Send out the outbound FMP4
if (streamCanBeSent) {
msg["payload"]["description"] =
"Outbound FMP4 stream created.";
msg["payload"]["status"] = "SUCCESS";
msg.SerializeToJSON(response, true);
return SendCommandData(response);
} else {
errMsg = "Requested stream could not be sent!";
WARN("%s", STR(errMsg));
}
} else {
errMsg = "Missing name field!";
WARN("%s", STR(errMsg));
}
// If this point was reached, then something went wrong
msg["payload"]["description"] = errMsg;
msg["payload"]["status"] = "FAIL";
msg.SerializeToJSON(response, true);
return SendCommandData(response);
} else if (msg["type"] =="command" ) {
FINE("Command received: %s - [%s]", STR(msg["payload"]["command"]), STR(msg["payload"]["argument"]));
msg["payload"]["instanceStreamName"] = _streamName;
msg["payload"]["baseStreamName"] = GetBaseStreamName(_streamName);
GetEventLogger()->LogWebRTCCommandReceived(msg);
string command = lowerCase((string)msg["payload"]["command"]);
string argument = (string)msg["payload"]["argument"];
_cmdReceived.assign(argument);
if (command == "stop") {
INFO("Received Stop Command: %s", STR(argument));
// We tear down this session if we received this command from the player
EnqueueForDelete();
} else if (command == "pause") {
HandlePauseCommand();
} else if (command == "resume") {
HandleResumeCommand();
} else if (command == "ping") {
if (_pOutNetMP4Stream) {
((OutNetFMP4Stream*)_pOutNetMP4Stream)->SignalPing();
}
}
return true;
}
#ifdef WRTC_CAPAB_HAS_HEARTBEAT
else if (msg["type"] == "heartbeat") {
ProcessHeartbeat();
return true;
}
#endif // WRTC_CAPAB_HAS_HEARTBEAT
else {
// invalid request
WARN("Invalid message type!");
}
} else {
WARN("Invalid message format!");
}
FINEST("Message received: %s", STR(msg.ToString()));
return false;
}
bool WrtcConnection::SendStreamAsMp4(string &streamName) {
// Get the application
BaseClientApplication *pApp = NULL;
if ((pApp = GetApplication()) == NULL) {
FATAL("Unable to get the application");
return false;
}
uint64_t outputStreamType = ST_OUT_NET_FMP4;
if (_fullMp4) {
outputStreamType = ST_OUT_NET_MP4;
}
// Get the private stream name
string privateStreamName = pApp->GetStreamNameByAlias(streamName, false);
if (privateStreamName == "") {
FATAL("Stream name alias value not found: %s", STR(streamName));
return false;
}
// Get the streams manager
StreamsManager *pSM = NULL;
if ((pSM = pApp->GetStreamsManager()) == NULL) {
FATAL("Unable to get the streams manager");
return false;
}
map<uint32_t, BaseStream *> outStreams = pSM->FindByTypeByName(outputStreamType, privateStreamName, false, false);
if (!outStreams.empty()) {
if (_fullMp4) {
_pOutNetMP4Stream = (OutNetMP4Stream *) MAP_VAL(outStreams.begin());
} else {
_pOutNetMP4Stream = (OutNetFMP4Stream *) MAP_VAL(outStreams.begin());
}
}
if (_pOutNetMP4Stream == NULL) {
//there is no output stream with this name. Create one
if (_fullMp4) {
_pOutNetMP4Stream = OutNetMP4Stream::GetInstance(pApp, privateStreamName);
} else {
_pOutNetMP4Stream = OutNetFMP4Stream::GetInstance(pApp, privateStreamName, true);
}
if (_pOutNetMP4Stream == NULL) {
FATAL("Unable to create the output stream");
return 0;
}
BaseInStream *pInStream = NULL;
map<uint32_t, BaseStream *> inStreams = pSM->FindByTypeByName(ST_IN_NET, privateStreamName, true, false);
if (inStreams.size() != 0) {
pInStream = (BaseInStream *) MAP_VAL(inStreams.begin());
}
// Link the inbound stream to this output stream
if ((pInStream != NULL) && (pInStream->IsCompatibleWithType(outputStreamType))) {
if (!pInStream->Link(_pOutNetMP4Stream)) {
FATAL("Unable to link the in/out streams");
_pOutNetMP4Stream->EnqueueForDelete();
_pOutNetMP4Stream = NULL; // b2: don't delete it later
return false;
}
} else {
// Either we can't find the input stream or it is incompatible with outFMP4
if (!pInStream) {
FATAL("Input stream (%s) not found!", STR(privateStreamName));
} else {
FATAL("Input stream (%s) is not compatible with %s!",
STR(*pInStream), STR(tagToString(outputStreamType)));
}
return false;
}
}
((OutNetFMP4Stream *)_pOutNetMP4Stream)->SetWrtcConnection(this);
// Register the underlying protocol (this one)
if (_fullMp4) {
((OutNetMP4Stream *)_pOutNetMP4Stream)->RegisterOutputProtocol(GetId(), NULL);
} else {
((OutNetFMP4Stream *)_pOutNetMP4Stream)->RegisterOutputProtocol(GetId(), NULL);
}
//it means we already attached the outstream to the wrtcconnection protocol but not the full stack
if(_isStreamAttached){
if (!_fullMp4) {
((OutNetFMP4Stream *)_pOutNetMP4Stream)->SetOutStreamStackEstablished();
}
}
_isStreamAttached = true;
PROBE_POINT("webrtc", "sess1", "instream_outstream_linked", false);
return true;
}
bool WrtcConnection::SendCommandData(string &message) {
// Make sure SCTP layer has been setup
if(!IsSctpAlive()) {
return false;
}
// Send data to the command channel
_outbandBuffer.IgnoreAll();
_outbandBuffer.ReadFromString(message);
if (_pSctp->SendData(_commandChannelId, GETIBPOINTER(_outbandBuffer),
GETAVAILABLEBYTESCOUNT(_outbandBuffer), false) > 0) {
//#ifdef WEBRTC_DEBUG
// Moving the log into this as it will spam if metadata are being sent out
FINE("Sent out: %s", STR(message));
//#endif
PROBE_POINT("webrtc", "sess1", "sct_cmd_send", false);
PROBE_FLUSH("webrtc", "sess1", false);
return true;
}
FATAL("Error sending data over command channel!");
return false;
}
bool WrtcConnection::InitializeCertificate() {
if (_pCertificate != NULL) {
// If this has been instantiated already, use this
DEBUG("wrtc is using pregenerated ssl cert");
return true;
}
bool useprebuiltsslcert = false;
if (_customParameters.HasKey(USE_PREBUILT_SSL_CERT)) {
useprebuiltsslcert = (bool) _customParameters[USE_PREBUILT_SSL_CERT];
}
if(useprebuiltsslcert) {
INFO("wrtc is using prebuilt ssl cert");
string cert = "";
string key = "";
// Get the certificate and key
if (_customParameters.HasKey(CONF_SSL_CERT)) {
cert = (string) _customParameters[CONF_SSL_CERT];
}
if (_customParameters.HasKey(CONF_SSL_KEY)) {
key = (string) _customParameters[CONF_SSL_KEY];
}
//TODO: For now, we require a physical certificate
if ((key == "") || (cert == "")) {
FATAL("Certificate and key should be provided on the config file!");
return false;
}
_pCertificate = X509Certificate::GetInstance(cert, key);
} else {
INFO("wrtc is generating ssl cert");
_pCertificate = X509Certificate::GetInstance();
}
INFO("Initializing certificate in WrtcConnection");
return true;
}
bool WrtcConnection::SendOutOfBandData(const IOBuffer &buffer, void *pUserData) {
if (pUserData == NULL) {
// skip data if there is streamChannel is not configured
if (_streamChannelId == 0xFFFFFFFF) {
// store moov; send later when there is streamChannel
if (GETAVAILABLEBYTESCOUNT(_moovBuffer) == 0) {
_moovBuffer.ReadFromInputBuffer(buffer, GETAVAILABLEBYTESCOUNT(buffer));
}
return true;
}
// send buffered moov first if not yet sent
if (GETAVAILABLEBYTESCOUNT(_moovBuffer) > 0) {
_outputBuffer.ReadFromInputBuffer(_moovBuffer, GETAVAILABLEBYTESCOUNT(_moovBuffer));
_moovBuffer.IgnoreAll();
EnqueueForOutbound();
}
// Read the buffer and send it out
_outputBuffer.ReadFromInputBuffer(buffer, GETAVAILABLEBYTESCOUNT(buffer));
return EnqueueForOutbound();
} else {
// pUserData has content, probably metadata
PushMetaData((Variant &) *((Variant *) pUserData));
}
return true;
}
void WrtcConnection::SignalOutOfBandDataEnd(void *pUserData) {
FINE("Outbound stream has been detached.");
// Stream has been disconnected
_isStreamAttached = false;
_pOutNetMP4Stream = NULL;
EnqueueForDelete();
}
void WrtcConnection::SignalEvent(string eventName, Variant &args) {
if (eventName == "srtpInitEvent") {
if (args.HasKeyChain(V_BOOL, false, 1, "result") && _pOutboundConnectivity != NULL) {
if (((bool)args.GetValue("result", false)) == true) {
_pOutboundConnectivity->Enable(true);
INFO("WrtcConnection: Enable the already created Outbound Connection");
}
else {
_rtcpReceiver.SetOutNetRTPStream(NULL);
INFO("WrtcConnection: Destroying Outbound Connection and Outbound Stream");
// destroy outboundConnectivity and Outbound Stream
_pOutboundConnectivity->SetOutStream(NULL);
_pOutStream->SetConnectivity(NULL);
delete _pOutboundConnectivity;
delete _pOutStream;
_pOutNetMP4Stream = NULL;
_pOutStream = NULL;
}
}
#ifdef PLAYBACK_SUPPORT
if (args.HasKeyChain(V_BOOL, false, 1, "result") && _pInboundConnectivity != NULL && _pTalkDownStream != NULL) {
if (((bool)args.GetValue("result", false)) == true) {
_pTalkDownStream->Enable(true);
if(_is2wayAudioSupported) {
#ifdef RTMSG
notifyLedManager(1);
#endif
}
}
else {
// destroy inboundConnectivity and Outbound Stream
delete _pInboundConnectivity;
delete _pTalkDownStream;
_pInboundConnectivity = NULL;
_pTalkDownStream = NULL;
}
}
#endif
}
else if (eventName == "updatePendingStream") {
BaseClientApplication *pApp = GetApplication();
if (pApp == NULL) {
FATAL("Unable to get application");
return;
}
StreamsManager *pSM = pApp->GetStreamsManager();
if (pSM == NULL) {
FATAL("Unable to get streams manager");
return;
}
if (_pPendingInStream == NULL) {
if (!args.HasKeyChain(_V_NUMERIC, false, 1, "streamID")) {
FATAL("Invalid update stream callback");
return;
}
uint32_t streamID = args.GetValue("streamID", false);
_pPendingInStream = (BaseInStream *) pSM->FindByUniqueId(streamID);
if (_pPendingInStream == NULL) { // for some reason, the stream does not exist anymore
FATAL("Unable to retrieve stream");
return;
}
_pendingFlag |= PENDING_STREAM_REGISTERED;
}
StreamCapabilities *pCaps = _pPendingInStream->GetCapabilities();
if (pCaps == NULL) {
return;
}
if (!(_pendingFlag & PENDING_HAS_VCODEC) && pCaps->GetVideoCodec() != NULL) {
_pendingFlag |= PENDING_HAS_VCODEC;
}
if (!(_pendingFlag & PENDING_HAS_ACODEC) && pCaps->GetAudioCodec() != NULL) {
_pendingFlag |= PENDING_HAS_ACODEC;
}
uint32_t pendingFlagCheck = _pendingFlag & PENDING_COMPLETE;
if ((pendingFlagCheck == PENDING_COMPLETE)
|| (_pPendingInStream->GetType() == ST_IN_NET_RTP &&
pendingFlagCheck == (PENDING_STREAM_REGISTERED | PENDING_HAS_VCODEC)
)
) {
if (_waiting) {
string streamName = args.GetValue("streamName", false);
DEBUG("creating out stream in updatePendingStream event");
CreateOutStream(streamName, _pPendingInStream, pSM);
_waiting = false;
_pendingFlag = 0;
_pPendingInStream = NULL;
Start();
}
}
}
}
void WrtcConnection::Stop() {
if (_pOutNetMP4Stream != NULL) {
_pOutNetMP4Stream->SignalDetachedFromInStream();
_pOutNetMP4Stream = NULL;
}
}
bool WrtcConnection::HasAudio() {
return _mediaContext.hasAudio;
}
bool WrtcConnection::HasVideo() {
return _mediaContext.hasVideo;
}
void WrtcConnection::HasAudio(bool value) {
_mediaContext.hasAudio = value;
}
void WrtcConnection::HasVideo(bool value) {
_mediaContext.hasVideo = value;
}
void WrtcConnection::UnlinkSignal(WrtcSigProtocol *pSig, bool external) {
if (pSig != _pSig)
return;
if (external && _pSig != NULL) {
_pSig->UnlinkConnection(this, false);
}
_pSig = NULL;
}
string WrtcConnection::GetBaseStreamName(string const &streamName) {
size_t pos = streamName.rfind(";*");
if (pos != string::npos) {
return streamName.substr(pos + 2);
}
return streamName;
}
bool WrtcConnection::IsSameStream(string const &localStreamName,
string const &streamName) {
if (localStreamName == streamName) {
return true;
}
//this is used to handle playlists using uuids on their names
bool isSame = false;
string baseName = GetBaseStreamName(streamName);
if (baseName != streamName) {
isSame = (localStreamName == baseName);
}
return isSame;
}
bool WrtcConnection::SendWebRTCCommand(Variant& settings) {
FINEST("WrtcConnection::SendWebRTCCommand()");
string command = settings["command"];
string localStreamName = settings["localstreamname"];
string argument = settings["argument"];
string isBase64 = settings["base64"];
string payload = "{\"command\":\"" + command + "\",\"argument\":\"" + argument + "\",\"base64\":" + isBase64 + "}";
BaseOutStream *pOutStream = GetOutboundStream();
if (pOutStream != NULL && IsSameStream(localStreamName, pOutStream->GetName())) {
DEBUG("Sending command through data channel...");
// Log the message only if client is connected to RMS
if (payload.find(TOGGLE_COMMAND) != string::npos ) {
INFO("StreamTeardown: toggling the Audio.");
}
return SendCommandData(payload);
}
return true;
}
bool WrtcConnection::HandlePauseCommand() {
//INFO("Stream playback paused");
// probe the TS for client pause command and store
std::stringstream sstrm;
sstrm << GetId();
string probSess("wrtcplayback");
probSess += sstrm.str();
uint64_t ts = PROBE_TRACK_TIME_MS(STR(probSess) );
INFO("Stream playback paused:%"PRId64"", ts);
probSess += "clientPaused";
PROBE_STORE_TIME(STR(probSess),ts);
BaseOutStream *pOutStream = GetOutboundStream();
if (pOutStream != NULL)
pOutStream->SignalPause();
return true;
}
bool WrtcConnection::HandleResumeCommand() {
//INFO("Stream playback resumed");
// probe the TS for client resume command and store
std::stringstream sstrm;
sstrm << GetId();
string probSess("wrtcplayback");
probSess += sstrm.str();
uint64_t ts = PROBE_TRACK_TIME_MS(STR(probSess) );
INFO("Stream playback resumed:%"PRId64"", ts);
probSess += "clientResumed";
PROBE_STORE_TIME(STR(probSess),ts);
BaseOutStream *pOutStream = GetOutboundStream();
if (pOutStream != NULL)
pOutStream->SignalResume();
return true;
}
uint32_t WrtcConnection::GetCommandChannelId() {
return _commandChannelId;
}
BaseOutStream *WrtcConnection::GetOutboundStream() {
return _useSrtp ? _pOutStream : _pOutNetMP4Stream;
}
void WrtcConnection::SetPeerCapabilities(string capabilities) {
// Reset values here
_capabPeer.hasHeartbeat = false;
//TODO: include other features
// Check for the features
#ifdef WRTC_CAPAB_HAS_HEARTBEAT
if (capabilities.find(WRTC_CAPAB_STR_HAS_HEARTBEAT) != string::npos) {
INFO("Peer has support for heartbeat mechanism.");
_capabPeer.hasHeartbeat = true;
}
#endif // WRTC_CAPAB_HAS_HEARTBEAT
}
Capabilities WrtcConnection::GetCapabilities(bool isRms) {
if (isRms) {
return _capabRms;
} else {
return _capabPeer;
}
}
void WrtcConnection::SetRmsCapabilities() {
// Reset values here
_capabRms.hasHeartbeat = false;
//TODO: include other features
#ifdef WRTC_CAPAB_HAS_HEARTBEAT
_capabRms.hasHeartbeat = true;
#endif // WRTC_CAPAB_HAS_HEARTBEAT
}
#ifdef WRTC_CAPAB_HAS_HEARTBEAT
bool WrtcConnection::SendHeartbeat() {
Variant meta;
meta["type"] = "heartbeat";
meta["payload"]= "";
string data = "";
meta.SerializeToJSON(data, true);
return SendCommandData(data);
}
void WrtcConnection::ProcessHeartbeat() {
_hbNoAckCounter = 0;
}
#endif // WRTC_CAPAB_HAS_HEARTBEAT
void WrtcConnection::RemoveIceInstance(BaseIceProtocol *pIce) {
// Remove all instances of this ice protocol from the lists being managed
FOR_VECTOR_ITERATOR(BaseIceProtocol *, _stuns, iterator) {
if (VECTOR_VAL(iterator)->GetId() == pIce->GetId()) {
_stuns.erase(iterator);
break;
}
}
}
#ifdef RTMSG
void WrtcConnection::notifyLedManager(int led_stat) {
BaseClientApplication *pApp = GetApplication();
if (pApp == NULL) {
FATAL("failed in notifying the Led Manager as unable to get the application");
return;
}
rtMessage_Create(&m);
rtMessage_SetInt32(m, "audio_status", led_stat);
WrtcAppProtocolHandler *handler = (WrtcAppProtocolHandler *) (pApp->GetProtocolHandler(PT_WRTC_SIG));
if(handler) {
rtConnection connectionSend = handler->GetRtSendMessageTag();
err = rtConnection_SendMessage(connectionSend, m, "RDKC.TWOWAYAUDIO");
if (err != RT_OK) {
FINE("Error sending msg via rtmessage to led manager");
}
}
else {
FATAL("failed in notifying the Led Manager as unable to get the sig protocol handler");
}
rtMessage_Release(m);
}
#endif
bool WrtcConnection::SetPeerState(PeerState peerState) {
if (_pSig != NULL) {
_pSig->SetPeerState(peerState);
return true;
}
else {
return false;
}
}
string WrtcConnection::GetPeerState() {
if (_pSig != NULL) {
return _pSig->GetPeerState();
}
else {
return NULL;
}
}
bool WrtcConnection::ResolveDomainName(string domainName, string &resolvedName) {
string domain;
uint16_t port;
if (!SplitIpStr(domainName, domain, port)) {
FATAL("Invalid STUN server format (%s)!", STR(domainName));
return false;
}
#if 0
string ip = getHostByName(domain);
if (ip == "") {
FATAL("Could not resolve STUN server (%s)!", STR(domain));
return false;
}
#endif
string ip;
vector <string> addrList;
if(!getAllHostByName(domain, addrList)) {
FATAL("Could not resolve STUN server (%s)!", STR(domain));
return false;
}
INFO("List of resolved ips for %s are: ", STR(domain));
FOR_VECTOR_ITERATOR(string, addrList, i) {
INFO(" %s", STR(VECTOR_VAL(i)) );
}
FOR_VECTOR_ITERATOR(string, addrList, i) {
INFO(" %s", STR(VECTOR_VAL(i)) );
ip = STR(VECTOR_VAL(i));
// break the loop once we get an ip
if (!(ip.empty())) {
break;
}
}
resolvedName = SocketAddress::getIPwithPort(ip, port);
return true;
}
#endif // HAS_PROTOCOL_WEBRTC
| 28.774415 | 357 | 0.693617 | [
"object",
"vector"
] |
b824db2439414c93240ab090c92a3cabd9c3ff88 | 10,432 | cpp | C++ | src/opt_flow.cpp | minxuanjun/basalt-mirror | 412c2728569727088d18ebdcb5dc34839b74f458 | [
"BSD-3-Clause"
] | 1 | 2020-05-01T14:10:21.000Z | 2020-05-01T14:10:21.000Z | src/opt_flow.cpp | minxuanjun/basalt-mirror | 412c2728569727088d18ebdcb5dc34839b74f458 | [
"BSD-3-Clause"
] | null | null | null | src/opt_flow.cpp | minxuanjun/basalt-mirror | 412c2728569727088d18ebdcb5dc34839b74f458 | [
"BSD-3-Clause"
] | 2 | 2020-05-01T14:11:09.000Z | 2020-05-01T14:47:59.000Z | /**
BSD 3-Clause License
This file is part of the Basalt project.
https://gitlab.com/VladyslavUsenko/basalt.git
Copyright (c) 2019, Vladyslav Usenko and Nikolaus Demmel.
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 the copyright holder 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 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.
*/
#include <algorithm>
#include <chrono>
#include <iostream>
#include <thread>
#include <sophus/se3.hpp>
#include <tbb/concurrent_unordered_map.h>
#include <tbb/tbb.h>
#include <pangolin/display/image_view.h>
#include <pangolin/gl/gldraw.h>
#include <pangolin/image/image.h>
#include <pangolin/image/image_io.h>
#include <pangolin/image/typed_image.h>
#include <pangolin/pangolin.h>
#include <CLI/CLI.hpp>
#include <basalt/io/dataset_io.h>
#include <basalt/spline/se3_spline.h>
#include <basalt/calibration/calibration.hpp>
#include <basalt/optical_flow/optical_flow.h>
#include <basalt/serialization/headers_serialization.h>
constexpr int UI_WIDTH = 200;
void draw_image_overlay(pangolin::View& v, size_t cam_id);
void load_data(const std::string& calib_path);
bool next_step();
bool prev_step();
pangolin::Var<int> show_frame("ui.show_frame", 0, 0, 1500);
pangolin::Var<bool> show_obs("ui.show_obs", true, false, true);
pangolin::Var<bool> show_ids("ui.show_ids", false, false, true);
using Button = pangolin::Var<std::function<void(void)>>;
Button next_step_btn("ui.next_step", &next_step);
Button prev_step_btn("ui.prev_step", &prev_step);
pangolin::Var<bool> continue_btn("ui.continue", true, false, true);
// Opt flow variables
basalt::VioDatasetPtr vio_dataset;
basalt::VioConfig vio_config;
basalt::OpticalFlowBase::Ptr opt_flow_ptr;
tbb::concurrent_unordered_map<int64_t, basalt::OpticalFlowResult::Ptr>
observations;
tbb::concurrent_bounded_queue<basalt::OpticalFlowResult::Ptr>
observations_queue;
basalt::Calibration<double> calib;
std::unordered_map<basalt::KeypointId, int> keypoint_stats;
void feed_images() {
std::cout << "Started input_data thread " << std::endl;
for (size_t i = 0; i < vio_dataset->get_image_timestamps().size(); i++) {
basalt::OpticalFlowInput::Ptr data(new basalt::OpticalFlowInput);
data->t_ns = vio_dataset->get_image_timestamps()[i];
data->img_data = vio_dataset->get_image_data(data->t_ns);
opt_flow_ptr->input_queue.push(data);
}
// Indicate the end of the sequence
basalt::OpticalFlowInput::Ptr data;
opt_flow_ptr->input_queue.push(data);
std::cout << "Finished input_data thread " << std::endl;
}
void read_result() {
std::cout << "Started read_result thread " << std::endl;
basalt::OpticalFlowResult::Ptr res;
while (true) {
observations_queue.pop(res);
if (!res.get()) break;
res->input_images.reset();
observations.emplace(res->t_ns, res);
for (size_t i = 0; i < res->observations.size(); i++)
for (const auto& kv : res->observations.at(i)) {
if (keypoint_stats.count(kv.first) == 0) {
keypoint_stats[kv.first] = 1;
} else {
keypoint_stats[kv.first]++;
}
}
}
std::cout << "Finished read_result thread " << std::endl;
double sum = 0;
for (const auto& kv : keypoint_stats) {
sum += kv.second;
}
std::cout << "Mean track length: " << sum / keypoint_stats.size()
<< " num_points: " << keypoint_stats.size() << std::endl;
}
int main(int argc, char** argv) {
bool show_gui = true;
std::string cam_calib_path;
std::string dataset_path;
std::string dataset_type;
std::string config_path;
CLI::App app{"App description"};
app.add_option("--show-gui", show_gui, "Show GUI");
app.add_option("--cam-calib", cam_calib_path,
"Ground-truth camera calibration used for simulation.")
->required();
app.add_option("--dataset-path", dataset_path, "Path to dataset.")
->required();
app.add_option("--dataset-type", dataset_type, "Type of dataset.")
->required();
app.add_option("--config-path", config_path, "Path to config file.");
try {
app.parse(argc, argv);
} catch (const CLI::ParseError& e) {
return app.exit(e);
}
if (!config_path.empty()) {
vio_config.load(config_path);
}
load_data(cam_calib_path);
{
basalt::DatasetIoInterfacePtr dataset_io =
basalt::DatasetIoFactory::getDatasetIo(dataset_type);
dataset_io->read(dataset_path);
vio_dataset = dataset_io->get_data();
vio_dataset->get_image_timestamps().erase(
vio_dataset->get_image_timestamps().begin());
show_frame.Meta().range[1] = vio_dataset->get_image_timestamps().size() - 1;
show_frame.Meta().gui_changed = true;
opt_flow_ptr =
basalt::OpticalFlowFactory::getOpticalFlow(vio_config, calib);
if (show_gui) opt_flow_ptr->output_queue = &observations_queue;
observations_queue.set_capacity(100);
keypoint_stats.reserve(50000);
}
std::thread t1(&feed_images);
if (show_gui) {
std::thread t2(&read_result);
pangolin::CreateWindowAndBind("Main", 1800, 1000);
glEnable(GL_DEPTH_TEST);
pangolin::View& img_view_display =
pangolin::CreateDisplay()
.SetBounds(0, 1.0, pangolin::Attach::Pix(UI_WIDTH), 1.0)
.SetLayout(pangolin::LayoutEqual);
pangolin::CreatePanel("ui").SetBounds(0.0, 1.0, 0.0,
pangolin::Attach::Pix(UI_WIDTH));
std::vector<std::shared_ptr<pangolin::ImageView>> img_view;
while (img_view.size() < calib.intrinsics.size()) {
std::shared_ptr<pangolin::ImageView> iv(new pangolin::ImageView);
size_t idx = img_view.size();
img_view.push_back(iv);
img_view_display.AddDisplay(*iv);
iv->extern_draw_function =
std::bind(&draw_image_overlay, std::placeholders::_1, idx);
}
while (!pangolin::ShouldQuit()) {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glClearColor(0.95f, 0.95f, 0.95f, 1.0f);
img_view_display.Activate();
if (show_frame.GuiChanged()) {
size_t frame_id = static_cast<size_t>(show_frame);
int64_t timestamp = vio_dataset->get_image_timestamps()[frame_id];
const std::vector<basalt::ImageData>& img_vec =
vio_dataset->get_image_data(timestamp);
for (size_t cam_id = 0; cam_id < calib.intrinsics.size(); cam_id++) {
if (img_vec[cam_id].img.get()) {
auto img = img_vec[cam_id].img;
pangolin::GlPixFormat fmt;
fmt.glformat = GL_LUMINANCE;
fmt.gltype = GL_UNSIGNED_SHORT;
fmt.scalable_internal_format = GL_LUMINANCE16;
img_view[cam_id]->SetImage(img->ptr, img->w, img->h, img->pitch,
fmt);
} else {
img_view[cam_id]->Clear();
}
}
}
pangolin::FinishFrame();
if (continue_btn) {
if (!next_step()) {
continue_btn = false;
}
} else {
std::this_thread::sleep_for(std::chrono::milliseconds(50));
}
}
t2.join();
}
t1.join();
return 0;
}
void draw_image_overlay(pangolin::View& v, size_t cam_id) {
UNUSED(v);
size_t frame_id = static_cast<size_t>(show_frame);
int64_t t_ns = vio_dataset->get_image_timestamps()[frame_id];
if (show_obs) {
glLineWidth(1.0);
glColor3f(1.0, 0.0, 0.0);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
if (observations.count(t_ns) > 0) {
const Eigen::aligned_map<basalt::KeypointId, Eigen::AffineCompact2f>&
kp_map = observations.at(t_ns)->observations[cam_id];
for (const auto& kv : kp_map) {
Eigen::MatrixXf transformed_patch =
kv.second.linear() * opt_flow_ptr->patch_coord;
transformed_patch.colwise() += kv.second.translation();
for (int i = 0; i < transformed_patch.cols(); i++) {
const Eigen::Vector2f c = transformed_patch.col(i);
pangolin::glDrawCirclePerimeter(c[0], c[1], 0.5f);
}
const Eigen::Vector2f c = kv.second.translation();
if (show_ids)
pangolin::GlFont::I().Text("%d", kv.first).Draw(5 + c[0], 5 + c[1]);
}
pangolin::GlFont::I()
.Text("Tracked %d keypoints", kp_map.size())
.Draw(5, 20);
}
}
}
void load_data(const std::string& calib_path) {
std::ifstream os(calib_path, std::ios::binary);
if (os.is_open()) {
cereal::JSONInputArchive archive(os);
archive(calib);
std::cout << "Loaded camera with " << calib.intrinsics.size() << " cameras"
<< std::endl;
} else {
std::cerr << "could not load camera calibration " << calib_path
<< std::endl;
std::abort();
}
}
bool next_step() {
if (show_frame < int(vio_dataset->get_image_timestamps().size()) - 1) {
show_frame = show_frame + 1;
show_frame.Meta().gui_changed = true;
return true;
} else {
return false;
}
}
bool prev_step() {
if (show_frame > 0) {
show_frame = show_frame - 1;
show_frame.Meta().gui_changed = true;
return true;
} else {
return false;
}
}
| 29.221289 | 80 | 0.668616 | [
"vector"
] |
b82ed8f53363f77d14bd89be77f783461004c826 | 1,483 | cpp | C++ | test/json.cpp | Collobos/nodeoze | 40d98bb085d27f6c283aac61d2b373bf761188d6 | [
"MIT"
] | null | null | null | test/json.cpp | Collobos/nodeoze | 40d98bb085d27f6c283aac61d2b373bf761188d6 | [
"MIT"
] | null | null | null | test/json.cpp | Collobos/nodeoze | 40d98bb085d27f6c283aac61d2b373bf761188d6 | [
"MIT"
] | null | null | null | #include <nodeoze/json.h>
#include <nodeoze/test.h>
using namespace nodeoze;
TEST_CASE( "nodeoze/smoke/json" )
{
SUBCASE( "inflate" )
{
auto obj = json::inflate( "{ \"a\" : [ 1, 2, 3 ], \"b\" : { \"c\" : true } }" );
REQUIRE( obj.type() == any::type_t::object );
REQUIRE( obj.is_member( "a" ) );
REQUIRE( obj[ "a" ].is_array() );
REQUIRE( obj[ "a" ].size() == 3 );
REQUIRE( obj.is_member( "b" ) );
REQUIRE( obj[ "b" ].is_object() );
REQUIRE( obj[ "b" ].size() == 1 );
REQUIRE( obj[ "b" ][ "c" ] == true );
}
SUBCASE( "deflate" )
{
auto obj = any::build(
{
{ "a", { 1, 2, 3 } },
{ "b", { { "c", true } } },
{ "c", "\b\f\n\r\t\"\\embedded" }
} );
REQUIRE( obj.type() == any::type_t::object );
REQUIRE( obj.is_member( "a" ) );
REQUIRE( obj[ "a" ].is_array() );
REQUIRE( obj[ "a" ].size() == 3 );
REQUIRE( obj.is_member( "b" ) );
REQUIRE( obj[ "b" ].is_object() );
REQUIRE( obj[ "b" ].size() == 1 );
REQUIRE( obj[ "b" ][ "c" ] == true );
REQUIRE( obj[ "c" ].is_string() );
REQUIRE( obj[ "c" ].to_string() == "\b\f\n\r\t\"\\embedded" );
{
std::ostringstream os;
auto str = json::deflate_to_stream( os, obj ).str();
REQUIRE( str.size() > 0 );
auto obj2 = json::inflate( str );
REQUIRE( obj == obj2 );
}
{
ostringstream os;
auto str = json::deflate_to_stream( os, obj ).str();
REQUIRE( str.size() > 0 );
auto obj2 = json::inflate( str );
REQUIRE( obj == obj2 );
}
}
}
| 23.919355 | 82 | 0.506406 | [
"object"
] |
b833c1716e5d27fbec1554231784f98a14b38987 | 3,194 | cpp | C++ | software/control/src/RobotStateDriver.cpp | liangfok/oh-distro | eeee1d832164adce667e56667dafc64a8d7b8cee | [
"BSD-3-Clause"
] | 92 | 2016-01-14T21:03:50.000Z | 2021-12-01T17:57:46.000Z | software/control/src/RobotStateDriver.cpp | liangfok/oh-distro | eeee1d832164adce667e56667dafc64a8d7b8cee | [
"BSD-3-Clause"
] | 62 | 2016-01-16T18:08:14.000Z | 2016-03-24T15:16:28.000Z | software/control/src/RobotStateDriver.cpp | liangfok/oh-distro | eeee1d832164adce667e56667dafc64a8d7b8cee | [
"BSD-3-Clause"
] | 41 | 2016-01-14T21:26:58.000Z | 2022-03-28T03:10:39.000Z | #include <stdexcept>
#include "RobotStateDriver.hpp"
#include "drake/util/drakeGeometryUtil.h"
using namespace std;
using namespace Eigen;
RobotStateDriver::RobotStateDriver(vector<string> state_coordinate_names) {
m_num_joints = 0;
m_num_floating_joints = 0;
string prefix("base_");
for (int i=0; i<state_coordinate_names.size(); i++) {
if (state_coordinate_names[i].compare(0, prefix.size(), prefix) == 0) {
m_floating_joint_map[state_coordinate_names[i]] = i;
m_num_floating_joints++;
}
else {
m_joint_map[state_coordinate_names[i]] = i;
m_num_joints++;
}
}
// this class is assuming an RPY floating base, not quaternion, so let's verify that's what we've got
map<string,int>::iterator it = m_floating_joint_map.find("base_roll");
if (it == m_floating_joint_map.end()) {
throw std::runtime_error("This method has not yet been updated to support quaternion floating base. It's assuming roll, pitch, yaw for floating base pose, but I couldn't find a 'base_roll' coordinate. \n");
}
}
void RobotStateDriver::decode(const bot_core::robot_state_t *msg, DrakeRobotState *state) {
state->t = ((double) msg->utime) / 1000000;
for (int i=0; i < msg->num_joints; i++) {
map<string,int>::iterator it = m_joint_map.find(msg->joint_name[i]);
if (it!=m_joint_map.end()) {
int index = it->second;
state->q(index) = msg->joint_position[i];
state->qd(index) = msg->joint_velocity[i];
}
}
map<string,int>::iterator it;
it = m_floating_joint_map.find("base_x");
if (it!=m_floating_joint_map.end()) {
int index = it->second;
state->q(index) = msg->pose.translation.x;
state->qd(index) = msg->twist.linear_velocity.x;
}
it = m_floating_joint_map.find("base_y");
if (it!=m_floating_joint_map.end()) {
int index = it->second;
state->q(index) = msg->pose.translation.y;
state->qd(index) = msg->twist.linear_velocity.y;
}
it = m_floating_joint_map.find("base_z");
if (it!=m_floating_joint_map.end()) {
int index = it->second;
state->q(index) = msg->pose.translation.z;
state->qd(index) = msg->twist.linear_velocity.z;
}
Vector4d q;
q(0) = msg->pose.rotation.w;
q(1) = msg->pose.rotation.x;
q(2) = msg->pose.rotation.y;
q(3) = msg->pose.rotation.z;
Vector3d rpy = quat2rpy(q);
Vector3d omega;
omega(0) = msg->twist.angular_velocity.x;
omega(1) = msg->twist.angular_velocity.y;
omega(2) = msg->twist.angular_velocity.z;
Matrix3d phi = Matrix3d::Zero();
angularvel2rpydotMatrix(rpy, phi, (MatrixXd*) nullptr, (MatrixXd*) nullptr);
Vector3d rpydot = phi * omega;
it = m_floating_joint_map.find("base_roll");
if (it!=m_floating_joint_map.end()) {
int index = it->second;
state->q(index) = rpy[0];
state->qd(index) = rpydot[0];
}
it = m_floating_joint_map.find("base_pitch");
if (it!=m_floating_joint_map.end()) {
int index = it->second;
state->q(index) = rpy[1];
state->qd(index) = rpydot[1];
}
it = m_floating_joint_map.find("base_yaw");
if (it!=m_floating_joint_map.end()) {
int index = it->second;
state->q(index) = rpy[2];
state->qd(index) = rpydot[2];
}
return;
}
| 31.313725 | 210 | 0.663118 | [
"vector"
] |
b8354841f820342f17ead4fb815a76eeb2369ffc | 16,950 | cpp | C++ | printscan/wia/test/wialogcfg/wialogcfgdlg.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | printscan/wia/test/wialogcfg/wialogcfgdlg.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | printscan/wia/test/wialogcfg/wialogcfgdlg.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | // WiaLogCFGDlg.cpp : implementation file
//
#include "stdafx.h"
#include "WiaLogCFG.h"
#include "WiaLogCFGDlg.h"
#include "AddRemove.h"
#include "LogViewer.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CWiaLogCFGDlg dialog
CWiaLogCFGDlg::CWiaLogCFGDlg(CWnd* pParent /*=NULL*/)
: CDialog(CWiaLogCFGDlg::IDD, pParent)
{
//{{AFX_DATA_INIT(CWiaLogCFGDlg)
m_dwCustomLevel = 0;
//}}AFX_DATA_INIT
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
m_bColorCodeLogViewerText = FALSE;
}
void CWiaLogCFGDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CWiaLogCFGDlg)
DDX_Control(pDX, IDC_COLOR_CODE_LOGVIEWER_TEXT, m_ColorCodeLogViewerTextCheckBox);
DDX_Control(pDX, IDC_LOG_TO_DEBUGGER, m_LogToDebuggerCheckBox);
DDX_Control(pDX, IDC_CLEARLOG_ON_BOOT, m_ClearLogOnBootCheckBox);
DDX_Control(pDX, IDC_PARSE_PROGRESS, m_ProgressCtrl);
DDX_Control(pDX, IDC_ADD_TIME, m_AddTimeCheckBox);
DDX_Control(pDX, IDC_ADD_THREADID, m_AddThreadIDCheckBox);
DDX_Control(pDX, IDC_ADD_MODULENAME, m_AddModuleCheckBox);
DDX_Control(pDX, IDC_TRUNCATE_ON_BOOT, m_TruncateOnBootCheckBox);
DDX_Control(pDX, IDC_SELECT_MODULE_COMBOBOX, m_ModuleComboBox);
DDX_Control(pDX, IDC_LOG_LEVEL_WARNING, m_WarningCheckBox);
DDX_Control(pDX, IDC_LOG_LEVEL_ERROR, m_ErrorCheckBox);
DDX_Control(pDX, IDC_LOG_LEVEL_TRACE, m_TraceCheckBox);
DDX_Control(pDX, IDC_FILTER_OFF, m_FilterOff);
DDX_Control(pDX, IDC_FILTER_1, m_Filter1);
DDX_Control(pDX, IDC_FILTER_2, m_Filter2);
DDX_Control(pDX, IDC_FILTER_3, m_Filter3);
DDX_Control(pDX, IDC_FILTER_CUSTOM, m_FilterCustom);
DDX_Text(pDX, IDC_EDIT_CUSTOM_LEVEL, m_dwCustomLevel);
DDV_MinMaxDWord(pDX, m_dwCustomLevel, 0, 9999);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CWiaLogCFGDlg, CDialog)
//{{AFX_MSG_MAP(CWiaLogCFGDlg)
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_BN_CLICKED(IDC_ADD_MODULE_BUTTON, OnAddModuleButton)
ON_BN_CLICKED(IDC_DELETE_MODULE_BUTTON, OnDeleteModuleButton)
ON_BN_CLICKED(IDC_WRITE_SETTINGS_BUTTON, OnWriteSettingsButton)
ON_CBN_SELCHANGE(IDC_SELECT_MODULE_COMBOBOX, OnSelchangeSelectModuleCombobox)
ON_BN_CLICKED(IDC_CLEARLOG_BUTTON, OnClearlogButton)
ON_BN_CLICKED(IDC_VIEW_LOG_BUTTON, OnViewLogButton)
ON_CBN_SETFOCUS(IDC_SELECT_MODULE_COMBOBOX, OnSetfocusSelectModuleCombobox)
ON_CBN_DROPDOWN(IDC_SELECT_MODULE_COMBOBOX, OnDropdownSelectModuleCombobox)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CWiaLogCFGDlg message handlers
BOOL CWiaLogCFGDlg::OnInitDialog()
{
m_hInstance = NULL;
m_hInstance = AfxGetInstanceHandle();
CDialog::OnInitDialog();
ShowProgress(FALSE);
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
m_LogInfo.dwLevel = 0;
m_LogInfo.dwMaxSize = 100000;
m_LogInfo.dwMode = 0;
m_LogInfo.dwTruncateOnBoot = 0;
memset(m_LogInfo.szKeyName,0,sizeof(m_LogInfo.szKeyName));
m_CurrentSelection = 0;
InitializeDialogSettings(SETTINGS_RESET_DIALOG);
RegistryOperation(REG_READ);
InitializeDialogSettings(SETTINGS_TO_DIALOG);
CheckGlobalServiceSettings();
return TRUE; // return TRUE unless you set the focus to a control
}
// If you add a minimize button to your dialog, you will need the code below
// to draw the icon. For MFC applications using the document/view model,
// this is automatically done for you by the framework.
void CWiaLogCFGDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // device context for painting
SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);
// Center icon in client rectangle
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// Draw the icon
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialog::OnPaint();
}
}
HCURSOR CWiaLogCFGDlg::OnQueryDragIcon()
{
return (HCURSOR) m_hIcon;
}
void CWiaLogCFGDlg::OnAddModuleButton()
{
CAddRemove AddRemoveDlg;
AddRemoveDlg.SetTitle(TEXT("Add a Module"));
AddRemoveDlg.SetStatusText(TEXT("Enter a Module Name:"));
if(AddRemoveDlg.DoModal() == IDOK) {
m_TruncateOnBootCheckBox.SetCheck(0);
m_ClearLogOnBootCheckBox.SetCheck(0);
AddRemoveDlg.GetNewKeyName(m_LogInfo.szKeyName);
RegistryOperation(REG_ADD_KEY);
RegistryOperation(REG_READ);
CheckGlobalServiceSettings();
}
}
void CWiaLogCFGDlg::OnDeleteModuleButton()
{
if(MessageBox(TEXT("Are you sure you want to DELETE this module?"),
TEXT("Delete Module"),
MB_YESNO|MB_ICONQUESTION) == IDYES) {
//
// Delete this module
//
RegistryOperation(REG_DELETE_KEY);
RegistryOperation(REG_READ);
}
}
void CWiaLogCFGDlg::RegistryOperation(ULONG ulFlags)
{
TCHAR szAppRegistryKey[MAX_PATH];
TCHAR szValueName[MAX_PATH];
LoadString(m_hInstance, REGSTR_PATH_STICONTROL, szAppRegistryKey, MAX_PATH);
CRegistry Registry(szAppRegistryKey,HKEY_LOCAL_MACHINE);
//
// move to logging
//
LoadString(m_hInstance,REGSTR_VAL_LOGGING , szValueName, MAX_PATH);
Registry.MoveToSubKey(szValueName);
if(ulFlags == REG_ADD_KEY) {
//
// Add a new key
//
Registry.CreateKey(m_LogInfo.szKeyName);
//
// change current selection to an invalid selection
//
m_CurrentSelection = -99;
return;
}
if( ulFlags == REG_DELETE_KEY) {
//
// delete a Key
//
Registry.DeleteKey(m_LogInfo.szKeyName);
return;
}
//
// enumerate keys
//
DWORD dwIndex = 0;
TCHAR pszKeyName[64];
m_ModuleComboBox.ResetContent();
while(Registry.EnumerateKeys(dwIndex++,pszKeyName, sizeof(pszKeyName)) != ERROR_NO_MORE_ITEMS) {
m_ModuleComboBox.AddString(pszKeyName);
}
if(m_CurrentSelection == -99){
INT nIndex = m_ModuleComboBox.FindString(-1, m_LogInfo.szKeyName);
m_CurrentSelection = nIndex;
m_ModuleComboBox.SetCurSel(nIndex);
} else {
m_ModuleComboBox.GetLBText(m_CurrentSelection,m_LogInfo.szKeyName);
}
m_ModuleComboBox.SetCurSel(m_CurrentSelection);
//
// move to DLL specifc subkey
//
Registry.MoveToSubKey(m_LogInfo.szKeyName);
switch(ulFlags) {
case REG_WRITE:
LoadString(m_hInstance,REGSTR_VAL_LOG_LEVEL , szValueName, MAX_PATH);
Registry.SetValue(szValueName,m_LogInfo.dwLevel);
LoadString(m_hInstance,REGSTR_VAL_MODE , szValueName, MAX_PATH);
Registry.SetValue(szValueName,m_LogInfo.dwMode);
LoadString(m_hInstance,REGSTR_VAL_MAXSIZE , szValueName, MAX_PATH);
Registry.SetValue(szValueName,m_LogInfo.dwMaxSize);
LoadString(m_hInstance,REGSTR_VAL_TRUNCATE_ON_BOOT , szValueName, MAX_PATH);
Registry.SetValue(szValueName,m_LogInfo.dwTruncateOnBoot);
LoadString(m_hInstance,REGSTR_VAL_CLEARLOG_ON_BOOT , szValueName, MAX_PATH);
Registry.SetValue(szValueName,m_LogInfo.dwClearLogOnBoot);
LoadString(m_hInstance,REGSTR_VAL_DETAIL , szValueName, MAX_PATH);
Registry.SetValue(szValueName,m_LogInfo.dwDetail);
LoadString(m_hInstance,REGSTR_VAL_LOG_TO_DEBUGGER, szValueName, MAX_PATH);
Registry.SetValue(szValueName,m_LogInfo.dwLogToDebugger);
break;
case REG_READ:
default:
LoadString(m_hInstance,REGSTR_VAL_LOG_LEVEL , szValueName, MAX_PATH);
m_LogInfo.dwLevel = Registry.GetValue(szValueName,WIALOG_NO_LEVEL);
LoadString(m_hInstance,REGSTR_VAL_MODE , szValueName, MAX_PATH);
m_LogInfo.dwMode = Registry.GetValue(szValueName,WIALOG_ADD_MODULE|WIALOG_ADD_THREAD);
LoadString(m_hInstance,REGSTR_VAL_MAXSIZE , szValueName, MAX_PATH);
m_LogInfo.dwMaxSize = Registry.GetValue(szValueName,100000);
LoadString(m_hInstance,REGSTR_VAL_TRUNCATE_ON_BOOT, szValueName, MAX_PATH);
m_LogInfo.dwTruncateOnBoot = Registry.GetValue(szValueName,0);
LoadString(m_hInstance,REGSTR_VAL_CLEARLOG_ON_BOOT, szValueName, MAX_PATH);
m_LogInfo.dwClearLogOnBoot = Registry.GetValue(szValueName,0);
LoadString(m_hInstance,REGSTR_VAL_DETAIL , szValueName, MAX_PATH);
m_LogInfo.dwDetail = Registry.GetValue(szValueName,0);
LoadString(m_hInstance,REGSTR_VAL_LOG_TO_DEBUGGER, szValueName, MAX_PATH);
m_LogInfo.dwLogToDebugger = Registry.GetValue(szValueName,0);
break;
}
}
void CWiaLogCFGDlg::InitializeDialogSettings(ULONG ulFlags)
{
switch (ulFlags) {
case SETTINGS_TO_DIALOG:
//
// set level of detail
//
switch (m_LogInfo.dwDetail) {
case WIALOG_NO_LEVEL:
m_FilterOff.SetCheck(1);
break;
case WIALOG_LEVEL1 :
m_Filter1.SetCheck(1);
break;
case WIALOG_LEVEL2:
m_Filter2.SetCheck(1);
break;
case WIALOG_LEVEL3:
m_Filter3.SetCheck(1);
break;
default:
m_FilterCustom.SetCheck(1);
m_dwCustomLevel = m_LogInfo.dwDetail;
UpdateData(FALSE);
break;
}
//
// set truncate on boot check box
//
if (m_LogInfo.dwTruncateOnBoot != 0)
m_TruncateOnBootCheckBox.SetCheck(1);
else
m_TruncateOnBootCheckBox.SetCheck(0);
//
// set clear log on boot check box
//
if (m_LogInfo.dwClearLogOnBoot != 0)
m_ClearLogOnBootCheckBox.SetCheck(1);
else
m_ClearLogOnBootCheckBox.SetCheck(0);
//
// set log to debugger check box
//
if (m_LogInfo.dwLogToDebugger != 0)
m_LogToDebuggerCheckBox.SetCheck(1);
else
m_LogToDebuggerCheckBox.SetCheck(0);
//
// set trace level check boxes
//
if (m_LogInfo.dwLevel & WIALOG_TRACE)
m_TraceCheckBox.SetCheck(1);
if (m_LogInfo.dwLevel & WIALOG_ERROR)
m_ErrorCheckBox.SetCheck(1);
if (m_LogInfo.dwLevel & WIALOG_WARNING)
m_WarningCheckBox.SetCheck(1);
//
// set additional details check boxes
//
if (m_LogInfo.dwMode & WIALOG_ADD_TIME)
m_AddTimeCheckBox.SetCheck(1);
if (m_LogInfo.dwMode & WIALOG_ADD_MODULE)
m_AddModuleCheckBox.SetCheck(1);
if (m_LogInfo.dwMode & WIALOG_ADD_THREAD)
m_AddThreadIDCheckBox.SetCheck(1);
break;
case SETTINGS_FROM_DIALOG:
//
// get level of detail
//
if (m_FilterOff.GetCheck() == 1)
m_LogInfo.dwDetail = WIALOG_NO_LEVEL;
if (m_Filter1.GetCheck() == 1)
m_LogInfo.dwDetail = WIALOG_LEVEL1;
if (m_Filter2.GetCheck() == 1)
m_LogInfo.dwDetail = WIALOG_LEVEL2;
if (m_Filter3.GetCheck() == 1)
m_LogInfo.dwDetail = WIALOG_LEVEL3;
if (m_FilterCustom.GetCheck() == 1) {
UpdateData(TRUE);
m_LogInfo.dwDetail = m_dwCustomLevel;
}
//
// get truncate on boot check box
//
if (m_TruncateOnBootCheckBox.GetCheck() == 1)
m_LogInfo.dwTruncateOnBoot = 1;
else
m_LogInfo.dwTruncateOnBoot = 0;
//
// get clear log on boot check box
//
if (m_ClearLogOnBootCheckBox.GetCheck() == 1)
m_LogInfo.dwClearLogOnBoot = 1;
else
m_LogInfo.dwClearLogOnBoot = 0;
//
// get log to debugger check box
//
if(m_LogToDebuggerCheckBox.GetCheck() == 1)
m_LogInfo.dwLogToDebugger = 1;
else
m_LogInfo.dwLogToDebugger = 0;
//
// get trace level check boxes
//
m_LogInfo.dwLevel = 0;
if (m_TraceCheckBox.GetCheck() == 1)
m_LogInfo.dwLevel = m_LogInfo.dwLevel | WIALOG_TRACE;
if (m_ErrorCheckBox.GetCheck() == 1)
m_LogInfo.dwLevel = m_LogInfo.dwLevel | WIALOG_ERROR;
if (m_WarningCheckBox.GetCheck() == 1)
m_LogInfo.dwLevel = m_LogInfo.dwLevel | WIALOG_WARNING;
//
// set additional details check boxes
//
m_LogInfo.dwMode = 0;
if (m_AddTimeCheckBox.GetCheck() == 1)
m_LogInfo.dwMode = m_LogInfo.dwMode | WIALOG_ADD_TIME;
if (m_AddModuleCheckBox.GetCheck() == 1)
m_LogInfo.dwMode = m_LogInfo.dwMode | WIALOG_ADD_MODULE;
if (m_AddThreadIDCheckBox.GetCheck() == 1)
m_LogInfo.dwMode = m_LogInfo.dwMode | WIALOG_ADD_THREAD;
break;
default:
m_FilterOff.SetCheck(0);
m_Filter1.SetCheck(0);
m_Filter2.SetCheck(0);
m_Filter3.SetCheck(0);
m_FilterCustom.SetCheck(0);
m_TruncateOnBootCheckBox.SetCheck(0);
m_TraceCheckBox.SetCheck(0);
m_ErrorCheckBox.SetCheck(0);
m_WarningCheckBox.SetCheck(0);
m_AddTimeCheckBox.SetCheck(0);
m_AddModuleCheckBox.SetCheck(0);
m_AddThreadIDCheckBox.SetCheck(0);
m_dwCustomLevel = 0;
UpdateData(FALSE);
break;
}
}
void CWiaLogCFGDlg::OnOK()
{
InitializeDialogSettings(SETTINGS_FROM_DIALOG);
RegistryOperation(REG_WRITE);
CDialog::OnOK();
}
void CWiaLogCFGDlg::OnWriteSettingsButton()
{
InitializeDialogSettings(SETTINGS_FROM_DIALOG);
RegistryOperation(REG_WRITE);
}
void CWiaLogCFGDlg::OnSelchangeSelectModuleCombobox()
{
m_CurrentSelection = m_ModuleComboBox.GetCurSel();
if(m_CurrentSelection < 0)
return;
CheckGlobalServiceSettings();
InitializeDialogSettings(SETTINGS_RESET_DIALOG);
RegistryOperation(REG_READ);
InitializeDialogSettings(SETTINGS_TO_DIALOG);
}
void CWiaLogCFGDlg::OnClearlogButton()
{
//
// Get Windows Directory
//
TCHAR szLogFilePath[MAX_PATH];
DWORD dwLength = 0;
dwLength = ::GetWindowsDirectory(szLogFilePath,sizeof(szLogFilePath));
if (( dwLength == 0) || !*szLogFilePath ) {
OutputDebugString(TEXT("Could not GetWindowsDirectory()"));
return;
}
//
// Add log file name to Windows Directory
//
lstrcat(lstrcat(szLogFilePath,TEXT("\\")),TEXT("wiaservc.log"));
//
// Create / open Log file
//
HANDLE hLogFile = ::CreateFile(szLogFilePath,
GENERIC_WRITE,
FILE_SHARE_WRITE | FILE_SHARE_READ,
NULL, // security attributes
CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
NULL); // template file handle
if(hLogFile != NULL)
CloseHandle(hLogFile);
}
void CWiaLogCFGDlg::OnViewLogButton()
{
CLogViewer LogViewer;
if (m_ColorCodeLogViewerTextCheckBox.GetCheck() == 1)
m_bColorCodeLogViewerText = TRUE;
else
m_bColorCodeLogViewerText = FALSE;
LogViewer.ColorizeText(m_bColorCodeLogViewerText);
//
// initialize progress
//
m_ProgCtrl.SetControl(&m_ProgressCtrl);
LogViewer.SetProgressCtrl(&m_ProgCtrl);
ShowProgress(TRUE);
LogViewer.DoModal();
ShowProgress(FALSE);
}
void CWiaLogCFGDlg::ShowProgress(BOOL bShow)
{
if(bShow) {
m_ProgressCtrl.ShowWindow(SW_SHOW);
} else {
m_ProgressCtrl.ShowWindow(SW_HIDE);
}
}
void CWiaLogCFGDlg::OnSetfocusSelectModuleCombobox()
{
OnWriteSettingsButton();
}
void CWiaLogCFGDlg::OnDropdownSelectModuleCombobox()
{
OnWriteSettingsButton();
}
void CWiaLogCFGDlg::CheckGlobalServiceSettings()
{
TCHAR szKeyName[MAX_PATH];
m_ModuleComboBox.GetLBText(m_CurrentSelection,szKeyName);
if(lstrcmp(szKeyName,TEXT("WIASERVC")) == 0) {
m_TruncateOnBootCheckBox.EnableWindow(TRUE);
m_ClearLogOnBootCheckBox.EnableWindow(TRUE);
} else {
m_TruncateOnBootCheckBox.EnableWindow(FALSE);
m_ClearLogOnBootCheckBox.EnableWindow(FALSE);
}
}
| 29.274611 | 101 | 0.639941 | [
"model"
] |
b8366d3fff6a299b77f4224a902f30f72feb2a5a | 5,044 | cpp | C++ | cpp/icub/IKD/example.cpp | BrunoDaCosta/NL_limit_cycles | 62c8c93d8ca9d6c7442154c467cd0f9e27329871 | [
"RSA-MD"
] | 2 | 2019-07-26T08:51:15.000Z | 2020-10-16T09:52:58.000Z | cpp/icub/IKD/example.cpp | BrunoDaCosta/NL_limit_cycles | 62c8c93d8ca9d6c7442154c467cd0f9e27329871 | [
"RSA-MD"
] | null | null | null | cpp/icub/IKD/example.cpp | BrunoDaCosta/NL_limit_cycles | 62c8c93d8ca9d6c7442154c467cd0f9e27329871 | [
"RSA-MD"
] | 1 | 2021-01-26T14:34:05.000Z | 2021-01-26T14:34:05.000Z | #include "IK.h"
#include "ID.h"
using namespace std;
/* Index reference and a natural posture of icub */
/* global positions */
/* pelvis pos: pos[0] pos[1] pos[2] */
/* pelvis rot: pos[3] pos[4] pos[5] pos[38] */
/* // right // left */
/* head pos[11] */
/* neck roll pos[10] */
/* neck pitch pos[9] */
/* shoulder pitch pos[31] pos[24] */
/* shoulder roll pos[32] pos[25] */
/* shoulder yaw pos[33] pos[26] */
/* elbow pos[34] pos[27] */
/* forearm yaw pos[35] pos[28] */
/* forearm roll pos[36] pos[29] */
/* forearm pitch pos[37] pos[30] */
/* torso pitch pos[6] */
/* torso roll pos[7] */
/* torso yaw pos[8] */
/* hip pitch pos[18] pos[12] */
/* hip roll pos[19] pos[13] */
/* hip yaw pos[20] pos[14] */
/* knee pos[21] pos[15] */
/* ankle pitch pos[22] pos[16] */
/* ankle roll pos[23] pos[17] */
int main()
{
// ****** Note that stages are linked together ****
//definitions
Model model;
model.init();
// contact definition
Contact_Manager points;
points.initialize(&model, 5);
points[CN_CM].init(CN_CM, body_base, offset_base, CT_FULL, PS_FLOATING, 0 , 0 );
points[CN_LF].init(CN_LF, body_l_foot, offset_l_foot, CT_FULL, PS_CONTACTED, foot_length*0.8, foot_width*0.8);
points[CN_RF].init(CN_RF, body_r_foot, offset_r_foot, CT_FULL, PS_CONTACTED, foot_length*0.8, foot_width*0.8);
points[CN_LH].init(CN_LH, body_l_hand, offset_l_hand, CT_FULL, PS_FLOATING, hand_length*0.8, hand_width*0.8);
points[CN_RH].init(CN_RH, body_r_hand, offset_r_hand, CT_FULL, PS_FLOATING, hand_length*0.8, hand_width*0.8);
// control CoM instead of pelvis
points.ifCoM = true;
// task flexibility
points[CN_CM].T.slack_cost = Cvector3(1,1,1) * 100;
points[CN_CM].R.slack_cost = Cvector3(1,1,1) * 1;
points[CN_LF].T.slack_cost = Cvector3(1,1,1) * 100;
points[CN_LF].R.slack_cost = Cvector3(1,1,1) * 100;
points[CN_RF].T.slack_cost = Cvector3(1,1,1) * 100;
points[CN_RF].R.slack_cost = Cvector3(1,1,1) * 100;
points[CN_LH].R.slack_cost = Cvector3(1,1,1) * 1;
points[CN_LH].T.slack_cost = Cvector3(1,1,1) * 1;
points[CN_RH].R.slack_cost = Cvector3(1,1,1) * 1;
points[CN_RH].T.slack_cost = Cvector3(1,1,1) * 1;
// joints variables
Cvector ref_pos = Cvector::Zero(AIR_N_U+1); ref_pos[AIR_N_U] = 1;
Cvector freeze = Cvector::Zero(AIR_N_U);
Cvector ref_vel = Cvector::Zero(AIR_N_U);
Cvector ref_acc = Cvector::Zero(AIR_N_U);
Cvector ref_tau = Cvector::Zero(AIR_N_U);
// fixed joints
for(int i=6;i<=11;i++)
freeze[i] = 1;
// position tasks
points[CN_CM].ref_p.pos = Cvector3(0, 0, 0.55);
points[CN_LF].ref_p.pos = Cvector3(0, 0.075,0);
points[CN_RF].ref_p.pos = Cvector3(0, -0.075,0);
points[CN_LH].ref_p.pos = Cvector3(0.2, 0.2,0.5);
points[CN_RH].ref_p.pos = Cvector3(0.2,-0.2,0.5);
// orientation tasks
points[CN_CM].ref_o.pos = zero_quat;
points[CN_LF].ref_o.pos = zero_quat;
points[CN_RF].ref_o.pos = zero_quat;
points[CN_LH].ref_o.pos = ang2quat(Cvector3(0,-M_PI/2,0));
points[CN_RH].ref_o.pos = ang2quat(Cvector3(0,-M_PI/2,0));
// solving IK problem
IKPARAM ikparam;
double IK_time = IK(points, ikparam, ref_pos, freeze);
// model update
model.set_state(0, ref_pos, ref_vel);
points.update_kinematics();
// dynamic limits
Cvector Qacc = Cvector::Ones(AIR_N_U) * 1e-3;
Cvector Qtau = Cvector::Ones(AIR_N_U)/30.0/30.0 * 1e-8;
// solving ID problem
IDPARAM idparam;
double ID_time = ID(points, idparam, Qacc, Qtau, ref_tau, ref_acc, freeze, Cvector::Zero(AIR_N_U));
model.set_acc(ref_acc);
points.update_dynamics();
// plot all joint variables
points.print_IK_errors();
points.print_ID_errors();
cout << setprecision( 3 ) << "IK time: " << IK_time << " --- ID time: " << ID_time << endl;
cout << fixed << endl;
cout << " joint min_pos pos max_pos vel acc torque " << endl;
for(int i=0;i<AIR_N_U;i++)
cout << std::setw( 5 ) << i << ":" <<
setprecision( 0 ) <<std::setw( 11 ) << (i<6 ? -1000 : model.qmin[i-6]) <<
setprecision( 2 ) <<std::setw( 11 ) << ref_pos[i] * (i>=6?180/M_PI:1) <<
setprecision( 0 ) <<std::setw( 11 ) << (i<6 ? -1000 : model.qmax[i-6]) <<
setprecision( 2 ) <<std::setw( 11 ) << ref_vel[i] <<
setprecision( 2 ) <<std::setw( 11 ) << ref_acc[i] <<
setprecision( 2 ) <<std::setw( 11 ) << ref_tau[i] <<
endl;
return 0;
}
| 41.00813 | 111 | 0.548771 | [
"model"
] |
b83757bcad87216a5b3bbc3895680eb75a3a669c | 4,534 | cpp | C++ | scipy/optimize/_highs/src/simplex/HVector.cpp | Ennosigaeon/scipy | 2d872f7cf2098031b9be863ec25e366a550b229c | [
"BSD-3-Clause"
] | 3 | 2021-12-15T10:06:16.000Z | 2022-02-08T19:55:58.000Z | scipy/optimize/_highs/src/simplex/HVector.cpp | Ennosigaeon/scipy | 2d872f7cf2098031b9be863ec25e366a550b229c | [
"BSD-3-Clause"
] | 44 | 2019-06-27T15:56:14.000Z | 2022-03-15T22:21:10.000Z | scipy/optimize/_highs/src/simplex/HVector.cpp | Ennosigaeon/scipy | 2d872f7cf2098031b9be863ec25e366a550b229c | [
"BSD-3-Clause"
] | 4 | 2019-07-25T01:57:45.000Z | 2021-04-29T06:54:23.000Z | /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* */
/* This file is part of the HiGHS linear optimization suite */
/* */
/* Written and engineered 2008-2020 at the University of Edinburgh */
/* */
/* Available as open-source under the MIT License */
/* */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/**@file simplex/HVector.cpp
* @brief
* @author Julian Hall, Ivet Galabova, Qi Huangfu and Michael Feldmeier
*/
#include "simplex/HVector.h"
#include <cassert>
#include <cmath>
#include "lp_data/HConst.h"
#include "stdio.h" //Just for temporary printf
void HVector::setup(int size_) {
/*
* Initialise an HVector instance
*/
size = size_;
count = 0;
index.resize(size);
array.assign(size, 0);
cwork.assign(size + 6400, 0); // MAX invert
iwork.assign(size * 4, 0);
packCount = 0;
packIndex.resize(size);
packValue.resize(size);
// Initialise three values that are initialised in clear(), but
// weren't originally initialised in setup(). Probably doesn't
// matter, since clear() is usually called before a vector is
// (re-)used.
packFlag = false;
syntheticTick = 0;
next = 0;
}
void HVector::clear() {
/*
* Clear an HVector instance
*/
// Standard HVector to clear
int clearVector_inDense = count < 0 || count > size * 0.3;
if (clearVector_inDense) {
// Treat the array as full if there are no indices or too many indices
array.assign(size, 0);
} else {
// Zero according to the indices of (possible) nonzeros
for (int i = 0; i < count; i++) {
array[index[i]] = 0;
}
}
// Reset the flag to indicate when to pack
packFlag = false;
// Zero the number of stored indices
count = 0;
// Zero the synthetic clock for operations with this vector
syntheticTick = 0;
// Initialise the next value
next = 0;
}
void HVector::tight() {
/*
* Packing: Zero values in Vector.array which exceed HIGHS_CONST_TINY in
* magnitude
*/
int totalCount = 0;
for (int i = 0; i < count; i++) {
const int my_index = index[i];
const double value = array[my_index];
if (fabs(value) > HIGHS_CONST_TINY) {
index[totalCount++] = my_index;
} else {
array[my_index] = 0;
}
}
count = totalCount;
}
void HVector::pack() {
/*
* Packing (if packFlag set): Pack values/indices in Vector.array
* into packValue/Index
*/
if (packFlag) {
packFlag = false;
packCount = 0;
for (int i = 0; i < count; i++) {
const int ipack = index[i];
packIndex[packCount] = ipack;
packValue[packCount] = array[ipack];
packCount++;
}
}
}
void HVector::copy(const HVector* from) {
/*
* Copy from another HVector structure to this instance
*/
clear();
syntheticTick = from->syntheticTick;
const int fromCount = count = from->count;
const int* fromIndex = &from->index[0];
const double* fromArray = &from->array[0];
for (int i = 0; i < fromCount; i++) {
const int iFrom = fromIndex[i];
const double xFrom = fromArray[iFrom];
index[i] = iFrom;
array[iFrom] = xFrom;
}
}
double HVector::norm2() {
/*
* Compute the squared 2-norm of the vector
*/
const int workCount = count;
const int* workIndex = &index[0];
const double* workArray = &array[0];
double result = 0;
for (int i = 0; i < workCount; i++) {
double value = workArray[workIndex[i]];
result += value * value;
}
return result;
}
void HVector::saxpy(const double pivotX, const HVector* pivot) {
/*
* Add a multiple pivotX of *pivot into this vector, maintaining
* indices of nonzeros but not tracking cancellation
*/
int workCount = count;
int* workIndex = &index[0];
double* workArray = &array[0];
const int pivotCount = pivot->count;
const int* pivotIndex = &pivot->index[0];
const double* pivotArray = &pivot->array[0];
for (int k = 0; k < pivotCount; k++) {
const int iRow = pivotIndex[k];
const double x0 = workArray[iRow];
const double x1 = x0 + pivotX * pivotArray[iRow];
if (x0 == 0) workIndex[workCount++] = iRow;
workArray[iRow] = (fabs(x1) < HIGHS_CONST_TINY) ? HIGHS_CONST_ZERO : x1;
}
count = workCount;
}
| 28.161491 | 76 | 0.569475 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.