text
stringlengths 5
1.04M
|
|---|
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define ull unsigned long long
#define dd double
#define ld long double
#define sl(n) scanf("%lld", &n)
#define si(n) scanf("%d", &n)
#define sd(n) scanf("%lf", &n)
#define pll pair <ll, ll>
#define pii pair <int, int>
#define mp make_pair
#define pb push_back
#define inf (1LL << 62)
#define loop(i, start, stop, inc) for(ll i = start; i <= stop; i += inc)
#define forn(i, stop) for(ll i = 1; i <= stop; i++)
#define rep(i, start) for(ll i = start; i >= 1; i--)
#define ms(n, i) memset(n, i, sizeof(n))
#define casep(n) printf("Case %lld:", ++n)
#define pn printf("\n")
#define pf printf
#define fastio std::ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
ll a[100009];
ll b[100009], red[100009], bl[100009];
unordered_map <ll, ll> check;
int main()
{
ll t;
sl(t);
while(t--) {
ll n;
sl(n);
forn(i, n) {
sl(a[i]);
red[i] = bl[i] = 0;
}
forn(i, n) {
sl(b[i]);
if(b[i] == 1)
red[i] = 1;
else
bl[i] = 1;
}
ll ans = 2*n;
check[red[n] - bl[n]] = n;
rep(i, (n-1)) {
red[i] += red[i+1];
bl[i] += bl[i+1];
ll diff = red[i] - bl[i];
check[diff] = i;
if(diff == 0)
ans = min(ans, n + i - 1);
}
ll rd = 0, be = 0;
if(red[1] == bl[1]) ans = n;
forn(i, n) {
if(a[i] == 1)
rd++;
else
be++;
ll diff = rd - be;
//cout << i << " " << diff << endl;
if(diff == 0)
ans = min(ans, (n - i) + n);
if(check.find(-diff) != check.end()) {
ll bad = check[-diff] - 1 + (n - i);
ans = min(ans, bad);
}
}
pf("%lld\n", ans);
check.clear();
}
return 0;
}
|
// Copyright (c) 2009 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 <gtk/gtk.h>
#include "app/gfx/gtk_util.h"
#include "app/l10n_util.h"
#include "base/message_loop.h"
#include "chrome/browser/gtk/options/url_picker_dialog_gtk.h"
#include "chrome/browser/net/url_fixer_upper.h"
#include "chrome/browser/possible_url_model.h"
#include "chrome/browser/profile.h"
#include "chrome/common/gtk_tree.h"
#include "chrome/common/gtk_util.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/pref_service.h"
#include "googleurl/src/gurl.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/locale_settings.h"
#include "net/base/net_util.h"
namespace {
// Style for recent history label.
const char kHistoryLabelMarkup[] = "<span weight='bold'>%s</span>";
// Column ids for |history_list_store_|.
enum {
COL_FAVICON,
COL_TITLE,
COL_DISPLAY_URL,
COL_COUNT,
};
} // anonymous namespace
UrlPickerDialogGtk::UrlPickerDialogGtk(UrlPickerCallback* callback,
Profile* profile,
GtkWindow* parent)
: profile_(profile),
callback_(callback) {
dialog_ = gtk_dialog_new_with_buttons(
l10n_util::GetStringUTF8(IDS_ASI_ADD_TITLE).c_str(),
parent,
static_cast<GtkDialogFlags>(GTK_DIALOG_MODAL | GTK_DIALOG_NO_SEPARATOR),
GTK_STOCK_CANCEL,
GTK_RESPONSE_CANCEL,
NULL);
add_button_ = gtk_dialog_add_button(GTK_DIALOG(dialog_),
GTK_STOCK_ADD, GTK_RESPONSE_OK);
gtk_dialog_set_default_response(GTK_DIALOG(dialog_), GTK_RESPONSE_OK);
gtk_box_set_spacing(GTK_BOX(GTK_DIALOG(dialog_)->vbox),
gtk_util::kContentAreaSpacing);
// URL entry.
GtkWidget* url_hbox = gtk_hbox_new(FALSE, gtk_util::kLabelSpacing);
GtkWidget* url_label = gtk_label_new(
l10n_util::GetStringUTF8(IDS_ASI_URL).c_str());
gtk_box_pack_start(GTK_BOX(url_hbox), url_label,
FALSE, FALSE, 0);
url_entry_ = gtk_entry_new();
gtk_entry_set_activates_default(GTK_ENTRY(url_entry_), TRUE);
g_signal_connect(G_OBJECT(url_entry_), "changed",
G_CALLBACK(OnUrlEntryChanged), this);
gtk_box_pack_start(GTK_BOX(url_hbox), url_entry_,
TRUE, TRUE, 0);
gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dialog_)->vbox), url_hbox,
FALSE, FALSE, 0);
// Recent history description label.
GtkWidget* history_vbox = gtk_vbox_new(FALSE, gtk_util::kLabelSpacing);
gtk_container_add(GTK_CONTAINER(GTK_DIALOG(dialog_)->vbox), history_vbox);
GtkWidget* history_label = gtk_label_new(NULL);
char* markup = g_markup_printf_escaped(kHistoryLabelMarkup,
l10n_util::GetStringUTF8(IDS_ASI_DESCRIPTION).c_str());
gtk_label_set_markup(GTK_LABEL(history_label), markup);
g_free(markup);
GtkWidget* history_label_alignment = gtk_alignment_new(0.0, 0.5, 0.0, 0.0);
gtk_container_add(GTK_CONTAINER(history_label_alignment), history_label);
gtk_box_pack_start(GTK_BOX(history_vbox), history_label_alignment,
FALSE, FALSE, 0);
// Recent history list.
GtkWidget* scroll_window = gtk_scrolled_window_new(NULL, NULL);
gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scroll_window),
GTK_POLICY_AUTOMATIC,
GTK_POLICY_AUTOMATIC);
gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(scroll_window),
GTK_SHADOW_ETCHED_IN);
gtk_container_add(GTK_CONTAINER(history_vbox), scroll_window);
history_list_store_ = gtk_list_store_new(COL_COUNT,
GDK_TYPE_PIXBUF,
G_TYPE_STRING,
G_TYPE_STRING);
history_list_sort_ = gtk_tree_model_sort_new_with_model(
GTK_TREE_MODEL(history_list_store_));
gtk_tree_sortable_set_sort_func(GTK_TREE_SORTABLE(history_list_sort_),
COL_TITLE, CompareTitle, this, NULL);
gtk_tree_sortable_set_sort_func(GTK_TREE_SORTABLE(history_list_sort_),
COL_DISPLAY_URL, CompareURL, this, NULL);
history_tree_ = gtk_tree_view_new_with_model(history_list_sort_);
g_object_unref(history_list_store_);
g_object_unref(history_list_sort_);
gtk_container_add(GTK_CONTAINER(scroll_window), history_tree_);
gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(history_tree_),
TRUE);
g_signal_connect(G_OBJECT(history_tree_), "row-activated",
G_CALLBACK(OnHistoryRowActivated), this);
history_selection_ = gtk_tree_view_get_selection(
GTK_TREE_VIEW(history_tree_));
gtk_tree_selection_set_mode(history_selection_,
GTK_SELECTION_SINGLE);
g_signal_connect(G_OBJECT(history_selection_), "changed",
G_CALLBACK(OnHistorySelectionChanged), this);
// History list columns.
GtkTreeViewColumn* column = gtk_tree_view_column_new();
GtkCellRenderer* renderer = gtk_cell_renderer_pixbuf_new();
gtk_tree_view_column_pack_start(column, renderer, FALSE);
gtk_tree_view_column_add_attribute(column, renderer, "pixbuf", COL_FAVICON);
renderer = gtk_cell_renderer_text_new();
gtk_tree_view_column_pack_start(column, renderer, TRUE);
gtk_tree_view_column_add_attribute(column, renderer, "text", COL_TITLE);
gtk_tree_view_append_column(GTK_TREE_VIEW(history_tree_),
column);
gtk_tree_view_column_set_title(
column, l10n_util::GetStringUTF8(IDS_ASI_PAGE_COLUMN).c_str());
gtk_tree_view_column_set_sizing(column, GTK_TREE_VIEW_COLUMN_FIXED);
gtk_tree_view_column_set_resizable(column, TRUE);
gtk_tree_view_column_set_sort_column_id(column, COL_TITLE);
GtkTreeViewColumn* url_column = gtk_tree_view_column_new_with_attributes(
l10n_util::GetStringUTF8(IDS_ASI_URL_COLUMN).c_str(),
gtk_cell_renderer_text_new(),
"text", COL_DISPLAY_URL,
NULL);
gtk_tree_view_append_column(GTK_TREE_VIEW(history_tree_), url_column);
gtk_tree_view_column_set_sort_column_id(url_column, COL_DISPLAY_URL);
// Loading data, showing dialog.
url_table_model_.reset(new PossibleURLModel());
url_table_adapter_.reset(new gtk_tree::TableAdapter(this, history_list_store_,
url_table_model_.get()));
url_table_model_->Reload(profile_);
EnableControls();
// Set the size of the dialog.
gtk_widget_realize(dialog_);
int width = 1, height = 1;
gtk_util::GetWidgetSizeFromResources(
dialog_,
IDS_URLPICKER_DIALOG_WIDTH_CHARS,
IDS_URLPICKER_DIALOG_HEIGHT_LINES,
&width, &height);
gtk_window_set_default_size(GTK_WINDOW(dialog_), width, height);
// Set the width of the first column as well.
gtk_util::GetWidgetSizeFromResources(
dialog_,
IDS_URLPICKER_DIALOG_LEFT_COLUMN_WIDTH_CHARS, 0,
&width, NULL);
gtk_tree_view_column_set_fixed_width(column, width);
gtk_widget_show_all(dialog_);
g_signal_connect(dialog_, "response", G_CALLBACK(OnResponse), this);
g_signal_connect(dialog_, "destroy", G_CALLBACK(OnWindowDestroy), this);
}
UrlPickerDialogGtk::~UrlPickerDialogGtk() {
delete callback_;
}
void UrlPickerDialogGtk::AddURL() {
GURL url(URLFixerUpper::FixupURL(
gtk_entry_get_text(GTK_ENTRY(url_entry_)), ""));
callback_->Run(url);
}
void UrlPickerDialogGtk::EnableControls() {
const gchar* text = gtk_entry_get_text(GTK_ENTRY(url_entry_));
gtk_widget_set_sensitive(add_button_, text && *text);
}
std::string UrlPickerDialogGtk::GetURLForPath(GtkTreePath* path) const {
gint row = gtk_tree::GetTreeSortChildRowNumForPath(history_list_sort_, path);
if (row < 0) {
NOTREACHED();
return std::string();
}
std::wstring languages =
profile_->GetPrefs()->GetString(prefs::kAcceptLanguages);
// Because the url_field_ is user-editable, we set the URL with
// username:password and escaped path and query.
std::wstring formatted = net::FormatUrl(url_table_model_->GetURL(row),
languages, false, UnescapeRule::NONE, NULL, NULL, NULL);
return WideToUTF8(formatted);
}
void UrlPickerDialogGtk::SetColumnValues(int row, GtkTreeIter* iter) {
SkBitmap bitmap = url_table_model_->GetIcon(row);
GdkPixbuf* pixbuf = gfx::GdkPixbufFromSkBitmap(&bitmap);
std::wstring title = url_table_model_->GetText(row, IDS_ASI_PAGE_COLUMN);
std::wstring url = url_table_model_->GetText(row, IDS_ASI_URL_COLUMN);
gtk_list_store_set(history_list_store_, iter,
COL_FAVICON, pixbuf,
COL_TITLE, WideToUTF8(title).c_str(),
COL_DISPLAY_URL, WideToUTF8(url).c_str(),
-1);
g_object_unref(pixbuf);
}
// static
gint UrlPickerDialogGtk::CompareTitle(GtkTreeModel* model,
GtkTreeIter* a,
GtkTreeIter* b,
gpointer window) {
int row1 = gtk_tree::GetRowNumForIter(model, a);
int row2 = gtk_tree::GetRowNumForIter(model, b);
return reinterpret_cast<UrlPickerDialogGtk*>(window)->url_table_model_->
CompareValues(row1, row2, IDS_ASI_PAGE_COLUMN);
}
// static
gint UrlPickerDialogGtk::CompareURL(GtkTreeModel* model,
GtkTreeIter* a,
GtkTreeIter* b,
gpointer window) {
int row1 = gtk_tree::GetRowNumForIter(model, a);
int row2 = gtk_tree::GetRowNumForIter(model, b);
return reinterpret_cast<UrlPickerDialogGtk*>(window)->url_table_model_->
CompareValues(row1, row2, IDS_ASI_URL_COLUMN);
}
// static
void UrlPickerDialogGtk::OnUrlEntryChanged(GtkEditable* editable,
UrlPickerDialogGtk* window) {
window->EnableControls();
}
// static
void UrlPickerDialogGtk::OnHistorySelectionChanged(
GtkTreeSelection *selection, UrlPickerDialogGtk* window) {
GtkTreeIter iter;
if (!gtk_tree_selection_get_selected(selection, NULL, &iter)) {
// The user has unselected the history element, nothing to do.
return;
}
GtkTreePath* path = gtk_tree_model_get_path(
GTK_TREE_MODEL(window->history_list_sort_), &iter);
gtk_entry_set_text(GTK_ENTRY(window->url_entry_),
window->GetURLForPath(path).c_str());
gtk_tree_path_free(path);
}
void UrlPickerDialogGtk::OnHistoryRowActivated(GtkTreeView* tree_view,
GtkTreePath* path,
GtkTreeViewColumn* column,
UrlPickerDialogGtk* window) {
GURL url(URLFixerUpper::FixupURL(window->GetURLForPath(path), ""));
window->callback_->Run(url);
gtk_widget_destroy(window->dialog_);
}
// static
void UrlPickerDialogGtk::OnResponse(GtkDialog* dialog, int response_id,
UrlPickerDialogGtk* window) {
if (response_id == GTK_RESPONSE_OK) {
window->AddURL();
}
gtk_widget_destroy(window->dialog_);
}
// static
void UrlPickerDialogGtk::OnWindowDestroy(GtkWidget* widget,
UrlPickerDialogGtk* window) {
MessageLoop::current()->DeleteSoon(FROM_HERE, window);
}
|
#include<string>
#include<cctype>
#include<iostream>
#include<vector>
#include<fstream>
#include<list>
#include<deque>
/*
std::vector read_f(std::string path) {
std::fstream pf{path};
std::vector code;
if(pf.good()){
//std::string tmpString;
std::stringstream tmpString;
while (std::getline(pf,tmpString))
{
}
}
}
int test9_2(void) {
std::list<int> buu {1,2,3,4,5,5,6,6,7,7};
std:list<std::deque<int>> t1 {{1,2,3,4,5}, {0,213,341,5341,3241}};
}
*/
std::vector<int>::iterator test9_2_1(std::vector<int>::iterator bg, std::vector<int>::iterator ed, int m){
std::cout<<"this is test 9.2.1 >> " <<std::endl;
std::cout<<"output a right iterator of std::vecotr<int>::iterator"<<std::endl;
std::cout<<"resutl is >>";
//std::cout<<*result<<std::endl;
while(bg != ed) {
if( m == *bg){
*bg = 9999;
return bg;
}
++bg;
}
return ed;
}
std::vector<int>::const_iterator test_9_2_2(std::vector<int>::const_iterator bg, std::vector<int>::const_iterator ed, int m) {
while( bg != ed) {
if( m == *bg)
//*bg = 9999;
return bg;
++bg;
}
return ed;
}
int test_9_2_3() {
const std::vector<int> vi;
const int m {9};
return 0;
}
std::vector<int> copy_vi(std::vector<int>::const_iterator bg, std::vector<int>::const_iterator ed) {
return std::vector<int>(bg, ed);
}
int test_9_13(void) {
using namespace std;
list<int> li = {1,23,4,5,5,6,63,121};
vector<double> vd (li.begin(),li.end());
std::cout << vd[1] << std::endl;
std::cout << li.front() << std::endl;
return 10;
}
int main(void) {
using namespace std;
string iii("this is a line charactor");
cout<<iii<<endl;
for(auto& c:iii) {
c = toupper(c);
}
cout<<iii<<endl;
// test 9.2.1
vector<int> vi {1,2,3,4,4,5,5,6,463,234,5545};
auto result = test9_2_1(vi.begin(), vi.end(), 5);
auto result1 = test_9_2_2(vi.cbegin(), vi.cend(), 463);
cout<<"resutl is >>";
cout<<*result<<endl;
cout<<"resutl1 is >>";
cout<<*result1<<endl;
cout<<" test_9_13 "<<endl;
return 0;
}
|
/**********************************************************************
* Copyright (c) 2008-2015, Alliance for Sustainable Energy.
* All rights reserved.
*
* This library 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 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
**********************************************************************/
#ifndef MODEL_VERSION_IMPL_HPP
#define MODEL_VERSION_IMPL_HPP
#include "ModelObject_Impl.hpp"
namespace openstudio {
namespace model {
class ParentObject;
namespace detail {
class MODEL_API Version_Impl : public ModelObject_Impl {
public:
/** @name Constructors and Destructors */
//@{
// constructor
Version_Impl(const IdfObject& idfObject,
Model_Impl* model,
bool keepHandle);
// construct from workspace
Version_Impl(const openstudio::detail::WorkspaceObject_Impl& other,
Model_Impl* model,
bool keepHandle);
// clone copy constructor
Version_Impl(const Version_Impl& other,
Model_Impl* model,
bool keepHandle);
// virtual destructor
virtual ~Version_Impl(){}
//@}
/** @name Virtual Methods */
//@{
// return the parent object in the hierarchy
virtual boost::optional<ParentObject> parent() const;
// set the parent, child may have to call methods on the parent
virtual bool setParent(ParentObject& newParent);
// Get all output variable names that could be associated with this object.
virtual const std::vector<std::string>& outputVariableNames() const;
virtual IddObjectType iddObjectType() const;
//@}
/** @name Getters */
//@{
std::string versionIdentifier() const;
//@}
/** @name Setters */
//@{
void setVersionIdentifier(const std::string& s);
//@}
private:
REGISTER_LOGGER("openstudio.model.Version");
};
} // detail
} // model
} // openstudio
#endif
|
#include <cstdlib>
#include <iostream>
using namespace std;
inline
void use_io_optimizations()
{
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
}
int main()
{
use_io_optimizations();
int x;
int y;
int steps;
cin >> x >> y >> steps;
int shortest_path {abs(x) + abs(y)};
if (shortest_path > steps || shortest_path % 2 != steps % 2)
{
cout << "No";
}
else
{
cout << "Yes";
}
cout << '\n';
return 0;
}
|
#include "SpriteSheet.h"
#include <SDL2/SDL.h>
#include "Texture.h"
#include <stdio.h>
SpriteSheet::SpriteSheet()
{
texture = new Texture();
}
SpriteSheet::~SpriteSheet()
{
delete texture;
}
bool SpriteSheet::LoadSpriteSheet(SDL_Renderer * renderer, const char * filepath)
{
if (texture->LoadTexture(renderer, filepath))
{
bounds.x = 0;
bounds.y = 0;
int status = SDL_QueryTexture(texture->GetSource(), NULL, NULL, &bounds.w, &bounds.h);
if (status == 0)
return true;
}
return false;
}
bool SpriteSheet::FreeSpriteSheet()
{
return texture->FreeTexture();
}
/*
x = column
y = row
if the source texture is 256x256 pixels
and I wanted to split the picture by 32x32 slices
I would have 8 slices every row and 8 slices every column
8 * 8 = 64 slices
[ 0,0 ] [ 1,0 ] [ 2,0 ] [ 3,0 ] [ 4,0 ] [ 5,0 ] [ 6,0 ] [ 7,0 ]
[ 0,1 ] [ 1,1 ] [ 2,1 ] [ 3,1 ] [ 4,1 ]
[ 0,2 ]
[ 0,3 ]
[ 0,4 ]
[ 0,5 ]
[ 0,6 ]
[ 0,7 ]
my task here is to convert 1d index into a 2d representable index
we know the index, and width and height of image sheet, and slice width and slice height
number of rows = sheet.height / slice.height
number of columns = sheet.width / slice.width
x = (1d index % number of columns) * slice.width
y = (1d index / number of rows) * slice.height
draw to SDL_Rect src
*/
bool SpriteSheet::DrawFrame(SDL_Renderer * renderer, int frameIndex)
{
//convert frame index to 2d sprite sheet coordinates
int numRows = bounds.w / SliceWidth;
int numCols = bounds.h / SliceHeight;
framesLength = numRows * numCols;
if (frameIndex >= framesLength || frameIndex < 0)
{
printf("Error: Invalid frame index %d\n", frameIndex);
return false;
}
int sheetX = (frameIndex % numCols) * SliceWidth;
int sheetY = (frameIndex / numRows) * SliceHeight;
SDL_Rect src;
src.h = SliceHeight;
src.w = SliceWidth;
src.x = sheetX;
src.y = sheetY;
if (SDL_RenderCopy(renderer, texture->GetSource(), &src, &bounds))
{
printf("Error: %s\n", SDL_GetError());
return false;
}
//SDL_RenderPresent(renderer);
return true;
}
//x = width in pixels
//y = height in pixels
SDL_Point SpriteSheet::GetSliceDimensions()
{
return SDL_Point{ SliceWidth, SliceHeight };
}
int SpriteSheet::GetFramesLength()
{
return framesLength;
}
|
/**
* SPOJ Problem Set (classical)
* 11736. Prime Time
* Problem code: PTIME
*
* For your math homework this week your teacher gave you five large
* numbers and asked you to find their prime factors. However these
* numbers aren't nearly large enough for someone with knowledge of
* programming like yourself. So you decide to take the factorial of
* each of these numbers. Recall that N! (N factorial) is the product
* of the integers from 1 through N (inclusive). It.s your job now to
* create a program to help you do your homework.
* Input
*
* Each test case contains a number N (2 . N . 10000).
*
*
* Output
*
* The output should contain a line representing the prime
* factorization of the factorial given number, which should be of
* the form: p1^e1 * p2^e2 * ... * pk^ek where p1, p2, ..., pk are
* the distinct prime factors of the factorial of the given number in
* increasing order, and e1, e2, ..., ek are their exponents.
*
*
* Example
*
*
*
* Input:
*
* 10
*
* Output:
*
* 2^8 * 3^4 * 5^2 * 7^1
*
*
* */
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
int p[]={2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013, 1019, 1021, 1031, 1033, 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091, 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151, 1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213, 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277, 1279, 1283, 1289, 1291, 1297, 1301, 1303, 1307, 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399, 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451, 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493, 1499, 1511, 1523, 1531, 1543, 1549, 1553, 1559, 1567, 1571, 1579, 1583, 1597, 1601, 1607, 1609, 1613, 1619, 1621, 1627, 1637, 1657, 1663, 1667, 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733, 1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789, 1801, 1811, 1823, 1831, 1847, 1861, 1867, 1871, 1873, 1877, 1879, 1889, 1901, 1907, 1913, 1931, 1933, 1949, 1951, 1973, 1979, 1987, 1993, 1997, 1999, 2003, 2011, 2017, 2027, 2029, 2039, 2053, 2063, 2069, 2081, 2083, 2087, 2089, 2099, 2111, 2113, 2129, 2131, 2137, 2141, 2143, 2153, 2161, 2179, 2203, 2207, 2213, 2221, 2237, 2239, 2243, 2251, 2267, 2269, 2273, 2281, 2287, 2293, 2297, 2309, 2311, 2333, 2339, 2341, 2347, 2351, 2357, 2371, 2377, 2381, 2383, 2389, 2393, 2399, 2411, 2417, 2423, 2437, 2441, 2447, 2459, 2467, 2473, 2477, 2503, 2521, 2531, 2539, 2543, 2549, 2551, 2557, 2579, 2591, 2593, 2609, 2617, 2621, 2633, 2647, 2657, 2659, 2663, 2671, 2677, 2683, 2687, 2689, 2693, 2699, 2707, 2711, 2713, 2719, 2729, 2731, 2741, 2749, 2753, 2767, 2777, 2789, 2791, 2797, 2801, 2803, 2819, 2833, 2837, 2843, 2851, 2857, 2861, 2879, 2887, 2897, 2903, 2909, 2917, 2927, 2939, 2953, 2957, 2963, 2969, 2971, 2999, 3001, 3011, 3019, 3023, 3037, 3041, 3049, 3061, 3067, 3079, 3083, 3089, 3109, 3119, 3121, 3137, 3163, 3167, 3169, 3181, 3187, 3191, 3203, 3209, 3217, 3221, 3229, 3251, 3253, 3257, 3259, 3271, 3299, 3301, 3307, 3313, 3319, 3323, 3329, 3331, 3343, 3347, 3359, 3361, 3371, 3373, 3389, 3391, 3407, 3413, 3433, 3449, 3457, 3461, 3463, 3467, 3469, 3491, 3499, 3511, 3517, 3527, 3529, 3533, 3539, 3541, 3547, 3557, 3559, 3571, 3581, 3583, 3593, 3607, 3613, 3617, 3623, 3631, 3637, 3643, 3659, 3671, 3673, 3677, 3691, 3697, 3701, 3709, 3719, 3727, 3733, 3739, 3761, 3767, 3769, 3779, 3793, 3797, 3803, 3821, 3823, 3833, 3847, 3851, 3853, 3863, 3877, 3881, 3889, 3907, 3911, 3917, 3919, 3923, 3929, 3931, 3943, 3947, 3967, 3989, 4001, 4003, 4007, 4013, 4019, 4021, 4027, 4049, 4051, 4057, 4073, 4079, 4091, 4093, 4099, 4111, 4127, 4129, 4133, 4139, 4153, 4157, 4159, 4177, 4201, 4211, 4217, 4219, 4229, 4231, 4241, 4243, 4253, 4259, 4261, 4271, 4273, 4283, 4289, 4297, 4327, 4337, 4339, 4349, 4357, 4363, 4373, 4391, 4397, 4409, 4421, 4423, 4441, 4447, 4451, 4457, 4463, 4481, 4483, 4493, 4507, 4513, 4517, 4519, 4523, 4547, 4549, 4561, 4567, 4583, 4591, 4597, 4603, 4621, 4637, 4639, 4643, 4649, 4651, 4657, 4663, 4673, 4679, 4691, 4703, 4721, 4723, 4729, 4733, 4751, 4759, 4783, 4787, 4789, 4793, 4799, 4801, 4813, 4817, 4831, 4861, 4871, 4877, 4889, 4903, 4909, 4919, 4931, 4933, 4937, 4943, 4951, 4957, 4967, 4969, 4973, 4987, 4993, 4999, 5003, 5009, 5011, 5021, 5023, 5039, 5051, 5059, 5077, 5081, 5087, 5099, 5101, 5107, 5113, 5119, 5147, 5153, 5167, 5171, 5179, 5189, 5197, 5209, 5227, 5231, 5233, 5237, 5261, 5273, 5279, 5281, 5297, 5303, 5309, 5323, 5333, 5347, 5351, 5381, 5387, 5393, 5399, 5407, 5413, 5417, 5419, 5431, 5437, 5441, 5443, 5449, 5471, 5477, 5479, 5483, 5501, 5503, 5507, 5519, 5521, 5527, 5531, 5557, 5563, 5569, 5573, 5581, 5591, 5623, 5639, 5641, 5647, 5651, 5653, 5657, 5659, 5669, 5683, 5689, 5693, 5701, 5711, 5717, 5737, 5741, 5743, 5749, 5779, 5783, 5791, 5801, 5807, 5813, 5821, 5827, 5839, 5843, 5849, 5851, 5857, 5861, 5867, 5869, 5879, 5881, 5897, 5903, 5923, 5927, 5939, 5953, 5981, 5987, 6007, 6011, 6029, 6037, 6043, 6047, 6053, 6067, 6073, 6079, 6089, 6091, 6101, 6113, 6121, 6131, 6133, 6143, 6151, 6163, 6173, 6197, 6199, 6203, 6211, 6217, 6221, 6229, 6247, 6257, 6263, 6269, 6271, 6277, 6287, 6299, 6301, 6311, 6317, 6323, 6329, 6337, 6343, 6353, 6359, 6361, 6367, 6373, 6379, 6389, 6397, 6421, 6427, 6449, 6451, 6469, 6473, 6481, 6491, 6521, 6529, 6547, 6551, 6553, 6563, 6569, 6571, 6577, 6581, 6599, 6607, 6619, 6637, 6653, 6659, 6661, 6673, 6679, 6689, 6691, 6701, 6703, 6709, 6719, 6733, 6737, 6761, 6763, 6779, 6781, 6791, 6793, 6803, 6823, 6827, 6829, 6833, 6841, 6857, 6863, 6869, 6871, 6883, 6899, 6907, 6911, 6917, 6947, 6949, 6959, 6961, 6967, 6971, 6977, 6983, 6991, 6997, 7001, 7013, 7019, 7027, 7039, 7043, 7057, 7069, 7079, 7103, 7109, 7121, 7127, 7129, 7151, 7159, 7177, 7187, 7193, 7207, 7211, 7213, 7219, 7229, 7237, 7243, 7247, 7253, 7283, 7297, 7307, 7309, 7321, 7331, 7333, 7349, 7351, 7369, 7393, 7411, 7417, 7433, 7451, 7457, 7459, 7477, 7481, 7487, 7489, 7499, 7507, 7517, 7523, 7529, 7537, 7541, 7547, 7549, 7559, 7561, 7573, 7577, 7583, 7589, 7591, 7603, 7607, 7621, 7639, 7643, 7649, 7669, 7673, 7681, 7687, 7691, 7699, 7703, 7717, 7723, 7727, 7741, 7753, 7757, 7759, 7789, 7793, 7817, 7823, 7829, 7841, 7853, 7867, 7873, 7877, 7879, 7883, 7901, 7907, 7919, 7927, 7933, 7937, 7949, 7951, 7963, 7993, 8009, 8011, 8017, 8039, 8053, 8059, 8069, 8081, 8087, 8089, 8093, 8101, 8111, 8117, 8123, 8147, 8161, 8167, 8171, 8179, 8191, 8209, 8219, 8221, 8231, 8233, 8237, 8243, 8263, 8269, 8273, 8287, 8291, 8293, 8297, 8311, 8317, 8329, 8353, 8363, 8369, 8377, 8387, 8389, 8419, 8423, 8429, 8431, 8443, 8447, 8461, 8467, 8501, 8513, 8521, 8527, 8537, 8539, 8543, 8563, 8573, 8581, 8597, 8599, 8609, 8623, 8627, 8629, 8641, 8647, 8663, 8669, 8677, 8681, 8689, 8693, 8699, 8707, 8713, 8719, 8731, 8737, 8741, 8747, 8753, 8761, 8779, 8783, 8803, 8807, 8819, 8821, 8831, 8837, 8839, 8849, 8861, 8863, 8867, 8887, 8893, 8923, 8929, 8933, 8941, 8951, 8963, 8969, 8971, 8999, 9001, 9007, 9011, 9013, 9029, 9041, 9043, 9049, 9059, 9067, 9091, 9103, 9109, 9127, 9133, 9137, 9151, 9157, 9161, 9173, 9181, 9187, 9199, 9203, 9209, 9221, 9227, 9239, 9241, 9257, 9277, 9281, 9283, 9293, 9311, 9319, 9323, 9337, 9341, 9343, 9349, 9371, 9377, 9391, 9397, 9403, 9413, 9419, 9421, 9431, 9433, 9437, 9439, 9461, 9463, 9467, 9473, 9479, 9491, 9497, 9511, 9521, 9533, 9539, 9547, 9551, 9587, 9601, 9613, 9619, 9623, 9629, 9631, 9643, 9649, 9661, 9677, 9679, 9689, 9697, 9719, 9721, 9733, 9739, 9743, 9749, 9767, 9769, 9781, 9787, 9791, 9803, 9811, 9817, 9829, 9833, 9839, 9851, 9857, 9859, 9871, 9883, 9887, 9901, 9907, 9923, 9929, 9931, 9941, 9949, 9967, 9973,10007};
void prime_fact_factorize(int n)
{
int count;
int index=lower_bound(p,p+1230,n) - p;
if(p[index] != n)
index=index-1;
for(int i=0;p[i]<=n;i++)//check prime factor in factorial
{
count=0;
for(int j=p[i];j<=n;j*=p[i])
{
count+=floor(n/j);
}
printf("%d^%d",p[i],count);
if(index)
printf(" * ");
index--;
}
printf("\n");
}
int main()
{
int n;
while(scanf("%d",&n) != EOF)
{
prime_fact_factorize(n);
}
return 0;
}
|
#include "xcore/xcore.h"
#include <stdio.h>
#include <QIcon>
#include <QDebug>
#include <QPainter>
#include <QFileDialog>
#include <QTemporaryFile>
#include <QTextCodec>
#include "debuger.h"
#include "dbg_sprscan.h"
#include "filer.h"
#include "xgui.h"
QColor colPC(32,200,32); // pc
QColor colBRK(200,128,128); // breakpoint
QColor colBG0(255,255,255); // background
QColor colBG1(230,230,230); // background alternative
QColor colSEL(128,255,128); // background selected
unsigned short dumpAdr = 0;
unsigned short disasmAdr = 0;
int blockStart = -1;
int blockEnd = -1;
// QMap<QString, xAdr> labels;
int getRFIData(QComboBox*);
int dasmSome(Computer*, unsigned short, dasmData&);
// trace type
enum {
DBG_TRACE_ALL = 0x100,
DBG_TRACE_INT,
DBG_TRACE_HERE,
DBG_TRACE_LOG
};
enum {
NES_SCR_OFF = 0x00,
NES_SCR_0,
NES_SCR_1,
NES_SCR_2,
NES_SCR_3,
NES_SCR_ALL
};
enum {
NES_TILE_0000 = 0x0000,
NES_TILE_1000 = 0x1000
};
typedef struct {
QLabel* name;
QLineEdit* edit;
} dbgRegPlace;
void DebugWin::start(Computer* c) {
// onStart = 1;
comp = c;
blockStart = -1;
blockEnd = -1;
chLayout();
// if (getRFIData(ui.cbDasmMode) == XVIEW_CPU)
// disasmAdr = comp->cpu->pc;
if (!fillAll()) {
disasmAdr = comp->cpu->pc;
fillDisasm();
}
updateScreen();
if (!comp->vid->tail)
vidDarkTail(comp->vid);
ui.tabsPanel->setTabEnabled(ui.tabsPanel->indexOf(ui.gbTab), comp->hw->id == HW_GBC);
ui.tabsPanel->setTabEnabled(ui.tabsPanel->indexOf(ui.nesTab), comp->hw->id == HW_NES);
this->move(winPos);
// ui.dasmTable->setFocus();
comp->vid->debug = 1;
comp->debug = 1;
comp->brk = 0;
show();
int wd = (ui.dasmTable->height() - 2) / ui.dasmTable->rows();
ui.dasmTable->verticalHeader()->setDefaultSectionSize(wd);
wd = (ui.dumpTable->height() - 2) / ui.dumpTable->rows();
ui.dumpTable->verticalHeader()->setDefaultSectionSize(wd);
if (memViewer->vis) {
memViewer->move(memViewer->winPos);
memViewer->show();
memViewer->fillImage();
}
chDumpView();
activateWindow();
}
void DebugWin::stop() {
compExec(comp); // to prevent double breakpoint catch
comp->debug = 0;
comp->vid->debug = 0;
comp->maping = ui.actMaping->isChecked() ? 1 : 0;
tCount = comp->tickCount;
winPos = pos();
trace = 0;
memViewer->vis = memViewer->isVisible() ? 1 : 0;
memViewer->winPos = memViewer->pos();
memViewer->hide();
hide();
emit closed();
}
void DebugWin::reject() {stop();}
xItemDelegate::xItemDelegate(int t) {type = t;}
QWidget* xItemDelegate::createEditor(QWidget* par, const QStyleOptionViewItem&, const QModelIndex&) const {
QLineEdit* edt = new QLineEdit(par);
switch (type) {
case XTYPE_NONE: delete(edt); edt = NULL; break;
case XTYPE_ADR: edt->setInputMask("Hhhh"); break;
case XTYPE_LABEL: break;
case XTYPE_DUMP: edt->setInputMask("Hhhhhhhhhhhh"); break; // 6 bytes max
case XTYPE_BYTE: edt->setInputMask("Hh"); break;
}
return edt;
}
int dmpmrd(unsigned short adr, void* ptr) {
Computer* comp = (Computer*)ptr;
MemPage* pg = &comp->mem->map[(adr >> 8) & 0xff];
int fadr = (pg->num << 8) | (adr & 0xff);
int res = 0xff;
switch (pg->type) {
case MEM_RAM:
res = comp->mem->ramData[fadr & comp->mem->ramMask];
break;
case MEM_ROM:
res = comp->mem->romData[fadr & comp->mem->romMask];
break;
case MEM_SLOT:
if (!comp->slot) break;
if (!comp->slot->data) break;
res = comp->slot->data[fadr & comp->slot->memMask];
break;
}
res |= getBrk(comp, adr) << 8;
return res;
}
void dmpmwr(unsigned short adr, unsigned char val, void* ptr) {
Computer* comp = (Computer*)ptr;
memWr(comp->mem, adr, val);
}
static xLabel* dbgRegLabs[16];
static xHexSpin* dbgRegEdit[16];
DebugWin::DebugWin(QWidget* par):QDialog(par) {
int i;
setFont(QFont("://DejaVuSansMono.ttf",10));
ui.setupUi(this);
xLabel* arrl[16] = {
ui.labReg00, ui.labReg01, ui.labReg02, ui.labReg03, ui.labReg04,
ui.labReg05, ui.labReg06, ui.labReg07, ui.labReg08, ui.labReg09,
ui.labReg10, ui.labReg11, ui.labReg12, ui.labReg13, ui.labReg14,
NULL
};
xHexSpin* arre[16] = {
ui.editReg00, ui.editReg01, ui.editReg02, ui.editReg03, ui.editReg04,
ui.editReg05, ui.editReg06, ui.editReg07, ui.editReg08, ui.editReg09,
ui.editReg10, ui.editReg11, ui.editReg12, ui.editReg13, ui.editReg14,
NULL
};
for (i = 0; i < 16; i++) {
dbgRegLabs[i] = arrl[i];
dbgRegEdit[i] = arre[i];
if (arrl[i]) {
arrl[i]->id = i;
connect(arrl[i], SIGNAL(clicked(QMouseEvent*)), this, SLOT(regClick(QMouseEvent*)));
dbgRegEdit[i]->setXFlag(XHS_BGR | XHS_DEC | XHS_FILL);
}
}
ui.dumpTable->setComp(&comp);
ui.dasmTable->setComp(&comp);
conf.dbg.labels = 1;
conf.dbg.segment = 0;
ui.actShowLabels->setChecked(conf.dbg.labels);
ui.actShowSeg->setChecked(conf.dbg.segment);
// actions data
ui.actFetch->setData(MEM_BRK_FETCH);
ui.actRead->setData(MEM_BRK_RD);
ui.actWrite->setData(MEM_BRK_WR);
ui.actViewOpcode->setData(DBG_VIEW_EXEC);
ui.actViewByte->setData(DBG_VIEW_BYTE);
ui.actViewWord->setData(DBG_VIEW_WORD);
ui.actViewAddr->setData(DBG_VIEW_ADDR);
ui.actViewText->setData(DBG_VIEW_TEXT);
ui.actTrace->setData(DBG_TRACE_ALL);
ui.actTraceHere->setData(DBG_TRACE_HERE);
ui.actTraceINT->setData(DBG_TRACE_INT);
ui.actTraceLog->setData(DBG_TRACE_LOG);
ui.dasmTable->setFocus();
// disasm table
ui.dasmTable->setColumnWidth(0,90);
ui.dasmTable->setColumnWidth(1,85);
ui.dasmTable->setColumnWidth(2,130);
ui.dasmTable->setItemDelegateForColumn(0, new xItemDelegate(XTYPE_LABEL));
ui.dasmTable->setItemDelegateForColumn(1, new xItemDelegate(XTYPE_DUMP));
ui.cbDasmMode->addItem("CPU", XVIEW_CPU);
ui.cbDasmMode->addItem("RAM", XVIEW_RAM);
ui.cbDasmMode->addItem("ROM", XVIEW_ROM);
// ui.dasmTable->setFont(QFont("://DejaVuSansMono.ttf",8));
connect(ui.cbDasmMode, SIGNAL(currentIndexChanged(int)),this,SLOT(setDasmMode()));
connect(ui.sbDasmPage, SIGNAL(valueChanged(int)),this,SLOT(setDasmMode()));
// actions
ui.tbBreak->addAction(ui.actFetch);
ui.tbBreak->addAction(ui.actRead);
ui.tbBreak->addAction(ui.actWrite);
ui.tbView->addAction(ui.actViewOpcode);
ui.tbView->addAction(ui.actViewByte);
ui.tbView->addAction(ui.actViewText);
ui.tbView->addAction(ui.actViewWord);
ui.tbView->addAction(ui.actViewAddr);
ui.tbSaveDasm->addAction(ui.actDisasm);
ui.tbSaveDasm->addAction(ui.actLoadDump);
// ui.tbSaveDasm->addAction(ui.actLoadMap);
ui.tbSaveDasm->addAction(ui.actLoadLabels);
ui.tbSaveDasm->addAction(ui.actSaveDump);
// ui.tbSaveDasm->addAction(ui.actSaveMap);
ui.tbSaveDasm->addAction(ui.actSaveLabels);
ui.tbTrace->addAction(ui.actTrace);
ui.tbTrace->addAction(ui.actTraceHere);
ui.tbTrace->addAction(ui.actTraceINT);
#ifdef ISDEBUG
ui.tbTrace->addAction(ui.actTraceLog);
#endif
ui.tbTool->addAction(ui.actSearch);
ui.tbTool->addAction(ui.actFill);
ui.tbTool->addAction(ui.actSprScan);
ui.tbTool->addAction(ui.actShowKeys);
ui.tbTool->addAction(ui.actWutcha);
ui.tbDbgOpt->addAction(ui.actShowLabels);
ui.tbDbgOpt->addAction(ui.actHideAddr);
ui.tbDbgOpt->addAction(ui.actShowSeg);
ui.tbDbgOpt->addAction(ui.actMaping);
ui.tbDbgOpt->addAction(ui.actMapingClear);
// connections
connect(this,SIGNAL(needStep()),this,SLOT(doStep()));
connect(ui.actMapingClear,SIGNAL(triggered()),this,SLOT(mapClear()));
connect(ui.dasmTable,SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(putBreakPoint()));
connect(ui.dasmTable,SIGNAL(rqRefill()),this,SLOT(fillDisasm()));
connect(ui.dasmTable,SIGNAL(rqRefill()),this,SLOT(fillDump()));
connect(ui.dasmTable,SIGNAL(rqRefill()),this,SLOT(updateScreen()));
connect(ui.dasmTable,SIGNAL(rqRefill()),ui.bpList,SLOT(update()));
connect(ui.dasmTable,SIGNAL(rqRefillAll()),this,SLOT(fillAll()));
connect(ui.dumpTable,SIGNAL(rqRefill()),this,SLOT(fillDump()));
connect(ui.dumpTable,SIGNAL(rqRefill()),this,SLOT(fillDisasm()));
connect(ui.dumpTable,SIGNAL(rqRefill()),ui.bpList,SLOT(update()));
connect(ui.dumpTable,SIGNAL(rqRefill()),this,SLOT(updateScreen()));
connect(ui.dumpTable->selectionModel(), SIGNAL(currentChanged(QModelIndex, QModelIndex)), this, SLOT(dumpChadr(QModelIndex)));
connect(ui.bpList,SIGNAL(rqDisasm()),this,SLOT(fillDisasm()));
connect(ui.bpList,SIGNAL(rqDasmDump()),this,SLOT(fillDisasm()));
connect(ui.bpList,SIGNAL(rqDasmDump()),this,SLOT(fillDump()));
connect(ui.actSearch,SIGNAL(triggered(bool)),this,SLOT(doFind()));
connect(ui.actFill,SIGNAL(triggered(bool)),this,SLOT(doFill()));
connect(ui.actSprScan,SIGNAL(triggered(bool)),this,SLOT(doMemView()));
connect(ui.actShowKeys,SIGNAL(triggered(bool)),this,SIGNAL(wannaKeys()));
connect(ui.actWutcha,SIGNAL(triggered(bool)),this,SIGNAL(wannaWutch()));
connect(ui.actShowLabels,SIGNAL(toggled(bool)),this,SLOT(setShowLabels(bool)));
connect(ui.actHideAddr,SIGNAL(toggled(bool)),this,SLOT(fillDisasm()));
connect(ui.actShowSeg,SIGNAL(toggled(bool)),this,SLOT(setShowSegment(bool)));
connect(ui.tbView, SIGNAL(triggered(QAction*)),this,SLOT(chaCellProperty(QAction*)));
connect(ui.tbBreak, SIGNAL(triggered(QAction*)),this,SLOT(chaCellProperty(QAction*)));
connect(ui.tbTrace, SIGNAL(triggered(QAction*)),this,SLOT(doTrace(QAction*)));
connect(ui.actLoadDump, SIGNAL(triggered(bool)),this,SLOT(doOpenDump()));
connect(ui.actSaveDump, SIGNAL(triggered(bool)),this,SLOT(doSaveDump()));
connect(ui.actLoadLabels, SIGNAL(triggered(bool)),this,SLOT(dbgLLab()));
connect(ui.actSaveLabels, SIGNAL(triggered(bool)),this,SLOT(dbgSLab()));
// connect(ui.actLoadMap, SIGNAL(triggered(bool)),this,SLOT(loadMap()));
// connect(ui.actSaveMap, SIGNAL(triggered(bool)),this,SLOT(saveMap()));
connect(ui.actDisasm, SIGNAL(triggered(bool)),this,SLOT(saveDasm()));
// dump table
ui.cbCodePage->addItem("WIN", XCP_1251);
ui.cbCodePage->addItem("DOS", XCP_866);
ui.cbCodePage->addItem("KOI8R", XCP_KOI8R);
ui.cbDumpView->addItem("CPU", XVIEW_CPU);
ui.cbDumpView->addItem("RAM", XVIEW_RAM);
ui.cbDumpView->addItem("ROM", XVIEW_ROM);
ui.dumpTable->setColumnWidth(0,60);
ui.dumpTable->setItemDelegate(new xItemDelegate(XTYPE_BYTE));
ui.dumpTable->setItemDelegateForColumn(0, new xItemDelegate(XTYPE_LABEL));
ui.dumpTable->setItemDelegateForColumn(9, new xItemDelegate(XTYPE_NONE));
connect(ui.dumpTable,SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(putBreakPoint()));
connect(ui.cbCodePage, SIGNAL(currentIndexChanged(int)), this, SLOT(setDumpCP()));
connect(ui.cbDumpView, SIGNAL(currentIndexChanged(int)), this, SLOT(chDumpView()));
connect(ui.sbDumpPage, SIGNAL(valueChanged(int)), this, SLOT(chDumpView()));
ui.cbDumpView->setCurrentIndex(0);
// registers
connect(ui.editReg00, SIGNAL(textChanged(QString)), this, SLOT(setCPU()));
connect(ui.editReg01, SIGNAL(textChanged(QString)), this, SLOT(setCPU()));
connect(ui.editReg02, SIGNAL(textChanged(QString)), this, SLOT(setCPU()));
connect(ui.editReg03, SIGNAL(textChanged(QString)), this, SLOT(setCPU()));
connect(ui.editReg04, SIGNAL(textChanged(QString)), this, SLOT(setCPU()));
connect(ui.editReg05, SIGNAL(textChanged(QString)), this, SLOT(setCPU()));
connect(ui.editReg06, SIGNAL(textChanged(QString)), this, SLOT(setCPU()));
connect(ui.editReg07, SIGNAL(textChanged(QString)), this, SLOT(setCPU()));
connect(ui.editReg08, SIGNAL(textChanged(QString)), this, SLOT(setCPU()));
connect(ui.editReg09, SIGNAL(textChanged(QString)), this, SLOT(setCPU()));
connect(ui.editReg10, SIGNAL(textChanged(QString)), this, SLOT(setCPU()));
connect(ui.editReg11, SIGNAL(textChanged(QString)), this, SLOT(setCPU()));
connect(ui.editReg12, SIGNAL(textChanged(QString)), this, SLOT(setCPU()));
connect(ui.editReg13, SIGNAL(textChanged(QString)), this, SLOT(setCPU()));
connect(ui.editReg14, SIGNAL(textChanged(QString)), this, SLOT(setCPU()));
connect(ui.boxIM,SIGNAL(valueChanged(int)),this,SLOT(setCPU()));
connect(ui.flagIFF1,SIGNAL(stateChanged(int)),this,SLOT(setCPU()));
connect(ui.flagIFF2,SIGNAL(stateChanged(int)),this,SLOT(setCPU()));
connect(ui.flagGroup,SIGNAL(buttonClicked(int)),this,SLOT(setFlags()));
// infoslots
scrImg = QImage(256, 192, QImage::Format_RGB888);
// ui.scrLabel->setFixedSize(256,192);
connect(ui.sbScrBank,SIGNAL(valueChanged(int)),this,SLOT(updateScreen()));
connect(ui.leScrAdr,SIGNAL(textChanged(QString)),this,SLOT(updateScreen()));
connect(ui.cbScrAtr,SIGNAL(stateChanged(int)),this,SLOT(updateScreen()));
connect(ui.cbScrPix,SIGNAL(stateChanged(int)),this,SLOT(updateScreen()));
connect(ui.cbScrGrid,SIGNAL(stateChanged(int)),this,SLOT(updateScreen()));
connect(ui.tbAddBrk, SIGNAL(clicked()), this, SLOT(addBrk()));
connect(ui.tbEditBrk, SIGNAL(clicked()), this, SLOT(editBrk()));
connect(ui.tbDelBrk, SIGNAL(clicked()), this, SLOT(delBrk()));
connect(ui.tbBrkOpen, SIGNAL(clicked()), this, SLOT(openBrk()));
connect(ui.tbBrkSave, SIGNAL(clicked()), this, SLOT(saveBrk()));
connect(ui.bpList, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(goToBrk(QModelIndex)));
// gb tab
connect(ui.gbModeGroup, SIGNAL(buttonClicked(int)), this, SLOT(fillGBoy()));
connect(ui.sbTileset, SIGNAL(valueChanged(int)), this, SLOT(fillGBoy()));
connect(ui.sbTilemap, SIGNAL(valueChanged(int)), this, SLOT(fillGBoy()));
// setFixedSize(size());
setFixedHeight(size().height());
block = 0;
disasmAdr = 0;
dumpAdr = 0;
tCount = 0;
trace = 0;
// nes tab
ui.nesScrType->addItem(trUtf8("BG off"), NES_SCR_OFF);
ui.nesScrType->addItem(trUtf8("BG scr 0"), NES_SCR_0);
ui.nesScrType->addItem(trUtf8("BG scr 1"), NES_SCR_1);
ui.nesScrType->addItem(trUtf8("BG scr 2"), NES_SCR_2);
ui.nesScrType->addItem(trUtf8("BG scr 3"), NES_SCR_3);
ui.nesScrType->addItem(trUtf8("All in 1"), NES_SCR_ALL);
ui.nesBGTileset->addItem(trUtf8("Tiles #0000"), NES_TILE_0000);
ui.nesBGTileset->addItem(trUtf8("Tiles #1000"), NES_TILE_1000);
connect(ui.nesScrType,SIGNAL(currentIndexChanged(int)), this, SLOT(drawNes()));
connect(ui.nesBGTileset,SIGNAL(currentIndexChanged(int)), this, SLOT(drawNes()));
// subwindows
dumpwin = new QDialog(this);
dui.setupUi(dumpwin);
dui.tbSave->addAction(dui.aSaveBin);
dui.tbSave->addAction(dui.aSaveHobeta);
dui.tbSave->addAction(dui.aSaveToA);
dui.tbSave->addAction(dui.aSaveToB);
dui.tbSave->addAction(dui.aSaveToC);
dui.tbSave->addAction(dui.aSaveToD);
dui.leStart->setMin(0);
dui.leStart->setMax(0xffff);
dui.leEnd->setMin(0);
dui.leEnd->setMax(0xffff);
dui.leLen->setMin(1);
dui.leLen->setMax(0x10000);
connect(dui.aSaveBin,SIGNAL(triggered()),this,SLOT(saveDumpBin()));
connect(dui.aSaveHobeta,SIGNAL(triggered()),this,SLOT(saveDumpHobeta()));
connect(dui.aSaveToA,SIGNAL(triggered()),this,SLOT(saveDumpToA()));
connect(dui.aSaveToB,SIGNAL(triggered()),this,SLOT(saveDumpToB()));
connect(dui.aSaveToC,SIGNAL(triggered()),this,SLOT(saveDumpToC()));
connect(dui.aSaveToD,SIGNAL(triggered()),this,SLOT(saveDumpToD()));
connect(dui.leStart,SIGNAL(valueChanged(int)),this,SLOT(dmpLimChanged()));
connect(dui.leEnd,SIGNAL(valueChanged(int)),this,SLOT(dmpLimChanged()));
connect(dui.leLen,SIGNAL(valueChanged(int)),this,SLOT(dmpLenChanged()));
openDumpDialog = new QDialog(this);
oui.setupUi(openDumpDialog);
connect(oui.tbFile,SIGNAL(clicked()),this,SLOT(chDumpFile()));
connect(oui.leStart,SIGNAL(textChanged(QString)),this,SLOT(dmpStartOpen()));
connect(oui.butOk,SIGNAL(clicked()), this, SLOT(loadDump()));
memViewer = new MemViewer(this);
memFinder = new xMemFinder(this);
connect(memFinder, SIGNAL(patFound(int)), this, SLOT(onFound(int)));
memFiller = new xMemFiller(this);
connect(memFiller, SIGNAL(rqRefill()),this,SLOT(fillAll()));
brkManager = new xBrkManager(this);
connect(brkManager, SIGNAL(completed(xBrkPoint, xBrkPoint)), this, SLOT(confirmBrk(xBrkPoint, xBrkPoint)));
// context menu
cellMenu = new QMenu(this);
QMenu* bpMenu = new QMenu("Breakpoints");
bpMenu->setIcon(QIcon(":/images/stop.png"));
cellMenu->addMenu(bpMenu);
bpMenu->addAction(ui.actFetch);
bpMenu->addAction(ui.actRead);
bpMenu->addAction(ui.actWrite);
QMenu* viewMenu = new QMenu("View");
viewMenu->setIcon(QIcon(":/images/bars.png"));
cellMenu->addMenu(viewMenu);
viewMenu->addAction(ui.actViewOpcode);
viewMenu->addAction(ui.actViewByte);
viewMenu->addAction(ui.actViewText);
viewMenu->addAction(ui.actViewWord);
viewMenu->addAction(ui.actViewAddr);
cellMenu->addSeparator();
cellMenu->addAction(ui.actTraceHere);
cellMenu->addAction(ui.actShowLabels);
// NOTE: actions already connected to slots by main menu. no need to double it here
}
DebugWin::~DebugWin() {
delete(dumpwin);
delete(openDumpDialog);
delete(memViewer);
delete(memFiller);
delete(memFinder);
}
void DebugWin::setShowLabels(bool f) {
conf.dbg.labels = f ? 1 : 0;
fillDisasm();
}
void DebugWin::setShowSegment(bool f) {
conf.dbg.segment = f ? 1 : 0;
fillDisasm();
}
void DebugWin::setDumpCP() {
int cp = getRFIData(ui.cbCodePage);
ui.dumpTable->setCodePage(cp);
fillDump();
}
void DebugWin::chDumpView() {
int mode = getRFIData(ui.cbDumpView);
int page = ui.sbDumpPage->value();
ui.sbDumpPage->setDisabled(mode == XVIEW_CPU);
ui.dumpTable->setMode(mode, page);
}
void DebugWin::setDasmMode() {
int mode = getRFIData(ui.cbDasmMode);
int page = ui.sbDasmPage->value();
ui.sbDasmPage->setDisabled(mode == XVIEW_CPU);
ui.dasmTable->setMode(mode, page);
}
static QFile logfile;
void DebugWin::doStep() {
#ifdef ISDEBUG
QString str;
if (traceType == DBG_TRACE_LOG) {
#if 0
str = gethexword(comp->cpu->pc).append(" ");
str.append(QString("A:%0 ").arg(gethexbyte(comp->cpu->a)));
str.append(QString("X:%0 ").arg(gethexbyte(comp->cpu->lx)));
str.append(QString("Y:%0 ").arg(gethexbyte(comp->cpu->ly)));
str.append(QString("P:%0 ").arg(gethexbyte(comp->cpu->f)));
str.append(QString("SP:%0 ").arg(gethexbyte(comp->cpu->lsp)));
str.append(QString("CYC:%0").arg(comp->vid->ray.x));
logfile.write(str.toUtf8());
logfile.write("\r\n");
if (comp->cpu->pc == 0xc66e)
trace = 0;
#elif 1
for (int i = 0; i < 8; i++) {
printf("%.4X ", comp->cpu->preg[i]);
}
printf("%.4X\n", comp->cpu->pflag);
#endif
}
#endif
do {
tCount = comp->tickCount;
compExec(comp);
if (!fillAll()) {
disasmAdr = comp->cpu->pc;
fillDisasm();
}
switch(traceType) {
case DBG_TRACE_INT:
if (comp->cpu->intrq & comp->cpu->inten)
trace = 0;
break;
case DBG_TRACE_HERE:
if (comp->cpu->pc == traceAdr)
trace = 0;
break;
case DBG_TRACE_LOG:
for (int i = 0; i < 8; i++) {
printf("%.4X ", comp->cpu->preg[i]);
}
printf("%.4X\n", comp->cpu->pflag);
break;
}
QApplication::processEvents();
} while(trace);
// if (trace) {
//emit needStep();
//QTimer::singleShot(1,this,SLOT(doStep()));
//QApplication::processEvents();
// } else {
ui.tbTrace->setEnabled(true);
if (logfile.isOpen()) logfile.close();
// }
}
void DebugWin::doTraceHere() {
doTrace(ui.actTraceHere);
}
void DebugWin::doTrace(QAction* act) {
if (trace) return;
traceType = act->data().toInt();
if (traceType == DBG_TRACE_LOG) {
QString path = QFileDialog::getSaveFileName(this, "Log file");
if (path.isEmpty()) return;
logfile.setFileName(path);
if (!logfile.open(QFile::WriteOnly)) return;
}
trace = 1;
traceAdr = getAdr();
ui.tbTrace->setEnabled(false);
doStep();
}
void DebugWin::keyPressEvent(QKeyEvent* ev) {
if (trace) {
trace = 0;
return;
}
// if (ev->isAutoRepeat() && onStart) return;
// onStart = 0;
int i;
unsigned short pc = comp->cpu->pc;
unsigned char* ptr;
int offset = (ui.dumpTable->rows() - 1) << 3;
// QString com;
int row;
int pos;
int adr;
int len;
dasmData drow;
QModelIndex idx;
switch(ev->modifiers()) {
case Qt::ControlModifier:
switch(ev->key()) {
case Qt::Key_F:
doFind();
break;
case Qt::Key_S:
doSaveDump();
break;
case Qt::Key_O:
doOpenDump();
break;
case Qt::Key_T:
doTrace(ui.actTrace);
break;
case Qt::Key_L:
ui.actShowLabels->setChecked(!conf.dbg.labels);
break;
}
break;
case Qt::AltModifier:
switch (ev->key()) {
case Qt::Key_K:
emit wannaKeys();
break;
}
break;
default:
switch(ev->key()) {
case Qt::Key_Escape:
if (!ev->isAutoRepeat()) stop();
break;
case Qt::Key_Home:
disasmAdr = pc;
fillDisasm();
break;
case Qt::Key_End:
// if (!ui.dasmTable->hasFocus()) break;
adr = getAdr();
if (adr < 0) break;
comp->cpu->pc = adr & 0xffff;
comp->cpu->preg[7] = adr & 0xffff;
fillCPU();
fillDisasm();
break;
case Qt::Key_F2:
// switchBP(MEM_BRK_FETCH);
break;
case Qt::Key_F4:
idx = ui.dasmTable->currentIndex();
if (!idx.isValid()) break;
row = idx.row();
if (row < 0) break;
pos = ui.dasmTable->getData(row, 2, Qt::UserRole).toInt();
if (pos < 0) break;
jumpHistory.append(disasmAdr);
if (jumpHistory.size() > 64)
jumpHistory.takeFirst();
disasmAdr = pos;
fillDisasm();
break;
case Qt::Key_F5:
if (jumpHistory.size() == 0) break;
disasmAdr = jumpHistory.takeLast();
fillDisasm();
break;
case Qt::Key_PageUp:
if (ui.dumpTable->hasFocus()) {
dumpAdr = (dumpAdr - offset) & 0xffff;
fillDump();
} else if (ui.dasmTable->hasFocus()) {
for (i = 0; i < ui.dasmTable->rows() - 1; i++) {
disasmAdr = getPrevAdr(disasmAdr);
}
fillDisasm();
}
break;
case Qt::Key_PageDown:
if (ui.dumpTable->hasFocus()) {
dumpAdr = (dumpAdr + offset) & 0xffff;
fillDump();
} else if (ui.dasmTable->hasFocus()) {
disasmAdr = ui.dasmTable->getData(ui.dasmTable->rows() - 1, 0, Qt::UserRole).toInt();
fillDisasm();
}
break;
case Qt::Key_F3:
load_file(comp, NULL, FG_ALL, -1);
disasmAdr = comp->cpu->pc;
fillAll();
break;
case Qt::Key_F7:
doStep();
break;
case Qt::Key_F8:
// if (!ui.dasmTable->hasFocus()) break;
len = dasmSome(comp, comp->cpu->pc, drow);
if (drow.oflag & OF_SKIPABLE) {
ptr = getBrkPtr(comp, (comp->cpu->pc + len) & 0xffff);
*ptr ^= MEM_BRK_TFETCH;
stop();
} else {
doStep();
}
break;
case Qt::Key_F9:
if (!ui.dasmTable->hasFocus()) break;
idx = ui.dasmTable->currentIndex();
i = ui.dasmTable->getData(idx.row(), 0, Qt::UserRole).toInt() & 0xffff;
ptr = getBrkPtr(comp, i);
*ptr |= MEM_BRK_TFETCH;
stop();
break;
case Qt::Key_F12:
rzxStop(comp);
compReset(comp, RES_DEFAULT);
if (!fillAll()) {
disasmAdr = comp->cpu->pc;
fillDisasm();
}
break;
}
break;
}
}
void setSignal(QLabel* lab, int on) {
QString col(on ? "160,255,160" : "255,160,160");
// QString bld(on ? "font-weight:bold" : "");
lab->setStyleSheet(QString("background-color: rgb(%0)").arg(col));
}
QString getAYmix(aymChan* ch) {
QString res = ch->ten ? "T" : "-";
res += ch->nen ? "N" : "-";
res += ch->een ? "E" : "-";
return res;
}
void DebugWin::fillAY() {
aymChip* chp = comp->ts->chipA;
ui.leToneA->setText(gethexword(((chp->reg[0] << 8) | chp->reg[1]) & 0x0fff));
ui.leToneB->setText(gethexword(((chp->reg[2] << 8) | chp->reg[3]) & 0x0fff));
ui.leToneC->setText(gethexword(((chp->reg[4] << 8) | chp->reg[5]) & 0x0fff));
ui.leVolA->setText(gethexbyte(chp->chanA.vol));
ui.leVolB->setText(gethexbyte(chp->chanB.vol));
ui.leVolC->setText(gethexbyte(chp->chanC.vol));
ui.leMixA->setText(getAYmix(&chp->chanA));
ui.leMixB->setText(getAYmix(&chp->chanB));
ui.leMixC->setText(getAYmix(&chp->chanC));
ui.leToneN->setText(gethexbyte(chp->reg[6]));
ui.leEnvTone->setText(gethexword((chp->reg[11] << 8) | chp->reg[12]));
ui.leEnvForm->setText(gethexbyte(chp->reg[13]));
ui.leVolE->setText(gethexbyte(chp->chanE.vol));
ui.labLevA->setText(chp->chanA.lev ? "1" : "0");
ui.labLevB->setText(chp->chanB.lev ? "1" : "0");
ui.labLevC->setText(chp->chanC.lev ? "1" : "0");
ui.labLevN->setText(chp->chanN.lev ? "1" : "0");
}
bool DebugWin::fillAll() {
ui.labTcount->setText(QString("%0 / %1").arg(comp->tickCount - tCount).arg(comp->frmtCount));
fillCPU();
fillMem();
fillDump();
fillFDC();
fillGBoy();
drawNes();
fillAY();
ui.brkTab->update();
if (ui.scrLabel->isVisible())
updateScreen();
ui.labRX->setNum(comp->vid->ray.x);
if (comp->vid->hblank)
ui.labRX->setStyleSheet("background-color: rgb(255,160,160);");
else
ui.labRX->setStyleSheet("");
ui.labRY->setNum(comp->vid->ray.y);
if (comp->vid->vblank)
ui.labRY->setStyleSheet("background-color: rgb(255,160,160);");
else
ui.labRY->setStyleSheet("");
setSignal(ui.labDOS, comp->dos);
setSignal(ui.labROM, comp->rom);
setSignal(ui.labCPM, comp->cpm);
setSignal(ui.labINT, comp->cpu->intrq & comp->cpu->inten);
if (memViewer->isVisible())
memViewer->fillImage();
return fillDisasm();
}
// gameboy
extern xColor iniCol[4];
void drawGBTile(QImage& img, Video* vid, int x, int y, int adr) {
int row, bit;
int data;
unsigned char col;
xColor xcol;
for (row = 0; row < 8; row++) {
data = vid->ram[adr & 0x3fff] & 0xff;
adr++;
data |= (vid->ram[adr & 0x3fff] & 0xff) << 8;
adr++;
for (bit = 0; bit < 8; bit++) {
col = ((data & 0x80) ? 1 : 0) | ((data & 0x8000) ? 2 : 0);
xcol = iniCol[col];
img.setPixel(x + bit, y + row, qRgb(xcol.r, xcol.g, xcol.b));
data <<= 1;
}
}
}
QImage getGBTiles(Video* vid, int tset) {
int tadr = (tset & 1) ? 0x800 : 0;
if (tset & 2) tadr |= 0x2000;
int x,y;
QImage img(128, 128, QImage::Format_RGB888);
for (y = 0; y < 16; y++) {
for (x = 0; x < 16; x++) {
drawGBTile(img, vid, x << 3, y << 3, tadr);
tadr += 16;
}
}
return img.scaled(256,256);
}
QImage getGBMap(Video* vid, int tmap, int tset) {
QImage img(256, 256, QImage::Format_RGB888);
img.fill(qRgb(0,0,0));
int adr = tmap ? 0x1c00 : 0x1800;
int badr = (tset & 1) ? 0x800 : 0;
if (tset & 2) badr |= 0x2000;
int tadr;
unsigned char tile;
int x,y;
for (y = 0; y < 32; y++) {
for (x = 0; x < 32; x++) {
tile = vid->ram[adr & 0x1fff];
adr++;
tadr = badr;
if (tset & 1) {
tadr += (tile ^ 0x80) << 4;
} else {
tadr += tile << 4;
}
drawGBTile(img, vid, x << 3, y << 3, tadr);
}
}
return img;
}
QImage getGBPal(Video* gbv) {
QImage img(256,256,QImage::Format_RGB888);
img.fill(Qt::black);
int x,y;
int idx = 0;
xColor col;
QPainter pnt;
pnt.begin(&img);
for (y = 0; y < 16; y++) {
for (x = 0; x < 4; x++) {
col = gbv->pal[idx++];
pnt.fillRect((x << 6) + 1, (y << 4) + 1, 62, 14, QColor(col.r, col.g, col.b));
if (idx == 32) idx += 32;
}
}
pnt.end();
return img;
}
void DebugWin::fillGBoy() {
QImage img;
int tset = ui.sbTileset->value();
int tmap = ui.sbTilemap->value();
if (ui.rbTilesetView->isChecked()) {
img = getGBTiles(comp->vid, tset);
} else if (ui.rbTilemapView->isChecked()) {
img = getGBMap(comp->vid, tmap, tset);
} else {
img = getGBPal(comp->vid);
}
ui.gbImage->setPixmap(QPixmap::fromImage(img));
}
// nes
extern xColor nesPal[64];
void dbgNesConvertColors(Video* vid, unsigned char* buf, QImage& img, int trn) {
int x, y;
unsigned char col;
xColor xcol;
int adr = 0;
for (y = 0; y < 240; y++) {
for (x = 0; x < 256; x++) {
col = buf[adr];
if (!(col & 3)) col = 0;
col = vid->ram[0x3f00 | (col & 0x3f)];
xcol = nesPal[col & 0x3f];
if (!trn || (col & 3)) {
img.setPixel(x, y, qRgba(xcol.r, xcol.g, xcol.b, 0xff));
} else {
img.setPixel(x, y, Qt::transparent);
}
adr++;
}
}
}
QImage dbgNesScreenImg(Video* vid, unsigned short adr, unsigned short tadr) {
QImage img(256, 240, QImage::Format_ARGB32);
img.fill(Qt::black);
unsigned char scrmap[256 * 240];
memset(scrmap, 0x00, 256 * 240);
if (adr != 0) {
for(int y = 0; y < 240; y++) {
ppuRenderBGLine(vid, scrmap + (y << 8), adr, 0, tadr);
adr = ppuYinc(adr);
}
}
dbgNesConvertColors(vid, scrmap, img, 0);
return img;
}
QImage dbgNesSpriteImg(Video* vid, unsigned short tadr) {
QImage img(256, 240, QImage::Format_ARGB32);
img.fill(Qt::transparent);
unsigned char scrmap[256 * 240];
memset(scrmap, 0x00, 256 * 240);
for (int y = 0; y < 240; y++) {
ppuRenderSpriteLine(vid, y, scrmap + (y << 8), NULL, tadr, 64);
}
dbgNesConvertColors(vid, scrmap, img, 1);
return img;
}
void DebugWin::drawNes() {
unsigned short adr = 0;
unsigned short tadr = 0;
QImage img;
QPixmap pic;
ui.labVAdr->setText(gethexword(comp->vid->vadr & 0x7fff));
ui.labTAdr->setText(gethexword(comp->vid->tadr & 0x7fff));
switch(ui.nesScrType->itemData(ui.nesScrType->currentIndex()).toInt()) {
case NES_SCR_OFF: adr = 0; break;
case NES_SCR_0: adr = 0x2000; break;
case NES_SCR_1: adr = 0x2400; break;
case NES_SCR_2: adr = 0x2800; break;
case NES_SCR_3: adr = 0x2c00; break;
case NES_SCR_ALL: adr = 0xffff; break;
}
tadr = getRFIData(ui.nesBGTileset) & 0xffff;
QPainter pnt;
pic = QPixmap(256, 240);
if (adr != 0xffff) {
img = dbgNesScreenImg(comp->vid, adr, tadr);
pnt.begin(&pic);
pnt.drawImage(0,0,img);
pnt.end();
ui.nesScreen->setPixmap(pic);
} else {
pnt.begin(&pic);
pnt.drawImage(0, 0, dbgNesScreenImg(comp->vid, 0x2000, tadr).scaled(128, 120));
pnt.drawImage(128, 0, dbgNesScreenImg(comp->vid, 0x2400, tadr).scaled(128, 120));
pnt.drawImage(0, 120, dbgNesScreenImg(comp->vid, 0x2800, tadr).scaled(128, 120));
pnt.drawImage(128, 120, dbgNesScreenImg(comp->vid, 0x2c00, tadr).scaled(128, 120));
pnt.end();
ui.nesScreen->setPixmap(pic);
}
}
// ...
void DebugWin::setFlagNames(const char name[8]) {
ui.labF7->setText(QString(name[0]));
ui.labF6->setText(QString(name[1]));
ui.labF5->setText(QString(name[2]));
ui.labF4->setText(QString(name[3]));
ui.labF3->setText(QString(name[4]));
ui.labF2->setText(QString(name[5]));
ui.labF1->setText(QString(name[6]));
ui.labF0->setText(QString(name[7]));
}
void DebugWin::chLayout() {
switch (comp->cpu->type) {
case CPU_Z80:
ui.boxIM->setEnabled(true);
break;
case CPU_LR35902:
ui.boxIM->setEnabled(false);
break;
case CPU_6502:
ui.boxIM->setEnabled(false);
break;
default:
break;
}
}
void DebugWin::regClick(QMouseEvent* ev) {
xLabel* lab = (xLabel*)sender();
int id = lab->id;
if (id < 0) return;
if (id > 15) return;
CPU* cpu = comp->cpu;
xRegBunch bunch = cpuGetRegs(cpu);
xRegister reg = bunch.regs[id];
unsigned short val = reg.value;
switch (ev->button()) {
case Qt::RightButton:
dumpAdr = val;
fillDump();
break;
case Qt::LeftButton:
disasmAdr = val;
fillDisasm();
break;
default:
break;
}
}
// rzx
/*
void dbgSetRzxIO(QLabel* lab, Computer* comp, int pos) {
#ifdef HAVEZLIB
if (pos < comp->rzx.frm.size) {
lab->setText(gethexbyte(comp->rzx.frm.data[pos]));
} else {
lab->setText("--");
}
#endif
}
void DebugWin::fillRZX() {
ui.rzxFrm->setText(QString::number(comp->rzx.frame).append(" / ").append(QString::number(comp->rzx.size)));
ui.rzxFetch->setText(QString::number(comp->rzx.fetches));
ui.rzxFSize->setText(QString::number(comp->rzx.data[comp->rzx.frame].frmSize));
int pos = comp->rzx.pos;
dbgSetRzxIO(ui.rzxIO1, comp, pos++);
dbgSetRzxIO(ui.rzxIO2, comp, pos++);
dbgSetRzxIO(ui.rzxIO3, comp, pos++);
dbgSetRzxIO(ui.rzxIO4, comp, pos++);
dbgSetRzxIO(ui.rzxIO5, comp, pos);
}
*/
// fdc
void DebugWin::fillFDC() {
ui.fdcBusyL->setText(comp->dif->fdc->idle ? "0" : "1");
ui.fdcComL->setText(comp->dif->fdc->idle ? "--" : gethexbyte(comp->dif->fdc->com));
ui.fdcIrqL->setText(comp->dif->fdc->irq ? "1" : "0");
ui.fdcDrqL->setText(comp->dif->fdc->drq ? "1" : "0");
ui.fdcTrkL->setText(gethexbyte(comp->dif->fdc->trk));
ui.fdcSecL->setText(gethexbyte(comp->dif->fdc->sec));
ui.fdcHeadL->setText(comp->dif->fdc->side ? "1" : "0");
ui.fdcDataL->setText(gethexbyte(comp->dif->fdc->data));
ui.fdcStateL->setText(gethexbyte(comp->dif->fdc->state));
ui.fdcSr0L->setText(gethexbyte(comp->dif->fdc->sr0));
ui.fdcSr1L->setText(gethexbyte(comp->dif->fdc->sr1));
ui.fdcSr2L->setText(gethexbyte(comp->dif->fdc->sr2));
ui.flpCRC->setText(gethexword(comp->dif->fdc->crc));
ui.flpCurL->setText(QString('A' + comp->dif->fdc->flp->id));
ui.flpRdyL->setText(comp->dif->fdc->flp->insert ? "1" : "0");
ui.flpTrkL->setText(gethexbyte(comp->dif->fdc->flp->trk));
ui.flpPosL->setText(QString::number(comp->dif->fdc->flp->pos));
ui.flpIdxL->setText(comp->dif->fdc->flp->index ? "1" : "0");
ui.flpDataL->setText(comp->dif->fdc->flp->insert ? gethexbyte(flpRd(comp->dif->fdc->flp)): "--"); comp->dif->fdc->flp->rd = 0;
ui.flpMotL->setText(comp->dif->fdc->flp->motor ? "1" : "0");
}
// z80 regs section
void setCBFlag(QCheckBox* cb, int state) {
if ((cb->isChecked() && !state) || (!cb->isChecked() && state)) {
cb->setStyleSheet("background-color: rgb(160,255,160);");
} else {
cb->setStyleSheet("");
}
cb->setChecked(state);
}
void DebugWin::fillFlags() {
unsigned char flg = comp->cpu->f;
setCBFlag(ui.cbF7, flg & 0x80);
setCBFlag(ui.cbF6, flg & 0x40);
setCBFlag(ui.cbF5, flg & 0x20);
setCBFlag(ui.cbF4, flg & 0x10);
setCBFlag(ui.cbF3, flg & 0x08);
setCBFlag(ui.cbF2, flg & 0x04);
setCBFlag(ui.cbF1, flg & 0x02);
setCBFlag(ui.cbF0, flg & 0x01);
}
void setLEReg(QLineEdit* le, int num) {
QString txt = gethexword(num);
if (le->text() == txt) {
le->setStyleSheet("");
} else {
le->setStyleSheet("background-color: rgb(160,255,160);");
}
le->setText(txt);
}
void DebugWin::fillCPU() {
block = 1;
CPU* cpu = comp->cpu;
xRegBunch bunch = cpuGetRegs(cpu);
int i = 0;
while(dbgRegLabs[i] != NULL) {
switch (bunch.regs[i].id) {
case REG_EMPTY:
case REG_NONE:
dbgRegLabs[i]->clear();
dbgRegEdit[i]->setVisible(false);
dbgRegEdit[i]->clear();
break;
default:
dbgRegLabs[i]->setText(bunch.regs[i].name);
dbgRegEdit[i]->setProperty("regid", bunch.regs[i].id);
dbgRegEdit[i]->setMax(bunch.regs[i].byte ? 0xff : 0xffff);
dbgRegEdit[i]->setValue(bunch.regs[i].value);
dbgRegEdit[i]->setVisible(true);
break;
}
i++;
}
setFlagNames(bunch.flags);
ui.boxIM->setValue(cpu->imode);
ui.flagIFF1->setChecked(cpu->iff1);
ui.flagIFF2->setChecked(cpu->iff2);
fillFlags();
block = 0;
fillStack();
}
void DebugWin::setFlags() {
if (block) return;
unsigned char f = 0;
if (ui.cbF7->isChecked()) f |= 0x80;
if (ui.cbF6->isChecked()) f |= 0x40;
if (ui.cbF5->isChecked()) f |= 0x20;
if (ui.cbF4->isChecked()) f |= 0x10;
if (ui.cbF3->isChecked()) f |= 0x08;
if (ui.cbF2->isChecked()) f |= 0x04;
if (ui.cbF1->isChecked()) f |= 0x02;
if (ui.cbF0->isChecked()) f |= 0x01;
comp->cpu->f = f;
fillCPU();
fillDisasm();
}
void DebugWin::setCPU() {
if (block) return;
CPU* cpu = comp->cpu;
int i = 0;
int idx = 0;
xRegBunch bunch;
while (dbgRegEdit[idx] != NULL) {
if (dbgRegEdit[idx]->isEnabled()) {
bunch.regs[i].id = dbgRegEdit[idx]->property("regid").toInt();
bunch.regs[i].value = dbgRegEdit[idx]->getValue();
i++;
} else {
bunch.regs[i].id = REG_NONE;
}
idx++;
}
cpuSetRegs(cpu, bunch);
cpu->imode = ui.boxIM->value();
cpu->iff1 = ui.flagIFF1->isChecked() ? 1 : 0;
cpu->iff2 = ui.flagIFF2->isChecked() ? 1 : 0;
fillFlags();
fillStack();
fillDisasm();
}
// memory map section
QString getPageName(MemPage& pg) {
QString res;
switch(pg.type) {
case MEM_RAM: res = "RAM:"; break;
case MEM_ROM: res = "ROM:"; break;
case MEM_EXT: res = "EXT:"; break;
case MEM_SLOT: res = "SLT:"; break;
default: res = "---:"; break;
}
res.append(gethexbyte(pg.num >> 6));
return res;
}
void DebugWin::fillMem() {
ui.labPG0->setText(getPageName(comp->mem->map[0x00]));
ui.labPG1->setText(getPageName(comp->mem->map[0x40]));
ui.labPG2->setText(getPageName(comp->mem->map[0x80]));
ui.labPG3->setText(getPageName(comp->mem->map[0xc0]));
}
// labels
void DebugWin::dbgLLab() {loadLabels(NULL); fillDisasm();}
void DebugWin::dbgSLab() {saveLabels(NULL);}
/*
void DebugWin::loadLabels(QString path) {
if (path.isEmpty())
path = QFileDialog::getOpenFileName(this, "Load SJASM labels");
if (path.isEmpty())
return;
conf.labels.clear();
QString line;
QString name;
QStringList arr;
QFile file(path);
xAdr xadr;
if (file.open(QFile::ReadOnly)) {
while(!file.atEnd()) {
line = file.readLine();
arr = line.split(QRegExp("[: \r\n]"),QString::SkipEmptyParts);
if (arr.size() > 2) {
xadr.type = MEM_RAM;
xadr.bank = arr.at(0).toInt(NULL,16);
xadr.adr = arr.at(1).toInt(NULL,16) & 0x3fff;
xadr.abs = (xadr.bank << 14) | xadr.adr;
name = arr.at(2);
switch (xadr.bank) {
case 0xff:
xadr.type = MEM_ROM;
xadr.bank = -1;
break;
case 0x05:
xadr.adr |= 0x4000;
break;
case 0x02:
xadr.adr |= 0x8000;
break;
default:
xadr.bank = -1;
xadr.adr |= 0xc000;
break;
}
conf.labels[name] = xadr;
}
}
} else {
shitHappens("Can't open file");
}
}
void DebugWin::saveLabels() {
QString path = QFileDialog::getSaveFileName(this, "save SJASM labels");
if (path.isEmpty()) return;
QStringList keys;
QString key;
xAdr xadr;
QString line;
QFile file(path);
if (file.open(QFile::WriteOnly)) {
keys = conf.labels.keys();
foreach(key, keys) {
xadr = conf.labels[key];
line = (xadr.type == MEM_RAM) ? gethexbyte(xadr.bank) : "FF";
line.append(QString(":%0 %1\n").arg(gethexword(xadr.adr & 0x3fff)).arg(key));
file.write(line.toUtf8());
}
file.close();
} else {
shitHappens("Can't open file for writing");
}
}
*/
/*
QString findLabel(int adr, int type, int bank) {
QString lab;
if (!conf.dbg.labels)
return lab;
QString key;
xAdr xadr;
QStringList keys = conf.labels.keys();
foreach(key, keys) {
xadr = conf.labels[key];
if (!((xadr.adr ^ adr) & 0x3fff) \
&& ((type < 0) || (xadr.type < 0) || (type == xadr.type))\
&& ((bank < 0) || (xadr.bank < 0) || (bank == xadr.bank))) {
lab = key;
break;
}
}
return lab;
}
*/
// map
/*
void fwritepack(QDataStream& strm, unsigned char* data, int size) {
QByteArray pack = qCompress(data, size);
strm << pack;
}
void freadpack(QDataStream& strm, unsigned char* data, int maxsize) {
QByteArray pack;
strm >> pack;
QByteArray unpk = qUncompress(pack);
int size = unpk.size();
if (size > maxsize) size = maxsize;
memcpy(data, unpk.data(), size);
}
void strmLabels(QDataStream& strm) {
QStringList keys = conf.labels.keys();
QString key;
xAdr xadr;
foreach(key, keys) { // labels list
xadr = conf.labels[key];
strm << xadr.type;
strm << xadr.bank;
strm << xadr.adr;
strm << key;
}
strm << 0x00 << 0x00 << 0x00; // end of labels list
strm << QString();
}
void strdLabels(QDataStream& strm) {
xAdr xadr;
QString key;
conf.labels.clear();
do {
strm >> xadr.type;
strm >> xadr.bank;
strm >> xadr.adr;
strm >> key;
if (!key.isEmpty()) {
conf.labels[key] = xadr;
}
} while (!key.isEmpty());
}
#define XDBGVER 0x00
void DebugWin::saveMap() {
QString path = QFileDialog::getSaveFileName(this, "Save deBUGa project","","deBUGa project (*.xdbg)",NULL,QFileDialog::DontUseNativeDialog);
if (path.isEmpty()) return;
if (!path.endsWith(".xdbg",Qt::CaseInsensitive))
path.append(".xdbg");
QFile file(path);
if (file.open(QFile::WriteOnly)) {
QDataStream strm(&file);
#if 1
strm << QString("XDBG"); // [new] signature
strm << XDBGVER; // version
strmLabels(strm);
int bit = 3; // b0:ram cells, b1:rom cells, b2:slt cells
if (comp->slot->brkMap)
bit |= 4;
strm << bit;
fwritepack(strm, comp->brkRamMap, 0x400000);
fwritepack(strm, comp->brkRomMap, 0x80000);
if (bit & 4)
fwritepack(strm, comp->slot->brkMap, comp->slot->memMask + 1);
#else
strm << QString("deBUGa"); // signature
strmLabels(strm);
fwritepack(strm, comp->brkRamMap, 0x400000);
fwritepack(strm, comp->brkRomMap, 0x80000);
#endif
file.close();
}
}
void DebugWin::loadMap() {
QString path = QFileDialog::getOpenFileName(this, "Open deBUGa project","","deBUGa project (*.xdbg)");
if (path.isEmpty()) return;
QFile file(path);
QString key;
int bt;
if (file.open(QFile::ReadOnly)) {
QDataStream strm(&file);
strm >> key;
if (key == QString("deBUGa")) { // old data
strdLabels(strm);
freadpack(strm, comp->brkRamMap, 0x400000);
freadpack(strm, comp->brkRomMap, 0x400000);
} else if (key == QString("XDBG")) { // new data
strm >> bt;
if (bt > XDBGVER) {
shitHappens("Version mismatch");
} else {
strdLabels(strm);
strm >> bt;
memset(comp->brkRamMap, 0x00, 0x400000);
memset(comp->brkRomMap, 0x00, 0x80000);
if (comp->slot->brkMap) memset(comp->slot->brkMap, 0x00, comp->slot->memMask + 1);
if (bt & 1)
freadpack(strm, comp->brkRamMap, 0x400000);
if (bt & 2)
freadpack(strm, comp->brkRomMap, 0x80000);
if ((bt & 4) && comp->slot->brkMap)
freadpack(strm, comp->slot->brkMap, comp->slot->memMask + 1);
}
} else {
shitHappens("Wrong signature");
}
file.close();
brkInstallAll();
fillAll();
}
}
*/
// disasm table
unsigned char rdbyte(unsigned short adr, void* ptr) {
Computer* comp = (Computer*)ptr;
MemPage* pg = &comp->mem->map[adr >> 8];
unsigned char res = 0xff;
int fadr = (pg->num << 8) | (adr & 0xff);
switch (pg->type) {
case MEM_RAM: res = comp->mem->ramData[fadr & comp->mem->ramMask]; break;
case MEM_ROM: res = comp->mem->romData[fadr & comp->mem->romMask]; break;
case MEM_SLOT:
if (!comp->slot) break;
if (!comp->slot->data) break;
res = comp->slot->data[fadr & comp->slot->memMask]; break;
}
return res;
}
int checkCond(Computer* comp, int num) {
int res = 0;
unsigned char flg = comp->cpu->f;
switch (num) {
case 0: res = (flg & FZ) ? 0 : 1; break; // NZ
case 1: res = (flg & FZ) ? 1 : 0; break; // Z
case 2: res = (flg & FC) ? 0 : 1; break; // NC
case 3: res = (flg & FC) ? 1 : 0; break; // C
case 4: res = (flg & FP) ? 0 : 1; break; // PO
case 5: res = (flg & FP) ? 1 : 0; break; // PE
case 6: res = (flg & FS) ? 0 : 1; break; // N
case 7: res = (flg & FS) ? 1 : 0; break; // M
}
return res;
}
int getCommandSize(Computer* comp, unsigned short adr) {
int type = getBrk(comp, adr) & 0xf0;
unsigned char fl;
unsigned char bt;
char buf[256];
xMnem mn;
int res;
switch (type) {
case DBG_VIEW_BYTE:
res = 1;
break;
case DBG_VIEW_ADDR:
case DBG_VIEW_WORD:
res = 2;
break;
case DBG_VIEW_TEXT:
fl = getBrk(comp, adr);
bt = rdbyte(adr, comp);
res = 0;
while (((fl & 0xc0) == DBG_VIEW_TEXT) && (bt > 31) && (bt < 128) && (res < 250)) {
res++;
adr++;
bt = rdbyte(adr & 0xffff, comp);
fl = getBrk(comp, adr & 0xffff);
}
if (res == 0)
res++;
break;
case DBG_VIEW_CODE:
case DBG_VIEW_EXEC:
mn = cpuDisasm(comp->cpu, adr, buf, &rdbyte, comp);
res = mn.len;
break;
default:
res = 1;
break;
}
return res;
}
int DebugWin::fillDisasm() {
conf.dbg.hideadr = ui.actHideAddr->isChecked() ? 1 : 0;
return ui.dasmTable->updContent();
}
unsigned short DebugWin::getPrevAdr(unsigned short adr) {
for (int i = 16; i > 0; i--) {
if (getCommandSize(comp, adr - i) == i)
return adr - i;
}
return (adr - 1);
}
void DebugWin::saveDasm() {
QString path = QFileDialog::getSaveFileName(this, "Save disasm");
if (path.isEmpty()) return;
QFile file(path);
dasmData drow;
QList<dasmData> list;
if (file.open(QFile::WriteOnly)) {
QTextStream strm(&file);
unsigned short adr = (blockStart < 0) ? 0 : (blockStart & 0xffff);
unsigned short end = (blockEnd < 0) ? 0 : (blockEnd & 0xffff);
int work = 1;
strm << "; Created by Xpeccy deBUGa\n\n";
strm << "\tORG 0x" << gethexword(adr) << "\n\n";
while ((adr <= end) && work) {
// TODO: check equ $-e
list = getDisasm(comp, adr);
foreach (drow, list) {
if (adr < drow.adr) work = 0; // address overfill (FFFF+)
if (drow.isequ) {
strm << drow.aname << ":";
} else if (drow.islab) {
strm << drow.aname << ":\n";
}
strm << "\t" << drow.command << "\n";
}
}
file.close();
} else {
shitHappens("Can't write to file");
}
}
// memory dump
void DebugWin::fillDump() {
block = 1;
ui.dumpTable->update();
fillStack();
dumpChadr(ui.dumpTable->selectionModel()->currentIndex());
block = 0;
}
void DebugWin::dumpChadr(QModelIndex idx) {
int col = idx.column();
int adr = dumpAdr + (idx.row() << 3);
if ((col > 0) && (col < 9)) {
adr += (idx.column() - 1);
}
if (ui.dumpTable->mode != XVIEW_CPU)
adr &= 0x3fff;
ui.labDump->setText(QString("Dump : %0").arg(gethexword(adr & 0xffff)));
}
// maping
void DebugWin::mapClear() {
if (!areSure("Clear memory mapping?")) return;
int adr;
for (adr = 0; adr < 0x400000; adr++) {
comp->brkRamMap[adr] &= 0x0f;
if (adr < 0x80000) comp->brkRomMap[adr] &= 0x0f;
if (comp->slot->data && (adr <= comp->slot->memMask))
comp->slot->brkMap[adr] &= 0x0f;
}
fillDisasm();
}
void DebugWin::mapAuto() {
}
// stack
void DebugWin::fillStack() {
int adr = comp->cpu->sp;
QString str;
for (int i = 0; i < 4; i++) {
str.append(gethexbyte(rdbyte(adr+1, comp)));
str.append(gethexbyte(rdbyte(adr, comp)));
adr += 2;
}
ui.labSP->setText(str.left(4));
ui.labSP2->setText(str.mid(4,4));
ui.labSP4->setText(str.mid(8,4));
ui.labSP6->setText(str.mid(12,4));
}
// breakpoint
int DebugWin::getAdr() {
int adr = -1;
int col;
QModelIndex idx;
if (ui.dumpTable->hasFocus()) {
idx = ui.dumpTable->currentIndex();
col = idx.column();
adr = (dumpAdr + (idx.row() << 3)) & 0xffff;
if ((col > 0) && (col < 9)) {
adr += idx.column() - 1;
}
} else {
idx = ui.dasmTable->currentIndex();
adr = ui.dasmTable->getData(idx.row(), 0, Qt::UserRole).toInt();
}
return adr;
}
void DebugWin::putBreakPoint() {
int adr = getAdr();
if (adr < 0) return;
doBreakPoint(adr);
cellMenu->move(QCursor::pos());
cellMenu->show();
}
void DebugWin::doBreakPoint(unsigned short adr) {
bpAdr = adr;
unsigned char flag = getBrk(comp, adr);
ui.actFetch->setChecked(flag & MEM_BRK_FETCH);
ui.actRead->setChecked(flag & MEM_BRK_RD);
ui.actWrite->setChecked(flag & MEM_BRK_WR);
}
void DebugWin::chaCellProperty(QAction* act) {
int data = act->data().toInt();
int adr = getAdr();
int bgn, end;
// unsigned short eadr;
unsigned char bt;
unsigned char* ptr;
if ((adr < blockStart) || (adr > blockEnd)) { // pointer outside block : process 1 cell
bgn = adr;
end = adr;
} else { // pointer inside block : process all block
bgn = blockStart;
end = blockEnd;
}
// eadr = end & 0xffff; getDisasm(comp, eadr); end = (eadr-1) & 0xffff; // move end to last byte of block
if (end < bgn)
end += 0x10000;
adr = bgn;
while (adr <= end) {
ptr = getBrkPtr(comp, adr);
if (data & MEM_BRK_ANY) {
bt = 0;
if (ui.actFetch->isChecked()) bt |= MEM_BRK_FETCH;
if (ui.actRead->isChecked()) bt |= MEM_BRK_RD;
if (ui.actWrite->isChecked()) bt |= MEM_BRK_WR;
brkSet(BRK_MEMCELL, bt, adr, -1);
ui.bpList->update();
} else {
*ptr &= 0x0f;
if ((data & 0xf0) == DBG_VIEW_TEXT) {
bt = rdbyte(adr, comp);
if ((bt < 32) || (bt > 127)) {
*ptr |= DBG_VIEW_BYTE;
} else {
*ptr |= DBG_VIEW_TEXT;
}
} else {
*ptr |= (data & 0xf0);
}
}
adr++;
}
fillDisasm();
fillDump();
// fillBrkTable();
}
// memDump
void DebugWin::doSaveDump() {
dui.leBank->setText(QString::number(comp->mem->map[0xc0].num >> 6, 16));
dumpwin->show();
}
void DebugWin::dmpLimChanged() {
int start = dui.leStart->getValue();
int end = dui.leEnd->getValue();
if (end < start) end = start;
int len = end - start + 1;
start = dui.leEnd->cursorPosition();
dui.leEnd->setValue(end);
dui.leLen->setValue(len);
dui.leEnd->setCursorPosition(start);
}
void DebugWin::dmpLenChanged() {
int start = dui.leStart->getValue();
int len = dui.leLen->getValue();
if (start + len > 0x10000) {
len = 0x10000 - start;
dui.leLen->setValue(len);
}
int end = start + len - 1;
start = dui.leLen->cursorPosition();
dui.leEnd->setValue(end);
dui.leLen->setCursorPosition(start);
}
QByteArray DebugWin::getDumpData() {
int bank = dui.leBank->text().toInt(NULL,16);
int adr = dui.leStart->getValue();
int len = dui.leLen->getValue();
QByteArray res;
while (len > 0) {
if (adr < 0xc000) {
res.append(rdbyte(adr, comp));
} else {
res.append(comp->mem->ramData[(bank << 14) | (adr & 0x3fff)]);
}
adr++;
len--;
}
return res;
}
void DebugWin::saveDumpBin() {
QByteArray data = getDumpData();
if (data.size() == 0) return;
QString path = QFileDialog::getSaveFileName(this,"Save memory dump");
if (path.isEmpty()) return;
QFile file(path);
if (file.open(QFile::WriteOnly)) file.write(data);
dumpwin->hide();
}
void DebugWin::saveDumpHobeta() {
QByteArray data = getDumpData();
if (data.size() == 0) return;
QString path = QFileDialog::getSaveFileName(this,"Save memory dump as hobeta","","Hobeta files (*.$C)");
if (path.isEmpty()) return;
TRFile dsc;
QString name = dui.leStart->text();
name.append(".").append(dui.leBank->text());
std::string nms = name.toStdString();
nms.resize(8,' ');
memcpy(dsc.name,nms.c_str(),8);
dsc.ext = 'C';
int start = dui.leStart->getValue();
int len = data.size();
dsc.hst = (start >> 8) & 0xff;
dsc.lst = start & 0xff;
dsc.hlen = (len >> 8) & 0xff;
dsc.llen = len & 0xff;
dsc.slen = dsc.hlen + ((len & 0xff) ? 1 : 0);
saveHobeta(dsc, data.data(), path.toStdString().c_str());
dumpwin->hide();
}
void DebugWin::saveDumpToA() {saveDumpToDisk(0);}
void DebugWin::saveDumpToB() {saveDumpToDisk(1);}
void DebugWin::saveDumpToC() {saveDumpToDisk(2);}
void DebugWin::saveDumpToD() {saveDumpToDisk(3);}
void DebugWin::saveDumpToDisk(int idx) {
QByteArray data = getDumpData();
if (data.size() == 0) return;
if (data.size() > 0xff00) return;
int start = dui.leStart->getValue();
int len = dui.leLen->getValue();
QString name = dui.leStart->text();
name.append(".").append(dui.leBank->text());
Floppy* flp = comp->dif->fdc->flop[idx & 3];
if (!flp->insert) {
diskFormat(flp);
flp->insert = 1;
}
TRFile dsc = diskMakeDescriptor(name.toStdString().c_str(), 'C', start, len);
if (diskCreateFile(flp, dsc, (unsigned char*)data.data(), data.size()) == ERR_OK)
dumpwin->hide();
}
// memfinder
void DebugWin::doFind() {
memFinder->mem = comp->mem;
memFinder->adr = (disasmAdr + 1) & 0xffff;
memFinder->show();
}
void DebugWin::onFound(int adr) {
disasmAdr = adr & 0xffff;
fillDisasm();
}
// memfiller
void DebugWin::doFill() {
memFiller->start(comp->mem, blockStart, blockEnd);
}
// spr scanner
void DebugWin::doMemView() {
memViewer->mem = comp->mem;
memViewer->ui.sbPage->setValue(comp->mem->map[0xc0].num >> 6);
memViewer->fillImage();
memViewer->show();
}
// open dump
void DebugWin::doOpenDump() {
dumpPath.clear();
oui.laPath->clear();
oui.leBank->setText(QString::number(comp->mem->map[0xc0].num >> 6, 16));
oui.leStart->setText("4000");
openDumpDialog->show();
}
void DebugWin::chDumpFile() {
QString path = QFileDialog::getOpenFileName(this,"Open dump");
if (path.isEmpty()) return;
QFileInfo inf(path);
if ((inf.size() == 0) || (inf.size() > 0xff00)) {
shitHappens("File is too long");
} else {
dumpPath = path;
oui.laPath->setText(path);
oui.leLen->setText(QString::number(inf.size(),16));
dmpStartOpen();
}
}
void DebugWin::dmpStartOpen() {
int start = oui.leStart->text().toInt(NULL,16);
int len = oui.leLen->text().toInt(NULL,16);
int pos = oui.leStart->cursorPosition();
if (start + len > 0xffff)
start = 0x10000 - len;
int end = start + len - 1;
oui.leStart->setText(QString::number(start,16));
oui.leEnd->setText(QString::number(end,16));
oui.leStart->setCursorPosition(pos);
}
void DebugWin::loadDump() {
if (dumpPath.isEmpty()) return;
int res = loadDUMP(comp, dumpPath.toStdString().c_str(),oui.leStart->text().toInt(NULL,16));
fillAll();
if (res == ERR_OK) {
openDumpDialog->hide();
} else {
shitHappens("Can't open file");
}
}
// screen
void DebugWin::updateScreen() {
int flag = ui.cbScrAtr->isChecked() ? 1 : 0;
flag |= ui.cbScrPix->isChecked() ? 2 : 0;
flag |= ui.cbScrGrid->isChecked() ? 4 : 0;
vidGetScreen(comp->vid, scrImg.bits(), ui.sbScrBank->value(), ui.leScrAdr->getValue(), flag);
ui.scrLabel->setPixmap(QPixmap::fromImage(scrImg));
}
// breakpoints
void DebugWin::addBrk() {
brkManager->edit(NULL);
}
void DebugWin::editBrk() {
QModelIndexList idxl = ui.bpList->selectionModel()->selectedRows();
if (idxl.size() < 1) return;
int row = idxl.first().row();
xBrkPoint* brk = &conf.prof.cur->brkList[row];
brkManager->edit(brk);
}
void DebugWin::delBrk() {
QModelIndexList idxl = ui.bpList->selectionModel()->selectedRows();
qSort(idxl.begin(), idxl.end(), qGreater<QModelIndex>());
QModelIndex idx;
xBrkPoint brk;
foreach(idx, idxl) {
brk = conf.prof.cur->brkList[idx.row()];
brkDelete(brk);
}
ui.bpList->update();
fillDisasm();
fillDump();
}
void DebugWin::confirmBrk(xBrkPoint obrk, xBrkPoint brk) {
brkDelete(obrk);
brkAdd(brk);
fillDisasm();
fillDump();
ui.bpList->update();
}
void DebugWin::goToBrk(QModelIndex idx) {
if (!idx.isValid()) return;
int row = idx.row();
xBrkPoint brk = conf.prof.cur->brkList[row];
int adr;
int mtype = MEM_EXT;
switch(brk.type) {
case BRK_CPUADR:
adr = brk.adr & 0xffff;
break;
default:
switch(brk.type) {
case BRK_MEMRAM: mtype = MEM_RAM; break;
case BRK_MEMROM: mtype = MEM_ROM; break;
case BRK_MEMSLT: mtype = MEM_SLOT; break;
}
adr = memFindAdr(comp->mem, mtype, brk.adr);
break;
}
if (adr < 0) return;
disasmAdr = adr & 0xffff;
fillDisasm();
}
void DebugWin::saveBrk(QString path) {
if (path.isEmpty())
path = QFileDialog::getSaveFileName(this, "Save breakpoints", "", "deBUGa breakpoints (*.xbrk)");
if (path.isEmpty())
return;
if (!path.endsWith(".xbrk"))
path.append(".xbrk");
xBrkPoint brk;
QFile file(path);
QString nm,ar1,ar2,flag;
if (file.open(QFile::WriteOnly)) {
file.write("; Xpeccy deBUGa breakpoints list\n");
foreach(brk, conf.prof.cur->brkList) {
if (!brk.off) {
switch(brk.type) {
case BRK_IOPORT:
nm = "IO";
ar1 = gethexword(brk.adr & 0xffff);
ar2 = gethexword(brk.mask & 0xffff);
break;
case BRK_CPUADR:
nm = "CPU";
ar1 = gethexword(brk.adr & 0xffff);
ar2.clear();
break;
case BRK_MEMRAM:
nm = "RAM";
ar1 = gethexbyte((brk.adr >> 14) & 0xff); // 16K page
ar2 = gethexword(brk.adr & 0x3fff); // adr in page
break;
case BRK_MEMROM:
nm = "ROM";
ar1 = gethexbyte((brk.adr >> 14) & 0xff);
ar2 = gethexword(brk.adr & 0x3fff);
break;
case BRK_MEMSLT:
nm = "SLT";
ar1 = gethexbyte((brk.adr >> 14) & 0xff);
ar2 = gethexword(brk.adr & 0x3fff);
break;
default:
nm.clear();
break;
}
if (!nm.isEmpty()) {
flag.clear();
if (brk.fetch) flag.append("F");
if (brk.read) flag.append("R");
if (brk.write) flag.append("W");
file.write(QString("%0:%1:%2:%3\n").arg(nm).arg(ar1).arg(ar2).arg(flag).toUtf8());
}
}
}
file.close();
} else {
shitHappens("Can't open file for writing");
}
}
void DebugWin::openBrk() {
QString path = QFileDialog::getOpenFileName(this, "Open breakpoints list", "", "deBUGa breakpoints (*.xbrk)");
if (path.isEmpty()) return;
QFile file(path);
QString line;
QStringList list;
xBrkPoint brk;
bool b0,b1;
if (file.open(QFile::ReadOnly)) {
conf.prof.cur->brkList.clear();
while(!file.atEnd()) {
line = trUtf8(file.readLine());
if (!line.startsWith(";")) {
b0 = true;
b1 = true;
list = line.split(":", QString::KeepEmptyParts);
while(list.size() < 4)
list.append(QString());
brk.fetch = list.at(3).contains("F") ? 1 : 0;
brk.read = list.at(3).contains("R") ? 1 : 0;
brk.write = list.at(3).contains("W") ? 1 : 0;
if (list.at(0) == "IO") {
brk.type = BRK_IOPORT;
brk.adr = list.at(1).toInt(&b0, 16) & 0xffff;
brk.mask = list.at(2).toInt(&b1, 16) & 0xffff;
} else if (list.at(0) == "CPU") {
brk.type = BRK_CPUADR;
brk.adr = list.at(1).toInt(&b0, 16) & 0xffff;
} else if (list.at(0) == "ROM") {
brk.type = BRK_MEMROM;
brk.adr = (list.at(1).toInt(&b0, 16) & 0xff) << 14;
brk.adr |= (list.at(2).toInt(&b1, 16) & 0x3fff);
} else if (list.at(0) == "RAM") {
brk.type = BRK_MEMRAM;
brk.adr = (list.at(1).toInt(&b0, 16) & 0xff) << 14;
brk.adr |= (list.at(2).toInt(&b1, 16) & 0x3fff);
} else if (list.at(0) == "SLT") {
brk.type = BRK_MEMSLT;
brk.adr = (list.at(1).toInt(&b0, 16) & 0xff) << 14;
brk.adr |= (list.at(2).toInt(&b1, 16) & 0x3fff);
} else {
b0 = false;
}
if (b0 && b1) {
conf.prof.cur->brkList.push_back(brk);
}
}
}
file.close();
brkInstallAll();
ui.bpList->update();
fillDisasm();
fillDump();
} else {
shitHappens("Can't open file for reading");
}
}
|
/**
* Copyright (c) 2017-present, Facebook, Inc. and its affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "ZookeeperConfigSource.h"
#include <atomic>
#include <condition_variable>
#include <mutex>
#include <queue>
#include <thread>
#include <boost/multi_index/composite_key.hpp>
#include <boost/multi_index/hashed_index.hpp>
#include <boost/multi_index/identity.hpp>
#include <boost/multi_index/mem_fun.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index_container.hpp>
#include <folly/MapUtil.h>
#include <folly/Random.h>
#include "logdevice/common/ConstructorFailed.h"
#include "logdevice/common/ThreadID.h"
#include "logdevice/common/ZookeeperClient.h"
#include "logdevice/common/configuration/Configuration.h"
#include "logdevice/common/configuration/TextConfigUpdater.h"
#include "logdevice/common/debug.h"
#include "logdevice/include/Err.h"
namespace facebook { namespace logdevice {
using std::chrono::steady_clock;
class ZookeeperConfigSource::BackgroundThread {
public:
explicit BackgroundThread(std::chrono::milliseconds max_delay)
: max_delay_(max_delay) {
thread_ = std::thread(&BackgroundThread::run, this);
}
~BackgroundThread() {
stop();
}
void requestWithDelay(std::unique_ptr<const RequestContext> context) {
std::chrono::milliseconds delay(
folly::Random::rand64(0.75 * max_delay_.count(), max_delay_.count()));
ld_debug(context->with_data ? "Will fetch %s in %ld ms"
: "Will check %s for changes in %ld ms",
context->path.c_str(),
delay.count());
{
std::unique_lock<std::mutex> lock(bg_mutex_);
auto insert_result =
tasks_.insert(Task{steady_clock::now() + delay, std::move(context)});
if (!insert_result.second) {
// There was already a pending request for this quorum path, didn't add
// another.
return;
}
}
cv_.notify_one();
}
void stop() {
if (!stop_.exchange(true)) {
{
std::unique_lock<std::mutex> lock(bg_mutex_);
}
cv_.notify_one();
thread_.join();
}
}
private:
std::chrono::milliseconds max_delay_;
// Protects tasks_. ZookeeperConfigSource::mutex_ and
// BackgroundThread::bg_mutex_ are never held together by the same thread.
// The general rule is that methods in this file are called with
// no mutex held.
std::mutex bg_mutex_;
std::condition_variable cv_;
struct Task {
steady_clock::time_point when;
std::unique_ptr<const RequestContext> context;
bool operator<(const Task& task) const {
return when < task.when;
}
std::string getQuorum() const {
return context->quorum;
}
std::string getPath() const {
return context->path;
}
bool withData() const {
return context->with_data;
}
};
// A container for Tasks ordered by their scheduled time. It ensures that no
// two tasks with the same quorum, path, and with_data are in the container
// at the same time.
struct OrderedIndex {};
boost::multi_index::multi_index_container<
Task,
boost::multi_index::indexed_by<
boost::multi_index::ordered_non_unique<
boost::multi_index::tag<OrderedIndex>,
boost::multi_index::identity<Task>>,
boost::multi_index::hashed_unique<boost::multi_index::composite_key<
Task,
boost::multi_index::
const_mem_fun<Task, std::string, &Task::getQuorum>,
boost::multi_index::
const_mem_fun<Task, std::string, &Task::getPath>,
boost::multi_index::const_mem_fun<Task, bool, &Task::withData>>>>>
tasks_;
std::atomic<bool> stop_{false};
std::thread thread_;
void run() {
ThreadID::set(ThreadID::Type::UTILITY, "ld:zookeeper");
std::unique_lock<std::mutex> lock(bg_mutex_);
while (!stop_.load()) {
auto& index = tasks_.get<OrderedIndex>();
auto first_ready = [&]() {
return !index.empty() && index.begin()->when <= steady_clock::now();
};
if (tasks_.empty()) {
cv_.wait(lock);
} else if (!first_ready()) {
cv_.wait_until(lock, index.begin()->when);
}
while (!stop_.load() && first_ready()) {
std::unique_ptr<const RequestContext> context =
index.begin()->context->clone();
index.erase(index.begin());
// Avoid calling requestZnode() with locked bg_mutex_.
// requestZnode() may call requestWithDelay() which locks bg_mutex_.
lock.unlock();
context->parent->requestZnode(
context->quorum, context->path, context->with_data);
lock.lock();
}
}
}
};
ZookeeperConfigSource::ZookeeperConfigSource(
std::chrono::milliseconds polling_delay)
: polling_delay_(polling_delay) {}
Status ZookeeperConfigSource::getConfig(const std::string& quorum_path,
Output* /* out */) {
size_t pos = quorum_path.find('/');
if (pos == std::string::npos) {
ld_error("ZookeeperConfigSource path parameter must include quorum and "
"path, e.g. \"%s\". Received \"%s\"",
"1.2.3.4:2181,5.6.7.8:2181,9.10.11.12:2181/path/to/node",
quorum_path.c_str());
return E::INVALID_PARAM;
}
std::string quorum = quorum_path.substr(0, pos);
std::string path = quorum_path.substr(pos);
int rv = requestZnode(quorum, path, /* with_data */ true);
return rv == 0 ? E::NOTREADY : err;
}
int ZookeeperConfigSource::requestZnode(const std::string& quorum,
const std::string& path,
const bool with_data) {
ZookeeperClient* zkclient = getClient(quorum);
if (zkclient == nullptr) {
return -1;
}
std::unique_ptr<RequestContext> ctx(
new RequestContext(this, quorum, path, with_data));
{
std::lock_guard<std::mutex> guard(mutex_);
requests_in_flight_.push_back(*ctx);
}
std::shared_ptr<zhandle_t> zh = zkclient->getHandle();
// Callbacks bind to `this'; destructor disarms all callbacks so this is
// safe.
int rv;
if (with_data) {
rv = zoo_aget(zh.get(),
path.c_str(),
0, // no watch
dataCompletionCallback,
ctx.get());
} else {
rv = zoo_aexists(zh.get(),
path.c_str(),
0, // no watch,
statCompletionCallback,
ctx.get());
}
if (rv != 0) {
ld_error("%s(%s) failed with status %d",
with_data ? "zoo_aget" : "zoo_aexists",
path.c_str(),
rv);
if (rv == ZBADARGUMENTS) {
// Caller error, no point in retrying
err = E::INVALID_PARAM;
return -1;
} else {
// Some other failure, retry later
bgThread().requestWithDelay(std::move(ctx));
return 0;
}
}
// Owned by the inflight requests now
ctx.release();
return 0;
}
ZookeeperClient* ZookeeperConfigSource::getClient(const std::string& quorum) {
std::lock_guard<std::mutex> guard(mutex_);
auto it = zkclients_.find(quorum);
if (it == zkclients_.end()) {
try {
auto insert_result = zkclients_.emplace(
quorum,
std::make_unique<ZookeeperClient>(quorum, std::chrono::seconds(10)));
it = insert_result.first;
} catch (const ConstructorFailed&) {
ld_info("ZookeeperClient constructor failed with %s", error_name(err));
return nullptr;
}
}
return it->second.get();
}
void ZookeeperConfigSource::dataCompletionCallback(int rc,
const char* value,
int value_len,
const struct ::Stat* stat,
const void* context_void) {
std::unique_ptr<RequestContext> context(
static_cast<RequestContext*>(const_cast<void*>(context_void)));
ld_debug("path=%s rc=%d version=%d len=%d",
context->path.c_str(),
rc,
stat != nullptr ? stat->version : -1,
value_len);
ZookeeperConfigSource* self = context->parent;
{
std::lock_guard<std::mutex> guard(self->mutex_);
context->list_hook.unlink(); // from `requests_in_flight_'
};
if (rc != 0) {
RATELIMIT_ERROR(
std::chrono::seconds(1),
1,
"zoo_aget(%s) asynchronously failed with error code %d. Scheduling "
"retry.",
context->path.c_str(),
rc);
// Retry later
ld_check(context->with_data);
self->bgThread().requestWithDelay(std::move(context));
return;
}
{
std::lock_guard<std::mutex> guard(self->mutex_);
// Record the delivered version for polling
self->delivered_versions_[context->quorum + context->path] = stat->version;
}
Output out;
out.contents = std::string(value, value_len);
// Zookeeper's mtime is in milliseconds
out.mtime = std::chrono::milliseconds(stat->mtime);
// `out.hash' stays clear, we don't have a good hash to supply
self->async_cb_->onAsyncGet(
self, context->quorum + context->path, E::OK, std::move(out));
// Kick off polling (schedule a light version check)
context->with_data = false;
self->bgThread().requestWithDelay(std::move(context));
}
void ZookeeperConfigSource::statCompletionCallback(int rc,
const struct ::Stat* stat,
const void* context_void) {
std::unique_ptr<RequestContext> context(
static_cast<RequestContext*>(const_cast<void*>(context_void)));
ld_debug("path=%s rc=%d version=%d",
context->path.c_str(),
rc,
stat != nullptr ? stat->version : -1);
ZookeeperConfigSource* self = context->parent;
int64_t delivered_version;
{
std::lock_guard<std::mutex> guard(self->mutex_);
context->list_hook.unlink(); // from `requests_in_flight_'
delivered_version = folly::get_default(
self->delivered_versions_, context->quorum + context->path, -1);
};
if (rc != 0) {
RATELIMIT_ERROR(
std::chrono::seconds(1),
1,
"zoo_aexists(%s) asynchronously failed with error code %d. Scheduling "
"retry.",
context->path.c_str(),
rc);
// Retry later
ld_check(!context->with_data);
self->bgThread().requestWithDelay(std::move(context));
return;
}
if (stat->version != delivered_version) {
ld_info("Polling detected change to znode %s (new version %d,"
" last delivered %ld), requesting data",
context->path.c_str(),
stat->version,
delivered_version);
self->requestZnode(context->quorum, context->path, /* with_data */ true);
} else {
ld_debug("Already delivered version %ld", delivered_version);
// Continue polling
ld_check(!context->with_data);
self->bgThread().requestWithDelay(std::move(context));
}
}
ZookeeperConfigSource::~ZookeeperConfigSource() {
if (bg_thread_) {
bg_thread_->stop();
}
// Tear down the ZK clients to ensure callbacks are disarmed before starting
// to tear down members
zkclients_.clear();
requests_in_flight_.clear_and_dispose(std::default_delete<RequestContext>());
}
ZookeeperConfigSource::BackgroundThread& ZookeeperConfigSource::bgThread() {
std::lock_guard<std::mutex> guard(mutex_);
if (!bg_thread_) {
ld_debug("Initializing BackgroundThread");
bg_thread_ = std::make_unique<BackgroundThread>(polling_delay_);
}
return *bg_thread_;
}
}} // namespace facebook::logdevice
|
class Solution {
public:
bool isInterleave(string s1, string s2, string s3) {
if (s1.size() + s2.size() != s3.size()) return false;
int len1 = s1.size();
int len2 = s2.size();
vector<vector<bool>> check(len1+1, vector<bool>(len2+1, false));
for (int i = 0; i <= len1; i ++)
{
for (int j = 0; j <= len2; j ++)
{
if (i == 0 && j == 0) check[i][j] = true;
else if (i == 0)
check[i][j] = check[i][j-1] && s2[j-1] == s3[j-1];
else if (j == 0)
check[i][j] = check[i-1][j] && s1[i-1] == s3[i-1];
else
check[i][j] = (check[i-1][j] && s1[i-1] == s3[i-1+j]) || (check[i][j-1] && s2[j-1] == s3[i+j-1]);
}
}
return check[len1][len2];
}
};
|
// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++, C#, and Java: http://www.viva64.com
/*
* MIT License (http://www.opensource.org/licenses/mit-license.php)
*
* Copyright (c) 2021, Viachaslau Tratsiak (aka restorer)
*
* 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 "machine.h"
#include "devices/border_device.h"
#include "devices/covox_device.h"
#include "devices/extport_device.h"
#include "devices/kempston_joystick_device.h"
#include "devices/kempston_mouse_device.h"
#include "devices/zx_keyboard_device.h"
#include "devices/memory_device.h"
#include "devices/trdos_device.h"
#include "devices/zxm_device.h"
namespace zemux {
Machine::Machine() : bus { this, &cpuChronometer }, cpu { &bus,
&Bus::onCpuMreqRd,
&Bus::onCpuMreqWr,
&Bus::onCpuIorqRd,
&Bus::onCpuIorqWr,
&Bus::onCpuIorqM1,
&Bus::onCpuPutAddress } {
brazeDevice(Device::KindMemory, std::make_unique<MemoryDevice>(&bus));
brazeDevice(Device::KindBorder, std::make_unique<BorderDevice>(&bus, &soundDesk));
brazeDevice(Device::KindZxKeyboard, std::make_unique<ZxKeyboardDevice>(&bus));
brazeDevice(Device::KindKempstonJoystick, std::make_unique<KempstonJoystickDevice>(&bus));
brazeDevice(Device::KindKempstonMouse, std::make_unique<KempstonMouseDevice>(&bus));
brazeDevice(Device::KindCovox, std::make_unique<CovoxDevice>(&bus, &soundDesk));
brazeDevice(Device::KindZxm, std::make_unique<ZxmDevice>(&bus, &soundDesk));
brazeDevice(Device::KindTrDos, std::make_unique<TrDosDevice>(&bus));
brazeDevice(Device::KindExtPort, std::make_unique<ExtPortDevice>(&bus));
deviceMap[Device::KindMemory]->onAttach();
deviceMap[Device::KindBorder]->onAttach();
deviceMap[Device::KindZxKeyboard]->onAttach();
deviceMap[Device::KindKempstonJoystick]->onAttach();
deviceMap[Device::KindKempstonMouse]->onAttach();
deviceMap[Device::KindCovox]->onAttach();
deviceMap[Device::KindZxm]->onAttach();
deviceMap[Device::KindTrDos]->onAttach();
deviceMap[Device::KindExtPort]->onAttach();
onBusReconfigure();
onBusReset();
}
void Machine::renderFrame() {
// TODO: ...
auto frameTicks = cpuChronometer.getSrcTicksPassed();
for (auto& device : attachedDevices) {
device->onFrameFinished(frameTicks);
}
cpuChronometer.srcConsume(frameTicks);
}
void Machine::brazeDevice(Device::DeviceKind kind, std::unique_ptr<Device> device) {
deviceMap[kind] = std::move(device);
if (device->getEventCategory()) {
eventListenerMap[device->getEventCategory()] = device.get();
}
}
void Machine::onBusReconfigure() {
attachedDevices.clear();
for (auto& entry : deviceMap) {
auto* device = entry.second.get();
if (device->isAttached()) {
attachedDevices.push_back(device);
}
}
for (auto& device : attachedDevices) {
device->onConfigureTimings(ulaFrameTicks);
}
bus.onMachineReconfigure(attachedDevices);
}
void Machine::onBusReset() {
bus.onMachineReset();
cpu.reset();
for (auto& device : attachedDevices) {
device->onReset();
}
}
}
|
/// \file delegate.hpp
/// \brief Classes and functions that implement delegate.
/// \bug No known bugs.
#ifndef DELEGATE_HPP
#define DELEGATE_HPP
#include <algorithm>
#include <list>
/// Contains classes and functions that extend the C++ STL.
namespace stdex {
/// Non-specialized template class that implements delegate base.
/// \tparam T Object type.
template <typename T>
class delegate_base;
/// Template class that implements delegate base.
/// \tparam R Return type.
/// \tparam P Argument type.
template <typename R, typename ...P>
class delegate_base<R(P...)> {
protected:
/// Callback function type.
using function_type = R(*)(void*, P...);
/// Internal class that stores pointers to an object and a function.
class invocation final {
public:
/// Constructor without arguments.
invocation() noexcept
: object_(nullptr), function_(nullptr) {
}
/// Constructor with pointers to an object and a function.
/// \param object Object pointer.
/// \param function Function pointer.
invocation(void* object, const function_type function) noexcept
: object_(object), function_(function) {
}
/// Boolean operator.
/// \return True if function pointer is not null and false
/// otherwise.
explicit operator bool() const noexcept {
return !empty();
}
/// Equality operator.
/// \return True if function pointer is null and false otherwise.
bool operator==(std::nullptr_t) const noexcept {
return empty();
}
/// Equality operator.
/// \return True if function pointer is not null and false
/// otherwise.
bool operator!=(std::nullptr_t) const noexcept {
return !(*this == nullptr);
}
/// Equality operator.
/// \param object Object to compare.
/// \return True if objects are equal and false otherwise.
bool operator==(const invocation& object) const noexcept {
return object_ == object.object_ &&
function_ == object.function_;
}
/// Equality operator.
/// \param object Object to compare.
/// \return True if objects aren't equal and false otherwise.
bool operator!=(const invocation& object) const noexcept {
return !(*this == object);
}
/// Indicates if function pointer is null.
/// \return True if function pointer is null and false otherwise.
bool empty() const noexcept {
return function_ == nullptr;
}
/// Returns a pointer to an object.
/// \return Pointer to an object.
void* object() const noexcept {
return object_;
}
/// Returns a pointer to a function.
/// \return Pointer to a function.
function_type function() const noexcept {
return function_;
}
private:
/// Pointer to an object.
void* object_;
/// Pointer to a function.
function_type function_;
};
};
/// Non-specialized template class that implements delegate.
/// \tparam T Object type.
template <typename T>
class delegate;
/// Non-specialized template class that implements multicast delegate.
/// \tparam T Object type.
template <typename T>
class multidelegate;
/// Template class that implements delegate.
/// \tparam R Return type.
/// \tparam P Parameter type.
template <typename R, typename ...P>
class delegate<R(P...)> final : delegate_base<R(P...)> {
public:
/// Constructor without arguments.
delegate() noexcept : invocation_() {
}
/// Constructor with the lambda object.
/// \tparam L Lambda type.
/// \param object Object.
template <typename L>
delegate(const L& object) noexcept
: invocation_() {
*this = object;
}
/// Assignment operator with the lambda object.
/// \tparam L Lambda type.
/// \param object Object.
/// \return This object.
template <typename L>
delegate& operator=(const L& object) noexcept {
invocation_ = typename delegate_base<R(P...)>::invocation(
(void*) (&object), lambda < L > );
return *this;
}
/// Boolean operator.
/// \return True if function pointer is not null and false otherwise.
explicit operator bool() const noexcept {
return !empty();
}
/// Equality operator.
/// \return True if function pointer is null and false otherwise.
bool operator==(std::nullptr_t) const noexcept {
return empty();
}
/// Equality operator.
/// \return True if function pointer is not null and false otherwise.
bool operator!=(std::nullptr_t) const noexcept {
return !(*this == nullptr);
}
/// Equality operator.
/// \param object Object to compare.
/// \return True if objects are equal and false otherwise.
bool operator==(const delegate& object) const noexcept {
return invocation_ == object.invocation_;
}
/// Equality operator.
/// \param object Object to compare.
/// \return True if objects aren't equal and false otherwise.
bool operator!=(const delegate& object) const noexcept {
return !(*this == object);
}
/// Equality operator.
/// \param object Object to compare.
/// \return True if objects are equal and false otherwise.
bool operator==(const multidelegate<R(P...)>& object) const noexcept {
return object == *this;
}
/// Equality operator.
/// \param object Object to compare.
/// \return True if objects aren't equal and false otherwise.
bool operator!=(const multidelegate<R(P...)>& object) const noexcept {
return object != *this;
}
/// Function call operator.
/// \param arg Possible arguments of the function.
/// \return Return value of the function.
R operator()(P... arg) const {
return (*invocation_.function())(invocation_.object(), arg...);
}
/// Indicates if function pointer is null.
/// \return True if function pointer is null and false otherwise.
bool empty() const noexcept {
return !invocation_;
}
/// Returns a delegate that points to a member function.
/// \tparam T Object type.
/// \tparam M Member function.
/// \param object Object.
/// \return Delegate that points to a member function.
template <typename T, R(T::*M)(P...)>
static delegate create(T& object) noexcept {
return delegate(&object, method < T, M > );
}
/// Returns a delegate that points to a const member function.
/// \tparam T Object type.
/// \tparam M Const member function.
/// \param object Object.
/// \return Delegate that points to a const member function.
template <typename T, R(T::*M)(P...) const>
static delegate create(const T& object) noexcept {
return delegate(const_cast<T*>(&object), const_method < T, M > );
}
/// Returns a delegate that points to a free function.
/// \tparam M Free function.
/// \return Delegate that points to a free function.
template <R(* M)(P...)>
static delegate create() noexcept {
return delegate(nullptr, free_function < M > );
}
/// Returns a delegate that points to a lambda function.
/// \tparam L Lambda type.
/// \param object Object.
/// \return Delegate that points to a lambda function.
template <typename L>
static delegate create(const L& object) noexcept {
return delegate(&object, lambda < L > );
}
/// Returns a delegate that points to a member function.
/// \tparam T Object type.
/// \tparam M Member function.
/// \param object Object pointer.
/// \return Delegate that points to a member function.
template <typename T, R(T::*M)(P...)>
static delegate create(T* object) noexcept {
return delegate(object, method < T, M > );
}
/// Returns a delegate that points to a const member function.
/// \tparam T Object type.
/// \tparam M Const member function.
/// \param object Object pointer.
/// \return Delegate that points to a const member function.
template <typename T, R(T::*M)(P...) const>
static delegate create(const T* object) noexcept {
return delegate(const_cast<T*>(object), const_method < T, M > );
}
private:
/// Constructor with the pointers to an object an a function.
/// \param object Object.
/// \param function Function.
delegate(void* object,
typename delegate_base<R(P...)>::function_type function)
noexcept : invocation_(object, function) {
}
/// Called a member function with the specified arguments.
/// \tparam T Object type.
/// \tparam M Member function.
/// \param object Object.
/// \param args Arguments.
/// \return Return value of the function.
template <typename T, R(T::*M)(P...)>
static R method(void* object, P... args) {
return (static_cast<T*>(object)->*M)(args...);
}
/// Calls a const member function with the specified arguments.
/// \tparam T Object type.
/// \tparam M Const member function.
/// \param object Object.
/// \param args Arguments.
/// \return Return value of the function.
template <typename T, R(T::*M)(P...) const>
static R const_method(void* object, P... args) {
return (static_cast<const T*>(object)->*M)(args...);
}
/// Calls a free function with the specified arguments.
/// \tparam M Free function.
/// \param object Object.
/// \param args Arguments.
/// \return Return value of the function.
template <R(* M)(P...)>
static R free_function(void* object, P... args) {
return (M)(args...);
}
/// Calls a lambda function with the specified arguments.
/// \tparam L Lambda type.
/// \param object Object.
/// \param args Arguments.
/// \return Return value of the function.
template <typename L>
static R lambda(void* object, P... args) {
return (static_cast<L*>(object)->operator())(args...);
}
/// Storage of the pointers to an object and a function.
typename delegate_base<R(P...)>::invocation invocation_;
/// Friend class multicast delegate for member access.
friend class multidelegate<R(P...)>;
};
/// Template class that implements multicast delegate.
/// \tparam R Return type.
/// \tparam P Parameter type.
template <typename R, typename ...P>
class multidelegate<R(P...)> final : delegate_base<R(P...)> {
public:
/// Container type.
using container_type =
typename std::list<typename delegate_base<R(P...)>::invocation>;
/// Container size type.
using size_type = typename container_type::size_type;
/// Constructor without arguments.
multidelegate() noexcept
: invocations_() {
}
/// Boolean operator.
/// \return True if invocations is not empty and false otherwise.
explicit operator bool() const noexcept {
return !empty();
}
/// Equality operator.
/// \return True if invocations is empty and false otherwise.
bool operator==(std::nullptr_t) const noexcept {
return empty();
}
/// Equality operator.
/// \return True if invocations is not empty and false otherwise.
bool operator!=(std::nullptr_t) const noexcept {
return !(*this == nullptr);
}
/// Equality operator.
/// \param object Object to compare.
/// \return True if objects are equal and false otherwise.
bool operator==(const multidelegate& object) const noexcept {
return invocations_ == object.invocations_;
}
/// Equality operator.
/// \param object Object to compare.
/// \return True if objects aren't equal and false otherwise.
bool operator!=(const multidelegate& object) const noexcept {
return !(*this == object);
}
/// Equality operator.
/// \param object Object to compare.
/// \return True if objects are equal and false otherwise.
bool operator==(const delegate<R(P...)>& object) const noexcept {
if (!(*this) && !object) return true;
if (size() != 1 || !object) return false;
return object.invocation_ == invocations_.front();
}
/// Equality operator.
/// \param object Object to compare.
/// \return True if objects aren't equal and false otherwise.
bool operator!=(const delegate<R(P...)>& object) const noexcept {
return !(*this == object);
}
/// Adds delegate to the queue.
/// \param object Multicast delegate to add.
/// \return This object.
multidelegate& operator+=(const multidelegate& object) {
for (const auto& invocation : object.invocations_)
invocations_.push_back(invocation);
return *this;
}
/// Adds delegate to the queue.
/// \param object Delegate to add.
/// \return This object.
multidelegate& operator+=(const delegate<R(P...)>& object) {
if (object) invocations_.push_back(object.invocation_);
return *this;
}
/// Removes delegate from the queue.
/// \param object Multicast delegate to remove.
/// \return This object.
multidelegate& operator-=(const multidelegate& object) {
for (const auto& invocation : object.invocations_) {
auto iterator = std::find(invocations_.begin(),
invocations_.end(), invocation);
if (iterator != invocations_.end())
invocations_.erase(iterator);
}
return *this;
}
/// Removes delegate from the queue.
/// \param object Delegate to remove.
/// \return This object.
multidelegate& operator-=(const delegate<R(P...)>& object) {
auto iterator = std::find(invocations_.begin(),
invocations_.end(), object.invocation_);
if (iterator != invocations_.end())
invocations_.erase(iterator);
return *this;
}
/// Function call operator.
/// The returned parameters are ignored.
/// \param args Possible arguments of the functions.
void operator()(P... args) const {
for (const auto& invocation : invocations_)
(*invocation.function())(invocation.object(), args...);
}
/// Function call operator.
/// The returned parameters are handled by callback handler.
/// \tparam H Handler type.
/// \param args Possible arguments of the functions.
/// \param handler Callback handler.
template <typename H>
void operator()(P... args, H handler) const {
size_type index { 0 };
for (const auto& invocation : invocations_) {
R item = (*invocation.function())(invocation.object(), args...);
handler(index++, &item);
}
}
/// Indicates if invocations is empty.
/// \return True if invocations is empty and false otherwise.
bool empty() const noexcept {
return invocations_.empty();
}
/// Returns the queue size.
/// \return Queue size.
size_type size() const noexcept {
return invocations_.size();
}
/// Clears the queue.
void clear() noexcept {
invocations_.clear();
}
private:
/// Storage of the invocations.
container_type invocations_;
};
}
#endif
|
/*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2020 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
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 "stdafx.h"
#include "FELinearSystem.h"
#include "FELinearConstraintManager.h"
#include "FEModel.h"
//-----------------------------------------------------------------------------
FELinearSystem::FELinearSystem(FESolver* solver, FEGlobalMatrix& K, vector<double>& F, vector<double>& u, bool bsymm) : m_K(K), m_F(F), m_u(u), m_solver(solver)
{
m_bsymm = bsymm;
}
//-----------------------------------------------------------------------------
FELinearSystem::~FELinearSystem()
{
}
//-----------------------------------------------------------------------------
// get symmetry flag
bool FELinearSystem::IsSymmetric() const
{
return m_bsymm;
}
//-----------------------------------------------------------------------------
// Get the solver that is using this linear system
FESolver* FELinearSystem::GetSolver()
{
return m_solver;
}
//-----------------------------------------------------------------------------
//! assemble global stiffness matrix
void FELinearSystem::Assemble(const FEElementMatrix& ke)
{
if ((ke.rows() == 0) || (ke.columns() == 0)) return;
// assemble into the global stiffness
m_K.Assemble(ke);
// check the prescribed contributions
SparseMatrix& K = m_K;
int N = ke.rows();
int neq = m_K.Rows();
// loop over columns
const vector<int>& lmi = ke.RowIndices();
const vector<int>& lmj = ke.ColumnsIndices();
for (int j = 0; j<N; ++j)
{
int J = -lmj[j] - 2;
if ((J >= 0) && (J<neq))
{
// dof j is a prescribed degree of freedom
// loop over rows
for (int i = 0; i<N; ++i)
{
int I = lmi[i];
if (I >= 0)
{
// dof i is not a prescribed degree of freedom
#pragma omp atomic
m_F[I] -= ke[i][j] * m_u[J];
}
}
// set the diagonal element of K to 1
K.set(J, J, 1);
}
}
#pragma omp critical
{
FEModel* fem = m_solver->GetFEModel();
FELinearConstraintManager& LCM = fem->GetLinearConstraintManager();
if (LCM.LinearConstraints())
{
const vector<int>& en = ke.Nodes();
LCM.AssembleStiffness(m_K, m_F, m_u, en, lmi, lmj, ke);
}
} // omp critical
}
//-----------------------------------------------------------------------------
void FELinearSystem::AssembleRHS(vector<int>& lm, matrix& ke, vector<double>& U)
{
int ne = (int)lm.size();
for (int j = 0; j<ne; ++j)
{
if (lm[j] >= 0)
{
double q = 0;
for (int k = 0; k<ne; ++k)
{
if (lm[k] >= 0) q += ke[j][k] * U[lm[k]];
else if (-lm[k] - 2 >= 0) q += ke[j][k] * U[-lm[k] - 2];
}
m_F[lm[j]] += q;
}
}
}
//-----------------------------------------------------------------------------
void FELinearSystem::AssembleRHS(vector<int>& lm, vector<double>& fe)
{
const int n = (int)lm.size();
for (int i = 0; i<n; ++i)
{
int nid = lm[i];
if (nid >= 0)
{
m_F[nid] += fe[i];
}
}
}
|
// Copyright 2019 The Fuchsia 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 "ftdi-i2c.h"
#include <fuchsia/hardware/ftdi/llcpp/fidl.h>
#include <fuchsia/hardware/serialimpl/cpp/banjo.h>
#include <lib/fake_ddk/fake_ddk.h>
#include <stdio.h>
#include <list>
#include <ddk/debug.h>
#include <zxtest/zxtest.h>
#include "ftdi.h"
namespace ftdi_mpsse {
// Fake for the raw nand protocol.
class FakeSerial : public ddk::SerialImplProtocol<FakeSerial> {
public:
FakeSerial() : proto_({&serial_impl_protocol_ops_, this}) {}
const serial_impl_protocol_t* proto() const { return &proto_; }
void PushExpectedRead(std::vector<uint8_t> read) { expected_reads_.push_back(std::move(read)); }
void PushExpectedWrite(std::vector<uint8_t> write) {
expected_writes_.push_back(std::move(write));
}
void FailOnUnexpectedReadWrite(bool b) { unexpected_is_error_ = b; }
zx_status_t SerialImplGetInfo(serial_port_info_t* out_info) { return ZX_OK; }
zx_status_t SerialImplConfig(uint32_t baud_rate, uint32_t flags) { return ZX_OK; }
zx_status_t SerialImplEnable(bool enable) { return ZX_OK; }
zx_status_t SerialImplRead(uint8_t* out_buf_buffer, size_t buf_size, size_t* out_buf_actual) {
uint8_t* out_buf = out_buf_buffer;
if (expected_reads_.size() == 0) {
if (unexpected_is_error_) {
printf("Read with no expected read set\n");
return ZX_ERR_INTERNAL;
} else {
*out_buf_actual = buf_size;
return ZX_OK;
}
}
std::vector<uint8_t>& read = expected_reads_.front();
if (buf_size != read.size()) {
printf("Read size mismatch (%lx != %lx\n", buf_size, read.size());
return ZX_ERR_INTERNAL;
}
for (size_t i = 0; i < buf_size; i++) {
out_buf[i] = read[i];
}
expected_reads_.pop_front();
*out_buf_actual = buf_size;
return ZX_OK;
}
zx_status_t SerialImplWrite(const uint8_t* buf_buffer, size_t buf_size, size_t* out_actual) {
const uint8_t* out_buf = buf_buffer;
if (expected_writes_.size() == 0) {
if (unexpected_is_error_) {
printf("Write with no expected wrte set\n");
return ZX_ERR_INTERNAL;
} else {
*out_actual = buf_size;
return ZX_OK;
}
}
std::vector<uint8_t>& write = expected_writes_.front();
if (buf_size != write.size()) {
printf("Write size mismatch (0x%lx != 0x%lx\n", buf_size, write.size());
return ZX_ERR_INTERNAL;
}
for (size_t i = 0; i < buf_size; i++) {
if (out_buf[i] != write[i]) {
printf("Write data mismatch index %ld (0x%x != 0x%x)\n", i, out_buf[i], write[i]);
return ZX_ERR_INTERNAL;
}
}
expected_writes_.pop_front();
*out_actual = buf_size;
return ZX_OK;
}
zx_status_t SerialImplSetNotifyCallback(const serial_notify_t* cb) { return ZX_OK; }
private:
bool unexpected_is_error_ = false;
std::list<std::vector<uint8_t>> expected_reads_;
std::list<std::vector<uint8_t>> expected_writes_;
serial_impl_protocol_t proto_;
};
class FtdiI2cTest : public zxtest::Test {
public:
void SetUp() override { ddk_.SetProtocol(ZX_PROTOCOL_SERIAL_IMPL, serial_.proto()); }
protected:
FtdiI2c FtdiBasicInit(void) {
FtdiI2c::I2cLayout layout = {0, 1, 2};
std::vector<FtdiI2c::I2cDevice> i2c_devices(1);
i2c_devices[0].address = 0x3c;
i2c_devices[0].vid = 0;
i2c_devices[0].pid = 0;
i2c_devices[0].did = 31;
return FtdiI2c(fake_ddk::kFakeParent, layout, i2c_devices);
}
fake_ddk::Bind ddk_;
FakeSerial serial_;
};
TEST_F(FtdiI2cTest, TrivialLifetimeTest) { FtdiI2c device = FtdiBasicInit(); }
TEST_F(FtdiI2cTest, DdkLifetimeTest) {
FtdiI2c::I2cLayout layout = {0, 1, 2};
std::vector<FtdiI2c::I2cDevice> i2c_devices(1);
i2c_devices[0].address = 0x3c;
i2c_devices[0].vid = 0;
i2c_devices[0].pid = 0;
i2c_devices[0].did = 31;
FtdiI2c* device(new FtdiI2c(fake_ddk::kFakeParent, layout, i2c_devices));
// These Reads and Writes are to sync the device on bind.
std::vector<uint8_t> first_write(1);
first_write[0] = 0xAB;
serial_.PushExpectedWrite(std::move(first_write));
std::vector<uint8_t> first_read(2);
first_read[0] = 0xFA;
first_read[1] = 0xAB;
serial_.PushExpectedRead(std::move(first_read));
// Check that bind works.
ASSERT_OK(device->Bind());
ASSERT_OK(ddk_.WaitUntilInitComplete());
device->DdkAsyncRemove();
EXPECT_TRUE(ddk_.Ok());
// This should delete the object, which means this test should not leak.
device->DdkRelease();
}
TEST_F(FtdiI2cTest, DdkLifetimeFailedInit) {
FtdiI2c::I2cLayout layout = {0, 1, 2};
std::vector<FtdiI2c::I2cDevice> i2c_devices(1);
i2c_devices[0].address = 0x3c;
i2c_devices[0].vid = 0;
i2c_devices[0].pid = 0;
i2c_devices[0].did = 31;
FtdiI2c* device(new FtdiI2c(fake_ddk::kFakeParent, layout, i2c_devices));
// These Reads and Writes are to sync the device on bind.
std::vector<uint8_t> first_write(1);
first_write[0] = 0xAB;
serial_.PushExpectedWrite(std::move(first_write));
// Set bad read data. This will cause the enable worker thread to fail.
std::vector<uint8_t> first_read(2);
first_read[0] = 0x00;
first_read[1] = 0x00;
serial_.PushExpectedRead(std::move(first_read));
// Bind should spawn the worker thread which will fail the init.
ASSERT_OK(device->Bind());
ASSERT_OK(ddk_.WaitUntilInitComplete());
ASSERT_OK(ddk_.WaitUntilRemove());
EXPECT_TRUE(ddk_.Ok());
// This should delete the object, which means this test should not leak.
device->DdkRelease();
}
TEST_F(FtdiI2cTest, PingTest) {
FtdiI2c device = FtdiBasicInit();
std::vector<uint8_t> ping_data = {
0x80, 0x3, 0x3, 0x82, 0x0, 0x0, 0x80, 0x1, 0x3, 0x82, 0x0, 0x0, 0x80, 0x0, 0x3, 0x82,
0x0, 0x0, 0x11, 0x0, 0x0, 0x78, 0x80, 0x2, 0x3, 0x82, 0x0, 0x0, 0x22, 0x0, 0x11, 0x0,
0x0, 0x0, 0x80, 0x2, 0x3, 0x82, 0x0, 0x0, 0x22, 0x0, 0x80, 0x0, 0x3, 0x82, 0x0, 0x0,
0x80, 0x1, 0x3, 0x82, 0x0, 0x0, 0x80, 0x3, 0x3, 0x82, 0x0, 0x0, 0x87};
serial_.PushExpectedWrite(std::move(ping_data));
zx_status_t status = device.Ping(0x3c);
ASSERT_OK(status);
}
TEST_F(FtdiI2cTest, ReadTest) {
FtdiI2c device = FtdiBasicInit();
serial_.FailOnUnexpectedReadWrite(false);
std::vector<uint8_t> serial_read_data = {
0x00, // The ACK for writing bus address.
0x00, // The ACK for writing register value.
0x00, // The ACK for initiating a read.
0xDE, // The Value we will be reading out.
};
serial_.PushExpectedRead(std::move(serial_read_data));
i2c_impl_op_t op_list[2] = {};
op_list[0].is_read = false;
op_list[0].stop = false;
uint8_t write_data = 0xAB;
op_list[0].data_buffer = &write_data;
op_list[0].data_size = sizeof(write_data);
op_list[1].is_read = true;
op_list[1].stop = true;
uint8_t read_data = 0;
op_list[1].data_buffer = &read_data;
op_list[1].data_size = sizeof(read_data);
zx_status_t status = device.I2cImplTransact(0, op_list, 2);
ASSERT_OK(status);
ASSERT_EQ(0xDE, read_data);
}
TEST_F(FtdiI2cTest, NackReadTest) {
FtdiI2c device = FtdiBasicInit();
serial_.FailOnUnexpectedReadWrite(false);
std::vector<uint8_t> serial_read_data = {
0x01, // The NACK for writing bus address.
0x01, // The NACK for writing register value.
0x01, // The NACK for initiating a read.
0x00, // The Value we will be reading out.
};
serial_.PushExpectedRead(std::move(serial_read_data));
i2c_impl_op_t op_list[2] = {};
op_list[0].is_read = false;
op_list[0].stop = false;
uint8_t write_data = 0xAB;
op_list[0].data_buffer = &write_data;
op_list[0].data_size = sizeof(write_data);
op_list[1].is_read = true;
op_list[1].stop = true;
uint8_t read_data = 0;
op_list[1].data_buffer = &read_data;
op_list[1].data_size = sizeof(read_data);
zx_status_t status = device.I2cImplTransact(0, op_list, 2);
ASSERT_EQ(ZX_ERR_INTERNAL, status);
}
} // namespace ftdi_mpsse
|
// ProgressMt.h
#include "StdAfx.h"
#include "ProgressMt.h"
void CMtCompressProgressMixer::Init(unsigned numItems, ICompressProgressInfo *progress)
{
NWindows::NSynchronization::CCriticalSectionLock lock(CriticalSection);
InSizes.Clear();
OutSizes.Clear();
for (unsigned i = 0; i < numItems; i++)
{
InSizes.Add(0);
OutSizes.Add(0);
}
TotalInSize = 0;
TotalOutSize = 0;
_progress = progress;
}
void CMtCompressProgressMixer::Reinit(unsigned index)
{
NWindows::NSynchronization::CCriticalSectionLock lock(CriticalSection);
InSizes[index] = 0;
OutSizes[index] = 0;
}
HRESULT CMtCompressProgressMixer::SetRatioInfo(unsigned index, const UInt64 *inSize, const UInt64 *outSize)
{
NWindows::NSynchronization::CCriticalSectionLock lock(CriticalSection);
if (inSize)
{
UInt64 diff = *inSize - InSizes[index];
InSizes[index] = *inSize;
TotalInSize += diff;
}
if (outSize)
{
UInt64 diff = *outSize - OutSizes[index];
OutSizes[index] = *outSize;
TotalOutSize += diff;
}
if (_progress)
return _progress->SetRatioInfo(&TotalInSize, &TotalOutSize);
return S_OK;
}
STDMETHODIMP CMtCompressProgress::SetRatioInfo(const UInt64 *inSize, const UInt64 *outSize)
{
return _progress->SetRatioInfo(_index, inSize, outSize);
}
|
/*Question:16- WAP to reverse the order of the elements in the stack using a additional stack.*/
#include<iostream>
using namespace std;
template <class T>
class Stack
{
public:
T *tack;
int size,top;
Stack(int n)
{
top=-1;
size=n;
tack=new T[size];
}
void PUSH(int);
void POP();
void Display();
};
template <class T>
void Stack<T>::PUSH(int n)
{
if(top==size-1)
{
cout<<"STACK IS OVERFLOW \n";
}else
{
tack[++top]=n;
}
}
template <class T>
void Stack<T>::POP()
{
if(top==-1)
cout<<"STACK IS UNDER FLOW \n";
else
{
cout<<"POPED ELEMENT IS ="<<tack[top--];
}
}
template <class T>
void Stack<T>::Display()
{
if(top==-1)
cout<<"SORRY! Your stack is empty \n";
else
{
for(int i=0;i<=top;i++)
cout<<tack[i]<<" ";
}
cout<<endl;
}
int main()
{
cout<<"Enter the size of the stack \n";
int n;
cin>>n;
Stack<int> s1(n);
Stack<int> s2(n);
while(1)
{
cout<<"\t Enter 1 for PUSH() function \n";
cout<<"\t Enter 2 for POP() function \n";
cout<<"\t Enter 3 for Display() function \n";
cout<<"\t Enter 4 to reverse the elements of Stack \n";
int choice;
cin>>choice;
switch(choice)
{
case 1:
cout<<"Enter the element \n";
int num;
cin>>num;
s1.PUSH(num);
break;
case 2:
s1.POP();
break;
case 3:
cout<<"STACK ELEMENTS ARE FOLLOWING \n";
s1.Display();
break;
case 4:
cout<<"Initially order of elements are following \n";
s1.Display();
for(int i=s1.top;i>=0;i--)
s2.PUSH(s1.tack[i]);
cout<<"Reversed order elements are following \n";
s2.Display();
break;
default:cout<<"WRONG CHOICE!\n";
}
cout<<"Enter 0 to exit and nonzero to conitnue \n";
int exit;
cin>>exit;
if(exit==0)
break;
}
}
|
// Copyright 2014 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/extensions/proxy_overridden_bubble_controller.h"
#include "base/metrics/histogram.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/extension_toolbar_model.h"
#include "chrome/browser/extensions/settings_api_helpers.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/url_constants.h"
#include "chrome/grit/generated_resources.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/browser/extension_system.h"
#include "grit/components_strings.h"
#include "ui/base/l10n/l10n_util.h"
namespace extensions {
namespace {
// The minimum time to wait (since the extension was installed) before notifying
// the user about it.
const int kDaysSinceInstallMin = 7;
////////////////////////////////////////////////////////////////////////////////
// ProxyOverriddenBubbleDelegate
class ProxyOverriddenBubbleDelegate
: public ExtensionMessageBubbleController::Delegate {
public:
ProxyOverriddenBubbleDelegate(ExtensionService* service, Profile* profile);
virtual ~ProxyOverriddenBubbleDelegate();
// ExtensionMessageBubbleController::Delegate methods.
virtual bool ShouldIncludeExtension(const std::string& extension_id) OVERRIDE;
virtual void AcknowledgeExtension(
const std::string& extension_id,
ExtensionMessageBubbleController::BubbleAction
user_action) OVERRIDE;
virtual void PerformAction(const ExtensionIdList& list) OVERRIDE;
virtual void OnClose() OVERRIDE;
virtual base::string16 GetTitle() const OVERRIDE;
virtual base::string16 GetMessageBody(
bool anchored_to_browser_action) const OVERRIDE;
virtual base::string16 GetOverflowText(
const base::string16& overflow_count) const OVERRIDE;
virtual base::string16 GetLearnMoreLabel() const OVERRIDE;
virtual GURL GetLearnMoreUrl() const OVERRIDE;
virtual base::string16 GetActionButtonLabel() const OVERRIDE;
virtual base::string16 GetDismissButtonLabel() const OVERRIDE;
virtual bool ShouldShowExtensionList() const OVERRIDE;
virtual void RestrictToSingleExtension(
const std::string& extension_id) OVERRIDE;
virtual void LogExtensionCount(size_t count) OVERRIDE;
virtual void LogAction(
ExtensionMessageBubbleController::BubbleAction
action) OVERRIDE;
private:
// Our extension service. Weak, not owned by us.
ExtensionService* service_;
// A weak pointer to the profile we are associated with. Not owned by us.
Profile* profile_;
// The ID of the extension we are showing the bubble for.
std::string extension_id_;
DISALLOW_COPY_AND_ASSIGN(ProxyOverriddenBubbleDelegate);
};
ProxyOverriddenBubbleDelegate::ProxyOverriddenBubbleDelegate(
ExtensionService* service,
Profile* profile)
: service_(service), profile_(profile) {}
ProxyOverriddenBubbleDelegate::~ProxyOverriddenBubbleDelegate() {}
bool ProxyOverriddenBubbleDelegate::ShouldIncludeExtension(
const std::string& extension_id) {
if (!extension_id_.empty() && extension_id_ != extension_id)
return false;
const Extension* extension =
ExtensionRegistry::Get(profile_)->enabled_extensions().GetByID(
extension_id);
if (!extension)
return false; // The extension provided is no longer enabled.
const Extension* overriding = GetExtensionOverridingProxy(profile_);
if (!overriding || overriding->id() != extension_id)
return false;
ExtensionPrefs* prefs = ExtensionPrefs::Get(profile_);
base::TimeDelta since_install =
base::Time::Now() - prefs->GetInstallTime(extension->id());
if (since_install.InDays() < kDaysSinceInstallMin)
return false;
if (ExtensionPrefs::Get(profile_)->HasProxyOverriddenBubbleBeenAcknowledged(
extension_id))
return false;
return true;
}
void ProxyOverriddenBubbleDelegate::AcknowledgeExtension(
const std::string& extension_id,
ExtensionMessageBubbleController::BubbleAction user_action) {
if (user_action != ExtensionMessageBubbleController::ACTION_EXECUTE) {
ExtensionPrefs::Get(profile_)->SetProxyOverriddenBubbleBeenAcknowledged(
extension_id, true);
}
}
void ProxyOverriddenBubbleDelegate::PerformAction(const ExtensionIdList& list) {
for (size_t i = 0; i < list.size(); ++i)
service_->DisableExtension(list[i], Extension::DISABLE_USER_ACTION);
}
void ProxyOverriddenBubbleDelegate::OnClose() {
ExtensionToolbarModel* toolbar_model =
ExtensionToolbarModel::Get(profile_);
if (toolbar_model)
toolbar_model->StopHighlighting();
}
base::string16 ProxyOverriddenBubbleDelegate::GetTitle() const {
return l10n_util::GetStringUTF16(
IDS_EXTENSIONS_PROXY_CONTROLLED_TITLE_HOME_PAGE_BUBBLE);
}
base::string16 ProxyOverriddenBubbleDelegate::GetMessageBody(
bool anchored_to_browser_action) const {
if (anchored_to_browser_action) {
return l10n_util::GetStringUTF16(
IDS_EXTENSIONS_PROXY_CONTROLLED_FIRST_LINE_EXTENSION_SPECIFIC);
} else {
return l10n_util::GetStringUTF16(
IDS_EXTENSIONS_PROXY_CONTROLLED_FIRST_LINE);
}
}
base::string16 ProxyOverriddenBubbleDelegate::GetOverflowText(
const base::string16& overflow_count) const {
// Does not have more than one extension in the list at a time.
NOTREACHED();
return base::string16();
}
base::string16 ProxyOverriddenBubbleDelegate::GetLearnMoreLabel() const {
return l10n_util::GetStringUTF16(IDS_LEARN_MORE);
}
GURL ProxyOverriddenBubbleDelegate::GetLearnMoreUrl() const {
return GURL(chrome::kExtensionControlledSettingLearnMoreURL);
}
base::string16 ProxyOverriddenBubbleDelegate::GetActionButtonLabel() const {
return l10n_util::GetStringUTF16(IDS_EXTENSION_CONTROLLED_RESTORE_SETTINGS);
}
base::string16 ProxyOverriddenBubbleDelegate::GetDismissButtonLabel() const {
return l10n_util::GetStringUTF16(IDS_EXTENSION_CONTROLLED_KEEP_CHANGES);
}
bool ProxyOverriddenBubbleDelegate::ShouldShowExtensionList() const {
return false;
}
void ProxyOverriddenBubbleDelegate::RestrictToSingleExtension(
const std::string& extension_id) {
extension_id_ = extension_id;
}
void ProxyOverriddenBubbleDelegate::LogExtensionCount(size_t count) {
UMA_HISTOGRAM_COUNTS_100("ProxyOverriddenBubble.ExtensionCount", count);
}
void ProxyOverriddenBubbleDelegate::LogAction(
ExtensionMessageBubbleController::BubbleAction action) {
UMA_HISTOGRAM_ENUMERATION("ProxyOverriddenBubble.UserSelection",
action,
ExtensionMessageBubbleController::ACTION_BOUNDARY);
}
} // namespace
////////////////////////////////////////////////////////////////////////////////
// ProxyOverriddenBubbleController
ProxyOverriddenBubbleController::ProxyOverriddenBubbleController(
Profile* profile)
: ExtensionMessageBubbleController(
new ProxyOverriddenBubbleDelegate(
ExtensionSystem::Get(profile)->extension_service(),
profile),
profile),
profile_(profile) {}
ProxyOverriddenBubbleController::~ProxyOverriddenBubbleController() {}
bool ProxyOverriddenBubbleController::ShouldShow(
const std::string& extension_id) {
if (!delegate()->ShouldIncludeExtension(extension_id))
return false;
delegate()->RestrictToSingleExtension(extension_id);
return true;
}
bool ProxyOverriddenBubbleController::CloseOnDeactivate() {
return false;
}
} // namespace extensions
|
/**********************************************************************************
Copyright (C) 2012 Syed Reza Ali (www.syedrezaali.com)
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 "ofxUIRangeSlider.h"
#include "ofxUI.h"
ofxUIRangeSlider::ofxUIRangeSlider(string _name, float _min, float _max, float _valuelow, float _valuehigh, float w, float h,
float x, float y, int _size) : ofxUIWidgetWithLabel()
{
useReference = false;
init(_name, _min, _max, &_valuelow, &_valuehigh, w, h, x, y, _size);
}
ofxUIRangeSlider::ofxUIRangeSlider(string _name, float _min, float _max, float *_valuelow, float *_valuehigh, float w, float h,
float x, float y, int _size) : ofxUIWidgetWithLabel()
{
useReference = true;
init(_name, _min, _max, _valuelow, _valuehigh, w, h, x, y, _size);
}
ofxUIRangeSlider::ofxUIRangeSlider(float x, float y, float w, float h, float _min, float _max, float _valuelow, float _valuehigh, string _name, int _size) : ofxUIWidgetWithLabel()
{
useReference = false;
init(_name, _min, _max, &_valuelow, &_valuehigh, w, h, x, y, _size);
// ofLogWarning("OFXUIRANGESLIDER: DON'T USE THIS CONSTRUCTOR. THIS WILL BE REMOVED ON FUTURE RELEASES.");
}
ofxUIRangeSlider::ofxUIRangeSlider(float w, float h, float _min, float _max, float _valuelow, float _valuehigh, string _name, int _size) : ofxUIWidgetWithLabel()
{
useReference = false;
init(_name, _min, _max, &_valuelow, &_valuehigh, w, h, 0, 0, _size);
// ofLogWarning("OFXUIRANGESLIDER: DON'T USE THIS CONSTRUCTOR. THIS WILL BE REMOVED ON FUTURE RELEASES.");
}
ofxUIRangeSlider::ofxUIRangeSlider(float x, float y, float w, float h, float _min, float _max, float *_valuelow, float *_valuehigh, string _name, int _size) : ofxUIWidgetWithLabel()
{
useReference = true;
init(_name, _min, _max, _valuelow, _valuehigh, w, h, x, y, _size);
// ofLogWarning("OFXUIRANGESLIDER: DON'T USE THIS CONSTRUCTOR. THIS WILL BE REMOVED ON FUTURE RELEASES.");
}
ofxUIRangeSlider::ofxUIRangeSlider(float w, float h, float _min, float _max, float *_valuelow, float *_valuehigh, string _name, int _size) : ofxUIWidgetWithLabel()
{
useReference = true;
init(_name, _min, _max, _valuelow, _valuehigh, w, h, 0, 0, _size);
// ofLogWarning("OFXUIRANGESLIDER: DON'T USE THIS CONSTRUCTOR. THIS WILL BE REMOVED ON FUTURE RELEASES.");
}
ofxUIRangeSlider::~ofxUIRangeSlider()
{
if(!useReference)
{
delete valuelowRef;
delete valuehighRef;
}
}
void ofxUIRangeSlider::init(string _name, float _min, float _max, float *_valuelow, float *_valuehigh, float w, float h,
float x, float y, int _size)
{
initRect(x,y,w,h);
name = string(_name);
if(w > h)
{
kind = OFX_UI_WIDGET_RSLIDER_H;
}
else
{
kind = OFX_UI_WIDGET_RSLIDER_V;
}
draw_fill = true;
valuelow = *_valuelow; //the widget's value
valuehigh = *_valuehigh; //the widget's value
if(useReference)
{
valuelowRef = _valuelow;
valuehighRef = _valuehigh;
}
else
{
valuelowRef = new float();
valuehighRef = new float();
*valuelowRef = valuelow;
*valuehighRef = valuehigh;
}
max = _max;
min = _min;
hitHigh = false;
hitLow = false;
hitCenter = false;
if(valuelow > max)
{
valuelow = max;
}
if(valuelow < min)
{
valuelow = min;
}
if(valuehigh > max)
{
valuehigh = max;
}
if(valuehigh < min)
{
valuehigh = min;
}
valuelow = ofxUIMap(valuelow, min, max, 0.0, 1.0, true);
valuehigh = ofxUIMap(valuehigh, min, max, 0.0, 1.0, true);
labelPrecision = 2;
valuelowString = ofxUIToString(getScaledValueLow(),labelPrecision);
valuehighString = ofxUIToString(getScaledValueHigh(),labelPrecision);
if(kind == OFX_UI_WIDGET_RSLIDER_H)
{
label = new ofxUILabel(0,h+padding,(name+" LABEL"), (name + ": " + valuelowString + " " + valuehighString), _size);
}
else
{
label = new ofxUILabel(0,h+padding,(name+" LABEL"), name, _size);
}
addEmbeddedWidget(label);
increment = fabs(max - min) / 10.0;
}
void ofxUIRangeSlider::update()
{
if(useReference)
{
valuelow = ofxUIMap(*valuelowRef, min, max, 0.0, 1.0, true);
valuehigh = ofxUIMap(*valuehighRef, min, max, 0.0, 1.0, true);
}
}
void ofxUIRangeSlider::setDrawPadding(bool _draw_padded_rect)
{
draw_padded_rect = _draw_padded_rect;
label->setDrawPadding(false);
}
void ofxUIRangeSlider::setDrawPaddingOutline(bool _draw_padded_rect_outline)
{
draw_padded_rect_outline = _draw_padded_rect_outline;
label->setDrawPaddingOutline(false);
}
void ofxUIRangeSlider::drawFill()
{
if(draw_fill)
{
ofxUIFill();
ofxUISetColor(color_fill);
if(kind == OFX_UI_WIDGET_RSLIDER_H)
{
ofxUIDrawRect(rect->getX()+rect->getWidth()*valuelow, rect->getY(), rect->getWidth()*(valuehigh-valuelow), rect->getHeight());
}
else
{
ofxUIDrawRect(rect->getX(), rect->getY()+(1.0-valuehigh)*rect->getHeight(), rect->getWidth(), rect->getHeight()*(valuehigh-valuelow));
}
}
}
void ofxUIRangeSlider::drawFillHighlight()
{
if(draw_fill_highlight)
{
ofxUIFill();
ofxUISetColor(color_fill_highlight);
if(kind == OFX_UI_WIDGET_RSLIDER_H)
{
ofxUIDrawRect(rect->getX()+rect->getWidth()*valuelow, rect->getY(), rect->getWidth()*(valuehigh-valuelow), rect->getHeight());
}
else
{
ofxUIDrawRect(rect->getX(), rect->getY()+(1.0-valuehigh)*rect->getHeight(), rect->getWidth(), rect->getHeight()*(valuehigh-valuelow));
}
if(kind == OFX_UI_WIDGET_RSLIDER_V)
{
label->drawString(rect->getX()+rect->getWidth()+padding, label->getRect()->getHeight()/2.0+rect->getY()+rect->getHeight()-rect->getHeight()*valuehigh, valuehighString);
label->drawString(rect->getX()+rect->getWidth()+padding, label->getRect()->getHeight()/2.0+rect->getY()+rect->getHeight()-rect->getHeight()*valuelow, valuelowString);
}
}
}
void ofxUIRangeSlider::mouseMoved(int x, int y )
{
if(rect->inside(x, y))
{
state = OFX_UI_STATE_OVER;
}
else
{
state = OFX_UI_STATE_NORMAL;
}
stateChange();
}
void ofxUIRangeSlider::mouseDragged(int x, int y, int button)
{
if(hit)
{
state = OFX_UI_STATE_DOWN;
hitValueHigh = valuehigh;
hitValueLow = valuelow;
if(triggerType & OFX_UI_TRIGGER_CHANGE)
{
input(x, y);
triggerEvent(this);
}
}
else
{
state = OFX_UI_STATE_NORMAL;
}
stateChange();
}
void ofxUIRangeSlider::mousePressed(int x, int y, int button)
{
if(rect->inside(x, y))
{
hit = true;
state = OFX_UI_STATE_DOWN;
hitValueHigh = valuehigh;
hitValueLow = valuelow;
if(triggerType & OFX_UI_TRIGGER_BEGIN)
{
input(x, y);
triggerEvent(this);
}
}
else
{
state = OFX_UI_STATE_NORMAL;
}
stateChange();
}
void ofxUIRangeSlider::mouseReleased(int x, int y, int button)
{
if(hit)
{
#ifdef OFX_UI_TARGET_TOUCH
state = OFX_UI_STATE_NORMAL;
#else
state = OFX_UI_STATE_OVER;
#endif
if(triggerType & OFX_UI_TRIGGER_END)
{
input(x, y);
triggerEvent(this);
}
}
else
{
state = OFX_UI_STATE_NORMAL;
}
stateChange();
hit = false;
hitHigh = false;
hitLow = false;
hitCenter = false;
}
void ofxUIRangeSlider::keyPressed(int key)
{
if(state == OFX_UI_STATE_OVER)
{
switch (key)
{
case OF_KEY_RIGHT:
setValueHigh(getScaledValueHigh()+increment);
setValueLow(getScaledValueLow()+increment);
triggerEvent(this);
break;
case OF_KEY_LEFT:
setValueHigh(getScaledValueHigh()-increment);
setValueLow(getScaledValueLow()-increment);
triggerEvent(this);
break;
case OF_KEY_UP:
setValueHigh(getScaledValueHigh()+increment);
setValueLow(getScaledValueLow()-increment);
triggerEvent(this);
break;
case OF_KEY_DOWN:
setValueHigh(getScaledValueHigh()-increment);
setValueLow(getScaledValueLow()+increment);
triggerEvent(this);
break;
default:
break;
}
}
}
void ofxUIRangeSlider::keyReleased(int key)
{
}
void ofxUIRangeSlider::windowResized(int w, int h)
{
}
void ofxUIRangeSlider::setIncrement(float _increment)
{
increment = _increment;
}
void ofxUIRangeSlider::input(float x, float y)
{
float v = 0;
if(kind == OFX_UI_WIDGET_RSLIDER_H)
{
v = rect->percentInside(x, y).x;
}
else
{
v = 1.0-rect->percentInside(x, y).y;
}
if(hitHigh)
{
valuehigh = v;
}
else if(hitLow)
{
valuelow = v;
}
else if(hitCenter)
{
valuehigh +=(v-hitPoint);
valuelow +=(v-hitPoint);
hitPoint = v;
}
else
{
float dvh = fabs(valuehigh - v);
float dvl = fabs(valuelow - v);
if(dvh < .05 || v > valuehigh)
{
valuehigh = v;
hitHigh = true;
}
else if(dvl < .05 || v < valuelow)
{
valuelow = v;
hitLow = true;
}
else
{
hitCenter = true;
hitPoint = v;
}
}
if(valuehigh < valuelow && hitHigh)
{
valuehigh = hitValueLow;
hitHigh = false;
hitLow = true;
}
else if(valuelow > valuehigh && hitLow)
{
valuelow = hitValueHigh;
hitHigh = true;
hitLow = false;
}
valuehigh = MIN(1.0, MAX(0.0, valuehigh));
valuelow = MIN(1.0, MAX(0.0, valuelow));
updateValueRef();
updateLabel();
}
void ofxUIRangeSlider::updateValueRef()
{
(*valuelowRef) = getScaledValueLow();
(*valuehighRef) = getScaledValueHigh();
}
void ofxUIRangeSlider::updateLabel()
{
valuelowString = ofxUIToString(getValueLow(),labelPrecision);
valuehighString = ofxUIToString(getValueHigh(),labelPrecision);
if(kind == OFX_UI_WIDGET_RSLIDER_H)
{
label->setLabel(name + ": " + valuelowString + " " + valuehighString);
}
}
void ofxUIRangeSlider::stateChange()
{
if(valuehigh > 0)
{
draw_fill = true;
}
else
{
draw_fill = false;
}
switch (state) {
case OFX_UI_STATE_NORMAL:
{
draw_fill_highlight = false;
draw_outline_highlight = false;
label->unfocus();
}
break;
case OFX_UI_STATE_OVER:
{
draw_fill_highlight = false;
draw_outline_highlight = true;
label->unfocus();
}
break;
case OFX_UI_STATE_DOWN:
{
draw_fill_highlight = true;
draw_outline_highlight = true;
label->focus();
}
break;
case OFX_UI_STATE_SUSTAINED:
{
draw_fill_highlight = false;
draw_outline_highlight = false;
label->unfocus();
}
break;
default:
break;
}
}
void ofxUIRangeSlider::setValueLow(float _value)
{
valuelow = ofxUIMap(_value, min, max, 0.0, 1.0, true);
updateValueRef();
updateLabel();
}
void ofxUIRangeSlider::setValueHigh(float _value)
{
valuehigh = ofxUIMap(_value, min, max, 0.0, 1.0, true);
updateValueRef();
updateLabel();
}
float ofxUIRangeSlider::getValueLow()
{
return (*valuelowRef);
}
float ofxUIRangeSlider::getValueHigh()
{
return (*valuehighRef);
}
float ofxUIRangeSlider::getNormalizedValueLow()
{
return valuelow;
}
float ofxUIRangeSlider::getNormalizedValueHigh()
{
return valuehigh;
}
float ofxUIRangeSlider::getPercentValueLow()
{
return valuelow;
}
float ofxUIRangeSlider::getPercentValueHigh()
{
return valuehigh;
}
float ofxUIRangeSlider::getScaledValueLow()
{
return ofxUIMap(valuelow, 0.0, 1.0, min, max, true);
}
float ofxUIRangeSlider::getScaledValueHigh()
{
return ofxUIMap(valuehigh, 0.0, 1.0, min, max, true);
}
void ofxUIRangeSlider::setLabelPrecision(int _precision)
{
labelPrecision = _precision;
updateValueRef();
updateLabel();
}
void ofxUIRangeSlider::setParent(ofxUIWidget *_parent)
{
parent = _parent;
calculatePaddingRect();
}
void ofxUIRangeSlider::setMax(float _max)
{
setMaxAndMin(_max, min);
}
void ofxUIRangeSlider::setMin(float _min)
{
setMaxAndMin(max, _min);
}
void ofxUIRangeSlider::setMaxAndMin(float _max, float _min)
{
max = _max;
min = _min;
valuelow= ofxUIMap(valuelow, 0, 1.0, min, max, true);
valuelow = ofxUIMap(valuelow, min, max, 0.0, 1.0, true);
valuehigh = ofxUIMap(valuehigh, 0, 1.0, min, max, true);
valuehigh = ofxUIMap(valuehigh, min, max, 0.0, 1.0, true);
updateValueRef();
updateLabel();
}
bool ofxUIRangeSlider::isDraggable()
{
return true;
}
#ifndef OFX_UI_NO_XML
void ofxUIRangeSlider::saveState(ofxXmlSettings *XML)
{
XML->setValue("HighValue", getValueHigh(), 0);
XML->setValue("LowValue", getValueLow(), 0);
}
void ofxUIRangeSlider::loadState(ofxXmlSettings *XML)
{
setValueHigh(XML->getValue("HighValue", getValueHigh(), 0));
setValueLow(XML->getValue("LowValue", getValueLow(), 0));
}
#endif
|
// Copyright (c) 2012-2016 The Ilcoin Core developers
// All Rights Reserved. ILCoin Blockchain Project 2019©
#include "consensus/merkle.h"
#include "merkleblock.h"
#include "serialize.h"
#include "streams.h"
#include "uint256.h"
#include "arith_uint256.h"
#include "version.h"
#include "test/test_ilcoin.h"
#include "test/test_random.h"
#include <vector>
#include <boost/assign/list_of.hpp>
#include <boost/test/unit_test.hpp>
class CPartialMerkleTreeTester : public CPartialMerkleTree
{
public:
// flip one bit in one of the hashes - this should break the authentication
void Damage() {
unsigned int n = insecure_rand() % vHash.size();
int bit = insecure_rand() % 256;
*(vHash[n].begin() + (bit>>3)) ^= 1<<(bit&7);
}
};
BOOST_FIXTURE_TEST_SUITE(pmt_tests, BasicTestingSetup)
BOOST_AUTO_TEST_CASE(pmt_test1)
{
seed_insecure_rand(false);
static const unsigned int nTxCounts[] = {1, 4, 7, 17, 56, 100, 127, 256, 312, 513, 1000, 4095};
for (int i = 0; i < 12; i++) {
unsigned int nTx = nTxCounts[i];
// build a block with some dummy transactions
CBlock block;
for (unsigned int j=0; j<nTx; j++) {
CMutableTransaction tx;
tx.nLockTime = j; // actual transaction data doesn't matter; just make the nLockTime's unique
block.vtx.push_back(MakeTransactionRef(std::move(tx)));
}
// calculate actual merkle root and height
uint256 merkleRoot1 = BlockMerkleRoot(block);
std::vector<uint256> vTxid(nTx, uint256());
for (unsigned int j=0; j<nTx; j++)
vTxid[j] = block.vtx[j]->GetHash();
int nHeight = 1, nTx_ = nTx;
while (nTx_ > 1) {
nTx_ = (nTx_+1)/2;
nHeight++;
}
// check with random subsets with inclusion chances 1, 1/2, 1/4, ..., 1/128
for (int att = 1; att < 15; att++) {
// build random subset of txid's
std::vector<bool> vMatch(nTx, false);
std::vector<uint256> vMatchTxid1;
for (unsigned int j=0; j<nTx; j++) {
bool fInclude = (insecure_rand() & ((1 << (att/2)) - 1)) == 0;
vMatch[j] = fInclude;
if (fInclude)
vMatchTxid1.push_back(vTxid[j]);
}
// build the partial merkle tree
CPartialMerkleTree pmt1(vTxid, vMatch);
// serialize
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << pmt1;
// verify CPartialMerkleTree's size guarantees
unsigned int n = std::min<unsigned int>(nTx, 1 + vMatchTxid1.size()*nHeight);
BOOST_CHECK(ss.size() <= 10 + (258*n+7)/8);
// deserialize into a tester copy
CPartialMerkleTreeTester pmt2;
ss >> pmt2;
// extract merkle root and matched txids from copy
std::vector<uint256> vMatchTxid2;
std::vector<unsigned int> vIndex;
uint256 merkleRoot2 = pmt2.ExtractMatches(vMatchTxid2, vIndex);
// check that it has the same merkle root as the original, and a valid one
BOOST_CHECK(merkleRoot1 == merkleRoot2);
BOOST_CHECK(!merkleRoot2.IsNull());
// check that it contains the matched transactions (in the same order!)
BOOST_CHECK(vMatchTxid1 == vMatchTxid2);
// check that random bit flips break the authentication
for (int j=0; j<4; j++) {
CPartialMerkleTreeTester pmt3(pmt2);
pmt3.Damage();
std::vector<uint256> vMatchTxid3;
uint256 merkleRoot3 = pmt3.ExtractMatches(vMatchTxid3, vIndex);
BOOST_CHECK(merkleRoot3 != merkleRoot1);
}
}
}
}
BOOST_AUTO_TEST_CASE(pmt_malleability)
{
std::vector<uint256> vTxid = boost::assign::list_of
(ArithToUint256(1))(ArithToUint256(2))
(ArithToUint256(3))(ArithToUint256(4))
(ArithToUint256(5))(ArithToUint256(6))
(ArithToUint256(7))(ArithToUint256(8))
(ArithToUint256(9))(ArithToUint256(10))
(ArithToUint256(9))(ArithToUint256(10));
std::vector<bool> vMatch = boost::assign::list_of(false)(false)(false)(false)(false)(false)(false)(false)(false)(true)(true)(false);
CPartialMerkleTree tree(vTxid, vMatch);
std::vector<unsigned int> vIndex;
BOOST_CHECK(tree.ExtractMatches(vTxid, vIndex).IsNull());
}
BOOST_AUTO_TEST_SUITE_END()
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Copyright (c) 2014-2017 The Dash Core developers
// Copyright (c) 2018 The FlatEarth Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "chainparams.h"
#include "clientversion.h"
#include "rpc/server.h"
#include "init.h"
#include "noui.h"
#include "scheduler.h"
#include "util.h"
#include "masternodeconfig.h"
#include "httpserver.h"
#include "httprpc.h"
#include <boost/algorithm/string/predicate.hpp>
#include <boost/filesystem.hpp>
#include <boost/thread.hpp>
#include <stdio.h>
/* Introduction text for doxygen: */
/*! \mainpage Developer documentation
*
* \section intro_sec Introduction
*
* This is the developer documentation of the reference client for an experimental new digital currency called FlatEarth (https://www.flatearthcrypto.com/),
* which enables instant payments to anyone, anywhere in the world. FlatEarth uses peer-to-peer technology to operate
* with no central authority: managing transactions and issuing money are carried out collectively by the network.
*
* The software is a community-driven open source project, released under the MIT license.
*
* \section Navigation
* Use the buttons <code>Namespaces</code>, <code>Classes</code> or <code>Files</code> at the top of the page to start navigating the code.
*/
static bool fDaemon;
void WaitForShutdown(boost::thread_group* threadGroup)
{
bool fShutdown = ShutdownRequested();
// Tell the main threads to shutdown.
while (!fShutdown)
{
MilliSleep(200);
fShutdown = ShutdownRequested();
}
if (threadGroup)
{
Interrupt(*threadGroup);
threadGroup->join_all();
}
}
//////////////////////////////////////////////////////////////////////////////
//
// Start
//
bool AppInit(int argc, char* argv[])
{
boost::thread_group threadGroup;
CScheduler scheduler;
bool fRet = false;
//
// Parameters
//
// If Qt is used, parameters/flatearth.conf are parsed in qt/flatearth.cpp's main()
ParseParameters(argc, argv);
// Process help and version before taking care about datadir
if (mapArgs.count("-?") || mapArgs.count("-h") || mapArgs.count("-help") || mapArgs.count("-version"))
{
std::string strUsage = _("FlatEarth Core Daemon") + " " + _("version") + " " + FormatFullVersion() + "\n";
if (mapArgs.count("-version"))
{
strUsage += LicenseInfo();
}
else
{
strUsage += "\n" + _("Usage:") + "\n" +
" flatearthd [options] " + _("Start FlatEarth Core Daemon") + "\n";
strUsage += "\n" + HelpMessage(HMM_BITCOIND);
}
fprintf(stdout, "%s", strUsage.c_str());
return true;
}
try
{
bool datadirFromCmdLine = mapArgs.count("-datadir") != 0;
if (datadirFromCmdLine && !boost::filesystem::is_directory(GetDataDir(false)))
{
fprintf(stderr, "Error: Specified data directory \"%s\" does not exist.\n", mapArgs["-datadir"].c_str());
return false;
}
try
{
ReadConfigFile(mapArgs, mapMultiArgs);
} catch (const std::exception& e) {
fprintf(stderr,"Error reading configuration file: %s\n", e.what());
return false;
}
if (!datadirFromCmdLine && !boost::filesystem::is_directory(GetDataDir(false)))
{
fprintf(stderr, "Error: Specified data directory \"%s\" from config file does not exist.\n", mapArgs["-datadir"].c_str());
return EXIT_FAILURE;
}
// Check for -testnet or -regtest parameter (Params() calls are only valid after this clause)
try {
SelectParams(ChainNameFromCommandLine());
} catch (const std::exception& e) {
fprintf(stderr, "Error: %s\n", e.what());
return false;
}
// parse masternode.conf
std::string strErr;
if(!masternodeConfig.read(strErr)) {
fprintf(stderr,"Error reading masternode configuration file: %s\n", strErr.c_str());
return false;
}
// Command-line RPC
bool fCommandLine = false;
for (int i = 1; i < argc; i++)
if (!IsSwitchChar(argv[i][0]) && !boost::algorithm::istarts_with(argv[i], "flatearth:"))
fCommandLine = true;
if (fCommandLine)
{
fprintf(stderr, "Error: There is no RPC client functionality in flatearthd. Use the flatearth-cli utility instead.\n");
exit(EXIT_FAILURE);
}
#ifndef WIN32
fDaemon = GetBoolArg("-daemon", false);
if (fDaemon)
{
fprintf(stdout, "FlatEarth Core server starting\n");
// Daemonize
pid_t pid = fork();
if (pid < 0)
{
fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
return false;
}
if (pid > 0) // Parent process, pid is child process id
{
return true;
}
// Child process falls through to rest of initialization
pid_t sid = setsid();
if (sid < 0)
fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
}
#endif
SoftSetBoolArg("-server", true);
// Set this early so that parameter interactions go to console
InitLogging();
InitParameterInteraction();
fRet = AppInit2(threadGroup, scheduler);
}
catch (const std::exception& e) {
PrintExceptionContinue(&e, "AppInit()");
} catch (...) {
PrintExceptionContinue(NULL, "AppInit()");
}
if (!fRet)
{
Interrupt(threadGroup);
// threadGroup.join_all(); was left out intentionally here, because we didn't re-test all of
// the startup-failure cases to make sure they don't result in a hang due to some
// thread-blocking-waiting-for-another-thread-during-startup case
} else {
WaitForShutdown(&threadGroup);
}
Shutdown();
return fRet;
}
int main(int argc, char* argv[])
{
SetupEnvironment();
// Connect flatearthd signal handlers
noui_connect();
return (AppInit(argc, argv) ? EXIT_SUCCESS : EXIT_FAILURE);
}
|
#include "Core/Core.h"
#include "PackFile.h"
#include <lz4\lz4.h>
namespace asset
{
FileSpan::FileSpan() : offset(0), size(0), compressedSize(0), assetType(AssetType::Unknown) { }
PackFile::PackFile() : _file(nullptr)
{
}
PackFile::~PackFile()
{
if (_file != nullptr)
{
fclose(_file);
}
}
bool PackFile::load(const char* fileName)
{
_file = fopen(fileName, "rb");
if (_file == nullptr) { return false; }
//Check the magic number
uint32_t magicNumber = 0;
fread(&magicNumber, sizeof(uint32_t), 1, _file);
if (magicNumber != PackFile::MAGIC_NUMBER)
{
return false;
}
//Read hashSeed and fileCount
uint32_t fileCount;
fread(&_hashSeed, sizeof(uint32_t), 1, _file);
fread(&fileCount, sizeof(uint32_t), 1, _file);
//Read the file headers
eastl::pair<AssetRef, FileSpan> temp;
for (uint32_t i = 0; i < fileCount; i++)
{
uint32_t hash;
fread(&hash, sizeof(hash), 1, _file);
fread(&temp.second, sizeof(FileSpan), 1, _file);
temp.first = AssetRef(hash);
_fileSpans.insert(temp);
}
return true;
}
uint32_t PackFile::getHashSeed()
{
return _hashSeed;
}
FileSpan PackFile::getFileSpan(AssetRef ref)
{
auto search = _fileSpans.find(ref);
if (search == _fileSpans.end())
{
return FileSpan();
}
else
{
return search->second;
}
}
void PackFile::lock()
{
_mutex.lock();
}
void PackFile::unlock()
{
_mutex.unlock();
}
void PackFile::seek(uint32_t offset)
{
NW_ASSERT(!_mutex.try_lock());
fseek(_file, offset, SEEK_SET);
}
void PackFile::read(uint32_t size, void* buffer)
{
NW_ASSERT(!_mutex.try_lock());
fread(buffer, 1, size, _file);
}
void PackFile::read(uint32_t offset, uint32_t size, void* buffer)
{
NW_ASSERT(!_mutex.try_lock());
fseek(_file, offset, SEEK_SET);
fread(buffer, 1, size, _file);
}
void PackFile::decompress(const FileSpan& span, void* buffer)
{
NW_ASSERT(!_mutex.try_lock());
LZ4_streamDecode_t lz4StreamDecode_body;
LZ4_streamDecode_t* lz4StreamDecode = &lz4StreamDecode_body;
//Seek to the proper place in the file
fseek(_file, span.offset, SEEK_SET);
char decBuf[2][BLOCK_BYTES];
int decBufIndex = 0;
size_t totalBytesRead = 0;
size_t totalUncompressed = 0;
LZ4_setStreamDecode(lz4StreamDecode, NULL, 0);
while (1)
{
char cmpBuf[LZ4_COMPRESSBOUND(BLOCK_BYTES)];
int cmpBytes = 0;
{
const size_t readCount0 = fread(&cmpBytes, sizeof(cmpBytes), 1, _file);
totalBytesRead += sizeof(cmpBytes);
if (readCount0 != 1 || cmpBytes <= 0)
{
break;
}
const size_t readCount1 = fread(cmpBuf, 1, (size_t)cmpBytes, _file);
totalBytesRead += cmpBytes;
if (readCount1 != (size_t)cmpBytes)
{
break;
}
}
char* const decPtr = decBuf[decBufIndex];
const int decBytes = LZ4_decompress_safe_continue(lz4StreamDecode, cmpBuf, decPtr, cmpBytes, BLOCK_BYTES);
totalUncompressed += decBytes;
if (decBytes <= 0)
{
break;
}
memcpy(buffer, decPtr, (size_t)decBytes);
buffer = (char*)buffer + decBytes;
decBufIndex = (decBufIndex + 1) % 2;
}
NW_ASSERT(totalBytesRead == span.compressedSize);
NW_ASSERT(totalUncompressed == span.size);
}
}
|
//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, 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
//
//===----------------------------------------------------------------------===//
// <locale>
// class num_get<charT, InputIterator>
// iter_type get(iter_type in, iter_type end, ios_base&,
// ios_base::iostate& err, unsigned long long& v) const;
#include <locale>
#include <ios>
#include <cassert>
#include <streambuf>
#include "test_macros.h"
#include "test_iterators.h"
typedef std::num_get<char, cpp17_input_iterator<const char*> > F;
class my_facet
: public F
{
public:
explicit my_facet(std::size_t refs = 0)
: F(refs) {}
};
class my_numpunct
: public std::numpunct<char>
{
public:
my_numpunct() : std::numpunct<char>() {}
protected:
virtual char_type do_thousands_sep() const {return '_';}
virtual std::string do_grouping() const {return std::string("\1\2\3");}
};
int main(int, char**)
{
const my_facet f(1);
std::ios ios(0);
unsigned long long v = static_cast<unsigned long long>(-1);
{
const char str[] = "0";
std::ios_base::iostate err = ios.goodbit;
cpp17_input_iterator<const char*> iter =
f.get(cpp17_input_iterator<const char*>(str),
cpp17_input_iterator<const char*>(str+sizeof(str)),
ios, err, v);
assert(iter.base() == str+sizeof(str)-1);
assert(err == ios.goodbit);
assert(v == 0);
}
{
const char str[] = "1";
std::ios_base::iostate err = ios.goodbit;
cpp17_input_iterator<const char*> iter =
f.get(cpp17_input_iterator<const char*>(str),
cpp17_input_iterator<const char*>(str+sizeof(str)),
ios, err, v);
assert(iter.base() == str+sizeof(str)-1);
assert(err == ios.goodbit);
assert(v == 1);
}
std::hex(ios);
{
const char str[] = "0xFFFFFFFFFFFFFFFF";
std::ios_base::iostate err = ios.goodbit;
cpp17_input_iterator<const char*> iter =
f.get(cpp17_input_iterator<const char*>(str),
cpp17_input_iterator<const char*>(str+sizeof(str)),
ios, err, v);
assert(iter.base() == str+sizeof(str)-1);
assert(err == ios.goodbit);
assert(v == 0xFFFFFFFFFFFFFFFFULL);
}
return 0;
}
|
// 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 "base/task/sequence_manager/sequence_manager_impl.h"
#include <queue>
#include <vector>
#include "base/bind.h"
#include "base/bit_cast.h"
#include "base/compiler_specific.h"
#include "base/debug/crash_logging.h"
#include "base/debug/stack_trace.h"
#include "base/json/json_writer.h"
#include "base/memory/ptr_util.h"
#include "base/message_loop/message_loop_current.h"
#include "base/no_destructor.h"
#include "base/optional.h"
#include "base/rand_util.h"
#include "base/task/sequence_manager/real_time_domain.h"
#include "base/task/sequence_manager/task_time_observer.h"
#include "base/task/sequence_manager/thread_controller_impl.h"
#include "base/task/sequence_manager/thread_controller_with_message_pump_impl.h"
#include "base/task/sequence_manager/work_queue.h"
#include "base/task/sequence_manager/work_queue_sets.h"
#include "base/threading/thread_id_name_manager.h"
#include "base/threading/thread_local.h"
#include "base/time/default_tick_clock.h"
#include "base/time/tick_clock.h"
#include "base/trace_event/trace_event.h"
#include "build/build_config.h"
namespace base {
namespace sequence_manager {
namespace {
base::ThreadLocalPointer<internal::SequenceManagerImpl>*
GetTLSSequenceManagerImpl() {
static NoDestructor<ThreadLocalPointer<internal::SequenceManagerImpl>>
lazy_tls_ptr;
return lazy_tls_ptr.get();
}
const scoped_refptr<SequencedTaskRunner>& GetNullTaskRunner() {
static const base::NoDestructor<scoped_refptr<SequencedTaskRunner>>
null_task_runner;
return *null_task_runner;
}
} // namespace
// This controls how big the the initial for
// |MainThreadOnly::task_execution_stack| should be. We don't expect to see
// depths of more than 2 unless cooperative scheduling is used on Blink, where
// we might get up to 6. Anyway 10 was chosen because it's a round number
// greater than current anticipated usage.
static constexpr const size_t kInitialTaskExecutionStackReserveCount = 10;
std::unique_ptr<SequenceManager> CreateSequenceManagerOnCurrentThread(
SequenceManager::Settings settings) {
return internal::SequenceManagerImpl::CreateOnCurrentThread(
std::move(settings));
}
std::unique_ptr<SequenceManager> CreateSequenceManagerOnCurrentThreadWithPump(
std::unique_ptr<MessagePump> message_pump,
SequenceManager::Settings settings) {
std::unique_ptr<SequenceManager> sequence_manager =
internal::SequenceManagerImpl::CreateUnbound(std::move(settings));
sequence_manager->BindToMessagePump(std::move(message_pump));
return sequence_manager;
}
std::unique_ptr<SequenceManager> CreateUnboundSequenceManager(
SequenceManager::Settings settings) {
return internal::SequenceManagerImpl::CreateUnbound(std::move(settings));
}
BASE_EXPORT std::unique_ptr<SequenceManager> CreateFunneledSequenceManager(
scoped_refptr<SingleThreadTaskRunner> task_runner,
SequenceManager::Settings settings) {
std::unique_ptr<SequenceManager> sequence_manager =
internal::SequenceManagerImpl::CreateSequenceFunneled(
std::move(task_runner), std::move(settings));
sequence_manager->BindToCurrentThread();
return sequence_manager;
}
namespace internal {
using TimeRecordingPolicy =
base::sequence_manager::TaskQueue::TaskTiming::TimeRecordingPolicy;
namespace {
constexpr TimeDelta kLongTaskTraceEventThreshold =
TimeDelta::FromMilliseconds(50);
// Proportion of tasks which will record thread time for metrics.
const double kTaskSamplingRateForRecordingCPUTime = 0.01;
// Proprortion of SequenceManagers which will record thread time for each task,
// enabling advanced metrics.
const double kThreadSamplingRateForRecordingCPUTime = 0.0001;
// Magic value to protect against memory corruption and bail out
// early when detected.
constexpr int kMemoryCorruptionSentinelValue = 0xdeadbeef;
void ReclaimMemoryFromQueue(internal::TaskQueueImpl* queue,
std::map<TimeDomain*, TimeTicks>* time_domain_now) {
TimeDomain* time_domain = queue->GetTimeDomain();
if (time_domain_now->find(time_domain) == time_domain_now->end())
time_domain_now->insert(std::make_pair(time_domain, time_domain->Now()));
queue->ReclaimMemory(time_domain_now->at(time_domain));
queue->delayed_work_queue()->RemoveAllCanceledTasksFromFront();
queue->immediate_work_queue()->RemoveAllCanceledTasksFromFront();
}
SequenceManager::MetricRecordingSettings InitializeMetricRecordingSettings(
bool randomised_sampling_enabled) {
if (!randomised_sampling_enabled)
return SequenceManager::MetricRecordingSettings(0);
bool records_cpu_time_for_each_task =
base::RandDouble() < kThreadSamplingRateForRecordingCPUTime;
return SequenceManager::MetricRecordingSettings(
records_cpu_time_for_each_task ? 1
: kTaskSamplingRateForRecordingCPUTime);
}
// Writes |address| in hexadecimal ("0x11223344") form starting from |output|
// and moving backwards in memory. Returns a pointer to the first digit of the
// result. Does *not* NUL-terminate the number.
#if !defined(OS_NACL)
char* PrependHexAddress(char* output, const void* address) {
uintptr_t value = reinterpret_cast<uintptr_t>(address);
static const char kHexChars[] = "0123456789ABCDEF";
do {
*output-- = kHexChars[value % 16];
value /= 16;
} while (value);
*output-- = 'x';
*output = '0';
return output;
}
#endif // !defined(OS_NACL)
} // namespace
class SequenceManagerImpl::NativeWorkHandleImpl : public NativeWorkHandle {
public:
NativeWorkHandleImpl(SequenceManagerImpl* sequence_manager,
TaskQueue::QueuePriority priority)
: sequence_manager_(sequence_manager->GetWeakPtr()), priority_(priority) {
TRACE_EVENT_ASYNC_BEGIN1("sequence_manager", "NativeWork", this, "priority",
TaskQueue::PriorityToString(priority_));
sequence_manager_->main_thread_only().pending_native_work.insert(priority_);
}
~NativeWorkHandleImpl() final {
TRACE_EVENT_ASYNC_END0("sequence_manager", "NativeWork", this);
if (!sequence_manager_)
return;
TaskQueue::QueuePriority prev_priority = effective_priority();
sequence_manager_->main_thread_only().pending_native_work.erase(priority_);
// We should always have at least one instance of pending native work. By
// default it is of the lowest priority, which doesn't cause SequenceManager
// to yield.
DCHECK_GE(sequence_manager_->main_thread_only().pending_native_work.size(),
1u);
if (prev_priority != effective_priority())
sequence_manager_->ScheduleWork();
}
TaskQueue::QueuePriority effective_priority() const {
return *sequence_manager_->main_thread_only().pending_native_work.begin();
}
private:
WeakPtr<SequenceManagerImpl> sequence_manager_;
const TaskQueue::QueuePriority priority_;
};
// static
SequenceManagerImpl* SequenceManagerImpl::GetCurrent() {
return GetTLSSequenceManagerImpl()->Get();
}
SequenceManagerImpl::SequenceManagerImpl(
std::unique_ptr<internal::ThreadController> controller,
SequenceManager::Settings settings)
: associated_thread_(controller->GetAssociatedThread()),
controller_(std::move(controller)),
settings_(std::move(settings)),
metric_recording_settings_(InitializeMetricRecordingSettings(
settings_.randomised_sampling_enabled)),
add_queue_time_to_tasks_(settings_.add_queue_time_to_tasks),
empty_queues_to_reload_(associated_thread_),
memory_corruption_sentinel_(kMemoryCorruptionSentinelValue),
main_thread_only_(associated_thread_, settings_) {
TRACE_EVENT_OBJECT_CREATED_WITH_ID(
TRACE_DISABLED_BY_DEFAULT("sequence_manager"), "SequenceManager", this);
main_thread_only().selector.SetTaskQueueSelectorObserver(this);
main_thread_only().next_time_to_reclaim_memory =
settings_.clock->NowTicks() + kReclaimMemoryInterval;
RegisterTimeDomain(main_thread_only().real_time_domain.get());
controller_->SetSequencedTaskSource(this);
}
SequenceManagerImpl::~SequenceManagerImpl() {
DCHECK_CALLED_ON_VALID_THREAD(associated_thread_->thread_checker);
TRACE_EVENT_OBJECT_DELETED_WITH_ID(
TRACE_DISABLED_BY_DEFAULT("sequence_manager"), "SequenceManager", this);
#if defined(OS_IOS)
if (settings_.message_loop_type == MessagePumpType::UI &&
associated_thread_->IsBound()) {
controller_->DetachFromMessagePump();
}
#endif
// Make sure no Task is running as given that RunLoop does not support the
// Delegate being destroyed from a Task and
// ThreadControllerWithMessagePumpImpl does not support being destroyed from a
// Task. If we are using a ThreadControllerImpl (i.e. no pump) destruction is
// fine
DCHECK(!controller_->GetBoundMessagePump() ||
main_thread_only().task_execution_stack.empty());
for (internal::TaskQueueImpl* queue : main_thread_only().active_queues) {
main_thread_only().selector.RemoveQueue(queue);
queue->UnregisterTaskQueue();
}
// TODO(altimin): restore default task runner automatically when
// ThreadController is destroyed.
controller_->RestoreDefaultTaskRunner();
main_thread_only().active_queues.clear();
main_thread_only().queues_to_gracefully_shutdown.clear();
main_thread_only().selector.SetTaskQueueSelectorObserver(nullptr);
// In some tests a NestingObserver may not have been registered.
if (main_thread_only().nesting_observer_registered_)
controller_->RemoveNestingObserver(this);
// Let interested parties have one last shot at accessing this.
for (auto& observer : main_thread_only().destruction_observers)
observer.WillDestroyCurrentMessageLoop();
// OK, now make it so that no one can find us.
if (GetMessagePump()) {
DCHECK_EQ(this, GetTLSSequenceManagerImpl()->Get());
GetTLSSequenceManagerImpl()->Set(nullptr);
}
}
SequenceManagerImpl::MainThreadOnly::MainThreadOnly(
const scoped_refptr<AssociatedThreadId>& associated_thread,
const SequenceManager::Settings& settings)
: selector(associated_thread, settings),
real_time_domain(new internal::RealTimeDomain()) {
if (settings.randomised_sampling_enabled) {
random_generator = std::mt19937_64(RandUint64());
uniform_distribution = std::uniform_real_distribution<double>(0.0, 1.0);
}
task_execution_stack.reserve(kInitialTaskExecutionStackReserveCount);
}
SequenceManagerImpl::MainThreadOnly::~MainThreadOnly() = default;
// static
std::unique_ptr<ThreadControllerImpl>
SequenceManagerImpl::CreateThreadControllerImplForCurrentThread(
const TickClock* clock) {
auto* sequence_manager = GetTLSSequenceManagerImpl()->Get();
return ThreadControllerImpl::Create(sequence_manager, clock);
}
// static
std::unique_ptr<SequenceManagerImpl> SequenceManagerImpl::CreateOnCurrentThread(
SequenceManager::Settings settings) {
std::unique_ptr<SequenceManagerImpl> manager(new SequenceManagerImpl(
CreateThreadControllerImplForCurrentThread(settings.clock),
std::move(settings)));
manager->BindToCurrentThread();
return manager;
}
// static
std::unique_ptr<SequenceManagerImpl> SequenceManagerImpl::CreateUnbound(
SequenceManager::Settings settings) {
return WrapUnique(new SequenceManagerImpl(
ThreadControllerWithMessagePumpImpl::CreateUnbound(settings),
std::move(settings)));
}
// static
std::unique_ptr<SequenceManagerImpl>
SequenceManagerImpl::CreateSequenceFunneled(
scoped_refptr<SingleThreadTaskRunner> task_runner,
SequenceManager::Settings settings) {
return WrapUnique(
new SequenceManagerImpl(ThreadControllerImpl::CreateSequenceFunneled(
std::move(task_runner), settings.clock),
std::move(settings)));
}
void SequenceManagerImpl::BindToMessagePump(std::unique_ptr<MessagePump> pump) {
controller_->BindToCurrentThread(std::move(pump));
CompleteInitializationOnBoundThread();
// On Android attach to the native loop when there is one.
#if defined(OS_ANDROID)
if (settings_.message_loop_type == MessagePumpType::UI ||
settings_.message_loop_type == MessagePumpType::JAVA) {
controller_->AttachToMessagePump();
}
#endif
// On iOS attach to the native loop when there is one.
#if defined(OS_IOS)
if (settings_.message_loop_type == MessagePumpType::UI) {
controller_->AttachToMessagePump();
}
#endif
}
void SequenceManagerImpl::BindToCurrentThread() {
associated_thread_->BindToCurrentThread();
CompleteInitializationOnBoundThread();
}
void SequenceManagerImpl::BindToCurrentThread(
std::unique_ptr<MessagePump> pump) {
associated_thread_->BindToCurrentThread();
BindToMessagePump(std::move(pump));
}
const scoped_refptr<SequencedTaskRunner>&
SequenceManagerImpl::GetTaskRunnerForCurrentTask() {
DCHECK_CALLED_ON_VALID_THREAD(associated_thread_->thread_checker);
if (main_thread_only().task_execution_stack.empty())
return GetNullTaskRunner();
return main_thread_only()
.task_execution_stack.back()
.pending_task.task_runner;
}
void SequenceManagerImpl::CompleteInitializationOnBoundThread() {
controller_->AddNestingObserver(this);
main_thread_only().nesting_observer_registered_ = true;
if (GetMessagePump()) {
DCHECK(!GetTLSSequenceManagerImpl()->Get())
<< "Can't register a second SequenceManagerImpl on the same thread.";
GetTLSSequenceManagerImpl()->Set(this);
}
}
void SequenceManagerImpl::RegisterTimeDomain(TimeDomain* time_domain) {
main_thread_only().time_domains.insert(time_domain);
time_domain->OnRegisterWithSequenceManager(this);
}
void SequenceManagerImpl::UnregisterTimeDomain(TimeDomain* time_domain) {
main_thread_only().time_domains.erase(time_domain);
}
TimeDomain* SequenceManagerImpl::GetRealTimeDomain() const {
return main_thread_only().real_time_domain.get();
}
std::unique_ptr<internal::TaskQueueImpl>
SequenceManagerImpl::CreateTaskQueueImpl(const TaskQueue::Spec& spec) {
DCHECK_CALLED_ON_VALID_THREAD(associated_thread_->thread_checker);
TimeDomain* time_domain = spec.time_domain
? spec.time_domain
: main_thread_only().real_time_domain.get();
DCHECK(main_thread_only().time_domains.find(time_domain) !=
main_thread_only().time_domains.end());
std::unique_ptr<internal::TaskQueueImpl> task_queue =
std::make_unique<internal::TaskQueueImpl>(this, time_domain, spec);
main_thread_only().active_queues.insert(task_queue.get());
main_thread_only().selector.AddQueue(task_queue.get());
return task_queue;
}
void SequenceManagerImpl::SetAddQueueTimeToTasks(bool enable) {
base::subtle::NoBarrier_Store(&add_queue_time_to_tasks_, enable ? 1 : 0);
}
bool SequenceManagerImpl::GetAddQueueTimeToTasks() {
return base::subtle::NoBarrier_Load(&add_queue_time_to_tasks_);
}
void SequenceManagerImpl::SetObserver(Observer* observer) {
main_thread_only().observer = observer;
}
void SequenceManagerImpl::ShutdownTaskQueueGracefully(
std::unique_ptr<internal::TaskQueueImpl> task_queue) {
main_thread_only().queues_to_gracefully_shutdown[task_queue.get()] =
std::move(task_queue);
}
void SequenceManagerImpl::UnregisterTaskQueueImpl(
std::unique_ptr<internal::TaskQueueImpl> task_queue) {
TRACE_EVENT1("sequence_manager", "SequenceManagerImpl::UnregisterTaskQueue",
"queue_name", task_queue->GetName());
DCHECK_CALLED_ON_VALID_THREAD(associated_thread_->thread_checker);
main_thread_only().selector.RemoveQueue(task_queue.get());
// After UnregisterTaskQueue returns no new tasks can be posted.
// It's important to call it first to avoid race condition between removing
// the task queue from various lists here and adding it to the same lists
// when posting a task.
task_queue->UnregisterTaskQueue();
// Add |task_queue| to |main_thread_only().queues_to_delete| so we can prevent
// it from being freed while any of our structures hold hold a raw pointer to
// it.
main_thread_only().active_queues.erase(task_queue.get());
main_thread_only().queues_to_delete[task_queue.get()] = std::move(task_queue);
}
AtomicFlagSet::AtomicFlag
SequenceManagerImpl::GetFlagToRequestReloadForEmptyQueue(
TaskQueueImpl* task_queue) {
return empty_queues_to_reload_.AddFlag(BindRepeating(
&TaskQueueImpl::ReloadEmptyImmediateWorkQueue, Unretained(task_queue)));
}
void SequenceManagerImpl::ReloadEmptyWorkQueues() const {
// There are two cases where a queue needs reloading. First, it might be
// completely empty and we've just posted a task (this method handles that
// case). Secondly if the work queue becomes empty when calling
// WorkQueue::TakeTaskFromWorkQueue (handled there).
//
// Invokes callbacks created by GetFlagToRequestReloadForEmptyQueue above.
empty_queues_to_reload_.RunActiveCallbacks();
}
void SequenceManagerImpl::MoveReadyDelayedTasksToWorkQueues(LazyNow* lazy_now) {
TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("sequence_manager"),
"SequenceManagerImpl::MoveReadyDelayedTasksToWorkQueues");
for (TimeDomain* time_domain : main_thread_only().time_domains) {
if (time_domain == main_thread_only().real_time_domain.get()) {
time_domain->MoveReadyDelayedTasksToWorkQueues(lazy_now);
} else {
LazyNow time_domain_lazy_now = time_domain->CreateLazyNow();
time_domain->MoveReadyDelayedTasksToWorkQueues(&time_domain_lazy_now);
}
}
}
void SequenceManagerImpl::OnBeginNestedRunLoop() {
main_thread_only().nesting_depth++;
if (main_thread_only().observer)
main_thread_only().observer->OnBeginNestedRunLoop();
}
void SequenceManagerImpl::OnExitNestedRunLoop() {
main_thread_only().nesting_depth--;
DCHECK_GE(main_thread_only().nesting_depth, 0);
if (main_thread_only().nesting_depth == 0) {
// While we were nested some non-nestable tasks may have been deferred.
// We push them back onto the *front* of their original work queues,
// that's why we iterate |non_nestable_task_queue| in FIFO order.
while (!main_thread_only().non_nestable_task_queue.empty()) {
internal::TaskQueueImpl::DeferredNonNestableTask& non_nestable_task =
main_thread_only().non_nestable_task_queue.back();
non_nestable_task.task_queue->RequeueDeferredNonNestableTask(
std::move(non_nestable_task));
main_thread_only().non_nestable_task_queue.pop_back();
}
}
if (main_thread_only().observer)
main_thread_only().observer->OnExitNestedRunLoop();
}
void SequenceManagerImpl::ScheduleWork() {
controller_->ScheduleWork();
}
void SequenceManagerImpl::SetNextDelayedDoWork(LazyNow* lazy_now,
TimeTicks run_time) {
controller_->SetNextDelayedDoWork(lazy_now, run_time);
}
namespace {
const char* RunTaskTraceNameForPriority(TaskQueue::QueuePriority priority) {
switch (priority) {
case TaskQueue::QueuePriority::kControlPriority:
return "RunControlPriorityTask";
case TaskQueue::QueuePriority::kHighestPriority:
return "RunHighestPriorityTask";
case TaskQueue::QueuePriority::kVeryHighPriority:
return "RunVeryHighPriorityTask";
case TaskQueue::QueuePriority::kHighPriority:
return "RunHighPriorityTask";
case TaskQueue::QueuePriority::kNormalPriority:
return "RunNormalPriorityTask";
case TaskQueue::QueuePriority::kLowPriority:
return "RunLowPriorityTask";
case TaskQueue::QueuePriority::kBestEffortPriority:
return "RunBestEffortPriorityTask";
case TaskQueue::QueuePriority::kQueuePriorityCount:
NOTREACHED();
return nullptr;
}
}
} // namespace
Task* SequenceManagerImpl::SelectNextTask() {
Task* task = SelectNextTaskImpl();
if (!task)
return nullptr;
ExecutingTask& executing_task =
*main_thread_only().task_execution_stack.rbegin();
// It's important that there are no active trace events here which will
// terminate before we finish executing the task.
TRACE_EVENT_BEGIN1("sequence_manager",
RunTaskTraceNameForPriority(executing_task.priority),
"task_type", executing_task.task_type);
TRACE_EVENT_BEGIN0("sequence_manager", executing_task.task_queue_name);
return task;
}
#if DCHECK_IS_ON() && !defined(OS_NACL)
void SequenceManagerImpl::LogTaskDebugInfo(
const WorkQueue* selected_work_queue) const {
const Task* task = selected_work_queue->GetFrontTask();
switch (settings_.task_execution_logging) {
case Settings::TaskLogging::kNone:
break;
case Settings::TaskLogging::kEnabled:
LOG(INFO) << "#" << static_cast<uint64_t>(task->enqueue_order()) << " "
<< selected_work_queue->task_queue()->GetName()
<< (task->cross_thread_ ? " Run crossthread " : " Run ")
<< task->posted_from.ToString();
break;
case Settings::TaskLogging::kEnabledWithBacktrace: {
std::array<const void*, PendingTask::kTaskBacktraceLength + 1> task_trace;
task_trace[0] = task->posted_from.program_counter();
std::copy(task->task_backtrace.begin(), task->task_backtrace.end(),
task_trace.begin() + 1);
size_t length = 0;
while (length < task_trace.size() && task_trace[length])
++length;
if (length == 0)
break;
LOG(INFO) << "#" << static_cast<uint64_t>(task->enqueue_order()) << " "
<< selected_work_queue->task_queue()->GetName()
<< (task->cross_thread_ ? " Run crossthread " : " Run ")
<< debug::StackTrace(task_trace.data(), length);
break;
}
case Settings::TaskLogging::kReorderedOnly: {
std::vector<const Task*> skipped_tasks;
main_thread_only().selector.CollectSkippedOverLowerPriorityTasks(
selected_work_queue, &skipped_tasks);
if (skipped_tasks.empty())
break;
LOG(INFO) << "#" << static_cast<uint64_t>(task->enqueue_order()) << " "
<< selected_work_queue->task_queue()->GetName()
<< (task->cross_thread_ ? " Run crossthread " : " Run ")
<< task->posted_from.ToString();
for (const Task* skipped_task : skipped_tasks) {
LOG(INFO) << "# (skipped over) "
<< static_cast<uint64_t>(skipped_task->enqueue_order()) << " "
<< skipped_task->posted_from.ToString();
}
}
}
}
#endif // DCHECK_IS_ON() && !defined(OS_NACL)
Task* SequenceManagerImpl::SelectNextTaskImpl() {
CHECK(Validate());
DCHECK_CALLED_ON_VALID_THREAD(associated_thread_->thread_checker);
TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("sequence_manager"),
"SequenceManagerImpl::SelectNextTask");
ReloadEmptyWorkQueues();
LazyNow lazy_now(controller_->GetClock());
MoveReadyDelayedTasksToWorkQueues(&lazy_now);
// If we sampled now, check if it's time to reclaim memory next time we go
// idle.
if (lazy_now.has_value() &&
lazy_now.Now() >= main_thread_only().next_time_to_reclaim_memory) {
main_thread_only().memory_reclaim_scheduled = true;
}
while (true) {
internal::WorkQueue* work_queue =
main_thread_only().selector.SelectWorkQueueToService();
TRACE_EVENT_OBJECT_SNAPSHOT_WITH_ID(
TRACE_DISABLED_BY_DEFAULT("sequence_manager.debug"), "SequenceManager",
this, AsValueWithSelectorResult(work_queue, /* force_verbose */ false));
if (!work_queue)
return nullptr;
// If the head task was canceled, remove it and run the selector again.
if (UNLIKELY(work_queue->RemoveAllCanceledTasksFromFront()))
continue;
if (UNLIKELY(work_queue->GetFrontTask()->nestable ==
Nestable::kNonNestable &&
main_thread_only().nesting_depth > 0)) {
// Defer non-nestable work. NOTE these tasks can be arbitrarily delayed so
// the additional delay should not be a problem.
// Note because we don't delete queues while nested, it's perfectly OK to
// store the raw pointer for |queue| here.
internal::TaskQueueImpl::DeferredNonNestableTask deferred_task{
work_queue->TakeTaskFromWorkQueue(), work_queue->task_queue(),
work_queue->queue_type()};
main_thread_only().non_nestable_task_queue.push_back(
std::move(deferred_task));
continue;
}
if (UNLIKELY(!ShouldRunTaskOfPriority(
work_queue->task_queue()->GetQueuePriority()))) {
TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("sequence_manager"),
"SequenceManager.YieldToNative");
return nullptr;
}
#if DCHECK_IS_ON() && !defined(OS_NACL)
LogTaskDebugInfo(work_queue);
#endif // DCHECK_IS_ON() && !defined(OS_NACL)
main_thread_only().task_execution_stack.emplace_back(
work_queue->TakeTaskFromWorkQueue(), work_queue->task_queue(),
InitializeTaskTiming(work_queue->task_queue()));
ExecutingTask& executing_task =
*main_thread_only().task_execution_stack.rbegin();
NotifyWillProcessTask(&executing_task, &lazy_now);
return &executing_task.pending_task;
}
}
bool SequenceManagerImpl::ShouldRunTaskOfPriority(
TaskQueue::QueuePriority priority) const {
return priority <= *main_thread_only().pending_native_work.begin();
}
void SequenceManagerImpl::DidRunTask() {
LazyNow lazy_now(controller_->GetClock());
ExecutingTask& executing_task =
*main_thread_only().task_execution_stack.rbegin();
TRACE_EVENT_END0("sequence_manager", executing_task.task_queue_name);
TRACE_EVENT_END0("sequence_manager",
RunTaskTraceNameForPriority(executing_task.priority));
NotifyDidProcessTask(&executing_task, &lazy_now);
main_thread_only().task_execution_stack.pop_back();
if (main_thread_only().nesting_depth == 0)
CleanUpQueues();
}
TimeDelta SequenceManagerImpl::DelayTillNextTask(LazyNow* lazy_now) const {
DCHECK_CALLED_ON_VALID_THREAD(associated_thread_->thread_checker);
if (auto priority = main_thread_only().selector.GetHighestPendingPriority()) {
// If the selector has non-empty queues we trivially know there is immediate
// work to be done. However we may want to yield to native work if it is
// more important.
if (UNLIKELY(!ShouldRunTaskOfPriority(*priority)))
return GetDelayTillNextDelayedTask(lazy_now);
return TimeDelta();
}
// There may be some incoming immediate work which we haven't accounted for.
// NB ReloadEmptyWorkQueues involves a memory barrier, so it's fastest to not
// do this always.
ReloadEmptyWorkQueues();
if (auto priority = main_thread_only().selector.GetHighestPendingPriority()) {
if (UNLIKELY(!ShouldRunTaskOfPriority(*priority)))
return GetDelayTillNextDelayedTask(lazy_now);
return TimeDelta();
}
// Otherwise we need to find the shortest delay, if any. NB we don't need to
// call MoveReadyDelayedTasksToWorkQueues because it's assumed
// DelayTillNextTask will return TimeDelta>() if the delayed task is due to
// run now.
return GetDelayTillNextDelayedTask(lazy_now);
}
TimeDelta SequenceManagerImpl::GetDelayTillNextDelayedTask(
LazyNow* lazy_now) const {
DCHECK_CALLED_ON_VALID_THREAD(associated_thread_->thread_checker);
TimeDelta delay_till_next_task = TimeDelta::Max();
for (TimeDomain* time_domain : main_thread_only().time_domains) {
Optional<TimeDelta> delay = time_domain->DelayTillNextTask(lazy_now);
if (!delay)
continue;
if (*delay < delay_till_next_task)
delay_till_next_task = *delay;
}
return delay_till_next_task;
}
bool SequenceManagerImpl::HasPendingHighResolutionTasks() {
for (TimeDomain* time_domain : main_thread_only().time_domains) {
if (time_domain->HasPendingHighResolutionTasks())
return true;
}
return false;
}
bool SequenceManagerImpl::OnSystemIdle() {
bool have_work_to_do = false;
for (TimeDomain* time_domain : main_thread_only().time_domains) {
if (time_domain->MaybeFastForwardToNextTask(
controller_->ShouldQuitRunLoopWhenIdle())) {
have_work_to_do = true;
}
}
if (!have_work_to_do)
MaybeReclaimMemory();
return have_work_to_do;
}
void SequenceManagerImpl::WillQueueTask(Task* pending_task,
const char* task_queue_name) {
controller_->WillQueueTask(pending_task, task_queue_name);
}
TaskQueue::TaskTiming SequenceManagerImpl::InitializeTaskTiming(
internal::TaskQueueImpl* task_queue) {
bool records_wall_time =
ShouldRecordTaskTiming(task_queue) == TimeRecordingPolicy::DoRecord;
bool records_thread_time = records_wall_time && ShouldRecordCPUTimeForTask();
return TaskQueue::TaskTiming(records_wall_time, records_thread_time);
}
TimeRecordingPolicy SequenceManagerImpl::ShouldRecordTaskTiming(
const internal::TaskQueueImpl* task_queue) {
if (task_queue->RequiresTaskTiming())
return TimeRecordingPolicy::DoRecord;
if (main_thread_only().nesting_depth == 0 &&
main_thread_only().task_time_observers.might_have_observers()) {
return TimeRecordingPolicy::DoRecord;
}
return TimeRecordingPolicy::DoNotRecord;
}
void SequenceManagerImpl::NotifyWillProcessTask(ExecutingTask* executing_task,
LazyNow* time_before_task) {
TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("sequence_manager"),
"SequenceManagerImpl::NotifyWillProcessTaskObservers");
RecordCrashKeys(executing_task->pending_task);
if (executing_task->task_queue->GetQuiescenceMonitored())
main_thread_only().task_was_run_on_quiescence_monitored_queue = true;
TimeRecordingPolicy recording_policy =
ShouldRecordTaskTiming(executing_task->task_queue);
if (recording_policy == TimeRecordingPolicy::DoRecord)
executing_task->task_timing.RecordTaskStart(time_before_task);
if (!executing_task->task_queue->GetShouldNotifyObservers())
return;
const bool was_blocked_or_low_priority =
executing_task->task_queue->WasBlockedOrLowPriority(
executing_task->pending_task.enqueue_order());
{
TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("sequence_manager"),
"SequenceManager.WillProcessTaskObservers");
for (auto& observer : main_thread_only().task_observers) {
observer.WillProcessTask(executing_task->pending_task,
was_blocked_or_low_priority);
}
}
{
TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("sequence_manager"),
"SequenceManager.QueueNotifyWillProcessTask");
executing_task->task_queue->NotifyWillProcessTask(
executing_task->pending_task, was_blocked_or_low_priority);
}
if (recording_policy != TimeRecordingPolicy::DoRecord)
return;
if (main_thread_only().nesting_depth == 0) {
TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("sequence_manager"),
"SequenceManager.WillProcessTaskTimeObservers");
for (auto& observer : main_thread_only().task_time_observers)
observer.WillProcessTask(executing_task->task_timing.start_time());
}
{
TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("sequence_manager"),
"SequenceManager.QueueOnTaskStarted");
executing_task->task_queue->OnTaskStarted(executing_task->pending_task,
executing_task->task_timing);
}
}
void SequenceManagerImpl::NotifyDidProcessTask(ExecutingTask* executing_task,
LazyNow* time_after_task) {
TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("sequence_manager"),
"SequenceManagerImpl::NotifyDidProcessTaskObservers");
if (!executing_task->task_queue->GetShouldNotifyObservers())
return;
TaskQueue::TaskTiming& task_timing = executing_task->task_timing;
{
TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("sequence_manager"),
"SequenceManager.QueueOnTaskCompleted");
if (task_timing.has_wall_time()) {
executing_task->task_queue->OnTaskCompleted(
executing_task->pending_task, &task_timing, time_after_task);
}
}
TimeRecordingPolicy recording_policy =
ShouldRecordTaskTiming(executing_task->task_queue);
// Record end time ASAP to avoid bias due to the overhead of observers.
if (recording_policy == TimeRecordingPolicy::DoRecord)
task_timing.RecordTaskEnd(time_after_task);
if (task_timing.has_wall_time() && main_thread_only().nesting_depth == 0) {
TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("sequence_manager"),
"SequenceManager.DidProcessTaskTimeObservers");
for (auto& observer : main_thread_only().task_time_observers) {
observer.DidProcessTask(task_timing.start_time(), task_timing.end_time());
}
}
{
TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("sequence_manager"),
"SequenceManager.DidProcessTaskObservers");
for (auto& observer : main_thread_only().task_observers)
observer.DidProcessTask(executing_task->pending_task);
}
{
TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("sequence_manager"),
"SequenceManager.QueueNotifyDidProcessTask");
executing_task->task_queue->NotifyDidProcessTask(
executing_task->pending_task);
}
// TODO(altimin): Move this back to blink.
if (task_timing.has_wall_time() &&
recording_policy == TimeRecordingPolicy::DoRecord &&
task_timing.wall_duration() > kLongTaskTraceEventThreshold &&
main_thread_only().nesting_depth == 0) {
TRACE_EVENT_INSTANT1("blink", "LongTask", TRACE_EVENT_SCOPE_THREAD,
"duration", task_timing.wall_duration().InSecondsF());
}
}
void SequenceManagerImpl::SetWorkBatchSize(int work_batch_size) {
DCHECK_CALLED_ON_VALID_THREAD(associated_thread_->thread_checker);
DCHECK_GE(work_batch_size, 1);
controller_->SetWorkBatchSize(work_batch_size);
}
void SequenceManagerImpl::SetTimerSlack(TimerSlack timer_slack) {
DCHECK_CALLED_ON_VALID_THREAD(associated_thread_->thread_checker);
controller_->SetTimerSlack(timer_slack);
}
void SequenceManagerImpl::AddTaskObserver(TaskObserver* task_observer) {
DCHECK_CALLED_ON_VALID_THREAD(associated_thread_->thread_checker);
main_thread_only().task_observers.AddObserver(task_observer);
}
void SequenceManagerImpl::RemoveTaskObserver(TaskObserver* task_observer) {
DCHECK_CALLED_ON_VALID_THREAD(associated_thread_->thread_checker);
main_thread_only().task_observers.RemoveObserver(task_observer);
}
void SequenceManagerImpl::AddTaskTimeObserver(
TaskTimeObserver* task_time_observer) {
DCHECK_CALLED_ON_VALID_THREAD(associated_thread_->thread_checker);
main_thread_only().task_time_observers.AddObserver(task_time_observer);
}
void SequenceManagerImpl::RemoveTaskTimeObserver(
TaskTimeObserver* task_time_observer) {
DCHECK_CALLED_ON_VALID_THREAD(associated_thread_->thread_checker);
main_thread_only().task_time_observers.RemoveObserver(task_time_observer);
}
bool SequenceManagerImpl::GetAndClearSystemIsQuiescentBit() {
bool task_was_run =
main_thread_only().task_was_run_on_quiescence_monitored_queue;
main_thread_only().task_was_run_on_quiescence_monitored_queue = false;
return !task_was_run;
}
EnqueueOrder SequenceManagerImpl::GetNextSequenceNumber() {
return enqueue_order_generator_.GenerateNext();
}
std::unique_ptr<trace_event::ConvertableToTraceFormat>
SequenceManagerImpl::AsValueWithSelectorResult(
internal::WorkQueue* selected_work_queue,
bool force_verbose) const {
DCHECK_CALLED_ON_VALID_THREAD(associated_thread_->thread_checker);
std::unique_ptr<trace_event::TracedValue> state(
new trace_event::TracedValue());
TimeTicks now = NowTicks();
state->BeginArray("active_queues");
for (auto* const queue : main_thread_only().active_queues)
queue->AsValueInto(now, state.get(), force_verbose);
state->EndArray();
state->BeginArray("queues_to_gracefully_shutdown");
for (const auto& pair : main_thread_only().queues_to_gracefully_shutdown)
pair.first->AsValueInto(now, state.get(), force_verbose);
state->EndArray();
state->BeginArray("queues_to_delete");
for (const auto& pair : main_thread_only().queues_to_delete)
pair.first->AsValueInto(now, state.get(), force_verbose);
state->EndArray();
state->BeginDictionary("selector");
main_thread_only().selector.AsValueInto(state.get());
state->EndDictionary();
if (selected_work_queue) {
state->SetString("selected_queue",
selected_work_queue->task_queue()->GetName());
state->SetString("work_queue_name", selected_work_queue->name());
}
state->SetString("native_work_priority",
TaskQueue::PriorityToString(
*main_thread_only().pending_native_work.begin()));
state->BeginArray("time_domains");
for (auto* time_domain : main_thread_only().time_domains)
time_domain->AsValueInto(state.get());
state->EndArray();
return std::move(state);
}
void SequenceManagerImpl::OnTaskQueueEnabled(internal::TaskQueueImpl* queue) {
DCHECK_CALLED_ON_VALID_THREAD(associated_thread_->thread_checker);
DCHECK(queue->IsQueueEnabled());
// Only schedule DoWork if there's something to do.
if (queue->HasTaskToRunImmediately() && !queue->BlockedByFence())
ScheduleWork();
}
void SequenceManagerImpl::MaybeReclaimMemory() {
if (!main_thread_only().memory_reclaim_scheduled)
return;
TRACE_EVENT0("sequence_manager", "SequenceManagerImpl::MaybeReclaimMemory");
ReclaimMemory();
// To avoid performance regressions we only want to do this every so often.
main_thread_only().next_time_to_reclaim_memory =
NowTicks() + kReclaimMemoryInterval;
main_thread_only().memory_reclaim_scheduled = false;
}
void SequenceManagerImpl::ReclaimMemory() {
std::map<TimeDomain*, TimeTicks> time_domain_now;
for (auto* const queue : main_thread_only().active_queues)
ReclaimMemoryFromQueue(queue, &time_domain_now);
for (const auto& pair : main_thread_only().queues_to_gracefully_shutdown)
ReclaimMemoryFromQueue(pair.first, &time_domain_now);
}
void SequenceManagerImpl::CleanUpQueues() {
for (auto it = main_thread_only().queues_to_gracefully_shutdown.begin();
it != main_thread_only().queues_to_gracefully_shutdown.end();) {
if (it->first->IsEmpty()) {
UnregisterTaskQueueImpl(std::move(it->second));
main_thread_only().active_queues.erase(it->first);
main_thread_only().queues_to_gracefully_shutdown.erase(it++);
} else {
++it;
}
}
main_thread_only().queues_to_delete.clear();
}
void SequenceManagerImpl::RemoveAllCanceledTasksFromFrontOfWorkQueues() {
for (internal::TaskQueueImpl* queue : main_thread_only().active_queues) {
queue->delayed_work_queue()->RemoveAllCanceledTasksFromFront();
queue->immediate_work_queue()->RemoveAllCanceledTasksFromFront();
}
}
WeakPtr<SequenceManagerImpl> SequenceManagerImpl::GetWeakPtr() {
return weak_factory_.GetWeakPtr();
}
void SequenceManagerImpl::SetDefaultTaskRunner(
scoped_refptr<SingleThreadTaskRunner> task_runner) {
controller_->SetDefaultTaskRunner(task_runner);
}
const TickClock* SequenceManagerImpl::GetTickClock() const {
return controller_->GetClock();
}
TimeTicks SequenceManagerImpl::NowTicks() const {
return controller_->GetClock()->NowTicks();
}
bool SequenceManagerImpl::ShouldRecordCPUTimeForTask() {
DCHECK(ThreadTicks::IsSupported() ||
!metric_recording_settings_.records_cpu_time_for_some_tasks());
return metric_recording_settings_.records_cpu_time_for_some_tasks() &&
main_thread_only().uniform_distribution(
main_thread_only().random_generator) <
metric_recording_settings_
.task_sampling_rate_for_recording_cpu_time;
}
const SequenceManager::MetricRecordingSettings&
SequenceManagerImpl::GetMetricRecordingSettings() const {
return metric_recording_settings_;
}
// TODO(altimin): Ensure that this removes all pending tasks.
void SequenceManagerImpl::DeletePendingTasks() {
DCHECK(main_thread_only().task_execution_stack.empty())
<< "Tasks should be deleted outside RunLoop";
for (TaskQueueImpl* task_queue : main_thread_only().active_queues)
task_queue->DeletePendingTasks();
for (const auto& it : main_thread_only().queues_to_gracefully_shutdown)
it.first->DeletePendingTasks();
for (const auto& it : main_thread_only().queues_to_delete)
it.first->DeletePendingTasks();
}
bool SequenceManagerImpl::HasTasks() {
DCHECK_CALLED_ON_VALID_THREAD(associated_thread_->thread_checker);
RemoveAllCanceledTasksFromFrontOfWorkQueues();
for (TaskQueueImpl* task_queue : main_thread_only().active_queues) {
if (task_queue->HasTasks())
return true;
}
for (const auto& it : main_thread_only().queues_to_gracefully_shutdown) {
if (it.first->HasTasks())
return true;
}
for (const auto& it : main_thread_only().queues_to_delete) {
if (it.first->HasTasks())
return true;
}
return false;
}
MessagePumpType SequenceManagerImpl::GetType() const {
return settings_.message_loop_type;
}
void SequenceManagerImpl::SetTaskExecutionAllowed(bool allowed) {
controller_->SetTaskExecutionAllowed(allowed);
}
bool SequenceManagerImpl::IsTaskExecutionAllowed() const {
return controller_->IsTaskExecutionAllowed();
}
#if defined(OS_IOS)
void SequenceManagerImpl::AttachToMessagePump() {
return controller_->AttachToMessagePump();
}
#endif
bool SequenceManagerImpl::IsIdleForTesting() {
ReloadEmptyWorkQueues();
RemoveAllCanceledTasksFromFrontOfWorkQueues();
return !main_thread_only().selector.GetHighestPendingPriority().has_value();
}
size_t SequenceManagerImpl::GetPendingTaskCountForTesting() const {
size_t total = 0;
for (internal::TaskQueueImpl* task_queue : main_thread_only().active_queues) {
total += task_queue->GetNumberOfPendingTasks();
}
return total;
}
scoped_refptr<TaskQueue> SequenceManagerImpl::CreateTaskQueue(
const TaskQueue::Spec& spec) {
return WrapRefCounted(new TaskQueue(CreateTaskQueueImpl(spec), spec));
}
std::string SequenceManagerImpl::DescribeAllPendingTasks() const {
return AsValueWithSelectorResult(nullptr, /* force_verbose */ true)
->ToString();
}
std::unique_ptr<NativeWorkHandle> SequenceManagerImpl::OnNativeWorkPending(
TaskQueue::QueuePriority priority) {
return std::make_unique<NativeWorkHandleImpl>(this, priority);
}
void SequenceManagerImpl::AddDestructionObserver(
MessageLoopCurrent::DestructionObserver* destruction_observer) {
main_thread_only().destruction_observers.AddObserver(destruction_observer);
}
void SequenceManagerImpl::RemoveDestructionObserver(
MessageLoopCurrent::DestructionObserver* destruction_observer) {
main_thread_only().destruction_observers.RemoveObserver(destruction_observer);
}
void SequenceManagerImpl::SetTaskRunner(
scoped_refptr<SingleThreadTaskRunner> task_runner) {
controller_->SetDefaultTaskRunner(task_runner);
}
scoped_refptr<SingleThreadTaskRunner> SequenceManagerImpl::GetTaskRunner() {
return controller_->GetDefaultTaskRunner();
}
bool SequenceManagerImpl::IsBoundToCurrentThread() const {
return associated_thread_->IsBoundToCurrentThread();
}
MessagePump* SequenceManagerImpl::GetMessagePump() const {
return controller_->GetBoundMessagePump();
}
bool SequenceManagerImpl::IsType(MessagePumpType type) const {
return settings_.message_loop_type == type;
}
NOINLINE bool SequenceManagerImpl::Validate() {
return memory_corruption_sentinel_ == kMemoryCorruptionSentinelValue;
}
void SequenceManagerImpl::EnableCrashKeys(const char* async_stack_crash_key) {
DCHECK(!main_thread_only().async_stack_crash_key);
#if !defined(OS_NACL)
main_thread_only().async_stack_crash_key = debug::AllocateCrashKeyString(
async_stack_crash_key, debug::CrashKeySize::Size64);
static_assert(sizeof(main_thread_only().async_stack_buffer) ==
static_cast<size_t>(debug::CrashKeySize::Size64),
"Async stack buffer size must match crash key size.");
#endif // OS_NACL
}
void SequenceManagerImpl::RecordCrashKeys(const PendingTask& pending_task) {
#if !defined(OS_NACL)
// SetCrashKeyString is a no-op even if the crash key is null, but we'd still
// have construct the StringPiece that is passed in.
if (!main_thread_only().async_stack_crash_key)
return;
// Write the async stack trace onto a crash key as whitespace-delimited hex
// addresses. These will be symbolized by the crash reporting system. With
// 63 characters we can fit the address of the task that posted the current
// task and its predecessor. Avoid HexEncode since it incurs a memory
// allocation and snprintf because it's about 3.5x slower on Android this
// this.
//
// See
// https://chromium.googlesource.com/chromium/src/+/master/docs/debugging_with_crash_keys.md
// for instructions for symbolizing these crash keys.
//
// TODO(skyostil): Find a way to extract the destination function address
// from the task.
size_t max_size = main_thread_only().async_stack_buffer.size();
char* const buffer = &main_thread_only().async_stack_buffer[0];
char* const buffer_end = &buffer[max_size - 1];
char* pos = buffer_end;
// Leave space for the NUL terminator.
pos = PrependHexAddress(pos - 1, pending_task.task_backtrace[0]);
*(--pos) = ' ';
pos = PrependHexAddress(pos - 1, pending_task.posted_from.program_counter());
DCHECK_GE(pos, buffer);
debug::SetCrashKeyString(main_thread_only().async_stack_crash_key,
StringPiece(pos, buffer_end - pos));
#endif // OS_NACL
}
internal::TaskQueueImpl* SequenceManagerImpl::currently_executing_task_queue()
const {
if (main_thread_only().task_execution_stack.empty())
return nullptr;
return main_thread_only().task_execution_stack.rbegin()->task_queue;
}
constexpr TimeDelta SequenceManagerImpl::kReclaimMemoryInterval;
} // namespace internal
} // namespace sequence_manager
} // namespace base
|
/* ============================================================================
* Copyright (c) 2009-2016 BlueQuartz Software, LLC
*
* 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 BlueQuartz Software, the US Air Force, 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.
*
* The code contained herein was partially funded by the following contracts:
* United States Air Force Prime Contract FA8650-07-D-5800
* United States Air Force Prime Contract FA8650-10-D-5210
* United States Prime Contract Navy N00173-07-C-2068
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
#include "ChoiceWidget.h"
#include "SIMPLib/FilterParameters/LinkedChoicesFilterParameter.h"
#include "SIMPLib/Filtering/AbstractFilter.h"
#include "SIMPLib/Utilities/FilterCompatibility.hpp"
#include "FilterParameterWidgetsDialogs.h"
#include "SVWidgetsLib/Core/SVWidgetsLibConstants.h"
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
ChoiceWidget::ChoiceWidget(FilterParameter* parameter, AbstractFilter* filter, QWidget* parent)
: FilterParameterWidget(parameter, filter, parent)
{
m_FilterParameter = SIMPL_FILTER_PARAMETER_COMPATIBILITY_CHECK(filter, parameter, ChoiceWidget, ChoiceFilterParameter);
setupUi(this);
setupGui();
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
ChoiceWidget::~ChoiceWidget() = default;
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void ChoiceWidget::setupGui()
{
// Catch when the filter is about to execute the preflight
connect(getFilter(), &AbstractFilter::preflightAboutToExecute, this, &ChoiceWidget::beforePreflight);
// Catch when the filter is finished running the preflight
connect(getFilter(), &AbstractFilter::preflightExecuted, this, &ChoiceWidget::afterPreflight);
// Catch when the filter wants its values updated
connect(getFilter(), &AbstractFilter::updateFilterParameters, this, &ChoiceWidget::filterNeedsInputParameters);
connect(value, SIGNAL(currentIndexChanged(int)), this, SLOT(widgetChanged(int)));
if(getFilterParameter() != nullptr)
{
label->setText(getFilterParameter()->getHumanLabel());
// setup the list of choices for the widget
ChoiceFilterParameter* choice = dynamic_cast<ChoiceFilterParameter*>(getFilterParameter());
if(choice != nullptr)
{
std::vector<QString> choiceVec = choice->getChoices();
QList<QString> choices;
for(const QString& value : choiceVec)
{
choices.push_back(value);
}
value->blockSignals(true);
value->addItems(choices);
value->blockSignals(false);
}
// Get the Default value from the filter
int i = m_FilterParameter->getGetterCallback()();
value->setCurrentIndex(i);
}
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
int ChoiceWidget::getCurrentIndex()
{
return value->currentIndex();
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void ChoiceWidget::widgetChanged(int index, bool emitParametersChanged)
{
FilterParameter* fp = getFilterParameter();
// If the parameter type is LinkedChoicesFilterParameter then we need to emit the index that
// was selected
LinkedChoicesFilterParameter* lnkedChoices = dynamic_cast<LinkedChoicesFilterParameter*>(fp);
if(lnkedChoices != nullptr)
{
Q_EMIT conditionalPropertyChanged(index);
}
// We emit no matter what
if(emitParametersChanged)
{
Q_EMIT parametersChanged();
}
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void ChoiceWidget::filterNeedsInputParameters(AbstractFilter* filter)
{
Q_UNUSED(filter)
ChoiceFilterParameter::SetterCallbackType setter = m_FilterParameter->getSetterCallback();
if(setter)
{
setter(value->currentIndex());
}
else
{
getFilter()->notifyMissingProperty(getFilterParameter());
}
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void ChoiceWidget::beforePreflight()
{
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void ChoiceWidget::afterPreflight()
{
}
|
#pragma once
// This file is generated from the Game's Reflection data
#include <cstdint>
#include <RED4ext/Common.hpp>
#include <RED4ext/Scripting/Natives/Generated/quest/IGameManagerNodeType.hpp>
namespace RED4ext
{
namespace quest {
struct SetTimer_NodeType : quest::IGameManagerNodeType
{
static constexpr const char* NAME = "questSetTimer_NodeType";
static constexpr const char* ALIAS = NAME;
bool enable; // 38
uint8_t unk39[0x3C - 0x39]; // 39
float duration; // 3C
};
RED4EXT_ASSERT_SIZE(SetTimer_NodeType, 0x40);
} // namespace quest
} // namespace RED4ext
|
#ifndef _RAR_HEADERS_
#define _RAR_HEADERS_
#define SIZEOF_MARKHEAD 7
#define SIZEOF_OLDMHD 7
#define SIZEOF_NEWMHD 13
#define SIZEOF_OLDLHD 21
#define SIZEOF_NEWLHD 32
#define SIZEOF_SHORTBLOCKHEAD 7
#define SIZEOF_LONGBLOCKHEAD 11
#define SIZEOF_SUBBLOCKHEAD 14
#define SIZEOF_COMMHEAD 13
#define SIZEOF_PROTECTHEAD 26
#define SIZEOF_AVHEAD 14
#define SIZEOF_SIGNHEAD 15
#define SIZEOF_UOHEAD 18
#define SIZEOF_MACHEAD 22
#define SIZEOF_EAHEAD 24
#define SIZEOF_BEEAHEAD 24
#define SIZEOF_STREAMHEAD 26
#define PACK_VER 29
#define PACK_CRYPT_VER 29
#define UNP_VER 29
#define CRYPT_VER 29
#define AV_VER 20
#define PROTECT_VER 20
#define MHD_VOLUME 0x0001
#define MHD_COMMENT 0x0002
#define MHD_LOCK 0x0004
#define MHD_SOLID 0x0008
#define MHD_PACK_COMMENT 0x0010
#define MHD_NEWNUMBERING 0x0010
#define MHD_AV 0x0020
#define MHD_PROTECT 0x0040
#define MHD_PASSWORD 0x0080
#define MHD_FIRSTVOLUME 0x0100
#define LHD_SPLIT_BEFORE 0x0001
#define LHD_SPLIT_AFTER 0x0002
#define LHD_PASSWORD 0x0004
#define LHD_COMMENT 0x0008
#define LHD_SOLID 0x0010
#define LHD_WINDOWMASK 0x00e0
#define LHD_WINDOW64 0x0000
#define LHD_WINDOW128 0x0020
#define LHD_WINDOW256 0x0040
#define LHD_WINDOW512 0x0060
#define LHD_WINDOW1024 0x0080
#define LHD_WINDOW2048 0x00a0
#define LHD_WINDOW4096 0x00c0
#define LHD_DIRECTORY 0x00e0
#define LHD_LARGE 0x0100
#define LHD_UNICODE 0x0200
#define LHD_SALT 0x0400
#define LHD_VERSION 0x0800
#define LHD_EXTTIME 0x1000
#define LHD_EXTFLAGS 0x2000
#define SKIP_IF_UNKNOWN 0x4000
#define LONG_BLOCK 0x8000
#define EARC_NEXT_VOLUME 0x0001
#define EARC_DATACRC 0x0002
#define EARC_REVSPACE 0x0004
#define EARC_VOLNUMBER 0x0008
enum HEADER_TYPE {
MARK_HEAD=0x72,MAIN_HEAD=0x73,FILE_HEAD=0x74,COMM_HEAD=0x75,AV_HEAD=0x76,
SUB_HEAD=0x77,PROTECT_HEAD=0x78,SIGN_HEAD=0x79,NEWSUB_HEAD=0x7a,
ENDARC_HEAD=0x7b
};
enum { EA_HEAD=0x100,UO_HEAD=0x101,MAC_HEAD=0x102,BEEA_HEAD=0x103,
NTACL_HEAD=0x104,STREAM_HEAD=0x105 };
enum HOST_SYSTEM {
HOST_MSDOS=0,HOST_OS2=1,HOST_WIN32=2,HOST_UNIX=3,HOST_MACOS=4,
HOST_BEOS=5,HOST_MAX
};
#define SUBHEAD_TYPE_CMT "CMT"
#define SUBHEAD_TYPE_ACL "ACL"
#define SUBHEAD_TYPE_STREAM "STM"
#define SUBHEAD_TYPE_UOWNER "UOW"
#define SUBHEAD_TYPE_AV "AV"
#define SUBHEAD_TYPE_RR "RR"
#define SUBHEAD_TYPE_OS2EA "EA2"
#define SUBHEAD_TYPE_BEOSEA "EABE"
/* new file inherits a subblock when updating a host file */
#define SUBHEAD_FLAGS_INHERITED 0x80000000
#define SUBHEAD_FLAGS_CMT_UNICODE 0x00000001
struct OldMainHeader
{
byte Mark[4];
ushort HeadSize;
byte Flags;
};
struct OldFileHeader
{
uint PackSize;
uint UnpSize;
ushort FileCRC;
ushort HeadSize;
uint FileTime;
byte FileAttr;
byte Flags;
byte UnpVer;
byte NameSize;
byte Method;
};
struct MarkHeader
{
byte Mark[7];
};
struct BaseBlock
{
ushort HeadCRC;
HEADER_TYPE HeadType;//byte
ushort Flags;
ushort HeadSize;
bool IsSubBlock()
{
if (HeadType==SUB_HEAD)
return(true);
if (HeadType==NEWSUB_HEAD && (Flags & LHD_SOLID)!=0)
return(true);
return(false);
}
};
struct BlockHeader:BaseBlock
{
union {
uint DataSize;
uint PackSize;
};
};
struct MainHeader:BlockHeader
{
ushort HighPosAV;
uint PosAV;
};
#define SALT_SIZE 8
struct FileHeader:BlockHeader
{
uint UnpSize;
byte HostOS;
uint FileCRC;
uint FileTime;
byte UnpVer;
byte Method;
ushort NameSize;
union {
uint FileAttr;
uint SubFlags;
};
/* optional */
uint HighPackSize;
uint HighUnpSize;
/* names */
char FileName[NM];
wchar FileNameW[NM];
/* optional */
Array<byte> SubData;
byte Salt[SALT_SIZE];
RarTime mtime;
RarTime ctime;
RarTime atime;
RarTime arctime;
/* dummy */
Int64 FullPackSize;
Int64 FullUnpSize;
void Clear(int SubDataSize)
{
SubData.Alloc(SubDataSize);
Flags=LONG_BLOCK;
SubFlags=0;
}
bool CmpName(const char *Name)
{
return(strcmp(FileName,Name)==0);
}
FileHeader& operator = (FileHeader &hd)
{
SubData.Reset();
memcpy(this,&hd,sizeof(*this));
SubData.CleanData();
SubData=hd.SubData;
return(*this);
}
};
struct EndArcHeader:BaseBlock
{
uint ArcDataCRC;
ushort VolNumber;
};
struct SubBlockHeader:BlockHeader
{
ushort SubType;
byte Level;
};
struct CommentHeader:BaseBlock
{
ushort UnpSize;
byte UnpVer;
byte Method;
ushort CommCRC;
};
struct ProtectHeader:BlockHeader
{
byte Version;
ushort RecSectors;
uint TotalBlocks;
byte Mark[8];
};
struct AVHeader:BaseBlock
{
byte UnpVer;
byte Method;
byte AVVer;
uint AVInfoCRC;
};
struct SignHeader:BaseBlock
{
uint CreationTime;
ushort ArcNameSize;
ushort UserNameSize;
};
struct UnixOwnersHeader:SubBlockHeader
{
ushort OwnerNameSize;
ushort GroupNameSize;
/* dummy */
char OwnerName[NM];
char GroupName[NM];
};
struct EAHeader:SubBlockHeader
{
uint UnpSize;
byte UnpVer;
byte Method;
uint EACRC;
};
struct StreamHeader:SubBlockHeader
{
uint UnpSize;
byte UnpVer;
byte Method;
uint StreamCRC;
ushort StreamNameSize;
/* dummy */
byte StreamName[NM];
};
struct MacFInfoHeader:SubBlockHeader
{
uint fileType;
uint fileCreator;
};
#endif
|
#pragma once
//------------------------------------------------------------------------------
//
// Copyright 2018-2019 Fetch.AI Limited
//
// 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 "fetch_pybind.hpp"
namespace fetch {
namespace storage {
template <typename S>
void BuildFileObjectImplementation(std::string const &custom_name, pybind11::module &module)
{
/*
namespace py = pybind11;
py::class_<FileObjectImplementation< S >>(module, custom_name )
.def(py::init< const uint64_t &,
fetch::storage::FileObjectImplementation::stack_type & >()) .def("Read",
&FileObjectImplementation< S >::Read) .def("tell", &FileObjectImplementation<
S >::tell) .def("Write", &FileObjectImplementation< S >::Write)
.def("file_position", &FileObjectImplementation< S >::file_position)
.def("seek", &FileObjectImplementation< S >::seek)
.def("Shrink", &FileObjectImplementation< S >::Shrink)
.def("Size", &FileObjectImplementation< S >::Size);
*/
}
}; // namespace storage
}; // namespace fetch
|
#pragma once
#include <Register/Utility.hpp>
namespace Kvasir {
//Interrupts
namespace IntreqDrqsel{ ///<DMA Request Selection Register
using Addr = Register::Address<0x40031000,0x00000000,0x00000000,unsigned>;
///The interrupt signal of the external interrupt ch.3 is output as a transfer request to the DMAC (including extension).
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,unsigned> exint3{};
///The interrupt signal of the external interrupt ch.2 is output as a transfer request to the DMAC (including extension).
constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,30),Register::ReadWriteAccess,unsigned> exint2{};
///The interrupt signal of the external interrupt ch.1 is output as a transfer request to the DMAC (including extension).
constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,29),Register::ReadWriteAccess,unsigned> exint1{};
///The interrupt signal of the external interrupt ch.0 is output as a transfer request to the DMAC (including extension).
constexpr Register::FieldLocation<Addr,Register::maskFromRange(28,28),Register::ReadWriteAccess,unsigned> exint0{};
///The transmission interrupt signal of the MFS ch.7 is output as a transfer request to the DMAC (including extension).
constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,27),Register::ReadWriteAccess,unsigned> mfs7tx{};
///The reception interrupt signal of the MFS ch.7 is output as a transfer request to the DMAC (including extension).
constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,26),Register::ReadWriteAccess,unsigned> mfs7rx{};
///The transmission interrupt signal of the MFS ch.6 is output as a transfer request to the DMAC (including extension).
constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,25),Register::ReadWriteAccess,unsigned> mfs6tx{};
///The reception interrupt signal of the MFS ch.6 is output as a transfer request to the DMAC (including extension).
constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,unsigned> mfs6rx{};
///The transmission interrupt signal of the MFS ch.5 is output as a transfer request to the DMAC (including extension).
constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::ReadWriteAccess,unsigned> mfs5tx{};
///The reception interrupt signal of the MFS ch.5 is output as a transfer request to the DMAC (including extension).
constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,unsigned> mfs5rx{};
///The transmission interrupt signal of the MFS ch.4 is output as a transfer request to the DMAC (including extension).
constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,unsigned> mfs4tx{};
///The reception interrupt signal of the MFS ch.4 is output as a transfer request to the DMAC (including extension).
constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,unsigned> mfs4rx{};
///The transmission interrupt signal of the MFS ch.3 is output as a transfer request to the DMAC (including extension).
constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::ReadWriteAccess,unsigned> mfs3tx{};
///The reception interrupt signal of the MFS ch.3 is output as a transfer request to the DMAC (including extension).
constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> mfs3rx{};
///The transmission interrupt signal of the MFS ch.2 is output as a transfer request to the DMAC (including extension).
constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::ReadWriteAccess,unsigned> mfs2tx{};
///The reception interrupt signal of the MFS ch.2 is output as a transfer request to the DMAC (including extension).
constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,unsigned> mfs2rx{};
///The transmission interrupt signal of the MFS ch.1 is output as a transfer request to the DMAC (including extension).
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> mfs1tx{};
///The reception interrupt signal of the MFS ch.1 is output as a transfer request to the DMAC (including extension).
constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> mfs1rx{};
///The transmission interrupt signal of the MFS ch.0 is output as a transfer request to the DMAC (including extension).
constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> mfs0tx{};
///The reception interrupt signal of the MFS ch.0 is output as a transfer request to the DMAC (including extension).
constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> mfs0rx{};
///The IRQ0 interrupt signal of the base timer ch.6 is output as a transfer request to the DMAC.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> irq0bt6{};
///The IRQ0 interrupt signal of the base timer ch.4 is output as a transfer request to the DMAC.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> irq0bt4{};
///The IRQ0 interrupt signal of the base timer ch.3 is output as a transfer request to the DMAC.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> irq0bt2{};
///The IRQ0 interrupt signal of the base timer ch.0 is output as a transfer request to the DMAC.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> irq0bt0{};
///The scan conversion interrupt signal of the A/D converter unit 2 is output as a transfer request to the DMAC.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> adcscan2{};
///The scan conversion interrupt signal of the A/D converter unit 1 is output as a transfer request to the DMAC.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> adcscan1{};
///The scan conversion interrupt signal of the A/D converter unit 0 is output as a transfer request to the DMAC.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> adcscan0{};
///The EP5 DRQ interrupt signal of the USB ch.0 is output as a transfer request to the DMAC.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> usbep5{};
///The EP4 DRQ interrupt signal of the USB ch.0 is output as a transfer request to the DMAC.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> usbep4{};
///The EP3 DRQ interrupt signal of the USB ch.0 is output as a transfer request to the DMAC.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> usbep3{};
///The EP2 DRQ interrupt signal of the USB ch.0 is output as a transfer request to the DMAC.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> usbep2{};
///The EP1 DRQ interrupt signal of the USB ch.0 is output as a transfer request to the DMAC.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> usbep1{};
}
namespace IntreqOddpks{ ///<USB ch.0 Odd Packet Size DMA Enable Register
using Addr = Register::Address<0x4003100b,0xffffffff,0x00000000,unsigned char>;
}
namespace IntreqIrqcmode{ ///<Interrupt Factor Vector Relocate Setting Register
using Addr = Register::Address<0x4003100c,0xfffffffe,0x00000000,unsigned>;
///Interrupt Factor Vector Relocate Setting
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> irqcmode{};
}
namespace IntreqExc02mon{ ///<EXC02 batch read register
using Addr = Register::Address<0x40031010,0xfffffffc,0x00000000,unsigned>;
///Hardware watchdog timer interrupt request
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> hwint{};
///External NMIX pin interrupt request
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> nmi{};
}
namespace IntreqIrq00mon{ ///<IRQ00 Batch Read Register
using Addr = Register::Address<0x40031014,0xfffffffe,0x00000000,unsigned>;
///Anomalous frequency detection by CSV interrupt request
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> fcsint{};
}
namespace IntreqIrq01mon{ ///<IRQ01 Batch Read Register
using Addr = Register::Address<0x40031018,0xfffffffe,0x00000000,unsigned>;
///Software watchdog timer interrupt request
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> swwdtint{};
}
namespace IntreqIrq02mon{ ///<IRQ02 Batch Read Register
using Addr = Register::Address<0x4003101c,0xfffffffe,0x00000000,unsigned>;
///Low voltage detection (LVD) interrupt request
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> lvdint{};
}
namespace IntreqIrq03mon{ ///<IRQ03 Batch Read Register
using Addr = Register::Address<0x40031020,0xfffffff0,0x00000000,unsigned>;
///WFG timer 54 interrupt request in MFT unit 0
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> wave0int3{};
///WFG timer 32 interrupt request in MFT unit 0
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> wave0int2{};
///WFG timer 10 interrupt request in MFT unit 0
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> wave0int1{};
///DTIF (motor emergency stop) interrupt request in MFT unit 0
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> wave0int0{};
}
namespace IntreqIrq04mon{ ///<IRQ04 Batch Read Register
using Addr = Register::Address<0x40031024,0xffffff30,0x00000000,unsigned>;
///Interrupt request on external interrupt ch.7
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> extint7{};
///Interrupt request on external interrupt ch.6
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> extint6{};
///Interrupt request on external interrupt ch.3
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> extint3{};
///Interrupt request on external interrupt ch.2
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> extint2{};
///Interrupt request on external interrupt ch.1
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> extint1{};
///Interrupt request on external interrupt ch.0
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> extint0{};
}
namespace IntreqIrq05mon{ ///<IRQ05 Batch Read Register
using Addr = Register::Address<0x40031028,0xffffc03f,0x00000000,unsigned>;
///Interrupt request on external interrupt ch.21
constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> extint13{};
///Interrupt request on external interrupt ch.20
constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> extint12{};
///Interrupt request on external interrupt ch.19
constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> extint11{};
///Interrupt request on external interrupt ch.18
constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> extint10{};
///Interrupt request on external interrupt ch.17
constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> extint9{};
///Interrupt request on external interrupt ch.16
constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> extint8{};
///Interrupt request on external interrupt ch.15
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> extint7{};
///Interrupt request on external interrupt ch.14
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> extint6{};
}
namespace IntreqIrq06mon{ ///<IRQ06 Batch Read Register
using Addr = Register::Address<0x4003102c,0xfffffffc,0x00000000,unsigned>;
///Dual timer 2 interrupt request
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> timint2{};
///Dual timer 1 interrupt request
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> timint1{};
}
namespace IntreqIrq07mon{ ///<IRQ07 Batch Read Register
using Addr = Register::Address<0x40031030,0xfffffffe,0x00000000,unsigned>;
///Reception interrupt request on MFS ch.0
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> mfsint0{};
}
namespace IntreqIrq08mon{ ///<IRQ08 Batch Read Register
using Addr = Register::Address<0x40031034,0xfffffffc,0x00000000,unsigned>;
///Status interrupt request on MFS ch.0
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> mfsint1{};
///Transmission interrupt request on MFS ch.0
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> mfsint0{};
}
namespace IntreqIrq09mon{ ///<IRQ09 Batch Read Register
using Addr = Register::Address<0x40031038,0xfffffffe,0x00000000,unsigned>;
///Reception interrupt request on MFS ch.1
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> mfsint0{};
}
namespace IntreqIrq10mon{ ///<IRQ10 Batch Read Register
using Addr = Register::Address<0x4003103c,0xfffffffc,0x00000000,unsigned>;
///Status interrupt request on MFS ch.1
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> mfsint1{};
///Transmission interrupt request on MFS ch.1
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> mfsint0{};
}
namespace IntreqIrq11mon{ ///<IRQ11 Batch Read Register
using Addr = Register::Address<0x40031040,0xffffffff,0x00000000,unsigned>;
}
namespace IntreqIrq12mon{ ///<IRQ12 Batch Read Register
using Addr = Register::Address<0x40031044,0xffffffff,0x00000000,unsigned>;
}
namespace IntreqIrq13mon{ ///<IRQ13 Batch Read Register
using Addr = Register::Address<0x40031048,0xfffffffe,0x00000000,unsigned>;
///Reception interrupt request on MFS ch.3
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> mfsint0{};
}
namespace IntreqIrq14mon{ ///<IRQ14 Batch Read Register
using Addr = Register::Address<0x4003104c,0xfffffffc,0x00000000,unsigned>;
///Status interrupt request on MFS ch.3
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> mfsint1{};
///Transmission interrupt request on MFS ch.3
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> mfsint0{};
}
namespace IntreqIrq15mon{ ///<IRQ15 Batch Read Register
using Addr = Register::Address<0x40031050,0xffffffff,0x00000000,unsigned>;
}
namespace IntreqIrq16mon{ ///<IRQ16 Batch Read Register
using Addr = Register::Address<0x40031054,0xffffffff,0x00000000,unsigned>;
}
namespace IntreqIrq17mon{ ///<IRQ17 Batch Read Register
using Addr = Register::Address<0x40031058,0xfffffffe,0x00000000,unsigned>;
///Reception interrupt request on MFS ch.5
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> mfsint0{};
}
namespace IntreqIrq18mon{ ///<IRQ18 Batch Read Register
using Addr = Register::Address<0x4003105c,0xfffffffc,0x00000000,unsigned>;
///Status interrupt request on MFS ch.5
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> mfsint1{};
///Transmission interrupt request on MFS ch.5
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> mfsint0{};
}
namespace IntreqIrq19mon{ ///<IRQ19 Batch Read Register
using Addr = Register::Address<0x40031060,0xffffffff,0x00000000,unsigned>;
}
namespace IntreqIrq20mon{ ///<IRQ20 Batch Read Register
using Addr = Register::Address<0x40031064,0xffffffff,0x00000000,unsigned>;
}
namespace IntreqIrq21mon{ ///<IRQ21 Batch Read Register
using Addr = Register::Address<0x40031068,0xffffffff,0x00000000,unsigned>;
}
namespace IntreqIrq22mon{ ///<IRQ22 Batch Read Register
using Addr = Register::Address<0x4003106c,0xffffffff,0x00000000,unsigned>;
}
namespace IntreqIrq23mon{ ///<IRQ23 Batch Read Register
using Addr = Register::Address<0x40031070,0xfffffff8,0x00000000,unsigned>;
///Interrupt request on PPG ch.4
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> ppgint2{};
///Interrupt request on PPG ch.2
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> ppgint1{};
///Interrupt request on PPG ch.0
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> ppgint0{};
}
namespace IntreqIrq24mon{ ///<IRQ24 Batch Read Register
using Addr = Register::Address<0x40031074,0xffffffd8,0x00000000,unsigned>;
///RTC interrupt request
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> rtcint{};
///Stabilization wait completion interrupt request for main PLL oscillation
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> mpllint{};
///Stabilization wait completion interrupt request for sub-clock oscillation
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> soscint{};
///Stabilization wait completion interrupt request for main clock oscillation
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> moscint{};
}
namespace IntreqIrq25mon{ ///<IRQ25 Batch Read Register
using Addr = Register::Address<0x40031078,0xfffffff0,0x00000000,unsigned>;
///Conversion result comparison interrupt request in the corresponding A/D unit 0.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> adcint3{};
///FIFO overrun interrupt request in the corresponding A/D unit 0.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> adcint2{};
///Scan conversion interrupt request in the corresponding A/D unit 0.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> adcint1{};
///Priority conversion interrupt request in the corresponding A/D unit 0.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> adcint0{};
}
namespace IntreqIrq26mon{ ///<IRQ26 Batch Read Register
using Addr = Register::Address<0x4003107c,0xffffffff,0x00000000,unsigned>;
}
namespace IntreqIrq27mon{ ///<IRQ27 Batch Read Register
using Addr = Register::Address<0x40031080,0xffffffff,0x00000000,unsigned>;
}
namespace IntreqIrq28mon{ ///<IRQ28 Batch Read Register
using Addr = Register::Address<0x40031084,0xffffffc0,0x00000000,unsigned>;
///Zero detection interrupt request on the free run timer ch.2 in the MFT unit 0
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> frt0int5{};
///Zero detection interrupt request on the free run timer ch.1 in the MFT unit 0
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> frt0int4{};
///Zero detection interrupt request on the free run timer ch.0 in the MFT unit 0
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> frt0int3{};
///Peak value detection interrupt request on the free run timer ch.2 in the MFT unit 0
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> frt0int2{};
///Peak value detection interrupt request on the free run timer ch.1 in the MFT unit 0
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> frt0int1{};
///Peak value detection interrupt request on the free run timer ch.0 in the MFT unit 0
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> frt0int0{};
}
namespace IntreqIrq29mon{ ///<IRQ29 Batch Read Register
using Addr = Register::Address<0x40031088,0xfffffff0,0x00000000,unsigned>;
///Interrupt request on the input capture ch.3 in the MFT unit 0
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> icu0int3{};
///Interrupt request on the input capture ch.2 in the MFT unit 0
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> icu0int2{};
///Interrupt request on the input capture ch.1 in the MFT unit 0
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> icu0int1{};
///Interrupt request on the input capture ch.0 in the MFT unit 0
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> icu0int0{};
}
namespace IntreqIrq30mon{ ///<IRQ30 Batch Read Register
using Addr = Register::Address<0x4003108c,0xffffffc0,0x00000000,unsigned>;
///Interrupt request on the output compare ch.5 in the MFT unit 0
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> ocu0int5{};
///Interrupt request on the output compare ch.4 in the MFT unit 0
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> ocu0int4{};
///Interrupt request on the output compare ch.3 in the MFT unit 0
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> ocu0int3{};
///Interrupt request on the output compare ch.2 in the MFT unit 0
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> ocu0int2{};
///Interrupt request on the output compare ch.1 in the MFT unit 0
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> ocu0int1{};
///Interrupt request on the output compare ch.0 in the MFT unit 0
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> ocu0int0{};
}
namespace IntreqIrq31mon{ ///<IRQ31 Batch Read Register
using Addr = Register::Address<0x40031090,0xffff0000,0x00000000,unsigned>;
///IRQ1 interrupt request on the base timer ch.7
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> btint15{};
///IRQ0 interrupt request on the base timer ch.7
constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> btint14{};
///IRQ1 interrupt request on the base timer ch.6
constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> btint13{};
///IRQ0 interrupt request on the base timer ch.6
constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> btint12{};
///IRQ1 interrupt request on the base timer ch.5
constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> btint11{};
///IRQ0 interrupt request on the base timer ch.5
constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> btint10{};
///IRQ1 interrupt request on the base timer ch.4
constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> btint9{};
///IRQ0 interrupt request on the base timer ch.4
constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> btint8{};
///IRQ1 interrupt request on the base timer ch.3
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> btint7{};
///IRQ0 interrupt request on the base timer ch.3
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> btint6{};
///IRQ1 interrupt request on the base timer ch.2
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> btint5{};
///IRQ0 interrupt request on the base timer ch.2
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> btint4{};
///IRQ1 interrupt request on the base timer ch.1
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> btint3{};
///IRQ0 interrupt request on the base timer ch.1
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> btint2{};
///IRQ1 interrupt request on the base timer ch.0
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> btint1{};
///IRQ0 interrupt request on the base timer ch.0
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> btint0{};
}
namespace IntreqIrq32mon{ ///<IRQ32 Batch Read Register
using Addr = Register::Address<0x40031094,0xffffffff,0x00000000,unsigned>;
}
namespace IntreqIrq33mon{ ///<IRQ33 Batch Read Register
using Addr = Register::Address<0x40031098,0xffffffff,0x00000000,unsigned>;
}
namespace IntreqIrq34mon{ ///<IRQ34 Batch Read Register
using Addr = Register::Address<0x4003109c,0xffffffff,0x00000000,unsigned>;
}
namespace IntreqIrq35mon{ ///<IRQ35 Batch Read Register
using Addr = Register::Address<0x400310a0,0xffffffff,0x00000000,unsigned>;
}
namespace IntreqIrq36mon{ ///<IRQ36 Batch Read Register
using Addr = Register::Address<0x400310a4,0xffffffff,0x00000000,unsigned>;
}
namespace IntreqIrq37mon{ ///<IRQ37 Batch Read Register
using Addr = Register::Address<0x400310a8,0xffffffff,0x00000000,unsigned>;
}
namespace IntreqIrq38mon{ ///<IRQ38 Batch Read Register
using Addr = Register::Address<0x400310ac,0xffffffff,0x00000000,unsigned>;
}
namespace IntreqIrq39mon{ ///<IRQ39 Batch Read Register
using Addr = Register::Address<0x400310b0,0xffffffff,0x00000000,unsigned>;
}
namespace IntreqIrq40mon{ ///<IRQ40 Batch Read Register
using Addr = Register::Address<0x400310b4,0xffffffff,0x00000000,unsigned>;
}
namespace IntreqIrq41mon{ ///<IRQ41 Batch Read Register
using Addr = Register::Address<0x400310b8,0xffffffff,0x00000000,unsigned>;
}
namespace IntreqIrq42mon{ ///<IRQ42 Batch Read Register
using Addr = Register::Address<0x400310bc,0xffffffff,0x00000000,unsigned>;
}
namespace IntreqIrq43mon{ ///<IRQ43 Batch Read Register
using Addr = Register::Address<0x400310c0,0xffffffff,0x00000000,unsigned>;
}
namespace IntreqIrq44mon{ ///<IRQ44 Batch Read Register
using Addr = Register::Address<0x400310c4,0xffffffff,0x00000000,unsigned>;
}
namespace IntreqIrq45mon{ ///<IRQ45 Batch Read Register
using Addr = Register::Address<0x400310c8,0xffffffff,0x00000000,unsigned>;
}
namespace IntreqIrq46mon{ ///<IRQ46 Batch Read Register
using Addr = Register::Address<0x400310cc,0xffffffff,0x00000000,unsigned>;
}
namespace IntreqIrq47mon{ ///<IRQ47 Batch Read Register
using Addr = Register::Address<0x400310d0,0xfffff7ff,0x00000000,unsigned>;
///"RDY, HANG interrupt request for flash "
constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> flashint{};
}
namespace IntreqRcintsel0{ ///<Interrupt Factor Selection Register 0
using Addr = Register::Address<0x40031210,0x00000000,0x00000000,unsigned>;
///select the interrupt factor of the interrupt vector No.22.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,24),Register::ReadWriteAccess,unsigned> intsel3{};
///select the interrupt factor of the interrupt vector No.21.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,16),Register::ReadWriteAccess,unsigned> intsel2{};
///select the interrupt factor of the interrupt vector No.20.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,8),Register::ReadWriteAccess,unsigned> intsel1{};
///select the interrupt factor of the interrupt vector No.19.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,0),Register::ReadWriteAccess,unsigned> intsel0{};
}
namespace IntreqRcintsel1{ ///<Interrupt Factor Selection Register 1
using Addr = Register::Address<0x40031214,0x00000000,0x00000000,unsigned>;
///select the interrupt factor of the interrupt vector No.26.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,24),Register::ReadWriteAccess,unsigned> intsel7{};
///select the interrupt factor of the interrupt vector No.25.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,16),Register::ReadWriteAccess,unsigned> intsel6{};
///select the interrupt factor of the interrupt vector No.24.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,8),Register::ReadWriteAccess,unsigned> intsel5{};
///select the interrupt factor of the interrupt vector No.23.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,0),Register::ReadWriteAccess,unsigned> intsel4{};
}
}
|
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_char_memcpy_14.cpp
Label Definition File: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805.string.label.xml
Template File: sources-sink-14.tmpl.cpp
*/
/*
* @description
* CWE: 122 Heap Based Buffer Overflow
* BadSource: Allocate using new[] and set data pointer to a small buffer
* GoodSource: Allocate using new[] and set data pointer to a large buffer
* Sink: memcpy
* BadSink : Copy string to data using memcpy
* Flow Variant: 14 Control flow: if(globalFive==5) and if(globalFive!=5)
*
* */
#include "std_testcase.h"
#include <wchar.h>
namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_char_memcpy_14
{
#ifndef OMITBAD
void bad()
{
char * data;
data = NULL;
if(globalFive==5)
{
/* FLAW: Allocate using new[] and point data to a small buffer that is smaller than the large buffer used in the sinks */
data = new char[50];
data[0] = '\0'; /* null terminate */
}
{
char source[100];
memset(source, 'C', 100-1); /* fill with 'C's */
source[100-1] = '\0'; /* null terminate */
/* POTENTIAL FLAW: Possible buffer overflow if source is larger than data */
memcpy(data, source, 100*sizeof(char));
data[100-1] = '\0'; /* Ensure the destination buffer is null terminated */
printLine(data);
delete [] data;
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B1() - use goodsource and badsink by changing the globalFive==5 to globalFive!=5 */
static void goodG2B1()
{
char * data;
data = NULL;
if(globalFive!=5)
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
printLine("Benign, fixed string");
}
else
{
/* FIX: Allocate using new[] and point data to a large buffer that is at least as large as the large buffer used in the sink */
data = new char[100];
data[0] = '\0'; /* null terminate */
}
{
char source[100];
memset(source, 'C', 100-1); /* fill with 'C's */
source[100-1] = '\0'; /* null terminate */
/* POTENTIAL FLAW: Possible buffer overflow if source is larger than data */
memcpy(data, source, 100*sizeof(char));
data[100-1] = '\0'; /* Ensure the destination buffer is null terminated */
printLine(data);
delete [] data;
}
}
/* goodG2B2() - use goodsource and badsink by reversing the blocks in the if statement */
static void goodG2B2()
{
char * data;
data = NULL;
if(globalFive==5)
{
/* FIX: Allocate using new[] and point data to a large buffer that is at least as large as the large buffer used in the sink */
data = new char[100];
data[0] = '\0'; /* null terminate */
}
{
char source[100];
memset(source, 'C', 100-1); /* fill with 'C's */
source[100-1] = '\0'; /* null terminate */
/* POTENTIAL FLAW: Possible buffer overflow if source is larger than data */
memcpy(data, source, 100*sizeof(char));
data[100-1] = '\0'; /* Ensure the destination buffer is null terminated */
printLine(data);
delete [] data;
}
}
void good()
{
goodG2B1();
goodG2B2();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
using namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_char_memcpy_14; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
|
// -----------------------------------------------------------------------------
// LowSocket.cpp
// -----------------------------------------------------------------------------
#include "LowSocket.h"
#include "LowSocketDirect.h"
#include "LowTLSContext.h"
#include "low_alloc.h"
#include "low_config.h"
#include "low_main.h"
#include "low_system.h"
#include "low_web_thread.h"
#include <errno.h>
#include <netinet/in.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <unistd.h>
#if LOW_ESP32_LWIP_SPECIALITIES
#include <lwip/sockets.h>
#define ioctl lwip_ioctl
#else
#include <netinet/tcp.h>
#include <sys/uio.h>
#endif /* LOW_ESP32_LWIP_SPECIALITIES */
// -----------------------------------------------------------------------------
// LowSocket::LowSocket
// -----------------------------------------------------------------------------
LowSocket::LowSocket(low_main_t *low, int fd) :
LowFD(low, LOWFD_TYPE_SOCKET, fd), LowLoopCallback(low), mLow(low),
mType(LOWSOCKET_TYPE_STDINOUT), mAcceptConnectCallID(0),
mAcceptConnectError(false), mReadCallID(0), mWriteCallID(0),
mConnected(true), mClosed(false), mDestroyed(false), mCloseCallID(0),
mReadData(NULL), mWriteData(NULL), mDirect(nullptr),
mDirectReadEnabled(false), mDirectWriteEnabled(false), mTLSContext(NULL),
mSSL(NULL)
{
AdvertiseFD();
InitSocket(NULL);
}
// -----------------------------------------------------------------------------
// LowSocket::LowSocket
// -----------------------------------------------------------------------------
LowSocket::LowSocket(low_main_t *low,
int fd,
struct sockaddr *remoteAddr,
int acceptCallID,
LowSocketDirect *direct,
int directType,
LowTLSContext *tlsContext,
bool clearOnReset) :
LowFD(low, LOWFD_TYPE_SOCKET, fd),
LowLoopCallback(low), mLow(low), mType(LOWSOCKET_TYPE_ACCEPTED),
mAcceptConnectCallID(acceptCallID), mAcceptConnectError(false),
mReadCallID(0), mWriteCallID(0), mConnected(false), mClosed(false),
mDestroyed(false), mCloseCallID(0), mReadData(NULL), mWriteData(NULL),
mDirect(direct), mDirectType(directType),
mDirectReadEnabled(direct != NULL), mDirectWriteEnabled(direct != NULL),
mTLSContext(tlsContext), mSSL(NULL)
{
mFDClearOnReset = clearOnReset;
mLoopClearOnReset = clearOnReset;
if(mDirect)
mDirect->SetSocket(this);
if(!InitSocket(remoteAddr))
{
if(mAcceptConnectCallID)
low_loop_set_callback(mLow, this); // to output error
else
low_web_set_poll_events(mLow, this, POLLOUT);
mTLSContext = NULL;
return;
}
else if(mTLSContext)
{
low_web_set_poll_events(mLow, this, POLLOUT);
AdvertiseFD();
}
else
{
mConnected = true;
AdvertiseFD();
if(mAcceptConnectCallID)
low_loop_set_callback(mLow, this);
if(mDirect)
low_web_set_poll_events(mLow, this, POLLIN | POLLOUT);
}
if(mTLSContext)
mTLSContext->AddRef();
}
// -----------------------------------------------------------------------------
// LowSocket::LowSocket
// -----------------------------------------------------------------------------
LowSocket::LowSocket(low_main_t *low,
LowSocketDirect *direct,
int directType,
LowTLSContext *tlsContext,
bool clearOnReset) :
LowFD(low, LOWFD_TYPE_SOCKET),
LowLoopCallback(low), mLow(low), mType(LOWSOCKET_TYPE_CONNECTED),
mAcceptConnectCallID(0), mAcceptConnectError(false), mReadCallID(0),
mWriteCallID(0), mConnected(false), mClosed(false), mDestroyed(false),
mCloseCallID(0), mReadData(NULL), mWriteData(NULL), mDirect(direct),
mDirectType(directType), mDirectReadEnabled(direct != NULL),
mDirectWriteEnabled(direct != NULL), mTLSContext(tlsContext), mSSL(NULL)
{
mFDClearOnReset = clearOnReset;
mLoopClearOnReset = clearOnReset;
if(mDirect)
mDirect->SetSocket(this);
if(mTLSContext)
mTLSContext->AddRef();
}
// -----------------------------------------------------------------------------
// LowSocket::~LowSocket
// -----------------------------------------------------------------------------
LowSocket::~LowSocket()
{
low_web_clear_poll(mLow, this);
if(mDirect)
{
delete mDirect;
low_free(mReadData);
}
if(mAcceptConnectCallID)
{
if(mType == LOWSOCKET_TYPE_CONNECTED)
low_remove_stash(mLow->duk_ctx, mAcceptConnectCallID);
}
if(mReadCallID)
low_remove_stash(mLow->duk_ctx, mReadCallID);
if(mWriteCallID)
low_remove_stash(mLow->duk_ctx, mWriteCallID);
if(FD() >= 0 && mType != LOWSOCKET_TYPE_STDINOUT)
close(FD());
SetFD(-1);
if(mSSL)
{
mbedtls_ssl_free(mSSL);
low_free(mSSL);
}
if(mTLSContext)
{
mTLSContext->DecRef();
}
}
// -----------------------------------------------------------------------------
// LowSocket::InitSocket
// -----------------------------------------------------------------------------
bool LowSocket::InitSocket(struct sockaddr *remoteAddr)
{
if(remoteAddr && remoteAddr->sa_family == AF_INET)
{
struct sockaddr_in *addr;
unsigned char *ip;
mNodeFamily = 4;
addr = (struct sockaddr_in *)remoteAddr;
ip = (unsigned char *)&addr->sin_addr.s_addr;
sprintf(mRemoteHost, "%u.%u.%u.%u", ip[0], ip[1], ip[2], ip[3]);
mRemotePort = ntohs(addr->sin_port);
}
else if(remoteAddr && remoteAddr->sa_family == AF_INET6)
{
struct sockaddr_in6 *addr;
mNodeFamily = 6;
addr = (struct sockaddr_in6 *)remoteAddr;
if(inet_ntop(AF_INET6,
addr->sin6_addr.s6_addr,
mRemoteHost,
sizeof(mRemoteHost)) == NULL)
{
mAcceptConnectErrno = errno;
mAcceptConnectErrnoSSL = false;
mAcceptConnectError = true;
mAcceptConnectSyscall = "inet_ntop";
}
mRemotePort = ntohs(addr->sin6_port);
}
else
mNodeFamily = 0; // UNIX
u_long mode = 1;
if(ioctl(FD(), FIONBIO, &mode) < 0)
{
mAcceptConnectErrno = errno;
mAcceptConnectErrnoSSL = false;
mAcceptConnectError = true;
mAcceptConnectSyscall = "ioctl";
return false;
}
if(mTLSContext)
{
mSSL = (mbedtls_ssl_context *)low_alloc(sizeof(mbedtls_ssl_context));
if(!mSSL)
{
mAcceptConnectErrno = ENOMEM;
mAcceptConnectErrnoSSL = false;
mAcceptConnectError = true;
mAcceptConnectSyscall = "malloc";
return false;
}
mbedtls_ssl_init(mSSL);
int ret;
if((ret = mbedtls_ssl_setup(mSSL, &mTLSContext->GetSSLConfig())) != 0)
{
mAcceptConnectErrno = ret;
mAcceptConnectErrnoSSL = true;
mAcceptConnectError = true;
mAcceptConnectSyscall = "mbedtls_ssl_setup";
return false;
}
mbedtls_ssl_set_bio(
mSSL, &FD(), mbedtls_net_send, mbedtls_net_recv, NULL);
}
return true;
}
// -----------------------------------------------------------------------------
// LowSocket::Connect
// -----------------------------------------------------------------------------
bool LowSocket::Connect(struct sockaddr *remoteAddr,
int remoteAddrLen,
int callIndex,
int &err,
const char *&syscall)
{
if(mType != LOWSOCKET_TYPE_CONNECTED || FD() >= 0)
{
err = mConnected ? EISCONN : EALREADY;
syscall = "connect";
return false;
}
SetFD(socket(remoteAddr->sa_family, SOCK_STREAM, 0));
if(FD() < 0)
{
err = errno;
syscall = "socket";
return false;
}
AdvertiseFD();
if(InitSocket(remoteAddr))
{
if(connect(FD(), remoteAddr, remoteAddrLen) < 0)
{
if(errno != EINPROGRESS)
{
mAcceptConnectErrno = errno;
mAcceptConnectErrnoSSL = false;
mAcceptConnectError = true;
mAcceptConnectSyscall = "connect";
}
}
else if(!mTLSContext)
mConnected = true;
}
if(mAcceptConnectError)
{
close(FD());
SetFD(-1);
err = mAcceptConnectError;
syscall = mAcceptConnectSyscall;
return false;
}
else
{
if(mConnected)
{
if(callIndex == -1)
return true;
else
return CallAcceptConnect(callIndex, false);
}
else
{
mAcceptConnectCallID =
callIndex != -1 ? low_add_stash(mLow->duk_ctx, callIndex) : 0;
low_web_set_poll_events(mLow, this, POLLOUT);
return true;
}
}
}
// -----------------------------------------------------------------------------
// LowSocket::Read
// -----------------------------------------------------------------------------
void LowSocket::Read(int pos, unsigned char *data, int len, int callIndex)
{
#if LOW_ESP32_LWIP_SPECIALITIES
if(FD() >= 0 && FD() <= 2)
{
// don't call back, we are busy waiting for "input"
return;
}
#endif /* LOW_ESP32_LWIP_SPECIALITIES */
if(mDirect || mReadData)
{
duk_dup(mLow->duk_ctx, callIndex);
low_push_error(mLow, EAGAIN, "read");
low_call_next_tick(mLow->duk_ctx, 1);
return;
}
mReadPos = 0;
mReadData = data;
mReadLen = len;
// If TLS context is used, always use other thread to read
bool tryNow = !mTLSContext && mConnected;
len = mClosed ? 0 : (tryNow ? DoRead() : -1);
if(len >= 0 ||
(tryNow && len == -1 && (mReadErrno != EAGAIN || mReadErrnoSSL)))
{
if(len == 0)
mClosed = true;
mReadData = NULL;
duk_dup(mLow->duk_ctx, callIndex);
if(len >= 0)
{
duk_push_null(mLow->duk_ctx);
duk_push_int(mLow->duk_ctx, len);
low_call_next_tick(mLow->duk_ctx, 2);
}
else
{
PushError(0);
low_call_next_tick(mLow->duk_ctx, 1);
}
}
else
{
mReadCallID = low_add_stash(mLow->duk_ctx, callIndex);
short events =
mClosed ? 0
: (POLLIN | (!mConnected || (mWriteData && !mWritePos) ||
mDirectWriteEnabled
? POLLOUT
: 0));
low_web_set_poll_events(mLow, this, events);
}
}
// -----------------------------------------------------------------------------
// LowSocket::Write
// -----------------------------------------------------------------------------
#if LOW_ESP32_LWIP_SPECIALITIES
void neoniousConsoleInput(char *data, int len, int fd);
#endif /* LOW_ESP32_LWIP_SPECIALITIES */
void LowSocket::Write(int pos, unsigned char *data, int len, int callIndex)
{
#if LOW_ESP32_LWIP_SPECIALITIES
if(FD() >= 0 && FD() <= 2)
{
neoniousConsoleInput((char *)data, len, FD());
duk_dup(mLow->duk_ctx, callIndex);
duk_push_null(mLow->duk_ctx);
duk_push_int(mLow->duk_ctx, len);
low_call_next_tick(mLow->duk_ctx, 2);
return;
}
#endif /* LOW_ESP32_LWIP_SPECIALITIES */
if(mDirect || mWriteData)
{
duk_dup(mLow->duk_ctx, callIndex);
low_push_error(mLow, EAGAIN, "write");
low_call_next_tick(mLow->duk_ctx, 1);
return;
}
mWritePos = 0;
mWriteData = data;
mWriteLen = len;
// If TLS context is used, always use other thread to read
bool tryNow = !mTLSContext && mConnected;
len = mClosed ? 0 : (tryNow ? DoWrite() : -1);
if(len >= 0 ||
(tryNow && len == -1 && (mWriteErrno != EAGAIN || mWriteErrnoSSL)))
{
mWriteData = NULL;
duk_dup(mLow->duk_ctx, callIndex);
if(len > 0)
{
duk_push_null(mLow->duk_ctx);
duk_push_int(mLow->duk_ctx, len);
low_call_next_tick(mLow->duk_ctx, 2);
}
else
{
PushError(1);
low_call_next_tick(mLow->duk_ctx, 1);
}
}
else
{
mWriteCallID = low_add_stash(mLow->duk_ctx, callIndex);
short events =
((mReadData && !mReadPos) || mDirectReadEnabled ? POLLIN : 0) |
POLLOUT;
low_web_set_poll_events(mLow, this, events);
}
}
// -----------------------------------------------------------------------------
// LowSocket::Shutdown
// -----------------------------------------------------------------------------
void LowSocket::Shutdown(int callIndex)
{
duk_dup(mLow->duk_ctx, callIndex);
if(!mConnected)
{
low_push_error(mLow, ENOTCONN, "shutdown");
low_call_next_tick(mLow->duk_ctx, 1);
}
else if(Shutdown() < 0)
{
int err = errno;
duk_dup(mLow->duk_ctx, callIndex);
low_push_error(mLow, err, "shutdown");
}
else
{
duk_dup(mLow->duk_ctx, callIndex);
duk_push_null(mLow->duk_ctx);
}
low_call_next_tick(mLow->duk_ctx, 1);
}
// -----------------------------------------------------------------------------
// LowSocket::Shutdown
// -----------------------------------------------------------------------------
int LowSocket::Shutdown()
{
if(mTLSContext)
{
if(mSSL)
return mbedtls_ssl_close_notify(mSSL); // todo: errnos are wrong
}
else
return shutdown(FD(), SHUT_WR);
return 0;
}
// -----------------------------------------------------------------------------
// LowSocket::Close
// -----------------------------------------------------------------------------
bool LowSocket::Close(int callIndex)
{
if(mDestroyed)
return true;
if(callIndex != -1)
mCloseCallID = low_add_stash(mLow->duk_ctx, callIndex);
mDestroyed = true;
if(mCloseCallID)
low_loop_set_callback(mLow, this);
// for direct
else
low_web_mark_delete(mLow, this);
return true;
}
// -----------------------------------------------------------------------------
// LowSocket::KeepAlive
// -----------------------------------------------------------------------------
void LowSocket::KeepAlive(bool enable, int secs)
{
if(FD() < 0)
return;
int opt = enable;
if(setsockopt(FD(), SOL_SOCKET, SO_KEEPALIVE, &opt, sizeof(int)) < 0)
{
low_push_error(mLow, errno, "setsockopt");
duk_throw(mLow->duk_ctx);
}
if(secs)
{
#ifdef __APPLE__
if(setsockopt(FD(), IPPROTO_TCP, TCP_KEEPALIVE, &secs, sizeof(int)) < 0)
#else
if(setsockopt(FD(), IPPROTO_TCP, TCP_KEEPIDLE, &secs, sizeof(int)) < 0)
#endif /* #ifdef __APPLE__ */
{
low_push_error(mLow, errno, "setsockopt");
duk_throw(mLow->duk_ctx);
}
}
}
// -----------------------------------------------------------------------------
// LowSocket::NoDelay
// -----------------------------------------------------------------------------
void LowSocket::NoDelay(bool enable)
{
int opt = enable;
if(setsockopt(FD(), IPPROTO_TCP, TCP_NODELAY, &opt, sizeof(int)) < 0)
{
low_push_error(mLow, errno, "setsockopt");
duk_throw(mLow->duk_ctx);
}
}
// -----------------------------------------------------------------------------
// LowSocket::SetDirect
// -----------------------------------------------------------------------------
bool LowSocket::SetDirect(LowSocketDirect *direct, int type, bool fromWebThread)
{
if(direct && (mDirect || !mConnected || mReadData || mWriteData))
return false;
if(!direct && !mDirect)
return false;
if(!direct && mDirect)
{
if(!fromWebThread)
low_web_clear_poll(mLow, this);
low_free(mReadData);
mReadData = NULL;
}
mDirect = direct;
mDirectType = type;
if(mDirect)
{
mDirectReadEnabled = true;
mDirect->SetSocket(this);
if(!mDestroyed)
low_web_set_poll_events(
mLow,
this,
mClosed ? 0
: (POLLIN | (mTLSContext ? POLLOUT : 0) |
(!mConnected || mDirectWriteEnabled ? POLLOUT : 0)));
}
return true;
}
// -----------------------------------------------------------------------------
// LowSocket::GetDirect
// -----------------------------------------------------------------------------
LowSocketDirect *LowSocket::GetDirect(int &type)
{
type = mDirectType;
return mDirect;
}
// -----------------------------------------------------------------------------
// LowSocket::TriggerDirect
// -----------------------------------------------------------------------------
void LowSocket::TriggerDirect(int trigger)
{
if(mDestroyed)
return;
if(trigger & LOWSOCKET_TRIGGER_READ)
mDirectReadEnabled = true;
if(trigger & LOWSOCKET_TRIGGER_WRITE)
mDirectWriteEnabled = true;
short events =
mClosed
? 0
: (mDirectReadEnabled ? (POLLIN | (mTLSContext ? POLLOUT : 0)) : 0) |
(!mConnected || mDirectWriteEnabled ? POLLOUT : 0);
low_web_set_poll_events(mLow, this, events);
}
// -----------------------------------------------------------------------------
// LowSocket::OnEvents
// -----------------------------------------------------------------------------
bool LowSocket::OnEvents(short events)
{
if((mDestroyed || mAcceptConnectError) && !mCloseCallID)
{
// We will be destroyed on other ways ASAP
low_web_set_poll_events(mLow, this, 0);
return true;
}
if(mClosed)
{
low_web_set_poll_events(mLow, this, 0);
return true;
}
while(mTLSContext && mSSL->state != MBEDTLS_SSL_HANDSHAKE_OVER &&
(events & (POLLIN | POLLOUT)))
{
int ret = mbedtls_ssl_handshake_step(mSSL);
if(mSSL->state == MBEDTLS_SSL_HANDSHAKE_OVER)
{
mDirectReadEnabled = mDirect;
mDirectWriteEnabled = mDirect;
}
else if(ret)
{
if(ret == MBEDTLS_ERR_SSL_WANT_READ)
{
mDirectWriteEnabled = false;
mDirectReadEnabled = true;
}
else if(ret == MBEDTLS_ERR_SSL_WANT_WRITE)
{
mDirectReadEnabled = false;
mDirectWriteEnabled = true;
}
else
{
mDirectReadEnabled = false;
mDirectWriteEnabled = false;
if(mAcceptConnectCallID)
{
mAcceptConnectErrno = ret;
mAcceptConnectErrnoSSL = true;
mAcceptConnectError = true;
mAcceptConnectSyscall = "mbedtls_ssl_handshake_step";
low_loop_set_callback(mLow, this);
}
else
return false;
low_web_set_poll_events(mLow, this, 0);
return true;
}
short events = (mDirectReadEnabled ? POLLIN : 0) |
(mDirectWriteEnabled ? POLLOUT : 0);
low_web_set_poll_events(mLow, this, events);
return true;
}
}
if(!mConnected)
{
int error;
socklen_t len = sizeof(error);
if(getsockopt(FD(), SOL_SOCKET, SO_ERROR, &error, &len) < 0)
error = errno;
if(error)
{
if(mAcceptConnectCallID)
{
mAcceptConnectErrno = error;
mAcceptConnectErrnoSSL = false;
mAcceptConnectError = true;
mAcceptConnectSyscall = "connect";
low_loop_set_callback(mLow, this);
}
else
return false;
return true;
}
if(mDirect)
mDirect->OnSocketConnected();
mConnected = true;
if(mAcceptConnectCallID)
low_loop_set_callback(mLow, this);
}
if(!mTLSContext || mSSL->state == MBEDTLS_SSL_HANDSHAKE_OVER)
{
if(mDirect)
{
if(((events & (POLLIN | POLLHUP | POLLERR)) || mTLSContext) &&
mDirectReadEnabled)
{
if(!mReadData)
{
mReadData = (unsigned char *)low_alloc(1024);
mReadLen = 1024;
}
if(mReadData)
{
mDirectReadEnabled = false; // no race conditions
while(true) // required with SSL b/c Read might not always
// be retriggered if SSL still has data
{
int len = DoRead();
if(len < 0 && mReadErrno == EAGAIN && !mReadErrnoSSL)
{
mDirectReadEnabled = true;
break;
}
if(len == 0)
mClosed = true;
if(!mDirect->OnSocketData(mReadData, len))
break;
if(!mTLSContext)
{
mDirectReadEnabled = true;
break;
}
}
}
}
if((events & POLLOUT) && mDirectWriteEnabled)
{
mDirectWriteEnabled = false; // no race conditions
if(mDirect->OnSocketWrite())
mDirectWriteEnabled = true;
}
short events = mClosed ? 0
: (mDirectReadEnabled ? POLLIN : 0) |
(mDirectWriteEnabled ? POLLOUT : 0);
low_web_set_poll_events(mLow, this, events);
}
else
{
bool change = false;
if((events & (POLLIN | POLLHUP | POLLERR)) && mReadData &&
!mReadPos)
{
int len = DoRead();
if(len == 0)
mClosed = true;
if(len >= 0 || mReadErrno != EAGAIN || mReadErrnoSSL)
{
mReadPos = len;
change = true;
}
}
if((events & POLLOUT) && mWriteData && !mWritePos)
{
int len = DoWrite();
if(len >= 0 || mReadErrno != EAGAIN || mReadErrnoSSL)
{
mWritePos = len;
change = true;
}
}
low_web_set_poll_events(mLow, this, 0);
if(change)
low_loop_set_callback(mLow, this);
}
}
return true;
}
// -----------------------------------------------------------------------------
// LowSocket::OnLoop
// -----------------------------------------------------------------------------
bool LowSocket::OnLoop()
{
duk_context *ctx = mLow->duk_ctx;
if(mDestroyed)
{
if(mCloseCallID)
{
low_push_stash(ctx, mCloseCallID, true);
duk_push_null(ctx);
duk_call(ctx, 1);
}
return false;
}
if(mAcceptConnectCallID)
{
if(!CallAcceptConnect(mAcceptConnectCallID, true))
{
if(mCloseCallID)
{
low_push_stash(ctx, mCloseCallID, true);
duk_push_null(ctx);
duk_call(ctx, 1);
}
return false;
}
}
else if(mAcceptConnectError)
{
if(mCloseCallID)
{
low_push_stash(ctx, mCloseCallID, true);
duk_push_null(ctx);
duk_call(ctx, 1);
}
return false;
}
if(mDirect || !mConnected)
return true;
if(mReadData && (mClosed || mReadPos))
{
mReadData = NULL;
int callID = mReadCallID;
mReadCallID = 0;
low_push_stash(ctx, callID, true);
if(mReadPos >= 0)
{
duk_push_null(ctx);
duk_push_int(ctx, mReadPos);
duk_call(ctx, 2);
}
else
{
PushError(0);
duk_call(ctx, 1);
}
}
if(mWriteData && mWritePos)
{
mWriteData = NULL;
int callID = mWriteCallID;
mWriteCallID = 0;
low_push_stash(ctx, callID, true);
if(mWritePos > 0)
{
duk_push_null(ctx);
duk_push_int(ctx, mWritePos);
duk_call(ctx, 2);
}
else
{
PushError(1);
duk_call(ctx, 1);
}
}
short events =
mClosed ? 0 : (mReadData ? POLLIN : 0) | (mWriteData ? POLLOUT : 0);
low_web_set_poll_events(mLow, this, events);
return true;
}
// -----------------------------------------------------------------------------
// LowSocket::CallAcceptConnect
// -----------------------------------------------------------------------------
bool LowSocket::CallAcceptConnect(int callIndex, bool onStash)
{
duk_context *ctx = mLow->duk_ctx;
char localHost[INET6_ADDRSTRLEN];
int localPort;
mAcceptConnectCallID = 0;
if(!mAcceptConnectError && mNodeFamily)
{
if(mNodeFamily == 4)
{
sockaddr_in localAddr;
socklen_t localAddrLen = sizeof(localAddr);
if(getsockname(FD(), (sockaddr *)&localAddr, &localAddrLen) < 0)
{
mAcceptConnectErrno = errno;
mAcceptConnectErrnoSSL = false;
mAcceptConnectError = true;
mAcceptConnectSyscall = "getsockname";
}
unsigned char *ip = (unsigned char *)&localAddr.sin_addr.s_addr;
sprintf(localHost, "%u.%u.%u.%u", ip[0], ip[1], ip[2], ip[3]);
localPort = ntohs(localAddr.sin_port);
}
else
{
sockaddr_in6 localAddr;
socklen_t localAddrLen = sizeof(localAddr);
if(getsockname(FD(), (sockaddr *)&localAddr, &localAddrLen) < 0 ||
inet_ntop(AF_INET6,
localAddr.sin6_addr.s6_addr,
localHost,
sizeof(localHost)) == NULL)
{
mAcceptConnectErrno = errno;
mAcceptConnectErrnoSSL = false;
mAcceptConnectError = true;
mAcceptConnectSyscall = "getsockname";
}
localPort = ntohs(localAddr.sin6_port);
}
}
if(mAcceptConnectError)
{
if(onStash)
low_push_stash(ctx, callIndex, mType == LOWSOCKET_TYPE_CONNECTED);
else
duk_dup(ctx, callIndex);
PushError(2);
if(onStash)
duk_call(ctx, 1);
else
low_call_next_tick(ctx, 1);
return false;
}
else if(mConnected)
{
if(onStash)
low_push_stash(ctx, callIndex, mType == LOWSOCKET_TYPE_CONNECTED);
else
duk_dup(ctx, callIndex);
duk_push_null(ctx);
duk_push_int(ctx, FD());
duk_push_int(ctx, mNodeFamily);
if(mNodeFamily)
{
duk_push_string(ctx, localHost);
duk_push_int(ctx, localPort);
duk_push_string(ctx, mRemoteHost);
duk_push_int(ctx, mRemotePort);
if(onStash)
duk_call(ctx, 7);
else
low_call_next_tick(ctx, 7);
}
else
{
if(onStash)
duk_call(ctx, 3);
else
low_call_next_tick(ctx, 3);
}
}
return true;
}
// -----------------------------------------------------------------------------
// LowSocket::DoRead
// -----------------------------------------------------------------------------
int LowSocket::DoRead()
{
int len = 0;
while(len != mReadLen)
{
int size = mTLSContext
? mbedtls_ssl_read(mSSL, mReadData + len, mReadLen - len)
#if LOW_ESP32_LWIP_SPECIALITIES
: lwip_read(FD(), mReadData + len, mReadLen - len);
#else
: read(FD(), mReadData + len, mReadLen - len);
#endif /* LOW_ESP32_LWIP_SPECIALITIES */
if(size < 0)
{
if(mTLSContext)
{
if(size == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY)
return len;
if(size == MBEDTLS_ERR_SSL_WANT_READ)
{
mReadErrno = EAGAIN;
mReadErrnoSSL = false;
}
else
{
mReadErrno = size;
mReadErrnoSSL = true;
}
}
else
{
mReadErrno = errno;
mReadErrnoSSL = false;
}
return len ? len : -1;
}
else if(size == 0)
return len;
else
len += size;
}
return len;
}
// -----------------------------------------------------------------------------
// LowSocket::DoWrite
// -----------------------------------------------------------------------------
int LowSocket::DoWrite()
{
int len = 0;
while(len != mWriteLen)
{
int size =
mTLSContext
? mbedtls_ssl_write(mSSL, mWriteData + len, mWriteLen - len)
#if LOW_ESP32_LWIP_SPECIALITIES
: ::lwip_write(FD(), mWriteData + len, mWriteLen - len);
#else
: ::write(FD(), mWriteData + len, mWriteLen - len);
#endif /* LOW_ESP32_LWIP_SPECIALITIES */
if(size < 0)
{
if(mTLSContext)
{
if(size == MBEDTLS_ERR_SSL_WANT_WRITE)
{
mWriteErrno = EAGAIN;
mWriteErrnoSSL = false;
}
else
{
mWriteErrno = size;
mWriteErrnoSSL = true;
}
}
else
{
mWriteErrno = errno;
mWriteErrnoSSL = false;
}
return len ? len : -1;
}
else if(size == 0)
return len;
else
len += size;
}
return len;
}
// -----------------------------------------------------------------------------
// LowSocket::write
// -----------------------------------------------------------------------------
int LowSocket::write(const unsigned char *data, int len)
{
if(!len)
return 0;
int size;
if(mTLSContext)
{
size = mbedtls_ssl_write(mSSL, data, len);
if(size < 0)
{
if(size == MBEDTLS_ERR_SSL_WANT_WRITE)
{
errno = EAGAIN; // because we are checking this in LowHTTPDirect
mWriteErrno = EAGAIN;
mWriteErrnoSSL = false;
}
else
{
mWriteErrno = size;
mWriteErrnoSSL = true;
}
}
return size;
}
else
{
#if LOW_ESP32_LWIP_SPECIALITIES
size = ::lwip_write(FD(), data, len);
#else
size = ::write(FD(), data, len);
#endif /* LOW_ESP32_LWIP_SPECIALITIES */
if(size < 0)
{
mWriteErrno = errno;
mWriteErrnoSSL = true;
}
}
return size;
}
// -----------------------------------------------------------------------------
// LowSocket::writev
// -----------------------------------------------------------------------------
int LowSocket::writev(const struct iovec *iov, int iovcnt)
{
if(!iovcnt)
return 0;
int size;
if(mTLSContext)
{
size =
mbedtls_ssl_write(mSSL, (unsigned char *)iov->iov_base, iov->iov_len);
if(size < 0)
{
if(size == MBEDTLS_ERR_SSL_WANT_WRITE)
{
errno = EAGAIN; // because we are checking this in LowHTTPDirect
mWriteErrno = EAGAIN;
mWriteErrnoSSL = false;
}
else
{
mWriteErrno = size;
mWriteErrnoSSL = true;
}
}
return size;
}
else
{
#if LOW_ESP32_LWIP_SPECIALITIES
size = lwip_writev(FD(), iov, iovcnt);
#else
size = ::writev(FD(), iov, iovcnt);
#endif /* #if LOW_ESP32_LWIP_SPECIALITIES */
if(size < 0)
{
mWriteErrno = errno;
mWriteErrnoSSL = true;
}
}
return size;
}
// -----------------------------------------------------------------------------
// LowSocket::SetError
// -----------------------------------------------------------------------------
void LowSocket::SetError(bool write, int error, bool ssl)
{
if(write)
{
mWriteErrno = error;
mWriteErrnoSSL = ssl;
}
else
{
mReadErrno = error;
mReadErrnoSSL = ssl;
}
}
// -----------------------------------------------------------------------------
// LowSocket::PushError
// -----------------------------------------------------------------------------
void LowSocket::PushError(int call)
{
int error;
bool ssl;
const char *syscall;
switch(call)
{
case 0:
error = mReadErrno;
ssl = mReadErrnoSSL;
syscall = "read";
break;
case 1:
error = mWriteErrno;
ssl = mWriteErrnoSSL;
syscall = "write";
break;
case 2:
error = mAcceptConnectErrno;
ssl = mAcceptConnectErrnoSSL;
syscall = mAcceptConnectSyscall;
break;
}
if(error && ssl)
{
duk_context *ctx = mLow->duk_ctx;
char code[32], message[256];
mbedtls_strerror(error, message, sizeof(message));
strerror_r(error, message, sizeof(message) - 16 - strlen(syscall));
sprintf(message + strlen(message), " (at %s)", syscall);
duk_push_error_object(ctx, DUK_ERR_ERROR, message);
sprintf(code, "ERR_MBEDTLS_%X", -error);
duk_push_string(ctx, code);
duk_put_prop_string(ctx, -2, "code");
duk_push_int(ctx, -error);
duk_put_prop_string(ctx, -2, "errno");
duk_push_string(ctx, syscall);
duk_put_prop_string(ctx, -2, "syscall");
}
else
low_push_error(mLow, error, syscall);
}
|
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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 "google/cloud/storage/list_objects_reader.h"
#include "google/cloud/storage/internal/nljson.h"
#include "google/cloud/storage/testing/canonical_errors.h"
#include "google/cloud/storage/testing/mock_client.h"
#include <gmock/gmock.h>
namespace google {
namespace cloud {
namespace storage {
inline namespace STORAGE_CLIENT_NS {
namespace {
namespace nl = internal::nl;
using internal::ListObjectsRequest;
using internal::ListObjectsResponse;
using storage::testing::MockClient;
using storage::testing::canonical_errors::PermanentError;
using ::testing::_;
using ::testing::ContainerEq;
using ::testing::HasSubstr;
using ::testing::Invoke;
using ::testing::Return;
ObjectMetadata CreateElement(int index) {
std::string id = "object-" + std::to_string(index);
std::string name = id;
std::string link =
"https://www.googleapis.com/storage/v1/b/test-bucket/" + id + "/1";
internal::nl::json metadata{
{"bucket", "test-bucket"},
{"id", id},
{"name", name},
{"selfLink", link},
{"kind", "storage#object"},
};
return internal::ObjectMetadataParser::FromJson(metadata).value();
};
TEST(ListObjectsReaderTest, Basic) {
// Create a synthetic list of ObjectMetadata elements, each request will
// return 2 of them.
std::vector<ObjectMetadata> expected;
int page_count = 3;
for (int i = 0; i != 2 * page_count; ++i) {
expected.emplace_back(CreateElement(i));
}
auto create_mock = [page_count](int i) {
ListObjectsResponse response;
if (i < page_count) {
if (i != page_count - 1) {
response.next_page_token = "page-" + std::to_string(i);
}
response.items.emplace_back(CreateElement(2 * i));
response.items.emplace_back(CreateElement(2 * i + 1));
}
return [response](ListObjectsRequest const&) {
return StatusOr<ListObjectsResponse>(response);
};
};
auto mock = std::make_shared<MockClient>();
EXPECT_CALL(*mock, ListObjects(_))
.WillOnce(Invoke(create_mock(0)))
.WillOnce(Invoke(create_mock(1)))
.WillOnce(Invoke(create_mock(2)));
ListObjectsReader reader(mock, "foo-bar-baz", Prefix("dir/"));
std::vector<ObjectMetadata> actual;
for (auto&& object : reader) {
ASSERT_TRUE(object.ok());
actual.emplace_back(std::move(object).value());
}
EXPECT_THAT(actual, ContainerEq(expected));
}
TEST(ListObjectsReaderTest, Empty) {
auto mock = std::make_shared<MockClient>();
EXPECT_CALL(*mock, ListObjects(_))
.WillOnce(Return(make_status_or(ListObjectsResponse{})));
ListObjectsReader reader(mock, "foo-bar-baz", Prefix("dir/"));
auto count = std::distance(reader.begin(), reader.end());
EXPECT_EQ(0U, count);
}
TEST(ListObjectsReaderTest, PermanentFailure) {
// Create a synthetic list of ObjectMetadata elements, each request will
// return 2 of them.
std::vector<ObjectMetadata> expected;
int const page_count = 2;
for (int i = 0; i != 2 * page_count; ++i) {
expected.emplace_back(CreateElement(i));
}
auto create_mock = [&](int i) {
ListObjectsResponse response;
response.next_page_token = "page-" + std::to_string(i);
response.items.emplace_back(CreateElement(2 * i));
response.items.emplace_back(CreateElement(2 * i + 1));
return [response](ListObjectsRequest const&) {
return StatusOr<ListObjectsResponse>(response);
};
};
auto mock = std::make_shared<MockClient>();
EXPECT_CALL(*mock, ListObjects(_))
.WillOnce(Invoke(create_mock(0)))
.WillOnce(Invoke(create_mock(1)))
.WillOnce(Invoke([](ListObjectsRequest const&) {
return StatusOr<ListObjectsResponse>(PermanentError());
}));
ListObjectsReader reader(mock, "test-bucket");
std::vector<ObjectMetadata> actual;
bool has_status_or_error = false;
for (auto&& object : reader) {
if (object.ok()) {
actual.emplace_back(*std::move(object));
continue;
}
// The iteration should fail only once, an error should reset the iterator
// to `end()`.
EXPECT_FALSE(has_status_or_error);
has_status_or_error = true;
// Verify the error is what we expect.
Status status = std::move(object).status();
EXPECT_EQ(PermanentError().code(), status.code());
EXPECT_EQ(PermanentError().message(), status.message());
}
// The iteration should have returned an error at least once.
EXPECT_TRUE(has_status_or_error);
// The iteration should have returned all the elements prior to the error.
EXPECT_THAT(actual, ContainerEq(expected));
}
TEST(ListObjectsReaderTest, IteratorCompare) {
// Create a synthetic list of ObjectMetadata elements, each request will
// return 2 of them.
int const page_count = 1;
auto create_mock = [](int i, int page_count) {
ListObjectsResponse response;
if (i < page_count) {
if (i != page_count - 1) {
response.next_page_token = "page-" + std::to_string(i);
}
response.items.emplace_back(CreateElement(2 * i));
response.items.emplace_back(CreateElement(2 * i + 1));
}
return [response](ListObjectsRequest const&) {
return StatusOr<ListObjectsResponse>(response);
};
};
auto mock1 = std::make_shared<MockClient>();
EXPECT_CALL(*mock1, ListObjects(_))
.WillOnce(Invoke(create_mock(0, page_count)));
auto mock2 = std::make_shared<MockClient>();
EXPECT_CALL(*mock2, ListObjects(_))
.WillOnce(Invoke(create_mock(0, page_count)));
ListObjectsReader reader1(mock1, "foo-bar-baz", Prefix("dir/"));
ListObjectsIterator a1 = reader1.begin();
ListObjectsIterator b1 = a1;
ListObjectsIterator e1 = reader1.end();
EXPECT_EQ(b1, a1);
++b1;
EXPECT_NE(b1, a1);
EXPECT_NE(a1, e1);
EXPECT_NE(b1, e1);
++b1;
EXPECT_EQ(b1, e1);
ListObjectsReader reader2(mock2, "foo-bar-baz", Prefix("dir/"));
ListObjectsIterator a2 = reader2.begin();
// Verify that iterators from different streams, even when pointing to the
// same elements are different.
EXPECT_NE(a1, a2);
}
} // namespace
} // namespace STORAGE_CLIENT_NS
} // namespace storage
} // namespace cloud
} // namespace google
|
/////////////////////////////////////////////////////////////////////////////
// Name: defaultsettings.cpp
// Purpose:
// Author: Ake Hedman
// Modified by:
// Created: Thu 23 Oct 2009 16:00:29 CEST
// RCS-ID:
// Copyright: Copyright (C) 2007 eurosource
// Licence:
/////////////////////////////////////////////////////////////////////////////
// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif
////@begin includes
////@end includes
#include "defaultsettings.h"
////@begin XPM images
////@end XPM images
/*!
* DefaultSettings type definition
*/
IMPLEMENT_DYNAMIC_CLASS( DefaultSettings, wxDialog )
/*!
* DefaultSettings event table definition
*/
BEGIN_EVENT_TABLE( DefaultSettings, wxDialog )
////@begin DefaultSettings event table entries
////@end DefaultSettings event table entries
END_EVENT_TABLE()
/*!
* DefaultSettings constructors
*/
DefaultSettings::DefaultSettings()
{
Init();
}
DefaultSettings::DefaultSettings( wxWindow* parent, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style )
{
Init();
Create(parent, id, caption, pos, size, style);
}
/*!
* DefaultSettings creator
*/
bool DefaultSettings::Create( wxWindow* parent, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style )
{
////@begin DefaultSettings creation
SetExtraStyle(wxWS_EX_BLOCK_EVENTS);
wxDialog::Create( parent, id, caption, pos, size, style );
CreateControls();
if (GetSizer())
{
GetSizer()->SetSizeHints(this);
}
Centre();
////@end DefaultSettings creation
return true;
}
/*!
* DefaultSettings destructor
*/
DefaultSettings::~DefaultSettings()
{
////@begin DefaultSettings destruction
////@end DefaultSettings destruction
}
/*!
* Member initialisation
*/
void DefaultSettings::Init()
{
////@begin DefaultSettings member initialisation
////@end DefaultSettings member initialisation
}
/*!
* Control creation for DefaultSettings
*/
void DefaultSettings::CreateControls()
{
////@begin DefaultSettings content construction
DefaultSettings* itemDialog1 = this;
wxBoxSizer* itemBoxSizer2 = new wxBoxSizer(wxVERTICAL);
itemDialog1->SetSizer(itemBoxSizer2);
////@end DefaultSettings content construction
}
/*!
* Should we show tooltips?
*/
bool DefaultSettings::ShowToolTips()
{
return true;
}
/*!
* Get bitmap resources
*/
wxBitmap DefaultSettings::GetBitmapResource( const wxString& name )
{
// Bitmap retrieval
////@begin DefaultSettings bitmap retrieval
wxUnusedVar(name);
return wxNullBitmap;
////@end DefaultSettings bitmap retrieval
}
/*!
* Get icon resources
*/
wxIcon DefaultSettings::GetIconResource( const wxString& name )
{
// Icon retrieval
////@begin DefaultSettings icon retrieval
wxUnusedVar(name);
return wxNullIcon;
////@end DefaultSettings icon retrieval
}
|
// Copyright (c) 2016 ASMlover. 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 ofconditions 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 materialsprovided 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 <sys/syscall.h>
#include <execinfo.h>
#include <unistd.h>
#include <stdlib.h>
#include "../TPlatform.h"
namespace tyr { namespace basic {
pid_t kern_getpid(void) {
return getpid();
}
int kern_backtrace(std::string& bt) {
static const int kMaxBackTrace = 256;
void* buff[kMaxBackTrace];
int nptrs = backtrace(buff, kMaxBackTrace);
char** messages = backtrace_symbols(buff, nptrs);
if (nullptr != messages) {
char message[1024];
for (int i = 0; i < nptrs; ++i) {
snprintf(message, sizeof(message), "%i: %s\n", nptrs - i - 1, messages[i]);
bt.append(message);
}
free(messages);
}
return 0;
}
int kern_mutex_init(KernMutex* mtx) {
return pthread_mutex_init(mtx, nullptr);
}
int kern_mutex_destroy(KernMutex* mtx) {
return pthread_mutex_destroy(mtx);
}
int kern_mutex_lock(KernMutex* mtx) {
return pthread_mutex_lock(mtx);
}
int kern_mutex_unlock(KernMutex* mtx) {
return pthread_mutex_unlock(mtx);
}
int kern_cond_init(KernCond* cond) {
return pthread_cond_init(cond, nullptr);
}
int kern_cond_destroy(KernCond* cond) {
return pthread_cond_destroy(cond);
}
int kern_cond_signal(KernCond* cond) {
return pthread_cond_signal(cond);
}
int kern_cond_broadcast(KernCond* cond) {
return pthread_cond_broadcast(cond);
}
int kern_cond_wait(KernCond* cond, KernMutex* mtx) {
return pthread_cond_wait(cond, mtx);
}
int kern_cond_timedwait(KernCond* cond, KernMutex* mtx, uint64_t nanosec) {
struct timespec ts;
kern_gettime(&ts);
ts.tv_sec += nanosec / NANOSEC;
ts.tv_nsec = nanosec % NANOSEC;
return pthread_cond_timedwait(cond, mtx, &ts);
}
int kern_thread_create(KernThread* thread, void* (*start_routine)(void*), void* arg) {
return pthread_create(thread, nullptr, start_routine, arg);
}
int kern_thread_join(KernThread thread) {
return pthread_join(thread, nullptr);
}
int kern_thread_detach(KernThread thread) {
return pthread_detach(thread);
}
int kern_thread_atfork(void (*prepare)(void), void (*parent)(void), void (*child)(void)) {
return pthread_atfork(prepare, parent, child);
}
int kern_threadkey_create(KernThreadKey* key, void (*destructor)(void*)) {
return pthread_key_create(key, destructor);
}
int kern_threadkey_delete(KernThreadKey key) {
return pthread_key_delete(key);
}
int kern_setspecific(KernThreadKey key, const void* value) {
return pthread_setspecific(key, value);
}
void* kern_getspecific(KernThreadKey key) {
return pthread_getspecific(key);
}
}}
|
/*
Ucglib.cpp
ucglib = universal color graphics library
ucglib = micro controller graphics library
Universal uC Color Graphics Library
Copyright (c) 2014, olikraus@gmail.com
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 s_t ource code must retain the above copyright notice, this list
of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or other
materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <SPI.h>
#include "Ucglib.h"
/*=========================================================================*/
/* 8 Bit SW SPI */
#if defined(__SAM3X8E__)
//#elif defined(__SAM3X8E__)
//#define setbit(pio, mask) PIO_Set( (pio), (mask) )
//#define clrbit(pio, mask) PIO_Clear( (pio), (mask) )
#define setbit(pio, mask) ((pio)->PIO_SODR = (mask))
#define clrbit(pio, mask) ((pio)->PIO_CODR = (mask))
static void ucg_nano_delay(void)
{
volatile uint32_t i;
for( i = 0; i < 1; i++ )
{
__NOP;
}
//delayMicroseconds(1);
}
static void ucg_com_arduino_send_generic_SW_SPI(ucg_t *ucg, uint8_t data)
{
uint32_t sda_pin = ucg->pin_list[UCG_PIN_SDA];
uint32_t scl_pin = ucg->pin_list[UCG_PIN_SCL];
Pio *sda_port = g_APinDescription[sda_pin].pPort;
Pio *scl_port = g_APinDescription[scl_pin].pPort;
uint8_t i = 8;
sda_pin = g_APinDescription[sda_pin].ulPin;
scl_pin = g_APinDescription[scl_pin].ulPin;
do
{
if ( data & 128 )
{
setbit( sda_port, sda_pin) ;
}
else
{
clrbit( sda_port, sda_pin) ;
}
//delayMicroseconds(1);
ucg_nano_delay();
setbit( scl_port, scl_pin);
//delayMicroseconds(1);
ucg_nano_delay();
i--;
clrbit( scl_port, scl_pin) ;
data <<= 1;
} while( i > 0 );
}
#elif defined(__AVR__)
uint8_t u8g_bitData, u8g_bitNotData;
uint8_t u8g_bitClock, u8g_bitNotClock;
volatile uint8_t *u8g_outData;
volatile uint8_t *u8g_outClock;
static void ucg_com_arduino_init_shift_out(uint8_t dataPin, uint8_t clockPin)
{
u8g_outData = portOutputRegister(digitalPinToPort(dataPin));
u8g_outClock = portOutputRegister(digitalPinToPort(clockPin));
u8g_bitData = digitalPinToBitMask(dataPin);
u8g_bitClock = digitalPinToBitMask(clockPin);
u8g_bitNotClock = u8g_bitClock;
u8g_bitNotClock ^= 0x0ff;
u8g_bitNotData = u8g_bitData;
u8g_bitNotData ^= 0x0ff;
}
static void ucg_com_arduino_send_generic_SW_SPI(ucg_t *ucg, uint8_t val) UCG_NOINLINE;
static void ucg_com_arduino_send_generic_SW_SPI(ucg_t *ucg, uint8_t val)
{
uint8_t cnt = 8;
uint8_t bitData = u8g_bitData;
uint8_t bitNotData = u8g_bitNotData;
uint8_t bitClock = u8g_bitClock;
uint8_t bitNotClock = u8g_bitNotClock;
volatile uint8_t *outData = u8g_outData;
volatile uint8_t *outClock = u8g_outClock;
UCG_ATOMIC_START();
do
{
if ( val & 128 )
*outData |= bitData;
else
*outData &= bitNotData;
*outClock |= bitClock;
val <<= 1;
cnt--;
*outClock &= bitNotClock;
} while( cnt != 0 );
UCG_ATOMIC_END();
}
#else
static void ucg_com_arduino_send_generic_SW_SPI(ucg_t *ucg, uint8_t data)
{
uint8_t i = 8;
do
{
if ( data & 128 )
{
digitalWrite(ucg->pin_list[UCG_PIN_SDA], 1 );
}
else
{
digitalWrite(ucg->pin_list[UCG_PIN_SDA], 0 );
}
// no delay required, also Arduino Due is slow enough
//delayMicroseconds(1);
digitalWrite(ucg->pin_list[UCG_PIN_SCL], 1 );
//delayMicroseconds(1);
i--;
digitalWrite(ucg->pin_list[UCG_PIN_SCL], 0 );
//delayMicroseconds(1);
data <<= 1;
} while( i > 0 );
}
#endif
static int16_t ucg_com_arduino_generic_SW_SPI(ucg_t *ucg, int16_t msg, uint16_t arg, uint8_t *data)
{
switch(msg)
{
case UCG_COM_MSG_POWER_UP:
/* "data" is a pointer to ucg_com_info_t structure with the following information: */
/* ((ucg_com_info_t *)data)->serial_clk_speed value in nanoseconds */
/* ((ucg_com_info_t *)data)->parallel_clk_speed value in nanoseconds */
#ifdef __AVR__
ucg_com_arduino_init_shift_out(ucg->pin_list[UCG_PIN_SDA], ucg->pin_list[UCG_PIN_SCL]);
#endif
/* setup pins */
pinMode(ucg->pin_list[UCG_PIN_CD], OUTPUT);
pinMode(ucg->pin_list[UCG_PIN_SDA], OUTPUT);
pinMode(ucg->pin_list[UCG_PIN_SCL], OUTPUT);
if ( ucg->pin_list[UCG_PIN_CS] != UCG_PIN_VAL_NONE )
pinMode(ucg->pin_list[UCG_PIN_CS], OUTPUT);
if ( ucg->pin_list[UCG_PIN_RST] != UCG_PIN_VAL_NONE )
pinMode(ucg->pin_list[UCG_PIN_RST], OUTPUT);
digitalWrite(ucg->pin_list[UCG_PIN_CD], 1);
digitalWrite(ucg->pin_list[UCG_PIN_SDA], 1);
digitalWrite(ucg->pin_list[UCG_PIN_SCL], 0);
if ( ucg->pin_list[UCG_PIN_CS] != UCG_PIN_VAL_NONE )
digitalWrite(ucg->pin_list[UCG_PIN_CS], 1);
if ( ucg->pin_list[UCG_PIN_RST] != UCG_PIN_VAL_NONE )
digitalWrite(ucg->pin_list[UCG_PIN_RST], 1);
break;
case UCG_COM_MSG_POWER_DOWN:
break;
case UCG_COM_MSG_DELAY:
delayMicroseconds(arg);
break;
case UCG_COM_MSG_CHANGE_RESET_LINE:
if ( ucg->pin_list[UCG_PIN_RST] != UCG_PIN_VAL_NONE )
digitalWrite(ucg->pin_list[UCG_PIN_RST], arg);
break;
case UCG_COM_MSG_CHANGE_CS_LINE:
#ifdef __AVR__
ucg_com_arduino_init_shift_out(ucg->pin_list[UCG_PIN_SDA], ucg->pin_list[UCG_PIN_SCL]);
#endif
if ( ucg->pin_list[UCG_PIN_CS] != UCG_PIN_VAL_NONE )
digitalWrite(ucg->pin_list[UCG_PIN_CS], arg);
break;
case UCG_COM_MSG_CHANGE_CD_LINE:
digitalWrite(ucg->pin_list[UCG_PIN_CD], arg);
break;
case UCG_COM_MSG_SEND_BYTE:
ucg_com_arduino_send_generic_SW_SPI(ucg, arg);
break;
case UCG_COM_MSG_REPEAT_1_BYTE:
while( arg > 0 ) {
ucg_com_arduino_send_generic_SW_SPI(ucg, data[0]);
arg--;
}
break;
case UCG_COM_MSG_REPEAT_2_BYTES:
while( arg > 0 ) {
ucg_com_arduino_send_generic_SW_SPI(ucg, data[0]);
ucg_com_arduino_send_generic_SW_SPI(ucg, data[1]);
arg--;
}
break;
case UCG_COM_MSG_REPEAT_3_BYTES:
while( arg > 0 ) {
ucg_com_arduino_send_generic_SW_SPI(ucg, data[0]);
ucg_com_arduino_send_generic_SW_SPI(ucg, data[1]);
ucg_com_arduino_send_generic_SW_SPI(ucg, data[2]);
arg--;
}
break;
case UCG_COM_MSG_SEND_STR:
while( arg > 0 ) {
ucg_com_arduino_send_generic_SW_SPI(ucg, *data++);
arg--;
}
break;
case UCG_COM_MSG_SEND_CD_DATA_SEQUENCE:
while(arg > 0)
{
if ( *data != 0 )
{
if ( *data == 1 )
{
digitalWrite(ucg->pin_list[UCG_PIN_CD], 0);
}
else
{
digitalWrite(ucg->pin_list[UCG_PIN_CD], 1);
}
}
data++;
ucg_com_arduino_send_generic_SW_SPI(ucg, *data);
data++;
arg--;
}
break;
}
return 1;
}
void Ucglib4WireSWSPI::begin(uint8_t is_transparent)
{
ucg_Init(&ucg, dev_cb, ext_cb, ucg_com_arduino_generic_SW_SPI);
ucg_SetFontMode(&ucg, is_transparent);
}
/*=========================================================================*/
/* 8 Bit SW SPI for ILI9325 (mode IM3=0, IM2=1, IM1=0, IM0=0 */
static int16_t ucg_com_arduino_illi9325_SW_SPI(ucg_t *ucg, int16_t msg, uint16_t arg, uint8_t *data)
{
switch(msg)
{
case UCG_COM_MSG_POWER_UP:
/* "data" is a pointer to ucg_com_info_t structure with the following information: */
/* ((ucg_com_info_t *)data)->serial_clk_speed value in nanoseconds */
/* ((ucg_com_info_t *)data)->parallel_clk_speed value in nanoseconds */
#ifdef __AVR__
ucg_com_arduino_init_shift_out(ucg->pin_list[UCG_PIN_SDA], ucg->pin_list[UCG_PIN_SCL]);
#endif
/* setup pins */
pinMode(ucg->pin_list[UCG_PIN_CD], OUTPUT);
pinMode(ucg->pin_list[UCG_PIN_SDA], OUTPUT);
pinMode(ucg->pin_list[UCG_PIN_SCL], OUTPUT);
if ( ucg->pin_list[UCG_PIN_CS] != UCG_PIN_VAL_NONE )
pinMode(ucg->pin_list[UCG_PIN_CS], OUTPUT);
if ( ucg->pin_list[UCG_PIN_RST] != UCG_PIN_VAL_NONE )
pinMode(ucg->pin_list[UCG_PIN_RST], OUTPUT);
digitalWrite(ucg->pin_list[UCG_PIN_CD], 1);
digitalWrite(ucg->pin_list[UCG_PIN_SDA], 1);
digitalWrite(ucg->pin_list[UCG_PIN_SCL], 0);
if ( ucg->pin_list[UCG_PIN_CS] != UCG_PIN_VAL_NONE )
digitalWrite(ucg->pin_list[UCG_PIN_CS], 1);
if ( ucg->pin_list[UCG_PIN_RST] != UCG_PIN_VAL_NONE )
digitalWrite(ucg->pin_list[UCG_PIN_RST], 1);
break;
case UCG_COM_MSG_POWER_DOWN:
break;
case UCG_COM_MSG_DELAY:
delayMicroseconds(arg);
break;
case UCG_COM_MSG_CHANGE_RESET_LINE:
if ( ucg->pin_list[UCG_PIN_RST] != UCG_PIN_VAL_NONE )
digitalWrite(ucg->pin_list[UCG_PIN_RST], arg);
break;
case UCG_COM_MSG_CHANGE_CS_LINE:
#ifdef __AVR__
ucg_com_arduino_init_shift_out(ucg->pin_list[UCG_PIN_SDA], ucg->pin_list[UCG_PIN_SCL]);
#endif
if ( ucg->pin_list[UCG_PIN_CS] != UCG_PIN_VAL_NONE )
digitalWrite(ucg->pin_list[UCG_PIN_CS], arg);
break;
case UCG_COM_MSG_CHANGE_CD_LINE:
if ( ucg->pin_list[UCG_PIN_CS] != UCG_PIN_VAL_NONE )
{
digitalWrite(ucg->pin_list[UCG_PIN_CS], 1);
digitalWrite(ucg->pin_list[UCG_PIN_CS], 0);
}
if ( ucg->com_status & UCG_COM_STATUS_MASK_CD )
ucg_com_arduino_send_generic_SW_SPI(ucg, 0x072);
else
ucg_com_arduino_send_generic_SW_SPI(ucg, 0x070);
break;
case UCG_COM_MSG_SEND_BYTE:
ucg_com_arduino_send_generic_SW_SPI(ucg, arg);
break;
case UCG_COM_MSG_REPEAT_1_BYTE:
while( arg > 0 ) {
ucg_com_arduino_send_generic_SW_SPI(ucg, data[0]);
arg--;
}
break;
case UCG_COM_MSG_REPEAT_2_BYTES:
while( arg > 0 ) {
ucg_com_arduino_send_generic_SW_SPI(ucg, data[0]);
ucg_com_arduino_send_generic_SW_SPI(ucg, data[1]);
arg--;
}
break;
case UCG_COM_MSG_REPEAT_3_BYTES:
while( arg > 0 ) {
ucg_com_arduino_send_generic_SW_SPI(ucg, data[0]);
ucg_com_arduino_send_generic_SW_SPI(ucg, data[1]);
ucg_com_arduino_send_generic_SW_SPI(ucg, data[2]);
arg--;
}
break;
case UCG_COM_MSG_SEND_STR:
while( arg > 0 ) {
ucg_com_arduino_send_generic_SW_SPI(ucg, *data++);
arg--;
}
break;
case UCG_COM_MSG_SEND_CD_DATA_SEQUENCE:
while(arg > 0)
{
if ( *data != 0 )
{
if ( *data == 1 )
{
if ( ucg->pin_list[UCG_PIN_CS] != UCG_PIN_VAL_NONE )
{
digitalWrite(ucg->pin_list[UCG_PIN_CS], 1);
digitalWrite(ucg->pin_list[UCG_PIN_CS], 0);
}
ucg_com_arduino_send_generic_SW_SPI(ucg, 0x070);
}
else
{
if ( ucg->pin_list[UCG_PIN_CS] != UCG_PIN_VAL_NONE )
{
digitalWrite(ucg->pin_list[UCG_PIN_CS], 1);
digitalWrite(ucg->pin_list[UCG_PIN_CS], 0);
}
ucg_com_arduino_send_generic_SW_SPI(ucg, 0x072);
}
}
data++;
ucg_com_arduino_send_generic_SW_SPI(ucg, *data);
data++;
arg--;
}
break;
}
return 1;
}
void Ucglib3WireILI9325SWSPI::begin(uint8_t is_transparent)
{
ucg_Init(&ucg, dev_cb, ext_cb, ucg_com_arduino_illi9325_SW_SPI);
ucg_SetFontMode(&ucg, is_transparent);
}
/*=========================================================================*/
/* 9 Bit SW SPI */
static void ucg_com_arduino_send_3wire_9bit_SW_SPI(ucg_t *ucg, uint8_t first_bit, uint8_t data)
{
uint8_t i;
if ( first_bit != 0 )
{
digitalWrite(ucg->pin_list[UCG_PIN_SDA], 1 );
}
else
{
digitalWrite(ucg->pin_list[UCG_PIN_SDA], 0 );
}
// no delay required, also Arduino Due is slow enough
//delayMicroseconds(1);
digitalWrite(ucg->pin_list[UCG_PIN_SCL], 1 );
//delayMicroseconds(1);
digitalWrite(ucg->pin_list[UCG_PIN_SCL], 0 );
//delayMicroseconds(1);
i = 8;
do
{
if ( data & 128 )
{
digitalWrite(ucg->pin_list[UCG_PIN_SDA], 1 );
}
else
{
digitalWrite(ucg->pin_list[UCG_PIN_SDA], 0 );
}
// no delay required, also Arduino Due is slow enough
//delayMicroseconds(1);
digitalWrite(ucg->pin_list[UCG_PIN_SCL], 1 );
//delayMicroseconds(1);
i--;
digitalWrite(ucg->pin_list[UCG_PIN_SCL], 0 );
//delayMicroseconds(1);
data <<= 1;
} while( i > 0 );
}
static int16_t ucg_com_arduino_3wire_9bit_SW_SPI(ucg_t *ucg, int16_t msg, uint16_t arg, uint8_t *data)
{
switch(msg)
{
case UCG_COM_MSG_POWER_UP:
/* "data" is a pointer to ucg_com_info_t structure with the following information: */
/* ((ucg_com_info_t *)data)->serial_clk_speed value in nanoseconds */
/* ((ucg_com_info_t *)data)->parallel_clk_speed value in nanoseconds */
/* setup pins */
pinMode(ucg->pin_list[UCG_PIN_SDA], OUTPUT);
pinMode(ucg->pin_list[UCG_PIN_SCL], OUTPUT);
if ( ucg->pin_list[UCG_PIN_CS] != UCG_PIN_VAL_NONE )
pinMode(ucg->pin_list[UCG_PIN_CS], OUTPUT);
if ( ucg->pin_list[UCG_PIN_RST] != UCG_PIN_VAL_NONE )
pinMode(ucg->pin_list[UCG_PIN_RST], OUTPUT);
digitalWrite(ucg->pin_list[UCG_PIN_SDA], 1);
digitalWrite(ucg->pin_list[UCG_PIN_SCL], 0);
if ( ucg->pin_list[UCG_PIN_CS] != UCG_PIN_VAL_NONE )
digitalWrite(ucg->pin_list[UCG_PIN_CS], 1);
if ( ucg->pin_list[UCG_PIN_RST] != UCG_PIN_VAL_NONE )
digitalWrite(ucg->pin_list[UCG_PIN_RST], 1);
break;
case UCG_COM_MSG_POWER_DOWN:
break;
case UCG_COM_MSG_DELAY:
delayMicroseconds(arg);
break;
case UCG_COM_MSG_CHANGE_RESET_LINE:
if ( ucg->pin_list[UCG_PIN_RST] != UCG_PIN_VAL_NONE )
digitalWrite(ucg->pin_list[UCG_PIN_RST], arg);
break;
case UCG_COM_MSG_CHANGE_CS_LINE:
if ( ucg->pin_list[UCG_PIN_CS] != UCG_PIN_VAL_NONE )
digitalWrite(ucg->pin_list[UCG_PIN_CS], arg);
break;
case UCG_COM_MSG_CHANGE_CD_LINE:
/* ignored, there is not CD line */
break;
case UCG_COM_MSG_SEND_BYTE:
ucg_com_arduino_send_3wire_9bit_SW_SPI(ucg, ucg->com_status &UCG_COM_STATUS_MASK_CD, arg);
break;
case UCG_COM_MSG_REPEAT_1_BYTE:
while( arg > 0 ) {
ucg_com_arduino_send_3wire_9bit_SW_SPI(ucg, ucg->com_status &UCG_COM_STATUS_MASK_CD, data[0]);
arg--;
}
break;
case UCG_COM_MSG_REPEAT_2_BYTES:
while( arg > 0 ) {
ucg_com_arduino_send_3wire_9bit_SW_SPI(ucg, ucg->com_status &UCG_COM_STATUS_MASK_CD, data[0]);
ucg_com_arduino_send_3wire_9bit_SW_SPI(ucg, ucg->com_status &UCG_COM_STATUS_MASK_CD, data[1]);
arg--;
}
break;
case UCG_COM_MSG_REPEAT_3_BYTES:
while( arg > 0 ) {
ucg_com_arduino_send_3wire_9bit_SW_SPI(ucg, ucg->com_status &UCG_COM_STATUS_MASK_CD, data[0]);
ucg_com_arduino_send_3wire_9bit_SW_SPI(ucg, ucg->com_status &UCG_COM_STATUS_MASK_CD, data[1]);
ucg_com_arduino_send_3wire_9bit_SW_SPI(ucg, ucg->com_status &UCG_COM_STATUS_MASK_CD, data[2]);
arg--;
}
break;
case UCG_COM_MSG_SEND_STR:
while( arg > 0 ) {
ucg_com_arduino_send_3wire_9bit_SW_SPI(ucg, ucg->com_status &UCG_COM_STATUS_MASK_CD, *data++);
arg--;
}
break;
case UCG_COM_MSG_SEND_CD_DATA_SEQUENCE:
{
uint8_t last_cd = ucg->com_status &UCG_COM_STATUS_MASK_CD;
while(arg > 0)
{
if ( *data != 0 )
{
if ( *data == 1 )
{
last_cd = 0;
}
else
{
last_cd = 1;
}
}
data++;
ucg_com_arduino_send_3wire_9bit_SW_SPI(ucg, last_cd, *data);
data++;
arg--;
}
}
break;
}
return 1;
}
void Ucglib3Wire9bitSWSPI::begin(uint8_t is_transparent)
{
ucg_Init(&ucg, dev_cb, ext_cb, ucg_com_arduino_3wire_9bit_SW_SPI);
ucg_SetFontMode(&ucg, is_transparent);
}
/*=========================================================================*/
/* 9 Bit HW SPI */
#define UCG_COM_ARDUINO_3WIRE_8BIT_BUF_LEN 9
static uint8_t ucg_com_3wire_9bit_buffer[UCG_COM_ARDUINO_3WIRE_8BIT_BUF_LEN];
static uint8_t ucg_com_3wire_9bit_buf_bytepos;
static uint8_t ucg_com_3wire_9bit_buf_bitpos;
static uint8_t ucg_com_3wire_9bit_cd_mask;
static void ucg_com_arduino_init_3wire_9bit_HW_SPI(ucg_t *ucg) UCG_NOINLINE;
static void ucg_com_arduino_init_3wire_9bit_HW_SPI(ucg_t *ucg)
{
uint8_t i;
ucg_com_3wire_9bit_buf_bytepos = 0;
ucg_com_3wire_9bit_buf_bitpos = 7;
ucg_com_3wire_9bit_cd_mask = 128;
for( i = 0; i < UCG_COM_ARDUINO_3WIRE_8BIT_BUF_LEN; i++ )
ucg_com_3wire_9bit_buffer[i] = 0; /* this is also the NOP command for the PCF8833 */
}
static void ucg_com_arduino_flush_3wire_9bit_HW_SPI(ucg_t *ucg) UCG_NOINLINE;
static void ucg_com_arduino_flush_3wire_9bit_HW_SPI(ucg_t *ucg)
{
uint8_t i;
if ( ucg_com_3wire_9bit_buf_bytepos == 0 && ucg_com_3wire_9bit_buf_bitpos == 7 )
return;
for( i = 0; i < UCG_COM_ARDUINO_3WIRE_8BIT_BUF_LEN; i++ )
SPI.transfer(ucg_com_3wire_9bit_buffer[i] );
ucg_com_arduino_init_3wire_9bit_HW_SPI(ucg);
}
static void ucg_com_arduino_send_3wire_9bit_HW_SPI(ucg_t *ucg, uint8_t first_bit, uint8_t data)
{
if ( first_bit != 0 )
ucg_com_3wire_9bit_buffer[ucg_com_3wire_9bit_buf_bytepos] |= ucg_com_3wire_9bit_cd_mask;
if ( ucg_com_3wire_9bit_buf_bitpos > 0 )
{
ucg_com_3wire_9bit_buf_bitpos--;
ucg_com_3wire_9bit_cd_mask >>= 1;
}
else
{
ucg_com_3wire_9bit_buf_bitpos = 7;
ucg_com_3wire_9bit_buf_bytepos++;
ucg_com_3wire_9bit_cd_mask = 128;
}
ucg_com_3wire_9bit_buffer[ucg_com_3wire_9bit_buf_bytepos] |= data >> (7-ucg_com_3wire_9bit_buf_bitpos);
if ( ucg_com_3wire_9bit_buf_bitpos == 7 )
{
ucg_com_3wire_9bit_buf_bytepos++;
if ( ucg_com_3wire_9bit_buf_bytepos >= UCG_COM_ARDUINO_3WIRE_8BIT_BUF_LEN )
ucg_com_arduino_flush_3wire_9bit_HW_SPI(ucg);
}
else
{
ucg_com_3wire_9bit_buf_bytepos++;
ucg_com_3wire_9bit_buffer[ucg_com_3wire_9bit_buf_bytepos] |= data << (ucg_com_3wire_9bit_buf_bitpos+1);
}
}
static int16_t ucg_com_arduino_3wire_9bit_HW_SPI(ucg_t *ucg, int16_t msg, uint16_t arg, uint8_t *data)
{
switch(msg)
{
case UCG_COM_MSG_POWER_UP:
/* "data" is a pointer to ucg_com_info_t structure with the following information: */
/* ((ucg_com_info_t *)data)->serial_clk_speed value in nanoseconds */
/* ((ucg_com_info_t *)data)->parallel_clk_speed value in nanoseconds */
ucg_com_arduino_init_3wire_9bit_HW_SPI(ucg);
/* setup pins */
if ( ucg->pin_list[UCG_PIN_CS] != UCG_PIN_VAL_NONE )
pinMode(ucg->pin_list[UCG_PIN_CS], OUTPUT);
if ( ucg->pin_list[UCG_PIN_RST] != UCG_PIN_VAL_NONE )
pinMode(ucg->pin_list[UCG_PIN_RST], OUTPUT);
if ( ucg->pin_list[UCG_PIN_CS] != UCG_PIN_VAL_NONE )
digitalWrite(ucg->pin_list[UCG_PIN_CS], 1);
if ( ucg->pin_list[UCG_PIN_RST] != UCG_PIN_VAL_NONE )
digitalWrite(ucg->pin_list[UCG_PIN_RST], 1);
/* setup Arduino SPI */
SPI.begin();
#if defined(__AVR__)
SPI.setClockDivider( SPI_CLOCK_DIV2 );
//SPI.setClockDivider( SPI_CLOCK_DIV64 );
//SPI.setDataMode(SPI_MODE0);
#endif
#if defined(__SAM3X8E__)
SPI.setClockDivider( (((ucg_com_info_t *)data)->serial_clk_speed * 84L + 999)/1000L );
#endif
SPI.setDataMode(SPI_MODE0);
SPI.setBitOrder(MSBFIRST);
break;
case UCG_COM_MSG_POWER_DOWN:
SPI.end();
break;
case UCG_COM_MSG_DELAY:
/* flush pending data first, then do the delay */
ucg_com_arduino_flush_3wire_9bit_HW_SPI(ucg);
delayMicroseconds(arg);
break;
case UCG_COM_MSG_CHANGE_RESET_LINE:
if ( ucg->pin_list[UCG_PIN_RST] != UCG_PIN_VAL_NONE )
digitalWrite(ucg->pin_list[UCG_PIN_RST], arg);
break;
case UCG_COM_MSG_CHANGE_CS_LINE:
if ( arg != 0 )
ucg_com_arduino_flush_3wire_9bit_HW_SPI(ucg);
if ( ucg->pin_list[UCG_PIN_CS] != UCG_PIN_VAL_NONE )
digitalWrite(ucg->pin_list[UCG_PIN_CS], arg);
if ( arg == 0 )
ucg_com_arduino_init_3wire_9bit_HW_SPI(ucg);
break;
case UCG_COM_MSG_CHANGE_CD_LINE:
/* not used */
break;
case UCG_COM_MSG_SEND_BYTE:
ucg_com_arduino_send_3wire_9bit_HW_SPI(ucg, ucg->com_status &UCG_COM_STATUS_MASK_CD, arg);
break;
case UCG_COM_MSG_REPEAT_1_BYTE:
while( arg > 0 ) {
ucg_com_arduino_send_3wire_9bit_HW_SPI(ucg, ucg->com_status &UCG_COM_STATUS_MASK_CD, data[0]);
arg--;
}
break;
case UCG_COM_MSG_REPEAT_2_BYTES:
while( arg > 0 ) {
ucg_com_arduino_send_3wire_9bit_HW_SPI(ucg, ucg->com_status &UCG_COM_STATUS_MASK_CD, data[0]);
ucg_com_arduino_send_3wire_9bit_HW_SPI(ucg, ucg->com_status &UCG_COM_STATUS_MASK_CD, data[1]);
arg--;
}
break;
case UCG_COM_MSG_REPEAT_3_BYTES:
while( arg > 0 ) {
ucg_com_arduino_send_3wire_9bit_HW_SPI(ucg, ucg->com_status &UCG_COM_STATUS_MASK_CD, data[0]);
ucg_com_arduino_send_3wire_9bit_HW_SPI(ucg, ucg->com_status &UCG_COM_STATUS_MASK_CD, data[1]);
ucg_com_arduino_send_3wire_9bit_HW_SPI(ucg, ucg->com_status &UCG_COM_STATUS_MASK_CD, data[2]);
arg--;
}
break;
case UCG_COM_MSG_SEND_STR:
while( arg > 0 ) {
ucg_com_arduino_send_3wire_9bit_HW_SPI(ucg, ucg->com_status &UCG_COM_STATUS_MASK_CD, *data++);
arg--;
}
break;
case UCG_COM_MSG_SEND_CD_DATA_SEQUENCE:
{
uint8_t last_cd = ucg->com_status &UCG_COM_STATUS_MASK_CD;
while(arg > 0)
{
if ( *data != 0 )
{
if ( *data == 1 )
{
last_cd = 0;
}
else
{
last_cd = 1;
}
}
data++;
ucg_com_arduino_send_3wire_9bit_HW_SPI(ucg, last_cd, *data);
data++;
arg--;
}
}
break;
}
return 1;
}
void Ucglib3Wire9bitHWSPI::begin(uint8_t is_transparent)
{
ucg_Init(&ucg, dev_cb, ext_cb, ucg_com_arduino_3wire_9bit_HW_SPI);
ucg_SetFontMode(&ucg, is_transparent);
}
/*=========================================================================*/
/* 8 Bit Parallel */
#if defined(__PIC32MX) || defined(__arm__) || defined(ESP8266)
/* CHIPKIT PIC32 */
static volatile uint32_t *u8g_data_port[9];
static uint32_t u8g_data_mask[9];
#else
static volatile uint8_t *u8g_data_port[9];
static uint8_t u8g_data_mask[9];
#endif
static void ucg_com_arduino_init_8bit(ucg_t *ucg)
{
u8g_data_port[0] = portOutputRegister(digitalPinToPort(ucg->pin_list[UCG_PIN_D0]));
u8g_data_mask[0] = digitalPinToBitMask(ucg->pin_list[UCG_PIN_D0]);
u8g_data_port[1] = portOutputRegister(digitalPinToPort(ucg->pin_list[UCG_PIN_D1]));
u8g_data_mask[1] = digitalPinToBitMask(ucg->pin_list[UCG_PIN_D1]);
u8g_data_port[2] = portOutputRegister(digitalPinToPort(ucg->pin_list[UCG_PIN_D2]));
u8g_data_mask[2] = digitalPinToBitMask(ucg->pin_list[UCG_PIN_D2]);
u8g_data_port[3] = portOutputRegister(digitalPinToPort(ucg->pin_list[UCG_PIN_D3]));
u8g_data_mask[3] = digitalPinToBitMask(ucg->pin_list[UCG_PIN_D3]);
u8g_data_port[4] = portOutputRegister(digitalPinToPort(ucg->pin_list[UCG_PIN_D4]));
u8g_data_mask[4] = digitalPinToBitMask(ucg->pin_list[UCG_PIN_D4]);
u8g_data_port[5] = portOutputRegister(digitalPinToPort(ucg->pin_list[UCG_PIN_D5]));
u8g_data_mask[5] = digitalPinToBitMask(ucg->pin_list[UCG_PIN_D5]);
if ( ucg->pin_list[UCG_PIN_D6] != UCG_PIN_VAL_NONE )
{
u8g_data_port[6] = portOutputRegister(digitalPinToPort(ucg->pin_list[UCG_PIN_D6]));
u8g_data_mask[6] = digitalPinToBitMask(ucg->pin_list[UCG_PIN_D6]);
}
if ( ucg->pin_list[UCG_PIN_D7] != UCG_PIN_VAL_NONE )
{
u8g_data_port[7] = portOutputRegister(digitalPinToPort(ucg->pin_list[UCG_PIN_D7]));
u8g_data_mask[7] = digitalPinToBitMask(ucg->pin_list[UCG_PIN_D7]);
}
u8g_data_port[8] = portOutputRegister(digitalPinToPort(ucg->pin_list[UCG_PIN_WR]));
u8g_data_mask[8] = digitalPinToBitMask(ucg->pin_list[UCG_PIN_WR]);
}
static void ucg_com_arduino_send_8bit(ucg_t *ucg, uint8_t data)
{
int i;
#if defined(__arm__)
__NOP;
__NOP;
__NOP;
__NOP;
__NOP;
__NOP;
__NOP;
__NOP;
__NOP;
__NOP;
__NOP;
__NOP;
__NOP;
__NOP;
__NOP;
__NOP;
#endif
for( i = 0; i < 8; i++ )
{
if ( data & 1 )
*u8g_data_port[i] |= u8g_data_mask[i];
else
*u8g_data_port[i] &= ~u8g_data_mask[i];
data >>= 1;
}
#if defined(__arm__)
__NOP;
__NOP;
__NOP;
__NOP;
__NOP;
__NOP;
__NOP;
__NOP;
__NOP;
__NOP;
__NOP;
__NOP;
__NOP;
__NOP;
__NOP;
__NOP;
delayMicroseconds(1);
#elif defined(__AVR__)
#else
delayMicroseconds(1);
#endif
*u8g_data_port[8] &= ~u8g_data_mask[8];
#if defined(__arm__)
__NOP;
__NOP;
__NOP;
__NOP;
__NOP;
__NOP;
__NOP;
__NOP;
__NOP;
__NOP;
__NOP;
__NOP;
__NOP;
__NOP;
__NOP;
__NOP;
delayMicroseconds(1);
#elif defined(__AVR__)
#else
delayMicroseconds(1);
#endif
*u8g_data_port[8] |= u8g_data_mask[8];
}
/*
static void ucg_com_arduino_send_8bit(ucg_t *ucg, uint8_t data)
{
digitalWrite(ucg->pin_list[UCG_PIN_D0], (data & 1) == 0 ? 0 : 1 );
digitalWrite(ucg->pin_list[UCG_PIN_D1], (data & 2) == 0 ? 0 : 1 );
digitalWrite(ucg->pin_list[UCG_PIN_D2], (data & 4) == 0 ? 0 : 1 );
digitalWrite(ucg->pin_list[UCG_PIN_D3], (data & 8) == 0 ? 0 : 1 );
digitalWrite(ucg->pin_list[UCG_PIN_D4], (data & 16) == 0 ? 0 : 1 );
digitalWrite(ucg->pin_list[UCG_PIN_D5], (data & 32) == 0 ? 0 : 1 );
if ( ucg->pin_list[UCG_PIN_D6] != UCG_PIN_VAL_NONE )
digitalWrite(ucg->pin_list[UCG_PIN_D6], (data & 64) == 0 ? 0 : 1 );
if ( ucg->pin_list[UCG_PIN_D7] != UCG_PIN_VAL_NONE )
digitalWrite(ucg->pin_list[UCG_PIN_D7], (data & 128) == 0 ? 0 : 1 );
delayMicroseconds(1);
digitalWrite(ucg->pin_list[UCG_PIN_WR], 0);
delayMicroseconds(1);
digitalWrite(ucg->pin_list[UCG_PIN_WR], 1);
}
*/
static int16_t ucg_com_arduino_generic_8bit(ucg_t *ucg, int16_t msg, uint16_t arg, uint8_t *data)
{
switch(msg)
{
case UCG_COM_MSG_POWER_UP:
/* "data" is a pointer to ucg_com_info_t structure with the following information: */
/* ((ucg_com_info_t *)data)->serial_clk_speed value in nanoseconds */
/* ((ucg_com_info_t *)data)->parallel_clk_speed value in nanoseconds */
/* setup pins */
pinMode(ucg->pin_list[UCG_PIN_CD], OUTPUT);
pinMode(ucg->pin_list[UCG_PIN_WR], OUTPUT);
if ( ucg->pin_list[UCG_PIN_CS] != UCG_PIN_VAL_NONE )
pinMode(ucg->pin_list[UCG_PIN_CS], OUTPUT);
if ( ucg->pin_list[UCG_PIN_RST] != UCG_PIN_VAL_NONE )
pinMode(ucg->pin_list[UCG_PIN_RST], OUTPUT);
pinMode(ucg->pin_list[UCG_PIN_D0], OUTPUT);
pinMode(ucg->pin_list[UCG_PIN_D1], OUTPUT);
pinMode(ucg->pin_list[UCG_PIN_D2], OUTPUT);
pinMode(ucg->pin_list[UCG_PIN_D3], OUTPUT);
pinMode(ucg->pin_list[UCG_PIN_D4], OUTPUT);
pinMode(ucg->pin_list[UCG_PIN_D5], OUTPUT);
if ( ucg->pin_list[UCG_PIN_D6] != UCG_PIN_VAL_NONE )
pinMode(ucg->pin_list[UCG_PIN_D6], OUTPUT);
if ( ucg->pin_list[UCG_PIN_D7] != UCG_PIN_VAL_NONE )
pinMode(ucg->pin_list[UCG_PIN_D7], OUTPUT);
digitalWrite(ucg->pin_list[UCG_PIN_CD], 1);
digitalWrite(ucg->pin_list[UCG_PIN_WR], 1);
if ( ucg->pin_list[UCG_PIN_CS] != UCG_PIN_VAL_NONE )
digitalWrite(ucg->pin_list[UCG_PIN_CS], 1);
if ( ucg->pin_list[UCG_PIN_RST] != UCG_PIN_VAL_NONE )
digitalWrite(ucg->pin_list[UCG_PIN_RST], 1);
ucg_com_arduino_init_8bit(ucg);
break;
case UCG_COM_MSG_POWER_DOWN:
break;
case UCG_COM_MSG_DELAY:
delayMicroseconds(arg);
break;
case UCG_COM_MSG_CHANGE_RESET_LINE:
if ( ucg->pin_list[UCG_PIN_RST] != UCG_PIN_VAL_NONE )
digitalWrite(ucg->pin_list[UCG_PIN_RST], arg);
break;
case UCG_COM_MSG_CHANGE_CS_LINE:
if ( ucg->pin_list[UCG_PIN_CS] != UCG_PIN_VAL_NONE )
digitalWrite(ucg->pin_list[UCG_PIN_CS], arg);
break;
case UCG_COM_MSG_CHANGE_CD_LINE:
digitalWrite(ucg->pin_list[UCG_PIN_CD], arg);
break;
case UCG_COM_MSG_SEND_BYTE:
ucg_com_arduino_send_8bit(ucg, arg);
break;
case UCG_COM_MSG_REPEAT_1_BYTE:
while( arg > 0 ) {
ucg_com_arduino_send_8bit(ucg, data[0]);
arg--;
}
break;
case UCG_COM_MSG_REPEAT_2_BYTES:
while( arg > 0 ) {
ucg_com_arduino_send_8bit(ucg, data[0]);
ucg_com_arduino_send_8bit(ucg, data[1]);
arg--;
}
break;
case UCG_COM_MSG_REPEAT_3_BYTES:
while( arg > 0 ) {
ucg_com_arduino_send_8bit(ucg, data[0]);
ucg_com_arduino_send_8bit(ucg, data[1]);
ucg_com_arduino_send_8bit(ucg, data[2]);
arg--;
}
break;
case UCG_COM_MSG_SEND_STR:
while( arg > 0 ) {
ucg_com_arduino_send_8bit(ucg, *data++);
arg--;
}
break;
case UCG_COM_MSG_SEND_CD_DATA_SEQUENCE:
while(arg > 0)
{
if ( *data != 0 )
{
if ( *data == 1 )
{
digitalWrite(ucg->pin_list[UCG_PIN_CD], 0);
}
else
{
digitalWrite(ucg->pin_list[UCG_PIN_CD], 1);
}
}
data++;
ucg_com_arduino_send_8bit(ucg, *data);
data++;
arg--;
}
break;
}
return 1;
}
void Ucglib8Bit::begin(uint8_t is_transparent)
{
ucg_Init(&ucg, dev_cb, ext_cb, ucg_com_arduino_generic_8bit);
ucg_SetFontMode(&ucg, is_transparent);
}
/*=========================================================================*/
/* 8 Bit Parallel on Port D of AVR controller */
#ifdef __AVR__
static void ucg_com_arduino_port_d_send(uint8_t data, volatile uint8_t *port, uint8_t and_mask, uint8_t or_mask)
{
PORTD = data;
*port &= and_mask;
*port |= or_mask;
}
static int16_t ucg_com_arduino_port_d(ucg_t *ucg, int16_t msg, uint16_t arg, uint8_t *data)
{
switch(msg)
{
case UCG_COM_MSG_POWER_UP:
/* "data" is a pointer to ucg_com_info_t structure with the following information: */
/* ((ucg_com_info_t *)data)->serial_clk_speed value in nanoseconds */
/* ((ucg_com_info_t *)data)->parallel_clk_speed value in nanoseconds */
/* setup pins */
pinMode(ucg->pin_list[UCG_PIN_CD], OUTPUT);
pinMode(ucg->pin_list[UCG_PIN_WR], OUTPUT);
if ( ucg->pin_list[UCG_PIN_CS] != UCG_PIN_VAL_NONE )
pinMode(ucg->pin_list[UCG_PIN_CS], OUTPUT);
if ( ucg->pin_list[UCG_PIN_RST] != UCG_PIN_VAL_NONE )
pinMode(ucg->pin_list[UCG_PIN_RST], OUTPUT);
pinMode(0, OUTPUT);
pinMode(1, OUTPUT);
pinMode(2, OUTPUT);
pinMode(3, OUTPUT);
pinMode(4, OUTPUT);
pinMode(5, OUTPUT);
pinMode(6, OUTPUT);
pinMode(7, OUTPUT);
digitalWrite(ucg->pin_list[UCG_PIN_CD], 1);
digitalWrite(ucg->pin_list[UCG_PIN_WR], 1);
if ( ucg->pin_list[UCG_PIN_CS] != UCG_PIN_VAL_NONE )
digitalWrite(ucg->pin_list[UCG_PIN_CS], 1);
if ( ucg->pin_list[UCG_PIN_RST] != UCG_PIN_VAL_NONE )
digitalWrite(ucg->pin_list[UCG_PIN_RST], 1);
break;
case UCG_COM_MSG_POWER_DOWN:
break;
case UCG_COM_MSG_DELAY:
delayMicroseconds(arg);
break;
case UCG_COM_MSG_CHANGE_RESET_LINE:
if ( ucg->pin_list[UCG_PIN_RST] != UCG_PIN_VAL_NONE )
digitalWrite(ucg->pin_list[UCG_PIN_RST], arg);
break;
case UCG_COM_MSG_CHANGE_CS_LINE:
if ( ucg->pin_list[UCG_PIN_CS] != UCG_PIN_VAL_NONE )
digitalWrite(ucg->pin_list[UCG_PIN_CS], arg);
break;
case UCG_COM_MSG_CHANGE_CD_LINE:
if ( arg == 0 )
*ucg->data_port[UCG_PIN_CD] &= ~ucg->data_mask[UCG_PIN_CD];
else
*ucg->data_port[UCG_PIN_CD] |= ucg->data_mask[UCG_PIN_CD];
//digitalWrite(ucg->pin_list[UCG_PIN_CD], arg);
break;
case UCG_COM_MSG_SEND_BYTE:
ucg_com_arduino_port_d_send(arg, ucg->data_port[UCG_PIN_WR], ~ucg->data_mask[UCG_PIN_WR], ucg->data_mask[UCG_PIN_WR]);
break;
case UCG_COM_MSG_REPEAT_1_BYTE:
while( arg > 0 ) {
ucg_com_arduino_port_d_send(data[0], ucg->data_port[UCG_PIN_WR], ~ucg->data_mask[UCG_PIN_WR], ucg->data_mask[UCG_PIN_WR]);
arg--;
}
break;
case UCG_COM_MSG_REPEAT_2_BYTES:
while( arg > 0 ) {
ucg_com_arduino_port_d_send(data[0], ucg->data_port[UCG_PIN_WR], ~ucg->data_mask[UCG_PIN_WR], ucg->data_mask[UCG_PIN_WR]);
ucg_com_arduino_port_d_send(data[1], ucg->data_port[UCG_PIN_WR], ~ucg->data_mask[UCG_PIN_WR], ucg->data_mask[UCG_PIN_WR]);
arg--;
}
break;
case UCG_COM_MSG_REPEAT_3_BYTES:
while( arg > 0 ) {
ucg_com_arduino_port_d_send(data[0], ucg->data_port[UCG_PIN_WR], ~ucg->data_mask[UCG_PIN_WR], ucg->data_mask[UCG_PIN_WR]);
ucg_com_arduino_port_d_send(data[1], ucg->data_port[UCG_PIN_WR], ~ucg->data_mask[UCG_PIN_WR], ucg->data_mask[UCG_PIN_WR]);
ucg_com_arduino_port_d_send(data[2], ucg->data_port[UCG_PIN_WR], ~ucg->data_mask[UCG_PIN_WR], ucg->data_mask[UCG_PIN_WR]);
arg--;
}
break;
case UCG_COM_MSG_SEND_STR:
while( arg > 0 ) {
ucg_com_arduino_port_d_send(*data++, ucg->data_port[UCG_PIN_WR], ~ucg->data_mask[UCG_PIN_WR], ucg->data_mask[UCG_PIN_WR]);
arg--;
}
break;
case UCG_COM_MSG_SEND_CD_DATA_SEQUENCE:
while(arg > 0)
{
if ( *data != 0 )
{
if ( *data == 1 )
{
*ucg->data_port[UCG_PIN_CD] &= ~ucg->data_mask[UCG_PIN_CD];
}
else
{
*ucg->data_port[UCG_PIN_CD] |= ucg->data_mask[UCG_PIN_CD];
}
}
data++;
ucg_com_arduino_port_d_send(*data, ucg->data_port[UCG_PIN_WR], ~ucg->data_mask[UCG_PIN_WR], ucg->data_mask[UCG_PIN_WR]);
data++;
arg--;
}
break;
}
return 1;
}
void Ucglib8BitPortD::begin(uint8_t is_transparent)
{
ucg_Init(&ucg, dev_cb, ext_cb, ucg_com_arduino_port_d);
ucg_SetFontMode(&ucg, is_transparent);
}
#endif /* __AVR__ */
/*=========================================================================*/
static int16_t ucg_com_arduino_4wire_HW_SPI(ucg_t *ucg, int16_t msg, uint16_t arg, uint8_t *data)
{
switch(msg)
{
case UCG_COM_MSG_POWER_UP:
/* "data" is a pointer to ucg_com_info_t structure with the following information: */
/* ((ucg_com_info_t *)data)->serial_clk_speed value in nanoseconds */
/* ((ucg_com_info_t *)data)->parallel_clk_speed value in nanoseconds */
/* setup pins */
if ( ucg->pin_list[UCG_PIN_RST] != UCG_PIN_VAL_NONE )
pinMode(ucg->pin_list[UCG_PIN_RST], OUTPUT);
pinMode(ucg->pin_list[UCG_PIN_CD], OUTPUT);
if ( ucg->pin_list[UCG_PIN_CS] != UCG_PIN_VAL_NONE )
pinMode(ucg->pin_list[UCG_PIN_CS], OUTPUT);
/* setup Arduino SPI */
SPI.begin();
#if defined(__AVR__)
SPI.setClockDivider( SPI_CLOCK_DIV2 );
#endif
#if defined(__SAM3X8E__)
SPI.setClockDivider( (((ucg_com_info_t *)data)->serial_clk_speed * 84L + 999)/1000L );
#endif
SPI.setDataMode(SPI_MODE0);
SPI.setBitOrder(MSBFIRST);
break;
case UCG_COM_MSG_POWER_DOWN:
SPI.end();
break;
case UCG_COM_MSG_DELAY:
delayMicroseconds(arg);
break;
case UCG_COM_MSG_CHANGE_RESET_LINE:
if ( ucg->pin_list[UCG_PIN_RST] != UCG_PIN_VAL_NONE )
digitalWrite(ucg->pin_list[UCG_PIN_RST], arg);
break;
case UCG_COM_MSG_CHANGE_CS_LINE:
if ( ucg->pin_list[UCG_PIN_CS] != UCG_PIN_VAL_NONE )
digitalWrite(ucg->pin_list[UCG_PIN_CS], arg);
break;
case UCG_COM_MSG_CHANGE_CD_LINE:
digitalWrite(ucg->pin_list[UCG_PIN_CD], arg);
break;
case UCG_COM_MSG_SEND_BYTE:
SPI.transfer(arg);
break;
case UCG_COM_MSG_REPEAT_1_BYTE:
while( arg > 0 ) {
SPI.transfer(data[0]);
arg--;
}
break;
case UCG_COM_MSG_REPEAT_2_BYTES:
while( arg > 0 ) {
SPI.transfer(data[0]);
SPI.transfer(data[1]);
arg--;
}
break;
case UCG_COM_MSG_REPEAT_3_BYTES:
while( arg > 0 ) {
SPI.transfer(data[0]);
SPI.transfer(data[1]);
SPI.transfer(data[2]);
arg--;
}
break;
case UCG_COM_MSG_SEND_STR:
while( arg > 0 ) {
SPI.transfer(*data++);
arg--;
}
break;
case UCG_COM_MSG_SEND_CD_DATA_SEQUENCE:
while(arg > 0)
{
if ( *data != 0 )
{
/* set the data line directly, ignore the setting from UCG_CFG_CD */
if ( *data == 1 )
{
digitalWrite(ucg->pin_list[UCG_PIN_CD], 0);
}
else
{
digitalWrite(ucg->pin_list[UCG_PIN_CD], 1);
}
}
data++;
SPI.transfer(*data);
data++;
arg--;
}
break;
}
return 1;
}
void Ucglib4WireHWSPI::begin(uint8_t is_transparent)
{
ucg_Init(&ucg, dev_cb, ext_cb, ucg_com_arduino_4wire_HW_SPI);
ucg_SetFontMode(&ucg, is_transparent);
}
/*=========================================================================*/
void Ucglib::init(void) {
uint8_t i;
// do a dummy init so that something usefull is part of the ucg structure
ucg_Init(&ucg, ucg_dev_default_cb, ucg_ext_none, (ucg_com_fnptr)0);
// reset cursor position
tx = 0;
ty = 0;
tdir = 0; // default direction for Arduino print()
for( i = 0; i < UCG_PIN_COUNT; i++ )
ucg.pin_list[i] = UCG_PIN_VAL_NONE;
}
size_t Ucglib::write(uint8_t c) {
ucg_int_t delta;
delta = ucg_DrawGlyph(get_ucg(), get_tx(), get_ty(), get_tdir(), c);
switch(get_tdir()) {
case 0: get_tx() += delta; break;
case 1: get_ty() += delta; break;
case 2: get_tx() -= delta; break;
default: case 3: get_ty() -= delta; break;
}
return 1;
}
|
/*
* 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 "DefaultLitePullConsumer.h"
#include <memory>
#include "DefaultLitePullConsumerConfigImpl.hpp"
#include "DefaultLitePullConsumerImpl.h"
#include "MQClientConfigProxy.h"
#include "UtilAll.h"
namespace rocketmq {
namespace {
class TopicMessageQueuesChangedListenerImpl {
public:
TopicMessageQueuesChangedListenerImpl(TopicMessageQueueChangeListener* listener) : listener_(listener) {}
void operator()(const std::string& topic, const std::vector<MessageQueue>& message_queues) noexcept {
listener_->onChanged(topic, message_queues);
}
private:
TopicMessageQueueChangeListener* listener_;
};
} // namespace
DefaultLitePullConsumer::DefaultLitePullConsumer(const std::string& groupname)
: DefaultLitePullConsumer(groupname, nullptr) {}
DefaultLitePullConsumer::DefaultLitePullConsumer(const std::string& groupname, RPCHookPtr rpc_hook)
: DefaultLitePullConsumer(groupname, rpc_hook, std::make_shared<DefaultLitePullConsumerConfigImpl>()) {}
DefaultLitePullConsumer::DefaultLitePullConsumer(const std::string& groupname,
RPCHookPtr rpc_hook,
std::shared_ptr<DefaultLitePullConsumerConfigImpl> config)
: DefaultLitePullConsumerConfigProxy(*config), MQClientConfigProxy(config), pull_consumer_config_impl_(config) {
// set default group name
if (groupname.empty()) {
set_group_name(DEFAULT_CONSUMER_GROUP);
} else {
set_group_name(groupname);
}
// create DefaultLitePullConsumerImpl
pull_consumer_impl_ = DefaultLitePullConsumerImpl::Create(pull_consumer_config_impl_, rpc_hook);
}
void DefaultLitePullConsumer::start() {
pull_consumer_impl_->start();
}
void DefaultLitePullConsumer::shutdown() {
pull_consumer_impl_->shutdown();
}
bool DefaultLitePullConsumer::isAutoCommit() const {
return pull_consumer_impl_->isAutoCommit();
}
void DefaultLitePullConsumer::setAutoCommit(bool auto_commit) {
pull_consumer_impl_->setAutoCommit(auto_commit);
}
std::vector<MQMessageExt> DefaultLitePullConsumer::poll() {
return poll(pull_consumer_config_impl_->poll_timeout_millis());
}
std::vector<MQMessageExt> DefaultLitePullConsumer::poll(long timeout) {
return pull_consumer_impl_->Poll(timeout);
}
void DefaultLitePullConsumer::subscribe(const std::string& topic, const std::string& expression) {
pull_consumer_impl_->Subscribe(topic, expression);
}
void DefaultLitePullConsumer::subscribe(const std::string& topic, const MessageSelector& selector) {
pull_consumer_impl_->Subscribe(topic, selector);
}
void DefaultLitePullConsumer::unsubscribe(const std::string& topic) {
pull_consumer_impl_->Unsubscribe(topic);
}
std::vector<MessageQueue> DefaultLitePullConsumer::fetchMessageQueues(const std::string& topic) {
return pull_consumer_impl_->FetchMessageQueues(topic);
}
void DefaultLitePullConsumer::assign(std::vector<MessageQueue>& message_queues) {
pull_consumer_impl_->Assign(message_queues);
}
void DefaultLitePullConsumer::seek(const MessageQueue& message_queue, int64_t offset) {
pull_consumer_impl_->Seek(message_queue, offset);
}
void DefaultLitePullConsumer::seekToBegin(const MessageQueue& message_queue) {
pull_consumer_impl_->SeekToBegin(message_queue);
}
void DefaultLitePullConsumer::seekToEnd(const MessageQueue& message_queue) {
pull_consumer_impl_->SeekToEnd(message_queue);
}
int64_t DefaultLitePullConsumer::offsetForTimestamp(const MessageQueue& message_queue, int64_t timestamp) {
return pull_consumer_impl_->OffsetForTimestamp(message_queue, timestamp);
}
void DefaultLitePullConsumer::pause(const std::vector<MessageQueue>& message_queues) {
pull_consumer_impl_->Pause(message_queues);
}
void DefaultLitePullConsumer::resume(const std::vector<MessageQueue>& message_queues) {
pull_consumer_impl_->Resume(message_queues);
}
void DefaultLitePullConsumer::commitSync() {
pull_consumer_impl_->CommitSync();
}
int64_t DefaultLitePullConsumer::committed(const MessageQueue& message_queue) {
return pull_consumer_impl_->Committed(message_queue);
}
void DefaultLitePullConsumer::registerTopicMessageQueueChangeListener(
const std::string& topic,
TopicMessageQueueChangeListener* topic_message_queue_change_listener) {
pull_consumer_impl_->RegisterTopicMessageQueuesChangedListener(
topic, TopicMessageQueuesChangedListenerImpl{topic_message_queue_change_listener});
}
void DefaultLitePullConsumer::setRPCHook(RPCHookPtr rpc_hook) {
pull_consumer_impl_->setRPCHook(rpc_hook);
}
} // namespace rocketmq
|
/* Copyright (c) 2018 Francis James Franklin
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided
* that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and
* the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
* the following disclaimer in the documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 "netip/ip_manager.hh"
bool IP_Channel::slip_next_to_send (const u8_t *& byte, u8_t & flags) { // returns true if there are byte(s) to be sent
static const u8_t END = IP_SLIP_END;
static const u8_t ESC_END[2] = { IP_SLIP_ESC, IP_SLIP_ESC_END };
static const u8_t ESC_ESC[2] = { IP_SLIP_ESC, IP_SLIP_ESC_ESC };
flags = IP_SLIP_NONE;
if (!buffer_out) {
buffer_out = chain_out.chain_pop (); // which may still be 0
if (buffer_out) { // we have a new buffer; reset
bytes_sent = 0;
}
return false; // even if we have data to send, return now; this is a low priority job
}
if (bytes_sent == buffer_out->length ()) { // we've finished sending the buffer; add the frame end
flags = IP_SLIP_SINGLE | IP_SLIP_PACKET_LAST;
byte = &END;
/* don't need the buffer any more; set it free...
*/
buffer_out->unref ();
IP_Manager::manager().add_to_spares (buffer_out);
buffer_out = 0;
return true; // there's data to send
}
byte = buffer_out->bytes () + bytes_sent;
if (!bytes_sent) { // first byte of a new buffer!
flags |= IP_SLIP_PACKET_FIRST;
}
switch (*byte) {
case IP_SLIP_END:
flags |= IP_SLIP_ESCAPE;
byte = ESC_END;
break;
case IP_SLIP_ESC:
flags |= IP_SLIP_ESCAPE;
byte = ESC_ESC;
break;
default:
flags |= IP_SLIP_SINGLE;
break;
}
++bytes_sent;
return true; // there's data to send
}
bool IP_Channel::slip_can_receive () {
if (slip_read_flags == IP_SLIP_READ_COMPLETE) {
if (!IP_Manager::manager().queue (buffer_in)) {
return false; // oops, need to hang onto the buffer
}
// DEBUG_PRINT ("~ ");
slip_read_flags = 0;
buffer_in->clear (); // this is now actually a different buffer
}
return true;
}
void IP_Channel::slip_receive (u8_t byte) {
bool bAddByte = false;
bool bPacketComplete = false;
if (slip_read_flags == IP_SLIP_READ_COMPLETE) { // should call slip_can_receive() to check before calling slip_receive().
return;
}
if (slip_read_flags & IP_SLIP_READ_ERROR) {
if (byte == IP_SLIP_END) { // end of discarded packet; reset
slip_read_flags = 0;
buffer_in->clear ();
}
} else if (slip_read_flags & IP_SLIP_READ_ESCAPE) {
slip_read_flags = 0;
switch (byte) {
case IP_SLIP_END: // well, this is wrong; quietly discard packet
slip_read_flags = 0;
buffer_in->clear ();
break;
case IP_SLIP_ESC_END:
byte = IP_SLIP_END;
bAddByte = true;
break;
case IP_SLIP_ESC_ESC:
byte = IP_SLIP_ESC;
bAddByte = true;
break;
default: // set error flag
slip_read_flags = IP_SLIP_READ_ERROR;
break;
}
} else {
switch (byte) {
case IP_SLIP_END:
bPacketComplete = true;
break;
case IP_SLIP_ESC:
slip_read_flags = IP_SLIP_READ_ESCAPE;
break;
default:
bAddByte = true;
break;
}
}
if (bAddByte) {
if (buffer_in->available ()) {
buffer_in->append (&byte, 1);
} else {
slip_read_flags = IP_SLIP_READ_ERROR;
}
}
if (bPacketComplete) {
buffer_in->channel (channel_number); // note the buffer's originating channel
if (IP_Manager::manager().queue (buffer_in)) {
// DEBUG_PRINT (" ~ ");
slip_read_flags = 0;
buffer_in->clear ();
} else { // oops, need to hang onto the buffer
// DEBUG_PRINT (" !");
slip_read_flags = IP_SLIP_READ_COMPLETE;
}
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#include "pal_config.h"
#include "pal_errno.h"
#include "pal_networkchange.h"
#include "pal_types.h"
#include "pal_utilities.h"
#include <errno.h>
#include <linux/rtnetlink.h>
#include <net/if.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <unistd.h>
#pragma clang diagnostic ignored "-Wcast-align" // NLMSG_* macros trigger this
extern "C" Error SystemNative_CreateNetworkChangeListenerSocket(int32_t* retSocket)
{
sockaddr_nl sa = {};
sa.nl_family = AF_NETLINK;
sa.nl_groups = RTMGRP_LINK | RTMGRP_IPV4_IFADDR | RTMGRP_IPV4_ROUTE | RTMGRP_IPV6_ROUTE;
int32_t sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
if (sock == -1)
{
*retSocket = -1;
return static_cast<Error>(SystemNative_ConvertErrorPlatformToPal(errno));
}
if (bind(sock, reinterpret_cast<sockaddr*>(&sa), sizeof(sa)) != 0)
{
*retSocket = -1;
return static_cast<Error>(SystemNative_ConvertErrorPlatformToPal(errno));
}
*retSocket = sock;
return Error_SUCCESS;
}
extern "C" Error SystemNative_CloseNetworkChangeListenerSocket(int32_t socket)
{
int err = close(socket);
return err == 0 || CheckInterrupted(err) ? Error_SUCCESS : static_cast<Error>(SystemNative_ConvertErrorPlatformToPal(errno));
}
extern "C" void SystemNative_ReadEvents(int32_t sock, NetworkChangeEvent onNetworkChange)
{
char buffer[4096];
iovec iov = {buffer, sizeof(buffer)};
sockaddr_nl sanl;
msghdr msg = { .msg_name = reinterpret_cast<void*>(&sanl), .msg_namelen = sizeof(sockaddr_nl), .msg_iov = &iov, .msg_iovlen = 1 };
ssize_t len;
while (CheckInterrupted(len = recvmsg(sock, &msg, 0)));
if (len == -1)
{
// Probably means the socket has been closed.
return;
}
for (nlmsghdr* hdr = reinterpret_cast<nlmsghdr*>(buffer); NLMSG_OK(hdr, UnsignedCast(len)); NLMSG_NEXT(hdr, len))
{
switch (hdr->nlmsg_type)
{
case NLMSG_DONE:
return; // End of a multi-part message; stop reading.
case NLMSG_ERROR:
return;
case RTM_NEWADDR:
onNetworkChange(sock, NetworkChangeKind::AddressAdded);
break;
case RTM_DELADDR:
onNetworkChange(sock, NetworkChangeKind::AddressRemoved);
break;
case RTM_NEWLINK:
onNetworkChange(sock, ReadNewLinkMessage(hdr));
break;
case RTM_DELLINK:
onNetworkChange(sock, NetworkChangeKind::LinkRemoved);
break;
case RTM_NEWROUTE:
case RTM_DELROUTE:
{
rtmsg* dataAsRtMsg = reinterpret_cast<rtmsg*>(NLMSG_DATA(hdr));
if (dataAsRtMsg->rtm_table == RT_TABLE_MAIN)
{
onNetworkChange(sock, NetworkChangeKind::AvailabilityChanged);
return;
}
break;
}
default:
break;
}
}
}
NetworkChangeKind ReadNewLinkMessage(nlmsghdr* hdr)
{
assert(hdr != nullptr);
ifinfomsg* ifimsg;
ifimsg = reinterpret_cast<ifinfomsg*>(NLMSG_DATA(hdr));
if (ifimsg->ifi_family == AF_INET)
{
if ((ifimsg->ifi_flags & IFF_UP) != 0)
{
return NetworkChangeKind::LinkAdded;
}
}
return NetworkChangeKind::None;
}
|
// 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 "ppapi/tests/test_net_address.h"
#include <cstring>
#include "ppapi/cpp/net_address.h"
#include "ppapi/tests/test_utils.h"
#include "ppapi/tests/testing_instance.h"
using pp::NetAddress;
REGISTER_TEST_CASE(NetAddress);
namespace {
bool EqualIPv4Address(const PP_NetAddress_IPv4& addr1,
const PP_NetAddress_IPv4& addr2) {
return addr1.port == addr2.port &&
!memcmp(addr1.addr, addr2.addr, sizeof(addr1.addr));
}
bool EqualIPv6Address(const PP_NetAddress_IPv6& addr1,
const PP_NetAddress_IPv6& addr2) {
return addr1.port == addr2.port &&
!memcmp(addr1.addr, addr2.addr, sizeof(addr1.addr));
}
NetAddress CreateFromHostOrderIPv6Address(
const pp::InstanceHandle& instance,
const uint16_t host_order_addr[8],
uint16_t host_order_port) {
PP_NetAddress_IPv6 ipv6_addr;
ipv6_addr.port = ConvertToNetEndian16(host_order_port);
for (size_t i = 0; i < 8; ++i) {
uint16_t net_order_addr = ConvertToNetEndian16(host_order_addr[i]);
memcpy(&ipv6_addr.addr[2 * i], &net_order_addr, 2);
}
return NetAddress(instance, ipv6_addr);
}
} // namespace
TestNetAddress::TestNetAddress(TestingInstance* instance) : TestCase(instance) {
}
bool TestNetAddress::Init() {
return NetAddress::IsAvailable();
}
void TestNetAddress::RunTests(const std::string& filter) {
RUN_TEST(IPv4Address, filter);
RUN_TEST(IPv6Address, filter);
RUN_TEST(DescribeAsString, filter);
}
std::string TestNetAddress::TestIPv4Address() {
PP_NetAddress_IPv4 ipv4_addr = { ConvertToNetEndian16(80), { 127, 0, 0, 1 } };
NetAddress net_addr(instance_, ipv4_addr);
ASSERT_NE(0, net_addr.pp_resource());
ASSERT_EQ(PP_NETADDRESS_FAMILY_IPV4, net_addr.GetFamily());
PP_NetAddress_IPv4 out_ipv4_addr;
ASSERT_TRUE(net_addr.DescribeAsIPv4Address(&out_ipv4_addr));
ASSERT_TRUE(EqualIPv4Address(ipv4_addr, out_ipv4_addr));
PP_NetAddress_IPv6 out_ipv6_addr;
ASSERT_FALSE(net_addr.DescribeAsIPv6Address(&out_ipv6_addr));
PASS();
}
std::string TestNetAddress::TestIPv6Address() {
PP_NetAddress_IPv6 ipv6_addr = {
ConvertToNetEndian16(1024),
{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 }
};
NetAddress net_addr(instance_, ipv6_addr);
ASSERT_NE(0, net_addr.pp_resource());
ASSERT_EQ(PP_NETADDRESS_FAMILY_IPV6, net_addr.GetFamily());
PP_NetAddress_IPv6 out_ipv6_addr;
ASSERT_TRUE(net_addr.DescribeAsIPv6Address(&out_ipv6_addr));
ASSERT_TRUE(EqualIPv6Address(ipv6_addr, out_ipv6_addr));
PP_NetAddress_IPv4 out_ipv4_addr;
ASSERT_FALSE(net_addr.DescribeAsIPv4Address(&out_ipv4_addr));
PASS();
}
std::string TestNetAddress::TestDescribeAsString() {
{
// Test describing IPv4 addresses.
PP_NetAddress_IPv4 ipv4_addr1 = { ConvertToNetEndian16(1234),
{ 127, 0, 0, 1 } };
NetAddress addr1(instance_, ipv4_addr1);
ASSERT_EQ("127.0.0.1", addr1.DescribeAsString(false).AsString());
ASSERT_EQ("127.0.0.1:1234", addr1.DescribeAsString(true).AsString());
PP_NetAddress_IPv4 ipv4_addr2 = { ConvertToNetEndian16(80),
{ 192, 168, 0, 2 } };
NetAddress addr2(instance_, ipv4_addr2);
ASSERT_EQ("192.168.0.2", addr2.DescribeAsString(false).AsString());
ASSERT_EQ("192.168.0.2:80", addr2.DescribeAsString(true).AsString());
}
{
// Test describing IPv6 addresses.
static const struct {
uint16_t host_order_addr[8];
uint16_t host_order_port;
const char* expected_without_port;
const char* expected_with_port;
} ipv6_test_cases[] = {
{ // Generic test case (unique longest run of zeros to collapse).
{ 0x12, 0xabcd, 0, 0x0001, 0, 0, 0, 0xcdef }, 12,
"12:abcd:0:1::cdef", "[12:abcd:0:1::cdef]:12"
},
{ // Ignore the first (non-longest) run of zeros.
{ 0, 0, 0, 0x0123, 0, 0, 0, 0 }, 123,
"0:0:0:123::", "[0:0:0:123::]:123"
},
{ // Collapse the first (equally-longest) run of zeros.
{ 0x1234, 0xabcd, 0, 0, 0xff, 0, 0, 0xcdef }, 123,
"1234:abcd::ff:0:0:cdef", "[1234:abcd::ff:0:0:cdef]:123"
},
{ // Don't collapse "runs" of zeros of length 1.
{ 0, 0xa, 1, 2, 3, 0, 5, 0 }, 123,
"0:a:1:2:3:0:5:0", "[0:a:1:2:3:0:5:0]:123"
},
{ // Collapse a run of zeros at the beginning.
{ 0, 0, 0, 2, 3, 0, 0, 0 }, 123,
"::2:3:0:0:0", "[::2:3:0:0:0]:123"
},
{ // Collapse a run of zeros at the end.
{ 0, 0xa, 1, 2, 3, 0, 0, 0 }, 123,
"0:a:1:2:3::", "[0:a:1:2:3::]:123"
},
{ // IPv4 192.168.1.2 embedded in IPv6 in the deprecated way.
{ 0, 0, 0, 0, 0, 0, 0xc0a8, 0x102 }, 123,
"::192.168.1.2", "[::192.168.1.2]:123"
},
{ // IPv4 192.168.1.2 embedded in IPv6.
{ 0, 0, 0, 0, 0, 0xffff, 0xc0a8, 0x102 }, 123,
"::ffff:192.168.1.2", "[::ffff:192.168.1.2]:123"
},
{ // *Not* IPv4 embedded in IPv6.
{ 0, 0, 0, 0, 0, 0x1234, 0xc0a8, 0x102 }, 123,
"::1234:c0a8:102", "[::1234:c0a8:102]:123"
}
};
for (size_t i = 0;
i < sizeof(ipv6_test_cases) / sizeof(ipv6_test_cases[0]);
++i) {
NetAddress addr = CreateFromHostOrderIPv6Address(
instance_, ipv6_test_cases[i].host_order_addr,
ipv6_test_cases[i].host_order_port);
ASSERT_EQ(ipv6_test_cases[i].expected_without_port,
addr.DescribeAsString(false).AsString());
ASSERT_EQ(ipv6_test_cases[i].expected_with_port,
addr.DescribeAsString(true).AsString());
}
}
PASS();
}
|
#include "catch.hpp"
#include <inser.h>
SCENARIO("SORT_INSERT") {
int nums1[] = { 9,1,7,2,5,8,3,6,4 };
int nums_proverka1[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
inser(nums1, nums1+9);
for (int i = 0; i < 9; ++i) {
REQUIRE(nums1[i] == nums_proverka1[i]);
}
}
|
#pragma once
#include "coding/endianness.hpp"
#include "coding/files_container.hpp"
#include "coding/memory_region.hpp"
#include "coding/reader.hpp"
#include "coding/succinct_mapper.hpp"
#include "coding/varint.hpp"
#include "coding/write_to_sink.hpp"
#include "coding/writer.hpp"
#include "base/assert.hpp"
#include "base/checked_cast.hpp"
#include "base/logging.hpp"
#if defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-private-field"
#endif
#include "3party/succinct/elias_fano.hpp"
#include "3party/succinct/rs_bit_vector.hpp"
#if defined(__clang__)
#pragma clang diagnostic pop
#endif
#include <algorithm>
#include <cstdint>
#include <functional>
#include <memory>
#include <type_traits>
#include <unordered_map>
#include <vector>
// A data structure that allows storing a map from small 32-bit integers (the main use
// case is feature ids of a single mwm) to arbitrary values and accessing this map
// with a small RAM footprint.
//
// Format:
// File offset (bytes) Field name Field size (bytes)
// 0 version 2
// 2 endianness 2
// 4 positions offset 4
// 8 variables offset 4
// 12 end of section 4
// 16 identifiers table positions offset - 16
// positions offset positions table variables offset - positions offset
// variables offset variables blocks end of section - variables offset
//
// Version and endianness are always stored in the little-endian format.
// 0 value of endianness means little-endian, whereas 1 means big-endian.
//
// All offsets are in the little-endian format.
//
// Identifiers table is a bit-vector with rank-select table, where set
// bits denote that values for the corresponding features are in the
// table. Identifiers table is stored in the native endianness.
//
// Positions table is an Elias-Fano table where each entry corresponds
// to the start position of the variables block. Positions table is
// stored in the native endianness.
//
// Variables is a sequence of blocks, where each block (with the
// exception of the last one) is a sequence of kBlockSize variables
// encoded by block encoding callback.
//
// On Get call kBlockSize consecutive variables are decoded and cached in RAM. Get is not
// threadsafe.
//
// GetThreadsafe does not use cache.
template <typename Value>
class MapUint32ToValue
{
public:
using ReadBlockCallback =
std::function<void(NonOwningReaderSource &, uint32_t, std::vector<Value> &)>;
static uint32_t constexpr kBlockSize = 64;
struct Header
{
void Read(Reader & reader)
{
NonOwningReaderSource source(reader);
m_version = ReadPrimitiveFromSource<uint16_t>(source);
m_endianness = ReadPrimitiveFromSource<uint16_t>(source);
m_positionsOffset = ReadPrimitiveFromSource<uint32_t>(source);
m_variablesOffset = ReadPrimitiveFromSource<uint32_t>(source);
m_endOffset = ReadPrimitiveFromSource<uint32_t>(source);
}
void Write(Writer & writer)
{
WriteToSink(writer, m_version);
WriteToSink(writer, m_endianness);
WriteToSink(writer, m_positionsOffset);
WriteToSink(writer, m_variablesOffset);
WriteToSink(writer, m_endOffset);
}
bool IsValid() const
{
if (m_version != 0)
{
LOG(LERROR, ("Unknown version."));
return false;
}
if (m_endianness > 1)
{
LOG(LERROR, ("Wrong endianness value."));
return false;
}
if (m_positionsOffset < sizeof(m_header))
{
LOG(LERROR, ("Positions before header:", m_positionsOffset, sizeof(m_header)));
return false;
}
if (m_variablesOffset < m_positionsOffset)
{
LOG(LERROR, ("Deltas before positions:", m_variablesOffset, m_positionsOffset));
return false;
}
if (m_endOffset < m_variablesOffset)
{
LOG(LERROR, ("End of section before variables:", m_endOffset, m_variablesOffset));
return false;
}
return true;
}
uint16_t m_version = 0;
uint16_t m_endianness = 0;
uint32_t m_positionsOffset = 0;
uint32_t m_variablesOffset = 0;
uint32_t m_endOffset = 0;
};
static_assert(sizeof(Header) == 16, "Wrong header size");
MapUint32ToValue(Reader & reader, ReadBlockCallback const & readBlockCallback)
: m_reader(reader), m_readBlockCallback(readBlockCallback)
{
}
~MapUint32ToValue() = default;
// Tries to get |value| for key identified by |id|. Returns
// false if table does not have entry for this id.
WARN_UNUSED_RESULT bool Get(uint32_t id, Value & value)
{
if (id >= m_ids.size() || !m_ids[id])
return false;
uint32_t const rank = static_cast<uint32_t>(m_ids.rank(id));
uint32_t const base = rank / kBlockSize;
uint32_t const offset = rank % kBlockSize;
auto & entry = m_cache[base];
if (entry.empty())
entry = GetImpl(id);
value = entry[offset];
return true;
}
// Tries to get |value| for key identified by |id|. Returns
// false if table does not have entry for this id.
WARN_UNUSED_RESULT bool GetThreadsafe(uint32_t id, Value & value) const
{
if (id >= m_ids.size() || !m_ids[id])
return false;
uint32_t const rank = static_cast<uint32_t>(m_ids.rank(id));
uint32_t const offset = rank % kBlockSize;
auto const entry = GetImpl(id);
value = entry[offset];
return true;
}
// Loads MapUint32ToValue instance. Note that |reader| must be alive
// until the destruction of loaded table. Returns nullptr if
// MapUint32ToValue can't be loaded.
// It's guaranteed that |readBlockCallback| will not be called for empty block.
static std::unique_ptr<MapUint32ToValue> Load(Reader & reader,
ReadBlockCallback const & readBlockCallback)
{
uint16_t const version = ReadPrimitiveFromPos<uint16_t>(reader, 0 /* pos */);
if (version != 0)
return {};
// Only single version of centers table is supported now. If you need to implement new
// versions, implement dispatching based on first-four-bytes version.
auto table = std::make_unique<MapUint32ToValue>(reader, readBlockCallback);
if (!table->Init())
return {};
return table;
}
template <typename Fn>
void ForEach(Fn && fn)
{
for (uint64_t i = 0; i < m_ids.num_ones(); ++i)
{
auto const j = static_cast<uint32_t>(m_ids.select(i));
Value value;
bool const ok = Get(j, value);
CHECK(ok, ());
fn(j, value);
}
}
uint64_t Count() const { return m_ids.num_ones(); }
private:
std::vector<Value> GetImpl(uint32_t id) const
{
ASSERT_LESS(id, m_ids.size(), ());
ASSERT(m_ids[id], ());
uint32_t const rank = static_cast<uint32_t>(m_ids.rank(id));
uint32_t const base = rank / kBlockSize;
std::vector<Value> values(kBlockSize);
auto const start = m_offsets.select(base);
auto const end = base + 1 < m_offsets.num_ones()
? m_offsets.select(base + 1)
: m_header.m_endOffset - m_header.m_variablesOffset;
std::vector<uint8_t> data(static_cast<size_t>(end - start));
m_reader.Read(m_header.m_variablesOffset + start, data.data(), data.size());
MemReader mreader(data.data(), data.size());
NonOwningReaderSource msource(mreader);
m_readBlockCallback(msource, kBlockSize, values);
return values;
}
bool Init()
{
m_header.Read(m_reader);
if (!m_header.IsValid())
return false;
bool const isHostBigEndian = IsBigEndianMacroBased();
bool const isDataBigEndian = m_header.m_endianness == 1;
bool const endiannesMismatch = isHostBigEndian != isDataBigEndian;
{
uint32_t const idsSize = m_header.m_positionsOffset - sizeof(m_header);
std::vector<uint8_t> data(idsSize);
m_reader.Read(sizeof(m_header), data.data(), data.size());
m_idsRegion = std::make_unique<CopiedMemoryRegion>(move(data));
EndiannessAwareMap(endiannesMismatch, *m_idsRegion, m_ids);
}
{
uint32_t const offsetsSize = m_header.m_variablesOffset - m_header.m_positionsOffset;
std::vector<uint8_t> data(offsetsSize);
m_reader.Read(m_header.m_positionsOffset, data.data(), data.size());
m_offsetsRegion = std::make_unique<CopiedMemoryRegion>(move(data));
EndiannessAwareMap(endiannesMismatch, *m_offsetsRegion, m_offsets);
}
return true;
}
template <typename Cont>
void EndiannessAwareMap(bool endiannesMismatch, CopiedMemoryRegion & region, Cont & cont)
{
Cont c;
if (endiannesMismatch)
{
coding::ReverseMapVisitor visitor(region.MutableData());
c.map(visitor);
}
else
{
coding::MapVisitor visitor(region.ImmutableData());
c.map(visitor);
}
c.swap(cont);
}
Header m_header;
Reader & m_reader;
std::unique_ptr<CopiedMemoryRegion> m_idsRegion;
std::unique_ptr<CopiedMemoryRegion> m_offsetsRegion;
succinct::rs_bit_vector m_ids;
succinct::elias_fano m_offsets;
ReadBlockCallback m_readBlockCallback;
std::unordered_map<uint32_t, std::vector<Value>> m_cache;
};
template <typename Value>
class MapUint32ToValueBuilder
{
public:
using Iter = typename std::vector<Value>::const_iterator;
using WriteBlockCallback = std::function<void(Writer &, Iter, Iter)>;
using Map = MapUint32ToValue<Value>;
void Put(uint32_t id, Value value)
{
if (!m_ids.empty())
CHECK_LESS(m_ids.back(), id, ());
m_values.push_back(value);
m_ids.push_back(id);
}
// It's guaranteed that |writeBlockCallback| will not be called for empty block.
void Freeze(Writer & writer, WriteBlockCallback const & writeBlockCallback) const
{
typename Map::Header header;
auto const startOffset = writer.Pos();
header.Write(writer);
{
uint64_t const numBits = m_ids.empty() ? 0 : m_ids.back() + 1;
succinct::bit_vector_builder builder(numBits);
for (auto const & id : m_ids)
builder.set(id, true);
coding::FreezeVisitor<Writer> visitor(writer);
succinct::rs_bit_vector(&builder).map(visitor);
}
std::vector<uint32_t> offsets;
std::vector<uint8_t> variables;
{
MemWriter<std::vector<uint8_t>> writer(variables);
for (size_t i = 0; i < m_values.size(); i += Map::kBlockSize)
{
offsets.push_back(static_cast<uint32_t>(variables.size()));
auto const endOffset = std::min(i + Map::kBlockSize, m_values.size());
CHECK_GREATER(endOffset, i, ());
writeBlockCallback(writer, m_values.cbegin() + i, m_values.cbegin() + endOffset);
}
}
{
succinct::elias_fano::elias_fano_builder builder(offsets.empty() ? 0 : offsets.back() + 1,
offsets.size());
for (auto const & offset : offsets)
builder.push_back(offset);
header.m_positionsOffset = base::checked_cast<uint32_t>(writer.Pos() - startOffset);
coding::FreezeVisitor<Writer> visitor(writer);
succinct::elias_fano(&builder).map(visitor);
}
{
header.m_variablesOffset = base::checked_cast<uint32_t>(writer.Pos() - startOffset);
writer.Write(variables.data(), variables.size());
header.m_endOffset = base::checked_cast<uint32_t>(writer.Pos() - startOffset);
}
auto const endOffset = writer.Pos();
writer.Seek(startOffset);
CHECK_EQUAL(header.m_endianness, 0, ("|m_endianness| should be set to little-endian."));
header.Write(writer);
writer.Seek(endOffset);
}
private:
std::vector<Value> m_values;
std::vector<uint32_t> m_ids;
};
|
//
// Copyright (c) 2015-2018 CNRS
// Copyright (c) 2016 Wandercraft, 86 rue de Paris 91400 Orsay, France.
//
#ifndef __pinocchio_spatial_fwd_hpp__
#define __pinocchio_spatial_fwd_hpp__
#include "pinocchio/fwd.hpp"
#include "pinocchio/macros.hpp"
namespace pinocchio
{
template<typename Scalar, int Options=0> struct SE3Tpl;
template<typename Derived> class MotionBase;
template<typename Derived> class MotionDense;
template<typename Vector6ArgType> class MotionRef;
template<typename Scalar, int Options=0> class MotionTpl;
template<typename Scalar, int Options=0> struct BiasZeroTpl;
template<typename Derived> class ForceBase;
template<typename Derived> class ForceDense;
template<typename Vector6ArgType> class ForceRef;
template<typename Scalar, int Options=0> class ForceTpl;
template<typename Scalar, int Options=0> class InertiaTpl;
template<typename Scalar, int Options=0> class Symmetric3Tpl;
/**
* \addtogroup spatial
* @{
*/
typedef SE3Tpl <double,0> SE3;
typedef MotionTpl <double,0> Motion;
typedef ForceTpl <double,0> Force;
typedef InertiaTpl <double,0> Inertia;
typedef Symmetric3Tpl <double,0> Symmetric3;
typedef BiasZeroTpl <double,0> BiasZero;
/**
* @}
*/
// end of group spatial
#define SPATIAL_TYPEDEF_TEMPLATE_GENERIC(derived,TYPENAME) \
typedef TYPENAME traits<derived>::Scalar Scalar; \
typedef TYPENAME traits<derived>::Vector3 Vector3; \
typedef TYPENAME traits<derived>::Vector4 Vector4; \
typedef TYPENAME traits<derived>::Vector6 Vector6; \
typedef TYPENAME traits<derived>::Matrix3 Matrix3; \
typedef TYPENAME traits<derived>::Matrix4 Matrix4; \
typedef TYPENAME traits<derived>::Matrix6 Matrix6; \
typedef TYPENAME traits<derived>::Angular_t Angular_t; \
typedef TYPENAME traits<derived>::Linear_t Linear_t; \
typedef TYPENAME traits<derived>::ConstAngular_t ConstAngular_t; \
typedef TYPENAME traits<derived>::ConstLinear_t ConstLinear_t; \
typedef TYPENAME traits<derived>::ActionMatrix_t ActionMatrix_t; \
typedef TYPENAME traits<derived>::Quaternion_t Quaternion_t; \
typedef TYPENAME traits<derived>::SE3 SE3; \
typedef TYPENAME traits<derived>::Force Force; \
typedef TYPENAME traits<derived>::Motion Motion; \
typedef TYPENAME traits<derived>::Symmetric3 Symmetric3; \
enum { \
LINEAR = traits<derived>::LINEAR, \
ANGULAR = traits<derived>::ANGULAR \
}
#define SPATIAL_TYPEDEF_TEMPLATE(derived) \
SPATIAL_TYPEDEF_TEMPLATE_GENERIC(derived,typename)
#define SPATIAL_TYPEDEF_NO_TEMPLATE(derived) \
SPATIAL_TYPEDEF_TEMPLATE_GENERIC(derived,PINOCCHIO_MACRO_EMPTY_ARG)
} // namespace pinocchio
#endif // ifndef __pinocchio_spatial_fwd_hpp__
|
/**
* Copyright 2019-2020 Huawei Technologies Co., Ltd
*
* 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 "src/ops/space_to_depth.h"
#include <limits>
#include "src/common/common.h"
#ifndef PRIMITIVE_WRITEABLE
#include "src/ops/ops_register.h"
#endif
namespace mindspore {
namespace lite {
#ifdef PRIMITIVE_WRITEABLE
int SpaceToDepth::GetBlockSize() const { return this->primitive_->value.AsSpaceToDepth()->blockSize; }
int SpaceToDepth::GetFormat() const { return this->primitive_->value.AsSpaceToDepth()->format; }
void SpaceToDepth::SetBlockSize(int block_size) { this->primitive_->value.AsSpaceToDepth()->blockSize = block_size; }
void SpaceToDepth::SetFormat(int format) { this->primitive_->value.AsSpaceToDepth()->format = (schema::Format)format; }
#else
int SpaceToDepth::GetBlockSize() const { return this->primitive_->value_as_SpaceToDepth()->blockSize(); }
int SpaceToDepth::GetFormat() const { return this->primitive_->value_as_SpaceToDepth()->format(); }
int SpaceToDepth::UnPackToFlatBuilder(const schema::Primitive *primitive, flatbuffers::FlatBufferBuilder *fbb) {
MS_ASSERT(nullptr != primitive);
MS_ASSERT(nullptr != fbb);
auto attr = primitive->value_as_SpaceToDepth();
if (attr == nullptr) {
MS_LOG(ERROR) << "value_as_SpaceToDepth return nullptr";
return RET_ERROR;
}
auto val_offset = schema::CreateSpaceToDepth(*fbb, attr->blockSize(), attr->format());
auto prim_offset = schema::CreatePrimitive(*fbb, schema::PrimitiveType_SpaceToDepth, val_offset.o);
fbb->Finish(prim_offset);
return RET_OK;
}
PrimitiveC *SpaceToDepthCreator(const schema::Primitive *primitive) {
return PrimitiveC::NewPrimitiveC<SpaceToDepth>(primitive);
}
Registry SpaceToDepthRegistry(schema::PrimitiveType_SpaceToDepth, SpaceToDepthCreator);
#endif
namespace {
constexpr int kSpaceToDepthOutputNum = 1;
constexpr int kSpaceToDepthInputNum = 1;
} // namespace
int SpaceToDepth::InferShape(std::vector<lite::Tensor *> inputs, std::vector<lite::Tensor *> outputs) {
MS_ASSERT(this->primitive_ != nullptr);
if (outputs.size() != kSpaceToDepthOutputNum || inputs.size() != kSpaceToDepthInputNum) {
MS_LOG(ERROR) << "Invalid output/input size! output size: " << outputs.size() << ",input size: " << inputs.size();
return RET_ERROR;
}
auto input = inputs.at(0);
if (input->format() != schema::Format::Format_NHWC) {
MS_LOG(ERROR) << "space_to_depth only support NHWC now!";
return RET_ERROR;
}
outputs.at(0)->set_format(input->format());
outputs.at(0)->set_data_type(input->data_type());
if (!infer_flag()) {
return RET_INFER_INVALID;
}
auto input_shape = input->shape();
if (input_shape.size() != kDimension_4d) {
MS_LOG(ERROR) << "input shape dimension size should == " << kDimension_4d;
return RET_ERROR;
}
int32_t block_size = GetBlockSize();
if (block_size == 0) {
MS_LOG(ERROR) << "block_size is zero";
return RET_ERROR;
}
if (input_shape.at(NHWC_H) % block_size != 0 || input_shape.at(NHWC_H) == 0 ||
input_shape.at(NHWC_W) % block_size != 0 || input_shape.at(NHWC_W) == 0) {
MS_LOG(ERROR) << "input dimension h or w size error!";
return RET_ERROR;
}
std::vector<int32_t> output_shape(input_shape.size());
output_shape.at(NHWC_N) = input_shape.at(NHWC_N);
output_shape.at(NHWC_H) = input_shape.at(NHWC_H) / block_size;
output_shape.at(NHWC_W) = input_shape.at(NHWC_W) / block_size;
if (block_size * block_size > std::numeric_limits<int32_t>::max() / input_shape.at(NHWC_C)) {
MS_LOG(ERROR) << "The value of block_size * block_size is too big";
return RET_ERROR;
}
output_shape.at(NHWC_C) = input_shape.at(NHWC_C) * (block_size * block_size);
outputs.at(0)->set_shape(output_shape);
return RET_OK;
}
} // namespace lite
} // namespace mindspore
|
/*
*
* Copyright 2018 Asylo 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.
*
*/
#include "asylo/identity/attestation/sgx/sgx_local_assertion_verifier.h"
#include <cstdint>
#include <string>
#include <vector>
#include "absl/synchronization/mutex.h"
#include "asylo/crypto/sha256_hash.h"
#include "asylo/crypto/util/bytes.h"
#include "asylo/crypto/util/trivial_object_util.h"
#include "asylo/identity/attestation/sgx/internal/local_assertion.pb.h"
#include "asylo/identity/attestation/sgx/sgx_local_assertion_authority_config.pb.h"
#include "asylo/identity/descriptions.h"
#include "asylo/identity/platform/sgx/internal/code_identity_constants.h"
#include "asylo/identity/platform/sgx/internal/identity_key_management_structs.h"
#include "asylo/identity/platform/sgx/internal/sgx_identity_util_internal.h"
#include "asylo/util/status_macros.h"
namespace asylo {
const char *const SgxLocalAssertionVerifier::authority_type_ =
sgx::kSgxLocalAssertionAuthority;
SgxLocalAssertionVerifier::SgxLocalAssertionVerifier() : initialized_(false) {}
Status SgxLocalAssertionVerifier::Initialize(const std::string &config) {
if (IsInitialized()) {
return Status(error::GoogleError::FAILED_PRECONDITION,
"Already initialized");
}
SgxLocalAssertionAuthorityConfig authority_config;
if (!authority_config.ParseFromString(config)) {
return Status(error::GoogleError::INVALID_ARGUMENT,
"Could not parse input config");
}
if (!authority_config.has_attestation_domain()) {
return Status(error::GoogleError::INVALID_ARGUMENT,
"Config is missing attestation domain");
}
attestation_domain_ = authority_config.attestation_domain();
absl::MutexLock lock(&initialized_mu_);
initialized_ = true;
return Status::OkStatus();
}
bool SgxLocalAssertionVerifier::IsInitialized() const {
absl::MutexLock lock(&initialized_mu_);
return initialized_;
}
EnclaveIdentityType SgxLocalAssertionVerifier::IdentityType() const {
return identity_type_;
}
std::string SgxLocalAssertionVerifier::AuthorityType() const {
return authority_type_;
}
Status SgxLocalAssertionVerifier::CreateAssertionRequest(
AssertionRequest *request) const {
if (!IsInitialized()) {
return Status(error::GoogleError::FAILED_PRECONDITION, "Not initialized");
}
request->mutable_description()->set_identity_type(IdentityType());
request->mutable_description()->set_authority_type(AuthorityType());
sgx::LocalAssertionRequestAdditionalInfo additional_info;
additional_info.set_local_attestation_domain(attestation_domain_);
// The request contains a dump of the raw TARGETINFO structure, which
// specifies the verifier as the target for the requested assertion. Note that
// since the layout and endianness of the TARGETINFO structure is defined by
// the Intel SGX architecture, it is safe to exchange the raw bytes of the
// structure. An SGX enclave that receives the request can reconstruct the
// original structure directly from the byte field in the AssertionRequest
// proto.
sgx::Targetinfo targetinfo;
sgx::SetTargetinfoFromSelfIdentity(&targetinfo);
additional_info.set_targetinfo(
ConvertTrivialObjectToBinaryString(targetinfo));
if (!additional_info.SerializeToString(
request->mutable_additional_information())) {
return Status(error::GoogleError::INTERNAL,
"Failed to serialize LocalAssertionRequestAdditionalInfo");
}
return Status::OkStatus();
}
StatusOr<bool> SgxLocalAssertionVerifier::CanVerify(
const AssertionOffer &offer) const {
if (!IsInitialized()) {
return Status(error::GoogleError::FAILED_PRECONDITION, "Not initialized");
}
if (!IsCompatibleAssertionDescription(offer.description())) {
return Status(error::GoogleError::INVALID_ARGUMENT,
"AssertionOffer has incompatible assertion description");
}
sgx::LocalAssertionOfferAdditionalInfo additional_info;
if (!additional_info.ParseFromString(offer.additional_information())) {
return Status(error::GoogleError::INTERNAL,
"Failed to parse offer additional information");
}
return additional_info.local_attestation_domain() == attestation_domain_;
}
Status SgxLocalAssertionVerifier::Verify(const std::string &user_data,
const Assertion &assertion,
EnclaveIdentity *peer_identity) const {
if (!IsInitialized()) {
return Status(error::GoogleError::FAILED_PRECONDITION, "Not initialized");
}
if (!IsCompatibleAssertionDescription(assertion.description())) {
return Status(error::GoogleError::INVALID_ARGUMENT,
"Assertion has incompatible assertion description");
}
sgx::LocalAssertion local_assertion;
if (!local_assertion.ParseFromString(assertion.assertion())) {
return Status(error::GoogleError::INTERNAL,
"Failed to parse LocalAssertion");
}
// First, verify the hardware REPORT embedded in the assertion. This will only
// succeed if the REPORT is targeted at this enclave. Note that since the
// layout and endianness of the REPORT structure is defined by the Intel SGX
// architecture, two SGX enclaves can exchange a REPORT by simply dumping the
// raw bytes of a REPORT structure into a proto. This code assumes that the
// assertion originates from a machine that supports the Intel SGX
// architecture and was copied into the assertion byte-for-byte, so is safe to
// restore the REPORT structure directly from the deserialized LocalAssertion.
sgx::Report report;
ASYLO_RETURN_IF_ERROR(SetTrivialObjectFromBinaryString<sgx::Report>(
local_assertion.report(), &report));
ASYLO_RETURN_IF_ERROR(sgx::VerifyHardwareReport(report));
// Next, verify that the REPORT is cryptographically-bound to the provided
// |user_data|. This is done by re-constructing the expected REPORTDATA (a
// SHA256 hash of |user_data| padded with zeros), and comparing it to the
// actual REPORTDATA inside the REPORT.
Sha256Hash hash;
hash.Update(user_data);
sgx::Reportdata expected_reportdata;
expected_reportdata.data =
TrivialZeroObject<UnsafeBytes<sgx::kReportdataSize>>();
std::vector<uint8_t> digest;
ASYLO_RETURN_IF_ERROR(hash.CumulativeHash(&digest));
expected_reportdata.data.replace(/*pos=*/0, digest);
if (expected_reportdata.data != report.body.reportdata.data) {
return Status(error::GoogleError::INTERNAL,
"Assertion is not bound to the provided user-data");
}
// Serialize the protobuf representation of the peer's SGX identity and save
// it in |peer_identity|.
SgxIdentity sgx_identity =
sgx::ParseSgxIdentityFromHardwareReport(report.body);
ASYLO_RETURN_IF_ERROR(sgx::SerializeSgxIdentity(sgx_identity, peer_identity));
return Status::OkStatus();
}
// Static registration of the LocalAssertionVerifier library.
SET_STATIC_MAP_VALUE_OF_DERIVED_TYPE(AssertionVerifierMap,
SgxLocalAssertionVerifier);
} // namespace asylo
|
#include "MethodArg.h"
MethodArg::MethodArg(const char* value, ArgType type)
: argValue(value), argType(type) {}
std::string MethodArg::GetValue() const {
return argValue;
}
ArgType MethodArg::GetType() const {
return argType;
}
|
#pragma once
#include "Base.hpp"
#include <iostream>
using namespace std;
class Derived:public Base{
// a will be public
// b will be protected
// c will not be accessible
private:
int double_value;
public:
Derived();
Derived(int x);
void access_base_members(){
a=100;
b=200;
// c=300; // c is not accessible
}
~Derived();
};
|
/*
* Copyright (c) 2011-2022, The DART development contributors
* All rights reserved.
*
* The list of contributors can be found at:
* https://github.com/dartsim/dart/blob/master/LICENSE
*
* This file is provided under the following "BSD-style" License:
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef DART_DYNAMICS_PYRAMIDSHAPE_HPP_
#define DART_DYNAMICS_PYRAMIDSHAPE_HPP_
#include "dart/dynamics/Shape.hpp"
namespace dart {
namespace dynamics {
/// PyramidShape represents a polyhedron formed by connecting a rectangular base
/// and a point (apex) where each base edge and apex form a triangle.
///
/// The origin of the reference frame is at the center of a rectangular that
/// intersect the pyramid and is parallel to the base. The line from the origin
/// to the apex is aligned with the Z-axis while the lateral and the
/// longitudinal lengths of the base are aligned with the X-axis and Y-axis,
/// respectively.
class PyramidShape : public Shape
{
public:
/// Constructor.
///
/// \param[in] baseWidth Lateral length (along X-axis) of the rectangular
/// base.
/// \param[in] baseDepth Longitudinal length (along Y-axis) of the rectangular
/// base.
/// \param[in] height Perpendicular height from the base to the apex.
PyramidShape(double baseWidth, double baseDepth, double height);
// Documentation inherited.
const std::string& getType() const override;
/// Returns shape type string for this shape.
static const std::string& getStaticType();
/// Returns the lateral length (algon X-axis) of the base.
double getBaseWidth() const;
/// Sets the lateral length (algon X-axis) of the base.
void setBaseWidth(double width);
/// Returns the longitudinal length (algon Y-axis) of the base.
double getBaseDepth() const;
/// Sets the longitudinal length (algon Y-axis) of the base.
void setBaseDepth(double depth);
/// Returns the perpendicular height from the base to the apex.
double getHeight() const;
/// Returns the Perpendicular height from the base to the apex.
void setHeight(double height);
/// Computes the volume given properties.
///
/// \param[in] baseWidth Lateral length (along X-axis) of the rectangular
/// base.
/// \param[in] baseDepth Longitudinal length (along Y-axis) of the rectangular
/// base.
/// \param[in] height Perpendicular height from the base to the apex.
static double computeVolume(
double baseWidth, double baseDepth, double height);
// Documentation inherited.
Eigen::Matrix3d computeInertia(double mass) const override;
// Documentation inherited.
ShapePtr clone() const override;
protected:
// Documentation inherited.
void updateBoundingBox() const override;
// Documentation inherited.
void updateVolume() const override;
private:
/// Lateral length (algon X-axis) of the base.
double mBaseWidth;
/// Longitudinal length (algon Y-axis) of the base.
double mBaseDepth;
/// Perpendicular height from the base to the apex.
double mHeight;
};
} // namespace dynamics
} // namespace dart
#endif // DART_DYNAMICS_PYRAMIDSHAPE_HPP_
|
#include "Effect.h"
Effect::Effect(){
}
void Effect::run(Adafruit_NeoPixel *strip, EffectData data){
}
void Effect::randomize(){
}
void Effect::off(Adafruit_NeoPixel *strip){
for(uint8_t i = 0; i < LED_COUNT; i++){
strip -> setPixelColor(i, 0);
}
}
// Input a value 0 to 255 to get a color value.
// The colors are a transition r - g - b - back to r.
uint32_t Color(uint8_t r, uint8_t g, uint8_t b) {
return ((uint32_t)r << 16) | ((uint32_t)g << 8) | b;
}
uint32_t Effect::wheel(uint8_t WheelPos, uint8_t brightness) {
uint16_t b = (uint16_t)brightness;
if(WheelPos < 85) {
return Color( WheelPos*3*b/255, (255 - WheelPos*3)*b/255, 0);
}
else if(WheelPos < 170) {
WheelPos -= 85;
return Color((255 - WheelPos*3)*b/255, 0, WheelPos*3*b/255);
}
else {
WheelPos -= 170;
return Color(0, WheelPos*3*b/255, (255 - WheelPos*3)*b/255);
}
}
|
/**
* Copyright (c) 2016-present, Facebook, Inc.
*
* 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 <caffe2/core/common_gpu.h>
#include <caffe2/core/context_gpu.h>
#include <caffe2/video/video_input_op.h>
namespace caffe2 {
REGISTER_CUDA_OPERATOR(VideoInput, VideoInputOp<CUDAContext>);
} // namespace caffe2
|
// Copyright (c) 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 "ash/common/wm/dock/docked_window_layout_manager.h"
#include "ash/aura/wm_window_aura.h"
#include "ash/common/ash_switches.h"
#include "ash/common/shelf/shelf_model.h"
#include "ash/common/shelf/shelf_types.h"
#include "ash/common/shell_window_ids.h"
#include "ash/common/wm/panels/panel_layout_manager.h"
#include "ash/common/wm/window_resizer.h"
#include "ash/common/wm/window_state.h"
#include "ash/display/display_manager.h"
#include "ash/root_window_controller.h"
#include "ash/shelf/shelf.h"
#include "ash/shelf/shelf_layout_manager.h"
#include "ash/shelf/shelf_widget.h"
#include "ash/shell.h"
#include "ash/test/ash_test_base.h"
#include "ash/test/display_manager_test_api.h"
#include "ash/test/shelf_test_api.h"
#include "ash/test/shelf_view_test_api.h"
#include "ash/test/shell_test_api.h"
#include "ash/test/test_shelf_delegate.h"
#include "ash/wm/window_state_aura.h"
#include "ash/wm/window_util.h"
#include "base/command_line.h"
#include "base/strings/string_number_conversions.h"
#include "ui/aura/client/aura_constants.h"
#include "ui/aura/test/test_window_delegate.h"
#include "ui/aura/window.h"
#include "ui/aura/window_event_dispatcher.h"
#include "ui/base/hit_test.h"
#include "ui/display/manager/display_layout.h"
#include "ui/display/screen.h"
#include "ui/views/widget/widget.h"
#include "ui/wm/core/coordinate_conversion.h"
namespace ash {
class DockedWindowLayoutManagerTest
: public test::AshTestBase,
public testing::WithParamInterface<ui::wm::WindowType> {
public:
DockedWindowLayoutManagerTest() : window_type_(GetParam()) {}
virtual ~DockedWindowLayoutManagerTest() {}
void SetUp() override {
AshTestBase::SetUp();
UpdateDisplay("600x600");
ASSERT_TRUE(test::TestShelfDelegate::instance());
shelf_view_test_.reset(new test::ShelfViewTestAPI(
test::ShelfTestAPI(Shelf::ForPrimaryDisplay()).shelf_view()));
shelf_view_test_->SetAnimationDuration(1);
}
protected:
enum DockedEdge {
DOCKED_EDGE_NONE,
DOCKED_EDGE_LEFT,
DOCKED_EDGE_RIGHT,
};
int min_dock_gap() const { return DockedWindowLayoutManager::kMinDockGap; }
int ideal_width() const { return DockedWindowLayoutManager::kIdealWidth; }
int docked_width(const DockedWindowLayoutManager* layout_manager) const {
return layout_manager->docked_width_;
}
aura::Window* CreateTestWindow(const gfx::Rect& bounds) {
aura::Window* window = CreateTestWindowInShellWithDelegateAndType(
nullptr, window_type_, 0, bounds);
if (window_type_ == ui::wm::WINDOW_TYPE_PANEL) {
test::TestShelfDelegate* shelf_delegate =
test::TestShelfDelegate::instance();
shelf_delegate->AddShelfItem(window);
PanelLayoutManager* manager =
PanelLayoutManager::Get(WmWindowAura::Get(window));
manager->Relayout();
}
return window;
}
aura::Window* CreateTestWindowWithDelegate(
const gfx::Rect& bounds,
aura::test::TestWindowDelegate* delegate) {
aura::Window* window = CreateTestWindowInShellWithDelegateAndType(
delegate, window_type_, 0, bounds);
if (window_type_ == ui::wm::WINDOW_TYPE_PANEL) {
test::TestShelfDelegate* shelf_delegate =
test::TestShelfDelegate::instance();
shelf_delegate->AddShelfItem(window);
PanelLayoutManager* manager =
PanelLayoutManager::Get(WmWindowAura::Get(window));
manager->Relayout();
}
return window;
}
static WindowResizer* CreateSomeWindowResizer(
aura::Window* window,
const gfx::Point& point_in_parent,
int window_component) {
return CreateWindowResizer(WmWindowAura::Get(window), point_in_parent,
window_component,
aura::client::WINDOW_MOVE_SOURCE_MOUSE)
.release();
}
void DragStart(aura::Window* window) {
DragStartAtOffsetFromwindowOrigin(window, 0, 0);
}
void DragStartAtOffsetFromwindowOrigin(aura::Window* window, int dx, int dy) {
initial_location_in_parent_ =
window->bounds().origin() + gfx::Vector2d(dx, dy);
resizer_.reset(CreateSomeWindowResizer(window, initial_location_in_parent_,
HTCAPTION));
ASSERT_TRUE(resizer_.get());
}
void DragMove(int dx, int dy) {
resizer_->Drag(initial_location_in_parent_ + gfx::Vector2d(dx, dy), 0);
}
void DragEnd() {
resizer_->CompleteDrag();
resizer_.reset();
}
void DragRevert() {
resizer_->RevertDrag();
resizer_.reset();
}
// Panels are parented by panel container during drags.
// Docked windows are parented by dock container during drags.
// All other windows that we are testing here have default container as a
// parent.
int CorrectContainerIdDuringDrag() {
if (window_type_ == ui::wm::WINDOW_TYPE_PANEL)
return kShellWindowId_PanelContainer;
return kShellWindowId_DockedContainer;
}
// Test dragging the window vertically (to detach if it is a panel) and then
// horizontally to the edge with an added offset from the edge of |dx|.
void DragRelativeToEdge(DockedEdge edge, aura::Window* window, int dx) {
DragVerticallyAndRelativeToEdge(
edge, window, dx,
window_type_ == ui::wm::WINDOW_TYPE_PANEL ? -100 : 20);
}
void DragToVerticalPositionAndToEdge(DockedEdge edge,
aura::Window* window,
int y) {
DragToVerticalPositionRelativeToEdge(edge, window, 0, y);
}
void DragToVerticalPositionRelativeToEdge(DockedEdge edge,
aura::Window* window,
int dx,
int y) {
gfx::Rect initial_bounds = window->GetBoundsInScreen();
DragVerticallyAndRelativeToEdge(edge, window, dx, y - initial_bounds.y());
}
// Detach if our window is a panel, then drag it vertically by |dy| and
// horizontally to the edge with an added offset from the edge of |dx|.
void DragVerticallyAndRelativeToEdge(DockedEdge edge,
aura::Window* window,
int dx,
int dy) {
gfx::Rect initial_bounds = window->GetBoundsInScreen();
// avoid snap by clicking away from the border
ASSERT_NO_FATAL_FAILURE(DragStartAtOffsetFromwindowOrigin(window, 25, 5));
gfx::Rect work_area = display::Screen::GetScreen()
->GetDisplayNearestWindow(window)
.work_area();
gfx::Point initial_location_in_screen = initial_location_in_parent_;
::wm::ConvertPointToScreen(window->parent(), &initial_location_in_screen);
// Drag the window left or right to the edge (or almost to it).
if (edge == DOCKED_EDGE_LEFT)
dx += work_area.x() - initial_location_in_screen.x();
else if (edge == DOCKED_EDGE_RIGHT)
dx += work_area.right() - 1 - initial_location_in_screen.x();
DragMove(dx, dy);
EXPECT_EQ(CorrectContainerIdDuringDrag(), window->parent()->id());
// Release the mouse and the panel should be attached to the dock.
DragEnd();
// x-coordinate can get adjusted by snapping or sticking.
// y-coordinate could be changed by possible automatic layout if docked.
if (window->parent()->id() != kShellWindowId_DockedContainer &&
!wm::GetWindowState(window)->HasRestoreBounds()) {
EXPECT_EQ(initial_bounds.y() + dy, window->GetBoundsInScreen().y());
}
}
private:
std::unique_ptr<WindowResizer> resizer_;
std::unique_ptr<test::ShelfViewTestAPI> shelf_view_test_;
ui::wm::WindowType window_type_;
// Location at start of the drag in |window->parent()|'s coordinates.
gfx::Point initial_location_in_parent_;
DISALLOW_COPY_AND_ASSIGN(DockedWindowLayoutManagerTest);
};
// Tests that a created window is successfully added to the dock
// layout manager.
TEST_P(DockedWindowLayoutManagerTest, AddOneWindow) {
if (!SupportsHostWindowResize())
return;
gfx::Rect bounds(0, 0, 201, 201);
std::unique_ptr<aura::Window> window(CreateTestWindow(bounds));
DragRelativeToEdge(DOCKED_EDGE_RIGHT, window.get(), 0);
// The window should be attached and docked at the right edge.
// Its width should shrink or grow to ideal width.
EXPECT_EQ(window->GetRootWindow()->bounds().right(),
window->GetBoundsInScreen().right());
EXPECT_EQ(ideal_width(), window->bounds().width());
EXPECT_EQ(kShellWindowId_DockedContainer, window->parent()->id());
}
// Tests that a docked window's bounds cannot be changed programmatically.
TEST_P(DockedWindowLayoutManagerTest, DockedWindowBoundsDontChange) {
if (!SupportsHostWindowResize())
return;
gfx::Rect bounds(0, 0, 201, 201);
std::unique_ptr<aura::Window> window(CreateTestWindow(bounds));
DragRelativeToEdge(DOCKED_EDGE_RIGHT, window.get(), 0);
// The window should be attached and docked at the right edge.
EXPECT_EQ(kShellWindowId_DockedContainer, window->parent()->id());
bounds = window->GetBoundsInScreen();
window->SetBounds(gfx::Rect(210, 210, 210, 210));
EXPECT_EQ(bounds.ToString(), window->GetBoundsInScreen().ToString());
}
// Tests that with a window docked on the left the auto-placing logic in
// RearrangeVisibleWindowOnShow places windows flush with work area edges.
TEST_P(DockedWindowLayoutManagerTest, AutoPlacingLeft) {
if (!SupportsHostWindowResize())
return;
gfx::Rect bounds(0, 0, 201, 201);
std::unique_ptr<aura::Window> window(CreateTestWindow(bounds));
DragRelativeToEdge(DOCKED_EDGE_LEFT, window.get(), 0);
// The window should be attached and snapped to the right side of the screen.
EXPECT_EQ(window->GetRootWindow()->bounds().x(),
window->GetBoundsInScreen().x());
EXPECT_EQ(kShellWindowId_DockedContainer, window->parent()->id());
DockedWindowLayoutManager* manager =
DockedWindowLayoutManager::Get(WmWindowAura::Get(window.get()));
// Create two additional windows and test their auto-placement
std::unique_ptr<aura::Window> window1(CreateTestWindowInShellWithId(1));
gfx::Rect desktop_area = window1->parent()->bounds();
wm::GetWindowState(window1.get())->set_window_position_managed(true);
window1->Hide();
window1->SetBounds(gfx::Rect(250, 32, 231, 320));
window1->Show();
// |window1| should be centered in work area.
EXPECT_EQ(base::IntToString(docked_width(manager) + min_dock_gap() +
(desktop_area.width() - docked_width(manager) -
min_dock_gap() - window1->bounds().width()) /
2) +
",32 231x320",
window1->bounds().ToString());
std::unique_ptr<aura::Window> window2(CreateTestWindowInShellWithId(2));
wm::GetWindowState(window2.get())->set_window_position_managed(true);
// To avoid any auto window manager changes due to SetBounds, the window
// gets first hidden and then shown again.
window2->Hide();
window2->SetBounds(gfx::Rect(250, 48, 150, 300));
window2->Show();
// |window1| should be flush left and |window2| flush right.
EXPECT_EQ(
base::IntToString(docked_width(manager) + min_dock_gap()) + ",32 231x320",
window1->bounds().ToString());
EXPECT_EQ(
base::IntToString(desktop_area.width() - window2->bounds().width()) +
",48 150x300",
window2->bounds().ToString());
}
// Tests that with a window docked on the right the auto-placing logic in
// RearrangeVisibleWindowOnShow places windows flush with work area edges.
TEST_P(DockedWindowLayoutManagerTest, AutoPlacingRight) {
if (!SupportsHostWindowResize())
return;
gfx::Rect bounds(0, 0, 201, 201);
std::unique_ptr<aura::Window> window(CreateTestWindow(bounds));
DragRelativeToEdge(DOCKED_EDGE_RIGHT, window.get(), 0);
// The window should be attached and snapped to the right side of the screen.
EXPECT_EQ(window->GetRootWindow()->bounds().right(),
window->GetBoundsInScreen().right());
EXPECT_EQ(kShellWindowId_DockedContainer, window->parent()->id());
DockedWindowLayoutManager* manager =
DockedWindowLayoutManager::Get(WmWindowAura::Get(window.get()));
// Create two additional windows and test their auto-placement
std::unique_ptr<aura::Window> window1(CreateTestWindowInShellWithId(1));
gfx::Rect desktop_area = window1->parent()->bounds();
wm::GetWindowState(window1.get())->set_window_position_managed(true);
window1->Hide();
window1->SetBounds(gfx::Rect(16, 32, 231, 320));
window1->Show();
// |window1| should be centered in work area.
EXPECT_EQ(base::IntToString((desktop_area.width() - docked_width(manager) -
min_dock_gap() - window1->bounds().width()) /
2) +
",32 231x320",
window1->bounds().ToString());
std::unique_ptr<aura::Window> window2(CreateTestWindowInShellWithId(2));
wm::GetWindowState(window2.get())->set_window_position_managed(true);
// To avoid any auto window manager changes due to SetBounds, the window
// gets first hidden and then shown again.
window2->Hide();
window2->SetBounds(gfx::Rect(32, 48, 256, 512));
window2->Show();
// |window1| should be flush left and |window2| flush right.
EXPECT_EQ("0,32 231x320", window1->bounds().ToString());
EXPECT_EQ(base::IntToString(desktop_area.width() - window2->bounds().width() -
docked_width(manager) - min_dock_gap()) +
",48 256x512",
window2->bounds().ToString());
}
// Tests that with a window docked on the right the auto-placing logic in
// RearrangeVisibleWindowOnShow places windows flush with work area edges.
// Test case for the secondary screen.
TEST_P(DockedWindowLayoutManagerTest, AutoPlacingRightSecondScreen) {
if (!SupportsMultipleDisplays() || !SupportsHostWindowResize())
return;
// Create a dual screen layout.
UpdateDisplay("600x600,600x600");
gfx::Rect bounds(600, 0, 201, 201);
std::unique_ptr<aura::Window> window(CreateTestWindow(bounds));
// Drag pointer to the right edge of the second screen.
DragRelativeToEdge(DOCKED_EDGE_RIGHT, window.get(), 0);
// The window should be attached and snapped to the right side of the screen.
EXPECT_EQ(window->GetRootWindow()->GetBoundsInScreen().right(),
window->GetBoundsInScreen().right());
EXPECT_EQ(kShellWindowId_DockedContainer, window->parent()->id());
DockedWindowLayoutManager* manager =
DockedWindowLayoutManager::Get(WmWindowAura::Get(window.get()));
// Create two additional windows and test their auto-placement
bounds = gfx::Rect(616, 32, 231, 320);
std::unique_ptr<aura::Window> window1(
CreateTestWindowInShellWithDelegate(nullptr, 1, bounds));
gfx::Rect desktop_area = window1->parent()->bounds();
wm::GetWindowState(window1.get())->set_window_position_managed(true);
window1->Hide();
window1->Show();
// |window1| should be centered in work area.
EXPECT_EQ(base::IntToString(600 +
(desktop_area.width() - docked_width(manager) -
min_dock_gap() - window1->bounds().width()) /
2) +
",32 231x320",
window1->GetBoundsInScreen().ToString());
bounds = gfx::Rect(632, 48, 256, 512);
std::unique_ptr<aura::Window> window2(
CreateTestWindowInShellWithDelegate(nullptr, 2, bounds));
wm::GetWindowState(window2.get())->set_window_position_managed(true);
// To avoid any auto window manager changes due to SetBounds, the window
// gets first hidden and then shown again.
window2->Hide();
window2->Show();
// |window1| should be flush left and |window2| flush right.
EXPECT_EQ("600,32 231x320", window1->GetBoundsInScreen().ToString());
EXPECT_EQ(
base::IntToString(600 + desktop_area.width() - window2->bounds().width() -
docked_width(manager) - min_dock_gap()) +
",48 256x512",
window2->GetBoundsInScreen().ToString());
}
// Adds two windows and tests that the gaps are evenly distributed.
TEST_P(DockedWindowLayoutManagerTest, AddTwoWindows) {
if (!SupportsHostWindowResize())
return;
std::unique_ptr<aura::Window> w1(CreateTestWindow(gfx::Rect(0, 0, 201, 201)));
std::unique_ptr<aura::Window> w2(CreateTestWindow(gfx::Rect(0, 0, 210, 202)));
DragToVerticalPositionAndToEdge(DOCKED_EDGE_RIGHT, w1.get(), 20);
DragToVerticalPositionAndToEdge(DOCKED_EDGE_RIGHT, w2.get(), 300);
// The windows should be attached and snapped to the right side of the screen.
EXPECT_EQ(w1->GetRootWindow()->bounds().right(),
w1->GetBoundsInScreen().right());
EXPECT_EQ(kShellWindowId_DockedContainer, w1->parent()->id());
EXPECT_EQ(w2->GetRootWindow()->bounds().right(),
w2->GetBoundsInScreen().right());
EXPECT_EQ(kShellWindowId_DockedContainer, w2->parent()->id());
// Test that the gaps differ at most by a single pixel.
gfx::Rect work_area = display::Screen::GetScreen()
->GetDisplayNearestWindow(w1.get())
.work_area();
int gap1 = w1->GetBoundsInScreen().y();
int gap2 = w2->GetBoundsInScreen().y() - w1->GetBoundsInScreen().bottom();
int gap3 = work_area.bottom() - w2->GetBoundsInScreen().bottom();
EXPECT_EQ(0, gap1);
EXPECT_NEAR(gap2, min_dock_gap(), 1);
EXPECT_EQ(0, gap3);
}
// Adds two non-overlapping windows and tests layout after a drag.
TEST_P(DockedWindowLayoutManagerTest, TwoWindowsDragging) {
if (!SupportsHostWindowResize())
return;
std::unique_ptr<aura::Window> w1(CreateTestWindow(gfx::Rect(0, 0, 201, 201)));
std::unique_ptr<aura::Window> w2(CreateTestWindow(gfx::Rect(0, 0, 210, 202)));
DragToVerticalPositionAndToEdge(DOCKED_EDGE_RIGHT, w1.get(), 20);
DragToVerticalPositionAndToEdge(DOCKED_EDGE_RIGHT, w2.get(), 300);
// The windows should be attached and snapped to the right side of the screen.
EXPECT_EQ(w1->GetRootWindow()->bounds().right(),
w1->GetBoundsInScreen().right());
EXPECT_EQ(kShellWindowId_DockedContainer, w1->parent()->id());
EXPECT_EQ(w2->GetRootWindow()->bounds().right(),
w2->GetBoundsInScreen().right());
EXPECT_EQ(kShellWindowId_DockedContainer, w2->parent()->id());
// Drag w2 above w1.
ASSERT_NO_FATAL_FAILURE(DragStartAtOffsetFromwindowOrigin(w2.get(), 0, 20));
DragMove(0, -w2->bounds().height() / 2 - min_dock_gap() - 1);
DragEnd();
// Test the new windows order and that the gaps differ at most by a pixel.
gfx::Rect work_area = display::Screen::GetScreen()
->GetDisplayNearestWindow(w1.get())
.work_area();
int gap1 = w2->GetBoundsInScreen().y() - work_area.y();
int gap2 = w1->GetBoundsInScreen().y() - w2->GetBoundsInScreen().bottom();
int gap3 = work_area.bottom() - w1->GetBoundsInScreen().bottom();
EXPECT_EQ(0, gap1);
EXPECT_NEAR(gap2, min_dock_gap(), 1);
EXPECT_EQ(0, gap3);
}
// Adds three overlapping windows and tests layout after a drag.
TEST_P(DockedWindowLayoutManagerTest, ThreeWindowsDragging) {
if (!SupportsHostWindowResize())
return;
UpdateDisplay("600x1000");
std::unique_ptr<aura::Window> w1(CreateTestWindow(gfx::Rect(0, 0, 201, 310)));
DragToVerticalPositionAndToEdge(DOCKED_EDGE_RIGHT, w1.get(), 20);
std::unique_ptr<aura::Window> w2(CreateTestWindow(gfx::Rect(0, 0, 210, 310)));
DragToVerticalPositionAndToEdge(DOCKED_EDGE_RIGHT, w2.get(), 500);
std::unique_ptr<aura::Window> w3(CreateTestWindow(gfx::Rect(0, 0, 220, 310)));
DragToVerticalPositionAndToEdge(DOCKED_EDGE_RIGHT, w3.get(), 600);
// All windows should be attached and snapped to the right side of the screen.
EXPECT_EQ(w1->GetRootWindow()->bounds().right(),
w1->GetBoundsInScreen().right());
EXPECT_EQ(kShellWindowId_DockedContainer, w1->parent()->id());
EXPECT_EQ(w2->GetRootWindow()->bounds().right(),
w2->GetBoundsInScreen().right());
EXPECT_EQ(kShellWindowId_DockedContainer, w2->parent()->id());
EXPECT_EQ(w3->GetRootWindow()->bounds().right(),
w3->GetBoundsInScreen().right());
EXPECT_EQ(kShellWindowId_DockedContainer, w3->parent()->id());
// Test that the top and bottom windows are clamped in work area and
// that the gaps between the windows differ at most by a pixel.
gfx::Rect work_area = display::Screen::GetScreen()
->GetDisplayNearestWindow(w1.get())
.work_area();
int gap1 = w1->GetBoundsInScreen().y() - work_area.y();
int gap2 = w2->GetBoundsInScreen().y() - w1->GetBoundsInScreen().bottom();
int gap3 = w3->GetBoundsInScreen().y() - w2->GetBoundsInScreen().bottom();
int gap4 = work_area.bottom() - w3->GetBoundsInScreen().bottom();
EXPECT_EQ(0, gap1);
EXPECT_NEAR(gap2, min_dock_gap(), 1);
EXPECT_NEAR(gap3, min_dock_gap(), 1);
EXPECT_EQ(0, gap4);
// Drag w1 below the point where w1 and w2 would swap places. This point is
// half way between the tops of those two windows.
// A bit more vertical drag is needed to account for a window bounds changing
// to its restore bounds during the drag.
ASSERT_NO_FATAL_FAILURE(DragStartAtOffsetFromwindowOrigin(w1.get(), 0, 20));
DragMove(0, min_dock_gap() + w2->bounds().height() / 2 + 10);
// During the drag the windows get rearranged and the top and the bottom
// should be limited by the work area.
EXPECT_EQ(work_area.y(), w2->GetBoundsInScreen().y());
EXPECT_GT(w1->GetBoundsInScreen().y(), w2->GetBoundsInScreen().y());
EXPECT_EQ(work_area.bottom(), w3->GetBoundsInScreen().bottom());
DragEnd();
// Test the new windows order and that the gaps differ at most by a pixel.
gap1 = w2->GetBoundsInScreen().y() - work_area.y();
gap2 = w1->GetBoundsInScreen().y() - w2->GetBoundsInScreen().bottom();
gap3 = w3->GetBoundsInScreen().y() - w1->GetBoundsInScreen().bottom();
gap4 = work_area.bottom() - w3->GetBoundsInScreen().bottom();
EXPECT_EQ(0, gap1);
EXPECT_NEAR(gap2, min_dock_gap(), 1);
EXPECT_NEAR(gap3, min_dock_gap(), 1);
EXPECT_EQ(0, gap4);
}
// Adds three windows in bottom display and tests layout after a drag.
TEST_P(DockedWindowLayoutManagerTest, ThreeWindowsDraggingSecondScreen) {
if (!SupportsMultipleDisplays() || !SupportsHostWindowResize())
return;
// Create two screen vertical layout.
UpdateDisplay("600x1000,600x1000");
// Layout the secondary display to the bottom of the primary.
ASSERT_GT(display::Screen::GetScreen()->GetNumDisplays(), 1);
Shell::GetInstance()->display_manager()->SetLayoutForCurrentDisplays(
test::CreateDisplayLayout(display::DisplayPlacement::BOTTOM, 0));
std::unique_ptr<aura::Window> w1(
CreateTestWindow(gfx::Rect(0, 1000, 201, 310)));
DragToVerticalPositionAndToEdge(DOCKED_EDGE_RIGHT, w1.get(), 1000 + 20);
std::unique_ptr<aura::Window> w2(
CreateTestWindow(gfx::Rect(0, 1000, 210, 310)));
DragToVerticalPositionAndToEdge(DOCKED_EDGE_RIGHT, w2.get(), 1000 + 500);
std::unique_ptr<aura::Window> w3(
CreateTestWindow(gfx::Rect(0, 1000, 220, 310)));
DragToVerticalPositionAndToEdge(DOCKED_EDGE_RIGHT, w3.get(), 1000 + 600);
// All windows should be attached and snapped to the right side of the screen.
EXPECT_EQ(w1->GetRootWindow()->bounds().right(),
w1->GetBoundsInScreen().right());
EXPECT_EQ(kShellWindowId_DockedContainer, w1->parent()->id());
EXPECT_EQ(w2->GetRootWindow()->bounds().right(),
w2->GetBoundsInScreen().right());
EXPECT_EQ(kShellWindowId_DockedContainer, w2->parent()->id());
EXPECT_EQ(w3->GetRootWindow()->bounds().right(),
w3->GetBoundsInScreen().right());
EXPECT_EQ(kShellWindowId_DockedContainer, w3->parent()->id());
gfx::Rect work_area = display::Screen::GetScreen()
->GetDisplayNearestWindow(w1.get())
.work_area();
// Test that the top and bottom windows are clamped in work area and
// that the overlaps between the windows differ at most by a pixel.
int gap1 = w1->GetBoundsInScreen().y() - work_area.y();
int gap2 = w2->GetBoundsInScreen().y() - w1->GetBoundsInScreen().bottom();
int gap3 = w3->GetBoundsInScreen().y() - w2->GetBoundsInScreen().bottom();
int gap4 = work_area.bottom() - w3->GetBoundsInScreen().bottom();
EXPECT_EQ(0, gap1);
EXPECT_NEAR(gap2, min_dock_gap(), 1);
EXPECT_NEAR(gap3, min_dock_gap(), 1);
EXPECT_EQ(0, gap4);
// Drag w1 below the point where w1 and w2 would swap places. This point is
// half way between the tops of those two windows.
// A bit more vertical drag is needed to account for a window bounds changing
// to its restore bounds during the drag.
ASSERT_NO_FATAL_FAILURE(DragStartAtOffsetFromwindowOrigin(w1.get(), 0, 20));
DragMove(0, min_dock_gap() + w2->bounds().height() / 2 + 10);
// During the drag the windows get rearranged and the top and the bottom
// should be limited by the work area.
EXPECT_EQ(work_area.y(), w2->GetBoundsInScreen().y());
EXPECT_GT(w1->GetBoundsInScreen().y(), w2->GetBoundsInScreen().y());
EXPECT_EQ(work_area.bottom(), w3->GetBoundsInScreen().bottom());
DragEnd();
// Test the new windows order and that the overlaps differ at most by a pixel.
gap1 = w2->GetBoundsInScreen().y() - work_area.y();
gap2 = w1->GetBoundsInScreen().y() - w2->GetBoundsInScreen().bottom();
gap3 = w3->GetBoundsInScreen().y() - w1->GetBoundsInScreen().bottom();
gap4 = work_area.bottom() - w3->GetBoundsInScreen().bottom();
EXPECT_EQ(0, gap1);
EXPECT_NEAR(gap2, min_dock_gap(), 1);
EXPECT_NEAR(gap3, min_dock_gap(), 1);
EXPECT_EQ(0, gap4);
}
// Tests that a second window added to the dock is resized to match.
TEST_P(DockedWindowLayoutManagerTest, TwoWindowsWidthNew) {
if (!SupportsHostWindowResize())
return;
std::unique_ptr<aura::Window> w1(CreateTestWindow(gfx::Rect(0, 0, 201, 201)));
std::unique_ptr<aura::Window> w2(CreateTestWindow(gfx::Rect(0, 0, 280, 202)));
DragToVerticalPositionAndToEdge(DOCKED_EDGE_RIGHT, w1.get(), 20);
// The first window should get resized to ideal width.
EXPECT_EQ(ideal_width(), w1->bounds().width());
DragToVerticalPositionAndToEdge(DOCKED_EDGE_RIGHT, w2.get(), 300);
// The second window should get resized to the existing dock.
EXPECT_EQ(ideal_width(), w2->bounds().width());
}
// Tests that a first non-resizable window added to the dock is not resized.
TEST_P(DockedWindowLayoutManagerTest, TwoWindowsWidthNonResizableFirst) {
if (!SupportsHostWindowResize())
return;
std::unique_ptr<aura::Window> w1(CreateTestWindow(gfx::Rect(0, 0, 201, 201)));
w1->SetProperty(aura::client::kCanResizeKey, false);
std::unique_ptr<aura::Window> w2(CreateTestWindow(gfx::Rect(0, 0, 280, 202)));
DragToVerticalPositionAndToEdge(DOCKED_EDGE_RIGHT, w1.get(), 20);
// The first window should not get resized.
EXPECT_EQ(201, w1->bounds().width());
DragToVerticalPositionAndToEdge(DOCKED_EDGE_RIGHT, w2.get(), 300);
// The second window should get resized to the first window's width.
EXPECT_EQ(w1->bounds().width(), w2->bounds().width());
}
// Tests that a second non-resizable window added to the dock is not resized.
TEST_P(DockedWindowLayoutManagerTest, TwoWindowsWidthNonResizableSecond) {
if (!SupportsHostWindowResize())
return;
std::unique_ptr<aura::Window> w1(CreateTestWindow(gfx::Rect(0, 0, 201, 201)));
std::unique_ptr<aura::Window> w2(CreateTestWindow(gfx::Rect(0, 0, 280, 202)));
w2->SetProperty(aura::client::kCanResizeKey, false);
DragToVerticalPositionAndToEdge(DOCKED_EDGE_RIGHT, w1.get(), 20);
// The first window should get resized to ideal width.
EXPECT_EQ(ideal_width(), w1->bounds().width());
DragToVerticalPositionAndToEdge(DOCKED_EDGE_RIGHT, w2.get(), 300);
// The second window should not get resized.
EXPECT_EQ(280, w2->bounds().width());
// The first window should get resized again - to match the second window.
EXPECT_EQ(w1->bounds().width(), w2->bounds().width());
}
// Test that restrictions on minimum and maximum width of windows are honored.
TEST_P(DockedWindowLayoutManagerTest, TwoWindowsWidthRestrictions) {
if (!SupportsHostWindowResize())
return;
aura::test::TestWindowDelegate delegate1;
delegate1.set_maximum_size(gfx::Size(240, 0));
std::unique_ptr<aura::Window> w1(
CreateTestWindowWithDelegate(gfx::Rect(0, 0, 201, 201), &delegate1));
aura::test::TestWindowDelegate delegate2;
delegate2.set_minimum_size(gfx::Size(260, 0));
std::unique_ptr<aura::Window> w2(
CreateTestWindowWithDelegate(gfx::Rect(0, 0, 280, 202), &delegate2));
DragToVerticalPositionAndToEdge(DOCKED_EDGE_RIGHT, w1.get(), 20);
// The first window should get resized to its maximum width.
EXPECT_EQ(240, w1->bounds().width());
DragToVerticalPositionAndToEdge(DOCKED_EDGE_RIGHT, w2.get(), 300);
// The second window should get resized to its minimum width.
EXPECT_EQ(260, w2->bounds().width());
// The first window should be centered relative to the second.
EXPECT_EQ(w1->bounds().CenterPoint().x(), w2->bounds().CenterPoint().x());
}
// Test that restrictions on minimum width of windows are honored.
TEST_P(DockedWindowLayoutManagerTest, WidthMoreThanMax) {
if (!SupportsHostWindowResize())
return;
aura::test::TestWindowDelegate delegate;
delegate.set_minimum_size(gfx::Size(400, 0));
std::unique_ptr<aura::Window> window(
CreateTestWindowWithDelegate(gfx::Rect(0, 0, 400, 201), &delegate));
DragToVerticalPositionAndToEdge(DOCKED_EDGE_RIGHT, window.get(), 20);
// Secondary drag ensures that we are testing the minimum size restriction
// and not just failure to get past the tiling step in SnapSizer.
ASSERT_NO_FATAL_FAILURE(
DragStartAtOffsetFromwindowOrigin(window.get(), 25, 5));
DragMove(150, 0);
DragEnd();
// The window should not get docked even though it is dragged past the edge.
EXPECT_NE(window->GetRootWindow()->bounds().right(),
window->GetBoundsInScreen().right());
EXPECT_NE(kShellWindowId_DockedContainer, window->parent()->id());
}
// Docks three windows and tests that the very first window gets minimized.
TEST_P(DockedWindowLayoutManagerTest, ThreeWindowsMinimize) {
if (!SupportsHostWindowResize())
return;
std::unique_ptr<aura::Window> w1(CreateTestWindow(gfx::Rect(0, 0, 201, 201)));
DragToVerticalPositionAndToEdge(DOCKED_EDGE_RIGHT, w1.get(), 20);
std::unique_ptr<aura::Window> w2(CreateTestWindow(gfx::Rect(0, 0, 210, 202)));
DragToVerticalPositionAndToEdge(DOCKED_EDGE_RIGHT, w2.get(), 200);
std::unique_ptr<aura::Window> w3(CreateTestWindow(gfx::Rect(0, 0, 220, 204)));
DragToVerticalPositionAndToEdge(DOCKED_EDGE_RIGHT, w3.get(), 300);
// The last two windows should be attached and snapped to the right edge.
EXPECT_EQ(w2->GetRootWindow()->bounds().right(),
w2->GetBoundsInScreen().right());
EXPECT_EQ(kShellWindowId_DockedContainer, w2->parent()->id());
EXPECT_EQ(w3->GetRootWindow()->bounds().right(),
w3->GetBoundsInScreen().right());
EXPECT_EQ(kShellWindowId_DockedContainer, w3->parent()->id());
// The first window should get hidden but parented by the dock container.
EXPECT_TRUE(wm::GetWindowState(w1.get())->IsMinimized());
EXPECT_TRUE(wm::GetWindowState(w1.get())->IsDocked());
EXPECT_FALSE(w1->IsVisible());
EXPECT_EQ(ui::SHOW_STATE_MINIMIZED,
w1->GetProperty(aura::client::kShowStateKey));
EXPECT_EQ(ui::SHOW_STATE_DOCKED,
w1->GetProperty(aura::client::kRestoreShowStateKey));
// The other two windows should be still docked.
EXPECT_FALSE(wm::GetWindowState(w2.get())->IsMinimized());
EXPECT_TRUE(wm::GetWindowState(w2.get())->IsDocked());
EXPECT_FALSE(wm::GetWindowState(w3.get())->IsMinimized());
EXPECT_TRUE(wm::GetWindowState(w3.get())->IsDocked());
EXPECT_EQ(kShellWindowId_DockedContainer, w1->parent()->id());
}
// Docks up to three windows and tests that they split vertical space.
TEST_P(DockedWindowLayoutManagerTest, ThreeWindowsSplitHeightEvenly) {
if (!SupportsHostWindowResize())
return;
UpdateDisplay("600x1000");
std::unique_ptr<aura::Window> w1(CreateTestWindow(gfx::Rect(0, 0, 201, 201)));
DragToVerticalPositionAndToEdge(DOCKED_EDGE_RIGHT, w1.get(), 20);
std::unique_ptr<aura::Window> w2(CreateTestWindow(gfx::Rect(0, 0, 210, 202)));
DragToVerticalPositionAndToEdge(DOCKED_EDGE_RIGHT, w2.get(), 200);
// The two windows should be attached and snapped to the right edge.
EXPECT_EQ(w1->GetRootWindow()->bounds().right(),
w1->GetBoundsInScreen().right());
EXPECT_EQ(kShellWindowId_DockedContainer, w1->parent()->id());
EXPECT_EQ(w2->GetRootWindow()->bounds().right(),
w2->GetBoundsInScreen().right());
EXPECT_EQ(kShellWindowId_DockedContainer, w2->parent()->id());
// The two windows should be same size vertically and almost 1/2 of work area.
gfx::Rect work_area = display::Screen::GetScreen()
->GetDisplayNearestWindow(w1.get())
.work_area();
EXPECT_NEAR(w1->GetBoundsInScreen().height(),
w2->GetBoundsInScreen().height(), 1);
EXPECT_NEAR(work_area.height() / 2, w1->GetBoundsInScreen().height(),
min_dock_gap() * 2);
// Create and dock the third window.
std::unique_ptr<aura::Window> w3(CreateTestWindow(gfx::Rect(0, 0, 220, 204)));
DragToVerticalPositionAndToEdge(DOCKED_EDGE_RIGHT, w3.get(), 300);
// All three windows should be docked and snapped to the right edge.
EXPECT_EQ(kShellWindowId_DockedContainer, w1->parent()->id());
EXPECT_EQ(kShellWindowId_DockedContainer, w2->parent()->id());
EXPECT_EQ(kShellWindowId_DockedContainer, w3->parent()->id());
// All windows should be near same size vertically and about 1/3 of work area.
EXPECT_NEAR(w1->GetBoundsInScreen().height(),
w2->GetBoundsInScreen().height(), 1);
EXPECT_NEAR(w2->GetBoundsInScreen().height(),
w3->GetBoundsInScreen().height(), 1);
EXPECT_NEAR(work_area.height() / 3, w1->GetBoundsInScreen().height(),
min_dock_gap() * 2);
}
// Docks two windows and tests that restrictions on vertical size are honored.
TEST_P(DockedWindowLayoutManagerTest, TwoWindowsHeightRestrictions) {
if (!SupportsHostWindowResize())
return;
// The first window is fixed height.
aura::test::TestWindowDelegate delegate1;
delegate1.set_minimum_size(gfx::Size(0, 300));
delegate1.set_maximum_size(gfx::Size(0, 300));
std::unique_ptr<aura::Window> w1(
CreateTestWindowWithDelegate(gfx::Rect(0, 0, 201, 300), &delegate1));
// The second window has maximum height.
aura::test::TestWindowDelegate delegate2;
delegate2.set_maximum_size(gfx::Size(0, 100));
std::unique_ptr<aura::Window> w2(
CreateTestWindowWithDelegate(gfx::Rect(0, 0, 280, 90), &delegate2));
DragToVerticalPositionAndToEdge(DOCKED_EDGE_RIGHT, w1.get(), 20);
DragToVerticalPositionAndToEdge(DOCKED_EDGE_RIGHT, w2.get(), 200);
// The two windows should be attached and snapped to the right edge.
EXPECT_EQ(w1->GetRootWindow()->bounds().right(),
w1->GetBoundsInScreen().right());
EXPECT_EQ(kShellWindowId_DockedContainer, w1->parent()->id());
EXPECT_EQ(w2->GetRootWindow()->bounds().right(),
w2->GetBoundsInScreen().right());
EXPECT_EQ(kShellWindowId_DockedContainer, w2->parent()->id());
// The two windows should have their heights restricted.
EXPECT_EQ(300, w1->GetBoundsInScreen().height());
EXPECT_EQ(100, w2->GetBoundsInScreen().height());
// w1 should be more than half of the work area height (even with a margin).
// w2 should be less than half of the work area height (even with a margin).
gfx::Rect work_area = display::Screen::GetScreen()
->GetDisplayNearestWindow(w1.get())
.work_area();
EXPECT_GT(w1->GetBoundsInScreen().height(), work_area.height() / 2 + 10);
EXPECT_LT(w2->GetBoundsInScreen().height(), work_area.height() / 2 - 10);
}
// Tests that a docked window is moved to primary display when secondary display
// is disconnected and that it stays docked and properly positioned.
TEST_P(DockedWindowLayoutManagerTest, DisplayDisconnectionMovesDocked) {
if (!SupportsMultipleDisplays() || !SupportsHostWindowResize())
return;
// Create a dual screen layout.
UpdateDisplay("600x700,800x600");
gfx::Rect bounds(600, 0, 201, 201);
std::unique_ptr<aura::Window> window(CreateTestWindow(bounds));
// Drag pointer to the right edge of the second screen.
DragRelativeToEdge(DOCKED_EDGE_RIGHT, window.get(), 0);
// Simulate disconnection of the secondary display.
UpdateDisplay("600x700");
// The window should be still docked at the right edge.
// Its height should grow to match the new work area.
EXPECT_EQ(window->GetRootWindow()->bounds().right(),
window->GetBoundsInScreen().right());
EXPECT_EQ(kShellWindowId_DockedContainer, window->parent()->id());
EXPECT_EQ(ideal_width(), window->bounds().width());
gfx::Rect work_area = display::Screen::GetScreen()
->GetDisplayNearestWindow(window.get())
.work_area();
EXPECT_EQ(work_area.height(), window->GetBoundsInScreen().height());
}
// Tests run twice - on both panels and normal windows
INSTANTIATE_TEST_CASE_P(NormalOrPanel,
DockedWindowLayoutManagerTest,
testing::Values(ui::wm::WINDOW_TYPE_NORMAL,
ui::wm::WINDOW_TYPE_PANEL));
} // namespace ash
|
//===- AArch64RegisterInfo.cpp - AArch64 Register Information -------------===//
//
// Part of the LLVM Project, 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
//
//===----------------------------------------------------------------------===//
//
// This file contains the AArch64 implementation of the TargetRegisterInfo
// class.
//
//===----------------------------------------------------------------------===//
#include "AArch64RegisterInfo.h"
#include "AArch64FrameLowering.h"
#include "AArch64InstrInfo.h"
#include "AArch64MachineFunctionInfo.h"
#include "AArch64StackOffset.h"
#include "AArch64Subtarget.h"
#include "MCTargetDesc/AArch64AddressingModes.h"
#include "llvm/ADT/BitVector.h"
#include "llvm/ADT/Triple.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/RegisterScavenging.h"
#include "llvm/CodeGen/TargetFrameLowering.h"
#include "llvm/IR/DiagnosticInfo.h"
#include "llvm/IR/Function.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetOptions.h"
using namespace llvm;
#define GET_REGINFO_TARGET_DESC
#include "AArch64GenRegisterInfo.inc"
AArch64RegisterInfo::AArch64RegisterInfo(const Triple &TT)
: AArch64GenRegisterInfo(AArch64::LR), TT(TT) {
AArch64_MC::initLLVMToCVRegMapping(this);
}
/// Return whether the register needs a CFI entry. Not all unwinders may know
/// about SVE registers, so we assume the lowest common denominator, i.e. the
/// callee-saves required by the base ABI. For the SVE registers z8-z15 only the
/// lower 64-bits (d8-d15) need to be saved. The lower 64-bits subreg is
/// returned in \p RegToUseForCFI.
bool AArch64RegisterInfo::regNeedsCFI(unsigned Reg,
unsigned &RegToUseForCFI) const {
if (AArch64::PPRRegClass.contains(Reg))
return false;
if (AArch64::ZPRRegClass.contains(Reg)) {
RegToUseForCFI = getSubReg(Reg, AArch64::dsub);
for (int I = 0; CSR_AArch64_AAPCS_SaveList[I]; ++I) {
if (CSR_AArch64_AAPCS_SaveList[I] == RegToUseForCFI)
return true;
}
return false;
}
RegToUseForCFI = Reg;
return true;
}
bool AArch64RegisterInfo::hasSVEArgsOrReturn(const MachineFunction *MF) {
const Function &F = MF->getFunction();
return isa<ScalableVectorType>(F.getReturnType()) ||
any_of(F.args(), [](const Argument &Arg) {
return isa<ScalableVectorType>(Arg.getType());
});
}
const MCPhysReg *
AArch64RegisterInfo::getCalleeSavedRegs(const MachineFunction *MF) const {
assert(MF && "Invalid MachineFunction pointer.");
if (MF->getFunction().getCallingConv() == CallingConv::GHC)
// GHC set of callee saved regs is empty as all those regs are
// used for passing STG regs around
return CSR_AArch64_NoRegs_SaveList;
if (MF->getFunction().getCallingConv() == CallingConv::AnyReg)
return CSR_AArch64_AllRegs_SaveList;
// Darwin has its own CSR_AArch64_AAPCS_SaveList, which means most CSR save
// lists depending on that will need to have their Darwin variant as well.
if (MF->getSubtarget<AArch64Subtarget>().isTargetDarwin())
return getDarwinCalleeSavedRegs(MF);
if (MF->getFunction().getCallingConv() == CallingConv::CFGuard_Check)
return CSR_Win_AArch64_CFGuard_Check_SaveList;
if (MF->getSubtarget<AArch64Subtarget>().isTargetWindows())
return CSR_Win_AArch64_AAPCS_SaveList;
if (MF->getFunction().getCallingConv() == CallingConv::AArch64_VectorCall)
return CSR_AArch64_AAVPCS_SaveList;
if (MF->getFunction().getCallingConv() == CallingConv::AArch64_SVE_VectorCall)
return CSR_AArch64_SVE_AAPCS_SaveList;
if (MF->getSubtarget<AArch64Subtarget>().getTargetLowering()
->supportSwiftError() &&
MF->getFunction().getAttributes().hasAttrSomewhere(
Attribute::SwiftError))
return CSR_AArch64_AAPCS_SwiftError_SaveList;
if (MF->getFunction().getCallingConv() == CallingConv::PreserveMost)
return CSR_AArch64_RT_MostRegs_SaveList;
if (MF->getFunction().getCallingConv() == CallingConv::Win64)
// This is for OSes other than Windows; Windows is a separate case further
// above.
return CSR_AArch64_AAPCS_X18_SaveList;
if (hasSVEArgsOrReturn(MF))
return CSR_AArch64_SVE_AAPCS_SaveList;
return CSR_AArch64_AAPCS_SaveList;
}
const MCPhysReg *
AArch64RegisterInfo::getDarwinCalleeSavedRegs(const MachineFunction *MF) const {
assert(MF && "Invalid MachineFunction pointer.");
assert(MF->getSubtarget<AArch64Subtarget>().isTargetDarwin() &&
"Invalid subtarget for getDarwinCalleeSavedRegs");
if (MF->getFunction().getCallingConv() == CallingConv::CFGuard_Check)
report_fatal_error(
"Calling convention CFGuard_Check is unsupported on Darwin.");
if (MF->getFunction().getCallingConv() == CallingConv::AArch64_VectorCall)
return CSR_Darwin_AArch64_AAVPCS_SaveList;
if (MF->getFunction().getCallingConv() == CallingConv::AArch64_SVE_VectorCall)
report_fatal_error(
"Calling convention SVE_VectorCall is unsupported on Darwin.");
if (MF->getFunction().getCallingConv() == CallingConv::CXX_FAST_TLS)
return MF->getInfo<AArch64FunctionInfo>()->isSplitCSR()
? CSR_Darwin_AArch64_CXX_TLS_PE_SaveList
: CSR_Darwin_AArch64_CXX_TLS_SaveList;
if (MF->getSubtarget<AArch64Subtarget>().getTargetLowering()
->supportSwiftError() &&
MF->getFunction().getAttributes().hasAttrSomewhere(
Attribute::SwiftError))
return CSR_Darwin_AArch64_AAPCS_SwiftError_SaveList;
if (MF->getFunction().getCallingConv() == CallingConv::PreserveMost)
return CSR_Darwin_AArch64_RT_MostRegs_SaveList;
return CSR_Darwin_AArch64_AAPCS_SaveList;
}
const MCPhysReg *AArch64RegisterInfo::getCalleeSavedRegsViaCopy(
const MachineFunction *MF) const {
assert(MF && "Invalid MachineFunction pointer.");
if (MF->getFunction().getCallingConv() == CallingConv::CXX_FAST_TLS &&
MF->getInfo<AArch64FunctionInfo>()->isSplitCSR())
return CSR_Darwin_AArch64_CXX_TLS_ViaCopy_SaveList;
return nullptr;
}
void AArch64RegisterInfo::UpdateCustomCalleeSavedRegs(
MachineFunction &MF) const {
const MCPhysReg *CSRs = getCalleeSavedRegs(&MF);
SmallVector<MCPhysReg, 32> UpdatedCSRs;
for (const MCPhysReg *I = CSRs; *I; ++I)
UpdatedCSRs.push_back(*I);
for (size_t i = 0; i < AArch64::GPR64commonRegClass.getNumRegs(); ++i) {
if (MF.getSubtarget<AArch64Subtarget>().isXRegCustomCalleeSaved(i)) {
UpdatedCSRs.push_back(AArch64::GPR64commonRegClass.getRegister(i));
}
}
// Register lists are zero-terminated.
UpdatedCSRs.push_back(0);
MF.getRegInfo().setCalleeSavedRegs(UpdatedCSRs);
}
const TargetRegisterClass *
AArch64RegisterInfo::getSubClassWithSubReg(const TargetRegisterClass *RC,
unsigned Idx) const {
// edge case for GPR/FPR register classes
if (RC == &AArch64::GPR32allRegClass && Idx == AArch64::hsub)
return &AArch64::FPR32RegClass;
else if (RC == &AArch64::GPR64allRegClass && Idx == AArch64::hsub)
return &AArch64::FPR64RegClass;
// Forward to TableGen's default version.
return AArch64GenRegisterInfo::getSubClassWithSubReg(RC, Idx);
}
const uint32_t *
AArch64RegisterInfo::getDarwinCallPreservedMask(const MachineFunction &MF,
CallingConv::ID CC) const {
assert(MF.getSubtarget<AArch64Subtarget>().isTargetDarwin() &&
"Invalid subtarget for getDarwinCallPreservedMask");
if (CC == CallingConv::CXX_FAST_TLS)
return CSR_Darwin_AArch64_CXX_TLS_RegMask;
if (CC == CallingConv::AArch64_VectorCall)
return CSR_Darwin_AArch64_AAVPCS_RegMask;
if (CC == CallingConv::AArch64_SVE_VectorCall)
report_fatal_error(
"Calling convention SVE_VectorCall is unsupported on Darwin.");
if (CC == CallingConv::CFGuard_Check)
report_fatal_error(
"Calling convention CFGuard_Check is unsupported on Darwin.");
if (MF.getSubtarget<AArch64Subtarget>()
.getTargetLowering()
->supportSwiftError() &&
MF.getFunction().getAttributes().hasAttrSomewhere(Attribute::SwiftError))
return CSR_Darwin_AArch64_AAPCS_SwiftError_RegMask;
if (CC == CallingConv::PreserveMost)
return CSR_Darwin_AArch64_RT_MostRegs_RegMask;
return CSR_Darwin_AArch64_AAPCS_RegMask;
}
const uint32_t *
AArch64RegisterInfo::getCallPreservedMask(const MachineFunction &MF,
CallingConv::ID CC) const {
bool SCS = MF.getFunction().hasFnAttribute(Attribute::ShadowCallStack);
if (CC == CallingConv::GHC)
// This is academic because all GHC calls are (supposed to be) tail calls
return SCS ? CSR_AArch64_NoRegs_SCS_RegMask : CSR_AArch64_NoRegs_RegMask;
if (CC == CallingConv::AnyReg)
return SCS ? CSR_AArch64_AllRegs_SCS_RegMask : CSR_AArch64_AllRegs_RegMask;
// All the following calling conventions are handled differently on Darwin.
if (MF.getSubtarget<AArch64Subtarget>().isTargetDarwin()) {
if (SCS)
report_fatal_error("ShadowCallStack attribute not supported on Darwin.");
return getDarwinCallPreservedMask(MF, CC);
}
if (CC == CallingConv::AArch64_VectorCall)
return SCS ? CSR_AArch64_AAVPCS_SCS_RegMask : CSR_AArch64_AAVPCS_RegMask;
if (CC == CallingConv::AArch64_SVE_VectorCall)
return SCS ? CSR_AArch64_SVE_AAPCS_SCS_RegMask
: CSR_AArch64_SVE_AAPCS_RegMask;
if (CC == CallingConv::CFGuard_Check)
return CSR_Win_AArch64_CFGuard_Check_RegMask;
if (MF.getSubtarget<AArch64Subtarget>().getTargetLowering()
->supportSwiftError() &&
MF.getFunction().getAttributes().hasAttrSomewhere(Attribute::SwiftError))
return SCS ? CSR_AArch64_AAPCS_SwiftError_SCS_RegMask
: CSR_AArch64_AAPCS_SwiftError_RegMask;
if (CC == CallingConv::PreserveMost)
return SCS ? CSR_AArch64_RT_MostRegs_SCS_RegMask
: CSR_AArch64_RT_MostRegs_RegMask;
else
return SCS ? CSR_AArch64_AAPCS_SCS_RegMask : CSR_AArch64_AAPCS_RegMask;
}
const uint32_t *AArch64RegisterInfo::getTLSCallPreservedMask() const {
if (TT.isOSDarwin())
return CSR_Darwin_AArch64_TLS_RegMask;
assert(TT.isOSBinFormatELF() && "Invalid target");
return CSR_AArch64_TLS_ELF_RegMask;
}
void AArch64RegisterInfo::UpdateCustomCallPreservedMask(MachineFunction &MF,
const uint32_t **Mask) const {
uint32_t *UpdatedMask = MF.allocateRegMask();
unsigned RegMaskSize = MachineOperand::getRegMaskSize(getNumRegs());
memcpy(UpdatedMask, *Mask, sizeof(UpdatedMask[0]) * RegMaskSize);
for (size_t i = 0; i < AArch64::GPR64commonRegClass.getNumRegs(); ++i) {
if (MF.getSubtarget<AArch64Subtarget>().isXRegCustomCalleeSaved(i)) {
for (MCSubRegIterator SubReg(AArch64::GPR64commonRegClass.getRegister(i),
this, true);
SubReg.isValid(); ++SubReg) {
// See TargetRegisterInfo::getCallPreservedMask for how to interpret the
// register mask.
UpdatedMask[*SubReg / 32] |= 1u << (*SubReg % 32);
}
}
}
*Mask = UpdatedMask;
}
const uint32_t *AArch64RegisterInfo::getNoPreservedMask() const {
return CSR_AArch64_NoRegs_RegMask;
}
const uint32_t *
AArch64RegisterInfo::getThisReturnPreservedMask(const MachineFunction &MF,
CallingConv::ID CC) const {
// This should return a register mask that is the same as that returned by
// getCallPreservedMask but that additionally preserves the register used for
// the first i64 argument (which must also be the register used to return a
// single i64 return value)
//
// In case that the calling convention does not use the same register for
// both, the function should return NULL (does not currently apply)
assert(CC != CallingConv::GHC && "should not be GHC calling convention.");
if (MF.getSubtarget<AArch64Subtarget>().isTargetDarwin())
return CSR_Darwin_AArch64_AAPCS_ThisReturn_RegMask;
return CSR_AArch64_AAPCS_ThisReturn_RegMask;
}
const uint32_t *AArch64RegisterInfo::getWindowsStackProbePreservedMask() const {
return CSR_AArch64_StackProbe_Windows_RegMask;
}
BitVector
AArch64RegisterInfo::getReservedRegs(const MachineFunction &MF) const {
const AArch64FrameLowering *TFI = getFrameLowering(MF);
// FIXME: avoid re-calculating this every time.
BitVector Reserved(getNumRegs());
markSuperRegs(Reserved, AArch64::WSP);
markSuperRegs(Reserved, AArch64::WZR);
if (TFI->hasFP(MF) || TT.isOSDarwin())
markSuperRegs(Reserved, AArch64::W29);
for (size_t i = 0; i < AArch64::GPR32commonRegClass.getNumRegs(); ++i) {
if (MF.getSubtarget<AArch64Subtarget>().isXRegisterReserved(i))
markSuperRegs(Reserved, AArch64::GPR32commonRegClass.getRegister(i));
}
if (hasBasePointer(MF))
markSuperRegs(Reserved, AArch64::W19);
// SLH uses register W16/X16 as the taint register.
if (MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening))
markSuperRegs(Reserved, AArch64::W16);
assert(checkAllSuperRegsMarked(Reserved));
return Reserved;
}
bool AArch64RegisterInfo::isReservedReg(const MachineFunction &MF,
MCRegister Reg) const {
return getReservedRegs(MF)[Reg];
}
bool AArch64RegisterInfo::isAnyArgRegReserved(const MachineFunction &MF) const {
return std::any_of(std::begin(*AArch64::GPR64argRegClass.MC),
std::end(*AArch64::GPR64argRegClass.MC),
[this, &MF](MCPhysReg r){return isReservedReg(MF, r);});
}
void AArch64RegisterInfo::emitReservedArgRegCallError(
const MachineFunction &MF) const {
const Function &F = MF.getFunction();
F.getContext().diagnose(DiagnosticInfoUnsupported{F, ("AArch64 doesn't support"
" function calls if any of the argument registers is reserved.")});
}
bool AArch64RegisterInfo::isAsmClobberable(const MachineFunction &MF,
MCRegister PhysReg) const {
return !isReservedReg(MF, PhysReg);
}
bool AArch64RegisterInfo::isConstantPhysReg(MCRegister PhysReg) const {
return PhysReg == AArch64::WZR || PhysReg == AArch64::XZR;
}
const TargetRegisterClass *
AArch64RegisterInfo::getPointerRegClass(const MachineFunction &MF,
unsigned Kind) const {
return &AArch64::GPR64spRegClass;
}
const TargetRegisterClass *
AArch64RegisterInfo::getCrossCopyRegClass(const TargetRegisterClass *RC) const {
if (RC == &AArch64::CCRRegClass)
return &AArch64::GPR64RegClass; // Only MSR & MRS copy NZCV.
return RC;
}
unsigned AArch64RegisterInfo::getBaseRegister() const { return AArch64::X19; }
bool AArch64RegisterInfo::hasBasePointer(const MachineFunction &MF) const {
const MachineFrameInfo &MFI = MF.getFrameInfo();
// In the presence of variable sized objects or funclets, if the fixed stack
// size is large enough that referencing from the FP won't result in things
// being in range relatively often, we can use a base pointer to allow access
// from the other direction like the SP normally works.
//
// Furthermore, if both variable sized objects are present, and the
// stack needs to be dynamically re-aligned, the base pointer is the only
// reliable way to reference the locals.
if (MFI.hasVarSizedObjects() || MF.hasEHFunclets()) {
if (needsStackRealignment(MF))
return true;
if (MF.getSubtarget<AArch64Subtarget>().hasSVE()) {
const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
// Frames that have variable sized objects and scalable SVE objects,
// should always use a basepointer.
if (!AFI->hasCalculatedStackSizeSVE() || AFI->getStackSizeSVE())
return true;
}
// Conservatively estimate whether the negative offset from the frame
// pointer will be sufficient to reach. If a function has a smallish
// frame, it's less likely to have lots of spills and callee saved
// space, so it's all more likely to be within range of the frame pointer.
// If it's wrong, we'll materialize the constant and still get to the
// object; it's just suboptimal. Negative offsets use the unscaled
// load/store instructions, which have a 9-bit signed immediate.
return MFI.getLocalFrameSize() >= 256;
}
return false;
}
Register
AArch64RegisterInfo::getFrameRegister(const MachineFunction &MF) const {
const AArch64FrameLowering *TFI = getFrameLowering(MF);
return TFI->hasFP(MF) ? AArch64::FP : AArch64::SP;
}
bool AArch64RegisterInfo::requiresRegisterScavenging(
const MachineFunction &MF) const {
return true;
}
bool AArch64RegisterInfo::requiresVirtualBaseRegisters(
const MachineFunction &MF) const {
return true;
}
bool
AArch64RegisterInfo::useFPForScavengingIndex(const MachineFunction &MF) const {
// This function indicates whether the emergency spillslot should be placed
// close to the beginning of the stackframe (closer to FP) or the end
// (closer to SP).
//
// The beginning works most reliably if we have a frame pointer.
// In the presence of any non-constant space between FP and locals,
// (e.g. in case of stack realignment or a scalable SVE area), it is
// better to use SP or BP.
const AArch64FrameLowering &TFI = *getFrameLowering(MF);
const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
assert((!MF.getSubtarget<AArch64Subtarget>().hasSVE() ||
AFI->hasCalculatedStackSizeSVE()) &&
"Expected SVE area to be calculated by this point");
return TFI.hasFP(MF) && !needsStackRealignment(MF) && !AFI->getStackSizeSVE();
}
bool AArch64RegisterInfo::requiresFrameIndexScavenging(
const MachineFunction &MF) const {
return true;
}
bool
AArch64RegisterInfo::cannotEliminateFrame(const MachineFunction &MF) const {
const MachineFrameInfo &MFI = MF.getFrameInfo();
if (MF.getTarget().Options.DisableFramePointerElim(MF) && MFI.adjustsStack())
return true;
return MFI.hasVarSizedObjects() || MFI.isFrameAddressTaken();
}
/// needsFrameBaseReg - Returns true if the instruction's frame index
/// reference would be better served by a base register other than FP
/// or SP. Used by LocalStackFrameAllocation to determine which frame index
/// references it should create new base registers for.
bool AArch64RegisterInfo::needsFrameBaseReg(MachineInstr *MI,
int64_t Offset) const {
for (unsigned i = 0; !MI->getOperand(i).isFI(); ++i)
assert(i < MI->getNumOperands() &&
"Instr doesn't have FrameIndex operand!");
// It's the load/store FI references that cause issues, as it can be difficult
// to materialize the offset if it won't fit in the literal field. Estimate
// based on the size of the local frame and some conservative assumptions
// about the rest of the stack frame (note, this is pre-regalloc, so
// we don't know everything for certain yet) whether this offset is likely
// to be out of range of the immediate. Return true if so.
// We only generate virtual base registers for loads and stores, so
// return false for everything else.
if (!MI->mayLoad() && !MI->mayStore())
return false;
// Without a virtual base register, if the function has variable sized
// objects, all fixed-size local references will be via the frame pointer,
// Approximate the offset and see if it's legal for the instruction.
// Note that the incoming offset is based on the SP value at function entry,
// so it'll be negative.
MachineFunction &MF = *MI->getParent()->getParent();
const AArch64FrameLowering *TFI = getFrameLowering(MF);
MachineFrameInfo &MFI = MF.getFrameInfo();
// Estimate an offset from the frame pointer.
// Conservatively assume all GPR callee-saved registers get pushed.
// FP, LR, X19-X28, D8-D15. 64-bits each.
int64_t FPOffset = Offset - 16 * 20;
// Estimate an offset from the stack pointer.
// The incoming offset is relating to the SP at the start of the function,
// but when we access the local it'll be relative to the SP after local
// allocation, so adjust our SP-relative offset by that allocation size.
Offset += MFI.getLocalFrameSize();
// Assume that we'll have at least some spill slots allocated.
// FIXME: This is a total SWAG number. We should run some statistics
// and pick a real one.
Offset += 128; // 128 bytes of spill slots
// If there is a frame pointer, try using it.
// The FP is only available if there is no dynamic realignment. We
// don't know for sure yet whether we'll need that, so we guess based
// on whether there are any local variables that would trigger it.
if (TFI->hasFP(MF) && isFrameOffsetLegal(MI, AArch64::FP, FPOffset))
return false;
// If we can reference via the stack pointer or base pointer, try that.
// FIXME: This (and the code that resolves the references) can be improved
// to only disallow SP relative references in the live range of
// the VLA(s). In practice, it's unclear how much difference that
// would make, but it may be worth doing.
if (isFrameOffsetLegal(MI, AArch64::SP, Offset))
return false;
// If even offset 0 is illegal, we don't want a virtual base register.
if (!isFrameOffsetLegal(MI, AArch64::SP, 0))
return false;
// The offset likely isn't legal; we want to allocate a virtual base register.
return true;
}
bool AArch64RegisterInfo::isFrameOffsetLegal(const MachineInstr *MI,
Register BaseReg,
int64_t Offset) const {
assert(MI && "Unable to get the legal offset for nil instruction.");
StackOffset SaveOffset(Offset, MVT::i8);
return isAArch64FrameOffsetLegal(*MI, SaveOffset) & AArch64FrameOffsetIsLegal;
}
/// Insert defining instruction(s) for BaseReg to be a pointer to FrameIdx
/// at the beginning of the basic block.
void AArch64RegisterInfo::materializeFrameBaseRegister(MachineBasicBlock *MBB,
Register BaseReg,
int FrameIdx,
int64_t Offset) const {
MachineBasicBlock::iterator Ins = MBB->begin();
DebugLoc DL; // Defaults to "unknown"
if (Ins != MBB->end())
DL = Ins->getDebugLoc();
const MachineFunction &MF = *MBB->getParent();
const AArch64InstrInfo *TII =
MF.getSubtarget<AArch64Subtarget>().getInstrInfo();
const MCInstrDesc &MCID = TII->get(AArch64::ADDXri);
MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
MRI.constrainRegClass(BaseReg, TII->getRegClass(MCID, 0, this, MF));
unsigned Shifter = AArch64_AM::getShifterImm(AArch64_AM::LSL, 0);
BuildMI(*MBB, Ins, DL, MCID, BaseReg)
.addFrameIndex(FrameIdx)
.addImm(Offset)
.addImm(Shifter);
}
void AArch64RegisterInfo::resolveFrameIndex(MachineInstr &MI, Register BaseReg,
int64_t Offset) const {
// ARM doesn't need the general 64-bit offsets
StackOffset Off(Offset, MVT::i8);
unsigned i = 0;
while (!MI.getOperand(i).isFI()) {
++i;
assert(i < MI.getNumOperands() && "Instr doesn't have FrameIndex operand!");
}
const MachineFunction *MF = MI.getParent()->getParent();
const AArch64InstrInfo *TII =
MF->getSubtarget<AArch64Subtarget>().getInstrInfo();
bool Done = rewriteAArch64FrameIndex(MI, i, BaseReg, Off, TII);
assert(Done && "Unable to resolve frame index!");
(void)Done;
}
// Create a scratch register for the frame index elimination in an instruction.
// This function has special handling of stack tagging loop pseudos, in which
// case it can also change the instruction opcode (but not the operands).
static Register
createScratchRegisterForInstruction(MachineInstr &MI,
const AArch64InstrInfo *TII) {
// ST*Gloop have a reserved scratch register in operand 1. Use it, and also
// replace the instruction with the writeback variant because it will now
// satisfy the operand constraints for it.
if (MI.getOpcode() == AArch64::STGloop) {
MI.setDesc(TII->get(AArch64::STGloop_wback));
return MI.getOperand(1).getReg();
} else if (MI.getOpcode() == AArch64::STZGloop) {
MI.setDesc(TII->get(AArch64::STZGloop_wback));
return MI.getOperand(1).getReg();
} else {
return MI.getMF()->getRegInfo().createVirtualRegister(
&AArch64::GPR64RegClass);
}
}
void AArch64RegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator II,
int SPAdj, unsigned FIOperandNum,
RegScavenger *RS) const {
assert(SPAdj == 0 && "Unexpected");
MachineInstr &MI = *II;
MachineBasicBlock &MBB = *MI.getParent();
MachineFunction &MF = *MBB.getParent();
const MachineFrameInfo &MFI = MF.getFrameInfo();
const AArch64InstrInfo *TII =
MF.getSubtarget<AArch64Subtarget>().getInstrInfo();
const AArch64FrameLowering *TFI = getFrameLowering(MF);
int FrameIndex = MI.getOperand(FIOperandNum).getIndex();
bool Tagged =
MI.getOperand(FIOperandNum).getTargetFlags() & AArch64II::MO_TAGGED;
Register FrameReg;
// Special handling of dbg_value, stackmap and patchpoint instructions.
if (MI.isDebugValue() || MI.getOpcode() == TargetOpcode::STACKMAP ||
MI.getOpcode() == TargetOpcode::PATCHPOINT) {
StackOffset Offset =
TFI->resolveFrameIndexReference(MF, FrameIndex, FrameReg,
/*PreferFP=*/true,
/*ForSimm=*/false);
Offset += StackOffset(MI.getOperand(FIOperandNum + 1).getImm(), MVT::i8);
MI.getOperand(FIOperandNum).ChangeToRegister(FrameReg, false /*isDef*/);
MI.getOperand(FIOperandNum + 1).ChangeToImmediate(Offset.getBytes());
return;
}
if (MI.getOpcode() == TargetOpcode::LOCAL_ESCAPE) {
MachineOperand &FI = MI.getOperand(FIOperandNum);
int Offset = TFI->getNonLocalFrameIndexReference(MF, FrameIndex);
FI.ChangeToImmediate(Offset);
return;
}
StackOffset Offset;
if (MI.getOpcode() == AArch64::TAGPstack) {
// TAGPstack must use the virtual frame register in its 3rd operand.
const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
FrameReg = MI.getOperand(3).getReg();
Offset = {MFI.getObjectOffset(FrameIndex) +
AFI->getTaggedBasePointerOffset(),
MVT::i8};
} else if (Tagged) {
StackOffset SPOffset = {
MFI.getObjectOffset(FrameIndex) + (int64_t)MFI.getStackSize(), MVT::i8};
if (MFI.hasVarSizedObjects() ||
isAArch64FrameOffsetLegal(MI, SPOffset, nullptr, nullptr, nullptr) !=
(AArch64FrameOffsetCanUpdate | AArch64FrameOffsetIsLegal)) {
// Can't update to SP + offset in place. Precalculate the tagged pointer
// in a scratch register.
Offset = TFI->resolveFrameIndexReference(
MF, FrameIndex, FrameReg, /*PreferFP=*/false, /*ForSimm=*/true);
Register ScratchReg =
MF.getRegInfo().createVirtualRegister(&AArch64::GPR64RegClass);
emitFrameOffset(MBB, II, MI.getDebugLoc(), ScratchReg, FrameReg, Offset,
TII);
BuildMI(MBB, MI, MI.getDebugLoc(), TII->get(AArch64::LDG), ScratchReg)
.addReg(ScratchReg)
.addReg(ScratchReg)
.addImm(0);
MI.getOperand(FIOperandNum)
.ChangeToRegister(ScratchReg, false, false, true);
return;
}
FrameReg = AArch64::SP;
Offset = {MFI.getObjectOffset(FrameIndex) + (int64_t)MFI.getStackSize(),
MVT::i8};
} else {
Offset = TFI->resolveFrameIndexReference(
MF, FrameIndex, FrameReg, /*PreferFP=*/false, /*ForSimm=*/true);
}
// Modify MI as necessary to handle as much of 'Offset' as possible
if (rewriteAArch64FrameIndex(MI, FIOperandNum, FrameReg, Offset, TII))
return;
assert((!RS || !RS->isScavengingFrameIndex(FrameIndex)) &&
"Emergency spill slot is out of reach");
// If we get here, the immediate doesn't fit into the instruction. We folded
// as much as possible above. Handle the rest, providing a register that is
// SP+LargeImm.
Register ScratchReg = createScratchRegisterForInstruction(MI, TII);
emitFrameOffset(MBB, II, MI.getDebugLoc(), ScratchReg, FrameReg, Offset, TII);
MI.getOperand(FIOperandNum).ChangeToRegister(ScratchReg, false, false, true);
}
unsigned AArch64RegisterInfo::getRegPressureLimit(const TargetRegisterClass *RC,
MachineFunction &MF) const {
const AArch64FrameLowering *TFI = getFrameLowering(MF);
switch (RC->getID()) {
default:
return 0;
case AArch64::GPR32RegClassID:
case AArch64::GPR32spRegClassID:
case AArch64::GPR32allRegClassID:
case AArch64::GPR64spRegClassID:
case AArch64::GPR64allRegClassID:
case AArch64::GPR64RegClassID:
case AArch64::GPR32commonRegClassID:
case AArch64::GPR64commonRegClassID:
return 32 - 1 // XZR/SP
- (TFI->hasFP(MF) || TT.isOSDarwin()) // FP
- MF.getSubtarget<AArch64Subtarget>().getNumXRegisterReserved()
- hasBasePointer(MF); // X19
case AArch64::FPR8RegClassID:
case AArch64::FPR16RegClassID:
case AArch64::FPR32RegClassID:
case AArch64::FPR64RegClassID:
case AArch64::FPR128RegClassID:
return 32;
case AArch64::DDRegClassID:
case AArch64::DDDRegClassID:
case AArch64::DDDDRegClassID:
case AArch64::QQRegClassID:
case AArch64::QQQRegClassID:
case AArch64::QQQQRegClassID:
return 32;
case AArch64::FPR128_loRegClassID:
case AArch64::FPR64_loRegClassID:
case AArch64::FPR16_loRegClassID:
return 16;
}
}
unsigned AArch64RegisterInfo::getLocalAddressRegister(
const MachineFunction &MF) const {
const auto &MFI = MF.getFrameInfo();
if (!MF.hasEHFunclets() && !MFI.hasVarSizedObjects())
return AArch64::SP;
else if (needsStackRealignment(MF))
return getBaseRegister();
return getFrameRegister(MF);
}
|
#include <miopen/scgemm/conv.hpp>
#include <miopen/logger.hpp>
#include <miopen/scgemm/scgemm.hpp>
#include <boost/algorithm/string.hpp>
#include <cstring>
#include <vector>
#include <unordered_map>
namespace miopen {
namespace scgemm {
bool is_fconv(const std::string& kernel_name)
{
return kernel_name.find("sconv_") != std::string::npos;
}
scgemm_conv_routine_t get_fconv_routine(const std::string& kernel_name)
{
std::vector<std::string> ss;
boost::split(ss, kernel_name, [](char c) { return c == '_'; });
static const std::unordered_map<std::string, scgemm_conv_routine_t> data{
{"6x4", sconv_064x016},
{"6x5", sconv_064x032},
{"6x6", sconv_064x064},
{"7x5", sconv_128x032},
{"7x6", sconv_128x064},
{"7x7", sconv_128x128},
{"8x5", sconv_256x032},
{"8x6", sconv_256x064},
};
auto result = data.find(ss[1]);
if(result != data.end())
{
return result->second;
}
else
{
MIOPEN_LOG_E("Conv kernel: " << kernel_name << ", cannot find associate routine.");
return sconv_064x016;
}
}
std::string get_conv_kernel_tile_string(scgemm_conv_routine_t routine)
{
switch(routine)
{
case sconv_064x016: return "6x4";
case sconv_064x032: return "6x5";
case sconv_064x064: return "6x6";
case sconv_128x032: return "7x5";
case sconv_128x064: return "7x6";
case sconv_128x128: return "7x7";
case sconv_256x032: return "8x5";
case sconv_256x064: return "8x6";
}
MIOPEN_LOG_E("Conv routine " << routine << " tile not found.");
return "6x4";
}
static void gen_fconv_kernel_prop(kernel_prop_t* prop, scgemm_conv_routine_t routine, bool is_relu)
{
prop->name = "sconv_";
prop->name.append(get_conv_kernel_tile_string(routine));
if(is_relu)
{
prop->name.append("_relu");
}
switch(routine)
{
case sconv_064x016:
prop->tile_x = 6;
prop->tile_y = 4;
prop->block_size = 64;
break;
case sconv_064x032:
prop->tile_x = 6;
prop->tile_y = 5;
prop->block_size = 64;
break;
case sconv_064x064:
prop->tile_x = 6;
prop->tile_y = 6;
prop->block_size = 64;
break;
case sconv_128x032:
prop->tile_x = 7;
prop->tile_y = 5;
prop->block_size = 128;
break;
case sconv_128x064:
prop->tile_x = 7;
prop->tile_y = 6;
prop->block_size = 128;
break;
case sconv_128x128:
prop->tile_x = 7;
prop->tile_y = 7;
prop->block_size = 256;
break;
case sconv_256x032:
prop->tile_x = 8;
prop->tile_y = 5;
prop->block_size = 256;
break;
case sconv_256x064:
prop->tile_x = 8;
prop->tile_y = 6;
prop->block_size = 256;
break;
}
}
scgemm_fconv_params create_fconv_params(std::string& kernel_name,
std::vector<uint32_t>& grids,
std::vector<uint32_t>& blocks,
scgemm_conv_routine_t routine,
const group_prop_t* gprop,
uint32_t mask,
uint32_t ng)
{
kernel_prop_t kprop{};
size_t nb_span, nb_amap;
uint32_t k, ls, ocs, onpx, inc, onc, snpx, sgs, gdx, gdy, ntidx;
uint32_t aozero, bozero;
snpx = gprop->pnx * gprop->pny * gprop->pnz;
onpx = gprop->qnx * gprop->qny * gprop->qnz;
inc = gprop->pnc;
onc = gprop->qnc;
k = gprop->fnx * gprop->fny * gprop->fnz * inc;
ocs = gprop->bat * onpx;
sgs = gprop->bat * snpx * inc;
ls = PSIZE(k, 8);
gen_fconv_kernel_prop(&kprop, routine, static_cast<bool>(mask & 1u));
gdx = (ocs + (1u << kprop.tile_x) - 1) >> kprop.tile_x;
gdy = (onc + (1u << kprop.tile_y) - 1) >> kprop.tile_y;
ntidx = gdx << kprop.tile_x;
nb_span = (ls + 16) << 2;
nb_amap = ntidx << 2;
aozero = 0;
bozero = 0;
if((k & 7) != 0)
{
aozero = (sgs * ng) << 2;
bozero = k;
}
(void)nb_span; // Suppress warning
kernel_name = kprop.name;
grids[0] = routine == 0 ? gdx : gdy;
grids[1] = routine == 0 ? gdy : gdx;
grids[2] = ng;
blocks[0] = kprop.block_size;
blocks[1] = 1;
blocks[2] = 1;
scgemm_fconv_params params{ntidx, static_cast<uint32_t>(nb_amap),
aozero, bozero,
onc, ocs,
ls, sgs,
onpx, gprop->pnx,
gprop->pny, gprop->pnz,
gprop->qnx, gprop->qny,
gprop->qnz, gprop->fnx,
gprop->fny, gprop->fnz,
gprop->pnc, gprop->qnc,
gprop->bat};
return params;
}
/// This fucintion is used to present how to fill in the kernel arguments for a
/// Static Compiled GEMM - Forwared Convolution Kernel.
/// Left the code here for reference.
/*
scgemm_kernel_args_t compiled_fconv_args(size_t& args_size,
const void* src,
const void* wei,
const void* bias,
void* dst,
void* auxbuf,
scgemm_fconv_params* params,
float alpha)
{
(void)bias; // Suppress warning
args_size = 72;
scgemm_kernel_args_t args(new char[args_size]);
auto _args = reinterpret_cast<char*>(args.get());
*(reinterpret_cast<void**>(&_args[0x00])) = auxbuf;
*(reinterpret_cast<void**>(&_args[0x08])) =
reinterpret_cast<void*>(reinterpret_cast<char*>(auxbuf) + params->nb_amap);
*(reinterpret_cast<uint32_t*>(&_args[0x10])) = params->onc;
*(reinterpret_cast<uint32_t*>(&_args[0x14])) = params->ocs;
*(reinterpret_cast<uint32_t*>(&_args[0x18])) = params->ls;
*(reinterpret_cast<uint32_t*>(&_args[0x1c])) = params->sgs;
*(reinterpret_cast<const void**>(&_args[0x20])) = src;
*(reinterpret_cast<const void**>(&_args[0x28])) = wei;
*(reinterpret_cast<void**>(&_args[0x30])) = dst;
*(reinterpret_cast<uint32_t*>(&_args[0x38])) = params->onpx;
memcpy(&_args[0x3c], &alpha, sizeof(float));
// *(reinterpret_cast<float*>(&_args[0x3c])) = alpha;
*(reinterpret_cast<void**>(&_args[0x40])) =
reinterpret_cast<void*>(reinterpret_cast<char*>(auxbuf) + (params->nb_amap << 1));
return args;
}
*/
} // namespace scgemm
} // namespace miopen
|
/**
* @file array_schema.cc
*
* @section LICENSE
*
* The MIT License
*
* @copyright Copyright (c) 2017-2021 TileDB, Inc.
* @copyright Copyright (c) 2016 MIT and 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.
*
* @section DESCRIPTION
*
* This file implements the ArraySchema class.
*/
#include "tiledb/sm/array_schema/array_schema.h"
#include "tiledb/common/heap_memory.h"
#include "tiledb/common/logger.h"
#include "tiledb/sm/array_schema/attribute.h"
#include "tiledb/sm/array_schema/dimension.h"
#include "tiledb/sm/array_schema/domain.h"
#include "tiledb/sm/buffer/buffer.h"
#include "tiledb/sm/enums/array_type.h"
#include "tiledb/sm/enums/compressor.h"
#include "tiledb/sm/enums/datatype.h"
#include "tiledb/sm/enums/filter_type.h"
#include "tiledb/sm/enums/layout.h"
#include "tiledb/sm/filter/compression_filter.h"
#include "tiledb/sm/misc/hilbert.h"
#include "tiledb/sm/misc/utils.h"
#include <cassert>
#include <iostream>
#include <set>
#include <sstream>
using namespace tiledb::common;
namespace tiledb {
namespace sm {
/* ****************************** */
/* CONSTRUCTORS & DESTRUCTORS */
/* ****************************** */
ArraySchema::ArraySchema()
: ArraySchema(ArrayType::DENSE) {
}
ArraySchema::ArraySchema(ArrayType array_type)
: array_type_(array_type) {
allows_dups_ = false;
array_uri_ = URI();
uri_ = URI();
name_ = "";
capacity_ = constants::capacity;
cell_order_ = Layout::ROW_MAJOR;
domain_ = nullptr;
tile_order_ = Layout::ROW_MAJOR;
version_ = constants::format_version;
auto timestamp = utils::time::timestamp_now_ms();
timestamp_range_ = std::make_pair(timestamp, timestamp);
// Set up default filter pipelines for coords, offsets, and validity values.
coords_filters_.add_filter(CompressionFilter(
constants::coords_compression, constants::coords_compression_level));
cell_var_offsets_filters_.add_filter(CompressionFilter(
constants::cell_var_offsets_compression,
constants::cell_var_offsets_compression_level));
cell_validity_filters_.add_filter(CompressionFilter(
constants::cell_validity_compression,
constants::cell_validity_compression_level));
}
ArraySchema::ArraySchema(const ArraySchema* array_schema) {
allows_dups_ = array_schema->allows_dups_;
array_uri_ = array_schema->array_uri_;
uri_ = array_schema->uri_;
array_type_ = array_schema->array_type_;
domain_ = nullptr;
timestamp_range_ = array_schema->timestamp_range_;
capacity_ = array_schema->capacity_;
cell_order_ = array_schema->cell_order_;
cell_var_offsets_filters_ = array_schema->cell_var_offsets_filters_;
cell_validity_filters_ = array_schema->cell_validity_filters_;
coords_filters_ = array_schema->coords_filters_;
tile_order_ = array_schema->tile_order_;
version_ = array_schema->version_;
set_domain(array_schema->domain_);
attribute_map_.clear();
for (auto attr : array_schema->attributes_)
add_attribute(attr, false);
// This has to be the last thing set because add_attribute sets the name
// TODO: This behavior needs to be changed
name_ = array_schema->name_;
}
ArraySchema::~ArraySchema() {
clear();
}
/* ****************************** */
/* API */
/* ****************************** */
bool ArraySchema::allows_dups() const {
return allows_dups_;
}
ArrayType ArraySchema::array_type() const {
return array_type_;
}
const URI& ArraySchema::array_uri() const {
return array_uri_;
}
const Attribute* ArraySchema::attribute(unsigned int id) const {
if (id < attributes_.size())
return attributes_[id];
return nullptr;
}
const Attribute* ArraySchema::attribute(const std::string& name) const {
auto it = attribute_map_.find(name);
return it == attribute_map_.end() ? nullptr : it->second;
}
unsigned int ArraySchema::attribute_num() const {
return (unsigned)attributes_.size();
}
const std::vector<Attribute*>& ArraySchema::attributes() const {
return attributes_;
}
uint64_t ArraySchema::capacity() const {
return capacity_;
}
Layout ArraySchema::cell_order() const {
return cell_order_;
}
uint64_t ArraySchema::cell_size(const std::string& name) const {
// Special zipped coordinates attribute
if (name == constants::coords) {
auto dim_num = domain_->dim_num();
assert(dim_num > 0);
auto coord_size = domain_->dimension(0)->coord_size();
return dim_num * coord_size;
}
// Attribute
auto attr_it = attribute_map_.find(name);
if (attr_it != attribute_map_.end()) {
auto attr = attr_it->second;
auto cell_val_num = attr->cell_val_num();
return (cell_val_num == constants::var_num) ?
constants::var_size :
cell_val_num * datatype_size(attr->type());
}
// Dimension
auto dim_it = dim_map_.find(name);
assert(dim_it != dim_map_.end());
auto dim = dim_it->second;
auto cell_val_num = dim->cell_val_num();
return (cell_val_num == constants::var_num) ?
constants::var_size :
cell_val_num * datatype_size(dim->type());
}
unsigned int ArraySchema::cell_val_num(const std::string& name) const {
// Special zipped coordinates
if (name == constants::coords)
return 1;
// Attribute
auto attr_it = attribute_map_.find(name);
if (attr_it != attribute_map_.end())
return attr_it->second->cell_val_num();
// Dimension
auto dim_it = dim_map_.find(name);
assert(dim_it != dim_map_.end());
return dim_it->second->cell_val_num();
}
const FilterPipeline& ArraySchema::cell_var_offsets_filters() const {
return cell_var_offsets_filters_;
}
const FilterPipeline& ArraySchema::cell_validity_filters() const {
return cell_validity_filters_;
}
Status ArraySchema::check() const {
if (domain_ == nullptr)
return LOG_STATUS(
Status::ArraySchemaError("Array schema check failed; Domain not set"));
auto dim_num = this->dim_num();
if (dim_num == 0)
return LOG_STATUS(Status::ArraySchemaError(
"Array schema check failed; No dimensions provided"));
if (cell_order_ == Layout::HILBERT && dim_num > Hilbert::HC_MAX_DIM) {
return LOG_STATUS(Status::ArraySchemaError(
"Array schema check failed; Maximum dimensions supported by Hilbert "
"order exceeded"));
}
if (array_type_ == ArrayType::DENSE) {
auto type = domain_->dimension(0)->type();
if (datatype_is_real(type)) {
return LOG_STATUS(
Status::ArraySchemaError("Array schema check failed; Dense arrays "
"cannot have floating point domains"));
}
if (attributes_.size() == 0) {
return LOG_STATUS(Status::ArraySchemaError(
"Array schema check failed; No attributes provided"));
}
}
RETURN_NOT_OK(check_double_delta_compressor());
if (!check_attribute_dimension_names())
return LOG_STATUS(
Status::ArraySchemaError("Array schema check failed; Attributes "
"and dimensions must have unique names"));
// Success
return Status::Ok();
}
Status ArraySchema::check_attributes(
const std::vector<std::string>& attributes) const {
for (const auto& attr : attributes) {
if (attr == constants::coords)
continue;
if (attribute_map_.find(attr) == attribute_map_.end())
return LOG_STATUS(Status::ArraySchemaError(
"Attribute check failed; cannot find attribute"));
}
return Status::Ok();
}
const FilterPipeline& ArraySchema::filters(const std::string& name) const {
if (name == constants::coords)
return coords_filters();
// Attribute
auto attr_it = attribute_map_.find(name);
if (attr_it != attribute_map_.end())
return attr_it->second->filters();
// Dimension (if filters not set, return default coordinate filters)
auto dim_it = dim_map_.find(name);
assert(dim_it != dim_map_.end());
const auto& ret = dim_it->second->filters();
return !ret.empty() ? ret : coords_filters();
}
const FilterPipeline& ArraySchema::coords_filters() const {
return coords_filters_;
}
bool ArraySchema::dense() const {
return array_type_ == ArrayType::DENSE;
}
const Dimension* ArraySchema::dimension(unsigned int i) const {
return domain_->dimension(i);
}
const Dimension* ArraySchema::dimension(const std::string& name) const {
auto it = dim_map_.find(name);
return it == dim_map_.end() ? nullptr : it->second;
}
std::vector<std::string> ArraySchema::dim_names() const {
auto dim_num = this->dim_num();
std::vector<std::string> ret;
ret.reserve(dim_num);
for (uint32_t d = 0; d < dim_num; ++d)
ret.emplace_back(domain_->dimension(d)->name());
return ret;
}
std::vector<Datatype> ArraySchema::dim_types() const {
auto dim_num = this->dim_num();
std::vector<Datatype> ret;
ret.reserve(dim_num);
for (uint32_t d = 0; d < dim_num; ++d)
ret.emplace_back(domain_->dimension(d)->type());
return ret;
}
unsigned int ArraySchema::dim_num() const {
return domain_->dim_num();
}
void ArraySchema::dump(FILE* out) const {
if (out == nullptr)
out = stdout;
std::stringstream ss;
ss << "- Array type: " << array_type_str(array_type_) << "\n";
ss << "- Cell order: " << layout_str(cell_order_) << "\n";
ss << "- Tile order: " << layout_str(tile_order_) << "\n";
ss << "- Capacity: " << capacity_ << "\n";
ss << "- Allows duplicates: " << (allows_dups_ ? "true" : "false") << "\n";
ss << "- Coordinates filters: " << coords_filters_.size();
fprintf(out, "%s", ss.str().c_str());
coords_filters_.dump(out);
fprintf(
out,
"\n- Offsets filters: %u",
(unsigned)cell_var_offsets_filters_.size());
cell_var_offsets_filters_.dump(out);
fprintf(
out, "\n- Validity filters: %u", (unsigned)cell_validity_filters_.size());
cell_validity_filters_.dump(out);
fprintf(out, "\n");
if (domain_ != nullptr)
domain_->dump(out);
for (auto& attr : attributes_) {
fprintf(out, "\n");
attr->dump(out);
}
}
Status ArraySchema::has_attribute(
const std::string& name, bool* has_attr) const {
*has_attr = false;
for (auto& attr : attributes_) {
if (name == attr->name()) {
*has_attr = true;
break;
}
}
return Status::Ok();
}
bool ArraySchema::is_attr(const std::string& name) const {
return this->attribute(name) != nullptr;
}
bool ArraySchema::is_dim(const std::string& name) const {
return this->dimension(name) != nullptr;
}
bool ArraySchema::is_field(const std::string& name) const {
return is_attr(name) || is_dim(name) || name == constants::coords;
}
bool ArraySchema::is_nullable(const std::string& name) const {
const Attribute* const attr = this->attribute(name);
if (attr == nullptr)
return false;
return attr->nullable();
}
// ===== FORMAT =====
// version (uint32_t)
// allow_dups (bool)
// array_type (uint8_t)
// tile_order (uint8_t)
// cell_order (uint8_t)
// capacity (uint64_t)
// coords_filters (see FilterPipeline::serialize)
// cell_var_offsets_filters (see FilterPipeline::serialize)
// cell_validity_filters (see FilterPipeline::serialize)
// domain
// attribute_num (uint32_t)
// attribute #1
// attribute #2
// ...
Status ArraySchema::serialize(Buffer* buff) const {
// Write version, which is always the current version. Despite
// the in-memory `version_`, we will serialize every array schema
// as the latest version.
const uint32_t version = constants::format_version;
RETURN_NOT_OK(buff->write(&version, sizeof(uint32_t)));
// Write allows_dups
RETURN_NOT_OK(buff->write(&allows_dups_, sizeof(bool)));
// Write array type
auto array_type = (uint8_t)array_type_;
RETURN_NOT_OK(buff->write(&array_type, sizeof(uint8_t)));
// Write tile and cell order
auto tile_order = (uint8_t)tile_order_;
RETURN_NOT_OK(buff->write(&tile_order, sizeof(uint8_t)));
auto cell_order = (uint8_t)cell_order_;
RETURN_NOT_OK(buff->write(&cell_order, sizeof(uint8_t)));
// Write capacity
RETURN_NOT_OK(buff->write(&capacity_, sizeof(uint64_t)));
// Write coords filters
RETURN_NOT_OK(coords_filters_.serialize(buff));
// Write offsets filters
RETURN_NOT_OK(cell_var_offsets_filters_.serialize(buff));
// Write validity filters
RETURN_NOT_OK(cell_validity_filters_.serialize(buff));
// Write domain
RETURN_NOT_OK(domain_->serialize(buff, version));
// Write attributes
auto attribute_num = (uint32_t)attributes_.size();
RETURN_NOT_OK(buff->write(&attribute_num, sizeof(uint32_t)));
for (auto& attr : attributes_)
RETURN_NOT_OK(attr->serialize(buff, version));
return Status::Ok();
}
Layout ArraySchema::tile_order() const {
return tile_order_;
}
Datatype ArraySchema::type(const std::string& name) const {
// Special zipped coordinates attribute
if (name == constants::coords)
return domain_->dimension(0)->type();
// Attribute
auto attr_it = attribute_map_.find(name);
if (attr_it != attribute_map_.end())
return attr_it->second->type();
// Dimension
auto dim_it = dim_map_.find(name);
assert(dim_it != dim_map_.end());
return dim_it->second->type();
}
bool ArraySchema::var_size(const std::string& name) const {
// Special case for zipped coordinates
if (name == constants::coords)
return false;
// Attribute
auto attr_it = attribute_map_.find(name);
if (attr_it != attribute_map_.end())
return attr_it->second->var_size();
// Dimension
auto dim_it = dim_map_.find(name);
if (dim_it != dim_map_.end())
return dim_it->second->var_size();
// Name is not an attribute or dimension
assert(false);
return false;
}
Status ArraySchema::add_attribute(const Attribute* attr, bool check_special) {
// Sanity check
if (attr == nullptr)
return LOG_STATUS(Status::ArraySchemaError(
"Cannot add attribute; Input attribute is null"));
// Do not allow attributes with special names
if (check_special && attr->name().find(constants::special_name_prefix) == 0) {
std::string msg = "Cannot add attribute; Attribute names starting with '";
msg += std::string(constants::special_name_prefix) + "' are reserved";
return LOG_STATUS(Status::ArraySchemaError(msg));
}
// Create new attribute and potentially set a default name
auto new_attr = tdb_new(Attribute, attr);
attributes_.emplace_back(new_attr);
attribute_map_[new_attr->name()] = new_attr;
RETURN_NOT_OK(generate_uri());
return Status::Ok();
}
Status ArraySchema::drop_attribute(const std::string& attr_name) {
std::lock_guard<std::mutex> lock(mtx_);
if (attr_name.empty()) {
return LOG_STATUS(
Status::ArraySchemaError("Cannot remove an empty name attribute"));
}
if (attribute_map_.find(attr_name) == attribute_map_.end()) {
// Not exists.
return LOG_STATUS(
Status::ArraySchemaError("Cannot remove a non-exist attribute"));
}
attribute_map_.erase(attr_name);
// Iterate backwards and remove the attribute pointer, it should be slightly
// faster than iterating forward.
std::vector<Attribute*>::iterator it;
for (it = attributes_.end(); it != attributes_.begin();) {
--it;
if ((*it)->name() == attr_name) {
tdb_delete(*it);
it = attributes_.erase(it);
}
}
RETURN_NOT_OK(generate_uri());
return Status::Ok();
}
Status ArraySchema::deserialize(ConstBuffer* buff) {
// Load version
RETURN_NOT_OK(buff->read(&version_, sizeof(uint32_t)));
// Load allows_dups
if (version_ >= 5)
RETURN_NOT_OK(buff->read(&allows_dups_, sizeof(bool)));
// Load array type
uint8_t array_type;
RETURN_NOT_OK(buff->read(&array_type, sizeof(uint8_t)));
array_type_ = (ArrayType)array_type;
// Load tile order
uint8_t tile_order;
RETURN_NOT_OK(buff->read(&tile_order, sizeof(uint8_t)));
tile_order_ = (Layout)tile_order;
// Load cell order
uint8_t cell_order;
RETURN_NOT_OK(buff->read(&cell_order, sizeof(uint8_t)));
cell_order_ = (Layout)cell_order;
// Load capacity
RETURN_NOT_OK(buff->read(&capacity_, sizeof(uint64_t)));
// Load coords filters
RETURN_NOT_OK(coords_filters_.deserialize(buff));
// Load offsets filters
RETURN_NOT_OK(cell_var_offsets_filters_.deserialize(buff));
// Load validity filters
if (version_ >= 7)
RETURN_NOT_OK(cell_validity_filters_.deserialize(buff));
// Load domain
domain_ = tdb_new(Domain);
RETURN_NOT_OK(domain_->deserialize(buff, version_));
// Load attributes
uint32_t attribute_num;
RETURN_NOT_OK(buff->read(&attribute_num, sizeof(uint32_t)));
for (uint32_t i = 0; i < attribute_num; ++i) {
auto&& [st_attr, attr]{Attribute::deserialize(buff, version_)};
if (!st_attr.ok()) {
return st_attr;
}
Attribute* attr_ptr = tdb_new(Attribute, std::move(attr.value()));
attributes_.emplace_back(attr_ptr);
attribute_map_[attr_ptr->name()] = attr_ptr;
}
// Create dimension map
auto dim_num = domain()->dim_num();
for (unsigned d = 0; d < dim_num; ++d) {
auto dim = dimension(d);
dim_map_[dim->name()] = dim;
}
// Initialize the rest of the object members
RETURN_NOT_OK(init());
// Success
return Status::Ok();
}
const Domain* ArraySchema::domain() const {
return domain_;
}
Status ArraySchema::init() {
// Perform check of all members
RETURN_NOT_OK(check());
// Initialize domain
RETURN_NOT_OK(domain_->init(cell_order_, tile_order_));
// Success
return Status::Ok();
}
Status ArraySchema::set_allows_dups(bool allows_dups) {
if (allows_dups && array_type_ == ArrayType::DENSE)
return LOG_STATUS(Status::ArraySchemaError(
"Dense arrays cannot allow coordinate duplicates"));
allows_dups_ = allows_dups;
return Status::Ok();
}
void ArraySchema::set_array_uri(const URI& array_uri) {
array_uri_ = array_uri;
}
void ArraySchema::set_capacity(uint64_t capacity) {
capacity_ = capacity;
}
Status ArraySchema::set_coords_filter_pipeline(const FilterPipeline* pipeline) {
coords_filters_ = *pipeline;
return Status::Ok();
}
Status ArraySchema::set_cell_var_offsets_filter_pipeline(
const FilterPipeline* pipeline) {
cell_var_offsets_filters_ = *pipeline;
return Status::Ok();
}
Status ArraySchema::set_cell_order(Layout cell_order) {
if (dense() && cell_order == Layout::HILBERT)
return LOG_STATUS(
Status::ArraySchemaError("Cannot set cell order; Hilbert order is only "
"applicable to sparse arrays"));
cell_order_ = cell_order;
return Status::Ok();
}
Status ArraySchema::set_cell_validity_filter_pipeline(
const FilterPipeline* pipeline) {
cell_validity_filters_ = *pipeline;
return Status::Ok();
}
Status ArraySchema::set_domain(Domain* domain) {
if (domain == nullptr)
return LOG_STATUS(
Status::ArraySchemaError("Cannot set domain; Input domain is nullptr"));
if (domain->dim_num() == 0)
return LOG_STATUS(Status::ArraySchemaError(
"Cannot set domain; Domain must contain at least one dimension"));
if (array_type_ == ArrayType::DENSE) {
if (!domain->all_dims_same_type())
return LOG_STATUS(
Status::ArraySchemaError("Cannot set domain; In dense arrays, all "
"dimensions must have the same datatype"));
auto type = domain->dimension(0)->type();
if (!datatype_is_integer(type) && !datatype_is_datetime(type) &&
!datatype_is_time(type)) {
return LOG_STATUS(Status::ArraySchemaError(
std::string("Cannot set domain; Dense arrays "
"do not support dimension datatype '") +
datatype_str(type) + "'"));
}
}
if (cell_order_ != Layout::HILBERT) {
RETURN_NOT_OK(domain->set_null_tile_extents_to_range());
}
// Set domain
tdb_delete(domain_);
domain_ = tdb_new(Domain, domain);
// Create dimension map
dim_map_.clear();
auto dim_num = domain_->dim_num();
for (unsigned d = 0; d < dim_num; ++d) {
auto dim = dimension(d);
dim_map_[dim->name()] = dim;
}
return Status::Ok();
}
Status ArraySchema::set_tile_order(Layout tile_order) {
if (tile_order == Layout::HILBERT)
return LOG_STATUS(Status::ArraySchemaError(
"Cannot set tile order; Hilbert order is not applicable to tiles"));
tile_order_ = tile_order;
return Status::Ok();
}
void ArraySchema::set_version(uint32_t version) {
version_ = version;
}
uint32_t ArraySchema::write_version() const {
return version_ < constants::back_compat_writes_min_format_version ?
constants::format_version :
version_;
}
uint32_t ArraySchema::version() const {
return version_;
}
Status ArraySchema::set_timestamp_range(
const std::pair<uint64_t, uint64_t>& timestamp_range) {
timestamp_range_ = timestamp_range;
return Status::Ok();
}
std::pair<uint64_t, uint64_t> ArraySchema::timestamp_range() const {
return std::pair<uint64_t, uint64_t>(
timestamp_range_.first, timestamp_range_.second);
}
uint64_t ArraySchema::timestamp_start() const {
return timestamp_range_.first;
}
URI ArraySchema::uri() {
std::lock_guard<std::mutex> lock(mtx_);
if (uri_.is_invalid()) {
generate_uri();
}
URI result = uri_;
return result;
}
void ArraySchema::set_uri(const URI& uri) {
std::lock_guard<std::mutex> lock(mtx_);
uri_ = uri;
name_ = uri_.last_path_part();
utils::parse::get_timestamp_range(uri_, ×tamp_range_);
}
Status ArraySchema::get_uri(URI* uri) {
if (uri_.is_invalid()) {
return LOG_STATUS(
Status::ArraySchemaError("Error in ArraySchema; invalid URI"));
}
*uri = uri_;
return Status::Ok();
}
std::string ArraySchema::name() {
std::lock_guard<std::mutex> lock(mtx_);
if (name_.empty()) {
generate_uri();
}
return name_;
}
Status ArraySchema::get_name(std::string* name) const {
if (name_.empty()) {
return LOG_STATUS(
Status::ArraySchemaError("Error in ArraySchema; Empty name"));
}
*name = name_;
return Status::Ok();
}
/* ****************************** */
/* PRIVATE METHODS */
/* ****************************** */
bool ArraySchema::check_attribute_dimension_names() const {
std::set<std::string> names;
auto dim_num = this->dim_num();
for (auto attr : attributes_)
names.insert(attr->name());
for (unsigned int i = 0; i < dim_num; ++i)
names.insert(domain_->dimension(i)->name());
return (names.size() == attributes_.size() + dim_num);
}
Status ArraySchema::check_double_delta_compressor() const {
// Check if coordinate filters have DOUBLE DELTA as a compressor
bool has_double_delta = false;
for (unsigned i = 0; i < coords_filters_.size(); ++i) {
if (coords_filters_.get_filter(i)->type() ==
FilterType::FILTER_DOUBLE_DELTA) {
has_double_delta = true;
break;
}
}
// Not applicable when DOUBLE DELTA no present in coord filters
if (!has_double_delta)
return Status::Ok();
// Error if any real dimension inherits the coord filters with DOUBLE DELTA.
// A dimension inherits the filters when it has no filters.
auto dim_num = domain_->dim_num();
for (unsigned d = 0; d < dim_num; ++d) {
auto dim = domain_->dimension(d);
const auto& dim_filters = dim->filters();
auto dim_type = dim->type();
if (datatype_is_real(dim_type) && dim_filters.empty())
return LOG_STATUS(
Status::ArraySchemaError("Real dimension cannot inherit coordinate "
"filters with DOUBLE DELTA compression"));
}
return Status::Ok();
}
void ArraySchema::clear() {
array_uri_ = URI();
uri_ = URI();
name_.clear();
array_type_ = ArrayType::DENSE;
capacity_ = constants::capacity;
cell_order_ = Layout::ROW_MAJOR;
tile_order_ = Layout::ROW_MAJOR;
for (auto& attr : attributes_)
tdb_delete(attr);
attributes_.clear();
tdb_delete(domain_);
domain_ = nullptr;
timestamp_range_ = std::make_pair(0, 0);
}
Status ArraySchema::generate_uri() {
std::string uuid;
RETURN_NOT_OK(uuid::generate_uuid(&uuid, false));
auto timestamp = utils::time::timestamp_now_ms();
timestamp_range_ = std::make_pair(timestamp, timestamp);
std::stringstream ss;
ss << "__" << timestamp_range_.first << "_" << timestamp_range_.second << "_"
<< uuid;
name_ = ss.str();
uri_ = array_uri_.join_path(constants::array_schema_folder_name)
.join_path(name_);
return Status::Ok();
}
} // namespace sm
} // namespace tiledb
|
//
// https://codeforces.com/problemset/problem/282/A
//
#include <iostream>
using namespace std;
int main() {
int n = 0;
cin >> n;
int result = 0;
for (int i = 0; i < n; ++i) {
string op;
cin >> op;
if (op.find("++") != string::npos) {
++result;
} else {
--result;
}
}
cout << result << "\n";
return 0;
}
|
//
// Copyright (c) 2011-2012 Krzysztof Jusiak (krzysztof at jusiak dot net)
//
// 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)
//
#include <gtest/gtest.h>
#include <boost/mpl/vector.hpp>
#include "QFsm/Back/Detail/Composite.hpp"
#include "QFsm/Front/Operations/Transition.hpp"
#include "QFsm/Front/Operations/None.hpp"
#include "Common/FsmStub.hpp"
#include "Common/Events.hpp"
namespace QFsm
{
using Front::Operations::Transition;
using Front::Operations::_;
using namespace Test::Common;
namespace Back
{
namespace Detail
{
namespace UT
{
TEST(Composite, NoCompletionTransitions)
{
//given
typedef FsmStub< boost::mpl::vector< Transition<_, e1, _> > > Fsm;
Fsm l_fsm;
//when & then
EXPECT_FALSE(Composite<Fsm>::execute(l_fsm, e1()));
}
TEST(Composite, InitStateFsmHandleTrue)
{
//given
typedef FsmStub< boost::mpl::vector< Transition<_, e1, _> > > CompositeFsm;
typedef FsmStub< boost::mpl::vector< Transition<CompositeFsm, e1, _> > > Fsm;
Fsm l_fsm;
//when
EXPECT_TRUE(Composite<Fsm>::execute(l_fsm, e1()));
//then
verifyProcessEvent< boost::mpl::vector1<e1>, CompositeFsm>();
}
TEST(Composite, InitStateFsmHandleFalse)
{
//given
typedef FsmStub< boost::mpl::vector< Transition<_, e2, _> > > CompositeFsm;
typedef FsmStub< boost::mpl::vector< Transition<CompositeFsm, e1, _> > > Fsm;
Fsm l_fsm;
//when
EXPECT_FALSE(Composite<Fsm>::execute(l_fsm, e1()));
//then
verifyProcessEvent< boost::mpl::vector<>, CompositeFsm>();
}
} // namespace UT
} // namespace Detail
} // namespace Back
} // namespace QFsm
|
#include "diablo.h"
DEVILUTION_BEGIN_NAMESPACE
BYTE L5dungeon[80][80];
BYTE L5dflags[DMAXX][DMAXY];
BOOL setloadflag;
int HR1;
int HR2;
int HR3;
int VR1;
int VR2;
int VR3;
BYTE *pSetPiece;
const ShadowStruct SPATS[37] = {
// clang-format off
// strig, s1, s2, s3, nv1, nv2, nv3
{ 7, 13, 0, 13, 144, 0, 142 },
{ 16, 13, 0, 13, 144, 0, 142 },
{ 15, 13, 0, 13, 145, 0, 142 },
{ 5, 13, 13, 13, 152, 140, 139 },
{ 5, 13, 1, 13, 143, 146, 139 },
{ 5, 13, 13, 2, 143, 140, 148 },
{ 5, 0, 1, 2, 0, 146, 148 },
{ 5, 13, 11, 13, 143, 147, 139 },
{ 5, 13, 13, 12, 143, 140, 149 },
{ 5, 13, 11, 12, 150, 147, 149 },
{ 5, 13, 1, 12, 143, 146, 149 },
{ 5, 13, 11, 2, 143, 147, 148 },
{ 9, 13, 13, 13, 144, 140, 142 },
{ 9, 13, 1, 13, 144, 146, 142 },
{ 9, 13, 11, 13, 151, 147, 142 },
{ 8, 13, 0, 13, 144, 0, 139 },
{ 8, 13, 0, 12, 143, 0, 149 },
{ 8, 0, 0, 2, 0, 0, 148 },
{ 11, 0, 0, 13, 0, 0, 139 },
{ 11, 13, 0, 13, 139, 0, 139 },
{ 11, 2, 0, 13, 148, 0, 139 },
{ 11, 12, 0, 13, 149, 0, 139 },
{ 11, 13, 11, 12, 139, 0, 149 },
{ 14, 0, 0, 13, 0, 0, 139 },
{ 14, 13, 0, 13, 139, 0, 139 },
{ 14, 2, 0, 13, 148, 0, 139 },
{ 14, 12, 0, 13, 149, 0, 139 },
{ 14, 13, 11, 12, 139, 0, 149 },
{ 10, 0, 13, 0, 0, 140, 0 },
{ 10, 13, 13, 0, 140, 140, 0 },
{ 10, 0, 1, 0, 0, 146, 0 },
{ 10, 13, 11, 0, 140, 147, 0 },
{ 12, 0, 13, 0, 0, 140, 0 },
{ 12, 13, 13, 0, 140, 140, 0 },
{ 12, 0, 1, 0, 0, 146, 0 },
{ 12, 13, 11, 0, 140, 147, 0 },
{ 3, 13, 11, 12, 150, 0, 0 }
// clang-format on
};
const BYTE BSTYPES[206] = {
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12, 13, 14, 15, 16, 17, 0, 0,
0, 0, 0, 0, 0, 1, 2, 10, 4, 5,
6, 7, 8, 9, 10, 11, 12, 14, 5, 14,
10, 4, 14, 4, 5, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
2, 3, 4, 1, 6, 7, 16, 17, 2, 1,
1, 2, 2, 1, 1, 2, 2, 2, 2, 2,
1, 1, 11, 1, 13, 13, 13, 1, 2, 1,
2, 1, 2, 1, 2, 2, 2, 2, 12, 0,
0, 11, 1, 11, 1, 13, 0, 0, 0, 0,
0, 0, 0, 13, 13, 13, 13, 13, 13, 13,
13, 13, 13, 13, 13, 13, 1, 11, 2, 12,
13, 13, 13, 12, 2, 1, 2, 2, 4, 14,
4, 10, 13, 13, 4, 4, 1, 1, 4, 2,
2, 13, 13, 13, 13, 25, 26, 28, 30, 31,
41, 43, 40, 41, 42, 43, 25, 41, 43, 28,
28, 1, 2, 25, 26, 22, 22, 25, 26, 0,
0, 0, 0, 0, 0, 0
};
const BYTE L5BTYPES[206] = {
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12, 13, 14, 15, 16, 17, 0, 0,
0, 0, 0, 0, 0, 25, 26, 0, 28, 0,
30, 31, 0, 0, 0, 0, 0, 0, 0, 0,
40, 41, 42, 43, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 79,
80, 0, 82, 0, 0, 0, 0, 0, 0, 79,
0, 80, 0, 0, 79, 80, 0, 2, 2, 2,
1, 1, 11, 25, 13, 13, 13, 1, 2, 1,
2, 1, 2, 1, 2, 2, 2, 2, 12, 0,
0, 11, 1, 11, 1, 13, 0, 0, 0, 0,
0, 0, 0, 13, 13, 13, 13, 13, 13, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0
};
const BYTE STAIRSUP[] = { 4, 4, 13, 13, 13, 13, 2, 2, 2, 2, 13, 13, 13, 13, 13, 13, 13, 13, 0, 66, 6, 0, 63, 64, 65, 0, 0, 67, 68, 0, 0, 0, 0, 0 };
const BYTE L5STAIRSUP[] = { 4, 4, 22, 22, 22, 22, 2, 2, 2, 2, 13, 13, 13, 13, 13, 13, 13, 13, 0, 66, 23, 0, 63, 64, 65, 0, 0, 67, 68, 0, 0, 0, 0, 0 };
const BYTE STAIRSDOWN[] = { 4, 3, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 62, 57, 58, 0, 61, 59, 60, 0, 0, 0, 0, 0 };
const BYTE LAMPS[] = { 2, 2, 13, 0, 13, 13, 129, 0, 130, 128 };
const BYTE PWATERIN[] = { 6, 6, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 0, 0, 0, 0, 0, 0, 0, 202, 200, 200, 84, 0, 0, 199, 203, 203, 83, 0, 0, 85, 206, 80, 81, 0, 0, 0, 134, 135, 0, 0, 0, 0, 0, 0, 0, 0 };
/* data */
BYTE L5ConvTbl[16] = { 22, 13, 1, 13, 2, 13, 13, 13, 4, 13, 1, 13, 2, 13, 16, 13 };
void DRLG_Init_Globals()
{
char c;
memset(dFlags, 0, sizeof(dFlags));
memset(dPlayer, 0, sizeof(dPlayer));
memset(dMonster, 0, sizeof(dMonster));
memset(dDead, 0, sizeof(dDead));
memset(dObject, 0, sizeof(dObject));
memset(dItem, 0, sizeof(dItem));
memset(dMissile, 0, sizeof(dMissile));
memset(dArch, 0, sizeof(dArch));
if (!lightflag)
c = (light4flag) ? 3 : 15;
else
c = 0;
memset(dLight, c, sizeof(dLight));
}
#ifndef SPAWN
void LoadL1Dungeon(char *sFileName, int vx, int vy)
{
int i, j, rw, rh;
BYTE *pLevelMap, *lm;
dminx = 16;
dminy = 16;
dmaxx = 96;
dmaxy = 96;
DRLG_InitTrans();
pLevelMap = LoadFileInMem(sFileName, NULL);
for (j = 0; j < DMAXY; j++) {
for (i = 0; i < DMAXX; i++) {
dungeon[i][j] = 22;
L5dflags[i][j] = 0;
}
}
lm = pLevelMap;
rw = *lm;
lm += 2;
rh = *lm;
lm += 2;
for (j = 0; j < rh; j++) {
for (i = 0; i < rw; i++) {
if (*lm != 0) {
dungeon[i][j] = *lm;
L5dflags[i][j] |= DLRG_PROTECTED;
} else {
dungeon[i][j] = 13;
}
lm += 2;
}
}
DRLG_L1Floor();
ViewX = vx;
ViewY = vy;
DRLG_L1Pass3();
DRLG_Init_Globals();
DRLG_InitL1Vals();
SetMapMonsters(pLevelMap, 0, 0);
SetMapObjects(pLevelMap, 0, 0);
mem_free_dbg(pLevelMap);
}
#endif
void DRLG_L1Floor()
{
int i, j;
LONG rv;
for (j = 0; j < DMAXY; j++) {
for (i = 0; i < DMAXX; i++) {
if (L5dflags[i][j] == 0 && dungeon[i][j] == 13) {
rv = random(0, 3);
if (rv == 1)
dungeon[i][j] = 162;
if (rv == 2)
dungeon[i][j] = 163;
}
}
}
}
void DRLG_L1Pass3()
{
int i, j, xx, yy;
long v1, v2, v3, v4, lv;
lv = 22 - 1;
v1 = *((WORD *)&pMegaTiles[lv * 8]) + 1;
v2 = *((WORD *)&pMegaTiles[lv * 8] + 1) + 1;
v3 = *((WORD *)&pMegaTiles[lv * 8] + 2) + 1;
v4 = *((WORD *)&pMegaTiles[lv * 8] + 3) + 1;
for (j = 0; j < MAXDUNY; j += 2)
{
for (i = 0; i < MAXDUNX; i += 2) {
dPiece[i][j] = v1;
dPiece[i + 1][j] = v2;
dPiece[i][j + 1] = v3;
dPiece[i + 1][j + 1] = v4;
}
}
yy = 16;
for (j = 0; j < DMAXY; j++) {
xx = 16;
for (i = 0; i < DMAXX; i++) {
lv = dungeon[i][j] - 1;
/// ASSERT: assert(lv >= 0);
v1 = *((WORD *)&pMegaTiles[lv * 8]) + 1;
v2 = *((WORD *)&pMegaTiles[lv * 8] + 1) + 1;
v3 = *((WORD *)&pMegaTiles[lv * 8] + 2) + 1;
v4 = *((WORD *)&pMegaTiles[lv * 8] + 3) + 1;
dPiece[xx][yy] = v1;
dPiece[xx + 1][yy] = v2;
dPiece[xx][yy + 1] = v3;
dPiece[xx + 1][yy + 1] = v4;
xx += 2;
}
yy += 2;
}
}
void DRLG_InitL1Vals()
{
int i, j, pc;
for (j = 0; j < MAXDUNY; j++) {
for (i = 0; i < MAXDUNX; i++) {
if (dPiece[i][j] == 12) {
pc = 1;
} else if (dPiece[i][j] == 11) {
pc = 2;
} else if (dPiece[i][j] == 71) {
pc = 1;
} else if (dPiece[i][j] == 259) {
pc = 5;
} else if (dPiece[i][j] == 249) {
pc = 2;
} else if (dPiece[i][j] == 325) {
pc = 2;
} else if (dPiece[i][j] == 321) {
pc = 1;
} else if (dPiece[i][j] == 255) {
pc = 4;
} else if (dPiece[i][j] == 211) {
pc = 1;
} else if (dPiece[i][j] == 344) {
pc = 2;
} else if (dPiece[i][j] == 341) {
pc = 1;
} else if (dPiece[i][j] == 331) {
pc = 2;
} else if (dPiece[i][j] == 418) {
pc = 1;
} else if (dPiece[i][j] == 421) {
pc = 2;
} else {
continue;
}
dArch[i][j] = pc;
}
}
}
#ifndef SPAWN
void LoadPreL1Dungeon(char *sFileName, int vx, int vy)
{
int i, j, rw, rh;
BYTE *pLevelMap, *lm;
dminx = 16;
dminy = 16;
dmaxx = 96;
dmaxy = 96;
pLevelMap = LoadFileInMem(sFileName, NULL);
for (j = 0; j < DMAXY; j++) {
for (i = 0; i < DMAXX; i++) {
dungeon[i][j] = 22;
L5dflags[i][j] = 0;
}
}
lm = pLevelMap;
rw = *lm;
lm += 2;
rh = *lm;
lm += 2;
for (j = 0; j < rh; j++) {
for (i = 0; i < rw; i++) {
if (*lm != 0) {
dungeon[i][j] = *lm;
L5dflags[i][j] |= DLRG_PROTECTED;
} else {
dungeon[i][j] = 13;
}
lm += 2;
}
}
DRLG_L1Floor();
for (j = 0; j < DMAXY; j++) {
for (i = 0; i < DMAXX; i++) {
pdungeon[i][j] = dungeon[i][j];
}
}
mem_free_dbg(pLevelMap);
}
#endif
void CreateL5Dungeon(DWORD rseed, int entry)
{
SetRndSeed(rseed);
dminx = 16;
dminy = 16;
dmaxx = 96;
dmaxy = 96;
DRLG_InitTrans();
DRLG_InitSetPC();
DRLG_LoadL1SP();
DRLG_L5(entry);
DRLG_L1Pass3();
DRLG_FreeL1SP();
DRLG_InitL1Vals();
DRLG_SetPC();
}
void DRLG_LoadL1SP()
{
setloadflag = FALSE;
if (QuestStatus(QTYPE_BUTCH)) {
pSetPiece = LoadFileInMem("Levels\\L1Data\\rnd6.DUN", NULL);
setloadflag = TRUE;
}
if (QuestStatus(QTYPE_KING) && gbMaxPlayers == 1) {
pSetPiece = LoadFileInMem("Levels\\L1Data\\SKngDO.DUN", NULL);
setloadflag = TRUE;
}
if (QuestStatus(QTYPE_BOL)) {
pSetPiece = LoadFileInMem("Levels\\L1Data\\Banner2.DUN", NULL);
setloadflag = TRUE;
}
}
void DRLG_FreeL1SP()
{
MemFreeDbg(pSetPiece);
}
void DRLG_L5(int entry)
{
int i, j;
LONG minarea;
BOOL doneflag;
switch (currlevel) {
case 1:
minarea = 533;
break;
case 2:
minarea = 693;
break;
case 3:
case 4:
minarea = 761;
break;
}
do {
DRLG_InitTrans();
do {
InitL5Dungeon();
L5firstRoom();
} while (L5GetArea() < minarea);
L5makeDungeon();
L5makeDmt();
L5FillChambers();
L5tileFix();
L5AddWall();
L5ClearFlags();
DRLG_L5FloodTVal();
doneflag = TRUE;
if (QuestStatus(QTYPE_PW)) {
if (entry == 0) {
if (DRLG_PlaceMiniSet(PWATERIN, 1, 1, 0, 0, 1, -1, 0) < 0)
doneflag = FALSE;
} else {
if (DRLG_PlaceMiniSet(PWATERIN, 1, 1, 0, 0, 0, -1, 0) < 0)
doneflag = FALSE;
ViewY--;
}
}
if (QuestStatus(QTYPE_BOL)) {
if (entry == 0) {
if (DRLG_PlaceMiniSet(STAIRSUP, 1, 1, 0, 0, 1, -1, 0) < 0)
doneflag = FALSE;
} else {
if (DRLG_PlaceMiniSet(STAIRSUP, 1, 1, 0, 0, 0, -1, 0) < 0)
doneflag = FALSE;
if (entry == 1) {
ViewX = 2 * setpc_x + 20;
ViewY = 2 * setpc_y + 28;
} else {
ViewY--;
}
}
} else if (entry == 0) {
if (DRLG_PlaceMiniSet(L5STAIRSUP, 1, 1, 0, 0, 1, -1, 0) < 0)
doneflag = FALSE;
else if (DRLG_PlaceMiniSet(STAIRSDOWN, 1, 1, 0, 0, 0, -1, 1) < 0)
doneflag = FALSE;
} else {
if (DRLG_PlaceMiniSet(L5STAIRSUP, 1, 1, 0, 0, 0, -1, 0) < 0)
doneflag = FALSE;
else if (DRLG_PlaceMiniSet(STAIRSDOWN, 1, 1, 0, 0, 1, -1, 1) < 0)
doneflag = FALSE;
ViewY--;
}
} while (doneflag == FALSE);
for (j = 0; j < DMAXY; j++) {
for (i = 0; i < DMAXX; i++) {
if (dungeon[i][j] == 64) {
int xx = 2 * i + 16; /* todo: fix loop */
int yy = 2 * j + 16;
DRLG_CopyTrans(xx, yy + 1, xx, yy);
DRLG_CopyTrans(xx + 1, yy + 1, xx + 1, yy);
}
}
}
DRLG_L5TransFix();
DRLG_L5DirtFix();
DRLG_L5CornerFix();
for (j = 0; j < DMAXY; j++) {
for (i = 0; i < DMAXX; i++) {
if (L5dflags[i][j] & 0x7F)
DRLG_PlaceDoor(i, j);
}
}
DRLG_L5Subs();
DRLG_L1Shadows();
DRLG_PlaceMiniSet(LAMPS, 5, 10, 0, 0, 0, -1, 4);
DRLG_L1Floor();
for (j = 0; j < DMAXY; j++) {
for (i = 0; i < DMAXX; i++) {
pdungeon[i][j] = dungeon[i][j];
}
}
DRLG_Init_Globals();
DRLG_CheckQuests(setpc_x, setpc_y);
}
void DRLG_PlaceDoor(int x, int y)
{
if ((L5dflags[x][y] & DLRG_PROTECTED) == 0) {
BYTE df = L5dflags[x][y] & 0x7F;
BYTE c = dungeon[x][y];
if (df == 1) {
if (y != 1 && c == 2)
dungeon[x][y] = 26;
if (y != 1 && c == 7)
dungeon[x][y] = 31;
if (y != 1 && c == 14)
dungeon[x][y] = 42;
if (y != 1 && c == 4)
dungeon[x][y] = 43;
if (x != 1 && c == 1)
dungeon[x][y] = 25;
if (x != 1 && c == 10)
dungeon[x][y] = 40;
if (x != 1 && c == 6)
dungeon[x][y] = 30;
}
if (df == 2) {
if (x != 1 && c == 1)
dungeon[x][y] = 25;
if (x != 1 && c == 6)
dungeon[x][y] = 30;
if (x != 1 && c == 10)
dungeon[x][y] = 40;
if (x != 1 && c == 4)
dungeon[x][y] = 41;
if (y != 1 && c == 2)
dungeon[x][y] = 26;
if (y != 1 && c == 14)
dungeon[x][y] = 42;
if (y != 1 && c == 7)
dungeon[x][y] = 31;
}
if (df == 3) {
if (x != 1 && y != 1 && c == 4)
dungeon[x][y] = 28;
if (x != 1 && c == 10)
dungeon[x][y] = 40;
if (y != 1 && c == 14)
dungeon[x][y] = 42;
if (y != 1 && c == 2)
dungeon[x][y] = 26;
if (x != 1 && c == 1)
dungeon[x][y] = 25;
if (y != 1 && c == 7)
dungeon[x][y] = 31;
if (x != 1 && c == 6)
dungeon[x][y] = 30;
}
}
L5dflags[x][y] = DLRG_PROTECTED;
}
void DRLG_L1Shadows()
{
int x, y, i;
BYTE sd[2][2];
BYTE tnv3;
BOOL patflag;
for (y = 1; y < DMAXY; y++) {
for (x = 1; x < DMAXX; x++) {
sd[0][0] = BSTYPES[dungeon[x][y]];
sd[1][0] = BSTYPES[dungeon[x - 1][y]];
sd[0][1] = BSTYPES[dungeon[x][y - 1]];
sd[1][1] = BSTYPES[dungeon[x - 1][y - 1]];
for (i = 0; i < 37; i++) {
if (SPATS[i].strig == sd[0][0]) {
patflag = TRUE;
if (SPATS[i].s1 && SPATS[i].s1 != sd[1][1])
patflag = FALSE;
if (SPATS[i].s2 && SPATS[i].s2 != sd[0][1])
patflag = FALSE;
if (SPATS[i].s3 && SPATS[i].s3 != sd[1][0])
patflag = FALSE;
if (patflag == TRUE) {
if (SPATS[i].nv1 && !L5dflags[x - 1][y - 1])
dungeon[x - 1][y - 1] = SPATS[i].nv1;
if (SPATS[i].nv2 && !L5dflags[x][y - 1])
dungeon[x][y - 1] = SPATS[i].nv2;
if (SPATS[i].nv3) {
if (!L5dflags[x - 1][y])
dungeon[x - 1][y] = SPATS[i].nv3;
}
}
}
}
}
}
for (y = 1; y < DMAXY; y++) {
for (x = 1; x < DMAXX; x++) {
if (dungeon[x - 1][y] == 139 && !L5dflags[x - 1][y]) {
tnv3 = 139;
if (dungeon[x][y] == 29)
tnv3 = 141;
if (dungeon[x][y] == 32)
tnv3 = 141;
if (dungeon[x][y] == 35)
tnv3 = 141;
if (dungeon[x][y] == 37)
tnv3 = 141;
if (dungeon[x][y] == 38)
tnv3 = 141;
if (dungeon[x][y] == 39)
tnv3 = 141;
dungeon[x - 1][y] = tnv3;
}
if (dungeon[x - 1][y] == 149 && !L5dflags[x - 1][y]) {
tnv3 = 149;
if (dungeon[x][y] == 29)
tnv3 = 153;
if (dungeon[x][y] == 32)
tnv3 = 153;
if (dungeon[x][y] == 35)
tnv3 = 153;
if (dungeon[x][y] == 37)
tnv3 = 153;
if (dungeon[x][y] == 38)
tnv3 = 153;
if (dungeon[x][y] == 39)
tnv3 = 153;
dungeon[x - 1][y] = tnv3;
}
if (dungeon[x - 1][y] == 148 && !L5dflags[x - 1][y]) {
tnv3 = 148;
if (dungeon[x][y] == 29)
tnv3 = 154;
if (dungeon[x][y] == 32)
tnv3 = 154;
if (dungeon[x][y] == 35)
tnv3 = 154;
if (dungeon[x][y] == 37)
tnv3 = 154;
if (dungeon[x][y] == 38)
tnv3 = 154;
if (dungeon[x][y] == 39)
tnv3 = 154;
dungeon[x - 1][y] = tnv3;
}
}
}
}
int DRLG_PlaceMiniSet(const BYTE *miniset, int tmin, int tmax, int cx, int cy, BOOL setview, int noquad, int ldir)
{
int xx, yy, sx, sy;
int ii, i, t, found;
int numt;
BOOL abort;
int sw = miniset[0];
int sh = miniset[1];
if (tmax - tmin == 0)
numt = 1;
else
numt = random(0, tmax - tmin) + tmin;
for (i = 0; i < numt; i++) {
sx = random(0, DMAXX - sw);
sy = random(0, DMAXY - sh);
abort = FALSE;
found = 0;
while (abort == FALSE) {
abort = TRUE;
if (cx != -1 && sx >= cx - sw && sx <= cx + 12) {
sx++;
abort = FALSE;
}
if (cy != -1 && sy >= cy - sh && sy <= cy + 12) {
sy++;
abort = FALSE;
}
switch (noquad) {
case 0:
if (sx < cx && sy < cy)
abort = FALSE;
break;
case 1:
if (sx > cx && sy < cy)
abort = FALSE;
break;
case 2:
if (sx < cx && sy > cy)
abort = FALSE;
break;
case 3:
if (sx > cx && sy > cy)
abort = FALSE;
break;
}
ii = 2;
for (yy = 0; yy < sh && abort == TRUE; yy++) {
for (xx = 0; xx < sw && abort == TRUE; xx++) {
if (miniset[ii] && dungeon[xx + sx][sy + yy] != miniset[ii])
abort = FALSE;
if (L5dflags[xx + sx][sy + yy])
abort = FALSE;
ii++;
}
}
if (abort == FALSE) {
if (++sx == DMAXX - sw) {
sx = 0;
if (++sy == DMAXY - sh)
sy = 0;
}
if (++found > 4000)
return -1;
}
}
ii = sw * sh + 2;
for (yy = 0; yy < sh; yy++) {
for (xx = 0; xx < sw; xx++) {
if (miniset[ii])
dungeon[xx + sx][sy + yy] = miniset[ii];
ii++;
}
}
}
if (miniset == PWATERIN) {
t = TransVal;
TransVal = 0;
DRLG_MRectTrans(sx, sy + 2, sx + 5, sy + 4);
TransVal = t;
quests[QTYPE_PW]._qtx = 2 * sx + 21;
quests[QTYPE_PW]._qty = 2 * sy + 22;
}
if (setview == TRUE) {
ViewX = 2 * sx + 19;
ViewY = 2 * sy + 20;
}
if (ldir == 0) {
LvlViewX = 2 * sx + 19;
LvlViewY = 2 * sy + 20;
}
if (sx < cx && sy < cy)
return 0;
if (sx > cx && sy < cy)
return 1;
if (sx < cx && sy > cy)
return 2;
else
return 3;
}
void InitL5Dungeon()
{
int i, j;
for (j = 0; j < DMAXY; j++) {
for (i = 0; i < DMAXX; i++) {
dungeon[i][j] = 0;
L5dflags[i][j] = 0;
}
}
}
void L5ClearFlags()
{
int i, j;
for (j = 0; j < DMAXY; j++) {
for (i = 0; i < DMAXX; i++) {
L5dflags[i][j] &= 0xBF;
}
}
}
void L5firstRoom()
{
int ys, ye, y;
int xs, xe, x;
if (random(0, 2) == 0) {
ys = 1;
ye = DMAXY - 1;
VR1 = random(0, 2);
VR2 = random(0, 2);
VR3 = random(0, 2);
if (VR1 + VR3 <= 1)
VR2 = 1;
if (VR1)
L5drawRoom(15, 1, 10, 10);
else
ys = 18;
if (VR2)
L5drawRoom(15, 15, 10, 10);
if (VR3)
L5drawRoom(15, 29, 10, 10);
else
ye = 22;
for (y = ys; y < ye; y++) {
dungeon[17][y] = 1;
dungeon[18][y] = 1;
dungeon[19][y] = 1;
dungeon[20][y] = 1;
dungeon[21][y] = 1;
dungeon[22][y] = 1;
}
if (VR1)
L5roomGen(15, 1, 10, 10, 0);
if (VR2)
L5roomGen(15, 15, 10, 10, 0);
if (VR3)
L5roomGen(15, 29, 10, 10, 0);
HR3 = 0;
HR2 = 0;
HR1 = 0;
} else {
xs = 1;
xe = DMAXX - 1;
HR1 = random(0, 2);
HR2 = random(0, 2);
HR3 = random(0, 2);
if (HR1 + HR3 <= 1)
HR2 = 1;
if (HR1)
L5drawRoom(1, 15, 10, 10);
else
xs = 18;
if (HR2)
L5drawRoom(15, 15, 10, 10);
if (HR3)
L5drawRoom(29, 15, 10, 10);
else
xe = 22;
for (x = xs; x < xe; x++) {
dungeon[x][17] = 1;
dungeon[x][18] = 1;
dungeon[x][19] = 1;
dungeon[x][20] = 1;
dungeon[x][21] = 1;
dungeon[x][22] = 1;
}
if (HR1)
L5roomGen(1, 15, 10, 10, 1);
if (HR2)
L5roomGen(15, 15, 10, 10, 1);
if (HR3)
L5roomGen(29, 15, 10, 10, 1);
VR3 = 0;
VR2 = 0;
VR1 = 0;
}
}
void L5drawRoom(int x, int y, int w, int h)
{
int i, j;
for (j = 0; j < h; j++) {
for (i = 0; i < w; i++) {
dungeon[x + i][y + j] = 1;
}
}
}
void L5roomGen(int x, int y, int w, int h, int dir)
{
int num, dirProb;
BOOL ran, ran2;
int width, height, rx, ry, ry2;
int cw, ch, cx1, cy1, cx2;
dirProb = random(0, 4);
switch (dir == 1 ? dirProb != 0 : dirProb == 0) {
case FALSE:
num = 0;
do {
cw = (random(0, 5) + 2) & 0xFFFFFFFE;
ch = (random(0, 5) + 2) & 0xFFFFFFFE;
cy1 = h / 2 + y - ch / 2;
cx1 = x - cw;
ran = L5checkRoom(cx1 - 1, cy1 - 1, ch + 2, cw + 1); /// BUGFIX: swap args 3 and 4 ("ch+2" and "cw+1")
num++;
} while (ran == FALSE && num < 20);
if (ran == TRUE)
L5drawRoom(cx1, cy1, cw, ch);
cx2 = x + w;
ran2 = L5checkRoom(cx2, cy1 - 1, cw + 1, ch + 2);
if (ran2 == TRUE)
L5drawRoom(cx2, cy1, cw, ch);
if (ran == TRUE)
L5roomGen(cx1, cy1, cw, ch, 1);
if (ran2 == TRUE)
L5roomGen(cx2, cy1, cw, ch, 1);
break;
case TRUE:
num = 0;
do {
width = (random(0, 5) + 2) & 0xFFFFFFFE;
height = (random(0, 5) + 2) & 0xFFFFFFFE;
rx = w / 2 + x - width / 2;
ry = y - height;
ran = L5checkRoom(rx - 1, ry - 1, width + 2, height + 1);
num++;
} while (ran == FALSE && num < 20);
if (ran == TRUE)
L5drawRoom(rx, ry, width, height);
ry2 = y + h;
ran2 = L5checkRoom(rx - 1, ry2, width + 2, height + 1);
if (ran2 == TRUE)
L5drawRoom(rx, ry2, width, height);
if (ran == TRUE)
L5roomGen(rx, ry, width, height, 0);
if (ran2 == TRUE)
L5roomGen(rx, ry2, width, height, 0);
break;
}
}
BOOL L5checkRoom(int x, int y, int width, int height)
{
int i, j;
for (j = 0; j < height; j++) {
for (i = 0; i < width; i++) {
if (i + x < 0 || i + x >= DMAXX || j + y < 0 || j + y >= DMAXY)
return FALSE;
if (dungeon[i + x][j + y])
return FALSE;
}
}
return TRUE;
}
int L5GetArea()
{
int i, j;
int rv;
rv = 0;
for (j = 0; j < DMAXY; j++) {
for (i = 0; i < DMAXX; i++) {
if (dungeon[i][j] == 1)
rv++;
}
}
return rv;
}
void L5makeDungeon()
{
int i, j;
int i_2, j_2;
for (j = 0; j < DMAXY; j++) {
for (i = 0; i < DMAXX; i++) {
j_2 = j << 1;
i_2 = i << 1;
L5dungeon[i_2][j_2] = dungeon[i][j];
L5dungeon[i_2][j_2 + 1] = dungeon[i][j];
L5dungeon[i_2 + 1][j_2] = dungeon[i][j];
L5dungeon[i_2 + 1][j_2 + 1] = dungeon[i][j];
}
}
}
void L5makeDmt()
{
int i, j, dmtx, dmty;
for (j = 0; j < DMAXY; j++) {
for (i = 0; i < DMAXX; i++) {
dungeon[i][j] = 22;
}
}
for (j = 0, dmty = 1; dmty <= 77; j++, dmty += 2) {
for (i = 0, dmtx = 1; dmtx <= 77; i++, dmtx += 2) {
int val = L5dungeon[dmtx + 1][dmty + 1];
val = 2 * val + L5dungeon[dmtx][dmty + 1];
val = 2 * val + L5dungeon[dmtx + 1][dmty];
val = 2 * val + L5dungeon[dmtx][dmty];
dungeon[i][j] = L5ConvTbl[val];
}
}
}
void L5AddWall()
{
int i, j, x, y;
for (j = 0; j < DMAXY; j++) {
for (i = 0; i < DMAXX; i++) {
if (!L5dflags[i][j]) {
if (dungeon[i][j] == 3 && random(0, 100) < 100) {
x = L5HWallOk(i, j);
if (x != -1)
L5HorizWall(i, j, 2, x);
}
if (dungeon[i][j] == 3 && random(0, 100) < 100) {
y = L5VWallOk(i, j);
if (y != -1)
L5VertWall(i, j, 1, y);
}
if (dungeon[i][j] == 6 && random(0, 100) < 100) {
x = L5HWallOk(i, j);
if (x != -1)
L5HorizWall(i, j, 4, x);
}
if (dungeon[i][j] == 7 && random(0, 100) < 100) {
y = L5VWallOk(i, j);
if (y != -1)
L5VertWall(i, j, 4, y);
}
if (dungeon[i][j] == 2 && random(0, 100) < 100) {
x = L5HWallOk(i, j);
if (x != -1)
L5HorizWall(i, j, 2, x);
}
if (dungeon[i][j] == 1 && random(0, 100) < 100) {
y = L5VWallOk(i, j);
if (y != -1)
L5VertWall(i, j, 1, y);
}
}
}
}
}
int L5HWallOk(int i, int j)
{
int x;
BOOL wallok;
for (x = 1; dungeon[i + x][j] == 13; x++) {
if (dungeon[i + x][j - 1] != 13 || dungeon[i + x][j + 1] != 13 || L5dflags[i + x][j])
break;
}
wallok = FALSE;
if (dungeon[i + x][j] >= 3 && dungeon[i + x][j] <= 7)
wallok = TRUE;
if (dungeon[i + x][j] >= 16 && dungeon[i + x][j] <= 24)
wallok = TRUE;
if (dungeon[i + x][j] == 22)
wallok = FALSE;
if (x == 1)
wallok = FALSE;
if (wallok)
return x;
else
return -1;
}
int L5VWallOk(int i, int j)
{
int y;
BOOL wallok;
for (y = 1; dungeon[i][j + y] == 13; y++) {
if (dungeon[i - 1][j + y] != 13 || dungeon[i + 1][j + y] != 13 || L5dflags[i][j + y])
break;
}
wallok = FALSE;
if (dungeon[i][j + y] >= 3 && dungeon[i][j + y] <= 7)
wallok = TRUE;
if (dungeon[i][j + y] >= 16 && dungeon[i][j + y] <= 24)
wallok = TRUE;
if (dungeon[i][j + y] == 22)
wallok = FALSE;
if (y == 1)
wallok = FALSE;
if (wallok)
return y;
else
return -1;
}
void L5HorizWall(int i, int j, char p, int dx)
{
int xx;
char wt, dt;
switch (random(0, 4)) {
case 0:
case 1:
dt = 2;
break;
case 2:
dt = 12;
if (p == 2)
p = 12;
if (p == 4)
p = 10;
break;
case 3:
dt = 36;
if (p == 2)
p = 36;
if (p == 4)
p = 27;
break;
}
if (random(0, 6) == 5)
wt = 12;
else
wt = 26;
if (dt == 12)
wt = 12;
dungeon[i][j] = p;
for (xx = 1; xx < dx; xx++) {
dungeon[i + xx][j] = dt;
}
xx = random(0, dx - 1) + 1;
if (wt == 12) {
dungeon[i + xx][j] = wt;
} else {
dungeon[i + xx][j] = 2;
L5dflags[i + xx][j] |= DLRG_HDOOR;
}
}
void L5VertWall(int i, int j, char p, int dy)
{
int yy;
char wt, dt;
switch (random(0, 4)) {
case 0:
case 1:
dt = 1;
break;
case 2:
dt = 11;
if (p == 1)
p = 11;
if (p == 4)
p = 14;
break;
case 3:
dt = 35;
if (p == 1)
p = 35;
if (p == 4)
p = 37;
break;
}
if (random(0, 6) == 5)
wt = 11;
else
wt = 25;
if (dt == 11)
wt = 11;
dungeon[i][j] = p;
for (yy = 1; yy < dy; yy++) {
dungeon[i][j + yy] = dt;
}
yy = random(0, dy - 1) + 1;
if (wt == 11) {
dungeon[i][j + yy] = wt;
} else {
dungeon[i][j + yy] = 1;
L5dflags[i][j + yy] |= DLRG_VDOOR;
}
}
void L5tileFix()
{
int i, j;
for (j = 0; j < DMAXY; j++) {
for (i = 0; i < DMAXX; i++) {
if (dungeon[i][j] == 2 && dungeon[i + 1][j] == 22)
dungeon[i + 1][j] = 23;
if (dungeon[i][j] == 13 && dungeon[i + 1][j] == 22)
dungeon[i + 1][j] = 18;
if (dungeon[i][j] == 13 && dungeon[i + 1][j] == 2)
dungeon[i + 1][j] = 7;
if (dungeon[i][j] == 6 && dungeon[i + 1][j] == 22)
dungeon[i + 1][j] = 24;
if (dungeon[i][j] == 1 && dungeon[i][j + 1] == 22)
dungeon[i][j + 1] = 24;
if (dungeon[i][j] == 13 && dungeon[i][j + 1] == 1)
dungeon[i][j + 1] = 6;
if (dungeon[i][j] == 13 && dungeon[i][j + 1] == 22)
dungeon[i][j + 1] = 19;
}
}
for (j = 0; j < DMAXY; j++) {
for (i = 0; i < DMAXX; i++) {
if (dungeon[i][j] == 13 && dungeon[i + 1][j] == 19)
dungeon[i + 1][j] = 21;
if (dungeon[i][j] == 13 && dungeon[i + 1][j] == 22)
dungeon[i + 1][j] = 20;
if (dungeon[i][j] == 7 && dungeon[i + 1][j] == 22)
dungeon[i + 1][j] = 23;
if (dungeon[i][j] == 13 && dungeon[i + 1][j] == 24)
dungeon[i + 1][j] = 21;
if (dungeon[i][j] == 19 && dungeon[i + 1][j] == 22)
dungeon[i + 1][j] = 20;
if (dungeon[i][j] == 2 && dungeon[i + 1][j] == 19)
dungeon[i + 1][j] = 21;
if (dungeon[i][j] == 19 && dungeon[i + 1][j] == 1)
dungeon[i + 1][j] = 6;
if (dungeon[i][j] == 7 && dungeon[i + 1][j] == 19)
dungeon[i + 1][j] = 21;
if (dungeon[i][j] == 2 && dungeon[i + 1][j] == 1)
dungeon[i + 1][j] = 6;
if (dungeon[i][j] == 3 && dungeon[i + 1][j] == 22)
dungeon[i + 1][j] = 24;
if (dungeon[i][j] == 21 && dungeon[i + 1][j] == 1)
dungeon[i + 1][j] = 6;
if (dungeon[i][j] == 7 && dungeon[i + 1][j] == 1)
dungeon[i + 1][j] = 6;
if (dungeon[i][j] == 7 && dungeon[i + 1][j] == 24)
dungeon[i + 1][j] = 21;
if (dungeon[i][j] == 4 && dungeon[i + 1][j] == 16)
dungeon[i + 1][j] = 17;
if (dungeon[i][j] == 7 && dungeon[i + 1][j] == 13)
dungeon[i + 1][j] = 17;
if (dungeon[i][j] == 2 && dungeon[i + 1][j] == 24)
dungeon[i + 1][j] = 21;
if (dungeon[i][j] == 2 && dungeon[i + 1][j] == 13)
dungeon[i + 1][j] = 17;
if (dungeon[i][j] == 23 && dungeon[i - 1][j] == 22)
dungeon[i - 1][j] = 19;
if (dungeon[i][j] == 19 && dungeon[i - 1][j] == 23)
dungeon[i - 1][j] = 21;
if (dungeon[i][j] == 6 && dungeon[i - 1][j] == 22)
dungeon[i - 1][j] = 24;
if (dungeon[i][j] == 6 && dungeon[i - 1][j] == 23)
dungeon[i - 1][j] = 21;
if (dungeon[i][j] == 1 && dungeon[i][j + 1] == 2)
dungeon[i][j + 1] = 7;
if (dungeon[i][j] == 6 && dungeon[i][j + 1] == 18)
dungeon[i][j + 1] = 21;
if (dungeon[i][j] == 18 && dungeon[i][j + 1] == 2)
dungeon[i][j + 1] = 7;
if (dungeon[i][j] == 6 && dungeon[i][j + 1] == 2)
dungeon[i][j + 1] = 7;
if (dungeon[i][j] == 21 && dungeon[i][j + 1] == 2)
dungeon[i][j + 1] = 7;
if (dungeon[i][j] == 6 && dungeon[i][j + 1] == 22)
dungeon[i][j + 1] = 24;
if (dungeon[i][j] == 6 && dungeon[i][j + 1] == 13)
dungeon[i][j + 1] = 16;
if (dungeon[i][j] == 1 && dungeon[i][j + 1] == 13)
dungeon[i][j + 1] = 16;
if (dungeon[i][j] == 13 && dungeon[i][j + 1] == 16)
dungeon[i][j + 1] = 17;
if (dungeon[i][j] == 6 && dungeon[i][j - 1] == 22)
dungeon[i][j - 1] = 7;
if (dungeon[i][j] == 6 && dungeon[i][j - 1] == 22)
dungeon[i][j - 1] = 24;
if (dungeon[i][j] == 7 && dungeon[i][j - 1] == 24)
dungeon[i][j - 1] = 21;
if (dungeon[i][j] == 18 && dungeon[i][j - 1] == 24)
dungeon[i][j - 1] = 21;
}
}
for (j = 0; j < DMAXY; j++) {
for (i = 0; i < DMAXX; i++) {
if (dungeon[i][j] == 4 && dungeon[i][j + 1] == 2)
dungeon[i][j + 1] = 7;
if (dungeon[i][j] == 2 && dungeon[i + 1][j] == 19)
dungeon[i + 1][j] = 21;
if (dungeon[i][j] == 18 && dungeon[i][j + 1] == 22)
dungeon[i][j + 1] = 20;
}
}
}
void DRLG_L5Subs()
{
int x, y, rv, i;
for (y = 0; y < DMAXY; y++) {
for (x = 0; x < DMAXX; x++) {
if (!random(0, 4)) {
BYTE c = L5BTYPES[dungeon[x][y]];
if (c && !L5dflags[x][y]) {
rv = random(0, 16);
i = -1;
while (rv >= 0) {
if (++i == sizeof(L5BTYPES))
i = 0;
if (c == L5BTYPES[i])
rv--;
}
if (i == 89) {
if (L5BTYPES[dungeon[x][y - 1]] != 79 || L5dflags[x][y - 1])
i = 79;
else
dungeon[x][y - 1] = 90;
}
if (i == 91) {
if (L5BTYPES[dungeon[x + 1][y]] != 80 || L5dflags[x + 1][y])
i = 80;
else
dungeon[x + 1][y] = 92;
}
dungeon[x][y] = i;
}
}
}
}
}
void L5FillChambers()
{
int c;
if (HR1)
DRLG_L5GChamber(0, 14, 0, 0, 0, 1);
if (HR2) {
if (HR1 && !HR3)
DRLG_L5GChamber(14, 14, 0, 0, 1, 0);
if (!HR1 && HR3)
DRLG_L5GChamber(14, 14, 0, 0, 0, 1);
if (HR1 && HR3)
DRLG_L5GChamber(14, 14, 0, 0, 1, 1);
if (!HR1 && !HR3)
DRLG_L5GChamber(14, 14, 0, 0, 0, 0);
}
if (HR3)
DRLG_L5GChamber(28, 14, 0, 0, 1, 0);
if (HR1 && HR2)
DRLG_L5GHall(12, 18, 14, 18);
if (HR2 && HR3)
DRLG_L5GHall(26, 18, 28, 18);
if (HR1 && !HR2 && HR3)
DRLG_L5GHall(12, 18, 28, 18);
if (VR1)
DRLG_L5GChamber(14, 0, 0, 1, 0, 0);
if (VR2) {
if (VR1 && !VR3)
DRLG_L5GChamber(14, 14, 1, 0, 0, 0);
if (!VR1 && VR3)
DRLG_L5GChamber(14, 14, 0, 1, 0, 0);
if (VR1 && VR3)
DRLG_L5GChamber(14, 14, 1, 1, 0, 0);
if (!VR1 && !VR3)
DRLG_L5GChamber(14, 14, 0, 0, 0, 0);
}
if (VR3)
DRLG_L5GChamber(14, 28, 1, 0, 0, 0);
if (VR1 && VR2)
DRLG_L5GHall(18, 12, 18, 14);
if (VR2 && VR3)
DRLG_L5GHall(18, 26, 18, 28);
if (VR1 && !VR2 && VR3)
DRLG_L5GHall(18, 12, 18, 28);
if (setloadflag) {
if (VR1 || VR2 || VR3) {
c = 1;
if (!VR1 && VR2 && VR3 && random(0, 2))
c = 2;
if (VR1 && VR2 && !VR3 && random(0, 2))
c = 0;
if (VR1 && !VR2 && VR3) {
if (random(0, 2))
c = 0;
else
c = 2;
}
if (VR1 && VR2 && VR3)
c = random(0, 3);
switch (c) {
case 0:
DRLG_L5SetRoom(16, 2);
break;
case 1:
DRLG_L5SetRoom(16, 16);
break;
case 2:
DRLG_L5SetRoom(16, 30);
break;
}
} else {
c = 1;
if (!HR1 && HR2 && HR3 && random(0, 2))
c = 2;
if (HR1 && HR2 && !HR3 && random(0, 2))
c = 0;
if (HR1 && !HR2 && HR3) {
if (random(0, 2))
c = 0;
else
c = 2;
}
if (HR1 && HR2 && HR3)
c = random(0, 3);
switch (c) {
case 0:
DRLG_L5SetRoom(2, 16);
break;
case 1:
DRLG_L5SetRoom(16, 16);
break;
case 2:
DRLG_L5SetRoom(30, 16);
break;
}
}
}
}
void DRLG_L5GChamber(int sx, int sy, BOOL topflag, BOOL bottomflag, BOOL leftflag, BOOL rightflag)
{
int i, j;
if (topflag == TRUE) {
dungeon[sx + 2][sy] = 12;
dungeon[sx + 3][sy] = 12;
dungeon[sx + 4][sy] = 3;
dungeon[sx + 7][sy] = 9;
dungeon[sx + 8][sy] = 12;
dungeon[sx + 9][sy] = 2;
}
if (bottomflag == TRUE) {
sy += 11;
dungeon[sx + 2][sy] = 10;
dungeon[sx + 3][sy] = 12;
dungeon[sx + 4][sy] = 8;
dungeon[sx + 7][sy] = 5;
dungeon[sx + 8][sy] = 12;
if (dungeon[sx + 9][sy] != 4) {
dungeon[sx + 9][sy] = 21;
}
sy -= 11;
}
if (leftflag == TRUE) {
dungeon[sx][sy + 2] = 11;
dungeon[sx][sy + 3] = 11;
dungeon[sx][sy + 4] = 3;
dungeon[sx][sy + 7] = 8;
dungeon[sx][sy + 8] = 11;
dungeon[sx][sy + 9] = 1;
}
if (rightflag == TRUE) {
sx += 11;
dungeon[sx][sy + 2] = 14;
dungeon[sx][sy + 3] = 11;
dungeon[sx][sy + 4] = 9;
dungeon[sx][sy + 7] = 5;
dungeon[sx][sy + 8] = 11;
if (dungeon[sx][sy + 9] != 4) {
dungeon[sx][sy + 9] = 21;
}
sx -= 11;
}
for (j = 1; j < 11; j++) {
for (i = 1; i < 11; i++) {
dungeon[i + sx][j + sy] = 13;
L5dflags[i + sx][j + sy] |= DLRG_CHAMBER;
}
}
dungeon[sx + 4][sy + 4] = 15;
dungeon[sx + 7][sy + 4] = 15;
dungeon[sx + 4][sy + 7] = 15;
dungeon[sx + 7][sy + 7] = 15;
}
void DRLG_L5GHall(int x1, int y1, int x2, int y2)
{
int i;
if (y1 == y2) {
for (i = x1; i < x2; i++) {
dungeon[i][y1] = 12;
dungeon[i][y1 + 3] = 12;
}
} else {
for (i = y1; i < y2; i++) {
dungeon[x1][i] = 11;
dungeon[x1 + 3][i] = 11;
}
}
}
void DRLG_L5SetRoom(int rx1, int ry1)
{
int rw, rh, i, j;
BYTE *sp;
rw = *pSetPiece;
rh = *(pSetPiece + 2);
setpc_x = rx1;
setpc_y = ry1;
setpc_w = rw;
setpc_h = rh;
sp = pSetPiece + 4;
for (j = 0; j < rh; j++) {
for (i = 0; i < rw; i++) {
if (*sp) {
dungeon[rx1 + i][ry1 + j] = *sp;
L5dflags[rx1 + i][ry1 + j] |= DLRG_PROTECTED;
} else {
dungeon[rx1 + i][ry1 + j] = 13;
}
sp += 2;
}
}
}
void DRLG_L5FloodTVal()
{
int xx, yy, i, j;
yy = 16;
for (j = 0; j < DMAXY; j++) {
xx = 16;
for (i = 0; i < DMAXX; i++) {
if (dungeon[i][j] == 13 && !dTransVal[xx][yy]) {
DRLG_L5FTVR(i, j, xx, yy, 0);
TransVal++;
}
xx += 2;
}
yy += 2;
}
}
void DRLG_L5FTVR(int i, int j, int x, int y, int d)
{
if (dTransVal[x][y] || dungeon[i][j] != 13) {
if (d == 1) {
dTransVal[x][y] = TransVal;
dTransVal[x][y + 1] = TransVal;
}
if (d == 2) {
dTransVal[x + 1][y] = TransVal;
dTransVal[x + 1][y + 1] = TransVal;
}
if (d == 3) {
dTransVal[x][y] = TransVal;
dTransVal[x + 1][y] = TransVal;
}
if (d == 4) {
dTransVal[x][y + 1] = TransVal;
dTransVal[x + 1][y + 1] = TransVal;
}
if (d == 5)
dTransVal[x + 1][y + 1] = TransVal;
if (d == 6)
dTransVal[x][y + 1] = TransVal;
if (d == 7)
dTransVal[x + 1][y] = TransVal;
if (d == 8)
dTransVal[x][y] = TransVal;
} else {
dTransVal[x][y] = TransVal;
dTransVal[x + 1][y] = TransVal;
dTransVal[x][y + 1] = TransVal;
dTransVal[x + 1][y + 1] = TransVal;
DRLG_L5FTVR(i + 1, j, x + 2, y, 1);
DRLG_L5FTVR(i - 1, j, x - 2, y, 2);
DRLG_L5FTVR(i, j + 1, x, y + 2, 3);
DRLG_L5FTVR(i, j - 1, x, y - 2, 4);
DRLG_L5FTVR(i - 1, j - 1, x - 2, y - 2, 5);
DRLG_L5FTVR(i + 1, j - 1, x + 2, y - 2, 6);
DRLG_L5FTVR(i - 1, j + 1, x - 2, y + 2, 7);
DRLG_L5FTVR(i + 1, j + 1, x + 2, y + 2, 8);
}
}
void DRLG_L5TransFix()
{
int xx, yy, i, j;
yy = 16;
for (j = 0; j < DMAXY; j++) {
xx = 16;
for (i = 0; i < DMAXX; i++) {
if (dungeon[i][j] == 23 && dungeon[i][j - 1] == 18) {
dTransVal[xx + 1][yy] = dTransVal[xx][yy];
dTransVal[xx + 1][yy + 1] = dTransVal[xx][yy];
}
if (dungeon[i][j] == 24 && dungeon[i + 1][j] == 19) {
dTransVal[xx][yy + 1] = dTransVal[xx][yy];
dTransVal[xx + 1][yy + 1] = dTransVal[xx][yy];
}
if (dungeon[i][j] == 18) {
dTransVal[xx + 1][yy] = dTransVal[xx][yy];
dTransVal[xx + 1][yy + 1] = dTransVal[xx][yy];
}
if (dungeon[i][j] == 19) {
dTransVal[xx][yy + 1] = dTransVal[xx][yy];
dTransVal[xx + 1][yy + 1] = dTransVal[xx][yy];
}
if (dungeon[i][j] == 20) {
dTransVal[xx + 1][yy] = dTransVal[xx][yy];
dTransVal[xx][yy + 1] = dTransVal[xx][yy];
dTransVal[xx + 1][yy + 1] = dTransVal[xx][yy];
}
xx += 2;
}
yy += 2;
}
}
void DRLG_L5DirtFix()
{
int i, j;
for (j = 0; j < DMAXY; j++) {
for (i = 0; i < DMAXX; i++) {
if (dungeon[i][j] == 21 && dungeon[i + 1][j] != 19)
dungeon[i][j] = 202;
if (dungeon[i][j] == 19 && dungeon[i + 1][j] != 19)
dungeon[i][j] = 200;
if (dungeon[i][j] == 24 && dungeon[i + 1][j] != 19)
dungeon[i][j] = 205;
if (dungeon[i][j] == 18 && dungeon[i][j + 1] != 18)
dungeon[i][j] = 199;
if (dungeon[i][j] == 21 && dungeon[i][j + 1] != 18)
dungeon[i][j] = 202;
if (dungeon[i][j] == 23 && dungeon[i][j + 1] != 18)
dungeon[i][j] = 204;
}
}
}
void DRLG_L5CornerFix()
{
int i, j;
for (j = 1; j < DMAXY - 1; j++) {
for (i = 1; i < DMAXX - 1; i++) {
if (!(L5dflags[i][j] & DLRG_PROTECTED) && dungeon[i][j] == 17 && dungeon[i - 1][j] == 13 && dungeon[i][j - 1] == 1) {
dungeon[i][j] = 16;
L5dflags[i][j - 1] &= DLRG_PROTECTED;
}
if (dungeon[i][j] == 202 && dungeon[i + 1][j] == 13 && dungeon[i][j + 1] == 1) {
dungeon[i][j] = 8;
}
}
}
}
DEVILUTION_END_NAMESPACE
|
#include "Log.h"
#include "EU4ToVic2Converter.h"
#include "Mappers/VersionParser/VersionParser.h"
int main(const int argc, const char * argv[])
{
try
{
const mappers::VersionParser versionParser;
LOG(LogLevel::Info) << versionParser;
LOG(LogLevel::Info) << "Built on " << __TIMESTAMP__;
if (argc >= 2)
{
std::string argv1 = argv[1];
if (argv1 != "input.eu4")
{
LOG(LogLevel::Info) << "EU4toVic2 no longer takes savegame path as a parameter";
LOG(LogLevel::Info) << "It uses configuration.txt, configured manually or by the frontend.";
}
}
convertEU4ToVic2(versionParser);
return 0;
}
catch (const std::exception& e)
{
LOG(LogLevel::Error) << e.what();
return -1;
}
}
|
#ifndef WAYPOINTS_H
#define WAYPOINTS_H
#include <QStandardItemModel>
#include "dji_vehicle.hpp"
#include "sdk_widgets.hpp"
#include <QWidget>
namespace Ui
{
class MissionWidget;
}
class QWaypoints : public QWidget
{
Q_OBJECT
public:
explicit QWaypoints(QWidget* parent = 0, DJI::OSDK::Vehicle* vehicle = 0);
~QWaypoints();
void initWayPoint();
void wpAddPoint();
void wpRemovePoint();
Ui::MissionWidget* getMissionUi()
{
return this->ui;
}
private slots:
void on_btn_waypoint_init_clicked();
void on_cb_waypoint_point_currentIndexChanged(int index);
void on_le_waypoint_number_editingFinished();
void on_btn_waypoint_action_clicked();
void on_btn_waypoint_reset_clicked();
void on_btn_waypoint_removeAction_clicked();
void on_btn_waypoint_viewPoint_clicked();
void on_btn_wp_ivset_clicked();
void on_btn_wp_ivRead_clicked();
void on_btn_waypoint_add_clicked();
void on_btn_waypoint_remove_clicked();
void on_btn_wp_pr_clicked(bool checked);
void on_le_wp_exec_editingFinished();
void on_btn_wp_loadAll_clicked();
void on_btn_wp_start_stop_clicked(bool checked);
void on_btn_wp_loadOne_clicked();
void wpDataChanged(const QModelIndex& topLeft, const QModelIndex& bottomRight,
const QVector<int>& roles);
// void on_btn_webTool_clicked(bool checked);
void on_btn_AbortWaypoint_clicked();
private:
QStandardItemModel* initAction();
Ui::MissionWidget* ui;
DJI::OSDK::WayPointSettings wayPointDataTmp;
DJI::OSDK::WayPointInitSettings* wpInitSettings;
DJI::OSDK::Vehicle* vehicle;
QStandardItemModel* waypointData;
QStandardItemModel* currentAction;
QStandardItemModel* nullAction;
QStandardItemModel* persistentActionPtr;
QList<QStandardItemModel*>* actionData;
};
#endif // WAYPOINTS_H
|
#pragma once
#include <cassert>
#include <ostream>
namespace zasm
{
enum class Error
{
None = 0,
// Generic.
InvalidMode,
NotInitialized,
InvalidOperation,
// Program
LabelNotFound,
UnresolvedLabel,
InvalidLabel,
// Decoder.
InvalidInstruction,
OutOfBounds,
// Encoder.
ImpossibleInstruction,
};
inline constexpr const char* getErrorName(Error err)
{
#define ERROR_STRING(e) \
case e: \
return #e
switch (err)
{
ERROR_STRING(Error::None);
ERROR_STRING(Error::InvalidMode);
ERROR_STRING(Error::NotInitialized);
ERROR_STRING(Error::InvalidOperation);
ERROR_STRING(Error::LabelNotFound);
ERROR_STRING(Error::UnresolvedLabel);
ERROR_STRING(Error::InvalidLabel);
ERROR_STRING(Error::InvalidInstruction);
ERROR_STRING(Error::OutOfBounds);
ERROR_STRING(Error::ImpossibleInstruction);
default:
assert(false);
break;
}
#undef ERROR_STRING
return nullptr;
}
} // namespace zasm
inline std::ostream& operator<<(std::ostream& os, const zasm::Error err)
{
return os << zasm::getErrorName(err);
}
|
/*-------------------------------------------------------------------------
* drawElements Quality Program OpenGL ES 3.1 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 Drawing stress tests.
*//*--------------------------------------------------------------------*/
#include "es31sDrawTests.hpp"
#include "glsDrawTest.hpp"
#include "gluRenderContext.hpp"
#include "gluCallLogWrapper.hpp"
#include "gluShaderProgram.hpp"
#include "glwEnums.hpp"
#include "glwFunctions.hpp"
#include "deRandom.hpp"
#include "deStringUtil.hpp"
#include "deUniquePtr.hpp"
#include <set>
namespace deqp
{
namespace gles31
{
namespace Stress
{
namespace
{
static const char* s_colorVertexShaderSource = "#version 310 es\n"
"in highp vec4 a_position;\n"
"in highp vec4 a_color;\n"
"out highp vec4 v_color;\n"
"void main (void)\n"
"{\n"
" gl_Position = a_position;\n"
" v_color = a_color;\n"
"}\n";
static const char* s_colorFragmentShaderSource = "#version 310 es\n"
"layout(location = 0) out highp vec4 fragColor;\n"
"in highp vec4 v_color;\n"
"void main (void)\n"
"{\n"
" fragColor = v_color;\n"
"}\n";
struct DrawElementsCommand
{
deUint32 count;
deUint32 primCount;
deUint32 firstIndex;
deInt32 baseVertex;
deUint32 reservedMustBeZero;
};
DE_STATIC_ASSERT(5 * sizeof(deUint32) == sizeof(DrawElementsCommand)); // tight packing
struct DrawArraysCommand
{
deUint32 count;
deUint32 primCount;
deUint32 first;
deUint32 reservedMustBeZero;
};
DE_STATIC_ASSERT(4 * sizeof(deUint32) == sizeof(DrawArraysCommand)); // tight packing
class InvalidDrawCase : public TestCase
{
public:
enum DrawType
{
DRAW_ARRAYS,
DRAW_ELEMENTS,
DRAW_LAST
};
enum InvalidOperation
{
INVALID_DATA_COUNT = 0,
INVALID_DATA_FIRST,
INVALID_DATA_INSTANCED,
INVALID_INDEX_COUNT,
INVALID_INDEX_FIRST,
INVALID_RESERVED,
INVALID_INDEX,
INVALID_LAST
};
InvalidDrawCase (Context& context, const char* name, const char* desc, DrawType type, InvalidOperation op);
~InvalidDrawCase (void);
void init (void);
void deinit (void);
IterateResult iterate (void);
private:
const DrawType m_drawType;
const InvalidOperation m_op;
glw::GLuint m_dataBufferID;
glw::GLuint m_indexBufferID;
glw::GLuint m_cmdBufferID;
glw::GLuint m_colorBufferID;
glw::GLuint m_vao;
};
InvalidDrawCase::InvalidDrawCase (Context& context, const char* name, const char* desc, DrawType type, InvalidOperation op)
: TestCase (context, name, desc)
, m_drawType (type)
, m_op (op)
, m_dataBufferID (0)
, m_indexBufferID (0)
, m_cmdBufferID (0)
, m_colorBufferID (0)
, m_vao (0)
{
DE_ASSERT(type < DRAW_LAST);
DE_ASSERT(op < INVALID_LAST);
}
InvalidDrawCase::~InvalidDrawCase (void)
{
deinit();
}
void InvalidDrawCase::init (void)
{
}
void InvalidDrawCase::deinit (void)
{
if (m_dataBufferID)
{
m_context.getRenderContext().getFunctions().deleteBuffers(1, &m_dataBufferID);
m_dataBufferID = 0;
}
if (m_indexBufferID)
{
m_context.getRenderContext().getFunctions().deleteBuffers(1, &m_indexBufferID);
m_indexBufferID = 0;
}
if (m_cmdBufferID)
{
m_context.getRenderContext().getFunctions().deleteBuffers(1, &m_cmdBufferID);
m_cmdBufferID = 0;
}
if (m_colorBufferID)
{
m_context.getRenderContext().getFunctions().deleteBuffers(1, &m_colorBufferID);
m_colorBufferID = 0;
}
if (m_vao)
{
m_context.getRenderContext().getFunctions().deleteVertexArrays(1, &m_vao);
m_vao = 0;
}
}
InvalidDrawCase::IterateResult InvalidDrawCase::iterate (void)
{
const int drawCount = 10; //!< number of elements safe to draw (all buffers have this)
const int overBoundDrawCount = 10000; //!< number of elements in all other buffers than our target buffer
const int drawInstances = 1;
const int overBoundInstances = 1000;
glu::CallLogWrapper gl (m_context.getRenderContext().getFunctions(), m_testCtx.getLog());
glu::ShaderProgram program (m_context.getRenderContext(), glu::ProgramSources() << glu::VertexSource(s_colorVertexShaderSource) << glu::FragmentSource(s_colorFragmentShaderSource));
const deUint32 programID = program.getProgram();
const deInt32 posLocation = gl.glGetAttribLocation(programID, "a_position");
const deInt32 colorLocation = gl.glGetAttribLocation(programID, "a_color");
gl.enableLogging(true);
gl.glGenVertexArrays(1, &m_vao);
gl.glBindVertexArray(m_vao);
glu::checkError(gl.glGetError(), "gen vao", __FILE__, __LINE__);
// indices
if (m_drawType == DRAW_ELEMENTS)
{
const int indexBufferSize = (m_op == INVALID_INDEX_COUNT) ? (drawCount) : (overBoundDrawCount);
std::vector<deUint16> indices (indexBufferSize);
for (int ndx = 0; ndx < (int)indices.size(); ++ndx)
indices[ndx] = (deUint16)((m_op == INVALID_INDEX) ? (overBoundDrawCount + ndx) : (ndx));
gl.glGenBuffers(1, &m_indexBufferID);
gl.glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_indexBufferID);
gl.glBufferData(GL_ELEMENT_ARRAY_BUFFER, (int)(indices.size() * sizeof(deUint16)), &indices[0], GL_STATIC_DRAW);
glu::checkError(gl.glGetError(), "", __FILE__, __LINE__);
}
// data
{
const int dataSize = (m_op == INVALID_DATA_COUNT) ? (drawCount) : (overBoundDrawCount);
// any data is ok
gl.glGenBuffers(1, &m_dataBufferID);
gl.glBindBuffer(GL_ARRAY_BUFFER, m_dataBufferID);
gl.glBufferData(GL_ARRAY_BUFFER, dataSize * sizeof(float[4]), DE_NULL, GL_STATIC_DRAW);
gl.glVertexAttribPointer(posLocation, 4, GL_FLOAT, GL_FALSE, 0, DE_NULL);
gl.glEnableVertexAttribArray(posLocation);
glu::checkError(gl.glGetError(), "", __FILE__, __LINE__);
}
// potentially instanced data
{
const int dataSize = drawInstances;
gl.glGenBuffers(1, &m_colorBufferID);
gl.glBindBuffer(GL_ARRAY_BUFFER, m_colorBufferID);
gl.glBufferData(GL_ARRAY_BUFFER, dataSize * sizeof(float[4]), DE_NULL, GL_STATIC_DRAW);
gl.glVertexAttribPointer(colorLocation, 4, GL_FLOAT, GL_FALSE, 0, DE_NULL);
gl.glEnableVertexAttribArray(colorLocation);
gl.glVertexAttribDivisor(colorLocation, 1);
glu::checkError(gl.glGetError(), "", __FILE__, __LINE__);
}
// command
if (m_drawType == DRAW_ARRAYS)
{
DrawArraysCommand drawCommand;
drawCommand.count = overBoundDrawCount;
drawCommand.primCount = (m_op == INVALID_DATA_INSTANCED) ? (overBoundInstances) : (drawInstances);
drawCommand.first = (m_op == INVALID_DATA_FIRST) ? (overBoundDrawCount) : (0);
drawCommand.reservedMustBeZero = (m_op == INVALID_RESERVED) ? (5) : (0);
m_testCtx.getLog()
<< tcu::TestLog::Message
<< "drawCommand:"
<< "\n\tcount:\t" << drawCommand.count
<< "\n\tprimCount\t" << drawCommand.primCount
<< "\n\tfirst\t" << drawCommand.first
<< "\n\treservedMustBeZero\t" << drawCommand.reservedMustBeZero
<< tcu::TestLog::EndMessage;
gl.glGenBuffers(1, &m_cmdBufferID);
gl.glBindBuffer(GL_DRAW_INDIRECT_BUFFER, m_cmdBufferID);
gl.glBufferData(GL_DRAW_INDIRECT_BUFFER, sizeof(drawCommand), &drawCommand, GL_STATIC_DRAW);
glu::checkError(gl.glGetError(), "", __FILE__, __LINE__);
}
else if (m_drawType == DRAW_ELEMENTS)
{
DrawElementsCommand drawCommand;
drawCommand.count = overBoundDrawCount;
drawCommand.primCount = (m_op == INVALID_DATA_INSTANCED) ? (overBoundInstances) : (drawInstances);
drawCommand.firstIndex = (m_op == INVALID_INDEX_FIRST) ? (overBoundDrawCount) : (0);
drawCommand.baseVertex = (m_op == INVALID_DATA_FIRST) ? (overBoundDrawCount) : (0);
drawCommand.reservedMustBeZero = (m_op == INVALID_RESERVED) ? (5) : (0);
m_testCtx.getLog()
<< tcu::TestLog::Message
<< "drawCommand:"
<< "\n\tcount:\t" << drawCommand.count
<< "\n\tprimCount\t" << drawCommand.primCount
<< "\n\tfirstIndex\t" << drawCommand.firstIndex
<< "\n\tbaseVertex\t" << drawCommand.baseVertex
<< "\n\treservedMustBeZero\t" << drawCommand.reservedMustBeZero
<< tcu::TestLog::EndMessage;
gl.glGenBuffers(1, &m_cmdBufferID);
gl.glBindBuffer(GL_DRAW_INDIRECT_BUFFER, m_cmdBufferID);
gl.glBufferData(GL_DRAW_INDIRECT_BUFFER, sizeof(drawCommand), &drawCommand, GL_STATIC_DRAW);
glu::checkError(gl.glGetError(), "", __FILE__, __LINE__);
}
else
DE_ASSERT(DE_FALSE);
gl.glViewport(0, 0, 1, 1);
gl.glUseProgram(programID);
if (m_drawType == DRAW_ELEMENTS)
gl.glDrawElementsIndirect(GL_TRIANGLES, GL_UNSIGNED_SHORT, DE_NULL);
else if (m_drawType == DRAW_ARRAYS)
gl.glDrawArraysIndirect(GL_TRIANGLES, DE_NULL);
else
DE_ASSERT(DE_FALSE);
gl.glUseProgram(0);
gl.glFinish();
m_testCtx.setTestResult(QP_TEST_RESULT_PASS, "Pass");
return STOP;
}
class RandomGroup : public TestCaseGroup
{
public:
RandomGroup (Context& context, const char* name, const char* descr);
~RandomGroup (void);
void init (void);
};
template <int SIZE>
struct UniformWeightArray
{
float weights[SIZE];
UniformWeightArray (void)
{
for (int i=0; i<SIZE; ++i)
weights[i] = 1.0f;
}
};
RandomGroup::RandomGroup (Context& context, const char* name, const char* descr)
: TestCaseGroup (context, name, descr)
{
}
RandomGroup::~RandomGroup (void)
{
}
void RandomGroup::init (void)
{
const int numAttempts = 100;
const int attribCounts[] = { 1, 2, 5 };
const float attribWeights[] = { 30, 10, 1 };
const int primitiveCounts[] = { 1, 5, 64 };
const float primitiveCountWeights[] = { 20, 10, 1 };
const int indexOffsets[] = { 0, 7, 13 };
const float indexOffsetWeights[] = { 20, 20, 1 };
const int firsts[] = { 0, 7, 13 };
const float firstWeights[] = { 20, 20, 1 };
const int instanceCounts[] = { 1, 2, 16, 17 };
const float instanceWeights[] = { 20, 10, 5, 1 };
const int indexMins[] = { 0, 1, 3, 8 };
const int indexMaxs[] = { 4, 8, 128, 257 };
const float indexWeights[] = { 50, 50, 50, 50 };
const int offsets[] = { 0, 1, 5, 12 };
const float offsetWeights[] = { 50, 10, 10, 10 };
const int strides[] = { 0, 7, 16, 17 };
const float strideWeights[] = { 50, 10, 10, 10 };
const int instanceDivisors[] = { 0, 1, 3, 129 };
const float instanceDivisorWeights[]= { 70, 30, 10, 10 };
const int indirectOffsets[] = { 0, 1, 2 };
const float indirectOffsetWeigths[] = { 2, 1, 1 };
const int baseVertices[] = { 0, 1, -2, 4, 3 };
const float baseVertexWeigths[] = { 4, 1, 1, 1, 1 };
gls::DrawTestSpec::Primitive primitives[] =
{
gls::DrawTestSpec::PRIMITIVE_POINTS,
gls::DrawTestSpec::PRIMITIVE_TRIANGLES,
gls::DrawTestSpec::PRIMITIVE_TRIANGLE_FAN,
gls::DrawTestSpec::PRIMITIVE_TRIANGLE_STRIP,
gls::DrawTestSpec::PRIMITIVE_LINES,
gls::DrawTestSpec::PRIMITIVE_LINE_STRIP,
gls::DrawTestSpec::PRIMITIVE_LINE_LOOP
};
const UniformWeightArray<DE_LENGTH_OF_ARRAY(primitives)> primitiveWeights;
gls::DrawTestSpec::DrawMethod drawMethods[] =
{
gls::DrawTestSpec::DRAWMETHOD_DRAWARRAYS_INDIRECT,
gls::DrawTestSpec::DRAWMETHOD_DRAWELEMENTS_INDIRECT,
};
const UniformWeightArray<DE_LENGTH_OF_ARRAY(drawMethods)> drawMethodWeights;
gls::DrawTestSpec::IndexType indexTypes[] =
{
gls::DrawTestSpec::INDEXTYPE_BYTE,
gls::DrawTestSpec::INDEXTYPE_SHORT,
gls::DrawTestSpec::INDEXTYPE_INT,
};
const UniformWeightArray<DE_LENGTH_OF_ARRAY(indexTypes)> indexTypeWeights;
gls::DrawTestSpec::InputType inputTypes[] =
{
gls::DrawTestSpec::INPUTTYPE_FLOAT,
gls::DrawTestSpec::INPUTTYPE_FIXED,
gls::DrawTestSpec::INPUTTYPE_BYTE,
gls::DrawTestSpec::INPUTTYPE_SHORT,
gls::DrawTestSpec::INPUTTYPE_UNSIGNED_BYTE,
gls::DrawTestSpec::INPUTTYPE_UNSIGNED_SHORT,
gls::DrawTestSpec::INPUTTYPE_INT,
gls::DrawTestSpec::INPUTTYPE_UNSIGNED_INT,
gls::DrawTestSpec::INPUTTYPE_HALF,
gls::DrawTestSpec::INPUTTYPE_UNSIGNED_INT_2_10_10_10,
gls::DrawTestSpec::INPUTTYPE_INT_2_10_10_10,
};
const UniformWeightArray<DE_LENGTH_OF_ARRAY(inputTypes)> inputTypeWeights;
gls::DrawTestSpec::OutputType outputTypes[] =
{
gls::DrawTestSpec::OUTPUTTYPE_FLOAT,
gls::DrawTestSpec::OUTPUTTYPE_VEC2,
gls::DrawTestSpec::OUTPUTTYPE_VEC3,
gls::DrawTestSpec::OUTPUTTYPE_VEC4,
gls::DrawTestSpec::OUTPUTTYPE_INT,
gls::DrawTestSpec::OUTPUTTYPE_UINT,
gls::DrawTestSpec::OUTPUTTYPE_IVEC2,
gls::DrawTestSpec::OUTPUTTYPE_IVEC3,
gls::DrawTestSpec::OUTPUTTYPE_IVEC4,
gls::DrawTestSpec::OUTPUTTYPE_UVEC2,
gls::DrawTestSpec::OUTPUTTYPE_UVEC3,
gls::DrawTestSpec::OUTPUTTYPE_UVEC4,
};
const UniformWeightArray<DE_LENGTH_OF_ARRAY(outputTypes)> outputTypeWeights;
gls::DrawTestSpec::Usage usages[] =
{
gls::DrawTestSpec::USAGE_DYNAMIC_DRAW,
gls::DrawTestSpec::USAGE_STATIC_DRAW,
gls::DrawTestSpec::USAGE_STREAM_DRAW,
gls::DrawTestSpec::USAGE_STREAM_READ,
gls::DrawTestSpec::USAGE_STREAM_COPY,
gls::DrawTestSpec::USAGE_STATIC_READ,
gls::DrawTestSpec::USAGE_STATIC_COPY,
gls::DrawTestSpec::USAGE_DYNAMIC_READ,
gls::DrawTestSpec::USAGE_DYNAMIC_COPY,
};
const UniformWeightArray<DE_LENGTH_OF_ARRAY(usages)> usageWeights;
std::set<deUint32> insertedHashes;
size_t insertedCount = 0;
for (int ndx = 0; ndx < numAttempts; ++ndx)
{
de::Random random(0xc551393 + ndx); // random does not depend on previous cases
int attributeCount = random.chooseWeighted<int, const int*, const float*>(DE_ARRAY_BEGIN(attribCounts), DE_ARRAY_END(attribCounts), attribWeights);
int drawCommandSize;
gls::DrawTestSpec spec;
spec.apiType = glu::ApiType::es(3,1);
spec.primitive = random.chooseWeighted<gls::DrawTestSpec::Primitive> (DE_ARRAY_BEGIN(primitives), DE_ARRAY_END(primitives), primitiveWeights.weights);
spec.primitiveCount = random.chooseWeighted<int, const int*, const float*> (DE_ARRAY_BEGIN(primitiveCounts), DE_ARRAY_END(primitiveCounts), primitiveCountWeights);
spec.drawMethod = random.chooseWeighted<gls::DrawTestSpec::DrawMethod> (DE_ARRAY_BEGIN(drawMethods), DE_ARRAY_END(drawMethods), drawMethodWeights.weights);
if (spec.drawMethod == gls::DrawTestSpec::DRAWMETHOD_DRAWARRAYS_INDIRECT)
drawCommandSize = sizeof(deUint32[4]);
else if (spec.drawMethod == gls::DrawTestSpec::DRAWMETHOD_DRAWELEMENTS_INDIRECT)
drawCommandSize = sizeof(deUint32[5]);
else
{
DE_ASSERT(DE_FALSE);
return;
}
spec.indexType = random.chooseWeighted<gls::DrawTestSpec::IndexType> (DE_ARRAY_BEGIN(indexTypes), DE_ARRAY_END(indexTypes), indexTypeWeights.weights);
spec.indexPointerOffset = random.chooseWeighted<int, const int*, const float*> (DE_ARRAY_BEGIN(indexOffsets), DE_ARRAY_END(indexOffsets), indexOffsetWeights);
spec.indexStorage = gls::DrawTestSpec::STORAGE_BUFFER;
spec.first = random.chooseWeighted<int, const int*, const float*> (DE_ARRAY_BEGIN(firsts), DE_ARRAY_END(firsts), firstWeights);
spec.indexMin = random.chooseWeighted<int, const int*, const float*> (DE_ARRAY_BEGIN(indexMins), DE_ARRAY_END(indexMins), indexWeights);
spec.indexMax = random.chooseWeighted<int, const int*, const float*> (DE_ARRAY_BEGIN(indexMaxs), DE_ARRAY_END(indexMaxs), indexWeights);
spec.instanceCount = random.chooseWeighted<int, const int*, const float*> (DE_ARRAY_BEGIN(instanceCounts), DE_ARRAY_END(instanceCounts), instanceWeights);
spec.indirectOffset = random.chooseWeighted<int, const int*, const float*> (DE_ARRAY_BEGIN(indirectOffsets), DE_ARRAY_END(indirectOffsets), indirectOffsetWeigths) * drawCommandSize;
spec.baseVertex = random.chooseWeighted<int, const int*, const float*> (DE_ARRAY_BEGIN(baseVertices), DE_ARRAY_END(baseVertices), baseVertexWeigths);
// check spec is legal
if (!spec.valid())
continue;
for (int attrNdx = 0; attrNdx < attributeCount;)
{
bool valid;
gls::DrawTestSpec::AttributeSpec attribSpec;
attribSpec.inputType = random.chooseWeighted<gls::DrawTestSpec::InputType> (DE_ARRAY_BEGIN(inputTypes), DE_ARRAY_END(inputTypes), inputTypeWeights.weights);
attribSpec.outputType = random.chooseWeighted<gls::DrawTestSpec::OutputType> (DE_ARRAY_BEGIN(outputTypes), DE_ARRAY_END(outputTypes), outputTypeWeights.weights);
attribSpec.storage = gls::DrawTestSpec::STORAGE_BUFFER;
attribSpec.usage = random.chooseWeighted<gls::DrawTestSpec::Usage> (DE_ARRAY_BEGIN(usages), DE_ARRAY_END(usages), usageWeights.weights);
attribSpec.componentCount = random.getInt(1, 4);
attribSpec.offset = random.chooseWeighted<int, const int*, const float*>(DE_ARRAY_BEGIN(offsets), DE_ARRAY_END(offsets), offsetWeights);
attribSpec.stride = random.chooseWeighted<int, const int*, const float*>(DE_ARRAY_BEGIN(strides), DE_ARRAY_END(strides), strideWeights);
attribSpec.normalize = random.getBool();
attribSpec.instanceDivisor = random.chooseWeighted<int, const int*, const float*>(DE_ARRAY_BEGIN(instanceDivisors), DE_ARRAY_END(instanceDivisors), instanceDivisorWeights);
attribSpec.useDefaultAttribute = random.getBool();
// check spec is legal
valid = attribSpec.valid(spec.apiType);
// we do not want interleaved elements. (Might result in some weird floating point values)
if (attribSpec.stride && attribSpec.componentCount * gls::DrawTestSpec::inputTypeSize(attribSpec.inputType) > attribSpec.stride)
valid = false;
// try again if not valid
if (valid)
{
spec.attribs.push_back(attribSpec);
++attrNdx;
}
}
// Do not collapse all vertex positions to a single positions
if (spec.primitive != gls::DrawTestSpec::PRIMITIVE_POINTS)
spec.attribs[0].instanceDivisor = 0;
// Is render result meaningful?
{
// Only one vertex
if (spec.drawMethod == gls::DrawTestSpec::DRAWMETHOD_DRAWELEMENTS_RANGED && spec.indexMin == spec.indexMax && spec.primitive != gls::DrawTestSpec::PRIMITIVE_POINTS)
continue;
if (spec.attribs[0].useDefaultAttribute && spec.primitive != gls::DrawTestSpec::PRIMITIVE_POINTS)
continue;
// Triangle only on one axis
if (spec.primitive == gls::DrawTestSpec::PRIMITIVE_TRIANGLES || spec.primitive == gls::DrawTestSpec::PRIMITIVE_TRIANGLE_FAN || spec.primitive == gls::DrawTestSpec::PRIMITIVE_TRIANGLE_STRIP)
{
if (spec.attribs[0].componentCount == 1)
continue;
if (spec.attribs[0].outputType == gls::DrawTestSpec::OUTPUTTYPE_FLOAT || spec.attribs[0].outputType == gls::DrawTestSpec::OUTPUTTYPE_INT || spec.attribs[0].outputType == gls::DrawTestSpec::OUTPUTTYPE_UINT)
continue;
if (spec.drawMethod == gls::DrawTestSpec::DRAWMETHOD_DRAWELEMENTS_RANGED && (spec.indexMax - spec.indexMin) < 2)
continue;
}
}
// Add case
{
deUint32 hash = spec.hash();
for (int attrNdx = 0; attrNdx < attributeCount; ++attrNdx)
hash = (hash << 2) ^ (deUint32)spec.attribs[attrNdx].hash();
if (insertedHashes.find(hash) == insertedHashes.end())
{
// Only unaligned cases
if (spec.isCompatibilityTest() == gls::DrawTestSpec::COMPATIBILITY_UNALIGNED_OFFSET ||
spec.isCompatibilityTest() == gls::DrawTestSpec::COMPATIBILITY_UNALIGNED_STRIDE)
this->addChild(new gls::DrawTest(m_testCtx, m_context.getRenderContext(), spec, de::toString(insertedCount).c_str(), spec.getDesc().c_str()));
insertedHashes.insert(hash);
++insertedCount;
}
}
}
}
} // anonymous
DrawTests::DrawTests (Context& context)
: TestCaseGroup(context, "draw_indirect", "Indirect drawing tests")
{
}
DrawTests::~DrawTests (void)
{
}
void DrawTests::init (void)
{
tcu::TestCaseGroup* const unalignedGroup = new tcu::TestCaseGroup(m_testCtx, "unaligned_data", "Test with unaligned data");
tcu::TestCaseGroup* const drawArraysGroup = new tcu::TestCaseGroup(m_testCtx, "drawarrays", "draw arrays");
tcu::TestCaseGroup* const drawElementsGroup = new tcu::TestCaseGroup(m_testCtx, "drawelements", "draw elements");
addChild(unalignedGroup);
addChild(drawArraysGroup);
addChild(drawElementsGroup);
// .unaligned_data
{
unalignedGroup->addChild(new RandomGroup(m_context, "random", "random draw commands."));
}
// .drawarrays
{
drawArraysGroup->addChild(new InvalidDrawCase(m_context, "data_over_bounds_with_count", "Draw arrays vertex elements beyond the array end are accessed", InvalidDrawCase::DRAW_ARRAYS, InvalidDrawCase::INVALID_DATA_COUNT));
drawArraysGroup->addChild(new InvalidDrawCase(m_context, "data_over_bounds_with_first", "Draw arrays vertex elements beyond the array end are accessed", InvalidDrawCase::DRAW_ARRAYS, InvalidDrawCase::INVALID_DATA_FIRST));
drawArraysGroup->addChild(new InvalidDrawCase(m_context, "data_over_bounds_with_primcount", "Draw arrays vertex elements beyond the array end are accessed", InvalidDrawCase::DRAW_ARRAYS, InvalidDrawCase::INVALID_DATA_INSTANCED));
drawArraysGroup->addChild(new InvalidDrawCase(m_context, "reserved_non_zero", "reservedMustBeZero is set to non-zero value", InvalidDrawCase::DRAW_ARRAYS, InvalidDrawCase::INVALID_RESERVED));
}
// .drawelements
{
drawElementsGroup->addChild(new InvalidDrawCase(m_context, "data_over_bounds_with_count", "Draw elements vertex elements beyond the array end are accessed", InvalidDrawCase::DRAW_ELEMENTS, InvalidDrawCase::INVALID_DATA_COUNT));
drawElementsGroup->addChild(new InvalidDrawCase(m_context, "data_over_bounds_with_basevertex", "Draw elements vertex elements beyond the array end are accessed", InvalidDrawCase::DRAW_ELEMENTS, InvalidDrawCase::INVALID_DATA_FIRST));
drawElementsGroup->addChild(new InvalidDrawCase(m_context, "data_over_bounds_with_indices", "Draw elements vertex elements beyond the array end are accessed", InvalidDrawCase::DRAW_ELEMENTS, InvalidDrawCase::INVALID_INDEX));
drawElementsGroup->addChild(new InvalidDrawCase(m_context, "data_over_bounds_with_primcount", "Draw elements vertex elements beyond the array end are accessed", InvalidDrawCase::DRAW_ELEMENTS, InvalidDrawCase::INVALID_DATA_INSTANCED));
drawElementsGroup->addChild(new InvalidDrawCase(m_context, "index_over_bounds_with_count", "Draw elements index elements beyond the array end are accessed", InvalidDrawCase::DRAW_ELEMENTS, InvalidDrawCase::INVALID_INDEX_COUNT));
drawElementsGroup->addChild(new InvalidDrawCase(m_context, "index_over_bounds_with_firstindex", "Draw elements index elements beyond the array end are accessed", InvalidDrawCase::DRAW_ELEMENTS, InvalidDrawCase::INVALID_INDEX_FIRST));
drawElementsGroup->addChild(new InvalidDrawCase(m_context, "reserved_non_zero", "reservedMustBeZero is set to non-zero value", InvalidDrawCase::DRAW_ELEMENTS, InvalidDrawCase::INVALID_RESERVED));
}
}
} // Stress
} // gles31
} // deqp
|
#include <QtGlobal>
// Automatically generated by extract_strings.py
#ifdef __GNUC__
#define UNUSED __attribute__((unused))
#else
#define UNUSED
#endif
static const char UNUSED *zencoin_strings[] = {
QT_TRANSLATE_NOOP("zencoin-core", ""
"(1 = keep tx meta data e.g. account owner and payment request information, 2 "
"= drop tx meta data)"),
QT_TRANSLATE_NOOP("zencoin-core", ""
"Allow JSON-RPC connections from specified source. Valid for <ip> are a "
"single IP (e.g. 1.2.3.4), a network/netmask (e.g. 1.2.3.4/255.255.255.0) or "
"a network/CIDR (e.g. 1.2.3.4/24). This option can be specified multiple times"),
QT_TRANSLATE_NOOP("zencoin-core", ""
"An error occurred while setting up the RPC address %s port %u for listening: "
"%s"),
QT_TRANSLATE_NOOP("zencoin-core", ""
"Bind to given address and always listen on it. Use [host]:port notation for "
"IPv6"),
QT_TRANSLATE_NOOP("zencoin-core", ""
"Bind to given address and whitelist peers connecting to it. Use [host]:port "
"notation for IPv6"),
QT_TRANSLATE_NOOP("zencoin-core", ""
"Bind to given address to listen for JSON-RPC connections. Use [host]:port "
"notation for IPv6. This option can be specified multiple times (default: "
"bind to all interfaces)"),
QT_TRANSLATE_NOOP("zencoin-core", ""
"Cannot obtain a lock on data directory %s. zencoin Core is probably already "
"running."),
QT_TRANSLATE_NOOP("zencoin-core", ""
"Continuously rate-limit free transactions to <n>*1000 bytes per minute "
"(default:%u)"),
QT_TRANSLATE_NOOP("zencoin-core", ""
"Create new files with system default permissions, instead of umask 077 (only "
"effective with disabled wallet functionality)"),
QT_TRANSLATE_NOOP("zencoin-core", ""
"Delete all wallet transactions and only recover those parts of the "
"blockchain through -rescan on startup"),
QT_TRANSLATE_NOOP("zencoin-core", ""
"Disable all zencoin specific functionality (Masternodes, Obfuscation, SwiftX) "
"(0-1, default: %u)"),
QT_TRANSLATE_NOOP("zencoin-core", ""
"Distributed under the MIT software license, see the accompanying file "
"COPYING or <http://www.opensource.org/licenses/mit-license.php>."),
QT_TRANSLATE_NOOP("zencoin-core", ""
"Enable spork administration functionality with the appropriate private key."),
QT_TRANSLATE_NOOP("zencoin-core", ""
"Enable swifttx, show confirmations for locked transactions (bool, default: "
"%s)"),
QT_TRANSLATE_NOOP("zencoin-core", ""
"Enable use of automated obfuscation for funds stored in this wallet (0-1, "
"default: %u)"),
QT_TRANSLATE_NOOP("zencoin-core", ""
"Enter regression test mode, which uses a special chain in which blocks can "
"be solved instantly."),
QT_TRANSLATE_NOOP("zencoin-core", ""
"Error: Listening for incoming connections failed (listen returned error %s)"),
QT_TRANSLATE_NOOP("zencoin-core", ""
"Error: Unsupported argument -socks found. Setting SOCKS version isn't "
"possible anymore, only SOCKS5 proxies are supported."),
QT_TRANSLATE_NOOP("zencoin-core", ""
"Execute command when a relevant alert is received or we see a really long "
"fork (%s in cmd is replaced by message)"),
QT_TRANSLATE_NOOP("zencoin-core", ""
"Execute command when a wallet transaction changes (%s in cmd is replaced by "
"TxID)"),
QT_TRANSLATE_NOOP("zencoin-core", ""
"Execute command when the best block changes (%s in cmd is replaced by block "
"hash)"),
QT_TRANSLATE_NOOP("zencoin-core", ""
"Fees (in zencoin/Kb) smaller than this are considered zero fee for relaying "
"(default: %s)"),
QT_TRANSLATE_NOOP("zencoin-core", ""
"Fees (in zencoin/Kb) smaller than this are considered zero fee for transaction "
"creation (default: %s)"),
QT_TRANSLATE_NOOP("zencoin-core", ""
"Flush database activity from memory pool to disk log every <n> megabytes "
"(default: %u)"),
QT_TRANSLATE_NOOP("zencoin-core", ""
"Found unconfirmed denominated outputs, will wait till they confirm to "
"continue."),
QT_TRANSLATE_NOOP("zencoin-core", ""
"How thorough the block verification of -checkblocks is (0-4, default: %u)"),
QT_TRANSLATE_NOOP("zencoin-core", ""
"If paytxfee is not set, include enough fee so transactions begin "
"confirmation on average within n blocks (default: %u)"),
QT_TRANSLATE_NOOP("zencoin-core", ""
"In this mode -genproclimit controls how many blocks are generated "
"immediately."),
QT_TRANSLATE_NOOP("zencoin-core", ""
"Invalid amount for -maxtxfee=<amount>: '%s' (must be at least the minrelay "
"fee of %s to prevent stuck transactions)"),
QT_TRANSLATE_NOOP("zencoin-core", ""
"Keep the specified amount available for spending at all times (default: 0)"),
QT_TRANSLATE_NOOP("zencoin-core", ""
"Log transaction priority and fee per kB when mining blocks (default: %u)"),
QT_TRANSLATE_NOOP("zencoin-core", ""
"Maintain a full transaction index, used by the getrawtransaction rpc call "
"(default: %u)"),
QT_TRANSLATE_NOOP("zencoin-core", ""
"Maximum size of data in data carrier transactions we relay and mine "
"(default: %u)"),
QT_TRANSLATE_NOOP("zencoin-core", ""
"Maximum total fees to use in a single wallet transaction, setting too low "
"may abort large transactions (default: %s)"),
QT_TRANSLATE_NOOP("zencoin-core", ""
"Number of seconds to keep misbehaving peers from reconnecting (default: %u)"),
QT_TRANSLATE_NOOP("zencoin-core", ""
"Obfuscation uses exact denominated amounts to send funds, you might simply "
"need to anonymize some more coins."),
QT_TRANSLATE_NOOP("zencoin-core", ""
"Output debugging information (default: %u, supplying <category> is optional)"),
QT_TRANSLATE_NOOP("zencoin-core", ""
"Provide liquidity to Obfuscation by infrequently mixing coins on a continual "
"basis (0-100, default: %u, 1=very frequent, high fees, 100=very infrequent, "
"low fees)"),
QT_TRANSLATE_NOOP("zencoin-core", ""
"Query for peer addresses via DNS lookup, if low on addresses (default: 1 "
"unless -connect)"),
QT_TRANSLATE_NOOP("zencoin-core", ""
"Require high priority for relaying free or low-fee transactions (default:%u)"),
QT_TRANSLATE_NOOP("zencoin-core", ""
"Send trace/debug info to console instead of debug.log file (default: %u)"),
QT_TRANSLATE_NOOP("zencoin-core", ""
"Set maximum size of high-priority/low-fee transactions in bytes (default: %d)"),
QT_TRANSLATE_NOOP("zencoin-core", ""
"Set the number of script verification threads (%u to %d, 0 = auto, <0 = "
"leave that many cores free, default: %d)"),
QT_TRANSLATE_NOOP("zencoin-core", ""
"Set the number of threads for coin generation if enabled (-1 = all cores, "
"default: %d)"),
QT_TRANSLATE_NOOP("zencoin-core", ""
"Show N confirmations for a successfully locked transaction (0-9999, default: "
"%u)"),
QT_TRANSLATE_NOOP("zencoin-core", ""
"Support filtering of blocks and transaction with bloom filters (default: %u)"),
QT_TRANSLATE_NOOP("zencoin-core", ""
"SwiftX requires inputs with at least 6 confirmations, you might need to "
"wait a few minutes and try again."),
QT_TRANSLATE_NOOP("zencoin-core", ""
"This is a pre-release test build - use at your own risk - do not use for "
"staking or merchant applications!"),
QT_TRANSLATE_NOOP("zencoin-core", ""
"This product includes software developed by the OpenSSL Project for use in "
"the OpenSSL Toolkit <https://www.openssl.org/> and cryptographic software "
"written by Eric Young and UPnP software written by Thomas Bernard."),
QT_TRANSLATE_NOOP("zencoin-core", ""
"To use zencoind, or the -server option to zencoin-qt, you must set an rpcpassword "
"in the configuration file:\n"
"%s\n"
"It is recommended you use the following random password:\n"
"rpcuser=zencoinrpc\n"
"rpcpassword=%s\n"
"(you do not need to remember this password)\n"
"The username and password MUST NOT be the same.\n"
"If the file does not exist, create it with owner-readable-only file "
"permissions.\n"
"It is also recommended to set alertnotify so you are notified of problems;\n"
"for example: alertnotify=echo %%s | mail -s \"zencoin Alert\" admin@foo.com\n"),
QT_TRANSLATE_NOOP("zencoin-core", ""
"Unable to bind to %s on this computer. zencoin Core is probably already running."),
QT_TRANSLATE_NOOP("zencoin-core", ""
"Unable to locate enough Obfuscation denominated funds for this transaction."),
QT_TRANSLATE_NOOP("zencoin-core", ""
"Unable to locate enough Obfuscation non-denominated funds for this "
"transaction that are not equal 1000/3000/5000 zencoin."),
QT_TRANSLATE_NOOP("zencoin-core", ""
"Unable to locate enough funds for this transaction that are not equal 1000/3000/5000 "
"zencoin."),
QT_TRANSLATE_NOOP("zencoin-core", ""
"Use separate SOCKS5 proxy to reach peers via Tor hidden services (default: "
"%s)"),
QT_TRANSLATE_NOOP("zencoin-core", ""
"Warning: -maxtxfee is set very high! Fees this large could be paid on a "
"single transaction."),
QT_TRANSLATE_NOOP("zencoin-core", ""
"Warning: -paytxfee is set very high! This is the transaction fee you will "
"pay if you send a transaction."),
QT_TRANSLATE_NOOP("zencoin-core", ""
"Warning: Please check that your computer's date and time are correct! If "
"your clock is wrong zencoin Core will not work properly."),
QT_TRANSLATE_NOOP("zencoin-core", ""
"Warning: The network does not appear to fully agree! Some miners appear to "
"be experiencing issues."),
QT_TRANSLATE_NOOP("zencoin-core", ""
"Warning: We do not appear to fully agree with our peers! You may need to "
"upgrade, or other nodes may need to upgrade."),
QT_TRANSLATE_NOOP("zencoin-core", ""
"Warning: error reading wallet.dat! All keys read correctly, but transaction "
"data or address book entries might be missing or incorrect."),
QT_TRANSLATE_NOOP("zencoin-core", ""
"Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as "
"wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect "
"you should restore from a backup."),
QT_TRANSLATE_NOOP("zencoin-core", ""
"Whitelist peers connecting from the given netmask or IP address. Can be "
"specified multiple times."),
QT_TRANSLATE_NOOP("zencoin-core", ""
"Whitelisted peers cannot be DoS banned and their transactions are always "
"relayed, even if they are already in the mempool, useful e.g. for a gateway"),
QT_TRANSLATE_NOOP("zencoin-core", ""
"You must specify a masternodeprivkey in the configuration. Please see "
"documentation for help."),
QT_TRANSLATE_NOOP("zencoin-core", "(22288 could be used only on mainnet)"),
QT_TRANSLATE_NOOP("zencoin-core", "(default: %s)"),
QT_TRANSLATE_NOOP("zencoin-core", "(default: 1)"),
QT_TRANSLATE_NOOP("zencoin-core", "(must be 22288 for mainnet)"),
QT_TRANSLATE_NOOP("zencoin-core", "<category> can be:"),
QT_TRANSLATE_NOOP("zencoin-core", "Accept command line and JSON-RPC commands"),
QT_TRANSLATE_NOOP("zencoin-core", "Accept connections from outside (default: 1 if no -proxy or -connect)"),
QT_TRANSLATE_NOOP("zencoin-core", "Accept public REST requests (default: %u)"),
QT_TRANSLATE_NOOP("zencoin-core", "Acceptable ciphers (default: %s)"),
QT_TRANSLATE_NOOP("zencoin-core", "Add a node to connect to and attempt to keep the connection open"),
QT_TRANSLATE_NOOP("zencoin-core", "Allow DNS lookups for -addnode, -seednode and -connect"),
QT_TRANSLATE_NOOP("zencoin-core", "Already have that input."),
QT_TRANSLATE_NOOP("zencoin-core", "Always query for peer addresses via DNS lookup (default: %u)"),
QT_TRANSLATE_NOOP("zencoin-core", "Attempt to force blockchain corruption recovery"),
QT_TRANSLATE_NOOP("zencoin-core", "Attempt to recover private keys from a corrupt wallet.dat"),
QT_TRANSLATE_NOOP("zencoin-core", "Block creation options:"),
QT_TRANSLATE_NOOP("zencoin-core", "Can't denominate: no compatible inputs left."),
QT_TRANSLATE_NOOP("zencoin-core", "Can't find random Masternode."),
QT_TRANSLATE_NOOP("zencoin-core", "Can't mix while sync in progress."),
QT_TRANSLATE_NOOP("zencoin-core", "Cannot downgrade wallet"),
QT_TRANSLATE_NOOP("zencoin-core", "Cannot resolve -bind address: '%s'"),
QT_TRANSLATE_NOOP("zencoin-core", "Cannot resolve -externalip address: '%s'"),
QT_TRANSLATE_NOOP("zencoin-core", "Cannot resolve -whitebind address: '%s'"),
QT_TRANSLATE_NOOP("zencoin-core", "Cannot write default address"),
QT_TRANSLATE_NOOP("zencoin-core", "Collateral not valid."),
QT_TRANSLATE_NOOP("zencoin-core", "Connect only to the specified node(s)"),
QT_TRANSLATE_NOOP("zencoin-core", "Connect through SOCKS5 proxy"),
QT_TRANSLATE_NOOP("zencoin-core", "Connect to a node to retrieve peer addresses, and disconnect"),
QT_TRANSLATE_NOOP("zencoin-core", "Connection options:"),
QT_TRANSLATE_NOOP("zencoin-core", "Copyright (C) 2009-%i The Bitcoin Core Developers"),
QT_TRANSLATE_NOOP("zencoin-core", "Copyright (C) 2014-%i The Dash Core Developers"),
QT_TRANSLATE_NOOP("zencoin-core", "Copyright (C) 2015-%i The PIVX Core Developers"),
QT_TRANSLATE_NOOP("zencoin-core", "Copyright (C) 2015-%i The zencoin Core Developers"),
QT_TRANSLATE_NOOP("zencoin-core", "Corrupted block database detected"),
QT_TRANSLATE_NOOP("zencoin-core", "Could not parse -rpcbind value %s as network address"),
QT_TRANSLATE_NOOP("zencoin-core", "Could not parse masternode.conf"),
QT_TRANSLATE_NOOP("zencoin-core", "Debugging/Testing options:"),
QT_TRANSLATE_NOOP("zencoin-core", "Disable safemode, override a real safe mode event (default: %u)"),
QT_TRANSLATE_NOOP("zencoin-core", "Discover own IP address (default: 1 when listening and no -externalip)"),
QT_TRANSLATE_NOOP("zencoin-core", "Display the stake modifier calculations in the debug.log file."),
QT_TRANSLATE_NOOP("zencoin-core", "Display verbose coin stake messages in the debug.log file."),
QT_TRANSLATE_NOOP("zencoin-core", "Do not load the wallet and disable wallet RPC calls"),
QT_TRANSLATE_NOOP("zencoin-core", "Do you want to rebuild the block database now?"),
QT_TRANSLATE_NOOP("zencoin-core", "Done loading"),
QT_TRANSLATE_NOOP("zencoin-core", "Enable publish hash block in <address>"),
QT_TRANSLATE_NOOP("zencoin-core", "Enable publish hash transaction (locked via SwiftX) in <address>"),
QT_TRANSLATE_NOOP("zencoin-core", "Enable publish hash transaction in <address>"),
QT_TRANSLATE_NOOP("zencoin-core", "Enable publish raw block in <address>"),
QT_TRANSLATE_NOOP("zencoin-core", "Enable publish raw transaction (locked via SwiftX) in <address>"),
QT_TRANSLATE_NOOP("zencoin-core", "Enable publish raw transaction in <address>"),
QT_TRANSLATE_NOOP("zencoin-core", "Enable staking functionality (0-1, default: %u)"),
QT_TRANSLATE_NOOP("zencoin-core", "Enable the client to act as a masternode (0-1, default: %u)"),
QT_TRANSLATE_NOOP("zencoin-core", "Entries are full."),
QT_TRANSLATE_NOOP("zencoin-core", "Error connecting to Masternode."),
QT_TRANSLATE_NOOP("zencoin-core", "Error initializing block database"),
QT_TRANSLATE_NOOP("zencoin-core", "Error initializing wallet database environment %s!"),
QT_TRANSLATE_NOOP("zencoin-core", "Error loading block database"),
QT_TRANSLATE_NOOP("zencoin-core", "Error loading wallet.dat"),
QT_TRANSLATE_NOOP("zencoin-core", "Error loading wallet.dat: Wallet corrupted"),
QT_TRANSLATE_NOOP("zencoin-core", "Error loading wallet.dat: Wallet requires newer version of zencoin Core"),
QT_TRANSLATE_NOOP("zencoin-core", "Error opening block database"),
QT_TRANSLATE_NOOP("zencoin-core", "Error reading from database, shutting down."),
QT_TRANSLATE_NOOP("zencoin-core", "Error recovering public key."),
QT_TRANSLATE_NOOP("zencoin-core", "Error"),
QT_TRANSLATE_NOOP("zencoin-core", "Error: A fatal internal error occured, see debug.log for details"),
QT_TRANSLATE_NOOP("zencoin-core", "Error: Can't select current denominated inputs"),
QT_TRANSLATE_NOOP("zencoin-core", "Error: Disk space is low!"),
QT_TRANSLATE_NOOP("zencoin-core", "Error: Unsupported argument -tor found, use -onion."),
QT_TRANSLATE_NOOP("zencoin-core", "Error: Wallet locked, unable to create transaction!"),
QT_TRANSLATE_NOOP("zencoin-core", "Error: You already have pending entries in the Obfuscation pool"),
QT_TRANSLATE_NOOP("zencoin-core", "Failed to listen on any port. Use -listen=0 if you want this."),
QT_TRANSLATE_NOOP("zencoin-core", "Failed to read block"),
QT_TRANSLATE_NOOP("zencoin-core", "Fee (in zencoin/kB) to add to transactions you send (default: %s)"),
QT_TRANSLATE_NOOP("zencoin-core", "Finalizing transaction."),
QT_TRANSLATE_NOOP("zencoin-core", "Force safe mode (default: %u)"),
QT_TRANSLATE_NOOP("zencoin-core", "Found enough users, signing ( waiting %s )"),
QT_TRANSLATE_NOOP("zencoin-core", "Found enough users, signing ..."),
QT_TRANSLATE_NOOP("zencoin-core", "Generate coins (default: %u)"),
QT_TRANSLATE_NOOP("zencoin-core", "How many blocks to check at startup (default: %u, 0 = all)"),
QT_TRANSLATE_NOOP("zencoin-core", "If <category> is not supplied, output all debugging information."),
QT_TRANSLATE_NOOP("zencoin-core", "Importing..."),
QT_TRANSLATE_NOOP("zencoin-core", "Imports blocks from external blk000??.dat file"),
QT_TRANSLATE_NOOP("zencoin-core", "Include IP addresses in debug output (default: %u)"),
QT_TRANSLATE_NOOP("zencoin-core", "Incompatible mode."),
QT_TRANSLATE_NOOP("zencoin-core", "Incompatible version."),
QT_TRANSLATE_NOOP("zencoin-core", "Incorrect or no genesis block found. Wrong datadir for network?"),
QT_TRANSLATE_NOOP("zencoin-core", "Information"),
QT_TRANSLATE_NOOP("zencoin-core", "Initialization sanity check failed. zencoin Core is shutting down."),
QT_TRANSLATE_NOOP("zencoin-core", "Input is not valid."),
QT_TRANSLATE_NOOP("zencoin-core", "Insufficient funds."),
QT_TRANSLATE_NOOP("zencoin-core", "Invalid -onion address or hostname: '%s'"),
QT_TRANSLATE_NOOP("zencoin-core", "Invalid -proxy address or hostname: '%s'"),
QT_TRANSLATE_NOOP("zencoin-core", "Invalid amount for -maxtxfee=<amount>: '%s'"),
QT_TRANSLATE_NOOP("zencoin-core", "Invalid amount for -minrelaytxfee=<amount>: '%s'"),
QT_TRANSLATE_NOOP("zencoin-core", "Invalid amount for -mintxfee=<amount>: '%s'"),
QT_TRANSLATE_NOOP("zencoin-core", "Invalid amount for -paytxfee=<amount>: '%s' (must be at least %s)"),
QT_TRANSLATE_NOOP("zencoin-core", "Invalid amount for -paytxfee=<amount>: '%s'"),
QT_TRANSLATE_NOOP("zencoin-core", "Invalid amount for -reservebalance=<amount>"),
QT_TRANSLATE_NOOP("zencoin-core", "Invalid masternodeprivkey. Please see documenation."),
QT_TRANSLATE_NOOP("zencoin-core", "Invalid netmask specified in -whitelist: '%s'"),
QT_TRANSLATE_NOOP("zencoin-core", "Invalid port detected in masternode.conf"),
QT_TRANSLATE_NOOP("zencoin-core", "Invalid private key."),
QT_TRANSLATE_NOOP("zencoin-core", "Invalid script detected."),
QT_TRANSLATE_NOOP("zencoin-core", "Keep N zencoin anonymized (default: %u)"),
QT_TRANSLATE_NOOP("zencoin-core", "Keep at most <n> unconnectable transactions in memory (default: %u)"),
QT_TRANSLATE_NOOP("zencoin-core", "Last Obfuscation was too recent."),
QT_TRANSLATE_NOOP("zencoin-core", "Last successful Obfuscation action was too recent."),
QT_TRANSLATE_NOOP("zencoin-core", "Limit size of signature cache to <n> entries (default: %u)"),
QT_TRANSLATE_NOOP("zencoin-core", "Line: %d"),
QT_TRANSLATE_NOOP("zencoin-core", "Listen for JSON-RPC connections on <port> (default: %u or testnet: %u)"),
QT_TRANSLATE_NOOP("zencoin-core", "Listen for connections on <port> (default: %u or testnet: %u)"),
QT_TRANSLATE_NOOP("zencoin-core", "Loading addresses..."),
QT_TRANSLATE_NOOP("zencoin-core", "Loading block index..."),
QT_TRANSLATE_NOOP("zencoin-core", "Loading masternode cache..."),
QT_TRANSLATE_NOOP("zencoin-core", "Loading masternode payment cache..."),
QT_TRANSLATE_NOOP("zencoin-core", "Loading wallet... (%3.2f %%)"),
QT_TRANSLATE_NOOP("zencoin-core", "Loading wallet..."),
QT_TRANSLATE_NOOP("zencoin-core", "Lock is already in place."),
QT_TRANSLATE_NOOP("zencoin-core", "Lock masternodes from masternode configuration file (default: %u)"),
QT_TRANSLATE_NOOP("zencoin-core", "Maintain at most <n> connections to peers (default: %u)"),
QT_TRANSLATE_NOOP("zencoin-core", "Masternode options:"),
QT_TRANSLATE_NOOP("zencoin-core", "Masternode queue is full."),
QT_TRANSLATE_NOOP("zencoin-core", "Masternode:"),
QT_TRANSLATE_NOOP("zencoin-core", "Maximum per-connection receive buffer, <n>*1000 bytes (default: %u)"),
QT_TRANSLATE_NOOP("zencoin-core", "Maximum per-connection send buffer, <n>*1000 bytes (default: %u)"),
QT_TRANSLATE_NOOP("zencoin-core", "Missing input transaction information."),
QT_TRANSLATE_NOOP("zencoin-core", "Mixing in progress..."),
QT_TRANSLATE_NOOP("zencoin-core", "Need to specify a port with -whitebind: '%s'"),
QT_TRANSLATE_NOOP("zencoin-core", "No Masternodes detected."),
QT_TRANSLATE_NOOP("zencoin-core", "No compatible Masternode found."),
QT_TRANSLATE_NOOP("zencoin-core", "No funds detected in need of denominating."),
QT_TRANSLATE_NOOP("zencoin-core", "No matching denominations found for mixing."),
QT_TRANSLATE_NOOP("zencoin-core", "Node relay options:"),
QT_TRANSLATE_NOOP("zencoin-core", "Non-standard public key detected."),
QT_TRANSLATE_NOOP("zencoin-core", "Not compatible with existing transactions."),
QT_TRANSLATE_NOOP("zencoin-core", "Not enough file descriptors available."),
QT_TRANSLATE_NOOP("zencoin-core", "Not in the Masternode list."),
QT_TRANSLATE_NOOP("zencoin-core", "Number of automatic wallet backups (default: 10)"),
QT_TRANSLATE_NOOP("zencoin-core", "Obfuscation is idle."),
QT_TRANSLATE_NOOP("zencoin-core", "Obfuscation options:"),
QT_TRANSLATE_NOOP("zencoin-core", "Obfuscation request complete:"),
QT_TRANSLATE_NOOP("zencoin-core", "Obfuscation request incomplete:"),
QT_TRANSLATE_NOOP("zencoin-core", "Only accept block chain matching built-in checkpoints (default: %u)"),
QT_TRANSLATE_NOOP("zencoin-core", "Only connect to nodes in network <net> (ipv4, ipv6 or onion)"),
QT_TRANSLATE_NOOP("zencoin-core", "Options:"),
QT_TRANSLATE_NOOP("zencoin-core", "Password for JSON-RPC connections"),
QT_TRANSLATE_NOOP("zencoin-core", "Prepend debug output with timestamp (default: %u)"),
QT_TRANSLATE_NOOP("zencoin-core", "Print version and exit"),
QT_TRANSLATE_NOOP("zencoin-core", "RPC SSL options: (see the Bitcoin Wiki for SSL setup instructions)"),
QT_TRANSLATE_NOOP("zencoin-core", "RPC server options:"),
QT_TRANSLATE_NOOP("zencoin-core", "RPC support for HTTP persistent connections (default: %d)"),
QT_TRANSLATE_NOOP("zencoin-core", "Randomly drop 1 of every <n> network messages"),
QT_TRANSLATE_NOOP("zencoin-core", "Randomly fuzz 1 of every <n> network messages"),
QT_TRANSLATE_NOOP("zencoin-core", "Rebuild block chain index from current blk000??.dat files"),
QT_TRANSLATE_NOOP("zencoin-core", "Receive and display P2P network alerts (default: %u)"),
QT_TRANSLATE_NOOP("zencoin-core", "Relay and mine data carrier transactions (default: %u)"),
QT_TRANSLATE_NOOP("zencoin-core", "Relay non-P2SH multisig (default: %u)"),
QT_TRANSLATE_NOOP("zencoin-core", "Rescan the block chain for missing wallet transactions"),
QT_TRANSLATE_NOOP("zencoin-core", "Rescanning..."),
QT_TRANSLATE_NOOP("zencoin-core", "Run a thread to flush wallet periodically (default: %u)"),
QT_TRANSLATE_NOOP("zencoin-core", "Run in the background as a daemon and accept commands"),
QT_TRANSLATE_NOOP("zencoin-core", "Send transactions as zero-fee transactions if possible (default: %u)"),
QT_TRANSLATE_NOOP("zencoin-core", "Server certificate file (default: %s)"),
QT_TRANSLATE_NOOP("zencoin-core", "Server private key (default: %s)"),
QT_TRANSLATE_NOOP("zencoin-core", "Session not complete!"),
QT_TRANSLATE_NOOP("zencoin-core", "Session timed out."),
QT_TRANSLATE_NOOP("zencoin-core", "Set database cache size in megabytes (%d to %d, default: %d)"),
QT_TRANSLATE_NOOP("zencoin-core", "Set external address:port to get to this masternode (example: %s)"),
QT_TRANSLATE_NOOP("zencoin-core", "Set key pool size to <n> (default: %u)"),
QT_TRANSLATE_NOOP("zencoin-core", "Set maximum block size in bytes (default: %d)"),
QT_TRANSLATE_NOOP("zencoin-core", "Set minimum block size in bytes (default: %u)"),
QT_TRANSLATE_NOOP("zencoin-core", "Set the masternode private key"),
QT_TRANSLATE_NOOP("zencoin-core", "Set the number of threads to service RPC calls (default: %d)"),
QT_TRANSLATE_NOOP("zencoin-core", "Sets the DB_PRIVATE flag in the wallet db environment (default: %u)"),
QT_TRANSLATE_NOOP("zencoin-core", "Show all debugging options (usage: --help -help-debug)"),
QT_TRANSLATE_NOOP("zencoin-core", "Shrink debug.log file on client startup (default: 1 when no -debug)"),
QT_TRANSLATE_NOOP("zencoin-core", "Signing failed."),
QT_TRANSLATE_NOOP("zencoin-core", "Signing timed out."),
QT_TRANSLATE_NOOP("zencoin-core", "Signing transaction failed"),
QT_TRANSLATE_NOOP("zencoin-core", "Specify configuration file (default: %s)"),
QT_TRANSLATE_NOOP("zencoin-core", "Specify connection timeout in milliseconds (minimum: 1, default: %d)"),
QT_TRANSLATE_NOOP("zencoin-core", "Specify data directory"),
QT_TRANSLATE_NOOP("zencoin-core", "Specify masternode configuration file (default: %s)"),
QT_TRANSLATE_NOOP("zencoin-core", "Specify pid file (default: %s)"),
QT_TRANSLATE_NOOP("zencoin-core", "Specify wallet file (within data directory)"),
QT_TRANSLATE_NOOP("zencoin-core", "Specify your own public address"),
QT_TRANSLATE_NOOP("zencoin-core", "Spend unconfirmed change when sending transactions (default: %u)"),
QT_TRANSLATE_NOOP("zencoin-core", "Staking options:"),
QT_TRANSLATE_NOOP("zencoin-core", "Stop running after importing blocks from disk (default: %u)"),
QT_TRANSLATE_NOOP("zencoin-core", "Submitted following entries to masternode: %u / %d"),
QT_TRANSLATE_NOOP("zencoin-core", "Submitted to masternode, waiting for more entries ( %u / %d ) %s"),
QT_TRANSLATE_NOOP("zencoin-core", "Submitted to masternode, waiting in queue %s"),
QT_TRANSLATE_NOOP("zencoin-core", "SwiftX options:"),
QT_TRANSLATE_NOOP("zencoin-core", "Synchronization failed"),
QT_TRANSLATE_NOOP("zencoin-core", "Synchronization finished"),
QT_TRANSLATE_NOOP("zencoin-core", "Synchronization pending..."),
QT_TRANSLATE_NOOP("zencoin-core", "Synchronizing masternode winners..."),
QT_TRANSLATE_NOOP("zencoin-core", "Synchronizing masternodes..."),
QT_TRANSLATE_NOOP("zencoin-core", "Synchronizing sporks..."),
QT_TRANSLATE_NOOP("zencoin-core", "This help message"),
QT_TRANSLATE_NOOP("zencoin-core", "This is experimental software."),
QT_TRANSLATE_NOOP("zencoin-core", "This is intended for regression testing tools and app development."),
QT_TRANSLATE_NOOP("zencoin-core", "This is not a Masternode."),
QT_TRANSLATE_NOOP("zencoin-core", "Threshold for disconnecting misbehaving peers (default: %u)"),
QT_TRANSLATE_NOOP("zencoin-core", "Transaction amount too small"),
QT_TRANSLATE_NOOP("zencoin-core", "Transaction amounts must be positive"),
QT_TRANSLATE_NOOP("zencoin-core", "Transaction created successfully."),
QT_TRANSLATE_NOOP("zencoin-core", "Transaction fees are too high."),
QT_TRANSLATE_NOOP("zencoin-core", "Transaction not valid."),
QT_TRANSLATE_NOOP("zencoin-core", "Transaction too large for fee policy"),
QT_TRANSLATE_NOOP("zencoin-core", "Transaction too large"),
QT_TRANSLATE_NOOP("zencoin-core", "Transmitting final transaction."),
QT_TRANSLATE_NOOP("zencoin-core", "Unable to bind to %s on this computer (bind returned error %s)"),
QT_TRANSLATE_NOOP("zencoin-core", "Unable to sign spork message, wrong key?"),
QT_TRANSLATE_NOOP("zencoin-core", "Unknown network specified in -onlynet: '%s'"),
QT_TRANSLATE_NOOP("zencoin-core", "Unknown state: id = %u"),
QT_TRANSLATE_NOOP("zencoin-core", "Upgrade wallet to latest format"),
QT_TRANSLATE_NOOP("zencoin-core", "Use N separate masternodes to anonymize funds (2-8, default: %u)"),
QT_TRANSLATE_NOOP("zencoin-core", "Use OpenSSL (https) for JSON-RPC connections"),
QT_TRANSLATE_NOOP("zencoin-core", "Use UPnP to map the listening port (default: %u)"),
QT_TRANSLATE_NOOP("zencoin-core", "Use UPnP to map the listening port (default: 1 when listening)"),
QT_TRANSLATE_NOOP("zencoin-core", "Use the test network"),
QT_TRANSLATE_NOOP("zencoin-core", "Username for JSON-RPC connections"),
QT_TRANSLATE_NOOP("zencoin-core", "Value more than Obfuscation pool maximum allows."),
QT_TRANSLATE_NOOP("zencoin-core", "Verifying blocks..."),
QT_TRANSLATE_NOOP("zencoin-core", "Verifying wallet..."),
QT_TRANSLATE_NOOP("zencoin-core", "Wallet %s resides outside data directory %s"),
QT_TRANSLATE_NOOP("zencoin-core", "Wallet is locked."),
QT_TRANSLATE_NOOP("zencoin-core", "Wallet needed to be rewritten: restart zencoin Core to complete"),
QT_TRANSLATE_NOOP("zencoin-core", "Wallet options:"),
QT_TRANSLATE_NOOP("zencoin-core", "Wallet window title"),
QT_TRANSLATE_NOOP("zencoin-core", "Warning"),
QT_TRANSLATE_NOOP("zencoin-core", "Warning: This version is obsolete, upgrade required!"),
QT_TRANSLATE_NOOP("zencoin-core", "Warning: Unsupported argument -benchmark ignored, use -debug=bench."),
QT_TRANSLATE_NOOP("zencoin-core", "Warning: Unsupported argument -debugnet ignored, use -debug=net."),
QT_TRANSLATE_NOOP("zencoin-core", "Will retry..."),
QT_TRANSLATE_NOOP("zencoin-core", "You need to rebuild the database using -reindex to change -txindex"),
QT_TRANSLATE_NOOP("zencoin-core", "Your entries added successfully."),
QT_TRANSLATE_NOOP("zencoin-core", "Your transaction was accepted into the pool!"),
QT_TRANSLATE_NOOP("zencoin-core", "Zapping all transactions from wallet..."),
QT_TRANSLATE_NOOP("zencoin-core", "ZeroMQ notification options:"),
QT_TRANSLATE_NOOP("zencoin-core", "on startup"),
QT_TRANSLATE_NOOP("zencoin-core", "wallet.dat corrupt, salvage failed"),
};
|
#include "Random.h"
static const int A = 48271;
static const int M = 2147483647;
static const int Q = M / A;
static const int R = M % A;
/**
* Construct with initialValue for the state.
*/
Random::Random( int initialValue )
{
if( initialValue < 0 )
initialValue += M;
state = initialValue;
if( state == 0 )
state = 1;
}
/**
* Return a pseudorandom int, and change the
* internal state.
*/
int Random::randomInt( )
{
int tmpState = A * ( state % Q ) - R * ( state / Q );
if( tmpState >= 0 )
state = tmpState;
else
state = tmpState + M;
return state;
}
/**
* Return a pseudorandom int, and change the
* internal state. DOES NOT WORK.
*/
int Random::randomIntWRONG( )
{
return state = ( A * state ) % M;
}
/**
* Return a pseudorandom double in the open range 0..1
* and change the internal state.
*/
double Random::random0_1( )
{
return static_cast<double>( randomInt( ) ) / M;
}
/**
* Return an int in the closed range [low,high], and
* change the internal state. This is a poor implementation and
* will be biased toward some numbers, especially if the range is large.
*/
int Random::randomInt( int low, int high )
{
double partitionSize = static_cast<double>( M ) / ( high - low + 1 );
return static_cast<int>( randomInt( ) / partitionSize ) + low;
}
|
#include "MetaImageExporter.hpp"
#include "FAST/Data/Image.hpp"
#include <fstream>
#include <zlib/zlib.h>
namespace fast {
MetaImageExporter::MetaImageExporter() : FileExporter() {
createInputPort<Image>(0);
mIsModified = true;
mUseCompression = false;
}
MetaImageExporter::MetaImageExporter(std::string filename, bool compress) : FileExporter(filename) {
createInputPort<Image>(0);
setCompression(compress);
}
template <class T>
inline std::size_t writeToRawFile(std::string filename, T * data, unsigned int numberOfElements, bool useCompression) {
// TODO use mapped_file_sink form boost instead
FILE* file = fopen(filename.c_str(), "wb");
if(file == NULL) {
throw Exception("Could not open file " + filename + " for writing");
}
std::size_t returnSize;
if(useCompression) {
// Have to allocate enough memory for compression: 1.1*DATA_SIZE_IN_BYTES + 12
std::size_t sizeDataCompressed = compressBound(sizeof(T)*numberOfElements);
std::size_t sizeDataOriginal = sizeof(T)*numberOfElements;
Bytef* writeData = (Bytef*)malloc(sizeDataCompressed);
int z_result = compress(
(Bytef*)writeData,
(uLongf*)&sizeDataCompressed,
(Bytef*)data,
sizeDataOriginal
);
switch(z_result) {
case Z_OK:
break;
case Z_MEM_ERROR:
throw Exception("Out of memory while compressing raw file");
break;
case Z_BUF_ERROR:
throw Exception("Output buffer was not large enough while compressing raw file");
break;
}
// sizeDataCompressed was changed after compress call
fwrite(writeData, sizeDataCompressed, 1, file);
returnSize = sizeDataCompressed;
fclose(file);
free(writeData);
} else {
returnSize = sizeof(T)*numberOfElements;
fwrite(data, sizeof(T), numberOfElements, file);
fclose(file);
}
return returnSize;
}
void MetaImageExporter::execute() {
if(m_filename == "")
throw Exception("No filename was given to the MetaImageExporter");
Image::pointer input = getInputData<Image>();
// Check that filename ends with .mhd if not, append it
if(m_filename.substr(m_filename.length()-4) != ".mhd") {
m_filename += ".mhd";
}
// Create mhd file
std::fstream mhdFile;
mhdFile.open(m_filename.c_str(), std::fstream::out);
if(!mhdFile.is_open()) {
throw Exception("Could not open file " + m_filename + " for writing");
}
mhdFile << "ObjectType = Image\n";
if(input->getDimensions() == 2) {
mhdFile << "NDims = 2\n";
mhdFile << "DimSize = " << input->getWidth() << " " <<
input->getHeight() << "\n";
} else {
mhdFile << "NDims = 3\n";
mhdFile << "DimSize = " << input->getWidth() << " " <<
input->getHeight() << " " << input->getDepth() << "\n";
}
mhdFile << "BinaryData = True\n";
mhdFile << "ElementNumberOfChannels = " << input->getNrOfChannels() << "\n";
mhdFile << "ElementSpacing = " << input->getSpacing()[0] << " " << input->getSpacing()[1];
if(input->getDimensions() == 3)
mhdFile << " " << input->getSpacing()[2];
mhdFile << "\n";
auto T = SceneGraph::getEigenTransformFromData(input);
mhdFile << "Offset = " << T.translation().x() << " " << T.translation().y() << " " << T.translation().z() << "\n";
mhdFile << "TransformMatrix =";
for(unsigned int i = 0; i < 3; i++) {
for(unsigned int j = 0; j < 3; j++) {
mhdFile << " " << T.matrix()(j,i);
}}
mhdFile << "\n";
mhdFile << "Timestamp = " << std::to_string(input->getCreationTimestamp()) << "\n";
// Save to raw file
// set rawFilename, by removing the end .mhd from m_filename and add .raw
std::string extension = ".raw";
if(mUseCompression) {
extension = ".zraw";
}
std::string rawFilename = m_filename.substr(0,m_filename.length()-4) + extension;
const unsigned int numberOfElements = input->getWidth()*input->getHeight()*
input->getDepth()*input->getNrOfChannels();
ImageAccess::pointer access = input->getImageAccess(ACCESS_READ);
void* data = access->get();
std::size_t compressedSize;
switch(input->getDataType()) {
case TYPE_FLOAT:
mhdFile << "ElementType = MET_FLOAT\n";
compressedSize = writeToRawFile<float>(rawFilename,(float*)data,numberOfElements,mUseCompression);
break;
case TYPE_UINT8:
mhdFile << "ElementType = MET_UCHAR\n";
compressedSize = writeToRawFile<uchar>(rawFilename,(uchar*)data,numberOfElements,mUseCompression);
break;
case TYPE_INT8:
mhdFile << "ElementType = MET_CHAR\n";
compressedSize = writeToRawFile<char>(rawFilename,(char*)data,numberOfElements,mUseCompression);
break;
case TYPE_UINT16:
mhdFile << "ElementType = MET_USHORT\n";
compressedSize = writeToRawFile<ushort>(rawFilename,(ushort*)data,numberOfElements,mUseCompression);
break;
case TYPE_INT16:
mhdFile << "ElementType = MET_SHORT\n";
compressedSize = writeToRawFile<short>(rawFilename,(short*)data,numberOfElements,mUseCompression);
break;
}
if(mUseCompression) {
mhdFile << "CompressedData = True" << "\n";
mhdFile << "CompressedDataSize = " << compressedSize << "\n";
}
// Add metadata
for(auto&& item : mMetadata) {
mhdFile << item.first << " = " << item.second << "\n";
}
for(auto&& item : input->getMetadata()) {
mhdFile << item.first << " = " << item.second << "\n";
}
// Remove any path information from rawFilename
std::size_t slashPos = rawFilename.find_last_of('/');
if(slashPos != std::string::npos) {
rawFilename = rawFilename.substr(slashPos+1);
}
mhdFile << "ElementDataFile = " << rawFilename << "\n";
mhdFile.close();
}
void MetaImageExporter::enableCompression() {
mUseCompression = true;
mIsModified = true;
}
void MetaImageExporter::disableCompression() {
mUseCompression = false;
mIsModified = true;
}
void MetaImageExporter::setCompression(bool compress) {
mUseCompression = compress;
mIsModified = true;
}
void MetaImageExporter::setMetadata(std::string key, std::string value) {
mMetadata[key] = value;
}
}
|
/**
* Copyright (c) 2015 by Contributors
*/
#include <unistd.h>
#include <thread>
#include <chrono>
#include "ps/internal/postoffice.h"
#include "ps/internal/message.h"
#include "ps/base.h"
namespace ps {
Postoffice::Postoffice() : van_(new Van()) {
const char* val = NULL;
val = CHECK_NOTNULL(getenv("DMLC_NUM_WORKER"));
num_workers_ = atoi(val);
val = CHECK_NOTNULL(getenv("DMLC_NUM_SERVER"));
num_servers_ = atoi(val);
val = CHECK_NOTNULL(getenv("TENSORFLOW_ROLE"));
std::string role(val);
is_worker_ = role == "worker";
is_server_ = role == "server";
is_scheduler_ = role == "scheduler";
}
void Postoffice::Start(const char* argv0) {
// init glog
if (argv0) {
dmlc::InitLogging(argv0);
} else {
dmlc::InitLogging("ps-lite\0");
}
// init node info.
for (int i = 0; i < num_workers_; ++i) {
int id = WorkerRankToID(i);
for (int g : {id, kWorkerGroup, kWorkerGroup + kServerGroup,
kWorkerGroup + kScheduler,
kWorkerGroup + kServerGroup + kScheduler}) {
node_ids_[g].push_back(id);
}
}
for (int i = 0; i < num_servers_; ++i) {
int id = ServerRankToID(i);
for (int g : {id, kServerGroup, kWorkerGroup + kServerGroup,
kServerGroup + kScheduler,
kWorkerGroup + kServerGroup + kScheduler}) {
node_ids_[g].push_back(id);
}
}
for (int g : {kScheduler, kScheduler + kServerGroup + kWorkerGroup,
kScheduler + kWorkerGroup, kScheduler + kServerGroup}) {
node_ids_[g].push_back(kScheduler);
}
// start van
van_->Start();
// do a barrier here
Barrier(kWorkerGroup + kServerGroup + kScheduler);
}
void Postoffice::Finalize() {
Barrier(kWorkerGroup + kServerGroup + kScheduler);
van_->Stop();
if (exit_callback_) exit_callback_();
}
void Postoffice::AddCustomer(Customer* customer) {
std::lock_guard<std::mutex> lk(mu_);
int id = CHECK_NOTNULL(customer)->id();
CHECK_EQ(customers_.count(id), (size_t)0) << "id " << id << " already exists";
customers_[id] = customer;
}
void Postoffice::RemoveCustomer(Customer* customer) {
std::lock_guard<std::mutex> lk(mu_);
int id = CHECK_NOTNULL(customer)->id();
customers_.erase(id);
}
Customer* Postoffice::GetCustomer(int id, int timeout) const {
Customer* obj = nullptr;
for (int i = 0; i < timeout*1000+1; ++i) {
{
std::lock_guard<std::mutex> lk(mu_);
const auto it = customers_.find(id);
if (it != customers_.end()) {
obj = it->second;
break;
}
}
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
return obj;
}
void Postoffice::Barrier(int node_group) {
if (GetNodeIDs(node_group).size() <= 1) return;
auto role = van_->my_node().role;
if (role == Node::SCHEDULER) {
CHECK(node_group & kScheduler);
} else if (role == Node::WORKER) {
CHECK(node_group & kWorkerGroup);
} else if (role == Node::SERVER) {
CHECK(node_group & kServerGroup);
}
std::unique_lock<std::mutex> ulk(barrier_mu_);
barrier_done_ = false;
Message req;
req.meta.recver = kScheduler;
req.meta.request = true;
req.meta.control.cmd = Control::BARRIER;
req.meta.control.barrier_group = node_group;
CHECK_GT(van_->Send(req), 0);
barrier_cond_.wait(ulk, [this] {
return barrier_done_;
});
}
const std::vector<Range>& Postoffice::GetServerKeyRanges() {
if (server_key_ranges_.empty()) {
for (int i = 0; i < num_servers_; ++i) {
server_key_ranges_.push_back(Range(
kMaxKey / num_servers_ * i,
kMaxKey / num_servers_ * (i+1)));
}
}
return server_key_ranges_;
}
void Postoffice::Manage(const Message& recv) {
CHECK(!recv.meta.control.empty());
const auto& ctrl = recv.meta.control;
if (ctrl.cmd == Control::BARRIER && !recv.meta.request) {
barrier_mu_.lock();
barrier_done_ = true;
barrier_mu_.unlock();
barrier_cond_.notify_all();
}
}
} // namespace ps
|
//
// Character.cpp for Character in /home/gwendoline/Epitech/Tek2/Piscine_cpp/piscine_cpp_d09/ex00
//
// Made by Gwendoline Rodriguez
// Login <gwendoline@epitech.net>
//
// Started on Thu Jan 14 09:51:59 2016 Gwendoline Rodriguez
// Last update Thu Jan 14 11:52:35 2016 Gwendoline Rodriguez
//
#include "Character.hh"
Character::Character(const std::string& name, int lvl) : name(name), Range(CLOSE) {
this->lvl = lvl;
this->Pv = 100;
this->Energy = 100;
this->Strength = 5;
this->Stamina = 5;
this->Intelligence = 5;
this->Spirit = 5;
this->Agility = 5;
std::cout << this->name << " Created" << std::endl;
}
Character::~Character() {}
const std::string &Character::getName() const {
return this->name;
}
int Character::getLvl() const {
return this->lvl;
}
int Character::getPv() const {
return this->Pv;
}
int Character::getPower() const {
return this->Energy;
}
int Character::CloseAttack() {
if (this->Energy >= 10) {
this->Energy -= 10;
std::cout << this->name << " strikes with a wood stick" << std::endl;
return (10 + this->Strength);
}
else {
std::cout << this->name << " out of power" << std::endl;
return 0;
}
}
int Character::RangeAttack() {
if (this->Energy >= 10) {
this->Energy -= 10;
std::cout << this->name << " launches a stone" << std::endl;
return 5 + this->Strength;
}
else {
std::cout << this->name << " out of power" << std::endl;
return 0;
}
}
void Character::Heal() {
this->Pv += 50;
if (this->Pv > 100)
this->Pv = 100;
std::cout << this->name << " takes a potion" << std::endl;
}
void Character::RestorePower() {
this->Energy = 100;
std::cout << this->name << " eats" << std::endl;
}
void Character::TakeDamage(int _damage) {
this->Pv -= _damage;
if (this->Pv <= 0) {
this->Energy = 0;
std::cout << this->name << " out of combat" << std::endl;
}
else
std::cout << this->name << " takes " << _damage << " damage" << std::endl;
}
// int main()
// {
// Character koala("john", 2);;
// koala.TakeDamage(70);
// koala.Heal();
// koala.TakeDamage(70);
// koala.TakeDamage(70);
// koala.TakeDamage(70);
// koala.Range = Character::CLOSE;
// return (0);
// }
|
/*
* 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.
*/
/*!
* Copyright (c) 2017 by Contributors
* \file pooling.cc
* \brief
* \author Bing Xu, Jun Wu, Da Zheng
*/
#include "../elemwise_op_common.h"
#include "./pooling-inl.h"
#if MXNET_USE_NNPACK == 1
#include "./nnpack/nnpack_pooling-inl.h"
#endif // MXNET_USE_NNPACK
#if MXNET_USE_MKLDNN == 1
#include "./mkldnn/mkldnn_pooling-inl.h"
#endif // MXNET_USE_MKLDNN
namespace mxnet {
namespace op {
static void PoolingParamParser(nnvm::NodeAttrs *attrs) {
using namespace mshadow;
PoolingParam param;
param.Init(attrs->dict);
if (param.kernel.ndim() == 1) {
if (param.stride.ndim() == 0) param.stride = Shape1(1);
if (param.pad.ndim() == 0) param.pad = Shape1(0);
} else if (param.kernel.ndim() == 2) {
if (param.stride.ndim() == 0) param.stride = Shape2(1, 1);
if (param.pad.ndim() == 0) param.pad = Shape2(0, 0);
} else {
CHECK_EQ(param.kernel.ndim(), 3U) << param.kernel.ndim()
<< "D pooling not supported";
if (param.stride.ndim() == 0) param.stride = Shape3(1, 1, 1);
if (param.pad.ndim() == 0) param.pad = Shape3(0, 0, 0);
}
CHECK_EQ(param.stride.ndim(), param.kernel.ndim())
<< "stride and kernel should have the same length";
CHECK_EQ(param.pad.ndim(), param.kernel.ndim())
<< "pad and kernel should have the same length";
attrs->parsed = std::move(param);
}
int GetNumOutputs(const PoolingParam ¶m) {
#if MXNET_USE_MKLDNN == 1
return MKLDNNRequireWorkspace(param) && SupportMKLDNNPooling(param) ? 2 : 1;
#else
return 1;
#endif
}
int GetNumBackInputs(const PoolingParam ¶m) {
#if MXNET_USE_MKLDNN == 1
return MKLDNNRequireWorkspace(param) && SupportMKLDNNPooling(param) ? 5 : 3;
#else
return 3;
#endif
}
static bool PoolingType(const nnvm::NodeAttrs& attrs,
std::vector<int> *in_attrs,
std::vector<int> *out_attrs) {
out_attrs->at(0) = in_attrs->at(0);
#if MXNET_USE_MKLDNN == 1
const PoolingParam ¶m = nnvm::get<PoolingParam>(attrs.parsed);
if (MKLDNNRequireWorkspace(param) && SupportMKLDNNPooling(param)) {
CHECK_GT(out_attrs->size(), 1U);
out_attrs->at(1) = mshadow::kInt32;
}
#endif
return true;
}
static bool PoolingShape(const nnvm::NodeAttrs &attrs,
std::vector<TShape> *in_shape,
std::vector<TShape> *out_shape) {
const PoolingParam ¶m = nnvm::get<PoolingParam>(attrs.parsed);
CHECK_EQ(in_shape->size(), 1U);
const TShape &dshape = (*in_shape)[0];
CHECK_GE(dshape.ndim(), 3U)
<< "Pooling: Input data should be 3D in (batch, channel, x)"
<< " Or 4D in (batch, channel, y, x) "
<< " Or 5D in (batch, channel, d, y, x)";
TShape oshape = dshape;
if (dshape.ndim() == 0) return false;
if (param.kernel.ndim() == 1) {
CHECK_EQ(dshape.ndim(), 3U)
<< "Pooling: Input data should be 3D in (batch, channel, x)";
if (param.global_pool) {
oshape[2] = 1;
} else {
CHECK(param.kernel[0] <= dshape[2] + 2 * param.pad[0])
<< "kernel size (" << param.kernel[0] << ") exceeds input ("
<< dshape[2] << " padded to " << (dshape[2] + 2 * param.pad[0])
<< ")";
if (param.pooling_convention == pool_enum::kValid) {
oshape[2] = 1 +
(dshape[2] + 2 * param.pad[0] - param.kernel[0]) /
param.stride[0];
} else {
oshape[2] = 1 + static_cast<int>(ceil(
static_cast<float>(dshape[2] + 2 * param.pad[0] -
param.kernel[0]) /
param.stride[0]));
}
}
out_shape->clear();
out_shape->push_back(oshape); // save output shape
#if MXNET_USE_MKLDNN == 1
if (MKLDNNRequireWorkspace(param) && SupportMKLDNNPooling(param))
out_shape->push_back(oshape); // for workspace
#endif
} else if (param.kernel.ndim() == 2) {
CHECK_EQ(dshape.ndim(), 4U)
<< "Pooling: Input data should be 4D in (batch, channel, y, x)";
if (param.global_pool) {
oshape[2] = 1;
oshape[3] = 1;
} else {
CHECK(param.kernel[0] <= dshape[2] + 2 * param.pad[0])
<< "kernel size (" << param.kernel[0] << ") exceeds input ("
<< dshape[2] << " padded to " << (dshape[2] + 2 * param.pad[0])
<< ")";
CHECK(param.kernel[1] <= dshape[3] + 2 * param.pad[1])
<< "kernel size (" << param.kernel[1] << ") exceeds input ("
<< dshape[3] << " padded to " << (dshape[3] + 2 * param.pad[1])
<< ")";
if (param.pooling_convention == pool_enum::kValid) {
oshape[2] = 1 +
(dshape[2] + 2 * param.pad[0] - param.kernel[0]) /
param.stride[0];
oshape[3] = 1 +
(dshape[3] + 2 * param.pad[1] - param.kernel[1]) /
param.stride[1];
} else {
oshape[2] = 1 + static_cast<int>(ceil(
static_cast<float>(dshape[2] + 2 * param.pad[0] -
param.kernel[0]) /
param.stride[0]));
oshape[3] = 1 + static_cast<int>(ceil(
static_cast<float>(dshape[3] + 2 * param.pad[1] -
param.kernel[1]) /
param.stride[1]));
}
}
out_shape->clear();
out_shape->push_back(oshape); // save output shape
#if MXNET_USE_MKLDNN == 1
if (MKLDNNRequireWorkspace(param) && SupportMKLDNNPooling(param))
out_shape->push_back(oshape); // for workspace
#endif
} else if (param.kernel.ndim() == 3) {
CHECK_EQ(dshape.ndim(), 5U)
<< "Pooling: Input data should be 5D in (batch, channel, d, y, x)";
CHECK_LE(param.kernel[0], dshape[2] + 2 * param.pad[0])
<< "kernel size exceeds input";
CHECK_LE(param.kernel[1], dshape[3] + 2 * param.pad[1])
<< "kernel size exceeds input";
CHECK_LE(param.kernel[2], dshape[4] + 2 * param.pad[2])
<< "kernel size exceeds input";
if (param.global_pool) {
oshape[2] = 1;
oshape[3] = 1;
oshape[4] = 1;
} else {
if (param.pooling_convention == pool_enum::kValid) {
oshape[2] = 1 +
(dshape[2] + 2 * param.pad[0] - param.kernel[0]) /
param.stride[0];
oshape[3] = 1 +
(dshape[3] + 2 * param.pad[1] - param.kernel[1]) /
param.stride[1];
oshape[4] = 1 +
(dshape[4] + 2 * param.pad[2] - param.kernel[2]) /
param.stride[2];
} else {
oshape[2] = 1 + static_cast<int>(ceil(
static_cast<float>(dshape[2] + 2 * param.pad[0] -
param.kernel[0]) /
param.stride[0]));
oshape[3] = 1 + static_cast<int>(ceil(
static_cast<float>(dshape[3] + 2 * param.pad[1] -
param.kernel[1]) /
param.stride[1]));
oshape[4] = 1 + static_cast<int>(ceil(
static_cast<float>(dshape[4] + 2 * param.pad[2] -
param.kernel[2]) /
param.stride[2]));
}
}
out_shape->clear();
out_shape->push_back(oshape); // save output shape
#if MXNET_USE_MKLDNN == 1
if (MKLDNNRequireWorkspace(param) && SupportMKLDNNPooling(param))
out_shape->push_back(oshape); // for workspace
#endif
}
return true;
}
#if MXNET_USE_MKLDNN == 1
void PoolingComputeExCPU(const nnvm::NodeAttrs &attrs, const OpContext &ctx,
const std::vector<NDArray> &inputs,
const std::vector<OpReqType> &req,
const std::vector<NDArray> &outputs) {
const PoolingParam ¶m = nnvm::get<PoolingParam>(attrs.parsed);
const NDArray *workspace = nullptr;
if (MKLDNNRequireWorkspace(param)) {
CHECK_GT(outputs.size(), 1U);
workspace = &outputs[1];
}
if (SupportMKLDNN(inputs[0])
&& SupportMKLDNNPooling(param, inputs[0].shape())) {
MKLDNN_OPCHECK_INIT(false, 1, inputs, outputs);
MKLDNNPoolingCompute(ctx, param, inputs[0], req[0], outputs[0], workspace);
MKLDNN_OPCHECK_RUN(PoolingCompute<cpu>, attrs, ctx, inputs, req, outputs);
return;
}
FallBackCompute(PoolingCompute<cpu>, attrs, ctx, inputs, req, outputs);
}
void PoolingGradComputeExCPU(const nnvm::NodeAttrs &attrs, const OpContext &ctx,
const std::vector<NDArray> &inputs,
const std::vector<OpReqType> &req,
const std::vector<NDArray> &outputs) {
const PoolingParam ¶m = nnvm::get<PoolingParam>(attrs.parsed);
const NDArray &out_grad = inputs[0];
const NDArray *workspace = nullptr;
const NDArray *in_data = nullptr;
if (MKLDNNRequireWorkspace(param)) {
// The first two elements are the gradient of the outputs in forward.
// The third is the input of forward.
// The fourth and the fifth are the outputs of forward.
CHECK_EQ(inputs.size(), 5U);
in_data = &inputs[2];
workspace = &inputs[4];
} else {
CHECK_EQ(inputs.size(), 3U);
in_data = &inputs[1];
}
const NDArray &in_grad = outputs[0];
if (SupportMKLDNN(inputs[0])
&& SupportMKLDNNPooling(param, inputs[0].shape())) {
MKLDNN_OPCHECK_INIT(true, outputs.size(), inputs, outputs);
MKLDNNPoolingGradCompute(ctx, param, out_grad, *in_data, workspace,
req[0], in_grad);
MKLDNN_OPCHECK_RUN(PoolingGradCompute<cpu>, attrs, ctx, inputs, req,
outputs);
return;
}
FallBackCompute(PoolingGradCompute<cpu>, attrs, ctx, inputs, req, outputs);
}
#endif
inline static bool PoolingStorageType(const nnvm::NodeAttrs &attrs,
const int dev_mask,
DispatchMode *dispatch_mode,
std::vector<int> *in_attrs,
std::vector<int> *out_attrs) {
CHECK_EQ(in_attrs->size(), 1);
#if MXNET_USE_MKLDNN == 1
const PoolingParam ¶m = nnvm::get<PoolingParam>(attrs.parsed);
if (dev_mask == mshadow::cpu::kDevMask && SupportMKLDNNPooling(param)) {
return storage_type_assign(out_attrs, mxnet::kDefaultStorage,
dispatch_mode, DispatchMode::kFComputeEx);
}
#else
CHECK_EQ(out_attrs->size(), 1);
#endif
return storage_type_assign(out_attrs, mxnet::kDefaultStorage,
dispatch_mode, DispatchMode::kFCompute);
}
inline static bool BackwardPoolingStorageType(const nnvm::NodeAttrs &attrs,
const int dev_mask,
DispatchMode *dispatch_mode,
std::vector<int> *in_attrs,
std::vector<int> *out_attrs) {
const PoolingParam ¶m = nnvm::get<PoolingParam>(attrs.parsed);
CHECK_EQ(in_attrs->size(), GetNumBackInputs(param));
CHECK_EQ(out_attrs->size(), 1);
#if MXNET_USE_MKLDNN == 1
if (dev_mask == mshadow::cpu::kDevMask && SupportMKLDNNPooling(param)) {
return storage_type_assign(out_attrs, mxnet::kDefaultStorage,
dispatch_mode, DispatchMode::kFComputeEx);
}
#else
CHECK_EQ(in_attrs->size(), 3);
#endif
return storage_type_assign(out_attrs, mxnet::kDefaultStorage,
dispatch_mode, DispatchMode::kFCompute);
}
DMLC_REGISTER_PARAMETER(PoolingParam);
NNVM_REGISTER_OP(Pooling)
.describe(R"code(Performs pooling on the input.
The shapes for 1-D pooling are
- **data**: *(batch_size, channel, width)*,
- **out**: *(batch_size, num_filter, out_width)*.
The shapes for 2-D pooling are
- **data**: *(batch_size, channel, height, width)*
- **out**: *(batch_size, num_filter, out_height, out_width)*, with::
out_height = f(height, kernel[0], pad[0], stride[0])
out_width = f(width, kernel[1], pad[1], stride[1])
The definition of *f* depends on ``pooling_convention``, which has two options:
- **valid** (default)::
f(x, k, p, s) = floor((x+2*p-k)/s)+1
- **full**, which is compatible with Caffe::
f(x, k, p, s) = ceil((x+2*p-k)/s)+1
But ``global_pool`` is set to be true, then do a global pooling, namely reset
``kernel=(height, width)``.
Three pooling options are supported by ``pool_type``:
- **avg**: average pooling
- **max**: max pooling
- **sum**: sum pooling
For 3-D pooling, an additional *depth* dimension is added before
*height*. Namely the input data will have shape *(batch_size, channel, depth,
height, width)*.
)code" ADD_FILELINE)
.set_num_inputs(1)
.set_num_outputs([](const NodeAttrs& attrs) {
const PoolingParam ¶m = nnvm::get<PoolingParam>(attrs.parsed);
return GetNumOutputs(param);
})
#if MXNET_USE_MKLDNN == 1
.set_attr<nnvm::FNumVisibleOutputs>("FNumVisibleOutputs",
[](const NodeAttrs& attrs) { return 1; })
#endif
.set_attr<nnvm::FListInputNames>("FListInputNames",
[](const NodeAttrs& attrs) {
return std::vector<std::string>{"data"};
})
.set_attr<nnvm::FListOutputNames>("FListOutputNames",
[](const NodeAttrs& attrs) {
return std::vector<std::string>{"output"};
})
.set_attr_parser(PoolingParamParser)
.set_attr<FInferStorageType>("FInferStorageType", PoolingStorageType)
.set_attr<nnvm::FInferType>("FInferType", PoolingType)
.set_attr<nnvm::FInferShape>("FInferShape", PoolingShape)
.set_attr<FCompute>("FCompute<cpu>", PoolingCompute<cpu>)
#if MXNET_USE_MKLDNN == 1
.set_attr<FComputeEx>("FComputeEx<cpu>", PoolingComputeExCPU)
#endif
.set_attr<nnvm::FGradient>("FGradient",
ElemwiseGradUseInOut{"_backward_Pooling"})
.add_argument("data", "NDArray-or-Symbol",
"Input data to the pooling operator.")
.add_arguments(PoolingParam::__FIELDS__());
NNVM_REGISTER_OP(_backward_Pooling)
.set_num_outputs(1)
.set_attr<nnvm::TIsBackward>("TIsBackward", true)
.set_attr<nnvm::FInplaceOption>(
"FInplaceOption",
[](const NodeAttrs &attrs) {
#if MXNET_USE_CUDNN == 1
return std::vector<std::pair<int, int> >();
#else
return std::vector<std::pair<int, int> >{{1, 0}};
#endif
})
#if MXNET_USE_MKLDNN == 1
.set_attr<FResourceRequest>("FResourceRequest", [](const NodeAttrs& n) {
return std::vector<ResourceRequest>{ResourceRequest::kTempSpace};
})
#endif
.set_attr<FInferStorageType>("FInferStorageType",
BackwardPoolingStorageType)
.set_attr_parser(PoolingParamParser)
#if MXNET_USE_MKLDNN == 1
.set_attr<FComputeEx>("FComputeEx<cpu>", PoolingGradComputeExCPU)
#endif
.set_attr<FCompute>("FCompute<cpu>", PoolingGradCompute<cpu>);
} // namespace op
} // namespace mxnet
|
/*=========================================================================
*
* Copyright Insight Software Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#include <iostream>
#include "itkRegularSphereMeshSource.h"
#include "itkTriangleMeshToSimplexMeshFilter.h"
#include "itkDefaultDynamicMeshTraits.h"
#include "itkTimeProbe.h"
int itkTriangleMeshToSimplexMeshFilter2Test(int , char *[] )
{
// Declare the type of the input and output mesh
using MeshTraits = itk::DefaultDynamicMeshTraits<double, 3, 3, double, double, double>;
using TriangleMeshType = itk::Mesh<double,3,MeshTraits>;
using SimplexMeshType = itk::SimplexMesh<double,3,MeshTraits>;
// declare triangle mesh source
using SphereMeshSourceType = itk::RegularSphereMeshSource<TriangleMeshType>;
using PointType = SphereMeshSourceType::PointType;
using VectorType = SphereMeshSourceType::VectorType;
// Declare the type of the gradient image
using SimplexFilterType = itk::TriangleMeshToSimplexMeshFilter<TriangleMeshType, SimplexMeshType>;
SphereMeshSourceType::Pointer mySphereMeshSource = SphereMeshSourceType::New();
PointType center; center.Fill(0);
PointType::ValueType scaleInit[3] = {10,10,10};
VectorType scale = scaleInit;
mySphereMeshSource->SetCenter(center);
mySphereMeshSource->SetResolution(2);
mySphereMeshSource->SetScale(scale);
SimplexFilterType::Pointer simplexFilter = SimplexFilterType::New();
simplexFilter->SetInput( mySphereMeshSource->GetOutput() );
simplexFilter->Update();
SimplexMeshType::Pointer simplexMesh = simplexFilter->GetOutput();
simplexMesh->DisconnectPipeline();
using NeighborsListType = SimplexMeshType::NeighborListType;
for (int i=0; i < 7; i++)
{
itk::TimeProbe timeProbe;
NeighborsListType* neighbors = nullptr;
timeProbe.Start();
const unsigned int lastIndex = simplexMesh->GetPoints()->Size();
for (unsigned int pointIndex = 0; pointIndex < lastIndex; pointIndex++)
{
neighbors = simplexMesh->GetNeighbors( pointIndex, i );
if (pointIndex != (lastIndex - 1))
{
delete neighbors;
}
}
timeProbe.Stop();
if(neighbors)
{
std::cout << "Rigidity: " << i << ", neighbor list size: " << neighbors->size() << std::endl;
delete neighbors;
}
else
{
std::cout << "Rigidity: " << i << ", no neighbor" << std::endl;
}
std::cout << ", Elapsed time (for getting neighbors): " << timeProbe.GetMean() << std::endl;
}
std::cout << "[TEST DONE]" << std::endl;
return EXIT_SUCCESS;
}
|
/*
Project : mainmenu
Author : Mohammad Al-Husseini
Description : Displays the main menu for the Serendipity Project.
*/
///////////////////////////////////////////////////////////////////////////////////////////////////
#include <iostream> // cout object for command line output
#include "cashier.h"
#include "bookinfo.h"
#include "invmenu.h"
#include "reports.h"
using namespace std;
int main()
{
// Menu Variable
char choice;
// Loop
do
{
// Display Menu
cout << " Serendipity Booksellers" << endl;
cout << " Main Menu" << endl << endl;
cout << " 1. Cashier Module" << endl;
cout << " 2. Inventory Database Module" << endl;
cout << " 3. Report Module" << endl;
cout << " 4. Exit" << endl << endl;
cout << " Enter Your Choice: ";
cin >> choice;
// Validate Input
while (static_cast<int>(choice) > 52 || static_cast<int>(choice) < 49) // ASCII Representations
{
cout << endl << " Invalid - Enter Your Choice (1-4): ";
cin >> choice;
}
// Branch
switch (choice)
{
case '1':
cashier();
break;
case '2':
invmenu();
break;
case '3':
reports();
break;
}
} while (choice != '4');
return 0;
}
|
#ifndef LOWI_HEADER_REGISTERS_CL_HH
#define LOWI_HEADER_REGISTERS_CL_HH
#include <lowi/register_type.hh>
namespace lowi
{
namespace registers
{
class cl final : public register_type
{
public:
cl();
cl(const cl& cl) = default;
cl(cl&& cl) noexcept = default;
virtual ~cl() override = default;
public:
cl& operator=(const cl& cl) = default;
cl& operator=(cl&& cl) noexcept = default;
bool operator==(const cl& cl) const noexcept;
bool operator!=(const cl& cl) const noexcept;
public:
cl& assign(const cl& cl);
cl& assign(cl&& cl) noexcept;
bool equal(const cl& cl) const noexcept;
public:
static ptr create();
};
}
}
#endif
|
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include "precompiled.h"
#include <AzCore/Serialization/SerializeContext.h>
#include <QCoreApplication>
#include <qmenu.h>
#include <GraphCanvas/Components/GridBus.h>
#include <GraphCanvas/Components/SceneBus.h>
#include <GraphCanvas/Components/StyleBus.h>
#include <GraphCanvas/Components/VisualBus.h>
#include <GraphCanvas/Widgets/GraphCanvasGraphicsView/GraphCanvasGraphicsView.h>
#include "VariableNodePaletteTreeItemTypes.h"
#include "Editor/Components/IconComponent.h"
#include "Editor/Nodes/NodeUtils.h"
#include "Editor/Translation/TranslationHelper.h"
#include "ScriptCanvas/Bus/RequestBus.h"
#include "Editor/Include/ScriptCanvas/GraphCanvas/NodeDescriptorBus.h"
#include <Core/Attributes.h>
#include <Editor/Metrics.h>
#include <Libraries/Core/Assign.h>
#include <Libraries/Core/BehaviorContextObjectNode.h>
#include <Libraries/Core/Method.h>
#include <Editor/GraphCanvas/GraphCanvasEditorNotificationBusId.h>
namespace ScriptCanvasEditor
{
///////////////////////////////////
// CreateGetVariableNodeMimeEvent
///////////////////////////////////
void CreateGetVariableNodeMimeEvent::Reflect(AZ::ReflectContext* reflectContext)
{
AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(reflectContext);
if (serializeContext)
{
serializeContext->Class<CreateGetVariableNodeMimeEvent, CreateNodeMimeEvent>()
->Version(0)
->Field("VariableId", &CreateGetVariableNodeMimeEvent::m_variableId)
;
}
}
CreateGetVariableNodeMimeEvent::CreateGetVariableNodeMimeEvent(const ScriptCanvas::VariableId& variableId)
: m_variableId(variableId)
{
}
ScriptCanvasEditor::NodeIdPair CreateGetVariableNodeMimeEvent::CreateNode(const AZ::EntityId& scriptCanvasGraphId) const
{
Metrics::MetricsEventsBus::Broadcast(&Metrics::MetricsEventRequests::SendNodeMetric, ScriptCanvasEditor::Metrics::Events::Canvas::DropObject, "{A9784FF3-E749-4EB4-B5DB-DF510F7CD151}", scriptCanvasGraphId);
return Nodes::CreateGetVariableNode(m_variableId, scriptCanvasGraphId);
}
///////////////////////////////////
// GetVariableNodePaletteTreeItem
///////////////////////////////////
const QString& GetVariableNodePaletteTreeItem::GetDefaultIcon()
{
static QString defaultIcon;
if (defaultIcon.isEmpty())
{
defaultIcon = IconComponent::LookupClassIcon(AZ::Uuid()).c_str();
}
return defaultIcon;
}
GetVariableNodePaletteTreeItem::GetVariableNodePaletteTreeItem()
: DraggableNodePaletteTreeItem("Get Variable", ScriptCanvasEditor::AssetEditorId)
{
SetToolTip("After specifying a variable name, this node will expose output slots that return the specified variable's values.\nVariable names must begin with # (for example, #MyVar).");
}
GetVariableNodePaletteTreeItem::GetVariableNodePaletteTreeItem(const ScriptCanvas::VariableId& variableId, const AZ::EntityId& scriptCanvasGraphId)
: DraggableNodePaletteTreeItem("", ScriptCanvasEditor::AssetEditorId)
, m_variableId(variableId)
{
AZStd::string_view variableName;
ScriptCanvas::GraphVariableManagerRequestBus::EventResult(variableName, scriptCanvasGraphId, &ScriptCanvas::GraphVariableManagerRequests::GetVariableName, variableId);
OnVariableRenamed(variableName);
ScriptCanvas::VariableNotificationBus::Handler::BusConnect(m_variableId);
ScriptCanvas::Data::Type scriptCanvasType = ScriptCanvas::Data::Type::Invalid();
ScriptCanvas::VariableRequestBus::EventResult(scriptCanvasType, m_variableId, &ScriptCanvas::VariableRequests::GetType);
if (scriptCanvasType.IsValid())
{
AZ::Uuid azType = ScriptCanvas::Data::ToAZType(scriptCanvasType);
AZStd::string colorPalette;
GraphCanvas::StyleManagerRequestBus::EventResult(colorPalette, ScriptCanvasEditor::AssetEditorId, &GraphCanvas::StyleManagerRequests::GetDataPaletteStyle, azType);
SetTitlePalette(colorPalette);
}
}
GetVariableNodePaletteTreeItem::~GetVariableNodePaletteTreeItem()
{
ScriptCanvas::VariableNotificationBus::Handler::BusDisconnect();
}
void GetVariableNodePaletteTreeItem::OnVariableRenamed(AZStd::string_view variableName)
{
AZStd::string fullName = AZStd::string::format("Get %s", variableName.data());
SetName(fullName.c_str());
AZStd::string tooltip = AZStd::string::format("This node returns %s's values", variableName.data());
SetToolTip(tooltip.c_str());
}
GraphCanvas::GraphCanvasMimeEvent* GetVariableNodePaletteTreeItem::CreateMimeEvent() const
{
return aznew CreateGetVariableNodeMimeEvent(m_variableId);
}
///////////////////////////////////
// CreateSetVariableNodeMimeEvent
///////////////////////////////////
void CreateSetVariableNodeMimeEvent::Reflect(AZ::ReflectContext* reflectContext)
{
AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(reflectContext);
if (serializeContext)
{
serializeContext->Class<CreateSetVariableNodeMimeEvent, CreateNodeMimeEvent>()
->Version(0)
->Field("VariableId", &CreateSetVariableNodeMimeEvent::m_variableId)
;
}
}
CreateSetVariableNodeMimeEvent::CreateSetVariableNodeMimeEvent(const ScriptCanvas::VariableId& variableId)
: m_variableId(variableId)
{
}
ScriptCanvasEditor::NodeIdPair CreateSetVariableNodeMimeEvent::CreateNode(const AZ::EntityId& scriptCanvasGraphId) const
{
Metrics::MetricsEventsBus::Broadcast(&Metrics::MetricsEventRequests::SendNodeMetric, ScriptCanvasEditor::Metrics::Events::Canvas::DropObject, "{D855EE9C-74E0-4760-AA0F-239ADF7507B6}", scriptCanvasGraphId);
return Nodes::CreateSetVariableNode(m_variableId, scriptCanvasGraphId);
}
///////////////////////////////////
// SetVariableNodePaletteTreeItem
///////////////////////////////////
const QString& SetVariableNodePaletteTreeItem::GetDefaultIcon()
{
static QString defaultIcon;
if (defaultIcon.isEmpty())
{
defaultIcon = IconComponent::LookupClassIcon(AZ::Uuid()).c_str();
}
return defaultIcon;
}
SetVariableNodePaletteTreeItem::SetVariableNodePaletteTreeItem()
: GraphCanvas::DraggableNodePaletteTreeItem("Set Variable", ScriptCanvasEditor::AssetEditorId)
{
SetToolTip("This node changes a variable's values according to the data connected to the input slots");
}
SetVariableNodePaletteTreeItem::SetVariableNodePaletteTreeItem(const ScriptCanvas::VariableId& variableId, const AZ::EntityId& scriptCanvasGraphId)
: GraphCanvas::DraggableNodePaletteTreeItem("", ScriptCanvasEditor::AssetEditorId)
, m_variableId(variableId)
{
AZStd::string_view variableName;
ScriptCanvas::GraphVariableManagerRequestBus::EventResult(variableName, scriptCanvasGraphId, &ScriptCanvas::GraphVariableManagerRequests::GetVariableName, variableId);
OnVariableRenamed(variableName);
ScriptCanvas::VariableNotificationBus::Handler::BusConnect(m_variableId);
ScriptCanvas::Data::Type scriptCanvasType = ScriptCanvas::Data::Type::Invalid();
ScriptCanvas::VariableRequestBus::EventResult(scriptCanvasType, m_variableId, &ScriptCanvas::VariableRequests::GetType);
if (scriptCanvasType.IsValid())
{
AZ::Uuid azType = ScriptCanvas::Data::ToAZType(scriptCanvasType);
AZStd::string colorPalette;
GraphCanvas::StyleManagerRequestBus::EventResult(colorPalette, ScriptCanvasEditor::AssetEditorId, &GraphCanvas::StyleManagerRequests::GetDataPaletteStyle, azType);
SetTitlePalette(colorPalette);
}
}
SetVariableNodePaletteTreeItem::~SetVariableNodePaletteTreeItem()
{
ScriptCanvas::VariableNotificationBus::Handler::BusDisconnect();
}
void SetVariableNodePaletteTreeItem::OnVariableRenamed(AZStd::string_view variableName)
{
AZStd::string fullName = AZStd::string::format("Set %s", variableName.data());
SetName(fullName.c_str());
AZStd::string tooltip = AZStd::string::format("This node changes %s's values according to the data connected to the input slots", variableName.data());
SetToolTip(tooltip.c_str());
}
GraphCanvas::GraphCanvasMimeEvent* SetVariableNodePaletteTreeItem::CreateMimeEvent() const
{
return aznew CreateSetVariableNodeMimeEvent(m_variableId);
}
////////////////////////////////////////
// CreateGetOrSetVariableNodeMimeEvent
////////////////////////////////////////
void CreateGetOrSetVariableNodeMimeEvent::Reflect(AZ::ReflectContext* reflectContext)
{
AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(reflectContext);
if (serializeContext)
{
serializeContext->Class<CreateGetOrSetVariableNodeMimeEvent, SpecializedCreateNodeMimeEvent>()
->Version(0)
->Field("VariableId", &CreateGetOrSetVariableNodeMimeEvent::m_variableId)
;
}
}
CreateGetOrSetVariableNodeMimeEvent::CreateGetOrSetVariableNodeMimeEvent(const ScriptCanvas::VariableId& variableId)
: m_variableId(variableId)
{
}
bool CreateGetOrSetVariableNodeMimeEvent::ExecuteEvent(const AZ::Vector2& mousePosition, AZ::Vector2& sceneDropPosition, const AZ::EntityId& graphCanvasGraphId)
{
Metrics::MetricsEventsBus::Broadcast(&Metrics::MetricsEventRequests::SendNodeMetric, ScriptCanvasEditor::Metrics::Events::Canvas::DropHandler, AZ::Uuid("{CE31F6F6-1536-4C97-BB59-863408ABA736}"), graphCanvasGraphId);
NodeIdPair nodeId = ConstructNode(graphCanvasGraphId, sceneDropPosition);
if (nodeId.m_graphCanvasId.IsValid())
{
AZ::EntityId gridId;
GraphCanvas::SceneRequestBus::EventResult(gridId, graphCanvasGraphId, &GraphCanvas::SceneRequests::GetGrid);
AZ::Vector2 offset;
GraphCanvas::GridRequestBus::EventResult(offset, gridId, &GraphCanvas::GridRequests::GetMinorPitch);
sceneDropPosition += offset;
}
return nodeId.m_graphCanvasId.IsValid();
}
ScriptCanvasEditor::NodeIdPair CreateGetOrSetVariableNodeMimeEvent::ConstructNode(const AZ::EntityId& graphCanvasGraphId, const AZ::Vector2& scenePosition)
{
Metrics::MetricsEventsBus::Broadcast(&Metrics::MetricsEventRequests::SendNodeMetric, ScriptCanvasEditor::Metrics::Events::Canvas::DropObject, "{924C1192-C32A-4A35-B146-2739AB4383DB}", graphCanvasGraphId);
AZ::EntityId scriptCanvasGraphId;
GeneralRequestBus::BroadcastResult(scriptCanvasGraphId, &GeneralRequests::GetScriptCanvasGraphId, graphCanvasGraphId);
ScriptCanvasEditor::NodeIdPair nodeIdPair;
AZ::EntityId viewId;
GraphCanvas::SceneRequestBus::EventResult(viewId, graphCanvasGraphId, &GraphCanvas::SceneRequests::GetViewId);
GraphCanvas::GraphCanvasGraphicsView* graphicsView = nullptr;
GraphCanvas::ViewRequestBus::EventResult(graphicsView, viewId, &GraphCanvas::ViewRequests::AsGraphicsView);
if (graphicsView)
{
AZStd::string variableName;
ScriptCanvas::VariableRequestBus::EventResult(variableName, m_variableId, &ScriptCanvas::VariableRequests::GetName);
QMenu menu(graphicsView);
QAction* createGet = new QAction(QString("Get %1").arg(variableName.c_str()), &menu);
menu.addAction(createGet);
QAction* createSet = new QAction(QString("Set %1").arg(variableName.c_str()), &menu);
menu.addAction(createSet);
QAction* result = menu.exec(QCursor::pos());
if (result == createGet)
{
CreateGetVariableNodeMimeEvent createGetVariableNode(m_variableId);
nodeIdPair = createGetVariableNode.CreateNode(scriptCanvasGraphId);
}
else if (result == createSet)
{
CreateSetVariableNodeMimeEvent createSetVariableNode(m_variableId);
nodeIdPair = createSetVariableNode.CreateNode(scriptCanvasGraphId);
}
if (nodeIdPair.m_graphCanvasId.IsValid() && nodeIdPair.m_scriptCanvasId.IsValid())
{
GraphCanvas::SceneRequestBus::Event(graphCanvasGraphId, &GraphCanvas::SceneRequests::AddNode, nodeIdPair.m_graphCanvasId, scenePosition);
GraphCanvas::SceneMemberUIRequestBus::Event(nodeIdPair.m_graphCanvasId, &GraphCanvas::SceneMemberUIRequests::SetSelected, true);
}
}
return nodeIdPair;
}
////////////////////////////////////////
// VariableCategoryNodePaletteTreeItem
////////////////////////////////////////
VariableCategoryNodePaletteTreeItem::VariableCategoryNodePaletteTreeItem(const QString& displayName)
: NodePaletteTreeItem(displayName, ScriptCanvasEditor::AssetEditorId)
{
}
void VariableCategoryNodePaletteTreeItem::PreOnChildAdded(GraphCanvasTreeItem* item)
{
// Force elements to display in the order they were added rather then alphabetical.
static_cast<NodePaletteTreeItem*>(item)->SetItemOrdering(GetChildCount());
}
//////////////////////////////////////////
// LocalVariablesListNodePaletteTreeItem
//////////////////////////////////////////
LocalVariablesListNodePaletteTreeItem::LocalVariablesListNodePaletteTreeItem(const QString& displayName)
: NodePaletteTreeItem(displayName, ScriptCanvasEditor::AssetEditorId)
{
GraphCanvas::AssetEditorNotificationBus::Handler::BusConnect(ScriptCanvasEditor::AssetEditorId);
}
void LocalVariablesListNodePaletteTreeItem::OnActiveGraphChanged(const AZ::EntityId& graphCanvasGraphId)
{
AZ::EntityId scriptCanvasGraphId;
GeneralRequestBus::BroadcastResult(scriptCanvasGraphId, &GeneralRequests::GetScriptCanvasGraphId, graphCanvasGraphId);
if (m_scriptCanvasGraphId != scriptCanvasGraphId)
{
GraphItemCommandNotificationBus::Handler::BusDisconnect(m_scriptCanvasGraphId);
ScriptCanvas::GraphVariableManagerNotificationBus::Handler::BusDisconnect(m_scriptCanvasGraphId);
m_scriptCanvasGraphId = scriptCanvasGraphId;
if (m_scriptCanvasGraphId.IsValid())
{
ScriptCanvas::GraphVariableManagerNotificationBus::Handler::BusConnect(m_scriptCanvasGraphId);
GraphItemCommandNotificationBus::Handler::BusConnect(m_scriptCanvasGraphId);
}
RefreshVariableList();
}
}
void LocalVariablesListNodePaletteTreeItem::PostRestore(const UndoData&)
{
RefreshVariableList();
}
void LocalVariablesListNodePaletteTreeItem::OnVariableAddedToGraph(const ScriptCanvas::VariableId& variableId, AZStd::string_view /*variableName*/)
{
LocalVariableNodePaletteTreeItem* localVariableTreeItem = CreateChildNode<LocalVariableNodePaletteTreeItem>(variableId, m_scriptCanvasGraphId);
localVariableTreeItem->PopulateChildren();
}
void LocalVariablesListNodePaletteTreeItem::OnVariableRemovedFromGraph(const ScriptCanvas::VariableId& variableId, AZStd::string_view /*variableName*/)
{
int rows = GetChildCount();
for (int i = 0; i < rows; ++i)
{
LocalVariableNodePaletteTreeItem* treeItem = static_cast<LocalVariableNodePaletteTreeItem*>(FindChildByRow(i));
if (treeItem->GetVariableId() == variableId)
{
RemoveChild(treeItem);
break;
}
}
}
void LocalVariablesListNodePaletteTreeItem::RefreshVariableList()
{
// Need to let the child clear signal out
ClearChildren();
SignalLayoutAboutToBeChanged();
BlockSignals();
const ScriptCanvas::GraphVariableMapping* variableMapping = nullptr;
ScriptCanvas::GraphVariableManagerRequestBus::EventResult(variableMapping, m_scriptCanvasGraphId, &ScriptCanvas::GraphVariableManagerRequests::GetVariables);
if (variableMapping != nullptr)
{
for (const auto& mapPair : (*variableMapping))
{
LocalVariableNodePaletteTreeItem* rootItem = this->CreateChildNode<LocalVariableNodePaletteTreeItem>(mapPair.first, m_scriptCanvasGraphId);
rootItem->PopulateChildren();
}
}
UnblockSignals();
SignalLayoutChanged();
}
/////////////////////////////////////
// LocalVariableNodePaletteTreeItem
/////////////////////////////////////
LocalVariableNodePaletteTreeItem::LocalVariableNodePaletteTreeItem(ScriptCanvas::VariableId variableId, const AZ::EntityId& scriptCanvasGraphId)
: NodePaletteTreeItem("", ScriptCanvasEditor::AssetEditorId)
, m_scriptCanvasGraphId(scriptCanvasGraphId)
, m_variableId(variableId)
{
AZStd::string_view variableName;
ScriptCanvas::GraphVariableManagerRequestBus::EventResult(variableName, m_scriptCanvasGraphId, &ScriptCanvas::GraphVariableManagerRequests::GetVariableName, variableId);
OnVariableRenamed(variableName);
ScriptCanvas::VariableNotificationBus::Handler::BusConnect(variableId);
}
LocalVariableNodePaletteTreeItem::~LocalVariableNodePaletteTreeItem()
{
ScriptCanvas::VariableNotificationBus::Handler::BusDisconnect();
}
void LocalVariableNodePaletteTreeItem::PopulateChildren()
{
if (GetChildCount() == 0)
{
SignalLayoutAboutToBeChanged();
BlockSignals();
CreateChildNode<GetVariableNodePaletteTreeItem>(GetVariableId(), m_scriptCanvasGraphId);
CreateChildNode<SetVariableNodePaletteTreeItem>(GetVariableId(), m_scriptCanvasGraphId);
UnblockSignals();
SignalLayoutChanged();
}
}
const ScriptCanvas::VariableId& LocalVariableNodePaletteTreeItem::GetVariableId() const
{
return m_variableId;
}
void LocalVariableNodePaletteTreeItem::OnVariableRenamed(AZStd::string_view variableName)
{
SetName(variableName.data());
}
}
|
#include "voxel_terrain.h"
#include "../edition/voxel_tool_terrain.h"
#include "../streams/voxel_stream_file.h"
#include "../util/macros.h"
#include "../util/profiling_clock.h"
#include "../util/utility.h"
#include "../voxel_string_names.h"
#include "voxel_block.h"
#include "voxel_map.h"
#include <core/core_string_names.h>
#include <core/engine.h>
#include <scene/3d/mesh_instance.h>
const uint32_t MAIN_THREAD_MESHING_BUDGET_MS = 8;
VoxelTerrain::VoxelTerrain() {
// Note: don't do anything heavy in the constructor.
// Godot may create and destroy dozens of instances of all node types on startup,
// due to how ClassDB gets its default values.
_map.instance();
_view_distance_blocks = 8;
_last_view_distance_blocks = 0;
_stream_thread = nullptr;
_block_updater = nullptr;
Ref<VoxelLibrary> library;
library.instance();
set_voxel_library(library);
}
VoxelTerrain::~VoxelTerrain() {
PRINT_VERBOSE("Destroying VoxelTerrain");
if (_stream_thread != nullptr) {
// Schedule saving of all modified blocks,
// without copy because we are destroying the map anyways
save_all_modified_blocks(false);
memdelete(_stream_thread);
}
if (_block_updater) {
memdelete(_block_updater);
}
}
String VoxelTerrain::get_configuration_warning() const {
if (_stream.is_valid()) {
Ref<Script> script = _stream->get_script();
if (script.is_valid()) {
if (script->is_tool()) {
// TODO This is very annoying. Probably needs an issue or proposal in Godot so we can handle this properly?
return TTR("Be careful! Don't edit your custom stream while it's running, "
"it can cause crashes. Turn off `run_stream_in_editor` before doing so.");
} else {
return TTR("The custom stream is not tool, the editor won't be able to use it.");
}
}
if (!(_stream->get_used_channels_mask() & ((1 << VoxelBuffer::CHANNEL_TYPE) | (1 << VoxelBuffer::CHANNEL_SDF)))) {
return TTR("VoxelTerrain supports only stream channels \"Type\" or \"Sdf\", "
"but `get_used_channels_mask()` tells it's providing none of these.");
}
}
return String();
}
// TODO See if there is a way to specify materials in voxels directly?
bool VoxelTerrain::_set(const StringName &p_name, const Variant &p_value) {
if (p_name.operator String().begins_with("material/")) {
unsigned int idx = p_name.operator String().get_slicec('/', 1).to_int();
ERR_FAIL_COND_V(idx >= VoxelMesherBlocky::MAX_MATERIALS || idx < 0, false);
set_material(idx, p_value);
return true;
}
return false;
}
bool VoxelTerrain::_get(const StringName &p_name, Variant &r_ret) const {
if (p_name.operator String().begins_with("material/")) {
unsigned int idx = p_name.operator String().get_slicec('/', 1).to_int();
ERR_FAIL_COND_V(idx >= VoxelMesherBlocky::MAX_MATERIALS || idx < 0, false);
r_ret = get_material(idx);
return true;
}
return false;
}
void VoxelTerrain::_get_property_list(List<PropertyInfo> *p_list) const {
for (unsigned int i = 0; i < VoxelMesherBlocky::MAX_MATERIALS; ++i) {
p_list->push_back(PropertyInfo(Variant::OBJECT, "material/" + itos(i), PROPERTY_HINT_RESOURCE_TYPE, "ShaderMaterial,SpatialMaterial"));
}
}
void VoxelTerrain::set_stream(Ref<VoxelStream> p_stream) {
if (p_stream == _stream) {
return;
}
_stream = p_stream;
#ifdef TOOLS_ENABLED
if (_stream.is_valid()) {
if (Engine::get_singleton()->is_editor_hint()) {
if (_stream->has_script()) {
// Safety check. It's too easy to break threads by making a script reload.
// You can turn it back on, but be careful.
_run_stream_in_editor = false;
_change_notify();
}
}
}
#endif
_on_stream_params_changed();
}
Ref<VoxelStream> VoxelTerrain::get_stream() const {
return _stream;
}
void VoxelTerrain::set_block_size_po2(unsigned int p_block_size_po2) {
ERR_FAIL_COND(p_block_size_po2 < 1);
ERR_FAIL_COND(p_block_size_po2 > 32);
unsigned int block_size_po2 = p_block_size_po2;
Ref<VoxelStreamFile> file_stream = _stream;
if (file_stream.is_valid()) {
block_size_po2 = file_stream->get_block_size_po2();
}
if (block_size_po2 == get_block_size_pow2()) {
return;
}
_on_stream_params_changed();
}
void VoxelTerrain::_set_block_size_po2(int p_block_size_po2) {
_map->create(p_block_size_po2, 0);
}
unsigned int VoxelTerrain::get_block_size_pow2() const {
return _map->get_block_size_pow2();
}
void VoxelTerrain::restart_stream() {
_on_stream_params_changed();
}
void VoxelTerrain::_on_stream_params_changed() {
stop_streamer();
bool was_updater_running = _block_updater != nullptr;
stop_updater();
Ref<VoxelStreamFile> file_stream = _stream;
if (file_stream.is_valid()) {
int stream_block_size_po2 = file_stream->get_block_size_po2();
_set_block_size_po2(stream_block_size_po2);
}
// The whole map might change, so regenerate it
reset_map();
if (_stream.is_valid() && (!Engine::get_singleton()->is_editor_hint() || _run_stream_in_editor)) {
start_streamer();
}
if (was_updater_running) {
start_updater();
}
update_configuration_warning();
}
Ref<VoxelLibrary> VoxelTerrain::get_voxel_library() const {
return _library;
}
void VoxelTerrain::set_voxel_library(Ref<VoxelLibrary> library) {
if (library == _library) {
return;
}
#ifdef TOOLS_ENABLED
if (library->get_voxel_count() == 0) {
library->load_default();
}
#endif
_library = library;
const bool updater_was_running = _block_updater != nullptr;
stop_updater();
if (updater_was_running) {
start_updater();
}
// Voxel appearance might completely change
make_all_view_dirty_deferred();
}
void VoxelTerrain::set_generate_collisions(bool enabled) {
_generate_collisions = enabled;
}
int VoxelTerrain::get_view_distance() const {
return _view_distance_blocks * _map->get_block_size();
}
void VoxelTerrain::set_view_distance(int distance_in_voxels) {
ERR_FAIL_COND(distance_in_voxels < 0);
const int d = distance_in_voxels / _map->get_block_size();
if (d != _view_distance_blocks) {
PRINT_VERBOSE(String("View distance changed from ") + String::num(_view_distance_blocks) + String(" blocks to ") + String::num(d));
_view_distance_blocks = d;
// Blocks too far away will be removed in _process, same for blocks to load
}
}
void VoxelTerrain::set_viewer_path(NodePath path) {
_viewer_path = path;
}
NodePath VoxelTerrain::get_viewer_path() const {
return _viewer_path;
}
Spatial *VoxelTerrain::get_viewer() const {
if (!is_inside_tree()) {
return nullptr;
}
if (_viewer_path.is_empty()) {
return nullptr;
}
Node *node = get_node(_viewer_path);
if (node == nullptr) {
return nullptr;
}
return Object::cast_to<Spatial>(node);
}
void VoxelTerrain::set_material(unsigned int id, Ref<Material> material) {
// TODO Update existing block surfaces
ERR_FAIL_COND(id < 0 || id >= VoxelMesherBlocky::MAX_MATERIALS);
_materials[id] = material;
}
Ref<Material> VoxelTerrain::get_material(unsigned int id) const {
ERR_FAIL_COND_V(id < 0 || id >= VoxelMesherBlocky::MAX_MATERIALS, Ref<Material>());
return _materials[id];
}
void VoxelTerrain::make_block_dirty(Vector3i bpos) {
// TODO Immediate update viewer distance?
VoxelBlock *block = _map->get_block(bpos);
if (block == nullptr) {
// The block isn't available, we may need to load it
if (!_loading_blocks.has(bpos)) {
_blocks_pending_load.push_back(bpos);
_loading_blocks.insert(bpos);
}
} else if (block->get_mesh_state() != VoxelBlock::MESH_UPDATE_NOT_SENT) {
// Regardless of if the updater is updating the block already,
// the block was modified again so we schedule another update
block->set_mesh_state(VoxelBlock::MESH_UPDATE_NOT_SENT);
_blocks_pending_update.push_back(bpos);
if (!block->is_modified()) {
PRINT_VERBOSE(String("Marking block {0} as modified").format(varray(bpos.to_vec3())));
block->set_modified(true);
}
}
//OS::get_singleton()->print("Dirty (%i, %i, %i)", bpos.x, bpos.y, bpos.z);
// TODO What if a block is made dirty, goes through threaded update, then gets changed again before it gets updated?
// this will make the second change ignored, which is not correct!
}
namespace {
struct ScheduleSaveAction {
std::vector<VoxelDataLoader::InputBlock> &blocks_to_save;
bool with_copy;
void operator()(VoxelBlock *block) {
if (block->is_modified()) {
//print_line(String("Scheduling save for block {0}").format(varray(block->position.to_vec3())));
VoxelDataLoader::InputBlock b;
b.data.voxels_to_save = with_copy ? block->voxels->duplicate() : block->voxels;
b.position = block->position;
b.can_be_discarded = false;
blocks_to_save.push_back(b);
block->set_modified(false);
}
}
};
} // namespace
void VoxelTerrain::immerge_block(Vector3i bpos) {
ERR_FAIL_COND(_map.is_null());
_map->remove_block(bpos, [this, bpos](VoxelBlock *block) {
emit_block_unloaded(block);
// Note: no need to copy the block because it gets removed from the map anyways
ScheduleSaveAction{ _blocks_to_save, false }(block);
});
_loading_blocks.erase(bpos);
// Blocks in the update queue will be cancelled in _process,
// because it's too expensive to linear-search all blocks for each block
}
void VoxelTerrain::save_all_modified_blocks(bool with_copy) {
ERR_FAIL_COND(_stream_thread == nullptr);
// That may cause a stutter, so should be used when the player won't notice
_map->for_all_blocks(ScheduleSaveAction{ _blocks_to_save, with_copy });
// And flush immediately
send_block_data_requests();
}
Dictionary VoxelTerrain::get_statistics() const {
Dictionary d;
d["stream"] = VoxelDataLoader::Mgr::to_dictionary(_stats.stream);
d["updater"] = VoxelMeshUpdater::Mgr::to_dictionary(_stats.updater);
// Breakdown of time spent in _process
d["time_detect_required_blocks"] = _stats.time_detect_required_blocks;
d["time_request_blocks_to_load"] = _stats.time_request_blocks_to_load;
d["time_process_load_responses"] = _stats.time_process_load_responses;
d["time_request_blocks_to_update"] = _stats.time_request_blocks_to_update;
d["time_process_update_responses"] = _stats.time_process_update_responses;
d["remaining_main_thread_blocks"] = (int)_blocks_pending_main_thread_update.size();
d["dropped_block_loads"] = _stats.dropped_block_loads;
d["dropped_block_meshs"] = _stats.dropped_block_meshs;
d["updated_blocks"] = _stats.updated_blocks;
return d;
}
//void VoxelTerrain::make_blocks_dirty(Vector3i min, Vector3i size) {
// Vector3i max = min + size;
// Vector3i pos;
// for (pos.z = min.z; pos.z < max.z; ++pos.z) {
// for (pos.y = min.y; pos.y < max.y; ++pos.y) {
// for (pos.x = min.x; pos.x < max.x; ++pos.x) {
// make_block_dirty(pos);
// }
// }
// }
//}
void VoxelTerrain::make_all_view_dirty_deferred() {
// We do this because we query blocks only when the viewer area changes.
// This trick will regenerate all chunks in view, according to the view distance found during block updates.
// The point of doing this instead of immediately scheduling updates is that it will
// always use an up-to-date view distance, which is not necessarily loaded yet on initialization.
_last_view_distance_blocks = 0;
// Vector3i radius(_view_distance_blocks, _view_distance_blocks, _view_distance_blocks);
// make_blocks_dirty(-radius, 2*radius);
}
void VoxelTerrain::start_updater() {
// The meshing thread must be stopped
ERR_FAIL_COND(_block_updater != nullptr);
if (_library.is_valid()) {
// TODO Any way to execute this function just after the TRES resource loader has finished to load?
// VoxelLibrary should be baked ahead of time, like MeshLibrary
_library->bake();
}
// TODO Thread-safe way to change those parameters
VoxelMeshUpdater::MeshingParams params;
if (_stream.is_valid()) {
params.smooth_surface = _stream->get_used_channels_mask() & (1 << VoxelBuffer::CHANNEL_SDF);
}
params.library = _library;
_block_updater = memnew(VoxelMeshUpdater(1, params));
}
void VoxelTerrain::stop_updater() {
struct ResetMeshStateAction {
void operator()(VoxelBlock *block) {
if (block->get_mesh_state() == VoxelBlock::MESH_UPDATE_SENT) {
block->set_mesh_state(VoxelBlock::MESH_UPDATE_NOT_SENT);
}
}
};
if (_block_updater) {
memdelete(_block_updater);
_block_updater = nullptr;
}
_blocks_pending_main_thread_update.clear();
_blocks_pending_update.clear();
ResetMeshStateAction a;
_map->for_all_blocks(a);
}
void VoxelTerrain::start_streamer() {
ERR_FAIL_COND(_stream_thread != nullptr);
ERR_FAIL_COND(_stream.is_null());
_stream_thread = memnew(VoxelDataLoader(1, _stream, get_block_size_pow2()));
}
void VoxelTerrain::stop_streamer() {
if (_stream_thread) {
memdelete(_stream_thread);
_stream_thread = nullptr;
}
_loading_blocks.clear();
_blocks_pending_load.clear();
}
void VoxelTerrain::reset_map() {
// Don't reset while streaming, the result can be dirty
CRASH_COND(_stream_thread != nullptr);
_map->for_all_blocks([this](VoxelBlock *block) {
emit_block_unloaded(block);
});
_map->create(get_block_size_pow2(), 0);
// To force queries to happen again, because we only listen for viewer position changes
make_all_view_dirty_deferred();
}
inline int get_border_index(int x, int max) {
return x == 0 ? 0 : x != max ? 1 : 2;
}
void VoxelTerrain::make_voxel_dirty(Vector3i pos) {
// Update the block in which the voxel is
const Vector3i bpos = _map->voxel_to_block(pos);
make_block_dirty(bpos);
//OS::get_singleton()->print("Dirty (%i, %i, %i)\n", bpos.x, bpos.y, bpos.z);
// Update neighbor blocks if the voxel is touching a boundary
const Vector3i rpos = _map->to_local(pos);
// TODO Thread-safe way of getting this parameter
const bool check_corners = true; //_mesher->get_occlusion_enabled();
const int max = _map->get_block_size() - 1;
if (rpos.x == 0) {
make_block_dirty(bpos - Vector3i(1, 0, 0));
} else if (rpos.x == max) {
make_block_dirty(bpos + Vector3i(1, 0, 0));
}
if (rpos.y == 0) {
make_block_dirty(bpos - Vector3i(0, 1, 0));
} else if (rpos.y == max) {
make_block_dirty(bpos + Vector3i(0, 1, 0));
}
if (rpos.z == 0) {
make_block_dirty(bpos - Vector3i(0, 0, 1));
} else if (rpos.z == max) {
make_block_dirty(bpos + Vector3i(0, 0, 1));
}
// We might want to update blocks in corners in order to update ambient occlusion
if (check_corners) {
// 24------25------26
// /| /|
// / | / |
// 21 | 23 |
// / 15 / 17
// / | / |
// 18------19------20 |
// | | | |
// | 6-------7-|-----8
// | / | /
// 9 / 11 /
// | 3 | 5
// | / | / y z
// |/ |/ |/
// 0-------1-------2 o--x
// I'm not good at writing piles of ifs
static const int normals[27][3] = {
{ -1, -1, -1 }, { 0, -1, -1 }, { 1, -1, -1 },
{ -1, -1, 0 }, { 0, -1, 0 }, { 1, -1, 0 },
{ -1, -1, 1 }, { 0, -1, 1 }, { 1, -1, 1 },
{ -1, 0, -1 }, { 0, 0, -1 }, { 1, 0, -1 },
{ -1, 0, 0 }, { 0, 0, 0 }, { 1, 0, 0 },
{ -1, 0, 1 }, { 0, 0, 1 }, { 1, 0, 1 },
{ -1, 1, -1 }, { 0, 1, -1 }, { 1, 1, -1 },
{ -1, 1, 0 }, { 0, 1, 0 }, { 1, 1, 0 },
{ -1, 1, 1 }, { 0, 1, 1 }, { 1, 1, 1 }
};
static const int ce_counts[27] = {
4, 1, 4,
1, 0, 1,
4, 1, 4,
1, 0, 1,
0, 0, 0,
1, 0, 1,
4, 1, 4,
1, 0, 1,
4, 1, 4
};
static const int ce_indexes_lut[27][4] = {
{ 0, 1, 3, 9 }, { 1 }, { 2, 1, 5, 11 },
{ 3 }, {}, { 5 },
{ 6, 3, 7, 15 }, { 7 }, { 8, 7, 5, 17 },
{ 9 }, {}, { 11 },
{}, {}, {},
{ 15 }, {}, { 17 },
{ 18, 9, 19, 21 }, { 19 }, { 20, 11, 19, 23 },
{ 21 }, {}, { 23 },
{ 24, 15, 21, 25 }, { 25 }, { 26, 17, 23, 25 }
};
const int m = get_border_index(rpos.x, max) + 3 * get_border_index(rpos.z, max) + 9 * get_border_index(rpos.y, max);
const int *ce_indexes = ce_indexes_lut[m];
const int ce_count = ce_counts[m];
//OS::get_singleton()->print("m=%i, rpos=(%i, %i, %i)\n", m, rpos.x, rpos.y, rpos.z);
for (int i = 0; i < ce_count; ++i) {
// TODO Because it's about ambient occlusion across 1 voxel only,
// we could optimize it even more by looking at neighbor voxels,
// and discard the update if we know it won't change anything
const int *normal = normals[ce_indexes[i]];
const Vector3i nbpos(bpos.x + normal[0], bpos.y + normal[1], bpos.z + normal[2]);
//OS::get_singleton()->print("Corner dirty (%i, %i, %i)\n", nbpos.x, nbpos.y, nbpos.z);
make_block_dirty(nbpos);
}
}
}
void VoxelTerrain::make_area_dirty(Rect3i box) {
Vector3i min_pos = box.pos;
Vector3i max_pos = box.pos + box.size - Vector3(1, 1, 1);
// TODO Thread-safe way of getting this parameter
const bool check_corners = true; //_mesher->get_occlusion_enabled();
if (check_corners) {
min_pos -= Vector3i(1, 1, 1);
max_pos += Vector3i(1, 1, 1);
} else {
Vector3i min_rpos = _map->to_local(min_pos);
if (min_rpos.x == 0) {
--min_pos.x;
}
if (min_rpos.y == 0) {
--min_pos.y;
}
if (min_rpos.z == 0) {
--min_pos.z;
}
const int max = _map->get_block_size() - 1;
const Vector3i max_rpos = _map->to_local(max_pos);
if (max_rpos.x == max) {
++max_pos.x;
}
if (max_rpos.y == max) {
++max_pos.y;
}
if (max_rpos.z == max) {
++max_pos.z;
}
}
const Vector3i min_block_pos = _map->voxel_to_block(min_pos);
const Vector3i max_block_pos = _map->voxel_to_block(max_pos);
Vector3i bpos;
for (bpos.z = min_block_pos.z; bpos.z <= max_block_pos.z; ++bpos.z) {
for (bpos.x = min_block_pos.x; bpos.x <= max_block_pos.x; ++bpos.x) {
for (bpos.y = min_block_pos.y; bpos.y <= max_block_pos.y; ++bpos.y) {
make_block_dirty(bpos);
}
}
}
}
void VoxelTerrain::_notification(int p_what) {
struct SetWorldAction {
World *world;
SetWorldAction(World *w) :
world(w) {}
void operator()(VoxelBlock *block) {
block->set_world(world);
}
};
struct SetParentVisibilityAction {
bool visible;
SetParentVisibilityAction(bool v) :
visible(v) {}
void operator()(VoxelBlock *block) {
block->set_parent_visible(visible);
}
};
switch (p_what) {
case NOTIFICATION_ENTER_TREE:
if (_block_updater == nullptr) {
start_updater();
}
set_process(true);
break;
case NOTIFICATION_PROCESS:
_process();
break;
case NOTIFICATION_EXIT_TREE:
break;
case NOTIFICATION_ENTER_WORLD: {
ERR_FAIL_COND(_map.is_null());
_map->for_all_blocks(SetWorldAction(*get_world()));
} break;
case NOTIFICATION_EXIT_WORLD:
ERR_FAIL_COND(_map.is_null());
_map->for_all_blocks(SetWorldAction(nullptr));
break;
case NOTIFICATION_VISIBILITY_CHANGED:
ERR_FAIL_COND(_map.is_null());
_map->for_all_blocks(SetParentVisibilityAction(is_visible()));
break;
// TODO Listen for transform changes
default:
break;
}
}
static void remove_positions_outside_box(
Vector<Vector3i> &positions,
Rect3i box,
Set<Vector3i> &loading_set) {
for (int i = 0; i < positions.size(); ++i) {
const Vector3i bpos = positions[i];
if (!box.contains(bpos)) {
const int last = positions.size() - 1;
positions.write[i] = positions[last];
positions.resize(last);
loading_set.erase(bpos);
--i;
}
}
}
void VoxelTerrain::get_viewer_pos_and_direction(Vector3 &out_pos, Vector3 &out_direction) const {
if (Engine::get_singleton()->is_editor_hint()) {
// TODO Use editor's camera here
out_pos = Vector3();
out_direction = Vector3(0, -1, 0);
} else {
// TODO Have option to use viewport camera
const Spatial *viewer = get_viewer();
if (viewer) {
Transform gt = viewer->get_global_transform();
out_pos = gt.origin;
out_direction = -gt.basis.get_axis(Vector3::AXIS_Z);
} else {
// TODO Just remember last viewer pos
out_pos = (_last_viewer_block_pos << _map->get_block_size_pow2()).to_vec3();
out_direction = Vector3(0, -1, 0);
}
}
}
void VoxelTerrain::send_block_data_requests() {
ERR_FAIL_COND(_stream_thread == nullptr);
VoxelDataLoader::Input input;
Vector3 viewer_pos;
get_viewer_pos_and_direction(viewer_pos, input.priority_direction);
input.priority_position = _map->voxel_to_block(Vector3i(viewer_pos));
for (int i = 0; i < _blocks_pending_load.size(); ++i) {
VoxelDataLoader::InputBlock input_block;
input_block.position = _blocks_pending_load[i];
input_block.lod = 0;
input.blocks.push_back(input_block);
}
for (unsigned int i = 0; i < _blocks_to_save.size(); ++i) {
PRINT_VERBOSE(String("Requesting save of block {0}").format(varray(_blocks_to_save[i].position.to_vec3())));
input.blocks.push_back(_blocks_to_save[i]);
}
//print_line(String("Sending {0} block requests").format(varray(input.blocks_to_emerge.size())));
_blocks_pending_load.clear();
_blocks_to_save.clear();
_stream_thread->push(input);
}
void VoxelTerrain::emit_block_loaded(const VoxelBlock *block) {
const Variant vpos = block->position.to_vec3();
const Variant vbuffer = block->voxels;
const Variant *args[2] = { &vpos, &vbuffer };
emit_signal(VoxelStringNames::get_singleton()->block_loaded, args, 2);
}
void VoxelTerrain::emit_block_unloaded(const VoxelBlock *block) {
const Variant vpos = block->position.to_vec3();
const Variant vbuffer = block->voxels;
const Variant *args[2] = { &vpos, &vbuffer };
emit_signal(VoxelStringNames::get_singleton()->block_unloaded, args, 2);
}
void VoxelTerrain::_process() {
// TODO Should be able to run without library, tho!
if (_library.is_null()) {
return;
}
OS &os = *OS::get_singleton();
ERR_FAIL_COND(_map.is_null());
ProfilingClock profiling_clock;
_stats.dropped_block_loads = 0;
_stats.dropped_block_meshs = 0;
// Get viewer location
// TODO Transform to local (Spatial Transform)
Vector3 viewer_pos;
Vector3 viewer_direction;
get_viewer_pos_and_direction(viewer_pos, viewer_direction);
Vector3i viewer_block_pos = _map->voxel_to_block(Vector3i(viewer_pos));
// Find out which blocks need to appear and which need to be unloaded
{
Rect3i new_box = Rect3i::from_center_extents(viewer_block_pos, Vector3i(_view_distance_blocks));
Rect3i prev_box = Rect3i::from_center_extents(_last_viewer_block_pos, Vector3i(_last_view_distance_blocks));
if (prev_box != new_box) {
//print_line(String("Loaded area changed: from ") + prev_box.to_string() + String(" to ") + new_box.to_string());
prev_box.difference(new_box, [this](Rect3i out_of_range_box) {
out_of_range_box.for_each_cell([=](Vector3i bpos) {
// Unload block
immerge_block(bpos);
});
});
new_box.difference(prev_box, [this](Rect3i box_to_load) {
box_to_load.for_each_cell([=](Vector3i bpos) {
// Load or update block
make_block_dirty(bpos);
});
});
}
// Eliminate pending blocks that aren't needed
remove_positions_outside_box(_blocks_pending_load, new_box, _loading_blocks);
remove_positions_outside_box(_blocks_pending_update, new_box, _loading_blocks);
}
_stats.time_detect_required_blocks = profiling_clock.restart();
_last_view_distance_blocks = _view_distance_blocks;
_last_viewer_block_pos = viewer_block_pos;
// It's possible the user didn't set a stream yet, or it is turned off
if (_stream_thread != nullptr) {
send_block_data_requests();
}
_stats.time_request_blocks_to_load = profiling_clock.restart();
// Get block loading responses
// Note: if block loading is too fast, this can cause stutters. It should only happen on first load, though.
if (_stream_thread != nullptr) {
VoxelDataLoader::Output output;
_stream_thread->pop(output);
//print_line(String("Receiving {0} blocks").format(varray(output.emerged_blocks.size())));
_stats.stream = output.stats;
for (int i = 0; i < output.blocks.size(); ++i) {
const VoxelDataLoader::OutputBlock &ob = output.blocks[i];
if (ob.data.type != VoxelDataLoader::TYPE_LOAD) {
continue;
}
const Vector3i block_pos = ob.position;
{
Set<Vector3i>::Element *E = _loading_blocks.find(block_pos);
if (E == nullptr) {
// That block was not requested, drop it
++_stats.dropped_block_loads;
continue;
}
_loading_blocks.erase(E);
}
if (ob.drop_hint) {
// That block was dropped by the data loader thread, but we were still expecting it...
// This is not good, because it means the loader is out of sync due to a bug.
PRINT_VERBOSE(String("Received a block loading drop while we were still expecting it: lod{0} ({1}, {2}, {3})")
.format(varray(ob.lod, ob.position.x, ob.position.y, ob.position.z)));
++_stats.dropped_block_loads;
continue;
}
if (ob.data.voxels_loaded->get_size() != Vector3i(_map->get_block_size())) {
// Voxel block size is incorrect, drop it
ERR_PRINT("Block size obtained from stream is different from expected size");
++_stats.dropped_block_loads;
continue;
}
// TODO Discard blocks out of range
// Store buffer
VoxelBlock *block = _map->get_block(block_pos);
bool update_neighbors = block == nullptr;
block = _map->set_block_buffer(block_pos, ob.data.voxels_loaded);
block->set_world(get_world());
emit_block_loaded(block);
// TODO The following code appears to have order-dependency with block loading.
// i.e if block loading responses arrive in a different order they were requested in,
// some blocks will be stuck in LOAD. For now I made it so no re-ordering happens,
// but it needs to be made more robust
// Trigger mesh updates
if (update_neighbors) {
// All neighbors have to be checked. If they are now surrounded, they can be updated
Vector3i ndir;
for (ndir.z = -1; ndir.z < 2; ++ndir.z) {
for (ndir.x = -1; ndir.x < 2; ++ndir.x) {
for (ndir.y = -1; ndir.y < 2; ++ndir.y) {
const Vector3i npos = block_pos + ndir;
// TODO What if the map is really composed of empty blocks?
if (_map->is_block_surrounded(npos)) {
VoxelBlock *nblock = _map->get_block(npos);
if (nblock == nullptr || nblock->get_mesh_state() == VoxelBlock::MESH_UPDATE_NOT_SENT) {
// Assuming it is scheduled to be updated already.
// In case of BLOCK_UPDATE_SENT, we'll have to resend it.
continue;
}
nblock->set_mesh_state(VoxelBlock::MESH_UPDATE_NOT_SENT);
_blocks_pending_update.push_back(npos);
}
}
}
}
} else {
// Only update the block, neighbors will probably follow if needed
block->set_mesh_state(VoxelBlock::MESH_UPDATE_NOT_SENT);
_blocks_pending_update.push_back(block_pos);
//OS::get_singleton()->print("Update (%i, %i, %i)\n", block_pos.x, block_pos.y, block_pos.z);
}
}
}
_stats.time_process_load_responses = profiling_clock.restart();
// Send mesh updates
{
ERR_FAIL_COND(_block_updater == nullptr);
VoxelMeshUpdater::Input input;
input.priority_position = viewer_block_pos;
input.priority_direction = viewer_direction;
for (int i = 0; i < _blocks_pending_update.size(); ++i) {
Vector3i block_pos = _blocks_pending_update[i];
// Check if the block is worth meshing
// Smooth meshing works on more neighbors, so checking a single block isn't enough to ignore it,
// but that will slow down meshing a lot.
// TODO This is one reason to separate terrain systems between blocky and smooth (other reason is LOD)
if (!(_stream->get_used_channels_mask() & (1 << VoxelBuffer::CHANNEL_SDF))) {
VoxelBlock *block = _map->get_block(block_pos);
if (block == nullptr) {
continue;
} else {
CRASH_COND(block->voxels.is_null());
const uint64_t air_type = 0;
if (
block->voxels->is_uniform(VoxelBuffer::CHANNEL_TYPE) &&
block->voxels->is_uniform(VoxelBuffer::CHANNEL_SDF) &&
block->voxels->get_voxel(0, 0, 0, VoxelBuffer::CHANNEL_TYPE) == air_type) {
// If we got here, it must have been because of scheduling an update
CRASH_COND(block->get_mesh_state() != VoxelBlock::MESH_UPDATE_NOT_SENT);
// The block contains empty voxels
block->set_mesh(Ref<Mesh>(), this, _generate_collisions, Vector<Array>(), get_tree()->is_debugging_collisions_hint());
block->set_mesh_state(VoxelBlock::MESH_UP_TO_DATE);
// Optional, but I guess it might spare some memory
block->voxels->clear_channel(VoxelBuffer::CHANNEL_TYPE, air_type);
continue;
}
}
}
VoxelBlock *block = _map->get_block(block_pos);
// If we got here, it must have been because of scheduling an update
CRASH_COND(block == nullptr);
CRASH_COND(block->get_mesh_state() != VoxelBlock::MESH_UPDATE_NOT_SENT);
// Create buffer padded with neighbor voxels
Ref<VoxelBuffer> nbuffer;
nbuffer.instance();
// TODO Make the buffer re-usable
unsigned int block_size = _map->get_block_size();
unsigned int min_padding = _block_updater->get_minimum_padding();
unsigned int max_padding = _block_updater->get_maximum_padding();
nbuffer->create(Vector3i(block_size + min_padding + max_padding));
unsigned int channels_mask = (1 << VoxelBuffer::CHANNEL_TYPE) | (1 << VoxelBuffer::CHANNEL_SDF);
_map->get_buffer_copy(_map->block_to_voxel(block_pos) - Vector3i(min_padding), **nbuffer, channels_mask);
VoxelMeshUpdater::InputBlock iblock;
iblock.data.voxels = nbuffer;
iblock.position = block_pos;
input.blocks.push_back(iblock);
block->set_mesh_state(VoxelBlock::MESH_UPDATE_SENT);
}
_block_updater->push(input);
_blocks_pending_update.clear();
}
_stats.time_request_blocks_to_update = profiling_clock.restart();
// Get mesh updates
{
{
VoxelMeshUpdater::Output output;
_block_updater->pop(output);
_stats.updater = output.stats;
_stats.updated_blocks = output.blocks.size();
_blocks_pending_main_thread_update.append_array(output.blocks);
}
const uint32_t timeout = os.get_ticks_msec() + MAIN_THREAD_MESHING_BUDGET_MS;
int queue_index = 0;
// The following is done on the main thread because Godot doesn't really support multithreaded Mesh allocation.
// This also proved to be very slow compared to the meshing process itself...
// hopefully Vulkan will allow us to upload graphical resources without stalling rendering as they upload?
for (; queue_index < _blocks_pending_main_thread_update.size() && os.get_ticks_msec() < timeout; ++queue_index) {
const VoxelMeshUpdater::OutputBlock &ob = _blocks_pending_main_thread_update[queue_index];
VoxelBlock *block = _map->get_block(ob.position);
if (block == nullptr) {
// That block is no longer loaded, drop the result
++_stats.dropped_block_meshs;
continue;
}
if (ob.drop_hint) {
// That block is loaded, but its meshing request was dropped.
// TODO Not sure what to do in this case, the code sending update queries has to be tweaked
PRINT_VERBOSE("Received a block mesh drop while we were still expecting it");
++_stats.dropped_block_meshs;
continue;
}
Ref<ArrayMesh> mesh;
mesh.instance();
Vector<Array> collidable_surfaces; //need to put both blocky and smooth surfaces into one list
int surface_index = 0;
const VoxelMeshUpdater::OutputBlockData &data = ob.data;
for (int i = 0; i < data.blocky_surfaces.surfaces.size(); ++i) {
Array surface = data.blocky_surfaces.surfaces[i];
if (surface.empty()) {
continue;
}
CRASH_COND(surface.size() != Mesh::ARRAY_MAX);
if (!is_surface_triangulated(surface)) {
continue;
}
collidable_surfaces.push_back(surface);
mesh->add_surface_from_arrays(
data.blocky_surfaces.primitive_type, surface, Array(), data.blocky_surfaces.compression_flags);
mesh->surface_set_material(surface_index, _materials[i]);
++surface_index;
}
for (int i = 0; i < data.smooth_surfaces.surfaces.size(); ++i) {
Array surface = data.smooth_surfaces.surfaces[i];
if (surface.empty()) {
continue;
}
CRASH_COND(surface.size() != Mesh::ARRAY_MAX);
if (!is_surface_triangulated(surface)) {
continue;
}
collidable_surfaces.push_back(surface);
mesh->add_surface_from_arrays(
data.smooth_surfaces.primitive_type, surface, Array(), data.smooth_surfaces.compression_flags);
mesh->surface_set_material(surface_index, _materials[i]);
++surface_index;
}
if (is_mesh_empty(mesh)) {
mesh = Ref<Mesh>();
}
block->set_mesh(mesh, this, _generate_collisions, collidable_surfaces, get_tree()->is_debugging_collisions_hint());
block->set_parent_visible(is_visible());
}
shift_up(_blocks_pending_main_thread_update, queue_index);
}
_stats.time_process_update_responses = profiling_clock.restart();
//print_line(String("d:") + String::num(_dirty_blocks.size()) + String(", q:") + String::num(_block_update_queue.size()));
}
Ref<VoxelTool> VoxelTerrain::get_voxel_tool() {
Ref<VoxelTool> vt = memnew(VoxelToolTerrain(this, _map));
if (_stream.is_valid()) {
if (_stream->get_used_channels_mask() & (1 << VoxelBuffer::CHANNEL_SDF)) {
vt->set_channel(VoxelBuffer::CHANNEL_SDF);
} else {
vt->set_channel(VoxelBuffer::CHANNEL_TYPE);
}
}
return vt;
}
void VoxelTerrain::set_run_stream_in_editor(bool enable) {
if (enable == _run_stream_in_editor) {
return;
}
_run_stream_in_editor = enable;
if (Engine::get_singleton()->is_editor_hint()) {
if (_run_stream_in_editor) {
_on_stream_params_changed();
} else {
// This is expected to block the main thread until the streaming thread is done.
stop_streamer();
}
}
}
bool VoxelTerrain::is_stream_running_in_editor() const {
return _run_stream_in_editor;
}
Vector3 VoxelTerrain::_b_voxel_to_block(Vector3 pos) {
return Vector3i(_map->voxel_to_block(pos)).to_vec3();
}
Vector3 VoxelTerrain::_b_block_to_voxel(Vector3 pos) {
return Vector3i(_map->block_to_voxel(pos)).to_vec3();
}
void VoxelTerrain::_b_save_modified_blocks() {
save_all_modified_blocks(true);
}
// Explicitely ask to save a block if it was modified
void VoxelTerrain::_b_save_block(Vector3 p_block_pos) {
ERR_FAIL_COND(_map.is_null());
const Vector3i block_pos(p_block_pos);
VoxelBlock *block = _map->get_block(block_pos);
ERR_FAIL_COND(block == nullptr);
if (!block->is_modified()) {
return;
}
ScheduleSaveAction{ _blocks_to_save, true }(block);
}
void VoxelTerrain::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_stream", "stream"), &VoxelTerrain::set_stream);
ClassDB::bind_method(D_METHOD("get_stream"), &VoxelTerrain::get_stream);
ClassDB::bind_method(D_METHOD("set_voxel_library", "library"), &VoxelTerrain::set_voxel_library);
ClassDB::bind_method(D_METHOD("get_voxel_library"), &VoxelTerrain::get_voxel_library);
ClassDB::bind_method(D_METHOD("set_material", "id", "material"), &VoxelTerrain::set_material);
ClassDB::bind_method(D_METHOD("get_material", "id"), &VoxelTerrain::get_material);
ClassDB::bind_method(D_METHOD("set_view_distance", "distance_in_voxels"), &VoxelTerrain::set_view_distance);
ClassDB::bind_method(D_METHOD("get_view_distance"), &VoxelTerrain::get_view_distance);
ClassDB::bind_method(D_METHOD("get_generate_collisions"), &VoxelTerrain::get_generate_collisions);
ClassDB::bind_method(D_METHOD("set_generate_collisions", "enabled"), &VoxelTerrain::set_generate_collisions);
ClassDB::bind_method(D_METHOD("get_viewer_path"), &VoxelTerrain::get_viewer_path);
ClassDB::bind_method(D_METHOD("set_viewer_path", "path"), &VoxelTerrain::set_viewer_path);
ClassDB::bind_method(D_METHOD("voxel_to_block", "voxel_pos"), &VoxelTerrain::_b_voxel_to_block);
ClassDB::bind_method(D_METHOD("block_to_voxel", "block_pos"), &VoxelTerrain::_b_block_to_voxel);
ClassDB::bind_method(D_METHOD("get_statistics"), &VoxelTerrain::get_statistics);
ClassDB::bind_method(D_METHOD("get_voxel_tool"), &VoxelTerrain::get_voxel_tool);
ClassDB::bind_method(D_METHOD("save_modified_blocks"), &VoxelTerrain::_b_save_modified_blocks);
ClassDB::bind_method(D_METHOD("save_block"), &VoxelTerrain::_b_save_block);
ClassDB::bind_method(D_METHOD("set_run_stream_in_editor"), &VoxelTerrain::set_run_stream_in_editor);
ClassDB::bind_method(D_METHOD("is_stream_running_in_editor"), &VoxelTerrain::is_stream_running_in_editor);
//ClassDB::bind_method(D_METHOD("_on_stream_params_changed"), &VoxelTerrain::_on_stream_params_changed);
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "stream", PROPERTY_HINT_RESOURCE_TYPE, "VoxelStream"),
"set_stream", "get_stream");
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "voxel_library", PROPERTY_HINT_RESOURCE_TYPE, "VoxelLibrary"),
"set_voxel_library", "get_voxel_library");
ADD_PROPERTY(PropertyInfo(Variant::INT, "view_distance"), "set_view_distance", "get_view_distance");
ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "viewer_path"), "set_viewer_path", "get_viewer_path");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "generate_collisions"),
"set_generate_collisions", "get_generate_collisions");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "run_stream_in_editor"),
"set_run_stream_in_editor", "is_stream_running_in_editor");
ADD_SIGNAL(MethodInfo(VoxelStringNames::get_singleton()->block_loaded,
PropertyInfo(Variant::VECTOR3, "position"),
PropertyInfo(Variant::OBJECT, "voxels", PROPERTY_HINT_RESOURCE_TYPE, "VoxelBuffer")));
ADD_SIGNAL(MethodInfo(VoxelStringNames::get_singleton()->block_unloaded,
PropertyInfo(Variant::VECTOR3, "position"),
PropertyInfo(Variant::OBJECT, "voxels", PROPERTY_HINT_RESOURCE_TYPE, "VoxelBuffer")));
}
|
/*
*
* Copyright 2019 gRPC 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.
*
*/
#include "src/cpp/server/external_connection_acceptor_impl.h"
#include <memory>
#include <grpcpp/server_builder.h>
#include <grpcpp/support/channel_arguments.h>
namespace grpc {
namespace internal {
namespace {
// The actual type to return to user. It co-owns the internal impl object with
// the server.
class AcceptorWrapper : public experimental::ExternalConnectionAcceptor {
public:
explicit AcceptorWrapper(std::shared_ptr<ExternalConnectionAcceptorImpl> impl)
: impl_(std::move(impl)) {}
void HandleNewConnection(NewConnectionParameters* p) override {
impl_->HandleNewConnection(p);
}
private:
std::shared_ptr<ExternalConnectionAcceptorImpl> impl_;
};
} // namespace
ExternalConnectionAcceptorImpl::ExternalConnectionAcceptorImpl(
const grpc::string& name,
ServerBuilder::experimental_type::ExternalConnectionType type,
std::shared_ptr<ServerCredentials> creds)
: name_(name), creds_(std::move(creds)) {
GPR_ASSERT(type ==
ServerBuilder::experimental_type::ExternalConnectionType::FROM_FD);
}
std::unique_ptr<experimental::ExternalConnectionAcceptor>
ExternalConnectionAcceptorImpl::GetAcceptor() {
grpc_core::MutexLock lock(&mu_);
GPR_ASSERT(!has_acceptor_);
has_acceptor_ = true;
return std::unique_ptr<experimental::ExternalConnectionAcceptor>(
new AcceptorWrapper(shared_from_this()));
}
void ExternalConnectionAcceptorImpl::HandleNewConnection(
experimental::ExternalConnectionAcceptor::NewConnectionParameters* p) {
grpc_core::MutexLock lock(&mu_);
if (shutdown_ || !started_) {
// TODO(yangg) clean up.
gpr_log(
GPR_ERROR,
"NOT handling external connection with fd %d, started %d, shutdown %d",
p->fd, started_, shutdown_);
return;
}
if (handler_) {
handler_->Handle(p->listener_fd, p->fd, p->read_buffer.c_buffer());
}
}
void ExternalConnectionAcceptorImpl::Shutdown() {
grpc_core::MutexLock lock(&mu_);
shutdown_ = true;
}
void ExternalConnectionAcceptorImpl::Start() {
grpc_core::MutexLock lock(&mu_);
GPR_ASSERT(!started_);
GPR_ASSERT(has_acceptor_);
GPR_ASSERT(!shutdown_);
started_ = true;
}
void ExternalConnectionAcceptorImpl::SetToChannelArgs(ChannelArguments* args) {
args->SetPointer(name_.c_str(), &handler_);
}
} // namespace internal
} // namespace grpc
|
// Copyright (c) 2011-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
//
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "askpassphrasedialog.h"
#include "ui_askpassphrasedialog.h"
#include "guiconstants.h"
#include "walletmodel.h"
#include "allocators.h"
#include <QKeyEvent>
#include <QMessageBox>
#include <QPushButton>
AskPassphraseDialog::AskPassphraseDialog(Mode mode, QWidget* parent, WalletModel* model) : QDialog(parent),
ui(new Ui::AskPassphraseDialog),
mode(mode),
model(model),
fCapsLock(false)
{
ui->setupUi(this);
ui->passEdit1->setMinimumSize(ui->passEdit1->sizeHint());
ui->passEdit2->setMinimumSize(ui->passEdit2->sizeHint());
ui->passEdit3->setMinimumSize(ui->passEdit3->sizeHint());
ui->passEdit1->setMaxLength(MAX_PASSPHRASE_SIZE);
ui->passEdit2->setMaxLength(MAX_PASSPHRASE_SIZE);
ui->passEdit3->setMaxLength(MAX_PASSPHRASE_SIZE);
// Setup Caps Lock detection.
ui->passEdit1->installEventFilter(this);
ui->passEdit2->installEventFilter(this);
ui->passEdit3->installEventFilter(this);
this->model = model;
switch (mode) {
case Encrypt: // Ask passphrase x2
ui->warningLabel->setText(tr("Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>ten or more random characters</b>, or <b>eight or more words</b>."));
ui->passLabel1->hide();
ui->passEdit1->hide();
setWindowTitle(tr("Encrypt wallet"));
break;
case UnlockAnonymize:
ui->anonymizationCheckBox->setChecked(true);
ui->anonymizationCheckBox->show();
case Unlock: // Ask passphrase
ui->warningLabel->setText(tr("This operation needs your wallet passphrase to unlock the wallet."));
ui->passLabel2->hide();
ui->passEdit2->hide();
ui->passLabel3->hide();
ui->passEdit3->hide();
setWindowTitle(tr("Unlock wallet"));
break;
case Decrypt: // Ask passphrase
ui->warningLabel->setText(tr("This operation needs your wallet passphrase to decrypt the wallet."));
ui->passLabel2->hide();
ui->passEdit2->hide();
ui->passLabel3->hide();
ui->passEdit3->hide();
setWindowTitle(tr("Decrypt wallet"));
break;
case ChangePass: // Ask old passphrase + new passphrase x2
setWindowTitle(tr("Change passphrase"));
ui->warningLabel->setText(tr("Enter the old and new passphrase to the wallet."));
break;
}
ui->anonymizationCheckBox->setChecked(model->isAnonymizeOnlyUnlocked());
textChanged();
connect(ui->passEdit1, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
connect(ui->passEdit2, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
connect(ui->passEdit3, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
}
AskPassphraseDialog::~AskPassphraseDialog()
{
// Attempt to overwrite text so that they do not linger around in memory
ui->passEdit1->setText(QString(" ").repeated(ui->passEdit1->text().size()));
ui->passEdit2->setText(QString(" ").repeated(ui->passEdit2->text().size()));
ui->passEdit3->setText(QString(" ").repeated(ui->passEdit3->text().size()));
delete ui;
}
void AskPassphraseDialog::accept()
{
SecureString oldpass, newpass1, newpass2;
if (!model)
return;
oldpass.reserve(MAX_PASSPHRASE_SIZE);
newpass1.reserve(MAX_PASSPHRASE_SIZE);
newpass2.reserve(MAX_PASSPHRASE_SIZE);
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make this input mlock()'d to begin with.
oldpass.assign(ui->passEdit1->text().toStdString().c_str());
newpass1.assign(ui->passEdit2->text().toStdString().c_str());
newpass2.assign(ui->passEdit3->text().toStdString().c_str());
switch (mode) {
case Encrypt: {
if (newpass1.empty() || newpass2.empty()) {
// Cannot encrypt with empty passphrase
break;
}
QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm wallet encryption"),
tr("Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR HRD</b>!") + "<br><br>" + tr("Are you sure you wish to encrypt your wallet?"),
QMessageBox::Yes | QMessageBox::Cancel,
QMessageBox::Cancel);
if (retval == QMessageBox::Yes) {
if (newpass1 == newpass2) {
if (model->setWalletEncrypted(true, newpass1)) {
QMessageBox::warning(this, tr("Wallet encrypted"),
"<qt>" +
tr("HRD will close now to finish the encryption process. "
"Remember that encrypting your wallet cannot fully protect "
"your HRDs from being stolen by malware infecting your computer.") +
"<br><br><b>" +
tr("IMPORTANT: Any previous backups you have made of your wallet file "
"should be replaced with the newly generated, encrypted wallet file. "
"For security reasons, previous backups of the unencrypted wallet file "
"will become useless as soon as you start using the new, encrypted wallet.") +
"</b></qt>");
QApplication::quit();
} else {
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("Wallet encryption failed due to an internal error. Your wallet was not encrypted."));
}
QDialog::accept(); // Success
} else {
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The supplied passphrases do not match."));
}
} else {
QDialog::reject(); // Cancelled
}
} break;
case UnlockAnonymize:
case Unlock:
if (!model->setWalletLocked(false, oldpass, ui->anonymizationCheckBox->isChecked())) {
QMessageBox::critical(this, tr("Wallet unlock failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
} else {
QDialog::accept(); // Success
}
break;
case Decrypt:
if (!model->setWalletEncrypted(false, oldpass)) {
QMessageBox::critical(this, tr("Wallet decryption failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
} else {
QDialog::accept(); // Success
}
break;
case ChangePass:
if (newpass1 == newpass2) {
if (model->changePassphrase(oldpass, newpass1)) {
QMessageBox::information(this, tr("Wallet encrypted"),
tr("Wallet passphrase was successfully changed."));
QDialog::accept(); // Success
} else {
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
}
} else {
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The supplied passphrases do not match."));
}
break;
}
}
void AskPassphraseDialog::textChanged()
{
// Validate input, set Ok button to enabled when acceptable
bool acceptable = false;
switch (mode) {
case Encrypt: // New passphrase x2
acceptable = !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();
break;
case UnlockAnonymize: // Old passphrase x1
case Unlock: // Old passphrase x1
case Decrypt:
acceptable = !ui->passEdit1->text().isEmpty();
break;
case ChangePass: // Old passphrase x1, new passphrase x2
acceptable = !ui->passEdit1->text().isEmpty() && !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();
break;
}
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(acceptable);
}
bool AskPassphraseDialog::event(QEvent* event)
{
// Detect Caps Lock key press.
if (event->type() == QEvent::KeyPress) {
QKeyEvent* ke = static_cast<QKeyEvent*>(event);
if (ke->key() == Qt::Key_CapsLock) {
fCapsLock = !fCapsLock;
}
if (fCapsLock) {
ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!"));
} else {
ui->capsLabel->clear();
}
}
return QWidget::event(event);
}
bool AskPassphraseDialog::eventFilter(QObject* object, QEvent* event)
{
/* Detect Caps Lock.
* There is no good OS-independent way to check a key state in Qt, but we
* can detect Caps Lock by checking for the following condition:
* Shift key is down and the result is a lower case character, or
* Shift key is not down and the result is an upper case character.
*/
if (event->type() == QEvent::KeyPress) {
QKeyEvent* ke = static_cast<QKeyEvent*>(event);
QString str = ke->text();
if (str.length() != 0) {
const QChar* psz = str.unicode();
bool fShift = (ke->modifiers() & Qt::ShiftModifier) != 0;
if ((fShift && *psz >= 'a' && *psz <= 'z') || (!fShift && *psz >= 'A' && *psz <= 'Z')) {
fCapsLock = true;
ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!"));
} else if (psz->isLetter()) {
fCapsLock = false;
ui->capsLabel->clear();
}
}
}
return QDialog::eventFilter(object, event);
}
|
/*
BSD 2-Clause License
Copyright (c) 2017 - 2020, FORNO
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.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef XMAHO_STD_EXT_VALARRAY_H
#define XMAHO_STD_EXT_VALARRAY_H
#include <cstddef>
#include <valarray>
/**
* @file std_ext/valarray.hpp
* @brief The utility functions for std::valarray.
*/
namespace xmaho::std_ext
{
/**
* @brief Return inner product "a * b"
*
* @pre a.size() == b.size()
* @param[in] a lhs value.
* @param[in] b rhs value.
* @return The inner product by a and b.
*
* @code
* const valarray<int> a {2, 4, 6};
* cosnt valarray<int> b {1, 3, 5};
* const auto result {inner_product(a, b)}
* assert(44 == result);
* @endcode
*/
template<typename T>
T inner_product(const std::valarray<T>& a, const std::valarray<T>& b);
/**
* @brief Return vector product "a cross b"
*
* @pre a.size() == b.size()
* @param[in] a lhs value.
* @param[in] b rhs value.
* @return The vector product by a and b.
*
* @code
* const valarray<int> a {2, 4, 6};
* cosnt valarray<int> b {1, 3, 5};
* const auto result {vector_product(a, b)}
* const auto correct {2, -4, 2};
* assert(equal(begin(correct), end(correct), begin(result), end(result)));
* @endcode
*/
template<typename T>
std::valarray<T> vector_product(const std::valarray<T>& a, const std::valarray<T>& b);
/**
* @brief Return size of vector.
*
* @tparam ordinal The norm of vector space.
* @tparam T The value type of valarray.
* @param[in] vector Input vector.
* @return The vector size.
*
* @code
* const valarray<int> v {1, -2, 2};
* const auto euclidean_distance {norm(v)};
* static_assert(is_same_v<const double, decltype(euclidean_distance)>, "norm on ordinal 2 return floting point type");
* assert(euclidean_distance == 3.); // It is correct operation with "==" because result is interger.
*
* const auto taxicab_distance {norm<1>(v)};
* static_assert(is_same_v<const int, decltype(taxicab_distance)>, "norm on ordinal 1 return same as value type");
* assert(taxicab_distance == 5);
*
* const auto uniform_norm {norm<numeric_limits<size_t>::max()>(v)};
* static_assert(is_same_v<const int, decltype(uniform_norm)>, "norm on ordinal max return same as value type");
* assert(uniform_norm == 2);
* @endcode
*/
template<std::size_t ordinal = 2, typename T>
auto norm(const std::valarray<T>& vector);
}
#include "detail/valarray.hpp"
#endif
|
#include <atomic>
#include <chrono>
#include <cstdlib>
#include <cstring>
#include <errno.h>
#include <inttypes.h>
#include <memory>
#include <mutex>
#if !defined(_WIN32)
#include <pthread.h>
#include <signal.h>
#include <unistd.h>
#endif
#include "thread.h"
#include <setjmp.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <thread>
#include <time.h>
#include <vector>
static const char *const RETVAL_PREFIX = "retval:";
static const char *const SLEEP_PREFIX = "sleep:";
static const char *const STDERR_PREFIX = "stderr:";
static const char *const SET_MESSAGE_PREFIX = "set-message:";
static const char *const PRINT_MESSAGE_COMMAND = "print-message:";
static const char *const GET_DATA_ADDRESS_PREFIX = "get-data-address-hex:";
static const char *const GET_STACK_ADDRESS_COMMAND = "get-stack-address-hex:";
static const char *const GET_HEAP_ADDRESS_COMMAND = "get-heap-address-hex:";
static const char *const GET_CODE_ADDRESS_PREFIX = "get-code-address-hex:";
static const char *const CALL_FUNCTION_PREFIX = "call-function:";
static const char *const THREAD_PREFIX = "thread:";
static const char *const THREAD_COMMAND_NEW = "new";
static const char *const THREAD_COMMAND_PRINT_IDS = "print-ids";
static const char *const THREAD_COMMAND_SEGFAULT = "segfault";
static const char *const PRINT_PID_COMMAND = "print-pid";
static bool g_print_thread_ids = false;
static std::mutex g_print_mutex;
static bool g_threads_do_segfault = false;
static std::mutex g_jump_buffer_mutex;
static jmp_buf g_jump_buffer;
static bool g_is_segfaulting = false;
static char g_message[256];
static volatile char g_c1 = '0';
static volatile char g_c2 = '1';
static void print_pid() {
#if defined(_WIN32)
fprintf(stderr, "PID: %d\n", ::GetCurrentProcessId());
#else
fprintf(stderr, "PID: %d\n", getpid());
#endif
}
static void signal_handler(int signo) {
#if defined(_WIN32)
// No signal support on Windows.
#else
const char *signal_name = nullptr;
switch (signo) {
case SIGUSR1:
signal_name = "SIGUSR1";
break;
case SIGSEGV:
signal_name = "SIGSEGV";
break;
default:
signal_name = nullptr;
}
// Print notice that we received the signal on a given thread.
char buf[100];
if (signal_name)
snprintf(buf, sizeof(buf), "received %s on thread id: %" PRIx64 "\n", signal_name, get_thread_id());
else
snprintf(buf, sizeof(buf), "received signo %d (%s) on thread id: %" PRIx64 "\n", signo, strsignal(signo), get_thread_id());
write(STDOUT_FILENO, buf, strlen(buf));
// Reset the signal handler if we're one of the expected signal handlers.
switch (signo) {
case SIGSEGV:
if (g_is_segfaulting) {
// Fix up the pointer we're writing to. This needs to happen if nothing
// intercepts the SIGSEGV (i.e. if somebody runs this from the command
// line).
longjmp(g_jump_buffer, 1);
}
break;
case SIGUSR1:
if (g_is_segfaulting) {
// Fix up the pointer we're writing to. This is used to test gdb remote
// signal delivery. A SIGSEGV will be raised when the thread is created,
// switched out for a SIGUSR1, and then this code still needs to fix the
// seg fault. (i.e. if somebody runs this from the command line).
longjmp(g_jump_buffer, 1);
}
break;
}
// Reset the signal handler.
sig_t sig_result = signal(signo, signal_handler);
if (sig_result == SIG_ERR) {
fprintf(stderr, "failed to set signal handler: errno=%d\n", errno);
exit(1);
}
#endif
}
static void swap_chars() {
#if defined(__x86_64__) || defined(__i386__)
asm volatile("movb %1, (%2)\n\t"
"movb %0, (%3)\n\t"
"movb %0, (%2)\n\t"
"movb %1, (%3)\n\t"
:
: "i"('0'), "i"('1'), "r"(&g_c1), "r"(&g_c2)
: "memory");
#elif defined(__aarch64__)
asm volatile("strb %w1, [%2]\n\t"
"strb %w0, [%3]\n\t"
"strb %w0, [%2]\n\t"
"strb %w1, [%3]\n\t"
:
: "r"('0'), "r"('1'), "r"(&g_c1), "r"(&g_c2)
: "memory");
#elif defined(__arm__)
asm volatile("strb %1, [%2]\n\t"
"strb %0, [%3]\n\t"
"strb %0, [%2]\n\t"
"strb %1, [%3]\n\t"
:
: "r"('0'), "r"('1'), "r"(&g_c1), "r"(&g_c2)
: "memory");
#else
#warning This may generate unpredictible assembly and cause the single-stepping test to fail.
#warning Please add appropriate assembly for your target.
g_c1 = '1';
g_c2 = '0';
g_c1 = '0';
g_c2 = '1';
#endif
}
static void hello() {
std::lock_guard<std::mutex> lock(g_print_mutex);
printf("hello, world\n");
}
static void *thread_func(void *arg) {
static std::atomic<int> s_thread_index(1);
const int this_thread_index = s_thread_index++;
if (g_print_thread_ids) {
std::lock_guard<std::mutex> lock(g_print_mutex);
printf("thread %d id: %" PRIx64 "\n", this_thread_index, get_thread_id());
}
if (g_threads_do_segfault) {
// Sleep for a number of seconds based on the thread index.
// TODO add ability to send commands to test exe so we can
// handle timing more precisely. This is clunky. All we're
// trying to do is add predictability as to the timing of
// signal generation by created threads.
int sleep_seconds = 2 * (this_thread_index - 1);
std::this_thread::sleep_for(std::chrono::seconds(sleep_seconds));
// Test creating a SEGV.
{
std::lock_guard<std::mutex> lock(g_jump_buffer_mutex);
g_is_segfaulting = true;
int *bad_p = nullptr;
if (setjmp(g_jump_buffer) == 0) {
// Force a seg fault signal on this thread.
*bad_p = 0;
} else {
// Tell the system we're no longer seg faulting.
// Used by the SIGUSR1 signal handler that we inject
// in place of the SIGSEGV so it only tries to
// recover from the SIGSEGV if this seg fault code
// was in play.
g_is_segfaulting = false;
}
}
{
std::lock_guard<std::mutex> lock(g_print_mutex);
printf("thread %" PRIx64 ": past SIGSEGV\n", get_thread_id());
}
}
int sleep_seconds_remaining = 60;
std::this_thread::sleep_for(std::chrono::seconds(sleep_seconds_remaining));
return nullptr;
}
int main(int argc, char **argv) {
lldb_enable_attach();
std::vector<std::thread> threads;
std::unique_ptr<uint8_t[]> heap_array_up;
int return_value = 0;
#if !defined(_WIN32)
// Set the signal handler.
sig_t sig_result = signal(SIGALRM, signal_handler);
if (sig_result == SIG_ERR) {
fprintf(stderr, "failed to set SIGALRM signal handler: errno=%d\n", errno);
exit(1);
}
sig_result = signal(SIGUSR1, signal_handler);
if (sig_result == SIG_ERR) {
fprintf(stderr, "failed to set SIGUSR1 handler: errno=%d\n", errno);
exit(1);
}
sig_result = signal(SIGSEGV, signal_handler);
if (sig_result == SIG_ERR) {
fprintf(stderr, "failed to set SIGUSR1 handler: errno=%d\n", errno);
exit(1);
}
#endif
// Process command line args.
for (int i = 1; i < argc; ++i) {
if (std::strstr(argv[i], STDERR_PREFIX)) {
// Treat remainder as text to go to stderr.
fprintf(stderr, "%s\n", (argv[i] + strlen(STDERR_PREFIX)));
} else if (std::strstr(argv[i], RETVAL_PREFIX)) {
// Treat as the return value for the program.
return_value = std::atoi(argv[i] + strlen(RETVAL_PREFIX));
} else if (std::strstr(argv[i], SLEEP_PREFIX)) {
// Treat as the amount of time to have this process sleep (in seconds).
int sleep_seconds_remaining = std::atoi(argv[i] + strlen(SLEEP_PREFIX));
// Loop around, sleeping until all sleep time is used up. Note that
// signals will cause sleep to end early with the number of seconds
// remaining.
std::this_thread::sleep_for(
std::chrono::seconds(sleep_seconds_remaining));
} else if (std::strstr(argv[i], SET_MESSAGE_PREFIX)) {
// Copy the contents after "set-message:" to the g_message buffer.
// Used for reading inferior memory and verifying contents match
// expectations.
strncpy(g_message, argv[i] + strlen(SET_MESSAGE_PREFIX),
sizeof(g_message));
// Ensure we're null terminated.
g_message[sizeof(g_message) - 1] = '\0';
} else if (std::strstr(argv[i], PRINT_MESSAGE_COMMAND)) {
std::lock_guard<std::mutex> lock(g_print_mutex);
printf("message: %s\n", g_message);
} else if (std::strstr(argv[i], GET_DATA_ADDRESS_PREFIX)) {
volatile void *data_p = nullptr;
if (std::strstr(argv[i] + strlen(GET_DATA_ADDRESS_PREFIX), "g_message"))
data_p = &g_message[0];
else if (std::strstr(argv[i] + strlen(GET_DATA_ADDRESS_PREFIX), "g_c1"))
data_p = &g_c1;
else if (std::strstr(argv[i] + strlen(GET_DATA_ADDRESS_PREFIX), "g_c2"))
data_p = &g_c2;
std::lock_guard<std::mutex> lock(g_print_mutex);
printf("data address: %p\n", data_p);
} else if (std::strstr(argv[i], GET_HEAP_ADDRESS_COMMAND)) {
// Create a byte array if not already present.
if (!heap_array_up)
heap_array_up.reset(new uint8_t[32]);
std::lock_guard<std::mutex> lock(g_print_mutex);
printf("heap address: %p\n", heap_array_up.get());
} else if (std::strstr(argv[i], GET_STACK_ADDRESS_COMMAND)) {
std::lock_guard<std::mutex> lock(g_print_mutex);
printf("stack address: %p\n", &return_value);
} else if (std::strstr(argv[i], GET_CODE_ADDRESS_PREFIX)) {
void (*func_p)() = nullptr;
if (std::strstr(argv[i] + strlen(GET_CODE_ADDRESS_PREFIX), "hello"))
func_p = hello;
else if (std::strstr(argv[i] + strlen(GET_CODE_ADDRESS_PREFIX),
"swap_chars"))
func_p = swap_chars;
std::lock_guard<std::mutex> lock(g_print_mutex);
printf("code address: %p\n", func_p);
} else if (std::strstr(argv[i], CALL_FUNCTION_PREFIX)) {
void (*func_p)() = nullptr;
// Default to providing the address of main.
if (std::strcmp(argv[i] + strlen(CALL_FUNCTION_PREFIX), "hello") == 0)
func_p = hello;
else if (std::strcmp(argv[i] + strlen(CALL_FUNCTION_PREFIX),
"swap_chars") == 0)
func_p = swap_chars;
else {
std::lock_guard<std::mutex> lock(g_print_mutex);
printf("unknown function: %s\n",
argv[i] + strlen(CALL_FUNCTION_PREFIX));
}
if (func_p)
func_p();
} else if (std::strstr(argv[i], THREAD_PREFIX)) {
// Check if we're creating a new thread.
if (std::strstr(argv[i] + strlen(THREAD_PREFIX), THREAD_COMMAND_NEW)) {
threads.push_back(std::thread(thread_func, nullptr));
} else if (std::strstr(argv[i] + strlen(THREAD_PREFIX),
THREAD_COMMAND_PRINT_IDS)) {
// Turn on thread id announcing.
g_print_thread_ids = true;
// And announce us.
{
std::lock_guard<std::mutex> lock(g_print_mutex);
printf("thread 0 id: %" PRIx64 "\n", get_thread_id());
}
} else if (std::strstr(argv[i] + strlen(THREAD_PREFIX),
THREAD_COMMAND_SEGFAULT)) {
g_threads_do_segfault = true;
} else {
// At this point we don't do anything else with threads.
// Later use thread index and send command to thread.
}
} else if (std::strstr(argv[i], PRINT_PID_COMMAND)) {
print_pid();
} else {
// Treat the argument as text for stdout.
printf("%s\n", argv[i]);
}
}
// If we launched any threads, join them
for (std::vector<std::thread>::iterator it = threads.begin();
it != threads.end(); ++it)
it->join();
return return_value;
}
|
// Copyright 2019 The Fuchsia 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 "src/cobalt/bin/system-metrics/memory_stats_fetcher_impl.h"
#include <fcntl.h>
#include <fuchsia/cobalt/cpp/fidl.h>
#include <fuchsia/sysinfo/c/fidl.h>
#include <lib/fdio/fdio.h>
#include <lib/zx/resource.h>
#include <zircon/status.h>
#include "src/lib/fxl/logging.h"
namespace cobalt {
MemoryStatsFetcherImpl::MemoryStatsFetcherImpl() {
InitializeRootResourceHandle();
}
bool MemoryStatsFetcherImpl::FetchMemoryStats(zx_info_kmem_stats_t* mem_stats) {
if (root_resource_handle_ == ZX_HANDLE_INVALID) {
FXL_LOG(ERROR) << "MemoryStatsFetcherImpl: No root resource"
<< "present. Reconnecting...";
InitializeRootResourceHandle();
return false;
}
zx_status_t err =
zx_object_get_info(root_resource_handle_, ZX_INFO_KMEM_STATS, mem_stats,
sizeof(*mem_stats), NULL, NULL);
if (err != ZX_OK) {
FXL_LOG(ERROR) << "MemoryStatsFetcherImpl: Fetching "
<< "ZX_INFO_KMEM_STATS through syscall returns "
<< zx_status_get_string(err);
return false;
}
return true;
}
// TODO(CF-691) When Component Stats (CS) supports memory metrics,
// switch to Component Stats / iquery, by creating a new class with the
// interface MemoryStatsFetcher.
void MemoryStatsFetcherImpl::InitializeRootResourceHandle() {
static const char kSysInfo[] = "/dev/misc/sysinfo";
int fd = open(kSysInfo, O_RDWR);
if (fd < 0) {
FXL_LOG(ERROR)
<< "Cobalt SystemMetricsDaemon: Error getting root_resource_handle_. "
<< "Cannot open sysinfo: " << strerror(errno);
return;
}
zx::channel channel;
zx_status_t status =
fdio_get_service_handle(fd, channel.reset_and_get_address());
if (status != ZX_OK) {
FXL_LOG(ERROR)
<< "Cobalt SystemMetricsDaemon: Error getting root_resource_handle_. "
<< "Cannot obtain sysinfo channel: " << zx_status_get_string(status);
return;
}
zx_status_t fidl_status = fuchsia_sysinfo_DeviceGetRootResource(
channel.get(), &status, &root_resource_handle_);
if (fidl_status != ZX_OK) {
FXL_LOG(ERROR)
<< "Cobalt SystemMetricsDaemon: Error getting root_resource_handle_. "
<< zx_status_get_string(fidl_status);
return;
} else if (status != ZX_OK) {
FXL_LOG(ERROR)
<< "Cobalt SystemMetricsDaemon: Error getting root_resource_handle_. "
<< zx_status_get_string(status);
return;
} else if (root_resource_handle_ == ZX_HANDLE_INVALID) {
FXL_LOG(ERROR)
<< "Cobalt SystemMetricsDaemon: Failed to get root_resource_handle_.";
return;
}
}
} // namespace cobalt
|
// Implementation based on:
// - DHT 12 Component
#include "tmp117.h"
#include "esphome/core/log.h"
namespace esphome {
namespace tmp117 {
static const char *const TAG = "tmp117";
void TMP117Component::update() {
int16_t data;
if (!this->read_data_(&data)) {
this->status_set_warning();
return;
}
if ((uint16_t) data != 0x8000) {
float temperature = data * 0.0078125f;
ESP_LOGD(TAG, "Got temperature=%.2f°C", temperature);
this->publish_state(temperature);
this->status_clear_warning();
} else {
ESP_LOGD(TAG, "TMP117 not ready");
}
}
void TMP117Component::setup() {
ESP_LOGCONFIG(TAG, "Setting up TMP117...");
if (!this->write_config_(this->config_)) {
this->mark_failed();
return;
}
int16_t data;
if (!this->read_data_(&data)) {
this->mark_failed();
return;
}
}
void TMP117Component::dump_config() {
ESP_LOGD(TAG, "TMP117:");
LOG_I2C_DEVICE(this);
if (this->is_failed()) {
ESP_LOGE(TAG, "Communication with TMP117 failed!");
}
LOG_SENSOR(" ", "Temperature", this);
}
float TMP117Component::get_setup_priority() const { return setup_priority::DATA; }
bool TMP117Component::read_data_(int16_t *data) {
if (!this->read_byte_16(0, (uint16_t *) data)) {
ESP_LOGW(TAG, "Updating TMP117 failed!");
return false;
}
return true;
}
bool TMP117Component::read_config_(uint16_t *config) {
if (!this->read_byte_16(1, (uint16_t *) config)) {
ESP_LOGW(TAG, "Reading TMP117 config failed!");
return false;
}
return true;
}
bool TMP117Component::write_config_(uint16_t config) {
if (!this->write_byte_16(1, config)) {
ESP_LOGE(TAG, "Writing TMP117 config failed!");
return false;
}
return true;
}
} // namespace tmp117
} // namespace esphome
|
#ifndef TERMOX_PAINTER_PALETTE_TELETEXT_HPP
#define TERMOX_PAINTER_PALETTE_TELETEXT_HPP
#include <termox/painter/color.hpp>
namespace ox::teletext {
constexpr auto Black = Color::Background;
constexpr auto Blue = Color{4};
constexpr auto Red = Color{1};
constexpr auto Magenta = Color{5};
constexpr auto Lime = Color{2};
constexpr auto Cyan = Color{6};
constexpr auto Yellow = Color{3};
constexpr auto White = Color::Foreground;
/// World System Teletext Level 1 Color Palette
inline auto const palette = Palette{
/* clang-format off */
{Black, ANSI{16}, 0x000000},
{Blue, ANSI{17}, 0x0000ff},
{Red, ANSI{18}, 0xff0000},
{Magenta, ANSI{19}, 0xff00ff},
{Lime, ANSI{20}, 0x00ff00},
{Cyan, ANSI{21}, 0x00ffff},
{Yellow, ANSI{22}, 0xffff00},
{White, ANSI{23}, 0xffffff},
/* clang-format on */
};
} // namespace ox::teletext
#endif // TERMOX_PAINTER_PALETTE_TELETEXT_HPP
|
/*
* See header file for a description of this class.
*
* $Date: 008/03/21 15:13:57 $
* $Revision: 1.2 $
* \author Paolo Ronchese INFN Padova
*
*/
//-----------------------
// This Class' Header --
//-----------------------
#include "CondTools/DT/test/validate/DTROMapValidateHandler.h"
//-------------------------------
// Collaborating Class Headers --
//-------------------------------
#include "CondFormats/DTObjects/interface/DTReadOutMapping.h"
//---------------
// C++ Headers --
//---------------
#include <iostream>
#include <fstream>
#include <sstream>
//-------------------
// Initializations --
//-------------------
//----------------
// Constructors --
//----------------
DTROMapValidateHandler::DTROMapValidateHandler(const edm::ParameterSet& ps)
: dataVersion(ps.getParameter<std::string>("version")),
dataFileName(ps.getParameter<std::string>("outFile")),
elogFileName(ps.getParameter<std::string>("logFile")) {
std::ofstream logFile(elogFileName.c_str());
}
//--------------
// Destructor --
//--------------
DTROMapValidateHandler::~DTROMapValidateHandler() {}
//--------------
// Operations --
//--------------
void DTROMapValidateHandler::getNewObjects() {
std::string dRosTag(dataVersion);
std::string dRobTag(dataVersion);
dRosTag += "_ROS";
dRobTag += "_ROB";
DTReadOutMapping* ro = new DTReadOutMapping(dRosTag, dRobTag);
// std::stringstream run_fn;
// run_fn << "run" << irun << dataFileName;
int status = 0;
// std::ofstream outFile( run_fn.str().c_str() );
std::ofstream outFile(dataFileName.c_str());
std::ofstream logFile(elogFileName.c_str(), std::ios_base::app);
int whe;
int sta;
int sec;
int qua;
int lay;
int cel;
int ddu;
int ros;
int rob;
int tdc;
int cha;
int ckwhe;
int cksta;
int cksec;
int ckqua;
int cklay;
int ckcel;
int ckddu;
int ckros;
int ckrob;
int cktdc;
int ckcha;
whe = 3;
while (--whe >= -2) {
ddu = whe + 773;
sta = 5;
while (--sta) {
// if ( sta == 4 ) sec = 15;
// else sec = 13;
sec = 13;
while (--sec) {
ros = sec;
qua = 4;
while (--qua) {
rob = ((sta - 1) * 6) + qua;
if ((sta == 4) && (qua == 2))
continue;
lay = 5;
while (--lay) {
cel = 20;
while (--cel) {
cha = ((cel - 1) * 4) + lay;
tdc = 0;
while (cha > 31) {
cha -= 32;
tdc++;
}
status = ro->insertReadOutGeometryLink(ddu, ros, rob, tdc, cha, whe, sta, sec, qua, lay, cel);
outFile << ddu << " " << ros << " " << rob << " " << tdc << " " << cha << " " << whe << " " << sta << " "
<< sec << " " << qua << " " << lay << " " << cel << std::endl;
if (status)
logFile << "ERROR while setting chan-cell map " << ddu << " " << ros << " " << rob << " " << tdc << " "
<< cha << " -> " << whe << " " << sta << " " << sec << " " << qua << " " << lay << " " << cel
<< " , status = " << status << std::endl;
status = ro->readOutToGeometry(ddu, ros, rob, tdc, cha, ckwhe, cksta, cksec, ckqua, cklay, ckcel);
if (status)
logFile << "ERROR while checking chan->cell map " << ddu << " " << ros << " " << rob << " " << tdc
<< " " << cha << " -> " << whe << " " << sta << " " << sec << " " << qua << " " << lay << " "
<< cel << " , status = " << status << std::endl;
if ((ckwhe != whe) || (cksta != sta) || (cksec != sec) || (ckqua != qua) || (cklay != lay) ||
(ckcel != cel))
logFile << "MISMATCH WHEN WRITING chan->cell " << ddu << " " << ros << " " << rob << " " << tdc << " "
<< cha << " : " << whe << " " << sta << " " << sec << " " << qua << " " << lay << " " << cel
<< " -> " << ckwhe << " " << cksta << " " << cksec << " " << ckqua << " " << cklay << " "
<< ckcel << std::endl;
status = ro->geometryToReadOut(whe, sta, sec, qua, lay, cel, ckddu, ckros, ckrob, cktdc, ckcha);
if (status)
logFile << "ERROR while checking cell->chan map " << whe << " " << sta << " " << sec << " " << qua
<< " " << lay << " " << cel << " -> " << ddu << " " << ros << " " << rob << " " << tdc << " "
<< cha << " , status = " << status << std::endl;
if ((ckddu != ddu) || (ckros != ros) || (ckrob != rob) || (cktdc != tdc) || (ckcha != cha))
logFile << "MISMATCH WHEN WRITING cell->chan " << whe << " " << sta << " " << sec << " " << qua << " "
<< lay << " " << cel << " : " << ddu << " " << ros << " " << rob << " " << tdc << " " << cha
<< " -> " << ckddu << " " << ckros << " " << ckrob << " " << cktdc << " " << ckcha << std::endl;
}
}
}
}
}
}
cond::Time_t snc = 1;
m_to_transfer.push_back(std::make_pair(ro, snc));
return;
}
std::string DTROMapValidateHandler::id() const { return dataVersion; }
|
/* Copyright (c) 2018, Ford Motor Company
* 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 Ford Motor Company 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 "policy/sql_pt_representation.h"
#include <stdio.h>
#include <sys/stat.h>
#include <algorithm>
#include <fstream>
#include <memory>
#include <string>
#include <vector>
#include "gtest/gtest.h"
#include "json/reader.h"
#include "json/writer.h"
#include "policy/driver_dbms.h"
#include "policy/mock_policy_settings.h"
#include "policy/policy_table/enums.h"
#include "policy/policy_table/types.h"
#include "policy/policy_types.h"
#include "rpc_base/rpc_base.h"
#include "sqlite_wrapper/sql_query.h"
#include "utils/file_system.h"
#include "utils/sqlite_wrapper/sql_database.h"
using testing::NiceMock;
using testing::ReturnRef;
namespace test {
namespace components {
namespace policy_test {
class SQLPTRepresentationStorageTest : public ::testing::Test {
protected:
const std::string kAppStorageFolder =
"storage_SQLPTRepresentationStorageTest";
std::shared_ptr<utils::dbms::SQLQuery> query_wrapper_;
std::shared_ptr<policy::SQLPTRepresentation> reps;
std::shared_ptr<NiceMock<policy_handler_test::MockPolicySettings> >
policy_settings_;
void SetUp() OVERRIDE {
file_system::CreateDirectory(kAppStorageFolder);
reps = std::make_shared<policy::SQLPTRepresentation>();
ASSERT_TRUE(reps != NULL);
policy_settings_ =
std::make_shared<NiceMock<policy_handler_test::MockPolicySettings> >();
ON_CALL(*policy_settings_, app_storage_folder())
.WillByDefault(ReturnRef(kAppStorageFolder));
ASSERT_EQ(policy::SUCCESS, reps->Init(policy_settings_.get()));
query_wrapper_ = std::make_shared<utils::dbms::SQLQuery>(reps->db());
ASSERT_TRUE(query_wrapper_ != NULL);
}
void TearDown() OVERRIDE {
EXPECT_TRUE(reps->Drop());
EXPECT_TRUE(reps->Close());
file_system::remove_directory_content(kAppStorageFolder);
file_system::RemoveDirectory(kAppStorageFolder, true);
}
};
TEST_F(
SQLPTRepresentationStorageTest,
CheckPermissionsAllowedWithoutParameters_SetLimitedPermissions_ExpectEmptyListOfAllowedParams) {
// Arrange
const std::string value_12345 = "12345";
const std::string query =
"INSERT OR REPLACE INTO `application` (`id`, `memory_kb`,"
" `heart_beat_timeout_ms`) VALUES ('" +
value_12345 +
"', 5, 10); "
"INSERT OR REPLACE INTO functional_group (`id`, `name`)"
" VALUES (1, 'Base-4'); "
"INSERT OR REPLACE INTO `app_group` (`application_id`,"
" `functional_group_id`) VALUES ('" +
value_12345 +
"', 1); "
"DELETE FROM `rpc`; "
"INSERT OR REPLACE INTO `rpc` (`name`, `hmi_level_value`,"
" `functional_group_id`) VALUES ('Update', 'LIMITED', 1);";
// Assert
ASSERT_TRUE(query_wrapper_->Exec(query));
// Act
policy::CheckPermissionResult ret;
reps->CheckPermissions(value_12345, "LIMITED", "Update", ret);
// Assert
EXPECT_TRUE(ret.hmi_level_permitted == ::policy::kRpcAllowed);
EXPECT_TRUE(ret.list_of_allowed_params.empty());
}
} // namespace policy_test
} // namespace components
} // namespace test
|
/******************************************************************************
* $Id: ogrgeojsonutils.cpp 33714 2016-03-13 05:42:13Z goatbar $
*
* Project: OpenGIS Simple Features Reference Implementation
* Purpose: Implementation of private utilities used within OGR GeoJSON Driver.
* Author: Mateusz Loskot, mateusz@loskot.net
*
******************************************************************************
* Copyright (c) 2007, Mateusz Loskot
* Copyright (c) 2010-2013, Even Rouault <even dot rouault at mines-paris dot org>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
****************************************************************************/
#include "ogrgeojsonutils.h"
#include <cpl_port.h>
#include <cpl_conv.h>
#include <ogr_geometry.h>
#include <json.h> // JSON-C
/************************************************************************/
/* GeoJSONIsObject() */
/************************************************************************/
int GeoJSONIsObject( const char* pszText )
{
if( NULL == pszText )
return FALSE;
/* Skip UTF-8 BOM (#5630) */
const GByte* pabyData = (const GByte*)pszText;
if( pabyData[0] == 0xEF && pabyData[1] == 0xBB && pabyData[2] == 0xBF )
pszText += 3;
/* -------------------------------------------------------------------- */
/* This is a primitive test, but we need to perform it fast. */
/* -------------------------------------------------------------------- */
while( *pszText != '\0' && isspace( (unsigned char)*pszText ) )
pszText++;
const char* const apszPrefix[] = { "loadGeoJSON(", "jsonp(" };
for(size_t iP = 0; iP < sizeof(apszPrefix) / sizeof(apszPrefix[0]); iP++ )
{
if( strncmp(pszText, apszPrefix[iP], strlen(apszPrefix[iP])) == 0 )
{
pszText += strlen(apszPrefix[iP]);
break;
}
}
if( *pszText != '{' )
return FALSE;
return ((strstr(pszText, "\"type\"") != NULL && strstr(pszText, "\"coordinates\"") != NULL)
|| (strstr(pszText, "\"type\"") != NULL && strstr(pszText, "\"Topology\"") != NULL)
|| strstr(pszText, "\"FeatureCollection\"") != NULL
|| strstr(pszText, "\"Feature\"") != NULL
|| (strstr(pszText, "\"geometryType\"") != NULL && strstr(pszText, "\"esriGeometry") != NULL));
}
/************************************************************************/
/* GeoJSONFileIsObject() */
/************************************************************************/
static
bool GeoJSONFileIsObject( GDALOpenInfo* poOpenInfo )
{
// by default read first 6000 bytes
// 6000 was chosen as enough bytes to
// enable all current tests to pass
if( poOpenInfo->fpL == NULL ||
!poOpenInfo->TryToIngest(6000) )
{
return false;
}
if( !GeoJSONIsObject((const char*)poOpenInfo->pabyHeader) )
{
return false;
}
return true;
}
/************************************************************************/
/* GeoJSONGetSourceType() */
/************************************************************************/
GeoJSONSourceType GeoJSONGetSourceType( GDALOpenInfo* poOpenInfo )
{
GeoJSONSourceType srcType = eGeoJSONSourceUnknown;
// NOTE: Sometimes URL ends with .geojson token, for example
// http://example/path/2232.geojson
// It's important to test beginning of source first.
if ( eGeoJSONProtocolUnknown != GeoJSONGetProtocolType( poOpenInfo->pszFilename ) )
{
if( (strstr(poOpenInfo->pszFilename, "SERVICE=WFS") ||
strstr(poOpenInfo->pszFilename, "service=WFS") ||
strstr(poOpenInfo->pszFilename, "service=wfs")) &&
!strstr(poOpenInfo->pszFilename, "json") )
return srcType;
srcType = eGeoJSONSourceService;
}
else if( EQUAL( CPLGetExtension( poOpenInfo->pszFilename ), "geojson" )
|| EQUAL( CPLGetExtension( poOpenInfo->pszFilename ), "json" )
|| EQUAL( CPLGetExtension( poOpenInfo->pszFilename ), "topojson" )
|| ((STARTS_WITH_CI(poOpenInfo->pszFilename, "/vsigzip/") || STARTS_WITH_CI(poOpenInfo->pszFilename, "/vsizip/")) &&
(strstr( poOpenInfo->pszFilename, ".json") || strstr( poOpenInfo->pszFilename, ".JSON") ||
strstr( poOpenInfo->pszFilename, ".geojson") || strstr( poOpenInfo->pszFilename, ".GEOJSON")) ))
{
if( poOpenInfo->fpL != NULL )
srcType = eGeoJSONSourceFile;
}
else if( GeoJSONIsObject( poOpenInfo->pszFilename ) )
{
srcType = eGeoJSONSourceText;
}
else if( GeoJSONFileIsObject( poOpenInfo ) )
{
srcType = eGeoJSONSourceFile;
}
return srcType;
}
/************************************************************************/
/* GeoJSONGetProtocolType() */
/************************************************************************/
GeoJSONProtocolType GeoJSONGetProtocolType( const char* pszSource )
{
GeoJSONProtocolType ptclType = eGeoJSONProtocolUnknown;
if( STARTS_WITH_CI(pszSource, "http:") )
ptclType = eGeoJSONProtocolHTTP;
else if( STARTS_WITH_CI(pszSource, "https:") )
ptclType = eGeoJSONProtocolHTTPS;
else if( STARTS_WITH_CI(pszSource, "ftp:") )
ptclType = eGeoJSONProtocolFTP;
return ptclType;
}
/************************************************************************/
/* GeoJSONPropertyToFieldType() */
/************************************************************************/
#define MY_INT64_MAX ((((GIntBig)0x7FFFFFFF) << 32) | 0xFFFFFFFF)
#define MY_INT64_MIN ((((GIntBig)0x80000000) << 32))
OGRFieldType GeoJSONPropertyToFieldType( json_object* poObject,
OGRFieldSubType& eSubType,
bool bArrayAsString )
{
eSubType = OFSTNone;
if (poObject == NULL) { return OFTString; }
json_type type = json_object_get_type( poObject );
if( json_type_boolean == type )
{
eSubType = OFSTBoolean;
return OFTInteger;
}
else if( json_type_double == type )
return OFTReal;
else if( json_type_int == type )
{
GIntBig nVal = json_object_get_int64(poObject);
if( !CPL_INT64_FITS_ON_INT32(nVal) )
{
if( nVal == MY_INT64_MIN || nVal == MY_INT64_MAX )
{
static bool bWarned = false;
if( !bWarned )
{
bWarned = true;
CPLError(CE_Warning, CPLE_AppDefined,
"Integer values probably ranging out of 64bit integer range "
"have been found. Will be clamped to INT64_MIN/INT64_MAX");
}
}
return OFTInteger64;
}
else
{
return OFTInteger;
}
}
else if( json_type_string == type )
return OFTString;
else if( json_type_array == type )
{
if( bArrayAsString )
return OFTString;
int nSize = json_object_array_length(poObject);
if (nSize == 0)
return OFTStringList; /* we don't know, so let's assume it's a string list */
OGRFieldType eType = OFTIntegerList;
int bOnlyBoolean = TRUE;
for(int i=0;i<nSize;i++)
{
json_object* poRow = json_object_array_get_idx(poObject, i);
if (poRow != NULL)
{
type = json_object_get_type( poRow );
bOnlyBoolean &= (type == json_type_boolean);
if (type == json_type_string)
return OFTStringList;
else if (type == json_type_double)
eType = OFTRealList;
else if (eType == OFTIntegerList &&
type == json_type_int)
{
GIntBig nVal = json_object_get_int64(poRow);
if( !CPL_INT64_FITS_ON_INT32(nVal) )
eType = OFTInteger64List;
}
else if (type != json_type_int &&
type != json_type_boolean)
return OFTString;
}
}
if( bOnlyBoolean )
eSubType = OFSTBoolean;
return eType;
}
else
return OFTString; /* null, object */
}
/************************************************************************/
/* GeoJSONStringPropertyToFieldType() */
/************************************************************************/
OGRFieldType GeoJSONStringPropertyToFieldType( json_object* poObject )
{
if (poObject == NULL) { return OFTString; }
const char* pszStr = json_object_get_string( poObject );
OGRField sWrkField;
CPLPushErrorHandler(CPLQuietErrorHandler);
const bool bSuccess = CPL_TO_BOOL(OGRParseDate( pszStr, &sWrkField, 0 ));
CPLPopErrorHandler();
CPLErrorReset();
if( bSuccess )
{
const bool bHasDate = strchr( pszStr, '/' ) != NULL ||
strchr( pszStr, '-' ) != NULL;
const bool bHasTime = strchr( pszStr, ':' ) != NULL;
if( bHasDate && bHasTime )
return OFTDateTime;
else if( bHasDate )
return OFTDate;
else
return OFTTime;
// TODO: What if both are false?
}
return OFTString;
}
/************************************************************************/
/* OGRGeoJSONGetGeometryName() */
/************************************************************************/
const char* OGRGeoJSONGetGeometryName( OGRGeometry const* poGeometry )
{
CPLAssert( NULL != poGeometry );
const OGRwkbGeometryType eType = poGeometry->getGeometryType();
if( wkbPoint == eType || wkbPoint25D == eType )
return "Point";
else if( wkbLineString == eType || wkbLineString25D == eType )
return "LineString";
else if( wkbPolygon == eType || wkbPolygon25D == eType )
return "Polygon";
else if( wkbMultiPoint == eType || wkbMultiPoint25D == eType )
return "MultiPoint";
else if( wkbMultiLineString == eType || wkbMultiLineString25D == eType )
return "MultiLineString";
else if( wkbMultiPolygon == eType || wkbMultiPolygon25D == eType )
return "MultiPolygon";
else if( wkbGeometryCollection == eType || wkbGeometryCollection25D == eType )
return "GeometryCollection";
return "Unknown";
}
|
#include "uml/impl/JoinNodeImpl.hpp"
#ifdef NDEBUG
#define DEBUG_MESSAGE(a) /**/
#else
#define DEBUG_MESSAGE(a) a
#endif
#ifdef ACTIVITY_DEBUG_ON
#define ACT_DEBUG(a) a
#else
#define ACT_DEBUG(a) /**/
#endif
//#include "util/ProfileCallCount.hpp"
#include <cassert>
#include <iostream>
#include <sstream>
#include "abstractDataTypes/Bag.hpp"
#include "abstractDataTypes/Subset.hpp"
#include "abstractDataTypes/SubsetUnion.hpp"
#include "abstractDataTypes/Union.hpp"
#include "abstractDataTypes/Any.hpp"
#include "abstractDataTypes/SubsetUnion.hpp"
#include "ecore/EAnnotation.hpp"
#include "ecore/EClass.hpp"
//Includes from codegen annotation
//Forward declaration includes
#include "persistence/interfaces/XLoadHandler.hpp" // used for Persistence
#include "persistence/interfaces/XSaveHandler.hpp" // used for Persistence
#include <exception> // used in Persistence
#include "uml/Activity.hpp"
#include "uml/ActivityEdge.hpp"
#include "uml/ActivityGroup.hpp"
#include "uml/ActivityNode.hpp"
#include "uml/ActivityPartition.hpp"
#include "uml/Classifier.hpp"
#include "uml/Comment.hpp"
#include "uml/ControlNode.hpp"
#include "uml/Dependency.hpp"
#include "uml/Element.hpp"
#include "uml/InterruptibleActivityRegion.hpp"
#include "uml/Namespace.hpp"
#include "uml/RedefinableElement.hpp"
#include "uml/StringExpression.hpp"
#include "uml/StructuredActivityNode.hpp"
#include "uml/ValueSpecification.hpp"
//Factories an Package includes
#include "uml/impl/umlFactoryImpl.hpp"
#include "uml/impl/umlPackageImpl.hpp"
#include "ecore/EAttribute.hpp"
#include "ecore/EStructuralFeature.hpp"
using namespace uml;
//*********************************
// Constructor / Destructor
//*********************************
JoinNodeImpl::JoinNodeImpl()
{
}
JoinNodeImpl::~JoinNodeImpl()
{
#ifdef SHOW_DELETION
std::cout << "-------------------------------------------------------------------------------------------------\r\ndelete JoinNode "<< this << "\r\n------------------------------------------------------------------------ " << std::endl;
#endif
}
//Additional constructor for the containments back reference
JoinNodeImpl::JoinNodeImpl(std::weak_ptr<uml::Activity > par_activity)
:JoinNodeImpl()
{
m_activity = par_activity;
m_owner = par_activity;
}
//Additional constructor for the containments back reference
JoinNodeImpl::JoinNodeImpl(std::weak_ptr<uml::StructuredActivityNode > par_inStructuredNode)
:JoinNodeImpl()
{
m_inStructuredNode = par_inStructuredNode;
m_owner = par_inStructuredNode;
}
//Additional constructor for the containments back reference
JoinNodeImpl::JoinNodeImpl(std::weak_ptr<uml::Namespace > par_namespace)
:JoinNodeImpl()
{
m_namespace = par_namespace;
m_owner = par_namespace;
}
//Additional constructor for the containments back reference
JoinNodeImpl::JoinNodeImpl(std::weak_ptr<uml::Element > par_owner)
:JoinNodeImpl()
{
m_owner = par_owner;
}
JoinNodeImpl::JoinNodeImpl(const JoinNodeImpl & obj):JoinNodeImpl()
{
//create copy of all Attributes
#ifdef SHOW_COPIES
std::cout << "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\r\ncopy JoinNode "<< this << "\r\n+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ " << std::endl;
#endif
m_isCombineDuplicate = obj.getIsCombineDuplicate();
m_isLeaf = obj.getIsLeaf();
m_name = obj.getName();
m_qualifiedName = obj.getQualifiedName();
m_visibility = obj.getVisibility();
//copy references with no containment (soft copy)
m_activity = obj.getActivity();
std::shared_ptr<Bag<uml::Dependency>> _clientDependency = obj.getClientDependency();
m_clientDependency.reset(new Bag<uml::Dependency>(*(obj.getClientDependency().get())));
std::shared_ptr<Union<uml::ActivityGroup>> _inGroup = obj.getInGroup();
m_inGroup.reset(new Union<uml::ActivityGroup>(*(obj.getInGroup().get())));
m_inStructuredNode = obj.getInStructuredNode();
std::shared_ptr<Bag<uml::ActivityEdge>> _incoming = obj.getIncoming();
m_incoming.reset(new Bag<uml::ActivityEdge>(*(obj.getIncoming().get())));
m_namespace = obj.getNamespace();
std::shared_ptr<Bag<uml::ActivityEdge>> _outgoing = obj.getOutgoing();
m_outgoing.reset(new Bag<uml::ActivityEdge>(*(obj.getOutgoing().get())));
m_owner = obj.getOwner();
std::shared_ptr<Union<uml::RedefinableElement>> _redefinedElement = obj.getRedefinedElement();
m_redefinedElement.reset(new Union<uml::RedefinableElement>(*(obj.getRedefinedElement().get())));
std::shared_ptr<Union<uml::Classifier>> _redefinitionContext = obj.getRedefinitionContext();
m_redefinitionContext.reset(new Union<uml::Classifier>(*(obj.getRedefinitionContext().get())));
//Clone references with containment (deep copy)
std::shared_ptr<Bag<uml::InterruptibleActivityRegion>> _inInterruptibleRegionList = obj.getInInterruptibleRegion();
for(std::shared_ptr<uml::InterruptibleActivityRegion> _inInterruptibleRegion : *_inInterruptibleRegionList)
{
this->getInInterruptibleRegion()->add(std::shared_ptr<uml::InterruptibleActivityRegion>(std::dynamic_pointer_cast<uml::InterruptibleActivityRegion>(_inInterruptibleRegion->copy())));
}
#ifdef SHOW_SUBSET_UNION
std::cout << "Copying the Subset: " << "m_inInterruptibleRegion" << std::endl;
#endif
std::shared_ptr<Bag<uml::ActivityPartition>> _inPartitionList = obj.getInPartition();
for(std::shared_ptr<uml::ActivityPartition> _inPartition : *_inPartitionList)
{
this->getInPartition()->add(std::shared_ptr<uml::ActivityPartition>(std::dynamic_pointer_cast<uml::ActivityPartition>(_inPartition->copy())));
}
#ifdef SHOW_SUBSET_UNION
std::cout << "Copying the Subset: " << "m_inPartition" << std::endl;
#endif
if(obj.getJoinSpec()!=nullptr)
{
m_joinSpec = std::dynamic_pointer_cast<uml::ValueSpecification>(obj.getJoinSpec()->copy());
}
#ifdef SHOW_SUBSET_UNION
std::cout << "Copying the Subset: " << "m_joinSpec" << std::endl;
#endif
if(obj.getNameExpression()!=nullptr)
{
m_nameExpression = std::dynamic_pointer_cast<uml::StringExpression>(obj.getNameExpression()->copy());
}
#ifdef SHOW_SUBSET_UNION
std::cout << "Copying the Subset: " << "m_nameExpression" << std::endl;
#endif
std::shared_ptr<Bag<uml::Comment>> _ownedCommentList = obj.getOwnedComment();
for(std::shared_ptr<uml::Comment> _ownedComment : *_ownedCommentList)
{
this->getOwnedComment()->add(std::shared_ptr<uml::Comment>(std::dynamic_pointer_cast<uml::Comment>(_ownedComment->copy())));
}
#ifdef SHOW_SUBSET_UNION
std::cout << "Copying the Subset: " << "m_ownedComment" << std::endl;
#endif
std::shared_ptr<Bag<uml::ActivityNode>> _redefinedNodeList = obj.getRedefinedNode();
for(std::shared_ptr<uml::ActivityNode> _redefinedNode : *_redefinedNodeList)
{
this->getRedefinedNode()->add(std::shared_ptr<uml::ActivityNode>(std::dynamic_pointer_cast<uml::ActivityNode>(_redefinedNode->copy())));
}
#ifdef SHOW_SUBSET_UNION
std::cout << "Copying the Subset: " << "m_redefinedNode" << std::endl;
#endif
}
std::shared_ptr<ecore::EObject> JoinNodeImpl::copy() const
{
std::shared_ptr<JoinNodeImpl> element(new JoinNodeImpl(*this));
element->setThisJoinNodePtr(element);
return element;
}
std::shared_ptr<ecore::EClass> JoinNodeImpl::eStaticClass() const
{
return uml::umlPackage::eInstance()->getJoinNode_Class();
}
//*********************************
// Attribute Setter Getter
//*********************************
/*
Getter & Setter for attribute isCombineDuplicate
*/
bool JoinNodeImpl::getIsCombineDuplicate() const
{
return m_isCombineDuplicate;
}
void JoinNodeImpl::setIsCombineDuplicate(bool _isCombineDuplicate)
{
m_isCombineDuplicate = _isCombineDuplicate;
}
//*********************************
// Operations
//*********************************
bool JoinNodeImpl::incoming_object_flow(Any diagnostics,std::map < Any, Any > context)
{
std::cout << __PRETTY_FUNCTION__ << std::endl;
throw "UnsupportedOperationException";
}
bool JoinNodeImpl::one_outgoing_edge(Any diagnostics,std::map < Any, Any > context)
{
std::cout << __PRETTY_FUNCTION__ << std::endl;
throw "UnsupportedOperationException";
}
//*********************************
// References
//*********************************
/*
Getter & Setter for reference joinSpec
*/
std::shared_ptr<uml::ValueSpecification > JoinNodeImpl::getJoinSpec() const
{
return m_joinSpec;
}
void JoinNodeImpl::setJoinSpec(std::shared_ptr<uml::ValueSpecification> _joinSpec)
{
m_joinSpec = _joinSpec;
}
//*********************************
// Union Getter
//*********************************
std::shared_ptr<Union<uml::ActivityGroup>> JoinNodeImpl::getInGroup() const
{
if(m_inGroup == nullptr)
{
/*Union*/
m_inGroup.reset(new Union<uml::ActivityGroup>());
#ifdef SHOW_SUBSET_UNION
std::cout << "Initialising Union: " << "m_inGroup - Union<uml::ActivityGroup>()" << std::endl;
#endif
}
return m_inGroup;
}
std::shared_ptr<Union<uml::Element>> JoinNodeImpl::getOwnedElement() const
{
if(m_ownedElement == nullptr)
{
/*Union*/
m_ownedElement.reset(new Union<uml::Element>());
#ifdef SHOW_SUBSET_UNION
std::cout << "Initialising Union: " << "m_ownedElement - Union<uml::Element>()" << std::endl;
#endif
}
return m_ownedElement;
}
std::weak_ptr<uml::Element > JoinNodeImpl::getOwner() const
{
return m_owner;
}
std::shared_ptr<Union<uml::RedefinableElement>> JoinNodeImpl::getRedefinedElement() const
{
if(m_redefinedElement == nullptr)
{
/*Union*/
m_redefinedElement.reset(new Union<uml::RedefinableElement>());
#ifdef SHOW_SUBSET_UNION
std::cout << "Initialising Union: " << "m_redefinedElement - Union<uml::RedefinableElement>()" << std::endl;
#endif
}
return m_redefinedElement;
}
std::shared_ptr<JoinNode> JoinNodeImpl::getThisJoinNodePtr() const
{
return m_thisJoinNodePtr.lock();
}
void JoinNodeImpl::setThisJoinNodePtr(std::weak_ptr<JoinNode> thisJoinNodePtr)
{
m_thisJoinNodePtr = thisJoinNodePtr;
setThisControlNodePtr(thisJoinNodePtr);
}
std::shared_ptr<ecore::EObject> JoinNodeImpl::eContainer() const
{
if(auto wp = m_activity.lock())
{
return wp;
}
if(auto wp = m_inStructuredNode.lock())
{
return wp;
}
if(auto wp = m_namespace.lock())
{
return wp;
}
if(auto wp = m_owner.lock())
{
return wp;
}
return nullptr;
}
//*********************************
// Structural Feature Getter/Setter
//*********************************
Any JoinNodeImpl::eGet(int featureID, bool resolve, bool coreType) const
{
switch(featureID)
{
case uml::umlPackage::JOINNODE_ATTRIBUTE_ISCOMBINEDUPLICATE:
return eAny(getIsCombineDuplicate()); //13120
case uml::umlPackage::JOINNODE_ATTRIBUTE_JOINSPEC:
return eAny(std::dynamic_pointer_cast<ecore::EObject>(getJoinSpec())); //13121
}
return ControlNodeImpl::eGet(featureID, resolve, coreType);
}
bool JoinNodeImpl::internalEIsSet(int featureID) const
{
switch(featureID)
{
case uml::umlPackage::JOINNODE_ATTRIBUTE_ISCOMBINEDUPLICATE:
return getIsCombineDuplicate() != true; //13120
case uml::umlPackage::JOINNODE_ATTRIBUTE_JOINSPEC:
return getJoinSpec() != nullptr; //13121
}
return ControlNodeImpl::internalEIsSet(featureID);
}
bool JoinNodeImpl::eSet(int featureID, Any newValue)
{
switch(featureID)
{
case uml::umlPackage::JOINNODE_ATTRIBUTE_ISCOMBINEDUPLICATE:
{
// BOOST CAST
bool _isCombineDuplicate = newValue->get<bool>();
setIsCombineDuplicate(_isCombineDuplicate); //13120
return true;
}
case uml::umlPackage::JOINNODE_ATTRIBUTE_JOINSPEC:
{
// BOOST CAST
std::shared_ptr<ecore::EObject> _temp = newValue->get<std::shared_ptr<ecore::EObject>>();
std::shared_ptr<uml::ValueSpecification> _joinSpec = std::dynamic_pointer_cast<uml::ValueSpecification>(_temp);
setJoinSpec(_joinSpec); //13121
return true;
}
}
return ControlNodeImpl::eSet(featureID, newValue);
}
//*********************************
// Persistence Functions
//*********************************
void JoinNodeImpl::load(std::shared_ptr<persistence::interfaces::XLoadHandler> loadHandler)
{
std::map<std::string, std::string> attr_list = loadHandler->getAttributeList();
loadAttributes(loadHandler, attr_list);
//
// Create new objects (from references (containment == true))
//
// get umlFactory
int numNodes = loadHandler->getNumOfChildNodes();
for(int ii = 0; ii < numNodes; ii++)
{
loadNode(loadHandler->getNextNodeName(), loadHandler);
}
}
void JoinNodeImpl::loadAttributes(std::shared_ptr<persistence::interfaces::XLoadHandler> loadHandler, std::map<std::string, std::string> attr_list)
{
try
{
std::map<std::string, std::string>::const_iterator iter;
iter = attr_list.find("isCombineDuplicate");
if ( iter != attr_list.end() )
{
// this attribute is a 'bool'
bool value;
std::istringstream(iter->second) >> std::boolalpha >> value;
this->setIsCombineDuplicate(value);
}
}
catch (std::exception& e)
{
std::cout << "| ERROR | " << e.what() << std::endl;
}
catch (...)
{
std::cout << "| ERROR | " << "Exception occurred" << std::endl;
}
ControlNodeImpl::loadAttributes(loadHandler, attr_list);
}
void JoinNodeImpl::loadNode(std::string nodeName, std::shared_ptr<persistence::interfaces::XLoadHandler> loadHandler)
{
std::shared_ptr<uml::umlFactory> modelFactory=uml::umlFactory::eInstance();
try
{
if ( nodeName.compare("joinSpec") == 0 )
{
std::string typeName = loadHandler->getCurrentXSITypeName();
if (typeName.empty())
{
std::cout << "| WARNING | type if an eClassifiers node it empty" << std::endl;
return; // no type name given and reference type is abstract
}
std::shared_ptr<uml::ValueSpecification> joinSpec = std::dynamic_pointer_cast<uml::ValueSpecification>(modelFactory->create(typeName));
if (joinSpec != nullptr)
{
this->setJoinSpec(joinSpec);
loadHandler->handleChild(joinSpec);
}
return;
}
}
catch (std::exception& e)
{
std::cout << "| ERROR | " << e.what() << std::endl;
}
catch (...)
{
std::cout << "| ERROR | " << "Exception occurred" << std::endl;
}
//load BasePackage Nodes
ControlNodeImpl::loadNode(nodeName, loadHandler);
}
void JoinNodeImpl::resolveReferences(const int featureID, std::list<std::shared_ptr<ecore::EObject> > references)
{
ControlNodeImpl::resolveReferences(featureID, references);
}
void JoinNodeImpl::save(std::shared_ptr<persistence::interfaces::XSaveHandler> saveHandler) const
{
saveContent(saveHandler);
ControlNodeImpl::saveContent(saveHandler);
ActivityNodeImpl::saveContent(saveHandler);
RedefinableElementImpl::saveContent(saveHandler);
NamedElementImpl::saveContent(saveHandler);
ElementImpl::saveContent(saveHandler);
ObjectImpl::saveContent(saveHandler);
ecore::EObjectImpl::saveContent(saveHandler);
}
void JoinNodeImpl::saveContent(std::shared_ptr<persistence::interfaces::XSaveHandler> saveHandler) const
{
try
{
std::shared_ptr<uml::umlPackage> package = uml::umlPackage::eInstance();
// Save 'joinSpec'
std::shared_ptr<uml::ValueSpecification > joinSpec = this->getJoinSpec();
if (joinSpec != nullptr)
{
saveHandler->addReference(joinSpec, "joinSpec", joinSpec->eClass() != package->getValueSpecification_Class());
}
// Add attributes
if ( this->eIsSet(package->getJoinNode_Attribute_isCombineDuplicate()) )
{
saveHandler->addAttribute("isCombineDuplicate", this->getIsCombineDuplicate());
}
}
catch (std::exception& e)
{
std::cout << "| ERROR | " << e.what() << std::endl;
}
}
|
/***************************************************
* Problem Name : CUTBOARD.cpp
* Problem Link : https://www.codechef.com/problems/CUTBOARD
* OJ : Codechef
* Verdict : AC
* Date : 2020-05-10
* Problem Type :
* Author Name : Saikat Sharma
* University : CSE, MBSTU
***************************************************/
#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <climits>
#include <cstring>
#include <string>
#include <sstream>
#include <vector>
#include <queue>
#include <list>
#include <unordered_map>
#include <unordered_set>
#include <cstdlib>
#include <deque>
#include <stack>
#include <bitset>
#include <cassert>
#include <map>
#include <set>
#include <cassert>
#include <iomanip>
#include <random>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
typedef long long ll;
typedef unsigned long long ull;
#define __FastIO ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0)
#define __FileRead freopen ("input.txt", "r", stdin)
#define __FileWrite freopen ("output.txt", "w", stdout)
#define SET(a,v) memset(a,v,sizeof(a))
#define SZ(v) (int)v.size()
#define pii pair<int,int>
#define pil pair <int, ll>
#define pli pair <ll, int>
#define pll pair <ll, ll>
#define debug cout <<"######\n"
#define debug1(x) cout <<"### " << x << " ###\n"
#define debug2(x,y) cout <<"# " << x <<" : "<< y <<" #\n"
#define nl cout << "\n";
#define sp cout << " ";
#define sl(n) scanf("%lld", &n)
#define sf(n) scanf("%lf", &n)
#define si(n) scanf("%d", &n)
#define ss(n) scanf("%s", n)
#define pf(n) scanf("%d", n)
#define pfl(n) scanf("%lld", n)
#define all(v) v.begin(), v.end()
#define rall(v) v.begin(), v.end()
#define srt(v) sort(v.begin(), v.end())
#define r_srt(v) sort(v.rbegin(), v.rend())
#define rev(v) reverse(v.rbegin(), v.rend())
#define Sqr(x) ((x)*(x))
#define Mod(x, m) ((((x) % (m)) + (m)) % (m))
#define max3(a, b, c) max(a, max(b, c))
#define min3(a, b, c) min(a, min(b, c))
#define pb push_back
#define mk make_pair
#define F first
#define S second
#define MAX 100005
#define INF 1000000009
#define MOD 1000000007
template<class T>
using min_heap = priority_queue<T, std::vector<T>, std::greater<T>>;
template<typename T>
using ordered_set = tree<T, null_type, less<T>, rb_tree_tag,
tree_order_statistics_node_update>;
template <typename T> string toString ( T Number ) {
stringstream ss;
ss << Number;
return ss.str();
}
template<typename T> int toInt (T str) {
stringstream ss;
ss << str;
int num;
ss >> num;
return num;
}
ll lcm ( ll a, ll b ) {
return ( a / __gcd ( a, b ) ) * b;
}
/************************************ Code Start Here ******************************************************/
int main () {
__FastIO;
//~ cout << setprecision (10) << fixed;
int tc;
cin >> tc;
while (tc--) {
int n, m;
cin >> n >> m;
cout << (n * m) - ( (m + n) - 1) << "\n";
}
return 0;
}
|
/* Code generated by IfcQuery EXPRESS generator, www.ifcquery.com */
#include <sstream>
#include <limits>
#include "ifcpp/model/AttributeObject.h"
#include "ifcpp/model/BuildingException.h"
#include "ifcpp/model/BuildingGuid.h"
#include "ifcpp/reader/ReaderUtil.h"
#include "ifcpp/writer/WriterUtil.h"
#include "ifcpp/IFC4/include/IfcElementAssemblyType.h"
#include "ifcpp/IFC4/include/IfcElementAssemblyTypeEnum.h"
#include "ifcpp/IFC4/include/IfcGloballyUniqueId.h"
#include "ifcpp/IFC4/include/IfcIdentifier.h"
#include "ifcpp/IFC4/include/IfcLabel.h"
#include "ifcpp/IFC4/include/IfcOwnerHistory.h"
#include "ifcpp/IFC4/include/IfcPropertySetDefinition.h"
#include "ifcpp/IFC4/include/IfcRelAggregates.h"
#include "ifcpp/IFC4/include/IfcRelAssigns.h"
#include "ifcpp/IFC4/include/IfcRelAssignsToProduct.h"
#include "ifcpp/IFC4/include/IfcRelAssociates.h"
#include "ifcpp/IFC4/include/IfcRelDeclares.h"
#include "ifcpp/IFC4/include/IfcRelDefinesByType.h"
#include "ifcpp/IFC4/include/IfcRelNests.h"
#include "ifcpp/IFC4/include/IfcRepresentationMap.h"
#include "ifcpp/IFC4/include/IfcText.h"
// ENTITY IfcElementAssemblyType
IfcElementAssemblyType::IfcElementAssemblyType() {}
IfcElementAssemblyType::IfcElementAssemblyType( int id ) { m_entity_id = id; }
IfcElementAssemblyType::~IfcElementAssemblyType() {}
shared_ptr<BuildingObject> IfcElementAssemblyType::getDeepCopy( BuildingCopyOptions& options )
{
shared_ptr<IfcElementAssemblyType> copy_self( new IfcElementAssemblyType() );
if( m_GlobalId )
{
if( options.create_new_IfcGloballyUniqueId ) { copy_self->m_GlobalId = shared_ptr<IfcGloballyUniqueId>(new IfcGloballyUniqueId( createGUID32_wstr().c_str() ) ); }
else { copy_self->m_GlobalId = dynamic_pointer_cast<IfcGloballyUniqueId>( m_GlobalId->getDeepCopy(options) ); }
}
if( m_OwnerHistory )
{
if( options.shallow_copy_IfcOwnerHistory ) { copy_self->m_OwnerHistory = m_OwnerHistory; }
else { copy_self->m_OwnerHistory = dynamic_pointer_cast<IfcOwnerHistory>( m_OwnerHistory->getDeepCopy(options) ); }
}
if( m_Name ) { copy_self->m_Name = dynamic_pointer_cast<IfcLabel>( m_Name->getDeepCopy(options) ); }
if( m_Description ) { copy_self->m_Description = dynamic_pointer_cast<IfcText>( m_Description->getDeepCopy(options) ); }
if( m_ApplicableOccurrence ) { copy_self->m_ApplicableOccurrence = dynamic_pointer_cast<IfcIdentifier>( m_ApplicableOccurrence->getDeepCopy(options) ); }
for( size_t ii=0; ii<m_HasPropertySets.size(); ++ii )
{
auto item_ii = m_HasPropertySets[ii];
if( item_ii )
{
copy_self->m_HasPropertySets.push_back( dynamic_pointer_cast<IfcPropertySetDefinition>(item_ii->getDeepCopy(options) ) );
}
}
for( size_t ii=0; ii<m_RepresentationMaps.size(); ++ii )
{
auto item_ii = m_RepresentationMaps[ii];
if( item_ii )
{
copy_self->m_RepresentationMaps.push_back( dynamic_pointer_cast<IfcRepresentationMap>(item_ii->getDeepCopy(options) ) );
}
}
if( m_Tag ) { copy_self->m_Tag = dynamic_pointer_cast<IfcLabel>( m_Tag->getDeepCopy(options) ); }
if( m_ElementType ) { copy_self->m_ElementType = dynamic_pointer_cast<IfcLabel>( m_ElementType->getDeepCopy(options) ); }
if( m_PredefinedType ) { copy_self->m_PredefinedType = dynamic_pointer_cast<IfcElementAssemblyTypeEnum>( m_PredefinedType->getDeepCopy(options) ); }
return copy_self;
}
void IfcElementAssemblyType::getStepLine( std::stringstream& stream ) const
{
stream << "#" << m_entity_id << "= IFCELEMENTASSEMBLYTYPE" << "(";
if( m_GlobalId ) { m_GlobalId->getStepParameter( stream ); } else { stream << "*"; }
stream << ",";
if( m_OwnerHistory ) { stream << "#" << m_OwnerHistory->m_entity_id; } else { stream << "*"; }
stream << ",";
if( m_Name ) { m_Name->getStepParameter( stream ); } else { stream << "*"; }
stream << ",";
if( m_Description ) { m_Description->getStepParameter( stream ); } else { stream << "*"; }
stream << ",";
if( m_ApplicableOccurrence ) { m_ApplicableOccurrence->getStepParameter( stream ); } else { stream << "*"; }
stream << ",";
writeEntityList( stream, m_HasPropertySets );
stream << ",";
writeEntityList( stream, m_RepresentationMaps );
stream << ",";
if( m_Tag ) { m_Tag->getStepParameter( stream ); } else { stream << "*"; }
stream << ",";
if( m_ElementType ) { m_ElementType->getStepParameter( stream ); } else { stream << "*"; }
stream << ",";
if( m_PredefinedType ) { m_PredefinedType->getStepParameter( stream ); } else { stream << "$"; }
stream << ");";
}
void IfcElementAssemblyType::getStepParameter( std::stringstream& stream, bool ) const { stream << "#" << m_entity_id; }
const std::wstring IfcElementAssemblyType::toString() const { return L"IfcElementAssemblyType"; }
void IfcElementAssemblyType::readStepArguments( const std::vector<std::wstring>& args, const std::map<int,shared_ptr<BuildingEntity> >& map )
{
const size_t num_args = args.size();
if( num_args != 10 ){ std::stringstream err; err << "Wrong parameter count for entity IfcElementAssemblyType, expecting 10, having " << num_args << ". Entity ID: " << m_entity_id << std::endl; throw BuildingException( err.str().c_str() ); }
m_GlobalId = IfcGloballyUniqueId::createObjectFromSTEP( args[0], map );
readEntityReference( args[1], m_OwnerHistory, map );
m_Name = IfcLabel::createObjectFromSTEP( args[2], map );
m_Description = IfcText::createObjectFromSTEP( args[3], map );
m_ApplicableOccurrence = IfcIdentifier::createObjectFromSTEP( args[4], map );
readEntityReferenceList( args[5], m_HasPropertySets, map );
readEntityReferenceList( args[6], m_RepresentationMaps, map );
m_Tag = IfcLabel::createObjectFromSTEP( args[7], map );
m_ElementType = IfcLabel::createObjectFromSTEP( args[8], map );
m_PredefinedType = IfcElementAssemblyTypeEnum::createObjectFromSTEP( args[9], map );
}
void IfcElementAssemblyType::getAttributes( std::vector<std::pair<std::string, shared_ptr<BuildingObject> > >& vec_attributes )
{
IfcElementType::getAttributes( vec_attributes );
vec_attributes.push_back( std::make_pair( "PredefinedType", m_PredefinedType ) );
}
void IfcElementAssemblyType::getAttributesInverse( std::vector<std::pair<std::string, shared_ptr<BuildingObject> > >& vec_attributes_inverse )
{
IfcElementType::getAttributesInverse( vec_attributes_inverse );
}
void IfcElementAssemblyType::setInverseCounterparts( shared_ptr<BuildingEntity> ptr_self_entity )
{
IfcElementType::setInverseCounterparts( ptr_self_entity );
}
void IfcElementAssemblyType::unlinkFromInverseCounterparts()
{
IfcElementType::unlinkFromInverseCounterparts();
}
|
// Copyright 2015-2020 Tier IV, 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.
#ifndef TRAFFIC_SIMULATOR__METRICS__REACTION_TIME_METRIC_HPP_
#define TRAFFIC_SIMULATOR__METRICS__REACTION_TIME_METRIC_HPP_
#include <string>
#include <traffic_simulator/metrics/metric_base.hpp>
namespace metrics
{
class ReactionTimeMetric : public MetricBase
{
public:
/**
* @brief Construct a new Reaction Time Metric object
* @param target_entity name of the target entity
* @param maximum_reaction_time maximum time
* @param jerk_upper_threshold If check_upper_threshold = true and the jerk of target entity overs this value, the metric becomes failure state.
* @param jerk_lower_threshold If check_lower_threshold = true the jerk of target entity go below this value, the metric becomes failure state.
* @param check_upper_threshold If true, check upper threshold of the jerk.
* @param check_lower_threshold If true, check lower threshold of the jerk.
*/
explicit ReactionTimeMetric(
std::string target_entity, double maximum_reaction_time, double jerk_upper_threshold,
double jerk_lower_threshold, bool check_upper_threshold = true,
bool check_lower_threshold = true);
~ReactionTimeMetric() override = default;
void update() override;
nlohmann::json toJson();
bool activateTrigger() override;
const std::string target_entity;
const double maximum_reaction_time;
const double jerk_upper_threshold;
const double jerk_lower_threshold;
const bool check_upper_threshold;
const bool check_lower_threshold;
private:
double elapsed_duration_;
double current_linear_jerk_;
};
} // namespace metrics
#endif // TRAFFIC_SIMULATOR__METRICS__REACTION_TIME_METRIC_HPP_
|
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include "StdAfx.h"
#include "SequenceAgentComponent.h"
#include <AzFramework/API/ApplicationAPI.h>
namespace Maestro
{
//=========================================================================
namespace ClassConverters
{
static bool UpgradeSequenceAgentComponent(AZ::SerializeContext&, AZ::SerializeContext::DataElementNode&);
} // namespace ClassConverters
/*static*/ void SequenceAgentComponent::Reflect(AZ::ReflectContext* context)
{
AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(context);
if (serializeContext)
{
serializeContext->Class<SequenceAgentComponent, Component>()
->Field("SequenceComponentEntityIds", &SequenceAgentComponent::m_sequenceEntityIds)
->Version(2, &ClassConverters::UpgradeSequenceAgentComponent)
;
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////
void SequenceAgentComponent::Init()
{
m_addressToBehaviorVirtualPropertiesMap.clear();
}
void SequenceAgentComponent::Activate()
{
// cache pointers and animatable addresses for animation
//
CacheAllVirtualPropertiesFromBehaviorContext(GetEntity());
ConnectAllSequences();
}
void SequenceAgentComponent::Deactivate()
{
// invalidate all cached pointers and addresses for animation
m_addressToBehaviorVirtualPropertiesMap.clear();
DisconnectAllSequences();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////
void SequenceAgentComponent::ConnectSequence(const AZ::EntityId& sequenceEntityId)
{
if (m_sequenceEntityIds.find(sequenceEntityId) != m_sequenceEntityIds.end())
{
m_sequenceEntityIds.insert(sequenceEntityId);
// connect to EBus between the given SequenceComponent and me
Maestro::SequenceAgentEventBusId busId(sequenceEntityId, GetEntityId());
SequenceAgentComponentRequestBus::MultiHandler::BusConnect(busId);
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////
void SequenceAgentComponent::DisconnectSequence()
{
const Maestro::SequenceAgentEventBusId *busIdToDisconnect = SequenceAgentComponentRequestBus::GetCurrentBusId();
if (busIdToDisconnect)
{
AZ::EntityId sequenceEntityId = busIdToDisconnect->first;
// we only process DisconnectSequence events sent over an ID'ed bus - otherwise we don't know which SequenceComponent to disconnect
auto findIter = m_sequenceEntityIds.find(sequenceEntityId);
AZ_Assert(findIter != m_sequenceEntityIds.end(), "A sequence not connected to SequenceAgentComponent on %s is requesting a disconnection", GetEntity()->GetName().c_str());
m_sequenceEntityIds.erase(sequenceEntityId);
// Disconnect from the bus between the SequenceComponent and me
SequenceAgentComponentRequestBus::MultiHandler::BusDisconnect(*busIdToDisconnect);
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////
void SequenceAgentComponent::ConnectAllSequences()
{
// Connect all buses
for (auto iter = m_sequenceEntityIds.begin(); iter != m_sequenceEntityIds.end(); iter++)
{
Maestro::SequenceAgentEventBusId busIdToConnect(*iter, GetEntityId());
SequenceAgentComponentRequestBus::MultiHandler::BusConnect(busIdToConnect);
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////
void SequenceAgentComponent::DisconnectAllSequences()
{
// disconnect all buses
for (auto iter = m_sequenceEntityIds.begin(); iter != m_sequenceEntityIds.end(); iter++)
{
Maestro::SequenceAgentEventBusId busIdToDisconnect(*iter, GetEntityId());
SequenceAgentComponentRequestBus::MultiHandler::BusDisconnect(busIdToDisconnect);
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////
void SequenceAgentComponent::GetAnimatedPropertyValue(AnimatedValue& returnValue, const Maestro::SequenceComponentRequests::AnimatablePropertyAddress& animatableAddress)
{
SequenceAgent::GetAnimatedPropertyValue(returnValue, GetEntityId(), animatableAddress);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////
bool SequenceAgentComponent::SetAnimatedPropertyValue(const Maestro::SequenceComponentRequests::AnimatablePropertyAddress& animatableAddress, const AnimatedValue& value)
{
return SequenceAgent::SetAnimatedPropertyValue(GetEntityId(), animatableAddress, value);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////
AZ::Uuid SequenceAgentComponent::GetAnimatedAddressTypeId(const AnimatablePropertyAddress& animatableAddress)
{
return GetVirtualPropertyTypeId(animatableAddress);
}
//=========================================================================
namespace ClassConverters
{
static bool UpgradeSequenceAgentComponent(AZ::SerializeContext& context, AZ::SerializeContext::DataElementNode& classElement)
{
if (classElement.GetVersion() == 1)
{
// upgrade V1 to V2 - change element named "SequenceEntityComponentPairIds" to "SequenceComponentEntityIds"
int oldSeqIdNameIdx = classElement.FindElement(AZ::Crc32("SequenceEntityComponentPairIds"));
if (oldSeqIdNameIdx == -1)
{
AZ_Error("Serialization", false, "Failed to find old SequenceEntityComponentPairIds element.");
return false;
}
auto seqIdNameElement = classElement.GetSubElement(oldSeqIdNameIdx);
seqIdNameElement.SetName("SequenceComponentEntityIds");
}
return true;
}
} // namespace ClassConverters
}// namespace Maestro
|
#include "MCP3426.h"
MCP3426::Config::Config() {
// Default configuration
mode = MODE_ONESHOT;
channel = CHANNEL1;
resolution = RESOLUTION_16BIT;
gain = GAIN_1X;
}
MCP3426::Config::Config(unsigned char channel, unsigned char mode,
unsigned char resolution, unsigned char gain) {
this->channel = channel;
this->mode = mode;
this->resolution = resolution;
this->gain = gain;
}
unsigned char MCP3426::Config::getByte() {
return channel | mode | resolution | gain | READY_BIT;
}
float MCP3426::Config::getMaxValue() {
int maxInt = 0;
if (resolution == RESOLUTION_12BIT) {
maxInt = 1 << 12;
} else if (resolution == RESOLUTION_14BIT) {
maxInt = 1 << 14;
} else if (resolution == RESOLUTION_16BIT) {
maxInt = 1 << 16;
}
return (2 * VREF) / maxInt;
}
float MCP3426::Config::getMinValue() {
int maxInt = 1;
if (resolution == RESOLUTION_12BIT) {
maxInt = 1 << 12;
} else if (resolution == RESOLUTION_14BIT) {
maxInt = 1 << 14;
} else if (resolution == RESOLUTION_16BIT) {
maxInt = 1 << 16;
}
return -((2 * VREF) / maxInt);
}
MCP3426::MCP3426() {
i2c = nullptr;
i2cConfig.address = 0x68;
i2cConfig.frequency = 400000;
valueUpdated = false;
}
MCP3426::MCP3426(I2C* i2c) {
this->i2c = i2c;
i2cConfig.address = 0x68;
i2cConfig.frequency = 400000;
valueUpdated = false;
}
void MCP3426::init() {
if (i2c != nullptr) {
i2c->init();
}
}
int MCP3426::channelIndex(int channel) { return channel >> 5; }
void MCP3426::configure(unsigned char channel, unsigned char mode,
unsigned char resolution, unsigned char gain) {
config[channelIndex(channel)] = Config(channel, mode, resolution, gain);
}
void MCP3426::configure(unsigned char channel, Config config) {
this->config[channelIndex(channel)] = config;
}
void MCP3426::startConversion(unsigned char channel) {
if (i2c == nullptr) {
return;
}
char cmd[] = {(char)config[channelIndex(channel)].getByte()};
i2c->send(i2cConfig, cmd, sizeof(cmd));
}
bool MCP3426::conversionFinished() {
unsigned char data[3];
if (!i2c->receive(i2cConfig, (char*)data, sizeof(data))) {
return false;
}
// The ready bit is cleared when data is ready
bool ready = !(data[2] & READY_BIT);
return ready;
}
float MCP3426::getValue(unsigned char channel) {
unsigned char data[2];
Config conf = config[channelIndex(channel)];
// Read the data registers
if (!i2c->receive(i2cConfig, (char*)data, sizeof(data))) {
return 0;
}
short value;
// Data is MSB first
value = data[0] << 8 | data[1];
float lsb = LSB_16BIT;
int gain = 1 << conf.gain;
// Preserve sign on values less than 16 bits
if (conf.resolution == RESOLUTION_14BIT) {
lsb = LSB_14BIT;
value <<= 2;
value >>= 2;
} else if (conf.resolution == RESOLUTION_12BIT) {
lsb = LSB_12BIT;
value <<= 4;
value >>= 4;
}
float result = value * (lsb / gain);
return result;
}
|
// Copyright (c) 2011-2013 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "walletframe.h"
#include "bitcoingui.h"
#include "walletview.h"
#include <cstdio>
#include <QHBoxLayout>
#include <QLabel>
WalletFrame::WalletFrame(BitcoinGUI* _gui) : QFrame(_gui),
gui(_gui)
{
// Leave HBox hook for adding a list view later
QHBoxLayout* walletFrameLayout = new QHBoxLayout(this);
setContentsMargins(0, 0, 0, 0);
walletStack = new QStackedWidget(this);
walletFrameLayout->setContentsMargins(0, 0, 0, 0);
walletFrameLayout->addWidget(walletStack);
QLabel* noWallet = new QLabel(tr("No wallet has been loaded."));
noWallet->setAlignment(Qt::AlignCenter);
walletStack->addWidget(noWallet);
}
WalletFrame::~WalletFrame()
{
}
void WalletFrame::setClientModel(ClientModel* clientModel)
{
this->clientModel = clientModel;
}
bool WalletFrame::addWallet(const QString& name, WalletModel* walletModel)
{
if (!gui || !clientModel || !walletModel || mapWalletViews.count(name) > 0)
return false;
WalletView* walletView = new WalletView(this);
walletView->setBitcoinGUI(gui);
walletView->setClientModel(clientModel);
walletView->setWalletModel(walletModel);
walletView->showOutOfSyncWarning(bOutOfSync);
/* TODO we should goto the currently selected page once dynamically adding wallets is supported */
walletView->gotoOverviewPage();
walletStack->addWidget(walletView);
mapWalletViews[name] = walletView;
// Ensure a walletView is able to show the main window
connect(walletView, SIGNAL(showNormalIfMinimized()), gui, SLOT(showNormalIfMinimized()));
return true;
}
bool WalletFrame::setCurrentWallet(const QString& name)
{
if (mapWalletViews.count(name) == 0)
return false;
WalletView* walletView = mapWalletViews.value(name);
walletStack->setCurrentWidget(walletView);
walletView->updateEncryptionStatus();
return true;
}
bool WalletFrame::removeWallet(const QString& name)
{
if (mapWalletViews.count(name) == 0)
return false;
WalletView* walletView = mapWalletViews.take(name);
walletStack->removeWidget(walletView);
return true;
}
void WalletFrame::removeAllWallets()
{
QMap<QString, WalletView*>::const_iterator i;
for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i)
walletStack->removeWidget(i.value());
mapWalletViews.clear();
}
bool WalletFrame::handlePaymentRequest(const SendCoinsRecipient& recipient)
{
WalletView* walletView = currentWalletView();
if (!walletView)
return false;
return walletView->handlePaymentRequest(recipient);
}
void WalletFrame::showOutOfSyncWarning(bool fShow)
{
bOutOfSync = fShow;
QMap<QString, WalletView*>::const_iterator i;
for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i)
i.value()->showOutOfSyncWarning(fShow);
}
void WalletFrame::gotoOverviewPage()
{
QMap<QString, WalletView*>::const_iterator i;
for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i)
i.value()->gotoOverviewPage();
}
void WalletFrame::gotoCreateContractPage()
{
QMap<QString, WalletView*>::const_iterator i;
for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i)
i.value()->gotoCreateContractPage();
}
void WalletFrame::gotoHistoryPage()
{
QMap<QString, WalletView*>::const_iterator i;
for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i)
i.value()->gotoHistoryPage();
}
void WalletFrame::gotoMasternodePage() // Masternode list
{
QMap<QString, WalletView*>::const_iterator i;
for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i)
i.value()->gotoMasternodePage();
}
void WalletFrame::gotoBlockExplorerPage()
{
QMap<QString, WalletView*>::const_iterator i;
for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i)
i.value()->gotoBlockExplorerPage();
}
void WalletFrame::gotoReceiveCoinsPage()
{
QMap<QString, WalletView*>::const_iterator i;
for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i)
i.value()->gotoReceiveCoinsPage();
}
void WalletFrame::gotoPrivacyPage()
{
QMap<QString, WalletView*>::const_iterator i;
for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i)
i.value()->gotoPrivacyPage();
}
void WalletFrame::gotoSendCoinsPage(QString addr)
{
QMap<QString, WalletView*>::const_iterator i;
for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i)
i.value()->gotoSendCoinsPage(addr);
}
void WalletFrame::gotoSignMessageTab(QString addr)
{
WalletView* walletView = currentWalletView();
if (walletView)
walletView->gotoSignMessageTab(addr);
}
void WalletFrame::gotoVerifyMessageTab(QString addr)
{
WalletView* walletView = currentWalletView();
if (walletView)
walletView->gotoVerifyMessageTab(addr);
}
void WalletFrame::gotoBip38Tool()
{
WalletView* walletView = currentWalletView();
if (walletView)
walletView->gotoBip38Tool();
}
void WalletFrame::gotoMultiSendDialog()
{
WalletView* walletView = currentWalletView();
if (walletView)
walletView->gotoMultiSendDialog();
}
void WalletFrame::gotoMultisigDialog(int index)
{
WalletView* walletView = currentWalletView();
if(walletView){
walletView->gotoMultisigDialog(index);
}
}
void WalletFrame::encryptWallet(bool status)
{
WalletView* walletView = currentWalletView();
if (walletView)
walletView->encryptWallet(status);
}
void WalletFrame::backupWallet()
{
WalletView* walletView = currentWalletView();
if (walletView)
walletView->backupWallet();
}
void WalletFrame::changePassphrase()
{
WalletView* walletView = currentWalletView();
if (walletView)
walletView->changePassphrase();
}
void WalletFrame::unlockWallet()
{
WalletView* walletView = currentWalletView();
if (walletView)
walletView->unlockWallet();
}
void WalletFrame::lockWallet()
{
WalletView* walletView = currentWalletView();
if (walletView)
walletView->lockWallet();
}
void WalletFrame::toggleLockWallet()
{
WalletView* walletView = currentWalletView();
if (walletView)
walletView->toggleLockWallet();
}
void WalletFrame::usedSendingAddresses()
{
WalletView* walletView = currentWalletView();
if (walletView)
walletView->usedSendingAddresses();
}
void WalletFrame::usedReceivingAddresses()
{
WalletView* walletView = currentWalletView();
if (walletView)
walletView->usedReceivingAddresses();
}
WalletView* WalletFrame::currentWalletView()
{
return qobject_cast<WalletView*>(walletStack->currentWidget());
}
|
#ifndef DIY_DECOMPOSITION_HPP
#define DIY_DECOMPOSITION_HPP
#include <vector>
#include <algorithm>
#include <iostream>
#include <cmath>
#include <sstream>
#include <stdexcept>
#include "link.hpp"
#include "assigner.hpp"
#include "master.hpp"
namespace diy
{
namespace detail
{
template<class Bounds_, class Enable = void>
struct BoundsHelper;
// discrete bounds
template<class Bounds>
struct BoundsHelper<Bounds, typename std::enable_if<std::is_integral<typename Bounds::Coordinate>::value>::type>
{
using Coordinate = typename Bounds::Coordinate;
static Coordinate from(int i, int n, Coordinate min, Coordinate max, bool) { return min + (max - min + 1)/n * i; }
static Coordinate to (int i, int n, Coordinate min, Coordinate max, bool shared_face)
{
if (i == n - 1)
return max;
else
return from(i+1, n, min, max, shared_face) - (shared_face ? 0 : 1);
}
static int lower(Coordinate x, int n, Coordinate min, Coordinate max, bool shared)
{
Coordinate width = (max - min + 1)/n;
Coordinate res = (x - min)/width;
if (res >= n) res = n - 1;
if (shared && x == from(res, n, min, max, shared))
--res;
return res;
}
static int upper(Coordinate x, int n, Coordinate min, Coordinate max, bool shared)
{
Coordinate width = (max - min + 1)/n;
Coordinate res = (x - min)/width + 1;
if (shared && x == from(res, n, min, max, shared))
++res;
return res;
}
};
// continuous bounds
template<class Bounds>
struct BoundsHelper<Bounds, typename std::enable_if<std::is_floating_point<typename Bounds::Coordinate>::value>::type>
{
using Coordinate = typename Bounds::Coordinate;
static Coordinate from(int i, int n, Coordinate min, Coordinate max, bool) { return min + (max - min)/n * i; }
static Coordinate to (int i, int n, Coordinate min, Coordinate max, bool) { return min + (max - min)/n * (i+1); }
static int lower(Coordinate x, int n, Coordinate min, Coordinate max, bool) { Coordinate width = (max - min)/n; Coordinate res = std::floor((x - min)/width); if (min + res*width == x) return (res - 1); else return res; }
static int upper(Coordinate x, int n, Coordinate min, Coordinate max, bool) { Coordinate width = (max - min)/n; Coordinate res = std::ceil ((x - min)/width); if (min + res*width == x) return (res + 1); else return res; }
};
}
//! \ingroup Decomposition
//! Decomposes a regular (discrete or continuous) domain into even blocks;
//! creates Links with Bounds along the way.
template<class Bounds_>
struct RegularDecomposer
{
using Bounds = Bounds_;
using Coordinate = typename BoundsValue<Bounds>::type;
using Link = RegularLink<Bounds>;
using Creator = std::function<void(int, Bounds, Bounds, Bounds, Link)>;
using Updater = std::function<void(int, int, Bounds, Bounds, Bounds, Link)>;
typedef std::vector<bool> BoolVector;
typedef std::vector<Coordinate> CoordinateVector;
typedef std::vector<int> DivisionsVector;
/// @param dim: dimensionality of the decomposition
/// @param domain: bounds of global domain
/// @param nblocks: total number of global blocks
/// @param share_face: indicates dimensions on which to share block faces
/// @param wrap: indicates dimensions on which to wrap the boundary
/// @param ghosts: indicates how many ghosts to use in each dimension
/// @param divisions: indicates how many cuts to make along each dimension
/// (0 means "no constraint," i.e., leave it up to the algorithm)
RegularDecomposer(int dim_,
const Bounds& domain_,
int nblocks_,
BoolVector share_face_ = BoolVector(),
BoolVector wrap_ = BoolVector(),
CoordinateVector ghosts_ = CoordinateVector(),
DivisionsVector divisions_ = DivisionsVector()):
dim(dim_), domain(domain_), nblocks(nblocks_),
share_face(share_face_),
wrap(wrap_), ghosts(ghosts_), divisions(divisions_)
{
if ((int) share_face.size() < dim) share_face.resize(dim);
if ((int) wrap.size() < dim) wrap.resize(dim);
if ((int) ghosts.size() < dim) ghosts.resize(dim);
if ((int) divisions.size() < dim) divisions.resize(dim);
fill_divisions(divisions);
}
// Calls create(int gid, const Bounds& bounds, const Link& link)
void decompose(int rank, const StaticAssigner& assigner, const Creator& create);
void decompose(int rank, const StaticAssigner& assigner, Master& master, const Updater& update);
void decompose(int rank, const StaticAssigner& assigner, Master& master);
// find lowest gid that owns a particular point
template<class Point>
int lowest_gid(const Point& p) const;
void gid_to_coords(int gid, DivisionsVector& coords) const { gid_to_coords(gid, coords, divisions); }
int coords_to_gid(const DivisionsVector& coords) const { return coords_to_gid(coords, divisions); }
void fill_divisions(std::vector<int>& divisions) const;
void fill_bounds(Bounds& bounds, const DivisionsVector& coords, bool add_ghosts = false) const;
void fill_bounds(Bounds& bounds, int gid, bool add_ghosts = false) const;
static bool all(const std::vector<int>& v, int x);
static void gid_to_coords(int gid, DivisionsVector& coords, const DivisionsVector& divisions);
static int coords_to_gid(const DivisionsVector& coords, const DivisionsVector& divisions);
static void factor(std::vector<unsigned>& factors, int n);
// Point to GIDs functions
template<class Point>
void point_to_gids(std::vector<int>& gids, const Point& p) const;
//! returns gid of a block that contains the point; ignores ghosts
template<class Point>
int point_to_gid(const Point& p) const;
template<class Point>
int num_gids(const Point& p) const;
template<class Point>
void top_bottom(int& top, int& bottom, const Point& p, int axis) const;
int dim;
Bounds domain;
int nblocks;
BoolVector share_face;
BoolVector wrap;
CoordinateVector ghosts;
DivisionsVector divisions;
};
/**
* \ingroup Decomposition
* \brief Decomposes the domain into a prescribed pattern of blocks.
*
* @param dim dimension of the domain
* @param rank local rank
* @param assigner decides how processors are assigned to blocks (maps a gid to a rank)
* also communicates the total number of blocks
* @param create the callback functor
* @param wrap indicates dimensions on which to wrap the boundary
* @param ghosts indicates how many ghosts to use in each dimension
* @param divs indicates how many cuts to make along each dimension
* (0 means "no constraint," i.e., leave it up to the algorithm)
*
* `create(...)` is called with each block assigned to the local domain. See [decomposition example](#decomposition-example).
*/
template<class Bounds>
void decompose(int dim,
int rank,
const Bounds& domain,
const StaticAssigner& assigner,
const typename RegularDecomposer<Bounds>::Creator& create,
typename RegularDecomposer<Bounds>::BoolVector share_face = typename RegularDecomposer<Bounds>::BoolVector(),
typename RegularDecomposer<Bounds>::BoolVector wrap = typename RegularDecomposer<Bounds>::BoolVector(),
typename RegularDecomposer<Bounds>::CoordinateVector ghosts = typename RegularDecomposer<Bounds>::CoordinateVector(),
typename RegularDecomposer<Bounds>::DivisionsVector divs = typename RegularDecomposer<Bounds>::DivisionsVector())
{
RegularDecomposer<Bounds>(dim, domain, assigner.nblocks(), share_face, wrap, ghosts, divs).decompose(rank, assigner, create);
}
/**
* \ingroup Decomposition
* \brief Decomposes the domain into a prescribed pattern of blocks.
*
* @param dim dimension of the domain
* @param rank local rank
* @param assigner decides how processors are assigned to blocks (maps a gid to a rank)
* also communicates the total number of blocks
* @param master gets the blocks once this function returns
* @param wrap indicates dimensions on which to wrap the boundary
* @param ghosts indicates how many ghosts to use in each dimension
* @param divs indicates how many cuts to make along each dimension
* (0 means "no constraint," i.e., leave it up to the algorithm)
*
* `master` must have been supplied a create function in order for this function to work.
*/
template<class Bounds>
void decompose(int dim,
int rank,
const Bounds& domain,
const StaticAssigner& assigner,
Master& master,
typename RegularDecomposer<Bounds>::BoolVector share_face = typename RegularDecomposer<Bounds>::BoolVector(),
typename RegularDecomposer<Bounds>::BoolVector wrap = typename RegularDecomposer<Bounds>::BoolVector(),
typename RegularDecomposer<Bounds>::CoordinateVector ghosts = typename RegularDecomposer<Bounds>::CoordinateVector(),
typename RegularDecomposer<Bounds>::DivisionsVector divs = typename RegularDecomposer<Bounds>::DivisionsVector())
{
RegularDecomposer<Bounds>(dim, domain, assigner.nblocks(), share_face, wrap, ghosts, divs).decompose(rank, assigner, master);
}
/**
* \ingroup Decomposition
* \brief A "null" decompositon that simply creates the blocks and adds them to the master
*
* @param rank local rank
* @param assigner decides how processors are assigned to blocks (maps a gid to a rank)
* also communicates the total number of blocks
* @param master gets the blocks once this function returns
*/
inline
void decompose(int rank,
const StaticAssigner& assigner,
Master& master)
{
std::vector<int> local_gids;
assigner.local_gids(rank, local_gids);
for (size_t i = 0; i < local_gids.size(); ++i)
master.add(local_gids[i], master.create(), new diy::Link);
}
/**
* \ingroup Decomposition
* \brief Add a decomposition (modify links) of an existing set of blocks that were
* added to the master previously
*
* @param rank local rank
* @param assigner decides how processors are assigned to blocks (maps a gid to a rank)
* also communicates the total number of blocks
*/
template<class Bounds>
void decompose(int dim,
int rank,
const Bounds& domain,
const StaticAssigner& assigner,
Master& master,
const typename RegularDecomposer<Bounds>::Updater& update,
typename RegularDecomposer<Bounds>::BoolVector share_face =
typename RegularDecomposer<Bounds>::BoolVector(),
typename RegularDecomposer<Bounds>::BoolVector wrap =
typename RegularDecomposer<Bounds>::BoolVector(),
typename RegularDecomposer<Bounds>::CoordinateVector ghosts =
typename RegularDecomposer<Bounds>::CoordinateVector(),
typename RegularDecomposer<Bounds>::DivisionsVector divs =
typename RegularDecomposer<Bounds>::DivisionsVector())
{
RegularDecomposer<Bounds>(dim, domain, assigner.nblocks(), share_face, wrap, ghosts, divs).
decompose(rank, assigner, master, update);
}
//! Decomposition example: \example decomposition/test-decomposition.cpp
//! Direct master insertion example: \example decomposition/test-direct-master.cpp
}
// decomposes domain and adds blocks to the master
template<class Bounds>
void
diy::RegularDecomposer<Bounds>::
decompose(int rank, const StaticAssigner& assigner, Master& master)
{
decompose(rank, assigner, [&master](int gid, const Bounds&, const Bounds&, const Bounds&, const Link& link)
{
void* b = master.create();
Link* l = new Link(link);
master.add(gid, b, l);
});
}
template<class Bounds>
void
diy::RegularDecomposer<Bounds>::
decompose(int rank, const StaticAssigner& assigner, const Creator& create)
{
std::vector<int> gids;
assigner.local_gids(rank, gids);
for (int i = 0; i < (int)gids.size(); ++i)
{
int gid = gids[i];
DivisionsVector coords;
gid_to_coords(gid, coords);
Bounds core(dim), bounds(dim);
fill_bounds(core, coords);
fill_bounds(bounds, coords, true);
// Fill link with all the neighbors
Link link(dim, core, bounds);
std::vector<int> offsets(dim, -1);
offsets[0] = -2;
while (!all(offsets, 1))
{
// next offset
int j;
for (j = 0; j < dim; ++j)
if (offsets[j] == 1)
offsets[j] = -1;
else
break;
++offsets[j];
if (all(offsets, 0)) continue; // skip ourselves
DivisionsVector nhbr_coords(dim);
Direction dir(dim,0), wrap_dir(dim,0);
bool inbounds = true;
for (int k = 0; k < dim; ++k)
{
nhbr_coords[k] = coords[k] + offsets[k];
// wrap
if (nhbr_coords[k] < 0)
{
if (wrap[k])
{
nhbr_coords[k] = divisions[k] - 1;
wrap_dir[k] = -1;
}
else
inbounds = false;
}
if (nhbr_coords[k] >= divisions[k])
{
if (wrap[k])
{
nhbr_coords[k] = 0;
wrap_dir[k] = 1;
}
else
inbounds = false;
}
// NB: this needs to match the addressing scheme in dir_t (in constants.h)
if (offsets[k] == -1 || offsets[k] == 1)
dir[k] = offsets[k];
}
if (!inbounds) continue;
int nhbr_gid = coords_to_gid(nhbr_coords);
BlockID bid; bid.gid = nhbr_gid; bid.proc = assigner.rank(nhbr_gid);
link.add_neighbor(bid);
Bounds nhbr_core(dim);
fill_bounds(nhbr_core, nhbr_coords);
link.add_core(nhbr_core);
Bounds nhbr_bounds(dim);
fill_bounds(nhbr_bounds, nhbr_coords, true);
link.add_bounds(nhbr_bounds);
link.add_direction(dir);
link.add_wrap(wrap_dir);
}
create(gid, core, bounds, domain, link);
}
}
// decomposes domain but does not add blocks to master, assumes they were added already
template<class Bounds>
void
diy::RegularDecomposer<Bounds>::
decompose(int rank, const StaticAssigner& assigner, Master& master, const Updater& update)
{
decompose(rank, assigner, [&master,&update](int gid, const Bounds& core, const Bounds& bounds, const Bounds& domain_, const Link& link)
{
int lid = master.lid(gid);
Link* l = new Link(link);
master.replace_link(lid, l);
update(gid, lid, core, bounds, domain_, *l);
});
}
template<class Bounds>
bool
diy::RegularDecomposer<Bounds>::
all(const std::vector<int>& v, int x)
{
for (unsigned i = 0; i < v.size(); ++i)
if (v[i] != x)
return false;
return true;
}
template<class Bounds>
void
diy::RegularDecomposer<Bounds>::
gid_to_coords(int gid, DivisionsVector& coords, const DivisionsVector& divisions)
{
int dim = static_cast<int>(divisions.size());
for (int i = 0; i < dim; ++i)
{
coords.push_back(gid % divisions[i]);
gid /= divisions[i];
}
}
template<class Bounds>
int
diy::RegularDecomposer<Bounds>::
coords_to_gid(const DivisionsVector& coords, const DivisionsVector& divisions)
{
int gid = 0;
for (int i = static_cast<int>(coords.size()) - 1; i >= 0; --i)
{
gid *= divisions[i];
gid += coords[i];
}
return gid;
}
//! \ingroup Decomposition
//! Gets the bounds, with or without ghosts, for a block specified by its block coordinates
template<class Bounds>
void
diy::RegularDecomposer<Bounds>::
fill_bounds(Bounds& bounds, //!< (output) bounds
const DivisionsVector& coords, //!< coordinates of the block in the decomposition
bool add_ghosts) //!< whether to include ghosts in the output bounds
const
{
for (int i = 0; i < dim; ++i)
{
bounds.min[i] = detail::BoundsHelper<Bounds>::from(coords[i], divisions[i], domain.min[i], domain.max[i], share_face[i]);
bounds.max[i] = detail::BoundsHelper<Bounds>::to (coords[i], divisions[i], domain.min[i], domain.max[i], share_face[i]);
}
if (!add_ghosts)
return;
for (int i = 0; i < dim; ++i)
{
if (wrap[i])
{
bounds.min[i] -= ghosts[i];
bounds.max[i] += ghosts[i];
} else
{
bounds.min[i] = std::max(domain.min[i], bounds.min[i] - ghosts[i]);
bounds.max[i] = std::min(domain.max[i], bounds.max[i] + ghosts[i]);
}
}
}
//! \ingroup Decomposition
//! Gets the bounds, with or without ghosts, for a block specified by its gid
template<class Bounds>
void
diy::RegularDecomposer<Bounds>::
fill_bounds(Bounds& bounds, //!< (output) bounds
int gid, //!< global id of the block
bool add_ghosts) //!< whether to include ghosts in the output bounds
const
{
DivisionsVector coords;
gid_to_coords(gid, coords);
if (add_ghosts)
fill_bounds(bounds, coords, true);
else
fill_bounds(bounds, coords);
}
namespace diy { namespace detail {
// current state of division in one dimension used in fill_divisions below
template<class Coordinate>
struct Div
{
int dim; // 0, 1, 2, etc. e.g. for x, y, z etc.
int nb; // number of blocks so far in this dimension
Coordinate b_size; // block size so far in this dimension
// sort on descending block size unless tied, in which case
// sort on ascending num blocks in current dim unless tied, in which case
// sort on ascending dimension
bool operator<(Div rhs) const
{
// sort on second value of the pair unless tied, in which case sort on first
if (b_size == rhs.b_size)
{
if (nb == rhs.nb)
return(dim < rhs.dim);
return(nb < rhs.nb);
}
return(b_size > rhs.b_size);
}
};
} }
template<class Bounds>
void
diy::RegularDecomposer<Bounds>::
fill_divisions(std::vector<int>& divisions_) const
{
// prod = number of blocks unconstrained by user; c = number of unconstrained dimensions
int prod = 1; int c = 0;
for (int i = 0; i < dim; ++i)
if (divisions_[i] != 0)
{
prod *= divisions_[i];
++c;
}
if (nblocks % prod != 0)
throw std::runtime_error("Total number of blocks cannot be factored into provided divs");
if (c == (int) divisions_.size()) // nothing to do; user provided all divs
return;
// factor number of blocks left in unconstrained dimensions
// factorization is sorted from smallest to largest factors
std::vector<unsigned> factors;
factor(factors, nblocks/prod);
using detail::Div;
std::vector< Div<Coordinate> > missing_divs; // pairs consisting of (dim, #divs)
// init missing_divs
for (int i = 0; i < dim; i++)
{
if (divisions_[i] == 0)
{
Div<Coordinate> div;
div.dim = i;
div.nb = 1;
div.b_size = domain.max[i] - domain.min[i];
missing_divs.push_back(div);
}
}
// iterate over factorization of number of blocks (factors are sorted smallest to largest)
// NB: using int instead of size_t because must be negative in order to break out of loop
for (int i = factors.size() - 1; i >= 0; --i)
{
// fill in missing divs by dividing dimension w/ largest block size
// except when this would be illegal (resulting in bounds.max < bounds.min;
// only a problem for discrete bounds
// sort on decreasing block size
std::sort(missing_divs.begin(), missing_divs.end());
// split the dimension with the largest block size (first element in vector)
Coordinate min =
detail::BoundsHelper<Bounds>::from(0,
missing_divs[0].nb * factors[i],
domain.min[missing_divs[0].dim],
domain.max[missing_divs[0].dim],
share_face[missing_divs[0].dim]);
Coordinate max =
detail::BoundsHelper<Bounds>::to(0,
missing_divs[0].nb * factors[i],
domain.min[missing_divs[0].dim],
domain.max[missing_divs[0].dim],
share_face[missing_divs[0].dim]);
if (max >= min)
{
missing_divs[0].nb *= factors[i];
missing_divs[0].b_size = max - min;
}
else
{
std::ostringstream oss;
oss << "Unable to decompose domain into " << nblocks << " blocks: " << min << " " << max;
throw std::runtime_error(oss.str());
}
}
// assign the divisions
for (size_t i = 0; i < missing_divs.size(); i++)
divisions_[missing_divs[i].dim] = missing_divs[i].nb;
}
template<class Bounds>
void
diy::RegularDecomposer<Bounds>::
factor(std::vector<unsigned>& factors, int n)
{
while (n != 1)
for (int i = 2; i <= n; ++i)
{
if (n % i == 0)
{
factors.push_back(i);
n /= i;
break;
}
}
}
// Point to GIDs
// TODO: deal with wrap correctly
// TODO: add an optional ghosts argument to ignore ghosts (if we want to find the true owners, or something like that)
template<class Bounds>
template<class Point>
void
diy::RegularDecomposer<Bounds>::
point_to_gids(std::vector<int>& gids, const Point& p) const
{
std::vector< std::pair<int, int> > ranges(dim);
for (int i = 0; i < dim; ++i)
top_bottom(ranges[i].second, ranges[i].first, p, i);
// look up gids for all combinations
DivisionsVector coords(dim), location(dim);
while(location.back() < ranges.back().second - ranges.back().first)
{
for (int i = 0; i < dim; ++i)
coords[i] = ranges[i].first + location[i];
gids.push_back(coords_to_gid(coords, divisions));
location[0]++;
unsigned i = 0;
while (i < dim-1 && location[i] == ranges[i].second - ranges[i].first)
{
location[i] = 0;
++i;
location[i]++;
}
}
}
template<class Bounds>
template<class Point>
int
diy::RegularDecomposer<Bounds>::
point_to_gid(const Point& p) const
{
int gid = 0;
for (int axis = dim - 1; axis >= 0; --axis)
{
int bottom = detail::BoundsHelper<Bounds>::lower(p[axis], divisions[axis], domain.min[axis], domain.max[axis], share_face[axis]);
bottom = std::max(0, bottom);
// coupled with coords_to_gid
gid *= divisions[axis];
gid += bottom;
}
return gid;
}
template<class Bounds>
template<class Point>
int
diy::RegularDecomposer<Bounds>::
num_gids(const Point& p) const
{
int res = 1;
for (int i = 0; i < dim; ++i)
{
int top, bottom;
top_bottom(top, bottom, p, i);
res *= top - bottom;
}
return res;
}
template<class Bounds>
template<class Point>
void
diy::RegularDecomposer<Bounds>::
top_bottom(int& top, int& bottom, const Point& p, int axis) const
{
Coordinate l = p[axis] - ghosts[axis];
Coordinate r = p[axis] + ghosts[axis];
top = detail::BoundsHelper<Bounds>::upper(r, divisions[axis], domain.min[axis], domain.max[axis], share_face[axis]);
bottom = detail::BoundsHelper<Bounds>::lower(l, divisions[axis], domain.min[axis], domain.max[axis], share_face[axis]);
if (!wrap[axis])
{
bottom = std::max(0, bottom);
top = std::min(divisions[axis], top);
}
}
// find lowest gid that owns a particular point
template<class Bounds>
template<class Point>
int
diy::RegularDecomposer<Bounds>::
lowest_gid(const Point& p) const
{
// TODO: optimize - no need to compute all gids
std::vector<int> gids;
point_to_gids(gids, p);
std::sort(gids.begin(), gids.end());
return gids[0];
}
#endif
|
/*
* Nimrod/G Agent
* https://github.com/UQ-RCC/nimrodg-agent
*
* SPDX-License-Identifier: Apache-2.0
* Copyright (c) 2019 The University of Queensland
*
* 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.
*/
#ifndef _NIM1_HPP
#define _NIM1_HPP
#include "nim1fwd.hpp"
#include "crypto_exception.hpp"
#include "evpbuf.hpp"
#include "hmacbuf.hpp"
#include "strbuf.hpp"
#include "auth_header.hpp"
#include "make_view.hpp"
#include "time.hpp"
#include "lc.hpp"
namespace nimrod::nim1 {
void init();
}
#endif /* _NIM1_HPP */
|
// 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 "gpu/command_buffer/service/shader_translator.h"
#include <string.h>
#include <GLES2/gl2.h>
#include <algorithm>
#include "base/at_exit.h"
#include "base/debug/trace_event.h"
#include "base/lazy_instance.h"
#include "base/logging.h"
#include "base/strings/string_number_conversions.h"
namespace gpu {
namespace gles2 {
namespace {
class ShaderTranslatorInitializer {
public:
ShaderTranslatorInitializer() {
TRACE_EVENT0("gpu", "ShInitialize");
CHECK(ShInitialize());
}
~ShaderTranslatorInitializer() {
TRACE_EVENT0("gpu", "ShFinalize");
ShFinalize();
}
};
base::LazyInstance<ShaderTranslatorInitializer> g_translator_initializer =
LAZY_INSTANCE_INITIALIZER;
void GetAttributes(ShHandle compiler, AttributeMap* var_map) {
if (!var_map)
return;
var_map->clear();
const std::vector<sh::Attribute>* attribs = ShGetAttributes(compiler);
if (attribs) {
for (size_t ii = 0; ii < attribs->size(); ++ii)
(*var_map)[(*attribs)[ii].mappedName] = (*attribs)[ii];
}
}
void GetUniforms(ShHandle compiler, UniformMap* var_map) {
if (!var_map)
return;
var_map->clear();
const std::vector<sh::Uniform>* uniforms = ShGetUniforms(compiler);
if (uniforms) {
for (size_t ii = 0; ii < uniforms->size(); ++ii)
(*var_map)[(*uniforms)[ii].mappedName] = (*uniforms)[ii];
}
}
void GetVaryings(ShHandle compiler, VaryingMap* var_map) {
if (!var_map)
return;
var_map->clear();
const std::vector<sh::Varying>* varyings = ShGetVaryings(compiler);
if (varyings) {
for (size_t ii = 0; ii < varyings->size(); ++ii)
(*var_map)[(*varyings)[ii].mappedName] = (*varyings)[ii];
}
}
void GetNameHashingInfo(ShHandle compiler, NameMap* name_map) {
if (!name_map)
return;
name_map->clear();
typedef std::map<std::string, std::string> NameMapANGLE;
const NameMapANGLE* angle_map = ShGetNameHashingMap(compiler);
DCHECK(angle_map);
for (NameMapANGLE::const_iterator iter = angle_map->begin();
iter != angle_map->end(); ++iter) {
// Note that in ANGLE, the map is (original_name, hash);
// here, we want (hash, original_name).
(*name_map)[iter->second] = iter->first;
}
}
} // namespace
ShaderTranslator::DestructionObserver::DestructionObserver() {
}
ShaderTranslator::DestructionObserver::~DestructionObserver() {
}
ShaderTranslator::ShaderTranslator()
: compiler_(NULL),
implementation_is_glsl_es_(false),
driver_bug_workarounds_(static_cast<ShCompileOptions>(0)) {
}
bool ShaderTranslator::Init(
GLenum shader_type,
ShShaderSpec shader_spec,
const ShBuiltInResources* resources,
ShaderTranslatorInterface::GlslImplementationType glsl_implementation_type,
ShCompileOptions driver_bug_workarounds) {
// Make sure Init is called only once.
DCHECK(compiler_ == NULL);
DCHECK(shader_type == GL_FRAGMENT_SHADER || shader_type == GL_VERTEX_SHADER);
DCHECK(shader_spec == SH_GLES2_SPEC || shader_spec == SH_WEBGL_SPEC);
DCHECK(resources != NULL);
g_translator_initializer.Get();
ShShaderOutput shader_output =
(glsl_implementation_type == kGlslES ? SH_ESSL_OUTPUT : SH_GLSL_OUTPUT);
{
TRACE_EVENT0("gpu", "ShConstructCompiler");
compiler_ = ShConstructCompiler(
shader_type, shader_spec, shader_output, resources);
}
compiler_options_ = *resources;
implementation_is_glsl_es_ = (glsl_implementation_type == kGlslES);
driver_bug_workarounds_ = driver_bug_workarounds;
return compiler_ != NULL;
}
int ShaderTranslator::GetCompileOptions() const {
int compile_options =
SH_OBJECT_CODE | SH_VARIABLES | SH_ENFORCE_PACKING_RESTRICTIONS |
SH_LIMIT_EXPRESSION_COMPLEXITY | SH_LIMIT_CALL_STACK_DEPTH |
SH_CLAMP_INDIRECT_ARRAY_BOUNDS;
compile_options |= driver_bug_workarounds_;
return compile_options;
}
bool ShaderTranslator::Translate(const std::string& shader_source,
std::string* info_log,
std::string* translated_source,
AttributeMap* attrib_map,
UniformMap* uniform_map,
VaryingMap* varying_map,
NameMap* name_map) const {
// Make sure this instance is initialized.
DCHECK(compiler_ != NULL);
bool success = false;
{
TRACE_EVENT0("gpu", "ShCompile");
const char* const shader_strings[] = { shader_source.c_str() };
success = ShCompile(
compiler_, shader_strings, 1, GetCompileOptions());
}
if (success) {
// Get translated shader.
if (translated_source) {
*translated_source = ShGetObjectCode(compiler_);
}
// Get info for attribs, uniforms, and varyings.
GetAttributes(compiler_, attrib_map);
GetUniforms(compiler_, uniform_map);
GetVaryings(compiler_, varying_map);
// Get info for name hashing.
GetNameHashingInfo(compiler_, name_map);
}
// Get info log.
if (info_log) {
*info_log = ShGetInfoLog(compiler_);
}
return success;
}
std::string ShaderTranslator::GetStringForOptionsThatWouldAffectCompilation()
const {
DCHECK(compiler_ != NULL);
return std::string(":CompileOptions:" +
base::IntToString(GetCompileOptions())) +
ShGetBuiltInResourcesString(compiler_);
}
void ShaderTranslator::AddDestructionObserver(
DestructionObserver* observer) {
destruction_observers_.AddObserver(observer);
}
void ShaderTranslator::RemoveDestructionObserver(
DestructionObserver* observer) {
destruction_observers_.RemoveObserver(observer);
}
ShaderTranslator::~ShaderTranslator() {
FOR_EACH_OBSERVER(DestructionObserver,
destruction_observers_,
OnDestruct(this));
if (compiler_ != NULL)
ShDestruct(compiler_);
}
} // namespace gles2
} // namespace gpu
|
#ifndef VK_RENDERDEVICE_HPP
#define VK_RENDERDEVICE_HPP
#include <cstddef>
#include <cstdint>
#include <deque>
#include <unordered_map>
#include <unordered_map>
#include <vector>
#include <shared_mutex>
#include <vulkan/vulkan.hpp>
#include "Core/Profiling.hpp"
#include "Core/RenderDevice.hpp"
#include "Core/BarrierManager.hpp"
#include "MemoryManager.hpp"
#include "DescriptorManager.hpp"
#include "CommandPool.h"
#include "VulkanImageView.hpp"
#include "Core/Sampler.hpp"
#include "VulkanShaderResourceSet.hpp"
#include "VulkanPipeline.hpp"
#include "VulkanBuffer.hpp"
#include "VulkanImage.hpp"
#include "VulkanSwapChain.hpp"
#include "VulkanRenderInstance.hpp"
#include "VulkanAccelerationStructures.hpp"
#include "RenderGraph/GraphicsTask.hpp"
#include "RenderGraph/ComputeTask.hpp"
#include "RenderGraph/RenderGraph.hpp"
// Debug option for finding which task is causing a device loss.
#define SUBMISSION_PER_TASK 0
struct GLFWwindow;
class RenderDevice;
class Pipeline;
struct vulkanResources
{
#if ENABLE_LOGGING
std::string mDebugName;
#endif
std::shared_ptr<PipelineTemplate> mPipelineTemplate;
std::vector<vk::DescriptorSetLayout> mDescSetLayout;
// Only needed for graphics tasks
std::optional<vk::RenderPass> mRenderPass;
std::optional<vk::VertexInputBindingDescription> mVertexBindingDescription;
std::optional<std::vector<vk::VertexInputAttributeDescription>> mVertexAttributeDescription;
};
struct GraphicsPipelineHandles
{
std::shared_ptr<PipelineTemplate> mGraphicsPipelineTemplate;
vk::RenderPass mRenderPass;
std::vector< vk::DescriptorSetLayout> mDescriptorSetLayout;
};
struct ComputePipelineHandles
{
std::shared_ptr<PipelineTemplate> mComputePipelineTemplate;
std::vector< vk::DescriptorSetLayout> mDescriptorSetLayout;
};
class VulkanRenderDevice : public RenderDevice
{
public:
VulkanRenderDevice(vk::Instance,
vk::PhysicalDevice,
vk::Device,
vk::SurfaceKHR,
vk::DynamicLoader&,
GLFWwindow*,
const uint32_t deviceFeatures,
const bool vsync);
~VulkanRenderDevice();
virtual CommandContextBase* getCommandContext(const uint32_t index, const QueueType) override;
virtual PipelineHandle compileGraphicsPipeline(const GraphicsTask& task,
const RenderGraph& graph,
const int vertexAttributes,
const Shader& vertexShader,
const Shader* geometryShader,
const Shader* tessControl,
const Shader* tessEval,
const Shader& fragmentShader) override;
virtual PipelineHandle compileComputePipeline(const ComputeTask& task,
const RenderGraph& graph,
const Shader& computeShader) override;
virtual void startFrame() override;
virtual void endFrame() override;
virtual void destroyImage(ImageBase& image) override
{
VulkanImage& vkImg = static_cast<VulkanImage&>(image);
mImagesPendingDestruction.push_back({image.getLastAccessed(), vkImg.getImage(), vkImg.getMemory()});
}
virtual void destroyImageView(ImageViewBase& view) override
{
VulkanImageView& vkView = static_cast<VulkanImageView&>(view);
mImageViewsPendingDestruction.push_back({view.getLastAccessed(), vkView.getImageView(), vkView.getCubeMapImageView()});
}
vk::ImageView createImageView(const vk::ImageViewCreateInfo& info)
{ return mDevice.createImageView(info); }
void destroyImageView(vk::ImageView& view)
{ mDevice.destroyImageView(view); }
vk::Buffer createBuffer(const uint32_t, const vk::BufferUsageFlags);
virtual void destroyBuffer(BufferBase& buffer) override
{
VulkanBuffer& vkBuffer = static_cast<VulkanBuffer&>(buffer);
mBuffersPendingDestruction.push_back({buffer.getLastAccessed(), vkBuffer.getBuffer(), vkBuffer.getMemory()});
}
virtual void destroyShaderResourceSet(const ShaderResourceSetBase& set) override
{
const VulkanShaderResourceSet& VkSRS = static_cast<const VulkanShaderResourceSet&>(set);
mSRSPendingDestruction.push_back({ set.getLastAccessed(), VkSRS.getPool(), VkSRS.getLayout(), VkSRS.getDescriptorSet() });
}
vk::AccelerationStructureKHR createAccelerationStructure(const vk::AccelerationStructureCreateInfoKHR& info) const
{
return mDevice.createAccelerationStructureKHR(info);
}
virtual void destroyBottomLevelAccelerationStructure(BottomLevelAccelerationStructureBase& structure) override
{
VulkanBottomLevelAccelerationStructure& VKAccel = static_cast<VulkanBottomLevelAccelerationStructure&>(structure);
mAccelerationStructuresPendingDestruction.push_back({getCurrentSubmissionIndex(), VKAccel.getAccelerationStructureHandle()});
}
virtual void destroyTopLevelAccelerationStructure(TopLevelAccelerationStructureBase& structure) override
{
VulkanTopLevelAccelerationStructure& VKAccel = static_cast<VulkanTopLevelAccelerationStructure&>(structure);
mAccelerationStructuresPendingDestruction.push_back({structure.getLastAccessed(), VKAccel.getAccelerationStructureHandle()});
}
void buildAccelerationStructure(const uint32_t count,
const vk::AccelerationStructureBuildGeometryInfoKHR* pInfos,
const vk::AccelerationStructureBuildRangeInfoKHR* const* ppBuildRangeInfos) const
{
vk::Result result = mDevice.buildAccelerationStructuresKHR(vk::DeferredOperationKHR(), count,
pInfos, ppBuildRangeInfos);
BELL_ASSERT(result == vk::Result::eSuccess, "Failed to build acceleration structure")
}
void destroyFrameBuffer(vk::Framebuffer& frameBuffer, uint64_t frameIndex)
{ mFramebuffersPendingDestruction.push_back({frameIndex, frameBuffer}); }
void destroyPipeline(const vk::Pipeline pipeline)
{ mDevice.destroyPipeline(pipeline); }
virtual size_t getMinStorageBufferAlignment() const override
{
return getLimits().minStorageBufferOffsetAlignment;
}
virtual bool getHasCommandPredicationSupport() const override
{
return mHasConditionalRenderingSupport;
}
virtual bool getHasAsyncComputeSupport() const override
{
return mGraphicsQueue != mComputeQueue;
}
virtual const std::vector<uint64_t>& getAvailableTimestamps() const override
{
return mFinishedTimeStamps;
}
vk::Image createImage(const vk::ImageCreateInfo& info)
{
return mDevice.createImage(info);
}
vk::Framebuffer createFrameBuffer(const RenderGraph &graph, const uint32_t taskIndex, const vk::RenderPass renderPass);
vk::CommandPool createCommandPool(const vk::CommandPoolCreateInfo& info)
{ return mDevice.createCommandPool(info); }
vk::CommandBuffer getPrefixCommandBuffer(); // Returns the first command buffer that will be submitted this frame.
void destroyCommandPool(vk::CommandPool& pool)
{ mDevice.destroyCommandPool(pool); }
std::vector<vk::CommandBuffer> allocateCommandBuffers(const vk::CommandBufferAllocateInfo& info)
{ return mDevice.allocateCommandBuffers(info); }
void resetCommandPool(vk::CommandPool& pool)
{ mDevice.resetCommandPool(pool, vk::CommandPoolResetFlags{}); }
void resetDescriptorPool(vk::DescriptorPool& pool)
{ mDevice.resetDescriptorPool(pool); }
vk::ShaderModule createShaderModule(const vk::ShaderModuleCreateInfo& info)
{ return mDevice.createShaderModule(info); }
void destroyShaderModule(vk::ShaderModule module)
{ mDevice.destroyShaderModule(module); }
vk::DescriptorPool createDescriptorPool(const vk::DescriptorPoolCreateInfo& info)
{ return mDevice.createDescriptorPool(info); }
void destroyDescriptorPool(vk::DescriptorPool& pool)
{ mDevice.destroyDescriptorPool(pool); }
std::vector<vk::DescriptorSet> allocateDescriptorSet(const vk::DescriptorSetAllocateInfo& info)
{ return mDevice.allocateDescriptorSets(info); }
void writeDescriptorSets(std::vector<vk::WriteDescriptorSet>& writes)
{ mDevice.updateDescriptorSets(writes, {}); }
vk::Semaphore createSemaphore(const vk::SemaphoreCreateInfo& info)
{ return mDevice.createSemaphore(info); }
void destroySemaphore(const vk::Semaphore semaphore)
{ mDevice.destroySemaphore(semaphore); }
vk::Sampler createSampler(const vk::SamplerCreateInfo& info)
{ return mDevice.createSampler(info); }
vk::DeviceAddress getBufferDeviceAddress(const BufferBase* base) const
{
const VulkanBuffer* vkBuffer = static_cast<const VulkanBuffer*>(base);
vk::Buffer bufferHandle = vkBuffer->getBuffer();
vk::BufferDeviceAddressInfoKHR info{};
info.buffer = bufferHandle;
return mDevice.getBufferAddress(info);
}
vk::SwapchainKHR createSwapchain(const vk::SwapchainCreateInfoKHR& info)
{ return mDevice.createSwapchainKHR(info); }
void destroySwapchain(vk::SwapchainKHR& swap)
{ mDevice.destroySwapchainKHR(swap); }
std::vector<vk::Image> getSwapchainImages(vk::SwapchainKHR& swap)
{ return mDevice.getSwapchainImagesKHR(swap); }
void aquireNextSwapchainImage(vk::SwapchainKHR& swap,
uint64_t timout,
vk::Semaphore semaphore,
uint32_t& imageIndex)
{
vk::Result result = mDevice.acquireNextImageKHR(swap, timout, semaphore, nullptr, &imageIndex);
BELL_ASSERT(result == vk::Result::eSuccess, "Add error handling here TODO")
}
vk::Pipeline createPipeline(const vk::ComputePipelineCreateInfo& info)
{
vk::ResultValue<vk::Pipeline> result = mDevice.createComputePipeline(nullptr, info);
BELL_ASSERT(result.result == vk::Result::eSuccess, "Failed to create compute pipeline");
return result.value;
}
vk::Pipeline createPipeline(const vk::GraphicsPipelineCreateInfo& info)
{
vk::ResultValue<vk::Pipeline> result = mDevice.createGraphicsPipeline(nullptr, info);
BELL_ASSERT(result.result == vk::Result::eSuccess, "Failed to create graphics pipeline");
return result.value;
}
GraphicsPipelineHandles createPipelineHandles(const GraphicsTask&, const RenderGraph&);
ComputePipelineHandles createPipelineHandles(const ComputeTask&, const RenderGraph&);
// Accessors
MemoryManager* getMemoryManager() { return &mMemoryManager; }
vk::PhysicalDevice* getPhysicalDevice() { return &mPhysicalDevice; }
DescriptorManager* getDescriptorManager() { return &mPermanentDescriptorManager; }
// Only these two can do usefull work when const
const vk::PhysicalDevice* getPhysicalDevice() const { return &mPhysicalDevice; }
vk::Sampler getImmutableSampler(const Sampler& sampler);
virtual void setDebugName(const std::string&, const uint64_t, const uint64_t) override;
// Memory management functions
vk::MemoryRequirements getMemoryRequirements(vk::Image image)
{ return mDevice.getImageMemoryRequirements(image); }
vk::MemoryRequirements getMemoryRequirements(vk::Buffer buffer)
{ return mDevice.getBufferMemoryRequirements(buffer); }
vk::Queue& getQueue(const QueueType);
uint32_t getQueueFamilyIndex(const QueueType) const;
vk::PhysicalDeviceMemoryProperties getMemoryProperties() const;
vk::DeviceMemory allocateMemory(vk::MemoryAllocateInfo);
void freeMemory(const vk::DeviceMemory);
void* mapMemory(vk::DeviceMemory, vk::DeviceSize, vk::DeviceSize);
void unmapMemory(vk::DeviceMemory);
void flushMemoryRange(const vk::MappedMemoryRange& range)
{ mDevice.flushMappedMemoryRanges(1, &range); }
void bindBufferMemory(vk::Buffer&, vk::DeviceMemory, const uint64_t);
void bindImageMemory(vk::Image&, vk::DeviceMemory, const uint64_t);
virtual void flushWait() const override { mGraphicsQueue.waitIdle(); mDevice.waitIdle(); }
virtual void invalidatePipelines() override;
virtual void submitContext(CommandContextBase*, const bool finalSubmission = false) override;
virtual void swap() override;
vk::PhysicalDeviceLimits getLimits() const { return mLimits; }
vk::Semaphore getAsyncQueueSemaphore() const
{
return mAsyncQueueSemaphores[mCurrentFrameIndex];
}
template<typename B>
vk::DescriptorSetLayout generateDescriptorSetLayoutBindings(const std::vector<B>&, const TaskType type);
vulkanResources getTaskResources(const RenderGraph&, const RenderTask& task, const uint64_t prefixHash);
vulkanResources getTaskResources(const RenderGraph&, const uint32_t taskIndex, const uint64_t prefixHash);
vk::QueryPool createTimeStampPool(const uint32_t queries)
{
vk::QueryPoolCreateInfo info{};
info.setFlags(vk::QueryPoolCreateFlags{});
info.setQueryType(vk::QueryType::eTimestamp);
info.setQueryCount(queries);
info.setPipelineStatistics(vk::QueryPipelineStatisticFlags{});
return mDevice.createQueryPool(info);
}
void destroyTimeStampPool(vk::QueryPool pool)
{
mDevice.destroyQueryPool(pool);
}
void writeTimeStampResults(const vk::QueryPool pool, uint64_t* data, const size_t queryCount)
{
if(queryCount == 0)
return;
mDevice.getQueryPoolResults(pool, 0, queryCount, sizeof(uint64_t) * queryCount, data, sizeof(uint64_t), vk::QueryResultFlagBits::e64);
}
float getTimeStampPeriod() const override
{
return mLimits.timestampPeriod;
}
vk::AccelerationStructureBuildSizesInfoKHR getAccelerationStructureMemoryRequirements(const vk::AccelerationStructureBuildTypeKHR type,
const vk::AccelerationStructureBuildGeometryInfoKHR& geoemtryInfo,
const std::vector<uint32_t>& maxPrimitives) const
{
return mDevice.getAccelerationStructureBuildSizesKHR(type, geoemtryInfo, maxPrimitives);
}
vk::Instance getParentInstance() const
{
return mInstance;
}
private:
vk::DescriptorSetLayout generateDescriptorSetLayout(const RenderTask&);
vk::PipelineLayout generatePipelineLayout(const std::vector< vk::DescriptorSetLayout>&, const RenderTask&);
vk::RenderPass generateRenderPass(const GraphicsTask&);
vulkanResources generateVulkanResources(const RenderGraph &, const RenderTask& task);
vulkanResources generateVulkanResources(const RenderGraph &, const uint32_t taskIndex);
std::vector<vk::DescriptorSetLayout> generateShaderResourceSetLayouts(const RenderTask&, const RenderGraph&);
void clearDeferredResources();
void frameSyncSetup();
vk::Fence createFence(const bool signaled);
void destroyImage(const vk::Image& image)
{ mDevice.destroyImage(image); }
void destroyBuffer(const vk::Buffer& buffer )
{ mDevice.destroyBuffer(buffer); }
#ifndef NDEBUG
public:
void insertDebugEventSignal(vk::CommandBuffer& buffer)
{ buffer.setEvent(mDebugEvent, vk::PipelineStageFlagBits::eAllCommands); }
void waitOnDebugEvent()
{
while(mDevice.getEventStatus(mDebugEvent) != vk::Result::eEventSet) {}
mDevice.resetEvent(mDebugEvent);
}
private:
#endif
std::deque<std::pair<uint64_t, vk::Framebuffer>> mFramebuffersPendingDestruction;
struct ImageDestructionInfo
{
uint64_t mLastUsed;
vk::Image mImageHandle;
Allocation mImageMemory;
};
std::deque<ImageDestructionInfo> mImagesPendingDestruction;
struct ImageViewDestructionInfo
{
uint64_t mLastUsed;
vk::ImageView mView;
vk::ImageView mCubeMapView;
};
std::deque<ImageViewDestructionInfo> mImageViewsPendingDestruction;
struct BufferDestructionInfo
{
uint64_t mLastUsed;
vk::Buffer mBufferHandle;
Allocation mBufferMemory;
};
std::deque<BufferDestructionInfo> mBuffersPendingDestruction;
struct ShaderResourceSetsInfo
{
uint64_t mLastUsed;
vk::DescriptorPool mPool;
vk::DescriptorSetLayout mLayout;
vk::DescriptorSet mDescSet;
};
std::deque<ShaderResourceSetsInfo> mSRSPendingDestruction;
struct AccelerationStructureDestructionInfo
{
uint64_t mLastused;
vk::AccelerationStructureKHR mAccelerationStructure;
};
std::deque<AccelerationStructureDestructionInfo> mAccelerationStructuresPendingDestruction;
std::shared_mutex mResourcesLock;
std::unordered_map<uint64_t, vulkanResources> mVulkanResources;
std::map<std::vector<vk::ImageView>, vk::Framebuffer> mFrameBufferCache;
// underlying devices
vk::Device mDevice;
vk::PhysicalDevice mPhysicalDevice;
#if PROFILE // Just copies of the vkhpp handles for interfacing with optik
VkDevice mProfileDeviceHandle;
VkPhysicalDevice mProfilePhysicalDeviceHandle;
VkQueue mProfileGraphicsQueue;
Optick::VulkanFunctions mProfilingVulkanFunctions;
void initProfilerVulkanFunctions(vk::DynamicLoader&);
#endif
vk::Instance mInstance;
vk::Queue mGraphicsQueue;
vk::Queue mComputeQueue;
vk::Queue mTransferQueue;
QueueIndicies mQueueFamilyIndicies;
std::vector<vk::Fence> mFrameFinished;
#ifndef NDEBUG
vk::Event mDebugEvent;
#endif
vk::PhysicalDeviceLimits mLimits;
bool mHasConditionalRenderingSupport;
std::unordered_map<Sampler, vk::Sampler> mImmutableSamplerCache;
struct SwapChainInitializer
{
SwapChainInitializer(RenderDevice* device, vk::SurfaceKHR windowSurface, GLFWwindow* window, const bool vsync, SwapChainBase** ptr)
{
*ptr = new VulkanSwapChain(device, windowSurface, window, vsync);
}
} mSwapChainInitializer;
MemoryManager mMemoryManager;
DescriptorManager mPermanentDescriptorManager;
std::vector<std::vector<CommandContextBase*>> mGraphicsCommandContexts;
std::vector<std::vector<CommandContextBase*>> mAsyncComputeCommandContexts;
uint32_t mSubmissionCount;
std::vector<vk::Semaphore> mAsyncQueueSemaphores;
std::vector<uint64_t> mFinishedTimeStamps;
};
#endif
|
// Copyright Contributors to the OpenVDB Project
// SPDX-License-Identifier: MPL-2.0
#include "Archive.h"
#include "GridDescriptor.h"
#include "DelayedLoadMetadata.h"
#include "io.h"
#include <openvdb/Exceptions.h>
#include <openvdb/Metadata.h>
#include <openvdb/tree/LeafManager.h>
#include <openvdb/util/logging.h>
#include <openvdb/openvdb.h>
// Boost.Interprocess uses a header-only portion of Boost.DateTime
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-macros"
#endif
#define BOOST_DATE_TIME_NO_LIB
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#include <boost/interprocess/file_mapping.hpp>
#include <boost/interprocess/mapped_region.hpp>
#include <boost/iostreams/device/array.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <atomic>
#ifdef _MSC_VER
#include <boost/interprocess/detail/os_file_functions.hpp> // open_existing_file(), close_file()
extern "C" __declspec(dllimport) bool __stdcall GetFileTime(
void* fh, void* ctime, void* atime, void* mtime);
// boost::interprocess::detail was renamed to boost::interprocess::ipcdetail in Boost 1.48.
// Ensure that both namespaces exist.
namespace boost { namespace interprocess { namespace detail {} namespace ipcdetail {} } }
#else
#include <sys/types.h> // for struct stat
#include <sys/stat.h> // for stat()
#include <unistd.h> // for unlink()
#endif
#include <algorithm> // for std::find_if()
#include <cerrno> // for errno
#include <cstdlib> // for getenv()
#include <cstring> // for std::memcpy()
#include <ctime> // for std::time()
#include <iostream>
#include <map>
#include <random>
#include <set>
#include <sstream>
#include <system_error> // for std::error_code()
namespace openvdb {
OPENVDB_USE_VERSION_NAMESPACE
namespace OPENVDB_VERSION_NAME {
namespace io {
#ifdef OPENVDB_USE_BLOSC
const uint32_t Archive::DEFAULT_COMPRESSION_FLAGS = (COMPRESS_BLOSC | COMPRESS_ACTIVE_MASK);
#else
#ifdef OPENVDB_USE_ZLIB
const uint32_t Archive::DEFAULT_COMPRESSION_FLAGS = (COMPRESS_ZIP | COMPRESS_ACTIVE_MASK);
#else
const uint32_t Archive::DEFAULT_COMPRESSION_FLAGS = (COMPRESS_ACTIVE_MASK);
#endif
#endif
namespace {
// Indices into a stream's internal extensible array of values used by readers and writers
struct StreamState
{
static const long MAGIC_NUMBER;
StreamState();
~StreamState();
// Important: The size and order of these member variables must *only* change when
// OpenVDB ABI changes to avoid potential segfaults when performing I/O
// across two different versions of the library. Adding new member
// variables to the end of the struct is allowed provided that they
// are only accessed from within an appropriate ABI guard.
int magicNumber;
int fileVersion;
int libraryMajorVersion;
int libraryMinorVersion;
int dataCompression;
int writeGridStatsMetadata;
int gridBackground;
int gridClass;
int halfFloat;
int mappedFile;
int metadata;
}
sStreamState;
const long StreamState::MAGIC_NUMBER =
long((uint64_t(OPENVDB_MAGIC) << 32) | (uint64_t(OPENVDB_MAGIC)));
////////////////////////////////////////
StreamState::StreamState(): magicNumber(std::ios_base::xalloc())
{
// Having reserved an entry (the one at index magicNumber) in the extensible array
// associated with every stream, store a magic number at that location in the
// array belonging to the cout stream.
std::cout.iword(magicNumber) = MAGIC_NUMBER;
std::cout.pword(magicNumber) = this;
// Search for a lower-numbered entry in cout's array that already contains the magic number.
/// @todo This assumes that the indices returned by xalloc() increase monotonically.
int existingArray = -1;
for (int i = 0; i < magicNumber; ++i) {
if (std::cout.iword(i) == MAGIC_NUMBER) {
existingArray = i;
break;
}
}
if (existingArray >= 0 && std::cout.pword(existingArray) != nullptr) {
// If a lower-numbered entry was found to contain the magic number,
// a coexisting version of this library must have registered it.
// In that case, the corresponding pointer should point to an existing
// StreamState struct. Copy the other array indices from that StreamState
// into this one, so as to share state with the other library.
const StreamState& other =
*static_cast<const StreamState*>(std::cout.pword(existingArray));
fileVersion = other.fileVersion;
libraryMajorVersion = other.libraryMajorVersion;
libraryMinorVersion = other.libraryMinorVersion;
dataCompression = other.dataCompression;
writeGridStatsMetadata = other.writeGridStatsMetadata;
gridBackground = other.gridBackground;
gridClass = other.gridClass;
if (other.mappedFile != 0) { // memory-mapped file support was added in OpenVDB 3.0.0
mappedFile = other.mappedFile;
metadata = other.metadata;
halfFloat = other.halfFloat;
} else {
mappedFile = std::ios_base::xalloc();
metadata = std::ios_base::xalloc();
halfFloat = std::ios_base::xalloc();
}
} else {
// Reserve storage for per-stream file format and library version numbers
// and other values of use to readers and writers. Each of the following
// values is an index into the extensible arrays associated with all streams.
// The indices are common to all streams, but the values stored at those indices
// are unique to each stream.
fileVersion = std::ios_base::xalloc();
libraryMajorVersion = std::ios_base::xalloc();
libraryMinorVersion = std::ios_base::xalloc();
dataCompression = std::ios_base::xalloc();
writeGridStatsMetadata = std::ios_base::xalloc();
gridBackground = std::ios_base::xalloc();
gridClass = std::ios_base::xalloc();
mappedFile = std::ios_base::xalloc();
metadata = std::ios_base::xalloc();
halfFloat = std::ios_base::xalloc();
}
}
StreamState::~StreamState()
{
// Ensure that this StreamState struct can no longer be accessed.
std::cout.iword(magicNumber) = 0;
std::cout.pword(magicNumber) = nullptr;
}
} // unnamed namespace
////////////////////////////////////////
struct StreamMetadata::Impl
{
// Important: The size and order of these member variables must *only* change when
// OpenVDB ABI changes to avoid potential segfaults when performing I/O
// across two different versions of the library. Adding new member
// variables to the end of the struct is allowed provided that they
// are only accessed from within an appropriate ABI guard.
uint32_t mFileVersion = OPENVDB_FILE_VERSION;
VersionId mLibraryVersion = { OPENVDB_LIBRARY_MAJOR_VERSION, OPENVDB_LIBRARY_MINOR_VERSION };
uint32_t mCompression = COMPRESS_NONE;
uint32_t mGridClass = GRID_UNKNOWN;
const void* mBackgroundPtr = nullptr; ///< @todo use Metadata::Ptr?
bool mHalfFloat = false;
bool mWriteGridStats = false;
bool mSeekable = false;
bool mCountingPasses = false;
uint32_t mPass = 0;
MetaMap mGridMetadata;
AuxDataMap mAuxData;
bool mDelayedLoadMeta = DelayedLoadMetadata::isRegisteredType();
uint64_t mLeaf = 0;
uint32_t mTest = 0; // for testing only
}; // struct StreamMetadata
StreamMetadata::StreamMetadata(): mImpl(new Impl)
{
}
StreamMetadata::StreamMetadata(const StreamMetadata& other): mImpl(new Impl(*other.mImpl))
{
}
StreamMetadata::StreamMetadata(std::ios_base& strm): mImpl(new Impl)
{
mImpl->mFileVersion = getFormatVersion(strm);
mImpl->mLibraryVersion = getLibraryVersion(strm);
mImpl->mCompression = getDataCompression(strm);
mImpl->mGridClass = getGridClass(strm);
mImpl->mHalfFloat = getHalfFloat(strm);
mImpl->mWriteGridStats = getWriteGridStatsMetadata(strm);
}
StreamMetadata::~StreamMetadata()
{
}
StreamMetadata&
StreamMetadata::operator=(const StreamMetadata& other)
{
if (&other != this) {
mImpl.reset(new Impl(*other.mImpl));
}
return *this;
}
void
StreamMetadata::transferTo(std::ios_base& strm) const
{
io::setVersion(strm, mImpl->mLibraryVersion, mImpl->mFileVersion);
io::setDataCompression(strm, mImpl->mCompression);
io::setGridBackgroundValuePtr(strm, mImpl->mBackgroundPtr);
io::setGridClass(strm, mImpl->mGridClass);
io::setHalfFloat(strm, mImpl->mHalfFloat);
io::setWriteGridStatsMetadata(strm, mImpl->mWriteGridStats);
}
uint32_t StreamMetadata::fileVersion() const { return mImpl->mFileVersion; }
VersionId StreamMetadata::libraryVersion() const { return mImpl->mLibraryVersion; }
uint32_t StreamMetadata::compression() const { return mImpl->mCompression; }
uint32_t StreamMetadata::gridClass() const { return mImpl->mGridClass; }
const void* StreamMetadata::backgroundPtr() const { return mImpl->mBackgroundPtr; }
bool StreamMetadata::halfFloat() const { return mImpl->mHalfFloat; }
bool StreamMetadata::writeGridStats() const { return mImpl->mWriteGridStats; }
bool StreamMetadata::seekable() const { return mImpl->mSeekable; }
bool StreamMetadata::delayedLoadMeta() const { return mImpl->mDelayedLoadMeta; }
bool StreamMetadata::countingPasses() const { return mImpl->mCountingPasses; }
uint32_t StreamMetadata::pass() const { return mImpl->mPass; }
uint64_t StreamMetadata::leaf() const { return mImpl->mLeaf; }
MetaMap& StreamMetadata::gridMetadata() { return mImpl->mGridMetadata; }
const MetaMap& StreamMetadata::gridMetadata() const { return mImpl->mGridMetadata; }
uint32_t StreamMetadata::__test() const { return mImpl->mTest; }
StreamMetadata::AuxDataMap& StreamMetadata::auxData() { return mImpl->mAuxData; }
const StreamMetadata::AuxDataMap& StreamMetadata::auxData() const { return mImpl->mAuxData; }
void StreamMetadata::setFileVersion(uint32_t v) { mImpl->mFileVersion = v; }
void StreamMetadata::setLibraryVersion(VersionId v) { mImpl->mLibraryVersion = v; }
void StreamMetadata::setCompression(uint32_t c) { mImpl->mCompression = c; }
void StreamMetadata::setGridClass(uint32_t c) { mImpl->mGridClass = c; }
void StreamMetadata::setBackgroundPtr(const void* ptr) { mImpl->mBackgroundPtr = ptr; }
void StreamMetadata::setHalfFloat(bool b) { mImpl->mHalfFloat = b; }
void StreamMetadata::setWriteGridStats(bool b) { mImpl->mWriteGridStats = b; }
void StreamMetadata::setSeekable(bool b) { mImpl->mSeekable = b; }
void StreamMetadata::setCountingPasses(bool b) { mImpl->mCountingPasses = b; }
void StreamMetadata::setPass(uint32_t i) { mImpl->mPass = i; }
void StreamMetadata::setLeaf(uint64_t i) { mImpl->mLeaf = i; }
void StreamMetadata::__setTest(uint32_t t) { mImpl->mTest = t; }
std::string
StreamMetadata::str() const
{
std::ostringstream ostr;
ostr << std::boolalpha;
ostr << "version: " << libraryVersion().first << "." << libraryVersion().second
<< "/" << fileVersion() << "\n";
ostr << "class: " << GridBase::gridClassToString(static_cast<GridClass>(gridClass())) << "\n";
ostr << "compression: " << compressionToString(compression()) << "\n";
ostr << "half_float: " << halfFloat() << "\n";
ostr << "seekable: " << seekable() << "\n";
ostr << "delayed_load_meta: " << delayedLoadMeta() << "\n";
ostr << "pass: " << pass() << "\n";
ostr << "counting_passes: " << countingPasses() << "\n";
ostr << "write_grid_stats_metadata: " << writeGridStats() << "\n";
if (!auxData().empty()) ostr << auxData();
if (gridMetadata().metaCount() != 0) {
ostr << "grid_metadata:\n" << gridMetadata().str(/*indent=*/" ");
}
return ostr.str();
}
std::ostream&
operator<<(std::ostream& os, const StreamMetadata& meta)
{
os << meta.str();
return os;
}
namespace {
template<typename T>
inline bool
writeAsType(std::ostream& os, const boost::any& val)
{
if (val.type() == typeid(T)) {
os << boost::any_cast<T>(val);
return true;
}
return false;
}
struct PopulateDelayedLoadMetadataOp
{
DelayedLoadMetadata& metadata;
uint32_t compression;
PopulateDelayedLoadMetadataOp(DelayedLoadMetadata& _metadata, uint32_t _compression)
: metadata(_metadata)
, compression(_compression) { }
template<typename GridT>
void operator()(const GridT& grid) const
{
using TreeT = typename GridT::TreeType;
using ValueT = typename TreeT::ValueType;
using LeafT = typename TreeT::LeafNodeType;
using MaskT = typename LeafT::NodeMaskType;
const TreeT& tree = grid.constTree();
const Index32 leafCount = tree.leafCount();
// early exit if not leaf nodes
if (leafCount == Index32(0)) return;
metadata.resizeMask(leafCount);
if (compression & (COMPRESS_BLOSC | COMPRESS_ZIP)) {
metadata.resizeCompressedSize(leafCount);
}
const auto background = tree.background();
const bool saveFloatAsHalf = grid.saveFloatAsHalf();
tree::LeafManager<const TreeT> leafManager(tree);
leafManager.foreach(
[&](const LeafT& leaf, size_t idx) {
// set mask value
MaskCompress<ValueT, MaskT> maskCompressData(
leaf.valueMask(), /*childMask=*/MaskT(), leaf.buffer().data(), background);
metadata.setMask(idx, maskCompressData.metadata);
if (compression & (COMPRESS_BLOSC | COMPRESS_ZIP)) {
// set compressed size value
size_t sizeBytes(8);
size_t compressedSize = io::writeCompressedValuesSize(
leaf.buffer().data(), LeafT::SIZE,
leaf.valueMask(), maskCompressData.metadata, saveFloatAsHalf, compression);
metadata.setCompressedSize(idx, compressedSize+sizeBytes);
}
}
);
}
};
bool populateDelayedLoadMetadata(DelayedLoadMetadata& metadata,
const GridBase& gridBase, uint32_t compression)
{
PopulateDelayedLoadMetadataOp op(metadata, compression);
using AllowedTypes = TypeList<
Int32Grid, Int64Grid,
FloatGrid, DoubleGrid,
Vec3IGrid, Vec3SGrid, Vec3DGrid>;
return gridBase.apply<AllowedTypes>(op);
}
} // unnamed namespace
std::ostream&
operator<<(std::ostream& os, const StreamMetadata::AuxDataMap& auxData)
{
for (StreamMetadata::AuxDataMap::const_iterator it = auxData.begin(), end = auxData.end();
it != end; ++it)
{
os << it->first << ": ";
// Note: boost::any doesn't support serialization.
const boost::any& val = it->second;
if (!writeAsType<int32_t>(os, val)
&& !writeAsType<int64_t>(os, val)
&& !writeAsType<int16_t>(os, val)
&& !writeAsType<int8_t>(os, val)
&& !writeAsType<uint32_t>(os, val)
&& !writeAsType<uint64_t>(os, val)
&& !writeAsType<uint16_t>(os, val)
&& !writeAsType<uint8_t>(os, val)
&& !writeAsType<float>(os, val)
&& !writeAsType<double>(os, val)
&& !writeAsType<long double>(os, val)
&& !writeAsType<bool>(os, val)
&& !writeAsType<std::string>(os, val)
&& !writeAsType<const char*>(os, val))
{
os << val.type().name() << "(...)";
}
os << "\n";
}
return os;
}
////////////////////////////////////////
// Memory-mapping a VDB file permits threaded input (and output, potentially,
// though that might not be practical for compressed files or files containing
// multiple grids). In particular, a memory-mapped file can be loaded lazily,
// meaning that the voxel buffers of the leaf nodes of a grid's tree are not allocated
// until they are actually accessed. When access to its buffer is requested,
// a leaf node allocates memory for the buffer and then streams in (and decompresses)
// its contents from the memory map, starting from a stream offset that was recorded
// at the time the node was constructed. The memory map must persist as long as
// there are unloaded leaf nodes; this is ensured by storing a shared pointer
// to the map in each unloaded node.
class MappedFile::Impl
{
public:
Impl(const std::string& filename, bool autoDelete)
: mMap(filename.c_str(), boost::interprocess::read_only)
, mRegion(mMap, boost::interprocess::read_only)
, mAutoDelete(autoDelete)
{
mLastWriteTime = this->getLastWriteTime();
if (mAutoDelete) {
#ifndef _MSC_VER
// On Unix systems, unlink the file so that it gets deleted once it is closed.
::unlink(mMap.get_name());
#endif
}
}
~Impl()
{
std::string filename;
if (const char* s = mMap.get_name()) filename = s;
OPENVDB_LOG_DEBUG_RUNTIME("closing memory-mapped file " << filename);
if (mNotifier) mNotifier(filename);
if (mAutoDelete) {
if (!boost::interprocess::file_mapping::remove(filename.c_str())) {
if (errno != ENOENT) {
// Warn if the file exists but couldn't be removed.
std::string mesg = getErrorString();
if (!mesg.empty()) mesg = " (" + mesg + ")";
OPENVDB_LOG_WARN("failed to remove temporary file " << filename << mesg);
}
}
}
}
Index64 getLastWriteTime() const
{
Index64 result = 0;
const char* filename = mMap.get_name();
#ifdef _MSC_VER
// boost::interprocess::detail was renamed to boost::interprocess::ipcdetail in Boost 1.48.
using namespace boost::interprocess::detail;
using namespace boost::interprocess::ipcdetail;
if (void* fh = open_existing_file(filename, boost::interprocess::read_only)) {
struct { unsigned long lo, hi; } mtime; // Windows FILETIME struct
if (GetFileTime(fh, nullptr, nullptr, &mtime)) {
result = (Index64(mtime.hi) << 32) | mtime.lo;
}
close_file(fh);
}
#else
struct stat info;
if (0 == ::stat(filename, &info)) {
result = Index64(info.st_mtime);
}
#endif
return result;
}
boost::interprocess::file_mapping mMap;
boost::interprocess::mapped_region mRegion;
bool mAutoDelete;
Notifier mNotifier;
mutable std::atomic<Index64> mLastWriteTime;
private:
Impl(const Impl&); // not copyable
Impl& operator=(const Impl&); // not copyable
};
MappedFile::MappedFile(const std::string& filename, bool autoDelete):
mImpl(new Impl(filename, autoDelete))
{
}
MappedFile::~MappedFile()
{
}
std::string
MappedFile::filename() const
{
std::string result;
if (const char* s = mImpl->mMap.get_name()) result = s;
return result;
}
SharedPtr<std::streambuf>
MappedFile::createBuffer() const
{
if (!mImpl->mAutoDelete && mImpl->mLastWriteTime > 0) {
// Warn if the file has been modified since it was opened
// (but don't bother checking if it is a private, temporary file).
if (mImpl->getLastWriteTime() > mImpl->mLastWriteTime) {
OPENVDB_LOG_WARN("file " << this->filename() << " might have changed on disk"
<< " since it was opened");
mImpl->mLastWriteTime = 0; // suppress further warnings
}
}
return SharedPtr<std::streambuf>{
new boost::iostreams::stream_buffer<boost::iostreams::array_source>{
static_cast<const char*>(mImpl->mRegion.get_address()), mImpl->mRegion.get_size()}};
}
void
MappedFile::setNotifier(const Notifier& notifier)
{
mImpl->mNotifier = notifier;
}
void
MappedFile::clearNotifier()
{
mImpl->mNotifier = nullptr;
}
////////////////////////////////////////
std::string
getErrorString(int errorNum)
{
return std::error_code(errorNum, std::generic_category()).message();
}
std::string
getErrorString()
{
return getErrorString(errno);
}
////////////////////////////////////////
Archive::Archive()
: mFileVersion(OPENVDB_FILE_VERSION)
, mLibraryVersion(OPENVDB_LIBRARY_MAJOR_VERSION, OPENVDB_LIBRARY_MINOR_VERSION)
, mUuid(boost::uuids::nil_uuid())
, mInputHasGridOffsets(false)
, mEnableInstancing(true)
, mCompression(DEFAULT_COMPRESSION_FLAGS)
, mEnableGridStats(true)
{
}
Archive::~Archive()
{
}
Archive::Ptr
Archive::copy() const
{
return Archive::Ptr(new Archive(*this));
}
////////////////////////////////////////
std::string
Archive::getUniqueTag() const
{
return boost::uuids::to_string(mUuid);
}
bool
Archive::isIdentical(const std::string& uuidStr) const
{
return uuidStr == getUniqueTag();
}
////////////////////////////////////////
uint32_t
getFormatVersion(std::ios_base& is)
{
/// @todo get from StreamMetadata
return static_cast<uint32_t>(is.iword(sStreamState.fileVersion));
}
void
Archive::setFormatVersion(std::istream& is)
{
is.iword(sStreamState.fileVersion) = mFileVersion; ///< @todo remove
if (StreamMetadata::Ptr meta = getStreamMetadataPtr(is)) {
meta->setFileVersion(mFileVersion);
}
}
VersionId
getLibraryVersion(std::ios_base& is)
{
/// @todo get from StreamMetadata
VersionId version;
version.first = static_cast<uint32_t>(is.iword(sStreamState.libraryMajorVersion));
version.second = static_cast<uint32_t>(is.iword(sStreamState.libraryMinorVersion));
return version;
}
void
Archive::setLibraryVersion(std::istream& is)
{
is.iword(sStreamState.libraryMajorVersion) = mLibraryVersion.first; ///< @todo remove
is.iword(sStreamState.libraryMinorVersion) = mLibraryVersion.second; ///< @todo remove
if (StreamMetadata::Ptr meta = getStreamMetadataPtr(is)) {
meta->setLibraryVersion(mLibraryVersion);
}
}
std::string
getVersion(std::ios_base& is)
{
VersionId version = getLibraryVersion(is);
std::ostringstream ostr;
ostr << version.first << "." << version.second << "/" << getFormatVersion(is);
return ostr.str();
}
void
setCurrentVersion(std::istream& is)
{
is.iword(sStreamState.fileVersion) = OPENVDB_FILE_VERSION; ///< @todo remove
is.iword(sStreamState.libraryMajorVersion) = OPENVDB_LIBRARY_MAJOR_VERSION; ///< @todo remove
is.iword(sStreamState.libraryMinorVersion) = OPENVDB_LIBRARY_MINOR_VERSION; ///< @todo remove
if (StreamMetadata::Ptr meta = getStreamMetadataPtr(is)) {
meta->setFileVersion(OPENVDB_FILE_VERSION);
meta->setLibraryVersion(VersionId(
OPENVDB_LIBRARY_MAJOR_VERSION, OPENVDB_LIBRARY_MINOR_VERSION));
}
}
void
setVersion(std::ios_base& strm, const VersionId& libraryVersion, uint32_t fileVersion)
{
strm.iword(sStreamState.fileVersion) = fileVersion; ///< @todo remove
strm.iword(sStreamState.libraryMajorVersion) = libraryVersion.first; ///< @todo remove
strm.iword(sStreamState.libraryMinorVersion) = libraryVersion.second; ///< @todo remove
if (StreamMetadata::Ptr meta = getStreamMetadataPtr(strm)) {
meta->setFileVersion(fileVersion);
meta->setLibraryVersion(libraryVersion);
}
}
std::string
Archive::version() const
{
std::ostringstream ostr;
ostr << mLibraryVersion.first << "." << mLibraryVersion.second << "/" << mFileVersion;
return ostr.str();
}
////////////////////////////////////////
uint32_t
getDataCompression(std::ios_base& strm)
{
/// @todo get from StreamMetadata
return uint32_t(strm.iword(sStreamState.dataCompression));
}
void
setDataCompression(std::ios_base& strm, uint32_t c)
{
strm.iword(sStreamState.dataCompression) = c; ///< @todo remove
if (StreamMetadata::Ptr meta = getStreamMetadataPtr(strm)) {
meta->setCompression(c);
}
}
void
Archive::setDataCompression(std::istream& is)
{
io::setDataCompression(is, mCompression); ///< @todo remove
if (StreamMetadata::Ptr meta = getStreamMetadataPtr(is)) {
meta->setCompression(mCompression);
}
}
//static
bool
Archive::hasBloscCompression()
{
#ifdef OPENVDB_USE_BLOSC
return true;
#else
return false;
#endif
}
//static
bool
Archive::hasZLibCompression()
{
#ifdef OPENVDB_USE_ZLIB
return true;
#else
return false;
#endif
}
void
Archive::setGridCompression(std::ostream& os, const GridBase& grid) const
{
// Start with the options that are enabled globally for this archive.
uint32_t c = compression();
// Disable options that are inappropriate for the given grid.
switch (grid.getGridClass()) {
case GRID_LEVEL_SET:
case GRID_FOG_VOLUME:
// ZLIB compression is not used on level sets or fog volumes.
c = c & ~COMPRESS_ZIP;
break;
case GRID_STAGGERED:
case GRID_UNKNOWN:
break;
}
io::setDataCompression(os, c);
os.write(reinterpret_cast<const char*>(&c), sizeof(uint32_t));
}
void
Archive::readGridCompression(std::istream& is)
{
if (getFormatVersion(is) >= OPENVDB_FILE_VERSION_NODE_MASK_COMPRESSION) {
uint32_t c = COMPRESS_NONE;
is.read(reinterpret_cast<char*>(&c), sizeof(uint32_t));
io::setDataCompression(is, c);
}
}
////////////////////////////////////////
bool
getWriteGridStatsMetadata(std::ios_base& strm)
{
/// @todo get from StreamMetadata
return strm.iword(sStreamState.writeGridStatsMetadata) != 0;
}
void
setWriteGridStatsMetadata(std::ios_base& strm, bool writeGridStats)
{
strm.iword(sStreamState.writeGridStatsMetadata) = writeGridStats; ///< @todo remove
if (StreamMetadata::Ptr meta = getStreamMetadataPtr(strm)) {
meta->setWriteGridStats(writeGridStats);
}
}
////////////////////////////////////////
uint32_t
getGridClass(std::ios_base& strm)
{
/// @todo get from StreamMetadata
const uint32_t val = static_cast<uint32_t>(strm.iword(sStreamState.gridClass));
if (val >= NUM_GRID_CLASSES) return GRID_UNKNOWN;
return val;
}
void
setGridClass(std::ios_base& strm, uint32_t cls)
{
strm.iword(sStreamState.gridClass) = long(cls); ///< @todo remove
if (StreamMetadata::Ptr meta = getStreamMetadataPtr(strm)) {
meta->setGridClass(cls);
}
}
bool
getHalfFloat(std::ios_base& strm)
{
/// @todo get from StreamMetadata
return strm.iword(sStreamState.halfFloat) != 0;
}
void
setHalfFloat(std::ios_base& strm, bool halfFloat)
{
strm.iword(sStreamState.halfFloat) = halfFloat; ///< @todo remove
if (StreamMetadata::Ptr meta = getStreamMetadataPtr(strm)) {
meta->setHalfFloat(halfFloat);
}
}
const void*
getGridBackgroundValuePtr(std::ios_base& strm)
{
/// @todo get from StreamMetadata
return strm.pword(sStreamState.gridBackground);
}
void
setGridBackgroundValuePtr(std::ios_base& strm, const void* background)
{
strm.pword(sStreamState.gridBackground) = const_cast<void*>(background); ///< @todo remove
if (StreamMetadata::Ptr meta = getStreamMetadataPtr(strm)) {
meta->setBackgroundPtr(background);
}
}
MappedFile::Ptr
getMappedFilePtr(std::ios_base& strm)
{
if (const void* ptr = strm.pword(sStreamState.mappedFile)) {
return *static_cast<const MappedFile::Ptr*>(ptr);
}
return MappedFile::Ptr();
}
void
setMappedFilePtr(std::ios_base& strm, io::MappedFile::Ptr& mappedFile)
{
strm.pword(sStreamState.mappedFile) = &mappedFile;
}
StreamMetadata::Ptr
getStreamMetadataPtr(std::ios_base& strm)
{
if (const void* ptr = strm.pword(sStreamState.metadata)) {
return *static_cast<const StreamMetadata::Ptr*>(ptr);
}
return StreamMetadata::Ptr();
}
void
setStreamMetadataPtr(std::ios_base& strm, StreamMetadata::Ptr& meta, bool transfer)
{
strm.pword(sStreamState.metadata) = &meta;
if (transfer && meta) meta->transferTo(strm);
}
StreamMetadata::Ptr
clearStreamMetadataPtr(std::ios_base& strm)
{
StreamMetadata::Ptr result = getStreamMetadataPtr(strm);
strm.pword(sStreamState.metadata) = nullptr;
return result;
}
////////////////////////////////////////
bool
Archive::readHeader(std::istream& is)
{
// 1) Read the magic number for VDB.
int64_t magic;
is.read(reinterpret_cast<char*>(&magic), sizeof(int64_t));
if (magic != OPENVDB_MAGIC) {
OPENVDB_THROW(IoError, "not a VDB file");
}
// 2) Read the file format version number.
is.read(reinterpret_cast<char*>(&mFileVersion), sizeof(uint32_t));
if (mFileVersion > OPENVDB_FILE_VERSION) {
OPENVDB_LOG_WARN("unsupported VDB file format (expected version "
<< OPENVDB_FILE_VERSION << " or earlier, got version " << mFileVersion << ")");
} else if (mFileVersion < 211) {
// Versions prior to 211 stored separate major, minor and patch numbers.
uint32_t version;
is.read(reinterpret_cast<char*>(&version), sizeof(uint32_t));
mFileVersion = 100 * mFileVersion + 10 * version;
is.read(reinterpret_cast<char*>(&version), sizeof(uint32_t));
mFileVersion += version;
}
// 3) Read the library version numbers (not stored prior to file format version 211).
mLibraryVersion.first = mLibraryVersion.second = 0;
if (mFileVersion >= 211) {
uint32_t version;
is.read(reinterpret_cast<char*>(&version), sizeof(uint32_t));
mLibraryVersion.first = version; // major version
is.read(reinterpret_cast<char*>(&version), sizeof(uint32_t));
mLibraryVersion.second = version; // minor version
}
// 4) Read the flag indicating whether the stream supports partial reading.
// (Versions prior to 212 have no flag because they always supported partial reading.)
mInputHasGridOffsets = true;
if (mFileVersion >= 212) {
char hasGridOffsets;
is.read(&hasGridOffsets, sizeof(char));
mInputHasGridOffsets = hasGridOffsets;
}
// 5) Read the flag that indicates whether data is compressed.
// (From version 222 on, compression information is stored per grid.)
mCompression = DEFAULT_COMPRESSION_FLAGS;
if (mFileVersion < OPENVDB_FILE_VERSION_BLOSC_COMPRESSION) {
// Prior to the introduction of Blosc, ZLIB was the default compression scheme.
mCompression = (COMPRESS_ZIP | COMPRESS_ACTIVE_MASK);
}
if (mFileVersion >= OPENVDB_FILE_VERSION_SELECTIVE_COMPRESSION &&
mFileVersion < OPENVDB_FILE_VERSION_NODE_MASK_COMPRESSION)
{
char isCompressed;
is.read(&isCompressed, sizeof(char));
mCompression = (isCompressed != 0 ? COMPRESS_ZIP : COMPRESS_NONE);
}
// 6) Read the 16-byte (128-bit) uuid.
boost::uuids::uuid oldUuid = mUuid;
if (mFileVersion >= OPENVDB_FILE_VERSION_BOOST_UUID) {
// UUID is stored as an ASCII string.
is >> mUuid;
} else {
// Older versions stored the UUID as a byte string.
char uuidBytes[16];
is.read(uuidBytes, 16);
std::memcpy(&mUuid.data[0], uuidBytes, std::min<size_t>(16, mUuid.size()));
}
return oldUuid != mUuid; // true if UUID in input stream differs from old UUID
}
void
Archive::writeHeader(std::ostream& os, bool seekable) const
{
// 1) Write the magic number for VDB.
int64_t magic = OPENVDB_MAGIC;
os.write(reinterpret_cast<char*>(&magic), sizeof(int64_t));
// 2) Write the file format version number.
uint32_t version = OPENVDB_FILE_VERSION;
os.write(reinterpret_cast<char*>(&version), sizeof(uint32_t));
// 3) Write the library version numbers.
version = OPENVDB_LIBRARY_MAJOR_VERSION;
os.write(reinterpret_cast<char*>(&version), sizeof(uint32_t));
version = OPENVDB_LIBRARY_MINOR_VERSION;
os.write(reinterpret_cast<char*>(&version), sizeof(uint32_t));
// 4) Write a flag indicating that this stream contains no grid offsets.
char hasGridOffsets = seekable;
os.write(&hasGridOffsets, sizeof(char));
// 5) Write a flag indicating that this stream contains compressed leaf data.
// (Omitted as of version 222)
// 6) Generate a new random 16-byte (128-bit) uuid and write it to the stream.
std::mt19937 ran;
ran.seed(std::mt19937::result_type(std::random_device()() + std::time(nullptr)));
boost::uuids::basic_random_generator<std::mt19937> gen(&ran);
mUuid = gen(); // mUuid is mutable
os << mUuid;
}
////////////////////////////////////////
int32_t
Archive::readGridCount(std::istream& is)
{
int32_t gridCount = 0;
is.read(reinterpret_cast<char*>(&gridCount), sizeof(int32_t));
return gridCount;
}
////////////////////////////////////////
void
Archive::connectInstance(const GridDescriptor& gd, const NamedGridMap& grids) const
{
if (!gd.isInstance() || grids.empty()) return;
NamedGridMap::const_iterator it = grids.find(gd.uniqueName());
if (it == grids.end()) return;
GridBase::Ptr grid = it->second;
if (!grid) return;
it = grids.find(gd.instanceParentName());
if (it != grids.end()) {
GridBase::Ptr parent = it->second;
if (mEnableInstancing) {
// Share the instance parent's tree.
grid->setTree(parent->baseTreePtr());
} else {
// Copy the instance parent's tree.
grid->setTree(parent->baseTree().copy());
}
} else {
OPENVDB_THROW(KeyError, "missing instance parent \""
<< GridDescriptor::nameAsString(gd.instanceParentName())
<< "\" for grid " << GridDescriptor::nameAsString(gd.uniqueName()));
}
}
////////////////////////////////////////
//static
bool
Archive::isDelayedLoadingEnabled()
{
return (nullptr == std::getenv("OPENVDB_DISABLE_DELAYED_LOAD"));
}
namespace {
struct NoBBox {};
template<typename BoxType>
void
doReadGrid(GridBase::Ptr grid, const GridDescriptor& gd, std::istream& is, const BoxType& bbox)
{
struct Local {
static void readBuffers(GridBase& g, std::istream& istrm, NoBBox) { g.readBuffers(istrm); }
static void readBuffers(GridBase& g, std::istream& istrm, const CoordBBox& indexBBox) {
g.readBuffers(istrm, indexBBox);
}
static void readBuffers(GridBase& g, std::istream& istrm, const BBoxd& worldBBox) {
g.readBuffers(istrm, g.constTransform().worldToIndexNodeCentered(worldBBox));
}
};
// Restore the file-level stream metadata on exit.
struct OnExit {
OnExit(std::ios_base& strm_): strm(&strm_), ptr(strm_.pword(sStreamState.metadata)) {}
~OnExit() { strm->pword(sStreamState.metadata) = ptr; }
std::ios_base* strm;
void* ptr;
};
OnExit restore(is);
// Stream metadata varies per grid, and it needs to persist
// in case delayed load is in effect.
io::StreamMetadata::Ptr streamMetadata;
if (io::StreamMetadata::Ptr meta = io::getStreamMetadataPtr(is)) {
// Make a grid-level copy of the file-level stream metadata.
streamMetadata.reset(new StreamMetadata(*meta));
} else {
streamMetadata.reset(new StreamMetadata);
}
streamMetadata->setHalfFloat(grid->saveFloatAsHalf());
io::setStreamMetadataPtr(is, streamMetadata, /*transfer=*/false);
io::setGridClass(is, GRID_UNKNOWN);
io::setGridBackgroundValuePtr(is, nullptr);
grid->readMeta(is);
// Add a description of the compression settings to the grid as metadata.
/// @todo Would this be useful?
//const uint32_t c = getDataCompression(is);
//grid->insertMeta(GridBase::META_FILE_COMPRESSION,
// StringMetadata(compressionToString(c)));
const VersionId version = getLibraryVersion(is);
if (version.first < 6 || (version.first == 6 && version.second <= 1)) {
// If delay load metadata exists, but the file format version does not support
// delay load metadata, this likely means the original grid was read and then
// written using a prior version of OpenVDB and ABI>=5 where unknown metadata
// can be blindly copied. This means that it is possible for the metadata to
// no longer be in sync with the grid, so we remove it to ensure correctness.
if ((*grid)[GridBase::META_FILE_DELAYED_LOAD]) {
grid->removeMeta(GridBase::META_FILE_DELAYED_LOAD);
}
}
streamMetadata->gridMetadata() = static_cast<MetaMap&>(*grid);
const GridClass gridClass = grid->getGridClass();
io::setGridClass(is, gridClass);
// reset leaf value to zero
streamMetadata->setLeaf(0);
// drop DelayedLoadMetadata from the grid as it is only useful for IO
// a stream metadata non-zero value disables this behaviour for testing
if (streamMetadata->__test() == uint32_t(0)) {
if ((*grid)[GridBase::META_FILE_DELAYED_LOAD]) {
grid->removeMeta(GridBase::META_FILE_DELAYED_LOAD);
}
}
if (getFormatVersion(is) >= OPENVDB_FILE_VERSION_GRID_INSTANCING) {
grid->readTransform(is);
if (!gd.isInstance()) {
grid->readTopology(is);
Local::readBuffers(*grid, is, bbox);
}
} else {
// Older versions of the library stored the transform after the topology.
grid->readTopology(is);
grid->readTransform(is);
Local::readBuffers(*grid, is, bbox);
}
if (getFormatVersion(is) < OPENVDB_FILE_VERSION_NO_GRIDMAP) {
// Older versions of the library didn't store grid names as metadata,
// so when reading older files, copy the grid name from the descriptor
// to the grid's metadata.
if (grid->getName().empty()) {
grid->setName(gd.gridName());
}
}
}
} // unnamed namespace
void
Archive::readGrid(GridBase::Ptr grid, const GridDescriptor& gd, std::istream& is)
{
// Read the compression settings for this grid and tag the stream with them
// so that downstream functions can reference them.
readGridCompression(is);
doReadGrid(grid, gd, is, NoBBox());
}
void
Archive::readGrid(GridBase::Ptr grid, const GridDescriptor& gd,
std::istream& is, const BBoxd& worldBBox)
{
readGridCompression(is);
doReadGrid(grid, gd, is, worldBBox);
}
void
Archive::readGrid(GridBase::Ptr grid, const GridDescriptor& gd,
std::istream& is, const CoordBBox& indexBBox)
{
readGridCompression(is);
doReadGrid(grid, gd, is, indexBBox);
}
////////////////////////////////////////
void
Archive::write(std::ostream& os, const GridPtrVec& grids, bool seekable,
const MetaMap& metadata) const
{
this->write(os, GridCPtrVec(grids.begin(), grids.end()), seekable, metadata);
}
void
Archive::write(std::ostream& os, const GridCPtrVec& grids, bool seekable,
const MetaMap& metadata) const
{
// Set stream flags so that downstream functions can reference them.
io::StreamMetadata::Ptr streamMetadata = io::getStreamMetadataPtr(os);
if (!streamMetadata) {
streamMetadata.reset(new StreamMetadata);
io::setStreamMetadataPtr(os, streamMetadata, /*transfer=*/false);
}
io::setDataCompression(os, compression());
io::setWriteGridStatsMetadata(os, isGridStatsMetadataEnabled());
this->writeHeader(os, seekable);
metadata.writeMeta(os);
// Write the number of non-null grids.
int32_t gridCount = 0;
for (GridCPtrVecCIter i = grids.begin(), e = grids.end(); i != e; ++i) {
if (*i) ++gridCount;
}
os.write(reinterpret_cast<char*>(&gridCount), sizeof(int32_t));
using TreeMap = std::map<const TreeBase*, GridDescriptor>;
using TreeMapIter = TreeMap::iterator;
TreeMap treeMap;
// Determine which grid names are unique and which are not.
using NameHistogram = std::map<std::string, int /*count*/>;
NameHistogram nameCount;
for (GridCPtrVecCIter i = grids.begin(), e = grids.end(); i != e; ++i) {
if (const GridBase::ConstPtr& grid = *i) {
const std::string name = grid->getName();
NameHistogram::iterator it = nameCount.find(name);
if (it != nameCount.end()) it->second++;
else nameCount[name] = 1;
}
}
std::set<std::string> uniqueNames;
// Write out the non-null grids.
for (GridCPtrVecCIter i = grids.begin(), e = grids.end(); i != e; ++i) {
if (const GridBase::ConstPtr& grid = *i) {
// Ensure that the grid's descriptor has a unique grid name, by appending
// a number to it if a grid with the same name was already written.
// Always add a number if the grid name is empty, so that the grid can be
// properly identified as an instance parent, if necessary.
std::string name = grid->getName();
if (name.empty() || nameCount[name] > 1) {
name = GridDescriptor::addSuffix(name, 0);
}
for (int n = 1; uniqueNames.find(name) != uniqueNames.end(); ++n) {
name = GridDescriptor::addSuffix(grid->getName(), n);
}
uniqueNames.insert(name);
// Create a grid descriptor.
GridDescriptor gd(name, grid->type(), grid->saveFloatAsHalf());
// Check if this grid's tree is shared with a grid that has already been written.
const TreeBase* treePtr = &(grid->baseTree());
TreeMapIter mapIter = treeMap.find(treePtr);
bool isInstance = ((mapIter != treeMap.end())
&& (mapIter->second.saveFloatAsHalf() == gd.saveFloatAsHalf()));
if (mEnableInstancing && isInstance) {
// This grid's tree is shared with another grid that has already been written.
// Get the name of the other grid.
gd.setInstanceParentName(mapIter->second.uniqueName());
// Write out this grid's descriptor and metadata, but not its tree.
writeGridInstance(gd, grid, os, seekable);
OPENVDB_LOG_DEBUG_RUNTIME("io::Archive::write(): "
<< GridDescriptor::nameAsString(gd.uniqueName())
<< " (" << std::hex << treePtr << std::dec << ")"
<< " is an instance of "
<< GridDescriptor::nameAsString(gd.instanceParentName()));
} else {
// Write out the grid descriptor and its associated grid.
writeGrid(gd, grid, os, seekable);
// Record the grid's tree pointer so that the tree doesn't get written
// more than once.
treeMap[treePtr] = gd;
}
}
// Some compression options (e.g., mask compression) are set per grid.
// Restore the original settings before writing the next grid.
io::setDataCompression(os, compression());
}
}
void
Archive::writeGrid(GridDescriptor& gd, GridBase::ConstPtr grid,
std::ostream& os, bool seekable) const
{
// Restore file-level stream metadata on exit.
struct OnExit {
OnExit(std::ios_base& strm_): strm(&strm_), ptr(strm_.pword(sStreamState.metadata)) {}
~OnExit() { strm->pword(sStreamState.metadata) = ptr; }
std::ios_base* strm;
void* ptr;
};
OnExit restore(os);
// Stream metadata varies per grid, so make a copy of the file-level stream metadata.
io::StreamMetadata::Ptr streamMetadata;
if (io::StreamMetadata::Ptr meta = io::getStreamMetadataPtr(os)) {
streamMetadata.reset(new StreamMetadata(*meta));
} else {
streamMetadata.reset(new StreamMetadata);
}
streamMetadata->setHalfFloat(grid->saveFloatAsHalf());
streamMetadata->gridMetadata() = static_cast<const MetaMap&>(*grid);
io::setStreamMetadataPtr(os, streamMetadata, /*transfer=*/false);
// Write out the Descriptor's header information (grid name and type)
gd.writeHeader(os);
// Save the curent stream position as postion to where the offsets for
// this GridDescriptor will be written to.
int64_t offsetPos = (seekable ? int64_t(os.tellp()) : 0);
// Write out the offset information. At this point it will be incorrect.
// But we need to write it out to move the stream head forward.
gd.writeStreamPos(os);
// Now we know the starting grid storage position.
if (seekable) gd.setGridPos(os.tellp());
// Save the compression settings for this grid.
setGridCompression(os, *grid);
// copy grid and add delay load metadata
const auto copyOfGrid = grid->copyGrid(); // shallow copy
const auto nonConstCopyOfGrid = ConstPtrCast<GridBase>(copyOfGrid);
nonConstCopyOfGrid->insertMeta(GridBase::META_FILE_DELAYED_LOAD,
DelayedLoadMetadata());
DelayedLoadMetadata::Ptr delayLoadMeta =
nonConstCopyOfGrid->getMetadata<DelayedLoadMetadata>(GridBase::META_FILE_DELAYED_LOAD);
if (!populateDelayedLoadMetadata(*delayLoadMeta, *grid, compression())) {
nonConstCopyOfGrid->removeMeta(GridBase::META_FILE_DELAYED_LOAD);
}
// Save the grid's metadata and transform.
if (getWriteGridStatsMetadata(os)) {
// Compute and add grid statistics metadata.
nonConstCopyOfGrid->addStatsMetadata();
nonConstCopyOfGrid->insertMeta(GridBase::META_FILE_COMPRESSION,
StringMetadata(compressionToString(getDataCompression(os))));
}
copyOfGrid->writeMeta(os);
grid->writeTransform(os);
// Save the grid's structure.
grid->writeTopology(os);
// Now we know the grid block storage position.
if (seekable) gd.setBlockPos(os.tellp());
// Save out the data blocks of the grid.
grid->writeBuffers(os);
// Now we know the end position of this grid.
if (seekable) gd.setEndPos(os.tellp());
if (seekable) {
// Now, go back to where the Descriptor's offset information is written
// and write the offsets again.
os.seekp(offsetPos, std::ios_base::beg);
gd.writeStreamPos(os);
// Now seek back to the end.
gd.seekToEnd(os);
}
}
void
Archive::writeGridInstance(GridDescriptor& gd, GridBase::ConstPtr grid,
std::ostream& os, bool seekable) const
{
// Write out the Descriptor's header information (grid name, type
// and instance parent name).
gd.writeHeader(os);
// Save the curent stream position as postion to where the offsets for
// this GridDescriptor will be written to.
int64_t offsetPos = (seekable ? int64_t(os.tellp()) : 0);
// Write out the offset information. At this point it will be incorrect.
// But we need to write it out to move the stream head forward.
gd.writeStreamPos(os);
// Now we know the starting grid storage position.
if (seekable) gd.setGridPos(os.tellp());
// Save the compression settings for this grid.
setGridCompression(os, *grid);
// Save the grid's metadata and transform.
grid->writeMeta(os);
grid->writeTransform(os);
// Now we know the end position of this grid.
if (seekable) gd.setEndPos(os.tellp());
if (seekable) {
// Now, go back to where the Descriptor's offset information is written
// and write the offsets again.
os.seekp(offsetPos, std::ios_base::beg);
gd.writeStreamPos(os);
// Now seek back to the end.
gd.seekToEnd(os);
}
}
} // namespace io
} // namespace OPENVDB_VERSION_NAME
} // namespace openvdb
|
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Solution {
public:
vector<vector<char>> updateBoard(vector<vector<char>>& board, vector<int>& click) {
}
};
int main(){
return 0;
}
|
/////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 1996-1997 Microsoft Corporation
//
// Module Name:
// BarfClus.cpp
//
// Abstract:
// Implementation of the Basic Artifical Resource Failure entry points
// for CLUSAPI functions.
//
// Author:
// David Potter (davidp) April 14, 1997
//
// Revision History:
//
// Notes:
//
/////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#define _NO_BARF_DEFINITIONS_
#include "Barf.h"
#include "BarfClus.h"
#include "TraceTag.h"
#include "ExcOper.h"
#ifdef _USING_BARF_
#error BARF failures should be disabled!
#endif
#ifdef _DEBUG // The entire file!
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
/////////////////////////////////////////////////////////////////////////////
// Global Variables
/////////////////////////////////////////////////////////////////////////////
CBarf g_barfClusApi(_T("CLUSAPI Calls"));
/////////////////////////////////////////////////////////////////////////////
// Cluster Management Functions
/////////////////////////////////////////////////////////////////////////////
BOOL BARFCloseCluster(HCLUSTER hCluster)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("CloseCluster()"));
SetLastError(ERROR_INVALID_FUNCTION);
return FALSE;
} // if: BARF failure
else
return CloseCluster(hCluster);
} //*** BARFCloseCluster()
BOOL BARFCloseClusterNotifyPort(HCHANGE hChange)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("CloseClusterNotifyPort()"));
SetLastError(ERROR_INVALID_FUNCTION);
return FALSE;
} // if: BARF failure
else
return CloseClusterNotifyPort(hChange);
} //*** BARFCloseClusterNotifyPort()
DWORD BARFClusterCloseEnum(HCLUSENUM hClusEnum)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("ClusterCloseEnum()"));
return ERROR_INVALID_FUNCTION;
} // if: BARF failure
else
return ClusterCloseEnum(hClusEnum);
} //*** BARFClusterCloseEnum()
DWORD BARFClusterEnum(
HCLUSENUM hClusEnum,
DWORD dwIndex,
LPDWORD lpdwType,
LPWSTR lpszName,
LPDWORD lpcchName
)
{
// if (g_barfClusApi.BFail())
// {
// Trace(g_tagBarf, _T("ClusterEnum()"));
// return ERROR_INVALID_FUNCTION;
// } // if: BARF failure
// else
return ClusterEnum(hClusEnum, dwIndex, lpdwType, lpszName, lpcchName);
} //*** BARFClusterEnum()
HCLUSENUM BARFClusterOpenEnum(HCLUSTER hCluster, DWORD dwType)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("ClusterOpenEnum()"));
SetLastError(ERROR_INVALID_FUNCTION);
return NULL;
} // if: BARF failure
else
return ClusterOpenEnum(hCluster, dwType);
} //*** BARFClusterOpenEnum()
DWORD BARFClusterResourceTypeControl(
HCLUSTER hCluster,
LPCWSTR lpszResourceTypeName,
HNODE hHostNode,
DWORD dwControlCode,
LPVOID lpInBuffer,
DWORD nInBufferSize,
LPVOID lpOutBuffer,
DWORD nOutBufferSize,
LPDWORD lpBytesReturned
)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("ClusterResourceTypeControl()"));
return ERROR_INVALID_FUNCTION;
} // if: BARF failure
else
return ClusterResourceTypeControl(
hCluster,
lpszResourceTypeName,
hHostNode,
dwControlCode,
lpInBuffer,
nInBufferSize,
lpOutBuffer,
nOutBufferSize,
lpBytesReturned
);
} //*** BARFClusterResourceTypeControl()
HCHANGE BARFCreateClusterNotifyPort(
HCHANGE hChange,
HCLUSTER hCluster,
DWORD dwFilter,
DWORD_PTR dwNotifyKey
)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("CreateClusterNotifyPort()"));
SetLastError(ERROR_INVALID_FUNCTION);
return NULL;
} // if: BARF failure
else
return CreateClusterNotifyPort(
hChange,
hCluster,
dwFilter,
dwNotifyKey
);
} //*** BARFCreateClusterNotifyPort()
DWORD BARFCreateClusterResourceType(
HCLUSTER hCluster,
LPCWSTR lpszResourceTypeName,
LPCWSTR lpszDisplayName,
LPCWSTR lpszResourceTypeDll,
DWORD dwLooksAlivePollInterval,
DWORD dwIsAlivePollInterval
)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("CreateClusterResourceType()"));
return ERROR_INVALID_FUNCTION;
} // if: BARF failure
else
return CreateClusterResourceType(
hCluster,
lpszResourceTypeName,
lpszDisplayName,
lpszDisplayName,
dwLooksAlivePollInterval,
dwIsAlivePollInterval
);
} //*** BARFCreateClusterResourceType()
DWORD BARFDeleteClusterResourceType(HCLUSTER hCluster, LPCWSTR lpszResourceTypeName)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("DeleteClusterResourceType()"));
return ERROR_INVALID_FUNCTION;
} // if: BARF failure
else
return DeleteClusterResourceType(
hCluster,
lpszResourceTypeName
);
} //*** BARFDeleteClusterResourceType()
DWORD BARFGetClusterInformation(
HCLUSTER hCluster,
LPWSTR lpszClusterName,
LPDWORD lpcchClusterName,
LPCLUSTERVERSIONINFO lpClusterInfo
)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("GetClusterInformation()"));
return ERROR_INVALID_FUNCTION;
} // if: BARF failure
else
return GetClusterInformation(
hCluster,
lpszClusterName,
lpcchClusterName,
lpClusterInfo
);
} //*** BARFGetClusterInformation()
DWORD BARFGetClusterNotify(
HCHANGE hChange,
DWORD_PTR *lpdwNotifyKey,
LPDWORD lpdwFilterType,
LPWSTR lpszName,
LPDWORD lpcchName,
DWORD dwMilliseconds
)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("GetClusterNotify()"));
return ERROR_INVALID_FUNCTION;
} // if: BARF failure
else
return GetClusterNotify(
hChange,
lpdwNotifyKey,
lpdwFilterType,
lpszName,
lpcchName,
dwMilliseconds
);
} //*** BARFGetClusterNotify()
DWORD BARFGetClusterQuorumResource(
HCLUSTER hCluster,
LPWSTR lpszResourceName,
LPDWORD lpcbResourceName,
LPWSTR lpszDeviceName,
LPDWORD lpcbDeviceName,
LPDWORD lpdwMaxQuorumLogSize
)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("GetClusterQuorumResource()"));
return ERROR_INVALID_FUNCTION;
} // if: BARF failure
else
return GetClusterQuorumResource(
hCluster,
lpszResourceName,
lpcbResourceName,
lpszDeviceName,
lpcbDeviceName,
lpdwMaxQuorumLogSize
);
} //*** BARFGetClusterQuorumResource()
HCLUSTER BARFOpenCluster(LPCWSTR lpszClusterName)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("OpenCluster()"));
SetLastError(ERROR_INVALID_FUNCTION);
return NULL;
} // if: BARF failure
else
return OpenCluster(lpszClusterName);
} //*** BARFOpenCluster()
DWORD BARFRegisterClusterNotify(
HCHANGE hChange,
DWORD dwFilter,
HANDLE hObject,
DWORD_PTR dwNotifyKey
)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("RegisterClusterNotify()"));
return ERROR_INVALID_FUNCTION;
} // if: BARF failure
else
return RegisterClusterNotify(
hChange,
dwFilter,
hObject,
dwNotifyKey
);
} //*** BARFRegisterClusterNotify()
DWORD BARFSetClusterName(HCLUSTER hCluster, LPCWSTR lpszNewClusterName)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("SetClusterName()"));
return ERROR_INVALID_FUNCTION;
} // if: BARF failure
else
return SetClusterName(hCluster, lpszNewClusterName);
} //*** BARFSetClusterName()
DWORD BARFSetClusterQuorumResource(
HRESOURCE hResource,
LPCWSTR lpszDeviceName,
DWORD dwMaxQuoLogSize
)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("SetClusterQuorumResource()"));
return ERROR_INVALID_FUNCTION;
} // if: BARF failure
else
return SetClusterQuorumResource(
hResource,
lpszDeviceName,
dwMaxQuoLogSize
);
} //*** BARFSetClusterQuorumResource()
/////////////////////////////////////////////////////////////////////////////
// Node Management Functions
/////////////////////////////////////////////////////////////////////////////
BOOL BARFCloseClusterNode(HNODE hNode)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("CloseClusterNode()"));
SetLastError(ERROR_INVALID_FUNCTION);
return FALSE;
} // if: BARF failure
else
return CloseClusterNode(hNode);
} //*** BARFCloseClusterNode()
DWORD BARFClusterNodeControl(
HNODE hNode,
HNODE hHostNode,
DWORD dwControlCode,
LPVOID lpInBuffer,
DWORD nInBufferSize,
LPVOID lpOutBuffer,
DWORD nOutBufferSize,
LPDWORD lpBytesReturned
)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("ClusterNodeControl()"));
return ERROR_INVALID_FUNCTION;
} // if: BARF failure
else
return ClusterNodeControl(
hNode,
hHostNode,
dwControlCode,
lpInBuffer,
nInBufferSize,
lpOutBuffer,
nOutBufferSize,
lpBytesReturned
);
} //*** BARFClusterNodeControl()
DWORD BARFEvictClusterNode(HNODE hNode)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("EvictClusterNode()"));
return ERROR_INVALID_FUNCTION;
} // if: BARF failure
else
return EvictClusterNode(hNode);
} //*** BARFEvictClusterNode()
DWORD BARFGetClusterNodeId(HNODE hNode, LPWSTR lpszNodeId, LPDWORD lpcchNodeId)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("GetClusterNodeId()"));
return ERROR_INVALID_FUNCTION;
} // if: BARF failure
else
return GetClusterNodeId(hNode, lpszNodeId, lpcchNodeId);
} //*** BARFGetClusterNodeId()
CLUSTER_NODE_STATE BARFGetClusterNodeState(HNODE hNode)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("GetClusterNodeState()"));
SetLastError(ERROR_INVALID_FUNCTION);
return ClusterNodeStateUnknown;
} // if: BARF failure
else
return GetClusterNodeState(hNode);
} //*** BARFGetClusterNodeState()
HNODE BARFOpenClusterNode(HCLUSTER hCluster, LPCWSTR lpszNodeName)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("OpenClusterNode()"));
SetLastError(ERROR_INVALID_FUNCTION);
return NULL;
} // if: BARF failure
else
return OpenClusterNode(hCluster, lpszNodeName);
} //*** BARFOpenClusterNode()
DWORD BARFPauseClusterNode(HNODE hNode)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("PauseClusterNode()"));
return ERROR_INVALID_FUNCTION;
} // if: BARF failure
else
return PauseClusterNode(hNode);
} //*** BARFPauseClusterNode()
DWORD BARFResumeClusterNode(HNODE hNode)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("ResumeClusterNode()"));
return ERROR_INVALID_FUNCTION;
} // if: BARF failure
else
return ResumeClusterNode(hNode);
} //*** BARFResumeClusterNode()
/////////////////////////////////////////////////////////////////////////////
// Group Management Functions
/////////////////////////////////////////////////////////////////////////////
BOOL BARFCloseClusterGroup(HGROUP hGroup)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("CloseClusterGroup()"));
SetLastError(ERROR_INVALID_FUNCTION);
return FALSE;
} // if: BARF failure
else
return CloseClusterGroup(hGroup);
} //*** BARFCloseClusterGroup()
DWORD BARFClusterGroupCloseEnum(HGROUPENUM hGroupEnum)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("ClusterGroupCloseEnum()"));
return ERROR_INVALID_FUNCTION;
} // if: BARF failure
else
return ClusterGroupCloseEnum(hGroupEnum);
} //*** BARFClusterGroupCloseEnum()
DWORD BARFClusterGroupControl(
HGROUP hGroup,
HNODE hHostNode,
DWORD dwControlCode,
LPVOID lpInBuffer,
DWORD nInBufferSize,
LPVOID lpOutBuffer,
DWORD nOutBufferSize,
LPDWORD lpBytesReturned
)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("ClusterGroupControl()"));
return ERROR_INVALID_FUNCTION;
} // if: BARF failure
else
return ClusterGroupControl(
hGroup,
hHostNode,
dwControlCode,
lpInBuffer,
nInBufferSize,
lpOutBuffer,
nOutBufferSize,
lpBytesReturned
);
} //*** BARFClusterGroupControl()
DWORD BARFClusterGroupEnum(
HGROUPENUM hGroupEnum,
DWORD dwIndex,
LPDWORD lpdwType,
LPWSTR lpszResourceName,
LPDWORD lpcchName
)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("ClusterGroupEnum()"));
return ERROR_INVALID_FUNCTION;
} // if: BARF failure
else
return ClusterGroupEnum(
hGroupEnum,
dwIndex,
lpdwType,
lpszResourceName,
lpcchName
);
} //*** BARFClusterGroupEnum()
HGROUPENUM BARFClusterGroupOpenEnum(HGROUP hGroup, DWORD dwType)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("ClusterGroupOpenEnum()"));
SetLastError(ERROR_INVALID_FUNCTION);
return NULL;
} // if: BARF failure
else
return ClusterGroupOpenEnum(hGroup, dwType);
} //*** BARFClusterGroupOpenEnum()
HGROUP BARFCreateClusterGroup(HCLUSTER hCluster, LPCWSTR lpszGroupName)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("CreateClusterGroup()"));
SetLastError(ERROR_INVALID_FUNCTION);
return NULL;
} // if: BARF failure
else
return CreateClusterGroup(hCluster, lpszGroupName);
} //*** BARFCreateClusterGroup()
DWORD BARFDeleteClusterGroup(HGROUP hGroup)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("DeleteClusterGroup()"));
SetLastError(ERROR_INVALID_FUNCTION);
return NULL;
} // if: BARF failure
else
return DeleteClusterGroup(hGroup);
} //*** BARFDeleteClusterGroup()
CLUSTER_GROUP_STATE BARFGetClusterGroupState(
HGROUP hGroup,
LPWSTR lpszNodeName,
LPDWORD lpcchNodeName
)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("GetClusterGroupState()"));
SetLastError(ERROR_INVALID_FUNCTION);
return ClusterGroupStateUnknown;
} // if: BARF failure
else
return GetClusterGroupState(
hGroup,
lpszNodeName,
lpcchNodeName
);
} //*** BARFGetClusterGroupState()
DWORD BARFMoveClusterGroup(HGROUP hGroup, HNODE hDestinationNode)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("MoveClusterGroup()"));
return ERROR_INVALID_FUNCTION;
} // if: BARF failure
else
return MoveClusterGroup(hGroup, hDestinationNode);
} //*** BARFMoveClusterGroup()
DWORD BARFOfflineClusterGroup(HGROUP hGroup)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("OfflineClusterGroup()"));
return ERROR_INVALID_FUNCTION;
} // if: BARF failure
else
return OfflineClusterGroup(hGroup);
} //*** BARFOfflineClusterGroup()
DWORD BARFOnlineClusterGroup(HGROUP hGroup, HNODE hDestinationNode)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("OnlineClusterGroup()"));
return ERROR_INVALID_FUNCTION;
} // if: BARF failure
else
return OnlineClusterGroup(hGroup, hDestinationNode);
} //*** BARFOnlineClusterGroup()
HGROUP BARFOpenClusterGroup(HCLUSTER hCluster, LPCWSTR lpszGroupName)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("OpenClusterGroup()"));
SetLastError(ERROR_INVALID_FUNCTION);
return NULL;
} // if: BARF failure
else
return OpenClusterGroup(hCluster, lpszGroupName);
} //*** BARFOpenClusterGroup()
DWORD BARFSetClusterGroupName(HGROUP hGroup, LPCWSTR lpszGroupName)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("SetClusterGroupName()"));
return ERROR_INVALID_FUNCTION;
} // if: BARF failure
else
return SetClusterGroupName(hGroup, lpszGroupName);
} //*** BARFSetClusterGroupName()
DWORD BARFSetClusterGroupNodeList(
HGROUP hGroup,
DWORD cNodeCount,
HNODE phNodeList[]
)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("SetClusterGroupNodeList()"));
return ERROR_INVALID_FUNCTION;
} // if: BARF failure
else
return SetClusterGroupNodeList(
hGroup,
cNodeCount,
phNodeList
);
} //*** BARFSetClusterGroupNodeList()
/////////////////////////////////////////////////////////////////////////////
// Resource Management Functions
/////////////////////////////////////////////////////////////////////////////
DWORD BARFAddClusterResourceDependency(HRESOURCE hResource, HRESOURCE hDependsOn)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("AddClusterResourceDependency()"));
return ERROR_INVALID_FUNCTION;
} // if: BARF failure
else
return AddClusterResourceDependency(hResource, hDependsOn);
} //*** BARFAddClusterResourceDependency()
DWORD BARFAddClusterResourceNode(HRESOURCE hResource, HNODE hNode)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("AddClusterResourceNode()"));
return ERROR_INVALID_FUNCTION;
} // if: BARF failure
else
return AddClusterResourceNode(hResource, hNode);
} //*** BARFAddClusterResourceNode()
BOOL BARFCanResourceBeDependent(HRESOURCE hResource, HRESOURCE hResourceDependent)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("CanResourceBeDependent()"));
SetLastError(ERROR_INVALID_FUNCTION);
return FALSE;
} // if: BARF failure
else
return CanResourceBeDependent(hResource, hResourceDependent);
} //*** BARFCanResourceBeDependent()
DWORD BARFChangeClusterResourceGroup(HRESOURCE hResource, HGROUP hGroup)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("ChangeClusterResourceGroup()"));
return ERROR_INVALID_FUNCTION;
} // if: BARF failure
else
return ChangeClusterResourceGroup(hResource, hGroup);
} //*** BARFChangeClusterResourceGroup()
BOOL BARFCloseClusterResource(HRESOURCE hResource)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("CloseClusterResource()"));
SetLastError(ERROR_INVALID_FUNCTION);
return FALSE;
} // if: BARF failure
else
return CloseClusterResource(hResource);
} //*** BARFCloseClusterResource()
DWORD BARFClusterResourceCloseEnum(HRESENUM hResEnum)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("ClusterResourceCloseEnum()"));
return ERROR_INVALID_FUNCTION;
} // if: BARF failure
else
return ClusterResourceCloseEnum(hResEnum);
} //*** BARFClusterResourceCloseEnum()
DWORD BARFClusterResourceControl(
HRESOURCE hResource,
HNODE hHostNode,
DWORD dwControlCode,
LPVOID lpInBuffer,
DWORD nInBufferSize,
LPVOID lpOutBuffer,
DWORD nOutBufferSize,
LPDWORD lpBytesReturned
)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("ClusterResourceControl()"));
return ERROR_INVALID_FUNCTION;
} // if: BARF failure
else
return ClusterResourceControl(
hResource,
hHostNode,
dwControlCode,
lpInBuffer,
nInBufferSize,
lpOutBuffer,
nOutBufferSize,
lpBytesReturned
);
} //*** BARFClusterResourceControl()
DWORD BARFClusterResourceEnum(
HRESENUM hResEnum,
DWORD dwIndex,
LPDWORD lpdwType,
LPWSTR lpszName,
LPDWORD lpcchName
)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("ClusterResourceEnum()"));
return ERROR_INVALID_FUNCTION;
} // if: BARF failure
else
return ClusterResourceEnum(
hResEnum,
dwIndex,
lpdwType,
lpszName,
lpcchName
);
} //*** BARFClusterResourceEnum()
HRESENUM BARFClusterResourceOpenEnum(HRESOURCE hResource, DWORD dwType)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("ClusterResourceOpenEnum()"));
SetLastError(ERROR_INVALID_FUNCTION);
return NULL;
} // if: BARF failure
else
return ClusterResourceOpenEnum(hResource, dwType);
} //*** BARFClusterResourceOpenEnum()
HRESOURCE BARFCreateClusterResource(
HGROUP hGroup,
LPCWSTR lpszResourceName,
LPCWSTR lpszResourceType,
DWORD dwFlags
)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("CreateClusterResource()"));
SetLastError(ERROR_INVALID_FUNCTION);
return NULL;
} // if: BARF failure
else
return CreateClusterResource(
hGroup,
lpszResourceName,
lpszResourceType,
dwFlags
);
} //*** BARFCreateClusterResource()
DWORD BARFDeleteClusterResource(HRESOURCE hResource)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("DeleteClusterResource()"));
return ERROR_INVALID_FUNCTION;
} // if: BARF failure
else
return DeleteClusterResource(hResource);
} //*** BARFDeleteClusterResource()
DWORD BARFFailClusterResource(HRESOURCE hResource)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("FailClusterResource()"));
return ERROR_INVALID_FUNCTION;
} // if: BARF failure
else
return FailClusterResource(hResource);
} //*** BARFFailClusterResource()
BOOL BARFGetClusterResourceNetworkName(
HRESOURCE hResource,
LPWSTR lpBuffer,
LPDWORD nSize
)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("GetClusterResourceNetworkName()"));
SetLastError(ERROR_INVALID_FUNCTION);
return NULL;
} // if: BARF failure
else
return GetClusterResourceNetworkName(
hResource,
lpBuffer,
nSize
);
} //*** BARFGetClusterResourceNetworkName()
CLUSTER_RESOURCE_STATE BARFGetClusterResourceState(
HRESOURCE hResource,
LPWSTR lpszNodeName,
LPDWORD lpcchNodeName,
LPWSTR lpszGroupName,
LPDWORD lpcchGroupName
)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("GetClusterResourceNetworkName()"));
SetLastError(ERROR_INVALID_FUNCTION);
return ClusterResourceStateUnknown;
} // if: BARF failure
else
return GetClusterResourceState(
hResource,
lpszNodeName,
lpcchNodeName,
lpszGroupName,
lpcchGroupName
);
} //*** BARFGetClusterResourceState()
DWORD BARFOfflineClusterResource(HRESOURCE hResource)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("OfflineClusterResource()"));
return ERROR_INVALID_FUNCTION;
} // if: BARF failure
else
return OfflineClusterResource(hResource);
} //*** BARFOfflineClusterResource()
DWORD BARFOnlineClusterResource(HRESOURCE hResource)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("OnlineClusterResource()"));
return ERROR_INVALID_FUNCTION;
} // if: BARF failure
else
return OnlineClusterResource(hResource);
} //*** BARFOnlineClusterResource()
HRESOURCE BARFOpenClusterResource(
HCLUSTER hCluster,
LPCWSTR lpszResourceName
)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("OpenClusterResource()"));
SetLastError(ERROR_INVALID_FUNCTION);
return NULL;
} // if: BARF failure
else
return OpenClusterResource(hCluster, lpszResourceName);
} //*** BARFOpenClusterResource()
DWORD BARFRemoveClusterResourceNode(
HRESOURCE hResource,
HNODE hNode
)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("RemoveClusterResourceNode()"));
return ERROR_INVALID_FUNCTION;
} // if: BARF failure
else
return RemoveClusterResourceNode(hResource, hNode);
} //*** BARFRemoveClusterResourceNode()
DWORD BARFRemoveClusterResourceDependency(
HRESOURCE hResource,
HRESOURCE hDependsOn
)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("RemoveClusterResourceDependency()"));
return ERROR_INVALID_FUNCTION;
} // if: BARF failure
else
return RemoveClusterResourceDependency(hResource, hDependsOn);
} //*** BARFRemoveClusterResourceDependency()
DWORD BARFSetClusterResourceName(
HRESOURCE hResource,
LPCWSTR lpszResourceName
)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("SetClusterResourceName()"));
return ERROR_INVALID_FUNCTION;
} // if: BARF failure
else
return SetClusterResourceName(hResource, lpszResourceName);
} //*** BARFSetClusterResourceName()
/////////////////////////////////////////////////////////////////////////////
// Network Management Functions
/////////////////////////////////////////////////////////////////////////////
HNETWORK BARFOpenClusterNetwork(
HCLUSTER hCluster,
LPCWSTR lpszNetworkName
)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("OpenClusterNetwork()"));
SetLastError(ERROR_INVALID_FUNCTION);
return NULL;
} // if: BARF failure
else
return OpenClusterNetwork(hCluster, lpszNetworkName);
} //*** BARFOpenClusterNetwork()
BOOL BARFCloseClusterNetwork(HNETWORK hNetwork)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("CloseClusterNetwork()"));
SetLastError(ERROR_INVALID_FUNCTION);
return FALSE;
} // if: BARF failure
else
return CloseClusterNetwork(hNetwork);
} //*** BARFOpenClusterNetwork()
HNETWORKENUM BARFClusterNetworkOpenEnum(
HNETWORK hNetwork,
DWORD dwType
)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("ClusterNetworkOpenEnum()"));
SetLastError(ERROR_INVALID_FUNCTION);
return NULL;
} // if: BARF failure
else
return ClusterNetworkOpenEnum(hNetwork, dwType);
} //*** BARFClusterNetworkOpenEnum()
DWORD BARFClusterNetworkEnum(
HNETWORKENUM hNetworkEnum,
DWORD dwIndex,
DWORD * lpdwType,
LPWSTR lpszName,
LPDWORD lpcchName
)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("ClusterNetworkEnum()"));
return ERROR_INVALID_FUNCTION;
} // if: BARF failure
else
return ClusterNetworkEnum(
hNetworkEnum,
dwIndex,
lpdwType,
lpszName,
lpcchName
);
} //*** BARFClusterNetworkEnum()
DWORD BARFClusterNetworkCloseEnum(HNETWORKENUM hNetworkEnum)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("ClusterNetworkCloseEnum()"));
return ERROR_INVALID_FUNCTION;
} // if: BARF failure
else
return ClusterNetworkCloseEnum(hNetworkEnum);
} //*** BARFClusterNetworkCloseEnum()
CLUSTER_NETWORK_STATE BARFGetClusterNetworkState(HNETWORK hNetwork)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("GetClusterNetworkState()"));
SetLastError(ERROR_INVALID_FUNCTION);
return ClusterNetworkStateUnknown;
} // if: BARF failure
else
return GetClusterNetworkState(hNetwork);
} //*** BARFGetClusterNetworkState()
DWORD BARFSetClusterNetworkName(
HNETWORK hNetwork,
LPCWSTR lpszName
)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("SetClusterNetworkName()"));
return ERROR_INVALID_FUNCTION;
} // if: BARF failure
else
return SetClusterNetworkName(hNetwork, lpszName);
} //*** BARFSetClusterNetworkName()
DWORD BARFClusterNetworkControl(
HNETWORK hNetwork,
HNODE hHostNode,
DWORD dwControlCode,
LPVOID lpInBuffer,
DWORD nInBufferSize,
LPVOID lpOutBuffer,
DWORD nOutBufferSize,
LPDWORD lpBytesReturned
)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("ClusterNetworkControl()"));
return ERROR_INVALID_FUNCTION;
} // if: BARF failure
else
return ClusterNetworkControl(
hNetwork,
hHostNode,
dwControlCode,
lpInBuffer,
nInBufferSize,
lpOutBuffer,
nOutBufferSize,
lpBytesReturned
);
} //*** BARFClusterNetworkControl()
/////////////////////////////////////////////////////////////////////////////
// Network Interface Management Functions
/////////////////////////////////////////////////////////////////////////////
HNETINTERFACE BARFOpenClusterNetInterface(
HCLUSTER hCluster,
LPCWSTR lpszInterfaceName
)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("OpenClusterNetInterface()"));
SetLastError(ERROR_INVALID_FUNCTION);
return NULL;
} // if: BARF failure
else
return OpenClusterNetInterface(hCluster, lpszInterfaceName);
} //*** BARFOpenClusterNetInterface()
DWORD BARFGetClusterNetInterface(
HCLUSTER hCluster,
LPCWSTR lpszNodeName,
LPCWSTR lpszNetworkName,
LPWSTR lpszNetInterfaceName,
DWORD * lpcchNetInterfaceName
)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("GetClusterNetInterface()"));
SetLastError(ERROR_INVALID_FUNCTION);
return NULL;
} // if: BARF failure
else
return GetClusterNetInterface(
hCluster,
lpszNodeName,
lpszNetworkName,
lpszNetInterfaceName,
lpcchNetInterfaceName
);
} //*** BARFGetClusterNetInterface()
BOOL BARFCloseClusterNetInterface(HNETINTERFACE hNetInterface)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("CloseClusterNetInterface()"));
SetLastError(ERROR_INVALID_FUNCTION);
return FALSE;
} // if: BARF failure
else
return CloseClusterNetInterface(hNetInterface);
} //*** BARFCloseClusterNetInterface()
CLUSTER_NETINTERFACE_STATE BARFGetClusterNetInterfaceState(HNETINTERFACE hNetInterface)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("GetClusterNetInterfaceState()"));
SetLastError(ERROR_INVALID_FUNCTION);
return ClusterNetInterfaceStateUnknown;
} // if: BARF failure
else
return GetClusterNetInterfaceState(hNetInterface);
} //*** BARFGetClusterNetInterfaceState()
DWORD BARFClusterNetInterfaceControl(
HNETINTERFACE hNetInterface,
HNODE hHostNode,
DWORD dwControlCode,
LPVOID lpInBuffer,
DWORD nInBufferSize,
LPVOID lpOutBuffer,
DWORD nOutBufferSize,
LPDWORD lpBytesReturned
)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("ClusterNetInterfaceControl()"));
return ERROR_INVALID_FUNCTION;
} // if: BARF failure
else
return ClusterNetInterfaceControl(
hNetInterface,
hHostNode,
dwControlCode,
lpInBuffer,
nInBufferSize,
lpOutBuffer,
nOutBufferSize,
lpBytesReturned
);
} //*** BARFClusterNetInterfaceControl()
/////////////////////////////////////////////////////////////////////////////
// Cluster Database Management Functions
/////////////////////////////////////////////////////////////////////////////
LONG BARFClusterRegCloseKey(HKEY hKey)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("ClusterRegCloseKey()"));
return ERROR_INVALID_FUNCTION;
} // if: BARF failure
else
return ClusterRegCloseKey(hKey);
} //*** BARFClusterRegCloseKey()
LONG BARFClusterRegCreateKey(
HKEY hKey,
LPCWSTR lpszSubKey,
DWORD dwOptions,
REGSAM samDesired,
LPSECURITY_ATTRIBUTES lpSecurityAttributes,
PHKEY phkResult,
LPDWORD lpdwDisposition
)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("ClusterRegCreateKey()"));
return ERROR_INVALID_FUNCTION;
} // if: BARF failure
else
return ClusterRegCreateKey(
hKey,
lpszSubKey,
dwOptions,
samDesired,
lpSecurityAttributes,
phkResult,
lpdwDisposition
);
} //*** BARFClusterRegCreateKey()
LONG BARFClusterRegDeleteKey(
HKEY hKey,
LPCWSTR lpszSubKey
)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("ClusterRegDeleteKey()"));
return ERROR_INVALID_FUNCTION;
} // if: BARF failure
else
return ClusterRegDeleteKey(hKey, lpszSubKey);
} //*** BARFClusterRegDeleteKey()
DWORD BARFClusterRegDeleteValue(
HKEY hKey,
LPCWSTR lpszValueName
)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("ClusterRegDeleteValue()"));
return ERROR_INVALID_FUNCTION;
} // if: BARF failure
else
return ClusterRegDeleteValue(hKey, lpszValueName);
} //*** BARFClusterRegDeleteValue()
LONG BARFClusterRegEnumKey(
HKEY hKey,
DWORD dwIndex,
LPWSTR lpszName,
LPDWORD lpcchName,
PFILETIME lpftLastWriteTime
)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("ClusterRegEnumKey()"));
return ERROR_INVALID_FUNCTION;
} // if: BARF failure
else
return ClusterRegEnumKey(
hKey,
dwIndex,
lpszName,
lpcchName,
lpftLastWriteTime
);
} //*** BARFClusterRegEnumKey()
DWORD BARFClusterRegEnumValue(
HKEY hKey,
DWORD dwIndex,
LPWSTR lpszValueName,
LPDWORD lpcchValueName,
LPDWORD lpdwType,
LPBYTE lpbData,
LPDWORD lpcbData
)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("ClusterRegEnumValue()"));
return ERROR_INVALID_FUNCTION;
} // if: BARF failure
else
return ClusterRegEnumValue(
hKey,
dwIndex,
lpszValueName,
lpcchValueName,
lpdwType,
lpbData,
lpcbData
);
} //*** BARFClusterRegEnumValue()
LONG BARFClusterRegGetKeySecurity(
HKEY hKey,
SECURITY_INFORMATION SecurityInformation,
PSECURITY_DESCRIPTOR pSecurityDescriptor,
LPDWORD lpcbSecurityDescriptor
)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("ClusterRegGetKeySecurity()"));
return ERROR_INVALID_FUNCTION;
} // if: BARF failure
else
return ClusterRegGetKeySecurity(
hKey,
SecurityInformation,
pSecurityDescriptor,
lpcbSecurityDescriptor
);
} //*** BARFClusterRegGetKeySecurity()
LONG BARFClusterRegOpenKey(
HKEY hKey,
LPCWSTR lpszSubKey,
REGSAM samDesired,
PHKEY phkResult
)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("ClusterRegOpenKey()"));
return ERROR_INVALID_FUNCTION;
} // if: BARF failure
else
return ClusterRegOpenKey(
hKey,
lpszSubKey,
samDesired,
phkResult
);
} //*** BARFClusterRegOpenKey()
LONG BARFClusterRegQueryInfoKey(
HKEY hKey,
LPDWORD lpcSubKeys,
LPDWORD lpcbMaxSubKeyLen,
LPDWORD lpcValues,
LPDWORD lpcbMaxValueNameLen,
LPDWORD lpcbMaxValueLen,
LPDWORD lpcbSecurityDescriptor,
PFILETIME lpftLastWriteTime
)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("ClusterRegQueryInfoKey()"));
return ERROR_INVALID_FUNCTION;
} // if: BARF failure
else
return ClusterRegQueryInfoKey(
hKey,
lpcSubKeys,
lpcbMaxSubKeyLen,
lpcValues,
lpcbMaxValueNameLen,
lpcbMaxValueLen,
lpcbSecurityDescriptor,
lpftLastWriteTime
);
} //*** BARFClusterRegQueryInfoKey()
LONG BARFClusterRegQueryValue(
HKEY hKey,
LPCWSTR lpszValueName,
LPDWORD lpdwValueType,
LPBYTE lpbData,
LPDWORD lpcbData
)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("ClusterRegQueryValue()"));
return ERROR_INVALID_FUNCTION;
} // if: BARF failure
else
return ClusterRegQueryValue(
hKey,
lpszValueName,
lpdwValueType,
lpbData,
lpcbData
);
} //*** BARFClusterRegQueryValue()
LONG BARFClusterRegSetKeySecurity(
HKEY hKey,
SECURITY_INFORMATION SecurityInformation,
PSECURITY_DESCRIPTOR pSecurityDescriptor
)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("ClusterRegSetKeySecurity()"));
return ERROR_INVALID_FUNCTION;
} // if: BARF failure
else
return ClusterRegSetKeySecurity(
hKey,
SecurityInformation,
pSecurityDescriptor
);
} //*** BARFClusterRegSetKeySecurity()
DWORD BARFClusterRegSetValue(
HKEY hKey,
LPCWSTR lpszValueName,
DWORD dwType,
CONST BYTE * lpbData,
DWORD cbData
)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("ClusterRegSetValue()"));
return ERROR_INVALID_FUNCTION;
} // if: BARF failure
else
return ClusterRegSetValue(
hKey,
lpszValueName,
dwType,
lpbData,
cbData
);
} //*** BARFClusterRegSetValue()
HKEY BARFGetClusterGroupKey(
HGROUP hGroup,
REGSAM samDesired
)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("GetClusterGroupKey()"));
SetLastError(ERROR_INVALID_FUNCTION);
return NULL;
} // if: BARF failure
else
return GetClusterGroupKey(hGroup, samDesired);
} //*** BARFGetClusterGroupKey()
HKEY BARFGetClusterKey(
HCLUSTER hCluster,
REGSAM samDesired
)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("GetClusterKey()"));
SetLastError(ERROR_INVALID_FUNCTION);
return NULL;
} // if: BARF failure
else
return GetClusterKey(hCluster, samDesired);
} //*** BARFGetClusterKey()
HKEY BARFGetClusterNodeKey(
HNODE hNode,
REGSAM samDesired
)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("GetClusterNodeKey()"));
SetLastError(ERROR_INVALID_FUNCTION);
return NULL;
} // if: BARF failure
else
return GetClusterNodeKey(hNode, samDesired);
} //*** BARFGetClusterNodeKey()
HKEY BARFGetClusterResourceKey(
HRESOURCE hResource,
REGSAM samDesired
)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("GetClusterResourceKey()"));
SetLastError(ERROR_INVALID_FUNCTION);
return NULL;
} // if: BARF failure
else
return GetClusterResourceKey(hResource, samDesired);
} //*** BARFGetClusterResourceKey()
HKEY BARFGetClusterResourceTypeKey(
HCLUSTER hCluster,
LPCWSTR lpszTypeName,
REGSAM samDesired
)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("GetClusterResourceTypeKey()"));
SetLastError(ERROR_INVALID_FUNCTION);
return NULL;
} // if: BARF failure
else
return GetClusterResourceTypeKey(hCluster, lpszTypeName, samDesired);
} //*** BARFGetClusterResourceTypeKey()
HKEY BARFGetClusterNetworkKey(
HNETWORK hNetwork,
REGSAM samDesired
)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("GetClusterNetworkKey()"));
SetLastError(ERROR_INVALID_FUNCTION);
return NULL;
} // if: BARF failure
else
return GetClusterNetworkKey(hNetwork, samDesired);
} //*** BARFGetClusterNetworkKey()
HKEY BARFGetClusterNetInterfaceKey(
HNETINTERFACE hNetInterface,
REGSAM samDesired
)
{
if (g_barfClusApi.BFail())
{
Trace(g_tagBarf, _T("GetClusterNetInterfaceKey()"));
SetLastError(ERROR_INVALID_FUNCTION);
return NULL;
} // if: BARF failure
else
return GetClusterNetInterfaceKey(hNetInterface, samDesired);
} //*** BARFGetClusterNetInterfaceKey()
#endif // _DEBUG
|
/*
* If not stated otherwise in this file or this component's LICENSE file the
* following copyright and licenses apply:
*
* Copyright 2021 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.
*/
#include "../ctrlm_voice_packet_analysis.h"
#define SEQUENCE_NUM_INVALID (0xFF)
class ctrlm_voice_packet_analysis_rf4ce_t : public ctrlm_voice_packet_analysis {
public:
ctrlm_voice_packet_analysis_rf4ce_t();
virtual void reset();
virtual ctrlm_voice_packet_analysis_result_t packet_check(const void* header, unsigned long header_len, const void* data, unsigned long data_len);
virtual void stats_get(ctrlm_voice_packet_analysis_stats_t& stats) const;
private:
guchar sequence_num_last;
guint32 total_packets;
guint32 duplicated_packets;
guint32 lost_packets;
guint32 sequence_error_count;
};
ctrlm_voice_packet_analysis_rf4ce_t::ctrlm_voice_packet_analysis_rf4ce_t() :
sequence_num_last(SEQUENCE_NUM_INVALID),
total_packets(0),
duplicated_packets(0),
lost_packets(0),
sequence_error_count(0)
{
}
void ctrlm_voice_packet_analysis_rf4ce_t::reset() {
sequence_num_last = 0x20;
total_packets = 0;
duplicated_packets = 0;
lost_packets = 0;
sequence_error_count = 0;
}
ctrlm_voice_packet_analysis_result_t ctrlm_voice_packet_analysis_rf4ce_t::packet_check(const void* header, unsigned long header_len, const void* data, unsigned long data_len) {
ctrlm_voice_packet_analysis_result_t result = CTRLM_VOICE_PACKET_ANALYSIS_GOOD;
return result;
}
void ctrlm_voice_packet_analysis_rf4ce_t::stats_get(ctrlm_voice_packet_analysis_stats_t& stats) const {
stats.total_packets = total_packets;
stats.bad_packets = 0;
stats.duplicated_packets = duplicated_packets;
stats.lost_packets = lost_packets;
stats.sequence_error_count = sequence_error_count;
}
ctrlm_voice_packet_analysis* ctrlm_voice_packet_analysis_factory() {
return new ctrlm_voice_packet_analysis_rf4ce_t;
}
|
//===--- SimplifyCFG.cpp - Clean up the SIL CFG ---------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "sil-simplify-cfg"
#include "swift/SILOptimizer/PassManager/Passes.h"
#include "swift/SIL/Dominance.h"
#include "swift/SIL/Projection.h"
#include "swift/SIL/SILArgument.h"
#include "swift/SIL/SILModule.h"
#include "swift/SIL/SILUndef.h"
#include "swift/SIL/DebugUtils.h"
#include "swift/SIL/InstructionUtils.h"
#include "swift/SILOptimizer/Analysis/DominanceAnalysis.h"
#include "swift/SILOptimizer/Analysis/SimplifyInstruction.h"
#include "swift/SILOptimizer/Analysis/ProgramTerminationAnalysis.h"
#include "swift/SILOptimizer/PassManager/Transforms.h"
#include "swift/SILOptimizer/Utils/CFG.h"
#include "swift/SILOptimizer/Utils/Local.h"
#include "swift/SILOptimizer/Utils/SILInliner.h"
#include "swift/SILOptimizer/Utils/SILSSAUpdater.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/CommandLine.h"
using namespace swift;
STATISTIC(NumBlocksDeleted, "Number of unreachable blocks removed");
STATISTIC(NumBlocksMerged, "Number of blocks merged together");
STATISTIC(NumJumpThreads, "Number of jumps threaded");
STATISTIC(NumTermBlockSimplified, "Number of programterm block simplified");
STATISTIC(NumConstantFolded, "Number of terminators constant folded");
STATISTIC(NumDeadArguments, "Number of unused arguments removed");
STATISTIC(NumSROAArguments, "Number of aggregate argument levels split by "
"SROA");
//===----------------------------------------------------------------------===//
// CFG Simplification
//===----------------------------------------------------------------------===//
/// dominatorBasedSimplify iterates between dominator based simplification of
/// terminator branch condition values and cfg simplification. This is the
/// maximum number of iterations we run. The number is the maximum number of
/// iterations encountered when compiling the stdlib on April 2 2015.
///
static unsigned MaxIterationsOfDominatorBasedSimplify = 10;
namespace {
class SimplifyCFG {
SILFunction &Fn;
SILPassManager *PM;
// WorklistList is the actual list that we iterate over (for determinism).
// Slots may be null, which should be ignored.
SmallVector<SILBasicBlock*, 32> WorklistList;
// WorklistMap keeps track of which slot a BB is in, allowing efficient
// containment query, and allows efficient removal.
llvm::SmallDenseMap<SILBasicBlock*, unsigned, 32> WorklistMap;
// Keep track of loop headers - we don't want to jump-thread through them.
SmallPtrSet<SILBasicBlock *, 32> LoopHeaders;
// The number of times jump threading was done through a block.
// Used to prevent infinite jump threading loops.
llvm::SmallDenseMap<SILBasicBlock*, unsigned, 8> JumpThreadedBlocks;
// Dominance and post-dominance info for the current function
DominanceInfo *DT = nullptr;
bool ShouldVerify;
bool EnableJumpThread;
public:
SimplifyCFG(SILFunction &Fn, SILPassManager *PM, bool Verify,
bool EnableJumpThread)
: Fn(Fn), PM(PM), ShouldVerify(Verify),
EnableJumpThread(EnableJumpThread) {}
bool run();
bool simplifyBlockArgs() {
auto *DA = PM->getAnalysis<DominanceAnalysis>();
DT = DA->get(&Fn);
bool Changed = false;
for (SILBasicBlock &BB : Fn) {
Changed |= simplifyArgs(&BB);
}
DT = nullptr;
return Changed;
}
private:
void clearWorklist() {
WorklistMap.clear();
WorklistList.clear();
}
/// popWorklist - Return the next basic block to look at, or null if the
/// worklist is empty. This handles skipping over null entries in the
/// worklist.
SILBasicBlock *popWorklist() {
while (!WorklistList.empty())
if (auto *BB = WorklistList.pop_back_val()) {
WorklistMap.erase(BB);
return BB;
}
return nullptr;
}
/// addToWorklist - Add the specified block to the work list if it isn't
/// already present.
void addToWorklist(SILBasicBlock *BB) {
unsigned &Entry = WorklistMap[BB];
if (Entry != 0) return;
WorklistList.push_back(BB);
Entry = WorklistList.size();
}
/// removeFromWorklist - Remove the specified block from the worklist if
/// present.
void removeFromWorklist(SILBasicBlock *BB) {
assert(BB && "Cannot add null pointer to the worklist");
auto It = WorklistMap.find(BB);
if (It == WorklistMap.end()) return;
// If the BB is in the worklist, null out its entry.
if (It->second) {
assert(WorklistList[It->second-1] == BB && "Consistency error");
WorklistList[It->second-1] = nullptr;
}
// Remove it from the map as well.
WorklistMap.erase(It);
if (LoopHeaders.count(BB))
LoopHeaders.erase(BB);
}
bool simplifyBlocks();
bool canonicalizeSwitchEnums();
bool simplifyThreadedTerminators();
bool dominatorBasedSimplifications(SILFunction &Fn,
DominanceInfo *DT);
bool dominatorBasedSimplify(DominanceAnalysis *DA);
/// \brief Remove the basic block if it has no predecessors. Returns true
/// If the block was removed.
bool removeIfDead(SILBasicBlock *BB);
bool tryJumpThreading(BranchInst *BI);
bool tailDuplicateObjCMethodCallSuccessorBlocks();
bool simplifyAfterDroppingPredecessor(SILBasicBlock *BB);
bool simplifyBranchOperands(OperandValueArrayRef Operands);
bool simplifyBranchBlock(BranchInst *BI);
bool simplifyCondBrBlock(CondBranchInst *BI);
bool simplifyCheckedCastBranchBlock(CheckedCastBranchInst *CCBI);
bool simplifyCheckedCastValueBranchBlock(CheckedCastValueBranchInst *CCBI);
bool simplifyCheckedCastAddrBranchBlock(CheckedCastAddrBranchInst *CCABI);
bool simplifyTryApplyBlock(TryApplyInst *TAI);
bool simplifySwitchValueBlock(SwitchValueInst *SVI);
bool simplifyTermWithIdenticalDestBlocks(SILBasicBlock *BB);
bool simplifySwitchEnumUnreachableBlocks(SwitchEnumInst *SEI);
bool simplifySwitchEnumBlock(SwitchEnumInst *SEI);
bool simplifyUnreachableBlock(UnreachableInst *UI);
bool simplifyProgramTerminationBlock(SILBasicBlock *BB);
bool simplifyArgument(SILBasicBlock *BB, unsigned i);
bool simplifyArgs(SILBasicBlock *BB);
void findLoopHeaders();
};
class RemoveUnreachable {
SILFunction &Fn;
llvm::SmallSet<SILBasicBlock *, 8> Visited;
public:
RemoveUnreachable(SILFunction &Fn) : Fn(Fn) { }
void visit(SILBasicBlock *BB);
bool run();
};
} // end anonymous namespace
/// Return true if there are any users of V outside the specified block.
static bool isUsedOutsideOfBlock(SILValue V, SILBasicBlock *BB) {
for (auto UI : V->getUses())
if (UI->getUser()->getParent() != BB)
return true;
return false;
}
/// Helper function to perform SSA updates in case of jump threading.
void swift::updateSSAAfterCloning(BaseThreadingCloner &Cloner,
SILBasicBlock *SrcBB, SILBasicBlock *DestBB,
bool NeedToSplitCriticalEdges) {
// We are updating SSA form. This means we need to be able to insert phi
// nodes. To make sure we can do this split all critical edges from
// instructions that don't support block arguments.
if (NeedToSplitCriticalEdges)
splitAllCriticalEdges(*DestBB->getParent(), true, nullptr, nullptr);
SILSSAUpdater SSAUp;
for (auto AvailValPair : Cloner.AvailVals) {
ValueBase *Inst = AvailValPair.first;
if (Inst->use_empty())
continue;
if (Inst->hasValue()) {
SILValue NewRes(AvailValPair.second);
SmallVector<UseWrapper, 16> UseList;
// Collect the uses of the value.
for (auto Use : Inst->getUses())
UseList.push_back(UseWrapper(Use));
SSAUp.Initialize(Inst->getType());
SSAUp.AddAvailableValue(DestBB, Inst);
SSAUp.AddAvailableValue(SrcBB, NewRes);
if (UseList.empty())
continue;
// Update all the uses.
for (auto U : UseList) {
Operand *Use = U;
SILInstruction *User = Use->getUser();
assert(User && "Missing user");
// Ignore uses in the same basic block.
if (User->getParent() == DestBB)
continue;
SSAUp.RewriteUse(*Use);
}
}
}
}
static SILValue getTerminatorCondition(TermInst *Term) {
if (auto *CondBr = dyn_cast<CondBranchInst>(Term))
return stripExpectIntrinsic(CondBr->getCondition());
if (auto *SEI = dyn_cast<SwitchEnumInst>(Term))
return SEI->getOperand();
return nullptr;
}
/// Is this basic block jump threadable.
static bool isThreadableBlock(SILBasicBlock *BB,
SmallPtrSet<SILBasicBlock *, 32> &LoopHeaders) {
if (isa<ReturnInst>(BB->getTerminator()))
return false;
// We know how to handle cond_br and switch_enum .
if (!isa<CondBranchInst>(BB->getTerminator()) &&
!isa<SwitchEnumInst>(BB->getTerminator()))
return false;
if (LoopHeaders.count(BB))
return false;
unsigned Cost = 0;
for (auto &Inst : *BB) {
if (!Inst.isTriviallyDuplicatable())
return false;
// Don't jumpthread function calls.
if (isa<ApplyInst>(Inst))
return false;
// Only thread 'small blocks'.
if (instructionInlineCost(Inst) != InlineCost::Free)
if (++Cost == 4)
return false;
}
return true;
}
/// A description of an edge leading to a conditionally branching (or switching)
/// block and the successor block to thread to.
///
/// Src:
/// br Dest
/// \
/// \ Edge
/// v
/// Dest:
/// ...
/// switch/cond_br
/// / \
/// ... v
/// EnumCase/ThreadedSuccessorIdx
class ThreadInfo {
SILBasicBlock *Src;
SILBasicBlock *Dest;
EnumElementDecl *EnumCase;
unsigned ThreadedSuccessorIdx;
public:
ThreadInfo(SILBasicBlock *Src, SILBasicBlock *Dest,
unsigned ThreadedBlockSuccessorIdx)
: Src(Src), Dest(Dest), EnumCase(nullptr),
ThreadedSuccessorIdx(ThreadedBlockSuccessorIdx) {}
ThreadInfo(SILBasicBlock *Src, SILBasicBlock *Dest, EnumElementDecl *EnumCase)
: Src(Src), Dest(Dest), EnumCase(EnumCase), ThreadedSuccessorIdx(0) {}
ThreadInfo() = default;
void threadEdge() {
DEBUG(llvm::dbgs() << "thread edge from bb" << Src->getDebugID() <<
" to bb" << Dest->getDebugID() << '\n');
auto *SrcTerm = cast<BranchInst>(Src->getTerminator());
EdgeThreadingCloner Cloner(SrcTerm);
for (auto &I : *Dest)
Cloner.process(&I);
// We have copied the threaded block into the edge.
Src = Cloner.getEdgeBB();
if (auto *CondTerm = dyn_cast<CondBranchInst>(Src->getTerminator())) {
// We know the direction this conditional branch is going to take thread
// it.
assert(Src->getSuccessors().size() > ThreadedSuccessorIdx &&
"Threaded terminator does not have enough successors");
auto *ThreadedSuccessorBlock =
Src->getSuccessors()[ThreadedSuccessorIdx].getBB();
auto Args = ThreadedSuccessorIdx == 0 ? CondTerm->getTrueArgs()
: CondTerm->getFalseArgs();
SILBuilderWithScope(CondTerm)
.createBranch(CondTerm->getLoc(), ThreadedSuccessorBlock, Args);
CondTerm->eraseFromParent();
} else {
// Get the enum element and the destination block of the block we jump
// thread.
auto *SEI = cast<SwitchEnumInst>(Src->getTerminator());
auto *ThreadedSuccessorBlock = SEI->getCaseDestination(EnumCase);
// Instantiate the payload if necessary.
SILBuilderWithScope Builder(SEI);
if (!ThreadedSuccessorBlock->args_empty()) {
auto EnumVal = SEI->getOperand();
auto EnumTy = EnumVal->getType();
auto Loc = SEI->getLoc();
auto Ty = EnumTy.getEnumElementType(EnumCase, SEI->getModule());
SILValue UED(
Builder.createUncheckedEnumData(Loc, EnumVal, EnumCase, Ty));
assert(UED->getType() ==
(*ThreadedSuccessorBlock->args_begin())->getType() &&
"Argument types must match");
Builder.createBranch(SEI->getLoc(), ThreadedSuccessorBlock, {UED});
} else
Builder.createBranch(SEI->getLoc(), ThreadedSuccessorBlock, {});
SEI->eraseFromParent();
// Split the edge from 'Dest' to 'ThreadedSuccessorBlock' it is now
// critical. Doing this here safes us from doing it over the whole
// function in updateSSAAfterCloning because we have split all other
// critical edges earlier.
splitEdgesFromTo(Dest, ThreadedSuccessorBlock, nullptr, nullptr);
}
updateSSAAfterCloning(Cloner, Src, Dest, false);
}
};
/// Give a cond_br or switch_enum instruction and one successor block return
/// true if we can infer the value of the condition/enum along the edge to this
/// successor blocks.
static bool isKnownEdgeValue(TermInst *Term, SILBasicBlock *SuccBB,
EnumElementDecl *&EnumCase) {
assert((isa<CondBranchInst>(Term) || isa<SwitchEnumInst>(Term)) &&
"Expect a cond_br or switch_enum");
if (auto *SEI = dyn_cast<SwitchEnumInst>(Term)) {
if (auto Case = SEI->getUniqueCaseForDestination(SuccBB)) {
EnumCase = Case.get();
return SuccBB->getSinglePredecessorBlock() != nullptr;
}
return false;
}
return SuccBB->getSinglePredecessorBlock() != nullptr;
}
/// Create an enum element by extracting the operand of a switch_enum.
static SILInstruction *createEnumElement(SILBuilder &Builder,
SwitchEnumInst *SEI,
EnumElementDecl *EnumElement) {
auto EnumVal = SEI->getOperand();
// Do we have a payload.
auto EnumTy = EnumVal->getType();
if (EnumElement->hasAssociatedValues()) {
auto Ty = EnumTy.getEnumElementType(EnumElement, SEI->getModule());
SILValue UED(Builder.createUncheckedEnumData(SEI->getLoc(), EnumVal,
EnumElement, Ty));
return Builder.createEnum(SEI->getLoc(), UED, EnumElement, EnumTy);
}
return Builder.createEnum(SEI->getLoc(), SILValue(), EnumElement, EnumTy);
}
/// Create a value for the condition of the terminator that flows along the edge
/// with 'EdgeIdx'. Insert it before the 'UserInst'.
static SILInstruction *createValueForEdge(SILInstruction *UserInst,
SILInstruction *DominatingTerminator,
unsigned EdgeIdx) {
SILBuilderWithScope Builder(UserInst);
if (auto *CBI = dyn_cast<CondBranchInst>(DominatingTerminator))
return Builder.createIntegerLiteral(
CBI->getLoc(), CBI->getCondition()->getType(), EdgeIdx == 0 ? -1 : 0);
auto *SEI = cast<SwitchEnumInst>(DominatingTerminator);
auto *DstBlock = SEI->getSuccessors()[EdgeIdx].getBB();
auto Case = SEI->getUniqueCaseForDestination(DstBlock);
assert(Case && "No unique case found for destination block");
return createEnumElement(Builder, SEI, Case.get());
}
/// Perform dominator based value simplifications and jump threading on all users
/// of the operand of 'DominatingBB's terminator.
static bool tryDominatorBasedSimplifications(
SILBasicBlock *DominatingBB, DominanceInfo *DT,
SmallPtrSet<SILBasicBlock *, 32> &LoopHeaders,
SmallVectorImpl<ThreadInfo> &JumpThreadableEdges,
llvm::DenseSet<std::pair<SILBasicBlock *, SILBasicBlock *>>
&ThreadedEdgeSet,
bool TryJumpThreading,
llvm::DenseMap<SILBasicBlock *, bool> &CachedThreadable) {
auto *DominatingTerminator = DominatingBB->getTerminator();
// We handle value propagation from cond_br and switch_enum terminators.
bool IsEnumValue = isa<SwitchEnumInst>(DominatingTerminator);
if (!isa<CondBranchInst>(DominatingTerminator) && !IsEnumValue)
return false;
auto DominatingCondition = getTerminatorCondition(DominatingTerminator);
if (!DominatingCondition)
return false;
if (isa<SILUndef>(DominatingCondition))
return false;
bool Changed = false;
// We will look at all the outgoing edges from the conditional branch to see
// whether any other uses of the condition or uses of the condition along an
// edge are dominated by said outgoing edges. The outgoing edge carries the
// value on which we switch/cond_branch.
auto Succs = DominatingBB->getSuccessors();
for (unsigned Idx = 0; Idx < Succs.size(); ++Idx) {
auto *DominatingSuccBB = Succs[Idx].getBB();
EnumElementDecl *EnumCase = nullptr;
if (!isKnownEdgeValue(DominatingTerminator, DominatingSuccBB, EnumCase))
continue;
// Look for other uses of DominatingCondition that are either:
// * dominated by the DominatingSuccBB
//
// cond_br %dominating_cond / switch_enum
// /
// /
// /
// DominatingSuccBB:
// ...
// use %dominating_cond
//
// * are a conditional branch that has an incoming edge that is
// dominated by DominatingSuccBB.
//
// cond_br %dominating_cond
// /
// /
// /
//
// DominatingSuccBB:
// ...
// br DestBB
//
// \
// \ E -> %dominating_cond = true
// \
// v
// DestBB
// cond_br %dominating_cond
SmallVector<SILInstruction *, 16> UsersToReplace;
for (auto *Op : ignore_expect_uses(DominatingCondition)) {
auto *CondUserInst = Op->getUser();
// Ignore the DominatingTerminator itself.
if (CondUserInst->getParent() == DominatingBB)
continue;
// For enum values we are only interested in switch_enum and select_enum
// users.
if (IsEnumValue && !isa<SwitchEnumInst>(CondUserInst) &&
!isa<SelectEnumInst>(CondUserInst))
continue;
// If the use is dominated we can replace this use by the value
// flowing to DominatingSuccBB.
if (DT->dominates(DominatingSuccBB, CondUserInst->getParent())) {
UsersToReplace.push_back(CondUserInst);
continue;
}
// Jump threading is expensive so we don't always do it.
if (!TryJumpThreading)
continue;
auto *DestBB = CondUserInst->getParent();
// The user must be the terminator we are trying to jump thread.
if (CondUserInst != DestBB->getTerminator())
continue;
// Check whether we have seen this destination block already.
auto CacheEntryIt = CachedThreadable.find(DestBB);
bool IsThreadable = CacheEntryIt != CachedThreadable.end()
? CacheEntryIt->second
: (CachedThreadable[DestBB] =
isThreadableBlock(DestBB, LoopHeaders));
// If the use is a conditional branch/switch then look for an incoming
// edge that is dominated by DominatingSuccBB.
if (IsThreadable) {
auto Preds = DestBB->getPredecessorBlocks();
for (SILBasicBlock *PredBB : Preds) {
if (!isa<BranchInst>(PredBB->getTerminator()))
continue;
if (!DT->dominates(DominatingSuccBB, PredBB))
continue;
// Don't jumpthread the same edge twice.
if (!ThreadedEdgeSet.insert(std::make_pair(PredBB, DestBB)).second)
continue;
if (isa<CondBranchInst>(DestBB->getTerminator()))
JumpThreadableEdges.push_back(ThreadInfo(PredBB, DestBB, Idx));
else
JumpThreadableEdges.push_back(ThreadInfo(PredBB, DestBB, EnumCase));
break;
}
}
}
// Replace dominated user instructions.
for (auto *UserInst : UsersToReplace) {
SILInstruction *EdgeValue = nullptr;
for (auto &Op : UserInst->getAllOperands()) {
if (stripExpectIntrinsic(Op.get()) == DominatingCondition) {
if (!EdgeValue)
EdgeValue = createValueForEdge(UserInst, DominatingTerminator, Idx);
Op.set(EdgeValue);
Changed = true;
}
}
}
}
return Changed;
}
/// Propagate values of branched upon values along the outgoing edges down the
/// dominator tree.
bool SimplifyCFG::dominatorBasedSimplifications(SILFunction &Fn,
DominanceInfo *DT) {
bool Changed = false;
// Collect jump threadable edges and propagate outgoing edge values of
// conditional branches/switches.
SmallVector<ThreadInfo, 8> JumpThreadableEdges;
llvm::DenseMap<SILBasicBlock *, bool> CachedThreadable;
llvm::DenseSet<std::pair<SILBasicBlock *, SILBasicBlock *>> ThreadedEdgeSet;
for (auto &BB : Fn)
if (DT->getNode(&BB)) // Only handle reachable blocks.
Changed |= tryDominatorBasedSimplifications(
&BB, DT, LoopHeaders, JumpThreadableEdges, ThreadedEdgeSet,
EnableJumpThread, CachedThreadable);
// Nothing to jump thread?
if (JumpThreadableEdges.empty())
return Changed;
for (auto &ThreadInfo : JumpThreadableEdges) {
ThreadInfo.threadEdge();
Changed = true;
}
return Changed;
}
/// Simplify terminators that could have been simplified by threading.
bool SimplifyCFG::simplifyThreadedTerminators() {
bool HaveChangedCFG = false;
for (auto &BB : Fn) {
auto *Term = BB.getTerminator();
// Simplify a switch_enum.
if (auto *SEI = dyn_cast<SwitchEnumInst>(Term)) {
if (auto *EI = dyn_cast<EnumInst>(SEI->getOperand())) {
DEBUG(llvm::dbgs() << "simplify threaded " << *SEI);
auto *LiveBlock = SEI->getCaseDestination(EI->getElement());
if (EI->hasOperand() && !LiveBlock->args_empty())
SILBuilderWithScope(SEI)
.createBranch(SEI->getLoc(), LiveBlock, EI->getOperand());
else
SILBuilderWithScope(SEI).createBranch(SEI->getLoc(), LiveBlock);
SEI->eraseFromParent();
if (EI->use_empty())
EI->eraseFromParent();
HaveChangedCFG = true;
}
continue;
} else if (auto *CondBr = dyn_cast<CondBranchInst>(Term)) {
// If the condition is an integer literal, we can constant fold the
// branch.
if (auto *IL = dyn_cast<IntegerLiteralInst>(CondBr->getCondition())) {
DEBUG(llvm::dbgs() << "simplify threaded " << *CondBr);
SILBasicBlock *TrueSide = CondBr->getTrueBB();
SILBasicBlock *FalseSide = CondBr->getFalseBB();
auto TrueArgs = CondBr->getTrueArgs();
auto FalseArgs = CondBr->getFalseArgs();
bool isFalse = !IL->getValue();
auto LiveArgs = isFalse ? FalseArgs : TrueArgs;
auto *LiveBlock = isFalse ? FalseSide : TrueSide;
SILBuilderWithScope(CondBr)
.createBranch(CondBr->getLoc(), LiveBlock, LiveArgs);
CondBr->eraseFromParent();
if (IL->use_empty())
IL->eraseFromParent();
HaveChangedCFG = true;
}
}
}
return HaveChangedCFG;
}
// Simplifications that walk the dominator tree to prove redundancy in
// conditional branching.
bool SimplifyCFG::dominatorBasedSimplify(DominanceAnalysis *DA) {
// Get the dominator tree.
DT = DA->get(&Fn);
// Split all critical edges such that we can move code onto edges. This is
// also required for SSA construction in dominatorBasedSimplifications' jump
// threading. It only splits new critical edges it creates by jump threading.
bool Changed =
EnableJumpThread ? splitAllCriticalEdges(Fn, false, DT, nullptr) : false;
unsigned MaxIter = MaxIterationsOfDominatorBasedSimplify;
SmallVector<SILBasicBlock *, 16> BlocksForWorklist;
bool HasChangedInCurrentIter;
do {
HasChangedInCurrentIter = false;
// Do dominator based simplification of terminator condition. This does not
// and MUST NOT change the CFG without updating the dominator tree to
// reflect such change.
if (tryCheckedCastBrJumpThreading(&Fn, DT, BlocksForWorklist)) {
for (auto BB: BlocksForWorklist)
addToWorklist(BB);
HasChangedInCurrentIter = true;
DT->recalculate(Fn);
}
BlocksForWorklist.clear();
if (ShouldVerify)
DT->verify();
// Simplify the block argument list. This is extremely subtle: simplifyArgs
// will not change the CFG iff the DT is null. Really we should move that
// one optimization out of simplifyArgs ... I am squinting at you
// simplifySwitchEnumToSelectEnum.
// simplifyArgs does use the dominator tree, though.
for (auto &BB : Fn)
HasChangedInCurrentIter |= simplifyArgs(&BB);
if (ShouldVerify)
DT->verify();
// Jump thread.
if (dominatorBasedSimplifications(Fn, DT)) {
DominanceInfo *InvalidDT = DT;
DT = nullptr;
HasChangedInCurrentIter = true;
// Simplify terminators.
simplifyThreadedTerminators();
DT = InvalidDT;
DT->recalculate(Fn);
}
Changed |= HasChangedInCurrentIter;
} while (HasChangedInCurrentIter && --MaxIter);
// Do the simplification that requires both the dom and postdom tree.
for (auto &BB : Fn)
Changed |= simplifyArgs(&BB);
if (ShouldVerify)
DT->verify();
// The functions we used to simplify the CFG put things in the worklist. Clear
// it here.
clearWorklist();
return Changed;
}
// If BB is trivially unreachable, remove it from the worklist, add its
// successors to the worklist, and then remove the block.
bool SimplifyCFG::removeIfDead(SILBasicBlock *BB) {
if (!BB->pred_empty() || BB == &*Fn.begin())
return false;
removeFromWorklist(BB);
// Add successor blocks to the worklist since their predecessor list is about
// to change.
for (auto &S : BB->getSuccessors())
addToWorklist(S);
DEBUG(llvm::dbgs() << "remove dead bb" << BB->getDebugID() << '\n');
removeDeadBlock(BB);
++NumBlocksDeleted;
return true;
}
/// This is called when a predecessor of a block is dropped, to simplify the
/// block and add it to the worklist.
bool SimplifyCFG::simplifyAfterDroppingPredecessor(SILBasicBlock *BB) {
// TODO: If BB has only one predecessor and has bb args, fold them away, then
// use instsimplify on all the users of those values - even ones outside that
// block.
// Make sure that DestBB is in the worklist, as well as its remaining
// predecessors, since they may not be able to be simplified.
addToWorklist(BB);
for (auto *P : BB->getPredecessorBlocks())
addToWorklist(P);
return false;
}
static NullablePtr<EnumElementDecl>
getEnumCaseRecursive(SILValue Val, SILBasicBlock *UsedInBB, int RecursionDepth,
llvm::SmallPtrSet<SILArgument *, 8> HandledArgs) {
// Limit the number of recursions. This is an easy way to cope with cycles
// in the SSA graph.
if (RecursionDepth > 3)
return nullptr;
// Handle the obvious case.
if (auto *EI = dyn_cast<EnumInst>(Val))
return EI->getElement();
// Check if the value is dominated by a switch_enum, e.g.
// switch_enum %val, case A: bb1, case B: bb2
// bb1:
// use %val // We know that %val has case A
SILBasicBlock *Pred = UsedInBB->getSinglePredecessorBlock();
int Limit = 3;
// A very simple dominator check: just walk up the single predecessor chain.
// The limit is just there to not run into an infinite loop in case of an
// unreachable CFG cycle.
while (Pred && --Limit > 0) {
if (auto *PredSEI = dyn_cast<SwitchEnumInst>(Pred->getTerminator())) {
if (PredSEI->getOperand() == Val)
return PredSEI->getUniqueCaseForDestination(UsedInBB);
}
UsedInBB = Pred;
Pred = UsedInBB->getSinglePredecessorBlock();
}
// In case of a block argument, recursively check the enum cases of all
// incoming predecessors.
if (auto *Arg = dyn_cast<SILArgument>(Val)) {
HandledArgs.insert(Arg);
llvm::SmallVector<std::pair<SILBasicBlock *, SILValue>, 8> IncomingVals;
if (!Arg->getIncomingValues(IncomingVals))
return nullptr;
EnumElementDecl *CommonCase = nullptr;
for (std::pair<SILBasicBlock *, SILValue> Incoming : IncomingVals) {
SILBasicBlock *IncomingBlock = Incoming.first;
SILValue IncomingVal = Incoming.second;
TermInst *TI = IncomingBlock->getTerminator();
// If the terminator of the incoming value is e.g. a switch_enum, the
// incoming value is the switch_enum operand and not the enum payload
// (which would be the real incoming value of the argument).
if (!isa<BranchInst>(TI) && !isa<CondBranchInst>(TI))
return nullptr;
auto *IncomingArg = dyn_cast<SILArgument>(IncomingVal);
if (IncomingArg && HandledArgs.count(IncomingArg) != 0)
continue;
NullablePtr<EnumElementDecl> IncomingCase =
getEnumCaseRecursive(Incoming.second, IncomingBlock, RecursionDepth + 1,
HandledArgs);
if (!IncomingCase)
return nullptr;
if (IncomingCase.get() != CommonCase) {
if (CommonCase)
return nullptr;
CommonCase = IncomingCase.get();
}
}
return CommonCase;
}
return nullptr;
}
/// Tries to figure out the enum case of an enum value \p Val which is used in
/// block \p UsedInBB.
static NullablePtr<EnumElementDecl> getEnumCase(SILValue Val,
SILBasicBlock *UsedInBB) {
llvm::SmallPtrSet<SILArgument *, 8> HandledArgs;
return getEnumCaseRecursive(Val, UsedInBB, /*RecursionDepth*/ 0, HandledArgs);
}
static int getThreadingCost(SILInstruction *I) {
if (!isa<DeallocStackInst>(I) && !I->isTriviallyDuplicatable())
return 1000;
// Don't jumpthread function calls.
if (isa<ApplyInst>(I))
return 1000;
// This is a really trivial cost model, which is only intended as a starting
// point.
if (instructionInlineCost(*I) != InlineCost::Free)
return 1;
return 0;
}
/// couldSimplifyUsers - Check to see if any simplifications are possible if
/// "Val" is substituted for BBArg. If so, return true, if nothing obvious
/// is possible, return false.
static bool couldSimplifyEnumUsers(SILArgument *BBArg, int Budget) {
SILBasicBlock *BB = BBArg->getParent();
int BudgetForBranch = 100;
for (Operand *UI : BBArg->getUses()) {
auto *User = UI->getUser();
if (User->getParent() != BB)
continue;
// We only know we can simplify if the switch_enum user is in the block we
// are trying to jump thread.
// The value must not be define in the same basic block as the switch enum
// user. If this is the case we have a single block switch_enum loop.
if (isa<SwitchEnumInst>(User) || isa<SelectEnumInst>(User))
return true;
// Also allow enum of enum, which usually can be combined to a single
// instruction. This helps to simplify the creation of an enum from an
// integer raw value.
if (isa<EnumInst>(User))
return true;
if (auto *SWI = dyn_cast<SwitchValueInst>(User)) {
if (SWI->getOperand() == BBArg)
return true;
}
if (auto *BI = dyn_cast<BranchInst>(User)) {
if (BudgetForBranch > Budget) {
BudgetForBranch = Budget;
for (SILInstruction &I : *BB) {
BudgetForBranch -= getThreadingCost(&I);
if (BudgetForBranch < 0)
break;
}
}
if (BudgetForBranch > 0) {
SILBasicBlock *DestBB = BI->getDestBB();
unsigned OpIdx = UI->getOperandNumber();
if (couldSimplifyEnumUsers(DestBB->getArgument(OpIdx), BudgetForBranch))
return true;
}
}
}
return false;
}
void SimplifyCFG::findLoopHeaders() {
/// Find back edges in the CFG. This performs a dfs search and identifies
/// back edges as edges going to an ancestor in the dfs search. If a basic
/// block is the target of such a back edge we will identify it as a header.
LoopHeaders.clear();
SmallPtrSet<SILBasicBlock *, 16> Visited;
SmallPtrSet<SILBasicBlock *, 16> InDFSStack;
SmallVector<std::pair<SILBasicBlock *, SILBasicBlock::succ_iterator>, 16>
DFSStack;
auto EntryBB = &Fn.front();
DFSStack.push_back(std::make_pair(EntryBB, EntryBB->succ_begin()));
Visited.insert(EntryBB);
InDFSStack.insert(EntryBB);
while (!DFSStack.empty()) {
auto &D = DFSStack.back();
// No successors.
if (D.second == D.first->succ_end()) {
// Retreat the dfs search.
DFSStack.pop_back();
InDFSStack.erase(D.first);
} else {
// Visit the next successor.
SILBasicBlock *NextSucc = *(D.second);
++D.second;
if (Visited.insert(NextSucc).second) {
InDFSStack.insert(NextSucc);
DFSStack.push_back(std::make_pair(NextSucc, NextSucc->succ_begin()));
} else if (InDFSStack.count(NextSucc)) {
// We have already visited this node and it is in our dfs search. This
// is a back-edge.
LoopHeaders.insert(NextSucc);
}
}
}
}
/// tryJumpThreading - Check to see if it looks profitable to duplicate the
/// destination of an unconditional jump into the bottom of this block.
bool SimplifyCFG::tryJumpThreading(BranchInst *BI) {
auto *DestBB = BI->getDestBB();
auto *SrcBB = BI->getParent();
// If the destination block ends with a return, we don't want to duplicate it.
// We want to maintain the canonical form of a single return where possible.
if (isa<ReturnInst>(DestBB->getTerminator()))
return false;
// We need to update SSA if a value duplicated is used outside of the
// duplicated block.
bool NeedToUpdateSSA = false;
// Are the arguments to this block used outside of the block.
for (auto Arg : DestBB->getArguments())
if ((NeedToUpdateSSA |= isUsedOutsideOfBlock(Arg, DestBB))) {
break;
}
// We don't have a great cost model at the SIL level, so we don't want to
// blissly duplicate tons of code with a goal of improved performance (we'll
// leave that to LLVM). However, doing limited code duplication can lead to
// major second order simplifications. Here we only do it if there are
// "constant" arguments to the branch or if we know how to fold something
// given the duplication.
int ThreadingBudget = 0;
for (unsigned i = 0, e = BI->getArgs().size(); i != e; ++i) {
// If the value being substituted is an enum, check to see if there are any
// switches on it.
SILValue Arg = BI->getArg(i);
if (!getEnumCase(Arg, BI->getParent()) &&
!isa<IntegerLiteralInst>(Arg))
continue;
if (couldSimplifyEnumUsers(DestBB->getArgument(i), 8)) {
ThreadingBudget = 8;
break;
}
}
if (ThreadingBudget == 0 && isa<CondBranchInst>(DestBB->getTerminator())) {
for (auto V : BI->getArgs()) {
if (isa<IntegerLiteralInst>(V) || isa<FloatLiteralInst>(V)) {
ThreadingBudget = 4;
break;
}
}
}
// If we don't have anything that we can simplify, don't do it.
if (ThreadingBudget == 0)
return false;
// If it looks potentially interesting, decide whether we *can* do the
// operation and whether the block is small enough to be worth duplicating.
for (auto &Inst : *DestBB) {
ThreadingBudget -= getThreadingCost(&Inst);
if (ThreadingBudget <= 0)
return false;
// We need to update ssa if a value is used outside the duplicated block.
if (!NeedToUpdateSSA)
NeedToUpdateSSA |= isUsedOutsideOfBlock(&Inst, DestBB);
}
// Don't jump thread through a potential header - this can produce irreducible
// control flow. Still, we make an exception for switch_enum.
bool DestIsLoopHeader = (LoopHeaders.count(DestBB) != 0);
if (DestIsLoopHeader) {
if (!isa<SwitchEnumInst>(DestBB->getTerminator()))
return false;
}
// Limit the number we jump-thread through a block.
// Otherwise we may end up with jump-threading indefinitely.
unsigned &NumThreaded = JumpThreadedBlocks[DestBB];
if (++NumThreaded > 16)
return false;
DEBUG(llvm::dbgs() << "jump thread from bb" << SrcBB->getDebugID() <<
" to bb" << DestBB->getDebugID() << '\n');
// Okay, it looks like we want to do this and we can. Duplicate the
// destination block into this one, rewriting uses of the BBArgs to use the
// branch arguments as we go.
EdgeThreadingCloner Cloner(BI);
for (auto &I : *DestBB)
Cloner.process(&I);
// Once all the instructions are copied, we can nuke BI itself. We also add
// the threaded and edge block to the worklist now that they (likely) can be
// simplified.
addToWorklist(SrcBB);
addToWorklist(Cloner.getEdgeBB());
if (NeedToUpdateSSA)
updateSSAAfterCloning(Cloner, Cloner.getEdgeBB(), DestBB);
// We may be able to simplify DestBB now that it has one fewer predecessor.
simplifyAfterDroppingPredecessor(DestBB);
// If we jump-thread a switch_enum in the loop header, we have to recalculate
// the loop header info.
if (DestIsLoopHeader)
findLoopHeaders();
++NumJumpThreads;
return true;
}
/// simplifyBranchOperands - Simplify operands of branches, since it can
/// result in exposing opportunities for CFG simplification.
bool SimplifyCFG::simplifyBranchOperands(OperandValueArrayRef Operands) {
bool Simplified = false;
for (auto O = Operands.begin(), E = Operands.end(); O != E; ++O)
if (auto *I = dyn_cast<SILInstruction>(*O))
if (SILValue Result = simplifyInstruction(I)) {
DEBUG(llvm::dbgs() << "simplify branch operand " << *I);
I->replaceAllUsesWith(Result);
if (isInstructionTriviallyDead(I)) {
eraseFromParentWithDebugInsts(I);
Simplified = true;
}
}
return Simplified;
}
static bool onlyHasTerminatorAndDebugInsts(SILBasicBlock *BB) {
TermInst *Terminator = BB->getTerminator();
SILBasicBlock::iterator Iter = BB->begin();
while (&*Iter != Terminator) {
if (!isDebugInst(&*Iter))
return false;
Iter++;
}
return true;
}
/// \return If this basic blocks has a single br instruction passing all of the
/// arguments in the original order, then returns the destination of that br.
static SILBasicBlock *getTrampolineDest(SILBasicBlock *SBB) {
// Ignore blocks with more than one instruction.
if (!onlyHasTerminatorAndDebugInsts(SBB))
return nullptr;
auto *BI = dyn_cast<BranchInst>(SBB->getTerminator());
if (!BI)
return nullptr;
// Disallow infinite loops through SBB.
llvm::SmallPtrSet<SILBasicBlock *, 8> VisitedBBs;
BranchInst *NextBI = BI;
do {
SILBasicBlock *NextBB = NextBI->getDestBB();
// We don't care about infinite loops after SBB.
if (!VisitedBBs.insert(NextBB).second)
break;
// Only if the infinite loop goes through SBB directly we bail.
if (NextBB == SBB)
return nullptr;
NextBI = dyn_cast<BranchInst>(NextBB->getTerminator());
} while (NextBI);
auto BrArgs = BI->getArgs();
if (BrArgs.size() != SBB->getNumArguments())
return nullptr;
// Check that the arguments are the same and in the right order.
for (int i = 0, e = SBB->getNumArguments(); i < e; ++i) {
SILArgument *BBArg = SBB->getArgument(i);
if (BrArgs[i] != BBArg)
return nullptr;
// The arguments may not be used in another block, because when the
// predecessor of SBB directly jumps to the successor, the SBB block does
// not dominate the other use anymore.
if (!BBArg->hasOneUse())
return nullptr;
}
return BI->getDestBB();
}
/// \return If this is a basic block without any arguments and it has
/// a single br instruction, return this br.
static BranchInst *getTrampolineWithoutBBArgsTerminator(SILBasicBlock *SBB) {
if (!SBB->args_empty())
return nullptr;
// Ignore blocks with more than one instruction.
if (!onlyHasTerminatorAndDebugInsts(SBB))
return nullptr;
auto *BI = dyn_cast<BranchInst>(SBB->getTerminator());
if (!BI)
return nullptr;
// Disallow infinite loops.
if (BI->getDestBB() == SBB)
return nullptr;
return BI;
}
#ifndef NDEBUG
/// Is the block reachable from the entry.
static bool isReachable(SILBasicBlock *Block) {
SmallPtrSet<SILBasicBlock *, 16> Visited;
llvm::SmallVector<SILBasicBlock *, 16> Worklist;
SILBasicBlock *EntryBB = &*Block->getParent()->begin();
Worklist.push_back(EntryBB);
Visited.insert(EntryBB);
while (!Worklist.empty()) {
auto *CurBB = Worklist.back();
Worklist.pop_back();
if (CurBB == Block)
return true;
for (auto &Succ : CurBB->getSuccessors())
// Second is true if the insertion took place.
if (Visited.insert(Succ).second)
Worklist.push_back(Succ);
}
return false;
}
#endif
/// simplifyBranchBlock - Simplify a basic block that ends with an unconditional
/// branch.
bool SimplifyCFG::simplifyBranchBlock(BranchInst *BI) {
// First simplify instructions generating branch operands since that
// can expose CFG simplifications.
bool Simplified = simplifyBranchOperands(BI->getArgs());
auto *BB = BI->getParent(), *DestBB = BI->getDestBB();
// If this block branches to a block with a single predecessor, then
// merge the DestBB into this BB.
if (BB != DestBB && DestBB->getSinglePredecessorBlock()) {
DEBUG(llvm::dbgs() << "merge bb" << BB->getDebugID() << " with bb" <<
DestBB->getDebugID() << '\n');
// If there are any BB arguments in the destination, replace them with the
// branch operands, since they must dominate the dest block.
for (unsigned i = 0, e = BI->getArgs().size(); i != e; ++i) {
if (DestBB->getArgument(i) != BI->getArg(i))
DestBB->getArgument(i)->replaceAllUsesWith(BI->getArg(i));
else {
// We must be processing an unreachable part of the cfg with a cycle.
// bb1(arg1): // preds: bb3
// br bb2
//
// bb2: // preds: bb1
// br bb3
//
// bb3: // preds: bb2
// br bb1(arg1)
assert(!isReachable(BB) && "Should only occur in unreachable block");
}
}
// Zap BI and move all of the instructions from DestBB into this one.
BI->eraseFromParent();
BB->spliceAtEnd(DestBB);
// Revisit this block now that we've changed it and remove the DestBB.
addToWorklist(BB);
// This can also expose opportunities in the successors of
// the merged block.
for (auto &Succ : BB->getSuccessors())
addToWorklist(Succ);
if (LoopHeaders.count(DestBB))
LoopHeaders.insert(BB);
removeFromWorklist(DestBB);
DestBB->eraseFromParent();
++NumBlocksMerged;
return true;
}
// If the destination block is a simple trampoline (jump to another block)
// then jump directly.
if (SILBasicBlock *TrampolineDest = getTrampolineDest(DestBB)) {
DEBUG(llvm::dbgs() << "jump to trampoline from bb" << BB->getDebugID() <<
" to bb" << TrampolineDest->getDebugID() << '\n');
SILBuilderWithScope(BI).createBranch(BI->getLoc(), TrampolineDest,
BI->getArgs());
// Eliminating the trampoline can expose opportunities to improve the
// new block we branch to.
if (LoopHeaders.count(DestBB))
LoopHeaders.insert(BB);
addToWorklist(TrampolineDest);
BI->eraseFromParent();
removeIfDead(DestBB);
addToWorklist(BB);
return true;
}
// If this unconditional branch has BBArgs, check to see if duplicating the
// destination would allow it to be simplified. This is a simple form of jump
// threading.
if (!BI->getArgs().empty() &&
tryJumpThreading(BI))
return true;
return Simplified;
}
/// \brief Check if replacing an existing edge of the terminator by another
/// one which has a DestBB as its destination would create a critical edge.
static bool wouldIntroduceCriticalEdge(TermInst *T, SILBasicBlock *DestBB) {
auto SrcSuccs = T->getSuccessors();
if (SrcSuccs.size() <= 1)
return false;
assert(!DestBB->pred_empty() && "There should be a predecessor");
if (DestBB->getSinglePredecessorBlock())
return false;
return true;
}
/// Returns the original boolean value, looking through possible invert
/// builtins. The parameter \p Inverted is inverted if the returned original
/// value is the inverted value of the passed \p Cond.
/// If \p onlyAcceptSingleUse is true and the operand of an invert builtin has
/// more than one use, an invalid SILValue() is returned.
static SILValue skipInvert(SILValue Cond, bool &Inverted,
bool onlyAcceptSingleUse) {
while (auto *BI = dyn_cast<BuiltinInst>(Cond)) {
if (onlyAcceptSingleUse && !BI->hasOneUse())
return SILValue();
OperandValueArrayRef Args = BI->getArguments();
if (BI->getBuiltinInfo().ID == BuiltinValueKind::Xor) {
// Check if it's a boolean inversion of the condition.
if (auto *IL = dyn_cast<IntegerLiteralInst>(Args[1])) {
if (IL->getValue().isAllOnesValue()) {
Cond = Args[0];
Inverted = !Inverted;
continue;
}
} else if (auto *IL = dyn_cast<IntegerLiteralInst>(Args[0])) {
if (IL->getValue().isAllOnesValue()) {
Cond = Args[1];
Inverted = !Inverted;
continue;
}
}
}
break;
}
return Cond;
}
/// \brief Returns the first cond_fail if it is the first side-effect
/// instruction in this block.
static CondFailInst *getFirstCondFail(SILBasicBlock *BB) {
auto It = BB->begin();
CondFailInst *CondFail = nullptr;
// Skip instructions that don't have side-effects.
while (It != BB->end() && !(CondFail = dyn_cast<CondFailInst>(It))) {
if (It->mayHaveSideEffects())
return nullptr;
++It;
}
return CondFail;
}
/// If the first side-effect instruction in this block is a cond_fail that
/// is guaranteed to fail, it is returned.
/// The \p Cond is the condition from a cond_br in the predecessor block. The
/// cond_fail must only fail if \p BB is entered through this predecessor block.
/// If \p Inverted is true, \p BB is on the false-edge of the cond_br.
static CondFailInst *getUnConditionalFail(SILBasicBlock *BB, SILValue Cond,
bool Inverted) {
CondFailInst *CondFail = getFirstCondFail(BB);
if (!CondFail)
return nullptr;
// The simple case: check if it is a "cond_fail 1".
auto *IL = dyn_cast<IntegerLiteralInst>(CondFail->getOperand());
if (IL && IL->getValue() != 0)
return CondFail;
// Check if the cond_fail has the same condition as the cond_br in the
// predecessor block.
Cond = skipInvert(Cond, Inverted, false);
SILValue CondFailCond = skipInvert(CondFail->getOperand(), Inverted, false);
if (Cond == CondFailCond && !Inverted)
return CondFail;
return nullptr;
}
/// \brief Creates a new cond_fail instruction, optionally with an xor inverted
/// condition.
static void createCondFail(CondFailInst *Orig, SILValue Cond, bool inverted,
SILBuilder &Builder) {
if (inverted) {
auto *True = Builder.createIntegerLiteral(Orig->getLoc(), Cond->getType(), 1);
Cond = Builder.createBuiltinBinaryFunction(Orig->getLoc(), "xor",
Cond->getType(), Cond->getType(),
{Cond, True});
}
Builder.createCondFail(Orig->getLoc(), Cond);
}
/// Inverts the expected value of 'PotentialExpect' (if it is an expect
/// intrinsic) and returns this expected value apply to 'V'.
static SILValue invertExpectAndApplyTo(SILBuilder &Builder,
SILValue PotentialExpect, SILValue V) {
auto *BI = dyn_cast<BuiltinInst>(PotentialExpect);
if (!BI)
return V;
if (BI->getIntrinsicInfo().ID != llvm::Intrinsic::expect)
return V;
auto Args = BI->getArguments();
auto *IL = dyn_cast<IntegerLiteralInst>(Args[1]);
if (!IL)
return V;
SILValue NegatedExpectedValue = Builder.createIntegerLiteral(
IL->getLoc(), Args[1]->getType(), IL->getValue() == 0 ? -1 : 0);
return Builder.createBuiltin(BI->getLoc(), BI->getName(), BI->getType(), {},
{V, NegatedExpectedValue});
}
/// simplifyCondBrBlock - Simplify a basic block that ends with a conditional
/// branch.
bool SimplifyCFG::simplifyCondBrBlock(CondBranchInst *BI) {
// First simplify instructions generating branch operands since that
// can expose CFG simplifications.
simplifyBranchOperands(OperandValueArrayRef(BI->getAllOperands()));
auto *ThisBB = BI->getParent();
SILBasicBlock *TrueSide = BI->getTrueBB();
SILBasicBlock *FalseSide = BI->getFalseBB();
auto TrueArgs = BI->getTrueArgs();
auto FalseArgs = BI->getFalseArgs();
// If the condition is an integer literal, we can constant fold the branch.
if (auto *IL = dyn_cast<IntegerLiteralInst>(BI->getCondition())) {
bool isFalse = !IL->getValue();
auto LiveArgs = isFalse ? FalseArgs : TrueArgs;
auto *LiveBlock = isFalse ? FalseSide : TrueSide;
auto *DeadBlock = !isFalse ? FalseSide : TrueSide;
DEBUG(llvm::dbgs() << "replace cond_br with br: " << *BI);
SILBuilderWithScope(BI).createBranch(BI->getLoc(), LiveBlock, LiveArgs);
BI->eraseFromParent();
if (IL->use_empty()) IL->eraseFromParent();
addToWorklist(ThisBB);
simplifyAfterDroppingPredecessor(DeadBlock);
addToWorklist(LiveBlock);
++NumConstantFolded;
return true;
}
// Canonicalize "cond_br (not %cond), BB1, BB2" to "cond_br %cond, BB2, BB1".
// This looks through expect intrinsic calls and applies the ultimate expect
// call inverted to the condition.
if (auto *Xor =
dyn_cast<BuiltinInst>(stripExpectIntrinsic(BI->getCondition()))) {
if (Xor->getBuiltinInfo().ID == BuiltinValueKind::Xor) {
// Check if it's a boolean inversion of the condition.
OperandValueArrayRef Args = Xor->getArguments();
if (auto *IL = dyn_cast<IntegerLiteralInst>(Args[1])) {
if (IL->getValue().isAllOnesValue()) {
DEBUG(llvm::dbgs() << "canonicalize cond_br: " << *BI);
auto Cond = Args[0];
SILBuilderWithScope Builder(BI);
Builder.createCondBranch(
BI->getLoc(),
invertExpectAndApplyTo(Builder, BI->getCondition(), Cond),
FalseSide, FalseArgs, TrueSide, TrueArgs);
BI->eraseFromParent();
addToWorklist(ThisBB);
return true;
}
}
}
}
// If the destination block is a simple trampoline (jump to another block)
// then jump directly.
SILBasicBlock *TrueTrampolineDest = getTrampolineDest(TrueSide);
if (TrueTrampolineDest && TrueTrampolineDest != FalseSide) {
DEBUG(llvm::dbgs() << "true-trampoline from bb" << ThisBB->getDebugID() <<
" to bb" << TrueTrampolineDest->getDebugID() << '\n');
SILBuilderWithScope(BI)
.createCondBranch(BI->getLoc(), BI->getCondition(),
TrueTrampolineDest, TrueArgs,
FalseSide, FalseArgs);
BI->eraseFromParent();
if (LoopHeaders.count(TrueSide))
LoopHeaders.insert(ThisBB);
removeIfDead(TrueSide);
addToWorklist(ThisBB);
return true;
}
SILBasicBlock *FalseTrampolineDest = getTrampolineDest(FalseSide);
if (FalseTrampolineDest && FalseTrampolineDest != TrueSide) {
DEBUG(llvm::dbgs() << "false-trampoline from bb" << ThisBB->getDebugID() <<
" to bb" << FalseTrampolineDest->getDebugID() << '\n');
SILBuilderWithScope(BI)
.createCondBranch(BI->getLoc(), BI->getCondition(),
TrueSide, TrueArgs,
FalseTrampolineDest, FalseArgs);
BI->eraseFromParent();
if (LoopHeaders.count(FalseSide))
LoopHeaders.insert(ThisBB);
removeIfDead(FalseSide);
addToWorklist(ThisBB);
return true;
}
// Simplify cond_br where both sides jump to the same blocks with the same
// args.
if (TrueArgs == FalseArgs && (TrueSide == FalseTrampolineDest ||
FalseSide == TrueTrampolineDest)) {
DEBUG(llvm::dbgs() << "replace cond_br with same dests with br: " << *BI);
SILBuilderWithScope(BI).createBranch(BI->getLoc(),
TrueTrampolineDest ? FalseSide : TrueSide, TrueArgs);
BI->eraseFromParent();
addToWorklist(ThisBB);
addToWorklist(TrueSide);
++NumConstantFolded;
return true;
}
auto *TrueTrampolineBr = getTrampolineWithoutBBArgsTerminator(TrueSide);
if (TrueTrampolineBr &&
!wouldIntroduceCriticalEdge(BI, TrueTrampolineBr->getDestBB())) {
DEBUG(llvm::dbgs() << "true-trampoline from bb" << ThisBB->getDebugID() <<
" to bb" << TrueTrampolineBr->getDestBB()->getDebugID() << '\n');
SILBuilderWithScope(BI).createCondBranch(
BI->getLoc(), BI->getCondition(),
TrueTrampolineBr->getDestBB(), TrueTrampolineBr->getArgs(),
FalseSide, FalseArgs);
BI->eraseFromParent();
if (LoopHeaders.count(TrueSide))
LoopHeaders.insert(ThisBB);
removeIfDead(TrueSide);
addToWorklist(ThisBB);
return true;
}
auto *FalseTrampolineBr = getTrampolineWithoutBBArgsTerminator(FalseSide);
if (FalseTrampolineBr &&
!wouldIntroduceCriticalEdge(BI, FalseTrampolineBr->getDestBB())) {
DEBUG(llvm::dbgs() << "false-trampoline from bb" << ThisBB->getDebugID() <<
" to bb" << FalseTrampolineBr->getDestBB()->getDebugID() << '\n');
SILBuilderWithScope(BI).createCondBranch(
BI->getLoc(), BI->getCondition(),
TrueSide, TrueArgs,
FalseTrampolineBr->getDestBB(), FalseTrampolineBr->getArgs());
BI->eraseFromParent();
if (LoopHeaders.count(FalseSide))
LoopHeaders.insert(ThisBB);
removeIfDead(FalseSide);
addToWorklist(ThisBB);
return true;
}
// If we have a (cond (select_enum)) on a two element enum, always have the
// first case as our checked tag. If we have the second, create a new
// select_enum with the first case and swap our operands. This simplifies
// later dominance based processing.
if (auto *SEI = dyn_cast<SelectEnumInst>(BI->getCondition())) {
EnumDecl *E = SEI->getEnumOperand()->getType().getEnumOrBoundGenericEnum();
auto AllElts = E->getAllElements();
auto Iter = AllElts.begin();
EnumElementDecl *FirstElt = *Iter;
if (SEI->getNumCases() >= 1
&& SEI->getCase(0).first != FirstElt) {
++Iter;
if (Iter != AllElts.end() &&
std::next(Iter) == AllElts.end() &&
*Iter == SEI->getCase(0).first) {
EnumElementDecl *SecondElt = *Iter;
SILValue FirstValue;
// SelectEnum must be exhaustive, so the second case must be handled
// either by a case or the default.
if (SEI->getNumCases() >= 2) {
assert(FirstElt == SEI->getCase(1).first
&& "select_enum missing a case?!");
FirstValue = SEI->getCase(1).second;
} else {
FirstValue = SEI->getDefaultResult();
}
std::pair<EnumElementDecl*, SILValue> SwappedCases[2] = {
{FirstElt, SEI->getCase(0).second},
{SecondElt, FirstValue},
};
DEBUG(llvm::dbgs() << "canonicalize " << *SEI);
auto *NewSEI = SILBuilderWithScope(SEI)
.createSelectEnum(SEI->getLoc(),
SEI->getEnumOperand(),
SEI->getType(),
SILValue(),
SwappedCases);
// We only change the condition to be NewEITI instead of all uses since
// EITI may have other uses besides this one that need to be updated.
BI->setCondition(NewSEI);
BI->swapSuccessors();
addToWorklist(BI->getParent());
addToWorklist(TrueSide);
addToWorklist(FalseSide);
return true;
}
}
}
// Simplify a condition branch to a block starting with "cond_fail 1".
//
// cond_br %cond, TrueSide, FalseSide
// TrueSide:
// cond_fail 1
//
auto CFCondition = BI->getCondition();
if (auto *TrueCFI = getUnConditionalFail(TrueSide, CFCondition, false)) {
DEBUG(llvm::dbgs() << "replace with cond_fail:" << *BI);
SILBuilderWithScope Builder(BI);
createCondFail(TrueCFI, CFCondition, false, Builder);
SILBuilderWithScope(BI).createBranch(BI->getLoc(), FalseSide, FalseArgs);
BI->eraseFromParent();
addToWorklist(ThisBB);
simplifyAfterDroppingPredecessor(TrueSide);
addToWorklist(FalseSide);
return true;
}
if (auto *FalseCFI = getUnConditionalFail(FalseSide, CFCondition, true)) {
DEBUG(llvm::dbgs() << "replace with inverted cond_fail:" << *BI);
SILBuilderWithScope Builder(BI);
createCondFail(FalseCFI, CFCondition, true, Builder);
SILBuilderWithScope(BI).createBranch(BI->getLoc(), TrueSide, TrueArgs);
BI->eraseFromParent();
addToWorklist(ThisBB);
simplifyAfterDroppingPredecessor(FalseSide);
addToWorklist(TrueSide);
return true;
}
return false;
}
// Does this basic block consist of only an "unreachable" instruction?
static bool isOnlyUnreachable(SILBasicBlock *BB) {
auto *Term = BB->getTerminator();
if (!isa<UnreachableInst>(Term))
return false;
return (&*BB->begin() == BB->getTerminator());
}
/// simplifySwitchEnumUnreachableBlocks - Attempt to replace a
/// switch_enum where all but one block consists of just an
/// "unreachable" with an unchecked_enum_data and branch.
bool SimplifyCFG::simplifySwitchEnumUnreachableBlocks(SwitchEnumInst *SEI) {
auto Count = SEI->getNumCases();
SILBasicBlock *Dest = nullptr;
EnumElementDecl *Element = nullptr;
if (SEI->hasDefault())
if (!isOnlyUnreachable(SEI->getDefaultBB()))
Dest = SEI->getDefaultBB();
for (unsigned i = 0; i < Count; ++i) {
auto EnumCase = SEI->getCase(i);
if (isOnlyUnreachable(EnumCase.second))
continue;
if (Dest)
return false;
assert(!Element && "Did not expect to have an element without a block!");
Element = EnumCase.first;
Dest = EnumCase.second;
}
if (!Dest) {
addToWorklist(SEI->getParent());
SILBuilderWithScope(SEI).createUnreachable(SEI->getLoc());
SEI->eraseFromParent();
return true;
}
if (!Element || !Element->hasAssociatedValues() || Dest->args_empty()) {
assert(Dest->args_empty() && "Unexpected argument at destination!");
SILBuilderWithScope(SEI).createBranch(SEI->getLoc(), Dest);
addToWorklist(SEI->getParent());
addToWorklist(Dest);
SEI->eraseFromParent();
return true;
}
DEBUG(llvm::dbgs() << "remove " << *SEI);
auto &Mod = SEI->getModule();
auto OpndTy = SEI->getOperand()->getType();
auto Ty = OpndTy.getEnumElementType(Element, Mod);
auto *UED = SILBuilderWithScope(SEI)
.createUncheckedEnumData(SEI->getLoc(), SEI->getOperand(), Element, Ty);
assert(Dest->args_size() == 1 && "Expected only one argument!");
SmallVector<SILValue, 1> Args;
Args.push_back(UED);
SILBuilderWithScope(SEI).createBranch(SEI->getLoc(), Dest, Args);
addToWorklist(SEI->getParent());
addToWorklist(Dest);
SEI->eraseFromParent();
return true;
}
/// simplifySwitchEnumBlock - Simplify a basic block that ends with a
/// switch_enum instruction that gets its operand from an enum
/// instruction.
bool SimplifyCFG::simplifySwitchEnumBlock(SwitchEnumInst *SEI) {
auto EnumCase = getEnumCase(SEI->getOperand(), SEI->getParent());
if (!EnumCase)
return false;
auto *LiveBlock = SEI->getCaseDestination(EnumCase.get());
auto *ThisBB = SEI->getParent();
bool DroppedLiveBlock = false;
// Copy the successors into a vector, dropping one entry for the liveblock.
SmallVector<SILBasicBlock*, 4> Dests;
for (auto &S : SEI->getSuccessors()) {
if (S == LiveBlock && !DroppedLiveBlock) {
DroppedLiveBlock = true;
continue;
}
Dests.push_back(S);
}
DEBUG(llvm::dbgs() << "remove " << *SEI);
auto *EI = dyn_cast<EnumInst>(SEI->getOperand());
SILBuilderWithScope Builder(SEI);
if (!LiveBlock->args_empty()) {
SILValue PayLoad;
if (EI) {
PayLoad = EI->getOperand();
} else {
PayLoad = Builder.createUncheckedEnumData(SEI->getLoc(),
SEI->getOperand(), EnumCase.get());
}
Builder.createBranch(SEI->getLoc(), LiveBlock, PayLoad);
} else {
Builder.createBranch(SEI->getLoc(), LiveBlock);
}
SEI->eraseFromParent();
if (EI && EI->use_empty()) EI->eraseFromParent();
addToWorklist(ThisBB);
for (auto B : Dests)
simplifyAfterDroppingPredecessor(B);
addToWorklist(LiveBlock);
++NumConstantFolded;
return true;
}
/// simplifySwitchValueBlock - Simplify a basic block that ends with a
/// switch_value instruction that gets its operand from an integer
/// literal instruction.
bool SimplifyCFG::simplifySwitchValueBlock(SwitchValueInst *SVI) {
auto *ThisBB = SVI->getParent();
if (auto *ILI = dyn_cast<IntegerLiteralInst>(SVI->getOperand())) {
SILBasicBlock *LiveBlock = nullptr;
auto Value = ILI->getValue();
// Find a case corresponding to this value
int i, e;
for (i = 0, e = SVI->getNumCases(); i < e; ++i) {
auto Pair = SVI->getCase(i);
auto *CaseIL = dyn_cast<IntegerLiteralInst>(Pair.first);
if (!CaseIL)
break;
auto CaseValue = CaseIL->getValue();
if (Value == CaseValue) {
LiveBlock = Pair.second;
break;
}
}
if (i == e && !LiveBlock) {
if (SVI->hasDefault()) {
LiveBlock = SVI->getDefaultBB();
}
}
if (LiveBlock) {
bool DroppedLiveBlock = false;
// Copy the successors into a vector, dropping one entry for the
// liveblock.
SmallVector<SILBasicBlock *, 4> Dests;
for (auto &S : SVI->getSuccessors()) {
if (S == LiveBlock && !DroppedLiveBlock) {
DroppedLiveBlock = true;
continue;
}
Dests.push_back(S);
}
DEBUG(llvm::dbgs() << "remove " << *SVI);
SILBuilderWithScope(SVI).createBranch(SVI->getLoc(), LiveBlock);
SVI->eraseFromParent();
if (ILI->use_empty())
ILI->eraseFromParent();
addToWorklist(ThisBB);
for (auto B : Dests)
simplifyAfterDroppingPredecessor(B);
addToWorklist(LiveBlock);
++NumConstantFolded;
return true;
}
}
return simplifyTermWithIdenticalDestBlocks(ThisBB);
}
/// simplifyUnreachableBlock - Simplify blocks ending with unreachable by
/// removing instructions that are safe to delete backwards until we
/// hit an instruction we cannot delete.
bool SimplifyCFG::simplifyUnreachableBlock(UnreachableInst *UI) {
bool Changed = false;
auto BB = UI->getParent();
auto I = std::next(BB->rbegin());
auto End = BB->rend();
SmallVector<SILInstruction *, 8> DeadInstrs;
// Walk backwards deleting instructions that should be safe to delete
// in a block that ends with unreachable.
while (I != End) {
auto MaybeDead = I++;
switch (MaybeDead->getKind()) {
// These technically have side effects, but not ones that matter
// in a block that we shouldn't really reach...
case ValueKind::StrongRetainInst:
case ValueKind::StrongReleaseInst:
case ValueKind::RetainValueInst:
case ValueKind::ReleaseValueInst:
break;
default:
if (MaybeDead->mayHaveSideEffects()) {
if (Changed)
for (auto Dead : DeadInstrs)
Dead->eraseFromParent();
return Changed;
}
}
if (!MaybeDead->use_empty()) {
auto Undef = SILUndef::get(MaybeDead->getType(), BB->getModule());
MaybeDead->replaceAllUsesWith(Undef);
}
DeadInstrs.push_back(&*MaybeDead);
Changed = true;
}
// If this block was changed and it now consists of only the unreachable,
// make sure we process its predecessors.
if (Changed) {
DEBUG(llvm::dbgs() << "remove dead insts in unreachable bb" <<
BB->getDebugID() << '\n');
for (auto Dead : DeadInstrs)
Dead->eraseFromParent();
if (isOnlyUnreachable(BB))
for (auto *P : BB->getPredecessorBlocks())
addToWorklist(P);
}
return Changed;
}
bool SimplifyCFG::simplifyCheckedCastBranchBlock(CheckedCastBranchInst *CCBI) {
auto SuccessBB = CCBI->getSuccessBB();
auto FailureBB = CCBI->getFailureBB();
auto ThisBB = CCBI->getParent();
bool MadeChange = false;
CastOptimizer CastOpt([&MadeChange](SILInstruction *I,
ValueBase *V) { /* ReplaceInstUsesAction */
MadeChange = true;
},
[&MadeChange](SILInstruction *I) { /* EraseInstAction */
MadeChange = true;
I->eraseFromParent();
},
[&]() { /* WillSucceedAction */
MadeChange |= removeIfDead(FailureBB);
addToWorklist(ThisBB);
},
[&]() { /* WillFailAction */
MadeChange |= removeIfDead(SuccessBB);
addToWorklist(ThisBB);
});
MadeChange |= bool(CastOpt.simplifyCheckedCastBranchInst(CCBI));
return MadeChange;
}
bool SimplifyCFG::simplifyCheckedCastValueBranchBlock(
CheckedCastValueBranchInst *CCBI) {
auto SuccessBB = CCBI->getSuccessBB();
auto FailureBB = CCBI->getFailureBB();
auto ThisBB = CCBI->getParent();
bool MadeChange = false;
CastOptimizer CastOpt(
[&MadeChange](SILInstruction *I,
ValueBase *V) { /* ReplaceInstUsesAction */
MadeChange = true;
},
[&MadeChange](SILInstruction *I) { /* EraseInstAction */
MadeChange = true;
I->eraseFromParent();
},
[&]() { /* WillSucceedAction */
MadeChange |= removeIfDead(FailureBB);
addToWorklist(ThisBB);
},
[&]() { /* WillFailAction */
MadeChange |= removeIfDead(SuccessBB);
addToWorklist(ThisBB);
});
MadeChange |= bool(CastOpt.simplifyCheckedCastValueBranchInst(CCBI));
return MadeChange;
}
bool
SimplifyCFG::
simplifyCheckedCastAddrBranchBlock(CheckedCastAddrBranchInst *CCABI) {
auto SuccessBB = CCABI->getSuccessBB();
auto FailureBB = CCABI->getFailureBB();
auto ThisBB = CCABI->getParent();
bool MadeChange = false;
CastOptimizer CastOpt([&MadeChange](SILInstruction *I, ValueBase *V) {
MadeChange = true;
}, /* ReplaceInstUsesAction */
[&MadeChange](SILInstruction *I) { /* EraseInstAction */
MadeChange = true;
I->eraseFromParent();
},
[&]() { /* WillSucceedAction */
MadeChange |= removeIfDead(FailureBB);
addToWorklist(ThisBB);
},
[&]() { /* WillFailAction */
MadeChange |= removeIfDead(SuccessBB);
addToWorklist(ThisBB);
});
MadeChange |= bool(CastOpt.simplifyCheckedCastAddrBranchInst(CCABI));
return MadeChange;
}
static SILValue getActualCallee(SILValue Callee) {
while (!isa<FunctionRefInst>(Callee)) {
if (auto *CFI = dyn_cast<ConvertFunctionInst>(Callee)) {
Callee = CFI->getConverted();
continue;
}
if (auto *TTI = dyn_cast<ThinToThickFunctionInst>(Callee)) {
Callee = TTI->getConverted();
continue;
}
break;
}
return Callee;
}
/// Checks if the callee of \p TAI is a convert from a function without
/// error result.
static bool isTryApplyOfConvertFunction(TryApplyInst *TAI,
SILValue &Callee,
SILType &CalleeType) {
auto *CFI = dyn_cast<ConvertFunctionInst>(TAI->getCallee());
if (!CFI)
return false;
// Check if it is a conversion of a non-throwing function into
// a throwing function. If this is the case, replace by a
// simple apply.
auto OrigFnTy = CFI->getConverted()->getType().getAs<SILFunctionType>();
if (!OrigFnTy || OrigFnTy->hasErrorResult())
return false;
auto TargetFnTy = CFI->getType().getAs<SILFunctionType>();
if (!TargetFnTy || !TargetFnTy->hasErrorResult())
return false;
// Look through the conversions and find the real callee.
Callee = getActualCallee(CFI->getConverted());
CalleeType = Callee->getType();
// If it a call of a throwing callee, bail.
auto CalleeFnTy = CalleeType.getAs<SILFunctionType>();
if (!CalleeFnTy || CalleeFnTy->hasErrorResult())
return false;
return true;
}
/// Checks if the error block of \p TAI has just an unreachable instruction.
/// In this case we know that the callee cannot throw.
static bool isTryApplyWithUnreachableError(TryApplyInst *TAI,
SILValue &Callee,
SILType &CalleeType) {
SILBasicBlock *ErrorBlock = TAI->getErrorBB();
TermInst *Term = ErrorBlock->getTerminator();
if (!isa<UnreachableInst>(Term))
return false;
if (&*ErrorBlock->begin() != Term)
return false;
Callee = TAI->getCallee();
CalleeType = TAI->getSubstCalleeSILType();
return true;
}
bool SimplifyCFG::simplifyTryApplyBlock(TryApplyInst *TAI) {
SILValue Callee;
SILType CalleeType;
// Two reasons for converting a try_apply to an apply.
if (isTryApplyOfConvertFunction(TAI, Callee, CalleeType) ||
isTryApplyWithUnreachableError(TAI, Callee, CalleeType)) {
auto CalleeFnTy = CalleeType.castTo<SILFunctionType>();
SILFunctionConventions calleeConv(CalleeFnTy, TAI->getModule());
auto ResultTy = calleeConv.getSILResultType();
auto OrigResultTy = TAI->getNormalBB()->getArgument(0)->getType();
SILBuilderWithScope Builder(TAI);
auto TargetFnTy = CalleeFnTy;
if (TargetFnTy->isPolymorphic()) {
TargetFnTy = TargetFnTy->substGenericArgs(TAI->getModule(),
TAI->getSubstitutions());
}
SILFunctionConventions targetConv(TargetFnTy, TAI->getModule());
auto OrigFnTy = TAI->getCallee()->getType().getAs<SILFunctionType>();
if (OrigFnTy->isPolymorphic()) {
OrigFnTy = OrigFnTy->substGenericArgs(TAI->getModule(),
TAI->getSubstitutions());
}
SILFunctionConventions origConv(OrigFnTy, TAI->getModule());
SmallVector<SILValue, 8> Args;
unsigned numArgs = TAI->getNumArguments();
for (unsigned i = 0; i < numArgs; ++i) {
auto Arg = TAI->getArgument(i);
// Cast argument if required.
Arg = castValueToABICompatibleType(&Builder, TAI->getLoc(), Arg,
origConv.getSILArgumentType(i),
targetConv.getSILArgumentType(i));
Args.push_back(Arg);
}
assert(calleeConv.getNumSILArguments() == Args.size()
&& "The number of arguments should match");
DEBUG(llvm::dbgs() << "replace with apply: " << *TAI);
ApplyInst *NewAI = Builder.createApply(TAI->getLoc(), Callee,
TAI->getSubstitutions(),
Args, CalleeFnTy->hasErrorResult());
auto Loc = TAI->getLoc();
auto *NormalBB = TAI->getNormalBB();
auto CastedResult = castValueToABICompatibleType(&Builder, Loc, NewAI,
ResultTy, OrigResultTy);
Builder.createBranch(Loc, NormalBB, { CastedResult });
TAI->eraseFromParent();
return true;
}
return false;
}
// Replace the terminator of BB with a simple branch if all successors go
// to trampoline jumps to the same destination block. The successor blocks
// and the destination blocks may have no arguments.
bool SimplifyCFG::simplifyTermWithIdenticalDestBlocks(SILBasicBlock *BB) {
SILBasicBlock *commonDest = nullptr;
for (auto *SuccBlock : BB->getSuccessorBlocks()) {
if (SuccBlock->getNumArguments() != 0)
return false;
SILBasicBlock *DestBlock = getTrampolineDest(SuccBlock);
if (!DestBlock)
return false;
if (!commonDest) {
commonDest = DestBlock;
} else if (DestBlock != commonDest) {
return false;
}
}
if (!commonDest)
return false;
assert(commonDest->getNumArguments() == 0 &&
"getTrampolineDest should have checked that commonDest has no args");
TermInst *Term = BB->getTerminator();
DEBUG(llvm::dbgs() << "replace term with identical dests: " << *Term);
SILBuilderWithScope(Term).createBranch(Term->getLoc(), commonDest, {});
Term->eraseFromParent();
addToWorklist(BB);
addToWorklist(commonDest);
return true;
}
void RemoveUnreachable::visit(SILBasicBlock *BB) {
if (!Visited.insert(BB).second)
return;
for (auto &Succ : BB->getSuccessors())
visit(Succ);
}
bool RemoveUnreachable::run() {
bool Changed = false;
// Clear each time we run so that we can run multiple times.
Visited.clear();
// Visit all blocks reachable from the entry block of the function.
visit(&*Fn.begin());
// Remove the blocks we never reached.
for (auto It = Fn.begin(), End = Fn.end(); It != End; ) {
auto *BB = &*It++;
if (!Visited.count(BB)) {
DEBUG(llvm::dbgs() << "remove unreachable bb" << BB->getDebugID() << '\n');
removeDeadBlock(BB);
Changed = true;
}
}
return Changed;
}
/// Checks if the block contains a cond_fail as first side-effect instruction
/// and tries to move it to the predecessors (if beneficial). A sequence
///
/// bb1:
/// br bb3(%c)
/// bb2:
/// %i = integer_literal
/// br bb3(%i) // at least one input argument must be constant
/// bb3(%a) // = BB
/// cond_fail %a // %a must not have other uses
///
/// is replaced with
///
/// bb1:
/// cond_fail %c
/// br bb3(%c)
/// bb2:
/// %i = integer_literal
/// cond_fail %i
/// br bb3(%i)
/// bb3(%a) // %a is dead
///
static bool tryMoveCondFailToPreds(SILBasicBlock *BB) {
CondFailInst *CFI = getFirstCondFail(BB);
if (!CFI)
return false;
// Find the underlying condition value of the cond_fail.
// We only accept single uses. This is not a correctness check, but we only
// want to the optimization if the condition gets dead after moving the
// cond_fail.
bool inverted = false;
SILValue cond = skipInvert(CFI->getOperand(), inverted, true);
if (!cond)
return false;
// Check if the condition is a single-used argument in the current block.
auto *condArg = dyn_cast<SILArgument>(cond);
if (!condArg || !condArg->hasOneUse())
return false;
if (condArg->getParent() != BB)
return false;
// Check if some of the predecessor blocks provide a constant for the
// cond_fail condition. So that the optimization has a positive effect.
bool somePredsAreConst = false;
for (auto *Pred : BB->getPredecessorBlocks()) {
// The cond_fail must post-dominate the predecessor block. We may not
// execute the cond_fail speculatively.
if (!Pred->getSingleSuccessorBlock())
return false;
// If we already found a constant pred, we do not need to check the incoming
// value to see if it is constant. We are already going to perform the
// optimization.
if (somePredsAreConst)
continue;
SILValue incoming = condArg->getIncomingValue(Pred);
somePredsAreConst |= isa<IntegerLiteralInst>(incoming);
}
if (!somePredsAreConst)
return false;
DEBUG(llvm::dbgs() << "move to predecessors: " << *CFI);
// Move the cond_fail to the predecessor blocks.
for (auto *Pred : BB->getPredecessorBlocks()) {
SILValue incoming = condArg->getIncomingValue(Pred);
SILBuilderWithScope Builder(Pred->getTerminator());
createCondFail(CFI, incoming, inverted, Builder);
}
CFI->eraseFromParent();
return true;
}
bool SimplifyCFG::simplifyBlocks() {
bool Changed = false;
// Add all of the blocks to the function.
for (auto &BB : Fn)
addToWorklist(&BB);
// Iteratively simplify while there is still work to do.
while (SILBasicBlock *BB = popWorklist()) {
// If the block is dead, remove it.
if (removeIfDead(BB)) {
Changed = true;
continue;
}
// Otherwise, try to simplify the terminator.
TermInst *TI = BB->getTerminator();
switch (TI->getTermKind()) {
case TermKind::BranchInst:
Changed |= simplifyBranchBlock(cast<BranchInst>(TI));
break;
case TermKind::CondBranchInst:
Changed |= simplifyCondBrBlock(cast<CondBranchInst>(TI));
break;
case TermKind::SwitchValueInst:
// FIXME: Optimize for known switch values.
Changed |= simplifySwitchValueBlock(cast<SwitchValueInst>(TI));
break;
case TermKind::SwitchEnumInst: {
auto *SEI = cast<SwitchEnumInst>(TI);
if (simplifySwitchEnumBlock(SEI)) {
Changed = false;
} else {
Changed |= simplifySwitchEnumUnreachableBlocks(SEI);
}
Changed |= simplifyTermWithIdenticalDestBlocks(BB);
break;
}
case TermKind::UnreachableInst:
Changed |= simplifyUnreachableBlock(cast<UnreachableInst>(TI));
break;
case TermKind::CheckedCastBranchInst:
Changed |= simplifyCheckedCastBranchBlock(cast<CheckedCastBranchInst>(TI));
break;
case TermKind::CheckedCastValueBranchInst:
Changed |= simplifyCheckedCastValueBranchBlock(
cast<CheckedCastValueBranchInst>(TI));
break;
case TermKind::CheckedCastAddrBranchInst:
Changed |= simplifyCheckedCastAddrBranchBlock(cast<CheckedCastAddrBranchInst>(TI));
break;
case TermKind::TryApplyInst:
Changed |= simplifyTryApplyBlock(cast<TryApplyInst>(TI));
break;
case TermKind::SwitchEnumAddrInst:
Changed |= simplifyTermWithIdenticalDestBlocks(BB);
break;
case TermKind::ThrowInst:
case TermKind::DynamicMethodBranchInst:
case TermKind::ReturnInst:
break;
}
// If the block has a cond_fail, try to move it to the predecessors.
Changed |= tryMoveCondFailToPreds(BB);
// Simplify the block argument list.
Changed |= simplifyArgs(BB);
// Simplify the program termination block.
Changed |= simplifyProgramTerminationBlock(BB);
}
return Changed;
}
/// Canonicalize all switch_enum and switch_enum_addr instructions.
/// If possible, replace the default with the corresponding unique case.
bool SimplifyCFG::canonicalizeSwitchEnums() {
bool Changed = false;
for (auto &BB : Fn) {
TermInst *TI = BB.getTerminator();
auto *SWI = dyn_cast<SwitchEnumInstBase>(TI);
if (!SWI)
continue;
if (!SWI->hasDefault())
continue;
NullablePtr<EnumElementDecl> elementDecl = SWI->getUniqueCaseForDefault();
if (!elementDecl)
continue;
// Construct a new instruction by copying all the case entries.
SmallVector<std::pair<EnumElementDecl*, SILBasicBlock*>, 4> CaseBBs;
for (int idx = 0, numIdcs = SWI->getNumCases(); idx < numIdcs; idx++) {
CaseBBs.push_back(SWI->getCase(idx));
}
// Add the default-entry of the original instruction as case-entry.
CaseBBs.push_back(std::make_pair(elementDecl.get(), SWI->getDefaultBB()));
if (SWI->getKind() == ValueKind::SwitchEnumInst) {
SILBuilderWithScope(SWI)
.createSwitchEnum(SWI->getLoc(), SWI->getOperand(), nullptr, CaseBBs);
} else {
assert(SWI->getKind() == ValueKind::SwitchEnumAddrInst &&
"unknown switch_enum instruction");
SILBuilderWithScope(SWI).createSwitchEnumAddr(
SWI->getLoc(), SWI->getOperand(), nullptr, CaseBBs);
}
SWI->eraseFromParent();
Changed = true;
}
return Changed;
}
static SILBasicBlock *isObjCMethodCallBlock(SILBasicBlock &Block) {
auto *Branch = dyn_cast<BranchInst>(Block.getTerminator());
if (!Branch)
return nullptr;
for (auto &Inst : Block) {
// Look for an objc method call.
auto *Apply = dyn_cast<ApplyInst>(&Inst);
if (!Apply)
continue;
auto *Callee = dyn_cast<WitnessMethodInst>(Apply->getCallee());
if (!Callee || !Callee->getMember().isForeign)
continue;
return Branch->getDestBB();
}
return nullptr;
}
/// We want to duplicate small blocks that contain a least on release and have
/// multiple predecessor.
static bool shouldTailDuplicate(SILBasicBlock &Block) {
unsigned Cost = 0;
bool SawRelease = false;
if (isa<ReturnInst>(Block.getTerminator()))
return false;
if (Block.getSinglePredecessorBlock())
return false;
for (auto &Inst : Block) {
if (!Inst.isTriviallyDuplicatable())
return false;
if (isa<ApplyInst>(&Inst))
return false;
if (isa<ReleaseValueInst>(&Inst) ||
isa<StrongReleaseInst>(&Inst))
SawRelease = true;
if (instructionInlineCost(Inst) != InlineCost::Free)
if (++Cost == 12)
return false;
}
return SawRelease;
}
/// Tail duplicate successor blocks of blocks that perform an objc method call
/// and who contain releases. Cloning such blocks can allow ARC to sink retain
/// releases onto the ObjC path.
bool SimplifyCFG::tailDuplicateObjCMethodCallSuccessorBlocks() {
SmallVector<SILBasicBlock *, 16> ObjCBlocks;
// Collect blocks to tail duplicate.
for (auto &BB : Fn) {
SILBasicBlock *DestBB;
if ((DestBB = isObjCMethodCallBlock(BB)) && !LoopHeaders.count(DestBB) &&
shouldTailDuplicate(*DestBB))
ObjCBlocks.push_back(&BB);
}
bool Changed = false;
for (auto *BB : ObjCBlocks) {
auto *Branch = cast<BranchInst>(BB->getTerminator());
auto *DestBB = Branch->getDestBB();
Changed = true;
// Okay, it looks like we want to do this and we can. Duplicate the
// destination block into this one, rewriting uses of the BBArgs to use the
// branch arguments as we go.
EdgeThreadingCloner Cloner(Branch);
for (auto &I : *DestBB)
Cloner.process(&I);
updateSSAAfterCloning(Cloner, Cloner.getEdgeBB(), DestBB);
addToWorklist(Cloner.getEdgeBB());
}
return Changed;
}
static void
deleteTriviallyDeadOperandsOfDeadArgument(MutableArrayRef<Operand> TermOperands,
unsigned DeadArgIndex, SILModule &M) {
Operand &Op = TermOperands[DeadArgIndex];
auto *I = dyn_cast<SILInstruction>(Op.get());
if (!I)
return;
Op.set(SILUndef::get(Op.get()->getType(), M));
recursivelyDeleteTriviallyDeadInstructions(I);
}
static void removeArgumentFromTerminator(SILBasicBlock *BB, SILBasicBlock *Dest,
int idx) {
TermInst *Branch = BB->getTerminator();
SILBuilderWithScope Builder(Branch);
DEBUG(llvm::dbgs() << "remove dead argument " << idx << " from " << *Branch);
if (auto *CBI = dyn_cast<CondBranchInst>(Branch)) {
SmallVector<SILValue, 8> TrueArgs;
SmallVector<SILValue, 8> FalseArgs;
for (auto A : CBI->getTrueArgs())
TrueArgs.push_back(A);
for (auto A : CBI->getFalseArgs())
FalseArgs.push_back(A);
if (Dest == CBI->getTrueBB()) {
deleteTriviallyDeadOperandsOfDeadArgument(CBI->getTrueOperands(), idx,
BB->getModule());
TrueArgs.erase(TrueArgs.begin() + idx);
}
if (Dest == CBI->getFalseBB()) {
deleteTriviallyDeadOperandsOfDeadArgument(CBI->getFalseOperands(), idx,
BB->getModule());
FalseArgs.erase(FalseArgs.begin() + idx);
}
Builder.createCondBranch(CBI->getLoc(), CBI->getCondition(),
CBI->getTrueBB(), TrueArgs, CBI->getFalseBB(),
FalseArgs);
Branch->eraseFromParent();
return;
}
if (auto *BI = dyn_cast<BranchInst>(Branch)) {
SmallVector<SILValue, 8> Args;
for (auto A : BI->getArgs())
Args.push_back(A);
deleteTriviallyDeadOperandsOfDeadArgument(BI->getAllOperands(), idx,
BB->getModule());
Args.erase(Args.begin() + idx);
Builder.createBranch(BI->getLoc(), BI->getDestBB(), Args);
Branch->eraseFromParent();
return;
}
llvm_unreachable("unsupported terminator");
}
static void removeArgument(SILBasicBlock *BB, unsigned i) {
NumDeadArguments++;
BB->eraseArgument(i);
// Determine the set of predecessors in case any predecessor has
// two edges to this block (e.g. a conditional branch where both
// sides reach this block).
llvm::SmallPtrSet<SILBasicBlock *, 4> PredBBs;
for (auto *Pred : BB->getPredecessorBlocks())
PredBBs.insert(Pred);
for (auto *Pred : PredBBs)
removeArgumentFromTerminator(Pred, BB, i);
}
namespace {
class ArgumentSplitter {
/// The argument we are splitting.
SILArgument *Arg;
/// The worklist of arguments that we still need to visit. We
/// simplify each argument recursively one step at a time.
std::vector<SILArgument *> &Worklist;
/// The values incoming into Arg.
llvm::SmallVector<std::pair<SILBasicBlock *, SILValue>, 8> IncomingValues;
/// The list of first level projections that Arg can be split into.
llvm::SmallVector<Projection, 4> Projections;
llvm::Optional<int> FirstNewArgIndex;
public:
ArgumentSplitter(SILArgument *A, std::vector<SILArgument *> &W)
: Arg(A), Worklist(W), IncomingValues() {}
bool split();
private:
bool createNewArguments();
void replaceIncomingArgs(SILBuilder &B, BranchInst *BI,
llvm::SmallVectorImpl<SILValue> &NewIncomingValues);
void replaceIncomingArgs(SILBuilder &B, CondBranchInst *CBI,
llvm::SmallVectorImpl<SILValue> &NewIncomingValues);
};
} // end anonymous namespace
void ArgumentSplitter::replaceIncomingArgs(
SILBuilder &B, BranchInst *BI,
llvm::SmallVectorImpl<SILValue> &NewIncomingValues) {
unsigned ArgIndex = Arg->getIndex();
for (unsigned i : reversed(indices(BI->getAllOperands()))) {
// Skip this argument.
if (i == ArgIndex)
continue;
NewIncomingValues.push_back(BI->getArg(i));
}
std::reverse(NewIncomingValues.begin(), NewIncomingValues.end());
B.createBranch(BI->getLoc(), BI->getDestBB(), NewIncomingValues);
}
void ArgumentSplitter::replaceIncomingArgs(
SILBuilder &B, CondBranchInst *CBI,
llvm::SmallVectorImpl<SILValue> &NewIncomingValues) {
llvm::SmallVector<SILValue, 4> OldIncomingValues;
ArrayRef<SILValue> NewTrueValues, NewFalseValues;
unsigned ArgIndex = Arg->getIndex();
if (Arg->getParent() == CBI->getTrueBB()) {
ArrayRef<Operand> TrueArgs = CBI->getTrueOperands();
for (unsigned i : reversed(indices(TrueArgs))) {
// Skip this argument.
if (i == ArgIndex)
continue;
NewIncomingValues.push_back(TrueArgs[i].get());
}
std::reverse(NewIncomingValues.begin(), NewIncomingValues.end());
for (SILValue V : CBI->getFalseArgs())
OldIncomingValues.push_back(V);
NewTrueValues = NewIncomingValues;
NewFalseValues = OldIncomingValues;
} else {
ArrayRef<Operand> FalseArgs = CBI->getFalseOperands();
for (unsigned i : reversed(indices(FalseArgs))) {
// Skip this argument.
if (i == ArgIndex)
continue;
NewIncomingValues.push_back(FalseArgs[i].get());
}
std::reverse(NewIncomingValues.begin(), NewIncomingValues.end());
for (SILValue V : CBI->getTrueArgs())
OldIncomingValues.push_back(V);
NewTrueValues = OldIncomingValues;
NewFalseValues = NewIncomingValues;
}
B.createCondBranch(CBI->getLoc(), CBI->getCondition(), CBI->getTrueBB(),
NewTrueValues, CBI->getFalseBB(), NewFalseValues);
}
bool ArgumentSplitter::createNewArguments() {
SILModule &Mod = Arg->getModule();
SILBasicBlock *ParentBB = Arg->getParent();
// Grab the incoming values. Return false if we can't find them.
if (!Arg->getIncomingValues(IncomingValues))
return false;
// Only handle struct and tuple type.
SILType Ty = Arg->getType();
if (!Ty.getStructOrBoundGenericStruct() && !Ty.is<TupleType>())
return false;
// Get the first level projection for the struct or tuple type.
Projection::getFirstLevelProjections(Arg->getType(), Mod, Projections);
// We do not want to split arguments with less than 2 projections.
if (Projections.size() < 2)
return false;
// We do not want to split arguments that have less than 2 non-trivial
// projections.
if (count_if(Projections, [&](const Projection &P) {
return !P.getType(Ty, Mod).isTrivial(Mod);
}) < 2)
return false;
// We subtract one since this will be the number of the first new argument
// *AFTER* we remove the old argument.
FirstNewArgIndex = ParentBB->getNumArguments() - 1;
// For now for simplicity, we put all new arguments on the end and delete the
// old one.
llvm::SmallVector<SILValue, 4> NewArgumentValues;
for (auto &P : Projections) {
auto *NewArg = ParentBB->createPHIArgument(P.getType(Ty, Mod),
ValueOwnershipKind::Owned);
// This is unfortunate, but it feels wrong to put in an API into SILBuilder
// that only takes in arguments.
//
// TODO: We really need some sort of entry point that is more flexible in
// these apis than a ArrayRef<SILValue>.
NewArgumentValues.push_back(NewArg);
}
SILInstruction *Agg = nullptr;
{
SILBuilder B(ParentBB->begin());
B.setCurrentDebugScope(ParentBB->getParent()->getDebugScope());
// Reform the original structure
//
// TODO: What is the right location to use here.
auto Loc = RegularLocation::getAutoGeneratedLocation();
Agg = Projection::createAggFromFirstLevelProjections(
B, Loc, Arg->getType(), NewArgumentValues).get();
assert(Agg->hasValue() && "Expected a result");
}
Arg->replaceAllUsesWith(Agg);
// Replace any references to Arg in IncomingValues with Agg. These
// references are used in generating new instructions that extract
// from the aggregate.
for (auto &P : IncomingValues)
if (P.second == Arg)
P.second = Agg;
// Look at all users of agg and see if we can simplify any of them. This will
// eliminate struct_extracts/tuple_extracts from the newly created aggregate
// and have them point directly at the argument.
simplifyUsers(Agg);
// If we only had such users of Agg and Agg is dead now (ignoring debug
// instructions), remove it.
if (onlyHaveDebugUses(Agg))
eraseFromParentWithDebugInsts(Agg);
return true;
}
static llvm::cl::opt<bool>
RemoveDeadArgsWhenSplitting("sroa-args-remove-dead-args-after",
llvm::cl::init(true));
bool ArgumentSplitter::split() {
SILBasicBlock *ParentBB = Arg->getParent();
if (!createNewArguments())
return false;
DEBUG(llvm::dbgs() << "split argument " << *Arg);
unsigned ArgIndex = Arg->getIndex();
llvm::SmallVector<SILValue, 4> NewIncomingValues;
// Then for each incoming value, fixup the branch, cond_branch instructions.
for (auto P : IncomingValues) {
SILBasicBlock *Pred = P.first;
SILValue Base = P.second;
auto *OldTerm = Pred->getTerminator();
SILBuilderWithScope B(OldTerm->getParent(), OldTerm);
auto Loc = RegularLocation::getAutoGeneratedLocation();
assert(NewIncomingValues.empty() && "NewIncomingValues was not cleared?");
for (auto &P : reversed(Projections)) {
auto *ProjInst = P.createProjection(B, Loc, Base).get();
NewIncomingValues.push_back(ProjInst);
}
if (auto *Br = dyn_cast<BranchInst>(OldTerm)) {
replaceIncomingArgs(B, Br, NewIncomingValues);
} else {
auto *CondBr = cast<CondBranchInst>(OldTerm);
replaceIncomingArgs(B, CondBr, NewIncomingValues);
}
OldTerm->eraseFromParent();
NewIncomingValues.clear();
}
// Delete the old argument. We need to do this before trying to remove any
// dead arguments that we added since otherwise the number of incoming values
// to the phi nodes will differ from the number of values coming
ParentBB->eraseArgument(ArgIndex);
++NumSROAArguments;
// This is here for testing purposes via sil-opt
if (!RemoveDeadArgsWhenSplitting)
return true;
// Perform some cleanups such as:
//
// 1. Removing any newly inserted arguments that are actually dead.
// 2. As a result of removing these arguments, remove any newly dead object
// projections.
// Do a quick pass over the new arguments to see if any of them are dead. We
// can do this unconditionally in a safe way since we are only dealing with
// cond_br, br.
for (int i = ParentBB->getNumArguments() - 1, e = *FirstNewArgIndex; i >= e;
--i) {
SILArgument *A = ParentBB->getArgument(i);
if (!A->use_empty()) {
// We know that the argument is not dead, so add it to the worklist for
// recursive processing.
Worklist.push_back(A);
continue;
}
removeArgument(ParentBB, i);
}
return true;
}
/// This currently invalidates the CFG since parts of PHI nodes are stored in
/// branch instructions and we replace the branch instructions as part of this
/// operation. If/when PHI nodes can be updated without invalidating the CFG,
/// this should be moved to the SROA pass.
static bool splitBBArguments(SILFunction &Fn) {
bool Changed = false;
std::vector<SILArgument *> Worklist;
// We know that we have at least one BB, so this is safe since in such a case
// std::next(Fn->begin()) == Fn->end(), the exit case of iteration on a range.
for (auto &BB : make_range(std::next(Fn.begin()), Fn.end())) {
for (auto *Arg : BB.getArguments()) {
SILType ArgTy = Arg->getType();
if (!ArgTy.isObject() ||
(!ArgTy.is<TupleType>() && !ArgTy.getStructOrBoundGenericStruct())) {
continue;
}
// Make sure that all predecessors of our BB have either a br or cond_br
// terminator. We only handle those cases.
if (std::any_of(BB.pred_begin(), BB.pred_end(),
[](SILBasicBlock *Pred) -> bool {
auto *TI = Pred->getTerminator();
return !isa<BranchInst>(TI) && !isa<CondBranchInst>(TI);
})) {
continue;
}
Worklist.push_back(Arg);
}
}
while (!Worklist.empty()) {
SILArgument *Arg = Worklist.back();
Worklist.pop_back();
Changed |= ArgumentSplitter(Arg, Worklist).split();
}
return Changed;
}
bool SimplifyCFG::run() {
DEBUG(llvm::dbgs() << "### Run SimplifyCFG on " << Fn.getName() << '\n');
RemoveUnreachable RU(Fn);
// First remove any block not reachable from the entry.
bool Changed = RU.run();
// Find the set of loop headers. We don't want to jump-thread through headers.
findLoopHeaders();
DT = nullptr;
// Perform SROA on BB arguments.
Changed |= splitBBArguments(Fn);
if (simplifyBlocks()) {
// Simplifying other blocks might have resulted in unreachable
// loops.
RU.run();
Changed = true;
}
// Do simplifications that require the dominator tree to be accurate.
DominanceAnalysis *DA = PM->getAnalysis<DominanceAnalysis>();
if (Changed) {
// Force dominator recomputation since we modified the cfg.
DA->invalidate(&Fn, SILAnalysis::InvalidationKind::Everything);
}
Changed |= dominatorBasedSimplify(DA);
DT = nullptr;
// Now attempt to simplify the remaining blocks.
if (simplifyBlocks()) {
// Simplifying other blocks might have resulted in unreachable
// loops.
RU.run();
Changed = true;
}
if (tailDuplicateObjCMethodCallSuccessorBlocks()) {
Changed = true;
if (simplifyBlocks())
RU.run();
}
// Split all critical edges from non cond_br terminators.
Changed |= splitAllCriticalEdges(Fn, true, nullptr, nullptr);
// Canonicalize switch_enum instructions.
Changed |= canonicalizeSwitchEnums();
return Changed;
}
/// Is an argument from this terminator considered mandatory?
static bool hasMandatoryArgument(TermInst *term) {
// It's more maintainable to just white-list the instructions that
// *do* have mandatory arguments.
return (!isa<BranchInst>(term) && !isa<CondBranchInst>(term));
}
// Get the element of Aggregate corresponding to the one extracted by
// Extract.
static SILValue getInsertedValue(SILInstruction *Aggregate,
SILInstruction *Extract) {
if (auto *Struct = dyn_cast<StructInst>(Aggregate)) {
auto *SEI = cast<StructExtractInst>(Extract);
return Struct->getFieldValue(SEI->getField());
}
if (auto *Enum = dyn_cast<EnumInst>(Aggregate)) {
assert(Enum->getElement() ==
cast<UncheckedEnumDataInst>(Extract)->getElement());
return Enum->getOperand();
}
auto *Tuple = cast<TupleInst>(Aggregate);
auto *TEI = cast<TupleExtractInst>(Extract);
return Tuple->getElement(TEI->getFieldNo());
}
/// Find a parent SwitchEnumInst of the block \p BB. The block \p BB is a
/// predecessor of the merge-block \p PostBB which should post-dominate the
/// switch_enum. Any successors of the switch_enum which reach \p BB (and are
/// post-dominated by \p BB) are added to \p Blocks.
static SwitchEnumInst *
getSwitchEnumPred(SILBasicBlock *BB, SILBasicBlock *PostBB,
SmallVectorImpl<SILBasicBlock *> &Blocks) {
if (BB->pred_empty())
return nullptr;
// Check that this block only produces the value, but does not
// have any side effects.
auto First = BB->begin();
auto *BI = dyn_cast<BranchInst>(BB->getTerminator());
if (!BI)
return nullptr;
assert(BI->getDestBB() == PostBB && "BB not a predecessor of PostBB");
if (BI != &*First) {
// There may be only one instruction before the branch.
if (BI != &*std::next(First))
return nullptr;
// There are some instructions besides the branch.
// It should be only an integer literal instruction.
// Handle only integer values for now.
auto *ILI = dyn_cast<IntegerLiteralInst>(First);
if (!ILI)
return nullptr;
// Check that this literal is only used by the terminator.
for (auto U : ILI->getUses())
if (U->getUser() != BI)
return nullptr;
}
// Check if BB is reachable from a single enum case, which means that the
// immediate predecessor of BB is the switch_enum itself.
if (SILBasicBlock *PredBB = BB->getSinglePredecessorBlock()) {
// Check if a predecessor BB terminates with a switch_enum instruction
if (auto *SEI = dyn_cast<SwitchEnumInst>(PredBB->getTerminator())) {
Blocks.push_back(BB);
return SEI;
}
}
// Check if BB is reachable from multiple enum cases. This means that there is
// a single-branch block for each enum case which branch to BB.
SILBasicBlock *CommonPredPredBB = nullptr;
for (auto PredBB : BB->getPredecessorBlocks()) {
TermInst *PredTerm = PredBB->getTerminator();
if (!isa<BranchInst>(PredTerm) || PredTerm != &*PredBB->begin())
return nullptr;
auto *PredPredBB = PredBB->getSinglePredecessorBlock();
if (!PredPredBB)
return nullptr;
// Check if all predecessors of BB have a single common predecessor (which
// should be the block with the switch_enum).
if (CommonPredPredBB && PredPredBB != CommonPredPredBB)
return nullptr;
CommonPredPredBB = PredPredBB;
Blocks.push_back(PredBB);
}
// Check if the common predecessor block has a switch_enum.
return dyn_cast<SwitchEnumInst>(CommonPredPredBB->getTerminator());
}
/// Helper function to produce a SILValue from a result value
/// produced by a basic block responsible for handling a
/// specific enum tag.
static SILValue
getSILValueFromCaseResult(SILBuilder &B, SILLocation Loc,
SILType Type, IntegerLiteralInst *ValInst) {
auto Value = ValInst->getValue();
if (Value.getBitWidth() != 1)
return B.createIntegerLiteral(Loc, Type, Value);
else
// This is a boolean value
return B.createIntegerLiteral(Loc, Type, Value.getBoolValue());
}
/// Given an integer argument, see if it is ultimately matching whether
/// a given enum is of a given tag. If so, create a new select_enum instruction
/// This is used to simplify arbitrary simple switch_enum diamonds into
/// select_enums.
static bool simplifySwitchEnumToSelectEnum(SILBasicBlock *BB, unsigned ArgNum,
SILArgument *IntArg) {
// Don't know which values should be passed if there is more
// than one basic block argument.
if (BB->args_size() > 1)
return false;
// Mapping from case values to the results corresponding to this case value.
SmallVector<std::pair<EnumElementDecl *, SILValue>, 8> CaseToValue;
// Mapping from BB responsible for a specific case value to the result it
// produces.
llvm::DenseMap<SILBasicBlock *, IntegerLiteralInst *> BBToValue;
// switch_enum instruction to be replaced.
SwitchEnumInst *SEI = nullptr;
// Iterate over all immediate predecessors of the target basic block.
// - Check that each one stems directly or indirectly from the same
// switch_enum instruction.
// - Remember for each case tag of the switch_enum instruction which
// integer value it produces.
// - Check that each block handling a given case tag of a switch_enum
// only produces an integer value and does not have any side-effects.
// Predecessors which do not satisfy these conditions are not included in the
// BBToValue map (but we don't bail in this case).
for (auto P : BB->getPredecessorBlocks()) {
// Only handle branch instructions.
auto *TI = P->getTerminator();
if (!isa<BranchInst>(TI))
return false;
// Find the Nth argument passed to BB.
auto Arg = TI->getOperand(ArgNum);
// Only handle integer values
auto *IntLit = dyn_cast<IntegerLiteralInst>(Arg);
if (!IntLit)
continue;
// Set of blocks that branch to/reach this basic block P and are immediate
// successors of a switch_enum instruction.
SmallVector<SILBasicBlock *, 8> Blocks;
// Try to find a parent SwitchEnumInst for the current predecessor of BB.
auto *PredSEI = getSwitchEnumPred(P, BB, Blocks);
// Check if the predecessor is not produced by a switch_enum instruction.
if (!PredSEI)
continue;
// Check if all predecessors stem from the same switch_enum instruction.
if (SEI && SEI != PredSEI)
continue;
SEI = PredSEI;
// Remember the result value used to branch to this instruction.
for (auto B : Blocks)
BBToValue[B] = IntLit;
}
if (!SEI)
return false;
// Check if all enum cases and the default case go to one of our collected
// blocks. This check ensures that the target block BB post-dominates the
// switch_enum block.
for (SILBasicBlock *Succ : SEI->getSuccessors()) {
if (!BBToValue.count(Succ))
return false;
}
// Insert the new enum_select instruction right after enum_switch
SILBuilder B(SEI);
// Form a set of case_tag:result pairs for select_enum
for (unsigned i = 0, e = SEI->getNumCases(); i != e; ++i) {
std::pair<EnumElementDecl *, SILBasicBlock *> Pair = SEI->getCase(i);
auto CaseValue = BBToValue[Pair.second];
auto CaseSILValue = getSILValueFromCaseResult(B, SEI->getLoc(),
IntArg->getType(),
CaseValue);
CaseToValue.push_back(std::make_pair(Pair.first, CaseSILValue));
}
// Default value for select_enum.
SILValue DefaultSILValue = SILValue();
if (SEI->hasDefault()) {
// Try to define a default case for enum_select based
// on the default case of enum_switch.
auto DefaultValue = BBToValue[SEI->getDefaultBB()];
DefaultSILValue = getSILValueFromCaseResult(B, SEI->getLoc(),
IntArg->getType(),
DefaultValue);
} else {
// Try to see if enum_switch covers all possible cases.
// If it does, then pick one of those cases as a default.
// Count the number of possible case tags for a given enum type
auto *Enum = SEI->getOperand()->getType().getEnumOrBoundGenericEnum();
unsigned ElemCount = 0;
for (auto E : Enum->getAllElements()) {
if (E)
ElemCount++;
}
// Check if all possible cases are covered.
if (ElemCount == SEI->getNumCases()) {
// This enum_switch instruction is exhaustive.
// Make the last case a default.
auto Pair = CaseToValue.pop_back_val();
DefaultSILValue = Pair.second;
}
}
// We don't need to have explicit cases for any case tags which produce the
// same result as the default branch.
if (DefaultSILValue != SILValue()) {
auto DefaultValue = DefaultSILValue;
auto *DefaultSI = dyn_cast<IntegerLiteralInst>(DefaultValue);
for (auto I = CaseToValue.begin(); I != CaseToValue.end();) {
auto CaseValue = I->second;
if (CaseValue == DefaultValue) {
I = CaseToValue.erase(I);
continue;
}
if (DefaultSI) {
if (auto CaseSI = dyn_cast<IntegerLiteralInst>(CaseValue)) {
if (DefaultSI->getValue() == CaseSI->getValue()) {
I = CaseToValue.erase(I);
continue;
}
}
}
++I;
}
}
DEBUG(llvm::dbgs() << "convert to select_enum: " << *SEI);
// Create a new select_enum instruction
auto SelectInst = B.createSelectEnum(SEI->getLoc(), SEI->getOperand(),
IntArg->getType(),
DefaultSILValue, CaseToValue);
// Do not replace the bbarg
SmallVector<SILValue, 4> Args;
Args.push_back(SelectInst);
B.setInsertionPoint(&*std::next(SelectInst->getIterator()));
B.createBranch(SEI->getLoc(), BB, Args);
// Remove switch_enum instruction
SEI->getParent()->getTerminator()->eraseFromParent();
return true;
}
/// Collected information for a select_value case or default case.
struct CaseInfo {
/// The input value or null if it is the default case.
IntegerLiteralInst *Literal = nullptr;
/// The result value.
SILInstruction *Result = nullptr;
/// The block which contains the cond_br of the input value comparison
/// or the block which assigns the default value.
SILBasicBlock *CmpOrDefault = nullptr;
};
/// Get information about a potential select_value case (or default).
/// \p Input is set to the common input value.
/// \p Pred is the predecessor block of the last merge block of the CFG pattern.
/// \p ArgNum is the index of the argument passed to the merge block.
CaseInfo getCaseInfo(SILValue &Input, SILBasicBlock *Pred, unsigned ArgNum) {
CaseInfo CaseInfo;
auto *TI = Pred->getTerminator();
if (!isa<BranchInst>(TI))
return CaseInfo;
// Find the Nth argument passed to BB.
auto Arg = TI->getOperand(ArgNum);
// Currently we only accept enums as result values.
auto *EI2 = dyn_cast<EnumInst>(Arg);
if (!EI2)
return CaseInfo;
if (EI2->hasOperand()) {
// ... or enums with enum data. This is exactly the pattern for an enum
// with integer raw value initialization.
auto *EI1 = dyn_cast<EnumInst>(EI2->getOperand());
if (!EI1)
return CaseInfo;
// But not enums with enums with data.
if (EI1->hasOperand())
return CaseInfo;
}
// Check if we come to the Pred block by comparing the input value to a
// constant.
SILBasicBlock *CmpBlock = Pred->getSinglePredecessorBlock();
if (!CmpBlock)
return CaseInfo;
auto *CmpInst = dyn_cast<CondBranchInst>(CmpBlock->getTerminator());
if (!CmpInst)
return CaseInfo;
auto *CondInst = dyn_cast<BuiltinInst>(CmpInst->getCondition());
if (!CondInst)
return CaseInfo;
if (!CondInst->getName().str().startswith("cmp_eq"))
return CaseInfo;
auto CondArgs = CondInst->getArguments();
assert(CondArgs.size() == 2);
SILValue Arg1 = CondArgs[0];
SILValue Arg2 = CondArgs[1];
if (isa<IntegerLiteralInst>(Arg1))
std::swap(Arg1, Arg2);
auto *CmpVal = dyn_cast<IntegerLiteralInst>(Arg2);
if (!CmpVal)
return CaseInfo;
SILBasicBlock *FalseBB = CmpInst->getFalseBB();
if (!FalseBB)
return CaseInfo;
// Check for a common input value.
if (Input && Input != Arg1)
return CaseInfo;
Input = Arg1;
CaseInfo.Result = EI2;
if (CmpInst->getTrueBB() == Pred) {
// This is a case for the select_value.
CaseInfo.Literal = CmpVal;
CaseInfo.CmpOrDefault = CmpBlock;
} else {
// This is the default for the select_value.
CaseInfo.CmpOrDefault = Pred;
}
return CaseInfo;
}
/// Move an instruction which is an operand to the new SelectValueInst to its
/// correct place.
/// Either the instruction is somewhere inside the CFG pattern, then we move it
/// up, immediately before the SelectValueInst in the pattern's dominating
/// entry block. Or it is somewhere above the entry block, then we can leave the
/// instruction there.
void moveIfNotDominating(SILInstruction *I, SILInstruction *InsertPos,
DominanceInfo *DT) {
SILBasicBlock *InstBlock = I->getParent();
SILBasicBlock *InsertBlock = InsertPos->getParent();
if (!DT->dominates(InstBlock, InsertBlock)) {
assert(DT->dominates(InsertBlock, InstBlock));
DEBUG(llvm::dbgs() << " move " << *I);
I->moveBefore(InsertPos);
}
}
/// Simplify a pattern of integer compares to a select_value.
/// \code
/// if input == 1 {
/// result = Enum.A
/// } else if input == 2 {
/// result = Enum.B
/// ...
/// } else {
/// result = Enum.X
/// }
/// \endcode
/// Currently this only works if the input value is an integer and the result
/// value is an enum.
/// \p MergeBlock The "last" block which contains an argument in which all
/// result values are merged.
/// \p ArgNum The index of the block argument which is the result value.
/// \p DT The dominance info.
/// \return Returns true if a select_value is generated.
bool simplifyToSelectValue(SILBasicBlock *MergeBlock, unsigned ArgNum,
DominanceInfo *DT) {
if (!DT)
return false;
// Collect all case infos from the merge block's predecessors.
SmallPtrSet<SILBasicBlock *, 8> FoundCmpBlocks;
SmallVector<CaseInfo, 8> CaseInfos;
SILValue Input;
for (auto *Pred : MergeBlock->getPredecessorBlocks()) {
CaseInfo CaseInfo = getCaseInfo(Input, Pred, ArgNum);
if (!CaseInfo.Result)
return false;
FoundCmpBlocks.insert(CaseInfo.CmpOrDefault);
CaseInfos.push_back(CaseInfo);
}
SmallVector<std::pair<SILValue, SILValue>, 8> Cases;
llvm::SmallDenseMap<SILValue, SILValue> CaseLiteralsToResultMap;
SILValue defaultResult;
// The block of the first input value compare. It dominates all other blocks
// in this CFG pattern.
SILBasicBlock *dominatingBlock = nullptr;
// Build the cases for the SelectValueInst and find the first dominatingBlock.
for (auto &CaseInfo : CaseInfos) {
if (CaseInfo.Literal) {
auto *BrInst = cast<CondBranchInst>(CaseInfo.CmpOrDefault->getTerminator());
if (FoundCmpBlocks.count(BrInst->getFalseBB()) != 1)
return false;
// Ignore duplicate cases
if (CaseLiteralsToResultMap.find(CaseInfo.Literal) ==
CaseLiteralsToResultMap.end()) {
CaseLiteralsToResultMap.insert({CaseInfo.Literal, CaseInfo.Result});
Cases.push_back({CaseInfo.Literal, CaseInfo.Result});
} else {
// Check if the result value matches
EnumInst *PrevResult =
dyn_cast<EnumInst>(CaseLiteralsToResultMap[CaseInfo.Literal]);
assert(PrevResult && "Prev. case result is not an EnumInst");
auto *CurrResult = dyn_cast<EnumInst>(CaseInfo.Result);
assert(CurrResult && "Curr. case result is not an EnumInst");
if (PrevResult->getElement() != CurrResult->getElement()) {
// result value does not match - bail
return false;
}
}
SILBasicBlock *Pred = CaseInfo.CmpOrDefault->getSinglePredecessorBlock();
if (!Pred || FoundCmpBlocks.count(Pred) == 0) {
// There may be only a single block whose predecessor we didn't see. And
// this is the entry block to the CFG pattern.
if (dominatingBlock)
return false;
dominatingBlock = CaseInfo.CmpOrDefault;
}
} else {
if (defaultResult)
return false;
defaultResult = CaseInfo.Result;
}
}
if (!defaultResult)
return false;
if (!dominatingBlock)
return false;
// Generate the select_value right before the first cond_br of the pattern.
SILInstruction *insertPos = dominatingBlock->getTerminator();
SILBuilder B(insertPos);
// Move all needed operands to a place where they dominate the select_value.
for (auto &CaseInfo : CaseInfos) {
if (CaseInfo.Literal)
moveIfNotDominating(CaseInfo.Literal, insertPos, DT);
auto *EI2 = dyn_cast<EnumInst>(CaseInfo.Result);
assert(EI2);
if (EI2->hasOperand()) {
auto *EI1 = dyn_cast<EnumInst>(EI2->getOperand());
assert(EI1);
assert(!EI1->hasOperand());
moveIfNotDominating(EI1, insertPos, DT);
}
moveIfNotDominating(EI2, insertPos, DT);
}
SILArgument *bbArg = MergeBlock->getArgument(ArgNum);
auto SelectInst = B.createSelectValue(dominatingBlock->getTerminator()->getLoc(),
Input, bbArg->getType(),
defaultResult, Cases);
bbArg->replaceAllUsesWith(SelectInst);
DEBUG(llvm::dbgs() << "convert if-structure to " << *SelectInst);
return true;
}
// Attempt to simplify the ith argument of BB. We simplify cases
// where there is a single use of the argument that is an extract from
// a struct, tuple or enum and where the predecessors all build the struct,
// tuple or enum and pass it directly.
bool SimplifyCFG::simplifyArgument(SILBasicBlock *BB, unsigned i) {
auto *A = BB->getArgument(i);
// Try to create a select_value.
if (simplifyToSelectValue(BB, i, DT))
return true;
// If we are reading an i1, then check to see if it comes from
// a switch_enum. If so, we may be able to lower this sequence to
// a select_enum.
if (!DT && A->getType().is<BuiltinIntegerType>())
return simplifySwitchEnumToSelectEnum(BB, i, A);
// For now, just focus on cases where there is a single use.
if (!A->hasOneUse())
return false;
auto *Use = *A->use_begin();
auto *User = cast<SILInstruction>(Use->getUser());
if (!isa<StructExtractInst>(User) &&
!isa<TupleExtractInst>(User) &&
!isa<UncheckedEnumDataInst>(User))
return false;
// For now, just handle the case where all predecessors are
// unconditional branches.
for (auto *Pred : BB->getPredecessorBlocks()) {
if (!isa<BranchInst>(Pred->getTerminator()))
return false;
auto *Branch = cast<BranchInst>(Pred->getTerminator());
SILValue BranchArg = Branch->getArg(i);
if (isa<StructInst>(BranchArg))
continue;
if (isa<TupleInst>(BranchArg))
continue;
if (auto *EI = dyn_cast<EnumInst>(BranchArg)) {
if (EI->getElement() == cast<UncheckedEnumDataInst>(User)->getElement())
continue;
}
return false;
}
// Okay, we'll replace the BB arg with one with the right type, replace
// the uses in this block, and then rewrite the branch operands.
DEBUG(llvm::dbgs() << "unwrap argument:" << *A);
A->replaceAllUsesWith(SILUndef::get(A->getType(), BB->getModule()));
auto *NewArg =
BB->replacePHIArgument(i, User->getType(), ValueOwnershipKind::Owned);
User->replaceAllUsesWith(NewArg);
// Rewrite the branch operand for each incoming branch.
for (auto *Pred : BB->getPredecessorBlocks()) {
if (auto *Branch = cast<BranchInst>(Pred->getTerminator())) {
auto V = getInsertedValue(cast<SILInstruction>(Branch->getArg(i)),
User);
Branch->setOperand(i, V);
addToWorklist(Pred);
}
}
User->eraseFromParent();
return true;
}
static void tryToReplaceArgWithIncomingValue(SILBasicBlock *BB, unsigned i,
DominanceInfo *DT) {
auto *A = BB->getArgument(i);
SmallVector<SILValue, 4> Incoming;
if (!A->getIncomingValues(Incoming) || Incoming.empty())
return;
SILValue V = Incoming[0];
for (size_t Idx = 1, Size = Incoming.size(); Idx < Size; ++Idx) {
if (Incoming[Idx] != V)
return;
}
// If the incoming values of all predecessors are equal usually this means
// that the common incoming value dominates the BB. But: this might be not
// the case if BB is unreachable. Therefore we still have to check it.
if (!DT->dominates(V->getParentBlock(), BB))
return;
// An argument has one result value. We need to replace this with the *value*
// of the incoming block(s).
DEBUG(llvm::dbgs() << "replace arg with incoming value:" << *A);
A->replaceAllUsesWith(V);
}
bool SimplifyCFG::simplifyArgs(SILBasicBlock *BB) {
// Ignore blocks with no arguments.
if (BB->args_empty())
return false;
// Ignore the entry block.
if (BB->pred_empty())
return false;
// Ignore blocks that are successors of terminators with mandatory args.
for (SILBasicBlock *pred : BB->getPredecessorBlocks()) {
if (hasMandatoryArgument(pred->getTerminator()))
return false;
}
bool Changed = false;
for (int i = BB->getNumArguments() - 1; i >= 0; --i) {
SILArgument *A = BB->getArgument(i);
// Replace a block argument if all incoming values are equal. If this
// succeeds, argument A will have no uses afterwards.
if (DT)
tryToReplaceArgWithIncomingValue(BB, i, DT);
// Try to simplify the argument
if (!A->use_empty()) {
if (simplifyArgument(BB, i))
Changed = true;
continue;
}
removeArgument(BB, i);
Changed = true;
}
return Changed;
}
bool SimplifyCFG::simplifyProgramTerminationBlock(SILBasicBlock *BB) {
// If this is not ARC-inert, do not do anything to it.
//
// TODO: should we use ProgramTerminationAnalysis ?. The reason we do not
// use the analysis is because the CFG is likely to be invalidated right
// after this pass, o we do not really get the benefit of reusing the
// computation for the next iteration of the pass.
if (!isARCInertTrapBB(BB))
return false;
// This is going to be the last basic block this program is going to execute
// and this block is inert from the ARC's prospective, no point to do any
// releases at this point.
bool Changed = false;
llvm::SmallPtrSet<SILInstruction *, 4> InstsToRemove;
for (auto &I : *BB) {
// We can only remove the instructions below from the ARC-inert BB
// We *can't* replace copy_addr with move instructions:
// If the copy_addr was [take] [initialization]:
// * previous passes would have replaced it with moves
// If the copy_addr contains [initialization]:
// * nothing we can do - the target address is invalid
// Else, i.e. the copy_addr was [take] assignment, it is not always safe:
// The type being operated on might contain weak references,
// or other side references - We'll corrupt the weak reference table
// if we fail to release the old value.
if (!isa<StrongReleaseInst>(I) && !isa<UnownedReleaseInst>(I) &&
!isa<ReleaseValueInst>(I) && !isa<DestroyAddrInst>(I))
continue;
InstsToRemove.insert(&I);
}
// Remove the instructions.
for (auto I : InstsToRemove) {
I->eraseFromParent();
Changed = true;
}
if (Changed)
++NumTermBlockSimplified;
return Changed;
}
namespace {
class SimplifyCFGPass : public SILFunctionTransform {
bool EnableJumpThread;
public:
SimplifyCFGPass(bool EnableJumpThread)
: EnableJumpThread(EnableJumpThread) {}
/// The entry point to the transformation.
void run() override {
if (SimplifyCFG(*getFunction(), PM, getOptions().VerifyAll,
EnableJumpThread)
.run())
invalidateAnalysis(SILAnalysis::InvalidationKind::FunctionBody);
}
};
} // end anonymous namespace
SILTransform *swift::createSimplifyCFG() {
return new SimplifyCFGPass(false);
}
SILTransform *swift::createJumpThreadSimplifyCFG() {
return new SimplifyCFGPass(true);
}
//===----------------------------------------------------------------------===//
// Passes only for Testing
//===----------------------------------------------------------------------===//
namespace {
// Used to test critical edge splitting with sil-opt.
class SplitCriticalEdges : public SILFunctionTransform {
bool OnlyNonCondBrEdges;
public:
SplitCriticalEdges(bool SplitOnlyNonCondBrEdges)
: OnlyNonCondBrEdges(SplitOnlyNonCondBrEdges) {}
void run() override {
auto &Fn = *getFunction();
// Split all critical edges from all or non only cond_br terminators.
bool Changed =
splitAllCriticalEdges(Fn, OnlyNonCondBrEdges, nullptr, nullptr);
if (Changed) {
invalidateAnalysis(SILAnalysis::InvalidationKind::BranchesAndInstructions);
}
}
};
// Used to test SimplifyCFG::simplifyArgs with sil-opt.
class SimplifyBBArgs : public SILFunctionTransform {
public:
SimplifyBBArgs() {}
/// The entry point to the transformation.
void run() override {
if (SimplifyCFG(*getFunction(), PM, getOptions().VerifyAll, false)
.simplifyBlockArgs()) {
invalidateAnalysis(SILAnalysis::InvalidationKind::BranchesAndInstructions);
}
}
};
// Used to test splitBBArguments with sil-opt
class SROABBArgs : public SILFunctionTransform {
public:
SROABBArgs() {}
void run() override {
if (splitBBArguments(*getFunction())) {
invalidateAnalysis(SILAnalysis::InvalidationKind::BranchesAndInstructions);
}
}
};
// Used to test tryMoveCondFailToPreds with sil-opt
class MoveCondFailToPreds : public SILFunctionTransform {
public:
MoveCondFailToPreds() {}
void run() override {
for (auto &BB : *getFunction()) {
if (tryMoveCondFailToPreds(&BB)) {
invalidateAnalysis(
SILAnalysis::InvalidationKind::BranchesAndInstructions);
}
}
}
};
} // end anonymous namespace
/// Splits all critical edges in a function.
SILTransform *swift::createSplitAllCriticalEdges() {
return new SplitCriticalEdges(false);
}
/// Splits all critical edges from non cond_br terminators in a function.
SILTransform *swift::createSplitNonCondBrCriticalEdges() {
return new SplitCriticalEdges(true);
}
// Simplifies basic block arguments.
SILTransform *swift::createSROABBArgs() { return new SROABBArgs(); }
// Simplifies basic block arguments.
SILTransform *swift::createSimplifyBBArgs() {
return new SimplifyBBArgs();
}
// Moves cond_fail instructions to predecessors.
SILTransform *swift::createMoveCondFailToPreds() {
return new MoveCondFailToPreds();
}
|
/*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#include "MotionSetsWindowPlugin.h"
#include <QPushButton>
#include <QLabel>
#include <QWidget>
#include <QHeaderView>
#include <QApplication>
#include <QMenu>
#include <QFileDialog>
#include <QMessageBox>
#include <QContextMenuEvent>
#include <QTableWidget>
#include <EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/Commands.h>
#include <EMotionFX/CommandSystem/Source/MotionCommands.h>
#include "../../../../EMStudioSDK/Source/MainWindow.h"
#include "../../../../EMStudioSDK/Source/FileManager.h"
#include <MCore/Source/LogManager.h>
#include <MCore/Source/IDGenerator.h>
#include <Editor/AnimGraphEditorBus.h>
#include <EMotionFX/Source/MotionManager.h>
#include <EMotionFX/Source/MotionSystem.h>
#include <EMotionFX/Source/MotionSet.h>
#include "../../../../EMStudioSDK/Source/EMStudioManager.h"
#include <EMotionStudio/Plugins/StandardPlugins/Source/MotionWindow/MotionPropertiesWindow.h>
#include <Editor/SaveDirtyFilesCallbacks.h>
#include <AzCore/Debug/Trace.h>
#include <AzFramework/API/ApplicationAPI.h>
namespace EMStudio
{
MotionSetsWindowPlugin::MotionSetsWindowPlugin()
: EMStudio::DockWidgetPlugin()
{
m_dialogStack = nullptr;
m_selectedSet = nullptr;
m_motionSetManagementWindow = nullptr;
m_motionSetWindow = nullptr;
}
MotionSetsWindowPlugin::~MotionSetsWindowPlugin()
{
delete m_motionPropertiesWindow;
m_motionPropertiesWindow = nullptr;
for (MCore::Command::Callback* callback : m_callbacks)
{
GetCommandManager()->RemoveCommandCallback(callback, false);
delete callback;
}
}
// init after the parent dock window has been created
bool MotionSetsWindowPlugin::Init()
{
CommandSystem::CommandManager* commandManager = GetCommandManager();
commandManager->RegisterCommandCallback<CommandReinitCallback>("RemoveMotionSet", m_callbacks, false);
commandManager->RegisterCommandCallback<CommandReinitCallback>("RemoveMotion", m_callbacks, false);
commandManager->RegisterCommandCallback<CommandAdjustMotionSetCallback>("AdjustMotionSet", m_callbacks, false);
commandManager->RegisterCommandCallback<CommandMotionSetAddMotionCallback>("MotionSetAddMotion", m_callbacks, false);
commandManager->RegisterCommandCallback<CommandMotionSetRemoveMotionCallback>("MotionSetRemoveMotion", m_callbacks, false);
commandManager->RegisterCommandCallback<CommandMotionSetAdjustMotionCallback>("MotionSetAdjustMotion", m_callbacks, false);
commandManager->RegisterCommandCallback<CommandCreateMotionSetCallback>("CreateMotionSet", m_callbacks, false);
commandManager->RegisterCommandCallback<CommandLoadMotionSetCallback>("LoadMotionSet", m_callbacks, false);
commandManager->RegisterCommandCallback<CommandAdjustMotionCallback>("AdjustMotion", m_callbacks, false);
commandManager->RegisterCommandCallback<CommandAdjustDefaultPlayBackInfoCallback>("AdjustDefaultPlayBackInfo", m_callbacks, false);
commandManager->RegisterCommandCallback<CommandSaveMotionAssetInfoCallback>("SaveMotionAssetInfo", m_callbacks, false);
// create the dialog stack
assert(m_dialogStack == nullptr);
m_dialogStack = new MysticQt::DialogStack(m_dock);
m_dock->setWidget(m_dialogStack);
// connect the window activation signal to refresh if reactivated
connect(m_dock, &QDockWidget::visibilityChanged, this, &MotionSetsWindowPlugin::WindowReInit);
m_motionPropertiesWindow = new MotionPropertiesWindow(nullptr);
m_motionPropertiesWindow->hide();
// create the set management window
m_motionSetManagementWindow = new MotionSetManagementWindow(this, m_dialogStack);
m_motionSetManagementWindow->Init();
m_dialogStack->Add(m_motionSetManagementWindow, "Motion Set Management", /*closed=*/false, /*maximizeSize=*/false, /*closable=*/true, /*strecthWhenMaximize=*/false);
// create the motion set properties window
m_motionSetWindow = new MotionSetWindow(this, m_dialogStack);
m_motionSetWindow->Init();
m_dialogStack->Add(m_motionSetWindow, "Motion Set", /*closed=*/false, /*maximizeSize=*/true);
ReInit();
CommandSystem::CreateDefaultMotionSet();
return true;
}
EMotionFX::MotionSet* MotionSetsWindowPlugin::GetSelectedSet() const
{
if (EMotionFX::GetMotionManager().FindMotionSetIndex(m_selectedSet) == InvalidIndex)
{
return nullptr;
}
return m_selectedSet;
}
void MotionSetsWindowPlugin::ReInit()
{
// Validate existence of selected motion set and reset selection in case selection is invalid.
if (EMotionFX::GetMotionManager().FindMotionSetIndex(m_selectedSet) == InvalidIndex)
{
m_selectedSet = nullptr;
}
SetSelectedSet(m_selectedSet);
m_motionSetManagementWindow->ReInit();
m_motionSetWindow->ReInit();
}
void MotionSetsWindowPlugin::SetSelectedSet(EMotionFX::MotionSet* motionSet, bool clearSelectionUpfront)
{
m_selectedSet = motionSet;
if (motionSet)
{
m_motionSetManagementWindow->SelectItemsById(motionSet->GetID(), clearSelectionUpfront);
}
m_motionSetManagementWindow->ReInit();
m_motionSetManagementWindow->UpdateInterface();
m_motionSetWindow->ReInit();
m_motionSetWindow->UpdateInterface();
}
// reinit the window when it gets activated
void MotionSetsWindowPlugin::WindowReInit(bool visible)
{
if (visible)
{
ReInit();
}
}
void MotionSetsWindowPlugin::LoadMotionSet(AZStd::string filename)
{
if (filename.empty())
{
return;
}
// Auto-relocate to asset source folder.
if (!GetMainWindow()->GetFileManager()->RelocateToAssetSourceFolder(filename))
{
const AZStd::string errorString = AZStd::string::format("Unable to find MotionSet -filename \"%s\"", filename.c_str());
AZ_Error("EMotionFX", false, errorString.c_str());
return;
}
const AZStd::string command = AZStd::string::format("LoadMotionSet -filename \"%s\"", filename.c_str());
AZStd::string result;
if (!EMStudio::GetCommandManager()->ExecuteCommand(command, result))
{
AZ_Error("EMotionFX", false, result.c_str());
}
}
//-----------------------------------------------------------------------------------------
// Command callbacks
//-----------------------------------------------------------------------------------------
MotionSetsWindowPlugin* GetMotionSetWindowPlugin()
{
EMStudioPlugin* plugin = EMStudio::GetPluginManager()->FindActivePlugin(MotionSetsWindowPlugin::CLASS_ID);
if (plugin)
{
return static_cast<MotionSetsWindowPlugin*>(plugin);
}
return nullptr;
}
bool ReInitMotionSetsPlugin()
{
MotionSetsWindowPlugin* motionSetsPlugin = GetMotionSetWindowPlugin();
if (motionSetsPlugin)
{
motionSetsPlugin->ReInit();
}
return true;
}
bool UpdateMotionSetsPlugin()
{
MotionSetsWindowPlugin* motionSetsPlugin = GetMotionSetWindowPlugin();
if (motionSetsPlugin)
{
motionSetsPlugin->SetSelectedSet(motionSetsPlugin->GetSelectedSet());
}
return true;
}
bool MotionSetsWindowPlugin::GetMotionSetCommandInfo(MCore::Command* command, const MCore::CommandLine& parameters, EMotionFX::MotionSet** outMotionSet, MotionSetsWindowPlugin** outPlugin)
{
// Get the motion set id and find the corresponding motion set.
const int32 motionSetID = parameters.GetValueAsInt("motionSetID", command);
EMotionFX::MotionSet* motionSet = EMotionFX::GetMotionManager().FindMotionSetByID(motionSetID);
if (!motionSet)
{
return false;
}
// Get the plugin and add the motion entry to the user interface.
EMStudioPlugin* plugin = EMStudio::GetPluginManager()->FindActivePlugin(MotionSetsWindowPlugin::CLASS_ID);
if (!plugin)
{
return false;
}
MotionSetsWindowPlugin* motionSetsPlugin = (MotionSetsWindowPlugin*)plugin;
*outMotionSet = motionSet;
*outPlugin = motionSetsPlugin;
return true;
}
EMotionFX::MotionSet::MotionEntry* MotionSetsWindowPlugin::FindBestMatchMotionEntryById(const AZStd::string& motionId)
{
// Find motion entry by motionId through motion sets, return nullptr if not found.
const CommandSystem::SelectionList& selectionList = GetCommandManager()->GetCurrentSelection();
EMotionFX::MotionSet* motionSet = nullptr;
EMotionFX::MotionSet::MotionEntry* motionEntry = nullptr;
// Look for motion entry in animgraph instance of the selected actor instance.
EMotionFX::ActorInstance* actorInstance = selectionList.GetSingleActorInstance();
if (actorInstance)
{
EMotionFX::AnimGraphInstance* animGraphInstance = actorInstance->GetAnimGraphInstance();
if (animGraphInstance)
{
EMotionFX::MotionSet* animGraphInstanceMotionSet = animGraphInstance->GetMotionSet();
if (animGraphInstanceMotionSet)
{
motionEntry = animGraphInstanceMotionSet->RecursiveFindMotionEntryById(motionId);
if (motionEntry)
{
return motionEntry;
}
}
}
}
// If motion entry not found, look in MotionSet combo box of the AnimGraph Editor, find the motion entry by motionId.
EMotionFX::AnimGraphEditorRequestBus::BroadcastResult(motionSet, &EMotionFX::AnimGraphEditorRequests::GetSelectedMotionSet);
if (motionSet)
{
motionEntry = motionSet->RecursiveFindMotionEntryById(motionId);
if (motionEntry)
{
return motionEntry;
}
}
// If motion entry is still not found, look through all motion sets not owned by runtime.
const EMotionFX::MotionManager& motionManager = EMotionFX::GetMotionManager();
for(size_t i = 0; i < motionManager.GetNumMotionSets(); ++i)
{
motionSet = motionManager.GetMotionSet(i);
if (motionSet->GetIsOwnedByRuntime())
{
continue;
}
motionEntry = motionSet->RecursiveFindMotionEntryById(motionId);
if (motionEntry)
{
return motionEntry;
}
}
return nullptr;
}
bool MotionSetsWindowPlugin::CommandReinitCallback::Execute([[maybe_unused]] MCore::Command* command, const MCore::CommandLine& commandLine)
{
MCORE_UNUSED(commandLine);
return ReInitMotionSetsPlugin();
}
bool MotionSetsWindowPlugin::CommandReinitCallback::Undo(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); MCORE_UNUSED(commandLine); return ReInitMotionSetsPlugin(); }
bool MotionSetsWindowPlugin::CommandAdjustMotionSetCallback::Execute(MCore::Command* command, const MCore::CommandLine& commandLine)
{
MCORE_UNUSED(command);
if (commandLine.CheckIfHasParameter("newName"))
{
// add it to the interfaces
EMStudioPlugin* plugin = EMStudio::GetPluginManager()->FindActivePlugin(MotionSetsWindowPlugin::CLASS_ID);
if (plugin == nullptr)
{
return false;
}
MotionSetsWindowPlugin* motionSetsPlugin = (MotionSetsWindowPlugin*)plugin;
motionSetsPlugin->GetManagementWindow()->ReInit();
}
return true;
}
bool MotionSetsWindowPlugin::CommandAdjustMotionSetCallback::Undo(MCore::Command* command, const MCore::CommandLine& commandLine)
{
MCORE_UNUSED(command);
if (commandLine.CheckIfHasParameter("newName"))
{
// add it to the interfaces
EMStudioPlugin* plugin = EMStudio::GetPluginManager()->FindActivePlugin(MotionSetsWindowPlugin::CLASS_ID);
if (plugin == nullptr)
{
return false;
}
MotionSetsWindowPlugin* motionSetsPlugin = (MotionSetsWindowPlugin*)plugin;
motionSetsPlugin->GetManagementWindow()->ReInit();
}
return true;
}
bool MotionSetsWindowPlugin::CommandMotionSetAddMotionCallback::Execute(MCore::Command* command, const MCore::CommandLine& commandLine)
{
MCORE_UNUSED(command);
MCORE_UNUSED(commandLine);
UpdateMotionSetsPlugin();
return true;
}
bool MotionSetsWindowPlugin::CommandMotionSetAddMotionCallback::Undo(MCore::Command* command, const MCore::CommandLine& commandLine)
{
MCORE_UNUSED(command);
MCORE_UNUSED(commandLine);
// Calls the MotionSetRemoveMotion command internally, so the callback from that is already called.
return true;
}
bool MotionSetsWindowPlugin::CommandMotionSetRemoveMotionCallback::Execute(MCore::Command* command, const MCore::CommandLine& commandLine)
{
MCORE_UNUSED(command);
MCORE_UNUSED(commandLine);
UpdateMotionSetsPlugin();
return true;
}
bool MotionSetsWindowPlugin::CommandMotionSetRemoveMotionCallback::Undo(MCore::Command* command, const MCore::CommandLine& commandLine)
{
MCORE_UNUSED(command);
MCORE_UNUSED(commandLine);
// Calls the MotionSetAddMotion command internally, so the callback from that is already called.
return true;
}
bool CommandMotionSetAdjustMotionCallbackHelper(MCore::Command* command, const MCore::CommandLine& commandLine, const char* newMotionId, const char* oldMotionId)
{
EMotionFX::MotionSet* motionSet = nullptr;
MotionSetsWindowPlugin* plugin = nullptr;
if (!MotionSetsWindowPlugin::GetMotionSetCommandInfo(command, commandLine, &motionSet, &plugin))
{
return false;
}
// Find the corresponding motion entry.
EMotionFX::MotionSet::MotionEntry* motionEntry = motionSet->FindMotionEntryById(newMotionId);
if (!motionEntry)
{
return false;
}
return plugin->GetMotionSetWindow()->UpdateMotion(motionSet, motionEntry, oldMotionId);
}
bool MotionSetsWindowPlugin::CommandMotionSetAdjustMotionCallback::Execute(MCore::Command* command, const MCore::CommandLine& commandLine)
{
// Get the previous motion id.
AZStd::string newMotionId;
AZStd::string oldMotionId;
if (commandLine.CheckIfHasParameter("newIDString"))
{
commandLine.GetValue("newIDString", command, newMotionId);
commandLine.GetValue("idString", command, oldMotionId);
}
else
{
commandLine.GetValue("idString", command, newMotionId);
commandLine.GetValue("idString", command, oldMotionId);
}
return CommandMotionSetAdjustMotionCallbackHelper(command, commandLine, newMotionId.c_str(), oldMotionId.c_str());
}
bool MotionSetsWindowPlugin::CommandMotionSetAdjustMotionCallback::Undo(MCore::Command* command, const MCore::CommandLine& commandLine)
{
MCORE_UNUSED(command);
MCORE_UNUSED(commandLine);
// Calls the MotionSetAdjustMotion command internally, so the callback from that is already called.
return true;
}
bool MotionSetsWindowPlugin::CommandCreateMotionSetCallback::Execute(MCore::Command* command, [[maybe_unused]] const MCore::CommandLine& commandLine)
{
MotionSetsWindowPlugin* motionSetsPlugin = GetMotionSetWindowPlugin();
if (motionSetsPlugin)
{
CommandSystem::CommandCreateMotionSet* createCommand = static_cast<CommandSystem::CommandCreateMotionSet*>(command);
EMotionFX::MotionSet* motionSet = EMotionFX::GetMotionManager().FindMotionSetByID(createCommand->m_previouslyUsedId);
if (motionSet)
{
motionSetsPlugin->SetSelectedSet(motionSet, /*clearSelectionUpfront=*/true);
}
}
return true;
}
bool MotionSetsWindowPlugin::CommandCreateMotionSetCallback::Undo([[maybe_unused]] MCore::Command* command, [[maybe_unused]] const MCore::CommandLine& commandLine)
{
return true;
}
bool MotionSetsWindowPlugin::CommandLoadMotionSetCallback::Execute(MCore::Command* command, const MCore::CommandLine& commandLine)
{
MCORE_UNUSED(command);
AZStd::string filename;
commandLine.GetValue("filename", command, filename);
EBUS_EVENT(AzFramework::ApplicationRequests::Bus, NormalizePathKeepCase, filename);
CommandEditorLoadAnimGraph::RelocateFilename(filename);
EMotionFX::MotionSet* motionSet = EMotionFX::GetMotionManager().FindMotionSetByFileName(filename.c_str());
if (motionSet == nullptr)
{
AZ_Error("Animation", false, "Cannot find motion set.");
return false;
}
if (!ReInitMotionSetsPlugin())
{
return false;
}
MotionSetsWindowPlugin* motionSetsPlugin = GetMotionSetWindowPlugin();
if (motionSetsPlugin)
{
motionSetsPlugin->SetSelectedSet(motionSet, /*clearSelectionUpfront=*/true);
}
return true;
}
bool MotionSetsWindowPlugin::CommandLoadMotionSetCallback::Undo(MCore::Command* command, const MCore::CommandLine& commandLine)
{
MCORE_UNUSED(command);
MCORE_UNUSED(commandLine);
return ReInitMotionSetsPlugin();
}
bool MotionSetsWindowPlugin::CommandAdjustMotionCallback::Execute(MCore::Command* command, [[maybe_unused]] const MCore::CommandLine& commandLine)
{
MotionSetsWindowPlugin* motionSetsPlugin = GetMotionSetWindowPlugin();
if (motionSetsPlugin)
{
CommandSystem::CommandAdjustMotion* adjustMotionCommand = static_cast<CommandSystem::CommandAdjustMotion*>(command);
motionSetsPlugin->GetMotionSetWindow()->SyncMotionDirtyFlag(adjustMotionCommand->GetMotionID());
}
return true;
}
bool MotionSetsWindowPlugin::CommandAdjustMotionCallback::Undo(MCore::Command* command, [[maybe_unused]] const MCore::CommandLine& commandLine)
{
return Execute(command, commandLine);
}
bool MotionSetsWindowPlugin::CommandAdjustDefaultPlayBackInfoCallback::Execute(MCore::Command* command, const MCore::CommandLine& commandLine)
{
MotionSetsWindowPlugin* motionSetsPlugin = GetMotionSetWindowPlugin();
if (motionSetsPlugin)
{
EMotionFX::Motion* motion = CommandSystem::CommandAdjustDefaultPlayBackInfo::GetMotionFromFilenameParameter(command, commandLine);
if (motion)
{
motionSetsPlugin->GetMotionSetWindow()->SyncMotionDirtyFlag(motion->GetID());
}
}
return true;
}
bool MotionSetsWindowPlugin::CommandAdjustDefaultPlayBackInfoCallback::Undo(MCore::Command* command, const MCore::CommandLine& commandLine)
{
return Execute(command, commandLine);
}
bool MotionSetsWindowPlugin::CommandSaveMotionAssetInfoCallback::Execute(MCore::Command* command, const MCore::CommandLine& commandLine)
{
MotionSetsWindowPlugin* motionSetsPlugin = GetMotionSetWindowPlugin();
if (motionSetsPlugin)
{
const int32 motionId = commandLine.GetValueAsInt("motionID", command);
motionSetsPlugin->GetMotionSetWindow()->SyncMotionDirtyFlag(motionId);
}
return true;
}
bool MotionSetsWindowPlugin::CommandSaveMotionAssetInfoCallback::Undo(MCore::Command* command, const MCore::CommandLine& commandLine)
{
return Execute(command, commandLine);
}
int MotionSetsWindowPlugin::OnSaveDirtyMotionSets()
{
return GetMainWindow()->GetDirtyFileManager()->SaveDirtyFiles(SaveDirtyMotionSetFilesCallback::TYPE_ID);
}
void MotionSetsWindowPlugin::OnAfterLoadProject()
{
ReInitMotionSetsPlugin();
}
} // namespace EMStudio
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "irc.h"
#include "net.h"
#include "strlcpy.h"
#include "base58.h"
using namespace std;
using namespace boost;
int nGotIRCAddresses = 0;
void ThreadIRCSeed2(void* parg);
#pragma pack(push, 1)
struct ircaddr
{
struct in_addr ip;
short port;
};
#pragma pack(pop)
string EncodeAddress(const CService& addr)
{
struct ircaddr tmp;
if (addr.GetInAddr(&tmp.ip))
{
tmp.port = htons(addr.GetPort());
vector<unsigned char> vch(UBEGIN(tmp), UEND(tmp));
return string("u") + EncodeBase58Check(vch);
}
return "";
}
bool DecodeAddress(string str, CService& addr)
{
vector<unsigned char> vch;
if (!DecodeBase58Check(str.substr(1), vch))
return false;
struct ircaddr tmp;
if (vch.size() != sizeof(tmp))
return false;
memcpy(&tmp, &vch[0], sizeof(tmp));
addr = CService(tmp.ip, ntohs(tmp.port));
return true;
}
static bool Send(SOCKET hSocket, const char* pszSend)
{
if (strstr(pszSend, "PONG") != pszSend)
printf("IRC SENDING: %s\n", pszSend);
const char* psz = pszSend;
const char* pszEnd = psz + strlen(psz);
while (psz < pszEnd)
{
int ret = send(hSocket, psz, pszEnd - psz, MSG_NOSIGNAL);
if (ret < 0)
return false;
psz += ret;
}
return true;
}
bool RecvLineIRC(SOCKET hSocket, string& strLine)
{
while (true)
{
bool fRet = RecvLine(hSocket, strLine);
if (fRet)
{
if (fShutdown)
return false;
vector<string> vWords;
ParseString(strLine, ' ', vWords);
if (vWords.size() >= 1 && vWords[0] == "PING")
{
strLine[1] = 'O';
strLine += '\r';
Send(hSocket, strLine.c_str());
continue;
}
}
return fRet;
}
}
int RecvUntil(SOCKET hSocket, const char* psz1, const char* psz2=NULL, const char* psz3=NULL, const char* psz4=NULL)
{
while (true)
{
string strLine;
strLine.reserve(10000);
if (!RecvLineIRC(hSocket, strLine))
return 0;
printf("IRC %s\n", strLine.c_str());
if (psz1 && strLine.find(psz1) != string::npos)
return 1;
if (psz2 && strLine.find(psz2) != string::npos)
return 2;
if (psz3 && strLine.find(psz3) != string::npos)
return 3;
if (psz4 && strLine.find(psz4) != string::npos)
return 4;
}
}
bool Wait(int nSeconds)
{
if (fShutdown)
return false;
printf("IRC waiting %d seconds to reconnect\n", nSeconds);
for (int i = 0; i < nSeconds; i++)
{
if (fShutdown)
return false;
MilliSleep(1000);
}
return true;
}
bool RecvCodeLine(SOCKET hSocket, const char* psz1, string& strRet)
{
strRet.clear();
while (true)
{
string strLine;
if (!RecvLineIRC(hSocket, strLine))
return false;
vector<string> vWords;
ParseString(strLine, ' ', vWords);
if (vWords.size() < 2)
continue;
if (vWords[1] == psz1)
{
printf("IRC %s\n", strLine.c_str());
strRet = strLine;
return true;
}
}
}
bool GetIPFromIRC(SOCKET hSocket, string strMyName, CNetAddr& ipRet)
{
Send(hSocket, strprintf("USERHOST %s\r", strMyName.c_str()).c_str());
string strLine;
if (!RecvCodeLine(hSocket, "302", strLine))
return false;
vector<string> vWords;
ParseString(strLine, ' ', vWords);
if (vWords.size() < 4)
return false;
string str = vWords[3];
if (str.rfind("@") == string::npos)
return false;
string strHost = str.substr(str.rfind("@")+1);
// Hybrid IRC used by lfnet always returns IP when you userhost yourself,
// but in case another IRC is ever used this should work.
printf("GetIPFromIRC() got userhost %s\n", strHost.c_str());
CNetAddr addr(strHost, true);
if (!addr.IsValid())
return false;
ipRet = addr;
return true;
}
void ThreadIRCSeed(void* parg)
{
// Make this thread recognisable as the IRC seeding thread
RenameThread("betscoin-ircseed");
try
{
ThreadIRCSeed2(parg);
}
catch (std::exception& e) {
PrintExceptionContinue(&e, "ThreadIRCSeed()");
} catch (...) {
PrintExceptionContinue(NULL, "ThreadIRCSeed()");
}
printf("ThreadIRCSeed exited\n");
}
void ThreadIRCSeed2(void* parg)
{
// Don't connect to IRC if we won't use IPv4 connections.
if (IsLimited(NET_IPV4))
return;
// ... or if we won't make outbound connections and won't accept inbound ones.
if (mapArgs.count("-connect") && fNoListen)
return;
// ... or if IRC is not enabled.
if (!GetBoolArg("-irc", false))
return;
printf("ThreadIRCSeed started\n");
int nErrorWait = 10;
int nRetryWait = 10;
int nNameRetry = 0;
while (!fShutdown)
{
CService addrConnect("92.243.23.21", 6667); // irc.lfnet.org
CService addrIRC("irc.lfnet.org", 6667, true);
if (addrIRC.IsValid())
addrConnect = addrIRC;
SOCKET hSocket;
if (!ConnectSocket(addrConnect, hSocket))
{
printf("IRC connect failed\n");
nErrorWait = nErrorWait * 11 / 10;
if (Wait(nErrorWait += 60))
continue;
else
return;
}
if (!RecvUntil(hSocket, "Found your hostname", "using your IP address instead", "Couldn't look up your hostname", "ignoring hostname"))
{
closesocket(hSocket);
hSocket = INVALID_SOCKET;
nErrorWait = nErrorWait * 11 / 10;
if (Wait(nErrorWait += 60))
continue;
else
return;
}
CNetAddr addrIPv4("1.2.3.4"); // arbitrary IPv4 address to make GetLocal prefer IPv4 addresses
CService addrLocal;
string strMyName;
// Don't use our IP as our nick if we're not listening
// or if it keeps failing because the nick is already in use.
if (!fNoListen && GetLocal(addrLocal, &addrIPv4) && nNameRetry<3)
strMyName = EncodeAddress(GetLocalAddress(&addrConnect));
if (strMyName == "")
strMyName = strprintf("x%"PRIu64"", GetRand(1000000000));
Send(hSocket, strprintf("NICK %s\r", strMyName.c_str()).c_str());
Send(hSocket, strprintf("USER %s 8 * : %s\r", strMyName.c_str(), strMyName.c_str()).c_str());
int nRet = RecvUntil(hSocket, " 004 ", " 433 ");
if (nRet != 1)
{
closesocket(hSocket);
hSocket = INVALID_SOCKET;
if (nRet == 2)
{
printf("IRC name already in use\n");
nNameRetry++;
Wait(10);
continue;
}
nErrorWait = nErrorWait * 11 / 10;
if (Wait(nErrorWait += 60))
continue;
else
return;
}
nNameRetry = 0;
MilliSleep(500);
// Get our external IP from the IRC server and re-nick before joining the channel
CNetAddr addrFromIRC;
if (GetIPFromIRC(hSocket, strMyName, addrFromIRC))
{
printf("GetIPFromIRC() returned %s\n", addrFromIRC.ToString().c_str());
// Don't use our IP as our nick if we're not listening
if (!fNoListen && addrFromIRC.IsRoutable())
{
// IRC lets you to re-nick
AddLocal(addrFromIRC, LOCAL_IRC);
strMyName = EncodeAddress(GetLocalAddress(&addrConnect));
Send(hSocket, strprintf("NICK %s\r", strMyName.c_str()).c_str());
}
}
if (fTestNet) {
Send(hSocket, "JOIN #betscoinTEST\r");
Send(hSocket, "WHO #betscoinTEST\r");
} else {
// randomly join #betscoin00-#betscoin05
int channel_number = GetRandInt(5);
// Channel number is always 0 for initial release
//int channel_number = 0;
Send(hSocket, strprintf("JOIN #betscoin%02d\r", channel_number).c_str());
Send(hSocket, strprintf("WHO #betscoin%02d\r", channel_number).c_str());
}
int64_t nStart = GetTime();
string strLine;
strLine.reserve(10000);
while (!fShutdown && RecvLineIRC(hSocket, strLine))
{
if (strLine.empty() || strLine.size() > 900 || strLine[0] != ':')
continue;
vector<string> vWords;
ParseString(strLine, ' ', vWords);
if (vWords.size() < 2)
continue;
char pszName[10000];
pszName[0] = '\0';
if (vWords[1] == "352" && vWords.size() >= 8)
{
// index 7 is limited to 16 characters
// could get full length name at index 10, but would be different from join messages
strlcpy(pszName, vWords[7].c_str(), sizeof(pszName));
printf("IRC got who\n");
}
if (vWords[1] == "JOIN" && vWords[0].size() > 1)
{
// :username!username@50000007.F000000B.90000002.IP JOIN :#channelname
strlcpy(pszName, vWords[0].c_str() + 1, sizeof(pszName));
if (strchr(pszName, '!'))
*strchr(pszName, '!') = '\0';
printf("IRC got join\n");
}
if (pszName[0] == 'u')
{
CAddress addr;
if (DecodeAddress(pszName, addr))
{
addr.nTime = GetAdjustedTime();
if (addrman.Add(addr, addrConnect, 51 * 60))
printf("IRC got new address: %s\n", addr.ToString().c_str());
nGotIRCAddresses++;
}
else
{
printf("IRC decode failed\n");
}
}
}
closesocket(hSocket);
hSocket = INVALID_SOCKET;
if (GetTime() - nStart > 20 * 60)
{
nErrorWait /= 3;
nRetryWait /= 3;
}
nRetryWait = nRetryWait * 11 / 10;
if (!Wait(nRetryWait += 60))
return;
}
}
#ifdef TEST
int main(int argc, char *argv[])
{
WSADATA wsadata;
if (WSAStartup(MAKEWORD(2,2), &wsadata) != NO_ERROR)
{
printf("Error at WSAStartup()\n");
return false;
}
ThreadIRCSeed(NULL);
WSACleanup();
return 0;
}
#endif
|
/*
===========================================================================
The Open Game Libraries.
Copyright (C) 2007-2010 Lusito Software
Author: Santo Pfingsten (TTK-Bandit)
Purpose: Dynamic Buffer
-----------------------------------------
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.
===========================================================================
*/
#ifndef __OG_DYNBUFFER_INL__
#define __OG_DYNBUFFER_INL__
namespace og {
/*
==============================================================================
DynBuffer
==============================================================================
*/
/*
================
DynBuffer::DynBuffer
================
*/
template<class T>
OG_INLINE DynBuffer<T>::DynBuffer( int _size ) {
size = _size;
if ( size > 0 )
data = new T[size];
else
data = NULL;
}
/*
================
DynBuffer::~DynBuffer
================
*/
template<class T>
OG_INLINE DynBuffer<T>::~DynBuffer() {
Clear();
}
/*
================
DynBuffer::Clear
================
*/
template<class T>
OG_INLINE void DynBuffer<T>::Clear( void ) {
SafeDeleteArray( data );
size = 0;
}
/*
================
DynBuffer::CheckSize
================
*/
template<class T>
OG_INLINE void DynBuffer<T>::CheckSize( int newSize ) {
if ( newSize > size ) {
delete[] data;
size = newSize;
data = new T[size];
}
}
}
#endif
|
//
// AnalyticsManager.cpp
// Implementation of the AnalyticsManager class.
//
#include "pch.h"
#include "AnalyticsManager.h"
#include "TimeSpanHelper.h"
#include "DateTimeHelper.h"
#include "HitBuilder.h"
using namespace GoogleAnalytics;
using namespace Platform;
using namespace Platform::Collections;
using namespace Windows::UI::Core;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Windows::System::Threading;
using namespace concurrency;
using namespace Windows::Web::Http;
using namespace Windows::Storage;
using namespace Windows::Networking::Connectivity;
using namespace Windows::ApplicationModel;
using namespace Windows::ApplicationModel::Core;
String^ AnalyticsManager::Key_AppOptOut = "GoogleAnaltyics.AppOptOut";
AnalyticsManager^ AnalyticsManager::current = nullptr;
Uri^ AnalyticsManager::endPointUnsecureDebug = ref new Uri("http://www.google-analytics.com/debug/collect");
Uri^ AnalyticsManager::endPointSecureDebug = ref new Uri("https://ssl.google-analytics.com/debug/collect");
Uri^ AnalyticsManager::endPointUnsecure = ref new Uri("http://www.google-analytics.com/collect");
Uri^ AnalyticsManager::endPointSecure = ref new Uri("https://ssl.google-analytics.com/collect");
AnalyticsManager^ AnalyticsManager::Current::get()
{
if (!current)
{
current = ref new AnalyticsManager(ref new GoogleAnalytics::PlatformInfoProvider());
}
return current;
}
AnalyticsManager::AnalyticsManager(GoogleAnalytics::IPlatformInfoProvider^ platformInfoProvider) :
isEnabled(true),
timer(nullptr),
hitTokenBucket(ref new TokenBucket(60, .5)),
reportUncaughtExceptions(false),
autoTrackNetworkConnectivity(false),
autoAppLifetimeMonitoring(false),
fireEventsOnUIThread(false),
dispatcher(nullptr),
hitSentListenerCount(0), hitMalformedListenerCount(0), hitFailedListenerCount(0)
{
this->platformTrackingInfo = platformInfoProvider;
DefaultTracker = nullptr;
AppOptOut = false;
IsSecure = true;
PostData = true;
BustCache = false;
dispatchPeriod = TimeSpanHelper::FromTicks(0);
}
Tracker^ AnalyticsManager::CreateTracker(String^ propertyId)
{
if (trackers.find(propertyId) == end(trackers))
{
auto tracker = ref new Tracker(propertyId, platformTrackingInfo, this);
tracker->AppName = Package::Current->Id->Name;
tracker->AppVersion = Package::Current->Id->Version.Major.ToString() + "." + Package::Current->Id->Version.Minor.ToString() + "." + Package::Current->Id->Version.Build.ToString() + "." + Package::Current->Id->Version.Revision.ToString();
trackers[propertyId] = tracker;
if (!DefaultTracker)
{
DefaultTracker = tracker;
}
return tracker;
}
else
{
return trackers[propertyId];
}
}
void AnalyticsManager::CloseTracker(Tracker^ tracker)
{
trackers.erase(tracker->PropertyId);
if (DefaultTracker == tracker)
{
DefaultTracker = nullptr;
}
}
TimeSpan AnalyticsManager::DispatchPeriod::get()
{
return dispatchPeriod;
}
void AnalyticsManager::DispatchPeriod::set(TimeSpan value)
{
if (dispatchPeriod.Duration != value.Duration)
{
dispatchPeriod = value;
if (timer)
{
timer->Cancel();
timer = nullptr;
}
if (dispatchPeriod.Duration > 0)
{
timer = ThreadPoolTimer::CreatePeriodicTimer(ref new TimerElapsedHandler(this, &AnalyticsManager::timer_Tick), dispatchPeriod);
}
}
}
bool AnalyticsManager::IsEnabled::get()
{
return isEnabled;
}
void AnalyticsManager::IsEnabled::set(bool value)
{
if (isEnabled != value)
{
isEnabled = value;
if (isEnabled)
{
if (dispatchPeriod.Duration >= 0)
{
DispatchAsync();
}
}
}
}
bool AnalyticsManager::FireEventsOnUIThread::get()
{
return fireEventsOnUIThread;
}
void AnalyticsManager::FireEventsOnUIThread::set(bool value)
{
if (fireEventsOnUIThread != value)
{
if (value)
{
if (dispatcher == nullptr)
{
auto window = CoreWindow::GetForCurrentThread();
if (window != nullptr)
{
dispatcher = window->Dispatcher;
}
if (dispatcher == nullptr)
{
throw ref new WrongThreadException("FireEventsOnUIThread must be called from UI Thread");
}
}
}
fireEventsOnUIThread = value;
}
}
bool AnalyticsManager::AutoAppLifetimeMonitoring::get()
{
return autoAppLifetimeMonitoring;
}
void AnalyticsManager::AutoAppLifetimeMonitoring::set(bool value)
{
if (autoAppLifetimeMonitoring != value)
{
autoAppLifetimeMonitoring = value;
if (autoAppLifetimeMonitoring)
{
coreAppSuspendingEventToken = CoreApplication::Suspending += ref new EventHandler<SuspendingEventArgs^>(this, &AnalyticsManager::CoreApplication_Suspending);
coreAppResumingEventToken = CoreApplication::Resuming += ref new EventHandler<Object^>(this, &AnalyticsManager::CoreApplication_Resuming);
}
else
{
CoreApplication::Suspending -= coreAppSuspendingEventToken;
CoreApplication::Resuming -= coreAppResumingEventToken;
coreAppResumingEventToken.Value = 0;
coreAppSuspendingEventToken.Value = 0;
}
}
}
void AnalyticsManager::Clear()
{
std::lock_guard<std::mutex> lg(hitLock);
while (!hits.empty()) hits.pop();
}
IAsyncAction^ AnalyticsManager::DispatchAsync()
{
return create_async([this]() { return _DispatchAsync(); });
}
task<void> AnalyticsManager::_DispatchAsync()
{
if (!isEnabled) return task<void>([]() {});
task<void> allDispatchingTasks;
{
std::lock_guard<std::mutex> lg(dispatcherLock);
allDispatchingTasks = when_all(begin(dispatchingTasks), end(dispatchingTasks));
}
return allDispatchingTasks.then([this]() {
if (!isEnabled) return task<void>([]() {});
std::vector<Hit^> hitsToSend;
{
std::lock_guard<std::mutex> lg(hitLock);
while (!hits.empty())
{
hitsToSend.push_back(hits.front());
hits.pop();
}
}
if (!hitsToSend.empty())
{
return RunDispatchingTask(DispatchQueuedHits(hitsToSend));
}
else
{
return task<void>([]() {});
}
});
}
void AnalyticsManager::EnqueueHit(IMap<String^, String^>^ params)
{
if (!AppOptOut)
{
auto hit = ref new Hit(params);
if (DispatchPeriod.Duration == 0 && IsEnabled)
{
RunDispatchingTask(DispatchImmediateHit(hit));
}
else
{
std::lock_guard<std::mutex> lg(hitLock);
hits.push(hit);
}
}
}
IAsyncAction^ AnalyticsManager::SuspendAsync()
{
return create_async([this]() { return _SuspendAsync(); });
}
task<void> AnalyticsManager::_SuspendAsync()
{
return _DispatchAsync().then([this] {
if (timer)
{
timer->Cancel();
timer = nullptr;
}
});
}
void AnalyticsManager::Resume()
{
if (dispatchPeriod.Duration > 0)
{
//This would only happen if Suspend did not complete before due to a long Dispatch; very unlikely (I hope)
if (timer != nullptr)
{
timer->Cancel();
timer = nullptr;
}
timer = ThreadPoolTimer::CreatePeriodicTimer(ref new TimerElapsedHandler(this, &AnalyticsManager::timer_Tick), dispatchPeriod);
}
}
void AnalyticsManager::timer_Tick(ThreadPoolTimer^ sender)
{
DispatchAsync();
}
task<void> AnalyticsManager::RunDispatchingTask(task<void> newDispatchingTask)
{
{
std::lock_guard<std::mutex> lg(dispatcherLock);
dispatchingTasks.push_back(newDispatchingTask);
}
return newDispatchingTask.then([this, newDispatchingTask](task<void> t) {
std::lock_guard<std::mutex> lg(dispatcherLock);
dispatchingTasks.erase(begin(dispatchingTasks), std::find(begin(dispatchingTasks), end(dispatchingTasks), newDispatchingTask));
t.get();
});
}
task<void> AnalyticsManager::DispatchQueuedHits(std::vector<Hit^> hits)
{
HttpClient^ httpClient = GetHttpClient();
auto now = DateTimeHelper::Now();
std::vector<task<void>> tasks;
for (auto it = begin(hits); it != end(hits); ++it)
{
Hit^ hit = *it;
if (isEnabled && (!ThrottlingEnabled || hitTokenBucket->Consume()))
{
// clone the data
std::unordered_map<String^, String^> payloadData;
for each (auto kvp in hit->Data)
{
payloadData[kvp->Key] = kvp->Value;
}
int milliSeconds = (int)(TimeSpanHelper::GetTotalMilliseconds(TimeSpanHelper::FromTicks(now.UniversalTime - hit->TimeStamp.UniversalTime)));
payloadData["qt"] = milliSeconds.ToString();
tasks.push_back(DispatchHitData(hit, httpClient, payloadData));
}
else
{
std::lock_guard<std::mutex> lg(hitLock);
this->hits.push(hit);
}
}
return when_all(begin(tasks), end(tasks));
}
task<void> AnalyticsManager::DispatchImmediateHit(Hit^ payload)
{
HttpClient^ httpClient = GetHttpClient();
// clone the data
std::unordered_map<String^, String^> hitData;
for each (auto kvp in payload->Data)
{
hitData[kvp->Key] = kvp->Value;
}
return DispatchHitData(payload, httpClient, hitData);
}
task<void> AnalyticsManager::DispatchHitData(Hit^ hit, HttpClient^ httpClient, std::unordered_map<String^, String^> hitData)
{
if (BustCache) hitData["z"] = GetCacheBuster();
return SendHitAsync(hit, httpClient, hitData).then([this, hit](task<HttpResponseMessage^> t) {
try
{
HttpResponseMessage^ response(t.get());
try
{
response->EnsureSuccessStatusCode();
OnHitSent(hit, response);
}
catch (Exception^ ex)
{
OnHitMalformed(hit, response);
}
}
catch (Exception^ ex)
{
OnHitFailed(hit, ex);
}
}, task_continuation_context::use_current());
}
task<HttpResponseMessage^> AnalyticsManager::SendHitAsync(Hit^ payload, HttpClient^ httpClient, std::unordered_map<String^, String^> payloadData)
{
auto endPoint = IsDebug ? (IsSecure ? endPointSecureDebug : endPointUnsecureDebug) : (IsSecure ? endPointSecure : endPointUnsecure);
std::wstring content;
auto it = begin(payloadData);
while (true)
{
content += std::wstring(it->first->Data()) + L"=" + std::wstring(Uri::EscapeComponent(it->second)->Data());
it++;
if (it == end(payloadData)) break;
content += '&';
}
#ifdef _DEBUG
// ::OutputDebugString(content.c_str());
#endif
if (PostData)
{
auto httpContent = ref new Windows::Web::Http::HttpStringContent(ref new String(content.c_str()));
return create_task([httpClient, endPoint, httpContent]() { return httpClient->PostAsync(endPoint, httpContent); });
}
else
{
auto url = endPoint->RawUri + L"?" + ref new String(content.c_str());
return create_task([httpClient, url]() { return httpClient->GetAsync(ref new Uri(url)); });
}
}
void AnalyticsManager::OnHitFailed(Hit^ payload, Exception^ exception)
{
HitFailed(this, ref new HitFailedEventArgs(payload, exception->Message));
}
void AnalyticsManager::OnHitSent(Hit^ payload, HttpResponseMessage^ response)
{
create_task([response]() { return response->Content->ReadAsStringAsync(); }).then([this, payload](task<Platform::String^> t) {
HitSent(this, ref new HitSentEventArgs(payload, t.get()));
});
}
void AnalyticsManager::OnHitMalformed(GoogleAnalytics::Hit^ payload, HttpResponseMessage^ response)
{
HitMalformed(this, ref new HitMalformedEventArgs(payload, (int)(response->StatusCode)));
}
HttpClient^ AnalyticsManager::GetHttpClient()
{
auto result = ref new HttpClient();
if (UserAgent)
{
result->DefaultRequestHeaders->UserAgent->ParseAdd(UserAgent);
}
return result;
}
String^ AnalyticsManager::GetCacheBuster()
{
return (rand() % 100000000).ToString();
}
bool AnalyticsManager::AppOptOut::get()
{
if (!isAppOptOutSet) LoadAppOptOut();
return appOptOut;
}
void AnalyticsManager::AppOptOut::set(bool value)
{
appOptOut = value;
isAppOptOutSet = true;
ApplicationData::Current->LocalSettings->Values->Insert(Key_AppOptOut, value);
if (value) Clear();
}
void AnalyticsManager::LoadAppOptOut()
{
if (ApplicationData::Current->LocalSettings->Values->HasKey(Key_AppOptOut))
{
appOptOut = (bool)ApplicationData::Current->LocalSettings->Values->Lookup(Key_AppOptOut);
}
else
{
appOptOut = false;
}
isAppOptOutSet = true;
}
bool AnalyticsManager::ReportUncaughtExceptions::get()
{
return reportUncaughtExceptions;
}
void AnalyticsManager::ReportUncaughtExceptions::set(bool value)
{
if (reportUncaughtExceptions != value)
{
reportUncaughtExceptions = value;
if (reportUncaughtExceptions)
{
unhandledErrorDetectedEventToken = CoreApplication::UnhandledErrorDetected += ref new EventHandler<UnhandledErrorDetectedEventArgs^>(this, &AnalyticsManager::CoreApplication_UnhandledErrorDetected);
}
else
{
CoreApplication::UnhandledErrorDetected -= unhandledErrorDetectedEventToken;
}
}
}
void AnalyticsManager::CoreApplication_Suspending(Object^ sender, SuspendingEventArgs^ e)
{
auto deferral = e->SuspendingOperation->GetDeferral();
_SuspendAsync().then([deferral]()
{
deferral->Complete();
});
}
void AnalyticsManager::CoreApplication_Resuming(Object^ sender, Object^ unused)
{
Resume();
}
void AnalyticsManager::CoreApplication_UnhandledErrorDetected(Object^ sender, UnhandledErrorDetectedEventArgs^ e)
{
try
{
e->UnhandledError->Propagate();
}
catch (Exception^ ex)
{
auto it = begin(trackers);
while (true)
{
it->second->Send(HitBuilder::CreateException(ex->Message, true)->Build());
it++;
if (it == end(trackers)) break;
}
DispatchAsync();
throw;
}
}
bool AnalyticsManager::AutoTrackNetworkConnectivity::get()
{
return autoTrackNetworkConnectivity;
}
void AnalyticsManager::AutoTrackNetworkConnectivity::set(bool value)
{
if (autoTrackNetworkConnectivity != value)
{
autoTrackNetworkConnectivity = value;
if (autoTrackNetworkConnectivity)
{
UpdateConnectionStatus();
networkStatusChangedEventToken = NetworkInformation::NetworkStatusChanged += ref new NetworkStatusChangedEventHandler(this, &AnalyticsManager::NetworkInformation_NetworkStatusChanged);
}
else
{
NetworkInformation::NetworkStatusChanged -= networkStatusChangedEventToken;
IsEnabled = true;
}
}
}
void AnalyticsManager::NetworkInformation_NetworkStatusChanged(Object^ sender)
{
UpdateConnectionStatus();
}
void AnalyticsManager::UpdateConnectionStatus()
{
auto profile = NetworkInformation::GetInternetConnectionProfile();
if (profile)
{
switch (profile->GetNetworkConnectivityLevel())
{
case NetworkConnectivityLevel::InternetAccess:
case NetworkConnectivityLevel::ConstrainedInternetAccess:
IsEnabled = true;
break;
default:
IsEnabled = false;
break;
}
}
}
Windows::Foundation::EventRegistrationToken AnalyticsManager::HitFailed::add(Windows::Foundation::EventHandler<GoogleAnalytics::HitFailedEventArgs^>^ handler)
{
hitFailedListenerCount++;
return internalHitFailedEventHandler += handler;
}
void AnalyticsManager::HitFailed::remove(Windows::Foundation::EventRegistrationToken token)
{
//Note: Count can be off if caller (incorrectly) unregisters same event twice.
hitFailedListenerCount--;
internalHitFailedEventHandler -= token;
}
void AnalyticsManager::HitFailed::raise(Platform::Object^ sender, HitFailedEventArgs^ args)
{
if (fireEventsOnUIThread)
{
if (hitFailedListenerCount > 0)
{
dispatcher->RunAsync(
Windows::UI::Core::CoreDispatcherPriority::Normal,
ref new Windows::UI::Core::DispatchedHandler([this, sender, args]()
{
internalHitFailedEventHandler(sender, args);
}));
}
}
else
internalHitFailedEventHandler(sender, args);
}
Windows::Foundation::EventRegistrationToken AnalyticsManager::HitSent::add(Windows::Foundation::EventHandler<GoogleAnalytics::HitSentEventArgs^>^ handler)
{
hitSentListenerCount++;
return internalHitSentEventHandler += handler;
}
void AnalyticsManager::HitSent::remove(Windows::Foundation::EventRegistrationToken token)
{
//Note: Count can be off if caller (incorrectly) unregisters same event twice.
hitSentListenerCount--;
internalHitSentEventHandler -= token;
}
void AnalyticsManager::HitSent::raise(Platform::Object^ sender, HitSentEventArgs^ args)
{
if (fireEventsOnUIThread)
{
if (hitSentListenerCount > 0)
{
dispatcher->RunAsync(
Windows::UI::Core::CoreDispatcherPriority::Normal,
ref new Windows::UI::Core::DispatchedHandler([this, sender, args]()
{
internalHitSentEventHandler(sender, args);
}));
}
}
else
internalHitSentEventHandler(sender, args);
}
Windows::Foundation::EventRegistrationToken AnalyticsManager::HitMalformed::add(Windows::Foundation::EventHandler<GoogleAnalytics::HitMalformedEventArgs^>^ handler)
{
hitMalformedListenerCount++;
return internalHitMalformedEventHandler += handler;
}
void AnalyticsManager::HitMalformed::remove(Windows::Foundation::EventRegistrationToken token)
{
//Note: Count can be off if caller (incorrectly) unregisters same event twice.
hitMalformedListenerCount--;
internalHitMalformedEventHandler -= token;
}
void AnalyticsManager::HitMalformed::raise(Platform::Object^ sender, HitMalformedEventArgs^ args)
{
if (fireEventsOnUIThread)
{
if (hitMalformedListenerCount > 0)
{
dispatcher->RunAsync(
Windows::UI::Core::CoreDispatcherPriority::Normal,
ref new Windows::UI::Core::DispatchedHandler([this, sender, args]()
{
internalHitMalformedEventHandler(sender, args);
}));
}
}
else
internalHitMalformedEventHandler(sender, args);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.