hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3acb9d700beb2c99c6898ec102203fe760f13835 | 1,860 | cpp | C++ | source/05_Graphs/04_Dinic's Maximum Flow.cpp | KerakTelor86/AlgoCopypasta | 900d989c0651b51b55c551d336c2e92faead0fc8 | [
"WTFPL"
] | 1 | 2021-06-25T05:46:11.000Z | 2021-06-25T05:46:11.000Z | source/05_Graphs/04_Dinic's Maximum Flow.cpp | KerakTelor86/AlgoCopypasta | 900d989c0651b51b55c551d336c2e92faead0fc8 | [
"WTFPL"
] | null | null | null | source/05_Graphs/04_Dinic's Maximum Flow.cpp | KerakTelor86/AlgoCopypasta | 900d989c0651b51b55c551d336c2e92faead0fc8 | [
"WTFPL"
] | null | null | null | // O(VE log(max_flow)) if scaling == 1
// O((V + E) sqrt(E)) if unit graph (turn scaling off)
// O((V + E) sqrt(V)) if bipartite matching (turn scaling off)
// indices are 0-based
const ll INF = 1e18;
struct Dinic {
struct Edge {
int v;
ll cap, flow;
Edge(int _v, ll _cap): v(_v), cap(_cap), flow(0) {}
};
int n;
ll lim;
vector<vector<int>> gr;
vector<Edge> e;
vector<int> idx, lv;
bool has_path(int s, int t) {
queue<int> q;
q.push(s);
lv.assign(n, -1);
lv[s] = 0;
while(!q.empty()) {
int c = q.front();
q.pop();
if(c == t)
break;
for(auto& i : gr[c]) {
ll cur_flow = e[i].cap - e[i].flow;
if(lv[e[i].v] == -1 && cur_flow >= lim) {
lv[e[i].v] = lv[c] + 1;
q.push(e[i].v);
}
}
}
return lv[t] != -1;
}
ll get_flow(int s, int t, ll left) {
if(!left || s == t)
return left;
while(idx[s] < (int) gr[s].size()) {
int i = gr[s][idx[s]];
if(lv[e[i].v] == lv[s] + 1) {
ll add = get_flow(e[i].v, t, min(left, e[i].cap - e[i].flow));
if(add) {
e[i].flow += add;
e[i ^ 1].flow -= add;
return add;
}
}
++idx[s];
}
return 0;
}
Dinic(int vertices, bool scaling = 1) : // toggle scaling here
n(vertices), lim(scaling ? 1 << 30 : 1), gr(n) {}
void add_edge(int from, int to, ll cap, bool directed = 1) {
gr[from].push_back(e.size());
e.emplace_back(to, cap);
gr[to].push_back(e.size());
e.emplace_back(from, directed ? 0 : cap);
}
ll get_max_flow(int s, int t) { // call this
ll res = 0;
while(lim) { // scaling
while(has_path(s, t)) {
idx.assign(n, 0);
while(ll add = get_flow(s, t, INF))
res += add;
}
lim >>= 1;
}
return res;
}
};
| 22.682927 | 70 | 0.474731 | [
"vector"
] |
3acc0da8e7f84649a0878cbfd1ddc8ca544cb08b | 1,462 | hh | C++ | include/Mu2eTargetInput.hh | brownd1978/Mu2eFast | 024f5155cc01e8a99cbed989f04a31281cbd6799 | [
"Apache-2.0"
] | null | null | null | include/Mu2eTargetInput.hh | brownd1978/Mu2eFast | 024f5155cc01e8a99cbed989f04a31281cbd6799 | [
"Apache-2.0"
] | null | null | null | include/Mu2eTargetInput.hh | brownd1978/Mu2eFast | 024f5155cc01e8a99cbed989f04a31281cbd6799 | [
"Apache-2.0"
] | null | null | null | // generate mu2e conversions on targets. Distributions given by
// beam parameters
#ifndef Mu2eTargetInput_HH
#define Mu2eTargetInput_HH
#include "mu2eFast/Mu2eInput.hh"
#include <TRandom3.h>
#include <TLorentzVector.h>
class PdtEntry;
class PacConfig;
class TRandom;
class TGraph;
class PacDetector;
class Mu2eTargetInput : public Mu2eInput {
public:
// momentum spectrum description
enum spectrum{flat=0,file};
// construct from the detector
Mu2eTargetInput(PacConfig& config, const PacDetector* det);
~Mu2eTargetInput();
// override virtual interface
virtual bool nextEvent(Mu2eEvent& event);
virtual void rewind();
protected:
TParticle* create(const TLorentzVector& pos, const TLorentzVector& mom) const;
void createPosition(TLorentzVector& pos) const;
void createMomentum(TLorentzVector& mom) const;
void prepareBeam(PacConfig& config);
private:
const PdtEntry* _pdt;
double _beamxsig;
double _beamtsig;
double _beamzlambda;
double _p_min, _p_max;
double _cost_min, _cost_max;
double _mass2;
// timing
double _lifetime;
double _bunchtime;
double _lnscale;
double _lnsigma;
double _lntheta;
// spectrum type
spectrum _stype;
TGraph* _invintspect;
// target description
std::vector<double> _diskradii;
std::vector<double> _halfthickness;
// seed
int _seed;
// event counters
protected:
mutable TRandom3 _rng;
std::vector<double> _diskz;
unsigned _nevents;
unsigned _ievt;
};
#endif
| 23.580645 | 80 | 0.757182 | [
"vector"
] |
3acded6fc8e71632683edca5312326d68b902d3b | 21,470 | cpp | C++ | Source/src/utilities/UTF8.cpp | ProtonMail/cpp-openpgp | b47316c51357b8d15eb3bcc376ea5e59a6a9a108 | [
"MIT"
] | 5 | 2019-10-30T06:10:10.000Z | 2020-04-25T16:52:06.000Z | Source/src/utilities/UTF8.cpp | ProtonMail/cpp-openpgp | b47316c51357b8d15eb3bcc376ea5e59a6a9a108 | [
"MIT"
] | null | null | null | Source/src/utilities/UTF8.cpp | ProtonMail/cpp-openpgp | b47316c51357b8d15eb3bcc376ea5e59a6a9a108 | [
"MIT"
] | 2 | 2019-11-27T23:47:54.000Z | 2020-01-13T16:36:03.000Z | //
// UTF8.cpp
// OpenPGP
//
// Created by Yanfeng Zhang on 1/31/15.
//
// The MIT License
//
// Copyright (c) 2019 Proton Technologies AG
//
// 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 <utilities/UTF8.h>
#include <string>
#include <sstream>
#include <iostream>
#include <locale>
#include <utilities/includes.h>
//#include <codecvt>
#include <iomanip>
#include <iostream>
#include <fstream>
#include <cmath>
#include <regex>
#include <string>
std::string to_hex( unsigned int c )
{
std::ostringstream stm ;
stm << '%' << std::hex << std::uppercase << c ;
return stm.str() ;
}
unsigned int to_string(char a, char b )
{
int cint = 0;
cint = (cint << 4) | e_val[a];
cint = (cint << 4) | e_val[b];
return cint;
}
std::string encode(std::string str)
{
static std::string unreserved = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_.~";
std::string r;
for (int i = 0; i < str.length(); i++ )
{
char c = str.at(i);
if (unreserved.find(c) != -1)
r+=c;
else
r+=to_hex(c);
}
return r;
}
typedef unsigned char BYTE;
inline BYTE toHex(const BYTE &x)
{
return x > 9 ? x -10 + 'A': x + '0';
}
inline BYTE fromHex(const BYTE &x)
{
return isdigit(x) ? x-'0' : x-'A'+10;
}
std::string URLEncode(const std::string &sIn)
{
std::string sOut;
for( size_t ix = 0; ix < sIn.size(); ix++ )
{
BYTE buf[4];
memset( buf, 0, 4 );
if( isalnum( (BYTE)sIn[ix] ) )
{
buf[0] = sIn[ix];
}
else
{
buf[0] = '%';
buf[1] = toHex( (BYTE)sIn[ix] >> 4 );
buf[2] = toHex( (BYTE)sIn[ix] % 16);
}
sOut += (char *)buf;
}
return sOut;
};
std::string URLDecode(const std::string &sIn)
{
std::string sOut;
for( size_t ix = 0; ix < sIn.size(); ix++ )
{
BYTE ch = 0;
if(sIn[ix]=='%')
{
ch = (fromHex(sIn[ix+1])<<4);
ch |= fromHex(sIn[ix+2]);
ix += 2;
}
else if(sIn[ix] == '+')
{
ch = ' ';
}
else
{
ch = sIn[ix];
}
sOut += (char)ch;
}
return sOut;
}
const signed char HEX2DEC[256] =
{
/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
/* 0 */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
/* 1 */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
/* 2 */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
/* 3 */ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,-1,-1, -1,-1,-1,-1,
/* 4 */ -1,10,11,12, 13,14,15,-1, -1,-1,-1,-1, -1,-1,-1,-1,
/* 5 */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
/* 6 */ -1,10,11,12, 13,14,15,-1, -1,-1,-1,-1, -1,-1,-1,-1,
/* 7 */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
/* 8 */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
/* 9 */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
/* A */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
/* B */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
/* C */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
/* D */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
/* E */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
/* F */ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1
};
std::string ecape(std::string & sin)
{
std::string aa = sin;
std::string ss = "";
size_t size = aa.size();
for(int i=0;i<size;i++)
{
if(aa[i] > (char)0xff) //翻译不翻译的关键
{
char tmp[5];
sprintf(tmp,"%x",aa[i]);
ss += "%u";
ss += tmp;
}
else
{
char tmp[5];
sprintf(tmp,"%c",aa[i]);
ss += tmp;
}
}
return 0;
}
std::string urlencode_new(const std::string &s)
{
//RFC 3986 section 2.3 Unreserved Characters (January 2005)
const std::string unreserved = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~";
std::string escaped="";
for(size_t i=0; i<s.length(); i++)
{
if (unreserved.find_first_of(s[i]) != std::string::npos)
{
escaped.push_back(s[i]);
}
else
{
escaped.append("%");
char buf[3];
sprintf(buf, "%.2X", s[i]);
escaped.append(buf);
}
}
return escaped;
}
////good part => save as js
std::string decodeURIComponent(const std::string & sSrc)
{
// Note from RFC1630: "Sequences which start with a percent sign
// but are not followed by two hexadecimal characters (0-9, A-F) are reserved
// for future extension"
const unsigned char * pSrc = (const unsigned char *)sSrc.c_str();
const size_t SRC_LEN = sSrc.length();
const unsigned char * const SRC_END = pSrc + SRC_LEN;
const unsigned char * const SRC_LAST_DEC = SRC_END - 2; // last decodable '%'
char * const pStart = new char[SRC_LEN];
char * pEnd = pStart;
while (pSrc < SRC_LAST_DEC)
{
if (*pSrc == '%')
{
char dec1, dec2;
if (-1 != (dec1 = HEX2DEC[*(pSrc + 1)])
&& -1 != (dec2 = HEX2DEC[*(pSrc + 2)]))
{
*pEnd++ = (dec1 << 4) + dec2;
pSrc += 3;
continue;
}
}
*pEnd++ = *pSrc++;
}
// the last 2- chars
while (pSrc < SRC_END)
*pEnd++ = *pSrc++;
std::string sResult(pStart, pEnd);
delete [] pStart;
return sResult;
}
// Only alphanum is safe.
const char SAFE[256] =
{
/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
/* 0 */ 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,
/* 1 */ 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,
/* 2 */ 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,1,0,
/* 3 */ 1,1,1,1, 1,1,1,1, 1,1,0,0, 0,0,0,0,
/* 4 */ 0,1,1,1, 1,1,1,1, 1,1,1,1, 1,1,1,1,
/* 5 */ 1,1,1,1, 1,1,1,1, 1,1,1,0, 0,0,0,0,
/* 6 */ 0,1,1,1, 1,1,1,1, 1,1,1,1, 1,1,1,1,
/* 7 */ 1,1,1,1, 1,1,1,1, 1,1,1,0, 0,0,0,0,
/* 8 */ 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,
/* 9 */ 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,
/* A */ 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,
/* B */ 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,
/* C */ 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,
/* D */ 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,
/* E */ 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,
/* F */ 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0
};
std::string js_encodeURIComponent(const std::string & sSrc)
{
size_t size = sSrc.length();
std::string out_str;
for (int i=0; i<size; i++) {
unsigned char code = sSrc[i];
if(code > 0x7f)
{
int charcode = code;
int first_bits = 6;
const int other_bits = 6;
int first_val = 0xC0;
int t = 0;
std::string low;
while (charcode >= (1 << first_bits))
{
{
t = 128 | (charcode & ((1 << other_bits)-1));
charcode >>= other_bits;
first_val |= 1 << (first_bits);
first_bits--;
}
low += to_hex(t);
}
t = first_val | charcode;
out_str += to_hex(t);
out_str += low;
}
else
{
if( (sSrc[i]>='a' && sSrc[i]<='z') || (sSrc[i]>='A' && sSrc[i]<='Z') || ( sSrc[i]>='0' && sSrc[i]<='9' ))
{
out_str += sSrc[i];
}
else
{
char tmp[3];
sprintf(tmp,"%02x", sSrc[i]);
out_str += "%";
out_str += tmp;
}
}
}
return out_str;
}
std::string js_decodeURIComponent(const std::string &input)
{
size_t size = input.length();
std::string out_s;
for (int i = 0 ; i<size; i++) {
unsigned char code = input[i];
if(code == '%')
{
unsigned int high = to_string(input[i+1], input[i+2]);
int first_val = 0xC0;
if(high > first_val)
{
unsigned int low = to_string(input[i+4], input[i+5]);
int charcode = 0;
int high_bit_mask = (1 << 6) -1;
int high_bit_shift = 0;
int total_bits = 0;
const int other_bits = 6;
int t = high;
while((t & 0xC0) == 0xC0)
{
t <<= 1;
t &= 0xff;
total_bits += 6;
high_bit_mask >>= 1;
high_bit_shift++;
charcode <<= other_bits;
charcode |= low & ((1 << other_bits)-1);
}
charcode |= ((t >> high_bit_shift) & high_bit_mask) << total_bits;
out_s += charcode;
i += 5;
}
else
{
unsigned int de_hex = to_string(input[i+1], input[i+2]);
out_s += de_hex;
i += 2;
}
}
else
{
out_s += code;
}
}
return out_s;
}
std::string encodeURIComponent(const std::string & sSrc)
{
const char DEC2HEX[16 + 1] = "0123456789ABCDEF";
const unsigned char * pSrc = (const unsigned char *)sSrc.c_str();
const size_t SRC_LEN = sSrc.length();
unsigned char * const pStart = new unsigned char[SRC_LEN * 3];
unsigned char * pEnd = pStart;
const unsigned char * const SRC_END = pSrc + SRC_LEN;
for (; pSrc < SRC_END; ++pSrc)
{
if (SAFE[*pSrc])
*pEnd++ = *pSrc;
else
{
// escape this char
*pEnd++ = '%';
*pEnd++ = DEC2HEX[*pSrc >> 4];
*pEnd++ = DEC2HEX[*pSrc & 0x0F];
}
}
std::string sResult((char *)pStart, (char *)pEnd);
delete [] pStart;
return sResult;
}
std::string escape(std::string& s) {
const int SRC_LEN = static_cast<int>(s.length());
std::string out;
for (int i = 0; i < SRC_LEN; i++) {
char ch = s.at(i);
if (ch == ' ') { // space : map to '+'
out += to_hex(ch);
} else if ('A' <= ch && ch <= 'Z') { // 'A'..'Z' : as it was
out += ch;
} else if ('a' <= ch && ch <= 'z') { // 'a'..'z' : as it was
out += ch;
} else if ('0' <= ch && ch <= '9') { // '0'..'9' : as it was
out += ch;
} else if (ch == '-' || ch == '_' // unreserved : as it was
|| ch == '.' || ch == '!'
|| ch == '~' || ch == '*'
|| ch == '\'' || ch == '('
|| ch == ')') {
out += ch;
} else if (ch <= 0x007F) { // other ASCII : map to %XX
// out += to_hex(ch);
// } else { // unicode : map to %uXXXX
out += '%';
out += 'u';
std::ostringstream stm ;
stm << 'u';// << std::hex << std::uppercase << c ;
for(int i = 0; i < 8; i++)
{
stm << std::hex << std::uppercase << ((ch >> i) & 1) ;
}
std::string h = e_hex[(ch >> 8)];
out += h ;
h = e_hex[(0x00FF & ch)];
out += h;
}
}
return out;
}
std::string url_encode(const std::string &value) {
std::ostringstream escaped;
escaped.fill('0');
escaped << std::hex;
for (std::string::const_iterator i = value.begin(), n = value.end(); i != n; ++i) {
std::string::value_type c = (*i);
// Keep alphanumeric and other accepted characters intact
if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') {
escaped << c;
continue;
}
// Any other characters are percent-encoded
escaped << '%' << std::setw(2) << int((unsigned char) c);
}
return escaped.str();
}
std::string getHex(std::string buf) {
std::string o;
for (int i = 0; i < buf.length(); i++) {
int n = static_cast<int>( buf[i] & 0xff );
char tmp[3];
sprintf(tmp,"%02x",n);
o += "%";
o += tmp;
}
return o;
}
int bin_value(char ch)
{
if('0'<=ch && ch<='9')
{
return ch - '0';
}
else if('a'<=ch && ch<='z')
{
return ch - 'a' + 0x0A;
}
else if('A'<=ch && ch<='Z')
{
return ch - 'A' + 0x0A;
}
else
{
return -1;
}
}
//not tested
std::string hex2bin(std::string& s_in)
{
std::string out;
for (int i = 0; i < s_in.size();) {
//int a = (bin_value(s_in[0])<<4) & 0xF0;
//int b = (bin_value(s_in[1]) ) & 0x0F;
// char out_a;
// sprintf(out, "%d", (a | b));
// out += std::string(static_cast<int>(a | b));
i+=2;
}
return out;
}
void A_to_B(const char* input)
{
int ascii; // used to store the ASCII number of a character
size_t length = strlen(input); //find the length of the user's input
// std::cout << " ";
for(int x = 0; x < length; x++) //repeat until user's input have all been read
// x < length because the last character is "\0"
{
ascii = input[x]; //store a character in its ASCII number
/* Refer to http://www.wikihow.com/Convert-from-Decimal-to-Binary for conversion method used
* in this program*/
char* binary_reverse = new char [9]; //dynamic memory allocation
char* binary = new char [9];
int y = 0; //counter used for arrays
while(ascii != 1) //continue until ascii == 1
{
if(ascii % 2 == 0) //if ascii is divisible by 2
{
binary_reverse[y] = '0'; //then put a zero
}
else if(ascii % 2 == 1) //if it isnt divisible by 2
{
binary_reverse[y] = '1'; //then put a 1
}
ascii /= 2; //find the quotient of ascii / 2
y++; //add 1 to y for next loop
}
if(ascii == 1) //when ascii is 1, we have to add 1 to the beginning
{
binary_reverse[y] = '1';
y++;
}
if(y < 8) //add zeros to the end of string if not 8 characters (1 byte)
{
for(; y < 8; y++) //add until binary_reverse[7] (8th element)
{
binary_reverse[y] = '0';
}
}
for(int z = 0; z < 8; z++) //our array is reversed. put the numbers in the rigth order (last comes first)
{
binary[z] = binary_reverse[7 - z];
}
// std::cout << binary; //display the 8 digit binary number
delete [] binary_reverse; //free the memory created by dynamic mem. allocation
delete [] binary;
}
}
void B_to_A(const char* input)
{
size_t length = strlen(input); //get length of string
int binary[8]; //array used to store 1 byte of binary number (1 character)
int asciiNum = 0; //the ascii number after conversion from binary
char ascii; //the ascii character itself
// std::cout << " ";
int z = 0; //counter used
for(int x = 0; x < length / 8; x++) //reading in bytes. total characters = length / 8
{
for(int a = 0; a < 8; a++) //store info into binary[0] through binary[7]
{
binary[a] = static_cast<int>( input[z] - 48 ); //z never resets
z++;
}
int power[8]; //will set powers of 2 in an array
int counter = 7; //power starts at 2^0, ends at 2^7
for(int x = 0; x < 8; x++)
{
power[x] = counter; //power[] = {7, 6, 5, ..... 1, 0}
counter--; //decrement counter each time
}
for(int y = 0; y < 8; y++) //will compute asciiNum
{
double a = binary[y]; //store the element from binary[] as "a"
double b = power[y]; //store the lement from power[] as "b"
asciiNum += a* std::pow(2, b); //asciiNum = sum of a * 2^power where 0 <= power <= 7, power is int
}
ascii = asciiNum; //assign the asciiNum value to ascii, to change it into an actual character
asciiNum = 0; //reset asciiNum for next loop
// std::cout << ascii; //display the ascii character
}
}
//encodeing
std::string btoa (std::string& s_in) {
// /var base64 = {};
std::string PADCHAR = "=";
std::string ALPHA = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
// base64.encode = function(s) {
// if (arguments.length !== 1) {
// throw new SyntaxError("Not enough arguments");
// }
// auto padchar = PADCHAR;
// auto alpha = ALPHA;
// var getbyte = base64.getbyte;
//
// var i, b10;
// var x = [];
//
// // convert to string
// s = '' + s;
//
// var imax = s.length - s.length % 3;
//
// if (s.length === 0) {
// return s;
// }
// for (i = 0; i < imax; i += 3) {
// b10 = (getbyte(s,i) << 16) | (getbyte(s,i+1) << 8) | getbyte(s,i+2);
// x.push(alpha.charAt(b10 >> 18));
// x.push(alpha.charAt((b10 >> 12) & 0x3F));
// x.push(alpha.charAt((b10 >> 6) & 0x3f));
// x.push(alpha.charAt(b10 & 0x3f));
// }
// switch (s.length - imax) {
// case 1:
// b10 = getbyte(s,i) << 16;
// x.push(alpha.charAt(b10 >> 18) + alpha.charAt((b10 >> 12) & 0x3F) +
// padchar + padchar);
// break;
// case 2:
// b10 = (getbyte(s,i) << 16) | (getbyte(s,i+1) << 8);
// x.push(alpha.charAt(b10 >> 18) + alpha.charAt((b10 >> 12) & 0x3F) +
// alpha.charAt((b10 >> 6) & 0x3f) + padchar);
// break;
// }
// return x.join('');
return "";
}
//base64.getbyte64 = function(s,i) {
// // This is oddly fast, except on Chrome/V8.
// // Minimal or no improvement in performance by using a
// // object with properties mapping chars to value (eg. 'A': 0)
// var idx = base64.ALPHA.indexOf(s.charAt(i));
// if (idx === -1) {
// throw base64.makeDOMException();
// }
// return idx;
//}
std::string atob (std::string& s_in) {
char PADCHAR = '=';
std::string ALPHA = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
// convert to string
//s_in = '' + s_in;
// var getbyte64 = base64.getbyte64;
int pads, i;//, b10;
auto imax = s_in.length();
if (imax == 0) {
return s_in;
}
if (imax % 4 != 0) {
// need throw exception throw base64.makeDOMException();
}
pads = 0;
if (s_in[imax - 1] == PADCHAR) {
pads = 1;
if (s_in[imax - 2] == PADCHAR) {
pads = 2;
}
// either way, we want to ignore this last block
imax -= 4;
}
std::string s_out;
for (i = 0; i < imax; i += 4) {
auto b10 = (ALPHA[s_in[i]]<< 18) | (ALPHA[s_in[i+1]] << 12) | (ALPHA[s_in[i+2]] << 6) | ALPHA[s_in[i+3]];
s_out += (uint8_t)(b10 >> 16);
s_out += (uint8_t)((b10 >> 8) & 0xff);
s_out += (uint8_t)(b10 & 0xff);
}
switch (pads) {
case 1:
{
auto b10 = (ALPHA[s_in[i]] << 18) | (ALPHA[s_in[i+1]] << 12) | (ALPHA[s_in[i+2]] << 6);
s_out += (uint8_t)(b10 >> 16);
s_out += (uint8_t)((b10 >> 8) & 0xff);
break;
}
case 2:
{
auto b11 = (ALPHA[s_in[i]] << 18) | (ALPHA[s_in[i+1]] << 12);
s_out += (uint8_t)(b11 >> 16);
break;
}
}
return s_out;
}
| 28.399471 | 117 | 0.449278 | [
"object"
] |
3ad36aca385c3a3e88e782639c87eabba0f0bd5c | 19,538 | cpp | C++ | firmware/arduino/get-started/libraries/EspMQTTClient/src/EspMQTTClient.cpp | fuyin21/lifuyin.github.io | cd1e229b9024481d53f42e16d755b75964d14e46 | [
"MulanPSL-1.0"
] | 480 | 2021-07-15T05:32:09.000Z | 2022-03-31T09:25:46.000Z | firmware/arduino/get-started/libraries/EspMQTTClient/src/EspMQTTClient.cpp | jsweidy2012/wumei-smart | 33ad05e288323342f20afad8e9984a6af45ee554 | [
"MulanPSL-1.0"
] | 5 | 2022-02-18T03:13:54.000Z | 2022-03-31T12:06:43.000Z | firmware/arduino/get-started/libraries/EspMQTTClient/src/EspMQTTClient.cpp | jsweidy2012/wumei-smart | 33ad05e288323342f20afad8e9984a6af45ee554 | [
"MulanPSL-1.0"
] | 150 | 2021-07-15T05:58:30.000Z | 2022-03-31T08:27:50.000Z | #include "EspMQTTClient.h"
// =============== Constructor / destructor ===================
// MQTT only (no wifi connection attempt)
EspMQTTClient::EspMQTTClient(
const char* mqttServerIp,
const short mqttServerPort,
const char* mqttClientName) :
EspMQTTClient(NULL, NULL, mqttServerIp, NULL, NULL, mqttClientName, mqttServerPort)
{
}
EspMQTTClient::EspMQTTClient(
const char* mqttServerIp,
const short mqttServerPort,
const char* mqttUsername,
const char* mqttPassword,
const char* mqttClientName) :
EspMQTTClient(NULL, NULL, mqttServerIp, mqttUsername, mqttPassword, mqttClientName, mqttServerPort)
{
}
// Wifi and MQTT handling
EspMQTTClient::EspMQTTClient(
const char* wifiSsid,
const char* wifiPassword,
const char* mqttServerIp,
const char* mqttClientName,
const short mqttServerPort) :
EspMQTTClient(wifiSsid, wifiPassword, mqttServerIp, NULL, NULL, mqttClientName, mqttServerPort)
{
}
EspMQTTClient::EspMQTTClient(
const char* wifiSsid,
const char* wifiPassword,
const char* mqttServerIp,
const char* mqttUsername,
const char* mqttPassword,
const char* mqttClientName,
const short mqttServerPort) :
_wifiSsid(wifiSsid),
_wifiPassword(wifiPassword),
_mqttServerIp(mqttServerIp),
_mqttUsername(mqttUsername),
_mqttPassword(mqttPassword),
_mqttClientName(mqttClientName),
_mqttServerPort(mqttServerPort),
_mqttClient(mqttServerIp, mqttServerPort, _wifiClient)
{
// WiFi connection
_handleWiFi = (wifiSsid != NULL);
_wifiConnected = false;
_connectingToWifi = false;
_nextWifiConnectionAttemptMillis = 500;
_lastWifiConnectiomAttemptMillis = 0;
_wifiReconnectionAttemptDelay = 60 * 1000;
// MQTT client
_mqttConnected = false;
_nextMqttConnectionAttemptMillis = 0;
_mqttReconnectionAttemptDelay = 15 * 1000; // 15 seconds of waiting between each mqtt reconnection attempts by default
_mqttLastWillTopic = 0;
_mqttLastWillMessage = 0;
_mqttLastWillRetain = false;
_mqttCleanSession = true;
_mqttClient.setCallback([this](char* topic, byte* payload, unsigned int length) {this->mqttMessageReceivedCallback(topic, payload, length);});
_failedMQTTConnectionAttemptCount = 0;
// Web updater
_updateServerAddress = NULL;
_httpServer = NULL;
_httpUpdater = NULL;
// other
_enableSerialLogs = false;
_drasticResetOnConnectionFailures = false;
_connectionEstablishedCallback = onConnectionEstablished;
_connectionEstablishedCount = 0;
}
EspMQTTClient::~EspMQTTClient()
{
if (_httpServer != NULL)
delete _httpServer;
if (_httpUpdater != NULL)
delete _httpUpdater;
}
// =============== Configuration functions, most of them must be called before the first loop() call ==============
void EspMQTTClient::enableDebuggingMessages(const bool enabled)
{
_enableSerialLogs = enabled;
}
void EspMQTTClient::enableHTTPWebUpdater(const char* username, const char* password, const char* address)
{
if (_httpServer == NULL)
{
_httpServer = new WebServer(80);
_httpUpdater = new ESPHTTPUpdateServer(_enableSerialLogs);
_updateServerUsername = (char*)username;
_updateServerPassword = (char*)password;
_updateServerAddress = (char*)address;
}
else if (_enableSerialLogs)
Serial.print("SYS! You can't call enableHTTPWebUpdater() more than once !\n");
}
void EspMQTTClient::enableHTTPWebUpdater(const char* address)
{
if(_mqttUsername == NULL || _mqttPassword == NULL)
enableHTTPWebUpdater("", "", address);
else
enableHTTPWebUpdater(_mqttUsername, _mqttPassword, address);
}
void EspMQTTClient::enableMQTTPersistence()
{
_mqttCleanSession = false;
}
void EspMQTTClient::enableLastWillMessage(const char* topic, const char* message, const bool retain)
{
_mqttLastWillTopic = (char*)topic;
_mqttLastWillMessage = (char*)message;
_mqttLastWillRetain = retain;
}
// =============== Main loop / connection state handling =================
void EspMQTTClient::loop()
{
// WIFI handling
bool wifiStateChanged = handleWiFi();
// If there is a change in the wifi connection state, don't handle the mqtt connection state right away.
// We will wait at least one lopp() call. This prevent the library from doing too much thing in the same loop() call.
if(wifiStateChanged)
return;
// MQTT Handling
bool mqttStateChanged = handleMQTT();
if(mqttStateChanged)
return;
// Procewss the delayed execution commands
processDelayedExecutionRequests();
}
bool EspMQTTClient::handleWiFi()
{
// When it's the first call, reset the wifi radio and schedule the wifi connection
static bool firstLoopCall = true;
if(_handleWiFi && firstLoopCall)
{
WiFi.disconnect(true);
_nextWifiConnectionAttemptMillis = millis() + 500;
firstLoopCall = false;
return true;
}
// Get the current connextion status
bool isWifiConnected = (WiFi.status() == WL_CONNECTED);
/***** Detect ans handle the current WiFi handling state *****/
// Connection established
if (isWifiConnected && !_wifiConnected)
{
onWiFiConnectionEstablished();
_connectingToWifi = false;
// At least 500 miliseconds of waiting before an mqtt connection attempt.
// Some people have reported instabilities when trying to connect to
// the mqtt broker right after being connected to wifi.
// This delay prevent these instabilities.
_nextMqttConnectionAttemptMillis = millis() + 500;
}
// Connection in progress
else if(_connectingToWifi)
{
if(WiFi.status() == WL_CONNECT_FAILED || millis() - _lastWifiConnectiomAttemptMillis >= _wifiReconnectionAttemptDelay)
{
if(_enableSerialLogs)
Serial.printf("WiFi! Connection attempt failed, delay expired. (%fs). \n", millis()/1000.0);
WiFi.disconnect(true);
MDNS.end();
_nextWifiConnectionAttemptMillis = millis() + 500;
_connectingToWifi = false;
}
}
// Connection lost
else if (!isWifiConnected && _wifiConnected)
{
onWiFiConnectionLost();
if(_handleWiFi)
_nextWifiConnectionAttemptMillis = millis() + 500;
}
// Connected since at least one loop() call
else if (isWifiConnected && _wifiConnected)
{
// Web updater handling
if (_httpServer != NULL)
{
_httpServer->handleClient();
#ifdef ESP8266
MDNS.update(); // We need to do this only for ESP8266
#endif
}
}
// Disconnected since at least one loop() call
// Then, if we handle the wifi reconnection process and the waiting delay has expired, we connect to wifi
else if(_handleWiFi && _nextWifiConnectionAttemptMillis > 0 && millis() >= _nextWifiConnectionAttemptMillis)
{
connectToWifi();
_nextWifiConnectionAttemptMillis = 0;
_connectingToWifi = true;
_lastWifiConnectiomAttemptMillis = millis();
}
/**** Detect and return if there was a change in the WiFi state ****/
if (isWifiConnected != _wifiConnected)
{
_wifiConnected = isWifiConnected;
return true;
}
else
return false;
}
bool EspMQTTClient::handleMQTT()
{
// PubSubClient main lopp() call
_mqttClient.loop();
// Get the current connextion status
bool isMqttConnected = (isWifiConnected() && _mqttClient.connected());
/***** Detect ans handle the current MQTT handling state *****/
// Connection established
if (isMqttConnected && !_mqttConnected)
{
_mqttConnected = true;
onMQTTConnectionEstablished();
}
// Connection lost
else if (!isMqttConnected && _mqttConnected)
{
onMQTTConnectionLost();
_nextMqttConnectionAttemptMillis = millis() + _mqttReconnectionAttemptDelay;
}
// It's time to connect to the MQTT broker
else if (isWifiConnected() && _nextMqttConnectionAttemptMillis > 0 && millis() >= _nextMqttConnectionAttemptMillis)
{
// Connect to MQTT broker
if(connectToMqttBroker())
{
_failedMQTTConnectionAttemptCount = 0;
_nextMqttConnectionAttemptMillis = 0;
}
else
{
// Connection failed, plan another connection attempt
_nextMqttConnectionAttemptMillis = millis() + _mqttReconnectionAttemptDelay;
_mqttClient.disconnect();
_failedMQTTConnectionAttemptCount++;
if (_enableSerialLogs)
Serial.printf("MQTT!: Failed MQTT connection count: %i \n", _failedMQTTConnectionAttemptCount);
// When there is too many failed attempt, sometimes it help to reset the WiFi connection or to restart the board.
if(_failedMQTTConnectionAttemptCount == 8)
{
if (_enableSerialLogs)
Serial.println("MQTT!: Can't connect to broker after too many attempt, resetting WiFi ...");
WiFi.disconnect(true);
MDNS.end();
_nextWifiConnectionAttemptMillis = millis() + 500;
if(!_drasticResetOnConnectionFailures)
_failedMQTTConnectionAttemptCount = 0;
}
else if(_drasticResetOnConnectionFailures && _failedMQTTConnectionAttemptCount == 12) // Will reset after 12 failed attempt (3 minutes of retry)
{
if (_enableSerialLogs)
Serial.println("MQTT!: Can't connect to broker after too many attempt, resetting board ...");
#ifdef ESP8266
ESP.reset();
#else
ESP.restart();
#endif
}
}
}
/**** Detect and return if there was a change in the MQTT state ****/
if(_mqttConnected != isMqttConnected)
{
_mqttConnected = isMqttConnected;
return true;
}
else
return false;
}
void EspMQTTClient::onWiFiConnectionEstablished()
{
if (_enableSerialLogs)
Serial.printf("WiFi: Connected (%fs), ip : %s \n", millis()/1000.0, WiFi.localIP().toString().c_str());
// Config of web updater
if (_httpServer != NULL)
{
MDNS.begin(_mqttClientName);
_httpUpdater->setup(_httpServer, _updateServerAddress, _updateServerUsername, _updateServerPassword);
_httpServer->begin();
MDNS.addService("http", "tcp", 80);
if (_enableSerialLogs)
Serial.printf("WEB: Updater ready, open http://%s.local in your browser and login with username '%s' and password '%s'.\n", _mqttClientName, _updateServerUsername, _updateServerPassword);
}
}
void EspMQTTClient::onWiFiConnectionLost()
{
if (_enableSerialLogs)
Serial.printf("WiFi! Lost connection (%fs). \n", millis()/1000.0);
// If we handle wifi, we force disconnection to clear the last connection
if (_handleWiFi)
{
WiFi.disconnect(true);
MDNS.end();
}
}
void EspMQTTClient::onMQTTConnectionEstablished()
{
_connectionEstablishedCount++;
_connectionEstablishedCallback();
}
void EspMQTTClient::onMQTTConnectionLost()
{
if (_enableSerialLogs)
{
Serial.printf("MQTT! Lost connection (%fs). \n", millis()/1000.0);
Serial.printf("MQTT: Retrying to connect in %i seconds. \n", _mqttReconnectionAttemptDelay / 1000);
}
}
// =============== Public functions for interaction with thus lib =================
bool EspMQTTClient::setMaxPacketSize(const uint16_t size)
{
bool success = _mqttClient.setBufferSize(size);
if(!success && _enableSerialLogs)
Serial.println("MQTT! failed to set the max packet size.");
return success;
}
bool EspMQTTClient::publish(const String &topic, const String &payload, bool retain)
{
// Do not try to publish if MQTT is not connected.
if(!isConnected())
{
if (_enableSerialLogs)
Serial.println("MQTT! Trying to publish when disconnected, skipping.");
return false;
}
bool success = _mqttClient.publish(topic.c_str(), payload.c_str(), retain);
if (_enableSerialLogs)
{
if(success)
Serial.printf("MQTT << [%s] %s\n", topic.c_str(), payload.c_str());
else
Serial.println("MQTT! publish failed, is the message too long ? (see setMaxPacketSize())"); // This can occurs if the message is too long according to the maximum defined in PubsubClient.h
}
return success;
}
bool EspMQTTClient::subscribe(const String &topic, MessageReceivedCallback messageReceivedCallback, uint8_t qos)
{
// Do not try to subscribe if MQTT is not connected.
if(!isConnected())
{
if (_enableSerialLogs)
Serial.println("MQTT! Trying to subscribe when disconnected, skipping.");
return false;
}
bool success = _mqttClient.subscribe(topic.c_str(), qos);
if(success)
{
// Add the record to the subscription list only if it does not exists.
bool found = false;
for (byte i = 0; i < _topicSubscriptionList.size() && !found; i++)
found = _topicSubscriptionList[i].topic.equals(topic);
if(!found)
_topicSubscriptionList.push_back({ topic, messageReceivedCallback, NULL });
}
if (_enableSerialLogs)
{
if(success)
Serial.printf("MQTT: Subscribed to [%s]\n", topic.c_str());
else
Serial.println("MQTT! subscribe failed");
}
return success;
}
bool EspMQTTClient::subscribe(const String &topic, MessageReceivedCallbackWithTopic messageReceivedCallback, uint8_t qos)
{
if(subscribe(topic, (MessageReceivedCallback)NULL, qos))
{
_topicSubscriptionList[_topicSubscriptionList.size()-1].callbackWithTopic = messageReceivedCallback;
return true;
}
return false;
}
bool EspMQTTClient::unsubscribe(const String &topic)
{
// Do not try to unsubscribe if MQTT is not connected.
if(!isConnected())
{
if (_enableSerialLogs)
Serial.println("MQTT! Trying to unsubscribe when disconnected, skipping.");
return false;
}
for (int i = 0; i < _topicSubscriptionList.size(); i++)
{
if (_topicSubscriptionList[i].topic.equals(topic))
{
if(_mqttClient.unsubscribe(topic.c_str()))
{
_topicSubscriptionList.erase(_topicSubscriptionList.begin() + i);
i--;
if(_enableSerialLogs)
Serial.printf("MQTT: Unsubscribed from %s\n", topic.c_str());
}
else
{
if(_enableSerialLogs)
Serial.println("MQTT! unsubscribe failed");
return false;
}
}
}
return true;
}
void EspMQTTClient::setKeepAlive(uint16_t keepAliveSeconds)
{
_mqttClient.setKeepAlive(keepAliveSeconds);
}
void EspMQTTClient::executeDelayed(const unsigned long delay, DelayedExecutionCallback callback)
{
DelayedExecutionRecord delayedExecutionRecord;
delayedExecutionRecord.targetMillis = millis() + delay;
delayedExecutionRecord.callback = callback;
_delayedExecutionList.push_back(delayedExecutionRecord);
}
// ================== Private functions ====================-
// Initiate a Wifi connection (non-blocking)
void EspMQTTClient::connectToWifi()
{
WiFi.mode(WIFI_STA);
#ifdef ESP32
WiFi.setHostname(_mqttClientName);
#else
WiFi.hostname(_mqttClientName);
#endif
WiFi.begin(_wifiSsid, _wifiPassword);
if (_enableSerialLogs)
Serial.printf("\nWiFi: Connecting to %s ... (%fs) \n", _wifiSsid, millis()/1000.0);
}
// Try to connect to the MQTT broker and return True if the connection is successfull (blocking)
bool EspMQTTClient::connectToMqttBroker()
{
if (_enableSerialLogs)
Serial.printf("MQTT: Connecting to broker \"%s\" with client name \"%s\" ... (%fs)", _mqttServerIp, _mqttClientName, millis()/1000.0);
bool success = _mqttClient.connect(_mqttClientName, _mqttUsername, _mqttPassword, _mqttLastWillTopic, 0, _mqttLastWillRetain, _mqttLastWillMessage, _mqttCleanSession);
if (_enableSerialLogs)
{
if (success)
Serial.printf(" - ok. (%fs) \n", millis()/1000.0);
else
{
Serial.printf("unable to connect (%fs), reason: ", millis()/1000.0);
switch (_mqttClient.state())
{
case -4:
Serial.println("MQTT_CONNECTION_TIMEOUT");
break;
case -3:
Serial.println("MQTT_CONNECTION_LOST");
break;
case -2:
Serial.println("MQTT_CONNECT_FAILED");
break;
case -1:
Serial.println("MQTT_DISCONNECTED");
break;
case 1:
Serial.println("MQTT_CONNECT_BAD_PROTOCOL");
break;
case 2:
Serial.println("MQTT_CONNECT_BAD_CLIENT_ID");
break;
case 3:
Serial.println("MQTT_CONNECT_UNAVAILABLE");
break;
case 4:
Serial.println("MQTT_CONNECT_BAD_CREDENTIALS");
break;
case 5:
Serial.println("MQTT_CONNECT_UNAUTHORIZED");
break;
}
Serial.printf("MQTT: Retrying to connect in %i seconds.\n", _mqttReconnectionAttemptDelay / 1000);
}
}
return success;
}
// Delayed execution handling.
// Check if there is delayed execution requests to process and execute them if needed.
void EspMQTTClient::processDelayedExecutionRequests()
{
if (_delayedExecutionList.size() > 0)
{
unsigned long currentMillis = millis();
for(int i = 0 ; i < _delayedExecutionList.size() ; i++)
{
if (_delayedExecutionList[i].targetMillis <= currentMillis)
{
_delayedExecutionList[i].callback();
_delayedExecutionList.erase(_delayedExecutionList.begin() + i);
i--;
}
}
}
}
/**
* Matching MQTT topics, handling the eventual presence of a single wildcard character
*
* @param topic1 is the topic may contain a wildcard
* @param topic2 must not contain wildcards
* @return true on MQTT topic match, false otherwise
*/
bool EspMQTTClient::mqttTopicMatch(const String &topic1, const String &topic2)
{
int i = 0;
if((i = topic1.indexOf('#')) >= 0)
{
String t1a = topic1.substring(0, i);
String t1b = topic1.substring(i+1);
if((t1a.length() == 0 || topic2.startsWith(t1a)) &&
(t1b.length() == 0 || topic2.endsWith(t1b)))
return true;
}
else if((i = topic1.indexOf('+')) >= 0)
{
String t1a = topic1.substring(0, i);
String t1b = topic1.substring(i+1);
if((t1a.length() == 0 || topic2.startsWith(t1a))&&
(t1b.length() == 0 || topic2.endsWith(t1b)))
{
if(topic2.substring(t1a.length(), topic2.length()-t1b.length()).indexOf('/') == -1)
return true;
}
}
else
{
return topic1.equals(topic2);
}
return false;
}
void EspMQTTClient::mqttMessageReceivedCallback(char* topic, byte* payload, unsigned int length)
{
// Convert the payload into a String
// First, We ensure that we dont bypass the maximum size of the PubSubClient library buffer that originated the payload
// This buffer has a maximum length of _mqttClient.getBufferSize() and the payload begin at "headerSize + topicLength + 1"
unsigned int strTerminationPos;
if (strlen(topic) + length + 9 >= _mqttClient.getBufferSize())
{
strTerminationPos = length - 1;
if (_enableSerialLogs)
Serial.print("MQTT! Your message may be truncated, please set setMaxPacketSize() to a higher value.\n");
}
else
strTerminationPos = length;
// Second, we add the string termination code at the end of the payload and we convert it to a String object
payload[strTerminationPos] = '\0';
String payloadStr((char*)payload);
String topicStr(topic);
// Logging
if (_enableSerialLogs)
Serial.printf("MQTT >> [%s] %s\n", topic, payloadStr.c_str());
// Send the message to subscribers
for (byte i = 0 ; i < _topicSubscriptionList.size() ; i++)
{
if (mqttTopicMatch(_topicSubscriptionList[i].topic, String(topic)))
{
if(_topicSubscriptionList[i].callback != NULL)
_topicSubscriptionList[i].callback(payloadStr); // Call the callback
if(_topicSubscriptionList[i].callbackWithTopic != NULL)
_topicSubscriptionList[i].callbackWithTopic(topicStr, payloadStr); // Call the callback
}
}
}
| 28.774669 | 195 | 0.686252 | [
"object"
] |
3ad5cc58d3459b9586fa756f1faf5144fbbc058e | 992 | cpp | C++ | books/tech/software_design/m_noback-object_design_style_guide/code/ch_03-creating_other_objs/05-validate_params_in_ctor/main.cpp | ordinary-developer/education | 1b1f40dacab873b28ee01dfa33a9bd3ec4cfed58 | [
"MIT"
] | null | null | null | books/tech/software_design/m_noback-object_design_style_guide/code/ch_03-creating_other_objs/05-validate_params_in_ctor/main.cpp | ordinary-developer/education | 1b1f40dacab873b28ee01dfa33a9bd3ec4cfed58 | [
"MIT"
] | null | null | null | books/tech/software_design/m_noback-object_design_style_guide/code/ch_03-creating_other_objs/05-validate_params_in_ctor/main.cpp | ordinary-developer/education | 1b1f40dacab873b28ee01dfa33a9bd3ec4cfed58 | [
"MIT"
] | null | null | null | #include <stdexcept>
#include <cassert>
namespace workspace {
class Line {
public:
static Line dotted(const int distanceBetweenDots) {
if (distanceBetweenDots <= 0)
throw std::invalid_argument("invalid distance between dots");
return Line(true, distanceBetweenDots);
}
static Line solid() {
return Line(false, -1);
}
private:
Line(const bool isDotted, const int distanceBetweenDots)
: isDotted_(isDotted), distanceBetweenDots_(distanceBetweenDots)
{}
const bool isDotted_;
const int distanceBetweenDots_;
};
void run() {
{
bool wasException = true;
try {
Line::dotted(-10);
}
catch (const std::invalid_argument&) { assert((wasException = true)); }
catch (...) { assert((false)); }
assert((wasException));
}
{
Line::solid();
assert((true));
}
}
} // workspace
int main() {
workspace::run();
return 0;
}
| 18.37037 | 79 | 0.584677 | [
"solid"
] |
3ad956438ad8daee0f842f29cca1c0c271692f27 | 51,827 | hpp | C++ | ptms/OneFilePTMWF.hpp | pramalhe/OneFile | 49654893f08123031b983c032066cb5b7a7db4ca | [
"MIT"
] | 158 | 2019-04-15T12:35:20.000Z | 2022-03-31T11:52:40.000Z | ptms/OneFilePTMWF.hpp | pramalhe/OneFile | 49654893f08123031b983c032066cb5b7a7db4ca | [
"MIT"
] | 1 | 2020-07-29T22:36:41.000Z | 2020-07-29T22:36:41.000Z | ptms/OneFilePTMWF.hpp | pramalhe/OneFile | 49654893f08123031b983c032066cb5b7a7db4ca | [
"MIT"
] | 18 | 2019-04-17T06:11:00.000Z | 2021-12-25T14:05:02.000Z | /*
* Copyright 2017-2019
* Andreia Correia <andreia.veiga@unine.ch>
* Pedro Ramalhete <pramalhe@gmail.com>
* Pascal Felber <pascal.felber@unine.ch>
* Nachshon Cohen <nachshonc@gmail.com>
*
* This work is published under the MIT license. See LICENSE.txt
*/
#ifndef _PERSISTENT_ONE_FILE_WAIT_FREE_TRANSACTIONAL_MEMORY_H_
#define _PERSISTENT_ONE_FILE_WAIT_FREE_TRANSACTIONAL_MEMORY_H_
#include <atomic>
#include <cassert>
#include <iostream>
#include <vector>
#include <functional>
#include <cstring>
#include <sys/mman.h> // Needed if we use mmap()
#include <sys/types.h> // Needed by open() and close()
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h> // Needed by close()
// Please keep this file in sync (as much as possible) with stms/OneFileWF.hpp
// Macros needed for persistence
#ifdef PWB_IS_CLFLUSH
/*
* More info at http://elixir.free-electrons.com/linux/latest/source/arch/x86/include/asm/special_insns.h#L213
* Intel programming manual at https://www.intel.com/content/dam/www/public/us/en/documents/manuals/64-ia-32-architectures-optimization-manual.pdf
* Use these for Broadwell CPUs (cervino server)
*/
#define PWB(addr) __asm__ volatile("clflush (%0)" :: "r" (addr) : "memory") // Broadwell only works with this.
#define PFENCE() {} // No ordering fences needed for CLFLUSH (section 7.4.6 of Intel manual)
#define PSYNC() {} // For durability it's not obvious, but CLFLUSH seems to be enough, and PMDK uses the same approach
#elif PWB_IS_CLWB
/* Use this for CPUs that support clwb, such as the SkyLake SP series (c5 compute intensive instances in AWS are an example of it) */
#define PWB(addr) __asm__ volatile(".byte 0x66; xsaveopt %0" : "+m" (*(volatile char *)(addr))) // clwb() only for Ice Lake onwards
#define PFENCE() __asm__ volatile("sfence" : : : "memory")
#define PSYNC() __asm__ volatile("sfence" : : : "memory")
#elif PWB_IS_NOP
/* pwbs are not needed for shared memory persistency (i.e. persistency across process failure) */
#define PWB(addr) {}
#define PFENCE() __asm__ volatile("sfence" : : : "memory")
#define PSYNC() __asm__ volatile("sfence" : : : "memory")
#elif PWB_IS_CLFLUSHOPT
/* Use this for CPUs that support clflushopt, which is most recent x86 */
#define PWB(addr) __asm__ volatile(".byte 0x66; clflush %0" : "+m" (*(volatile char *)(addr))) // clflushopt (Kaby Lake)
#define PFENCE() __asm__ volatile("sfence" : : : "memory")
#define PSYNC() __asm__ volatile("sfence" : : : "memory")
#else
#error "You must define what PWB is. Choose PWB_IS_CLFLUSHOPT if you don't know what your CPU is capable of"
#endif
/*
* Differences between POneFileWF and the non-persistent OneFileWF:
* - A secondary redo log (PWriteSet) is placed in persistent memory before attempting a 'commit'.
* - The set of the request in helpApply() is always done with a CAS to enforce ordering on the PWBs of the DCAS;
* - The persistent logs are allocated in PM, same as all user allocations from tmNew(), 'curTx', and 'request'
*/
namespace pofwf {
//
// User configurable variables.
// Feel free to change these if you need larger transactions, more allocations per transacation, or more threads.
//
// Maximum number of registered threads that can execute transactions
static const int REGISTRY_MAX_THREADS = 128;
// Maximum number of stores in the WriteSet per transaction
static const uint64_t TX_MAX_STORES = 40*1024;
// Number of buckets in the hashmap of the WriteSet.
static const uint64_t HASH_BUCKETS = 2048;
// Persistent-specific configuration
// Name of persistent file mapping
static const char * PFILE_NAME = "/dev/shm/ponefilewf_shared";
// Start address of mapped persistent memory
static uint8_t* PREGION_ADDR = (uint8_t*)0x7ff000000000;
// Size of persistent memory. Part of it will be used by the redo logs
static const uint64_t PREGION_SIZE = 1024*1024*1024ULL; // 1 GB by default
// End address of mapped persistent memory
static uint8_t* PREGION_END = (PREGION_ADDR+PREGION_SIZE);
// Maximum number of root pointers available for the user
static const uint64_t MAX_ROOT_POINTERS = 100;
// DCAS / CAS2 macro
#define DCAS(ptr, o1, o2, n1, n2) \
({ \
char __ret; \
__typeof__(o2) __junk; \
__typeof__(*(ptr)) __old1 = (o1); \
__typeof__(o2) __old2 = (o2); \
__typeof__(*(ptr)) __new1 = (n1); \
__typeof__(o2) __new2 = (n2); \
asm volatile("lock cmpxchg16b %2;setz %1" \
: "=d"(__junk), "=a"(__ret), "+m" (*ptr) \
: "b"(__new1), "c"(__new2), \
"a"(__old1), "d"(__old2)); \
__ret; })
// Functions to convert between a transaction identifier (uint64_t) and a pair of {sequence,index}
static inline uint64_t seqidx2trans(uint64_t seq, uint64_t idx) {
return (seq << 10) | idx;
}
static inline uint64_t trans2seq(uint64_t trans) {
return trans >> 10;
}
static inline uint64_t trans2idx(uint64_t trans) {
return trans & 0x3FF; // 10 bits
}
// Flush each cache line in a range
static inline void flushFromTo(void* from, void* to) noexcept {
const uint64_t cache_line_size = 64;
uint8_t* ptr = (uint8_t*)(((uint64_t)from) & (~(cache_line_size-1)));
for (; ptr < (uint8_t*)to; ptr += cache_line_size) PWB(ptr);
}
//
// Thread Registry stuff
//
extern void thread_registry_deregister_thread(const int tid);
// An helper class to do the checkin and checkout of the thread registry
struct ThreadCheckInCheckOut {
static const int NOT_ASSIGNED = -1;
int tid { NOT_ASSIGNED };
~ThreadCheckInCheckOut() {
if (tid == NOT_ASSIGNED) return;
thread_registry_deregister_thread(tid);
}
};
extern thread_local ThreadCheckInCheckOut tl_tcico;
// Forward declaration of global/singleton instance
class ThreadRegistry;
extern ThreadRegistry gThreadRegistry;
/*
* <h1> Registry for threads </h1>
*
* This is singleton type class that allows assignement of a unique id to each thread.
* The first time a thread calls ThreadRegistry::getTID() it will allocate a free slot in 'usedTID[]'.
* This tid wil be saved in a thread-local variable of the type ThreadCheckInCheckOut which
* upon destruction of the thread will call the destructor of ThreadCheckInCheckOut and free the
* corresponding slot to be used by a later thread.
*/
class ThreadRegistry {
private:
alignas(128) std::atomic<bool> usedTID[REGISTRY_MAX_THREADS]; // Which TIDs are in use by threads
alignas(128) std::atomic<int> maxTid {-1}; // Highest TID (+1) in use by threads
public:
ThreadRegistry() {
for (int it = 0; it < REGISTRY_MAX_THREADS; it++) {
usedTID[it].store(false, std::memory_order_relaxed);
}
}
// Progress condition: wait-free bounded (by the number of threads)
int register_thread_new(void) {
for (int tid = 0; tid < REGISTRY_MAX_THREADS; tid++) {
if (usedTID[tid].load(std::memory_order_acquire)) continue;
bool unused = false;
if (!usedTID[tid].compare_exchange_strong(unused, true)) continue;
// Increase the current maximum to cover our thread id
int curMax = maxTid.load();
while (curMax <= tid) {
maxTid.compare_exchange_strong(curMax, tid+1);
curMax = maxTid.load();
}
tl_tcico.tid = tid;
return tid;
}
std::cout << "ERROR: Too many threads, registry can only hold " << REGISTRY_MAX_THREADS << " threads\n";
assert(false);
}
// Progress condition: wait-free population oblivious
inline void deregister_thread(const int tid) {
usedTID[tid].store(false, std::memory_order_release);
}
// Progress condition: wait-free population oblivious
static inline uint64_t getMaxThreads(void) {
return gThreadRegistry.maxTid.load(std::memory_order_acquire);
}
// Progress condition: wait-free bounded (by the number of threads)
static inline int getTID(void) {
int tid = tl_tcico.tid;
if (tid != ThreadCheckInCheckOut::NOT_ASSIGNED) return tid;
return gThreadRegistry.register_thread_new();
}
};
// Each object tracked by Hazard Eras needs to have tmbase as one of its base classes.
struct tmbase {
uint64_t newEra_ {0}; // Filled by tmNew() or tmMalloc()
uint64_t delEra_ {0}; // Filled by tmDelete() or tmFree()
};
// A wrapper to std::function so that we can track it with Hazard Eras
struct TransFunc : public tmbase {
std::function<uint64_t()> func;
template<typename F> TransFunc(F&& f) : func{f} { }
};
// This is a specialized implementation of Hazard Eras meant to be used in the OneFile STM.
// Hazard Eras is a lock-free memory reclamation technique described here:
// https://github.com/pramalhe/ConcurrencyFreaks/blob/master/papers/hazarderas-2017.pdf
// https://dl.acm.org/citation.cfm?id=3087588
//
// We're using OF::curTx.seq as the global era.
//
// This implementation is different from the lock-free OneFile STM because we need
// to track the lifetime of the std::function objects where the lambdas are put.
class HazardErasOF {
private:
static const uint64_t NOERA = 0;
static const int CLPAD = 128/sizeof(std::atomic<uint64_t>);
static const int THRESHOLD_R = 0; // This is named 'R' in the HP paper
const unsigned int maxThreads;
alignas(128) std::atomic<uint64_t>* he;
// It's not nice that we have a lot of empty vectors, but we need padding to avoid false sharing
alignas(128) std::vector<TransFunc*> retiredListTx[REGISTRY_MAX_THREADS*CLPAD];
public:
HazardErasOF(unsigned int maxThreads=REGISTRY_MAX_THREADS) : maxThreads{maxThreads} {
he = new std::atomic<uint64_t>[REGISTRY_MAX_THREADS*CLPAD];
for (unsigned it = 0; it < REGISTRY_MAX_THREADS; it++) {
he[it*CLPAD].store(NOERA, std::memory_order_relaxed);
retiredListTx[it*CLPAD].reserve(REGISTRY_MAX_THREADS);
}
}
~HazardErasOF() {
// Clear the objects in the retired lists
for (unsigned it = 0; it < maxThreads; it++) {
for (unsigned iret = 0; iret < retiredListTx[it*CLPAD].size(); iret++) {
TransFunc* tx = retiredListTx[it*CLPAD][iret];
delete tx;
}
}
delete[] he;
}
// Progress condition: wait-free population oblivious
inline void clear(const int tid) {
he[tid*CLPAD].store(NOERA, std::memory_order_release);
}
// Progress condition: wait-free population oblivious
inline void set(uint64_t trans, const int tid) {
he[tid*CLPAD].store(trans2seq(trans));
}
// Progress condition: wait-free population oblivious
inline void addToRetiredListTx(TransFunc* tx, const int tid) {
retiredListTx[tid*CLPAD].push_back(tx);
}
/**
* Progress condition: bounded wait-free
*
* Attemps to delete the no-longer-in-use objects in the retired list.
* We need to pass the currEra coming from the seq of the currTx so that
* the objects from the current transaction don't get deleted.
*
* TODO: consider using erase() with std::remove_if()
*/
void clean(uint64_t curEra, const int tid) {
for (unsigned iret = 0; iret < retiredListTx[tid*CLPAD].size();) {
TransFunc* tx = retiredListTx[tid*CLPAD][iret];
if (canDelete(curEra, tx)) {
retiredListTx[tid*CLPAD].erase(retiredListTx[tid*CLPAD].begin() + iret);
delete tx;
continue;
}
iret++;
}
}
// Progress condition: wait-free bounded (by the number of threads)
inline bool canDelete(uint64_t curEra, tmbase* del) {
// We can't delete objects from the current transaction
if (del->delEra_ == curEra) return false;
for (unsigned it = 0; it < ThreadRegistry::getMaxThreads(); it++) {
const auto era = he[it*CLPAD].load(std::memory_order_acquire);
if (era == NOERA || era < del->newEra_ || era > del->delEra_) continue;
return false;
}
return true;
}
};
// T is typically a pointer to a node, but it can be integers or other stuff, as long as it fits in 64 bits
template<typename T> struct tmtype {
// Stores the actual value as an atomic
std::atomic<uint64_t> val;
// Lets hope this comes immediately after 'val' in memory mapping, otherwise the DCAS() will fail
std::atomic<uint64_t> seq;
tmtype() { }
tmtype(T initVal) { pstore(initVal); }
// Casting operator
operator T() { return pload(); }
// Prefix increment operator: ++x
void operator++ () { pstore(pload()+1); }
// Prefix decrement operator: --x
void operator-- () { pstore(pload()-1); }
void operator++ (int) { pstore(pload()+1); }
void operator-- (int) { pstore(pload()-1); }
// Equals operator: first downcast to T and then compare
bool operator == (const T& otherval) const { return pload() == otherval; }
// Difference operator: first downcast to T and then compare
bool operator != (const T& otherval) const { return pload() != otherval; }
// Relational operators
bool operator < (const T& rhs) { return pload() < rhs; }
bool operator > (const T& rhs) { return pload() > rhs; }
bool operator <= (const T& rhs) { return pload() <= rhs; }
bool operator >= (const T& rhs) { return pload() >= rhs; }
// Operator arrow ->
T operator->() { return pload(); }
// Copy constructor
tmtype<T>(const tmtype<T>& other) { pstore(other.pload()); }
// Assignment operator from an tmtype
tmtype<T>& operator=(const tmtype<T>& other) {
pstore(other.pload());
return *this;
}
// Assignment operator from a value
tmtype<T>& operator=(T value) {
pstore(value);
return *this;
}
// Operator &
T* operator&() {
return (T*)this;
}
// Meant to be called when know we're the only ones touching
// these contents, for example, in the constructor of an object, before
// making the object visible to other threads.
inline void isolated_store(T newVal) {
val.store((uint64_t)newVal, std::memory_order_relaxed);
}
// Used only internally to initialize the operations[] array
inline void operationsInit() {
val.store((uint64_t)nullptr, std::memory_order_relaxed);
seq.store(0, std::memory_order_relaxed);
}
// Used only internally to initialize the results[] array
inline void resultsInit() {
val.store(0, std::memory_order_relaxed);
seq.store(1, std::memory_order_relaxed);
}
// Used only internally by updateTx() to determine if the request is opened or not
inline uint64_t getSeq() const {
return seq.load(std::memory_order_acquire);
}
// Used only internally by updateTx()
inline void rawStore(T& newVal, uint64_t lseq) {
val.store((uint64_t)newVal, std::memory_order_relaxed);
seq.store(lseq, std::memory_order_release);
}
// Methods that are defined later because they have compilation dependencies on gOFWF
inline T pload() const;
inline bool rawLoad(T& keepVal, uint64_t& keepSeq);
inline void pstore(T newVal);
};
/*
* EsLoco is an Extremely Simple memory aLOCatOr
*
* It is based on intrusive singly-linked lists (a free-list), one for each power of two size.
* All blocks are powers of two, the smallest size enough to contain the desired user data plus the block header.
* There is an array named 'freelists' where each entry is a pointer to the head of a stack for that respective block size.
* Blocks are allocated in powers of 2 of words (64bit words).
* Each block has an header with two words: the size of the node (in words), the pointer to the next node.
* The minimum block size is 4 words, with 2 for the header and 2 for the user.
* When there is no suitable block in the freelist, it will create a new block from the remaining pool.
*
* EsLoco was designed for usage in PTMs but it doesn't have to be used only for that.
* Average number of stores for an allocation is 1.
* Average number of stores for a de-allocation is 2.
*
* Memory layout:
* ------------------------------------------------------------------------
* | poolTop | freelists[0] ... freelists[61] | ... allocated objects ... |
* ------------------------------------------------------------------------
*/
template <template <typename> class P>
class EsLoco {
private:
struct block {
P<block*> next; // Pointer to next block in free-list (when block is in free-list)
P<uint64_t> size; // Exponent of power of two of the size of this block in bytes.
};
const bool debugOn = false;
// Volatile data
uint8_t* poolAddr {nullptr};
uint64_t poolSize {0};
// Pointer to array of persistent heads of free-list
block* freelists {nullptr};
// Volatile pointer to persistent pointer to last unused address (the top of the pool)
P<uint8_t*>* poolTop {nullptr};
// Number of blocks in the freelists array.
// Each entry corresponds to an exponent of the block size: 2^4, 2^5, 2^6... 2^40
static const int kMaxBlockSize = 50; // 1024 TB of memory should be enough
// For powers of 2, returns the highest bit, otherwise, returns the next highest bit
uint64_t highestBit(uint64_t val) {
uint64_t b = 0;
while ((val >> (b+1)) != 0) b++;
if (val > (1ULL << b)) return b+1;
return b;
}
uint8_t* aligned(uint8_t* addr) {
return (uint8_t*)((size_t)addr & (~0x3FULL)) + 128;
}
public:
void init(void* addressOfMemoryPool, size_t sizeOfMemoryPool, bool clearPool=true) {
// Align the base address of the memory pool
poolAddr = aligned((uint8_t*)addressOfMemoryPool);
poolSize = sizeOfMemoryPool + (uint8_t*)addressOfMemoryPool - poolAddr;
// The first thing in the pool is a pointer to the top of the pool
poolTop = (P<uint8_t*>*)poolAddr;
// The second thing in the pool is the array of freelists
freelists = (block*)(poolAddr + sizeof(*poolTop));
if (clearPool) {
std::memset(poolAddr, 0, poolSize);
for (int i = 0; i < kMaxBlockSize; i++) freelists[i].next.pstore(nullptr);
// The size of the freelists array in bytes is sizeof(block)*kMaxBlockSize
// Align to cache line boundary (DCAS needs 16 byte alignment)
poolTop->pstore(aligned(poolAddr + sizeof(*poolTop) + sizeof(block)*kMaxBlockSize));
}
if (debugOn) printf("Starting EsLoco with poolAddr=%p and poolSize=%ld, up to %p\n", poolAddr, poolSize, poolAddr+poolSize);
}
// Resets the metadata of the allocator back to its defaults
void reset() {
std::memset(poolAddr, 0, sizeof(block)*kMaxBlockSize);
poolTop->pstore(nullptr);
}
// Returns the number of bytes that may (or may not) have allocated objects, from the base address to the top address
uint64_t getUsedSize() {
return poolTop->pload() - poolAddr;
}
// Takes the desired size of the object in bytes.
// Returns pointer to memory in pool, or nullptr.
// Does on average 1 store to persistent memory when re-utilizing blocks.
void* malloc(size_t size) {
P<uint8_t*>* top = (P<uint8_t*>*)(((uint8_t*)poolTop));
block* flists = (block*)(((uint8_t*)freelists));
// Adjust size to nearest (highest) power of 2
uint64_t bsize = highestBit(size + sizeof(block));
if (debugOn) printf("malloc(%ld) requested, block size exponent = %ld\n", size, bsize);
block* myblock = nullptr;
// Check if there is a block of that size in the corresponding freelist
if (flists[bsize].next.pload() != nullptr) {
if (debugOn) printf("Found available block in freelist\n");
// Unlink block
myblock = flists[bsize].next;
flists[bsize].next = myblock->next; // pstore()
} else {
if (debugOn) printf("Creating new block from top, currently at %p\n", top->pload());
// Couldn't find a suitable block, get one from the top of the pool if there is one available
if (top->pload() + (1<<bsize) > poolSize + poolAddr) {
printf("EsLoco: Out of memory for %ld bytes allocation\n", size);
return nullptr;
}
myblock = (block*)top->pload();
top->pstore(top->pload() + (1<<bsize)); // pstore()
myblock->size = bsize; // pstore()
}
if (debugOn) printf("returning ptr = %p\n", (void*)((uint8_t*)myblock + sizeof(block)));
// Return the block, minus the header
return (void*)((uint8_t*)myblock + sizeof(block));
}
// Takes a pointer to an object and puts the block on the free-list.
// Does on average 2 stores to persistent memory.
void free(void* ptr) {
if (ptr == nullptr) return;
block* flists = (block*)(((uint8_t*)freelists));
block* myblock = (block*)((uint8_t*)ptr - sizeof(block));
if (debugOn) printf("free(%p) block size exponent = %ld\n", ptr, myblock->size.pload());
// Insert the block in the corresponding freelist
myblock->next = flists[myblock->size].next; // pstore()
flists[myblock->size].next = myblock; // pstore()
}
};
// An entry in the persistent write-set (compacted for performance reasons)
struct PWriteSetEntry {
void* addr; // Address of value+sequence to change
uint64_t val; // Desired value to change to
};
// The persistent write-set
struct PWriteSet {
uint64_t numStores {0}; // Number of stores in the writeSet for the current transaction
std::atomic<uint64_t> request {0}; // Can be moved to CLOSED by other threads, using a CAS
PWriteSetEntry plog[TX_MAX_STORES]; // Redo log of stores
// Applies all entries in the log. Called only by recover() which is non-concurrent.
void applyFromRecover() {
// We're assuming that 'val' is the size of a uint64_t
for (uint64_t i = 0; i < numStores; i++) {
*((uint64_t*)plog[i].addr) = plog[i].val;
PWB(plog[i].addr);
}
}
};
// The persistent metadata is a 'header' that contains all the logs and the persistent curTx variable.
// It is located at the start of the persistent region, and the remaining region contains the data available for the allocator to use.
struct PMetadata {
static const uint64_t MAGIC_ID = 0x1337babe;
std::atomic<uint64_t> curTx {seqidx2trans(1,0)};
std::atomic<uint64_t> pad1[15];
tmtype<void*> rootPtrs[MAX_ROOT_POINTERS];
PWriteSet plog[REGISTRY_MAX_THREADS];
uint64_t id {0};
uint64_t pad2 {0};
};
// A single entry in the write-set
struct WriteSetEntry {
void* addr {nullptr}; // Address of value+sequence to change
uint64_t val; // Desired value to change to
WriteSetEntry* next {nullptr}; // Pointer to next node in the (intrusive) hash map
};
extern thread_local bool tl_is_read_only;
// The write-set is a log of the words modified during the transaction.
// This log is an array with an intrusive hashmap of size HASH_BUCKETS.
struct WriteSet {
static const uint64_t MAX_ARRAY_LOOKUP = 30; // Beyond this, it seems to be faster to use the hashmap
WriteSetEntry log[TX_MAX_STORES]; // Redo log of stores
uint64_t numStores {0}; // Number of stores in the writeSet for the current transaction
WriteSetEntry* buckets[HASH_BUCKETS]; // Intrusive HashMap for fast lookup in large(r) transactions
WriteSet() {
numStores = 0;
for (int i = 0; i < HASH_BUCKETS; i++) buckets[i] = &log[TX_MAX_STORES-1];
}
// Copies the current write set to persistent memory
inline void persistAndFlushLog(PWriteSet* const pwset) {
for (uint64_t i = 0; i < numStores; i++) {
pwset->plog[i].addr = log[i].addr;
pwset->plog[i].val = log[i].val;
}
pwset->numStores = numStores;
// Flush the log and the numStores variable
flushFromTo(&pwset->numStores, &pwset->plog[numStores+1]);
}
// Uses the log to flush the modifications to NVM.
// We assume tmtype does not cross cache line boundaries.
inline void flushModifications() {
for (uint64_t i = 0; i < numStores; i++) PWB(log[i].addr);
}
// Each address on a different bucket
inline uint64_t hash(const void* addr) const {
return (((uint64_t)addr) >> 3) % HASH_BUCKETS;
}
// Adds a modification to the redo log
inline void addOrReplace(void* addr, uint64_t val) {
if (tl_is_read_only) tl_is_read_only = false;
const uint64_t hashAddr = hash(addr);
if ((((size_t)addr & (~0xFULL)) != (size_t)addr)) {
printf("Alignment ERROR in addOrReplace() at address %p\n", addr);
assert(false);
}
if (numStores < MAX_ARRAY_LOOKUP) {
// Lookup in array
for (unsigned int idx = 0; idx < numStores; idx++) {
if (log[idx].addr == addr) {
log[idx].val = val;
return;
}
}
} else {
// Lookup in hashmap
WriteSetEntry* be = buckets[hashAddr];
if (be < &log[numStores] && hash(be->addr) == hashAddr) {
while (be != nullptr) {
if (be->addr == addr) {
be->val = val;
return;
}
be = be->next;
}
}
}
// Add to array
WriteSetEntry* e = &log[numStores++];
assert(numStores < TX_MAX_STORES);
e->addr = addr;
e->val = val;
// Add to hashmap
WriteSetEntry* be = buckets[hashAddr];
// Clear if entry is from previous tx
e->next = (be < e && hash(be->addr) == hashAddr) ? be : nullptr;
buckets[hashAddr] = e;
}
// Does a lookup on the WriteSet for an addr.
// If the numStores is lower than MAX_ARRAY_LOOKUP, the lookup is done on the log, otherwise, the lookup is done on the hashmap.
// If it's not in the write-set, return lval.
inline uint64_t lookupAddr(const void* addr, uint64_t lval) {
if (numStores < MAX_ARRAY_LOOKUP) {
// Lookup in array
for (unsigned int idx = 0; idx < numStores; idx++) {
if (log[idx].addr == addr) return log[idx].val;
}
} else {
// Lookup in hashmap
const uint64_t hashAddr = hash(addr);
WriteSetEntry* be = buckets[hashAddr];
if (be < &log[numStores] && hash(be->addr) == hashAddr) {
while (be != nullptr) {
if (be->addr == addr) return be->val;
be = be->next;
}
}
}
return lval;
}
// Returns true if there is a predecent log entry for the same cache line
inline bool lookupCacheLine(void* addr, int myidx) {
size_t cl = (size_t)addr & (~0x3F);
if (numStores < MAX_ARRAY_LOOKUP) {
// Lookup in array
for (unsigned int idx = 0; idx < myidx; idx++) {
if ((size_t)log[idx].addr & (~0x3F) == cl) return true;
}
} else {
// Lookup in hashmap. If it has the same cache line, it must be in this bucket
WriteSetEntry* be = buckets[hash(addr)];
if (be < &log[numStores]) {
while (be != nullptr) {
if ((size_t)be->addr & (~0x3F) == cl) return true;
be = be->next;
}
}
}
return false;
}
// Assignment operator, used when making a copy of a WriteSet to help another thread
WriteSet& operator = (const WriteSet &other) {
numStores = other.numStores;
for (uint64_t i = 0; i < numStores; i++) log[i] = other.log[i];
return *this;
}
// Applies all entries in the log as DCASes.
// Seq must match for DCAS to succeed. This method is on the "hot-path".
inline void apply(uint64_t seq, const int tid) {
for (uint64_t i = 0; i < numStores; i++) {
// Use an heuristic to give each thread 8 consecutive DCAS to apply
WriteSetEntry& e = log[(tid*8 + i) % numStores];
tmtype<uint64_t>* tmte = (tmtype<uint64_t>*)e.addr;
uint64_t lval = tmte->val.load(std::memory_order_acquire);
uint64_t lseq = tmte->seq.load(std::memory_order_acquire);
if (lseq < seq) DCAS((uint64_t*)e.addr, lval, lseq, e.val, seq);
}
}
};
// Forward declaration
struct OpData;
// This is used by addOrReplace() to know which OpData instance to use for the current transaction
extern thread_local OpData* tl_opdata;
// Its purpose is to hold thread-local data
struct OpData {
uint64_t curTx {0}; // Used during a transaction to keep the value of curTx read in beginTx() (owner thread only)
uint64_t nestedTrans {0}; // Thread-local: Number of nested transactions
PWriteSet* pWriteSet {nullptr}; // Pointer to the redo log in persistent memory
uint64_t padding[16-3]; // Padding to avoid false-sharing in nestedTrans and curTx
};
// Used to identify aborted transactions
struct AbortedTx {};
static constexpr AbortedTx AbortedTxException {};
class OneFileWF;
extern OneFileWF gOFWF;
/**
* <h1> OneFile STM (Wait-Free) </h1>
*
* OneFile is a Software Transacional Memory with wait-free progress, meant to
* implement wait-free data structures.
* OneFile is a word-based STM and it uses double-compare-and-swap (DCAS).
*
* Right now it has several limitations, some will be fixed in the future, some may be hard limitations of this approach:
* - We can't have stack allocated tmtype<> variables. For example, we can't created inside a transaction "tmtpye<uint64_t> tmp = a;",
* it will give weird errors because of stack allocation.
* - We need DCAS but it can be emulated with LL/SC or even with single-word CAS
* if we do redirection to a (lock-free) pool with SeqPtrs;
*/
class OneFileWF {
private:
static const bool debug = false;
OpData *opData;
int fd {-1};
HazardErasOF he {REGISTRY_MAX_THREADS};
// Maximum number of times a reader will fail a transaction before turning into an updateTx()
static const int MAX_READ_TRIES = 4;
// Member variables for wait-free consensus
tmtype<TransFunc*>* operations; // We've tried adding padding here but it didn't make a difference
tmtype<uint64_t>* results;
uint64_t padding[16];
public:
EsLoco<tmtype> esloco {};
PMetadata* pmd {nullptr};
std::atomic<uint64_t>* curTx {nullptr}; // Pointer to persistent memory location of curTx (it's in PMetadata)
WriteSet* writeSets; // Two write-sets for each thread
OneFileWF() {
opData = new OpData[REGISTRY_MAX_THREADS];
writeSets = new WriteSet[REGISTRY_MAX_THREADS];
operations = new tmtype<TransFunc*>[REGISTRY_MAX_THREADS];
for (unsigned i = 0; i < REGISTRY_MAX_THREADS; i++) operations[i].operationsInit();
results = new tmtype<uint64_t>[REGISTRY_MAX_THREADS];
for (unsigned i = 0; i < REGISTRY_MAX_THREADS; i++) results[i].resultsInit();
mapPersistentRegion(PFILE_NAME, PREGION_ADDR, PREGION_SIZE);
}
~OneFileWF() {
delete[] opData;
delete[] writeSets;
delete[] operations;
delete[] results;
}
static std::string className() { return "OneFilePTM-WF"; }
void mapPersistentRegion(const char* filename, uint8_t* regionAddr, const uint64_t regionSize) {
// Check that the header with the logs leaves at least half the memory available to the user
if (sizeof(PMetadata) > regionSize/2) {
printf("ERROR: the size of the logs in persistent memory is so large that it takes more than half the whole persistent memory\n");
printf("Please reduce some of the settings in OneFilePTM.hpp and try again\n");
assert(false);
}
bool reuseRegion = false;
// Check if the file already exists or not
struct stat buf;
if (stat(filename, &buf) == 0) {
// File exists
fd = open(filename, O_RDWR|O_CREAT, 0755);
assert(fd >= 0);
reuseRegion = true;
} else {
// File doesn't exist
fd = open(filename, O_RDWR|O_CREAT, 0755);
assert(fd >= 0);
if (lseek(fd, regionSize-1, SEEK_SET) == -1) {
perror("lseek() error");
}
if (write(fd, "", 1) == -1) {
perror("write() error");
}
}
// mmap() memory range
void* got_addr = (uint8_t *)mmap(regionAddr, regionSize, (PROT_READ | PROT_WRITE), MAP_SHARED, fd, 0);
if (got_addr == MAP_FAILED || got_addr != regionAddr) {
printf("got_addr = %p instead of %p\n", got_addr, regionAddr);
perror("ERROR: mmap() is not working !!! ");
assert(false);
}
// Check if the header is consistent and only then can we attempt to re-use, otherwise we clear everything that's there
pmd = reinterpret_cast<PMetadata*>(regionAddr);
if (reuseRegion) reuseRegion = (pmd->id == PMetadata::MAGIC_ID);
// Map pieces of persistent Metadata to pointers in volatile memory
for (uint64_t i = 0; i < REGISTRY_MAX_THREADS; i++) opData[i].pWriteSet = &(pmd->plog[i]);
curTx = &(pmd->curTx);
// If the file has just been created or if the header is not consistent, clear everything.
// Otherwise, re-use and recover to a consistent state.
if (reuseRegion) {
esloco.init(regionAddr+sizeof(PMetadata), regionSize-sizeof(PMetadata), false);
//recover(); // Not needed on x86
} else {
// Start by resetting all tmtypes::seq in the metadata region
std::memset(regionAddr, 0, sizeof(PMetadata));
new (regionAddr) PMetadata();
esloco.init(regionAddr+sizeof(PMetadata), regionSize-sizeof(PMetadata), true);
PFENCE();
pmd->id = PMetadata::MAGIC_ID;
PWB(&pmd->id);
PFENCE();
}
}
// My transaction was successful, it's my duty to cleanup any retired objects.
// This is called by the owner thread when the transaction succeeds, to pass
// the retired objects to Hazard Eras. We can't delete the objects
// immediately because there might be other threads trying to apply our log
// which may (or may not) contain addresses inside the objects in this list.
void retireRetiresFromLog(OpData& myopd, const int tid) {
uint64_t lseq = trans2seq(curTx->load(std::memory_order_acquire));
// Start a cleaning phase, scanning to see which ones can be removed
he.clean(lseq, tid);
}
// Progress condition: wait-free population-oblivious
// Attempts to publish our write-set (commit the transaction) and then applies the write-set.
// Returns true if my transaction was committed.
inline bool commitTx(OpData& myopd, const int tid) {
// If it's a read-only transaction, then commit immediately
if (writeSets[tid].numStores == 0) return true;
// Give up if the curTx has changed sinced our transaction started
if (myopd.curTx != curTx->load(std::memory_order_acquire)) return false;
// Move our request to OPEN, using the sequence of the previous transaction +1
const uint64_t seq = trans2seq(myopd.curTx);
const uint64_t newTx = seqidx2trans(seq+1,tid);
myopd.pWriteSet->request.store(newTx, std::memory_order_release);
// Copy the write-set to persistent memory and flush it
writeSets[tid].persistAndFlushLog(myopd.pWriteSet);
// Attempt to CAS curTx to our OpDesc instance (tid) incrementing the seq in it
uint64_t lcurTx = myopd.curTx;
if (debug) printf("tid=%i attempting CAS on curTx from (%ld,%ld) to (%ld,%ld)\n", tid, trans2seq(lcurTx), trans2idx(lcurTx), seq+1, (uint64_t)tid);
if (!curTx->compare_exchange_strong(lcurTx, newTx)) return false;
PWB(curTx);
// Execute each store in the write-set using DCAS() and close the request
helpApply(newTx, tid);
retireRetiresFromLog(myopd, tid);
// We should need a PSYNC() here to provide durable linearizabilty, but the CAS of the state in helpApply() acts as a PSYNC() (on x86).
if (debug) printf("Committed transaction (%ld,%ld) with %ld stores\n", seq+1, (uint64_t)tid, writeSets[tid].numStores);
return true;
}
// Progress condition: wait-free (bounded by the number of threads)
// Applies a mutative transaction or gets another thread with an ongoing
// transaction to apply it.
// If three 'seq' have passed since the transaction when we published our
// function, then the worst-case scenario is: the first transaction does not
// see our function; the second transaction transforms our function
// but doesn't apply the corresponding write-set; the third transaction
// guarantees that the log of the second transaction is applied.
inline void innerUpdateTx(OpData& myopd, TransFunc* funcptr, const int tid) {
++myopd.nestedTrans;
if (debug) printf("updateTx(tid=%d)\n", tid);
// We need an era from before the 'funcptr' is announced, so as to protect it
uint64_t firstEra = trans2seq(curTx->load(std::memory_order_acquire));
operations[tid].rawStore(funcptr, results[tid].getSeq());
tl_opdata = &myopd;
// Check 3x for the completion of our function because we don't have a fence
// on operations[tid].rawStore(), otherwise it would be just 2x.
for (int iter = 0; iter < 4; iter++) {
// An update transaction is read-only until it does the first store()
tl_is_read_only = true;
// Clear the logs of the previous transaction
writeSets[tid].numStores = 0;
myopd.curTx = curTx->load(std::memory_order_acquire);
// Optimization: if my request is answered, then my tx is committed
if (results[tid].getSeq() > operations[tid].getSeq()) break;
helpApply(myopd.curTx, tid);
// Reset the write-set after (possibly) helping another transaction complete
writeSets[tid].numStores = 0;
// Use HE to protect the TransFunc we're going to access
he.set(myopd.curTx, tid);
if (myopd.curTx != curTx->load()) continue;
try {
if (!transformAll(myopd.curTx, tid)) continue;
} catch (AbortedTx&) {
continue;
}
if (commitTx(myopd, tid)) break;
}
tl_opdata = nullptr;
--myopd.nestedTrans;
he.clear(tid);
retireMyFunc(tid, funcptr, firstEra);
}
// Update transaction with non-void return value
template<typename R, class F> static R updateTx(F&& func) {
const int tid = ThreadRegistry::getTID();
OpData& myopd = gOFWF.opData[tid];
if (myopd.nestedTrans > 0) return func();
// Copy the lambda to a std::function<> and announce a request with the pointer to it
gOFWF.innerUpdateTx(myopd, new TransFunc([func] () { return (uint64_t)func(); }), tid);
return (R)gOFWF.results[tid].pload();
}
// Update transaction with void return value
template<class F> static void updateTx(F&& func) {
const int tid = ThreadRegistry::getTID();
OpData& myopd = gOFWF.opData[tid];
if (myopd.nestedTrans > 0) {
func();
return;
}
// Copy the lambda to a std::function<> and announce a request with the pointer to it
gOFWF.innerUpdateTx(myopd, new TransFunc([func] () { func(); return 0; }), tid);
}
// Progress condition: wait-free (bounded by the number of threads + MAX_READ_TRIES)
template<typename R, class F> R readTransaction(F&& func) {
const int tid = ThreadRegistry::getTID();
OpData& myopd = opData[tid];
if (myopd.nestedTrans > 0) return func();
++myopd.nestedTrans;
tl_opdata = &myopd;
tl_is_read_only = true;
if (debug) printf("readTx(tid=%d)\n", tid);
R retval {};
writeSets[tid].numStores = 0;
for (int iter = 0; iter < MAX_READ_TRIES; iter++) {
myopd.curTx = curTx->load(std::memory_order_acquire);
helpApply(myopd.curTx, tid);
// Reset the write-set after (possibly) helping another transaction complete
writeSets[tid].numStores = 0;
// Use HE to protect the objects we're going to access during the simulation
he.set(myopd.curTx, tid);
if (myopd.curTx != curTx->load()) continue;
try {
retval = func();
} catch (AbortedTx&) {
continue;
}
--myopd.nestedTrans;
tl_opdata = nullptr;
he.clear(tid);
return retval;
}
if (debug) printf("readTx() executed MAX_READ_TRIES, posing as updateTx()\n");
--myopd.nestedTrans;
// Tried too many times unsucessfully, pose as an updateTx()
return updateTx<R>(func);
}
template<typename R, typename F> static R readTx(F&& func) { return gOFWF.readTransaction<R>(func); }
template<typename F> static void readTx(F&& func) { gOFWF.readTransaction(func); }
template <typename T, typename... Args> static T* tmNew(Args&&... args) {
//template <typename T> static T* tmNew() {
T* ptr = (T*)gOFWF.esloco.malloc(sizeof(T));
//new (ptr) T; // new placement
new (ptr) T(std::forward<Args>(args)...);
return ptr;
}
template<typename T> static void tmDelete(T* obj) {
if (obj == nullptr) return;
obj->~T(); // Execute destructor as part of the current transaction
tmFree(obj);
}
static void* tmMalloc(size_t size) {
if (tl_opdata == nullptr) {
printf("ERROR: Can not allocate outside a transaction\n");
return nullptr;
}
void* obj = gOFWF.esloco.malloc(size);
return obj;
}
// We assume there is a tmbase allocated in the beginning of the allocation
static void tmFree(void* obj) {
if (obj == nullptr) return;
if (tl_opdata == nullptr) {
printf("ERROR: Can not de-allocate outside a transaction\n");
return;
}
gOFWF.esloco.free(obj);
}
static void* pmalloc(size_t size) {
return gOFWF.esloco.malloc(size);
}
static void pfree(void* obj) {
if (obj == nullptr) return;
gOFWF.esloco.free(obj);
}
template <typename T> static inline T* get_object(int idx) {
tmtype<T*>* ptr = (tmtype<T*>*)&(gOFWF.pmd->rootPtrs[idx]);
return ptr->pload();
}
template <typename T> static inline void put_object(int idx, T* obj) {
tmtype<T*>* ptr = (tmtype<T*>*)&(gOFWF.pmd->rootPtrs[idx]);
ptr->pstore(obj);
}
private:
// Progress condition: wait-free population oblivious
inline void helpApply(uint64_t lcurTx, const int tid) {
const uint64_t idx = trans2idx(lcurTx);
const uint64_t seq = trans2seq(lcurTx);
OpData& opd = opData[idx];
// Nothing to apply unless the request matches the curTx
if (lcurTx != opd.pWriteSet->request.load(std::memory_order_acquire)) return;
if (idx != tid) {
// Make a copy of the write-set and check if it is consistent
writeSets[tid] = writeSets[idx];
std::atomic_thread_fence(std::memory_order_acquire);
if (lcurTx != curTx->load()) return;
if (lcurTx != opd.pWriteSet->request.load(std::memory_order_acquire)) return;
}
if (debug) printf("Applying %ld stores in write-set\n", writeSets[tid].numStores);
writeSets[tid].apply(seq, tid);
writeSets[tid].flushModifications();
if (opd.pWriteSet->request.load() == lcurTx) {
const uint64_t newReq = seqidx2trans(seq+1,idx);
opd.pWriteSet->request.compare_exchange_strong(lcurTx, newReq);
}
}
inline void retireMyFunc(const int tid, TransFunc* myfunc, uint64_t firstEra) {
myfunc->newEra_ = firstEra;
myfunc->delEra_ = trans2seq(curTx->load(std::memory_order_acquire))+1; // Do we really need the +1 ?
he.addToRetiredListTx(myfunc, tid);
}
// Aggregate all the functions of the different thread's writeTransaction()
// and transform them into to a single log (the current thread's log).
// Returns true if all active TransFunc were transformed
inline bool transformAll(const uint64_t lcurrTx, const int tid) {
for (unsigned i = 0; i < ThreadRegistry::getMaxThreads(); i++) {
// Check if the operation of thread i has been applied (has a matching result)
TransFunc* txfunc;
uint64_t res, operationsSeq, resultSeq;
if (!operations[i].rawLoad(txfunc, operationsSeq)) continue;
if (!results[i].rawLoad(res, resultSeq)) continue;
if (resultSeq > operationsSeq) continue;
// Operation has not yet been applied, check that transaction identifier has not changed
if (lcurrTx != curTx->load(std::memory_order_acquire)) return false;
// Apply the operation of thread i and save result in results[i],
// with this store being part of the transaction itself.
results[i] = txfunc->func();
}
return true;
}
// Upon restart, re-applies the last transaction, so as to guarantee that
// we have a consistent state in persistent memory.
// This is not used on x86 because the DCAS has atomicity writting to persistent memory.
void recover() {
uint64_t lcurTx = curTx->load(std::memory_order_acquire);
opData[trans2idx(lcurTx)].pWriteSet->applyFromRecover();
PSYNC();
}
};
//
// Wrapper methods to the global TM instance. The user should use these:
//
template<typename R, typename F> static R updateTx(F&& func) { return gOFWF.updateTx<R>(func); }
template<typename R, typename F> static R readTx(F&& func) { return gOFWF.readTx<R>(func); }
template<typename F> static void updateTx(F&& func) { gOFWF.updateTx(func); }
template<typename F> static void readTx(F&& func) { gOFWF.readTx(func); }
template<typename T, typename... Args> T* tmNew(Args&&... args) { return OneFileWF::tmNew<T>(args...); }
template<typename T> void tmDelete(T* obj) { OneFileWF::tmDelete<T>(obj); }
template<typename T> static T* get_object(int idx) { return OneFileWF::get_object<T>(idx); }
template<typename T> static void put_object(int idx, T* obj) { OneFileWF::put_object<T>(idx, obj); }
inline void* tmMalloc(size_t size) { return OneFileWF::tmMalloc(size); }
inline void tmFree(void* obj) { OneFileWF::tmFree(obj); }
// We have to check if there is a new ongoing transaction and if so, abort
// this execution immediately for two reasons:
// 1. Memory Reclamation: the val we're returning may be a pointer to an
// object that has since been retired and deleted, therefore we can't allow
// user code to de-reference it;
// 2. Invariant Conservation: The val we're reading may be from a newer
// transaction, which implies that it may break an invariant in the user code.
// See examples of invariant breaking in this post:
// http://concurrencyfreaks.com/2013/11/stampedlocktryoptimisticread-and.html
template<typename T> inline T tmtype<T>::pload() const {
T lval = (T)val.load(std::memory_order_acquire);
OpData* const myopd = tl_opdata;
if (myopd == nullptr) return lval;
if ((uint8_t*)this < PREGION_ADDR || (uint8_t*)this > PREGION_END) return lval;
uint64_t lseq = seq.load(std::memory_order_acquire);
if (lseq > trans2seq(myopd->curTx)) throw AbortedTxException;
if (tl_is_read_only) return lval;
return (T)gOFWF.writeSets[tl_tcico.tid].lookupAddr(this, (uint64_t)lval);
}
// This method is meant to be used by the internal consensus mechanism, not by the user.
// Returns true if the 'val' and 'seq' placed in 'keepVal' and 'keepSeq'
// are consistent, i.e. linearizabile. We need to use acquire-loads to keep
// order and re-check the 'seq' to make sure it corresponds to the 'val' we're returning.
template<typename T> inline bool tmtype<T>::rawLoad(T& keepVal, uint64_t& keepSeq) {
keepSeq = seq.load(std::memory_order_acquire);
keepVal = (T)val.load(std::memory_order_acquire);
return (keepSeq == seq.load(std::memory_order_acquire));
}
// We don't need to check currTx here because we're not de-referencing
// the val. It's only after a load() that the val may be de-referenced
// (in user code), therefore we do the check on load() only.
template<typename T> inline void tmtype<T>::pstore(T newVal) {
if (tl_opdata == nullptr) { // Looks like we're outside a transaction
val.store((uint64_t)newVal, std::memory_order_relaxed);
} else {
gOFWF.writeSets[tl_tcico.tid].addOrReplace(this, (uint64_t)newVal);
}
}
//
// Place these in a .cpp if you include this header from multiple files (compilation units)
//
OneFileWF gOFWF {};
thread_local OpData* tl_opdata {nullptr};
// Global/singleton to hold all the thread registry functionality
ThreadRegistry gThreadRegistry {};
// During a transaction, this is true up until the first store()
thread_local bool tl_is_read_only {false};
// This is where every thread stores the tid it has been assigned when it calls getTID() for the first time.
// When the thread dies, the destructor of ThreadCheckInCheckOut will be called and de-register the thread.
thread_local ThreadCheckInCheckOut tl_tcico {};
// Helper function for thread de-registration
void thread_registry_deregister_thread(const int tid) {
gThreadRegistry.deregister_thread(tid);
}
}
#endif /* _PERSISTENT_ONE_FILE_WAIT_FREE_TRANSACTIONAL_MEMORY_WITH_H_ */
| 43.883997 | 211 | 0.622919 | [
"object",
"vector",
"transform"
] |
3ada332022e16351d5924f74336c26b09a71ac61 | 11,907 | cpp | C++ | td/tl/tl_jni_object.cpp | 0855304041/td | 3a657d9072b324aad1143c6abe20a802f3b92cd5 | [
"BSL-1.0"
] | 1 | 2021-10-31T01:07:03.000Z | 2021-10-31T01:07:03.000Z | td/tl/tl_jni_object.cpp | 0855304041/td | 3a657d9072b324aad1143c6abe20a802f3b92cd5 | [
"BSL-1.0"
] | 8 | 2021-08-24T02:25:17.000Z | 2021-08-24T06:45:52.000Z | td/tl/tl_jni_object.cpp | 0855304041/td | 3a657d9072b324aad1143c6abe20a802f3b92cd5 | [
"BSL-1.0"
] | 1 | 2021-04-25T13:51:00.000Z | 2021-04-25T13:51:00.000Z | //
// Copyright Aliaksei Levin (levlam@telegram.org), Arseny Smirnov (arseny30@gmail.com) 2014-2021
//
// 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 "td/tl/tl_jni_object.h"
#include "td/utils/common.h"
#include "td/utils/ExitGuard.h"
#include "td/utils/logging.h"
#include "td/utils/misc.h"
#include "td/utils/Slice.h"
#include <memory>
namespace td {
namespace jni {
thread_local bool parse_error;
static jclass BooleanClass;
static jclass IntegerClass;
static jclass LongClass;
static jclass DoubleClass;
static jclass StringClass;
static jclass ObjectClass;
jclass ArrayKeyboardButtonClass;
jclass ArrayInlineKeyboardButtonClass;
jclass ArrayPageBlockTableCellClass;
jmethodID GetConstructorID;
jmethodID BooleanGetValueMethodID;
jmethodID IntegerGetValueMethodID;
jmethodID LongGetValueMethodID;
jmethodID DoubleGetValueMethodID;
static void fatal_error(JNIEnv *env, CSlice error) {
LOG(ERROR) << error;
env->FatalError(error.c_str());
}
jclass get_jclass(JNIEnv *env, const char *class_name) {
jclass clazz = env->FindClass(class_name);
if (!clazz) {
fatal_error(env, PSLICE() << "Can't find class [" << class_name << "]");
}
jclass clazz_global = (jclass)env->NewGlobalRef(clazz);
env->DeleteLocalRef(clazz);
if (!clazz_global) {
fatal_error(env, PSLICE() << "Can't create global reference to [" << class_name << "]");
}
return clazz_global;
}
jmethodID get_method_id(JNIEnv *env, jclass clazz, const char *name, const char *signature) {
jmethodID res = env->GetMethodID(clazz, name, signature);
if (!res) {
fatal_error(env, PSLICE() << "Can't find method [" << name << "] with signature [" << signature << "]");
}
return res;
}
jfieldID get_field_id(JNIEnv *env, jclass clazz, const char *name, const char *signature) {
jfieldID res = env->GetFieldID(clazz, name, signature);
if (!res) {
fatal_error(env, PSLICE() << "Can't find field [" << name << "] with signature [" << signature << "]");
}
return res;
}
void register_native_method(JNIEnv *env, jclass clazz, std::string name, std::string signature, void *function_ptr) {
JNINativeMethod native_method{&name[0], &signature[0], function_ptr};
if (env->RegisterNatives(clazz, &native_method, 1) != 0) {
fatal_error(env, PSLICE() << "RegisterNatives failed for " << name << " with signature " << signature);
}
}
std::unique_ptr<JNIEnv, JvmThreadDetacher> get_jni_env(JavaVM *java_vm, jint jni_version) {
JNIEnv *env = nullptr;
if (!ExitGuard::is_exited() && java_vm->GetEnv(reinterpret_cast<void **>(&env), jni_version) == JNI_EDETACHED) {
#ifdef JDK1_2 // if not Android JNI
auto p_env = reinterpret_cast<void **>(&env);
#else
auto p_env = &env;
#endif
if (java_vm->AttachCurrentThread(p_env, nullptr) != JNI_OK) {
java_vm = nullptr;
env = nullptr;
}
} else {
java_vm = nullptr;
}
return std::unique_ptr<JNIEnv, JvmThreadDetacher>(env, JvmThreadDetacher(java_vm));
}
void init_vars(JNIEnv *env, const char *td_api_java_package) {
BooleanClass = get_jclass(env, "java/lang/Boolean");
IntegerClass = get_jclass(env, "java/lang/Integer");
LongClass = get_jclass(env, "java/lang/Long");
DoubleClass = get_jclass(env, "java/lang/Double");
StringClass = get_jclass(env, "java/lang/String");
ObjectClass = get_jclass(env, (PSLICE() << td_api_java_package << "/TdApi$Object").c_str());
ArrayKeyboardButtonClass =
get_jclass(env, (PSLICE() << "[L" << td_api_java_package << "/TdApi$KeyboardButton;").c_str());
ArrayInlineKeyboardButtonClass =
get_jclass(env, (PSLICE() << "[L" << td_api_java_package << "/TdApi$InlineKeyboardButton;").c_str());
ArrayPageBlockTableCellClass =
get_jclass(env, (PSLICE() << "[L" << td_api_java_package << "/TdApi$PageBlockTableCell;").c_str());
GetConstructorID = get_method_id(env, ObjectClass, "getConstructor", "()I");
BooleanGetValueMethodID = get_method_id(env, BooleanClass, "booleanValue", "()Z");
IntegerGetValueMethodID = get_method_id(env, IntegerClass, "intValue", "()I");
LongGetValueMethodID = get_method_id(env, LongClass, "longValue", "()J");
DoubleGetValueMethodID = get_method_id(env, DoubleClass, "doubleValue", "()D");
}
static size_t get_utf8_from_utf16_length(const jchar *p, jsize len) {
size_t result = 0;
for (jsize i = 0; i < len; i++) {
unsigned int cur = p[i];
if ((cur & 0xF800) == 0xD800) {
if (i < len) {
unsigned int next = p[++i];
if ((next & 0xFC00) == 0xDC00 && (cur & 0x400) == 0) {
result += 4;
continue;
}
}
// TODO wrong UTF-16, it is possible
return 0;
}
result += 1 + (cur >= 0x80) + (cur >= 0x800);
}
return result;
}
static void utf16_to_utf8(const jchar *p, jsize len, char *res) {
for (jsize i = 0; i < len; i++) {
unsigned int cur = p[i];
// TODO conversion unsigned int -> signed char is implementation defined
if (cur <= 0x7f) {
*res++ = static_cast<char>(cur);
} else if (cur <= 0x7ff) {
*res++ = static_cast<char>(0xc0 | (cur >> 6));
*res++ = static_cast<char>(0x80 | (cur & 0x3f));
} else if ((cur & 0xF800) != 0xD800) {
*res++ = static_cast<char>(0xe0 | (cur >> 12));
*res++ = static_cast<char>(0x80 | ((cur >> 6) & 0x3f));
*res++ = static_cast<char>(0x80 | (cur & 0x3f));
} else {
// correctness is already checked
unsigned int next = p[++i];
unsigned int val = ((cur - 0xD800) << 10) + next - 0xDC00 + 0x10000;
*res++ = static_cast<char>(0xf0 | (val >> 18));
*res++ = static_cast<char>(0x80 | ((val >> 12) & 0x3f));
*res++ = static_cast<char>(0x80 | ((val >> 6) & 0x3f));
*res++ = static_cast<char>(0x80 | (val & 0x3f));
}
}
}
static jsize get_utf16_from_utf8_length(const char *p, size_t len, jsize *surrogates) {
// UTF-8 correctness is supposed
jsize result = 0;
for (size_t i = 0; i < len; i++) {
result += ((p[i] & 0xc0) != 0x80);
*surrogates += ((p[i] & 0xf8) == 0xf0);
}
return result;
}
static void utf8_to_utf16(const char *p, size_t len, jchar *res) {
// UTF-8 correctness is supposed
for (size_t i = 0; i < len;) {
unsigned int a = static_cast<unsigned char>(p[i++]);
if (a >= 0x80) {
unsigned int b = static_cast<unsigned char>(p[i++]);
if (a >= 0xe0) {
unsigned int c = static_cast<unsigned char>(p[i++]);
if (a >= 0xf0) {
unsigned int d = static_cast<unsigned char>(p[i++]);
unsigned int val = ((a & 0x07) << 18) + ((b & 0x3f) << 12) + ((c & 0x3f) << 6) + (d & 0x3f) - 0x10000;
*res++ = static_cast<jchar>(0xD800 + (val >> 10));
*res++ = static_cast<jchar>(0xDC00 + (val & 0x3ff));
} else {
*res++ = static_cast<jchar>(((a & 0x0f) << 12) + ((b & 0x3f) << 6) + (c & 0x3f));
}
} else {
*res++ = static_cast<jchar>(((a & 0x1f) << 6) + (b & 0x3f));
}
} else {
*res++ = static_cast<jchar>(a);
}
}
}
std::string fetch_string(JNIEnv *env, jobject o, jfieldID id) {
jstring s = (jstring)env->GetObjectField(o, id);
if (s == nullptr) {
// treat null as an empty string
return std::string();
}
std::string res = from_jstring(env, s);
env->DeleteLocalRef(s);
return res;
}
std::string from_jstring(JNIEnv *env, jstring s) {
if (!s) {
return "";
}
jsize s_len = env->GetStringLength(s);
const jchar *p = env->GetStringChars(s, nullptr);
if (p == nullptr) {
parse_error = true;
return std::string();
}
size_t len = get_utf8_from_utf16_length(p, s_len);
std::string res(len, '\0');
if (len) {
utf16_to_utf8(p, s_len, &res[0]);
}
env->ReleaseStringChars(s, p);
return res;
}
jstring to_jstring(JNIEnv *env, const std::string &s) {
jsize surrogates = 0;
jsize unicode_len = get_utf16_from_utf8_length(s.c_str(), s.size(), &surrogates);
if (surrogates == 0) {
// TODO '\0'
return env->NewStringUTF(s.c_str());
}
jsize result_len = surrogates + unicode_len;
if (result_len <= 256) {
jchar result[256];
utf8_to_utf16(s.c_str(), s.size(), result);
return env->NewString(result, result_len);
}
auto result = std::make_unique<jchar[]>(result_len);
utf8_to_utf16(s.c_str(), s.size(), result.get());
return env->NewString(result.get(), result_len);
}
std::string from_bytes(JNIEnv *env, jbyteArray arr) {
std::string b;
if (arr != nullptr) {
jsize length = env->GetArrayLength(arr);
if (length != 0) {
b.resize(narrow_cast<size_t>(length));
env->GetByteArrayRegion(arr, 0, length, reinterpret_cast<jbyte *>(&b[0]));
}
env->DeleteLocalRef(arr);
}
return b;
}
jbyteArray to_bytes(JNIEnv *env, const std::string &b) {
static_assert(sizeof(char) == sizeof(jbyte), "Mismatched jbyte size");
jsize length = narrow_cast<jsize>(b.size());
jbyteArray arr = env->NewByteArray(length);
if (arr != nullptr && length != 0) {
env->SetByteArrayRegion(arr, 0, length, reinterpret_cast<const jbyte *>(b.data()));
}
return arr;
}
jintArray store_vector(JNIEnv *env, const std::vector<std::int32_t> &v) {
static_assert(sizeof(std::int32_t) == sizeof(jint), "Mismatched jint size");
jsize length = narrow_cast<jsize>(v.size());
jintArray arr = env->NewIntArray(length);
if (arr != nullptr && length != 0) {
env->SetIntArrayRegion(arr, 0, length, reinterpret_cast<const jint *>(&v[0]));
}
return arr;
}
jlongArray store_vector(JNIEnv *env, const std::vector<std::int64_t> &v) {
static_assert(sizeof(std::int64_t) == sizeof(jlong), "Mismatched jlong size");
jsize length = narrow_cast<jsize>(v.size());
jlongArray arr = env->NewLongArray(length);
if (arr != nullptr && length != 0) {
env->SetLongArrayRegion(arr, 0, length, reinterpret_cast<const jlong *>(&v[0]));
}
return arr;
}
jdoubleArray store_vector(JNIEnv *env, const std::vector<double> &v) {
static_assert(sizeof(double) == sizeof(jdouble), "Mismatched jdouble size");
jsize length = narrow_cast<jsize>(v.size());
jdoubleArray arr = env->NewDoubleArray(length);
if (arr != nullptr && length != 0) {
env->SetDoubleArrayRegion(arr, 0, length, reinterpret_cast<const jdouble *>(&v[0]));
}
return arr;
}
jobjectArray store_vector(JNIEnv *env, const std::vector<std::string> &v) {
jsize length = narrow_cast<jsize>(v.size());
jobjectArray arr = env->NewObjectArray(length, StringClass, 0);
if (arr != nullptr) {
for (jsize i = 0; i < length; i++) {
jstring str = to_jstring(env, v[i]);
if (str) {
env->SetObjectArrayElement(arr, i, str);
env->DeleteLocalRef(str);
}
}
}
return arr;
}
std::vector<std::int32_t> fetch_vector(JNIEnv *env, jintArray arr) {
std::vector<std::int32_t> result;
if (arr != nullptr) {
jsize length = env->GetArrayLength(arr);
if (length != 0) {
result.resize(length);
env->GetIntArrayRegion(arr, 0, length, reinterpret_cast<jint *>(&result[0]));
}
env->DeleteLocalRef(arr);
}
return result;
}
std::vector<std::int64_t> fetch_vector(JNIEnv *env, jlongArray arr) {
std::vector<std::int64_t> result;
if (arr != nullptr) {
jsize length = env->GetArrayLength(arr);
if (length != 0) {
result.resize(length);
env->GetLongArrayRegion(arr, 0, length, reinterpret_cast<jlong *>(&result[0]));
}
env->DeleteLocalRef(arr);
}
return result;
}
std::vector<double> fetch_vector(JNIEnv *env, jdoubleArray arr) {
std::vector<double> result;
if (arr != nullptr) {
jsize length = env->GetArrayLength(arr);
if (length != 0) {
result.resize(length);
env->GetDoubleArrayRegion(arr, 0, length, reinterpret_cast<jdouble *>(&result[0]));
}
env->DeleteLocalRef(arr);
}
return result;
}
} // namespace jni
} // namespace td
| 33.075 | 117 | 0.640044 | [
"object",
"vector"
] |
3ae47df386ee604fe64c9010f1a1f4a696208d1c | 1,110 | cpp | C++ | c++/.leetcode/380.insert-delete-get-random-o-1.cpp | ming197/MyLeetCode | eba575765976b12db07be0857faad85b9c60d723 | [
"Apache-2.0"
] | null | null | null | c++/.leetcode/380.insert-delete-get-random-o-1.cpp | ming197/MyLeetCode | eba575765976b12db07be0857faad85b9c60d723 | [
"Apache-2.0"
] | null | null | null | c++/.leetcode/380.insert-delete-get-random-o-1.cpp | ming197/MyLeetCode | eba575765976b12db07be0857faad85b9c60d723 | [
"Apache-2.0"
] | null | null | null | /*
* @lc app=leetcode id=380 lang=cpp
*
* [380] Insert Delete GetRandom O(1)
*/
// @lc code=start
#include <bits/stdc++.h>
using namespace std;
class RandomizedSet {
private:
vector<int> nums;
unordered_map<int, int> indices;
public:
RandomizedSet() {
}
bool insert(int val) {
if(indices.count(val)) return false;
int index = nums.size();
nums.emplace_back(val);
indices[val] = index;
return true;
}
bool remove(int val) {
if (!indices.count(val)) {
return false;
}
int index = indices[val];
int last = nums.back();
nums[index] = last;
indices[last] = index;
nums.pop_back();
indices.erase(val);
return true;
}
int getRandom() {
return nums[rand() % nums.size()];
}
};
/**
* Your RandomizedSet object will be instantiated and called as such:
* RandomizedSet* obj = new RandomizedSet();
* bool param_1 = obj->insert(val);
* bool param_2 = obj->remove(val);
* int param_3 = obj->getRandom();
*/
// @lc code=end
| 20.555556 | 69 | 0.562162 | [
"object",
"vector"
] |
3ae67038ca143c1cc1304d706535ff86acc07bf1 | 3,433 | cc | C++ | win_h264_accel/win_h264_factory.cc | eagle3dstreaming/webrtc | fef9b3652f7744f722785fc1f4cc6b099f4c7aa7 | [
"BSD-3-Clause"
] | null | null | null | win_h264_accel/win_h264_factory.cc | eagle3dstreaming/webrtc | fef9b3652f7744f722785fc1f4cc6b099f4c7aa7 | [
"BSD-3-Clause"
] | null | null | null | win_h264_accel/win_h264_factory.cc | eagle3dstreaming/webrtc | fef9b3652f7744f722785fc1f4cc6b099f4c7aa7 | [
"BSD-3-Clause"
] | null | null | null |
#include <vector>
#include "absl/strings/match.h"
#include "rtc_base/logging.h"
#include "win_h264_accel/win_h264_factory.h"
#include "win_h264_accel/H264Encoder/H264Encoder.h"
#include "win_h264_accel/H264Decoder/H264Decoder.h"
#include "modules/video_coding/codecs/vp8/include/vp8.h"
#include "modules/video_coding/codecs/vp9/include/vp9.h"
namespace webrtc {
namespace {
bool IsFormatSupported(
const std::vector<webrtc::SdpVideoFormat>& supported_formats,
const webrtc::SdpVideoFormat& format) {
for (const webrtc::SdpVideoFormat& supported_format : supported_formats) {
if (cricket::IsSameCodec(format.name, format.parameters,
supported_format.name,
supported_format.parameters)) {
return true;
}
}
return false;
}
} // namespace
WinH264EncoderFactory::WinH264EncoderFactory() {
}
std::vector<SdpVideoFormat> WinH264EncoderFactory::GetSupportedFormats() const
{
std::vector<SdpVideoFormat> supported_codecs;
supported_codecs.push_back(SdpVideoFormat(cricket::kH264CodecName));
supported_codecs.push_back(SdpVideoFormat(cricket::kVp8CodecName));
for (const webrtc::SdpVideoFormat& format : webrtc::SupportedVP9Codecs())
supported_codecs.push_back(format);
return supported_codecs;
}
VideoEncoderFactory::CodecInfo WinH264EncoderFactory::QueryVideoEncoder(
const SdpVideoFormat& format) const
{
CodecInfo info;
if (absl::EqualsIgnoreCase(format.name, cricket::kH264CodecName))
info.is_hardware_accelerated = true;
else
info.is_hardware_accelerated = false;
info.has_internal_source = false;
return info;
}
std::unique_ptr<VideoEncoder> WinH264EncoderFactory::CreateVideoEncoder(
const SdpVideoFormat& format)
{
if (absl::EqualsIgnoreCase(format.name, cricket::kVp8CodecName))
return VP8Encoder::Create();
if (absl::EqualsIgnoreCase(format.name, cricket::kVp9CodecName))
return VP9Encoder::Create(cricket::VideoCodec(format));
if (absl::EqualsIgnoreCase(format.name, cricket::kH264CodecName))
return std::unique_ptr<VideoEncoder>(new WinUWPH264EncoderImpl());
RTC_LOG(LS_ERROR) << "Trying to created encoder of unsupported format "
<< format.name;
return nullptr;
}
std::vector<SdpVideoFormat> WinUWPH264DecoderFactory::GetSupportedFormats() const
{
std::vector<SdpVideoFormat> formats;
formats.push_back(SdpVideoFormat(cricket::kH264CodecName));
formats.push_back(SdpVideoFormat(cricket::kVp8CodecName));
for (const SdpVideoFormat& format : SupportedVP9Codecs())
formats.push_back(format);
return formats;
}
std::unique_ptr<VideoDecoder> WinUWPH264DecoderFactory::CreateVideoDecoder(
const SdpVideoFormat& format)
{
if (!IsFormatSupported(GetSupportedFormats(), format)) {
RTC_LOG(LS_ERROR) << "Trying to create decoder for unsupported format";
return nullptr;
}
if (absl::EqualsIgnoreCase(format.name, cricket::kVp8CodecName))
return VP8Decoder::Create();
if (absl::EqualsIgnoreCase(format.name, cricket::kVp9CodecName))
return VP9Decoder::Create();
if (absl::EqualsIgnoreCase(format.name, cricket::kH264CodecName))
return std::unique_ptr<VideoDecoder>(new WinUWPH264DecoderImpl());
RTC_NOTREACHED();
return nullptr;
}
} // namespace webrtc
| 34.33 | 83 | 0.718613 | [
"vector"
] |
3ae8fef022bb753b4a04dd9d7f7d9a1369ec2db5 | 5,172 | cpp | C++ | released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/gui/z3drenderprocessor.cpp | zzhmark/vaa3d_tools | 3ca418add85a59ac7e805d55a600b78330d7e53d | [
"MIT"
] | 1 | 2021-12-27T19:14:03.000Z | 2021-12-27T19:14:03.000Z | released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/gui/z3drenderprocessor.cpp | zzhmark/vaa3d_tools | 3ca418add85a59ac7e805d55a600b78330d7e53d | [
"MIT"
] | 1 | 2016-12-03T05:33:13.000Z | 2016-12-03T05:33:13.000Z | released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/gui/z3drenderprocessor.cpp | zzhmark/vaa3d_tools | 3ca418add85a59ac7e805d55a600b78330d7e53d | [
"MIT"
] | null | null | null | #include "zglew.h"
#include "z3drenderprocessor.h"
#include "z3dshaderprogram.h"
#include "z3dcameraparameter.h"
#include "QsLog.h"
#include "z3dgpuinfo.h"
#include <QImageWriter>
Z3DRenderProcessor::Z3DRenderProcessor()
: Z3DProcessor()
, m_hardwareSupportVAO(Z3DGpuInfoInstance.isVAOSupported())
, m_privateVAO(0)
{
m_rendererBase = new Z3DRendererBase();
}
Z3DRenderProcessor::~Z3DRenderProcessor()
{
delete m_rendererBase;
}
void Z3DRenderProcessor::initialize()
{
Z3DProcessor::initialize();
const std::vector<Z3DRenderOutputPort*> pports = getPrivateRenderPorts();
for (size_t i=0; i<pports.size(); ++i) {
pports[i]->initialize();
}
if (m_hardwareSupportVAO) {
glGenVertexArrays(1, &m_privateVAO);
}
CHECK_GL_ERROR;
}
void Z3DRenderProcessor::deinitialize()
{
const std::vector<Z3DRenderOutputPort*> pports = getPrivateRenderPorts();
for (size_t i=0; i<pports.size(); ++i) {
pports[i]->deinitialize();
}
if (m_hardwareSupportVAO) {
glDeleteVertexArrays(1, &m_privateVAO);
}
CHECK_GL_ERROR;
Z3DProcessor::deinitialize();
}
void Z3DRenderProcessor::updateSize()
{
// 1. update outport size
bool resized = false;
const std::vector<Z3DOutputPortBase*> outports = getOutputPorts();
glm::ivec2 maxOutportSize(-1, -1);
for(size_t i=0; i<outports.size(); ++i) {
Z3DRenderOutputPort* rp = dynamic_cast<Z3DRenderOutputPort*>(outports[i]);
if (rp) {
glm::ivec2 outportSize = rp->getExpectedSize();
if (outportSize.x > 0 && outportSize != rp->getSize()) {
resized = true;
rp->resize(outportSize);
}
maxOutportSize = glm::max(maxOutportSize, rp->getSize());
}
}
// 2. update private ports
const std::vector<Z3DRenderOutputPort*> privatePorts = getPrivateRenderPorts();
for (size_t i=0; i<privatePorts.size(); ++i) {
privatePorts[i]->resize(maxOutportSize);
}
// 3. update inport expected size
const std::vector<Z3DInputPortBase*> inports = getInputPorts();
for (size_t i=0; i<inports.size(); i++) {
Z3DRenderInputPort *renderInport = dynamic_cast< Z3DRenderInputPort* >(inports[i]);
if (renderInport)
renderInport->setExpectedSize(maxOutportSize);
}
// 4. notify cameras about viewport change
if(resized) {
const std::vector<ZParameter*> parameters = getParameters();
for (size_t i=0; i<parameters.size(); ++i) {
Z3DCameraParameter* cameraPara = dynamic_cast<Z3DCameraParameter*>(parameters[i]);
if (cameraPara) {
cameraPara->viewportChanged(maxOutportSize);
}
}
}
invalidate();
}
void Z3DRenderProcessor::addPrivateRenderPort(Z3DRenderOutputPort* port)
{
port->setProcessor(this);
m_privateRenderPorts.push_back(port);
std::map<QString, Z3DOutputPortBase*>::const_iterator it = m_outputPortMap.find(port->getName());
if (it == m_outputPortMap.end())
m_outputPortMap.insert(std::make_pair(port->getName(), port));
else {
LERROR() << getClassName() << "port" << port->getName() << "has already been inserted!";
assert(false);
}
}
void Z3DRenderProcessor::addPrivateRenderPort(Z3DRenderOutputPort& port)
{
addPrivateRenderPort(&port);
}
void Z3DRenderProcessor::renderScreenQuad(const Z3DShaderProgram &shader)
{
if (!shader.isLinked())
return;
glDepthFunc(GL_ALWAYS);
if (m_hardwareSupportVAO) {
glBindVertexArray(m_privateVAO);
}
GLfloat vertices[] = {-1.f, 1.f, 0.f, //top left corner
-1.f, -1.f, 0.f, //bottom left corner
1.f, 1.f, 0.f, //top right corner
1.f, -1.f, 0.f}; // bottom right rocner
GLint attr_vertex = shader.attributeLocation("attr_vertex");
GLuint bufObjects[1];
glGenBuffers(1, bufObjects);
glEnableVertexAttribArray(attr_vertex);
glBindBuffer(GL_ARRAY_BUFFER, bufObjects[0]);
glBufferData(GL_ARRAY_BUFFER, 3*4*sizeof(GLfloat), vertices, GL_STATIC_DRAW);
glVertexAttribPointer(attr_vertex, 3, GL_FLOAT, GL_FALSE, 0, 0);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glDeleteBuffers(1, bufObjects);
glDisableVertexAttribArray(attr_vertex);
if (m_hardwareSupportVAO) {
glBindVertexArray(0);
}
glDepthFunc(GL_LESS);
}
const std::vector<Z3DRenderOutputPort*> &Z3DRenderProcessor::getPrivateRenderPorts() const
{
return m_privateRenderPorts;
}
void Z3DRenderProcessor::saveTextureAsImage(Z3DTexture *tex, const QString &filename)
{
try {
GLubyte* colorBuffer = 0;
colorBuffer = tex->downloadTextureToBuffer(GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV);
glm::ivec2 size = glm::ivec2(tex->getDimensions());
QImage upsideDownImage((const uchar*)colorBuffer, size.x, size.y,
QImage::Format_ARGB32);
QImage image = upsideDownImage.mirrored(false, true);
QImageWriter writer(filename);
writer.setCompression(1);
if(!writer.write(image)) {
LERROR() << writer.errorString();
delete[] colorBuffer;
}
delete[] colorBuffer;
}
catch (Exception const & e) {
LERROR() << "Exception:" << e.what();
}
catch (std::exception const & e) {
LERROR() << "std exception:" << e.what();
}
}
| 27.510638 | 99 | 0.685808 | [
"vector"
] |
3aede1ca6898378e9e7122ba653a87ab6396c1d5 | 11,860 | cpp | C++ | Sources/Core/Emitter/VolumeParticleEmitter2.cpp | ADMTec/CubbyFlow | c71457fd04ccfaf3ef22772bab9bcec4a0a3b611 | [
"MIT"
] | 216 | 2017-01-25T04:34:30.000Z | 2021-07-15T12:36:06.000Z | Sources/Core/Emitter/VolumeParticleEmitter2.cpp | ADMTec/CubbyFlow | c71457fd04ccfaf3ef22772bab9bcec4a0a3b611 | [
"MIT"
] | 323 | 2017-01-26T13:53:13.000Z | 2021-07-14T16:03:38.000Z | Sources/Core/Emitter/VolumeParticleEmitter2.cpp | ADMTec/CubbyFlow | c71457fd04ccfaf3ef22772bab9bcec4a0a3b611 | [
"MIT"
] | 33 | 2017-01-25T05:05:49.000Z | 2021-06-17T17:30:56.000Z | // This code is based on Jet framework.
// Copyright (c) 2018 Doyub Kim
// CubbyFlow is voxel-based fluid simulation engine for computer games.
// Copyright (c) 2020 CubbyFlow Team
// Core Part: Chris Ohk, Junwoo Hwang, Jihong Sin, Seungwoo Yoo
// AI Part: Dongheon Cho, Minseo Kim
// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.
#include <Core/Emitter/VolumeParticleEmitter2.hpp>
#include <Core/Geometry/SurfaceToImplicit.hpp>
#include <Core/Matrix/Matrix.hpp>
#include <Core/PointGenerator/TrianglePointGenerator.hpp>
#include <Core/Searcher/PointHashGridSearcher.hpp>
#include <Core/Utils/Logging.hpp>
#include <utility>
namespace CubbyFlow
{
static const size_t DEFAULT_HASH_GRID_RESOLUTION = 64;
VolumeParticleEmitter2::VolumeParticleEmitter2(
ImplicitSurface2Ptr implicitSurface, BoundingBox2D maxRegion,
double spacing, const Vector2D& initialVel, const Vector2D& linearVel,
double angularVel, size_t maxNumberOfParticles, double jitter,
bool isOneShot, bool allowOverlapping, uint32_t seed)
: m_rng(seed),
m_implicitSurface(std::move(implicitSurface)),
m_maxRegion(std::move(maxRegion)),
m_spacing(spacing),
m_initialVel(initialVel),
m_linearVel(linearVel),
m_angularVel(angularVel),
m_maxNumberOfParticles(maxNumberOfParticles),
m_jitter(jitter),
m_isOneShot(isOneShot),
m_allowOverlapping(allowOverlapping)
{
m_pointsGen = std::make_shared<TrianglePointGenerator>();
}
void VolumeParticleEmitter2::OnUpdate(double currentTimeInSeconds,
double timeIntervalInSeconds)
{
UNUSED_VARIABLE(currentTimeInSeconds);
UNUSED_VARIABLE(timeIntervalInSeconds);
auto particles = GetTarget();
if (particles == nullptr)
{
return;
}
if (!GetIsEnabled())
{
return;
}
Array1<Vector2D> newPositions;
Array1<Vector2D> newVelocities;
Emit(particles, &newPositions, &newVelocities);
particles->AddParticles(newPositions, newVelocities);
if (m_isOneShot)
{
SetIsEnabled(false);
}
}
void VolumeParticleEmitter2::Emit(const ParticleSystemData2Ptr& particles,
Array1<Vector2D>* newPositions,
Array1<Vector2D>* newVelocities)
{
if (m_implicitSurface == nullptr)
{
return;
}
m_implicitSurface->UpdateQueryEngine();
BoundingBox2D region = m_maxRegion;
if (m_implicitSurface->IsBounded())
{
const BoundingBox2D surfaceBBox = m_implicitSurface->GetBoundingBox();
region.lowerCorner = Max(region.lowerCorner, surfaceBBox.lowerCorner);
region.upperCorner = Min(region.upperCorner, surfaceBBox.upperCorner);
}
// Reserving more space for jittering
const double j = GetJitter();
const double maxJitterDist = 0.5 * j * m_spacing;
size_t numNewParticles = 0;
if (m_allowOverlapping || m_isOneShot)
{
m_pointsGen->ForEachPoint(
region, m_spacing, [&](const Vector2D& point) {
const double newAngleInRadian =
(Random() - 0.5) * (2 * PI_DOUBLE);
const Matrix2x2D rotationMatrix =
Matrix2x2D::MakeRotationMatrix(newAngleInRadian);
const Vector2D randomDir = rotationMatrix * Vector2D();
const Vector2D offset = maxJitterDist * randomDir;
const Vector2D candidate = point + offset;
if (m_implicitSurface->SignedDistance(candidate) <= 0.0)
{
if (m_numberOfEmittedParticles < m_maxNumberOfParticles)
{
newPositions->Append(candidate);
++m_numberOfEmittedParticles;
++numNewParticles;
}
else
{
return false;
}
}
return true;
});
}
else
{
// Use serial hash grid searcher for continuous update.
PointHashGridSearcher2 neighborSearcher(
Vector2UZ(DEFAULT_HASH_GRID_RESOLUTION,
DEFAULT_HASH_GRID_RESOLUTION),
2.0 * m_spacing);
if (!m_allowOverlapping)
{
neighborSearcher.Build(particles->Positions());
}
m_pointsGen->ForEachPoint(
region, m_spacing, [&](const Vector2D& point) {
const double newAngleInRadian =
(Random() - 0.5) * (2 * PI_DOUBLE);
const Matrix2x2D rotationMatrix =
Matrix2x2D::MakeRotationMatrix(newAngleInRadian);
const Vector2D randomDir = rotationMatrix * Vector2D();
const Vector2D offset = maxJitterDist * randomDir;
const Vector2D candidate = point + offset;
if (m_implicitSurface->IsInside(candidate) &&
(!m_allowOverlapping &&
!neighborSearcher.HasNearbyPoint(candidate, m_spacing)))
{
if (m_numberOfEmittedParticles < m_maxNumberOfParticles)
{
newPositions->Append(candidate);
neighborSearcher.Add(candidate);
++m_numberOfEmittedParticles;
++numNewParticles;
}
else
{
return false;
}
}
return true;
});
}
CUBBYFLOW_INFO << "Number of newly generated particles: "
<< numNewParticles;
CUBBYFLOW_INFO << "Number of total generated particles: "
<< m_numberOfEmittedParticles;
newVelocities->Resize(newPositions->Length());
ParallelForEachIndex(newVelocities->Length(), [&](size_t i) {
(*newVelocities)[i] = VelocityAt((*newPositions)[i]);
});
}
void VolumeParticleEmitter2::SetPointGenerator(
const PointGenerator2Ptr& newPointsGen)
{
m_pointsGen = newPointsGen;
}
const ImplicitSurface2Ptr& VolumeParticleEmitter2::GetSurface() const
{
return m_implicitSurface;
}
void VolumeParticleEmitter2::SetSurface(const ImplicitSurface2Ptr& newSurface)
{
m_implicitSurface = newSurface;
}
const BoundingBox2D& VolumeParticleEmitter2::GetMaxRegion() const
{
return m_maxRegion;
}
void VolumeParticleEmitter2::SetMaxRegion(const BoundingBox2D& newMaxRegion)
{
m_maxRegion = newMaxRegion;
}
double VolumeParticleEmitter2::GetJitter() const
{
return m_jitter;
}
void VolumeParticleEmitter2::SetJitter(double newJitter)
{
m_jitter = std::clamp(newJitter, 0.0, 1.0);
}
bool VolumeParticleEmitter2::GetIsOneShot() const
{
return m_isOneShot;
}
void VolumeParticleEmitter2::SetIsOneShot(bool newValue)
{
m_isOneShot = newValue;
}
bool VolumeParticleEmitter2::GetAllowOverlapping() const
{
return m_allowOverlapping;
}
void VolumeParticleEmitter2::SetAllowOverlapping(bool newValue)
{
m_allowOverlapping = newValue;
}
size_t VolumeParticleEmitter2::GetMaxNumberOfParticles() const
{
return m_maxNumberOfParticles;
}
void VolumeParticleEmitter2::SetMaxNumberOfParticles(
size_t newMaxNumberOfParticles)
{
m_maxNumberOfParticles = newMaxNumberOfParticles;
}
double VolumeParticleEmitter2::GetSpacing() const
{
return m_spacing;
}
void VolumeParticleEmitter2::SetSpacing(double newSpacing)
{
m_spacing = newSpacing;
}
Vector2D VolumeParticleEmitter2::GetInitialVelocity() const
{
return m_initialVel;
}
void VolumeParticleEmitter2::SetInitialVelocity(const Vector2D& newInitialVel)
{
m_initialVel = newInitialVel;
}
Vector2D VolumeParticleEmitter2::GetLinearVelocity() const
{
return m_linearVel;
}
void VolumeParticleEmitter2::SetLinearVelocity(const Vector2D& newLinearVel)
{
m_linearVel = newLinearVel;
}
double VolumeParticleEmitter2::GetAngularVelocity() const
{
return m_angularVel;
}
void VolumeParticleEmitter2::SetAngularVelocity(double newAngularVel)
{
m_angularVel = newAngularVel;
}
double VolumeParticleEmitter2::Random()
{
std::uniform_real_distribution<> d{ 0.0, 1.0 };
return d(m_rng);
}
Vector2D VolumeParticleEmitter2::VelocityAt(const Vector2D& point) const
{
const Vector2D r = point - m_implicitSurface->transform.GetTranslation();
return m_linearVel + m_angularVel * Vector2D{ -r.y, r.x } + m_initialVel;
}
VolumeParticleEmitter2::Builder VolumeParticleEmitter2::GetBuilder()
{
return Builder();
}
VolumeParticleEmitter2::Builder&
VolumeParticleEmitter2::Builder::WithImplicitSurface(
const ImplicitSurface2Ptr& implicitSurface)
{
m_implicitSurface = implicitSurface;
if (!m_isBoundSet)
{
m_maxRegion = m_implicitSurface->GetBoundingBox();
}
return *this;
}
VolumeParticleEmitter2::Builder& VolumeParticleEmitter2::Builder::WithSurface(
const Surface2Ptr& surface)
{
m_implicitSurface = std::make_shared<SurfaceToImplicit2>(surface);
if (!m_isBoundSet)
{
m_maxRegion = surface->GetBoundingBox();
}
return *this;
}
VolumeParticleEmitter2::Builder& VolumeParticleEmitter2::Builder::WithMaxRegion(
const BoundingBox2D& maxRegion)
{
m_maxRegion = maxRegion;
m_isBoundSet = true;
return *this;
}
VolumeParticleEmitter2::Builder& VolumeParticleEmitter2::Builder::WithSpacing(
double spacing)
{
m_spacing = spacing;
return *this;
}
VolumeParticleEmitter2::Builder&
VolumeParticleEmitter2::Builder::WithInitialVelocity(const Vector2D& initialVel)
{
m_initialVel = initialVel;
return *this;
}
VolumeParticleEmitter2::Builder&
VolumeParticleEmitter2::Builder::WithLinearVelocity(const Vector2D& linearVel)
{
m_linearVel = linearVel;
return *this;
}
VolumeParticleEmitter2::Builder&
VolumeParticleEmitter2::Builder::WithAngularVelocity(double angularVel)
{
m_angularVel = angularVel;
return *this;
}
VolumeParticleEmitter2::Builder&
VolumeParticleEmitter2::Builder::WithMaxNumberOfParticles(
size_t maxNumberOfParticles)
{
m_maxNumberOfParticles = maxNumberOfParticles;
return *this;
}
VolumeParticleEmitter2::Builder& VolumeParticleEmitter2::Builder::WithJitter(
double jitter)
{
m_jitter = jitter;
return *this;
}
VolumeParticleEmitter2::Builder& VolumeParticleEmitter2::Builder::WithIsOneShot(
bool isOneShot)
{
m_isOneShot = isOneShot;
return *this;
}
VolumeParticleEmitter2::Builder&
VolumeParticleEmitter2::Builder::WithAllowOverlapping(bool allowOverlapping)
{
m_allowOverlapping = allowOverlapping;
return *this;
}
VolumeParticleEmitter2::Builder&
VolumeParticleEmitter2::Builder::WithRandomSeed(uint32_t seed)
{
m_seed = seed;
return *this;
}
VolumeParticleEmitter2 VolumeParticleEmitter2::Builder::Build() const
{
return VolumeParticleEmitter2(m_implicitSurface, m_maxRegion, m_spacing,
m_initialVel, m_linearVel, m_angularVel,
m_maxNumberOfParticles, m_jitter, m_isOneShot,
m_allowOverlapping, m_seed);
}
VolumeParticleEmitter2Ptr VolumeParticleEmitter2::Builder::MakeShared() const
{
return std::shared_ptr<VolumeParticleEmitter2>(
new VolumeParticleEmitter2(m_implicitSurface, m_maxRegion, m_spacing,
m_initialVel, m_linearVel, m_angularVel,
m_maxNumberOfParticles, m_jitter,
m_isOneShot, m_allowOverlapping),
[](VolumeParticleEmitter2* obj) { delete obj; });
}
} // namespace CubbyFlow | 28.037825 | 80 | 0.66914 | [
"geometry",
"transform"
] |
3aeed3fe0e43b96ccf9df6db01952ec2a6944713 | 1,880 | cpp | C++ | json_viewer/test.cpp | void-hoge/json_tools | d13ff1f7cb30260ce0b0dff1c0fd77971141eba0 | [
"MIT"
] | null | null | null | json_viewer/test.cpp | void-hoge/json_tools | d13ff1f7cb30260ce0b0dff1c0fd77971141eba0 | [
"MIT"
] | null | null | null | json_viewer/test.cpp | void-hoge/json_tools | d13ff1f7cb30260ce0b0dff1c0fd77971141eba0 | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
#include <vector>
#include <algorithm>
std::string get_first_word(std::string& str, std::vector<char> separators) {
std::string res;
std::string remained;
std::string::size_type i = 0;
for (; i < str.length(); i++) {
if (std::find(separators.begin(), separators.end(), (char)str.at(i)) != separators.end()) {
// separatorが見つかった
break;
}
res += str.at(i);
}
i++;
for (; i < str.length(); i++) {
remained += str.at(i);
}
str = remained;
return res;
}
std::string get_word(std::string str, int n, std::vector<char> separators) {
// n番目(0~)の単語を返す。
std::string res;
for (int i = 0; i <= n; i++) {
res = get_first_word(str, separators);
}
return res;
}
std::vector<std::string> separate_words(std::string str, std::vector<char> separators) {
std::vector<std::string> res;
while(str != "") {
res.push_back(get_first_word(str, separators));
}
return res;
}
std::string add_space (std::string str, std::vector<char> separators) {
std::string res;
for (std::string::size_type i = 0; i < str.length(); i++) {
if (std::find(separators.begin(), separators.end(), str.at(i)) != separators.end()) {
res+=' ';
for (; i < str.length(); i++) {
if (std::find(separators.begin(), separators.end(), str.at(i)) == separators.end()) {
break;
}
res+=str.at(i);
}
res+=' ';
}
res+=str.at(i);
}
return res;
}
std::vector<std::vector<std::string>> separate_conditions(std::vector<std::string> str) {
if (str.size() % 4 != 2) {
return std::vector<std::vector<std::string>>();
}
std::vector<std::vector<std::string>> res((str.size()/4)+1);
std::vector<std::string> tmp;
for (size_t i = 0; i < str.size(); i++) {
tmp.push_back(str.at(i));
if (i%4 == 3) {
res.at(i/4).push_back(tmp);
tmp.clear();
}
}
return res;
}
int main(int argc, char const *argv[]) {
return 0;
}
| 23.5 | 93 | 0.603723 | [
"vector"
] |
3af0f2048fbb421e6ff9b5224517133b0a29c3e2 | 2,286 | cpp | C++ | Engine/Source/Sapphire/SDK/Assets/Mesh/MeshAsset.cpp | SapphireSuite/Sapphire | f4ec03f2602eb3fb6ba8c5fa8abf145f66179a47 | [
"MIT"
] | 2 | 2020-03-18T09:06:21.000Z | 2020-04-09T00:07:56.000Z | Engine/Source/Sapphire/SDK/Assets/Mesh/MeshAsset.cpp | SapphireSuite/Sapphire | f4ec03f2602eb3fb6ba8c5fa8abf145f66179a47 | [
"MIT"
] | null | null | null | Engine/Source/Sapphire/SDK/Assets/Mesh/MeshAsset.cpp | SapphireSuite/Sapphire | f4ec03f2602eb3fb6ba8c5fa8abf145f66179a47 | [
"MIT"
] | null | null | null | // Copyright 2020 Sapphire development team. All Rights Reserved.
#include <SDK/Assets/Mesh/MeshAsset.hpp>
#include <fstream>
#include <SDK/Wrappers/TinyOBJWrapper.hpp>
namespace Sa
{
MeshAsset::MeshAsset() noexcept : IAsset(AssetType::Mesh)
{
}
void MeshAsset::SetRawData(RawMesh&& _rawData)
{
UnLoad_Internal();
mRawData = Move(_rawData);
}
const RawMesh& MeshAsset::GetRawData() const noexcept
{
return mRawData;
}
bool MeshAsset::IsValid() const noexcept
{
return !mRawData.vertices.empty() && !mRawData.indices.empty();
}
bool MeshAsset::Load_Internal(const std::string& _filePath, std::fstream& _fStream)
{
// Layout.
VertexComp layout = VertexComp::None;
_fStream.read(reinterpret_cast<char*>(&layout), sizeof(VertexComp));
mRawData.SetLayout(layout);
// Vertices.
uint32 vSize = 0u;
_fStream.read(reinterpret_cast<char*>(&vSize), sizeof(uint32));
SA_ASSERT(vSize != 0u, InvalidParam, SDK_Asset, L"Parsing error! Empty vertices.");
mRawData.vertices.resize(vSize);
_fStream.read(mRawData.vertices.data(), vSize);
// Indices.
uint32 iSize = 0u;
_fStream.read(reinterpret_cast<char*>(&iSize), sizeof(uint32));
SA_ASSERT(vSize != 0u, InvalidParam, SDK_Asset, L"Parsing error! Empty vertices.");
mRawData.indices.resize(iSize / sizeof(uint32));
_fStream.read(reinterpret_cast<char*>(mRawData.indices.data()), iSize);
return true;
}
void MeshAsset::UnLoad_Internal()
{
mRawData.vertices.clear();
mRawData.indices.clear();
}
void MeshAsset::Save_Internal(std::fstream& _fStream) const
{
// Layout.
_fStream.write(reinterpret_cast<const char*>(&mRawData.GetLayout()->comps), sizeof(VertexComp));
// Vertices.
uint32 vSize = BitSizeOf(mRawData.vertices);
_fStream.write(reinterpret_cast<const char*>(&vSize), sizeof(uint32));
_fStream.write(mRawData.vertices.data(), vSize);
// Indices.
uint32 iSize = BitSizeOf(mRawData.indices);
_fStream.write(reinterpret_cast<const char*>(&iSize), sizeof(uint32));
_fStream.write(reinterpret_cast<const char*>(mRawData.indices.data()), iSize);
}
bool MeshAsset::Import(const std::string& _resourcePath, const IAssetImportInfos& _importInfos)
{
return TinyOBJWrapper::ImportOBJ(_resourcePath, *this, _importInfos.As<ImportT>());
}
}
| 24.847826 | 98 | 0.724847 | [
"mesh"
] |
3af4226fad358d765e1f7fcf12dd196ad7213c22 | 18,214 | cpp | C++ | run.cpp | Avraiel/glorified-pixeltextgen | 2c990aaa3b2868db39bc6648e60dff453294f737 | [
"MIT"
] | null | null | null | run.cpp | Avraiel/glorified-pixeltextgen | 2c990aaa3b2868db39bc6648e60dff453294f737 | [
"MIT"
] | null | null | null | run.cpp | Avraiel/glorified-pixeltextgen | 2c990aaa3b2868db39bc6648e60dff453294f737 | [
"MIT"
] | null | null | null | #include <cctype>
#include <iostream>
#include <conio.h>
#include <windows.h>
#include <vector>
#include <string>
using namespace std;
char i = 's';
int currentX = 0;
int currentY = 0;
void gotoxy (int x, int y){
COORD coord;
coord.X = x;
coord.Y = y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),coord);
}
void all() {
char ch;
int i;
for(i=1; i<255; i++)
{
ch=i;
cout<<i<<" - "<<ch<<"\n\n";
}
getch();
}
void topleft() {
currentX++;
i = 218;
cout << i;
}
void bottomleft() {
i = 192;
cout << i;
}
void topright() {
i = 191;
cout << i;
}
void bottomright() {
i = 217;
cout << i;
}
void horwall(int length) {
i = 196;
for(int x = 0; x < length; x++){
cout << i;
currentX++;
}
}
void vertwall(int length) {
i = 179;
for(int x = 0; x < length; x++){
cout << i;
currentY++;
gotoxy(currentX, currentY);
}
}
void makeBox(int height, int width) {
topleft();
horwall(width-2);
topright();
gotoxy(currentX,currentY+1);
currentY++;
vertwall(height-2);
bottomright();
gotoxy(0,1);
currentX = 0;
currentY = 1;
vertwall(height-2);
bottomleft();
horwall(width-2);
}
void makeBlock() {
char x = 219;
cout << x << x;
}
void makeBlockBox(int height, int width) {
for(int x = 0; x < height; x++) {
int originalX = currentX;
for(int y = 0; y < width; y++) {
makeBlock();
currentX++;
}
currentX = originalX;
currentY++;
gotoxy(currentX, currentY);
}
}
void setMargin() {
currentX = 2;
currentY = 4;
gotoxy(currentX, currentY);
}
void makeSpace() {
currentX = currentX + 8;
gotoxy(currentX, currentY);
}
void makeA() {
currentY = 9 + 1;
gotoxy(currentX, currentY);
makeBlockBox(2,2);
currentY = 9;
currentX = currentX + 2;
gotoxy(currentX, currentY);
makeBlockBox(2,5);
currentY = 9 + 1;
currentX = currentX + 8;
gotoxy(currentX, currentY);
makeBlockBox(7,2);
currentY = currentY;
currentX = currentX + 2;
gotoxy(currentX, currentY);
makeBlock();
currentY = currentY - 1;
currentX = currentX - 10;
gotoxy(currentX, currentY);
makeBlockBox(2,4);
currentY = currentY - 4;
currentX = currentX - 2;
gotoxy(currentX, currentY);
makeBlockBox(3,2);
currentY = currentY - 4;
currentX = currentX + 2;
gotoxy(currentX, currentY);
makeBlockBox(1,4);
currentX = currentX + 16;
}
void makeB() {
currentY = 4;
gotoxy(currentX, currentY);
makeBlockBox(14,2);
currentY = 4 + 6;
currentX = currentX + 4;
gotoxy(currentX, currentY);
makeBlockBox(2,1);
currentY = 4 + 5;
currentX = currentX + 2;
gotoxy(currentX, currentY);
makeBlockBox(2,3);
currentY = 4 + 6;
currentX = currentX + 4;
gotoxy(currentX, currentY);
makeBlockBox(7,2);
currentY = currentY - 1;
currentX = currentX - 4;
gotoxy(currentX, currentY);
makeBlockBox(2,3);
currentY = currentY - 3;
currentX = currentX - 2;
gotoxy(currentX, currentY);
makeBlockBox(2,1);
currentX = currentX + 14;
}
void makeC() {
currentY = 9 + 2;
gotoxy(currentX, currentY);
makeBlockBox(5,2);
currentY = 9 + 1;
currentX = currentX + 2;
gotoxy(currentX, currentY);
makeBlockBox(2,2);
currentY = 9;
currentX = currentX + 2;
gotoxy(currentX, currentY);
makeBlockBox(2,4);
currentY = 9 + 1;
currentX = currentX + 6;
gotoxy(currentX, currentY);
makeBlockBox(2,2);
currentY = 9 + 6;
currentX = currentX - 8;
gotoxy(currentX, currentY);
makeBlockBox(2,2);
currentY = 9 + 7;
currentX = currentX + 2;
gotoxy(currentX, currentY);
makeBlockBox(2,4);
currentY = 9 + 6;
currentX = currentX + 6;
gotoxy(currentX, currentY);
makeBlockBox(2,2);
currentX = currentX + 8;
}
void makeD() {
currentY = 9 + 1;
gotoxy(currentX, currentY);
makeBlockBox(7,2);
currentY = 9;
currentX = currentX + 2;
gotoxy(currentX, currentY);
makeBlockBox(2,3);
currentY = 9 + 1;
currentX = currentX + 6;
gotoxy(currentX, currentY);
makeBlockBox(2,1);
currentY = 4;
currentX = currentX + 2;
gotoxy(currentX, currentY);
makeBlockBox(14,2);
currentY = currentY - 3;
currentX = currentX - 2;
gotoxy(currentX, currentY);
makeBlockBox(2,1);
currentY = currentY - 1;
currentX = currentX - 6;
gotoxy(currentX, currentY);
makeBlockBox(2,3);
currentX = currentX + 16;
}
void makeE() {
currentY = 9 + 2;
gotoxy(currentX, currentY);
makeBlockBox(5,2);
currentY = 9 + 1;
currentX = currentX + 2;
gotoxy(currentX, currentY);
makeBlockBox(2,2);
currentY = 9;
currentX = currentX + 2;
gotoxy(currentX, currentY);
makeBlockBox(2,4);
currentY = 9 + 1;
currentX = currentX + 8;
gotoxy(currentX, currentY);
makeBlock();
currentY = 9 + 2;
gotoxy(currentX, currentY);
makeBlockBox(3,2);
currentY = currentY - 1;
currentX = currentX - 8;
gotoxy(currentX, currentY);
makeBlockBox(1,4);
currentY = currentY + 1;
currentX = currentX - 2;
gotoxy(currentX, currentY);
makeBlockBox(2,2);
currentY = currentY - 1;
currentX = currentX + 2;
gotoxy(currentX, currentY);
makeBlockBox(2,4);
currentY = currentY - 3;
currentX = currentX + 8;
gotoxy(currentX, currentY);
makeBlockBox(2,1);
currentY = currentY - 2;
currentX = currentX + 2;
gotoxy(currentX, currentY);
makeBlock();
currentX = currentX + 6;
}
void makeF() {
currentY = 4 + 1;
gotoxy(currentX,currentY);
makeBlockBox(13,2);
currentY = 4;
currentX = currentX + 2;
gotoxy(currentX,currentY);
makeBlockBox(2,3);
currentY = 4 + 4;
currentX = currentX - 4;
gotoxy(currentX,currentY);
makeBlockBox(2,1);
currentY = 4 + 4;
currentX = currentX + 6;
gotoxy(currentX,currentY);
makeBlockBox(2,2);
currentX = currentX + 8;
}
void makeG() {
currentY = 9 + 1;
gotoxy(currentX,currentY);
makeBlockBox(6,2);
currentY = 9;
currentX = currentX + 2;
gotoxy(currentX,currentY);
makeBlockBox(2,3);
currentY = 9 + 1;
currentX = currentX + 6;
gotoxy(currentX,currentY);
makeBlockBox(2,1);
currentY = 9;
currentX = currentX + 2;
gotoxy(currentX,currentY);
makeBlockBox(10,2);
currentY = currentY - 1;
currentX = currentX - 2;
gotoxy(currentX,currentY);
makeBlockBox(2,2);
currentY = currentY - 1;
currentX = currentX - 6;
gotoxy(currentX,currentY);
makeBlockBox(2,4);
currentY = currentY - 3;
currentX = currentX - 2;
gotoxy(currentX,currentY);
makeBlockBox(2,2);
currentY = currentY - 5;
currentX = currentX + 2;
gotoxy(currentX,currentY);
makeBlockBox(2,3);
currentY = currentY - 3;
currentX = currentX + 6;
gotoxy(currentX,currentY);
makeBlockBox(2,1);
currentX+=10;
}
void makeH() {
currentY = 4;
gotoxy(currentX, currentY);
makeBlockBox(14,2);
currentY = 4 + 5;
currentX = currentX + 4;
gotoxy(currentX,currentY);
makeBlockBox(2,1);
currentY = 4 + 4;
currentX = currentX + 2;
gotoxy(currentX, currentY);
makeBlockBox(2,3);
currentY = 4 + 5;
currentX = currentX + 4;
gotoxy(currentX, currentY);
makeBlockBox(9,2);
currentX = currentX + 8;
}
void makeI() {
currentY = 4;
gotoxy(currentX, currentY);
//dot
makeBlockBox(2,2);
//big line
currentY+=3;
gotoxy(currentX, currentY);
makeBlockBox(9,2);
currentX = currentX + 8;
}
void makeJ() {
currentY = 4;
currentX = currentX + 3;
gotoxy(currentX, currentY);
makeBlockBox(2,2);
currentY+=3;
gotoxy(currentX, currentY);
makeBlockBox(11,2);
makeBlock();
currentX = currentX - 4;
gotoxy(currentX, currentY);
makeBlockBox(2,2);
currentX = currentX + 12;
}
void makeK() {
currentY = 4;
gotoxy(currentX, currentY);
makeBlockBox(14,2);
currentY = 4 + 8;
currentX = currentX + 4;
gotoxy(currentX, currentY);
makeBlockBox(3,1);
for(int x = 0; x < 3; x++) {
currentY = currentY - 1;
currentX = currentX + 2;
gotoxy(currentX, currentY);
makeBlockBox(2,1);
}
currentY = currentY - 1;
currentX = currentX + 2;
gotoxy(currentX, currentY);
makeBlock();
currentY = 4 + 7;
currentX = currentX - 6;
gotoxy(currentX, currentY);
makeBlockBox(2,1);
for(int x = 0; x < 2; x++) {
currentY = currentY - 3;
currentX = currentX + 2;
gotoxy(currentX, currentY);
makeBlockBox(2,1);
}
currentY = currentY - 2;
currentX = currentX + 2;
gotoxy(currentX, currentY);
makeBlock();
currentX+=6;
}
void makeL() {
currentY = 4;
gotoxy(currentX, currentY);
makeBlockBox(14,2);
currentX+=8;
}
void makeM() {
currentY = 9;
gotoxy(currentX, currentY);
makeBlockBox(9,2);
currentY = 9 + 1;
currentX = currentX + 4;
gotoxy(currentX, currentY);
makeBlockBox(2,1);
currentY = 9;
currentX = currentX + 2;
gotoxy(currentX, currentY);
makeBlockBox(2,3);
currentY = 9 + 1;
currentX = currentX + 4;
gotoxy(currentX, currentY);
makeBlockBox(8,2);
currentY = 9 + 1;
currentX = currentX + 4;
gotoxy(currentX, currentY);
makeBlockBox(2,1);
currentY = 9;
currentX = currentX + 2;
gotoxy(currentX, currentY);
makeBlockBox(2,3);
currentY = 9 + 1;
currentX = currentX + 4;
gotoxy(currentX, currentY);
makeBlockBox(8,2);
currentX+=8;
}
void makeN() {
currentY = 9;
gotoxy(currentX, currentY);
makeBlockBox(9,2);
currentY = 9 + 1;
currentX = currentX + 4;
gotoxy(currentX, currentY);
makeBlockBox(2,1);
currentY = 9;
currentX = currentX + 2;
gotoxy(currentX, currentY);
makeBlockBox(2,3);
currentY = 9 + 1;
currentX = currentX + 4;
gotoxy(currentX, currentY);
makeBlockBox(8,2);
currentX+=8;
}
void makeO() {
currentY = 9 + 2;
gotoxy(currentX, currentY);
makeBlockBox(5,2);
currentY = 9 + 1;
currentX = currentX + 2;
gotoxy(currentX, currentY);
makeBlockBox(2,2);
currentY = 9;
currentX = currentX + 2;
gotoxy(currentX, currentY);
makeBlockBox(2,4);
currentY = 9 + 1;
currentX = currentX + 6;
gotoxy(currentX, currentY);
makeBlockBox(2,2);
currentY = 9 + 2;
currentX = currentX + 2;
gotoxy(currentX, currentY);
makeBlockBox(5,2);
currentY = currentY - 1;
currentX = currentX - 2;
gotoxy(currentX, currentY);
makeBlockBox(2,2);
currentY = currentY - 1;
currentX = currentX - 6;
gotoxy(currentX, currentY);
makeBlockBox(2,4);
currentY = currentY - 3;
currentX = currentX - 2;
gotoxy(currentX, currentY);
makeBlockBox(2,2);
currentX+=18;
}
void makeP() {
currentY = 9;
gotoxy(currentX, currentY);
makeBlockBox(14,2);
currentY = 9 + 1;
currentX = currentX + 4;
gotoxy(currentX, currentY);
makeBlockBox(2,1);
currentY = 9;
currentX = currentX + 2;
gotoxy(currentX, currentY);
makeBlockBox(2,3);
currentY = 9 + 1;
currentX = currentX + 4;
gotoxy(currentX, currentY);
makeBlockBox(7,2);
currentY = currentY - 1;
currentX = currentX - 4;
gotoxy(currentX, currentY);
makeBlockBox(2,3);
currentY = currentY - 3;
currentX = currentX - 2;
gotoxy(currentX, currentY);
makeBlockBox(2,1);
currentX+=14;
}
void makeQ() {
currentY = 9 + 1;
gotoxy(currentX, currentY);
makeBlockBox(7,2);
currentY = 9;
currentX = currentX + 2;
gotoxy(currentX, currentY);
makeBlockBox(2,3);
currentY = 9 + 1;
currentX = currentX + 6;
gotoxy(currentX, currentY);
makeBlockBox(2,1);
currentY = 9;
currentX = currentX + 2;
gotoxy(currentX, currentY);
makeBlockBox(14,2);
currentY = 9 + 6;
currentX = currentX - 2;
gotoxy(currentX, currentY);
makeBlockBox(2,1);
currentY = currentY - 1;
currentX = currentX - 6;
gotoxy(currentX, currentY);
makeBlockBox(2,3);
currentY = 9 + 1;
currentX = currentX - 2;
gotoxy(currentX, currentY);
makeBlockBox(7,2);
currentX+=18;
}
void makeR() {
currentY = 9;
gotoxy(currentX, currentY);
makeBlockBox(9,2);
currentY = 9 + 1;
currentX = currentX + 4;
gotoxy(currentX, currentY);
makeBlockBox(2,1);
currentY = 9;
currentX = currentX + 2;
gotoxy(currentX, currentY);
makeBlockBox(2,3);
currentX+=10;
}
void makeS() {
currentY = 9 + 1;
gotoxy(currentX, currentY);
makeBlockBox(3,2);
currentY = 9;
currentX = currentX + 2;
gotoxy(currentX, currentY);
makeBlockBox(2,4);
currentY = 9 + 1;
currentX = currentX + 6;
gotoxy(currentX, currentY);
makeBlockBox(2,2);
currentY = 9 + 3;
currentX = currentX - 6;
gotoxy(currentX, currentY);
makeBlockBox(2,2);
currentY = currentY - 1;
currentX = currentX + 4;
gotoxy(currentX, currentY);
makeBlockBox(2,2);
currentY = currentY - 1;
currentX = currentX + 2;
gotoxy(currentX, currentY);
makeBlockBox(3,2);
currentY = currentY - 1;
currentX = currentX - 6;
gotoxy(currentX, currentY);
makeBlockBox(2,4);
currentY = currentY - 3;
currentX = currentX - 2;
gotoxy(currentX, currentY);
makeBlockBox(2,2);
currentX+=16;
}
void makeT() {
currentY = 4 + 2;
gotoxy(currentX, currentY);
makeBlockBox(11,2);
currentY = 4;
currentX = currentX + 2;
gotoxy(currentX, currentY);
makeBlockBox(2,1);
currentY = 4 + 5;
currentX = currentX - 4;
gotoxy(currentX, currentY);
makeBlockBox(2,5);
currentY = 9 + 7;
currentX = currentX + 4;
gotoxy(currentX, currentY);
makeBlockBox(2,3);
currentX+=10;
}
void makeU() {
currentY = 9;
gotoxy(currentX, currentY);
makeBlockBox(8,2);
currentY = currentY + 1;
currentX = currentX + 2;
gotoxy(currentX, currentY);
makeBlockBox(2,5);
currentY = 9;
currentX = currentX + 8;
gotoxy(currentX, currentY);
makeBlockBox(8,2);
currentX+=8;
}
void makeV() {
currentY = 9;
gotoxy(currentX, currentY);
makeBlockBox(3,2);
currentY = currentY - 1;
currentX = currentX + 2;
gotoxy(currentX, currentY);
makeBlockBox(3,2);
currentY = currentY;
currentX = currentX + 2;
gotoxy(currentX, currentY);
makeBlockBox(2,1);
currentY = currentY - 2;
currentX = currentX + 2;
gotoxy(currentX, currentY);
makeBlockBox(4,2);
currentY = currentY - 4;
currentX = currentX + 4;
gotoxy(currentX, currentY);
makeBlockBox(2,1);
currentY = currentY - 5;
currentX = currentX;
gotoxy(currentX, currentY);
makeBlockBox(3,2);
currentY = 9;
currentX = currentX + 2;
gotoxy(currentX, currentY);
makeBlockBox(3,2);
currentX+=10;
}
void makeW() {
currentY = 9;
gotoxy(currentX, currentY);
makeBlockBox(3,2);
currentY = currentY - 1;
currentX = currentX + 2;
gotoxy(currentX, currentY);
makeBlockBox(5,2);
currentY = currentY - 1;
currentX = currentX + 2;
gotoxy(currentX, currentY);
makeBlockBox(3,2);
currentY = 9 + 2;
currentX = currentX + 4;
gotoxy(currentX, currentY);
makeBlockBox(5,1);
currentY = 9;
currentX = currentX + 2;
gotoxy(currentX, currentY);
makeBlockBox(4,2);
currentY = 9 + 2;
currentX = currentX + 4;
gotoxy(currentX, currentY);
makeBlockBox(5,1);
currentY = currentY - 1;
currentX = currentX + 2;
gotoxy(currentX, currentY);
makeBlockBox(3,2);
currentY = 9 + 2;
currentX = currentX + 2;
gotoxy(currentX, currentY);
makeBlockBox(5,2);
currentY = 9;
currentX = currentX + 2;
gotoxy(currentX, currentY);
makeBlockBox(3,2);
currentX+=8;
}
void makeX() {
currentY = 9;
gotoxy(currentX, currentY);
makeBlockBox(2,2);
currentY = currentY - 1;
currentX = currentX + 2;
gotoxy(currentX, currentY);
makeBlockBox(2,2);
currentX = currentX + 2;
gotoxy(currentX, currentY);
makeBlockBox(3,3);
currentX = currentX - 2;
gotoxy(currentX, currentY);
makeBlockBox(2,2);
currentY = currentY - 1;
currentX = currentX - 2;
gotoxy(currentX, currentY);
makeBlockBox(2,2);
currentY = 9 + 1;
currentX = currentX + 8;
gotoxy(currentX, currentY);
makeBlockBox(2,2);
currentY = 9;
currentX = currentX + 2;
gotoxy(currentX, currentY);
makeBlockBox(2,2);
currentY = 9 + 6;
currentX = currentX - 2;
gotoxy(currentX, currentY);
makeBlockBox(2,2);
currentY = currentY - 1;
currentX = currentX + 2;
gotoxy(currentX, currentY);
makeBlockBox(2,2);
currentX+=10;
}
void makeY() {
currentY = 9;
gotoxy(currentX, currentY);
makeBlockBox(3,2);
currentX = currentX + 2;
gotoxy(currentX, currentY);
makeBlockBox(3,2);
currentX = currentX + 2;
gotoxy(currentX, currentY);
makeBlockBox(1,1);
currentY = currentY - 1;
currentX = currentX + 2;
gotoxy(currentX, currentY);
makeBlockBox(3,2);
currentX = currentX - 2;
gotoxy(currentX, currentY);
makeBlockBox(2,2);
currentY = currentY - 1;
currentX = currentX - 4;
gotoxy(currentX, currentY);
makeBlockBox(2,3);
currentY = 9 + 3;
currentX = currentX + 8;
gotoxy(currentX, currentY);
makeBlockBox(3,2);
currentY = 9;
currentX = currentX + 2;
gotoxy(currentX, currentY);
makeBlockBox(3,2);
currentX+=8;
}
void makeZ() {
currentY = 9;
gotoxy(currentX, currentY);
makeBlockBox(2,7);
currentX = currentX + 12;
gotoxy(currentX, currentY);
makeBlock();
currentX = currentX - 4;
gotoxy(currentX, currentY);
makeBlockBox(2,2);
for(int x = 0; x < 4; x++) {
currentY = currentY - 1;
currentX = currentX - 2;
gotoxy(currentX, currentY);
makeBlockBox(2,2);
}
currentY = currentY - 1;
gotoxy(currentX, currentY);
makeBlockBox(2,7);
currentX+=18;
}
int main() {
system("color 0f");
string text = "asdasdasdasdasd";
cout << "Enter text: ";
while(text.size() > 12) {
getline(cin, text);
if(text.size() > 12)
cout << " More than 12 characters :< Enter text: ";
}
setMargin();
vector<char> letters;
for(int x = 0; x < text.size(); x++) {
letters.push_back(text[x]);
}
int size = letters.size();
for(int x = 0; x < size; x++) {
if(letters[x] == 'a')
makeA();
else if(letters[x] == 'b')
makeB();
else if(letters[x] == 'c')
makeC();
else if(letters[x] == 'd')
makeD();
else if(letters[x] == 'e')
makeE();
else if(letters[x] == 'f')
makeF();
else if(letters[x] == 'g')
makeG();
else if(letters[x] == 'h')
makeH();
else if(letters[x] == 'i')
makeI();
else if(letters[x] == 'j')
makeJ();
else if(letters[x] == 'k')
makeK();
else if(letters[x] == 'l')
makeL();
else if(letters[x] == 'm')
makeM();
else if(letters[x] == 'n')
makeN();
else if(letters[x] == 'o')
makeO();
else if(letters[x] == 'p')
makeP();
else if(letters[x] == 'q')
makeQ();
else if(letters[x] == 'r')
makeR();
else if(letters[x] == 's')
makeS();
else if(letters[x] == 't')
makeT();
else if(letters[x] == 'u')
makeU();
else if(letters[x] == 'v')
makeV();
else if(letters[x] == 'w')
makeW();
else if(letters[x] == 'x')
makeX();
else if(letters[x] == 'y')
makeY();
else if(letters[x] == 'z')
makeZ();
else if(letters[x] == ' ')
makeSpace();
}
}
| 17.547206 | 65 | 0.64412 | [
"vector"
] |
3af743a687a651a71fc5029fb03411145d6e65fc | 18,548 | hpp | C++ | include/HMUI/MouseBinder.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | include/HMUI/MouseBinder.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | include/HMUI/MouseBinder.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: System.Enum
#include "System/Enum.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: UnityEngine::Events
namespace UnityEngine::Events {
// Forward declaring type: UnityAction
class UnityAction;
// Forward declaring type: UnityAction`1<T0>
template<typename T0>
class UnityAction_1;
}
// Forward declaring namespace: System
namespace System {
// Forward declaring type: Action`1<T>
template<typename T>
class Action_1;
// Forward declaring type: Tuple`3<T1, T2, T3>
template<typename T1, typename T2, typename T3>
class Tuple_3;
}
// Forward declaring namespace: System::Collections::Generic
namespace System::Collections::Generic {
// Forward declaring type: List`1<T>
template<typename T>
class List_1;
}
// Forward declaring namespace: HMUI
namespace HMUI {
// Skipping declaration: ButtonType because it is already included!
// Skipping declaration: MouseEventType because it is already included!
}
// Completed forward declares
// Type namespace: HMUI
namespace HMUI {
// Forward declaring type: MouseBinder
class MouseBinder;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::HMUI::MouseBinder);
DEFINE_IL2CPP_ARG_TYPE(::HMUI::MouseBinder*, "HMUI", "MouseBinder");
// Type namespace: HMUI
namespace HMUI {
// Size: 0x28
#pragma pack(push, 1)
// Autogenerated type: HMUI.MouseBinder
// [TokenAttribute] Offset: FFFFFFFF
class MouseBinder : public ::Il2CppObject {
public:
// Nested type: ::HMUI::MouseBinder::MouseEventType
struct MouseEventType;
// Nested type: ::HMUI::MouseBinder::ButtonType
struct ButtonType;
// Size: 0x4
#pragma pack(push, 1)
// Autogenerated type: HMUI.MouseBinder/HMUI.MouseEventType
// [TokenAttribute] Offset: FFFFFFFF
struct MouseEventType/*, public ::System::Enum*/ {
public:
public:
// public System.Int32 value__
// Size: 0x4
// Offset: 0x0
int value;
// Field size check
static_assert(sizeof(int) == 0x4);
public:
// Creating value type constructor for type: MouseEventType
constexpr MouseEventType(int value_ = {}) noexcept : value{value_} {}
// Creating interface conversion operator: operator ::System::Enum
operator ::System::Enum() noexcept {
return *reinterpret_cast<::System::Enum*>(this);
}
// Creating conversion operator: operator int
constexpr operator int() const noexcept {
return value;
}
// static field const value: static public HMUI.MouseBinder/HMUI.MouseEventType ButtonDown
static constexpr const int ButtonDown = 0;
// Get static field: static public HMUI.MouseBinder/HMUI.MouseEventType ButtonDown
static ::HMUI::MouseBinder::MouseEventType _get_ButtonDown();
// Set static field: static public HMUI.MouseBinder/HMUI.MouseEventType ButtonDown
static void _set_ButtonDown(::HMUI::MouseBinder::MouseEventType value);
// static field const value: static public HMUI.MouseBinder/HMUI.MouseEventType ButtonUp
static constexpr const int ButtonUp = 1;
// Get static field: static public HMUI.MouseBinder/HMUI.MouseEventType ButtonUp
static ::HMUI::MouseBinder::MouseEventType _get_ButtonUp();
// Set static field: static public HMUI.MouseBinder/HMUI.MouseEventType ButtonUp
static void _set_ButtonUp(::HMUI::MouseBinder::MouseEventType value);
// static field const value: static public HMUI.MouseBinder/HMUI.MouseEventType ButtonPress
static constexpr const int ButtonPress = 2;
// Get static field: static public HMUI.MouseBinder/HMUI.MouseEventType ButtonPress
static ::HMUI::MouseBinder::MouseEventType _get_ButtonPress();
// Set static field: static public HMUI.MouseBinder/HMUI.MouseEventType ButtonPress
static void _set_ButtonPress(::HMUI::MouseBinder::MouseEventType value);
// Get instance field reference: public System.Int32 value__
int& dyn_value__();
}; // HMUI.MouseBinder/HMUI.MouseEventType
#pragma pack(pop)
static check_size<sizeof(MouseBinder::MouseEventType), 0 + sizeof(int)> __HMUI_MouseBinder_MouseEventTypeSizeCheck;
static_assert(sizeof(MouseBinder::MouseEventType) == 0x4);
// Size: 0x4
#pragma pack(push, 1)
// Autogenerated type: HMUI.MouseBinder/HMUI.ButtonType
// [TokenAttribute] Offset: FFFFFFFF
struct ButtonType/*, public ::System::Enum*/ {
public:
public:
// public System.Int32 value__
// Size: 0x4
// Offset: 0x0
int value;
// Field size check
static_assert(sizeof(int) == 0x4);
public:
// Creating value type constructor for type: ButtonType
constexpr ButtonType(int value_ = {}) noexcept : value{value_} {}
// Creating interface conversion operator: operator ::System::Enum
operator ::System::Enum() noexcept {
return *reinterpret_cast<::System::Enum*>(this);
}
// Creating conversion operator: operator int
constexpr operator int() const noexcept {
return value;
}
// static field const value: static public HMUI.MouseBinder/HMUI.ButtonType Primary
static constexpr const int Primary = 0;
// Get static field: static public HMUI.MouseBinder/HMUI.ButtonType Primary
static ::HMUI::MouseBinder::ButtonType _get_Primary();
// Set static field: static public HMUI.MouseBinder/HMUI.ButtonType Primary
static void _set_Primary(::HMUI::MouseBinder::ButtonType value);
// static field const value: static public HMUI.MouseBinder/HMUI.ButtonType Secondary
static constexpr const int Secondary = 1;
// Get static field: static public HMUI.MouseBinder/HMUI.ButtonType Secondary
static ::HMUI::MouseBinder::ButtonType _get_Secondary();
// Set static field: static public HMUI.MouseBinder/HMUI.ButtonType Secondary
static void _set_Secondary(::HMUI::MouseBinder::ButtonType value);
// static field const value: static public HMUI.MouseBinder/HMUI.ButtonType Middle
static constexpr const int Middle = 2;
// Get static field: static public HMUI.MouseBinder/HMUI.ButtonType Middle
static ::HMUI::MouseBinder::ButtonType _get_Middle();
// Set static field: static public HMUI.MouseBinder/HMUI.ButtonType Middle
static void _set_Middle(::HMUI::MouseBinder::ButtonType value);
// Get instance field reference: public System.Int32 value__
int& dyn_value__();
}; // HMUI.MouseBinder/HMUI.ButtonType
#pragma pack(pop)
static check_size<sizeof(MouseBinder::ButtonType), 0 + sizeof(int)> __HMUI_MouseBinder_ButtonTypeSizeCheck;
static_assert(sizeof(MouseBinder::ButtonType) == 0x4);
#ifdef USE_CODEGEN_FIELDS
public:
#else
#ifdef CODEGEN_FIELD_ACCESSIBILITY
CODEGEN_FIELD_ACCESSIBILITY:
#else
protected:
#endif
#endif
// private System.Boolean <enabled>k__BackingField
// Size: 0x1
// Offset: 0x10
bool enabled;
// Field size check
static_assert(sizeof(bool) == 0x1);
// Padding between fields: enabled and: scrollBindings
char __padding0[0x7] = {};
// private System.Collections.Generic.List`1<UnityEngine.Events.UnityAction`1<System.Single>> _scrollBindings
// Size: 0x8
// Offset: 0x18
::System::Collections::Generic::List_1<::UnityEngine::Events::UnityAction_1<float>*>* scrollBindings;
// Field size check
static_assert(sizeof(::System::Collections::Generic::List_1<::UnityEngine::Events::UnityAction_1<float>*>*) == 0x8);
// private System.Collections.Generic.List`1<System.Tuple`3<HMUI.MouseBinder/HMUI.ButtonType,HMUI.MouseBinder/HMUI.MouseEventType,UnityEngine.Events.UnityAction>> _buttonBindings
// Size: 0x8
// Offset: 0x20
::System::Collections::Generic::List_1<::System::Tuple_3<::HMUI::MouseBinder::ButtonType, ::HMUI::MouseBinder::MouseEventType, ::UnityEngine::Events::UnityAction*>*>* buttonBindings;
// Field size check
static_assert(sizeof(::System::Collections::Generic::List_1<::System::Tuple_3<::HMUI::MouseBinder::ButtonType, ::HMUI::MouseBinder::MouseEventType, ::UnityEngine::Events::UnityAction*>*>*) == 0x8);
public:
// Get instance field reference: private System.Boolean <enabled>k__BackingField
bool& dyn_$enabled$k__BackingField();
// Get instance field reference: private System.Collections.Generic.List`1<UnityEngine.Events.UnityAction`1<System.Single>> _scrollBindings
::System::Collections::Generic::List_1<::UnityEngine::Events::UnityAction_1<float>*>*& dyn__scrollBindings();
// Get instance field reference: private System.Collections.Generic.List`1<System.Tuple`3<HMUI.MouseBinder/HMUI.ButtonType,HMUI.MouseBinder/HMUI.MouseEventType,UnityEngine.Events.UnityAction>> _buttonBindings
::System::Collections::Generic::List_1<::System::Tuple_3<::HMUI::MouseBinder::ButtonType, ::HMUI::MouseBinder::MouseEventType, ::UnityEngine::Events::UnityAction*>*>*& dyn__buttonBindings();
// public System.Boolean get_enabled()
// Offset: 0x16847F8
bool get_enabled();
// public System.Void set_enabled(System.Boolean value)
// Offset: 0x1684800
void set_enabled(bool value);
// private System.Void Init()
// Offset: 0x1684834
void Init();
// public System.Void AddScrollBindings(System.Collections.Generic.List`1<System.Action`1<System.Single>> bindingData)
// Offset: 0x16848CC
void AddScrollBindings(::System::Collections::Generic::List_1<::System::Action_1<float>*>* bindingData);
// public System.Void AddScrollBinding(System.Action`1<System.Single> action)
// Offset: 0x16849C4
void AddScrollBinding(::System::Action_1<float>* action);
// public System.Void AddButtonBindings(System.Collections.Generic.List`1<System.Tuple`3<HMUI.MouseBinder/HMUI.ButtonType,HMUI.MouseBinder/HMUI.MouseEventType,UnityEngine.Events.UnityAction>> bindingData)
// Offset: 0x1684A64
void AddButtonBindings(::System::Collections::Generic::List_1<::System::Tuple_3<::HMUI::MouseBinder::ButtonType, ::HMUI::MouseBinder::MouseEventType, ::UnityEngine::Events::UnityAction*>*>* bindingData);
// public System.Void AddButtonBinding(HMUI.MouseBinder/HMUI.ButtonType buttonType, HMUI.MouseBinder/HMUI.MouseEventType keyBindingType, UnityEngine.Events.UnityAction action)
// Offset: 0x1684B70
void AddButtonBinding(::HMUI::MouseBinder::ButtonType buttonType, ::HMUI::MouseBinder::MouseEventType keyBindingType, ::UnityEngine::Events::UnityAction* action);
// public System.Void ClearBindings()
// Offset: 0x1684C48
void ClearBindings();
// public System.Void ManualUpdate()
// Offset: 0x1684CA8
void ManualUpdate();
// public System.Void .ctor()
// Offset: 0x168480C
// Implemented from: System.Object
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static MouseBinder* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("::HMUI::MouseBinder::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<MouseBinder*, creationType>()));
}
}; // HMUI.MouseBinder
#pragma pack(pop)
static check_size<sizeof(MouseBinder), 32 + sizeof(::System::Collections::Generic::List_1<::System::Tuple_3<::HMUI::MouseBinder::ButtonType, ::HMUI::MouseBinder::MouseEventType, ::UnityEngine::Events::UnityAction*>*>*)> __HMUI_MouseBinderSizeCheck;
static_assert(sizeof(MouseBinder) == 0x28);
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
DEFINE_IL2CPP_ARG_TYPE(::HMUI::MouseBinder::ButtonType, "HMUI", "MouseBinder/ButtonType");
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
DEFINE_IL2CPP_ARG_TYPE(::HMUI::MouseBinder::MouseEventType, "HMUI", "MouseBinder/MouseEventType");
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: HMUI::MouseBinder::get_enabled
// Il2CppName: get_enabled
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (HMUI::MouseBinder::*)()>(&HMUI::MouseBinder::get_enabled)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(HMUI::MouseBinder*), "get_enabled", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: HMUI::MouseBinder::set_enabled
// Il2CppName: set_enabled
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (HMUI::MouseBinder::*)(bool)>(&HMUI::MouseBinder::set_enabled)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(HMUI::MouseBinder*), "set_enabled", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: HMUI::MouseBinder::Init
// Il2CppName: Init
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (HMUI::MouseBinder::*)()>(&HMUI::MouseBinder::Init)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(HMUI::MouseBinder*), "Init", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: HMUI::MouseBinder::AddScrollBindings
// Il2CppName: AddScrollBindings
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (HMUI::MouseBinder::*)(::System::Collections::Generic::List_1<::System::Action_1<float>*>*)>(&HMUI::MouseBinder::AddScrollBindings)> {
static const MethodInfo* get() {
static auto* bindingData = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System.Collections.Generic", "List`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "Single")})})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(HMUI::MouseBinder*), "AddScrollBindings", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{bindingData});
}
};
// Writing MetadataGetter for method: HMUI::MouseBinder::AddScrollBinding
// Il2CppName: AddScrollBinding
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (HMUI::MouseBinder::*)(::System::Action_1<float>*)>(&HMUI::MouseBinder::AddScrollBinding)> {
static const MethodInfo* get() {
static auto* action = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "Single")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(HMUI::MouseBinder*), "AddScrollBinding", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{action});
}
};
// Writing MetadataGetter for method: HMUI::MouseBinder::AddButtonBindings
// Il2CppName: AddButtonBindings
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (HMUI::MouseBinder::*)(::System::Collections::Generic::List_1<::System::Tuple_3<::HMUI::MouseBinder::ButtonType, ::HMUI::MouseBinder::MouseEventType, ::UnityEngine::Events::UnityAction*>*>*)>(&HMUI::MouseBinder::AddButtonBindings)> {
static const MethodInfo* get() {
static auto* bindingData = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System.Collections.Generic", "List`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Tuple`3"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("HMUI", "MouseBinder/ButtonType"), ::il2cpp_utils::GetClassFromName("HMUI", "MouseBinder/MouseEventType"), ::il2cpp_utils::GetClassFromName("UnityEngine.Events", "UnityAction")})})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(HMUI::MouseBinder*), "AddButtonBindings", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{bindingData});
}
};
// Writing MetadataGetter for method: HMUI::MouseBinder::AddButtonBinding
// Il2CppName: AddButtonBinding
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (HMUI::MouseBinder::*)(::HMUI::MouseBinder::ButtonType, ::HMUI::MouseBinder::MouseEventType, ::UnityEngine::Events::UnityAction*)>(&HMUI::MouseBinder::AddButtonBinding)> {
static const MethodInfo* get() {
static auto* buttonType = &::il2cpp_utils::GetClassFromName("HMUI", "MouseBinder/ButtonType")->byval_arg;
static auto* keyBindingType = &::il2cpp_utils::GetClassFromName("HMUI", "MouseBinder/MouseEventType")->byval_arg;
static auto* action = &::il2cpp_utils::GetClassFromName("UnityEngine.Events", "UnityAction")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(HMUI::MouseBinder*), "AddButtonBinding", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{buttonType, keyBindingType, action});
}
};
// Writing MetadataGetter for method: HMUI::MouseBinder::ClearBindings
// Il2CppName: ClearBindings
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (HMUI::MouseBinder::*)()>(&HMUI::MouseBinder::ClearBindings)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(HMUI::MouseBinder*), "ClearBindings", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: HMUI::MouseBinder::ManualUpdate
// Il2CppName: ManualUpdate
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (HMUI::MouseBinder::*)()>(&HMUI::MouseBinder::ManualUpdate)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(HMUI::MouseBinder*), "ManualUpdate", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: HMUI::MouseBinder::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
| 56.895706 | 510 | 0.730591 | [
"object",
"vector"
] |
3af8f296fb429c2a0c937ed7b1203ce1627b2f43 | 10,438 | cpp | C++ | src/SolAR3DTransformEstimationSACFrom3D3D.cpp | wemap/SolARModuleTools | 43e8fc48061ab692ac37ddcbed530f4ae147ed8a | [
"Apache-2.0"
] | null | null | null | src/SolAR3DTransformEstimationSACFrom3D3D.cpp | wemap/SolARModuleTools | 43e8fc48061ab692ac37ddcbed530f4ae147ed8a | [
"Apache-2.0"
] | 8 | 2018-10-02T15:49:59.000Z | 2021-07-27T15:12:40.000Z | src/SolAR3DTransformEstimationSACFrom3D3D.cpp | wemap/SolARModuleTools | 43e8fc48061ab692ac37ddcbed530f4ae147ed8a | [
"Apache-2.0"
] | 3 | 2019-07-24T15:03:43.000Z | 2021-06-14T15:37:29.000Z | /**
* @copyright Copyright (c) 2017 B-com http://www.b-com.com/
*
* 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 "SolAR3DTransformEstimationSACFrom3D3D.h"
#include "core/Log.h"
XPCF_DEFINE_FACTORY_CREATE_INSTANCE(SolAR::MODULES::TOOLS::SolAR3DTransformEstimationSACFrom3D3D);
namespace xpcf = org::bcom::xpcf;
namespace SolAR {
using namespace datastructure;
using namespace api::geom;
namespace MODULES {
namespace TOOLS {
SolAR3DTransformEstimationSACFrom3D3D::SolAR3DTransformEstimationSACFrom3D3D() :ConfigurableBase(xpcf::toUUID<SolAR3DTransformEstimationSACFrom3D3D>())
{
declareInterface<api::solver::pose::I3DTransformSACFinderFrom3D3D>(this);
declareInjectable<I3DTransform>(m_transform3D);
declareInjectable<IProject>(m_projector);
declareProperty("iterationsCount", m_iterationsCount);
declareProperty("reprojError", m_reprojError);
declareProperty("distanceError", m_distanceError);
declareProperty("confidence", m_confidence);
declareProperty("minNbInliers", m_NbInliersToValidPose);
srand(time(NULL));
LOG_DEBUG(" SolAR3DTransformEstimationSACFrom3D3D constructor");
}
void SolAR3DTransformEstimationSACFrom3D3D::setCameraParameters(const CamCalibration & intrinsicParams, const CamDistortion & distortionParams)
{
m_projector->setCameraParameters(intrinsicParams, distortionParams);
}
void randomIndices(int maxIndex, int nbIndices, std::vector<int> &indices) {
while (indices.size() != nbIndices) {
int index = rand() % maxIndex;
if (std::find(indices.begin(), indices.end(), index) == indices.end())
indices.push_back(index);
}
}
bool find(const std::vector<Point3Df> & firstPoints3D,
const std::vector<Point3Df> & secondPoints3D,
Transform3Df & pose)
{
// init 3D transformation
pose.linear() = Eigen::Matrix3f::Identity(3, 3);
pose.translation() = Eigen::Vector3f::Zero();
Eigen::MatrixXf in, out;
in.resize(firstPoints3D.size(), 3);
out.resize(secondPoints3D.size(), 3);
if (in.rows() != out.rows())
return false;
for (int i = 0; i < firstPoints3D.size(); i++) {
in.row(i) = Eigen::Vector3f(firstPoints3D[i].getX(), firstPoints3D[i].getY(), firstPoints3D[i].getZ());
out.row(i) = Eigen::Vector3f(secondPoints3D[i].getX(), secondPoints3D[i].getY(), secondPoints3D[i].getZ());
}
// First find the scale, by finding the ratio of sums of some distances,
// then bring the datasets to the same scale.
float dist_in = 0, dist_out = 0;
for (int row = 0; row < in.rows() - 1; row++) {
dist_in += (in.row(row + 1) - in.row(row)).norm();
dist_out += (out.row(row + 1) - out.row(row)).norm();
}
if (dist_in <= 0 || dist_out <= 0)
return false;
float scale = dist_out / dist_in;
out /= scale;
// Find the centroids then shift to the origin
Eigen::Vector3f in_ctr = Eigen::Vector3f::Zero();
Eigen::Vector3f out_ctr = Eigen::Vector3f::Zero();
for (int row = 0; row < in.rows(); row++) {
in_ctr += in.row(row);
out_ctr += out.row(row);
}
in_ctr /= in.rows();
out_ctr /= out.rows();
for (int row = 0; row < in.rows(); row++) {
in.row(row) -= in_ctr;
out.row(row) -= out_ctr;
}
// SVD
Eigen::MatrixXf Cov = in.transpose() * out;
Eigen::JacobiSVD<Eigen::MatrixXf> svd(Cov, Eigen::ComputeThinU | Eigen::ComputeThinV);
// Find the rotation
float d = (svd.matrixV() * svd.matrixU().transpose()).determinant();
if (d > 0)
d = 1.f;
else
d = -1.f;
Eigen::Matrix3f I = Eigen::Matrix3f::Identity(3, 3);
I(2, 2) = d;
Eigen::Matrix3f R = svd.matrixV() * I * svd.matrixU().transpose();
// The final transform
pose.linear() = scale * R;
pose.translation() = scale * (out_ctr - R * in_ctr);
return true;
}
void getInliers(const std::vector<Point3Df> &firstPoints3DTrans, const std::vector<Point3Df> &secondPoints3D, const float &thres, std::vector<int> &inliers)
{
for (int i = 0; i < firstPoints3DTrans.size(); ++i)
if ((firstPoints3DTrans[i] - secondPoints3D[i]).norm() < thres)
inliers.push_back(i);
}
void getInliersByProject(const std::vector<Point2Df> &firstProjected2DPts, const std::vector<Point2Df> &keypoints2, const std::vector<Point2Df> &secondProjected2DPts, const std::vector<Point2Df> &keypoints1, const float &thres, std::vector<int> &inliers)
{
for (int i = 0; i < firstProjected2DPts.size(); ++i)
if (((firstProjected2DPts[i] - keypoints2[i]).norm() < thres) && ((secondProjected2DPts[i] - keypoints1[i]).norm() < thres))
inliers.push_back(i);
}
FrameworkReturnCode SolAR3DTransformEstimationSACFrom3D3D::estimate(const std::vector<Point3Df> & firstPoints3D,
const std::vector<Point3Df> & secondPoints3D,
Transform3Df & pose,
std::vector<int> &inliers)
{
if ((firstPoints3D.size() != secondPoints3D.size()) || (firstPoints3D.size() < 3))
return FrameworkReturnCode::_ERROR_;
int iterations = m_iterationsCount;
std::vector<int> bestInliers;
Transform3Df bestPose;
while (iterations != 0) {
// get 3 random indices
std::vector<int> indices;
randomIndices(static_cast<int>(firstPoints3D.size()), 3, indices);
// get 3 correspondences
std::vector<Point3Df> points3D1, points3D2;
for (auto &it : indices) {
points3D1.push_back(firstPoints3D[it]);
points3D2.push_back(secondPoints3D[it]);
}
// compute pose
Transform3Df tmpPose;
if (!find(points3D1, points3D2, tmpPose)) {
iterations--;
continue;
}
// transform first 3D points using the estimated pose
std::vector<Point3Df> firstPoints3DTrans;
m_transform3D->transform(firstPoints3D, tmpPose, firstPoints3DTrans);
// get inliers
std::vector<int> tmpInliers;
getInliers(firstPoints3DTrans, secondPoints3D, m_distanceError, tmpInliers);
if (tmpInliers.size() > bestInliers.size()) {
bestPose = tmpPose;
bestInliers.swap(tmpInliers);
}
// check confidence
if ((float)(bestInliers.size()) / firstPoints3D.size() > m_confidence)
break;
iterations--;
}
if (bestInliers.size() < m_NbInliersToValidPose) {
LOG_WARNING("Number of inliers points must be valid ( equal and > to {}): {} inliers for {} input points", m_NbInliersToValidPose, bestInliers.size(), firstPoints3D.size());
return FrameworkReturnCode::_ERROR_;
}
// find the best pose on all inliers
std::vector<Point3Df> points3D1, points3D2;
for (auto &it : bestInliers) {
points3D1.push_back(firstPoints3D[it]);
points3D2.push_back(secondPoints3D[it]);
}
// compute the best pose
if (!find(points3D1, points3D2, pose))
return FrameworkReturnCode::_ERROR_;
inliers.swap(bestInliers);
return FrameworkReturnCode::_SUCCESS;
}
FrameworkReturnCode SolAR3DTransformEstimationSACFrom3D3D::estimate(const SRef<Keyframe> firstKeyframe,
const SRef<Keyframe> secondKeyframe,
const std::vector<DescriptorMatch>& matches,
const std::vector<Point3Df>& firstPoints3D,
const std::vector<Point3Df>& secondPoints3D,
Transform3Df & pose,
std::vector<int>& inliers)
{
if ((firstPoints3D.size() != secondPoints3D.size()) || (matches.size() != firstPoints3D.size()) || (firstPoints3D.size() < 3))
return FrameworkReturnCode::_ERROR_;
// get poses
const Transform3Df &pose1 = firstKeyframe->getPose();
const Transform3Df &pose2 = secondKeyframe->getPose();
// get keypoints
std::vector<Point2Df> keypoints1, keypoints2;
for (const auto &it : matches) {
const Keypoint kp1 = firstKeyframe->getKeypoint(it.getIndexInDescriptorA());
const Keypoint kp2 = secondKeyframe->getKeypoint(it.getIndexInDescriptorB());
keypoints1.push_back(Point2Df(kp1.getX(), kp1.getY()));
keypoints2.push_back(Point2Df(kp2.getX(), kp2.getY()));
}
int iterations = m_iterationsCount;
std::vector<int> bestInliers;
Transform3Df bestPose;
while (iterations != 0) {
// get 3 random indices
std::vector<int> indices;
randomIndices(static_cast<int>(firstPoints3D.size()), 3, indices);
// get 3 correspondences
std::vector<Point3Df> points3D1, points3D2;
for (auto &it : indices) {
points3D1.push_back(firstPoints3D[it]);
points3D2.push_back(secondPoints3D[it]);
}
// compute pose
Transform3Df tmpPose;
if (!find(points3D1, points3D2, tmpPose)) {
iterations--;
continue;
}
// transform 3D points using the estimated pose
std::vector<Point3Df> firstPoints3DTrans, secondPoints3DTrans;
m_transform3D->transform(firstPoints3D, tmpPose, firstPoints3DTrans);
m_transform3D->transform(secondPoints3D, tmpPose.inverse(), secondPoints3DTrans);
// project the 3D tranformed points on the image
std::vector< Point2Df > firstProjected2DPts, secondProjected2DPts;
m_projector->project(firstPoints3DTrans, firstProjected2DPts, pose2);
m_projector->project(secondPoints3DTrans, secondProjected2DPts, pose1);
// get inliers
std::vector<int> tmpInliers;
getInliersByProject(firstProjected2DPts, keypoints2, secondProjected2DPts, keypoints1, m_reprojError, tmpInliers);
if (tmpInliers.size() > bestInliers.size()) {
bestPose = tmpPose;
bestInliers.swap(tmpInliers);
}
// check confidence
if ((float)(bestInliers.size()) / firstPoints3D.size() > m_confidence)
break;
iterations--;
}
if (bestInliers.size() < m_NbInliersToValidPose) {
LOG_WARNING("Number of inliers points must be valid ( equal and > to {}): {} inliers for {} input points", m_NbInliersToValidPose, bestInliers.size(), firstPoints3D.size());
return FrameworkReturnCode::_ERROR_;
}
// find the best pose on all inliers
std::vector<Point3Df> points3D1, points3D2;
for (auto &it : bestInliers) {
points3D1.push_back(firstPoints3D[it]);
points3D2.push_back(secondPoints3D[it]);
}
// compute the best pose
if (!find(points3D1, points3D2, pose))
return FrameworkReturnCode::_ERROR_;
inliers.swap(bestInliers);
return FrameworkReturnCode::_SUCCESS;
}
}
}
}
| 36.624561 | 254 | 0.704733 | [
"vector",
"transform",
"3d"
] |
3afaf9c36fc51a0d9787a60ce5af7bac4022dc01 | 2,897 | cpp | C++ | src/tasks.cpp | Algorithms-and-Data-Structures-2021/h00_cpp_basics-belyab | 92deb1b5ece0391335446637a677302356f90922 | [
"MIT"
] | null | null | null | src/tasks.cpp | Algorithms-and-Data-Structures-2021/h00_cpp_basics-belyab | 92deb1b5ece0391335446637a677302356f90922 | [
"MIT"
] | null | null | null | src/tasks.cpp | Algorithms-and-Data-Structures-2021/h00_cpp_basics-belyab | 92deb1b5ece0391335446637a677302356f90922 | [
"MIT"
] | null | null | null | #include <iostream> // cout
#include <algorithm> // copy, fill
#include "tasks.hpp"
// ИСПОЛЬЗОВАНИЕ ЛЮБЫХ ДРУГИХ БИБЛИОТЕК НЕ СОВЕТУЕТСЯ И МОЖЕТ ПОВЛИЯТЬ НА ВАШИ БАЛЛЫ
using std::cout;
using std::fill;
using std::copy;
// Задание 1
void swap_args(int *lhs, int *rhs) {
if(lhs && rhs){
int d = *lhs;
*lhs = *rhs;
*rhs = d;
}
}
// Задание 2
int **allocate_2d_array(int num_rows, int num_cols, int init_value) {
if(num_rows>0 && num_cols>0) {
int **array_2d = new int *[num_rows];
for (int row_index = 0; row_index < num_rows; row_index++) {
array_2d[row_index] = new int[num_cols];
}
for (int row_index = 0; row_index < num_rows; row_index++) {
for (int column_index = 0; column_index < num_cols; column_index++) {
array_2d[row_index][column_index]=init_value;
}
}
return array_2d;
}
return nullptr;
}
// Задание 3
bool copy_2d_array(int **arr_2d_source, int **arr_2d_target, int num_rows, int num_cols) {
if(arr_2d_source==0||arr_2d_target==0||num_cols<0||num_rows<0){
return false;
} else {
for (int i = 0; i < num_rows; i++) {
for (int j = 0; j < num_cols; j++) {
std::copy(arr_2d_target[i], arr_2d_target[i] + num_cols, arr_2d_source[i]);
}
}
return arr_2d_source;
}
}
// Задание 4
void reverse_1d_array(vector<int> &arr) {
for(int i = 0;i<arr.size()/2;i++){
int a = arr[i];
arr[i] = arr[arr.size()-i-1];
arr[arr.size()-i-1]=a;
}
}
// Задание 5
void reverse_1d_array(int *arr_begin, int *arr_end) {
if(arr_begin!= nullptr && arr_end!= nullptr){
int arrSize = arr_end-arr_begin+1;
for(int i =0;i<arrSize/2;i++){
int a = arr_begin[i];
arr_begin[i] = arr_begin[arrSize-i-1];
arr_begin[arrSize-i-1]=a;
}
}
}
// Задание 6
int *find_max_element(int *arr, int size) {
if (arr != nullptr && size >= 0) {
int *max = &arr[0];
for (int i = 1; i<size; i++) {
if (arr[i] > *max) {
max = &arr[i];
}
}
return max;
}
return nullptr;
}
// Задание 7
vector<int> find_odd_numbers(vector<int> &arr) {
vector<int> odd_numbers;
for(int element : arr){
if(abs(element) % 2 == 1){
odd_numbers.push_back(element);
}
}
if(!odd_numbers.empty()){
return odd_numbers;
}
return {};
}
// Задание 8
vector<int> find_common_elements(vector<int> &arr_a, vector<int> &arr_b) {
vector<int> common_elements;
for(int element1:arr_a){
for(int element2 : arr_b){
if(element1==element2){
common_elements.push_back(element1);
}
}
}
if(common_elements.size()>=0){
return common_elements;
}
return {};
}
| 23.362903 | 91 | 0.554712 | [
"vector"
] |
3afe6dad8ac3383f4202fe893a93c9d68feb9e11 | 10,580 | cpp | C++ | src/userdata.cpp | re3fork/librw-vita | 9f267c904d2ade5fd4703952b187241c0d7e997c | [
"MIT"
] | null | null | null | src/userdata.cpp | re3fork/librw-vita | 9f267c904d2ade5fd4703952b187241c0d7e997c | [
"MIT"
] | null | null | null | src/userdata.cpp | re3fork/librw-vita | 9f267c904d2ade5fd4703952b187241c0d7e997c | [
"MIT"
] | 1 | 2022-01-09T12:18:07.000Z | 2022-01-09T12:18:07.000Z | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include "rwbase.h"
#include "rwerror.h"
#include "rwplg.h"
#include "rwpipeline.h"
#include "rwobjects.h"
#include "rwengine.h"
#include "rwuserdata.h"
#include <vitaGL.h>
#define PLUGIN_ID ID_USERDATA
namespace rw {
UserDataGlobals userDataGlobals;
#define udMalloc(sz) rwMalloc(sz, MEMDUR_EVENT | ID_USERDATA)
void
UserDataArray::setString(int32 n, const char *s)
{
int32 len;
char **sp = &((char**)this->data)[n];
rwFree(*sp);
len = (int32)strlen(s)+1;
*sp = (char*)udMalloc(len);
if(*sp)
strncpy(*sp, s, len);
}
static void*
createUserData(void *object, int32 offset, int32)
{
UserDataExtension *ext = PLUGINOFFSET(UserDataExtension, object, offset);
ext->numArrays = 0;
ext->arrays = nil;
return object;
}
static void*
destroyUserData(void *object, int32 offset, int32)
{
int32 i, j;
char **strar;
UserDataArray *a;
UserDataExtension *ext = PLUGINOFFSET(UserDataExtension, object, offset);
a = ext->arrays;
for(i = 0; i < ext->numArrays; i++){
rwFree(a->name);
switch(a->datatype){
case USERDATASTRING:
strar = (char**)a->data;
for(j = 0; j < a->numElements; j++)
rwFree(strar[j]);
/* fallthrough */
case USERDATAINT:
case USERDATAFLOAT:
rwFree(a->data);
break;
}
a++;
}
rwFree(ext->arrays);
ext->numArrays = 0;
ext->arrays = nil;
return object;
}
static void*
copyUserData(void *dst, void *src, int32 offset, int32)
{
int32 i, j;
char **srcstrar, **dststrar;
UserDataArray *srca, *dsta;
UserDataExtension *srcext = PLUGINOFFSET(UserDataExtension, src, offset);
UserDataExtension *dstext = PLUGINOFFSET(UserDataExtension, dst, offset);
dstext->numArrays = srcext->numArrays;
dstext->arrays = (UserDataArray*)udMalloc(dstext->numArrays*sizeof(UserDataArray));
srca = srcext->arrays;
dsta = srcext->arrays;
for(i = 0; i < srcext->numArrays; i++){
int32 len = (int32)strlen(srca->name)+1;
dsta->name = (char*)udMalloc(len);
strncpy(dsta->name, srca->name, len);
dsta->datatype = srca->datatype;
dsta->numElements = srca->numElements;
switch(srca->datatype){
case USERDATAINT:
dsta->data = (int32*)udMalloc(sizeof(int32)*dsta->numElements);
memcpy_neon(dsta->data, srca->data, sizeof(int32)*dsta->numElements);
break;
case USERDATAFLOAT:
dsta->data = (float32*)udMalloc(sizeof(float32)*dsta->numElements);
memcpy_neon(dsta->data, srca->data, sizeof(float32)*dsta->numElements);
break;
case USERDATASTRING:
dststrar = (char**)udMalloc(sizeof(char*)*dsta->numElements);
dsta->data = dststrar;
srcstrar = (char**)srca->data;
for(j = 0; j < dsta->numElements; j++){
len = (int32)strlen(srcstrar[j])+1;
dststrar[j] = (char*)udMalloc(len);
strncpy(dststrar[j], srcstrar[j], len);
}
break;
}
srca++;
dsta++;
}
return dst;
}
static Stream*
readUserData(Stream *stream, int32, void *object, int32 offset, int32)
{
int32 i, j;
char **strar;
UserDataArray *a;
UserDataExtension *ext = PLUGINOFFSET(UserDataExtension, object, offset);
ext->numArrays = stream->readI32();
ext->arrays = (UserDataArray*)udMalloc(ext->numArrays*sizeof(UserDataArray));
a = ext->arrays;
for(i = 0; i < ext->numArrays; i++){
int32 len = stream->readI32();
a->name = (char*)udMalloc(len);
stream->read8(a->name, len);
a->datatype = stream->readU32();
a->numElements = stream->readI32();
switch(a->datatype){
case USERDATAINT:
a->data = (int32*)udMalloc(sizeof(int32)*a->numElements);
stream->read32(a->data, sizeof(int32)*a->numElements);
break;
case USERDATAFLOAT:
a->data = (float32*)udMalloc(sizeof(float32)*a->numElements);
stream->read32(a->data, sizeof(float32)*a->numElements);
break;
case USERDATASTRING:
strar = (char**)udMalloc(sizeof(char*)*a->numElements);
a->data = strar;
for(j = 0; j < a->numElements; j++){
len = stream->readI32();
strar[j] = (char*)udMalloc(len);
stream->read8(strar[j], len);
}
break;
}
a++;
}
return stream;
}
static Stream*
writeUserData(Stream *stream, int32, void *object, int32 offset, int32)
{
int32 len;
int32 i, j;
char **strar;
UserDataArray *a;
UserDataExtension *ext = PLUGINOFFSET(UserDataExtension, object, offset);
stream->writeI32(ext->numArrays);
a = ext->arrays;
for(i = 0; i < ext->numArrays; i++){
len = (int32)strlen(a->name)+1;
stream->writeI32(len);
stream->write8(a->name, len);
stream->writeU32(a->datatype);
stream->writeI32(a->numElements);
switch(a->datatype){
case USERDATAINT:
stream->write32(a->data, sizeof(int32)*a->numElements);
break;
case USERDATAFLOAT:
stream->write32(a->data, sizeof(float32)*a->numElements);
break;
case USERDATASTRING:
strar = (char**)a->data;
for(j = 0; j < a->numElements; j++){
len = (int32)strlen(strar[j])+1;
stream->writeI32(len);
stream->write8(strar[j], len);
}
break;
}
a++;
}
return stream;
}
static int32
getSizeUserData(void *object, int32 offset, int32)
{
int32 len;
int32 i, j;
char **strar;
int32 size;
UserDataArray *a;
UserDataExtension *ext = PLUGINOFFSET(UserDataExtension, object, offset);
if(ext->numArrays == 0)
return 0;
size = 4; // numArrays
a = ext->arrays;
for(i = 0; i < ext->numArrays; i++){
len = (int32)strlen(a->name)+1;
size += 4 + len + 4 + 4; // name len, name, type, numElements
switch(a->datatype){
case USERDATAINT:
size += sizeof(int32)*a->numElements;
break;
case USERDATAFLOAT:
size += sizeof(float32)*a->numElements;
break;
case USERDATASTRING:
strar = (char**)a->data;
for(j = 0; j < a->numElements; j++){
len = (int32)strlen(strar[j])+1;
size += 4 + len; // len and string
}
break;
}
a++;
}
return size;
}
int32
UserDataExtension::add(const char *name, int32 datatype, int32 numElements)
{
int32 i;
int32 len;
int32 typesz;
UserDataArray *a;
// try to find empty slot
for(i = 0; i < this->numArrays; i++)
if(this->arrays[i].datatype == USERDATANA)
goto alloc;
// have to realloc
a = (UserDataArray*)udMalloc((this->numArrays+1)*sizeof(UserDataArray));
if(a == nil)
return -1;
memcpy_neon(a, this->arrays, this->numArrays*sizeof(UserDataArray));
rwFree(this->arrays);
this->arrays = a;
i = this->numArrays++;
alloc:
a = &this->arrays[i];
len = (int32)strlen(name)+1;
a->name = (char*)udMalloc(len+1);
assert(a->name);
strncpy(a->name, name, len);
a->datatype = datatype;
a->numElements = numElements;
typesz = datatype == USERDATAINT ? sizeof(int32) :
datatype == USERDATAFLOAT ? sizeof(float32) :
datatype == USERDATASTRING ? sizeof(char*) : 0;
a->data = udMalloc(typesz*numElements);
assert(a->data);
memset(a->data, 0, typesz*numElements);
return i;
}
void
UserDataExtension::remove(int32 n)
{
int32 i;
UserDataArray *a = &this->arrays[n];
if(a->name){
rwFree(a->name);
a->name = nil;
}
if(a->datatype == USERDATASTRING)
for(i = 0; i < a->numElements; i++)
rwFree(((char**)a->data)[i]);
if(a->data){
rwFree(a->data);
a->data = nil;
}
a->datatype = USERDATANA;
a->numElements = 0;
}
int32
UserDataExtension::findIndex(const char *name) {
for(int32 i = 0; i < this->numArrays; i++)
if(strcmp(this->arrays[i].name, name) == 0)
return i;
return -1;
}
#define ACCESSOR(TYPE, NAME) \
int32 \
UserDataArray::NAME##Add(TYPE *t, const char *name, int32 datatype, int32 numElements) \
{ \
return PLUGINOFFSET(UserDataExtension, t, userDataGlobals.NAME##Offset)->add(name, datatype, numElements); \
} \
void \
UserDataArray::NAME##Remove(TYPE *t, int32 n) \
{ \
PLUGINOFFSET(UserDataExtension, t, userDataGlobals.NAME##Offset)->remove(n); \
} \
int32 \
UserDataArray::NAME##GetCount(TYPE *t) \
{ \
return PLUGINOFFSET(UserDataExtension, t, userDataGlobals.NAME##Offset)->getCount(); \
} \
UserDataArray* \
UserDataArray::NAME##Get(TYPE *t, int32 n) \
{ \
return PLUGINOFFSET(UserDataExtension, t, userDataGlobals.NAME##Offset)->get(n); \
} \
int32 \
UserDataArray::NAME##FindIndex(TYPE *t, const char *name) \
{ \
return PLUGINOFFSET(UserDataExtension, t, userDataGlobals.NAME##Offset)->findIndex(name); \
}
ACCESSOR(Geometry, geometry)
ACCESSOR(Frame, frame)
ACCESSOR(Camera, camera)
ACCESSOR(Light, light)
ACCESSOR(Material, material)
ACCESSOR(Texture, texture)
UserDataExtension *UserDataExtension::get(Geometry *geo) { return PLUGINOFFSET(UserDataExtension, geo, userDataGlobals.geometryOffset); }
UserDataExtension *UserDataExtension::get(Frame *frame) { return PLUGINOFFSET(UserDataExtension, frame, userDataGlobals.frameOffset); }
UserDataExtension *UserDataExtension::get(Camera *cam) { return PLUGINOFFSET(UserDataExtension, cam, userDataGlobals.cameraOffset); }
UserDataExtension *UserDataExtension::get(Light *light) { return PLUGINOFFSET(UserDataExtension, light, userDataGlobals.lightOffset); }
UserDataExtension *UserDataExtension::get(Material *mat) { return PLUGINOFFSET(UserDataExtension, mat, userDataGlobals.materialOffset); }
UserDataExtension *UserDataExtension::get(Texture *tex) { return PLUGINOFFSET(UserDataExtension, tex, userDataGlobals.textureOffset); }
void
registerUserDataPlugin(void)
{
// TODO: World Sector
userDataGlobals.geometryOffset = Geometry::registerPlugin(sizeof(UserDataExtension),
ID_USERDATA, createUserData, destroyUserData, copyUserData);
Geometry::registerPluginStream(ID_USERDATA, readUserData, writeUserData, getSizeUserData);
userDataGlobals.frameOffset = Frame::registerPlugin(sizeof(UserDataExtension),
ID_USERDATA, createUserData, destroyUserData, copyUserData);
Frame::registerPluginStream(ID_USERDATA, readUserData, writeUserData, getSizeUserData);
userDataGlobals.cameraOffset = Camera::registerPlugin(sizeof(UserDataExtension),
ID_USERDATA, createUserData, destroyUserData, copyUserData);
Camera::registerPluginStream(ID_USERDATA, readUserData, writeUserData, getSizeUserData);
userDataGlobals.lightOffset = Light::registerPlugin(sizeof(UserDataExtension),
ID_USERDATA, createUserData, destroyUserData, copyUserData);
Light::registerPluginStream(ID_USERDATA, readUserData, writeUserData, getSizeUserData);
userDataGlobals.materialOffset = Material::registerPlugin(sizeof(UserDataExtension),
ID_USERDATA, createUserData, destroyUserData, copyUserData);
Material::registerPluginStream(ID_USERDATA, readUserData, writeUserData, getSizeUserData);
userDataGlobals.textureOffset = Texture::registerPlugin(sizeof(UserDataExtension),
ID_USERDATA, createUserData, destroyUserData, copyUserData);
Texture::registerPluginStream(ID_USERDATA, readUserData, writeUserData, getSizeUserData);
}
}
| 28.828338 | 137 | 0.704537 | [
"geometry",
"object"
] |
d708930d52f3aa2d13c5411197b32870b9647f30 | 10,783 | cpp | C++ | tests/test-discovery.cpp | tklab-tud/umundo | 31da28e24c6c935370099745311dd78c80763bd8 | [
"BSD-3-Clause"
] | 44 | 2015-02-01T12:39:51.000Z | 2022-03-30T15:13:50.000Z | tests/test-discovery.cpp | tklab-tud/umundo | 31da28e24c6c935370099745311dd78c80763bd8 | [
"BSD-3-Clause"
] | 3 | 2015-01-13T12:47:21.000Z | 2017-06-24T04:13:46.000Z | tests/test-discovery.cpp | tklab-tud/umundo | 31da28e24c6c935370099745311dd78c80763bd8 | [
"BSD-3-Clause"
] | 19 | 2015-04-17T13:50:15.000Z | 2022-03-09T09:50:46.000Z | #define protected public
#define private public
#include "umundo.h"
#include "umundo/discovery/MDNSDiscovery.h"
#include "umundo/discovery/BroadcastDiscovery.h"
#include <iostream>
#include <stdio.h>
#include "umundo/connection/zeromq/ZeroMQNode.h"
#include "umundo/connection/zeromq/ZeroMQPublisher.h"
#include "umundo/connection/zeromq/ZeroMQSubscriber.h"
using namespace umundo;
static std::string hostId;
static Monitor monitor;
static RMutex mutex;
class EndPointResultSet : public ResultSet<ENDPOINT_RS_TYPE> {
public:
void added(ENDPOINT_RS_TYPE node) {
assert(_endPoints.find(node) == _endPoints.end());
_endPoints.insert(node);
}
void removed(ENDPOINT_RS_TYPE node) {
assert(_endPoints.find(node) != _endPoints.end());
_endPoints.erase(node);
}
void changed(ENDPOINT_RS_TYPE node, uint64_t what) {
assert(_endPoints.find(node) != _endPoints.end());
}
std::set<EndPoint> _endPoints;
};
class MDNSAdResultSet : public ResultSet<MDNSAdvertisement*> {
public:
void added(MDNSAdvertisement* node) {
assert(_endPoints.find(node) == _endPoints.end());
_endPoints.insert(node);
}
void removed(MDNSAdvertisement* node) {
assert(_endPoints.find(node) != _endPoints.end());
_endPoints.erase(node);
}
void changed(MDNSAdvertisement* node, uint64_t what) {
assert(_endPoints.find(node) != _endPoints.end());
}
std::set<MDNSAdvertisement*> _endPoints;
};
class DiscoveryObjectResultSet : public ResultSet<ENDPOINT_RS_TYPE> {
public:
DiscoveryObjectResultSet(const std::string& type) : _type(type) {
}
void added(ENDPOINT_RS_TYPE node) {
std::cout << "added '" << _type << "': " << node << std::endl;
}
void removed(ENDPOINT_RS_TYPE node) {
std::cout << "removed '" << _type << "': " << node << std::endl;
}
void changed(ENDPOINT_RS_TYPE node, uint64_t what) {
std::cout << "changed '" << _type << "': " << node << std::endl;
}
std::string _type;
};
bool testDiscoveryObject() {
// see https://developer.apple.com/library/mac/qa/qa1312/_index.html
std::list<Discovery> discoveries;
std::list<std::pair<std::string, DiscoveryConfigMDNS::Protocol> > services;
services.push_back(std::make_pair("afpovertcp", DiscoveryConfigMDNS::TCP));
services.push_back(std::make_pair("nfs", DiscoveryConfigMDNS::TCP));
services.push_back(std::make_pair("webdav", DiscoveryConfigMDNS::TCP));
services.push_back(std::make_pair("ftp", DiscoveryConfigMDNS::TCP));
services.push_back(std::make_pair("ssh", DiscoveryConfigMDNS::TCP));
services.push_back(std::make_pair("eppc", DiscoveryConfigMDNS::TCP));
services.push_back(std::make_pair("http", DiscoveryConfigMDNS::TCP));
services.push_back(std::make_pair("telnet", DiscoveryConfigMDNS::TCP));
services.push_back(std::make_pair("printer", DiscoveryConfigMDNS::TCP));
services.push_back(std::make_pair("ipp", DiscoveryConfigMDNS::TCP));
services.push_back(std::make_pair("pdl-datastream", DiscoveryConfigMDNS::TCP));
services.push_back(std::make_pair("riousbprint", DiscoveryConfigMDNS::TCP));
services.push_back(std::make_pair("daap", DiscoveryConfigMDNS::TCP));
services.push_back(std::make_pair("dpap", DiscoveryConfigMDNS::TCP));
services.push_back(std::make_pair("ichat", DiscoveryConfigMDNS::TCP));
services.push_back(std::make_pair("airport", DiscoveryConfigMDNS::TCP));
services.push_back(std::make_pair("xserveraid", DiscoveryConfigMDNS::TCP));
services.push_back(std::make_pair("distcc", DiscoveryConfigMDNS::TCP));
services.push_back(std::make_pair("apple-sasl", DiscoveryConfigMDNS::TCP));
services.push_back(std::make_pair("workstation", DiscoveryConfigMDNS::TCP));
services.push_back(std::make_pair("servermgr", DiscoveryConfigMDNS::TCP));
services.push_back(std::make_pair("raop", DiscoveryConfigMDNS::TCP));
for (std::list<std::pair<std::string, DiscoveryConfigMDNS::Protocol> >::iterator svcIter = services.begin();
svcIter != services.end();
svcIter++) {
DiscoveryConfigMDNS mdnsConfig;
mdnsConfig.setServiceType(svcIter->first);
mdnsConfig.setProtocol(svcIter->second);
Discovery mdnsDisc(&mdnsConfig);
DiscoveryObjectResultSet rs(svcIter->first);
mdnsDisc.browse(&rs);
discoveries.push_back(mdnsDisc);
}
tthread::this_thread::sleep_for(tthread::chrono::seconds(3));
for (std::list<Discovery>::iterator discIter = discoveries.begin();
discIter != discoveries.end();) {
discoveries.erase(discIter++);
}
return true;
}
bool testMulticastDNSDiscovery() {
SharedPtr<MDNSDiscoveryImpl> mdnsImpl = StaticPtrCast<MDNSDiscoveryImpl>(Factory::create("discovery.mdns.impl"));
std::string domain = "foo.local.";
std::string regType = "_umundo._tcp.";
MDNSAdResultSet* rs = new MDNSAdResultSet();
MDNSQuery query;
query.domain = domain;
query.regType = regType;
query.rs = rs;
mdnsImpl->browse(&query);
std::set<MDNSAdvertisement*> ads;
int retries;
int iterations = 3;
int nrAds = 4;
for (int i = 0; i < iterations; i++) {
for (int j = 0; j < nrAds; j++) {
MDNSAdvertisement* ad = new MDNSAdvertisement();
ad->name = toStr(j);
ad->regType = "_umundo._tcp.";
ad->domain = "foo.local.";
ad->port = i + 3000;
mdnsImpl->advertise(ad);
ads.insert(ad);
}
retries = 100;
while(rs->_endPoints.size() != nrAds) {
Thread::sleepMs(100);
if (retries-- == 0)
assert(false);
}
std::set<MDNSAdvertisement*>::iterator adIter = ads.begin();
while(adIter != ads.end()) {
mdnsImpl->unadvertise(*adIter);
delete *adIter;
adIter++;
}
retries = 50;
while(rs->_endPoints.size() != 0) {
Thread::sleepMs(100);
if (retries-- == 0)
assert(false);
}
ads.clear();
std::cout << std::endl << std::endl;
}
mdnsImpl->unbrowse(&query);
return true;
}
bool testEndpointDiscovery() {
DiscoveryConfigMDNS mdnsOuterOpts;
mdnsOuterOpts.setDomain("foo.local.");
Discovery discOuter(&mdnsOuterOpts);
EndPoint ep1("tcp://127.0.0.1:400");
discOuter.advertise(ep1);
int iterations = 4;
int nrEndPoints = 3;
for (int i = 0; i < iterations; ++i) {
EndPointResultSet eprs;
Discovery discInner(Discovery::MDNS);
discInner.browse(&eprs);
discOuter.browse(&eprs);
std::set<EndPoint> endPoints;
for (int j = 0; j < nrEndPoints; ++j) {
std::stringstream epAddress;
epAddress << "tcp://127.0.0.1:" << (i+j) % 4000 + 1000 ;
EndPoint ep(epAddress.str());
endPoints.insert(ep);
discInner.advertise(ep);
// discOuter.advertise(ep);
}
int retries = 50;
while(eprs._endPoints.size() != nrEndPoints + 1) {
Thread::sleepMs(100);
if (retries-- == 0)
assert(false);
}
std::set<EndPoint>::iterator epIter = endPoints.begin();
while(epIter != endPoints.end()) {
discInner.unadvertise(*epIter);
epIter++;
}
discOuter.unbrowse(&eprs);
endPoints.clear();
std::cout << std::endl << std::endl;
}
return true;
}
bool testNodeDiscovery() {
int retries;
int iterations = 10;
int nrNodes = 2;
std::vector<EndPoint> foundNodes;
for (int i = 0; i < iterations; ++i) {
Discovery disc(Discovery::MDNS);
// make sure there are no pending nodes
retries = 100;
foundNodes = disc.list();
while(foundNodes.size() != 0) {
Thread::sleepMs(100);
if (retries-- == 0)
assert(false);
foundNodes = disc.list();
}
assert(disc.list().size() == 0);
std::set<Node> nodes;
for (int j = 0; j < nrNodes; ++j) {
Node node;
disc.add(node);
nodes.insert(node);
}
retries = 100;
foundNodes = disc.list();
while(foundNodes.size() != nrNodes) {
Thread::sleepMs(100);
if (retries-- == 0)
assert(false);
foundNodes = disc.list();
}
assert(disc.list().size() == nrNodes);
std::map<std::string, NodeStub> peers;
std::set<Node>::iterator nodeIter1 = nodes.begin();
while(nodeIter1 != nodes.end()) {
peers = const_cast<Node&>(*nodeIter1).connectedTo();
std::set<Node>::iterator nodeIter2 = nodes.begin();
while(nodeIter2 != nodes.end()) {
// make sure everyone found exactly everyone else
if (nodeIter1->getUUID() != nodeIter2->getUUID()) {
retries = 200;
while(peers.find(nodeIter2->getUUID()) == peers.end()) {
Thread::sleepMs(100);
if (retries-- == 0)
assert(false);
peers = const_cast<Node&>(*nodeIter1).connectedTo();
}
}
nodeIter2++;
}
assert(peers.size() == nrNodes - 1);
nodeIter1++;
}
std::set<Node>::iterator nodeIter = nodes.begin();
while(nodeIter != nodes.end()) {
disc.remove(const_cast<Node&>(*nodeIter));
nodeIter++;
}
nodes.clear();
}
return true;
}
bool testPubSubConnections() {
// test node / publisher / subscriber churn
for (int i = 0; i < 10; i++) {
// Thread::sleepMs(2000);
Node node1;
Node node2;
node1.add(node2);
node2.add(node1);
Publisher pub("foo");
node1.addPublisher(pub);
for (int j = 0; j < 2; j++) {
Subscriber sub1("foo");
Subscriber sub2("foo");
Subscriber sub3("foo");
int subs = 0;
(void)subs;
subs = pub.waitForSubscribers(0);
assert(subs == 0);
Thread::sleepMs(300);
node2.addSubscriber(sub1);
std::cout << "Waiting for 1st subscriber" << std::endl;
subs = pub.waitForSubscribers(1);
assert(subs == 1);
node2.addSubscriber(sub2);
std::cout << "Waiting for 2nd subscriber" << std::endl;
subs = pub.waitForSubscribers(2);
assert(subs == 2);
node2.addSubscriber(sub3);
std::cout << "Waiting for 3rd subscriber" << std::endl;
subs = pub.waitForSubscribers(3);
assert(subs == 3);
node2.removeSubscriber(sub1);
Thread::sleepMs(300);
std::cout << "Removed 1st subscriber" << std::endl;
subs = pub.waitForSubscribers(0);
assert(subs == 2);
node2.removeSubscriber(sub2);
std::cout << "Removed 2nd subscriber" << std::endl;
Thread::sleepMs(300);
subs = pub.waitForSubscribers(0);
assert(subs == 1);
node2.removeSubscriber(sub3);
std::cout << "Removed 3rd subscriber" << std::endl;
Thread::sleepMs(300);
subs = pub.waitForSubscribers(0);
assert(subs == 0);
// node1.removePublisher(pub);
std::cout << "--- Successfully connected subscribers to publishers" << std::endl;
}
}
return true;
}
//bool testBroadCast() {
// Discovery disc(Discovery::BROADCAST);
// return true;
//}
//bool testExplicitAdressed() {
// Node n1("tcp://127.0.0.1:7700");
// return true;
//}
int main(int argc, char** argv, char** envp) {
setenv("UMUNDO_LOGLEVEL", "4", 1);
// if (!testBroadCast())
// return EXIT_FAILURE;
// if (!testExplicitAdressed())
// return EXIT_FAILURE;
// if (!testMulticastDNSDiscovery())
// return EXIT_FAILURE;
// if (!testEndpointDiscovery())
// return EXIT_FAILURE;
// if (!testDiscoveryObject())
// return EXIT_FAILURE;
// if (!testNodeDiscovery())
// return EXIT_FAILURE;
// if (!testPubSubConnections())
// return EXIT_FAILURE;
return EXIT_SUCCESS;
}
| 26.823383 | 114 | 0.676621 | [
"vector"
] |
d70d84d5a345d233739c9635f5f6f094bde23ac1 | 8,099 | cpp | C++ | src/topp/BaselineFilter.cpp | raghav17083/OpenMS | ddcdd3068a93a7c415675c39bac43d796a845f1d | [
"BSL-1.0",
"Apache-2.0",
"Zlib"
] | null | null | null | src/topp/BaselineFilter.cpp | raghav17083/OpenMS | ddcdd3068a93a7c415675c39bac43d796a845f1d | [
"BSL-1.0",
"Apache-2.0",
"Zlib"
] | null | null | null | src/topp/BaselineFilter.cpp | raghav17083/OpenMS | ddcdd3068a93a7c415675c39bac43d796a845f1d | [
"BSL-1.0",
"Apache-2.0",
"Zlib"
] | null | null | null | // --------------------------------------------------------------------------
// OpenMS -- Open-Source Mass Spectrometry
// --------------------------------------------------------------------------
// Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,
// ETH Zurich, and Freie Universitaet Berlin 2002-2017.
//
// This software is released under a three-clause BSD license:
// * 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 any author or any participating institution
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
// For a full list of authors, refer to the file AUTHORS.
// --------------------------------------------------------------------------
// 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 ANY OF THE AUTHORS OR THE CONTRIBUTING
// INSTITUTIONS 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.
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: $
// --------------------------------------------------------------------------
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/FORMAT/MzMLFile.h>
#include <OpenMS/FILTERING/BASELINE/MorphologicalFilter.h>
#include <OpenMS/FORMAT/PeakTypeEstimator.h>
#include <OpenMS/APPLICATIONS/TOPPBase.h>
using namespace OpenMS;
using namespace std;
//-------------------------------------------------------------
//Doxygen docu
//-------------------------------------------------------------
/**
@page TOPP_BaselineFilter BaselineFilter
@brief Executes the top-hat filter to remove the baseline of an MS experiment.
<CENTER>
<table>
<tr>
<td ALIGN = "center" BGCOLOR="#EBEBEB"> pot. predecessor tools </td>
<td VALIGN="middle" ROWSPAN=2> \f$ \longrightarrow \f$ BaselineFilter \f$ \longrightarrow \f$</td>
<td ALIGN = "center" BGCOLOR="#EBEBEB"> pot. successor tools </td>
</tr>
<tr>
<td VALIGN="middle" ALIGN = "center" ROWSPAN=1> @ref TOPP_NoiseFilterSGolay, @n @ref TOPP_NoiseFilterGaussian </td>
<td VALIGN="middle" ALIGN = "center" ROWSPAN=1> @ref TOPP_PeakPickerWavelet, @n @ref TOPP_PeakPickerHiRes @n (or ID engines on MS/MS data) </td>
</tr>
</table>
</CENTER>
This nonlinear filter, known as the top-hat operator in morphological
mathematics (see Soille, ''Morphological Image Analysis''), is independent
of the underlying baseline shape. It is able to detect an over brightness
even if the environment is not uniform. The principle is based on the
subtraction of a signal from its opening (erosion followed by a dilation).
The size the structuring element (here a flat line) being conditioned by the
width of the lineament (in our case the maximum width of a mass
spectrometric peak) to be detected.
@note The top-hat filter works only on roughly uniform data!
To generate equally-spaced data you can use the @ref TOPP_Resampler.
@note The length (given in Thomson) of the structuring element should be wider than the
maximum peak width in the raw data.
<B>The command line parameters of this tool are:</B>
@verbinclude TOPP_BaselineFilter.cli
<B>INI file documentation of this tool:</B>
@htmlinclude TOPP_BaselineFilter.html
*/
// We do not want this class to show up in the docu:
/// @cond TOPPCLASSES
class TOPPBaselineFilter :
public TOPPBase
{
public:
TOPPBaselineFilter() :
TOPPBase("BaselineFilter", "Removes the baseline from profile spectra using a top-hat filter.")
{
}
protected:
void registerOptionsAndFlags_() override
{
registerInputFile_("in", "<file>", "", "input raw data file ");
setValidFormats_("in", ListUtils::create<String>("mzML"));
registerOutputFile_("out", "<file>", "", "output raw data file ");
setValidFormats_("out", ListUtils::create<String>("mzML"));
registerDoubleOption_("struc_elem_length", "<size>", 3, "Length of the structuring element (should be wider than maximal peak width - see documentation).", false);
registerStringOption_("struc_elem_unit", "<unit>", "Thomson", "Unit of 'struc_elem_length' parameter.", false);
setValidStrings_("struc_elem_unit", ListUtils::create<String>("Thomson,DataPoints"));
registerStringOption_("method", "<string>", "tophat", "The name of the morphological filter to be applied. If you are unsure, use the default.", false);
setValidStrings_("method", ListUtils::create<String>("identity,erosion,dilation,opening,closing,gradient,tophat,bothat,erosion_simple,dilation_simple"));
}
ExitCodes main_(int, const char **) override
{
//-------------------------------------------------------------
// parameter handling
//-------------------------------------------------------------
String in = getStringOption_("in");
String out = getStringOption_("out");
//-------------------------------------------------------------
// loading input
//-------------------------------------------------------------
MzMLFile mz_data_file;
PeakMap ms_exp;
mz_data_file.setLogType(log_type_);
mz_data_file.load(in, ms_exp);
if (ms_exp.empty())
{
LOG_WARN << "The given file does not contain any conventional peak data, but might"
" contain chromatograms. This tool currently cannot handle them, sorry.";
return INCOMPATIBLE_INPUT_DATA;
}
// check for peak type (raw data required)
if (PeakTypeEstimator().estimateType(ms_exp[0].begin(), ms_exp[0].end()) == SpectrumSettings::CENTROID)
{
writeLog_("Warning: OpenMS peak type estimation indicates that this is not raw data!");
}
//check if spectra are sorted
for (Size i = 0; i < ms_exp.size(); ++i)
{
if (!ms_exp[i].isSorted())
{
writeLog_("Error: Not all spectra are sorted according to peak m/z positions. Use FileFilter to sort the input!");
return INCOMPATIBLE_INPUT_DATA;
}
}
//-------------------------------------------------------------
// calculations
//-------------------------------------------------------------
MorphologicalFilter morph_filter;
morph_filter.setLogType(log_type_);
Param parameters;
parameters.setValue("struc_elem_length", getDoubleOption_("struc_elem_length"));
parameters.setValue("struc_elem_unit", getStringOption_("struc_elem_unit"));
parameters.setValue("method", getStringOption_("method"));
morph_filter.setParameters(parameters);
morph_filter.filterExperiment(ms_exp);
//-------------------------------------------------------------
// writing output
//-------------------------------------------------------------
//annotate output with data processing info
addDataProcessing_(ms_exp, getProcessingInfo_(DataProcessing::BASELINE_REDUCTION));
mz_data_file.store(out, ms_exp);
return EXECUTION_OK;
}
};
int main(int argc, const char ** argv)
{
TOPPBaselineFilter tool;
return tool.main(argc, argv);
}
/// @endcond
| 42.403141 | 167 | 0.620447 | [
"shape"
] |
d70f4f8c9bd0937c68c45d9d351392181f0fca8a | 958 | cpp | C++ | locomotion_framework/controllers/hierarchical_control/src/actions/angles_merge.cpp | ADVRHumanoids/DrivingFramework | 34715c37bfe3c1f2bd92aeacecc12704a1a7820e | [
"Zlib"
] | 1 | 2019-12-02T07:10:42.000Z | 2019-12-02T07:10:42.000Z | locomotion_framework/controllers/hierarchical_control/src/actions/angles_merge.cpp | ADVRHumanoids/DrivingFramework | 34715c37bfe3c1f2bd92aeacecc12704a1a7820e | [
"Zlib"
] | null | null | null | locomotion_framework/controllers/hierarchical_control/src/actions/angles_merge.cpp | ADVRHumanoids/DrivingFramework | 34715c37bfe3c1f2bd92aeacecc12704a1a7820e | [
"Zlib"
] | 2 | 2020-10-22T19:06:44.000Z | 2021-06-07T03:32:52.000Z | #include "mwoibn/hierarchical_control/actions/angles_merge.h"
mwoibn::hierarchical_control::actions::AnglesMerge::AnglesMerge(actions::Compute& main_task, actions::Compute& secondary_task, hierarchical_control::State& state, mwoibn::Scalar eps, mwoibn::Scalar p, std::vector<mwoibn::hierarchical_control::tasks::Angle>& caster_tasks, mwoibn::hierarchical_control::tasks::Constraints& constraints, mwoibn::robot_class::Robot& robot) : Merge( main_task, secondary_task, state, eps, p, constraints, robot), _caster_tasks(caster_tasks){
}
void mwoibn::hierarchical_control::actions::AnglesMerge::_check(){
for(int i = 0; i < _task.getTaskSize(); i++) {
_current_id[i] = _primary.getJacobian().row(i).cwiseAbs().maxCoeff() > _eps;
//std::cout << "sing\t" << _primary.getJacobian().row(i).cwiseAbs().maxCoeff() << "\t";
}
// std::cout << _primary.getJacobian().row(0).cwiseAbs().maxCoeff() << "\t";
}
| 53.222222 | 474 | 0.695198 | [
"vector"
] |
d7108402ecdf56a485f1d0d8de3dfb99971cbcc3 | 13,915 | cpp | C++ | src/libzerocoin/Bulletproofs.cpp | PeterL73/veil | 2825d735275cd592b1fd5207b0dfdca2d4e3e78c | [
"MIT"
] | 1 | 2019-05-07T23:43:56.000Z | 2019-05-07T23:43:56.000Z | src/libzerocoin/Bulletproofs.cpp | PeterL73/veil | 2825d735275cd592b1fd5207b0dfdca2d4e3e78c | [
"MIT"
] | 1 | 2019-09-25T12:58:45.000Z | 2019-09-25T12:58:45.000Z | src/libzerocoin/Bulletproofs.cpp | PeterL73/veil | 2825d735275cd592b1fd5207b0dfdca2d4e3e78c | [
"MIT"
] | null | null | null | /**
* @file Bulletproofs.cpp
*
* @brief InnerProductArgument class for the Zerocoin library.
*
* @author Mary Maller, Jonathan Bootle and Gian Piero Dionisio
* @date May 2018
*
* @copyright Copyright 2018 The PIVX Developers
* @license This project is released under the MIT license.
**/
#include "hash.h"
#include "Bulletproofs.h"
#include <algorithm>
using namespace libzerocoin;
void Bulletproofs::Prove(const CBN_matrix ck_inner_g,
const CBigNum P_inner_prod, const CBigNum z,
const CBN_matrix a_sets, const CBN_matrix b_sets, const CBigNum y)
{
// ----------------------------- **** INNER-PRODUCT PROVE **** ------------------------------
// ------------------------------------------------------------------------------------------
// Algorithm used by the signer to prove the inner product argument for two vector polynomials
// @param P_inner_prod, z
// @param y : value used to create commitment keys ck_inner_{g,h}
// @param a_sets, b_sets : The two length 1x(N+PADS) matrices that are committed to
// @init final_a, final_b : final witness
// @init pi : final shifted commitments
const CBigNum q = params->serialNumberSoKCommitmentGroup.groupOrder;
const CBigNum p = params->serialNumberSoKCommitmentGroup.modulus;
const CBigNum u_inner_prod = params->serialNumberSoKCommitmentGroup.u_inner_prod;
int s = 2;
// Inserting the z into u
CHashWriter1024 hasher(0,0);
hasher << u_inner_prod.ToString() << P_inner_prod.ToString() << z.ToString();
CBigNum pre = CBigNum(hasher.GetHash()) % q;
CBigNum u_inner = u_inner_prod.pow_mod(pre,p);
// Starting the actual protocol
CBN_matrix a_sets2 = splitIntoSets(a_sets, s);
CBN_matrix b_sets2 = splitIntoSets(b_sets, s);
CBN_matrix g_sets = splitIntoSets(ck_inner_g, s);
CBN_matrix h_sets;
CBigNum Ak, Bk;
bool first = true;
int N1 = a_sets[0].size();
CBigNum x;
while (N1 > 1) {
hasher = CHashWriter1024(0,0);
pair<CBigNum, CBigNum> cLcR = findcLcR(a_sets2, b_sets2);
CBigNum cL = cLcR.first;
CBigNum cR = cLcR.second;
if (first) {
CBigNum ny = y.pow_mod(-ZKP_M, q);
CBN_vector ymPowers(1, CBigNum(1));
CBigNum temp = CBigNum(1);
for(unsigned int i=0; i<2*g_sets[0].size(); i++) {
temp = temp.mul_mod(ny, q);
ymPowers.push_back(temp);
}
pair<CBigNum, CBigNum> AkBk = firstPreChallengeShifts(
g_sets, u_inner, a_sets2, b_sets2, cL, cR, ymPowers);
Ak = AkBk.first;
Bk = AkBk.second;
hasher << Ak.ToString() << Bk.ToString();
x = CBigNum(hasher.GetHash()) % q;
// DEFINE h_sets first here
h_sets = first_get_new_hs(g_sets, x, s, ymPowers);
g_sets = get_new_gs_hs(g_sets, -1, x, s);
} else {
pair<CBigNum, CBigNum> AkBk = preChallengeShifts(
g_sets, h_sets, u_inner, a_sets2, b_sets2, cL, cR);
Ak = AkBk.first;
Bk = AkBk.second;
hasher << Ak.ToString() << Bk.ToString();
x = CBigNum(hasher.GetHash()) % q;
if (N1 == 2) s = 1;
g_sets = get_new_gs_hs(g_sets, -1, x, s);
h_sets = get_new_gs_hs(h_sets, 1, x, s);
}
a_sets2 = get_new_as_bs(a_sets2, 1, x, s);
b_sets2 = get_new_as_bs(b_sets2, -1, x, s);
first = false;
pi[0].push_back(Ak);
pi[1].push_back(Bk);
N1 = N1 / 2;
}
final_a = a_sets2;
final_b = b_sets2;
}
bool Bulletproofs::Verify(const ZerocoinParams* ZCp,
const CBN_matrix ck_inner_g, const CBN_matrix ck_inner_h,
CBigNum A, CBigNum B, CBigNum z)
{
// ---------------------------- **** INNER-PRODUCT VERIFY **** ------------------------------
// ------------------------------------------------------------------------------------------
// Algorithm used to verify the inner product proof
// @param ck_inner_g, ck_inner_h, u_inner_prod ?
// @param A, B : commitments (to a_sets and b_sets)
// @param z : target value
// @return bool : result of the verification
const CBigNum q = params->serialNumberSoKCommitmentGroup.groupOrder;
const CBigNum p = params->serialNumberSoKCommitmentGroup.modulus;
const CBigNum u_inner_prod = params->serialNumberSoKCommitmentGroup.u_inner_prod;
CBigNum P_inner_prod = A.mul_mod(B, p);
// Inserting the z into u
CHashWriter1024 hasher(0,0);
hasher << u_inner_prod.ToString() << P_inner_prod.ToString() << z.ToString();
CBigNum x1 = CBigNum(hasher.GetHash()) % q;
CBigNum u_inner = u_inner_prod.pow_mod(x1,p);
CBigNum P_inner = P_inner_prod.mul_mod(u_inner.pow_mod(z,p),p);
// Starting the actual protocol
int N1 = pi[0].size();
CBigNum x, Ak, Bk;
CBN_vector xlist;
for(int i=0; i<N1; i++) {
Ak = pi[0][i];
Bk = pi[1][i];
hasher << Ak.ToString() << Bk.ToString();
x = CBigNum(hasher.GetHash()) % q;
xlist.push_back(x);
P_inner = P_inner.mul_mod(
(Ak.pow_mod(x.pow_mod(2,q),p)).mul_mod(Bk.pow_mod(x.pow_mod(-2,q),p),p),p);
}
CBigNum z2 = final_a[0][0].mul_mod(final_b[0][0],q);
CBN_vector gh_final = getFinal_gh(ck_inner_g[0], ck_inner_h[0], xlist);
return testComsCorrect(gh_final, u_inner, P_inner, final_a, final_b, z2);
}
// Split set of 1 set (ck_inner_g) into set of many sets (g_sets)
CBN_matrix Bulletproofs::splitIntoSets(const CBN_matrix ck_inner_g, const int s)
{
const int N1 = ck_inner_g[0].size() / 2;
if (s==1) {
// allocate g_sets
CBN_matrix g_sets(ck_inner_g);
return g_sets;
}
else if (s==2) {
// allocate g_sets
CBN_matrix g_sets(2, CBN_vector());
for(int i=0; i<N1; i++) {
g_sets[0].push_back(ck_inner_g[0][i]);
g_sets[1].push_back(ck_inner_g[0][N1+i]);
}
return g_sets;
}
else throw std::runtime_error("wrong s inside splitIntoSets: " + s);
}
// Function for reduction when mu > 1
pair<CBigNum, CBigNum> Bulletproofs::findcLcR(const CBN_matrix a_sets, const CBN_matrix b_sets)
{
const CBigNum q = params->serialNumberSoKCommitmentGroup.groupOrder;
CBigNum cL = dotProduct(a_sets[0], b_sets[1], q);
CBigNum cR = dotProduct(a_sets[1], b_sets[0], q);
return make_pair(cL, cR);
}
// reduction used in innerProductProve when mu > 1
pair<CBigNum, CBigNum> Bulletproofs::firstPreChallengeShifts(
const CBN_matrix g_sets, const CBigNum u_inner,
const CBN_matrix a_sets, const CBN_matrix b_sets, CBigNum cL, CBigNum cR,
const CBN_vector ymPowers)
{
const CBigNum p = params->serialNumberSoKCommitmentGroup.modulus;
const CBigNum q = params->serialNumberSoKCommitmentGroup.groupOrder;
CBigNum Ak = u_inner.pow_mod(cL, p);
const int n1 = g_sets[0].size();
for(int i=0; i<n1; i++) {
Ak = Ak.mul_mod(g_sets[1][i].pow_mod(a_sets[0][i],p),p);
Ak = Ak.mul_mod(g_sets[0][i].pow_mod(b_sets[1][i].mul_mod(ymPowers[i+1],q),p),p);
}
CBigNum Bk = u_inner.pow_mod(cR, p);
for(int i=0; i<n1; i++) {
Bk = Bk.mul_mod(g_sets[0][i].pow_mod(a_sets[1][i],p),p);
Bk = Bk.mul_mod(g_sets[1][i].pow_mod(b_sets[0][i].mul_mod(ymPowers[n1+i+1],q),p),p);
}
return make_pair(Ak, Bk);
}
pair<CBigNum, CBigNum> Bulletproofs::preChallengeShifts(
const CBN_matrix g_sets, const CBN_matrix h_sets, const CBigNum u_inner,
const CBN_matrix a_sets, const CBN_matrix b_sets, CBigNum cL, CBigNum cR)
{
const CBigNum p = params->serialNumberSoKCommitmentGroup.modulus;
const CBigNum q = params->serialNumberSoKCommitmentGroup.groupOrder;
CBigNum Ak = u_inner.pow_mod(cL, p);
const int n1 = g_sets[0].size();
for(int i=0; i<n1; i++) {
Ak = Ak.mul_mod(g_sets[1][i].pow_mod(a_sets[0][i],p),p);
Ak = Ak.mul_mod(h_sets[0][i].pow_mod(b_sets[1][i],p),p);
}
CBigNum Bk = u_inner.pow_mod(cR, p);
for(int i=0; i<n1; i++) {
Bk = Bk.mul_mod(g_sets[0][i].pow_mod(a_sets[1][i],p),p);
Bk = Bk.mul_mod(h_sets[1][i].pow_mod(b_sets[0][i],p),p);
}
return make_pair(Ak, Bk);
}
// Find the new gs and hs in the inner product reduction
CBN_matrix Bulletproofs::first_get_new_hs(const CBN_matrix g_sets,
const CBigNum x, const int m2, const CBN_vector ymPowers)
{
const CBigNum q = params->serialNumberSoKCommitmentGroup.groupOrder;
const CBigNum p = params->serialNumberSoKCommitmentGroup.modulus;
const int N1 = g_sets[0].size();
CBN_matrix new_gs(1, CBN_vector());
CBigNum new_g, x1, x2; // temp
const CBigNum xn = x.pow_mod(-1,q);
for(int j=0; j<N1; j++) {
x1 = ymPowers[j+1].mul_mod(x,q);
x2 = ymPowers[N1+j+1].mul_mod(xn, q);
new_g = (g_sets[0][j].pow_mod(x1,p)).mul_mod(g_sets[1][j].pow_mod(x2,p),p);
new_gs[0].push_back(new_g);
}
return splitIntoSets(new_gs, m2);
}
CBN_matrix Bulletproofs::get_new_gs_hs(const CBN_matrix g_sets, const int sign,
const CBigNum x, const int m2)
{
const CBigNum q = params->serialNumberSoKCommitmentGroup.groupOrder;
const CBigNum p = params->serialNumberSoKCommitmentGroup.modulus;
const int N1 = g_sets[0].size();
CBN_matrix new_gs(1, CBN_vector());
CBigNum new_g;
const CBigNum xn = x.pow_mod(-1,q);
for(int j=0; j<N1; j++) {
if (sign > 0)
new_g = (g_sets[0][j].pow_mod(x,p)).mul_mod(
g_sets[1][j].pow_mod(xn,p),p);
else if (sign < 0)
new_g = (g_sets[0][j].pow_mod(xn,p)).mul_mod(
g_sets[1][j].pow_mod(x,p),p);
else
throw std::runtime_error("wrong sign inside get_new_gs_hs: " + sign);
new_gs[0].push_back(new_g);
}
return splitIntoSets(new_gs, m2);
}
// Get new as and bs in inner product reduction
CBN_matrix Bulletproofs::get_new_as_bs(const CBN_matrix a_sets, const int sign,
const CBigNum x, const int m2)
{
const CBigNum q = params->serialNumberSoKCommitmentGroup.groupOrder;
const int N1 = a_sets[0].size();
CBN_matrix a2(1, CBN_vector(N1));
CBigNum aj;
const CBigNum xn = x.pow_mod(-1,q);
for(int j=0; j<N1; j++) {
if (sign > 0)
aj = (a_sets[0][j].mul_mod(x,q) + a_sets[1][j].mul_mod(xn, q)) % q;
else if (sign < 0)
aj = (a_sets[0][j].mul_mod(xn,q) + a_sets[1][j].mul_mod(x, q)) % q;
else
throw std::runtime_error("wrong sign inside get_new_as_bs: " + sign);
a2[0][j] = aj;
}
return splitIntoSets(a2, m2);
}
// Verify Commitments
bool Bulletproofs::testComsCorrect(const CBN_vector gh_sets,
const CBigNum u_inner, const CBigNum P_inner,
const CBN_matrix final_a, const CBN_matrix final_b, const CBigNum z)
{
const CBigNum p = params->serialNumberSoKCommitmentGroup.modulus;
CBigNum Ptest = gh_sets[0].pow_mod(final_a[0][0],p);
Ptest = Ptest.mul_mod(gh_sets[1].pow_mod(final_b[0][0],p),p);
Ptest = Ptest.mul_mod(u_inner.pow_mod(z,p),p);
return (Ptest == P_inner);
}
// Optimizations
CBN_vector Bulletproofs::getFinal_gh(const CBN_vector gs, const CBN_vector hs, CBN_vector xlist)
{
const CBigNum q = params->serialNumberSoKCommitmentGroup.groupOrder;
const CBigNum p = params->serialNumberSoKCommitmentGroup.modulus;
const int logn = xlist.size();
const int n = gs.size();
CBN_vector xnlist;
CBigNum sg_i, sh_i, xg, xh;
CBN_vector sg_expo, sh_expo;
std::vector<int> bi;
std::reverse(xlist.begin(), xlist.end());
for(int i=0; i<logn; i++)
xnlist.push_back(xlist[i].pow_mod(-1,q));
std::vector< std::vector<int>> binary_lookup = findBinaryLookup(logn);
for(int i=0; i<n; i++) {
sg_i = CBigNum(1);
sh_i = CBigNum(1);
bi = binary_lookup[i];
for(int j=0; j<logn; j++) {
if (bi[j] == 1) {
xg = xlist[j];
xh = xnlist[j];
} else {
xg = xnlist[j];
xh = xlist[j];
}
sg_i = sg_i.mul_mod(xg,q);
sh_i = sh_i.mul_mod(xh,q);
}
sg_expo.push_back(sg_i);
sh_expo.push_back(sh_i);
}
CBN_vector ghfinal(2, CBigNum(1));
for(int i=0; i<n; i++) {
ghfinal[0] = ghfinal[0].mul_mod(gs[i].pow_mod(sg_expo[i],p),p);
ghfinal[1] = ghfinal[1].mul_mod(hs[i].pow_mod(sh_expo[i],p),p);
}
return ghfinal;
}
std::vector< std::vector<int>> Bulletproofs::findBinaryLookup(const int range)
{
std::vector< std::vector<int>> binary_lookup(2);
binary_lookup[0] = {0};
binary_lookup[1] = {1};
for(int i=0; i<range; i++)
binary_lookup = binaryBigger(binary_lookup);
return binary_lookup;
}
std::vector< std::vector<int>> Bulletproofs::binaryBigger(const std::vector< std::vector<int>> bin_lookup)
{
std::vector< std::vector<int>> bigger;
std::vector<int> lookup;
for(int i=0; i<2; i++)
for(int j=0; j<(int)bin_lookup.size(); j++) {
lookup = bin_lookup[j];
lookup.push_back(i);
bigger.push_back(lookup);
}
return bigger;
}
| 32.360465 | 107 | 0.578512 | [
"vector"
] |
d710b0095f52adefe277f97448f6d17864956097 | 5,334 | cpp | C++ | test/lights_test.cpp | lij0511/pandora | 5988618f29d2f1ba418ef54a02e227903c1e7108 | [
"Apache-2.0"
] | null | null | null | test/lights_test.cpp | lij0511/pandora | 5988618f29d2f1ba418ef54a02e227903c1e7108 | [
"Apache-2.0"
] | null | null | null | test/lights_test.cpp | lij0511/pandora | 5988618f29d2f1ba418ef54a02e227903c1e7108 | [
"Apache-2.0"
] | null | null | null | /*
* gltest1.cpp
*
* Created on: 2015年12月10日
* Author: lijing
*/
#include "pola/scene/camera/PerspectiveCamera.h"
#include "pola/scene/camera/DefaultCameraController.h"
#include "pola/Device.h"
#include "pola/io/FileInputStream.h"
#include "pola/scene/mesh/MeshLoader.h"
#include "pola/scene/mesh/MD2AnimatedMesh.h"
#include "pola/scene/node/SceneNode.h"
#include "pola/scene/mesh/BasicMesh.h"
#include "pola/scene/mesh/SkinnedMesh.h"
#include "pola/graphic/material/LambertMaterial.h"
#include "pola/graphic/material/PhongMaterial.h"
#include "pola/graphic/geometries/SphereGeometry.h"
#include "pola/graphic/geometries/CubeGeometry.h"
#include "pola/utils/Math.h"
using namespace pola;
using namespace pola::utils;
using namespace pola::scene;
using namespace pola::graphic;
int main(int argc, char *argv[]) {
DeviceParam param = {500, 500, false, 16};
Device* device = createDevice(param);
Scene* scene = device->getSceneManager()->getActiveScene();
scene->setClearColor({0.4f, 0.4f, 0.6f, 1.f});
Texture* texture = scene->graphic()->loadTexture("./res/ctf_r.png");
DirectionalLight* light = new DirectionalLight({1.f, 0.f, 0.f}, {1.f, 1.f, 1.f});
light->castShadow = true;
LightNode* lightNode = new LightNode(light);
lightNode->setPosition({-150.f, 0.f, 0.f});
scene->addChild(lightNode);
// scene->addChild(new LightNode(new DirectionalLight({1.f, 0.f, 0.f}, {1.f, 1.f, 1.f})));
scene->environment()->setAmbientLight({0.5f, 0.5f, 0.5f});
// scene->environment()->addLight(new DirectionalLight({1.f, 0.f, 0.f}, {1.f, 1.f, 1.f}));
// scene->addChild(new LightNode(new PointLight(graphic::vec3(200, 0, 0), 500, {0.f, 1.f, 0.f})));
Material* tm1 = new LambertMaterial({1.0f, 1.0f, 1.0f}, texture);
pola::utils::sp<MeshLoader::MeshInfo> result;
if ((result = MeshLoader::loadMesh("./res/ratamahatta.md2")) != nullptr) {
SceneNode* n = scene->addMesh(result->mesh.get(), scene);
SceneNode* node = scene->addMesh(result->mesh.get(), scene);
node->setPosition(graphic::vec3(0, 0, 20));
node->setMaterial(0, tm1);
n->setPosition(graphic::vec3(-100, 0, 0));
n->setMaterial(0, tm1);
if ((result = MeshLoader::loadMesh("./res/weapon.md2")) != nullptr) {
SceneNode* weaponNode = scene->addMesh(result->mesh.get(), n);
weaponNode->setMaterial(0, new LambertMaterial({1.0f, 1.0f, 1.0f}, scene->graphic()->loadTexture("./res/weapon.png")));
n->addChild(weaponNode);
}
}
if ((result = MeshLoader::loadMesh("./res/monster.ms3d")) != nullptr) {
SceneNode* n = scene->addMesh(result->mesh.get(), scene);
for (unsigned i = 0; i < result->materials.size(); i ++) {
const MaterialDescription& mate = result->materials[i];
std::string texName = "./res/";
texName += mate.texture;
n->setMaterial(i, new LambertMaterial({1.0f, 1.0f, 1.0f}, scene->graphic()->loadTexture(texName.c_str())));
}
}
if ((result = MeshLoader::loadMesh("./res/fbx/nvhai.FBX")) != nullptr) {
SceneNode* n = scene->addMesh(result->mesh.get(), scene);
// n->setScale({0.1f, 0.1f, 0.1f});
n->setPosition(graphic::vec3(- 50, 0, 0));
for (unsigned i = 0; i < result->materials.size(); i ++) {
const MaterialDescription& mate = result->materials[i];
std::string texName = "./res/";
texName += mate.texture;
n->setMaterial(i, new LambertMaterial({1.0f, 1.0f, 1.0f}, scene->graphic()->loadTexture(texName.c_str())));
}
for (unsigned i = 0; i < result->children.size(); i ++) {
SceneNode* node = scene->addMesh(result->children[i]->mesh.get(), n);
for (unsigned j = 0; i < result->children[i]->materials.size(); j ++) {
const MaterialDescription& mate = result->children[i]->materials[j];
std::string texName = "./res/";
texName += mate.texture;
n->setMaterial(j, new LambertMaterial({1.0f, 1.0f, 1.0f}, scene->graphic()->loadTexture(texName.c_str())));
}
}
}
BasicMesh* m = new BasicMesh(new SphereGeometry(30.f, 20, 20));
// BasicMesh* m = new BasicMesh(new CubeGeometry(30.f, 30.f, 30.f));
SceneNode* node = scene->addMesh(m, scene);
node->setMaterial(0, new LambertMaterial({1.0f, 1.0f, 1.0f}));
node->setPosition(graphic::vec3(50, 0, 0));
m = new BasicMesh(new CubeGeometry(60.f, 60.f, 60.f));
node = scene->addMesh(m, scene);
node->setMaterial(0, new LambertMaterial({1.0f, 1.0f, 1.0f}));
node->setPosition(graphic::vec3(100, 0, 0));
/*yunos::graphics::VPath path;
path.moveTo(0, 0);
path.quadTo(300, 0, 0, 300);
// path.lineTo(100, 0);
// path.lineTo(100, 200);
// path.lineTo(0, 200);
path.close();
Geometry2D* g = new Geometry2D();
yunos::graphics::VVertexBuffer vb;
yunos::graphics::VPathTessellator::tessellatePath(path, yunos::graphics::VPathTessellator::PaintInfo(), vb);
for (unsigned i = 0; i < vb.vertices.size(); i ++) {
g->addPosition(vec2(vb.vertices[i].x, vb.vertices[i].y));
printf("%f %f\n", vb.vertices[i].x, vb.vertices[i].y);
}
m = new BasicMesh(g);
node = scene->addMesh(m, scene);
node->setMaterial(0, new Material());
node->setPosition(graphic::vec3(0, 0, 50));*/
// scene->addCamera(new PerspectiveCameraFPS({0, 0, 1}, {0, 0, 0}));
Camera* camera = new PerspectiveCamera();
camera->setCameraController(new DefaultCameraController(camera));
camera->setPosition(vec3(0, 0, 100));
scene->addCamera(camera);
while (device->run()) {
scene->render();
device->swapBuffers();
}
return 1;
}
| 38.934307 | 122 | 0.668166 | [
"mesh",
"render"
] |
d7120a5ff87f5646caaa24f4863f91b5849f3b8a | 13,026 | cpp | C++ | interface/src/ui/overlays/Circle3DOverlay.cpp | manlea/hifi | 2dff75dac126a11da2d2bcf6cb4a2ab55e633a10 | [
"Apache-2.0"
] | 1 | 2015-03-11T19:49:20.000Z | 2015-03-11T19:49:20.000Z | interface/src/ui/overlays/Circle3DOverlay.cpp | manlea/hifi | 2dff75dac126a11da2d2bcf6cb4a2ab55e633a10 | [
"Apache-2.0"
] | null | null | null | interface/src/ui/overlays/Circle3DOverlay.cpp | manlea/hifi | 2dff75dac126a11da2d2bcf6cb4a2ab55e633a10 | [
"Apache-2.0"
] | null | null | null | //
// Circle3DOverlay.cpp
// interface/src/ui/overlays
//
// Copyright 2014 High Fidelity, Inc.
//
// Distributed under the Apache License, Version 2.0.
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
//
// include this before QGLWidget, which includes an earlier version of OpenGL
#include "InterfaceConfig.h"
#include <QGLWidget>
#include <SharedUtil.h>
#include <StreamUtils.h>
#include "Circle3DOverlay.h"
#include "renderer/GlowEffect.h"
Circle3DOverlay::Circle3DOverlay() :
_startAt(0.0f),
_endAt(360.0f),
_outerRadius(1.0f),
_innerRadius(0.0f),
_hasTickMarks(false),
_majorTickMarksAngle(0.0f),
_minorTickMarksAngle(0.0f),
_majorTickMarksLength(0.0f),
_minorTickMarksLength(0.0f)
{
_majorTickMarksColor.red = _majorTickMarksColor.green = _majorTickMarksColor.blue = (unsigned char)0;
_minorTickMarksColor.red = _minorTickMarksColor.green = _minorTickMarksColor.blue = (unsigned char)0;
}
Circle3DOverlay::~Circle3DOverlay() {
}
void Circle3DOverlay::render() {
if (!_visible) {
return; // do nothing if we're not visible
}
float alpha = getAlpha();
if (alpha == 0.0) {
return; // do nothing if our alpha is 0, we're not visible
}
const float FULL_CIRCLE = 360.0f;
const float SLICES = 180.0f; // The amount of segment to create the circle
const float SLICE_ANGLE = FULL_CIRCLE / SLICES;
//const int slices = 15;
xColor color = getColor();
const float MAX_COLOR = 255.0f;
glColor4f(color.red / MAX_COLOR, color.green / MAX_COLOR, color.blue / MAX_COLOR, alpha);
glDisable(GL_LIGHTING);
glm::vec3 position = getPosition();
glm::vec3 center = getCenter();
glm::vec2 dimensions = getDimensions();
glm::quat rotation = getRotation();
float glowLevel = getGlowLevel();
Glower* glower = NULL;
if (glowLevel > 0.0f) {
glower = new Glower(glowLevel);
}
glPushMatrix();
glTranslatef(position.x, position.y, position.z);
glm::vec3 axis = glm::axis(rotation);
glRotatef(glm::degrees(glm::angle(rotation)), axis.x, axis.y, axis.z);
glPushMatrix();
glm::vec3 positionToCenter = center - position;
glTranslatef(positionToCenter.x, positionToCenter.y, positionToCenter.z);
glScalef(dimensions.x, dimensions.y, 1.0f);
// Create the circle in the coordinates origin
float outerRadius = getOuterRadius();
float innerRadius = getInnerRadius(); // only used in solid case
float startAt = getStartAt();
float endAt = getEndAt();
glLineWidth(_lineWidth);
// for our overlay, is solid means we draw a ring between the inner and outer radius of the circle, otherwise
// we just draw a line...
if (getIsSolid()) {
glBegin(GL_QUAD_STRIP);
float angle = startAt;
float angleInRadians = glm::radians(angle);
glm::vec2 firstInnerPoint(cos(angleInRadians) * innerRadius, sin(angleInRadians) * innerRadius);
glm::vec2 firstOuterPoint(cos(angleInRadians) * outerRadius, sin(angleInRadians) * outerRadius);
glVertex2f(firstInnerPoint.x, firstInnerPoint.y);
glVertex2f(firstOuterPoint.x, firstOuterPoint.y);
while (angle < endAt) {
angleInRadians = glm::radians(angle);
glm::vec2 thisInnerPoint(cos(angleInRadians) * innerRadius, sin(angleInRadians) * innerRadius);
glm::vec2 thisOuterPoint(cos(angleInRadians) * outerRadius, sin(angleInRadians) * outerRadius);
glVertex2f(thisOuterPoint.x, thisOuterPoint.y);
glVertex2f(thisInnerPoint.x, thisInnerPoint.y);
angle += SLICE_ANGLE;
}
// get the last slice portion....
angle = endAt;
angleInRadians = glm::radians(angle);
glm::vec2 lastInnerPoint(cos(angleInRadians) * innerRadius, sin(angleInRadians) * innerRadius);
glm::vec2 lastOuterPoint(cos(angleInRadians) * outerRadius, sin(angleInRadians) * outerRadius);
glVertex2f(lastOuterPoint.x, lastOuterPoint.y);
glVertex2f(lastInnerPoint.x, lastInnerPoint.y);
glEnd();
} else {
if (getIsDashedLine()) {
glBegin(GL_LINES);
} else {
glBegin(GL_LINE_STRIP);
}
float angle = startAt;
float angleInRadians = glm::radians(angle);
glm::vec2 firstPoint(cos(angleInRadians) * outerRadius, sin(angleInRadians) * outerRadius);
glVertex2f(firstPoint.x, firstPoint.y);
while (angle < endAt) {
angle += SLICE_ANGLE;
angleInRadians = glm::radians(angle);
glm::vec2 thisPoint(cos(angleInRadians) * outerRadius, sin(angleInRadians) * outerRadius);
glVertex2f(thisPoint.x, thisPoint.y);
if (getIsDashedLine()) {
angle += SLICE_ANGLE / 2.0f; // short gap
angleInRadians = glm::radians(angle);
glm::vec2 dashStartPoint(cos(angleInRadians) * outerRadius, sin(angleInRadians) * outerRadius);
glVertex2f(dashStartPoint.x, dashStartPoint.y);
}
}
// get the last slice portion....
angle = endAt;
angleInRadians = glm::radians(angle);
glm::vec2 lastOuterPoint(cos(angleInRadians) * outerRadius, sin(angleInRadians) * outerRadius);
glVertex2f(lastOuterPoint.x, lastOuterPoint.y);
glEnd();
}
// draw our tick marks
// for our overlay, is solid means we draw a ring between the inner and outer radius of the circle, otherwise
// we just draw a line...
if (getHasTickMarks()) {
glBegin(GL_LINES);
// draw our major tick marks
if (getMajorTickMarksAngle() > 0.0f && getMajorTickMarksLength() != 0.0f) {
xColor color = getMajorTickMarksColor();
glColor4f(color.red / MAX_COLOR, color.green / MAX_COLOR, color.blue / MAX_COLOR, alpha);
float tickMarkAngle = getMajorTickMarksAngle();
float angle = startAt - fmod(startAt, tickMarkAngle) + tickMarkAngle;
float angleInRadians = glm::radians(angle);
float tickMarkLength = getMajorTickMarksLength();
float startRadius = (tickMarkLength > 0.0f) ? innerRadius : outerRadius;
float endRadius = startRadius + tickMarkLength;
while (angle <= endAt) {
angleInRadians = glm::radians(angle);
glm::vec2 thisPointA(cos(angleInRadians) * startRadius, sin(angleInRadians) * startRadius);
glm::vec2 thisPointB(cos(angleInRadians) * endRadius, sin(angleInRadians) * endRadius);
glVertex2f(thisPointA.x, thisPointA.y);
glVertex2f(thisPointB.x, thisPointB.y);
angle += tickMarkAngle;
}
}
// draw our minor tick marks
if (getMinorTickMarksAngle() > 0.0f && getMinorTickMarksLength() != 0.0f) {
xColor color = getMinorTickMarksColor();
glColor4f(color.red / MAX_COLOR, color.green / MAX_COLOR, color.blue / MAX_COLOR, alpha);
float tickMarkAngle = getMinorTickMarksAngle();
float angle = startAt - fmod(startAt, tickMarkAngle) + tickMarkAngle;
float angleInRadians = glm::radians(angle);
float tickMarkLength = getMinorTickMarksLength();
float startRadius = (tickMarkLength > 0.0f) ? innerRadius : outerRadius;
float endRadius = startRadius + tickMarkLength;
while (angle <= endAt) {
angleInRadians = glm::radians(angle);
glm::vec2 thisPointA(cos(angleInRadians) * startRadius, sin(angleInRadians) * startRadius);
glm::vec2 thisPointB(cos(angleInRadians) * endRadius, sin(angleInRadians) * endRadius);
glVertex2f(thisPointA.x, thisPointA.y);
glVertex2f(thisPointB.x, thisPointB.y);
angle += tickMarkAngle;
}
}
glEnd();
}
glPopMatrix();
glPopMatrix();
if (glower) {
delete glower;
}
}
void Circle3DOverlay::setProperties(const QScriptValue &properties) {
Planar3DOverlay::setProperties(properties);
QScriptValue startAt = properties.property("startAt");
if (startAt.isValid()) {
setStartAt(startAt.toVariant().toFloat());
}
QScriptValue endAt = properties.property("endAt");
if (endAt.isValid()) {
setEndAt(endAt.toVariant().toFloat());
}
QScriptValue outerRadius = properties.property("outerRadius");
if (outerRadius.isValid()) {
setOuterRadius(outerRadius.toVariant().toFloat());
}
QScriptValue innerRadius = properties.property("innerRadius");
if (innerRadius.isValid()) {
setInnerRadius(innerRadius.toVariant().toFloat());
}
QScriptValue hasTickMarks = properties.property("hasTickMarks");
if (hasTickMarks.isValid()) {
setHasTickMarks(hasTickMarks.toVariant().toBool());
}
QScriptValue majorTickMarksAngle = properties.property("majorTickMarksAngle");
if (majorTickMarksAngle.isValid()) {
setMajorTickMarksAngle(majorTickMarksAngle.toVariant().toFloat());
}
QScriptValue minorTickMarksAngle = properties.property("minorTickMarksAngle");
if (minorTickMarksAngle.isValid()) {
setMinorTickMarksAngle(minorTickMarksAngle.toVariant().toFloat());
}
QScriptValue majorTickMarksLength = properties.property("majorTickMarksLength");
if (majorTickMarksLength.isValid()) {
setMajorTickMarksLength(majorTickMarksLength.toVariant().toFloat());
}
QScriptValue minorTickMarksLength = properties.property("minorTickMarksLength");
if (minorTickMarksLength.isValid()) {
setMinorTickMarksLength(minorTickMarksLength.toVariant().toFloat());
}
QScriptValue majorTickMarksColor = properties.property("majorTickMarksColor");
if (majorTickMarksColor.isValid()) {
QScriptValue red = majorTickMarksColor.property("red");
QScriptValue green = majorTickMarksColor.property("green");
QScriptValue blue = majorTickMarksColor.property("blue");
if (red.isValid() && green.isValid() && blue.isValid()) {
_majorTickMarksColor.red = red.toVariant().toInt();
_majorTickMarksColor.green = green.toVariant().toInt();
_majorTickMarksColor.blue = blue.toVariant().toInt();
}
}
QScriptValue minorTickMarksColor = properties.property("minorTickMarksColor");
if (minorTickMarksColor.isValid()) {
QScriptValue red = minorTickMarksColor.property("red");
QScriptValue green = minorTickMarksColor.property("green");
QScriptValue blue = minorTickMarksColor.property("blue");
if (red.isValid() && green.isValid() && blue.isValid()) {
_minorTickMarksColor.red = red.toVariant().toInt();
_minorTickMarksColor.green = green.toVariant().toInt();
_minorTickMarksColor.blue = blue.toVariant().toInt();
}
}
}
bool Circle3DOverlay::findRayIntersection(const glm::vec3& origin,
const glm::vec3& direction, float& distance, BoxFace& face) const {
bool intersects = Planar3DOverlay::findRayIntersection(origin, direction, distance, face);
if (intersects) {
glm::vec3 hitAt = origin + (direction * distance);
float distanceToHit = glm::distance(hitAt, _position);
float maxDimension = glm::max(_dimensions.x, _dimensions.y);
float innerRadius = maxDimension * getInnerRadius();
float outerRadius = maxDimension * getOuterRadius();
// TODO: this really only works for circles, we should be handling the ellipse case as well...
if (distanceToHit < innerRadius || distanceToHit > outerRadius) {
intersects = false;
}
}
return intersects;
}
| 39.713415 | 121 | 0.595655 | [
"render",
"solid"
] |
d71548c1abffcda4791949d7fa458aad6e7dc20c | 6,400 | cpp | C++ | A Simple Logic Circuit Simulator/BoardCreator.cpp | amanda-matthes/A-Simple-Logic-Simulator | f4a884a72853d2d91245dfef69f69e2584b0c7bd | [
"MIT"
] | null | null | null | A Simple Logic Circuit Simulator/BoardCreator.cpp | amanda-matthes/A-Simple-Logic-Simulator | f4a884a72853d2d91245dfef69f69e2584b0c7bd | [
"MIT"
] | null | null | null | A Simple Logic Circuit Simulator/BoardCreator.cpp | amanda-matthes/A-Simple-Logic-Simulator | f4a884a72853d2d91245dfef69f69e2584b0c7bd | [
"MIT"
] | null | null | null | // A Simple Logic Circuit Simulator
// A project for PHYS 30762 Programming in C++
// Author : Amanda Matthes (10241789)
// Handed in on : 12.May.2018
// This program starts in Main.h
#include "BoardCreator.h"
void boardCreator() { // acts as a sub menu to navigate board creation
// 1. Ask for dimensions
intPair dimensions = askForTwoInts("How big do you want your board (widthxheight)?");
int width = dimensions.first;
int height = dimensions.second;
// 2. Create grid
Grid g = Grid(width, height);
cout << g;
// 3. Enter menu
string input; // temporarily stores the input
intPair loc; // temporarily stores a location
type t; // temporarily stores a type
bool state; // temporarily stores a state
while (true) {
cout << endl << "What do you want to do? \n";
cout << "A: Add a component \n";
cout << "B: Delete a component \n";
cout << "C: Flip an input \n";
cout << "D: Show me the legend again \n";
cout << "E: Exit to main menu (Deletes the board) \n";
getline(cin, input);
if (input != "A" && input != "B" && input != "C" && input != "D" && input != "E") {
cout << "Invalid input" << "\n";
}
// 3a. Add component
if (input == "A") {
// 3a 1) Ask for location of component
loc = askForTwoInts("Where do you want to add it (rowxcolumn)?");
if (loc.first >= width || loc.second >= height) { // check that the location lies on the grid
cout << "Invalid location. The place you entered is not on this board" << endl;
continue;
}
// 3a 2) Ask for component type and state if applicable
t = askForType(); // returns EMPTY if the user does not want to add a component after all
bool state = false; // gets overwritten iff the type is an INPUT that can actually have a set state
if (t != EMPTY) {
if (t == INPUT) {
state = askForBool();
}
// 3a 3) add to grid
g.add(loc.first, loc.second, t, state);
}
}
// 3b. Remove component
if (input == "B") {
// 3b 1) Ask for location of component
loc = askForTwoInts("Which component to you want to delete (rowxcolumn)?");
if (loc.first >= width || loc.second >= height) { // check that the location lies on the grid
cout << "Invalid location. The place you entered is not on this board" << endl;
continue;
}
// 3b 2) Remove component
g.remove(loc.first, loc.second);
}
// 3c. Flip an INPUT
if (input == "C") {
// 3c 1) Ask for location of INPUT
loc = askForTwoInts("Which input do you want to flip (rowxcolumn)?");
if (loc.first >= width || loc.second >= height) { // check that the location lies on the grid
cout << "Invalid location. The place you entered is not on this board" << endl;
continue;
}
if (g(loc.first, loc.second).getType() != INPUT) { // check that location contains an INPUT
cout << "Invalid location. There is no input component at that location" << endl;
continue;
}
// 3d 2) Flip INPUT
g(loc.first, loc.second).flip();
}
// 3d. Print Legend
if (input == "D") {
printLegend();
}
// 3c. Return to main menu
if (input == "E") {
break;
}
g.render();
cout << g;
}
}
intPair askForTwoInts(string message) { // asks the user for two numbers firstxsecond and returns them as an intPair (first, second)
string input; // temporarily stores the input
bool firstSet = false; // flags if a number has been entered before the x
bool xFound = false; // flags if the x in the middle has been read
bool errorFlag = false; // flags if errors are encountered
int first; // will store the first integer
int second; // will store the second integer
string current = ""; // temporarily stores a substring of the input to be interpreted
while (true) {
firstSet = false; xFound = false; current = ""; errorFlag = false; // reset in case of invalid input
cout << message << endl;
getline(cin, input);
for (auto letter : input) { // iterate input
if ((letter != 'x' && !isdigit(letter)) || (letter == 'x' && !firstSet)) { // check for invalid input
errorFlag = true;
break;
}
firstSet = true; // we need at least one digit before the x
if (letter == 'x') {
xFound = true;
first = stoi(current); // if the x is reached we can extract the first integer from current
current = ""; // reset current, so that it can hold the second integer
continue;
}
current += letter; // push the next character into current
}
if (!xFound || current == "") { // if we have reached the end of the input and no x has been found the input was invalid
errorFlag = true;
}
if (errorFlag) { // check error flag
cout << "Invalid Input. Try writing something like 5x4 or 13x7" << endl;
continue;
}
second = stoi(current); // if there haven't been any errors current will hold the second integer
break;
}
intPair result;
result.first = first;
result.second = second;
return result;
}
type askForType() { // asks the user for a component type and returns it
string input; // temporarily stores the input
while (true) {
cout << "What component do you want to add?\n";
cout << "A: Input \n";
cout << "B: Output (LED) \n";
cout << "C: AND Gate \n";
cout << "D: OR Gate \n";
cout << "E: NOT Gate \n";
cout << "F: Wire \n";
cout << "G: Show me the legend again \n";
cout << "H: I don't want to add anything after all \n";
getline(cin, input);
if (input != "A" && input != "B" && input != "C" && input != "D" && input != "E" && input != "F" && input != "G" && input != "H") {
cout << "Invalid input" << "\n";
}
if (input == "A") {
return INPUT;
}
if (input == "B") {
return OUTPUT;
}
if (input == "C") {
return AND;
}
if (input == "D") {
return OR;
}
if (input == "E") {
return NOT;
}
if (input == "F") {
return WIRE;
}
if (input == "G") {
printLegend();
}
if (input == "H") {
return EMPTY;
}
}
}
bool askForBool(){ // asks the user for a boolean and returns it
string input; // temporarily stores the input
while (true) {
cout << "Do you want it to be on or off? \n";
cout << "1: on \n";
cout << "0: off \n";
getline(cin, input);
if (input != "1" && input != "0") {
cout << "Invalid input" << "\n";
}
if (input == "1") {
return true;
}
if (input == "0") {
return false;
}
}
}
| 31.527094 | 133 | 0.602188 | [
"render",
"3d"
] |
d716158d36a97771554aab9770f439d4e0064331 | 6,834 | cc | C++ | pgutil/PgModelManager.cc | erikleitch/climax | 66ce64b0ab9f3a3722d3177cc5215ccf59369e88 | [
"MIT"
] | 1 | 2018-11-01T05:15:31.000Z | 2018-11-01T05:15:31.000Z | pgutil/PgModelManager.cc | erikleitch/climax | 66ce64b0ab9f3a3722d3177cc5215ccf59369e88 | [
"MIT"
] | null | null | null | pgutil/PgModelManager.cc | erikleitch/climax | 66ce64b0ab9f3a3722d3177cc5215ccf59369e88 | [
"MIT"
] | 2 | 2017-05-02T19:35:55.000Z | 2018-03-07T00:54:51.000Z | #include "gcp/pgutil/PgModelManager.h"
#include "cpgplot.h"
using namespace std;
using namespace gcp::util;
enum {
B_NORM=0,
B_LINE=1,
B_RECT=2,
B_YRNG=3,
B_XRNG=4,
B_YVAL=5,
B_XVAL=6,
B_CROSS=7
};
/**.......................................................................
* Constructor.
*/
PgModelManager::PgModelManager()
{
display_ = true;
}
/**.......................................................................
* Destructor.
*/
PgModelManager::~PgModelManager() {}
/**.......................................................................
* Display all models managed by this class
*/
void PgModelManager::display() {
for(unsigned iMod=0; iMod < models_.size(); iMod++) {
models_[iMod].precalculateShape();
models_[iMod].draw();
}
};
/**.......................................................................
* Remove a model from the list of models maintained by this class
*/
void PgModelManager::removeModel(float x, float y) {
float sep,minSep;
int minInd=0;
std::vector<PgModel>::iterator minIter=models_.end();
for(std::vector<PgModel>::iterator iter=models_.begin(); iter != models_.end(); iter++) {
PgModel& model = *iter;
sep = sqrt((model.xMid_ - x)*(model.xMid_ - x) + (model.yMid_ - y)*(model.yMid_ - y));
if(iter == models_.begin()) {
minSep = sep;
minIter = iter;
} else {
if(sep < minSep) {
minSep = sep;
minIter = iter;
}
}
}
if(minIter != models_.end())
models_.erase(minIter);
}
void PgModelManager::getModel(float xstart, float ystart, bool& read, char& key, std::string unit, Trans& trans)
{
bool done = false;
bool cancel = false;
float xMid, yMid;
float xRad1, yRad1;
float xRad2, yRad2;
float xtemp, ytemp;
float xIn=xstart;
float yIn=ystart;
xtemp = xIn;
ytemp = yIn;
std::ostringstream removeHelp;
removeHelp << "Use one of the following: " << std::endl
<< " A (left mouse) -- Select a model to remove" << std::endl
<< "Or use 'C' to cancel model selection";
std::ostringstream addHelp;
addHelp << "Use one of the following: " << std::endl
<< " A -- Arnaud model" << std::endl
<< " B -- Symmetric Beta model" << std::endl
<< " E -- Elliptical Beta model" << std::endl
<< " G -- Gaussian model" << std::endl
<< " P -- Point source model" << std::endl
<< "Or use 'C' to cancel model selection";
std::ostringstream actionHelp;
actionHelp << "Use one of the following: " << std::endl
<< " A -- Add a new model component" << std::endl
<< " R -- Remove the model component nearest the cursor" << std::endl
<< " D -- Toggle displaying model components" << std::endl
<< " P -- Print model components" << std::endl
<< "Or use 'C' to cancel model selection";
COUT(actionHelp.str());
bool haveModelType = false;
bool getCenter = false;
bool getRadius1 = false;
bool getRadius2 = false;
int cursorMode = B_NORM;
bool accepted = false;
bool getAction = true;
bool add = false;
bool remove = false;
PgModel model;
int ci;
cpgqci(&ci);
cpgsci(5);
do {
accepted = 0;
cpgband(cursorMode, 0, xIn, yIn, &xtemp, &ytemp, &key);
if(islower((int) key))
key = (char) toupper((int) key);
//------------------------------------------------------------
// If determining what the user wants to do
//------------------------------------------------------------
if(getAction) {
switch(key) {
case 'A':
getAction = false;
add = true;
COUT(addHelp.str());
break;
case 'R':
cursorMode = B_CROSS;
getAction = false;
remove = true;
COUT(removeHelp.str());
break;
case 'P':
printModels(unit, trans);
accepted = true;
read = false;
break;
case 'D':
display_ = !display_;
accepted = true;
read = false;
key = 'L';
break;
case 'C':
accepted = true;
cancel = true;
break;
default:
COUT(actionHelp.str());
break;
}
//------------------------------------------------------------
// Else if removing a model component
//------------------------------------------------------------
} else if(remove) {
switch(key) {
case 'A':
COUT("Removing model");
removeModel(xtemp, ytemp);
accepted = true;
read = false;
key = 'L';
COUT("Removing model done");
break;
case 'C':
accepted = true;
cancel = true;
break;
default:
COUT(removeHelp.str());
break;
}
//------------------------------------------------------------
// Else if defining a new model component
//------------------------------------------------------------
} else if(add) {
switch(key) {
// Arnaud model
case 'A':
if(getCenter) {
getCenter = false;
getRadius1 = true;
// Store the center of the model
model.xMid_ = xtemp;
model.yMid_ = ytemp;
model.peak_ = trans.valNearestToPoint(xtemp, ytemp);
COUT("Setting peak to: " << model.peak_);
// And set the anchor point to the midpoint
xIn = xMid=xtemp;
yIn = yMid=ytemp;
if(model.type_ == PgModel::TYPE_DELTA) {
cursorMode = B_NORM;
accepted = true;
add = true;
} else {
cursorMode = B_LINE;
COUT("Click to define the core radius");
}
break;
} else if(getRadius1) {
model.xRad1_ = xtemp;
model.yRad1_ = ytemp;
getRadius1 = false;
// If we just got a radius, we are done for symmetric models
if(model.type_ == PgModel::TYPE_ARNAUD || model.type_ == PgModel::TYPE_BETA) {
accepted = true;
add = true;
} else {
cpgmove(model.xMid_, model.yMid_);
cpgdraw(model.xRad1_, model.yRad1_);
getRadius2 = true;
COUT("Click to define the other axis");
}
break;
// Else we need to get a second radius for assymetric models
} else if(getRadius2) {
model.xRad2_ = xtemp;
model.yRad2_ = ytemp;
getRadius2 = false;
accepted = true;
add = true;
break;
}
// Point-source model
case 'P':
// Symmetric beta model
case 'B':
// Elliptical beta model
case 'E':
// Gaussian model
case 'G':
model.type_ = PgModel::keyToType(key);
COUT("Model typew is now " << model.type_);
haveModelType = true;
getCenter = true;
COUT("Click to locate the model center");
cursorMode = B_CROSS;
break;
case 'C':
accepted = true;
cancel = true;
break;
default:
COUT(addHelp.str());
break;
}
}
} while(!accepted);
if(add && !cancel) {
model.rectify();
model.draw();
models_.push_back(model);
}
cpgsci(ci);
}
void PgModelManager::printModels(string& unit, Trans& trans)
{
for(unsigned iMod=0; iMod < models_.size(); iMod++)
models_[iMod].print(unit, iMod, trans);
}
void PgModelManager::addModel(PgModel& model)
{
models_.push_back(model);
}
| 21.903846 | 112 | 0.546093 | [
"vector",
"model"
] |
d71a115adea0166275ce004fd10c916654b27bf9 | 13,754 | cpp | C++ | img/osu/main.cpp | Erawz/Bongo-cat | dd8f87a1c195c6283c6917b7574cda0cddebcbab | [
"MIT"
] | null | null | null | img/osu/main.cpp | Erawz/Bongo-cat | dd8f87a1c195c6283c6917b7574cda0cddebcbab | [
"MIT"
] | null | null | null | img/osu/main.cpp | Erawz/Bongo-cat | dd8f87a1c195c6283c6917b7574cda0cddebcbab | [
"MIT"
] | null | null | null | #include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sstream>
#include <time.h>
#include <windows.h>
#include <math.h>
#include <SFML/Graphics.hpp>
#include "json/json.h"
std::tuple<double, double> bezier(double ratio, std::vector<double> &points, int length) {
double fact[22] = {0.001, 0.001, 0.002, 0.006, 0.024, 0.12, 0.72, 5.04, 40.32, 362.88, 3628.8, 39916.8, 479001.6, 6227020.8, 87178291.2, 1307674368.0, 20922789888.0, 355687428096.0, 6402373705728.0, 121645100408832.0, 2432902008176640.0, 51090942171709440.0};
int nn = (length / 2) - 1;
double xx = 0;
double yy = 0;
for (int point = 0; point <= nn; point++) {
double tmp = fact[nn] / (fact[point] * fact[nn - point]) * pow(ratio, point) * pow(1 - ratio, nn - point);
xx += points[2 * point] * tmp;
yy += points[2 * point + 1] * tmp;
}
return std::make_tuple(xx / 1000, yy / 1000);
}
void GetDesktopResolution(int &horizontal, int &vertical) {
RECT desktop;
const HWND hDesktop = GetDesktopWindow();
GetWindowRect(hDesktop, &desktop);
horizontal = desktop.right;
vertical = desktop.bottom;
}
void loadTexture(sf::Texture &tex, std::string path) {
if (!tex.loadFromFile(path)) {
// error here
// exit(1);
}
}
void createConfig() {
std::ifstream f("config.json");
if (!f.good()) {
std::ofstream cfg("config.json");
cfg << "{ \n \
\"resolution\": { \n \
\"letterboxing\": false, \n \
\"width\": 1920, \n \
\"height\": 1080, \n \
\"horizontalPosition\": 100, \n \
\"verticalPosition\": -100 \n \
}, \n \
\"decoration\": { \n \
\"red\": 255, \n \
\"green\": 255, \n \
\"blue\": 255, \n \
\"leftHanded\": false, \n \
\"rgbArm\": false, \n \
\"mouseXOffset\": 0, \n \
\"mouseYOffset\": 0, \n \
\"mouseScalar\": 1, \n \
\"tabletXOffset\": 11, \n \
\"tabletYOffset\": -65, \n \
\"tabletScalar\": 1 \n \
}, \n \
\"osu\": { \n \
\"mouse\": true, \n \
\"key1\": 16, \n \
\"key2\": 32 \n \
} \n \
}";
}
}
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
sf::RenderWindow window(sf::VideoMode(612, 352), "\"ESC\" for Mouse | Set Keys/Letterboxing etc. in \"config.json\"", sf::Style::Titlebar | sf::Style::Close);
window.setFramerateLimit(240);
int horizontal = 0;
int vertical = 0;
GetDesktopResolution(horizontal, vertical);
// loading configs
createConfig();
std::ifstream cfgFile("config.json", std::ifstream::binary);
std::string cfgString((std::istreambuf_iterator<char>(cfgFile)), std::istreambuf_iterator<char>());
Json::Reader cfgReader;
Json::Value cfg;
if (!cfgReader.parse(cfgString, cfg)) {
std::cout << "Error reading the config\n";
return 0;
}
cfgFile.close();
bool isMouse = cfg["osu"]["mouse"].asBool();
// here leftKeyValue and rightKeyValue holds value for the virtual key-codes
// http://nehe.gamedevice.net/article/msdn_virtualkey_codes/15009/ for reference
int leftKeyValue = cfg["osu"]["key1"].asInt();
int rightKeyValue = cfg["osu"]["key2"].asInt();
bool isLetterbox = cfg["resolution"]["letterboxing"].asBool();
double osuX = cfg["resolution"]["width"].asInt();
double osuY = cfg["resolution"]["height"].asInt();
double osuH = cfg["resolution"]["horizontalPosition"].asInt();
double osuV = cfg["resolution"]["verticalPosition"].asInt();
int redValue = cfg["decoration"]["red"].asInt();
int greenValue = cfg["decoration"]["green"].asInt();
int blueValue = cfg["decoration"]["blue"].asInt();
bool isLeftHanded = cfg["decoration"]["leftHanded"].asBool();
bool rgbArm = cfg["decoration"]["rgbArm"].asBool();
double mouseDX = cfg["decoration"]["mouseXOffset"].asInt();
double mouseDY = cfg["decoration"]["mouseYOffset"].asInt();
double mouseScale = cfg["decoration"]["mouseScalar"].asInt();
double tabletDX = cfg["decoration"]["tabletXOffset"].asInt();
double tabletDY = cfg["decoration"]["tabletYOffset"].asInt();
double tabletScale = cfg["decoration"]["tabletScalar"].asInt();
bool isSwitch = false;
int keyState = 0;
bool leftKeyState = false;
bool rightKeyState = false;
double timerLeftKey = -1;
double timerRightKey = -1;
// loading textures
sf::Texture bgTex;
if (isMouse) {
loadTexture(bgTex, "img/osu/mousebg.png");
}
else {
loadTexture(bgTex, "img/osu/tabletbg.png");
}
sf::Sprite bg(bgTex);
sf::Texture upTex;
loadTexture(upTex, "img/osu/up.png");
sf::Sprite up(upTex);
sf::Texture leftTex;
loadTexture(leftTex, "img/osu/left.png");
sf::Sprite left(leftTex);
sf::Texture rightTex;
loadTexture(rightTex, "img/osu/right.png");
sf::Sprite right(rightTex);
sf::Texture deviceTex;
if (isMouse) {
loadTexture(deviceTex, "img/osu/mouse.png");
}
else {
loadTexture(deviceTex, "img/osu/tablet.png");
}
sf::Sprite device(deviceTex);
if (isMouse) {
device.setScale(mouseScale, mouseScale);
}
else {
device.setScale(tabletScale, tabletScale);
}
while (window.isOpen()) {
sf::Event event;
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed) {
window.close();
}
}
double letterX;
double letterY;
double sWidth;
double sHeight;
bool isBongo;
// getting resolution
HWND handle = GetForegroundWindow();
if (handle) {
RECT oblong;
TCHAR WTitle[256];
GetWindowRect(handle, &oblong);
GetWindowText(handle, WTitle, GetWindowTextLength(handle));
std::string test = WTitle; //and convert to string.
std::size_t index = test.find("osu!");
if (index < 300) {
if (!isLetterbox) {
sHeight = (oblong.bottom - oblong.top) * 0.8;
sWidth = sHeight * 4 / 3;
letterX = oblong.left + ((oblong.right - oblong.left) - sWidth) / 2;
letterY = oblong.top + sHeight / 0.8 * 0.117;
}
else {
sHeight = osuY * 0.8;
sWidth = sHeight * 4 / 3;
double lll = (horizontal - osuX) * (osuH + 100) / 200; ////109
double rrr = lll + osuX; ////1389
letterX = lll + ((rrr - lll) - sWidth) / 2;
letterY = (vertical - osuY) * (osuV + 100) / 200 + sHeight / 0.8 * 0.117;
}
}
else {
sWidth = horizontal;
sHeight = vertical;
letterX = 0;
letterY = 0;
}
index = test.find("Set Keys/Letterboxing et");
if (index < 300) {
isBongo = true;
}
else {
isBongo = false;
}
//std::cout << oblong.left;
}
else {
isBongo = false;
sWidth = horizontal;
sHeight = vertical;
letterX = 0;
letterY = 0;
}
double x;
double y;
POINT point;
if (GetCursorPos(&point)) {
double fx = ((double)point.x - letterX) / sWidth;
if (isLeftHanded) {
fx = 1 - fx;
}
double fy = ((double)point.y - letterY) / sHeight;
fx = std::min(fx, 1.0);
fx = std::max(fx, 0.0);
fy = std::min(fy, 1.0);
fy = std::max(fy, 0.0);
x = -97 * fx + 44 * fy + 184;
y = -76 * fx - 40 * fy + 324;
}
window.clear(sf::Color(redValue, greenValue, blueValue));
window.draw(bg);
// ESCAPE for switching device
// A few suggestion here, instead of switching device, we can implement so that ESCAPE means reloading the config.json file
// Which is better for later on since I'm planning to support other game modes if you don't bother?
if ((GetKeyState(VK_ESCAPE) & 0x8000) && isBongo) {
if (!isSwitch) {
isMouse = !isMouse;
if (isMouse) {
loadTexture(bgTex, "img/osu/mousebg.png");
loadTexture(deviceTex, "img/osu/mouse.png");
device.setScale(mouseScale, mouseScale);
}
else {
loadTexture(bgTex, "img/osu/tabletbg.png");
loadTexture(deviceTex, "img/osu/tablet.png");
device.setScale(tabletScale, tabletScale);
}
}
isSwitch = true;
}
else {
isSwitch = false;
}
// drawing keypresses
if (GetKeyState(leftKeyValue) & 0x8000) {
if (!leftKeyState) {
keyState = 1;
leftKeyState = true;
}
}
else {
leftKeyState = false;
}
if (GetKeyState(rightKeyValue) & 0x8000) {
if (!rightKeyState) {
keyState = 2;
rightKeyState = true;
}
}
else {
rightKeyState = false;
}
if (!leftKeyState && !rightKeyState) {
keyState = 0;
window.draw(up);
}
if (keyState == 1) {
if (clock() - 31 > timerRightKey) {
window.draw(left);
timerLeftKey = clock();
}
else {
window.draw(up);
}
}
else if (keyState == 2) {
if (clock() - 31 > timerLeftKey) {
window.draw(right);
timerRightKey = clock();
}
else {
window.draw(up);
}
}
// initializing pss and pss2
int oof = 6;
std::vector<double> pss = {211.0, 159.0};
double dist = hypot(211 - x, 159 - y);
double centreleft0 = 211 - 0.7237 * dist / 2;
double centreleft1 = 159 + 0.69 * dist / 2;
for (double i = 1; i < oof; i++) {
double p0;
double p1;
std::vector<double> bez = {211, 159, centreleft0, centreleft1, x, y};
std::tie(p0, p1) = bezier(i / oof, bez, 6);
pss.push_back(p0);
pss.push_back(p1);
}
pss.push_back(x);
pss.push_back(y);
double a = y - centreleft1;
double b = centreleft0 - x;
double le = hypot(a, b);
a = x + a / le * 60;
b = y + b / le * 60;
int a1 = 258;
int a2 = 228;
dist = hypot(a1 - a, a2 - b);
double centreright0 = a1 - 0.6 * dist / 2;
double centreright1 = a2 + 0.8 * dist / 2;
int push = 20;
double s = x - centreleft0;
double t = y - centreleft1;
le = hypot(s, t);
s *= push / le;
t *= push / le;
double s2 = a - centreright0;
double t2 = b - centreright1;
le = hypot(s2, t2);
s2 *= push / le;
t2 *= push / le;
for (double i = 1; i < oof; i++) {
double p0;
double p1;
std::vector<double> bez = {x, y, x + s, y + t, a + s2, b + t2, a, b};
std::tie(p0, p1) = bezier(i / oof, bez, 8);
pss.push_back(p0);
pss.push_back(p1);
}
pss.push_back(a);
pss.push_back(b);
for (double i = oof - 1; i > 0; i--) {
double p0;
double p1;
std::vector<double> bez = {1.0 * a1, 1.0 * a2, centreright0, centreright1, a, b};
std::tie(p0, p1) = bezier(i / oof, bez, 6);
pss.push_back(p0);
pss.push_back(p1);
}
pss.push_back(a1);
pss.push_back(a2);
double mpos0 = (a + x) / 2 - 52 - 15;
double mpos1 = (b + y) / 2 - 34 + 5;
double dx = -38;
double dy = -50;
const int iter = 25;
std::vector<double> pss2 = {pss[0] + dx, pss[1] + dy};
for (double i = 1; i < iter; i++) {
double p0;
double p1;
std::tie(p0, p1) = bezier(i / iter, pss, 38);
pss2.push_back(p0 + dx);
pss2.push_back(p1 + dy);
}
pss2.push_back(pss[36] + dx);
pss2.push_back(pss[37] + dy);
if (isMouse) {
device.setPosition(mpos0 + dx + mouseDX, mpos1 + dy + mouseDY);
}
else {
device.setPosition(mpos0 + dx + tabletDX, mpos1 + dy + tabletDY);
}
// drawing mouse
if (isMouse) {
window.draw(device);
}
// drawing arms
sf::VertexArray fill(sf::TriangleStrip, 26);
for (int i = 0; i < 26; i += 2) {
fill[i].position = sf::Vector2f(pss2[i], pss2[i + 1]);
fill[i + 1].position = sf::Vector2f(pss2[52 - i - 2], pss2[52 - i - 1]);
if (rgbArm) {
fill[i].color = sf::Color(redValue, greenValue, blueValue);
fill[i + 1].color = sf::Color(redValue, greenValue, blueValue);
}
}
window.draw(fill);
// drawing circ
int shad = 77;
sf::VertexArray edge(sf::TriangleStrip, 52);
double width = 7;
sf::CircleShape circ(width / 2);
circ.setFillColor(sf::Color(0, 0, 0, shad));
circ.setPosition(pss2[0] - width / 2, pss2[1] - width / 2);
window.draw(circ);
for (int i = 0; i < 50; i += 2) {
double vec0 = pss2[i] - pss2[i + 2];
double vec1 = pss2[i + 1] - pss2[i + 3];
double dist = hypot(vec0, vec1);
edge[i].position = sf::Vector2f(pss2[i] + vec1 / dist * width / 2, pss2[i + 1] - vec0 / dist * width / 2);
edge[i + 1].position = sf::Vector2f(pss2[i] - vec1 / dist * width / 2, pss2[i + 1] + vec0 / dist * width / 2);
edge[i].color = sf::Color(0, 0, 0, shad);
edge[i + 1].color = sf::Color(0, 0, 0, shad);
width -= 0.08;
}
double vec0 = pss2[50] - pss2[48];
double vec1 = pss2[51] - pss2[49];
dist = hypot(vec0, vec1);
edge[51].position = sf::Vector2f(pss2[50] + vec1 / dist * width / 2, pss2[51] - vec0 / dist * width / 2);
edge[50].position = sf::Vector2f(pss2[50] - vec1 / dist * width / 2, pss2[51] + vec0 / dist * width / 2);
edge[50].color = sf::Color(0, 0, 0, shad);
edge[51].color = sf::Color(0, 0, 0, shad);
window.draw(edge);
circ.setRadius(width / 2);
circ.setPosition(pss2[50] - width / 2, pss2[51] - width / 2);
window.draw(circ);
// drawing circ2
sf::VertexArray edge2(sf::TriangleStrip, 52);
width = 6;
sf::CircleShape circ2(width / 2);
circ2.setFillColor(sf::Color::Black);
circ2.setPosition(pss2[0] - width / 2, pss2[1] - width / 2);
window.draw(circ2);
for (int i = 0; i < 50; i += 2) {
vec0 = pss2[i] - pss2[i + 2];
vec1 = pss2[i + 1] - pss2[i + 3];
double dist = hypot(vec0, vec1);
edge2[i].position = sf::Vector2f(pss2[i] + vec1 / dist * width / 2, pss2[i + 1] - vec0 / dist * width / 2);
edge2[i + 1].position = sf::Vector2f(pss2[i] - vec1 / dist * width / 2, pss2[i + 1] + vec0 / dist * width / 2);
edge2[i].color = sf::Color::Black;
edge2[i + 1].color = sf::Color::Black;
width -= 0.08;
}
vec0 = pss2[50] - pss2[48];
vec1 = pss2[51] - pss2[49];
dist = hypot(vec0, vec1);
edge2[51].position = sf::Vector2f(pss2[50] + vec1 / dist * width / 2, pss2[51] - vec0 / dist * width / 2);
edge2[50].position = sf::Vector2f(pss2[50] - vec1 / dist * width / 2, pss2[51] + vec0 / dist * width / 2);
edge2[50].color = sf::Color::Black;
edge2[51].color = sf::Color::Black;
window.draw(edge2);
circ2.setRadius(width / 2);
circ2.setPosition(pss2[50] - width / 2, pss2[51] - width / 2);
window.draw(circ2);
// drawing tablet
if (!isMouse) {
window.draw(device);
}
// window.draw(message);
window.display();
}
return 0;
} | 28.01222 | 260 | 0.604551 | [
"vector"
] |
d71cb1ed0006e5fc5ef17d260c94569a40dc7a1c | 10,515 | cpp | C++ | vts-libs/vts/tileset/driver/httpfetcher.cpp | melowntech/vts-libs | ffbf889b6603a8f95d3c12a2602232ff9c5d2236 | [
"BSD-2-Clause"
] | 2 | 2020-04-20T01:44:46.000Z | 2021-01-15T06:54:51.000Z | externals/browser/externals/browser/externals/vts-libs/vts-libs/vts/tileset/driver/httpfetcher.cpp | HanochZhu/vts-browser-unity-plugin | 32a22d41e21b95fb015326f95e401d87756d0374 | [
"BSD-2-Clause"
] | 2 | 2020-01-29T16:30:49.000Z | 2020-06-03T15:21:29.000Z | externals/browser/externals/browser/externals/vts-libs/vts-libs/vts/tileset/driver/httpfetcher.cpp | HanochZhu/vts-browser-unity-plugin | 32a22d41e21b95fb015326f95e401d87756d0374 | [
"BSD-2-Clause"
] | 1 | 2019-09-25T05:10:07.000Z | 2019-09-25T05:10:07.000Z | /**
* Copyright (c) 2017 Melown Technologies SE
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <algorithm>
#include <iterator>
#include <future>
#include <boost/format.hpp>
#include <boost/iostreams/device/array.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <curl/curl.h>
#include "utility/uri.hpp"
#include "http/ondemandclient.hpp"
#include "http/error.hpp"
#include "../../../storage/error.hpp"
#include "../../../storage/sstreams.hpp"
#include "../../tileop.hpp"
#include "httpfetcher.hpp"
#include "runcallback.hpp"
namespace ba = boost::algorithm;
namespace vtslibs { namespace vts { namespace driver {
namespace {
const std::string ConfigName("tileset.conf");
const std::string ExtraConfigName("extra.conf");
const std::string TileIndexName("tileset.index");
const std::string RegistryName("tileset.registry");
const std::string filePath(File type)
{
switch (type) {
case File::config: return ConfigName;
case File::extraConfig: return ExtraConfigName;
case File::tileIndex: return TileIndexName;
case File::registry: return RegistryName;
default: break;
}
throw "unknown file type";
}
const std::string remotePath(const TileId &tileId, TileFile type
, unsigned int revision)
{
const char *ext([&]() -> const char*
{
switch (type) {
case TileFile::meta: return ".meta";
case TileFile::mesh: return ".rmesh";
case TileFile::atlas: return ".ratlas";
case TileFile::navtile: return ".rnavtile";
default: break;
}
throw "Unexpected TileFile value. Go fix your program.";
}());
return str(boost::format("%d-%d-%d%s?%d")
% tileId.lod % tileId.x % tileId.y % ext % revision);
}
std::string joinUrl(std::string url, const std::string &filename)
{
if (!url.empty() && (url.back() != '/')) {
url.push_back('/');
}
url.append(filename);
return url;
}
http::OnDemandClient sharedClient;
utility::ResourceFetcher& getFetcher(const OpenOptions &options) {
if (const auto &fetcher = options.resourceFetcher()) {
return *fetcher;
}
return sharedClient.fetcher();
}
IStream::pointer fetchAsStream(const std::string &rootUrl
, const std::string &filename
, const char *contentType
, const OpenOptions &options
, bool noSuchFile)
{
const auto &fetcher(getFetcher(options));
const std::string url(joinUrl(rootUrl, filename));
auto tryFetch([&](unsigned long delay) -> IStream::pointer
{
auto q(fetcher.perform
(utility::ResourceFetcher::Query(url)
.timeout(options.ioWait()).delay(delay)));
if (q.ec()) {
if (q.check(make_error_code(utility::HttpCode::NotFound))) {
if (noSuchFile) {
LOGTHROW(err2, storage::NoSuchFile)
<< "File at URL <" << url << "> doesn't exist.";
}
return {};
}
LOGTHROW(err1, storage::IOError)
<< "Failed to download tile data from <"
<< url << ">: Unexpected HTTP status code: <"
<< q.ec() << ">.";
}
try {
auto body(q.moveOut());
return storage::memIStream(contentType, std::move(body.data)
, body.lastModified, url);
} catch (const http::Error &e) {
LOGTHROW(err1, storage::IOError)
<< "Failed to download tile data from <"
<< url << ">: Unexpected error code <"
<< e.what() << ">.";
}
return {};
});
unsigned long delay(0);
for (auto tries(options.ioRetries()); tries; (tries > 0) ? --tries : 0) {
try {
return tryFetch(delay);
} catch (const storage::IOError &e) {
LOG(warn2) << "Failed to fetch file from <" << url
<< ">; retrying in " << options.ioRetryDelay()
<< " ms.";
delay = options.ioRetryDelay();
}
}
return tryFetch(delay);
}
class AsyncFetcher
: public std::enable_shared_from_this<AsyncFetcher>
{
public:
AsyncFetcher(const std::string &url, const char *contentType
, const OpenOptions &options, const InputCallback &cb
, const IStream::pointer *notFound)
: fetcher_(getFetcher(options))
, url_(url), contentType_(contentType)
, cb_(cb), notFound_(notFound)
, ioWait_(options.ioWait())
, ioRetryDelay_(options.ioRetryDelay())
, triesLeft_(options.ioRetries())
{}
void run(unsigned long delay = 0);
private:
typedef utility::ResourceFetcher::Query Query;
typedef utility::ResourceFetcher::MultiQuery MultiQuery;
void queryDone(MultiQuery &&query);
utility::ResourceFetcher &fetcher_;
const std::string url_;
const char *contentType_;
InputCallback cb_;
const IStream::pointer *notFound_;
const long ioWait_;
const unsigned long ioRetryDelay_;
int triesLeft_;
};
void AsyncFetcher::run(unsigned long delay)
{
fetcher_.perform(Query(url_).timeout(ioWait_).delay(delay)
, std::bind(&AsyncFetcher::queryDone
, shared_from_this()
, std::placeholders::_1));
}
void AsyncFetcher::queryDone(MultiQuery &&mq)
{
auto &q(mq.front());
try {
if (q.ec()) {
if (q.check(make_error_code(utility::HttpCode::NotFound))) {
if (notFound_) {
return runCallback([&]() { return *notFound_; }, cb_);
}
LOGTHROW(err2, storage::NoSuchFile)
<< "File at URL <" << url_ << "> doesn't exist.";
}
LOGTHROW(err1, storage::IOError)
<< "Failed to download tile data from <"
<< url_ << ">: Unexpected HTTP status code: <"
<< q.ec() << ">.";
}
try {
auto body(q.moveOut());
return runCallback([&]()
{
return storage::memIStream(contentType_, std::move(body.data)
, body.lastModified, url_);
}, cb_);
} catch (const http::Error &e) {
LOGTHROW(err1, storage::IOError)
<< "Failed to download tile data from <"
<< url_ << ">: Unexpected error code <"
<< e.what() << ">.";
}
} catch (...) {
// we do not touch negative number of tries, otherwise decrement
if (triesLeft_ > 0) { --triesLeft_; }
if (!triesLeft_) {
// no try left -> forward error
return runCallback([&]()
{
return std::current_exception();
}, cb_);
}
}
// failed, restart
LOG(warn2) << "Failed to fetch file from <" << url_
<< ">; retrying in " << ioRetryDelay_ << " ms.";
run(ioRetryDelay_);
}
std::string fixUrl(const std::string &input, const OpenOptions &options)
{
utility::Uri uri(input);
if (!uri.absolute()) {
LOGTHROW(err2, storage::IOError)
<< "Uri <" << input << "> is not absolute uri.";
}
const auto &cnames(options.cnames());
if (!uri.scheme().empty() && cnames.empty()) {
// nothing to be changed, return as-is
return input;
}
// something has to be changed
// no scheme, both http and https should work, force http
if (uri.scheme().empty()) {
uri.scheme("http");
}
if (!cnames.empty()) {
// apply cnames, case-insensitive way
for (const auto &item : cnames) {
if (ba::iequals(uri.host(), item.first)) {
uri.host(item.second);
break;
}
}
}
return str(uri);
}
} // namespace
HttpFetcher::HttpFetcher(const std::string &rootUrl
, const OpenOptions &options)
: rootUrl_(fixUrl(rootUrl, options))
, options_(options)
{
LOG(info1) << "Using URI: <" << rootUrl_ << ">.";
}
IStream::pointer HttpFetcher::input(File type, bool noSuchFile)
const
{
return fetchAsStream(rootUrl_, filePath(type), contentType(type), options_
, noSuchFile);
}
IStream::pointer HttpFetcher::input(const TileId &tileId, TileFile type
, unsigned int revision, bool noSuchFile)
const
{
return fetchAsStream(rootUrl_, remotePath(tileId, type, revision)
, contentType(type), options_, noSuchFile);
}
void HttpFetcher::input(const TileId &tileId, TileFile type
, unsigned int revision
, const InputCallback &cb
, const IStream::pointer *notFound) const
{
std::make_shared<AsyncFetcher>
(joinUrl(rootUrl_, remotePath(tileId, type, revision))
, contentType(type), options_, cb, notFound)->run();
}
} } } // namespace vtslibs::vts::driver
| 31.960486 | 78 | 0.576034 | [
"mesh"
] |
d71d24d9f22e3aa25fd88896bfc8efd8e6c9f2db | 10,621 | cpp | C++ | utils/logging/operations.cpp | racktopsystems/kyua | 1929dccc5cda71cddda71485094822d3c3862902 | [
"BSD-3-Clause"
] | null | null | null | utils/logging/operations.cpp | racktopsystems/kyua | 1929dccc5cda71cddda71485094822d3c3862902 | [
"BSD-3-Clause"
] | null | null | null | utils/logging/operations.cpp | racktopsystems/kyua | 1929dccc5cda71cddda71485094822d3c3862902 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2011 The Kyua Authors.
// 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 Google Inc. nor the names of its contributors
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "utils/logging/operations.hpp"
extern "C" {
#include <unistd.h>
}
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
#include "utils/datetime.hpp"
#include "utils/format/macros.hpp"
#include "utils/fs/path.hpp"
#include "utils/optional.ipp"
#include "utils/sanity.hpp"
#include "utils/stream.hpp"
namespace datetime = utils::datetime;
namespace fs = utils::fs;
namespace logging = utils::logging;
using utils::none;
using utils::optional;
/// The general idea for the application-wide logging goes like this:
///
/// 1. The application starts. Logging is initialized to capture _all_ log
/// messages into memory regardless of their level by issuing a call to the
/// set_inmemory() function.
///
/// 2. The application offers the user a way to select the logging level and a
/// file into which to store the log.
///
/// 3. The application calls set_persistency providing a new log level and a log
/// file. This must be done as early as possible, to minimize the chances of an
/// early crash not capturing any logs.
///
/// 4. At this point, any log messages stored into memory are flushed to disk
/// respecting the provided log level.
///
/// 5. The internal state of the logging module is updated to only capture
/// messages that are of the provided log level (or below) and is configured to
/// directly send messages to disk.
///
/// 6. The user may choose to call set_inmemory() again at a later stage, which
/// will cause the log to be flushed and messages to be recorded in memory
/// again. This is useful in case the logs are being sent to either stdout or
/// stderr and the process forks and wants to keep those child channels
/// unpolluted.
///
/// The call to set_inmemory() should only be performed by the user-facing
/// application. Tests should skip this call so that the logging messages go to
/// stderr by default, thus generating a useful log to debug the tests.
namespace {
/// Constant string to strftime to format timestamps.
static const char* timestamp_format = "%Y%m%d-%H%M%S";
/// Mutable global state.
struct global_state {
/// Current log level.
logging::level log_level;
/// Indicates whether set_persistency() will be called automatically or not.
bool auto_set_persistency;
/// First time recorded by the logging module.
optional< datetime::timestamp > first_timestamp;
/// In-memory record of log entries before persistency is enabled.
std::vector< std::pair< logging::level, std::string > > backlog;
/// Stream to the currently open log file.
std::auto_ptr< std::ostream > logfile;
global_state() :
log_level(logging::level_debug),
auto_set_persistency(true)
{
}
};
/// Single instance of the mutable global state.
///
/// Note that this is a raw pointer that we intentionally leak. We must do
/// this, instead of making all of the singleton's members static values,
/// because we want other destructors in the program to be able to log critical
/// conditions. If we use complex types in this translation unit, they may be
/// destroyed before the logging methods in the destructors get a chance to run
/// thus resulting in a premature crash. By using a plain pointer, we ensure
/// this state never gets cleaned up.
static struct global_state* globals_singleton = NULL;
/// Gets the singleton instance of global_state.
///
/// \return A pointer to the unique global_state instance.
static struct global_state*
get_globals(void)
{
if (globals_singleton == NULL) {
globals_singleton = new global_state();
}
return globals_singleton;
}
/// Converts a level to a printable character.
///
/// \param level The level to convert.
///
/// \return The printable character, to be used in log messages.
static char
level_to_char(const logging::level level)
{
switch (level) {
case logging::level_error: return 'E';
case logging::level_warning: return 'W';
case logging::level_info: return 'I';
case logging::level_debug: return 'D';
default: UNREACHABLE;
}
}
} // anonymous namespace
/// Generates a standard log name.
///
/// This always adds the same timestamp to the log name for a particular run.
/// Also, the timestamp added to the file name corresponds to the first
/// timestamp recorded by the module; it does not necessarily contain the
/// current value of "now".
///
/// \param logdir The path to the directory in which to place the log.
/// \param progname The name of the program that is generating the log.
fs::path
logging::generate_log_name(const fs::path& logdir, const std::string& progname)
{
struct global_state* globals = get_globals();
if (!globals->first_timestamp)
globals->first_timestamp = datetime::timestamp::now();
// Update kyua(1) if you change the name format.
return logdir / (F("%s.%s.log") % progname %
globals->first_timestamp.get().strftime(timestamp_format));
}
/// Logs an entry to the log file.
///
/// If the log is not yet set to persistent mode, the entry is recorded in the
/// in-memory backlog. Otherwise, it is just written to disk.
///
/// \param message_level The level of the entry.
/// \param file The file from which the log message is generated.
/// \param line The line from which the log message is generated.
/// \param user_message The raw message to store.
void
logging::log(const level message_level, const char* file, const int line,
const std::string& user_message)
{
struct global_state* globals = get_globals();
const datetime::timestamp now = datetime::timestamp::now();
if (!globals->first_timestamp)
globals->first_timestamp = now;
if (globals->auto_set_persistency) {
// These values are hardcoded here for testing purposes. The
// application should call set_inmemory() by itself during
// initialization to avoid this, so that it has explicit control on how
// the call to set_persistency() happens.
set_persistency("debug", fs::path("/dev/stderr"));
globals->auto_set_persistency = false;
}
if (message_level > globals->log_level)
return;
// Update doc/troubleshooting.texi if you change the log format.
const std::string message = F("%s %s %s %s:%s: %s") %
now.strftime(timestamp_format) % level_to_char(message_level) %
::getpid() % file % line % user_message;
if (globals->logfile.get() == NULL)
globals->backlog.push_back(std::make_pair(message_level, message));
else {
INV(globals->backlog.empty());
(*globals->logfile) << message << '\n';
globals->logfile->flush();
}
}
/// Sets the logging to record messages in memory for later flushing.
///
/// Can be called after set_persistency to flush logs and set recording to be
/// in-memory again.
void
logging::set_inmemory(void)
{
struct global_state* globals = get_globals();
globals->auto_set_persistency = false;
if (globals->logfile.get() != NULL) {
INV(globals->backlog.empty());
globals->logfile->flush();
globals->logfile.reset(NULL);
}
}
/// Makes the log persistent.
///
/// Calling this function flushes the in-memory log, if any, to disk and sets
/// the logging module to send log entries to disk from this point onwards.
/// There is no way back, and the caller program should execute this function as
/// early as possible to ensure that a crash at startup does not discard too
/// many useful log entries.
///
/// Any log entries above the provided new_level are discarded.
///
/// \param new_level The new log level.
/// \param path The file to write the logs to.
///
/// \throw std::range_error If the given log level is invalid.
/// \throw std::runtime_error If the given file cannot be created.
void
logging::set_persistency(const std::string& new_level, const fs::path& path)
{
struct global_state* globals = get_globals();
globals->auto_set_persistency = false;
PRE(globals->logfile.get() == NULL);
// Update doc/troubleshooting.info if you change the log levels.
if (new_level == "debug")
globals->log_level = level_debug;
else if (new_level == "error")
globals->log_level = level_error;
else if (new_level == "info")
globals->log_level = level_info;
else if (new_level == "warning")
globals->log_level = level_warning;
else
throw std::range_error(F("Unrecognized log level '%s'") % new_level);
try {
globals->logfile = utils::open_ostream(path);
} catch (const std::runtime_error& unused_error) {
throw std::runtime_error(F("Failed to create log file %s") % path);
}
for (std::vector< std::pair< logging::level, std::string > >::const_iterator
iter = globals->backlog.begin(); iter != globals->backlog.end();
++iter) {
if ((*iter).first <= globals->log_level)
(*globals->logfile) << (*iter).second << '\n';
}
globals->logfile->flush();
globals->backlog.clear();
}
| 35.285714 | 80 | 0.699934 | [
"vector"
] |
d71d85c733a556dfaec4705e150952364fb26cc4 | 12,296 | cpp | C++ | src/gui/main_window.cpp | evopen/blackness | d0187d17d5fee01a754fd3bc19353a53caacc1b0 | [
"MIT"
] | 2 | 2020-04-26T12:35:30.000Z | 2021-07-27T06:50:59.000Z | src/gui/main_window.cpp | evopen/blackness | d0187d17d5fee01a754fd3bc19353a53caacc1b0 | [
"MIT"
] | 5 | 2020-04-27T00:28:17.000Z | 2020-04-27T17:56:50.000Z | src/gui/main_window.cpp | evopen/blackness | d0187d17d5fee01a754fd3bc19353a53caacc1b0 | [
"MIT"
] | null | null | null | #include "pch.h"
#include "image_generator.h"
#include "main_window.h"
#include "ui_main_window.h"
MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent), ui_(new Ui::MainWindow)
{
img_generator_.reset(new ImageGenerator());
vid_generator_.reset(new VideoGenerator());
vid_generator_->SetImageGenerator(img_generator_);
ui_->setupUi(this);
SetupUI();
SetupAction();
}
void MainWindow::BlackholeCheckboxUpdate()
{
if (!ui_->blackhole_checkbox->isChecked())
{
ui_->accretion_disk_checkbox->setEnabled(false);
ui_->disk_browser_lineedit->setEnabled(false);
ui_->disk_browser_button->setEnabled(false);
}
else
{
ui_->accretion_disk_checkbox->setEnabled(true);
ui_->disk_browser_lineedit->setEnabled(true);
ui_->disk_browser_button->setEnabled(true);
}
}
void MainWindow::BloomCheckboxUpdate()
{
if (img_generator_->IsRendering())
return;
if (ui_->bloom_checkbox->isChecked())
{
img_generator_->Bloom();
img_ = img_generator_->ResultBuffer();
}
else
{
img_ = img_generator_->ColorBuffer();
}
pixmap_item_->setPixmap(QPixmap::fromImage(
QImage(img_->data, img_->size().width, img_->size().height, QImage::Format_RGB888).rgbSwapped()));
}
void MainWindow::AccretionDiskCheckboxUpdate()
{
if (!ui_->accretion_disk_checkbox->isChecked())
{
ui_->disk_browser_lineedit->setEnabled(false);
ui_->disk_browser_button->setEnabled(false);
ui_->disk_radius_widget->setEnabled(false);
}
else
{
ui_->disk_browser_lineedit->setEnabled(true);
ui_->disk_browser_button->setEnabled(true);
ui_->disk_radius_widget->setEnabled(true);
}
}
void MainWindow::SelectSkyboxFolder()
{
QString directory =
QFileDialog::getExistingDirectory(this, tr("Select Skybox Folder"), QDir::currentPath() + "resources/skybox");
if (!directory.isEmpty())
{
ui_->skybox_path_lineedit->setText(directory);
skybox_need_load_ = true;
}
}
void MainWindow::SelectDiskTexture()
{
QString directory =
QFileDialog::getOpenFileName(this, tr("Select Disk Texture"), QDir::currentPath() + "resources/disk");
if (!directory.isEmpty())
{
ui_->disk_browser_lineedit->setText(directory);
}
}
void MainWindow::Abort()
{
img_generator_->Abort();
vid_generator_->Abort();
rendering_ = false;
}
void MainWindow::RenderImage()
{
uint32_t width = ui_->width_lineedit->text().toInt();
uint32_t height = ui_->height_lineedit->text().toInt();
int samples = ui_->samples_box->currentText().toInt();
std::filesystem::path skybox_folder_path(ui_->skybox_path_lineedit->text().toStdString());
glm::dvec3 camera_pos(ui_->cam_pox_x_lineedit->text().toDouble(), ui_->cam_pox_y_lineedit->text().toDouble(),
ui_->cam_pox_z_lineedit->text().toDouble());
glm::dvec3 camera_lookat(ui_->cam_lookat_x_lineedit->text().toDouble(),
ui_->cam_lookat_y_lineedit->text().toDouble(), ui_->cam_lookat_z_lineedit->text().toDouble());
Camera camera(camera_pos, camera_lookat);
if (skybox_need_load_)
{
img_generator_->LoadSkybox(skybox_folder_path);
skybox_need_load_ = false;
}
img_generator_->SetCamera(camera);
img_generator_->SetSamples(samples);
img_generator_->SetSize(width, height);
img_ = img_generator_->ColorBuffer();
std::shared_ptr<Blackhole> blackhole;
if (ui_->blackhole_checkbox->isChecked())
{
double disk_inner, disk_outer;
if (ui_->accretion_disk_checkbox->isChecked())
{
disk_inner = ui_->disk_inner_lineedit->text().toDouble();
disk_outer = ui_->disk_outer_lineedit->text().toDouble();
}
else
{
disk_inner = 1;
disk_outer = 1;
}
std::filesystem::path disk_texture_path = ui_->disk_browser_lineedit->text().toStdString();
blackhole = std::make_shared<Blackhole>(glm::dvec3(0, 0, 0), disk_inner, disk_outer, disk_texture_path);
img_generator_->SetBlackhole(*blackhole);
}
else
{
img_generator_->RemoveBlackhole();
}
img_generator_->SetThreads(ui_->threads_box->currentText().toInt());
QImage::Format format = QImage::Format_RGB888;
std::atomic<bool> finished = false;
auto generate_thread = std::thread([&] {
img_generator_->Generate();
finished = true;
});
scene_->setSceneRect(0, 0, img_->size().width, img_->size().height);
while (!finished)
{
std::this_thread::sleep_for(0.1s);
pixmap_item_->setPixmap(
QPixmap::fromImage(QImage(img_->data, img_->size().width, img_->size().height, format).rgbSwapped()));
ui_->graphicsView->update();
scene_->update();
ui_->graphicsView->fitInView(pixmap_item_, Qt::KeepAspectRatio);
qApp->processEvents();
}
generate_thread.join();
pixmap_item_->setPixmap(
QPixmap::fromImage(QImage(img_->data, img_->size().width, img_->size().height, format).rgbSwapped()));
}
void MainWindow::RenderVideo()
{
uint32_t width = ui_->width_lineedit->text().toInt();
uint32_t height = ui_->height_lineedit->text().toInt();
int samples = ui_->samples_box->currentText().toInt();
std::filesystem::path skybox_folder_path(ui_->skybox_path_lineedit->text().toStdString());
Camera camera;
if (skybox_need_load_)
{
img_generator_->LoadSkybox(skybox_folder_path);
skybox_need_load_ = false;
}
img_generator_->SetCamera(camera);
img_generator_->SetSamples(samples);
img_generator_->SetSize(width, height);
img_ = img_generator_->ColorBuffer();
std::shared_ptr<Blackhole> blackhole;
if (ui_->blackhole_checkbox->isChecked())
{
double disk_inner, disk_outer;
if (ui_->accretion_disk_checkbox->isChecked())
{
disk_inner = ui_->disk_inner_lineedit->text().toDouble();
disk_outer = ui_->disk_outer_lineedit->text().toDouble();
}
else
{
disk_inner = 1;
disk_outer = 1;
}
std::filesystem::path disk_texture_path = ui_->disk_browser_lineedit->text().toStdString();
blackhole = std::make_shared<Blackhole>(glm::dvec3(0, 0, 0), disk_inner, disk_outer, disk_texture_path);
img_generator_->SetBlackhole(*blackhole);
}
else
{
img_generator_->RemoveBlackhole();
}
img_generator_->SetThreads(ui_->threads_box->currentText().toInt());
QImage::Format format = QImage::Format_RGB888;
std::atomic<bool> finished = false;
std::filesystem::path position_file_path(ui_->pos_browser_lineedit->text().toStdString());
vid_generator_->LoadPositions(position_file_path);
vid_generator_->SetBloom(ui_->bloom_checkbox->isChecked());
vid_generator_->SetOutputFilePath("video.mp4");
auto generate_thread = std::thread([&] {
vid_generator_->GenerateAndSave();
finished = true;
});
scene_->setSceneRect(0, 0, img_->size().width, img_->size().height);
while (!finished)
{
std::this_thread::sleep_for(0.1s);
pixmap_item_->setPixmap(
QPixmap::fromImage(QImage(img_->data, img_->size().width, img_->size().height, format).rgbSwapped()));
ui_->graphicsView->update();
scene_->update();
ui_->graphicsView->fitInView(pixmap_item_, Qt::KeepAspectRatio);
qApp->processEvents();
}
generate_thread.join();
pixmap_item_->setPixmap(
QPixmap::fromImage(QImage(img_->data, img_->size().width, img_->size().height, format).rgbSwapped()));
}
void MainWindow::RenderOrAbort()
{
ui_->render_button->setText("Abort");
if (rendering_)
{
Abort();
ui_->render_button->setText("Render");
return;
}
mode_ = ui_->image_mode_button->isChecked() ? kImageMode : kVideoMode;
auto start_time = std::chrono::high_resolution_clock::now();
switch (mode_)
{
case kImageMode:
rendering_ = true;
RenderImage();
break;
case kVideoMode:
rendering_ = true;
RenderVideo();
break;
default:
throw std::runtime_error("unknown mode");
break;
}
auto end_time = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::seconds>(end_time - start_time).count();
statusBar()->showMessage("Render Time: " + QString::number(duration) + " seconds");
ui_->render_button->setText("Render");
rendering_ = false;
}
void MainWindow::SetupUI()
{
QDoubleValidator* pos_validator = new QDoubleValidator(-10000, 10000, 2, this);
pos_validator->setNotation(QDoubleValidator::StandardNotation);
ui_->cam_pox_x_lineedit->setValidator(pos_validator);
ui_->cam_pox_y_lineedit->setValidator(pos_validator);
ui_->cam_pox_z_lineedit->setValidator(pos_validator);
ui_->cam_lookat_x_lineedit->setValidator(pos_validator);
ui_->cam_lookat_y_lineedit->setValidator(pos_validator);
ui_->cam_lookat_z_lineedit->setValidator(pos_validator);
ui_->width_lineedit->setValidator(new QIntValidator(1, 16384, this));
ui_->height_lineedit->setValidator(new QIntValidator(1, 16384, this));
scene_ = new QGraphicsScene();
pixmap_item_ = new QGraphicsPixmapItem();
scene_->addItem(pixmap_item_);
ui_->graphicsView->setScene(scene_);
}
void MainWindow::resizeEvent(QResizeEvent* event)
{
QMainWindow::resizeEvent(event);
// Your code here.
ui_->graphicsView->fitInView(pixmap_item_, Qt::KeepAspectRatio);
}
void MainWindow::WidthUpdate()
{
const QValidator* validator = ui_->width_lineedit->validator();
int pos = 0;
auto text = ui_->width_lineedit->text();
auto state = validator->validate(text, pos);
if (state != QValidator::Acceptable)
{
ui_->width_lineedit->setText(ui_->height_lineedit->text());
ui_->error_label->setText("Resolution ranges from 1 to 4096");
}
else
{
ui_->height_lineedit->setText(ui_->width_lineedit->text());
}
}
void MainWindow::SkyboxPathUpdate()
{
skybox_need_load_ = true;
}
void MainWindow::SaveToDisk()
{
QString filter = "PNG (*.png)";
QString directory = QFileDialog::getSaveFileName(this, tr("Save as"), QDir::currentPath(), filter, &filter);
if (ui_->bloom_checkbox->isChecked())
{
cv::imwrite(directory.toStdString(), *(img_generator_->ResultBuffer()));
}
else
{
cv::imwrite(directory.toStdString(), *(img_generator_->ColorBuffer()));
}
}
void MainWindow::SelectPositionFile()
{
QString directory =
QFileDialog::getOpenFileName(this, tr("Select Position file"), QDir::currentPath() + "resources/position");
if (!directory.isEmpty())
{
ui_->pos_browser_lineedit->setText(directory);
}
}
void MainWindow::SetupAction()
{
connect(ui_->skybox_browser_button, SIGNAL(clicked()), SLOT(SelectSkyboxFolder()));
connect(ui_->disk_browser_button, SIGNAL(clicked()), SLOT(SelectDiskTexture()));
connect(ui_->pos_browser_button, SIGNAL(clicked()), SLOT(SelectPositionFile()));
connect(ui_->render_button, SIGNAL(clicked()), SLOT(RenderOrAbort()));
connect(ui_->blackhole_checkbox, SIGNAL(stateChanged(int)), SLOT(BlackholeCheckboxUpdate()));
connect(ui_->accretion_disk_checkbox, SIGNAL(stateChanged(int)), SLOT(AccretionDiskCheckboxUpdate()));
connect(ui_->width_lineedit, SIGNAL(editingFinished()), SLOT(WidthUpdate()));
connect(ui_->bloom_checkbox, SIGNAL(stateChanged(int)), SLOT(BloomCheckboxUpdate()));
connect(ui_->skybox_path_lineedit, SIGNAL(editingFinished()), SLOT(SkyboxPathUpdate()));
connect(ui_->actionSave, SIGNAL(triggered()), SLOT(SaveToDisk()));
}
| 32.615385 | 119 | 0.643868 | [
"render"
] |
d71f5b3369866cdfa3d0b29ca3dec1f243b3f68a | 1,736 | cpp | C++ | Asteroids/Resources.cpp | kyranet/Asteroids | 9ec0ccadb28f9d7a6f3a2fa50c470e31dc80a643 | [
"MIT"
] | 1 | 2019-08-27T00:58:17.000Z | 2019-08-27T00:58:17.000Z | Asteroids/Resources.cpp | kyranet/Asteroids | 9ec0ccadb28f9d7a6f3a2fa50c470e31dc80a643 | [
"MIT"
] | null | null | null | Asteroids/Resources.cpp | kyranet/Asteroids | 9ec0ccadb28f9d7a6f3a2fa50c470e31dc80a643 | [
"MIT"
] | null | null | null | #include "Resources.h"
#include <tuple>
#include "sdl_includes.h"
vector<Resources::FontInfo> Resources::fonts_{
{ARIAL16, "../resources/fonts/ARIAL.ttf", 16},
{ARIAL24, "../resources/fonts/ARIAL.ttf", 24}};
vector<Resources::ImageInfo> Resources::images_{
{Blank, "../resources/images/blank.png"},
{TennisBall, "../resources/images/tennis_ball.png"},
{KeyBoardIcon, "../resources/images/keyboard.png"},
{MouseIcon, "../resources/images/mouse.png"},
{AIIcon, "../resources/images/ai.png"},
{SpaceShips, "../resources/images/spaceships.png"},
{Airplanes, "../resources/images/airplanes.png"},
{Star, "../resources/images/star.png"},
{Asteroid, "../resources/images/asteroid.png"},
{Badges, "../resources/images/badges.png"},
{WhiteRect, "../resources/images/whiterect.png"},
{BlackHole,"../resources/images/black-hole.png" }};
vector<Resources::TextMsgInfo> Resources::messages_{
{HelloWorld, "Hello World", {COLOR(0xaaffffff)}, ARIAL16},
{PressAnyKey, "Press Any Key ...", {COLOR(0xaaffbbff)}, ARIAL24},
{PressEnterToContinue,
"Press Enter to Continue",
{COLOR(0xaaffbbff)},
ARIAL24},
{GameOver, "Game Over", {COLOR(0xffffbbff)}, ARIAL24}};
vector<Resources::MusicInfo> Resources::musics_{
{Beat, "../resources/sound/beat.wav"},
{Cheer, "../resources/sound/cheer.wav"},
{Boooo, "../resources/sound/boooo.wav"},
{ImperialMarch, "../resources/sound/imperial_march.wav"}};
vector<Resources::SoundInfo> Resources::sounds_{
{Wall_Hit, "../resources/sound/wall_hit.wav"},
{Paddle_Hit, "../resources/sound/paddle_hit.wav"},
{GunShot, "../resources/sound/GunShot.wav"},
{Explosion, "../resources/sound/explosion.wav"}};
| 40.372093 | 69 | 0.666475 | [
"vector"
] |
d71f67a451dd7fe4d9b9d9694ededea1ee06cfea | 908 | cpp | C++ | cpp-leetcode/leetcode204-count-prims-sieveMethod_style2.cpp | yanglr/LeetCodeOJ | 27dd1e4a2442b707deae7921e0118752248bef5e | [
"MIT"
] | 45 | 2021-07-25T00:45:43.000Z | 2022-03-24T05:10:43.000Z | cpp-leetcode/leetcode204-count-prims-sieveMethod_style2.cpp | yanglr/LeetCodeOJ | 27dd1e4a2442b707deae7921e0118752248bef5e | [
"MIT"
] | null | null | null | cpp-leetcode/leetcode204-count-prims-sieveMethod_style2.cpp | yanglr/LeetCodeOJ | 27dd1e4a2442b707deae7921e0118752248bef5e | [
"MIT"
] | 15 | 2021-07-25T00:40:52.000Z | 2021-12-27T06:25:31.000Z | #include <algorithm>
#include <vector>
#include <cmath>
#include <iostream>
using namespace std;
class Solution {
public:
int countPrimes(int n) {
vector<int> isPrime(n, 1);
if(n < 2)
{
return 0;
}
else {
int count = 0;
for (int i = 2; i * i < n; i++)
{
if (isPrime[i])
{
for (int j = i; i * j < n; j++) // Use j to record times(倍数).
{
isPrime[i*j] = 0;
}
}
}
for (int i = 2; i < n; i++)
{
if (isPrime[i] == 1)
count++;
}
return count;
}
}
};
// Test
int main()
{
Solution sol;
auto result = sol.countPrimes(100156150);
cout << result << endl;
return 0;
} | 19.73913 | 82 | 0.362335 | [
"vector"
] |
d71f6981478360f6f930a77fd57bd12fe88a2000 | 3,224 | cc | C++ | libvis/src/libvis/test/point_cloud.cc | ulricheck/surfelmeshing | bacaf70a1877185af844b31597cb59d4cbed0722 | [
"BSD-3-Clause"
] | 1 | 2018-10-28T13:30:55.000Z | 2018-10-28T13:30:55.000Z | libvis/src/libvis/test/point_cloud.cc | ulricheck/surfelmeshing | bacaf70a1877185af844b31597cb59d4cbed0722 | [
"BSD-3-Clause"
] | null | null | null | libvis/src/libvis/test/point_cloud.cc | ulricheck/surfelmeshing | bacaf70a1877185af844b31597cb59d4cbed0722 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2018 ETH Zürich, Thomas Schöps
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <glog/logging.h>
#include <gtest/gtest.h>
#include "libvis/point_cloud.h"
using namespace vis;
// Tests that the bounds computation is correct.
TEST(PointCloud, ComputeMinMax) {
Point3fCloud cloud(4);
cloud[0] = Point3f(Vec3f(1, 2, 3));
cloud[1] = Point3f(Vec3f(2, 3, 4));
cloud[2] = Point3f(Vec3f(3, 4, 5));
cloud[3] = Point3f(Vec3f(4, 5, 6));
Vec3f min, max;
cloud.ComputeMinMax(&min, &max);
EXPECT_FLOAT_EQ(1, min.x());
EXPECT_FLOAT_EQ(2, min.y());
EXPECT_FLOAT_EQ(3, min.z());
EXPECT_FLOAT_EQ(4, max.x());
EXPECT_FLOAT_EQ(5, max.y());
EXPECT_FLOAT_EQ(6, max.z());
}
TEST(PointCloud, TransformSE3) {
Point3fCloud cloud(4);
cloud[0] = Point3f(Vec3f(1, 2, 3));
cloud[1] = Point3f(Vec3f(2, 3, 4));
cloud[2] = Point3f(Vec3f(3, 4, 5));
cloud[3] = Point3f(Vec3f(4, 5, 6));
SE3f transformation(
AngleAxisf(0.2f, Vec3f(1, 2, 3).normalized()).toRotationMatrix(),
Vec3f(5, 6, 7));
Point3fCloud expected_result(cloud.size());
for (usize i = 0; i < expected_result.size(); ++ i) {
expected_result[i] = Point3f(transformation * cloud[i].position());
}
Point3fCloud actual_result(cloud);
actual_result.Transform(transformation);
ASSERT_EQ(expected_result.size(), actual_result.size());
for (usize i = 0; i < expected_result.size(); ++ i) {
EXPECT_FLOAT_EQ(expected_result[i].position().x(),
actual_result[i].position().x());
EXPECT_FLOAT_EQ(expected_result[i].position().y(),
actual_result[i].position().y());
EXPECT_FLOAT_EQ(expected_result[i].position().z(),
actual_result[i].position().z());
}
}
| 37.929412 | 80 | 0.699442 | [
"transform"
] |
d7215ebee2cc1cdb0f71e9196ec907563369d2a7 | 6,037 | hpp | C++ | DemoApps/Vulkan/Bloom/source/RenderScene.hpp | alexvonduar/gtec-demo-framework | 6f8a7e429d0e15242ba64eb4cb41bfc2dd7dc749 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | DemoApps/Vulkan/Bloom/source/RenderScene.hpp | alexvonduar/gtec-demo-framework | 6f8a7e429d0e15242ba64eb4cb41bfc2dd7dc749 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | DemoApps/Vulkan/Bloom/source/RenderScene.hpp | alexvonduar/gtec-demo-framework | 6f8a7e429d0e15242ba64eb4cb41bfc2dd7dc749 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | #ifndef VULKAN_BLOOM_RENDERSCENE_HPP
#define VULKAN_BLOOM_RENDERSCENE_HPP
/****************************************************************************************************************************************************
* Copyright 2019 NXP
* 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 NXP. 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 <FslBase/Math/Vector3.hpp>
#include <FslBase/Math/Vector4.hpp>
#include <FslUtil/Vulkan1_0/Managed/VMBufferManager.hpp>
#include <FslUtil/Vulkan1_0/Managed/VMIndexBuffer.hpp>
#include <FslUtil/Vulkan1_0/Managed/VMVertexBuffer.hpp>
#include <FslUtil/Vulkan1_0/VUDevice.hpp>
#include <FslUtil/Vulkan1_0/VUDeviceQueueRecord.hpp>
#include <FslUtil/Vulkan1_0/VUTexture.hpp>
#include <RapidVulkan/DescriptorPool.hpp>
#include <RapidVulkan/DescriptorSetLayout.hpp>
#include <RapidVulkan/GraphicsPipeline.hpp>
#include <RapidVulkan/PipelineLayout.hpp>
#include <RapidVulkan/ShaderModule.hpp>
#include <Shared/Bloom/IScene.hpp>
#include <vector>
#include "IVulkanScene.hpp"
namespace Fsl
{
class RenderScene final : public IVulkanScene
{
//! Resources that are duplicated per command buffer to ensure that it wont be 'in-use' while we update it
struct FrameResources
{
Vulkan::VUBufferMemory UboBuffer;
VkDescriptorSet DescriptorSet{};
};
struct ModelMesh
{
Vulkan::VMVertexBuffer VertexBuffer;
Vulkan::VMIndexBuffer IndexBuffer;
std::array<VkVertexInputAttributeDescription, 4> VertexAttributeDescription;
VkVertexInputBindingDescription VertexInputBindingDescription{};
};
struct Resources
{
Vulkan::VUTexture Texture;
Vulkan::VUTexture TextureNormal;
Vulkan::VUTexture TextureSpecular;
RapidVulkan::ShaderModule VertShader;
RapidVulkan::ShaderModule FragShader;
ModelMesh Mesh;
RapidVulkan::DescriptorSetLayout SceneDescriptorSetLayout;
std::vector<FrameResources> SceneFrameResources;
RapidVulkan::PipelineLayout ScenePipelineLayout;
};
struct DependentResources
{
RapidVulkan::GraphicsPipeline Pipeline;
};
struct UBOData
{
Matrix MatWorldView;
Matrix MatWorldViewProjection;
Matrix NormalMatrix;
Vector4 LightDirection;
Vector4 LightColor;
Vector4 MatAmbient;
Vector4 MatSpecular;
float MatShininess{0};
UBOData(const Vector4& lightColor, const Vector4& matAmbient, const Vector4& matSpecular, const float matShininess)
: LightColor(lightColor)
, MatAmbient(matAmbient)
, MatSpecular(matSpecular)
, MatShininess(matShininess)
{
}
};
Resources m_resources;
DependentResources m_dependentResources;
Matrix m_matrixWorld;
Matrix m_matrixView;
Matrix m_matrixProjection;
Vector3 m_lightDirection;
UBOData m_uboData;
public:
RenderScene(const DemoAppConfig& config, const int32_t sceneId, const Vulkan::VUDevice& device, const Vulkan::VUDeviceQueueRecord& deviceQueue,
const std::shared_ptr<Vulkan::VMBufferManager>& bufferManager, const RapidVulkan::DescriptorPool& descriptorPool,
const uint32_t maxFrames);
~RenderScene() final;
void OnBuildResources(const VulkanBasic::BuildResourcesContext& context, const VkRenderPass hRenderPass) final;
void OnFreeResources() final;
void Update(const DemoTime& demoTime, const Matrix& cameraViewMatrix, const Matrix& cameraRotation, const Vector3& rotation,
const PxSize2D& windowSizePx) final;
void PreDraw(const uint32_t frameIndex, const VkCommandBuffer hCmdBuffer) final;
void Draw(const uint32_t frameIndex, const VkCommandBuffer hCmdBuffer) final;
private:
void PrepareShader(const VkDevice device, const std::shared_ptr<IContentManager>& contentManager, const bool useSpecMap, const bool useGlossMap,
const bool useNormalMap);
static RapidVulkan::GraphicsPipeline CreatePipeline(const RapidVulkan::PipelineLayout& pipelineLayout, const VkExtent2D& extent,
const VkShaderModule vertexShaderModule, const VkShaderModule fragmentShaderModule,
const ModelMesh& mesh, const VkRenderPass renderPass, const uint32_t subpass,
const bool cullEnabled);
};
}
#endif
| 40.790541 | 150 | 0.692728 | [
"mesh",
"vector"
] |
d721c00e494c6e3334ff4f3e2f69383670cf094c | 1,867 | hpp | C++ | include/encoders/sdc_sequence.hpp | jermp/pthash | f0a0fb929ecfe1d925d88bc9bf41f7b4eaf0516b | [
"MIT"
] | 52 | 2021-04-21T09:55:12.000Z | 2022-02-27T03:00:11.000Z | include/encoders/sdc_sequence.hpp | jermp/pthash | f0a0fb929ecfe1d925d88bc9bf41f7b4eaf0516b | [
"MIT"
] | null | null | null | include/encoders/sdc_sequence.hpp | jermp/pthash | f0a0fb929ecfe1d925d88bc9bf41f7b4eaf0516b | [
"MIT"
] | 3 | 2021-05-03T00:59:57.000Z | 2022-01-03T15:42:23.000Z | #pragma once
#include "bit_vector.hpp"
#include "ef_sequence.hpp"
namespace pthash {
struct sdc_sequence {
sdc_sequence() : m_size(0) {}
template <typename Iterator>
void build(Iterator begin, uint64_t n) {
m_size = n;
auto start = begin;
uint64_t bits = 0;
for (uint64_t i = 0; i < n; ++i, ++start) bits += std::floor(std::log2(*start + 1));
bit_vector_builder bvb_codewords(bits);
std::vector<uint64_t> lengths;
lengths.reserve(n + 1);
uint64_t pos = 0;
for (uint64_t i = 0; i < n; ++i, ++begin) {
auto v = *begin;
uint64_t len = std::floor(std::log2(v + 1));
assert(len <= 64);
uint64_t cw = v + 1 - (uint64_t(1) << len);
if (len > 0) bvb_codewords.set_bits(pos, cw, len);
lengths.push_back(pos);
pos += len;
}
assert(pos == bits);
lengths.push_back(pos);
bit_vector(&bvb_codewords).swap(m_codewords);
m_index.encode(lengths.data(), lengths.size());
}
inline uint64_t access(uint64_t i) const {
assert(i < size());
uint64_t pos = m_index.access(i);
uint64_t len = m_index.access(i + 1) - pos;
assert(len < 64);
uint64_t cw = m_codewords.get_bits(pos, len);
uint64_t value = cw + (uint64_t(1) << len) - 1;
return value;
}
uint64_t size() const {
return m_size;
}
uint64_t bytes() const {
return sizeof(m_size) + m_codewords.bytes() + m_index.num_bits() / 8;
}
template <typename Visitor>
void visit(Visitor& visitor) {
visitor.visit(m_size);
visitor.visit(m_codewords);
visitor.visit(m_index);
}
private:
uint64_t m_size;
bit_vector m_codewords;
ef_sequence<false> m_index;
};
} // namespace pthash | 27.865672 | 92 | 0.562935 | [
"vector"
] |
d724c6db866b6a0a951f1c18fbd5e5f66d701b56 | 1,013 | cpp | C++ | TWL/PopulateEmitters.cpp | tom1milman/Thomas-Was-Late | 5fc62a79b372eb06a7cd226593c5e54804d7085a | [
"MIT"
] | null | null | null | TWL/PopulateEmitters.cpp | tom1milman/Thomas-Was-Late | 5fc62a79b372eb06a7cd226593c5e54804d7085a | [
"MIT"
] | null | null | null | TWL/PopulateEmitters.cpp | tom1milman/Thomas-Was-Late | 5fc62a79b372eb06a7cd226593c5e54804d7085a | [
"MIT"
] | null | null | null | #include "Engine.h"
using namespace sf;
using namespace std;
//Goes over fire blocks, and adds them as emitters to the vector
//skips any fire block in radious of 6 tiles from each emitter
void Engine::populateEmitters(vector <Vector2f>& vSoundEmitters, int** arrayLevel)
{
//Empty vector
vSoundEmitters.empty();
//Keep track of previous emitter
FloatRect previousEmitter;
for (int x = 0; x < (int)m_LM.getLevelSize().x; x++)
{
for (int y = 0; y < (int)m_LM.getLevelSize().y; y++)
{
//if Fire block
if (arrayLevel[y][x] == 2)
{
int xTileSize = x * TILE_SIZE;
int yTileSize = y * TILE_SIZE;
//If not too close to previous emitter
if (!FloatRect(xTileSize, yTileSize, TILE_SIZE, TILE_SIZE).intersects(previousEmitter))
{
vSoundEmitters.push_back(Vector2f(xTileSize, yTileSize));
previousEmitter.left = xTileSize;
previousEmitter.top = yTileSize;
previousEmitter.width = TILE_SIZE * 6;
previousEmitter.height = TILE_SIZE * 6;
}
}
}
}
} | 25.325 | 91 | 0.681145 | [
"vector"
] |
d72713859fab5ae3d4652916ba05e440273cdd0a | 2,143 | cpp | C++ | src/TestXE/XETCommon/EditorControllerSystem.cpp | devxkh/FrankE | 72faca02759b54aaec842831f3c7a051e7cf5335 | [
"MIT"
] | 11 | 2017-01-17T15:02:25.000Z | 2020-11-27T16:54:42.000Z | src/TestXE/XETCommon/EditorControllerSystem.cpp | devxkh/FrankE | 72faca02759b54aaec842831f3c7a051e7cf5335 | [
"MIT"
] | 9 | 2016-10-23T20:15:38.000Z | 2018-02-06T11:23:17.000Z | src/TestXE/XETCommon/EditorControllerSystem.cpp | devxkh/FrankE | 72faca02759b54aaec842831f3c7a051e7cf5335 | [
"MIT"
] | 2 | 2019-08-29T10:23:51.000Z | 2020-04-03T06:08:34.000Z | #include "EditorControllerSystem.hpp"
#include <XEngine.hpp>
#include <ThirdParty/imgui/imgui.h>
#include <XERenderer/Editor/ImGuizmo.h>
#include <XEngine/Editor/SceneViewerUIState.hpp>
#include <memory>
namespace XET {
EditorControllerSystem::EditorControllerSystem(XE::XEngine& engine)
: m_engine(engine)
{
}
EditorControllerSystem::~EditorControllerSystem()
{
}
void EditorControllerSystem::update(entityx::EntityManager &es, entityx::EventManager &events, entityx::TimeDelta dt)
{
if (m_engine.getGraphicsManager()._isRenderThreadFinished)
{
//push scene data into rendererthread
entityx::ComponentHandle<XE::EditorComponent> tmpEditorComponent;
for (entityx::Entity entity : es.entities_with_components(tmpEditorComponent)) {
XE::BodyComponent body = *entity.getComponent<XE::BodyComponent>();
XE::EditorComponent editorComponent = *tmpEditorComponent.get();
if (!body.isDirty())
continue;
m_engine.getGraphicsManager().getIntoRendererQueue().push([this, body, editorComponent]()
{
auto _t_uistate = static_cast<XE::SceneViewerUIState*>(m_engine.getGraphicsManager().getGUIRenderer()._t_EditorUIRenderer->getUIState(XE::EUSID::SceneHierarchy));
//body id already displayed?
for each (auto& displayedEntity in _t_uistate->_t_displayedEntities)
{
//found
if (displayedEntity->id == editorComponent.id)
{
auto displayBody = static_cast<XE::DisplayBody*>(displayedEntity->displayInformation.get());
displayBody->position = body.getPosition();
displayBody->name = editorComponent.name;
return;
}
}
//not found -> add to vector
std::unique_ptr<XE::EntityDebug> entityDebug(new XE::EntityDebug());
entityDebug->id = editorComponent.id;
std::unique_ptr<XE::DisplayBody> displayBody(new XE::DisplayBody());
displayBody->position = body.getPosition();
displayBody->name = editorComponent.name;
entityDebug->displayInformation = std::move(displayBody);
_t_uistate->_t_displayedEntities.push_back(std::move(entityDebug));
});
}
}
}
} // namespace XE
| 28.959459 | 167 | 0.716752 | [
"vector"
] |
c017ea5ab5aea682cfd23436a46dc0419c9fe15b | 8,608 | cpp | C++ | Vic2ToHoI4/Source/Configuration.cpp | Thinking-waffle/Vic2ToHoI4 | 127d6528aef1eb2e5e189da9153806bb2162d72b | [
"MIT"
] | 1 | 2021-01-03T21:11:33.000Z | 2021-01-03T21:11:33.000Z | Vic2ToHoI4/Source/Configuration.cpp | Thinking-waffle/Vic2ToHoI4 | 127d6528aef1eb2e5e189da9153806bb2162d72b | [
"MIT"
] | null | null | null | Vic2ToHoI4/Source/Configuration.cpp | Thinking-waffle/Vic2ToHoI4 | 127d6528aef1eb2e5e189da9153806bb2162d72b | [
"MIT"
] | null | null | null | #include "Configuration.h"
#include "CommonFunctions.h"
#include "CommonRegexes.h"
#include "Log.h"
#include "OSCompatibilityLayer.h"
#include "ParserHelpers.h"
#include "V2World/Mods/ModFactory.h"
#include <fstream>
#include <vector>
Configuration::Factory::Factory()
{
registerKeyword("SaveGame", [this](std::istream& theStream) {
const commonItems::singleString filenameString(theStream);
configuration->inputFile = filenameString.getString();
const auto length = configuration->inputFile.find_last_of('.');
if ((length == std::string::npos) ||
(".v2" != configuration->inputFile.substr(length, configuration->inputFile.length())))
{
throw std::invalid_argument("The save was not a Vic2 save. Choose a save ending in '.v2' and convert again.");
}
Log(LogLevel::Info) << "\tVic2 save is " << configuration->inputFile;
});
registerKeyword("HoI4directory", [this](std::istream& theStream) {
configuration->HoI4Path = commonItems::singleString{theStream}.getString();
if (configuration->HoI4Path.empty() || !commonItems::DoesFolderExist(configuration->HoI4Path))
{
throw std::runtime_error("No HoI4 path was specified in configuration.txt, or the path was invalid");
}
if (!commonItems::DoesFileExist(configuration->HoI4Path + "/hoi4.exe") &&
!commonItems::DoesFileExist(configuration->HoI4Path + "/hoi4"))
{
throw std::runtime_error("The HoI4 path specified in configuration.txt does not contain HoI4");
}
Log(LogLevel::Info) << "\tHoI4 path install path is " << configuration->HoI4Path;
});
registerKeyword("Vic2directory", [this](std::istream& theStream) {
configuration->Vic2Path = commonItems::singleString{theStream}.getString();
if (configuration->Vic2Path.empty() || !commonItems::DoesFolderExist(configuration->Vic2Path))
{
throw std::runtime_error("No Victoria 2 path was specified in configuration.txt, or the path was invalid");
}
if (!commonItems::DoesFileExist(configuration->Vic2Path + "/v2game.exe") &&
!commonItems::DoesFileExist(configuration->Vic2Path + "/v2game") &&
!commonItems::DoesFolderExist(configuration->Vic2Path + "/Victoria 2 - Heart Of Darkness.app") &&
!commonItems::DoesFolderExist(configuration->Vic2Path + "/../../MacOS"))
{
throw std::runtime_error("The Victoria 2 path specified in configuration.txt does not contain Victoria 2");
}
Log(LogLevel::Info) << "\tVictoria 2 install path is " << configuration->Vic2Path;
});
registerKeyword("Vic2ModPath", [this](std::istream& theStream) {
configuration->Vic2ModPath = commonItems::singleString{theStream}.getString();
if (configuration->Vic2ModPath.empty() || !commonItems::DoesFolderExist(configuration->Vic2ModPath))
{
throw std::runtime_error("No Victoria 2 mod path was specified in configuration.txt, or the path was invalid");
}
Log(LogLevel::Info) << "\tVictoria 2 mod path is " << configuration->Vic2ModPath;
});
registerKeyword("selectedMods", [this](std::istream& theStream) {
const auto& theList = commonItems::stringList{theStream}.getStrings();
modFileNames.insert(theList.begin(), theList.end());
Log(LogLevel::Info) << modFileNames.size() << " mods selected by configuration. Deselected mods will be ignored.";
});
registerKeyword("force_multiplier", [this](std::istream& theStream) {
const commonItems::singleDouble factorValue(theStream);
configuration->forceMultiplier = std::clamp(static_cast<float>(factorValue.getDouble()), 0.01f, 100.0f);
Log(LogLevel::Info) << "\tForce multiplier: " << configuration->forceMultiplier;
});
registerKeyword("manpower_factor", [this](std::istream& theStream) {
const commonItems::singleDouble factorValue(theStream);
configuration->manpowerFactor = std::clamp(static_cast<float>(factorValue.getDouble()), 0.01f, 10.0f);
Log(LogLevel::Info) << "\tManpower factor: " << configuration->manpowerFactor;
});
registerKeyword("industrial_shape_factor", [this](std::istream& theStream) {
const commonItems::singleDouble factorValue(theStream);
configuration->industrialShapeFactor = std::clamp(static_cast<float>(factorValue.getDouble()), 0.0f, 1.0f);
Log(LogLevel::Info) << "\tIndustrial shape factor: " << configuration->industrialShapeFactor;
});
registerKeyword("factory_factor", [this](std::istream& theStream) {
const commonItems::singleDouble factorValue(theStream);
configuration->factoryFactor = std::clamp(static_cast<float>(factorValue.getDouble()), 0.0f, 1.0f);
Log(LogLevel::Info) << "\tFactory factor: " << configuration->factoryFactor;
});
registerKeyword("ideologies", [this](std::istream& theStream) {
const commonItems::singleString ideologiesOptionString(theStream);
if (ideologiesOptionString.getString() == "keep_default")
{
configuration->ideologiesOptions = ideologyOptions::keep_default;
Log(LogLevel::Info) << "\tKeeping default ideologies";
}
else if (ideologiesOptionString.getString() == "keep_all")
{
configuration->ideologiesOptions = ideologyOptions::keep_all;
Log(LogLevel::Info) << "\tKeeping all ideologies";
}
else if (ideologiesOptionString.getString() == "specify")
{
configuration->ideologiesOptions = ideologyOptions::specified;
Log(LogLevel::Info) << "\tKeeping specified ideologies";
}
else // (ideologiesOptionString.getString() == "keep_major")
{
configuration->ideologiesOptions = ideologyOptions::keep_major;
Log(LogLevel::Info) << "\tKeeping major ideologies";
}
});
registerKeyword("ideologies_choice", [this](std::istream& theStream) {
const commonItems::stringList choiceStrings(theStream);
for (const auto& choice: choiceStrings.getStrings())
{
configuration->specifiedIdeologies.push_back(choice);
Log(LogLevel::Info) << "\tSpecified " << choice;
}
});
registerKeyword("debug", [this](std::istream& theStream) {
const commonItems::singleString debugValue(theStream);
if (debugValue.getString() == "yes")
{
configuration->debug = true;
Log(LogLevel::Debug) << "\tDebug mode activated";
}
else
{
configuration->debug = false;
Log(LogLevel::Debug) << "\tDebug mode deactivated";
}
});
registerKeyword("remove_cores", [this](std::istream& theStream) {
const commonItems::singleString removeCoresValue(theStream);
if (removeCoresValue.getString() == "no")
{
configuration->removeCores = false;
Log(LogLevel::Info) << "\tDisabling remove cores";
}
else
{
configuration->removeCores = true;
Log(LogLevel::Info) << "\tEnabling remove cores";
}
});
registerKeyword("create_factions", [this](std::istream& theStream) {
const commonItems::singleString createFactionsValue(theStream);
if (createFactionsValue.getString() == "no")
{
configuration->createFactions = false;
Log(LogLevel::Info) << "\tDisabling keep factions";
}
else
{
configuration->createFactions = true;
Log(LogLevel::Info) << "\tEnabling keep factions";
}
});
registerRegex(commonItems::catchallRegex, commonItems::ignoreItem);
}
std::unique_ptr<Configuration> Configuration::Factory::importConfiguration(const std::string& filename)
{
Log(LogLevel::Info) << "Reading configuration file";
configuration = std::make_unique<Configuration>();
parseFile(filename);
setOutputName(configuration->inputFile);
importMods();
return std::move(configuration);
}
std::unique_ptr<Configuration> Configuration::Factory::importConfiguration(std::istream& theStream)
{
Log(LogLevel::Info) << "Reading configuration file";
configuration = std::make_unique<Configuration>();
parseStream(theStream);
setOutputName(configuration->inputFile);
importMods();
return std::move(configuration);
}
void Configuration::Factory::setOutputName(const std::string& V2SaveFileName)
{
std::string outputName = trimPath(V2SaveFileName);
if (outputName.empty())
{
return;
}
const auto length = outputName.find_last_of('.');
if ((length == std::string::npos) || (".v2" != outputName.substr(length, outputName.length())))
{
throw std::invalid_argument("The save was not a Vic2 save. Choose a save ending in '.v2' and convert again.");
}
outputName = trimExtension(outputName);
outputName = normalizeStringPath(outputName);
Log(LogLevel::Info) << "Using output name " << outputName;
configuration->outputName = outputName;
}
void Configuration::Factory::importMods()
{
Vic2::Mod::Factory modFactory;
for (const auto& modFileName: modFileNames)
{
if (commonItems::DoesFileExist(configuration->Vic2ModPath + "/" + modFileName))
{
auto mod = modFactory.getMod(modFileName, configuration->Vic2ModPath);
configuration->Vic2Mods.push_back(std::move(*mod));
}
}
} | 39.127273 | 116 | 0.726417 | [
"shape",
"vector"
] |
c01f8e47b9586eebaa1868fd06c31ab4e06bbd71 | 4,713 | cpp | C++ | LightRays/Scene.cpp | xif-fr/LightRays | 511ffc92e6efce68973ad5cee699f644a3a0a98d | [
"MIT"
] | 1 | 2020-03-10T11:07:38.000Z | 2020-03-10T11:07:38.000Z | LightRays/Scene.cpp | xif-fr/LightRays | 511ffc92e6efce68973ad5cee699f644a3a0a98d | [
"MIT"
] | null | null | null | LightRays/Scene.cpp | xif-fr/LightRays | 511ffc92e6efce68973ad5cee699f644a3a0a98d | [
"MIT"
] | null | null | null | #include "Scene.h"
#include <cmath>
#include "sfml_c01.hpp"
// Test d'interception du rayon contre toutes les objets de la scène puis renvoi des
// rayons ré-émis; la première interception sur le trajet du rayon est choisie.
// Voir ObjetComposite::essai_intercept_composite pour un code similaire.
//
std::vector<Rayon> Scene::interception_re_emission (const Rayon& ray) {
decltype(objets)::const_iterator objet_intercept = objets.end();
std::shared_ptr<void> intercept_struct;
float dist2_min = Inf;
for (auto it = objets.begin(); it != objets.end(); it++) {
// Objet::extension_t ex = (*it)->objet_extension();
// Todo. Pour que ça puisse apporter quelque chose, il faut que ça soit calculé à l'avance et faire une grille et un test très rapide
#warning To do
Objet::intercept_t intercept = (*it)->essai_intercept(ray);
if (intercept.dist2 < dist2_min) {
dist2_min = intercept.dist2;
objet_intercept = it;
intercept_struct = intercept.intercept_struct;
}
}
if (objet_intercept == objets.end())
return {};
else {
if (propag_intercept_dessin_window != nullptr)
(*objet_intercept)->dessiner_interception(*propag_intercept_dessin_window, ray, intercept_struct);
if (propag_rayons_dessin_window != nullptr) {
auto p = (*objet_intercept)->point_interception(intercept_struct);
if (p.has_value()) {
float c = propag_rayons_dessin_gain * ray.spectre.intensite_tot();
auto line = sf::c01::buildLine(ray.orig, *p, sf::Color(255, 255, 255, (uint8_t)std::min(255.f,c)));
propag_rayons_dessin_window->draw(line);
}
}
if (propag_intercept_cb)
propag_intercept_cb(**objet_intercept, ray, intercept_struct);
return (*objet_intercept)->re_emit(ray, intercept_struct);
}
}
// Fonction récurrente : interception par les objets de la scène puis ré-émission
// avec la méthode `interception_re_emission`.
//
void Scene::propagation_recur (const Rayon& ray, uint16_t profondeur_recur) {
stats_sum_prof_recur += profondeur_recur;
if (profondeur_recur >= propag_profondeur_recur_max) {
stats_n_rayons_profmax++;
return;
}
stats_n_rayons++;
std::vector<Rayon> rays = this->interception_re_emission(ray);
profondeur_recur++;
for (const Rayon& ray : rays) {
if (ray.spectre.intensite_tot() < intens_cutoff) {
stats_n_rayons_discarded++;
continue;
}
if (propag_emit_cb)
propag_emit_cb(ray, profondeur_recur);
this->propagation_recur(ray, profondeur_recur);
}
}
// Émet les rayons de toutes les sources de la scène et appelle `propagation_recur`.
//
void Scene::emission_propagation () {
for (auto& source : sources) {
std::vector<Rayon> rays = source->genere_rayons();
stats_n_rayons_emis += rays.size();
for (const Rayon& ray : rays) {
if (propag_emit_cb)
propag_emit_cb(ray, 0);
this->propagation_recur(ray, 0);
}
}
}
///------- Méthodes utilitaires et Scene_ObjetsBougeables -------///
void Scene::ecrans_do (std::function<void (Ecran_Base &)> f) {
for (auto obj : objets) {
Ecran_Base* ecran = dynamic_cast<Ecran_Base*>(obj.get());
if (ecran != nullptr)
f(*ecran);
}
}
bool Scene_ObjetsBougeables::objetsBougeables_event_SFML (const sf::Event& event) {
if (objet_bougeant == nullptr) {
if (event.type == sf::Event::KeyPressed and event.key.code == sf::Keyboard::LShift)
bouge_action_alt = true;
if (event.type == sf::Event::KeyReleased and event.key.code == sf::Keyboard::LShift)
bouge_action_alt = false;
if (event.type == sf::Event::MouseButtonReleased)
objet_bougeant = bougeable_nearest;
} else {
if (event.type == sf::Event::MouseButtonReleased) {
bouge_action_alt = false;
objet_bougeant = nullptr;
}
}
if (event.type == sf::Event::MouseMoved) {
mouse = sf::c01::fromWin(sf::Vector2f(event.mouseMove.x,event.mouseMove.y));
if (objet_bougeant == nullptr) {
if (bouge_actions.empty())
bougeable_nearest = nullptr;
else {
bougeable_nearest = &bouge_actions.front();
float dist2_min = Inf;
for (bouge_action_t& obj : bouge_actions) {
float dist2 = !(obj.pos - mouse);
if (dist2 < dist2_min) {
dist2_min = dist2;
bougeable_nearest = &obj;
}
}
}
} else {
vec_t v = mouse - objet_bougeant->pos;
float dir_angle = atan2f(v.y, v.x);
point_t new_pos = objet_bougeant->action_bouge(mouse, dir_angle, bouge_action_alt);
objet_bougeant->pos = new_pos;
return true;
}
}
return false;
}
void Scene_ObjetsBougeables::dessiner_pointeur_nearest_bougeable (sf::RenderWindow& win) {
if (objet_bougeant == nullptr and bougeable_nearest != nullptr) {
auto pointeur = sf::c01::buildCircleShapeCR(bougeable_nearest->pos, 0.005);
pointeur.setFillColor(sf::Color::Blue);
win.draw(pointeur);
}
}
| 33.425532 | 135 | 0.708042 | [
"vector"
] |
c02eed36c793477b1738dffc58a3e4e880170415 | 12,687 | cpp | C++ | source/MaterialXView/Material.cpp | mjyip-lucasfilm/MaterialX | 19b0bd84c4537539350c1c065cc68fb400567f05 | [
"BSD-3-Clause"
] | 973 | 2017-07-06T02:29:09.000Z | 2022-02-28T18:49:10.000Z | source/MaterialXView/Material.cpp | mjyip-lucasfilm/MaterialX | 19b0bd84c4537539350c1c065cc68fb400567f05 | [
"BSD-3-Clause"
] | 213 | 2017-07-12T09:44:10.000Z | 2022-02-25T21:29:20.000Z | source/MaterialXView/Material.cpp | mjyip-lucasfilm/MaterialX | 19b0bd84c4537539350c1c065cc68fb400567f05 | [
"BSD-3-Clause"
] | 305 | 2017-07-11T19:05:41.000Z | 2022-02-14T12:25:43.000Z | #include <MaterialXView/Material.h>
#include <MaterialXRenderGlsl/External/GLew/glew.h>
#include <MaterialXRenderGlsl/GLTextureHandler.h>
#include <MaterialXRenderGlsl/GLUtil.h>
#include <MaterialXRender/Util.h>
#include <MaterialXFormat/Util.h>
//
// Material methods
//
bool Material::loadSource(const mx::FilePath& vertexShaderFile, const mx::FilePath& pixelShaderFile, bool hasTransparency)
{
_hasTransparency = hasTransparency;
std::string vertexShader = mx::readFile(vertexShaderFile);
if (vertexShader.empty())
{
return false;
}
std::string pixelShader = mx::readFile(pixelShaderFile);
if (pixelShader.empty())
{
return false;
}
// TODO:
// Here we set new source code on the _glProgram without rebuilding
// the _hwShader instance. So the _hwShader is not in sync with the
// _glProgram after this operation.
_glProgram = mx::GlslProgram::create();
_glProgram->addStage(mx::Stage::VERTEX, vertexShader);
_glProgram->addStage(mx::Stage::PIXEL, pixelShader);
_glProgram->build();
updateUniformsList();
return true;
}
void Material::updateUniformsList()
{
_uniformVariable.clear();
if (!_glProgram)
{
return;
}
for (const auto& pair : _glProgram->getUniformsList())
{
_uniformVariable.insert(pair.first);
}
}
void Material::clearShader()
{
_hwShader = nullptr;
_glProgram = nullptr;
_uniformVariable.clear();
}
bool Material::generateShader(mx::GenContext& context)
{
if (!_elem)
{
return false;
}
_hasTransparency = mx::isTransparentSurface(_elem, context.getShaderGenerator().getTarget());
mx::GenContext materialContext = context;
materialContext.getOptions().hwTransparency = _hasTransparency;
// Initialize in case creation fails and throws an exception
clearShader();
_hwShader = createShader("Shader", materialContext, _elem);
if (!_hwShader)
{
return false;
}
_glProgram = mx::GlslProgram::create();
_glProgram->setStages(_hwShader);
_glProgram->build();
updateUniformsList();
return true;
}
bool Material::generateShader(mx::ShaderPtr hwShader)
{
_hwShader = hwShader;
_glProgram = mx::GlslProgram::create();
_glProgram->setStages(hwShader);
_glProgram->build();
updateUniformsList();
return true;
}
bool Material::generateEnvironmentShader(mx::GenContext& context,
const mx::FilePath& filename,
mx::DocumentPtr stdLib,
const mx::FilePath& imagePath)
{
// Read in the environment nodegraph.
mx::DocumentPtr doc = mx::createDocument();
doc->importLibrary(stdLib);
mx::DocumentPtr envDoc = mx::createDocument();
mx::readFromXmlFile(envDoc, filename);
doc->importLibrary(envDoc);
mx::NodeGraphPtr envGraph = doc->getNodeGraph("environmentDraw");
if (!envGraph)
{
return false;
}
mx::NodePtr image = envGraph->getNode("envImage");
if (!image)
{
return false;
}
image->setInputValue("file", imagePath.asString(), mx::FILENAME_TYPE_STRING);
mx::OutputPtr output = envGraph->getOutput("out");
if (!output)
{
return false;
}
// Create the shader.
std::string shaderName = "__ENV_SHADER__";
_hwShader = createShader(shaderName, context, output);
if (!_hwShader)
{
return false;
}
return generateShader(_hwShader);
}
void Material::bindShader()
{
if (_glProgram)
{
_glProgram->bind();
}
}
void Material::bindMesh(mx::MeshPtr mesh) const
{
if (!mesh || !_glProgram)
{
return;
}
_glProgram->bind();
_glProgram->bindMesh(mesh);
}
bool Material::bindPartition(mx::MeshPartitionPtr part) const
{
if (!_glProgram)
{
return false;
}
_glProgram->bind();
_glProgram->bindPartition(part);
return true;
}
void Material::bindViewInformation(mx::CameraPtr camera)
{
if (!_glProgram)
{
return;
}
_glProgram->bindViewInformation(camera);
}
void Material::unbindImages(mx::ImageHandlerPtr imageHandler)
{
for (mx::ImagePtr image : _boundImages)
{
imageHandler->unbindImage(image);
}
}
void Material::bindImages(mx::ImageHandlerPtr imageHandler, const mx::FileSearchPath& searchPath, bool enableMipmaps)
{
if (!_glProgram)
{
return;
}
_boundImages.clear();
const mx::VariableBlock* publicUniforms = getPublicUniforms();
if (!publicUniforms)
{
return;
}
for (const auto& uniform : publicUniforms->getVariableOrder())
{
if (uniform->getType() != mx::Type::FILENAME)
{
continue;
}
const std::string& uniformVariable = uniform->getVariable();
std::string filename;
if (uniform->getValue())
{
filename = searchPath.find(uniform->getValue()->getValueString());
}
// Extract out sampling properties
mx::ImageSamplingProperties samplingProperties;
samplingProperties.setProperties(uniformVariable, *publicUniforms);
// Set the requested mipmap sampling property,
samplingProperties.enableMipmaps = enableMipmaps;
mx::ImagePtr image = bindImage(filename, uniformVariable, imageHandler, samplingProperties);
if (image)
{
_boundImages.push_back(image);
}
}
}
mx::ImagePtr Material::bindImage(const mx::FilePath& filePath, const std::string& uniformName, mx::ImageHandlerPtr imageHandler,
const mx::ImageSamplingProperties& samplingProperties)
{
if (!_glProgram)
{
return nullptr;
}
// Create a filename resolver for geometric properties.
mx::StringResolverPtr resolver = mx::StringResolver::create();
if (!getUdim().empty())
{
resolver->setUdimString(getUdim());
}
imageHandler->setFilenameResolver(resolver);
// Acquire the given image.
mx::ImagePtr image = imageHandler->acquireImage(filePath);
if (!image)
{
return nullptr;
}
// Bind the image and set its sampling properties.
if (imageHandler->bindImage(image, samplingProperties))
{
mx::GLTextureHandlerPtr textureHandler = std::static_pointer_cast<mx::GLTextureHandler>(imageHandler);
int textureLocation = textureHandler->getBoundTextureLocation(image->getResourceId());
if (textureLocation >= 0)
{
_glProgram->bindUniform(uniformName, mx::Value::createValue(textureLocation), false);
return image;
}
}
return nullptr;
}
void Material::bindLighting(mx::LightHandlerPtr lightHandler, mx::ImageHandlerPtr imageHandler, const ShadowState& shadowState)
{
if (!_glProgram)
{
return;
}
// Bind environment and local lighting.
_glProgram->bindLighting(lightHandler, imageHandler);
// Bind shadow map properties
if (shadowState.shadowMap && _glProgram->hasUniform(mx::HW::SHADOW_MAP))
{
mx::ImageSamplingProperties samplingProperties;
samplingProperties.uaddressMode = mx::ImageSamplingProperties::AddressMode::CLAMP;
samplingProperties.vaddressMode = mx::ImageSamplingProperties::AddressMode::CLAMP;
samplingProperties.filterType = mx::ImageSamplingProperties::FilterType::LINEAR;
// Bind the shadow map.
if (imageHandler->bindImage(shadowState.shadowMap, samplingProperties))
{
mx::GLTextureHandlerPtr textureHandler = std::static_pointer_cast<mx::GLTextureHandler>(imageHandler);
int textureLocation = textureHandler->getBoundTextureLocation(shadowState.shadowMap->getResourceId());
if (textureLocation >= 0)
{
_glProgram->bindUniform(mx::HW::SHADOW_MAP, mx::Value::createValue(textureLocation));
}
}
_glProgram->bindUniform(mx::HW::SHADOW_MATRIX, mx::Value::createValue(shadowState.shadowMatrix));
}
// Bind ambient occlusion properties.
if (shadowState.ambientOcclusionMap && _glProgram->hasUniform(mx::HW::AMB_OCC_MAP))
{
mx::ImageSamplingProperties samplingProperties;
samplingProperties.uaddressMode = mx::ImageSamplingProperties::AddressMode::PERIODIC;
samplingProperties.vaddressMode = mx::ImageSamplingProperties::AddressMode::PERIODIC;
samplingProperties.filterType = mx::ImageSamplingProperties::FilterType::LINEAR;
// Bind the ambient occlusion map.
if (imageHandler->bindImage(shadowState.ambientOcclusionMap, samplingProperties))
{
mx::GLTextureHandlerPtr textureHandler = std::static_pointer_cast<mx::GLTextureHandler>(imageHandler);
int textureLocation = textureHandler->getBoundTextureLocation(shadowState.ambientOcclusionMap->getResourceId());
if (textureLocation >= 0)
{
_glProgram->bindUniform(mx::HW::AMB_OCC_MAP, mx::Value::createValue(textureLocation));
}
}
_glProgram->bindUniform(mx::HW::AMB_OCC_GAIN, mx::Value::createValue(shadowState.ambientOcclusionGain));
}
}
void Material::bindUnits(mx::UnitConverterRegistryPtr& registry, const mx::GenContext& context)
{
static std::string DISTANCE_UNIT_TARGET_NAME = "u_distanceUnitTarget";
_glProgram->bind();
mx::ShaderPort* port = nullptr;
mx::VariableBlock* publicUniforms = getPublicUniforms();
if (publicUniforms)
{
// Scan block based on unit name match predicate
port = publicUniforms->find(
[](mx::ShaderPort* port)
{
return (port && (port->getName() == DISTANCE_UNIT_TARGET_NAME));
});
// Check if the uniform exists in the shader program
if (port && !_uniformVariable.count(port->getVariable()))
{
port = nullptr;
}
}
if (port)
{
int intPortValue = registry->getUnitAsInteger(context.getOptions().targetDistanceUnit);
if (intPortValue >= 0)
{
port->setValue(mx::Value::createValue(intPortValue));
if (_glProgram->hasUniform(DISTANCE_UNIT_TARGET_NAME))
{
_glProgram->bindUniform(DISTANCE_UNIT_TARGET_NAME, mx::Value::createValue(intPortValue));
}
}
}
}
void Material::drawPartition(mx::MeshPartitionPtr part) const
{
if (!part || !bindPartition(part))
{
return;
}
mx::MeshIndexBuffer& indexData = part->getIndices();
glDrawElements(GL_TRIANGLES, (GLsizei) indexData.size(), GL_UNSIGNED_INT, (void*) 0);
mx::checkGlErrors("after draw partition");
}
void Material::unbindGeometry() const
{
if (_glProgram)
{
_glProgram->bind();
_glProgram->unbindGeometry();
}
}
mx::VariableBlock* Material::getPublicUniforms() const
{
if (!_hwShader)
{
return nullptr;
}
mx::ShaderStage& stage = _hwShader->getStage(mx::Stage::PIXEL);
mx::VariableBlock& block = stage.getUniformBlock(mx::HW::PUBLIC_UNIFORMS);
return █
}
mx::ShaderPort* Material::findUniform(const std::string& path) const
{
mx::ShaderPort* port = nullptr;
mx::VariableBlock* publicUniforms = getPublicUniforms();
if (publicUniforms)
{
// Scan block based on path match predicate
port = publicUniforms->find(
[path](mx::ShaderPort* port)
{
return (port && mx::stringEndsWith(port->getPath(), path));
});
// Check if the uniform exists in the shader program
if (port && !_uniformVariable.count(port->getVariable()))
{
port = nullptr;
}
}
return port;
}
void Material::modifyUniform(const std::string& path, mx::ConstValuePtr value, std::string valueString)
{
mx::ShaderPort* uniform = findUniform(path);
if (!uniform)
{
return;
}
_glProgram->bind();
_glProgram->bindUniform(uniform->getVariable(), value);
if (valueString.empty())
{
valueString = value->getValueString();
}
uniform->setValue(mx::Value::createValueFromStrings(valueString, uniform->getType()->getName()));
if (_doc)
{
mx::ElementPtr element = _doc->getDescendant(uniform->getPath());
if (element)
{
mx::ValueElementPtr valueElement = element->asA<mx::ValueElement>();
if (valueElement)
{
valueElement->setValueString(valueString);
}
}
}
}
| 28.068584 | 128 | 0.642311 | [
"mesh"
] |
c032d4d5a2cbc4e061e2ee82d03fadd4a96f1ffa | 1,780 | cc | C++ | systems/framework/diagram_state.cc | RobotLocomotion/drake-python3.7 | ae397a4c6985262d23e9675b9bf3927c08d027f5 | [
"BSD-3-Clause"
] | 2 | 2021-02-25T02:01:02.000Z | 2021-03-17T04:52:04.000Z | systems/framework/diagram_state.cc | RobotLocomotion/drake-python3.7 | ae397a4c6985262d23e9675b9bf3927c08d027f5 | [
"BSD-3-Clause"
] | null | null | null | systems/framework/diagram_state.cc | RobotLocomotion/drake-python3.7 | ae397a4c6985262d23e9675b9bf3927c08d027f5 | [
"BSD-3-Clause"
] | 1 | 2021-06-13T12:05:39.000Z | 2021-06-13T12:05:39.000Z | #include "drake/systems/framework/diagram_state.h"
#include "drake/systems/framework/diagram_continuous_state.h"
#include "drake/systems/framework/diagram_discrete_values.h"
namespace drake {
namespace systems {
template <typename T>
DiagramState<T>::DiagramState(int size)
: State<T>(),
substates_(size),
owned_substates_(size) {}
template <typename T>
void DiagramState<T>::Finalize() {
DRAKE_DEMAND(!finalized_);
finalized_ = true;
std::vector<ContinuousState<T>*> sub_xcs;
sub_xcs.reserve(num_substates());
std::vector<DiscreteValues<T>*> sub_xds;
std::vector<AbstractValue*> sub_xas;
for (State<T>* substate : substates_) {
// Continuous
sub_xcs.push_back(&substate->get_mutable_continuous_state());
// Discrete
sub_xds.push_back(&substate->get_mutable_discrete_state());
// Abstract (no substructure)
AbstractValues& xa = substate->get_mutable_abstract_state();
for (int i_xa = 0; i_xa < xa.size(); ++i_xa) {
sub_xas.push_back(&xa.get_mutable_value(i_xa));
}
}
// This State consists of a continuous, discrete, and abstract state, each
// of which is a spanning vector over the continuous, discrete, and abstract
// parts of the constituent states. The spanning vectors do not own any
// of the actual memory that contains state variables. They just hold
// pointers to that memory.
this->set_continuous_state(
std::make_unique<DiagramContinuousState<T>>(sub_xcs));
this->set_discrete_state(
std::make_unique<DiagramDiscreteValues<T>>(sub_xds));
this->set_abstract_state(std::make_unique<AbstractValues>(sub_xas));
}
} // namespace systems
} // namespace drake
DRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(
class ::drake::systems::DiagramState)
| 34.230769 | 78 | 0.733146 | [
"vector"
] |
c0391a2c5430b2b77dd26ab2a520ace29772338b | 9,964 | cc | C++ | chrome/browser/android/password_ui_view_android.cc | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | chrome/browser/android/password_ui_view_android.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | chrome/browser/android/password_ui_view_android.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/android/password_ui_view_android.h"
#include <algorithm>
#include <memory>
#include <vector>
#include "base/android/callback_android.h"
#include "base/android/jni_string.h"
#include "base/android/jni_weak_ref.h"
#include "base/android/scoped_java_ref.h"
#include "base/bind_helpers.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/metrics/field_trial.h"
#include "base/numerics/safe_conversions.h"
#include "base/strings/string_piece.h"
#include "base/task_scheduler/post_task.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/sync/profile_sync_service_factory.h"
#include "components/autofill/core/common/password_form.h"
#include "components/browser_sync/profile_sync_service.h"
#include "components/password_manager/core/browser/export/password_csv_writer.h"
#include "components/password_manager/core/browser/password_manager_constants.h"
#include "components/password_manager/core/browser/password_ui_utils.h"
#include "components/password_manager/core/browser/ui/credential_provider_interface.h"
#include "content/public/browser/browser_thread.h"
#include "jni/PasswordUIView_jni.h"
#include "ui/base/l10n/l10n_util.h"
using base::android::ConvertUTF16ToJavaString;
using base::android::ConvertUTF8ToJavaString;
using base::android::JavaParamRef;
using base::android::JavaRef;
using base::android::ScopedJavaLocalRef;
PasswordUIViewAndroid::PasswordUIViewAndroid(JNIEnv* env, jobject obj)
: password_manager_presenter_(this), weak_java_ui_controller_(env, obj) {}
PasswordUIViewAndroid::~PasswordUIViewAndroid() {}
void PasswordUIViewAndroid::Destroy(JNIEnv*, const JavaRef<jobject>&) {
switch (state_) {
case State::ALIVE:
delete this;
break;
case State::ALIVE_SERIALIZATION_PENDING:
// Postpone the deletion until the pending tasks are completed, so that
// the tasks do not attempt a use after free while reading data from
// |this|.
state_ = State::DELETION_PENDING;
break;
case State::DELETION_PENDING:
NOTREACHED();
break;
}
}
Profile* PasswordUIViewAndroid::GetProfile() {
return ProfileManager::GetLastUsedProfile();
}
void PasswordUIViewAndroid::ShowPassword(size_t index,
const base::string16& password_value) {
NOTIMPLEMENTED();
}
void PasswordUIViewAndroid::SetPasswordList(
const std::vector<std::unique_ptr<autofill::PasswordForm>>& password_list) {
JNIEnv* env = base::android::AttachCurrentThread();
ScopedJavaLocalRef<jobject> ui_controller = weak_java_ui_controller_.get(env);
if (!ui_controller.is_null()) {
Java_PasswordUIView_passwordListAvailable(
env, ui_controller, static_cast<int>(password_list.size()));
}
}
void PasswordUIViewAndroid::SetPasswordExceptionList(
const std::vector<std::unique_ptr<autofill::PasswordForm>>&
password_exception_list) {
JNIEnv* env = base::android::AttachCurrentThread();
ScopedJavaLocalRef<jobject> ui_controller = weak_java_ui_controller_.get(env);
if (!ui_controller.is_null()) {
Java_PasswordUIView_passwordExceptionListAvailable(
env, ui_controller, static_cast<int>(password_exception_list.size()));
}
}
void PasswordUIViewAndroid::UpdatePasswordLists(JNIEnv* env,
const JavaRef<jobject>&) {
DCHECK_EQ(State::ALIVE, state_);
password_manager_presenter_.UpdatePasswordLists();
}
ScopedJavaLocalRef<jobject> PasswordUIViewAndroid::GetSavedPasswordEntry(
JNIEnv* env,
const JavaRef<jobject>&,
int index) {
DCHECK_EQ(State::ALIVE, state_);
const autofill::PasswordForm* form =
password_manager_presenter_.GetPassword(index);
if (!form) {
return Java_PasswordUIView_createSavedPasswordEntry(
env, ConvertUTF8ToJavaString(env, std::string()),
ConvertUTF16ToJavaString(env, base::string16()),
ConvertUTF16ToJavaString(env, base::string16()));
}
return Java_PasswordUIView_createSavedPasswordEntry(
env,
ConvertUTF8ToJavaString(
env, password_manager::GetShownOriginAndLinkUrl(*form).first),
ConvertUTF16ToJavaString(env, form->username_value),
ConvertUTF16ToJavaString(env, form->password_value));
}
ScopedJavaLocalRef<jstring> PasswordUIViewAndroid::GetSavedPasswordException(
JNIEnv* env,
const JavaRef<jobject>&,
int index) {
DCHECK_EQ(State::ALIVE, state_);
const autofill::PasswordForm* form =
password_manager_presenter_.GetPasswordException(index);
if (!form)
return ConvertUTF8ToJavaString(env, std::string());
return ConvertUTF8ToJavaString(
env, password_manager::GetShownOriginAndLinkUrl(*form).first);
}
void PasswordUIViewAndroid::HandleRemoveSavedPasswordEntry(
JNIEnv* env,
const JavaRef<jobject>&,
int index) {
DCHECK_EQ(State::ALIVE, state_);
password_manager_presenter_.RemoveSavedPassword(index);
}
void PasswordUIViewAndroid::HandleRemoveSavedPasswordException(
JNIEnv* env,
const JavaRef<jobject>&,
int index) {
DCHECK_EQ(State::ALIVE, state_);
password_manager_presenter_.RemovePasswordException(index);
}
void PasswordUIViewAndroid::HandleSerializePasswords(
JNIEnv* env,
const JavaRef<jobject>&,
const JavaRef<jstring>& java_target_path,
const JavaRef<jobject>& success_callback,
const JavaRef<jobject>& error_callback) {
switch (state_) {
case State::ALIVE:
state_ = State::ALIVE_SERIALIZATION_PENDING;
break;
case State::ALIVE_SERIALIZATION_PENDING:
// The UI should not allow the user to re-request export before finishing
// or cancelling the pending one.
NOTREACHED();
return;
case State::DELETION_PENDING:
// The Java part should not first request destroying of |this| and then
// ask |this| for serialized passwords.
NOTREACHED();
return;
}
// The tasks are posted with base::Unretained, because deletion is postponed
// until the reply arrives (look for the occurrences of DELETION_PENDING in
// this file). The background processing is not expected to take very long,
// but still long enough not to block the UI thread. The main concern here is
// not to avoid the background computation if |this| is about to be deleted
// but to simply avoid use after free from the background task runner.
base::PostTaskWithTraitsAndReplyWithResult(
FROM_HERE, {base::TaskPriority::USER_VISIBLE, base::MayBlock()},
base::BindOnce(
&PasswordUIViewAndroid::ObtainAndSerializePasswords,
base::Unretained(this),
base::FilePath(ConvertJavaStringToUTF8(env, java_target_path))),
base::BindOnce(&PasswordUIViewAndroid::PostSerializedPasswords,
base::Unretained(this),
base::android::ScopedJavaGlobalRef<jobject>(
env, success_callback.obj()),
base::android::ScopedJavaGlobalRef<jobject>(
env, error_callback.obj())));
}
ScopedJavaLocalRef<jstring> JNI_PasswordUIView_GetAccountDashboardURL(
JNIEnv* env,
const JavaParamRef<jclass>&) {
return ConvertUTF8ToJavaString(
env, password_manager::kPasswordManagerAccountDashboardURL);
}
// static
static jlong JNI_PasswordUIView_Init(JNIEnv* env,
const JavaParamRef<jobject>& obj) {
PasswordUIViewAndroid* controller = new PasswordUIViewAndroid(env, obj.obj());
return reinterpret_cast<intptr_t>(controller);
}
PasswordUIViewAndroid::SerializationResult
PasswordUIViewAndroid::ObtainAndSerializePasswords(
const base::FilePath& target_path) {
// This is run on a backend task runner. Do not access any member variables
// except for |credential_provider_for_testing_| and
// |password_manager_presenter_|.
password_manager::CredentialProviderInterface* const provider =
credential_provider_for_testing_ ? credential_provider_for_testing_
: &password_manager_presenter_;
std::vector<std::unique_ptr<autofill::PasswordForm>> passwords =
provider->GetAllPasswords();
// The UI should not trigger serialization if there are not passwords.
DCHECK(!passwords.empty());
std::string data =
password_manager::PasswordCSVWriter::SerializePasswords(passwords);
int bytes_written = base::WriteFile(target_path, data.data(), data.size());
if (bytes_written != base::checked_cast<int>(data.size()))
return {0, logging::GetLastSystemErrorCode()};
return {static_cast<int>(passwords.size()), 0};
}
void PasswordUIViewAndroid::PostSerializedPasswords(
const base::android::JavaRef<jobject>& success_callback,
const base::android::JavaRef<jobject>& error_callback,
SerializationResult serialization_result) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
switch (state_) {
case State::ALIVE:
NOTREACHED();
break;
case State::ALIVE_SERIALIZATION_PENDING: {
state_ = State::ALIVE;
if (export_target_for_testing_) {
*export_target_for_testing_ = serialization_result;
} else {
if (serialization_result.entries_count) {
base::android::RunCallbackAndroid(success_callback,
serialization_result.entries_count);
} else {
base::android::RunCallbackAndroid(
error_callback, base::android::ConvertUTF8ToJavaString(
base::android::AttachCurrentThread(),
logging::SystemErrorCodeToString(
serialization_result.error)));
}
}
break;
}
case State::DELETION_PENDING:
delete this;
break;
}
}
| 38.323077 | 86 | 0.718888 | [
"vector"
] |
c04438cdafba218a5c26288140ef882dbc832ff8 | 1,890 | hpp | C++ | src/process_posix.hpp | BadOPCode/Oblivion2-XRM | d65d9aa4b8021fc3b50b2c09edd0b19eb7baa1b9 | [
"Zlib"
] | 78 | 2015-10-08T07:14:37.000Z | 2022-02-10T04:51:21.000Z | src/process_posix.hpp | BadOPCode/Oblivion2-XRM | d65d9aa4b8021fc3b50b2c09edd0b19eb7baa1b9 | [
"Zlib"
] | 117 | 2015-12-14T16:51:42.000Z | 2020-02-16T07:00:36.000Z | src/process_posix.hpp | BadOPCode/Oblivion2-XRM | d65d9aa4b8021fc3b50b2c09edd0b19eb7baa1b9 | [
"Zlib"
] | 10 | 2015-12-10T16:54:24.000Z | 2022-02-10T04:51:29.000Z | #ifndef PROCESS_POSIX_HPP
#define PROCESS_POSIX_HPP
#include "process_base.hpp"
#include <termios.h>
#include <memory>
#include <vector>
#include <string>
class SessionData;
typedef std::shared_ptr<SessionData> session_data_ptr;
/**
* @struct ThreadArguments
* @date 28/05/2017
* @brief pthread (Posix) Arguments passer
*/
typedef struct ThreadArguments
{
session_data_ptr m_session;
int m_pty_file_desc;
} ThreadArguments;
typedef std::shared_ptr<ThreadArguments> args_ptr;
/**
* @class ProcessPosix
* @author Michael Griffin
* @date 30/04/2017
* @file process.hpp
* @brief Process Posix class for piping data between user sessions and external programs.
*/
class ProcessPosix
: public ProcessBase
{
public:
ProcessPosix(session_data_ptr session, std::string cmdline);
~ProcessPosix();
// pty control structure
struct termios m_termbuf_original;
struct termios m_termbuf;
/**
* @brief Startup the inital Terminal buffer
*/
void initTerminalOptions();
/**
* @brief Setup the inital Terminal buffer
*/
void setTerminalOptions();
/**
* @brief Setup the inital Terminal buffer
*/
void setTerminalBuffer();
/**
* @brief Process Loop Thread (std::thread)
*/
//void executeProcessLoop();
/**
* @brief Startup a Windows Specific External Process
*/
virtual bool createProcess() override;
/**
* @brief Checks if the process is still running
* @return
*/
virtual bool isRunning() override;
/**
* @brief Pulls Input Data from User Session and Delivers to (Child Process)
*/
virtual void update() override;
/**
* @brief Kill Process
*/
virtual void terminate() override;
int m_pty_file_desc;
int m_proc_id;
args_ptr m_args;
};
#endif // PROCESS_HPP
| 18.712871 | 90 | 0.658201 | [
"vector"
] |
c0497761a9ef3d614fa615fbca16a63b6793b8bc | 570 | cc | C++ | libs/core/src/core/default_parse.cc | madeso/euphoria | 59b72d148a90ae7a19e197e91216d4d42f194fd5 | [
"MIT"
] | 24 | 2015-07-27T14:32:18.000Z | 2021-11-15T12:11:31.000Z | libs/core/src/core/default_parse.cc | madeso/euphoria | 59b72d148a90ae7a19e197e91216d4d42f194fd5 | [
"MIT"
] | 27 | 2021-07-09T21:18:40.000Z | 2021-07-14T13:39:56.000Z | libs/core/src/core/default_parse.cc | madeso/euphoria | 59b72d148a90ae7a19e197e91216d4d42f194fd5 | [
"MIT"
] | null | null | null | #include "core/default_parse.h"
#include "core/stringmerger.h"
#include "core/functional.h"
namespace euphoria::core::argparse
{
std::string
quote_and_combine_english_or(const std::vector<std::string>& matches)
{
const auto quoted_names =
map<std::string>(matches, [](const std::string& s)
{
return static_cast<std::string>
(
StringBuilder() << '\'' << s << '\''
);
});
return string_mergers::english_or.merge(quoted_names);
}
}
| 22.8 | 73 | 0.542105 | [
"vector"
] |
c04e759aa6f56d249782a0dcf6507ecf4d61af58 | 45,155 | hpp | C++ | unicorn/string.hpp | alesapin/unicorn-lib | b08b565fe2e8051d877193e8a6d0b355a14cca84 | [
"MIT"
] | 238 | 2016-02-12T11:00:16.000Z | 2021-12-29T00:29:53.000Z | unicorn/string.hpp | alesapin/unicorn-lib | b08b565fe2e8051d877193e8a6d0b355a14cca84 | [
"MIT"
] | 6 | 2016-02-13T17:26:08.000Z | 2022-01-17T03:38:12.000Z | unicorn/string.hpp | alesapin/unicorn-lib | b08b565fe2e8051d877193e8a6d0b355a14cca84 | [
"MIT"
] | 23 | 2016-02-12T21:40:14.000Z | 2021-11-17T06:10:46.000Z | #pragma once
#include "unicorn/character.hpp"
#include "unicorn/segment.hpp"
#include "unicorn/utf.hpp"
#include "unicorn/utility.hpp"
#include <algorithm>
#include <cerrno>
#include <cmath>
#include <cstring>
#include <initializer_list>
#include <iterator>
#include <limits>
#include <stdexcept>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>
namespace RS::Unicorn {
// Early declarations for functions used internally
inline void str_append(Ustring& str, const Ustring& suffix) { str += suffix; }
void str_append(Ustring& str, const Utf8Iterator& suffix_begin, const Utf8Iterator& suffix_end);
void str_append(Ustring& str, const Irange<Utf8Iterator>& suffix);
void str_append(Ustring& str, const char* suffix);
void str_append(Ustring& dst, const char* ptr, size_t n);
inline void str_append_char(Ustring& dst, char c) { dst += c; }
void str_append_chars(Ustring& dst, size_t n, char32_t c);
Ustring str_char(char32_t c);
Ustring str_chars(size_t n, char32_t c);
Ustring str_repeat(const Ustring& str, size_t n);
void str_repeat_in(Ustring& str, size_t n);
template <typename C>
void str_append(Ustring& str, const std::basic_string<C>& suffix) {
std::copy(utf_begin(suffix), utf_end(suffix), utf_writer(str));
}
template <typename C>
void str_append(Ustring& str, const UtfIterator<C>& suffix_begin, const UtfIterator<C>& suffix_end) {
std::copy(suffix_begin, suffix_end, utf_writer(str));
}
template <typename C>
void str_append(Ustring& str, const Irange<UtfIterator<C>>& suffix) {
str_append(str, suffix.begin(), suffix.end());
}
template <typename C>
void str_append(Ustring& str, const C* suffix) {
str_append(str, cstr(suffix));
}
template <typename C>
void str_append(Ustring& dst, const C* ptr, size_t n) {
if (ptr)
for (auto out = utf_writer(dst); n > 0; --n, ++ptr)
*out = char_to_uint(*ptr++);
}
template <typename C>
void str_append_char(Ustring& dst, C c) {
*utf_writer(dst) = char_to_uint(c);
}
template <typename C1, typename C2, typename... Chars>
void str_append_char(Ustring& dst, C1 c1, C2 c2, Chars... chars) {
str_append_char(dst, c1);
str_append_char(dst, c2, chars...);
}
// String size functions
// Remember that any other set of flags that might be combined with these
// needs to skip the bits that are already spoken for. The string length
// flags are linked to upper case letters for use with unicorn/format, so
// they have bit positions in the 0-25 range.
struct Length {
static constexpr auto characters = uint32_t(letter_to_mask('C')); // Measure string in characters
static constexpr auto graphemes = uint32_t(letter_to_mask('G')); // Measure string in grapheme clusters (default)
static constexpr auto narrow = uint32_t(letter_to_mask('N')); // East Asian width, defaulting to narrow
static constexpr auto wide = uint32_t(letter_to_mask('W')); // East Asian width, defaulting to wide
uint32_t flags = 0;
Length() = default;
explicit Length(uint32_t length_flags);
template <typename C> size_t operator()(const std::basic_string<C>& str) const;
template <typename C> size_t operator()(const Irange<UtfIterator<C>>& range) const;
template <typename C> size_t operator()(const UtfIterator<C>& b, const UtfIterator<C>& e) const;
};
namespace UnicornDetail {
constexpr auto east_asian_flags = Length::narrow | Length::wide;
constexpr auto all_length_flags = Length::characters | Length::graphemes | east_asian_flags;
inline bool char_is_advancing(char32_t c) {
return char_general_category(c) != GC::Mn;
}
template <typename C>
inline bool grapheme_is_advancing(Irange<UtfIterator<C>> g) {
return ! g.empty() && char_is_advancing(*g.begin());
}
inline void check_length_flags(uint32_t& flags) {
if (popcount(flags & (Length::characters | Length::graphemes)) > 1
|| popcount(flags & (Length::characters | east_asian_flags)) > 1)
throw std::invalid_argument("Inconsistent string length flags");
if (popcount(flags & all_length_flags) == 0)
flags |= Length::graphemes;
}
class EastAsianCount {
public:
explicit EastAsianCount(uint32_t flags) noexcept: count(), fset(flags) { memset(count, 0, sizeof(count)); }
void add(char32_t c) noexcept {
if (char_is_advancing(c))
++count[unsigned(east_asian_width(c))];
}
size_t get() const noexcept {
size_t default_width = fset & Length::wide ? 2 : 1;
return count[neut] + count[half] + count[narr] + 2 * count[full] + 2 * count[wide]
+ default_width * count[ambi];
}
private:
static constexpr auto neut = int(East_Asian_Width::N);
static constexpr auto ambi = int(East_Asian_Width::A);
static constexpr auto full = int(East_Asian_Width::F);
static constexpr auto half = int(East_Asian_Width::H);
static constexpr auto narr = int(East_Asian_Width::Na);
static constexpr auto wide = int(East_Asian_Width::W);
size_t count[6];
uint32_t fset;
};
template <typename C>
std::pair<UtfIterator<C>, bool> find_position(const Irange<UtfIterator<C>>& range, size_t pos, uint32_t flags = 0) {
check_length_flags(flags);
if (pos == 0)
return {range.begin(), true};
if (flags & Length::characters) {
auto i = range.begin();
size_t len = 0;
while (i != range.end() && len < pos) {
++i;
++len;
}
return {i, len == pos};
} else if (flags & east_asian_flags) {
EastAsianCount eac(flags);
if (flags & Length::graphemes) {
auto graph = grapheme_range(range);
auto g = graph.begin();
while (g != graph.end() && eac.get() < pos) {
eac.add(*g->begin());
++g;
}
return {g->begin(), eac.get() >= pos};
} else {
auto i = range.begin();
while (i != range.end() && eac.get() < pos) {
eac.add(*i);
++i;
}
return {i, eac.get() >= pos};
}
} else {
auto graph = grapheme_range(range);
size_t len = 0;
for (auto& g: graph) {
if (grapheme_is_advancing(g)) {
++len;
if (len == pos)
return {g.end(), true};
}
}
return {range.end(), len == pos};
}
}
}
inline Length::Length(uint32_t length_flags):
flags(length_flags) {
UnicornDetail::check_length_flags(flags);
}
template <typename C>
size_t Length::operator()(const std::basic_string<C>& str) const {
return (*this)(utf_range(str));
}
template <typename C>
size_t Length::operator()(const Irange<UtfIterator<C>>& range) const {
using namespace UnicornDetail;
if (flags & Length::characters) {
return range_count(range);
} else if (flags & east_asian_flags) {
EastAsianCount eac(flags);
if (flags & Length::graphemes) {
for (auto g: grapheme_range(range))
eac.add(*g.begin());
} else {
for (auto c: range)
eac.add(c);
}
return eac.get();
} else {
auto gr = grapheme_range(range);
return std::count_if(gr.begin(), gr.end(), grapheme_is_advancing<C>);
}
}
template <typename C>
size_t Length::operator()(const UtfIterator<C>& b, const UtfIterator<C>& e) const {
return (*this)(irange(b, e));
}
template <typename C>
size_t str_length(const std::basic_string<C>& str, uint32_t flags = 0) {
return Length(flags)(str);
}
template <typename C>
size_t str_length(const Irange<UtfIterator<C>>& range, uint32_t flags = 0) {
return Length(flags)(range);
}
template <typename C>
size_t str_length(const UtfIterator<C>& b, const UtfIterator<C>& e, uint32_t flags = 0) {
return Length(flags)(b, e);
}
template <typename C>
UtfIterator<C> str_find_index(const Irange<UtfIterator<C>>& range, size_t pos, uint32_t flags = 0) {
return UnicornDetail::find_position(range, pos, flags).first;
}
template <typename C>
UtfIterator<C> str_find_index(const UtfIterator<C>& b, const UtfIterator<C>& e, size_t pos, uint32_t flags = 0) {
return str_find_index(irange(b, e), pos, flags);
}
template <typename C>
UtfIterator<C> str_find_index(const std::basic_string<C>& str, size_t pos, uint32_t flags = 0) {
return str_find_index(utf_range(str), pos, flags);
}
template <typename C>
size_t str_find_offset(const std::basic_string<C>& str, size_t pos, uint32_t flags = 0) {
auto rc = UnicornDetail::find_position(utf_range(str), pos, flags);
return rc.second ? rc.first.offset() : npos;
}
// Other string properties
// Defined in string-property.cpp
template <typename C>
char32_t str_char_at(const std::basic_string<C>& str, size_t index) noexcept {
auto range = utf_range(str);
for (char32_t c: range)
if (! index--)
return c;
return 0;
}
template <typename C>
char32_t str_first_char(const std::basic_string<C>& str) noexcept {
return str.empty() ? 0 : *utf_begin(str);
}
template <typename C>
char32_t str_last_char(const std::basic_string<C>& str) noexcept {
return str.empty() ? 0 : *std::prev(utf_end(str));
}
bool str_is_east_asian(const Ustring& str);
bool str_starts_with(const Ustring& str, const Ustring& prefix) noexcept;
bool str_ends_with(const Ustring& str, const Ustring& suffix) noexcept;
// String comparison
// Defined in string-compare.cpp
namespace UnicornDetail {
int do_compare_basic(const Ustring& lhs, const Ustring& rhs);
int do_compare_icase(const Ustring& lhs, const Ustring& rhs);
int do_compare_natural(const Ustring& lhs, const Ustring& rhs);
}
struct Strcmp {
static constexpr uint32_t equal = setbit<0>;
static constexpr uint32_t less = setbit<1>;
static constexpr uint32_t triple = setbit<2>;
static constexpr uint32_t fallback = setbit<3>;
static constexpr uint32_t icase = setbit<4>;
static constexpr uint32_t natural = setbit<5>;
};
template <uint32_t Flags>
struct StringCompare {
static constexpr bool equal = (Flags & Strcmp::equal) != 0;
static constexpr bool less = (Flags & Strcmp::less) != 0;
static constexpr bool triple = (Flags & Strcmp::triple) != 0;
static constexpr bool fallback = (Flags & Strcmp::fallback) != 0;
static constexpr bool icase = (Flags & Strcmp::icase) != 0;
static constexpr bool natural = (Flags & Strcmp::natural) != 0;
static_assert(int(equal) + int(less) + int(triple) == 1, "Invalid string comparison flags");
using result_type = std::conditional_t<triple, int, bool>;
result_type operator()(const Ustring& lhs, const Ustring& rhs) const {
using namespace UnicornDetail;
int c = 0;
if constexpr (natural)
c = do_compare_natural(lhs, rhs);
if constexpr (icase)
if (c == 0)
c = do_compare_icase(lhs, rhs);
if constexpr (fallback || (! icase && ! natural))
if (c == 0)
c = do_compare_basic(lhs, rhs);
if constexpr (equal)
return result_type(c == 0);
else if constexpr (less)
return result_type(c == -1);
else
return result_type(c);
}
};
// Other string algorithms
// Defined in string-algorithm.cpp
size_t str_common(const Ustring& s1, const Ustring& s2, size_t start = 0) noexcept;
size_t str_common_utf(const Ustring& s1, const Ustring& s2, size_t start = 0) noexcept;
bool str_expect(Utf8Iterator& i, const Utf8Iterator& end, const Ustring& prefix);
bool str_expect(Utf8Iterator& i, const Ustring& prefix);
Utf8Iterator str_find_char(const Utf8Iterator& b, const Utf8Iterator& e, char32_t c);
Utf8Iterator str_find_char(const Irange<Utf8Iterator>& range, char32_t c);
Utf8Iterator str_find_char(const Ustring& str, char32_t c);
Utf8Iterator str_find_last_char(const Utf8Iterator& b, const Utf8Iterator& e, char32_t c);
Utf8Iterator str_find_last_char(const Irange<Utf8Iterator>& range, char32_t c);
Utf8Iterator str_find_last_char(const Ustring& str, char32_t c);
Utf8Iterator str_find_first_of(const Utf8Iterator& b, const Utf8Iterator& e, const Ustring& target);
Utf8Iterator str_find_first_of(const Irange<Utf8Iterator>& range, const Ustring& target);
Utf8Iterator str_find_first_of(const Ustring& str, const Ustring& target);
Utf8Iterator str_find_first_not_of(const Utf8Iterator& b, const Utf8Iterator& e, const Ustring& target);
Utf8Iterator str_find_first_not_of(const Irange<Utf8Iterator>& range, const Ustring& target);
Utf8Iterator str_find_first_not_of(const Ustring& str, const Ustring& target);
Utf8Iterator str_find_last_of(const Utf8Iterator& b, const Utf8Iterator& e, const Ustring& target);
Utf8Iterator str_find_last_of(const Irange<Utf8Iterator>& range, const Ustring& target);
Utf8Iterator str_find_last_of(const Ustring& str, const Ustring& target);
Utf8Iterator str_find_last_not_of(const Utf8Iterator& b, const Utf8Iterator& e, const Ustring& target);
Utf8Iterator str_find_last_not_of(const Irange<Utf8Iterator>& range, const Ustring& target);
Utf8Iterator str_find_last_not_of(const Ustring& str, const Ustring& target);
std::pair<size_t, size_t> str_line_column(const Ustring& str, size_t offset, uint32_t flags = 0);
Irange<Utf8Iterator> str_search(const Utf8Iterator& b, const Utf8Iterator& e, const Ustring& target);
Irange<Utf8Iterator> str_search(const Irange<Utf8Iterator>& range, const Ustring& target);
Irange<Utf8Iterator> str_search(const Ustring& str, const Ustring& target);
size_t str_skipws(Utf8Iterator& i, const Utf8Iterator& end);
size_t str_skipws(Utf8Iterator& i);
// String manipulation functions
// Defined in string-manip.cpp
namespace UnicornDetail {
enum { trimleft = 1, trimright = 2 };
Ustring expand_tabs(const Ustring& str, const std::vector<size_t>& tabs, uint32_t flags);
template <typename DS>
void concat_helper(Ustring&, const DS&) {}
template <typename DS, typename S2, typename... Strings>
void concat_helper(Ustring& s1, const DS& delim, const S2& s2, const Strings&... ss) {
str_append(s1, delim);
str_append(s1, s2);
concat_helper(s1, delim, ss...);
}
template <typename Pred>
Ustring trim_helper(const Ustring& src, int mode, Pred p) {
auto range = utf_range(src);
auto i = range.begin(), j = range.end();
if (mode & trimleft)
while (i != j && p(*i))
++i;
if ((mode & trimright) && i != j) {
for (;;) {
--j;
if (! p(*j)) {
++j;
break;
}
if (i == j)
break;
}
}
return u_str(i, j);
}
template <typename Pred>
void trim_in_helper(Ustring& src, int mode, Pred p) {
auto range = utf_range(src);
auto i = range.begin(), j = range.end();
if (mode & trimleft)
while (i != j && p(*i))
++i;
if ((mode & trimright) && i != j) {
for (;;) {
--j;
if (! p(*j)) {
++j;
break;
}
if (i == j)
break;
}
}
src.erase(j.offset(), npos);
src.erase(0, i.offset());
}
}
Ustring str_drop_prefix(const Ustring& str, const Ustring& prefix);
void str_drop_prefix_in(Ustring& str, const Ustring& prefix) noexcept;
Ustring str_drop_suffix(const Ustring& str, const Ustring& suffix);
void str_drop_suffix_in(Ustring& str, const Ustring& suffix) noexcept;
Ustring str_erase_left(const Ustring& str, size_t length);
void str_erase_left_in(Ustring& str, size_t length) noexcept;
Ustring str_erase_right(const Ustring& str, size_t length);
void str_erase_right_in(Ustring& str, size_t length) noexcept;
Ustring str_expand_tabs(const Ustring& str);
void str_expand_tabs_in(Ustring& str);
Ustring str_fix_left(const Ustring& str, size_t length, char32_t c = U' ', uint32_t flags = 0);
void str_fix_left_in(Ustring& str, size_t length, char32_t c = U' ', uint32_t flags = 0);
Ustring str_fix_right(const Ustring& str, size_t length, char32_t c = U' ', uint32_t flags = 0);
void str_fix_right_in(Ustring& str, size_t length, char32_t c = U' ', uint32_t flags = 0);
Ustring str_insert(const Utf8Iterator& dst, const Utf8Iterator& src_begin, const Utf8Iterator& src_end);
Ustring str_insert(const Utf8Iterator& dst, const Irange<Utf8Iterator>& src);
Ustring str_insert(const Utf8Iterator& dst, const Ustring& src);
Ustring str_insert(const Utf8Iterator& dst_begin, const Utf8Iterator& dst_end, const Utf8Iterator& src_begin, const Utf8Iterator& src_end);
Ustring str_insert(const Irange<Utf8Iterator>& dst, const Irange<Utf8Iterator>& src);
Ustring str_insert(const Utf8Iterator& dst_begin, const Utf8Iterator& dst_end, const Ustring& src);
Ustring str_insert(const Irange<Utf8Iterator>& dst, const Ustring& src);
Irange<Utf8Iterator> str_insert_in(Ustring& dst, const Utf8Iterator& where, const Utf8Iterator& src_begin, const Utf8Iterator& src_end);
Irange<Utf8Iterator> str_insert_in(Ustring& dst, const Utf8Iterator& where, const Irange<Utf8Iterator>& src);
Irange<Utf8Iterator> str_insert_in(Ustring& dst, const Utf8Iterator& where, const Ustring& src);
Irange<Utf8Iterator> str_insert_in(Ustring& dst, const Utf8Iterator& range_begin, const Utf8Iterator& range_end, const Utf8Iterator& src_begin, const Utf8Iterator& src_end);
Irange<Utf8Iterator> str_insert_in(Ustring& dst, const Irange<Utf8Iterator>& range, const Irange<Utf8Iterator>& src);
Irange<Utf8Iterator> str_insert_in(Ustring& dst, const Utf8Iterator& range_begin, const Utf8Iterator& range_end, const Ustring& src);
Irange<Utf8Iterator> str_insert_in(Ustring& dst, const Irange<Utf8Iterator>& range, const Ustring& src);
Ustring str_pad_left(const Ustring& str, size_t length, char32_t c = U' ', uint32_t flags = 0);
void str_pad_left_in(Ustring& str, size_t length, char32_t c = U' ', uint32_t flags = 0);
Ustring str_pad_right(const Ustring& str, size_t length, char32_t c = U' ', uint32_t flags = 0);
void str_pad_right_in(Ustring& str, size_t length, char32_t c = U' ', uint32_t flags = 0);
bool str_partition(const Ustring& str, Ustring& prefix, Ustring& suffix);
bool str_partition_at(const Ustring& str, Ustring& prefix, Ustring& suffix, const Ustring& delim);
bool str_partition_by(const Ustring& str, Ustring& prefix, Ustring& suffix, const Ustring& delim);
Ustring str_remove(const Ustring& str, char32_t c);
Ustring str_remove(const Ustring& str, const Ustring& chars);
void str_remove_in(Ustring& str, char32_t c);
void str_remove_in(Ustring& str, const Ustring& chars);
Ustring str_replace(const Ustring& str, const Ustring& target, const Ustring& sub, size_t n = npos);
void str_replace_in(Ustring& str, const Ustring& target, const Ustring& sub, size_t n = npos);
Strings str_splitv(const Ustring& src);
Strings str_splitv_at(const Ustring& src, const Ustring& delim);
Strings str_splitv_by(const Ustring& src, const Ustring& delim);
Strings str_splitv_lines(const Ustring& src);
Ustring str_squeeze(const Ustring& str);
Ustring str_squeeze(const Ustring& str, const Ustring& chars);
Ustring str_squeeze_trim(const Ustring& str);
Ustring str_squeeze_trim(const Ustring& str, const Ustring& chars);
void str_squeeze_in(Ustring& str);
void str_squeeze_in(Ustring& str, const Ustring& chars);
void str_squeeze_trim_in(Ustring& str);
void str_squeeze_trim_in(Ustring& str, const Ustring& chars);
Ustring str_substring(const Ustring& str, size_t offset, size_t count = npos);
Ustring utf_substring(const Ustring& str, size_t index, size_t length = npos, uint32_t flags = 0);
Ustring str_translate(const Ustring& str, const Ustring& target, const Ustring& sub);
void str_translate_in(Ustring& str, const Ustring& target, const Ustring& sub);
Ustring str_trim(const Ustring& str, const Ustring& chars);
Ustring str_trim(const Ustring& str);
Ustring str_trim_left(const Ustring& str, const Ustring& chars);
Ustring str_trim_left(const Ustring& str);
Ustring str_trim_right(const Ustring& str, const Ustring& chars);
Ustring str_trim_right(const Ustring& str);
void str_trim_in(Ustring& str, const Ustring& chars);
void str_trim_in(Ustring& str);
void str_trim_left_in(Ustring& str, const Ustring& chars);
void str_trim_left_in(Ustring& str);
void str_trim_right_in(Ustring& str, const Ustring& chars);
void str_trim_right_in(Ustring& str);
Ustring str_unify_lines(const Ustring& str, const Ustring& newline);
Ustring str_unify_lines(const Ustring& str, char32_t newline);
Ustring str_unify_lines(const Ustring& str);
void str_unify_lines_in(Ustring& str, const Ustring& newline);
void str_unify_lines_in(Ustring& str, char32_t newline);
void str_unify_lines_in(Ustring& str);
class Wrap {
public:
static constexpr Kwarg<bool, 1> enforce = {}; // Enforce right margin strictly (default false)
static constexpr Kwarg<bool, 2> lines = {}; // Treat every line as a paragraph (default false)
static constexpr Kwarg<bool, 3> preserve = {}; // Preserve layout on already indented lines (default false)
static constexpr Kwarg<uint32_t> flags = {}; // Flags for string length (default 0)
static constexpr Kwarg<size_t, 1> margin = {}; // Margin for first line (default 0)
static constexpr Kwarg<size_t, 2> margin2 = {}; // Margin for subsequent lines (default is same as margin)
static constexpr Kwarg<size_t, 3> width = {}; // Wrap width (default is $COLUMNS-2)
static constexpr Kwarg<Ustring, 1> newline = {}; // Line break (default LF)
static constexpr Kwarg<Ustring, 2> newpara = {}; // Paragraph break (default is two line breaks)
Wrap() { init(); }
template <typename... Args> Wrap(Args... args);
Ustring wrap(const Ustring& src) const { Ustring dst; do_wrap(src, dst); return dst; }
void wrap_in(Ustring& src) const { Ustring dst; do_wrap(src, dst); src = std::move(dst); }
Ustring operator()(const Ustring& src) const { return wrap(src); }
private:
bool enforce_ = false;
bool lines_ = false;
bool preserve_ = false;
uint32_t flags_ = 0;
size_t margin_ = 0;
size_t margin2_ = npos;
size_t width_ = npos;
Ustring newline_ = "\n";
Ustring newpara_ = "\n\n";
size_t pbreak_ = 2;
size_t spacing_ = 1;
void do_wrap(const Ustring& src, Ustring& dst) const;
void init();
};
template <typename... Args>
Wrap::Wrap(Args... args) {
using namespace std::literals;
enforce_ = kwget(enforce, false, args...);
lines_ = kwget(lines, false, args...);
preserve_ = kwget(preserve, false, args...);
flags_ = kwget(flags, uint32_t(0), args...);
margin_ = kwget(margin, size_t(0), args...);
margin2_ = kwget(margin2, npos, args...);
width_ = kwget(width, npos, args...);
newline_ = kwget(newline, "\n"s, args...);
newpara_ = kwget(newpara, newline_ + newline_, args...);
init();
}
template <typename... Args> Ustring str_wrap(const Ustring& str, Args... args) {
Wrap w(std::forward<Args>(args)...);
return w.wrap(str);
}
template <typename... Args> void str_wrap_in(Ustring& str, Args... args) {
Wrap w(std::forward<Args>(args)...);
w.wrap_in(str);
}
template <typename C, typename... Strings>
Ustring str_concat(const std::basic_string<C>& s, const Strings&... ss) {
Ustring result;
UnicornDetail::concat_helper(result, std::basic_string<C>(), s, ss...);
return result;
}
template <typename C, typename... Strings>
Ustring str_concat(const C* s, const Strings&... ss) {
Ustring result;
UnicornDetail::concat_helper(result, std::basic_string<C>(), cstr(s), ss...);
return result;
}
template <typename C>
Ustring str_concat_with(const std::basic_string<C>& /*delim*/) {
return {};
}
template <typename C>
Ustring str_concat_with(const C* /*delim*/) {
return {};
}
template <typename C1, typename C2, typename... Strings>
Ustring str_concat_with(const std::basic_string<C1>& delim, const std::basic_string<C2>& s, const Strings&... ss) {
Ustring result = to_utf8(s);
UnicornDetail::concat_helper(result, delim, ss...);
return result;
}
template <typename C1, typename C2, typename... Strings>
Ustring str_concat_with(const std::basic_string<C1>& delim, const C2* s, const Strings&... ss) {
Ustring result = to_utf8(cstr(s));
UnicornDetail::concat_helper(result, delim, ss...);
return result;
}
template <typename C1, typename C2, typename... Strings>
Ustring str_concat_with(const C1* delim, const std::basic_string<C2>& s, const Strings&... ss) {
Ustring result = to_utf8(s);
UnicornDetail::concat_helper(result, cstr(delim), ss...);
return result;
}
template <typename C1, typename C2, typename... Strings>
Ustring str_concat_with(const C1* delim, const C2* s, const Strings&... ss) {
Ustring result = to_utf8(cstr(s));
UnicornDetail::concat_helper(result, cstr(delim), ss...);
return result;
}
template <typename IntList>
Ustring str_expand_tabs(const Ustring& str, const IntList& tabs, uint32_t flags = 0) {
std::vector<size_t> tv(tabs.begin(), tabs.end());
return UnicornDetail::expand_tabs(str, tv, flags);
}
template <typename IntType>
Ustring str_expand_tabs(const Ustring& str, std::initializer_list<IntType> tabs, uint32_t flags = 0) {
std::vector<size_t> tv(tabs.begin(), tabs.end());
return UnicornDetail::expand_tabs(str, tv, flags);
}
template <typename IntList>
void str_expand_tabs_in(Ustring& str, const IntList& tabs, uint32_t flags = 0) {
std::vector<size_t> tv(tabs.begin(), tabs.end());
str = UnicornDetail::expand_tabs(str, tv, flags);
}
template <typename IntType>
void str_expand_tabs_in(Ustring& str, std::initializer_list<IntType> tabs, uint32_t flags = 0) {
std::vector<size_t> tv(tabs.begin(), tabs.end());
str = UnicornDetail::expand_tabs(str, tv, flags);
}
template <typename FwdRange>
Ustring str_join(const FwdRange& r, const Ustring& delim, bool term = false) {
using std::begin;
using std::end;
Ustring dst;
for (auto& s: r) {
dst += s;
dst += delim;
}
if (! term && ! dst.empty() && ! delim.empty())
dst.resize(dst.size() - delim.size());
return dst;
}
template <typename FwdRange>
auto str_join(const FwdRange& r) {
return str_join(r, Ustring());
}
template <typename Pred>
Ustring str_remove_if(const Ustring& str, Pred p) {
Ustring dst;
std::copy_if(utf_begin(str), utf_end(str), utf_writer(dst), [p] (char32_t x) { return ! p(x); });
return dst;
}
template <typename Pred>
Ustring str_remove_if_not(const Ustring& str, Pred p) {
Ustring dst;
std::copy_if(utf_begin(str), utf_end(str), utf_writer(dst), p);
return dst;
}
template <typename Pred>
void str_remove_in_if(Ustring& str, Pred p) {
Ustring dst;
std::copy_if(utf_begin(str), utf_end(str), utf_writer(dst), [p] (char32_t x) { return ! p(x); });
str.swap(dst);
}
template <typename Pred>
void str_remove_in_if_not(Ustring& str, Pred p) {
Ustring dst;
std::copy_if(utf_begin(str), utf_end(str), utf_writer(dst), p);
str.swap(dst);
}
template <typename OutIter>
void str_split(const Ustring& src, OutIter dst) {
auto range = utf_range(src);
auto i = range.begin(), j = i;
while (i != range.end()) {
j = std::find_if_not(i, range.end(), char_is_white_space);
if (j == range.end())
break;
i = std::find_if(j, range.end(), char_is_white_space);
*dst++ = u_str(j, i);
}
}
template <typename OutIter>
void str_split_at(const Ustring& src, OutIter dst, const Ustring& delim) {
if (delim.empty()) {
*dst++ = src;
return;
}
size_t i = 0, dsize = delim.size();
for (;;) {
auto j = src.find(delim, i);
if (j == npos) {
*dst++ = src.substr(i);
break;
}
*dst++ = src.substr(i, j - i);
i = j + dsize;
}
}
template <typename OutIter>
void str_split_by(const Ustring& src, OutIter dst, const Ustring& delim) {
if (delim.empty()) {
*dst++ = src;
return;
}
auto u_delim = to_utf32(delim);
if (delim.size() == u_delim.size()) {
size_t i = 0, n = src.size();
while (i < n) {
auto j = src.find_first_not_of(delim, i);
if (j == npos)
break;
i = src.find_first_of(delim, j);
if (i == npos)
i = n;
*dst++ = src.substr(j, i - j);
}
} else {
auto match = [&] (char32_t c) { return u_delim.find(c) != npos; };
auto range = utf_range(src);
auto i = range.begin(), j = i;
while (i != range.end()) {
j = std::find_if_not(i, range.end(), match);
if (j == range.end())
break;
i = std::find_if(j, range.end(), match);
*dst++ = u_str(j, i);
}
}
}
template <typename OutIter>
void str_split_lines(const Ustring& src, OutIter dst) {
auto i = utf_begin(src), j = i, e = utf_end(src);
while (i != e) {
j = std::find_if(i, e, char_is_line_break);
*dst++ = u_str(i, j);
if (j == e)
break;
char32_t c = *j;
if (++j == e)
break;
if (c == U'\r' && *j == U'\n')
++j;
i = j;
}
}
template <typename Pred>
Ustring str_trim_if(const Ustring& str, Pred p) {
using namespace UnicornDetail;
return trim_helper(str, trimleft | trimright, p);
}
template <typename Pred>
Ustring str_trim_left_if(const Ustring& str, Pred p) {
using namespace UnicornDetail;
return trim_helper(str, trimleft, p);
}
template <typename Pred>
Ustring str_trim_right_if(const Ustring& str, Pred p) {
using namespace UnicornDetail;
return trim_helper(str, trimright, p);
}
template <typename Pred>
Ustring str_trim_if_not(const Ustring& str, Pred p) {
using namespace UnicornDetail;
return trim_helper(str, trimleft | trimright, [p] (char32_t c) { return ! p(c); });
}
template <typename Pred>
Ustring str_trim_left_if_not(const Ustring& str, Pred p) {
using namespace UnicornDetail;
return trim_helper(str, trimleft, [p] (char32_t c) { return ! p(c); });
}
template <typename Pred>
Ustring str_trim_right_if_not(const Ustring& str, Pred p) {
using namespace UnicornDetail;
return trim_helper(str, trimright, [p] (char32_t c) { return ! p(c); });
}
template <typename Pred>
void str_trim_in_if(Ustring& str, Pred p) {
using namespace UnicornDetail;
trim_in_helper(str, trimleft | trimright, p);
}
template <typename Pred>
void str_trim_left_in_if(Ustring& str, Pred p) {
using namespace UnicornDetail;
trim_in_helper(str, trimleft, p);
}
template <typename Pred>
void str_trim_right_in_if(Ustring& str, Pred p) {
using namespace UnicornDetail;
trim_in_helper(str, trimright, p);
}
template <typename Pred>
void str_trim_in_if_not(Ustring& str, Pred p) {
using namespace UnicornDetail;
trim_in_helper(str, trimleft | trimright, [p] (char32_t c) { return ! p(c); });
}
template <typename Pred>
void str_trim_left_in_if_not(Ustring& str, Pred p) {
using namespace UnicornDetail;
trim_in_helper(str, trimleft, [p] (char32_t c) { return ! p(c); });
}
template <typename Pred>
void str_trim_right_in_if_not(Ustring& str, Pred p) {
using namespace UnicornDetail;
trim_in_helper(str, trimright, [p] (char32_t c) { return ! p(c); });
}
// Case mapping functions
// Defined in string-case.cpp
Ustring str_uppercase(const Ustring& str);
Ustring str_lowercase(const Ustring& str);
Ustring str_titlecase(const Ustring& str);
Ustring str_casefold(const Ustring& str);
Ustring str_case(const Ustring& str, Case c);
Ustring str_initial_titlecase(const Ustring& str);
void str_uppercase_in(Ustring& str);
void str_lowercase_in(Ustring& str);
void str_titlecase_in(Ustring& str);
void str_casefold_in(Ustring& str);
void str_case_in(Ustring& str, Case c);
void str_initial_titlecase_in(Ustring& str);
// Escaping and quoting functions
// Defined in string-escape.cpp
struct Escape {
static constexpr uint32_t ascii = setbit<0>; // Escape all non-ASCII characters
static constexpr uint32_t nostdc = setbit<1>; // Do not use standard C symbols such as `\n`
static constexpr uint32_t pcre = setbit<2>; // Use `\x{...}` instead of `\u` and `\U` (implies `nonascii`)
static constexpr uint32_t punct = setbit<3>; // Escape ASCII punctuation
};
Ustring str_encode_uri(const Ustring& str);
Ustring str_encode_uri_component(const Ustring& str);
void str_encode_uri_in(Ustring& str);
void str_encode_uri_component_in(Ustring& str);
Ustring str_unencode_uri(const Ustring& str);
void str_unencode_uri_in(Ustring& str);
Ustring str_escape(const Ustring& str, uint32_t flags = 0);
void str_escape_in(Ustring& str, uint32_t flags = 0);
Ustring str_unescape(const Ustring& str);
void str_unescape_in(Ustring& str);
Ustring str_quote(const Ustring& str, uint32_t flags = 0, char32_t quote = U'\"');
void str_quote_in(Ustring& str, uint32_t flags = 0, char32_t quote = U'\"');
Ustring str_unquote(const Ustring& str, char32_t quote = U'\"');
void str_unquote_in(Ustring& str, char32_t quote = U'\"');
// Type conversion functions
namespace UnicornDetail {
template <typename T>
Utf8Iterator convert_str_to_int(T& t, const Utf8Iterator& start, uint32_t flags, int base) {
static const Ustring dec_chars = "+-0123456789";
static const Ustring hex_chars = "+-0123456789ABCDEFabcdef";
const Ustring& src(start.source());
size_t offset = start.offset();
if (offset >= src.size()) {
if (flags & Utf::throws)
throw std::invalid_argument("Invalid integer (empty string)");
t = T(0);
return utf_end(src);
}
size_t endpos = src.find_first_not_of(base == 16 ? hex_chars : dec_chars, offset);
if (endpos == offset) {
if (flags & Utf::throws)
throw std::invalid_argument("Invalid integer: " + quote(to_utf8(start.str())));
t = T(0);
return start;
}
if (endpos == npos)
endpos = src.size();
Ustring fragment(src, offset, endpos - offset);
Utf8Iterator stop;
if (std::is_signed<T>::value) {
static constexpr auto min_value = static_cast<long long>(std::numeric_limits<T>::min());
static constexpr auto max_value = static_cast<long long>(std::numeric_limits<T>::max());
char* endptr = nullptr;
errno = 0;
long long value = strtoll(fragment.data(), &endptr, base);
int err = errno;
size_t len = endptr - fragment.data();
stop = utf_iterator(src, offset + len);
if ((flags & Utf::throws) && stop != utf_end(src))
throw std::invalid_argument("Invalid integer: " + quote(fragment));
if (len == 0) {
if (flags & Utf::throws)
throw std::invalid_argument("Invalid integer: " + quote(u_str(start, utf_end(src))));
t = T(0);
} else if (err == ERANGE || value < min_value || value > max_value) {
if (flags & Utf::throws)
throw std::range_error("Integer out of range: " + quote(fragment));
t = T(value > 0 ? max_value : min_value);
} else {
t = T(value);
}
} else {
static constexpr auto max_value = static_cast<unsigned long long>(std::numeric_limits<T>::max());
char* endptr = nullptr;
errno = 0;
unsigned long long value = strtoull(fragment.data(), &endptr, base);
int err = errno;
size_t len = endptr - fragment.data();
stop = utf_iterator(src, offset + len);
if ((flags & Utf::throws) && stop != utf_end(src))
throw std::invalid_argument("Invalid integer: " + quote(u_str(start, utf_end(src))));
if (len == 0) {
if (flags & Utf::throws)
throw std::invalid_argument("Invalid integer: " + quote(fragment));
t = T(0);
} else if (err == ERANGE || value > max_value) {
if (flags & Utf::throws)
throw std::range_error("Integer out of range: " + quote(fragment));
t = T(max_value);
} else {
t = T(value);
}
}
return stop;
}
template <typename T>
struct FloatConversionTraits {
static constexpr long double huge_val = HUGE_VALL;
static long double str_to_t(const char* p, char** ep) noexcept { return strtold(p, ep); }
};
template <>
struct FloatConversionTraits<float> {
static constexpr float huge_val = HUGE_VALF;
static float str_to_t(const char* p, char** ep) noexcept { return strtof(p, ep); }
};
template <>
struct FloatConversionTraits<double> {
static constexpr double huge_val = HUGE_VAL;
static double str_to_t(const char* p, char** ep) noexcept { return strtod(p, ep); }
};
}
template <typename T>
size_t str_to_int(T& t, const Ustring& str, size_t offset = 0, uint32_t flags = 0) {
return UnicornDetail::convert_str_to_int<T>(t, utf_iterator(str, offset), flags, 10).offset() - offset;
}
template <typename T>
Utf8Iterator str_to_int(T& t, const Utf8Iterator& start, uint32_t flags = 0) {
return UnicornDetail::convert_str_to_int<T>(t, start, flags, 10);
}
template <typename T>
T str_to_int(const Ustring& str, uint32_t flags = 0) {
T t = T(0);
UnicornDetail::convert_str_to_int<T>(t, utf_begin(str), flags, 10);
return t;
}
template <typename T>
T str_to_int(const Utf8Iterator& start, uint32_t flags = 0) {
T t = T(0);
UnicornDetail::convert_str_to_int<T>(t, start, flags, 10);
return t;
}
template <typename T>
size_t hex_to_int(T& t, const Ustring& str, size_t offset = 0, uint32_t flags = 0) {
return UnicornDetail::convert_str_to_int<T>(t, utf_iterator(str, offset), flags, 16).offset() - offset;
}
template <typename T>
Utf8Iterator hex_to_int(T& t, const Utf8Iterator& start, uint32_t flags = 0) {
return UnicornDetail::convert_str_to_int<T>(t, start, flags, 16);
}
template <typename T>
T hex_to_int(const Ustring& str, uint32_t flags = 0) {
T t = T(0);
UnicornDetail::convert_str_to_int<T>(t, utf_begin(str), flags, 16);
return t;
}
template <typename T>
T hex_to_int(const Utf8Iterator& start, uint32_t flags = 0) {
T t = T(0);
UnicornDetail::convert_str_to_int<T>(t, start, flags, 16);
return t;
}
template <typename T>
Utf8Iterator str_to_float(T& t, const Utf8Iterator& start, uint32_t flags = 0) {
using traits = UnicornDetail::FloatConversionTraits<T>;
static constexpr T max_value = std::numeric_limits<T>::max();
const Ustring& src(start.source());
size_t offset = start.offset();
if (offset >= src.size()) {
if (flags & Utf::throws)
throw std::invalid_argument("Invalid number (empty string)");
t = T(0);
return utf_end(src);
}
size_t endpos = src.find_first_not_of("+-.0123456789Ee", offset);
if (endpos == offset) {
if (flags & Utf::throws)
throw std::invalid_argument("Invalid number: " + quote(start.str()));
t = T(0);
return start;
}
if (endpos == npos)
endpos = src.size();
Ustring fragment(src, offset, endpos - offset);
char* endptr = nullptr;
T value = traits::str_to_t(fragment.data(), &endptr);
size_t len = endptr - fragment.data();
auto stop = utf_iterator(src, offset + len);
if ((flags & Utf::throws) && stop != utf_end(src))
throw std::invalid_argument("Invalid number: " + quote(u_str(start, utf_end(src))));
if (len == 0) {
if (flags & Utf::throws)
throw std::invalid_argument("Invalid number: " + quote(fragment));
t = T(0);
} else if (value == traits::huge_val || value == - traits::huge_val) {
if (flags & Utf::throws)
throw std::range_error("Number out of range: " + quote(fragment));
t = value > T(0) ? max_value : - max_value;
} else {
t = value;
}
return stop;
}
template <typename T>
size_t str_to_float(T& t, const Ustring& str, size_t offset = 0, uint32_t flags = 0) {
return str_to_float(t, utf_iterator(str, offset), flags).offset() - offset;
}
template <typename T>
T str_to_float(const Ustring& str, uint32_t flags = 0) {
T t = T(0);
str_to_float(t, utf_begin(str), flags);
return t;
}
template <typename T>
T str_to_float(const Utf8Iterator& start, uint32_t flags = 0) {
T t = T(0);
str_to_float(t, start, flags);
return t;
}
}
| 41.694367 | 177 | 0.599026 | [
"vector"
] |
c05657d5c593145bc161110ad0cf32754869b194 | 3,492 | cpp | C++ | ml-juce/JuceLookAndFeel/MLTriToggleButton.cpp | ngwese/soundplane | 92ed75035694db1a8886e4791aab0a23efff4cc3 | [
"MIT"
] | 20 | 2015-01-26T05:34:53.000Z | 2022-01-31T07:09:35.000Z | ml-juce/JuceLookAndFeel/MLTriToggleButton.cpp | ngwese/soundplane | 92ed75035694db1a8886e4791aab0a23efff4cc3 | [
"MIT"
] | 35 | 2015-03-07T18:26:09.000Z | 2021-07-16T17:07:32.000Z | ml-juce/JuceLookAndFeel/MLTriToggleButton.cpp | ngwese/soundplane | 92ed75035694db1a8886e4791aab0a23efff4cc3 | [
"MIT"
] | 8 | 2015-03-10T08:44:04.000Z | 2021-01-04T00:31:12.000Z |
// MadronaLib: a C++ framework for DSP applications.
// Copyright (c) 2013 Madrona Labs LLC. http://www.madronalabs.com
// Distributed under the MIT license: http://madrona-labs.mit-license.org/
#include "MLTriToggleButton.h"
#include "MLLookAndFeel.h"
#include "MLAppView.h"
MLTriToggleButton::MLTriToggleButton(MLWidget* pContainer) :
MLButton(pContainer)
{
setProperty("tri_button", true);
setOpaque(false);
}
MLTriToggleButton::~MLTriToggleButton()
{
}
void MLTriToggleButton::paint(Graphics& g)
{
MLLookAndFeel* myLookAndFeel = (&(getRootViewResources(this).mLookAndFeel));
int state = getFloatProperty("value");
// colors
const float alpha = isEnabled() ? 1.f : 0.25f;
const Colour offColor (findColour (MLLookAndFeel::darkFillColor));
const Colour onColor (findColour (MLButton::buttonOnColourId));
Colour outlineOnColor, outlineOffColor;
outlineOnColor = findColour(MLLookAndFeel::outlineColor).overlaidWith(onColor.withMultipliedAlpha(0.625f)).withMultipliedAlpha (alpha);
outlineOffColor = findColour(MLLookAndFeel::outlineColor).withMultipliedAlpha (alpha);
// geometry
const int width = getWidth();
const int height = getHeight();
int toggleSize = myLookAndFeel->getToggleButtonSize() * getWidgetGridUnitSize();
int halfSize = toggleSize/2;
int sixthSize = halfSize/3;
int thirdSize = sixthSize*2 + 1;
sixthSize = ml::max(sixthSize, 1);
thirdSize = ml::max(thirdSize, 2);
// get int center
int cx = width/2 - 1;
int cy = height/2 - 1;
// get toggle rect
int toggleX = cx - halfSize;
int toggleY = cy - halfSize;
int toggleWidth = halfSize*2;
int toggleHeight = halfSize*2;
int flair = eMLAdornShadow | eMLAdornGlow;
const float cornerSize = 0.;
// TODO toggle buttons are even-sized! I don’t think this was the idea.
// so there are some messy +1 and -1s going on here. investigate.
// dark background
myLookAndFeel->drawMLButtonShape (g, toggleX, toggleY, toggleWidth, toggleHeight,
cornerSize, offColor, outlineOffColor, kMLButtonOutlineThickness, flair, 0., 0.);
g.saveState();
switch(state)
{
case 0: // left
g.reduceClipRegion(toggleX - 1, toggleY - 1, thirdSize + 1, toggleHeight + 1);
break;
case 1: // center
g.reduceClipRegion(cx - sixthSize, toggleY - 1, thirdSize - 1, toggleHeight + 1);
break;
case 2: // right
g.reduceClipRegion(toggleX + toggleWidth - thirdSize, toggleY - 1, thirdSize + 1, toggleHeight + 1);
break;
default:
break;
}
myLookAndFeel->drawMLButtonShape (g, toggleX, toggleY, toggleWidth, toggleHeight,
cornerSize, onColor, outlineOnColor, mLineThickness, flair, 0., 0.);
g.restoreState();
}
void MLTriToggleButton::clicked()
{
int state = getFloatProperty("value");
state += 1;
if(state > 2) state = 0;
setPropertyImmediate ("value", state);
sendAction("change_property", getTargetPropertyName(), getProperty("value"));
}
void MLTriToggleButton::resizeWidget(const MLRect& b, const int u)
{
Component* pC = getComponent();
mLineThickness = u/64.f;
if(pC)
{
MLRect bb = b;
bb.expand(-2);
// make sure width is odd
int newWidth = (bb.width()/2)*2 + 1;
// adapt vrect to juce rect
Rectangle<int> c(bb.left(), bb.top(), newWidth, bb.height());
pC->setBounds(c);
}
}
| 30.631579 | 136 | 0.662658 | [
"geometry"
] |
c056babb5a818b4483221746ab02ae4c7f703307 | 5,401 | cpp | C++ | common/tool/imageconv/main.cpp | lovewsy/patrace | 97376a6aa759c1695e29dc9530aa609c9385cbd8 | [
"MIT"
] | 41 | 2018-12-09T13:41:18.000Z | 2022-03-25T03:05:32.000Z | common/tool/imageconv/main.cpp | lovewsy/patrace | 97376a6aa759c1695e29dc9530aa609c9385cbd8 | [
"MIT"
] | 37 | 2019-01-24T04:09:10.000Z | 2022-03-29T10:35:38.000Z | common/tool/imageconv/main.cpp | lovewsy/patrace | 97376a6aa759c1695e29dc9530aa609c9385cbd8 | [
"MIT"
] | 27 | 2018-12-09T13:41:38.000Z | 2022-03-30T08:24:24.000Z | #include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>
#include <cstring>
#include "tool/config.hpp"
#include "eglstate/common.hpp"
#include "image/image_all.hpp"
using namespace pat;
namespace
{
void PrintUsage(const char *argv0)
{
std::cout <<
"\n"
"Usage: " << argv0 << " [OPTION] INPUT_IMAGE [OUTPUT_IMAGE]\n"
"Version: " PATRACE_VERSION "\n"
" The input and output format will be depend on file extensions.\n"
" If the output path is not provided, the content is the input image will be displayed.\n"
" Accepted formats :\n"
" .ktx : Accept all OpenGL formats. (http://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec)\n"
" .png : Luminance only, alpha only, RGB or RGBA. (http://en.wikipedia.org/wiki/Portable_Network_Graphics)\n"
"\n"
" -h help, display this\n"
"\n"
;
}
// Return the lower-case file extension of the input filepath.
// E.g, return ".txt" for "./path_info /foo/bar/baa.txt"
// And return empty string if can't find the extension.
const std::string extension(const std::string &filepath)
{
const char dot = '.';
const std::size_t dot_pos = filepath.find_last_of(dot);
if (dot_pos == std::string::npos)
return std::string();
std::string ext = filepath.substr(dot_pos);
std::transform(ext.begin(), ext.end(), ext.begin(), tolower);
return ext;
}
const std::string KTX_EXTENSION = ".ktx";
const std::string PNG_EXTENSION = ".png";
const std::string TIFF_EXTENSION = ".tiff";
const std::string JPG_EXTENSION = ".jpg";
const std::string JPEG_EXTENSION = ".jpeg";
} // unnamed namespace
int main(int argc, char **argv)
{
int i = 1;
for (; i < argc; ++i)
{
const char *arg = argv[i];
if (arg[0] != '-') {
break;
}
if (!strcmp(arg, "-h")) {
PrintUsage(argv[0]);
return 0;
}
else {
std::cout << "Unknown option : " << arg << std::endl;
PrintUsage(argv[0]);
return -1;
}
}
if (i + 1 > argc)
{
PrintUsage(argv[0]);
return -1;
}
const std::string input_filename = argv[i++];
const std::string output_filename = (i >= argc) ? std::string() : argv[i++];
const std::string input_ext = extension(input_filename);
typedef mpl::vector<image_type<GL_RGBA, GL_UNSIGNED_BYTE>::type,
image_type<GL_RGB, GL_UNSIGNED_SHORT_5_6_5>::type> image_types;
typedef gil::any_image<image_types> runtime_image_t;
runtime_image_t input_image;
uint32_t ogl_format = GL_NONE, ogl_type = GL_NONE;
if (input_ext == KTX_EXTENSION)
{
ktx_read_image(input_filename, input_image, &ogl_format, &ogl_type);
}
//else if (input_ext == PNG_EXTENSION)
//{
//gil::png_read_image(input_filename, input_image);
//}
else
{
std::cout << "Unknown input file extension : " << input_ext << std::endl;
PrintUsage(argv[0]);
return -1;
}
// Print information of the input image
std::cout << "Input Image :" << std::endl;
std::cout << " Image path : " << input_filename << std::endl;
std::cout << " Width : " << input_image.width() << std::endl;
std::cout << " Height : " << input_image.height() << std::endl;
std::cout << " OpenGL Format : " << EnumString(ogl_format) << std::endl;
std::cout << " OpenGL Type : " << EnumString(ogl_type) << std::endl;
//std::cout << " Data size : " << image.DataSize() << std::endl;
std::cout << std::endl;
if (output_filename.empty() == false)
{
const std::string output_ext = extension(output_filename);
if (output_ext == PNG_EXTENSION)
{
typedef image_type<GL_RGBA, GL_UNSIGNED_BYTE>::type output_image_t;
output_image_t output_image(input_image.width(), input_image.height());
gil::copy_and_convert_pixels(gil::const_view(input_image), gil::view(output_image));
gil::png_write_view(output_filename, const_view(output_image));
// Print information of the output image
std::cout << "Output Image :" << std::endl;
std::cout << " Image path : " << output_filename << std::endl;
std::cout << " Width : " << output_image.width() << std::endl;
std::cout << " Height : " << output_image.height() << std::endl;
}
else
{
std::cout << "Unknown output file extension : " << output_ext << std::endl;
PrintUsage(argv[0]);
return -1;
}
}
//pat::Image image;
//if (pat::ReadImage(image, input_filename))
//{
//if (output_filename && pat::WriteImage(image, output_filename, false))
//{
//return 0;
//}
//else
//{
//std::cout << "Image path : " << input_filename << std::endl;
//std::cout << "Width : " << image.Width() << std::endl;
//std::cout << "Height : " << image.Height() << std::endl;
//std::cout << "Format : " << EnumString(image.Format()) << std::endl;
//std::cout << "Type : " << EnumString(image.Type()) << std::endl;
//std::cout << "Data size : " << image.DataSize() << std::endl;
//}
//}
return -1;
}
| 33.75625 | 122 | 0.563599 | [
"vector",
"transform"
] |
c056de59bc2facf2fd9755d72a773de0c0cfaa96 | 3,166 | cpp | C++ | frameworks/core/components/split_container/render_row_split.cpp | openharmony-gitee-mirror/ace_ace_engine | 78013960cdce81348d1910e466a3292605442a5e | [
"Apache-2.0"
] | null | null | null | frameworks/core/components/split_container/render_row_split.cpp | openharmony-gitee-mirror/ace_ace_engine | 78013960cdce81348d1910e466a3292605442a5e | [
"Apache-2.0"
] | null | null | null | frameworks/core/components/split_container/render_row_split.cpp | openharmony-gitee-mirror/ace_ace_engine | 78013960cdce81348d1910e466a3292605442a5e | [
"Apache-2.0"
] | 1 | 2021-09-13T11:17:50.000Z | 2021-09-13T11:17:50.000Z | /*
* Copyright (c) 2021 Huawei Device 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 "core/components/split_container/render_row_split.h"
#include "core/components/flex/render_flex.h"
#include "core/components/split_container/flutter_render_row_split.h"
#include "core/pipeline/base/position_layout_utils.h"
namespace OHOS::Ace {
namespace {
constexpr double DEFAULT_SPLIT_RESPOND_WIDTH = 25.0;
constexpr size_t DEFAULT_DRAG_INDEX = -1;
} // namespace
RefPtr<RenderNode> RenderRowSplit::Create()
{
return AceType::MakeRefPtr<FlutterRenderRowSplit>();
}
void RenderRowSplit::LayoutChildren()
{
splitRects_.clear();
if (dragSplitOffset_.size() == 0) {
dragSplitOffset_ = std::vector<double>(GetChildren().size(), 0.0);
}
Size maxSize = GetLayoutParam().GetMaxSize();
layoutHeight_ = maxSize.Height();
layoutWidth_ = 0.0;
size_t index = 0;
double childOffsetX = 0.0;
for (const auto& item : GetChildren()) {
Offset offset = Offset(childOffsetX, 0);
item->SetPosition(offset);
item->Layout(GetLayoutParam());
childOffsetX += item->GetLayoutSize().Width();
layoutWidth_ += item->GetLayoutSize().Width();
if (dragSplitOffset_[index] > 0) {
childOffsetX += dragSplitOffset_[index];
}
double posX = childOffsetX > DEFAULT_SPLIT_RESPOND_WIDTH ? (childOffsetX - DEFAULT_SPLIT_RESPOND_WIDTH) : 0.0;
splitRects_.push_back(Rect(posX, 0, 2 * DEFAULT_SPLIT_RESPOND_WIDTH + DEFAULT_SPLIT_HEIGHT, maxSize.Height()));
childOffsetX += DEFAULT_SPLIT_HEIGHT;
layoutWidth_ += DEFAULT_SPLIT_HEIGHT;
index++;
}
layoutWidth_ -= DEFAULT_SPLIT_HEIGHT;
}
void RenderRowSplit::HandleDragStart(const Offset& startPoint)
{
dragedSplitIndex_ = DEFAULT_DRAG_INDEX;
for (std::size_t i = 0; i < splitRects_.size(); i++) {
if (splitRects_[i].IsInRegion(Point(startPoint.GetX(), startPoint.GetY()))) {
dragedSplitIndex_ = i;
LOGD("dragedSplitIndex_ = %zu", dragedSplitIndex_);
break;
}
}
startX_ = startPoint.GetX();
}
void RenderRowSplit::HandleDragUpdate(const Offset& currentPoint)
{
if (dragedSplitIndex_ == DEFAULT_DRAG_INDEX) {
return;
}
if (!GetPaintRect().IsInRegion(Point(currentPoint.GetX(), currentPoint.GetY()))) {
return;
}
dragSplitOffset_[dragedSplitIndex_] += (currentPoint.GetX() - startX_);
startX_ = currentPoint.GetX();
MarkNeedLayout();
}
void RenderRowSplit::HandleDragEnd(const Offset& endPoint, double velocity)
{
startX_ = 0.0;
}
} // namespace OHOS::Ace | 32.979167 | 119 | 0.688882 | [
"vector"
] |
c05a2b0a3f0bf4a98ad2323a7f023588a3ef07cc | 12,297 | cpp | C++ | src/APGreenhouse.cpp | dtrotzjr/greenhouse_data_server | ade7f71404e48759d1c9702acb3c0cca2f70cd76 | [
"MIT"
] | null | null | null | src/APGreenhouse.cpp | dtrotzjr/greenhouse_data_server | ade7f71404e48759d1c9702acb3c0cca2f70cd76 | [
"MIT"
] | null | null | null | src/APGreenhouse.cpp | dtrotzjr/greenhouse_data_server | ade7f71404e48759d1c9702acb3c0cca2f70cd76 | [
"MIT"
] | null | null | null | //
// Created by David Trotz on 5/29/16.
//
#include "APGreenhouse.h"
#include "APSimpleJSONQuery.h"
#include "APSimpleSQL.h"
#include "APSQLException.h"
#include <sstream>
#include <string.h>
#include <json/json.h>
APGreenhouse::APGreenhouse(Json::Value& config) {
_jsonQueryObj = new APSimpleJSONQuery();
std::string databaseFile = config["sqlite3_file"].asString();
_sqlDb = new APSimpleSQL(databaseFile);
_config = config;
}
APGreenhouse::~APGreenhouse() {
delete _jsonQueryObj;
delete _sqlDb;
}
void APGreenhouse::InitializeSQLTables() {
// Create the needed tables
if (_sqlDb != NULL) {
_sqlDb->BeginTransaction();
try{
_sqlDb->DoSQL("CREATE TABLE IF NOT EXISTS gh_data_points (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, timestamp integer, synchronized integer DEFAULT 0);");
_sqlDb->DoSQL("CREATE INDEX IF NOT EXISTS index_gh_data_points_on_timestamp ON gh_data_points (timestamp);");
_sqlDb->DoSQL("CREATE TABLE IF NOT EXISTS gh_sensor_data (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, sensor_id integer, temperature float, humidity float, gh_data_point_id integer);");
_sqlDb->DoSQL("CREATE INDEX IF NOT EXISTS index_gh_sensor_data_on_gh_data_point_id ON gh_sensor_data (gh_data_point_id);");
_sqlDb->DoSQL("CREATE TABLE IF NOT EXISTS gh_system_data (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, soc_temperature float, wlan0_link_quality float, wlan0_signal_level integer, storage_total_size integer,storage_used integer, storage_avail integer, gh_data_point_id integer);");
_sqlDb->DoSQL("CREATE INDEX IF NOT EXISTS index_gh_system_data_on_gh_data_point_id ON gh_system_data(gh_data_point_id);");
_sqlDb->DoSQL("CREATE TABLE IF NOT EXISTS gh_image_data (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, filename text, gh_data_point_id integer);");
_sqlDb->DoSQL("CREATE INDEX IF NOT EXISTS index_gh_image_data_on_gh_data_point_id ON gh_image_data(gh_data_point_id);");
} catch (APSQLException& e) {
_sqlDb->RollbackTransaction();
throw e;
}
_sqlDb->EndTransaction();
}
}
void APGreenhouse::GetLatestSensorData() {
time_t started_at = time(NULL);
int afterTimestamp = -1;
time_t maxTimestamp = _getMaxTimestampDataPoint();
int beginCount = _getCurrentDataPointCount();
const char* messagePrefix = "| Getting greenhouse and local sensor data since [%s]:";
// Convert the timestamp into a readable format
struct tm localMaxTimestamp;
char readableTime[64];
(void) localtime_r(&maxTimestamp, &localMaxTimestamp);
if (strftime(readableTime, sizeof(readableTime), "%D %R", &localMaxTimestamp) == 0) {
(void) fprintf(stderr, "ERROR: timestamp conversion failed!\n");
strncpy(readableTime, "UNKNOWN", sizeof(readableTime));
}
fprintf(stdout, messagePrefix, readableTime);
while (maxTimestamp > afterTimestamp) {
afterTimestamp = maxTimestamp;
char *response = _getUpdateFeed(afterTimestamp, 25);
if (response != NULL && strlen(response) > 0) {
_parseJSONResponse(response);
} else {
break;
}
maxTimestamp = _getMaxTimestampDataPoint();
if (time(NULL) - started_at > 60) {
// We are taking too long to fetch so we will break and let others have some time.
break;
}
}
// Let's print some useful statistics about what just happened.
int endCount = _getCurrentDataPointCount();
int delta = endCount - beginCount;
int buffLen = 128;
char *messagePostfix = (char*)calloc(buffLen, sizeof(char));
char *message = (char*)calloc(buffLen, sizeof(char));
char *spaces = (char*)calloc(buffLen, sizeof(char));
if (delta == 1) {
strncpy(messagePostfix, "[1 DATA POINT FETCHED] |\n", buffLen);
} else if (delta > 1) {
snprintf(messagePostfix, buffLen, "[%d DATA POINTS FETCHED] |\n", delta);
} else {
strncpy(messagePostfix, "[NO DATA AVAILABLE] |\n", buffLen);
}
int totalSpaces = 89 - (strlen(messagePrefix) + strlen(messagePostfix));
for (int i = 0; i < totalSpaces; ++i) {
strcat(spaces, " ");
}
fprintf(stdout, "%s%s", spaces, messagePostfix);
}
time_t APGreenhouse::_getMaxTimestampDataPoint() {
time_t maxTimestampDataPoint = 0;
_sqlDb->BeginSelect("SELECT MAX(timestamp) FROM gh_data_points");
if (_sqlDb->StepSelect()) {
maxTimestampDataPoint = (time_t)_sqlDb->GetColAsInt64(0);
}
_sqlDb->EndSelect();
return maxTimestampDataPoint;
}
int APGreenhouse::_getCurrentDataPointCount() {
int count = 0;
_sqlDb->BeginSelect("SELECT COUNT(id) FROM gh_data_points");
if (_sqlDb->StepSelect()) {
count = _sqlDb->GetColAsInt64(0);
}
_sqlDb->EndSelect();
return count;
}
char* APGreenhouse::_getUpdateFeed(int afterTimestamp, int maxResults) {
char url[2048];
snprintf(url, sizeof(url), "http://192.168.0.190/data_points.json?after_timestamp=%d&limit=%d", afterTimestamp, maxResults);
JSONResponseStructType response = _jsonQueryObj->GetJSONResponseFromURL(url);
return (response.size > 0 && response.success) ? response.buffer : NULL;
}
void APGreenhouse::_parseJSONResponse(char *response) {
// Prep the JSON object...
std::stringstream s;
s << response;
Json::Value root;
s >> root;
std::vector<APKeyValuePair*> *pairs = NULL;
APKeyValuePair* pair;
int64_t gh_data_point_id;
_sqlDb->BeginTransaction();
try {
for (const Json::Value& json : root["data_points"]) {
pairs = new std::vector<APKeyValuePair*>();
// Timestamp
if (json["id"] != Json::Value::null && json["timestamp"] != Json::Value::null) {
gh_data_point_id = (int64_t)json["id"].asInt64();
pair = new APKeyValuePair("id", gh_data_point_id);
pairs->push_back(pair);
int64_t timestamp = json["timestamp"].asInt64();
pair = new APKeyValuePair("timestamp", timestamp);
pairs->push_back(pair);
if (json["synchronized"] != Json::Value::null) {
pair = new APKeyValuePair("synchronized", json["synchronized"].asInt64());
pairs->push_back(pair);
}
int64_t lastId = _sqlDb->DoInsert("gh_data_points", pairs);
_freeVectorAndData(pairs);
if(lastId == gh_data_point_id) {
// Try to parse any sensor data
for (const Json::Value& sensor_datum : json["sensor_data"]) {
if (sensor_datum["id"] != Json::Value::null && sensor_datum["sensor_id"] != Json::Value::null) {
pairs = new std::vector<APKeyValuePair*>();
pair = new APKeyValuePair("id", sensor_datum["id"].asInt64());
pairs->push_back(pair);
pair = new APKeyValuePair("sensor_id", sensor_datum["sensor_id"].asInt64());
pairs->push_back(pair);
if (sensor_datum["temperature"] != Json::Value::null) {
pair = new APKeyValuePair("temperature", sensor_datum["temperature"].asDouble());
pairs->push_back(pair);
}
if (sensor_datum["humidity"] != Json::Value::null) {
pair = new APKeyValuePair("humidity", sensor_datum["humidity"].asDouble());
pairs->push_back(pair);
}
pair = new APKeyValuePair("gh_data_point_id", gh_data_point_id);
pairs->push_back(pair);
_sqlDb->DoInsert("gh_sensor_data", pairs);
_freeVectorAndData(pairs);
}
}
// Try and parse system datum
Json::Value system_datum = json["system_datum"];
if (system_datum != Json::Value::null && system_datum["id"] != Json::Value::null) {
pairs = new std::vector<APKeyValuePair*>();
pair = new APKeyValuePair("id", system_datum["id"].asInt64());
pairs->push_back(pair);
if (system_datum["soc_temperature"] != Json::Value::null) {
pair = new APKeyValuePair("soc_temperature", system_datum["soc_temperature"].asDouble());
pairs->push_back(pair);
}
if (system_datum["wlan0_link_quality"] != Json::Value::null) {
pair = new APKeyValuePair("wlan0_link_quality", system_datum["wlan0_link_quality"].asDouble());
pairs->push_back(pair);
}
if (system_datum["wlan0_signal_level"] != Json::Value::null) {
pair = new APKeyValuePair("wlan0_signal_level", system_datum["wlan0_signal_level"].asInt64());
pairs->push_back(pair);
}
if (system_datum["storage_total_size"] != Json::Value::null) {
pair = new APKeyValuePair("storage_total_size", system_datum["storage_total_size"].asInt64());
pairs->push_back(pair);
}
if (system_datum["storage_used"] != Json::Value::null) {
pair = new APKeyValuePair("storage_used", system_datum["storage_used"].asInt64());
pairs->push_back(pair);
}
if (system_datum["storage_avail"] != Json::Value::null) {
pair = new APKeyValuePair("storage_avail", system_datum["storage_avail"].asInt64());
pairs->push_back(pair);
}
pair = new APKeyValuePair("gh_data_point_id", gh_data_point_id);
pairs->push_back(pair);
_sqlDb->DoInsert("gh_system_data", pairs);
_freeVectorAndData(pairs);
}
// Try and parse image data
for (const Json::Value& image_datum : json["image_data"]) {
if (image_datum["id"] != Json::Value::null && image_datum["filename"] != Json::Value::null) {
pairs = new std::vector<APKeyValuePair*>();
pair = new APKeyValuePair("id", image_datum["id"].asInt64());
pairs->push_back(pair);
pair = new APKeyValuePair("filename", image_datum["filename"].asString());
pairs->push_back(pair);
pair = new APKeyValuePair("gh_data_point_id", gh_data_point_id);
pairs->push_back(pair);
_sqlDb->DoInsert("gh_image_data", pairs);
_freeVectorAndData(pairs);
}
}
} else {
throw APException("Insert gh_data_point mismatched rowid!");
}
} else {
if (json["id"] != Json::Value::null) {
throw APException("Invalid Greenhouse Json Feed: Missing id.");
} else {
throw APException("Invalid Greenhouse Json Feed: Missing timestamp.");
}
}
}
} catch (APSQLException& e) {
fprintf(stdout, "Failed with exception: %s", e.what());
_sqlDb->RollbackTransaction();
throw e;
}
_sqlDb->EndTransaction();
}
void APGreenhouse::_freeVectorAndData(std::vector<APKeyValuePair*>* pairs) {
for (std::vector<APKeyValuePair *>::iterator it = pairs->begin(); it != pairs->end(); ++it) {
delete (*it);
}
delete pairs;
}
| 43.606383 | 295 | 0.567212 | [
"object",
"vector"
] |
c05c9ef768af3654f538b9742d59c0294e18dcbd | 9,680 | cpp | C++ | src/elona/adventurer.cpp | ElonaFoobar/ElonaFoobar | 35864685dcca96c4c9ad683c4f5b3537e86bc06f | [
"MIT"
] | 84 | 2018-03-03T02:44:32.000Z | 2019-07-14T16:16:24.000Z | src/elona/adventurer.cpp | ki-foobar/ElonaFoobar | d251cf5bd8c21789db3b56b1c9b1302ce69b2c2e | [
"MIT"
] | 685 | 2018-02-27T04:31:17.000Z | 2019-07-12T13:43:00.000Z | src/elona/adventurer.cpp | ki-foobar/ElonaFoobar | d251cf5bd8c21789db3b56b1c9b1302ce69b2c2e | [
"MIT"
] | 23 | 2019-07-26T08:52:38.000Z | 2021-11-09T09:21:58.000Z | #include "adventurer.hpp"
#include <string>
#include "area.hpp"
#include "character.hpp"
#include "character_status.hpp"
#include "data/types/type_item.hpp"
#include "data/types/type_skill.hpp"
#include "equipment.hpp"
#include "game.hpp"
#include "i18n.hpp"
#include "inventory.hpp"
#include "item.hpp"
#include "itemgen.hpp"
#include "map.hpp"
#include "message.hpp"
#include "random.hpp"
#include "skill.hpp"
#include "text.hpp"
#include "variables.hpp"
namespace elona
{
namespace
{
void add_adv_log(
const std::string& mark,
const std::string& headline,
const std::string& content)
{
const auto dt = game_date_time();
const auto date_str = std::to_string(dt.year()) + "/" +
std::to_string(dt.month()) + "/" + std::to_string(dt.day()) + " h" +
std::to_string(dt.hour());
txt("[News] " + content, Message::color{ColorIndex::light_brown});
auto headline_ = mark + " " + date_str + " " + headline;
talk_conv(headline_, 38 - en * 5);
auto content_ = content;
talk_conv(content_, 38 - en * 5);
game()->adventurer_logs.append(
AdventurerLog{game_now(), headline_, content_});
}
} // namespace
int i_at_m145 = 0;
void create_all_adventurers()
{
for (auto&& adv : cdata.adventurers())
{
create_adventurer(adv);
}
}
void create_adventurer(Character& adv)
{
flt(0, Quality::miracle);
initlv = rnd_capped(60 + cdata.player().level) + 1;
novoidlv = 1;
const data::InstanceId ids[] = {
"core.warrior", "core.wizard", "core.mercenary_archer"};
chara_create(adv.index, choice(ids), -1, -1);
adv.relationship = Relationship::friendly;
adv.original_relationship = Relationship::friendly;
adv._156 = 100;
adv.set_state(Character::State::adventurer_in_other_map);
adv.image = rnd(33) * 2 + 1 + adv.sex;
adv.name = random_name();
adv.alias = random_title(RandomTitleType::character);
adv.role = Role::adventurer;
p = rnd(450);
if (area_data[p].id == mdata_t::MapId::none ||
area_data[p].id == mdata_t::MapId::your_home ||
area_data[p].type == mdata_t::MapType::temporary)
{
p = 4;
}
if (rnd(4) == 0)
{
p = 5;
}
if (rnd(4) == 0)
{
p = 11;
}
if (rnd(6) == 0)
{
p = 12;
}
adv.current_map = p;
adv.current_dungeon_level = 1;
adv.fame = adv.level * adv.level * 30 + rnd_capped(adv.level * 200 + 100) +
rnd(500);
}
int adventurer_favorite_skill(const Character& adv)
{
const auto seed = adv.index;
randomize(seed);
std::vector<int> skills;
while (skills.size() < 2)
{
const auto skill_id = rnd(300) + 100;
if (the_skill_db[skill_id])
{
skills.push_back(skill_id);
}
}
randomize();
return choice(skills);
}
int adventurer_favorite_stat(const Character& adv)
{
const auto seed = adv.index;
randomize(seed);
const auto ret = rnd(8) + 10;
randomize();
return ret;
}
void adventurer_add_news(
NewsType news_type,
const Character& adventurer,
const std::string& extra_info)
{
switch (news_type)
{
case NewsType::discovery:
add_adv_log(
"@01"s,
i18n::s.get("core.news.discovery.title"),
i18n::s.get(
"core.news.discovery.text",
adventurer.alias,
adventurer.name,
extra_info /* discovered artifact */,
mapname(adventurer.current_map)));
break;
case NewsType::growth:
add_adv_log(
"@02"s,
i18n::s.get("core.news.growth.title"),
i18n::s.get(
"core.news.growth.text",
adventurer.alias,
adventurer.name,
adventurer.level));
break;
case NewsType::recovery:
add_adv_log(
"@02"s,
i18n::s.get("core.news.recovery.title"),
i18n::s.get(
"core.news.recovery.text", adventurer.alias, adventurer.name));
break;
case NewsType::accomplishment:
add_adv_log(
"@03"s,
i18n::s.get("core.news.accomplishment.title"),
i18n::s.get(
"core.news.accomplishment.text",
adventurer.alias,
adventurer.name,
extra_info /* gained fame */));
break;
case NewsType::retirement:
add_adv_log(
"@04"s,
i18n::s.get("core.news.retirement.title"),
i18n::s.get(
"core.news.retirement.text",
adventurer.alias,
adventurer.name));
break;
default: assert(0); break;
}
}
void adventurer_update()
{
for (auto&& adv : cdata.adventurers())
{
if (adv.hire_limit_time != time::Instant::epoch())
{
if (adv.hire_limit_time <= game_now())
{
adv.hire_limit_time = time::Instant::epoch();
adv.is_contracting() = false;
adv.relationship = Relationship::friendly;
txt(i18n::s.get("core.chara.contract_expired", adv));
}
}
if (adv.current_map != game()->current_map)
{
if (adv.state() == Character::State::adventurer_empty)
{
create_adventurer(adv);
continue;
}
if (adv.state() == Character::State::adventurer_dead)
{
if (game_now() >= adv.revival_time)
{
if (rnd(3) == 0)
{
adventurer_add_news(NewsType::retirement, adv);
adv.set_state(Character::State::empty);
create_adventurer(adv);
}
else
{
adventurer_add_news(NewsType::recovery, adv);
adv.set_state(
Character::State::adventurer_in_other_map);
}
continue;
}
}
}
if ((adv.current_map != game()->current_map ||
map_data.type == mdata_t::MapType::world_map) &&
rnd(60) == 0)
{
for (int cnt = 0; cnt < 10; ++cnt)
{
if (rnd(4) == 0)
{
p = rnd(50) + 450;
}
else
{
p = rnd(300);
}
if (area_data[p].id == mdata_t::MapId::none || p == 7 ||
area_data[p].type == mdata_t::MapType::temporary || p == 9)
{
p = 4;
}
if (cnt < 5)
{
if (area_data[p].type != mdata_t::MapType::town)
{
continue;
}
}
break;
}
adv.current_map = p;
adv.current_dungeon_level = 1;
}
if (adv.current_map == game()->current_map)
{
continue;
}
if (rnd(200) == 0)
{
if (area_data[adv.current_map].type != mdata_t::MapType::town)
{
adventurer_discover_equipment(adv);
}
}
if (rnd(10) == 0)
{
adv.experience += adv.level * adv.level * 2;
}
if (rnd(20) == 0)
{
adv.fame += rnd_capped(adv.level * adv.level / 40 + 5) -
rnd_capped(adv.level * adv.level / 50 + 5);
}
if (rnd(2000) == 0)
{
adv.experience +=
clamp(adv.level, 1, 1000) * clamp(adv.level, 1, 1000) * 100;
int fame = rnd_capped(adv.level * adv.level / 20 + 10) + 10;
adv.fame += fame;
adventurer_add_news(
NewsType::accomplishment, adv, std::to_string(fame));
adventurer_discover_equipment(adv);
}
if (adv.experience >= adv.required_experience)
{
r2 = 0;
gain_level(adv);
}
}
const size_t max_logs = 195; // TODO: make it configurable
game()->adventurer_logs.shrink(max_logs);
}
void adventurer_discover_equipment(Character& adv)
{
f = 0;
for (int _i = 0; _i < 10; ++_i)
{
const auto inv = adv.inventory();
const auto item = inv->at(inv_get_random_slot(inv));
if (!item)
{
f = 1;
break;
}
if (item->is_equipped())
{
continue;
}
if (item->number() != 0)
{
if (adv.ai_item == item)
{
adv.ai_item = nullptr;
}
item->remove();
f = 1;
break;
}
}
if (f == 0)
{
return;
}
flt(adv.level, Quality::miracle);
if (rnd(3) == 0)
{
flttypemajor = choice(fsetwear);
}
else
{
flttypemajor = choice(fsetitem);
}
if (const auto item = itemcreate_chara_inv(adv, 0, 0))
{
item->identify_state = IdentifyState::completely;
if (item->quality >= Quality::miracle)
{
if (is_equipment(the_item_db[item->id]->category))
{
adventurer_add_news(
NewsType::discovery, adv, itemname(item.unwrap()));
}
}
wear_most_valuable_equipment(adv, item.unwrap());
}
}
} // namespace elona
| 25.882353 | 79 | 0.489979 | [
"vector"
] |
c05dc3b1258560a99ac7a9fec264d91ba38c571d | 43,132 | hpp | C++ | include/geneva/GConstrainedFPT.hpp | denisbertini/geneva | eff76fc489001512022d1a20c5561623d73efc32 | [
"Apache-2.0",
"BSD-3-Clause"
] | 4 | 2020-05-20T07:23:19.000Z | 2021-09-12T23:12:21.000Z | include/geneva/GConstrainedFPT.hpp | denisbertini/geneva | eff76fc489001512022d1a20c5561623d73efc32 | [
"Apache-2.0",
"BSD-3-Clause"
] | 10 | 2020-05-05T13:24:08.000Z | 2021-07-27T13:23:17.000Z | include/geneva/GConstrainedFPT.hpp | denisbertini/geneva | eff76fc489001512022d1a20c5561623d73efc32 | [
"Apache-2.0",
"BSD-3-Clause"
] | 7 | 2020-04-09T10:33:11.000Z | 2021-09-08T12:24:55.000Z | /********************************************************************************
*
* This file is part of the Geneva library collection. The following license
* applies to this file:
*
* ------------------------------------------------------------------------------
* 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.
* ------------------------------------------------------------------------------
*
* Note that other files in the Geneva library collection may use a different
* license. Please see the licensing information in each file.
*
********************************************************************************
*
* Geneva was started by Dr. Rüdiger Berlich and was later maintained together
* with Dr. Ariel Garcia under the auspices of Gemfony scientific. For further
* information on Gemfony scientific, see http://www.gemfomy.eu .
*
* The majority of files in Geneva was released under the Apache license v2.0
* in February 2020.
*
* See the NOTICE file in the top-level directory of the Geneva library
* collection for a list of contributors and copyright information.
*
********************************************************************************/
#pragma once
// Global checks, defines and includes needed for all of Geneva
#include "common/GGlobalDefines.hpp"
// Standard headers go here
#include <type_traits>
#include <cmath>
#include <cfloat>
// Boost headers go here
#include <boost/math/special_functions/next.hpp> // Needed so we can calculate the next representable value smaller than a given upper boundary
// Geneva headers go here
#include "geneva/GObject.hpp"
#include "geneva/GConstrainedNumT.hpp"
#include "geneva/GParameterBase.hpp"
#include "common/GExceptions.hpp"
#include "common/GCommonMathHelperFunctions.hpp"
#include "hap/GRandomBase.hpp"
#include "hap/GRandomT.hpp"
namespace Gem {
namespace Geneva {
/******************************************************************************/
/* The GConstrainedFPT class represents a floating point type, such as a double,
* equipped with the ability to adapt itself. The value range can have an upper and a lower
* limit. Adapted values will only appear inside the given range to the user. Note that
* appropriate adaptors (see e.g the GDoubleGaussAdaptor class) need to be loaded in order
* to benefit from the adaption capabilities.
*/
template <typename fp_type>
class GConstrainedFPT
: public GConstrainedNumT<fp_type>
{
///////////////////////////////////////////////////////////////////////
friend class boost::serialization::access;
template<typename Archive>
void serialize(Archive & ar, const unsigned int) {
using boost::serialization::make_nvp;
// Save data
ar
& make_nvp("GConstrainedNumT_T", boost::serialization::base_object<GConstrainedNumT<fp_type>>(*this));
}
///////////////////////////////////////////////////////////////////////
// Make sure this class can only be instantiated if fp_type really is a floating point type
static_assert(
std::is_floating_point<fp_type>::value
, "fp_type must be a floating point type"
);
public:
/***************************************************************************/
/**
* The default constructor.
*/
GConstrainedFPT() = default;
/***************************************************************************/
/**
* A constructor that initializes the value only. The boundaries will
* be set to the maximum and minimum values of the corresponding type.
*
* @param val The desired external value of this object
*/
explicit GConstrainedFPT (const fp_type& val)
: GConstrainedNumT<fp_type>(val)
{ /* nothing */ }
/***************************************************************************/
/**
* Initializes the boundaries and assigns a random value.
*
* @param lowerBoundary The lower boundary of the value range
* @param upperBoundary The upper boundary of the value range
*/
GConstrainedFPT (const fp_type& lowerBoundary , const fp_type& upperBoundary)
: GConstrainedNumT<fp_type>(lowerBoundary, boost::math::float_prior<fp_type>(upperBoundary))
{
Gem::Hap::GRandomT<Gem::Hap::RANDFLAVOURS::RANDOMLOCAL> gr;
typename std::uniform_real_distribution<fp_type> uniform_real_distribution(lowerBoundary, upperBoundary);
GParameterT<fp_type>::setValue(uniform_real_distribution(gr));
}
/***************************************************************************/
/**
* Initialization with value and boundaries. We need somewhat tighter
* constraints for the allowed value range than implemented in the
* parent class. Note that we take the liberty to adapt val, if it is
* equal to the unmodified upper boundary. Otherwise you will get an
* error, where what you likely really meant was to start with the
* upper boundary.
*
* @param val The desired value of this object
* @param lowerBoundary The lower boundary of the value range
* @param upperBoundary The upper boundary of the value range
*/
GConstrainedFPT (
const fp_type& val
, const fp_type& lowerBoundary
, const fp_type& upperBoundary
)
: GConstrainedNumT<fp_type>(lowerBoundary, boost::math::float_prior<fp_type>(upperBoundary))
{
if(val == upperBoundary) {
GConstrainedNumT<fp_type>::setValue(boost::math::float_prior<fp_type>(upperBoundary));
} else {
GConstrainedNumT<fp_type>::setValue(val);
}
}
/***************************************************************************/
/**
* A standard copy constructor. Most work is done by the parent
* classes.
*
* @param cp Another GConstrainedNumT<fp_type> object
*/
GConstrainedFPT (const GConstrainedFPT<fp_type>& cp) = default;
/***************************************************************************/
/**
* The standard destructor
*/
~GConstrainedFPT() override = default;
/***************************************************************************/
/**
* A standard assignment operator for T values.
*
* @param The desired new external value
* @return The new external value of this object
*/
GConstrainedNumT<fp_type>& operator=(const fp_type& val) override {
fp_type tmpVal = val;
if(val==boost::math::float_next<fp_type>(this->getUpperBoundary())) {
tmpVal = boost::math::float_prior<fp_type>(val);
}
GConstrainedNumT<fp_type>::operator=(tmpVal);
return *this;
}
/* ----------------------------------------------------------------------------------
* Throwing tested in GConstrainedFPT<fp_type>::specificTestsFailuresExpected_GUnitTests()
* Tested in GConstrainedFPT<fp_type>::specificTestsNoFailuresExpected_GUnitTests()
* ----------------------------------------------------------------------------------
*/
/***************************************************************************/
/**
* Allows to set the value. Has the same constraints as the parent class'es function,
* applies additional restrictions. Note that we take the liberty to adapt val, if it
* is equal to the unmodified upper boundary. Otherwise you will get an error,
* where what you likely really meant was to start with the upper boundary.
*
* @param val The new fp_type value stored in this class
*/
void setValue(const fp_type& val) override {
fp_type tmpVal = val;
if(val==boost::math::float_next<fp_type>(this->getUpperBoundary())) {
tmpVal = boost::math::float_prior<fp_type>(val);
}
GConstrainedNumT<fp_type>::setValue(tmpVal);
}
/* ----------------------------------------------------------------------------------
* Throwing tested in GConstrainedFPT<fp_type>::specificTestsFailuresExpected_GUnitTests()
* Tested in GConstrainedFPT<fp_type>::specificTestsNoFailuresExpected_GUnitTests()
* ----------------------------------------------------------------------------------
*/
/***************************************************************************/
/**
* Allows to set the value of this object together with its boundaries. Note
* that we take the liberty to adapt val, if it is equal to the unmodified upper
* boundary. Otherwise you will get an error, where what you likely really meant
* was to start with the upper boundary.
*
* @param val The desired value of this object
* @param lowerBoundary The lower boundary of the value range
* @param upperBoundary The upper boundary of the value range
*/
void setValue(
const fp_type& val
, const fp_type& lowerBoundary
, const fp_type& upperBoundary
) override {
fp_type tmpVal = val;
if(val==upperBoundary) {
tmpVal = boost::math::float_prior<fp_type>(val);
}
GConstrainedNumT<fp_type>::setValue(
tmpVal
, lowerBoundary
, boost::math::float_prior<fp_type>(upperBoundary)
);
}
/* ----------------------------------------------------------------------------------
* Throwing tested in GConstrainedFPT<fp_type>::specificTestsFailuresExpected_GUnitTests()
* Tested in GConstrainedFPT<fp_type>::specificTestsNoFailuresExpected_GUnitTests()
* ----------------------------------------------------------------------------------
*/
/***************************************************************************/
/**
* Sets the boundaries of this object. This function differs from the parent
* class'es function in that it calculates an additional quantity, the closed
* upper boundary (upper is assumed to be an open, i.e. non-inclusive boundary).
*
* @param lower The new lower boundary for this object
* @param upper The new upper boundary for this object
*/
void setBoundaries(const fp_type& lowerBoundary, const fp_type& upperBoundary) override {
// Set the actual boundaries
GConstrainedNumT<fp_type>::setBoundaries(lowerBoundary, boost::math::float_prior<fp_type>(upperBoundary));
}
/***************************************************************************/
/**
* The transfer function needed to calculate the externally visible value.
* Note that in GConstrainedNumT<>::value() val is shifted to the
* "mapping" value, so it doesn't get too large. This happens centrally,
* as it is also relevant for the integer case. We calculate in long double
* precision here in order to avoid as much as possible numeric instabilities.
* Likewise we use int64_t for the region.
*
* @param val The value to which the transformation should be applied
* @return The transformed value
*/
fp_type transfer(const fp_type& val) const override {
// Check if val has a suitable value
#ifdef DEBUG
switch(std::fpclassify(val)) {
case FP_NORMAL:
case FP_ZERO: {
/* nothing */
} break;
case FP_INFINITE: {
throw gemfony_exception(
g_error_streamer(DO_LOG, time_and_place)
<< "In GConstrainedFPT::transfer(): Error" << std::endl
<< "val is infinite" << std::endl
);
} break;
case FP_NAN: {
throw gemfony_exception(
g_error_streamer(DO_LOG, time_and_place)
<< "In GConstrainedFPT::transfer(): Error" << std::endl
<< "val is NaN" << std::endl
);
} break;
case FP_SUBNORMAL: {
throw gemfony_exception(
g_error_streamer(DO_LOG, time_and_place)
<< "In GConstrainedFPT::transfer(): Error" << std::endl
<< "val is subnormal" << std::endl
);
} break;
default: {
throw gemfony_exception(
g_error_streamer(DO_LOG, time_and_place)
<< "In GConstrainedFPT::transfer(): Error" << std::endl
<< "Unknown value type" << std::endl
);
}
}
#endif /* DEBUG */
long double localVal = boost::numeric_cast<long double>(val);
long double lowerBoundary = boost::numeric_cast<long double>(GConstrainedNumT<fp_type>::getLowerBoundary());
long double upperBoundary = boost::numeric_cast<long double>(GConstrainedNumT<fp_type>::getUpperBoundary());
if(localVal >= lowerBoundary && localVal < upperBoundary) {
return val; // no cast needed
} else {
// Find out which region the value is in (compare figure transferFunction.pdf
// that should have been delivered with this software). Note that boost::numeric_cast<>
// may throw - exceptions must be caught in surrounding functions.
std::int64_t region = 0;
#ifdef DEBUG
long double fp_region = Gem::Common::gfloor((localVal - (long double)(lowerBoundary)) / ((long double)(upperBoundary) - (long double)(lowerBoundary)));
if(Gem::Common::gfabs(fp_region) < boost::numeric_cast<long double>((std::numeric_limits<std::int64_t>::max)())) {
// We need floor here, as an integer cast rounds towards 0, which would be wrong for negative values of val
region = boost::numeric_cast<std::int64_t>(fp_region);
} else {
throw gemfony_exception(
g_error_streamer(DO_LOG, time_and_place)
<< "In GConstrainedFPT::transfer(): Error" << std::endl
<< "fp_region = " << fp_region << " is too large and cannot be" << std::endl
<< "converted to a std::int64_t, which has a maximum value of " << (std::numeric_limits<std::int64_t>::max)() << std::endl
);
}
#else /* DEBUG */
region = static_cast<std::int64_t>(Gem::Common::gfloor((localVal - (long double)(lowerBoundary)) / ((long double)(upperBoundary) - (long double)(lowerBoundary))));
#endif /* DEBUG */
// Check whether we are in an odd or an even range and calculate the
// external value accordingly
long double mapping = (long double)(0.);
if(region%2 == 0) { // can it be divided by 2 ? Region 0,2,... or a negative even range
mapping = localVal - (long double)(region) * (upperBoundary - lowerBoundary);
} else { // Range 1,3,... or a negative odd range
mapping = -localVal + ((long double)(region-1)*(upperBoundary - lowerBoundary) + 2*upperBoundary);
}
// fabs(mapping) will always be <= fabs(val), so this cast should never fail (if val was a valid fp value)
return boost::numeric_cast<fp_type>(mapping);
}
// Make the compiler happy
return fp_type(0.);
}
/* ----------------------------------------------------------------------------------
* Tested in GConstrainedFPT<fp_type>::specificTestsNoFailuresExpected_GUnitTests()
* ----------------------------------------------------------------------------------
*/
protected:
/***************************************************************************/
/**
* Loads the data of another GConstrainedFPT<fp_type>, camouflaged as a GObject.
*
* @param cp Another GConstrainedFPT<fp_type> object, camouflaged as a GObject
*/
void load_(const GObject *cp) override {
// Check that we are dealing with a GConstrainedFPT<fp_type> reference independent of this object and convert the pointer
const GConstrainedFPT<fp_type> *p_load = Gem::Common::g_convert_and_compare<GObject, GConstrainedFPT<fp_type>>(cp, this);
// Load our parent class'es data ...
GConstrainedNumT<fp_type>::load_(cp);
// no local data ...
}
/***************************************************************************/
/** @brief Allow access to this classes compare_ function */
friend void Gem::Common::compare_base_t<GConstrainedFPT<fp_type>>(
GConstrainedFPT<fp_type> const &
, GConstrainedFPT<fp_type> const &
, Gem::Common::GToken &
);
/***************************************************************************/
/**
* Searches for compliance with expectations with respect to another object
* of the same type
*
* @param cp A constant reference to another GObject object
* @param e The expected outcome of the comparison
* @param limit The maximum deviation for floating point values (important for similarity checks)
*/
void compare_(
const GObject& cp
, const Gem::Common::expectation& e
, const double& limit
) const override {
using namespace Gem::Common;
// Check that we are dealing with a GConstrainedFPT<fp_type> reference independent of this object and convert the pointer
const GConstrainedFPT<fp_type> *p_load = Gem::Common::g_convert_and_compare<GObject, GConstrainedFPT<fp_type>>(cp, this);
GToken token("GConstrainedFPT<fp_type>", e);
// Compare our parent data ...
Gem::Common::compare_base_t<GConstrainedNumT<fp_type>>(*this, *p_load, token);
// React on deviations from the expectation
token.evaluate();
}
/***************************************************************************/
/**
* Randomly initializes the parameter (within its limits)
*/
bool randomInit_(
const activityMode&
, Gem::Hap::GRandomBase& gr
) override {
typename std::uniform_real_distribution<fp_type> uniform_real_distribution(
GConstrainedNumT<fp_type>::getLowerBoundary()
, GConstrainedNumT<fp_type>::getUpperBoundary()
);
this->setValue(uniform_real_distribution(gr));
return true;
}
/* ----------------------------------------------------------------------------------
* Tested in GConstrainedFPT<fp_type>::specificTestsNoFailuresExpected_GUnitTests()
* ----------------------------------------------------------------------------------
*/
/***************************************************************************/
/**
* Applies modifications to this object. This is needed for testing purposes
*
* @return A boolean which indicates whether modifications were made
*/
bool modify_GUnitTests_() override {
#ifdef GEM_TESTING
bool result = false;
// Call the parent classes' functions
if(GConstrainedNumT<fp_type>::modify_GUnitTests_()) result = true;
return result;
#else /* GEM_TESTING */ // If this function is called when GEM_TESTING isn't set, throw
Gem::Common::condnotset("GConstrainedFPT<>::modify_GUnitTests", "GEM_TESTING");
return false;
#endif /* GEM_TESTING */
}
/***************************************************************************/
/**
* Performs self tests that are expected to succeed. This is needed for testing purposes
*/
void specificTestsNoFailureExpected_GUnitTests_() override {
#ifdef GEM_TESTING
// Some general settings
const std::size_t nTests = 10000;
const fp_type testVal = fp_type(42);
const fp_type testVal2 = fp_type(17);
const fp_type lowerBoundary = fp_type(0);
const fp_type upperBoundary = fp_type(100);
const fp_type lowerRandomBoundary = fp_type(-100000);
const fp_type upperRandomBoundary = fp_type( 100000);
// Call the parent classes' functions
GConstrainedNumT<fp_type>::specificTestsNoFailureExpected_GUnitTests_();
// A random generator
Gem::Hap::GRandomT<Gem::Hap::RANDFLAVOURS::RANDOMPROXY> gr;
//------------------------------------------------------------------------------
{ // Check that assignment of a value with operator= works both for set and unset boundaries
std::shared_ptr<GConstrainedFPT<fp_type>> p_test = this->template clone<GConstrainedFPT<fp_type>>();
// Reset the boundaries so we are free to do what we want
BOOST_CHECK_NO_THROW(p_test->resetBoundaries());
// Assign a value with operator=
BOOST_CHECK_NO_THROW(*p_test = testVal2);
// Check the value
BOOST_CHECK(p_test->value() == testVal2);
// Assign boundaries and values
BOOST_CHECK_NO_THROW(p_test->setValue(testVal2, lowerBoundary, upperBoundary));
// Check the value again
BOOST_CHECK(p_test->value() == testVal2);
// Assign a value with operator=
BOOST_CHECK_NO_THROW(*p_test = testVal);
// Check the value again, should have changed
BOOST_CHECK(p_test->value() == testVal);
}
//------------------------------------------------------------------------------
{ // Check that assignment of a value with setValue(val) works both for set and unset boundaries
std::shared_ptr<GConstrainedFPT<fp_type>> p_test = this->template clone<GConstrainedFPT<fp_type>>();
// Reset the boundaries so we are free to do what we want
BOOST_CHECK_NO_THROW(p_test->resetBoundaries());
// Assign a value
BOOST_CHECK_NO_THROW(p_test->setValue(testVal2));
// Check the value
BOOST_CHECK(p_test->value() == testVal2);
// Assign new boundaries
BOOST_CHECK_NO_THROW(p_test->setBoundaries(lowerBoundary, upperBoundary));
// Cross-check that boundaries are o.k.
BOOST_CHECK(p_test->getLowerBoundary() == lowerBoundary);
BOOST_CHECK(p_test->getUpperBoundary() == boost::math::float_prior<fp_type>(upperBoundary));
// Check the value again
BOOST_CHECK(p_test->value() == testVal2);
// Assign a new value
BOOST_CHECK_NO_THROW(p_test->setValue(testVal));
// Check the value again, should have changed
BOOST_CHECK(p_test->value() == testVal);
}
//------------------------------------------------------------------------------
{ // Check that simultaneous assignment of a valid value and boundaries works
std::shared_ptr<GConstrainedFPT<fp_type>> p_test = this->template clone<GConstrainedFPT<fp_type>>();
// Reset the boundaries so we are free to do what we want
BOOST_CHECK_NO_THROW(p_test->resetBoundaries());
// Assign boundaries and values
BOOST_CHECK_NO_THROW(p_test->setValue(testVal, lowerBoundary, upperBoundary));
// Cross-check that value and boundaries are o.k.
BOOST_CHECK_MESSAGE(
p_test->getLowerBoundary() == lowerBoundary
, "\n"
<< std::setprecision(16)
<< "Invalid lower boundary found:\n"
<< "getLowerBoundary() = " << p_test->getLowerBoundary()
<< "expected " << lowerBoundary << "\n"
);
BOOST_CHECK_MESSAGE(
p_test->getUpperBoundary() == boost::math::float_prior<fp_type>(upperBoundary)
, "\n"
<< std::setprecision(16)
<< "Invalid upper boundary found:\n"
<< "getUpperBoundary() = " << p_test->getUpperBoundary() << "\n"
<< "expected " << boost::math::float_prior<fp_type>(upperBoundary) << "\n"
<< "Difference is " << p_test->getUpperBoundary() - boost::math::float_prior<fp_type>(upperBoundary) << "\n"
);
BOOST_CHECK(p_test->value() == testVal);
}
//------------------------------------------------------------------------------
{ // Check a number of times that calls to the transfer function do not lie outside of the allowed boundaries
std::shared_ptr<GConstrainedFPT<fp_type>> p_test = this->template clone<GConstrainedFPT<fp_type>>();
fp_type result = 0.;
for(fp_type offset = fp_type(-100); offset < fp_type(100); offset += fp_type(10)) {
fp_type tmpLowerBoundary = lowerBoundary + offset;
fp_type tmpUpperBoundary = upperBoundary + offset;
// Assign valid boundaries and value
BOOST_CHECK_NO_THROW(p_test->setValue(tmpLowerBoundary, tmpLowerBoundary, tmpUpperBoundary));
typename std::uniform_real_distribution<fp_type> uniform_real_distribution(lowerRandomBoundary, upperRandomBoundary);
for(std::size_t i=0; i<nTests; i++) {
fp_type randomValue = uniform_real_distribution(gr);
BOOST_CHECK_NO_THROW(result = p_test->transfer(randomValue));
BOOST_CHECK_MESSAGE(
result >= tmpLowerBoundary && result < tmpUpperBoundary
, "\n"
<< std::setprecision(6)
<< "randomValue = " << randomValue << "\n"
<< "after transfer = " << result << "\n"
<< "lowerBoundary = " << tmpLowerBoundary << "\n"
<< "upperBoundary = " << tmpUpperBoundary << "\n"
);
}
}
}
//------------------------------------------------------------------------------
{ // Test initialization with a single "fixed" value (chosen randomly in a given range)
std::shared_ptr<GConstrainedFPT<fp_type>> p_test = this->template clone<GConstrainedFPT<fp_type>>();
// Assign a valid value and boundaries
BOOST_CHECK_NO_THROW(p_test->setValue(testVal, lowerBoundary, upperBoundary));
typename std::uniform_real_distribution<fp_type> uniform_real_distribution(lowerRandomBoundary, upperRandomBoundary);
for(std::size_t i=0; i<nTests; i++) {
fp_type randomValue = uniform_real_distribution(gr);
// Randomly initialize with a "fixed" value
BOOST_CHECK_NO_THROW(p_test->GParameterBase::template fixedValueInit<fp_type>(randomValue, activityMode::ALLPARAMETERS));
// Check that the external value is inside of the allowed value range
// Check that the value is still in the allowed range
BOOST_CHECK_MESSAGE(
p_test->value() >= lowerBoundary && p_test->value() < upperBoundary
, "\n"
<< std::setprecision(10)
<< "p_test->value() = " << p_test->value() << "\n"
<< "lowerBoundary = " << lowerBoundary << "\n"
<< "upperBoundary = " << upperBoundary << "\n"
);
}
}
//------------------------------------------------------------------------------
{ // Test multiplication with a single floating point value that won't make the internal value leave the boundaries
std::shared_ptr<GConstrainedFPT<fp_type>> p_test = this->template clone<GConstrainedFPT<fp_type>>();
// Reset the boundaries so we are free to do what we want
BOOST_CHECK_NO_THROW(p_test->resetBoundaries());
// Assign a value
BOOST_CHECK_NO_THROW(p_test->setValue(fp_type(1), fp_type(0), fp_type(100)));
for(std::size_t i=1; i<99; i++) {
// Multiply by the counter variable
BOOST_CHECK_NO_THROW(p_test->GParameterBase::template multiplyBy<fp_type>(fp_type(i), activityMode::ALLPARAMETERS));
// Check that the external value is in the expected range
BOOST_CHECK_MESSAGE (
fabs(p_test->value() - fp_type(i)) < pow(10, -8) // This also means that the value has changed from its start value 1
, "\n"
<< std::setprecision(10)
<< "p_test->value() = " << p_test->value() << "\n"
<< "fp_type(i) = " << fp_type(i) << "\n"
<< "pow(10, -8) = " << pow(10, -8) << "\n"
);
// Check that the internal value is in the expected range
BOOST_CHECK_MESSAGE (
fabs(p_test->getInternalValue() - fp_type(i)) < pow(10, -8)
, "\n"
<< std::setprecision(10)
<< "p_test->getInternalValue() = " << p_test->getInternalValue() << "\n"
<< "fp_type(i) = " << fp_type(i) << "\n"
<< "pow(10, -8) = " << pow(10, -8) << "\n"
);
// Reset the value
BOOST_CHECK_NO_THROW(p_test->setValue(fp_type(1)));
}
}
//------------------------------------------------------------------------------
{ // Test multiplication with a single floating point value that will make the internal value leave its boundaries
std::shared_ptr<GConstrainedFPT<fp_type>> p_test = this->template clone<GConstrainedFPT<fp_type>>();
// Assign boundaries and values
BOOST_CHECK_NO_THROW(p_test->setValue(fp_type(1), lowerBoundary, upperBoundary));
typename std::uniform_real_distribution<fp_type> uniform_real_distribution(lowerRandomBoundary, upperRandomBoundary);
for(std::size_t i=0; i<nTests; i++) {
// Multiply with a random value in a very wide
BOOST_CHECK_NO_THROW(p_test->GParameterBase::template multiplyBy<fp_type>(uniform_real_distribution(gr), activityMode::ALLPARAMETERS));
// Check that the value is still in the allowed range
BOOST_CHECK_MESSAGE(
p_test->value() >= lowerBoundary && p_test->value() < upperBoundary
, "\n"
<< std::setprecision(10)
<< "p_test->value() = " << p_test->value() << "\n"
<< "lowerBoundary = " << lowerBoundary << "\n"
<< "upperBoundary = " << upperBoundary << "\n"
);
// Reset the value
BOOST_CHECK_NO_THROW(p_test->setValue(fp_type(1)));
}
}
//------------------------------------------------------------------------------
{ // Check multiplication with a random number in a wide range that might make the internal value leave its boundaries
std::shared_ptr<GConstrainedFPT<fp_type>> p_test = this->template clone<GConstrainedFPT<fp_type>>();
// Assign boundaries and values
BOOST_CHECK_NO_THROW(p_test->setValue(fp_type(1), lowerBoundary, upperBoundary));
for(std::size_t i=0; i<nTests; i++) {
// Multiply with a random value in a very wide
BOOST_CHECK_NO_THROW(p_test->GParameterBase::template multiplyByRandom<fp_type>(lowerRandomBoundary, upperRandomBoundary, activityMode::ALLPARAMETERS, gr));
// Check that the value is still in the allowed range
BOOST_CHECK_MESSAGE(
p_test->value() >= lowerBoundary && p_test->value() < upperBoundary
, "\n"
<< std::setprecision(10)
<< "p_test->value() = " << p_test->value() << "\n"
<< "lowerBoundary = " << lowerBoundary << "\n"
<< "upperBoundary = " << upperBoundary << "\n"
);
// Reset the value
BOOST_CHECK_NO_THROW(p_test->setValue(fp_type(1)));
}
}
//------------------------------------------------------------------------------
{ // Check multiplication with a random number in the range [0:1[. As the value used for the
// basis of this multiplication is the lower boundary, multiplication will bring the internal
// value outside of the external boundaries
std::shared_ptr<GConstrainedFPT<fp_type>> p_test = this->template clone<GConstrainedFPT<fp_type>>();
// Assign boundaries and values
BOOST_CHECK_NO_THROW(p_test->setValue(lowerBoundary, lowerBoundary, upperBoundary));
for(std::size_t i=0; i<nTests; i++) {
// Multiply with a random value in a very wide
BOOST_CHECK_NO_THROW(p_test->GParameterBase::template multiplyByRandom<fp_type>(activityMode::ALLPARAMETERS, gr));
// Check that the value is still in the allowed range
BOOST_CHECK_MESSAGE(
p_test->value() >= lowerBoundary && p_test->value() < upperBoundary
, "\n"
<< std::setprecision(10)
<< "p_test->value() = " << p_test->value() << "\n"
<< "lowerBoundary = " << lowerBoundary << "\n"
<< "upperBoundary = " << upperBoundary << "\n"
);
// Reset the value
BOOST_CHECK_NO_THROW(p_test->setValue(lowerBoundary));
}
}
//------------------------------------------------------------------------------
{ // Test adding of objects with fpAdd. We try to stay inside of the value range
const fp_type lower = fp_type(-10000.), upper = fp_type(10000.);
std::shared_ptr<GConstrainedFPT<fp_type>> p_test1 = this->template clone<GConstrainedFPT<fp_type>>();
std::shared_ptr<GConstrainedFPT<fp_type>> p_test2 = this->template clone<GConstrainedFPT<fp_type>>();
// Reset the boundaries so we are free to do what we want
BOOST_CHECK_NO_THROW(p_test1->resetBoundaries());
// Assign a value and boundaries
BOOST_CHECK_NO_THROW(p_test1->setValue(lower, lower, upper));
// Load p_test1 into p_test2
BOOST_CHECK_NO_THROW(p_test2->load(p_test1));
// Assign a value of 1 to p_test2
BOOST_CHECK_NO_THROW(p_test2->GParameterBase::template fixedValueInit<fp_type>(fp_type(1.), activityMode::ALLPARAMETERS));
fp_type currentVal = fp_type(-10000.);
for(std::int32_t i=-9999; i<9999; i++) {
BOOST_CHECK_NO_THROW(p_test1->GParameterBase::template add<fp_type>(p_test2, activityMode::ALLPARAMETERS));
currentVal += fp_type(1.);
BOOST_CHECK(p_test1->value() == currentVal);
}
}
//------------------------------------------------------------------------------
{ // Test subtraction of objects with fpSubtract. We try to stay inside of the value range
const fp_type lower = fp_type(-10000.), upper = fp_type(10000.);
std::shared_ptr<GConstrainedFPT<fp_type>> p_test1 = this->template clone<GConstrainedFPT<fp_type>>();
std::shared_ptr<GConstrainedFPT<fp_type>> p_test2 = this->template clone<GConstrainedFPT<fp_type>>();
// Reset the boundaries so we are free to do what we want
BOOST_CHECK_NO_THROW(p_test1->resetBoundaries());
// Assign a value and boundaries
BOOST_CHECK_NO_THROW(p_test1->setValue(upper - fp_type(1.), lower, upper));
// Load p_test1 into p_test2
BOOST_CHECK_NO_THROW(p_test2->load(p_test1));
// Assign a value of 1 to p_test2
BOOST_CHECK_NO_THROW(p_test2->GParameterBase::template fixedValueInit<fp_type>(fp_type(1.), activityMode::ALLPARAMETERS));
fp_type currentVal = fp_type(upper - fp_type(1));
for(std::int32_t i=9999; i>=-9998; i--) {
BOOST_CHECK_NO_THROW(p_test1->GParameterBase::template subtract<fp_type>(p_test2, activityMode::ALLPARAMETERS));
currentVal -= fp_type(1.);
BOOST_CHECK(p_test1->value() == currentVal);
}
}
//------------------------------------------------------------------------------
{ // Test random initialization, as well as adding and subtraction of random values, which may leave the value range
const fp_type lower = fp_type(-10000.), upper = fp_type(10000.);
std::shared_ptr<GConstrainedFPT<fp_type>> p_test1 = this->template clone<GConstrainedFPT<fp_type>>();
std::shared_ptr<GConstrainedFPT<fp_type>> p_test2 = this->template clone<GConstrainedFPT<fp_type>>();
// Assign a value and boundaries
BOOST_CHECK_NO_THROW(p_test1->setValue(fp_type(0.), lower, upper));
BOOST_CHECK_NO_THROW(p_test2->setValue(fp_type(0.), lower, upper));
// Repeatedly add and subtract a randomly initialized p_test2 from p_test1
for(std::size_t i=0; i<nTests; i++) {
// Randomly initialize p_test2
BOOST_CHECK_NO_THROW(p_test2->randomInit_(activityMode::ALLPARAMETERS, gr));
fp_type firstValue = p_test2->value();
// Inside of the allowed value range ?
BOOST_CHECK(firstValue >= lower);
BOOST_CHECK(firstValue < upper);
// Add to p_test1
BOOST_CHECK_NO_THROW(p_test1->GParameterBase::template add<fp_type>(p_test2, activityMode::ALLPARAMETERS));
// Check that p_test1 is still inside of the allowed value range
BOOST_CHECK(p_test1->value() >= lower);
BOOST_CHECK(p_test1->value() < upper);
// Randomly initialize p_test2 again
BOOST_CHECK_NO_THROW(p_test2->randomInit_(activityMode::ALLPARAMETERS, gr));
fp_type secondValue = p_test2->value();
// Inside of the allowed value range ?
BOOST_CHECK(secondValue >= lower);
BOOST_CHECK(secondValue < upper);
// Has the value changed at all ?
BOOST_CHECK(firstValue != secondValue);
// Subtract from p_test1
BOOST_CHECK_NO_THROW(p_test1->GParameterBase::template subtract<fp_type>(p_test2, activityMode::ALLPARAMETERS));
// Check that p_test1 is still inside of the allowed value range
BOOST_CHECK(p_test1->value() >= lower);
BOOST_CHECK(p_test1->value() < upper);
}
}
//------------------------------------------------------------------------------
#else /* GEM_TESTING */ // If this function is called when GEM_TESTING isn't set, throw
Gem::Common::condnotset("GConstrainedFPT<>::specificTestsNoFailureExpected_GUnitTests", "GEM_TESTING");
#endif /* GEM_TESTING */
}
/***************************************************************************/
/**
* Performs self tests that are expected to fail. This is needed for testing purposes
*/
void specificTestsFailuresExpected_GUnitTests_() override {
#ifdef GEM_TESTING
// Some general settings
const fp_type testVal = fp_type(42);
const fp_type lowerBoundary = fp_type(0);
const fp_type upperBoundary = fp_type(100);
// Call the parent classes' functions
GConstrainedNumT<fp_type>::specificTestsFailuresExpected_GUnitTests_();
//------------------------------------------------------------------------------
{ // Check that assignment of a value equal to the upper boundary with setValue(val, lower, upper) throws
std::shared_ptr<GConstrainedFPT<fp_type>> p_test = this->template clone<GConstrainedFPT<fp_type>>();
// Reset the boundaries so we are free to do what we want
BOOST_CHECK_NO_THROW(p_test->resetBoundaries());
// Set value, upper and lower boundaries; should throw, as value >= upperBoundary
BOOST_CHECK_THROW(p_test->setValue(1.1*upperBoundary, lowerBoundary, upperBoundary), gemfony_exception);
}
//------------------------------------------------------------------------------
{ // Check that assignment of a value equal to the upper boundary with setValue() throws
std::shared_ptr<GConstrainedFPT<fp_type>> p_test = this->template clone<GConstrainedFPT<fp_type>>();
// Reset the boundaries so we are free to do what we want
BOOST_CHECK_NO_THROW(p_test->resetBoundaries());
// Set value, upper and lower boundaries
BOOST_CHECK_NO_THROW(p_test->setValue(testVal, lowerBoundary, upperBoundary));
// Try to set a value equal to the upper boundary, should throw
BOOST_CHECK_THROW(p_test->setValue(1.1*upperBoundary), gemfony_exception);
}
//------------------------------------------------------------------------------
{ // Check that setting an upper boundary <= lower boundary with setBoundaries(lower, upper) throws
std::shared_ptr<GConstrainedFPT<fp_type>> p_test = this->template clone<GConstrainedFPT<fp_type>>();
// Reset the boundaries so we are free to do what we want
BOOST_CHECK_NO_THROW(p_test->resetBoundaries());
// Try to set an upper boundary == lower boundary
BOOST_CHECK_THROW(p_test->setBoundaries(lowerBoundary, lowerBoundary), gemfony_exception);
}
//------------------------------------------------------------------------------
{ // Check that setting an upper boundary <= lower boundary with setValue(val, lower, upper) throws
std::shared_ptr<GConstrainedFPT<fp_type>> p_test = this->template clone<GConstrainedFPT<fp_type>>();
// Reset the boundaries so we are free to do what we want
BOOST_CHECK_NO_THROW(p_test->resetBoundaries());
// Try to set an upper boundary == lower boundary
BOOST_CHECK_THROW(p_test->setValue(lowerBoundary, lowerBoundary, lowerBoundary), gemfony_exception);
}
//------------------------------------------------------------------------------
{ // Check that setting an upper boundary larger than the allowed value (see GConstrainedValueLimit<T>) with the setValue(val, lower, upper) function throws
std::shared_ptr<GConstrainedFPT<fp_type>> p_test = this->template clone<GConstrainedFPT<fp_type>>();
// Reset the boundaries so we are free to do what we want
BOOST_CHECK_NO_THROW(p_test->resetBoundaries());
// Check that the boundaries have the expected values
BOOST_CHECK(p_test->getLowerBoundary() == GConstrainedValueLimitT<fp_type>::lowest());
BOOST_CHECK(p_test->getUpperBoundary() == boost::math::float_prior<fp_type>(GConstrainedValueLimitT<fp_type>::highest()));
// Try to set a boundary to a bad value
BOOST_CHECK_THROW(p_test->setValue(lowerBoundary, lowerBoundary, boost::numeric::bounds<fp_type>::highest()), gemfony_exception);
}
//------------------------------------------------------------------------------
{ // Check that setting a lower boundary smaller than the allowed value (see GConstrainedValueLimit<T>) with the setValue(val, lower, upper) function throws
std::shared_ptr<GConstrainedFPT<fp_type>> p_test = this->template clone<GConstrainedFPT<fp_type>>();
// Reset the boundaries so we are free to do what we want
BOOST_CHECK_NO_THROW(p_test->resetBoundaries());
// Check that the boundaries have the expected values
BOOST_CHECK(p_test->getLowerBoundary() == GConstrainedValueLimitT<fp_type>::lowest());
BOOST_CHECK(p_test->getUpperBoundary() == boost::math::float_prior<fp_type>(GConstrainedValueLimitT<fp_type>::highest()));
// Try to set a boundary to a bad value
BOOST_CHECK_THROW(p_test->setValue(0., boost::numeric::bounds<fp_type>::lowest(), upperBoundary), gemfony_exception);
}
//------------------------------------------------------------------------------
{ // Check that setting an upper boundary larger than the allowed value (see GConstrainedValueLimit<T>) with the setBoundaries(lower, upper) function throws
std::shared_ptr<GConstrainedFPT<fp_type>> p_test = this->template clone<GConstrainedFPT<fp_type>>();
// Reset the boundaries so we are free to do what we want
BOOST_CHECK_NO_THROW(p_test->resetBoundaries());
// Check that the boundaries have the expected values
BOOST_CHECK(p_test->getLowerBoundary() == GConstrainedValueLimitT<fp_type>::lowest());
BOOST_CHECK(p_test->getUpperBoundary() == boost::math::float_prior<fp_type>(GConstrainedValueLimitT<fp_type>::highest()));
// Try to set a boundary to a bad value
BOOST_CHECK_THROW(p_test->setBoundaries(lowerBoundary, boost::numeric::bounds<fp_type>::highest()), gemfony_exception);
}
//------------------------------------------------------------------------------
{ // Check that setting a lower boundary smaller than the allowed value (see GConstrainedValueLimit<T>) with the setBoundaries(lower, upper) function throws
std::shared_ptr<GConstrainedFPT<fp_type>> p_test = this->template clone<GConstrainedFPT<fp_type>>();
// Reset the boundaries so we are free to do what we want
BOOST_CHECK_NO_THROW(p_test->resetBoundaries());
// Check that the boundaries have the expected values
BOOST_CHECK(p_test->getLowerBoundary() == GConstrainedValueLimitT<fp_type>::lowest());
BOOST_CHECK(p_test->getUpperBoundary() == boost::math::float_prior<fp_type>(GConstrainedValueLimitT<fp_type>::highest()));
// Try to set a boundary to a bad value
BOOST_CHECK_THROW(p_test->setBoundaries(boost::numeric::bounds<fp_type>::lowest(), upperBoundary), gemfony_exception);
}
//------------------------------------------------------------------------------
#else /* GEM_TESTING */ // If this function is called when GEM_TESTING isn't set, throw
Gem::Common::condnotset("GConstrainedFPT<>::specificTestsFailuresExpected_GUnitTests", "GEM_TESTING");
#endif /* GEM_TESTING */
}
private:
/***************************************************************************/
/**
* Emits a name for this class / object
*/
std::string name_() const override {
return std::string("GConstrainedFPT");
}
/***************************************************************************/
/** @brief Create a deep copy of this object */
GObject *clone_() const override = 0;
/***************************************************************************/
};
} /* namespace Geneva */
} /* namespace Gem */
/******************************************************************************/
// The content of BOOST_SERIALIZATION_ASSUME_ABSTRACT(T)
namespace boost {
namespace serialization {
template<typename fp_type>
struct is_abstract<Gem::Geneva::GConstrainedFPT<fp_type>> : public boost::true_type {};
template<typename fp_type>
struct is_abstract< const Gem::Geneva::GConstrainedFPT<fp_type>> : public boost::true_type {};
}
}
/******************************************************************************/
| 41.156489 | 167 | 0.623922 | [
"object"
] |
c061dcc30bd327540e47de2f1e54b46048876779 | 28,850 | cpp | C++ | plugins/cinema4dsdk/source/gui/objectdata_getsetdparameter.cpp | urender-vt/cinema4d_cpp_sdk_extended | 77235d2e382d1536e0e694609929dbb74883072a | [
"Apache-2.0"
] | 23 | 2018-09-05T21:11:07.000Z | 2022-01-12T10:43:17.000Z | plugins/cinema4dsdk/source/gui/objectdata_getsetdparameter.cpp | urender-vt/cinema4d_cpp_sdk_extended | 77235d2e382d1536e0e694609929dbb74883072a | [
"Apache-2.0"
] | null | null | null | plugins/cinema4dsdk/source/gui/objectdata_getsetdparameter.cpp | urender-vt/cinema4d_cpp_sdk_extended | 77235d2e382d1536e0e694609929dbb74883072a | [
"Apache-2.0"
] | 4 | 2019-07-12T16:57:20.000Z | 2021-06-23T15:33:09.000Z | // Example on how to handle Get-/SetDParameter for certain CustomGUIs
// This example has no use for the user.
// It simply creates CustomGUI descriptions dynamically and handles all subchannels in Get-/SetDParameter(),
// emulating the internal behavior of these CustomGUIs.
#include "c4d.h"
#include "c4d_symbols.h"
#include "main.h"
#include "customgui_texbox.h"
// NOTE: Be sure to use a unique ID obtained from www.plugincafe.com!
#define ID_GETSETDPARAMETEREXAMPLE 1035580
#define ID_SPLINE 1000
#define ID_GRADIENT 1001
#define ID_LINK 1002
static const Int32 SPLINE_SC_KNOT_POS_X = 0; // Float
static const Int32 SPLINE_SC_KNOT_POS_Y = 1; // Float
static const Int32 SPLINE_SC_KNOT_TANGENT_LEFT_X = 2; // Float
static const Int32 SPLINE_SC_KNOT_TANGENT_LEFT_Y = 3; // Float
static const Int32 SPLINE_SC_KNOT_TANGENT_RIGHT_X = 4; // Float
static const Int32 SPLINE_SC_KNOT_TANGENT_RIGHT_Y = 5; // Float
static const Int32 SPLINE_SC_KNOT_TANGENT_BREAK = 6; // Bool
static const Int32 SPLINE_SC_KNOT_INTERPOLATIOM = 7; // CustomSplineKnotInterpolation / Int32
static const Int32 SPLINE_SC_KNOT_LOCK_X = 8; // Bool
static const Int32 SPLINE_SC_KNOT_LOCK_Y = 9; // Bool
static const Int32 SPLINE_SC_KNOT_LOCK_TANGENT_ANGLE = 10; // Bool
static const Int32 SPLINE_SC_KNOT_LOCK_TANGENT_LENGTH = 11; // Bool
static const Int32 SPLINE_SC_TENSION = 1000; // Float
static const Int32 SPLINE_SC_KNOT_BASE = 10100; // if >=, decode subchannels
#define SPLINE_MAX_IDS_PER_KNOT 100
#define SPLINE_DECODE_KNOT_INDEX(id) ((id - (SPLINE_SC_KNOT_BASE + SPLINE_SC_TENSION)) / SPLINE_MAX_IDS_PER_KNOT)
#define SPLINE_DECODE_KNOT_SUBCHANNEL(id) (id % SPLINE_MAX_IDS_PER_KNOT)
static const Int32 GRADIENT_SC_KNOT_COLOR = 0; // Vector
static const Int32 GRADIENT_SC_KNOT_INTENSITY = 1; // Float
static const Int32 GRADIENT_SC_KNOT_POSITION = 2; //
static const Int32 GRADIENT_SC_KNOT_BIAS = 3; // Float
static const Int32 GRADIENT_SC_KNOT_INTERPOLATION = 4; // Float
// static const Int32 GRADIENT_SC_INTERPOLATION = 1000; // Int32
static const Int32 GRADIENT_SC_KNOT_BASE = 10000; // if >=, decode subchannels
static const Int32 GRADIENT_SC_ALPHAGRADIENT_OFFSET = 1000000000; // if id >=, it's a knot of an alpha gradient is addressed
#define GRADIENT_MAX_IDS_PER_KNOT 100
#define GRADIENT_DECODE_KNOT_INDEX(id) ((id - GRADIENT_SC_KNOT_BASE) / GRADIENT_MAX_IDS_PER_KNOT)
#define GRADIENT_DECODE_KNOT_SUBCHANNEL(id) (id % GRADIENT_MAX_IDS_PER_KNOT)
class GetSetDParameterExample : public ObjectData
{
INSTANCEOF(GetSetDParameterExample, ObjectData)
public:
virtual Bool Init(GeListNode *node);
virtual Bool GetDDescription(GeListNode* node, Description* description, DESCFLAGS_DESC& flags);
virtual Bool GetDParameter(GeListNode* node, const DescID& id, GeData& t_data, DESCFLAGS_GET& flags);
virtual Bool SetDParameter(GeListNode* node, const DescID& id, const GeData& t_data, DESCFLAGS_SET& flags);
virtual BaseObject* GetVirtualObjects(BaseObject* op, HierarchyHelp* hh);
static NodeData* Alloc() { return NewObjClear(GetSetDParameterExample); }
private:
void SplineInit(BaseContainer* const data);
Bool SplineGetDDescription(GeListNode *node, Description *description, DESCFLAGS_DESC &flags, const DescID* const singleid);
Bool SplineGetDParameter(GeListNode* node, const DescID& id, GeData& t_data, DESCFLAGS_GET& flags, BaseContainer* const data);
Bool SplineSetDParameter(GeListNode* node, const DescID& id, const GeData& t_data, DESCFLAGS_SET& flags, BaseContainer* const data);
void GradientInit(BaseContainer* const data);
Bool GradientGetDDescription(GeListNode *node, Description *description, DESCFLAGS_DESC &flags, const DescID* const singleid);
Bool GradientGetDParameter(GeListNode* node, const DescID& id, GeData& t_data, DESCFLAGS_GET& flags, BaseContainer* const data);
Bool GradientSetDParameter(GeListNode* node, const DescID& id, const GeData& t_data, DESCFLAGS_SET& flags, BaseContainer* const data);
Bool GradientFindKnot(Gradient* const gradient, Int32 knotIdx, GradientKnot& knot, Int32& idx);
void LinkInit(BaseContainer* const data);
Bool LinkGetDDescription(GeListNode *node, Description *description, DESCFLAGS_DESC &flags, const DescID* const singleid);
Bool LinkGetDParameter(GeListNode* node, const DescID& id, GeData& t_data, DESCFLAGS_GET& flags, BaseContainer* const data);
Bool LinkSetDParameter(GeListNode* node, const DescID& id, const GeData& t_data, DESCFLAGS_SET& flags, BaseContainer* const data);
void LinkGetVirtualObjectsTest(BaseObject* const op);
};
//
// Spline
//
void GetSetDParameterExample::SplineInit(BaseContainer* const data)
{
// Initialize spline description
GeData spline(CUSTOMDATATYPE_SPLINE, DEFAULTVALUE);
SplineData* const spd = static_cast<SplineData*>(spline.GetCustomDataType(CUSTOMDATATYPE_SPLINE));
if (spd)
{
spd->MakeLinearSplineBezier(2);
CustomSplineKnot* knot = spd->GetKnot(0);
// move points, so spline fits optimal area configured in GetDDescription()
knot->vPos = Vector(0.2, 0.2, 0.0);
knot = spd->GetKnot(1);
knot->vPos = Vector(0.8, 0.8, 0.0);
}
data->SetData(ID_SPLINE, spline);
}
Bool GetSetDParameterExample::SplineGetDDescription(GeListNode *node, Description *description, DESCFLAGS_DESC &flags, const DescID* const singleid)
{
// Create a spline description
const DescID cid = DescLevel(ID_SPLINE, CUSTOMDATATYPE_SPLINE, 0);
if (!singleid || cid.IsPartOf(*singleid, nullptr)) // important to check for speedup c4d!
{
BaseContainer bcSpline = GetCustomDataTypeDefault(CUSTOMDATATYPE_SPLINE);
bcSpline.SetInt32(DESC_CUSTOMGUI, CUSTOMGUI_SPLINE); // Actually this is already set by GetCustomDataTypeDefault()
bcSpline.SetString(DESC_SHORT_NAME, "Spline"_s); // This name is shown in the GUI
bcSpline.SetString(DESC_NAME, "Spline"_s); // This name is visible in Xpresso
bcSpline.SetInt32(DESC_ANIMATE, DESC_ANIMATE_ON); // Default is DESC_ANIMATE_ON
// Spline GUI configuration
// Set minimum size of spline GUI
bcSpline.SetInt32(SPLINECONTROL_MINSIZE_H, 100); // Default is 120
bcSpline.SetInt32(SPLINECONTROL_MINSIZE_V, 150); // Default is 160
// Spline GUI area may be defined as square
bcSpline.SetBool(SPLINECONTROL_SQUARE, false); // Default is false
// Gridline painting
bcSpline.SetBool(SPLINECONTROL_GRID_H, true); // Default is true
bcSpline.SetBool(SPLINECONTROL_GRID_V, false); // Default is true
// Axis labels, which will be shown, if GUI is extended (they are also shown on edit fields)
bcSpline.SetString(SPLINECONTROL_X_TEXT, "A"_s); // Default is "X"
bcSpline.SetString(SPLINECONTROL_Y_TEXT, "B"_s); // Default is "Y"
// Edit fields for x and y values, true is default, if false respective component will be locked, default is true
bcSpline.SetBool(SPLINECONTROL_VALUE_EDIT_H, true); // Default is true
bcSpline.SetBool(SPLINECONTROL_VALUE_EDIT_V, true); // Default is true
// Define increments of arrows on edit fields in extended GUI
bcSpline.SetFloat(SPLINECONTROL_X_STEPS, 0.05); // Default is 0.1
bcSpline.SetFloat(SPLINECONTROL_Y_STEPS, 0.1); // Default is 0.1
// Allow scaling of the spline area
bcSpline.SetBool(SPLINECONTROL_ALLOW_HORIZ_SCALE_MOVE, true); // Default is true
bcSpline.SetBool(SPLINECONTROL_ALLOW_VERT_SCALE_MOVE, true); // Default is true
// Hide "Show in separate window..." in popup menu, button in extended GUI is not influenced and will stay visible
bcSpline.SetBool(SPLINECONTROL_NO_FLOATING_WINDOW, true); // Default is false
// Hide the buttons to load and save presets in extended GUI
bcSpline.SetBool(SPLINECONTROL_NO_PRESETS, true); // Default is false
// Minimum and maximum values for spline points, on start area will be zoomed in on this range
bcSpline.SetFloat(SPLINECONTROL_X_MIN, 0.1); // Default is 0.0
bcSpline.SetFloat(SPLINECONTROL_Y_MIN, 0.1); // Default is 0.0
bcSpline.SetFloat(SPLINECONTROL_X_MAX, 0.9); // Default is 1.0
bcSpline.SetFloat(SPLINECONTROL_Y_MAX, 0.9); // Default is 1.0
// Optimal area, shows a highlighted rectangle in background, indicating a zone for "optimal" values, area will be zoomed in to this zone on start
bcSpline.SetBool(SPLINECONTROL_OPTIMAL, true); // Default is false
bcSpline.SetFloat(SPLINECONTROL_OPTIMAL_X_MIN, 0.2);
bcSpline.SetFloat(SPLINECONTROL_OPTIMAL_Y_MIN, 0.2);
bcSpline.SetFloat(SPLINECONTROL_OPTIMAL_X_MAX, 0.8);
bcSpline.SetFloat(SPLINECONTROL_OPTIMAL_Y_MAX, 0.8);
// Custom color for spline
bcSpline.SetBool(SPLINECONTROL_CUSTOMCOLOR_SET, true); // Default is false
bcSpline.SetVector(SPLINECONTROL_CUSTOMCOLOR_COL, Vector(0.6, 1.0, 0.6)); // Value range 0.0 to 1.0
if (!description->SetParameter(cid, bcSpline, DescLevel(ID_OBJECTPROPERTIES)))
return false;
}
return true;
}
Bool GetSetDParameterExample::SplineGetDParameter(GeListNode* node, const DescID& id, GeData& t_data, DESCFLAGS_GET& flags, BaseContainer* const data)
{
if (id[1].id == 0) // if second level id is zero, the complete custom datatype is requested
{
const GeData d = data->GetData(id[0].id);
SplineData* const spd = static_cast<SplineData*>(d.GetCustomDataType(CUSTOMDATATYPE_SPLINE));
t_data.SetCustomDataType(CUSTOMDATATYPE_SPLINE, *spd);
flags |= DESCFLAGS_GET::PARAM_GET;
}
else if (id[1].id == SPLINE_SC_TENSION)
{
// Can not be read directly, so pass this request on to parent
Bool result = SUPER::GetDParameter(node, id, t_data, flags);
// Then you could do something with read t_data, here...
return result;
}
else if (id[1].id > SPLINE_SC_KNOT_BASE)
{
// First decode ID to get the correct knot and subchannel
const Int32 knotIdx = SPLINE_DECODE_KNOT_INDEX(id[1].id);
const Int32 subchannelIdx = SPLINE_DECODE_KNOT_SUBCHANNEL(id[1].id);
// Now, get the SplineData, in order to access it directly.
// As mentioned before, there's no real need to do so, but you could...
const GeData d = data->GetData(id[0].id);
SplineData* const spd = static_cast<SplineData*>(d.GetCustomDataType(CUSTOMDATATYPE_SPLINE));
DebugAssert((knotIdx >= 0) && (knotIdx < spd->GetKnotCount()), "WRONG KNOT INDEX");
CustomSplineKnot* const knot = spd->GetKnot(knotIdx);
if (knot)
{
switch (subchannelIdx)
{
case SPLINE_SC_KNOT_POS_X:
t_data.SetFloat(knot->vPos.x);
break;
case SPLINE_SC_KNOT_POS_Y:
t_data.SetFloat(knot->vPos.y);
break;
case SPLINE_SC_KNOT_TANGENT_LEFT_X:
t_data.SetFloat(knot->vTangentLeft.x);
break;
case SPLINE_SC_KNOT_TANGENT_LEFT_Y:
t_data.SetFloat(knot->vTangentLeft.y);
break;
case SPLINE_SC_KNOT_TANGENT_RIGHT_X:
t_data.SetFloat(knot->vTangentRight.x);
break;
case SPLINE_SC_KNOT_TANGENT_RIGHT_Y:
t_data.SetFloat(knot->vTangentRight.y);
break;
case SPLINE_SC_KNOT_TANGENT_BREAK:
t_data.SetInt32(knot->lFlagsSettings & FLAG_KNOT_T_BREAK);
break;
case SPLINE_SC_KNOT_INTERPOLATIOM:
t_data.SetInt32(knot->interpol);
break;
case SPLINE_SC_KNOT_LOCK_X:
t_data.SetInt32(knot->lFlagsSettings & FLAG_KNOT_LOCK_X);
break;
case SPLINE_SC_KNOT_LOCK_Y:
t_data.SetInt32(knot->lFlagsSettings & FLAG_KNOT_LOCK_Y);
break;
case SPLINE_SC_KNOT_LOCK_TANGENT_ANGLE:
t_data.SetInt32(knot->lFlagsSettings & FLAG_KNOT_T_LOCK_A);
break;
case SPLINE_SC_KNOT_LOCK_TANGENT_LENGTH:
t_data.SetInt32(knot->lFlagsSettings & FLAG_KNOT_T_LOCK_L);
break;
}
}
flags |= DESCFLAGS_GET::PARAM_GET;
}
return SUPER::GetDParameter(node, id, t_data, flags);
}
Bool GetSetDParameterExample::SplineSetDParameter(GeListNode* node, const DescID& id, const GeData& t_data, DESCFLAGS_SET& flags, BaseContainer* const data)
{
if (id[1].id == 0)
{
// Updated spline data
SplineData* const spd = static_cast<SplineData*>(t_data.GetCustomDataType(CUSTOMDATATYPE_SPLINE));
GeData d;
d.SetCustomDataType(CUSTOMDATATYPE_SPLINE, *spd);
data->SetData(id[0].id, d); // store in container
flags |= DESCFLAGS_SET::PARAM_SET;
}
else if (id[1].id == SPLINE_SC_TENSION)
{
// Can not be set directly.
// Do something with new spline tension in t_data...
// Then pass this parameter on to parent, to get it correctly set in spline description
return SUPER::SetDParameter(node, id, t_data, flags);
}
else if (id[1].id > SPLINE_SC_KNOT_BASE)
{
// First decode ID to get the correct knot and subchannel
const Int32 knotIdx = SPLINE_DECODE_KNOT_INDEX(id[1].id);
const Int32 subchannelIdx = SPLINE_DECODE_KNOT_SUBCHANNEL(id[1].id);
// Now, get the SplineData, in order to access it directly.
// As mentioned before, there's no real need to do so, but you could...
const GeData d = data->GetData(id[0].id);
SplineData* const spd = static_cast<SplineData*>(d.GetCustomDataType(CUSTOMDATATYPE_SPLINE));
DebugAssert((knotIdx >= 0) && (knotIdx < spd->GetKnotCount()), "WRONG KNOT INDEX");
CustomSplineKnot* const knot = spd->GetKnot(knotIdx);
switch (subchannelIdx)
{
case SPLINE_SC_KNOT_POS_X:
knot->vPos.x = t_data.GetFloat();
break;
case SPLINE_SC_KNOT_POS_Y:
knot->vPos.y = t_data.GetFloat();
break;
case SPLINE_SC_KNOT_TANGENT_LEFT_X:
knot->vTangentLeft.x = t_data.GetFloat();
break;
case SPLINE_SC_KNOT_TANGENT_LEFT_Y:
knot->vTangentLeft.y = t_data.GetFloat();
break;
case SPLINE_SC_KNOT_TANGENT_RIGHT_X:
knot->vTangentRight.x = t_data.GetFloat();
break;
case SPLINE_SC_KNOT_TANGENT_RIGHT_Y:
knot->vTangentRight.y = t_data.GetFloat();
break;
case SPLINE_SC_KNOT_TANGENT_BREAK:
if (t_data.GetBool())
knot->lFlagsSettings |= FLAG_KNOT_T_BREAK;
else
knot->lFlagsSettings &= ~FLAG_KNOT_T_BREAK;
break;
case SPLINE_SC_KNOT_INTERPOLATIOM:
knot->interpol = (CustomSplineKnotInterpolation)t_data.GetInt32();
break;
case SPLINE_SC_KNOT_LOCK_X:
if (t_data.GetBool())
knot->lFlagsSettings |= FLAG_KNOT_LOCK_X;
else
knot->lFlagsSettings &= ~FLAG_KNOT_LOCK_X;
break;
case SPLINE_SC_KNOT_LOCK_Y:
if (t_data.GetBool())
knot->lFlagsSettings |= FLAG_KNOT_LOCK_Y;
else
knot->lFlagsSettings &= ~FLAG_KNOT_LOCK_Y;
break;
case SPLINE_SC_KNOT_LOCK_TANGENT_ANGLE:
if (t_data.GetBool())
knot->lFlagsSettings |= FLAG_KNOT_T_LOCK_A;
else
knot->lFlagsSettings &= ~FLAG_KNOT_T_LOCK_A;
break;
case SPLINE_SC_KNOT_LOCK_TANGENT_LENGTH:
if (t_data.GetBool())
knot->lFlagsSettings |= FLAG_KNOT_T_LOCK_L;
else
knot->lFlagsSettings &= ~FLAG_KNOT_T_LOCK_L;
break;
}
data->SetData(id[0].id, d); // store changed spline in container
flags |= DESCFLAGS_SET::PARAM_SET;
}
return SUPER::SetDParameter(node, id, t_data, flags);
}
//
// Gradient
//
void GetSetDParameterExample::GradientInit(BaseContainer* const data)
{
// Initialize color gradient description with a simple black/white gradient
GeData gradientData(CUSTOMDATATYPE_GRADIENT, DEFAULTVALUE);
Gradient* const gradient = static_cast<Gradient*>(gradientData.GetCustomDataType(CUSTOMDATATYPE_GRADIENT));
if (gradient)
{
GradientKnot gradientKnot;
gradientKnot.col = Vector(0.0);
gradientKnot.pos = 0.0;
gradientKnot.index = 0;
gradient->InsertKnot(gradientKnot);
gradientKnot.col = Vector(1.0);
gradientKnot.pos = 1.0;
gradientKnot.index = 1;
gradient->InsertKnot(gradientKnot);
}
data->SetData(ID_GRADIENT, gradientData);
}
Bool GetSetDParameterExample::GradientGetDDescription(GeListNode *node, Description *description, DESCFLAGS_DESC &flags, const DescID* const singleid)
{
// Create a color gradient description
const DescID cid = DescLevel(ID_GRADIENT, CUSTOMDATATYPE_GRADIENT, 0);
if (!singleid || cid.IsPartOf(*singleid, nullptr)) // important to check for speedup c4d!
{
BaseContainer bcGradient = GetCustomDataTypeDefault(CUSTOMDATATYPE_GRADIENT);
bcGradient.SetInt32(DESC_CUSTOMGUI, CUSTOMGUI_GRADIENT);
bcGradient.SetString(DESC_SHORT_NAME, "Gradient"_s); // This name is shown in the GUI
bcGradient.SetString(DESC_NAME, "Gradient"_s); // This name is visible in Xpresso
bcGradient.SetInt32(DESC_ANIMATE, DESC_ANIMATE_ON);
// Gradient GUI configuration
// Set gradient mode, defaults to GRADIENTMODE_COLOR if both are false, GRADIENTMODE_COLORALPHA if both are true
// GRADIENTMODE_ALPHA implies GRADIENTPROPERTY_NOEDITCOLOR true
// Here GRADIENTMODE_COLORALPHA is used
bcGradient.SetBool(GRADIENTPROPERTY_ALPHA_WITH_COLOR, true); // Default is false
bcGradient.SetBool(GRADIENTPROPERTY_ALPHA, true); // Default is false
// Hide color sliders in extended GUI (color of knots can still be edited via double click)
bcGradient.SetBool(GRADIENTPROPERTY_NOEDITCOLOR, false); // Default is false
// Hide the buttons to load and save presets in extended GUI
bcGradient.SetBool(GRADIENTPROPERTY_NOPRESETS, true); // Default is false
if (!description->SetParameter(cid, bcGradient, DescLevel(ID_OBJECTPROPERTIES)))
return false;
}
return true;
}
Bool GetSetDParameterExample::GradientGetDParameter(GeListNode* node, const DescID& id, GeData& t_data, DESCFLAGS_GET& flags, BaseContainer* const data)
{
// Get the Gradient, in order to access it directly.
// As mentioned before, there's no real need to do so, but you could...
GeData d = data->GetData(id[0].id);
Gradient* gradient = static_cast<Gradient*>(d.GetCustomDataType(CUSTOMDATATYPE_GRADIENT));
if (id[1].id == 0) // if second level id is zero, the complete custom datatype is requested
{
t_data.SetCustomDataType(CUSTOMDATATYPE_GRADIENT, *gradient);
flags |= DESCFLAGS_GET::PARAM_GET;
}
else if (id[1].id >= GRADIENT_SC_KNOT_BASE)
{
// First check, if a knot of an alpha gradient is addressed
Int32 idDecoded = id[1].id;
if (idDecoded >= GRADIENT_SC_ALPHAGRADIENT_OFFSET)
{
idDecoded -= GRADIENT_SC_ALPHAGRADIENT_OFFSET;
gradient = gradient->GetAlphaGradient();
if (!gradient)
return SUPER::GetDParameter(node, id, t_data, flags);
}
// Then decode ID to get the correct knot and subchannel
const Int32 knotIdx = GRADIENT_DECODE_KNOT_INDEX(idDecoded);
const Int32 subchannelIdx = GRADIENT_DECODE_KNOT_SUBCHANNEL(idDecoded);
// Now, find the addressed knot
// Note:
// Gradient is different than spline data, as the decoded knotIdx is not the index
// to directly access the knot. Instead on every knot an index is stored.
GradientKnot knot;
Int32 idx;
if (!GradientFindKnot(gradient, knotIdx, knot, idx))
return SUPER::GetDParameter(node, id, t_data, flags);
switch (subchannelIdx)
{
case GRADIENT_SC_KNOT_COLOR:
switch (id[2].id) // this switch does the same as HandleDescGetVector, just one description level deeper
{
case 0:
t_data.SetVector(knot.col);
break;
case 1000:
t_data.SetFloat(knot.col.x);
break;
case 1001:
t_data.SetFloat(knot.col.y);
break;
case 1002:
t_data.SetFloat(knot.col.z);
break;
}
break;
case GRADIENT_SC_KNOT_INTENSITY:
t_data.SetFloat(knot.brightness);
break;
case GRADIENT_SC_KNOT_POSITION:
t_data.SetFloat(knot.pos);
break;
case GRADIENT_SC_KNOT_BIAS:
t_data.SetFloat(knot.bias);
break;
case GRADIENT_SC_KNOT_INTERPOLATION:
t_data.SetInt32(knot.interpolation);
break;
}
flags |= DESCFLAGS_GET::PARAM_GET;
}
return SUPER::GetDParameter(node, id, t_data, flags);
}
Bool GetSetDParameterExample::GradientSetDParameter(GeListNode* node, const DescID& id, const GeData& t_data, DESCFLAGS_SET& flags, BaseContainer* const data)
{
if (id[1].id == 0)
{
// Updated gradient data
Gradient* const gradient = static_cast<Gradient*>(t_data.GetCustomDataType(CUSTOMDATATYPE_GRADIENT));
GeData d;
d.SetCustomDataType(CUSTOMDATATYPE_GRADIENT, *gradient);
data->SetData(id[0].id, d); // store in container
flags |= DESCFLAGS_SET::PARAM_SET;
}
else if (id[1].id >= GRADIENT_SC_KNOT_BASE)
{
// Get the Gradient, in order to access it directly.
// As mentioned before, there's no real need to do so, but you could...
const GeData d = data->GetData(id[0].id);
Gradient* gradient = static_cast<Gradient*>(d.GetCustomDataType(CUSTOMDATATYPE_GRADIENT));
// First check, if a knot of an alpha gradient is addressed
Int32 idDecoded = id[1].id;
if (idDecoded >= GRADIENT_SC_ALPHAGRADIENT_OFFSET)
{
idDecoded -= GRADIENT_SC_ALPHAGRADIENT_OFFSET;
gradient = gradient->GetAlphaGradient();
if (!gradient)
return SUPER::SetDParameter(node, id, t_data, flags);
}
// Then decode ID to get the correct knot and subchannel
const Int32 knotIdx = GRADIENT_DECODE_KNOT_INDEX(idDecoded);
const Int32 subchannelIdx = GRADIENT_DECODE_KNOT_SUBCHANNEL(idDecoded);
// Now, find the addressed knot
// Note:
// Gradient is different than spline data, as the decoded knotIdx is not the index
// to directly access the knot. Instead on every knot an index is stored.
GradientKnot knot;
Int32 idx;
if (!GradientFindKnot(gradient, knotIdx, knot, idx))
return SUPER::SetDParameter(node, id, t_data, flags);
switch (subchannelIdx)
{
case GRADIENT_SC_KNOT_COLOR:
switch (id[2].id) // this switch does the same as HandleDescSetVector, just one description level deeper
{
case 0:
knot.col = t_data.GetVector();
break;
case 1000:
knot.col = Vector(t_data.GetFloat(), knot.col.y, knot.col.z);
break;
case 1001:
knot.col = Vector(knot.col.x, t_data.GetFloat(), knot.col.z);
break;
case 1002:
knot.col = Vector(knot.col.x, knot.col.y, t_data.GetFloat());
break;
}
break;
case GRADIENT_SC_KNOT_INTENSITY:
knot.brightness = t_data.GetFloat();
break;
case GRADIENT_SC_KNOT_POSITION:
knot.pos = t_data.GetFloat();
break;
case GRADIENT_SC_KNOT_BIAS:
knot.bias = t_data.GetFloat();
break;
case GRADIENT_SC_KNOT_INTERPOLATION:
knot.interpolation = t_data.GetInt32();
break;
}
gradient->SetKnot(idx, knot);
data->SetData(id[0].id, d); // store changed gradient in container
flags |= DESCFLAGS_SET::PARAM_SET;
}
return SUPER::SetDParameter(node, id, t_data, flags);
}
// GradientFindKnot returns true, if knot is found. knot and idx are set in this case. idx is to be used with GetKnot().
Bool GetSetDParameterExample::GradientFindKnot(Gradient* const gradient, Int32 knotIdx, GradientKnot& knot, Int32& idx)
{
const Int32 knotCount = gradient->GetKnotCount();
for (idx = 0; idx < knotCount; ++idx)
{
knot = gradient->GetKnot(idx); // this idx is different from knotIdx!!!
if (knot.index == knotIdx)
break;
}
if (idx == knotCount)
return false; // Knot not found. This can happen for example, if the user animated the gradient and then removes a knot
return true;
}
//
// Link
//
void GetSetDParameterExample::LinkInit(BaseContainer* const data)
{
// Initialize link
data->SetLink(ID_LINK, nullptr);
}
Bool GetSetDParameterExample::LinkGetDDescription(GeListNode *node, Description *description, DESCFLAGS_DESC &flags, const DescID* const singleid)
{
// Create a link description
const DescID cid = DescLevel(ID_LINK, DTYPE_BASELISTLINK, 0);
if (!singleid || cid.IsPartOf(*singleid, nullptr))// important to check for speedup c4d!
{
BaseContainer bcLink = GetCustomDataTypeDefault(DTYPE_BASELISTLINK);
bcLink.SetString(DESC_SHORT_NAME, "Link"_s);
bcLink.SetString(DESC_NAME, "Link"_s);
bcLink.SetInt32(DESC_ANIMATE, DESC_ANIMATE_ON);
bcLink.SetInt32(DESC_CUSTOMGUI, CUSTOMGUI_TEXBOX);
bcLink.SetInt32(DESC_SHADERLINKFLAG, true);
if (!description->SetParameter(cid, bcLink, DescLevel(ID_OBJECTPROPERTIES)))
return false;
}
return true;
}
Bool GetSetDParameterExample::LinkGetDParameter(GeListNode* node, const DescID& id, GeData& t_data, DESCFLAGS_GET& flags, BaseContainer* const data)
{
const GeData d = data->GetData(id[0].id);
if (d.GetType() == DA_NIL) // If the link does not get properly initialized, you need to take care for this situation
{
AutoAlloc<BaseLink> bl;
// check the BaseLink returned pointer
if (!bl)
{
flags |= DESCFLAGS_GET::PARAM_GET;
return SUPER::GetDParameter(node, id, t_data, flags);
}
bl->SetLink(nullptr);
t_data.SetBaseLink(bl);
}
else
{
BaseLink* const bl = d.GetBaseLink();
// check the BaseLink returned pointer
if (!bl)
{
flags |= DESCFLAGS_GET::PARAM_GET;
return SUPER::GetDParameter(node, id, t_data, flags);
}
t_data.SetBaseLink(*bl);
}
flags |= DESCFLAGS_GET::PARAM_GET;
return SUPER::GetDParameter(node, id, t_data, flags);
}
Bool GetSetDParameterExample::LinkSetDParameter(GeListNode* node, const DescID& id, const GeData& t_data, DESCFLAGS_SET& flags, BaseContainer* const data)
{
BaseLink* const bl = static_cast<BaseLink*>(t_data.GetBaseLink());
GeData d;
d.SetBaseLink(*bl);
data->SetData(id[0].id, d); // store in container
flags |= DESCFLAGS_SET::PARAM_SET;
return SUPER::SetDParameter(node, id, t_data, flags);
}
void GetSetDParameterExample::LinkGetVirtualObjectsTest(BaseObject* const op)
{
BaseContainer* bc = op->GetDataInstance();
// For demonstration purposes, the link is accessed in two different ways:
// a) Using the BaseLink
BaseLink* bl = bc->GetBaseLink(ID_LINK);
if (bl)
{
BaseList2D* bl2d = bl->GetLink(op->GetDocument());
if (bl2d)
ApplicationOutput("Via GetBaseLink(): " + bl2d->GetName());
else
ApplicationOutput("Via GetBaseLink(): No Link"_s);
}
// b) Using directly GetLink()
BaseList2D* bl2d = bc->GetLink(ID_LINK, op->GetDocument());
if (bl2d)
ApplicationOutput("Via GetLink(): " + bl2d->GetName());
else
ApplicationOutput("Via GetLink(): No Link"_s);
}
//
// ObjectData function overrides
//
Bool GetSetDParameterExample::Init(GeListNode* node)
{
BaseContainer* const data = ((BaseMaterial*)node)->GetDataInstance();
SplineInit(data);
GradientInit(data);
LinkInit(data);
return true;
}
Bool GetSetDParameterExample::GetDDescription(GeListNode *node, Description *description, DESCFLAGS_DESC &flags)
{
if (!description->LoadDescription(node->GetType()))
return false;
const DescID* const singleid = description->GetSingleDescID();
if (!SplineGetDDescription(node, description, flags, singleid))
return false;
if (!GradientGetDDescription(node, description, flags, singleid))
return false;
if (!LinkGetDDescription(node, description, flags, singleid))
return false;
flags |= DESCFLAGS_DESC::LOADED;
return true;
}
Bool GetSetDParameterExample::GetDParameter(GeListNode* node, const DescID& id, GeData& t_data, DESCFLAGS_GET& flags)
{
BaseContainer* const data = static_cast<BaseObject*>(node)->GetDataInstance();
// This implementation is rather useless and is for demonstration purposes, only.
// Instead of reading the parameters manually, you could always call
// SUPER::GetDParameter() without setting DESCFLAGS_GET::PARAM_GET.
switch (id[0].id)
{
case ID_SPLINE:
{
return SplineGetDParameter(node, id, t_data, flags, data);
break;
}
case ID_GRADIENT:
{
return GradientGetDParameter(node, id, t_data, flags, data);
break;
}
case ID_LINK:
{
return LinkGetDParameter(node, id, t_data, flags, data);
break;
}
default:
CriticalOutput("Unknown description ID (@)!", id[0].id);
break;
}
return SUPER::GetDParameter(node, id, t_data, flags);
}
Bool GetSetDParameterExample::SetDParameter(GeListNode* node, const DescID& id, const GeData& t_data, DESCFLAGS_SET& flags)
{
BaseContainer* const data = static_cast<BaseObject*>(node)->GetDataInstance();
// This implementation is rather useless and is for demonstration purposes, only.
// Instead of setting the parameters manually, you could always call
// SUPER::SetDParameter() without setting DESCFLAGS_SET::PARAM_SET and would be done.
// In a real world plugin, you probably would want to set some internal variables here.
switch (id[0].id)
{
case ID_SPLINE:
{
return SplineSetDParameter(node, id, t_data, flags, data);
break;
}
case ID_GRADIENT:
{
return GradientSetDParameter(node, id, t_data, flags, data);
break;
}
case ID_LINK:
{
return LinkSetDParameter(node, id, t_data, flags, data);
break;
}
default:
CriticalOutput("Unknown description ID (@)!", id[0].id);
break;
}
return SUPER::SetDParameter(node, id, t_data, flags);
}
BaseObject* GetSetDParameterExample::GetVirtualObjects(BaseObject* op, HierarchyHelp* hh)
{
LinkGetVirtualObjectsTest(op);
// Just return a Null object, the generated object is useless in this example
return BaseObject::Alloc(Onull);
}
Bool RegisterGetSetDParameterExample()
{
return RegisterObjectPlugin(ID_GETSETDPARAMETEREXAMPLE,
GeLoadString(IDS_OBJECTDATA_GETSETDPARAMETEREXAMPLE),
OBJECT_GENERATOR,
GetSetDParameterExample::Alloc,
"Ogetsetdparameterexample"_s,
nullptr,
0);
}
| 36.704835 | 158 | 0.740485 | [
"object",
"vector"
] |
c06864629af4138bd89e28ff5a8f458999fc5d81 | 8,200 | cpp | C++ | test/test_rbdl.cpp | eric-heiden/tiny-differentiable-simulator | 025ed85c35c4241ac4a30ff9d28b418900bcaf48 | [
"Apache-2.0"
] | 1 | 2020-07-09T08:07:47.000Z | 2020-07-09T08:07:47.000Z | test/test_rbdl.cpp | eric-heiden/tiny-differentiable-simulator | 025ed85c35c4241ac4a30ff9d28b418900bcaf48 | [
"Apache-2.0"
] | 6 | 2020-10-20T21:31:32.000Z | 2021-07-02T06:12:49.000Z | test/test_rbdl.cpp | eric-heiden/tiny-differentiable-simulator | 025ed85c35c4241ac4a30ff9d28b418900bcaf48 | [
"Apache-2.0"
] | 1 | 2020-08-31T02:18:49.000Z | 2020-08-31T02:18:49.000Z | #include <gtest/gtest.h>
#include "rbdl_test_utils.hpp"
using namespace tds;
using namespace TINY;
using Algebra = TinyAlgebra<double, DoubleUtils>;
using Tf = Transform<Algebra>;
using Vector3 = Algebra::Vector3;
using VectorX = typename Algebra::VectorX;
using Matrix3 = Algebra::Matrix3;
using RigidBodyInertia = RigidBodyInertia<Algebra>;
void TestOnURDF(std::string filename)
{
Vector3 gravity(0., 0., -9.81);
World<Algebra> world;
MultiBody<Algebra> *mb = nullptr;
std::string urdf_filename;
bool is_floating = false;
bool result = FileUtils::find_file(filename, urdf_filename);
ASSERT_TRUE(result);
printf("urdf_filename=%s\n", urdf_filename.c_str());
#ifdef USE_BULLET_URDF_PARSER
UrdfCache<Algebra> cache;
mb = cache.construct(urdf_filename, world, false, is_floating);
#else //USE_BULLET_URDF_PARSER
UrdfParser<Algebra> parser;
MultiBody<Algebra> mb1;
mb = &mb1;
std::string full_path;
FileUtils::find_file(filename, full_path);
UrdfStructures<Algebra> urdf_structures =
parser.load_urdf(full_path);
UrdfToMultiBody<Algebra>::convert_to_multi_body(
urdf_structures, world, mb1);
mb1.initialize();
#endif//USE_BULLET_URDF_PARSER
std::string fail_message = "Failure at iteration ";
{
RigidBodyDynamics::Model rbdl_model = to_rbdl(*mb);
rbdl_model.gravity = to_rbdl<Algebra>(gravity);
using VectorND = RigidBodyDynamics::Math::VectorNd;
VectorND rbdl_q = VectorND::Zero(rbdl_model.q_size);
VectorND rbdl_qd = VectorND::Zero(rbdl_model.qdot_size);
VectorND rbdl_qdd = VectorND::Zero(rbdl_model.qdot_size);
VectorND rbdl_tau = VectorND::Zero(rbdl_model.qdot_size);
int q_offset = 0, qd_offset = 0;
if (mb->is_floating()) {
rbdl_q[0] = Algebra::to_double(mb->q(4));
rbdl_q[1] = Algebra::to_double(mb->q(5));
rbdl_q[2] = Algebra::to_double(mb->q(6));
// w coordinate of quat is stored at the end
rbdl_q[mb->dof() - 1] = Algebra::to_double(mb->q(3));
rbdl_q[3] = Algebra::to_double(mb->q(0));
rbdl_q[4] = Algebra::to_double(mb->q(1));
rbdl_q[5] = Algebra::to_double(mb->q(2));
q_offset = 7;
rbdl_qd[0] = Algebra::to_double(mb->qd(3));
rbdl_qd[1] = Algebra::to_double(mb->qd(4));
rbdl_qd[2] = Algebra::to_double(mb->qd(5));
rbdl_qd[3] = Algebra::to_double(mb->qd(0));
rbdl_qd[4] = Algebra::to_double(mb->qd(1));
rbdl_qd[5] = Algebra::to_double(mb->qd(2));
qd_offset = 6;
}
for (int i = q_offset; i < mb->dof(); ++i) {
rbdl_q[i - int(mb->is_floating())] = Algebra::to_double(mb->q(i));
}
for (int i = qd_offset; i < mb->dof_qd(); ++i) {
rbdl_qd[i] = Algebra::to_double(mb->qd(i));
rbdl_qdd[i] = Algebra::to_double(mb->qdd(i));
}
for (int i = 0; i < mb->dof_actuated(); ++i) {
rbdl_tau[i + qd_offset] = Algebra::to_double(mb->tau(i));
}
RigidBodyDynamics::UpdateKinematics(rbdl_model, rbdl_q, rbdl_qd, rbdl_qdd);
forward_kinematics(*mb);
// if (!is_equal<Algebra>(*mb, rbdl_model)) {
// // exit(1);
// }
double dt = 0.001;
for (int i = 0; i < 200; ++i) {
printf("\n\n\nt: %i\n", i);
forward_kinematics(*mb);
// traj.push_back(mb->q);
int nd = mb->dof_actuated();
// Algebra::Index j = 2;
// for (Algebra::Index j = 3; j < nd; ++j) {
// mb->tau(j) = Algebra::sin(i * dt * 10.) * 1e-4;
// rbdl_tau[j] = Algebra::to_double(mb->tau(j));
// }
for (int i = 0; i < mb->dof_actuated(); ++i) {
mb->tau(i) = Algebra::cos(i * dt * 10.) * 0.1;
rbdl_tau[i + qd_offset] = Algebra::to_double(mb->tau(i));
}
forward_dynamics(*mb, gravity);
for (auto &link : *mb) {
// Algebra::print(
// ("link[" + std::to_string(link.q_index) + "].D").c_str(),
// link.D);
// Algebra::print(
// ("link[" + std::to_string(link.q_index) + "].U").c_str(),
// link.U);
// Algebra::print(
// ("link[" + std::to_string(link.q_index) + "].S").c_str(),
// link.S);
// Algebra::print(
// ("link[" + std::to_string(link.q_index) + "].u").c_str(),
// link.u);
// Algebra::print(
// ("TDS link[" + std::to_string(link.q_index) + "].X_world")
// .c_str(),
// link.X_world);
// std::cout << "RBDL link[" << link.q_index << "].X_base\n"
// << rbdl_model.X_base[link.q_index + 1] << std::endl;
}
RigidBodyDynamics::ForwardDynamics(rbdl_model, rbdl_q, rbdl_qd, rbdl_tau,
rbdl_qdd);
mb->print_state();
std::cout << "RBDL q: " << rbdl_q.transpose()
<< " qd: " << rbdl_qd.transpose()
<< " qdd: " << rbdl_qdd.transpose()
<< " tau: " << rbdl_tau.transpose() << std::endl;
// if (!is_equal<Algebra>(*mb, rbdl_model)) {
// assert(0);
// exit(1);
// }
ASSERT_TRUE(is_equal<Algebra>(*mb, rbdl_model)) << fail_message << i;
// if (!is_equal<Algebra>(*mb, rbdl_q, rbdl_qd, rbdl_qdd)) {
// exit(1);
// }
ASSERT_TRUE(is_equal<Algebra>(*mb, rbdl_q, rbdl_qd, rbdl_qdd))
<< fail_message << i;
integrate_euler(*mb, dt);
rbdl_qd += rbdl_qdd * dt;
if (mb->is_floating()) {
// need to integrate quaternion
Algebra::Quaternion quat = Algebra::quat_from_xyzw(
rbdl_q[3], rbdl_q[4], rbdl_q[5], rbdl_q[mb->dof() - 1]);
// Algebra::print("Base quat (RBDL): ", quat);
Algebra::Vector3 ang_vel(rbdl_qd[3], rbdl_qd[4], rbdl_qd[5]);
// Algebra::print("Angular velocity (RBDL): ", ang_vel);
// Algebra::Vector3 ang_vel_tds(mb->qd(0), mb->qd(1), mb->qd(2));
// Algebra::print("Angular velocity (TDS): ", ang_vel_tds);
Algebra::Quaternion dquat = Algebra::quat_velocity(quat, ang_vel, dt);
quat += dquat;
Algebra::normalize(quat);
rbdl_q[3] = Algebra::quat_x(quat);
rbdl_q[4] = Algebra::quat_y(quat);
rbdl_q[5] = Algebra::quat_z(quat);
rbdl_q[mb->dof() - 1] = Algebra::quat_w(quat);
// linear velocity integration
rbdl_q[0] += rbdl_qd[0] * dt;
rbdl_q[1] += rbdl_qd[1] * dt;
rbdl_q[2] += rbdl_qd[2] * dt;
for (int i = 6; i < mb->dof_qd(); ++i) {
rbdl_q[i] += rbdl_qd[i] * dt;
}
} else {
rbdl_q += rbdl_qd * dt;
}
// std::cout << "RBDL q (before mod): " << rbdl_q.transpose() <<
// std::endl;
// if (!is_equal<Algebra>(*mb, rbdl_q, rbdl_qd, rbdl_qdd)) {
// exit(1);
// }
ASSERT_TRUE(is_equal<Algebra>(*mb, rbdl_q, rbdl_qd, rbdl_qdd))
<< fail_message << i;
mb->clear_forces();
// compare Jacobians
tds::forward_kinematics(*mb);
int jac_link_id = 2;
Algebra::Vector3 world_point(1., 2., 3.);
auto tds_jac = tds::point_jacobian2(*mb, jac_link_id, world_point, false);
RigidBodyDynamics::Math::MatrixNd rbdl_jac(Algebra::num_rows(tds_jac),
Algebra::num_cols(tds_jac));
rbdl_jac.setZero();
// left-associative inverse transform of body_to_world transform
// (rotation matrix is not inverted)
Transform<Algebra> link_tf = (*mb)[jac_link_id].X_world;
Algebra::Vector3 body_point =
link_tf.rotation * (world_point - link_tf.translation);
RigidBodyDynamics::CalcPointJacobian(rbdl_model, rbdl_q, jac_link_id + 1,
to_rbdl<Algebra>(body_point),
rbdl_jac);
// Algebra::print("TDS Jacobian", tds_jac);
// std::cout << "RBDL Jacobian:\n" << rbdl_jac << std::endl;
// if (!is_equal<Algebra>(tds_jac, rbdl_jac)) {
// exit(1);
// }
}
}
}
TEST(RBDLTest, Swimmer05) {
TestOnURDF("swimmer/swimmer05/swimmer05.urdf");
}
TEST(RBDLTest, Pendulum) {
TestOnURDF("pendulum5.urdf");
}
int main(int argc, char** argv)
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 35.497835 | 80 | 0.569268 | [
"model",
"transform"
] |
c06e37e09d2103dd842da21d723558d1a1678484 | 7,090 | cpp | C++ | tests/tests_atomics/tests_mains/devicesSwitch.cpp | SimulationEverywhere/NEP_DAM | bc8cdf661c4a4e050abae12fb756f41ec6240e6b | [
"BSD-2-Clause"
] | null | null | null | tests/tests_atomics/tests_mains/devicesSwitch.cpp | SimulationEverywhere/NEP_DAM | bc8cdf661c4a4e050abae12fb756f41ec6240e6b | [
"BSD-2-Clause"
] | null | null | null | tests/tests_atomics/tests_mains/devicesSwitch.cpp | SimulationEverywhere/NEP_DAM | bc8cdf661c4a4e050abae12fb756f41ec6240e6b | [
"BSD-2-Clause"
] | null | null | null | /**
* Copyright (c) 2017, Cristina Ruiz Martin
* Carleton University, Universidad de Valladolid
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
//This file include iestream test
#include <iostream>
#include <chrono>
#include <algorithm>
#include <string>
#include <cadmium/modeling/coupled_model.hpp>
#include <cadmium/modeling/ports.hpp>
#include <cadmium/concept/coupled_model_assert.hpp>
#include <cadmium/engine/pdevs_runner.hpp>
#include "../../DESTimes/include/NDTime.hpp"
#include "../../atomics/devicesSwitch.hpp"
#include "../../atomics/iestream.hpp"
#include "../../data_structures/struct_types.hpp"
#include "../../data_structures/communication.hpp"
#include "../../data_structures/nep_model_enum_types.hpp"
using namespace std;
using namespace nep_structures;
using namespace nep_model_enum_types;
using hclock=chrono::high_resolution_clock;
/****** Istream set answer atomic model definition *********/
using out_p_iestreamCom = iestream_input_defs<Communication>::out;
using out_p_iestreamCWD = iestream_input_defs<CommandWithDevice>::out;
using out_p_iestreamTDF = iestream_input_defs<TaskDeviceFinished>::out;
template<typename TIME>
using iestream_Communication=iestream_input<Communication,TIME>;
template<typename TIME>
using iestream_CommandWithDevice=iestream_input<CommandWithDevice,TIME>;
template<typename TIME>
using iestream_TaskDeviceFinished=iestream_input<TaskDeviceFinished,TIME>;
template<typename TIME>
class iestream_test_set_answer : public iestream_Communication<TIME> {
public:
iestream_test_set_answer(): iestream_Communication<TIME>("tests_inputs/test_switch_answer.txt") {};
};
/*******************************************/
/****** Istream set send atomic model definition *********/
template<typename TIME>
class iestream_test_set_send : public iestream_CommandWithDevice<TIME> {
public:
iestream_test_set_send(): iestream_CommandWithDevice<TIME>("tests_inputs/test_switch_send.txt") {};
};
/*******************************************/
/****** Istream set decide atomic model definition *********/
template<typename TIME>
class iestream_test_set_decide : public iestream_TaskDeviceFinished<TIME> {
public:
iestream_test_set_decide(): iestream_TaskDeviceFinished<TIME>("tests_inputs/test_switch_decide.txt") {};
};
/*******************************************/
/****** Istream communication atomic model definition *********/
template<typename TIME>
class iestream_test_communication : public iestream_Communication<TIME> {
public:
iestream_test_communication(): iestream_Communication<TIME>("tests_inputs/test_phone_communication.txt") {};
};
/*******************************************/
/****** switch3OutPerson atomic model definition *********/
using out_send_p = devicesSwitch_defs::sendOut;
using out_answer_p = devicesSwitch_defs::answerOut;
using out_decide_p = devicesSwitch_defs::decideOut;
using in_communication_p = devicesSwitch_defs::communicationIn;
using in_answer_p = devicesSwitch_defs::setAnswerIn;
using in_send_p = devicesSwitch_defs::setSendIn;
using in_decide_p = devicesSwitch_defs::setDecideIn;
//No atomic instantiation needed
/*******************************************/
/****** switch3OutPerson coupled model text definition *********/
using iports = std::tuple<>;
struct coupled_ports{
struct sendOut : public out_port<Communication> {
};
struct answerOut : public out_port<Communication> {
};
struct decideOut : public out_port<Communication> {
};
};
using oports = std::tuple<coupled_ports::sendOut, coupled_ports::answerOut, coupled_ports::decideOut>;
using submodels=cadmium::modeling::models_tuple<iestream_test_communication,iestream_test_set_decide,iestream_test_set_send,iestream_test_set_answer, devicesSwitch>;
using eics=std::tuple<>;
using eocs=std::tuple<
cadmium::modeling::EOC<devicesSwitch, out_send_p, coupled_ports::sendOut>,
cadmium::modeling::EOC<devicesSwitch, out_answer_p, coupled_ports::answerOut>,
cadmium::modeling::EOC<devicesSwitch, out_decide_p, coupled_ports::decideOut>
>;
using ics=std::tuple<
cadmium::modeling::IC<iestream_test_communication, out_p_iestreamCom , devicesSwitch, in_communication_p>,
cadmium::modeling::IC<iestream_test_set_decide, out_p_iestreamTDF , devicesSwitch, in_decide_p>,
cadmium::modeling::IC<iestream_test_set_send, out_p_iestreamCWD , devicesSwitch, in_send_p>,
cadmium::modeling::IC<iestream_test_set_answer, out_p_iestreamCom, devicesSwitch, in_answer_p>
>;
template<typename TIME>
using top_model=cadmium::modeling::coupled_model<TIME, iports, oports, submodels, eics, eocs, ics>;
/*******************************************/
/*************** Loggers *******************/
namespace {
std::ofstream out_data("tests_results/devicesSwitch.txt");
struct oss_sink_provider{
static std::ostream& sink(){
return out_data;
}
};
}
using log_states=cadmium::logger::logger<cadmium::logger::logger_state, cadmium::logger::verbatim_formatter, oss_sink_provider>;
using log_msg=cadmium::logger::logger<cadmium::logger::logger_messages, cadmium::logger::verbatim_formatter, oss_sink_provider>;
using log_gt=cadmium::logger::logger<cadmium::logger::logger_global_time, cadmium::logger::verbatim_formatter, oss_sink_provider>;
using logger_top=cadmium::logger::multilogger<log_states, log_msg, log_gt>;
/*******************************************/
int main(){
auto start = hclock::now(); //to measure simulation execution time
cadmium::engine::runner<NDTime, top_model, logger_top> r{{0}};
r.runUntil({3000});
auto elapsed = std::chrono::duration_cast<std::chrono::duration<double, std::ratio<1>>>(hclock::now() - start).count();
cout << "Simulation took:" << elapsed << "sec" << endl;
return 0;
}
| 40.056497 | 165 | 0.730183 | [
"model"
] |
c06eef1cc271e0c59bc6af0586fb6a2f48d78295 | 3,808 | cxx | C++ | osprey/common/com/x8664/targ_em_elf.cxx | sharugupta/OpenUH | daddd76858a53035f5d713f648d13373c22506e8 | [
"BSD-2-Clause"
] | null | null | null | osprey/common/com/x8664/targ_em_elf.cxx | sharugupta/OpenUH | daddd76858a53035f5d713f648d13373c22506e8 | [
"BSD-2-Clause"
] | null | null | null | osprey/common/com/x8664/targ_em_elf.cxx | sharugupta/OpenUH | daddd76858a53035f5d713f648d13373c22506e8 | [
"BSD-2-Clause"
] | null | null | null | /*
* Copyright 2005, 2006 PathScale, Inc. All Rights Reserved.
*/
/*
Copyright (C) 2000, 2001 Silicon Graphics, Inc. All Rights Reserved.
This program is free software; you can redistribute it and/or modify it
under the terms of version 2 of the GNU General Public License as
published by the Free Software Foundation.
This program is distributed in the hope that it would be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Further, this software is distributed without any warranty that it is
free of the rightful claim of any third person regarding infringement
or the like. Any license provided herein, whether implied or
otherwise, applies only to this software file. Patent licenses, if
any, provided herein do not apply to combinations of this program with
other software, or any other product whatsoever.
You should have received a copy of the GNU General Public License along
with this program; if not, write the Free Software Foundation, Inc., 59
Temple Place - Suite 330, Boston MA 02111-1307, USA.
Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pky,
Mountain View, CA 94043, or:
http://www.sgi.com
For further information regarding this notice, see:
http://oss.sgi.com/projects/GenInfo/NoticeExplan
*/
/* ====================================================================
* ====================================================================
*
* Module: em_elf.c
* $Revision: 1.5 $
* $Date: 05/11/07 20:34:18-08:00 $
* $Author: fchow@fluorspar.internal.keyresearch.com $
* $Source: common/com/x8664/SCCS/s.targ_em_elf.cxx $
*
* Description:
*
* Generate the elf headers and sections for the object file.
*
* ====================================================================
* ====================================================================
*/
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <errno.h>
#include <bstring.h>
#include "elf_stuff.h"
#include <elfaccess.h>
#include "libelf/libelf.h"
#include <stamp.h>
#include <alloca.h>
#include <cmplrs/leb128.h>
#include <cmplrs/elf_interfaces.h>
#include <sys/unwindP.h>
#define USE_STANDARD_TYPES 1
#include "defs.h"
#include "erlib.h"
#include "erglob.h"
#include "config.h"
#include "targ_const.h"
#include "glob.h"
#include "config.h"
#include "config_elf_targ.h"
#include "em_elf.h"
INT GP_DISP = 0;
pSCNINFO Interface_Scn;
void Em_Write_Reginfo (
Elf64_Addr gprvalue,
Elf64_Word gprmask,
Elf64_Word fprmask,
BOOL pure_abi)
{
/* should we put reginfo into the .options section? */
/* A: no */
return;
}
/* Add new entry to the .options section. */
void
Em_Add_New_Option (
Elf32_Byte option_kind,
Elf32_Section option_section,
Elf32_Word option_info,
void *buffer,
Elf32_Byte length)
{
Elf_Options option;
return;
}
/* Add a new event to the .events section. The operand1 and operand2
parameters are used to pass additional information needed for
certain event kinds.
EK_IF_ENTRY: operand1 is offset in interface scn.
EK_FCALL_LOCAL,
EK_FCALL_EXTERN,
EX_FCALL_EXTERN_BIG: operand1 is elf symbol index of called proc.
*/
void
Em_Add_New_Event (
Elf64_Word ev_kind,
Elf64_Word ev_ofst,
Elf64_Word operand1,
Elf64_Word operand2,
Elf64_Word operand3,
pSCNINFO scn)
{
return;
}
/* Add a new entry to the .contents section. */
void
Em_Add_New_Content (
Elf64_Word con_kind,
Elf64_Xword con_ofst,
Elf64_Word operand1,
Elf64_Word operand2,
pSCNINFO scn)
{
return;
}
void
Em_End_Unwind (FILE *trace_file, pSCNINFO text_scn)
{
}
void
Em_Cleanup_Unwind (void)
{
}
| 23.949686 | 73 | 0.664653 | [
"object"
] |
c07ebe50f0b9b6d0dfe22152c1fd89e7e9523740 | 32,377 | hpp | C++ | include/crest/geometry/indexed_mesh.hpp | Andlon/crest | f79bf5a68f3eb86f5e3422881678bc6f9011730a | [
"MIT"
] | null | null | null | include/crest/geometry/indexed_mesh.hpp | Andlon/crest | f79bf5a68f3eb86f5e3422881678bc6f9011730a | [
"MIT"
] | 5 | 2017-01-24T10:45:27.000Z | 2017-01-27T16:21:37.000Z | include/crest/geometry/indexed_mesh.hpp | Andlon/crest | f79bf5a68f3eb86f5e3422881678bc6f9011730a | [
"MIT"
] | null | null | null | #pragma once
#include <crest/geometry/vertex.hpp>
#include <crest/geometry/triangle.hpp>
#include <crest/util/algorithms.hpp>
#include <array>
#include <vector>
#include <cstdint>
#include <algorithm>
#include <unordered_map>
#include <ostream>
#include <limits>
#include <cassert>
namespace crest {
typedef uint32_t default_index_type;
typedef double default_scalar_type;
template <typename Index=default_index_type>
struct Element
{
std::array<Index, 3> vertex_indices;
explicit Element(std::array<Index, 3> indices) : vertex_indices(std::move(indices)) {}
};
template <typename Index=default_index_type>
struct Neighbors
{
std::array<Index, 3> indices;
explicit Neighbors(std::array<Index, 3> indices) : indices(std::move(indices)) {}
};
namespace detail
{
template <typename Index>
struct Edge;
}
/**
* IndexedMesh represents a 2D triangulation by an indexed set of vertices and a set of elements which holds
* indices into the indexed set of vertices.
*/
template <typename Scalar=default_scalar_type, typename Index=default_index_type>
class IndexedMesh
{
public:
typedef crest::Vertex<Scalar> Vertex;
typedef crest::Element<Index> Element;
typedef crest::Neighbors<Index> Neighbors;
typedef Index SentinelType;
IndexedMesh() {}
explicit IndexedMesh(std::vector<Vertex> vertices,
std::vector<Element> indices);
explicit IndexedMesh(std::vector<Vertex> vertices,
std::vector<Element> indices,
std::vector<Index> ancestry);
const std::vector<Vertex> & vertices() const { return _vertices; }
const std::vector<Element> & elements() const { return _elements; }
const std::vector<Neighbors> & neighbors() const { return _neighbors; }
std::array<Index, 3> neighbors_for(Index element_index) const;
Triangle<Scalar> triangle_for(Index element_index) const;
Index ancestor_for(Index element_index) const;
Index num_vertices() const { return static_cast<Index>(_vertices.size()); }
Index num_elements() const { return static_cast<Index>(_elements.size()); }
Index num_boundary_vertices() const { return static_cast<Index>(_boundary.size()); }
Index num_interior_vertices() const { return static_cast<Index>(num_vertices() - num_boundary_vertices()); };
const std::vector<Index> & boundary_vertices() const { return _boundary; }
// TODO: Consider rewriting interior indices as lazy iterators to avoid the potentially
// huge allocation of a vector of mostly consecutive integers.
std::vector<Index> compute_interior_vertices() const;
/**
* Use newest-vertex-bisection (NVB) to bisect all triangles indicated by their corresponding indices
* in the supplied vector of indices.
*
* Note that the application of NVB means that in addition to the marked elements,
* additional elements may have to be bisected in order for the mesh to remain conforming.
*
* In particular, for every triangle with vertices labelled (z0, z1, z2), if the triangle is marked
* or must be bisected to maintain a conforming triangulation, then it is replaced by two new
* triangles with vertices (z1, z_mid, z0) and (z2, z_mid, z1) respectively, where
* z_mid is the midpoint on the refinement edge (z2, z0).
*
* The implementation has been designed to be memory-efficient and very fast.
*
* @param marked A set of valid triangle indices that should be bisected.
*/
void bisect_marked(std::vector<Index> marked);
/**
* Attempts to compress the data structure so that it consumes less memory. Only use this when you are sure
* that you will not further refine the mesh, as it may negatively impact the performance of subsequent
* refinement.
*/
void compress();
/**
* Effectively makes every triangle its own ancestor.
*
* If one represents the mesh as a forest of trees, this would take every leaf node and build a new
* forest in which each lofe node becomes a standalone tree.
*/
void reset_ancestry();
/**
* Returns the sentinel value used when a sentinel value is required. This is a special value at the extreme
* of the range of valid values in the type, and is used to indicate special properties, such as when
* a triangle has no neighbor (the index of the neighbor is then given by a sentinel value).
*/
constexpr static SentinelType sentinel() { return std::numeric_limits<Index>::max(); }
private:
bool edge_has_hanging_node(Index element_index, Index local_edge_index);
Index find_local_edge_in_element(Index element_index, const detail::Edge<Index> & global_edge);
Index find_midpoint(Index element_index, Index first_refinement_neighbor);
Index find_second_refinement_neighbor(Index element_index,
Index first_refinement_neighbor,
Index midpoint_index);
std::vector<Vertex> _vertices;
std::vector<Element> _elements;
std::vector<Neighbors> _neighbors;
std::vector<Index> _boundary;
std::vector<Index> _ancestors;
};
class conformance_error : public std::logic_error
{
public:
explicit conformance_error(const std::string & what) : std::logic_error(what) {}
};
/*
* IMPLEMENTATION
*/
namespace detail {
template <typename I>
I find_neighbor_from_edge_vertices(I element_index,
const std::vector<I> & a_vertices,
const std::vector<I> & b_vertices)
{
// This algorithm is obviously N^2, but we except each vector to hold a very low amount of items,
// and since then both vectors most likely fit in cache, it might in fact outperform more efficient
// routines involving sorts (would require profiling to verify).
constexpr I NO_NEIGHBOR = std::numeric_limits<I>::max();
I neighbor_index = NO_NEIGHBOR;
size_t num_matches = 0;
for (auto i : a_vertices)
{
for (auto j : b_vertices)
{
if (i == j && i != element_index)
{
neighbor_index = i;
++num_matches;
}
}
}
if (num_matches > 1) throw conformance_error("An edge shared by more than two triangles is not conforming.");
return neighbor_index;
}
template <typename I>
std::vector<Neighbors<I>> find_neighbors(I num_vertices, const std::vector<Element<I>> & elements)
{
std::vector<Neighbors<I>> element_neighbors;
element_neighbors.resize(elements.size(), Neighbors<I>({0, 0, 0}));
std::unordered_map<I, std::vector<I>> vertex_to_triangles;
// Map each vertex to the set of triangles that contain it
for (size_t element_index = 0; element_index < elements.size(); ++element_index)
{
const auto & element = elements[element_index];
for (auto vertex_index : element.vertex_indices)
{
if (vertex_index < 0 || vertex_index >= num_vertices)
{
throw std::out_of_range("Invalid vertex index in element.");
}
vertex_to_triangles[vertex_index].push_back(element_index);
}
}
// For a conforming triangulation, each edge defined by two connected vertices
// can only be shared by at most two triangles.
for (size_t element_index = 0; element_index < elements.size(); ++element_index)
{
const auto & element = elements[element_index];
auto & neighbors = element_neighbors[element_index];
// for an element defined by the vertex indices (z0, z1, z2),
// we have the convention that the neighbors are ordered in the order of the edges
// (z0, z1), (z1, z2), (z2, z0),
// so that the first neighbor shares edge (z0, z1) and so on.
auto z0_triangles = vertex_to_triangles[element.vertex_indices[0]];
auto z1_triangles = vertex_to_triangles[element.vertex_indices[1]];
auto z2_triangles = vertex_to_triangles[element.vertex_indices[2]];
neighbors.indices[0] = find_neighbor_from_edge_vertices<I>(element_index, z0_triangles, z1_triangles);
neighbors.indices[1] = find_neighbor_from_edge_vertices<I>(element_index, z1_triangles, z2_triangles);
neighbors.indices[2] = find_neighbor_from_edge_vertices<I>(element_index, z2_triangles, z0_triangles);
}
return element_neighbors;
};
template <typename T, typename I>
std::vector<I> determine_new_boundary_vertices(const IndexedMesh<T, I> & mesh)
{
const auto NO_NEIGHBOR = mesh.sentinel();
std::vector<I> boundary;
auto push_boundary_edge = [&boundary] (auto from, auto to)
{
boundary.push_back(from);
boundary.push_back(to);
};
for (I element_index = 0; element_index < mesh.num_elements(); ++element_index)
{
const auto vertex_indices = mesh.elements()[element_index].vertex_indices;
const auto neighbors = mesh.neighbors_for(element_index);
const auto z0 = vertex_indices[0];
const auto z1 = vertex_indices[1];
const auto z2 = vertex_indices[2];
// Recall that edges are ordered (z0, z1), (z1, z2), (z2, z0).
if (neighbors[0] == NO_NEIGHBOR) push_boundary_edge(z0, z1);
if (neighbors[1] == NO_NEIGHBOR) push_boundary_edge(z1, z2);
if (neighbors[2] == NO_NEIGHBOR) push_boundary_edge(z2, z0);
}
std::sort(boundary.begin(), boundary.end());
boundary.erase(std::unique(boundary.begin(), boundary.end()), boundary.end());
return boundary;
};
template <typename Index>
struct Edge
{
Index from;
Index to;
explicit Edge(Index from, Index to) : from(from), to(to) {}
};
template <typename Index>
struct EdgeHash
{
std::size_t operator()(const Edge<Index> & e) const
{
const auto from_hash = std::hash<Index>{}(e.from);
const auto to_hash = std::hash<Index>{}(e.to);
// Note: it's important that the hash is symmetric, which XOR is
return from_hash ^ to_hash;
}
};
template <typename Index>
inline bool operator ==(const Edge<Index> & e1, const Edge<Index> &e2)
{
// Edge(a, b) == Edge(b, a)
return (e1.from == e2.from && e1.to == e2.to) || (e1.from == e2.to && e1.to == e2.from);
}
}
template <typename I>
inline bool operator==(const Element<I> & left, const Element<I> & right) {
return std::equal(left.vertex_indices.cbegin(), left.vertex_indices.cend(), right.vertex_indices.cbegin());
}
template <typename I>
inline std::ostream & operator<<(std::ostream & o, const Element<I> & element)
{
o << "[ "
<< element.vertex_indices[0] << ", "
<< element.vertex_indices[1] << ", "
<< element.vertex_indices[2]
<< " ]";
return o;
}
template <typename S, typename I>
inline std::ostream & operator<<(std::ostream & o, const IndexedMesh<S, I> & mesh)
{
using std::endl;
o << "IndexedMesh with " << mesh.num_vertices() << " vertices and " << mesh.num_elements() << " elements."
<< endl
<< "Vertices: " << endl;
for (const auto v : mesh.vertices())
{
o << "\t" << v << endl;
}
o << "Elements: " << endl;
for (I e = 0; e < mesh.num_elements(); ++e)
{
o << "\t" << mesh.elements()[e] << " with ancestor " << mesh.ancestor_for(e) << endl;
}
return o;
};
template <typename T, typename I>
inline IndexedMesh<T, I>::IndexedMesh(std::vector<IndexedMesh<T, I>::Vertex> vertices,
std::vector<IndexedMesh<T, I>::Element> elements)
: _vertices(std::move(vertices)), _elements(std::move(elements)),
_neighbors(detail::find_neighbors(static_cast<I>(_vertices.size()), _elements))
{
_boundary = detail::determine_new_boundary_vertices(*this);
_ancestors.reserve(num_elements());
for (I i = 0; i < num_elements(); ++i)
{
// Make every triangle an ancestor of itself
_ancestors.push_back(i);
}
}
template <typename T, typename I>
inline IndexedMesh<T, I>::IndexedMesh(std::vector<IndexedMesh<T, I>::Vertex> vertices,
std::vector<IndexedMesh<T, I>::Element> elements,
std::vector<I> ancestry)
: _vertices(std::move(vertices)), _elements(std::move(elements)),
_neighbors(detail::find_neighbors(static_cast<I>(_vertices.size()), _elements))
{
assert(ancestry.size() == _elements.size());
_boundary = detail::determine_new_boundary_vertices(*this);
_ancestors = std::move(ancestry);
}
template <typename T, typename I>
inline std::array<I, 3> IndexedMesh<T, I>::neighbors_for(I element_index) const
{
assert(element_index >= 0 && element_index < num_elements());
return _neighbors[element_index].indices;
};
template <typename T, typename I>
inline Triangle<T> IndexedMesh<T, I>::triangle_for(I element_index) const
{
assert(element_index >= 0 && element_index < num_elements());
const auto indices = _elements[static_cast<size_t>(element_index)].vertex_indices;
const auto a = _vertices[indices[0]];
const auto b = _vertices[indices[1]];
const auto c = _vertices[indices[2]];
return Triangle<T>(a, b, c);
}
template <typename T, typename I>
inline I IndexedMesh<T, I>::ancestor_for(I element_index) const
{
assert(element_index >= 0 && element_index < num_elements());
return _ancestors[element_index];
}
template <typename T, typename I>
inline void IndexedMesh<T, I>::compress()
{
_neighbors.shrink_to_fit();
_vertices.shrink_to_fit();
_elements.shrink_to_fit();
_boundary.shrink_to_fit();
};
template <typename T, typename I>
inline std::vector<I> IndexedMesh<T, I>::compute_interior_vertices() const {
std::vector<I> interior;
interior.reserve(num_interior_vertices());
const auto & boundary = boundary_vertices();
size_t boundary_index = 0;
for (I i = 0; i < num_vertices(); ++i)
{
if (boundary_index < boundary.size() && i == boundary[boundary_index])
{
++boundary_index;
} else
{
interior.push_back(i);
}
}
return interior;
};
template <typename T, typename I>
inline void IndexedMesh<T, I>::reset_ancestry()
{
for (I t = 0; t < num_elements(); ++t)
{
_ancestors[t] = t;
}
}
template <typename T, typename I>
inline bool IndexedMesh<T, I>::edge_has_hanging_node(I element_index, I local_edge_index)
{
typedef detail::Edge<I> Edge;
assert(element_index >= 0 && element_index < num_elements());
assert(local_edge_index >= 0 && local_edge_index < 3);
constexpr auto NO_NEIGHBOR = sentinel();
const auto neighbor = neighbors_for(element_index)[local_edge_index];
if (neighbor == NO_NEIGHBOR)
{
return false;
}
else
{
const auto element_vertices = elements()[element_index].vertex_indices;
const auto nb_vertices = elements()[neighbor].vertex_indices;
const auto nb_neighbors = neighbors_for(neighbor);
const auto nb_edge_index = algo::index_of(nb_neighbors, element_index);
const auto a = element_vertices[local_edge_index];
const auto b = element_vertices[(local_edge_index + 1) % 3];
const auto nb_a = nb_vertices[nb_edge_index];
const auto nb_b = nb_vertices[(nb_edge_index + 1) % 3];
const auto max_index = std::max({a, b, nb_a, nb_b});
const auto edge_is_shared = Edge(a, b) == Edge(nb_a, nb_b);
// From the aforementioned property, it follows that the midpoint must be the largest index
// in the set {a, b, nb_a, nb_b}. We can use this to determine if the midpoint is on (z2, z0),
// in which case the midpoint is not contained in the current triangle.
const auto midpoint_is_on_refinement_edge = max_index != a && max_index != b;
assert(algo::contains(nb_vertices, a) || algo::contains(nb_vertices, b));
return !edge_is_shared && midpoint_is_on_refinement_edge;
}
}
template <typename T, typename I>
inline I IndexedMesh<T, I>::find_local_edge_in_element(I element_index,
const crest::detail::Edge<I> & global_edge)
{
typedef detail::Edge<I> Edge;
for (I i = 0; i < 3; ++i)
{
const auto a = elements()[element_index].vertex_indices[i];
const auto b = elements()[element_index].vertex_indices[(i + 1) % 3];
if (Edge(a, b) == global_edge)
{
return i;
}
}
return sentinel();
}
template <typename T, typename I>
inline I IndexedMesh<T, I>::find_second_refinement_neighbor(I element_index,
I first_refinement_neighbor,
I midpoint_index)
{
// We need to recover the index of the second triangle connected to the midpoint
// which has the current element as its neighbor. In order to do so, we can
// cycle through the triangles connected to the midpoint.
auto current = first_refinement_neighbor;
auto previous = sentinel();
const auto is_next = [this, &previous, element_index, midpoint_index] (auto n)
{
constexpr auto NO_NEIGHBOR = this->sentinel();
return n != NO_NEIGHBOR
&& n != previous
&& algo::contains(this->elements()[n].vertex_indices, midpoint_index);
};
while (true)
{
const auto current_neighbors = neighbors_for(current);
const auto next = std::find_if(current_neighbors.cbegin(),
current_neighbors.cend(),
is_next);
if (next != current_neighbors.cend())
{
previous = current;
current = *next;
}
else
{
// Since the midpoint is a hanging node, we won't be able to cycle all the way back to the
// first refinement neighbor. Hence, when we'are at the last node in the cycle,
// we have found the second refinement neighbor.
return current;
}
}
}
template <typename T, typename I>
inline I IndexedMesh<T, I>::find_midpoint(I element_index, I first_refinement_neighbor)
{
// In order to determine the midpoint,
// we can note that the midpoint must be one of the vertices a, b in the first refinement neighbor on the edge
// which neighbors the current element. Recalling the property that for any edge (a, b)
// with a midpoint c, we have that c > a, c > b since midpoints are always added
// after the vertices that make up the edge.
const auto refinement_nb_vertices = elements()[first_refinement_neighbor].vertex_indices;
const auto refinement_neighbors = neighbors_for(first_refinement_neighbor);
const auto refinement_local_edge = algo::index_of(refinement_neighbors, element_index);
assert(refinement_local_edge >= 0 && refinement_local_edge < 3);
const auto a = refinement_nb_vertices[refinement_local_edge];
const auto b = refinement_nb_vertices[(refinement_local_edge + 1) % 3];
return std::max(a, b);
}
template <typename T, typename I>
inline void IndexedMesh<T, I>::bisect_marked(std::vector<I> marked)
{
// The implementation here relies heavily on certain important conventions.
// First, for any element K defined by vertex indices (z0, z1, z2),
// we define the *refinement edge* to be the edge between z2 and z0, denoted (z2, z0).
// For a triangle K defined by the vertices (z0, z1, z2), and the midpoint z_mid
// on the refinement edge (z2, z0), we define the 'left' and 'right' triangles as the two triangles defined
// by the vertices (z1, midpoint_index, z0) and (z2, midpoint_index, z1) respectively. The names correspond
// to the fact that if the vertices are defined in a counter-clockwise order, the 'left' triangle will
// correspond to the left triangle when facing the refinement edge, and similarly for the right one.
// Note also in particular that this choice of indices preserves the *winding order* of the original triangle.
// This is important, because for some applications (such as computer graphics), the winding order defines
// the orientation of the face associated with the triangle.
// The below implementation is quite complicated, because it is designed only to use memory-efficient
// flat data structures (std::vector), avoiding more complicated data structures like hash tables, which
// could simplify the implementation somewhat. For a justification, note that the current implementation
// runs about 10 times as fast as the implementation based on hash tables that was implemented first.
// In the below implementation, we leverage the following properties of the implementation:
// - Given a triangle T and a neighbor K on its refinement edge (z2, z0), its children L = (z1, z_mid, z0)
// and R = (z2, z_mid, z1) after bisection will have neighbors K and NO_NEIGHBOR, respectively,
// and K will have neighbor L on the refinement edge.
// - Any midpoint added to the triangulation is always added to the end of the list of vertices.
// Consequently, given an edge (a, b), its midpoint c will have index c > a, c > b.
typedef detail::Edge<I> Edge;
constexpr I NO_NEIGHBOR = sentinel();
// We will maintain a list of 'marked' elements, which are marked in this round of refinement,
// and a list of 'nonconforming' elements which correspond to elements which contain hanging nodes
// and must subsequently be refined.
std::vector<I> nonconforming;
if (std::any_of(marked.cbegin(), marked.cend(), [this] (auto i) { return i >= this->num_elements(); }))
{
throw std::invalid_argument("Set of marked elements contains element indices out of bounds.");
}
do {
// The algorithm may mark the same element multiple times in the course of a single iteration
// so we need to remove duplicates first. We also sort it so we can use binary search later.
// Using a hashset would provide better average complexity, but it would be less memory-efficient,
// and since triangulations usually don't grow too big (more than a few million elements, perhaps),
// std::sort is still extremely fast for integers.
std::sort(marked.begin(), marked.end());
marked.erase(std::unique(marked.begin(), marked.end()), marked.end());
for (const auto element_index : marked)
{
const auto & element = elements()[element_index];
const auto neighbors = neighbors_for(element_index);
const auto edge_is_on_boundary = [this, element_index] (I local_edge_index) {
return neighbors_for(element_index)[local_edge_index] == NO_NEIGHBOR;
};
auto update_neighbor_of = [this, &nonconforming, element_index, edge_is_on_boundary]
(I local_edge_index, I new_index) {
// Update the neighbor on the edge indicated by local_edge_index with the new index.
// This is of course only necessary if there exists a neighbor at all
// (i.e. we're not on the boundary)
if (!edge_is_on_boundary(local_edge_index))
{
const auto neighbor = neighbors_for(element_index)[local_edge_index];
auto & neighbors_of_neighbor = _neighbors[neighbor].indices;
auto pos_of_element_in_neighbor =
std::find(neighbors_of_neighbor.begin(), neighbors_of_neighbor.end(), element_index);
if (edge_has_hanging_node(element_index, local_edge_index))
{
nonconforming.push_back(new_index);
}
if (pos_of_element_in_neighbor != neighbors_of_neighbor.end())
{
*pos_of_element_in_neighbor = new_index;
}
}
};
const auto left_index = element_index;
const auto right_index = static_cast<I>(_elements.size());
const auto z0 = element.vertex_indices[0];
const auto z1 = element.vertex_indices[1];
const auto z2 = element.vertex_indices[2];
// Recall that we have the edges (z0, z1), (z1, z2), (z2, z0),
// and the indexing of neighbors is defined in the same order.
auto left_neighbors = Neighbors({right_index, neighbors[2], neighbors[0] });
auto right_neighbors = Neighbors({NO_NEIGHBOR, left_index, neighbors[1] });
const auto refinement_neighbor = neighbors[2];
I midpoint_index = sentinel();
if (edge_has_hanging_node(element_index, 2))
{
midpoint_index = find_midpoint(element_index, refinement_neighbor);
// Denote n20 as the neighbor on edge (z2, z0)
const auto & n20 = refinement_neighbor;
const auto n20_second = find_second_refinement_neighbor(element_index, n20, midpoint_index);
// Determine which child in the refinement neighbor (n20, n20_second) gets connected
// to the children of the triangle currently being bisected.
I left_refinement_neighbor, right_refinement_neighbor;
const auto n20_vertices = elements()[n20].vertex_indices;
if (algo::contains(n20_vertices, z0))
{
left_refinement_neighbor = n20;
right_refinement_neighbor = n20_second;
}
else
{
assert(algo::contains(n20_vertices, z2));
left_refinement_neighbor = n20_second;
right_refinement_neighbor = n20;
}
// Make the neighbor connections, effectively removing the hanging node.
left_neighbors.indices[1] = left_refinement_neighbor;
right_neighbors.indices[0] = right_refinement_neighbor;
const auto left_ref_local_edge = find_local_edge_in_element(left_refinement_neighbor,
Edge(z0, midpoint_index));
const auto right_ref_local_edge = find_local_edge_in_element(right_refinement_neighbor,
Edge(z2, midpoint_index));
_neighbors[left_refinement_neighbor].indices[left_ref_local_edge] = left_index;
_neighbors[right_refinement_neighbor].indices[right_ref_local_edge] = right_index;
assert(left_ref_local_edge != sentinel());
assert(right_ref_local_edge != sentinel());
}
else
{
// There is currently no hanging node on the refinement edge
const auto v0 = vertices()[z0];
const auto v2 = vertices()[z2];
midpoint_index = static_cast<I>(num_vertices());
_vertices.emplace_back(midpoint(v0, v2));
if (edge_is_on_boundary(2))
{
// Recall that _boundary must always be sorted. Since we already add new midpoint vertices
// to the end of the list of vertices, this invariant holds automatically when
// we add the midpoint to the list of boundary indices.
_boundary.push_back(midpoint_index);
}
else if (refinement_neighbor < element_index
|| !std::binary_search(marked.cbegin(), marked.cend(), refinement_neighbor))
{
// If the refinement neighbor is not currently already queued for bisection,
// we must mark it for bisection in the next round.
nonconforming.push_back(refinement_neighbor);
}
}
update_neighbor_of(0, left_index);
update_neighbor_of(1, right_index);
const auto left = Element({z1, midpoint_index, z0});
const auto right = Element({z2, midpoint_index, z1});
_elements[left_index] = left;
_elements.push_back(right);
_neighbors[left_index] = left_neighbors;
_neighbors.push_back(right_neighbors);
if (_ancestors[left_index] == sentinel())
{
// If the element being refined has no ancestor, we want to make this element the ancestor
// of the two new elements.
_ancestors[left_index] = element_index;
_ancestors.push_back(element_index);
} else
{
// If the element being refined has an ancestor, we want to keep this ancestor in the
// two new elements (and hence we do not need to change the ancestor of left_index).
_ancestors.push_back(_ancestors[left_index]);
}
assert(midpoint_index != sentinel());
}
// Note that this pattern minimizes reallocation
marked.swap(nonconforming);
nonconforming.clear();
} while (!marked.empty());
};
}
| 44.781466 | 121 | 0.582203 | [
"mesh",
"geometry",
"vector"
] |
c08f3f921f53663f14b7668f58e9e9da71bca687 | 846 | cc | C++ | implement/cpp/MyQueue.cc | 4soos/leetcode_practices | 0b6bde3f6832ce983bb39482c0da47509fc23c78 | [
"MIT"
] | null | null | null | implement/cpp/MyQueue.cc | 4soos/leetcode_practices | 0b6bde3f6832ce983bb39482c0da47509fc23c78 | [
"MIT"
] | null | null | null | implement/cpp/MyQueue.cc | 4soos/leetcode_practices | 0b6bde3f6832ce983bb39482c0da47509fc23c78 | [
"MIT"
] | null | null | null | #include <stack>
class MyQueue {
public:
MyQueue() {
}
void push(int x) {
in.push(x);
}
int pop() {
if (out.empty()) {
in_to_out();
}
int x = out.top();
out.pop();
return x;
}
int peek() {
if (out.empty()) {
in_to_out();
}
return out.top();
}
bool empty() {
return in.empty() && out.empty();
}
private:
std::stack<int> in, out;
void in_to_out() {
while (!in.empty()) {
out.push(in.top());
in.pop();
}
}
};
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue* obj = new MyQueue();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->peek();
* bool param_4 = obj->empty();
*/ | 16.92 | 63 | 0.433806 | [
"object"
] |
6a51125827f955a9ed909945afc282fee9e1f9ee | 62,524 | cpp | C++ | math3/sphere.cpp | Mixaill/directxmathtest | 0a7d946e4980608d9ee22c7887e37a1a87d2765e | [
"MIT"
] | null | null | null | math3/sphere.cpp | Mixaill/directxmathtest | 0a7d946e4980608d9ee22c7887e37a1a87d2765e | [
"MIT"
] | null | null | null | math3/sphere.cpp | Mixaill/directxmathtest | 0a7d946e4980608d9ee22c7887e37a1a87d2765e | [
"MIT"
] | null | null | null | //-------------------------------------------------------------------------------------
// sphere.cpp - DirectXMath Test Suite
//
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
//
// http://go.microsoft.com/fwlink/?LinkID=615560
//-------------------------------------------------------------------------------------
#include "math3.h"
using namespace DirectX;
static const float EPSILON = 0.001f;
inline bool IsEqual( const BoundingSphere& s1, const BoundingSphere& s2 )
{
return ( ( fabs( s1.Center.x - s2.Center.x ) < EPSILON )
&& ( fabs( s1.Center.y - s2.Center.y ) < EPSILON )
&& ( fabs( s1.Center.z - s2.Center.z ) < EPSILON )
&& ( fabs( s1.Radius - s2.Radius ) < EPSILON ) );
}
#define printxmv(v) printe("%s: %f,%f,%f,%f\n", #v, XMVectorGetX(v), XMVectorGetY(v), XMVectorGetZ(v), XMVectorGetW(v))
#define printsh(v) printe("%s: center=%f,%f,%f radius=%f\n", #v, v.Center.x, v.Center.y, v.Center.z, v.Radius )
#define printbb(v) printe("%s: center=%f,%f,%f extents=%f,%f,%f\n", #v, v.Center.x, v.Center.y, v.Center.z, v.Extents.x, v.Extents.y, v.Extents.z )
#define printobb(v) printe("%s: center=%f,%f,%f extents=%f,%f,%f orientation=%f,%f,%f,%f\n", #v, \
v.Center.x, v.Center.y, v.Center.z, v.Extents.x, v.Extents.y, v.Extents.z, \
v.Orientation.x, v.Orientation.y, v.Orientation.z, v.Orientation.w )
#define printfr(v) printe("%s: origin=%f,%f,%f\n\torientation=%f,%f,%f,%f\n\tright=%f left=%f\n\ttop=%f bottom=%f\n\tnear=%f far=%f\n", #v, \
v.Origin.x, v.Origin.y, v.Origin.z, v.Orientation.x, v.Orientation.y, v.Orientation.z, v.Orientation.w, \
v.RightSlope, v.LeftSlope, v.TopSlope, v.BottomSlope, v.Near, v.Far )
#define printtri(v,v0,v1,v2) printe("%s: v0=%f,%f,%f v1=%f,%f,%f v2=%f,%f,%f\n", #v, v0.x, v0.y, v0.z, v1.x, v1.y, v1.z, v2.x, v2.y, v2.z )
#define printct(t) switch(t) { case DISJOINT: printe("%s: DISJOINT\n", #t); break; \
case INTERSECTS: printe("%s: INTERSECTS\n", #t); break; \
case CONTAINS: printe("%s: CONTAINS\n", #t); break; }
#define printpt(t) switch(t) { case FRONT: printe("%s: FRONT\n", #t); break; \
case INTERSECTING: printe("%s: INTERSECTING\n", #t); break; \
case BACK: printe("%s: BACK\n", #t); break; }
//-------------------------------------------------------------------------------------
// BoundingSphere
HRESULT TestS01(LogProxy* pLog)
{
bool success = true;
static_assert(std::is_nothrow_copy_assignable<DirectX::BoundingSphere>::value, "Copy Assign.");
static_assert(std::is_nothrow_copy_constructible<DirectX::BoundingSphere>::value, "Copy Ctor.");
static_assert(std::is_nothrow_move_constructible<DirectX::BoundingSphere>::value, "Move Ctor.");
static_assert(std::is_nothrow_move_assignable<DirectX::BoundingSphere>::value, "Move Assign.");
// Default constructor
BoundingSphere sh;
if ( fabs( sh.Center.x ) > EPSILON
|| fabs( sh.Center.y ) > EPSILON
|| fabs( sh.Center.z ) > EPSILON
|| fabs( sh.Radius - 1.0f ) > EPSILON )
{
printe("%s: Default constructor didn't create unit sphere\n", TestName);
printsh( sh );
success = false;
}
// Vector + Radius constructor
BoundingSphere shp( XMFLOAT3(1.f, 2.f, 3.f), 4.f );
if ( fabs( shp.Center.x - 1.f) > EPSILON
|| fabs( shp.Center.y - 2.f) > EPSILON
|| fabs( shp.Center.z - 3.f) > EPSILON
|| fabs( shp.Radius - 4.0f ) > EPSILON )
{
printe("%s: Constructor didn't create correct sphere\n", TestName);
printsh( shp );
success = false;
}
BoundingSphere shp2( XMFLOAT3(1.1f, 2.2f, 3.3f), 4.4f );
if ( fabs( shp2.Center.x - 1.1f) > EPSILON
|| fabs( shp2.Center.y - 2.2f) > EPSILON
|| fabs( shp2.Center.z - 3.3f) > EPSILON
|| fabs( shp2.Radius - 4.4f ) > EPSILON )
{
printe("%s: Constructor didn't create correct sphere (2)\n", TestName);
printsh( shp2 );
success = false;
}
// Copy constructor
BoundingSphere shc(shp);
if ( !IsEqual(shc,shp) )
{
printe("%s: Copy constructor failed\n",TestName);
printsh( shc );
printsh( shp );
success = false;
}
// Test assignment operator
BoundingSphere shi;
shi = shp;
if ( !IsEqual(shi,shp) )
{
printe("%s: Assignment operator failed\n",TestName);
printsh( shi );
printsh( shp );
success = false;
}
return ( success ) ? S_OK : MATH_FAIL;
}
//-------------------------------------------------------------------------------------
// Sphere::Transform
HRESULT TestS02(LogProxy* pLog)
{
bool success = true;
BoundingSphere shu, shv;
XMMATRIX Mid = XMMatrixIdentity();
XMVECTOR Rid = XMQuaternionIdentity();
XMVECTOR Tid = XMVectorZero();
// Unit sphere
const BoundingSphere unit;
unit.Transform( shu, Mid );
if ( !IsEqual(unit,shu) )
{
printe("%s: Unit sphere tranform(1) failed\n",TestName);
printsh(unit);
printsh(shu);
success = false;
}
unit.Transform( shv, 1.0f, Rid, Tid );
if ( !IsEqual(unit,shv) )
{
printe("%s: Unit sphere tranform(2) failed\n",TestName);
printsh(unit);
printsh(shv);
success = false;
}
// Small sphere (w/ scaling)
const BoundingSphere _small( XMFLOAT3(0.1f, 0.0f, 0.0f), 0.5f );
XMMATRIX mat = XMMatrixTransformation( g_XMZero, // Scaling origin
Rid, // Scaling orientation
XMVectorSet( 3.f, 3.f, 3.f, 0.f ), // Scaling
g_XMZero, // Rotation origin
Rid, // Rotation
g_XMOne // Translation
);
XMMATRIX matNonUniform = XMMatrixTransformation( g_XMZero, // Scaling origin
Rid, // Scaling orientation
XMVectorSet( 1.f, 2.f, 3.f, 0.f ), // Scaling
g_XMZero, // Rotation origin
Rid, // Rotation
g_XMOne // Translation
);
_small.Transform( shu, mat );
if ( fabs( shu.Center.x - 1.3f) > EPSILON
|| fabs( shu.Center.y - 1.f) > EPSILON
|| fabs( shu.Center.z - 1.0f) > EPSILON
|| fabs( shu.Radius - 1.5f ) > EPSILON )
{
printe("%s: Small transform(1) failed\n",TestName);
printsh(_small);
printsh(shu);
success = false;
}
_small.Transform( shv, 3.0f, Rid, g_XMOne );
if ( !IsEqual(shu,shv) )
{
printe("%s: Small transform(2) failed\n",TestName);
printsh(_small);
printsh(shu);
printsh(shv);
success = false;
}
// Small sphere (w/ non-uniform scaling)
_small.Transform( shu, matNonUniform );
if ( fabs( shu.Center.x - 1.1f) > EPSILON
|| fabs( shu.Center.y - 1.f) > EPSILON
|| fabs( shu.Center.z - 1.f) > EPSILON
|| fabs( shu.Radius - 1.5f ) > EPSILON )
{
printe("%s: Small transform(3) failed\n",TestName);
printsh(_small);
printsh(shu);
success = false;
}
if ( IsEqual(shu,shv) )
{
// should not be equal to the uniform scale version
printe("%s: Small transform(4) failed\n",TestName);
printsh(_small);
printsh(shu);
printsh(shv);
success = false;
}
// Big sphere (w/ scaling)
const BoundingSphere big( XMFLOAT3(1.f, 2.f, 3.f), 10.0f );
big.Transform( shu, mat );
if ( fabs( shu.Center.x - 4.f) > EPSILON
|| fabs( shu.Center.y - 7.f) > EPSILON
|| fabs( shu.Center.z - 10.f) > EPSILON
|| fabs( shu.Radius - 30.f ) > EPSILON )
{
printe("%s: Big transform(1) failed\n",TestName);
printsh(big);
printsh(shu);
success = false;
}
big.Transform( shv, 3.0f, Rid, g_XMOne );
if ( !IsEqual(shu,shv) )
{
printe("%s: Big transform(2) failed\n",TestName);
printsh(big);
printsh(shu);
printsh(shv);
success = false;
}
// Big sphere (w/ non-uniform scaling)
big.Transform( shu, matNonUniform );
if ( fabs( shu.Center.x - 2.f) > EPSILON
|| fabs( shu.Center.y - 5.f) > EPSILON
|| fabs( shu.Center.z - 10.f) > EPSILON
|| fabs( shu.Radius - 30.f ) > EPSILON )
{
printe("%s: Big transform(3) failed\n",TestName);
printsh(big);
printsh(shu);
success = false;
}
if ( IsEqual(shu,shv) )
{
printe("%s: Big transform(4) failed\n",TestName);
printsh(big);
printsh(shu);
printsh(shv);
success = false;
}
// Small sphere (w/ rotation & scaling)
XMVECTOR rot = XMQuaternionRotationRollPitchYaw( 0.f, XM_PIDIV2, 0.f );
mat = XMMatrixTransformation( g_XMZero, // Scaling origin
Rid, // Scaling orientation
XMVectorSet( 3.f, 3.f, 3.f, 0.f ), // Scaling
g_XMZero, // Rotation origin
rot, // Rotation
g_XMOne // Translation
);
matNonUniform = XMMatrixTransformation( g_XMZero, // Scaling origin
Rid, // Scaling orientation
XMVectorSet( 1.f, 2.f, 3.f, 0.f ), // Scaling
g_XMZero, // Rotation origin
rot, // Rotation
g_XMOne // Translation
);
_small.Transform( shu, mat );
if ( fabs( shu.Center.x - 1.f) > EPSILON
|| fabs( shu.Center.y - 1.f) > EPSILON
|| fabs( shu.Center.z - 0.7f) > EPSILON
|| fabs( shu.Radius - 1.5f ) > EPSILON )
{
printe("%s: Small transform(5) failed\n",TestName);
printsh(_small);
printsh(shu);
success = false;
}
_small.Transform( shv, 3.0f, rot, g_XMOne );
if ( !IsEqual(shu,shv) )
{
printe("%s: Small transform(6) failed\n",TestName);
printsh(_small);
printsh(shu);
printsh(shv);
success = false;
}
// Small sphere (w/ rotation & non-uniform scaling)
_small.Transform( shu, matNonUniform );
if ( fabs( shu.Center.x - 1.f) > EPSILON
|| fabs( shu.Center.y - 1.f) > EPSILON
|| fabs( shu.Center.z - 0.9f) > EPSILON
|| fabs( shu.Radius - 1.5f ) > EPSILON )
{
printe("%s: Small transform(7) failed\n",TestName);
printsh(_small);
printsh(shu);
success = false;
}
if ( IsEqual(shu,shv) )
{
printe("%s: Small transform(8) failed\n",TestName);
printsh(_small);
printsh(shu);
printsh(shv);
success = false;
}
// Big sphere (w/ rotation & scaling)
big.Transform( shu, mat );
if ( fabs( shu.Center.x - 9.99999f) > EPSILON
|| fabs( shu.Center.y - 7.f) > EPSILON
|| fabs( shu.Center.z + 1.99999f) > EPSILON
|| fabs( shu.Radius - 30.f ) > EPSILON )
{
printe("%s: Big transform(5) failed\n",TestName);
printsh(big);
printsh(shu);
success = false;
}
big.Transform( shv, 3.0f, rot, g_XMOne );
if ( !IsEqual(shu,shv) )
{
printe("%s: Big transform(6) failed\n",TestName);
printsh(big);
printsh(shu);
printsh(shv);
success = false;
}
// Big sphere (w/ rotation & non-scaling)
big.Transform( shu, matNonUniform );
if ( fabs( shu.Center.x - 9.99999f) > EPSILON
|| fabs( shu.Center.y - 5.f) > EPSILON
|| fabs( shu.Center.z - 0.f) > EPSILON
|| fabs( shu.Radius - 30.f ) > EPSILON )
{
printe("%s: Big transform(7) failed\n",TestName);
printsh(big);
printsh(shu);
success = false;
}
if ( IsEqual(shu,shv) )
{
printe("%s: Big transform(8) failed\n",TestName);
printsh(big);
printsh(shu);
printsh(shv);
success = false;
}
return ( success ) ? S_OK : MATH_FAIL;
}
//-------------------------------------------------------------------------------------
// Sphere::Contains
HRESULT TestS03(LogProxy* pLog)
{
bool success = true;
const BoundingSphere unit;
ContainmentType c;
// Sphere-Point tests
{
const XMVECTORF32 pnts_in[6] =
{
{ 0.f, 0.f, 0.f, _Q_NAN },
{ 1.f, 0.f, 0.f, _Q_NAN },
{ 0.f, 1.f, 0.f, _Q_NAN },
{ 0.f, 0.f, 1.f, _Q_NAN },
{ 0.5f, 0.5f, 0.5f, _Q_NAN },
{ -0.5f, -0.5f, -0.5f, _Q_NAN }
};
const XMVECTORF32 pnts_out[6] =
{
{ 1.f, 1.f, 1.f, _Q_NAN },
{ 1.1f, 0.f, 0.f, _Q_NAN },
{ 10.f, -10.f, -15.f, _Q_NAN },
{ 0, -1.1f, 0.f, _Q_NAN },
{ -20.f, -20.f, -20.f, _Q_NAN },
{ 1.f, 2.f, 3.f, _Q_NAN }
};
static_assert( sizeof(pnts_in) == sizeof(pnts_out), "TestS03 Sphere-point tests" );
for( uint32_t i=0; i < (sizeof(pnts_in)/sizeof(XMVECTORF32)); ++i)
{
if ( (c=unit.Contains( pnts_in[i].v )) != CONTAINS )
{
printe("%s: Point-Sphere test failed (ins %d)\n",TestName, i);
printsh(unit);
printxmv( pnts_in[i].v );
printct( c );
success = false;
}
if ( (c=unit.Contains( pnts_out[i].v )) != DISJOINT )
{
printe("%s: Point-Sphere test failed (outs %d)\n",TestName, i);
printsh(unit);
printxmv( pnts_out[i].v );
printct( c );
success = false;
}
}
static const float test[][3] = { { 2.f, 0, 0 }, { -2.f, 0, 0 }, { 0, 2.f, 0 }, { 0, -2.f, 0 }, { 0, 0, 2.f }, { 0, 0, -2.f },
{ -2.0f, 2.0f, 2.0f }, { 0.0f, 2.0f, 2.0f }, { 2.0f, 2.0f, 2.0f }, { -2.0f, 0.0f, 2.0f },
{ 0.0f, 0.0f, 2.0f }, { 2.0f, 0.0f, 2.0f }, { -2.0f,-2.0f, 2.0f }, { 0.0f,-2.0f, 2.0f },
{ 2.0f,-2.0f, 2.0f }, { -2.0f, 2.0f, 0.0f }, { 0.0f, 2.0f, 0.0f }, { 2.0f, 2.0f, 0.0f },
{ -2.0f, 0.0f, 0.0f }, { 2.0f, 0.0f, 0.0f }, { -2.0f,-2.0f, 0.0f }, { 0.0f,-2.0f, 0.0f },
{ 2.0f,-2.0f, 0.0f }, { -2.0f, 2.0f,-2.0f }, { 0.0f, 2.0f,-2.0f }, { 2.0f, 2.0f,-2.0f },
{ -2.0f, 0.0f,-2.0f }, { 0.0f, 0.0f,-2.0f }, { 2.0f, 0.0f,-2.0f }, { -2.0f,-2.0f,-2.0f },
{ 0.0f,-2.0f,-2.0f }, { 2.0f,-2.0f,-2.0f } };
for( size_t i=0; i < sizeof(test)/(sizeof(float)*3); ++i )
{
XMVECTOR point = XMVectorSet(test[i][0], test[i][1], test[i][2], 0);
ContainmentType ct = unit.Contains( point );
if ( ct != DISJOINT )
{
printe( "%s: Failed Point-sphere test1 %zu\n",TestName, i );
printsh( unit );
printxmv( point );
printct( ct );
success = false;
}
}
static const float test2[][3] = { { .5f, 0, 0 }, { -.5f, 0, 0 }, { 0, .5f, 0 }, { 0, -.5f, 0 }, { 0, 0, .5f }, { 0, 0, -.5f },
{ -0.5f, 0.5f, 0.5f }, { 0.0f, 0.5f, 0.5f }, { 0.5f, 0.5f, 0.5f }, { -0.5f, 0.0f, 0.5f },
{ 0.0f, 0.0f, 0.5f }, { 0.5f, 0.0f, 0.5f }, { -0.5f,-0.5f, 0.5f }, { 0.0f,-0.5f, 0.5f },
{ 0.5f,-0.5f, 0.5f }, { -0.5f, 0.5f, 0.0f }, { 0.0f, 0.5f, 0.0f }, { 0.5f, 0.5f, 0.0f },
{ -0.5f, 0.0f, 0.0f }, { 0.5f, 0.0f, 0.0f }, { -0.5f,-0.5f, 0.0f }, { 0.0f,-0.5f, 0.0f },
{ 0.5f,-0.5f, 0.0f }, { -0.5f, 0.5f,-0.5f }, { 0.0f, 0.5f,-0.5f }, { 0.5f, 0.5f,-0.5f },
{ -0.5f, 0.0f,-0.5f }, { 0.0f, 0.0f,-0.5f }, { 0.5f, 0.0f,-0.5f }, { -0.5f,-0.5f,-0.5f },
{ 0.0f,-0.5f,-0.5f }, { 0.5f,-0.5f,-0.5f } };
for( size_t i=0; i < sizeof(test2)/(sizeof(float)*3); ++i )
{
XMVECTOR point = XMVectorSet(test2[i][0], test2[i][1], test2[i][2], 0);
ContainmentType ct = unit.Contains( point );
if ( ct != CONTAINS )
{
printe( "%s: Failed Point-sphere test2 %zu\n",TestName, i );
printsh( unit );
printxmv( point );
printct( ct );
success = false;
}
}
}
// Triangle-sphere tests
{
const XMVECTORF32 tri_CONTAINS[3] =
{
{ 0.2f, 0.2f, 0.2f, 0.f },
{ 0.5f, 0.f, 0.5f, 0.f },
{ 0.f, 0.f, 0.f, 0.f }
};
const XMVECTORF32 tri_INTERSECTS[3] =
{
{ 0.5f, 0.5f, 0.5f, 0.f },
{ 1.0f, 0.f, 1.f, 0.f },
{ 0.f, 0.f, 0.f, 0.f }
};
const XMVECTORF32 tri_DISJOINT[3] =
{
{ 10.f, 10.f, 10.f, 0.f },
{ 2.0f, 0.f, 2.f, 0.f },
{ 5.f, 5.f, 5.f, 0.f }
};
static_assert( (sizeof(tri_CONTAINS) == sizeof(tri_INTERSECTS)) && (sizeof(tri_CONTAINS) == sizeof(tri_DISJOINT)), "TestS03 Tri-sphere test" );
for( uint32_t i=0; i < (sizeof(tri_CONTAINS)/sizeof(XMVECTORF32)); i += 3 )
{
XMVECTOR t0 = tri_CONTAINS[i].v;
XMVECTOR t1 = tri_CONTAINS[i+1].v;
XMVECTOR t2 = tri_CONTAINS[i+2].v;
c = unit.Contains(t0, t1, t2);
if ( c != CONTAINS )
{
printe("%s: Triangle-Sphere test failed (CONTAINS %d)\n",TestName, i);
printct( c );
printsh(unit);
printxmv( t0 );
printxmv( t1 );
printxmv( t2 );
success = false;
}
t0 = tri_INTERSECTS[i].v;
t1 = tri_INTERSECTS[i+1].v;
t2 = tri_INTERSECTS[i+2].v;
c = unit.Contains(t0, t1, t2);
if ( c != INTERSECTS )
{
printe("%s: Triangle-Sphere test failed (INTERSECTS %d)\n",TestName, i);
printct( c );
printsh(unit);
printxmv( t0 );
printxmv( t1 );
printxmv( t2 );
success = false;
}
t0 = tri_DISJOINT[i].v;
t1 = tri_DISJOINT[i+1].v;
t2 = tri_DISJOINT[i+2].v;
c = unit.Contains(t0, t1, t2);
if ( c != DISJOINT )
{
printe("%s: Triangle-Sphere test failed (DISJOINT %d)\n",TestName, i);
printct( c );
printsh(unit);
printxmv( t0 );
printxmv( t1 );
printxmv( t2 );
success = false;
}
}
}
// Sphere-Sphere tests
{
if ( (c=unit.Contains(unit)) != CONTAINS )
{
printe("%s: Sphere-Sphere unit test failed\n",TestName);
printsh(unit);
printct(c);
success = false;
}
const BoundingSphere _small( XMFLOAT3(0.1f, 0.0f, 0.0f), 0.5f );
if ( (c=unit.Contains(_small)) != CONTAINS )
{
printe("%s: Sphere-Sphere small test failed\n",TestName );
printsh(unit);
printsh(_small);
printct( c );
success = false;
}
const BoundingSphere big( XMFLOAT3(1.f, 2.f, 3.f), 10.0f );
if ( (c=unit.Contains(big)) != INTERSECTS )
{
printe("%s: Sphere-Sphere big test failed\n",TestName );
printsh(unit);
printsh(big);
printct( c );
success = false;
}
const BoundingSphere _far( XMFLOAT3(10.f, -5.f, 4.f), 2.f );
if ( (c=unit.Contains(_far)) != DISJOINT )
{
printe("%s: Sphere-sphere far test failed\n",TestName );
printsh(unit);
printsh(_far);
printct( c );
success = false;
}
static const float test[][3] = { { 1.f, 0, 0 }, { -1.f, 0, 0 }, { 0, 1.f, 0 }, { 0, -1.f, 0 }, { 0, 0, 1.f }, { 0, 0, -1.f },
{ -1.f, 1.f, 1.f }, { 0.0f, 1.f, 1.f }, { 1.f, 1.f, 1.f }, { -1.f, 0.0f, 1.f },
{ 0.0f, 0.0f, 1.f }, { 1.f, 0.0f, 1.f }, { -1.f,-1.f, 1.f }, { 0.0f,-1.f, 1.f },
{ 1.f,-1.f, 1.f }, { -1.f, 1.f, 0.0f }, { 0.0f, 1.f, 0.0f }, { 1.f, 1.f, 0.0f },
{ -1.f, 0.0f, 0.0f }, { 1.f, 0.0f, 0.0f }, { -1.f,-1.f, 0.0f }, { 0.0f,-1.f, 0.0f },
{ 1.f,-1.f, 0.0f }, { -1.f, 1.f,-1.f }, { 0.0f, 1.f,-1.f }, { 1.f, 1.f,-1.f },
{ -1.f, 0.0f,-1.f }, { 0.0f, 0.0f,-1.f }, { 1.f, 0.0f,-1.f }, { -1.f,-1.f,-1.f },
{ 0.0f,-1.f,-1.f }, { 1.f,-1.f,-1.f } };
for( size_t i=0; i < sizeof(test)/(sizeof(float)*3); ++i )
{
XMVECTOR v = XMVector3Normalize( XMVectorSet( test[i][0], test[i][1], test[i][2], 0 ) );
v = XMVectorMultiply( v, XMVectorReplicate( 2.5f ) );
XMFLOAT3 center;
XMStoreFloat3( ¢er, v );
const BoundingSphere sph( center, 1.f );
ContainmentType ct = unit.Contains( sph );
if ( ct != DISJOINT )
{
printe( "%s: Failed sphere-sphere test1 %zu\n",TestName, i );
printsh( unit );
printsh( sph );
printct( ct );
success = false;
}
}
static const float test2[][3] = { { .5f, 0, 0 }, { -.5f, 0, 0 }, { 0, .5f, 0 }, { 0, -.5f, 0 }, { 0, 0, .5f }, { 0, 0, -.5f },
{ -0.5f, 0.5f, 0.5f }, { 0.0f, 0.5f, 0.5f }, { 0.5f, 0.5f, 0.5f }, { -0.5f, 0.0f, 0.5f },
{ 0.0f, 0.0f, 0.5f }, { 0.5f, 0.0f, 0.5f }, { -0.5f,-0.5f, 0.5f }, { 0.0f,-0.5f, 0.5f },
{ 0.5f,-0.5f, 0.5f }, { -0.5f, 0.5f, 0.0f }, { 0.0f, 0.5f, 0.0f }, { 0.5f, 0.5f, 0.0f },
{ -0.5f, 0.0f, 0.0f }, { 0.5f, 0.0f, 0.0f }, { -0.5f,-0.5f, 0.0f }, { 0.0f,-0.5f, 0.0f },
{ 0.5f,-0.5f, 0.0f }, { -0.5f, 0.5f,-0.5f }, { 0.0f, 0.5f,-0.5f }, { 0.5f, 0.5f,-0.5f },
{ -0.5f, 0.0f,-0.5f }, { 0.0f, 0.0f,-0.5f }, { 0.5f, 0.0f,-0.5f }, { -0.5f,-0.5f,-0.5f },
{ 0.0f,-0.5f,-0.5f }, { 0.5f,-0.5f,-0.5f } };
for( size_t i=0; i < sizeof(test2)/(sizeof(float)*3); ++i )
{
const XMFLOAT3 center(test2[i][0], test2[i][1], test2[i][2]);
const BoundingSphere sph( center, 1.f );
ContainmentType ct = unit.Contains( sph );
if ( ct != INTERSECTS )
{
printe( "%s: Failed sphere-sphere test2 %zu\n",TestName, i );
printsh( unit );
printsh( sph );
printct( ct );
success = false;
}
}
}
// Sphere-Axis-aligned Box tests
{
static const float test[][3] = { { 2.f, 0, 0 }, { -2.f, 0, 0 }, { 0, 2.f, 0 }, { 0, -2.f, 0 }, { 0, 0, 2.f }, { 0, 0, -2.f },
{ -2.0f, 2.0f, 2.0f }, { 0.0f, 2.0f, 2.0f }, { 2.0f, 2.0f, 2.0f }, { -2.0f, 0.0f, 2.0f },
{ 0.0f, 0.0f, 2.0f }, { 2.0f, 0.0f, 2.0f }, { -2.0f,-2.0f, 2.0f }, { 0.0f,-2.0f, 2.0f },
{ 2.0f,-2.0f, 2.0f }, { -2.0f, 2.0f, 0.0f }, { 0.0f, 2.0f, 0.0f }, { 2.0f, 2.0f, 0.0f },
{ -2.0f, 0.0f, 0.0f }, { 2.0f, 0.0f, 0.0f }, { -2.0f,-2.0f, 0.0f }, { 0.0f,-2.0f, 0.0f },
{ 2.0f,-2.0f, 0.0f }, { -2.0f, 2.0f,-2.0f }, { 0.0f, 2.0f,-2.0f }, { 2.0f, 2.0f,-2.0f },
{ -2.0f, 0.0f,-2.0f }, { 0.0f, 0.0f,-2.0f }, { 2.0f, 0.0f,-2.0f }, { -2.0f,-2.0f,-2.0f },
{ 0.0f,-2.0f,-2.0f }, { 2.0f,-2.0f,-2.0f } };
for( size_t i=0; i < sizeof(test)/(sizeof(float)*3); ++i )
{
const XMFLOAT3 center(test[i][0], test[i][1], test[i][2]);
const BoundingBox box( center, XMFLOAT3( 0.5f, 0.5f, 0.5f ) );
ContainmentType ct = unit.Contains( box );
if ( ct != DISJOINT )
{
printe( "%s: Failed sphere-box axis-based test1 %zu\n",TestName, i );
printsh( unit );
printbb( box );
printct( ct );
success = false;
}
}
static const float test2[][3] = { { .5f, 0, 0 }, { -.5f, 0, 0 }, { 0, .5f, 0 }, { 0, -.5f, 0 }, { 0, 0, .5f }, { 0, 0, -.5f },
{ -0.5f, 0.5f, 0.5f }, { 0.0f, 0.5f, 0.5f }, { 0.5f, 0.5f, 0.5f }, { -0.5f, 0.0f, 0.5f },
{ 0.0f, 0.0f, 0.5f }, { 0.5f, 0.0f, 0.5f }, { -0.5f,-0.5f, 0.5f }, { 0.0f,-0.5f, 0.5f },
{ 0.5f,-0.5f, 0.5f }, { -0.5f, 0.5f, 0.0f }, { 0.0f, 0.5f, 0.0f }, { 0.5f, 0.5f, 0.0f },
{ -0.5f, 0.0f, 0.0f }, { 0.5f, 0.0f, 0.0f }, { -0.5f,-0.5f, 0.0f }, { 0.0f,-0.5f, 0.0f },
{ 0.5f,-0.5f, 0.0f }, { -0.5f, 0.5f,-0.5f }, { 0.0f, 0.5f,-0.5f }, { 0.5f, 0.5f,-0.5f },
{ -0.5f, 0.0f,-0.5f }, { 0.0f, 0.0f,-0.5f }, { 0.5f, 0.0f,-0.5f }, { -0.5f,-0.5f,-0.5f },
{ 0.0f,-0.5f,-0.5f }, { 0.5f,-0.5f,-0.5f } };
for( size_t i=0; i < sizeof(test2)/(sizeof(float)*3); ++i )
{
const XMFLOAT3 center(test2[i][0], test2[i][1], test2[i][2]);
const BoundingBox box( center, XMFLOAT3( 1.f, 1.f, 1.f ) );
ContainmentType ct = unit.Contains( box );
if ( ct != INTERSECTS )
{
printe( "%s: Failed sphere-box axis-based test2 %zu\n",TestName, i );
printsh( unit );
printbb( box );
printct( ct );
success = false;
}
}
{
const BoundingSphere sph( XMFLOAT3( 0.1f, 0.1f, 0.1f ), 1.f );
const BoundingBox box( XMFLOAT3( 0.5f, 0.5f, 0.5f ), XMFLOAT3( 0.5f, 0.5f, 0.5f ) );
ContainmentType ct = sph.Contains( box );
if ( ct != INTERSECTS )
{
printe( "%s: Failed sphere-box axis-based test3\n",TestName );
printsh( sph );
printbb( box );
printct( ct );
success = false;
}
}
{
const BoundingBox box( XMFLOAT3(0,0,0), XMFLOAT3( 2.f, 2.f, 2.f ) );
ContainmentType ct = unit.Contains( box );
if ( ct != INTERSECTS )
{
printe( "%s: Failed sphere-box axis-based test4\n",TestName );
printsh( unit );
printbb( box );
printct( ct );
success = false;
}
}
{
const BoundingSphere sph( XMFLOAT3(0,0,0), 2.f );
const BoundingBox box( XMFLOAT3(0,0,0), XMFLOAT3( 0.5f, 0.5f, 0.5f ) );
ContainmentType ct = sph.Contains( box );
if ( ct != CONTAINS )
{
printe( "%s: Failed sphere-box axis-based test5\n",TestName );
printsh( sph );
printbb( box );
printct( ct );
success = false;
}
}
static const float test3[][3] = { { 1.f, 1.f, 1.f }, { 1.f, 1.f, -1.f }, { 1.f, -1.f, 1.f }, { 1.f, -1.f, -1.f },
{ -1.f, 1.f, 1.f }, { -1.f, 1.f, -1.f }, { -1.f, -1.f, 1.f }, { -1.f, -1.f, -1.f } };
for( size_t i=0; i < sizeof(test3)/(sizeof(float)*3); ++i )
{
const XMFLOAT3 center(test3[i][0], test3[i][1], test3[i][2]);
const BoundingBox box( center, XMFLOAT3( 0.5f, 0.5f, 0.5f ) );
ContainmentType ct = unit.Contains( box );
if ( ct != INTERSECTS )
{
printe( "%s: Failed sphere-box axis-based test6 %zu\n",TestName, i );
printsh( unit );
printbb( box );
printct( ct );
success = false;
}
}
}
// Sphere-Oriented Box tests
{
static const float test[][3] = { { 2.f, 0, 0 }, { -2.f, 0, 0 }, { 0, 2.f, 0 }, { 0, -2.f, 0 }, { 0, 0, 2.f }, { 0, 0, -2.f },
{ -2.0f, 2.0f, 2.0f }, { 0.0f, 2.0f, 2.0f }, { 2.0f, 2.0f, 2.0f }, { -2.0f, 0.0f, 2.0f },
{ 0.0f, 0.0f, 2.0f }, { 2.0f, 0.0f, 2.0f }, { -2.0f,-2.0f, 2.0f }, { 0.0f,-2.0f, 2.0f },
{ 2.0f,-2.0f, 2.0f }, { -2.0f, 2.0f, 0.0f }, { 0.0f, 2.0f, 0.0f }, { 2.0f, 2.0f, 0.0f },
{ -2.0f, 0.0f, 0.0f }, { 2.0f, 0.0f, 0.0f }, { -2.0f,-2.0f, 0.0f }, { 0.0f,-2.0f, 0.0f },
{ 2.0f,-2.0f, 0.0f }, { -2.0f, 2.0f,-2.0f }, { 0.0f, 2.0f,-2.0f }, { 2.0f, 2.0f,-2.0f },
{ -2.0f, 0.0f,-2.0f }, { 0.0f, 0.0f,-2.0f }, { 2.0f, 0.0f,-2.0f }, { -2.0f,-2.0f,-2.0f },
{ 0.0f,-2.0f,-2.0f }, { 2.0f,-2.0f,-2.0f } };
for( size_t i=0; i < sizeof(test)/(sizeof(float)*3); ++i )
{
const XMFLOAT3 center(test[i][0], test[i][1], test[i][2]);
const BoundingOrientedBox box( center, XMFLOAT3( 0.5f, 0.5f, 0.5f ), XMFLOAT4(0.461940f, 0.191342f, 0.191342f, 0.844623f) );
ContainmentType ct = unit.Contains( box );
if ( ct != DISJOINT )
{
printe( "%s: Failed sphere-oobox axis-based test1 %zu\n",TestName, i );
printsh( unit );
printobb( box );
printct( ct );
success = false;
}
}
static const float test2[][3] = { { .5f, 0, 0 }, { -.5f, 0, 0 }, { 0, .5f, 0 }, { 0, -.5f, 0 }, { 0, 0, .5f }, { 0, 0, -.5f },
{ -0.5f, 0.5f, 0.5f }, { 0.0f, 0.5f, 0.5f }, { 0.5f, 0.5f, 0.5f }, { -0.5f, 0.0f, 0.5f },
{ 0.0f, 0.0f, 0.5f }, { 0.5f, 0.0f, 0.5f }, { -0.5f,-0.5f, 0.5f }, { 0.0f,-0.5f, 0.5f },
{ 0.5f,-0.5f, 0.5f }, { -0.5f, 0.5f, 0.0f }, { 0.0f, 0.5f, 0.0f }, { 0.5f, 0.5f, 0.0f },
{ -0.5f, 0.0f, 0.0f }, { 0.5f, 0.0f, 0.0f }, { -0.5f,-0.5f, 0.0f }, { 0.0f,-0.5f, 0.0f },
{ 0.5f,-0.5f, 0.0f }, { -0.5f, 0.5f,-0.5f }, { 0.0f, 0.5f,-0.5f }, { 0.5f, 0.5f,-0.5f },
{ -0.5f, 0.0f,-0.5f }, { 0.0f, 0.0f,-0.5f }, { 0.5f, 0.0f,-0.5f }, { -0.5f,-0.5f,-0.5f },
{ 0.0f,-0.5f,-0.5f }, { 0.5f,-0.5f,-0.5f } };
for( size_t i=0; i < sizeof(test2)/(sizeof(float)*3); ++i )
{
const XMFLOAT3 center(test2[i][0], test2[i][1], test2[i][2]);
const BoundingOrientedBox box( center, XMFLOAT3( 0.5f, 0.5f, 0.5f ), XMFLOAT4(0.461940f, 0.191342f, 0.191342f, 0.844623f) );
ContainmentType ct = unit.Contains( box );
if ( ct != INTERSECTS )
{
printe( "%s: Failed sphere-obox axis-based test2 %zu\n",TestName, i );
printsh( unit );
printobb( box );
printct( ct );
success = false;
}
}
{
const BoundingSphere sph( XMFLOAT3( 0.1f, 0.1f, 0.1f ), 1.f );
const BoundingOrientedBox box ( XMFLOAT3(0.f, 0.f, 0.f), XMFLOAT3(1.f, 1.f, 1.f), XMFLOAT4(0.461940f, 0.191342f, 0.191342f, 0.844623f) );
ContainmentType ct = sph.Contains( box );
if ( ct != INTERSECTS )
{
printe( "%s: Failed sphere-oobox axis-based test3\n",TestName );
printsh( sph );
printobb( box );
printct( ct );
success = false;
}
}
{
const BoundingOrientedBox box ( XMFLOAT3(0.f, 0.f, 0.f), XMFLOAT3(1.f, 1.f, 1.f), XMFLOAT4(0.461940f, 0.191342f, 0.191342f, 0.844623f) );
ContainmentType ct = unit.Contains( box );
if ( ct != INTERSECTS )
{
printe( "%s: Failed sphere-oobox axis-based test4\n",TestName );
printsh( unit );
printobb( box );
printct( ct );
success = false;
}
}
{
const BoundingSphere sph( XMFLOAT3(0,0,0), 2.f );
const BoundingOrientedBox box ( XMFLOAT3(0.f, 0.f, 0.f), XMFLOAT3(1.f, 1.f, 1.f), XMFLOAT4(0.461940f, 0.191342f, 0.191342f, 0.844623f) );
ContainmentType ct = sph.Contains( box );
if ( ct != CONTAINS )
{
printe( "%s: Failed sphere-oobox axis-based test5\n",TestName );
printsh( sph );
printobb( box );
printct( ct );
success = false;
}
}
static const float test3[][3] = { { 1.f, 1.f, 1.f }, { 1.f, 1.f, -1.f }, { 1.f, -1.f, 1.f }, { 1.f, -1.f, -1.f },
{ -1.f, 1.f, 1.f }, { -1.f, 1.f, -1.f }, { -1.f, -1.f, 1.f }, { -1.f, -1.f, -1.f } };
for( size_t i=0; i < sizeof(test3)/(sizeof(float)*3); ++i )
{
const XMFLOAT3 center(test3[i][0], test3[i][1], test3[i][2]);
const BoundingOrientedBox box( center, XMFLOAT3( 0.4f, 0.4f, 0.4f ), XMFLOAT4(0.461940f, 0.191342f, 0.191342f, 0.844623f) );
ContainmentType ct = unit.Contains( box );
if ( ct != DISJOINT )
{
printe( "%s: Failed sphere-oobox axis-based test6 %zu\n",TestName, i );
printsh( unit );
printobb( box );
printct( ct );
success = false;
}
}
}
// Sphere-Frustum tests
{
static const float test[][3] = { { 2.f, 0, 0 }, { -2.f, 0, 0 }, { 0, 2.f, 0 }, { 0, -2.f, 0 }, { 0, 0, -2.f },
{ -2.0f, 2.0f, 0.0f }, { 0.0f, 2.0f, 0.0f }, { 2.0f, 2.0f, 0.0f },
{ -2.0f, 0.0f, 0.0f }, { 2.0f, 0.0f, 0.0f }, { -2.0f,-2.0f, 0.0f }, { 0.0f,-2.0f, 0.0f },
{ 2.0f,-2.0f, 0.0f }, { -2.0f, 2.0f,-2.0f }, { 0.0f, 2.0f,-2.0f }, { 2.0f, 2.0f,-2.0f },
{ -2.0f, 0.0f,-2.0f }, { 0.0f, 0.0f,-2.0f }, { 2.0f, 0.0f,-2.0f }, { -2.0f,-2.0f,-2.0f },
{ 0.0f,-2.0f,-2.0f }, { 2.0f,-2.0f,-2.0f } };
for( size_t i=0; i < sizeof(test)/(sizeof(float)*3); ++i )
{
const XMFLOAT3 center(test[i][0], test[i][1], test[i][2]);
BoundingFrustum fr( center, XMFLOAT4(0.f, 0.f, 0.f, 1.f), 2.f, -2.f, 2.f, -2.f, 1.f, 2.f );
ContainmentType ct = unit.Contains( fr );
if ( ct != INTERSECTS )
{
printe( "%s: Failed sphere-frustum test1 %zu\n",TestName, i );
printsh( unit );
printfr( fr );
printct( ct );
success = false;
}
}
static const float test2[][3] = { { 0, 0, 2.f }, { -2.0f, 2.0f, 2.0f }, { 0.0f, 2.0f, 2.0f }, { 2.0f, 2.0f, 2.0f },
{ -2.0f, 0.0f, 2.0f }, { 2.0f, 0.0f, 2.0f }, { -2.0f,-2.0f, 2.0f }, { 0.0f,-2.0f, 2.0f }, { 2.0f,-2.0f, 2.0f } };
for( size_t i=0; i < sizeof(test2)/(sizeof(float)*3); ++i )
{
const XMFLOAT3 center(test2[i][0], test2[i][1], test2[i][2]);
BoundingFrustum fr( center, XMFLOAT4(0.f, 0.f, 0.f, 1.f), 2.f, -2.f, 2.f, -2.f, 1.f, 2.f );
ContainmentType ct = unit.Contains( fr );
if ( ct != DISJOINT )
{
printe( "%s: Failed sphere-frustum test2 %zu\n",TestName, i );
printsh( unit );
printfr( fr );
printct( ct );
success = false;
}
}
}
return ( success ) ? S_OK : MATH_FAIL;
}
//-------------------------------------------------------------------------------------
// Sphere::Intersects
HRESULT TestS04(LogProxy* pLog)
{
bool success = true;
const BoundingSphere unit;
// Sphere-Sphere
{
if ( !unit.Intersects(unit) )
{
printe("%s: Sphere-Sphere unit test failed\n",TestName);
printsh(unit);
success = false;
}
const BoundingSphere _small( XMFLOAT3(0.1f, 0.0f, 0.0f), 0.5f );
if ( !unit.Intersects(_small) )
{
printe("%s: Sphere-Sphere small test failed\n",TestName);
printsh(unit);
printsh(_small);
success = false;
}
const BoundingSphere big( XMFLOAT3(1.f, 2.f, 3.f), 10.0f );
if ( !unit.Intersects(big) )
{
printe("%s: Sphere-Sphere big test failed\n",TestName);
printsh(unit);
printsh(big);
success = false;
}
const BoundingSphere _far( XMFLOAT3(10.f, -5.f, 4.f), 2.f );
if ( unit.Intersects(_far) )
{
printe("%s: Sphere-sphere far test failed\n",TestName);
printsh(unit);
printsh(_far);
success = false;
}
static const float test[][3] = { { 2.f, 0, 0 }, { -2.f, 0, 0 }, { 0, 2.f, 0 }, { 0, -2.f, 0 }, { 0, 0, 2.f }, { 0, 0, -2.f } };
for( size_t i=0; i < sizeof(test)/(sizeof(float)*3); ++i )
{
const BoundingSphere t( XMFLOAT3(test[i][0], test[i][1], test[i][2]), 1.f );
// Just-touching should intersect
if ( !unit.Intersects( t ) )
{
printe( "%s: Failed Sphere-Sphere axis-based test1A\n",TestName );
printsh( unit );
printsh( t );
success = false;
}
// Just missing should be disjoint
const BoundingSphere t2( XMFLOAT3(test[i][0], test[i][1], test[i][2]), 1.f - EPSILON );
if ( unit.Intersects( t2 ) )
{
printe( "%s: Failed Sphere-Sphere axis-based test1B\n",TestName );
printsh( unit );
printsh( t2 );
success = false;
}
}
static const float test2[][3] = { { .5f, 0, 0 }, { -.5f, 0, 0 }, { 0, .5f, 0 }, { 0, -.5f, 0 }, { 0, 0, .5f }, { 0, 0, -.5f } };
for( size_t i=0; i < sizeof(test2)/(sizeof(float)*3); ++i )
{
const BoundingSphere t( XMFLOAT3(test2[i][0], test2[i][1], test2[i][2]), 1.f );
if ( !unit.Intersects( t ) )
{
printe( "%s: Failed Sphere-Sphere axis-based test2\n",TestName );
printsh( unit );
printsh( t );
success = false;
}
}
}
// Box-sphere
{
const BoundingBox ubox;
if ( !unit.Intersects(ubox) )
{
printe("%s: Sphere-Box unit test failed\n",TestName);
printsh(unit);
printbb(ubox);
success = false;
}
const BoundingSphere _small( XMFLOAT3(0.1f, 0.0f, 0.0f), 0.5f );
if ( !_small.Intersects(ubox) )
{
printe("%s: Sphere-Box small test failed\n",TestName);
printsh(_small);
printbb(ubox);
success = false;
}
const BoundingSphere big( XMFLOAT3(1.f, 2.f, 3.f), 10.0f );
if ( !big.Intersects(ubox) )
{
printe("%s: Sphere-Box big test failed\n",TestName);
printsh(big);
printbb(ubox);
success = false;
}
const BoundingSphere _far( XMFLOAT3(10.f, -5.f, 4.f), 2.f );
if ( _far.Intersects(ubox) )
{
printe("%s: Sphere-Box far test failed\n",TestName);
printsh(_far);
printbb(ubox);
success = false;
}
static const float test[][3] = { { 2.f, 0, 0 }, { -2.f, 0, 0 }, { 0, 2.f, 0 }, { 0, -2.f, 0 }, { 0, 0, 2.f }, { 0, 0, -2.f } };
for( size_t i=0; i < sizeof(test)/(sizeof(float)*3); ++i )
{
const BoundingSphere t( XMFLOAT3(test[i][0], test[i][1], test[i][2]), 1.f );
// Just-touching should intersect
if ( !t.Intersects( ubox ) )
{
printe( "%s: Failed Sphere-Box axis-based test1A\n",TestName );
printsh( t );
printbb(ubox);
success = false;
}
// Just missing should be disjoint
const BoundingSphere t2( XMFLOAT3(test[i][0], test[i][1], test[i][2]), 1.f - EPSILON );
if ( t2.Intersects( ubox ) )
{
printe( "%s: Failed Sphere-Box axis-based test1B\n",TestName );
printsh( t2 );
printbb(ubox);
success = false;
}
}
static const float test2[][3] = { { .5f, 0, 0 }, { -.5f, 0, 0 }, { 0, .5f, 0 }, { 0, -.5f, 0 }, { 0, 0, .5f }, { 0, 0, -.5f } };
for( size_t i=0; i < sizeof(test2)/(sizeof(float)*3); ++i )
{
const BoundingSphere t( XMFLOAT3(test2[i][0], test2[i][1], test2[i][2]), 1.f );
if ( !t.Intersects( ubox ) )
{
printe( "%s: Failed Sphere-Box axis-based test2\n",TestName );
printsh( t );
printbb(ubox);
success = false;
}
}
}
// BoundingSphere::Intersects( const BoundingOrientedBox& box ) is covered by obox.cpp
// BoundingSphere::Intersects( const BoundingFrustum& fr ) is covered by frustum.cpp
// Triangle-Sphere
{
const XMVECTORF32 tri_in[3] =
{
{ 0.5f, 0.5f, 0.5f, 0.f },
{ 1.0f, 0.f, 1.f, 0.f },
{ 0.f, 0.f, 0.f, 0.f }
};
const XMVECTORF32 tri_out[3] =
{
{ 10.f, 10.f, 10.f, 0.f },
{ 2.0f, 0.f, 2.f, 0.f },
{ 5.f, 5.f, 5.f, 0.f }
};
static_assert( sizeof(tri_in) == sizeof(tri_out), "TestS04 Tri-Sphere test" );
for( uint32_t i=0; i < (sizeof(tri_in)/sizeof(XMVECTORF32)); i += 3 )
{
XMVECTOR t0 = tri_in[i].v;
XMVECTOR t1 = tri_in[i+1].v;
XMVECTOR t2 = tri_in[i+2].v;
if ( !unit.Intersects(t0, t1, t2) )
{
printe("%s: Triangle-Sphere test failed (ins %d)\n",TestName, i);
printsh(unit);
printxmv( t0 );
printxmv( t1 );
printxmv( t2 );
success = false;
}
t0 = tri_out[i].v;
t1 = tri_out[i+1].v;
t2 = tri_out[i+2].v;
if ( unit.Intersects(t0, t1, t2) )
{
printe("%s: Triangle-Sphere test failed (outs %d)\n",TestName, i);
printsh(unit);
printxmv( t0 );
printxmv( t1 );
printxmv( t2 );
success = false;
}
}
}
// Plane-Sphere
{
const XMVECTORF32 planes[9] =
{
{ 0.f, 1.f, 0.f, 2.f },
{ 0.f, 1.f, 0.f, -2.f },
{ 0.f, 1.f, 0.f, 0.f },
{ 0.577350f, 0.577350f, 0.577350f, 2.f },
{ 0.577350f, 0.577350f, 0.577350f, -2.f },
{ 0.577350f, 0.577350f, 0.577350f, 0.f },
{ -0.577350f, -0.577350f, -0.577350f, 2.f },
{ -0.577350f, -0.577350f, -0.577350f, -2.f },
{ -0.577350f, -0.577350f, -0.577350f, 0.f },
};
PlaneIntersectionType result[9] =
{
FRONT,
BACK,
INTERSECTING,
FRONT,
BACK,
INTERSECTING,
FRONT,
BACK,
INTERSECTING,
};
static_assert( (sizeof(planes)/sizeof(XMVECTORF32)) == (sizeof(result)/sizeof(PlaneIntersectionType)), "TestS04 plane-sphere test" );
for( uint32_t i=0; i < (sizeof(planes)/sizeof(XMVECTORF32)); ++i )
{
PlaneIntersectionType p = unit.Intersects( planes[i] );
if ( p != result[i] )
{
printe("%s: Plane-Sphere test failed ([%d] result %d, expected %d)\n",TestName, i, p, result[i] );
printsh(unit);
printxmv( planes[i] );
success = false;
}
}
}
// Ray-Sphere
{
float dist;
const XMVECTORF32 rayA[2] = { { 0.1f, 0.1f, 0.1f, 0.f }, { 0.f, 0.f, 1.f, 0.f } };
if ( !unit.Intersects( rayA[0], rayA[1], dist ) || (fabs(dist - 0.889950f) > EPSILON) )
{
printe("%s: Sphere-Ray test A failed (dist=%f)\n",TestName, dist);
printsh(unit);
printxmv( rayA[0] );
printxmv( rayA[1] );
success = false;
}
const XMVECTORF32 rayB[2] = { { 10.f, 10.f, 10.f, 0.f }, { 0.f, 0.f, 1.f, 0.f } };
if ( unit.Intersects( rayB[0], rayB[1], dist ) ) // Should miss box
{
printe("%s: Sphere-Ray test B failed (dist=%f)\n",TestName, dist);
printsh(unit);
printxmv( rayB[0] );
printxmv( rayB[1] );
success = false;
}
const XMVECTORF32 rayC[2] = { { 10.f, 10.f, 10.f, 0.f }, { -0.577350f, -0.577350f, -0.577350f, 0.f } };
if ( !unit.Intersects( rayC[0], rayC[1], dist ) || (fabs(dist - 16.320623f) > EPSILON) )
{
printe("%s: Sphere-Ray test C failed (dist=%f)\n",TestName, dist);
printsh(unit);
printxmv( rayC[0] );
printxmv( rayC[1] );
success = false;
}
}
return ( success ) ? S_OK : MATH_FAIL;
}
//-------------------------------------------------------------------------------------
// Sphere::ContainedBy
HRESULT TestS05(LogProxy* pLog)
{
bool success = true;
const BoundingSphere unit;
{
static const float test[][3] = { { 2.f, 0, 0 }, { -2.f, 0, 0 }, { 0, 2.f, 0 }, { 0, -2.f, 0 }, { 0, 0, -2.f },
{ -2.0f, 2.0f, 0.0f }, { 0.0f, 2.0f, 0.0f }, { 2.0f, 2.0f, 0.0f },
{ -2.0f, 0.0f, 0.0f }, { 2.0f, 0.0f, 0.0f }, { -2.0f,-2.0f, 0.0f }, { 0.0f,-2.0f, 0.0f },
{ 2.0f,-2.0f, 0.0f }, { -2.0f, 2.0f,-2.0f }, { 0.0f, 2.0f,-2.0f }, { 2.0f, 2.0f,-2.0f },
{ -2.0f, 0.0f,-2.0f }, { 0.0f, 0.0f,-2.0f }, { 2.0f, 0.0f,-2.0f }, { -2.0f,-2.0f,-2.0f },
{ 0.0f,-2.0f,-2.0f }, { 2.0f,-2.0f,-2.0f } };
for( size_t i=0; i < sizeof(test)/(sizeof(float)*3); ++i )
{
const XMFLOAT3 center(test[i][0], test[i][1], test[i][2]);
BoundingFrustum fr( center, XMFLOAT4(0.f, 0.f, 0.f, 1.f), 2.f, -2.f, 2.f, -2.f, 1.f, 2.f );
XMVECTOR Plane0, Plane1, Plane2, Plane3, Plane4, Plane5;
fr.GetPlanes( &Plane0, &Plane1, &Plane2, &Plane3, &Plane4, &Plane5 );
ContainmentType ct = unit.ContainedBy( Plane0, Plane1, Plane2, Plane3, Plane4, Plane5 );
if ( ct != INTERSECTS )
{
printe( "%s: Failed sphere-6planes test1 %zu\n",TestName,i );
printsh( unit );
printxmv( Plane0 );
printxmv( Plane1 );
printxmv( Plane2 );
printxmv( Plane3 );
printxmv( Plane4 );
printxmv( Plane5 );
printct( ct );
success = false;
}
}
static const float test2[][3] = { { 0, 0, 2.f }, { -2.0f, 2.0f, 2.0f }, { 0.0f, 2.0f, 2.0f }, { 2.0f, 2.0f, 2.0f },
{ -2.0f, 0.0f, 2.0f }, { 2.0f, 0.0f, 2.0f }, { -2.0f,-2.0f, 2.0f }, { 0.0f,-2.0f, 2.0f }, { 2.0f,-2.0f, 2.0f } };
for( size_t i=0; i < sizeof(test2)/(sizeof(float)*3); ++i )
{
const XMFLOAT3 center(test2[i][0], test2[i][1], test2[i][2]);
BoundingFrustum fr( center, XMFLOAT4(0.f, 0.f, 0.f, 1.f), 2.f, -2.f, 2.f, -2.f, 1.f, 2.f );
XMVECTOR Plane0, Plane1, Plane2, Plane3, Plane4, Plane5;
fr.GetPlanes( &Plane0, &Plane1, &Plane2, &Plane3, &Plane4, &Plane5 );
ContainmentType ct = unit.ContainedBy( Plane0, Plane1, Plane2, Plane3, Plane4, Plane5 );
if ( ct != DISJOINT )
{
printe( "%s: Failed sphere-6planes test2 %zu\n",TestName,i );
printsh( unit );
printxmv( Plane0 );
printxmv( Plane1 );
printxmv( Plane2 );
printxmv( Plane3 );
printxmv( Plane4 );
printxmv( Plane5 );
printct( ct );
success = false;
}
}
}
return ( success ) ? S_OK : MATH_FAIL;
};
//-------------------------------------------------------------------------------------
// Sphere::CreateMerged
HRESULT TestS06(LogProxy* pLog)
{
bool success = true;
BoundingSphere sht;
const BoundingSphere unit;
BoundingSphere::CreateMerged( sht, unit, unit );
if ( !IsEqual(sht,unit) )
{
printe("%s: unit test failed\n",TestName);
printsh(unit);
printsh(sht);
success = false;
}
const BoundingSphere _small( XMFLOAT3(0.1f, 0.0f, 0.0f), 0.5f );
BoundingSphere::CreateMerged( sht, unit, _small );
if ( !IsEqual(unit,sht) )
{
printe("%s: small test failed\n",TestName);
printsh(unit);
printsh(_small);
printsh(sht);
success = false;
}
const BoundingSphere big( XMFLOAT3(1.f, 2.f, 3.f), 10.0f );
BoundingSphere::CreateMerged( sht, unit, big );
if ( !IsEqual(sht,big) )
{
printe("%s: big test failed\n",TestName);
printsh(unit);
printsh(big);
printsh(sht);
success = false;
}
const BoundingSphere _far( XMFLOAT3(10.f, -5.f, 4.f), 2.f );
BoundingSphere::CreateMerged( sht, _far, big );
const BoundingSphere result( XMFLOAT3(2.354666f, 0.946371f, 3.150518f), 11.722761f );
if ( !IsEqual(sht,result) )
{
printe("%s: _far-big test failed\n",TestName);
printsh(_far);
printsh(big);
printsh(result);
printsh(sht);
success = false;
}
{
const BoundingSphere sph2( XMFLOAT3( 2.f, 0, 0 ), 1.f );
BoundingSphere::CreateMerged( sht, unit, sph2 );
const BoundingSphere result2( XMFLOAT3( 1.f, 0, 0), 2.f );
if ( !IsEqual( sht, result2 ) )
{
printe( "%s: create merge test1 failed\n",TestName );
printsh( unit );
printsh( sph2 );
printsh( sht );
printsh( result2 );
success = false;
}
}
{
const BoundingSphere sph1( XMFLOAT3( 0, 0, 0), 5.f );
const BoundingSphere sph2( XMFLOAT3( 2.f, 0, 0 ), 1.f );
BoundingSphere::CreateMerged( sht, sph1, sph2 );
if ( !IsEqual( sht, sph1 ) )
{
printe( "%s: create merge test2 failed\n",TestName );
printsh( sph1 );
printsh( sph2 );
printsh( sht );
success = false;
}
}
{
const BoundingSphere sph2( XMFLOAT3( 2.f, 0, 0 ), 5.f );
BoundingSphere::CreateMerged( sht, unit, sph2 );
if ( !IsEqual( sht, sph2 ) )
{
printe( "%s: create merge test3 failed\n",TestName );
printsh( unit );
printsh( sph2 );
printsh( sht );
success = false;
}
}
{
const BoundingSphere sph2( XMFLOAT3( 0, 0, 0 ), 2.f );
BoundingSphere::CreateMerged( sht, unit, sph2 );
if ( !IsEqual( sht, sph2 ) )
{
printe( "%s: create merge test4 failed\n",TestName );
printsh( unit );
printsh( sph2 );
printsh( sht );
success = false;
}
}
return ( success ) ? S_OK : MATH_FAIL;
}
//------------------------------------------------------------------------------------
// Sphere::CreateFromBoundingBox
HRESULT TestS07(LogProxy* pLog)
{
bool success = true;
BoundingSphere sht;
// Axis-aligned bounding box
XMVECTOR testmin = XMVectorSet(1.f, 2.f, 3.f, 0);
XMVECTOR testmax = XMVectorSet(4.f, 5.f, 6.f, 0);
BoundingBox abox;
BoundingBox::CreateFromPoints( abox, testmin, testmax );
BoundingSphere::CreateFromBoundingBox( sht, abox );
BoundingSphere result;
XMVECTOR dist = XMVectorSubtract( testmax, testmin );
XMStoreFloat3( &result.Center, XMVectorAdd( testmin, XMVectorDivide( dist, XMVectorReplicate( 2.f ) ) ) );
result.Radius = XMVectorGetX( XMVector3Length( dist ) ) * 0.5f;
if ( !IsEqual(sht,result) )
{
printe("%s: aa box test failed\n",TestName);
printbb(abox);
printsh(result);
printsh(sht);
success = false;
}
// Oriented bounding box
BoundingOrientedBox obox( XMFLOAT3(1.f, 2.f, 3.f), XMFLOAT3(4.f, 5.f, 6.f), XMFLOAT4( 0.f, 0.f, 0.f, 1.f ) );
BoundingSphere::CreateFromBoundingBox( sht, obox );
const BoundingSphere result2( XMFLOAT3( 1.f, 2.f, 3.f), 8.774964f );
if ( !IsEqual(sht,result2) )
{
printe("%s: oriented box test failed\n",TestName);
printobb(obox);
printsh(result2);
printsh(sht);
success = false;
}
return ( success ) ? S_OK : MATH_FAIL;
}
//-------------------------------------------------------------------------------------
// Sphere::CreateFromPoints
HRESULT TestS08(LogProxy* pLog)
{
bool success = true;
{
const float points[] = { 0, 0, 0, 1.f, 0, 0 };
BoundingSphere sht;
BoundingSphere::CreateFromPoints( sht, 2, reinterpret_cast<const XMFLOAT3*>( points ), sizeof(XMFLOAT3) );
const BoundingSphere result( XMFLOAT3(0.5f, 0, 0), 0.5f );
if ( !IsEqual(sht,result) )
{
printe("%s: creating from points test1 failed\n",TestName);
printsh(sht);
printsh(result);
success = false;
}
}
{
const float points[] = { 0, 0, 0, 0.5f, 0, 1.0f };
BoundingSphere sht;
BoundingSphere::CreateFromPoints( sht, 2, reinterpret_cast<const XMFLOAT3*>( points ), sizeof(XMFLOAT3) );
const BoundingSphere result( XMFLOAT3(0.25f, 0, 0.5f), 0.559017f );
if ( !IsEqual(sht,result) )
{
printe("%s: creating from points test2 failed\n",TestName);
printsh(sht);
printsh(result);
success = false;
}
}
{
const float points[] = { 0, 0, 0, 0.0f, 0.5f, 1.0f };
BoundingSphere sht;
BoundingSphere::CreateFromPoints( sht, 2, reinterpret_cast<const XMFLOAT3*>( points ), sizeof(XMFLOAT3) );
const BoundingSphere result( XMFLOAT3(0, 0.25f, 0.5f), 0.559017f );
if ( !IsEqual(sht,result) )
{
printe("%s: creating from points test3 failed\n",TestName);
printsh(sht);
printsh(result);
success = false;
}
}
{
float irt2 = 1.f / sqrtf(2.f);
float irt3 = 1.f / sqrtf(3.f);
const float points[] = { 0, 1.f, 0,
0, -irt2, -irt2,
-irt3, -irt3, irt3,
irt3, -irt3, irt3 };
BoundingSphere sht;
BoundingSphere::CreateFromPoints( sht, 4, reinterpret_cast<const XMFLOAT3*>( points ), sizeof(XMFLOAT3) );
const BoundingSphere result( XMFLOAT3(-0.0621097758f, 0.01741325f, -0.187598482f), 1.16094756f );
if ( !IsEqual(sht,result) )
{
printe("%s: creating from points test4 failed\n",TestName);
printsh(sht);
printsh(result);
success = false;
}
// See that the bound above is tighter than a sphere created from a bounding box of the same points
BoundingBox box;
BoundingBox::CreateFromPoints( box, 4, reinterpret_cast<const XMFLOAT3*>( points ), sizeof(XMFLOAT3) );
BoundingSphere shv;
BoundingSphere::CreateFromBoundingBox( shv, box );
if ( sht.Radius > shv.Radius )
{
printe("%s: creating from points test4 failed, expected tighter bounds\n",TestName);
printsh(sht);
printsh(shv);
success = false;
}
}
{
XMFLOAT3 points[32];
const uint32_t count = sizeof(points)/sizeof(XMFLOAT3);
for( uint32_t i=0; i < count; ++i )
{
XMStoreFloat3( &points[i], GetRandomVector16() );
}
BoundingSphere sht;
BoundingSphere::CreateFromPoints( sht, count, points, sizeof(XMFLOAT3) );
// Expand a bit to ensure Contains works for all input points on all platforms
sht.Radius += EPSILON;
for( uint32_t i=0; i < count; ++i )
{
XMVECTOR p = XMLoadFloat3( &points[i] );
ContainmentType ct = sht.Contains(p);
if ( ct != CONTAINS )
{
printe("%s: Sphere-Point verification test failed - %f %f %f (%d)\n",TestName,
points[i].x, points[i].y, points[i].z, i);
printsh(sht);
printct(ct);
success = false;
}
}
}
return ( success ) ? S_OK : MATH_FAIL;
}
//-------------------------------------------------------------------------------------
// Sphere::CreateFromFrustum
HRESULT TestS09(LogProxy* pLog)
{
bool success = true;
const BoundingFrustum fr( XMFLOAT3(1.f, 1.f, 1.f), XMFLOAT4(0.f, 0.f, 0.f, 1.f), 2.f, -2.f, 2.f, -2.f, 1.f, 2.f );
BoundingSphere sht;
BoundingSphere::CreateFromFrustum( sht, fr );
const BoundingSphere result( XMFLOAT3(1.f, 1.f, 3.f), 5.656854f);
if ( !IsEqual(sht,result) )
{
printe("%s: Frustum failed\n",TestName);
printfr(fr);
printsh(result);
printsh(sht);
success = false;
}
XMMATRIX matrix = XMMatrixPerspectiveFovRH( XM_PIDIV2 /* 90 degrees */, 1.f, 1.f, 100.f );
BoundingFrustum fr2;
BoundingFrustum::CreateFromMatrix( fr2, matrix );
BoundingSphere::CreateFromFrustum( sht, fr2 );
const BoundingSphere result2( XMFLOAT3(0, 0, -100.000694f ), 141.422333f );
if ( !IsEqual(sht,result2) )
{
printe("%s: Frustum2 failed\n",TestName);
printfr(fr2);
printsh(result2);
printsh(sht);
success = false;
}
return ( success ) ? S_OK : MATH_FAIL;
}
| 39.0775 | 159 | 0.427468 | [
"vector",
"transform"
] |
6a520ff210d09b5a80fa16f7de0168fa93be2aeb | 82,681 | cxx | C++ | com/ole32/com/objact/actvator.cxx | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | com/ole32/com/objact/actvator.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | com/ole32/com/objact/actvator.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | //+-------------------------------------------------------------------
//
// File: actvator.cxx
//
// Contents: Implementation of client context system activator.
//
// Classes: CClientContextActivator
//
// History: 21-Feb-98 SatishT Created
// 22-Jun-98 CBiks See comments in code.
// 27-Jun-98 CBiks See RAID# 171549 and comments
// in the code.
// 14-Sep-98 CBiks Fixed RAID# 214719.
// 10-Oct-98 CBiks Fixed RAID# 151056.
// 21-Oct-98 SteveSw 104665; 197253;
// fix COM+ persistent activation
// 03-Nov-98 CBiks Fix RAID# 231613.
//
//--------------------------------------------------------------------
#include <ole2int.h>
#include <actvator.hxx>
#include <resolver.hxx>
#include <dllcache.hxx>
#include <objact.hxx>
#include <marshal.hxx>
#include <context.hxx>
#if DBG==1
// Debugging hack: set this to TRUE to break on unexpected failures
// in debug builds.
BOOL gfDebugHResult = FALSE;
#endif
//+------------------------------------------------------------------------
//
// Secure references hash table buckets. This is defined as a global
// so that we dont have to run any code to initialize the hash table.
//
//+------------------------------------------------------------------------
SHashChain ApartmentBuckets[23] =
{
{&ApartmentBuckets[0], &ApartmentBuckets[0]},
{&ApartmentBuckets[1], &ApartmentBuckets[1]},
{&ApartmentBuckets[2], &ApartmentBuckets[2]},
{&ApartmentBuckets[3], &ApartmentBuckets[3]},
{&ApartmentBuckets[4], &ApartmentBuckets[4]},
{&ApartmentBuckets[5], &ApartmentBuckets[5]},
{&ApartmentBuckets[6], &ApartmentBuckets[6]},
{&ApartmentBuckets[7], &ApartmentBuckets[7]},
{&ApartmentBuckets[8], &ApartmentBuckets[8]},
{&ApartmentBuckets[9], &ApartmentBuckets[9]},
{&ApartmentBuckets[10], &ApartmentBuckets[10]},
{&ApartmentBuckets[11], &ApartmentBuckets[11]},
{&ApartmentBuckets[12], &ApartmentBuckets[12]},
{&ApartmentBuckets[13], &ApartmentBuckets[13]},
{&ApartmentBuckets[14], &ApartmentBuckets[14]},
{&ApartmentBuckets[15], &ApartmentBuckets[15]},
{&ApartmentBuckets[16], &ApartmentBuckets[16]},
{&ApartmentBuckets[17], &ApartmentBuckets[17]},
{&ApartmentBuckets[18], &ApartmentBuckets[18]},
{&ApartmentBuckets[19], &ApartmentBuckets[19]},
{&ApartmentBuckets[20], &ApartmentBuckets[20]},
{&ApartmentBuckets[21], &ApartmentBuckets[21]},
{&ApartmentBuckets[22], &ApartmentBuckets[22]}
};
CApartmentHashTable gApartmentTbl; // global table of apartment entries
COleStaticMutexSem CApartmentHashTable::_mxsAptTblLock;
const GUID *GetPartitionIDForClassInfo(IComClassInfo *pCI);
//+--------------------------------------------------------------------------
//
// Function: CheckMemoryGate
//
// Synopsis: Helper function to check memory gate. This code must
// be executed in two activators, so I wrote it as an inline
// function to maintain brevity of activator code.
//
// History: 01-Nov-99 a-sergiv Created to implement Memory Gates
//
//----------------------------------------------------------------------------
HRESULT CheckMemoryGate(IUnknown *punk, ResourceGateId id)
{
HRESULT hr = S_OK;
IResourceGates *pResGates = NULL;
if(punk->QueryInterface(IID_IResourceGates, (void**) &pResGates) == S_OK)
{
BOOL bResult = TRUE;
hr = pResGates->Test(id, &bResult);
pResGates->Release();
if(SUCCEEDED(hr) && !bResult)
{
// The gate said NO!
hr = E_OUTOFMEMORY;
}
else
{
// Make it S_OK
hr = S_OK;
}
}
return hr;
}
//----------------------------------------------------------------------------
// CClientContextActivator Implementation.
//----------------------------------------------------------------------------
//+--------------------------------------------------------------------------
//
// Member: CClientContextActivator::CheckInprocClass , private
//
// Synopsis: Check various parameters to determine if activation should be
// inproc and clear the ClientContextOK flag if not
//
// History: 21-Feb-98 SatishT Created
// 04-Apr-98 CBiks Added updated support for Wx86 that was removed
// during the Com+ merge.
// 23-Jun-98 CBiks See RAID# 169589. Added activation
// flags to NegotiateDllInstantiationProperties().
//
// 09-Oct-09 vinaykr Changed to not give RSN priority
//
//----------------------------------------------------------------------------
STDMETHODIMP CClientContextActivator::CheckInprocClass(
IActivationPropertiesIn *pInActProperties,
DLL_INSTANTIATION_PROPERTIES *pdip,
BOOL &bActivateInproc,
ILocalSystemActivator **ppAct)
{
DWORD dwClsCtx;
*ppAct = NULL;
IComClassInfo *pClassInfo = NULL;
IServerLocationInfo *pSrvLocInfo = NULL;
HRESULT hrNegotiate = S_OK;
ActivationPropertiesIn *pActIn=NULL;
// This does not need to be released
HRESULT hr = pInActProperties->QueryInterface(
CLSID_ActivationPropertiesIn,
(LPVOID*)&pActIn
);
Win4Assert((hr == S_OK) && (pActIn != NULL));
hr = pInActProperties->GetClsctx(&dwClsCtx);
CHECK_HRESULT(hr);
// This does not need to be released
pClassInfo = pActIn->GetComClassInfo();
Win4Assert(pClassInfo != NULL);
// Pick up RSN from Server Location Info
pSrvLocInfo = pActIn->GetServerLocationInfo();
Win4Assert(pSrvLocInfo != NULL);
PWSTR pwstrRSN = NULL;
// Note that, by the memory management rules
// of the catalog interfaces, this string is
// a direct pointer to the buffer in the
// properties object, and should not be deleted
hr = pSrvLocInfo->GetRemoteServerName(&pwstrRSN);
CLSID *pClsid;
hr = pClassInfo->GetConfiguredClsid(&pClsid);
if (dwClsCtx & CLSCTX_INPROC_MASK1632)
{
// Now see if the activation should occur INPROC
// CBiks, 10-Oct-98
// Cleaned up the code to let NegotiateDllInstantiationProperties()
// do all the work.
DWORD actvflags;
hr = pInActProperties->GetActivationFlags(&actvflags);
CHECK_HRESULT(hr)
hr = CClassCache::CDllPathEntry::NegotiateDllInstantiationProperties(
dwClsCtx,
actvflags,
*pClsid,
*pdip,
pClassInfo,
TRUE);
bActivateInproc = SUCCEEDED(hr);
// Propagate BADTHREADINGMODEL return code.
if (REGDB_E_BADTHREADINGMODEL == hr)
hrNegotiate = hr;
hr = S_OK;
}
else
{
bActivateInproc = FALSE;
}
IActivationStageInfo *pStageInfo = (IActivationStageInfo*)pActIn;
if (bActivateInproc) // get ready for server process stage
{
pActIn->SetDip(pdip);
hr = pStageInfo->SetStageAndIndex(SERVER_PROCESS_STAGE,0);
CHECK_HRESULT(hr);
}
else
{
if (((dwClsCtx &
~(CLSCTX_INPROC_MASK1632|CLSCTX_NO_CODE_DOWNLOAD|CLSCTX_NO_CUSTOM_MARSHAL)) != 0) ||
(pwstrRSN != NULL))
{
if (pwstrRSN == NULL)
{
//Try to intercept case where we are already running
//in a complus server app for which this activation
//is destined.
GUID *pProcessGuid=NULL;
if (CSurrogateActivator::AmIComplusProcess(&pProcessGuid))
{
Win4Assert(pProcessGuid);
IClassClassicInfo *pIClassCI;
hr = pClassInfo->QueryInterface (IID_IClassClassicInfo,
(void**) &pIClassCI );
if ((pIClassCI != NULL) &&
(SUCCEEDED(hr)))
{
IComProcessInfo *pProcessInfo;
hr = pIClassCI->GetProcess(IID_IComProcessInfo,
(void**) &pProcessInfo);
pIClassCI->Release();
if (SUCCEEDED(hr) && pProcessInfo)
{
GUID *pGuid;
hr = pProcessInfo->GetProcessId(&pGuid);
HRESULT hr2 = S_OK;
if (SUCCEEDED(hr) &&
(*pGuid == *pProcessGuid))
{
bActivateInproc = TRUE;
//DebugBreak();
*ppAct = (ILocalSystemActivator*)
CSurrogateActivator::GetSurrogateActivator();
Win4Assert(*ppAct);
DWORD actvflags;
hr2 = pInActProperties->GetActivationFlags(&actvflags);
CHECK_HRESULT(hr2)
hr2 = CClassCache::CDllPathEntry::NegotiateDllInstantiationProperties(
CLSCTX_INPROC,
actvflags,
*pClsid,
*pdip,
pClassInfo,
TRUE);
if (SUCCEEDED(hr2))
pActIn->SetDip(pdip);
}
pProcessInfo->Release();
if (FAILED(hr2))
{
return hr2;
}
}
}
hr = S_OK;
}
}
if (!bActivateInproc)
{
// get ready for client SCM stage
ContextInfo *pActCtxInfo;
pActCtxInfo = pActIn->GetContextInfo();
Win4Assert(pActCtxInfo != NULL);
hr = pActCtxInfo->SetClientContextNotOK();
CHECK_HRESULT(hr);
hr = pStageInfo->SetStageAndIndex(CLIENT_MACHINE_STAGE,0);
CHECK_HRESULT(hr);
}
}
else
{
hr = (hrNegotiate == S_OK) ? REGDB_E_CLASSNOTREG : hrNegotiate;
}
}
return hr;
}
//+--------------------------------------------------------------------------
//
// Member: CClientContextActivator::GetClassObject , public
//
// Synopsis: Delegate to server process stage if the activation will be
// completed inproc, otherwise, clear the ClientContextOK flag
// and delegate to the client SCM stage.
//
// History: 21-Feb-98 SatishT Created
// 01-Nov-99 a-sergiv Implemented Memory Gates
//
//----------------------------------------------------------------------------
STDMETHODIMP CClientContextActivator::GetClassObject(
IN IActivationPropertiesIn *pInActProperties,
OUT IActivationPropertiesOut **ppOutActProperties)
{
ComDebOut((DEB_ACTIVATE, "CClientContextActivator::GetClassObject [IN]\n"));
HRESULT hr;
BOOL bActivateInproc;
DLL_INSTANTIATION_PROPERTIES *pdip;
int nRetries = 0;
GETREFCOUNT(pInActProperties,__relCount__);
ActivationPropertiesIn *pActIn=NULL;
// This does not need to be released
hr = pInActProperties->QueryInterface(
CLSID_ActivationPropertiesIn,
(LPVOID*)&pActIn
);
Win4Assert((hr == S_OK) && (pActIn != NULL));
RETRY_ACTIVATION:
// Check CreateObjectMemoryGate
hr = CheckMemoryGate(pActIn->GetComClassInfo(), CreateObjectMemoryGate);
if(FAILED(hr)) goto exit_point;
pdip = (DLL_INSTANTIATION_PROPERTIES *) pActIn->GetDip();
if (!pdip)
{
pdip = (DLL_INSTANTIATION_PROPERTIES *) _alloca(sizeof(DLL_INSTANTIATION_PROPERTIES));
pdip->_pDCE = NULL;
}
ILocalSystemActivator *pAct;
hr = CheckInprocClass(pInActProperties, pdip, bActivateInproc, &pAct);
if (SUCCEEDED(hr))
{
if (bActivateInproc) // just move to the process stage already set
{
if (pAct)
hr = pAct->GetClassObject(pInActProperties,
ppOutActProperties);
else
{
hr = pInActProperties->DelegateGetClassObject(ppOutActProperties);
// Sajia-support for partitions
// If the delegated activation returns ERROR_RETRY,
// we walk the chain again, but AT MOST ONCE.
if (HRESULT_FROM_WIN32(ERROR_RETRY) == hr)
{
Win4Assert(!nRetries);
if (!nRetries)
{
nRetries++;
goto RETRY_ACTIVATION;
}
}
}
}
else
{
// Go to the SCM
hr = gResolver.GetClassObject(
pInActProperties,
ppOutActProperties
);
}
}
exit_point:
CHECKREFCOUNT(pInActProperties,__relCount__);
ComDebOut((DEB_ACTIVATE, "CClientContextActivator::GetClassObject [OUT] hr:%x\n", hr));
return hr;
}
//+--------------------------------------------------------------------------
//
// Member: CClientContextActivator::CreateInstance , public
//
// Synopsis:
//
// History: 21-Feb-98 SatishT Created
// 01-Nov-99 a-sergiv Implemented Memory Gates
//
//----------------------------------------------------------------------------
STDMETHODIMP CClientContextActivator::CreateInstance(
IN IUnknown *pUnkOuter,
IN IActivationPropertiesIn *pInActProperties,
OUT IActivationPropertiesOut **ppOutActProperties)
{
ComDebOut((DEB_ACTIVATE, "CClientContextActivator::CreateInstance [IN]\n"));
HRESULT hr;
BOOL bActivateInproc;
DLL_INSTANTIATION_PROPERTIES *pdip;
int nRetries = 0;
GETREFCOUNT(pInActProperties,__relCount__);
ActivationPropertiesIn *pActIn=NULL;
// This does not need to be released
hr = pInActProperties->QueryInterface(
CLSID_ActivationPropertiesIn,
(LPVOID*)&pActIn
);
Win4Assert((hr == S_OK) && (pActIn != NULL));
RETRY_ACTIVATION:
// Check CreateObjectMemoryGate
hr = CheckMemoryGate(pActIn->GetComClassInfo(), CreateObjectMemoryGate);
if(FAILED(hr)) goto exit_point;
pdip = (DLL_INSTANTIATION_PROPERTIES *) pActIn->GetDip();
if (!pdip)
{
pdip = (DLL_INSTANTIATION_PROPERTIES *) _alloca(sizeof(DLL_INSTANTIATION_PROPERTIES));
pdip->_pDCE = NULL;
}
ILocalSystemActivator *pAct;
hr = CheckInprocClass(pInActProperties, pdip, bActivateInproc, &pAct);
if (SUCCEEDED(hr))
{
if (bActivateInproc) // just move to the process stage already set
{
if (pAct)
{
hr = pAct->CreateInstance(pUnkOuter,
pInActProperties,
ppOutActProperties);
}
else
{
hr = pInActProperties->DelegateCreateInstance(pUnkOuter, ppOutActProperties);
// Sajia-support for partitions
// If the delegated activation returns ERROR_RETRY,
// we walk the chain again, but AT MOST ONCE.
if (HRESULT_FROM_WIN32(ERROR_RETRY) == hr)
{
Win4Assert(!nRetries);
if (!nRetries)
{
nRetries++;
goto RETRY_ACTIVATION;
}
}
}
}
else
{
IInstanceInfo* pInstanceInfo = NULL;
if ( pUnkOuter ) // can't send this to the SCM
{
hr = CLASS_E_NOAGGREGATION;
}
else if ( FAILED(pInActProperties->QueryInterface(IID_IInstanceInfo, (void**) &pInstanceInfo)) )
{
// Go to the SCM
hr = gResolver.CreateInstance(
pInActProperties,
ppOutActProperties
);
}
else
{
BOOL FoundInROT = FALSE;
DWORD cLoops = 0;
pInstanceInfo->Release();
do
{
hr = gResolver.GetPersistentInstance(pInActProperties, ppOutActProperties, &FoundInROT);
}
while ( (hr != S_OK) && (FoundInROT) && (++cLoops < 5) );
}
}
}
exit_point:
CHECKREFCOUNT(pInActProperties,__relCount__);
ComDebOut((DEB_ACTIVATE, "CClientContextActivator::CreateInstance [OUT] hr:%x\n", hr));
return hr;
}
//----------------------------------------------------------------------------
// CServerContextActivator Implementation.
//----------------------------------------------------------------------------
//+--------------------------------------------------------------------------
//
// Member: CServerContextActivator::GetClassObject , public
//
// Synopsis:
//
// History: 21-Feb-98 SatishT Created
// 22-Jun-98 CBiks See RAID# 164432. Added code to set
// OleStubInvoked when Wx86 is calling so
// whOleDllGetClassObject will allow
// the return of unknown interfaces.
// See RAID# 159589. Added the activation
// flags to ACTIVATION_PROPERTIES constructor.
// 12-Feb-01 JohnDoty Widened ACTIVATION_PROPERTIES for partitions.
//
//----------------------------------------------------------------------------
STDMETHODIMP CServerContextActivator::GetClassObject(
IN IActivationPropertiesIn *pInActProperties,
OUT IActivationPropertiesOut **ppOutActProperties)
{
ComDebOut((DEB_ACTIVATE, "CServerContextActivator::GetClassObject [IN]\n"));
CLSID *pClsid = NULL;
HRESULT hrSave = E_FAIL;
ActivationPropertiesIn *pActIn=NULL;
// This does not need to be released
HRESULT hr = pInActProperties->QueryInterface(
CLSID_ActivationPropertiesIn,
(LPVOID*)&pActIn
);
Win4Assert((hr == S_OK) && (pActIn != NULL));
// This does not need to be released
IComClassInfo *pComClassInfo;
pComClassInfo = pActIn->GetComClassInfo();
Win4Assert(pComClassInfo != NULL);
hr = pComClassInfo->GetConfiguredClsid(&pClsid);
CHECK_HRESULT(hr);
Win4Assert(pClsid && "Configured class id missing in class info");
DWORD ulCount = 0;
IID *prgIID = NULL;
IUnknown *pUnk = NULL;
hr = pInActProperties->GetRequestedIIDs(&ulCount, &prgIID);
CHECK_HRESULT(hr);
Win4Assert(ulCount == 1);
DWORD dwClsCtx = 0;
DWORD actvflags;
hr = pActIn->GetActivationFlags( &actvflags );
CHECK_HRESULT(hr);
// NOTE: Do not change the IID passed below. There are some objects in which
// IUnknown is broken and the object cannot be QI'd for the interface
// later. The work around for these objects relies on this code
// asking for the correct IID when calling DllGetClassObject.
DLL_INSTANTIATION_PROPERTIES *pdip = (DLL_INSTANTIATION_PROPERTIES *)pActIn->GetDip();
if (pdip && pdip->_pDCE)
{
//
// we have the cache line already, so just activate it
//
hr = hrSave = pdip->_pDCE->GetClassObject(*pClsid, prgIID[0], &pUnk, dwClsCtx);
}
else
{
if (pdip)
{
dwClsCtx = pdip->_dwContext;
}
else
{
hr = pInActProperties->GetClsctx(&dwClsCtx);
CHECK_HRESULT(hr)
}
// Grab the partition ID, if possible.
const GUID *pguidPartition = GetPartitionIDForClassInfo(pComClassInfo);
// This goes to the class cache to actually lookup the DPE and get the factory
//
ACTIVATION_PROPERTIES ap(*pClsid,
*pguidPartition,
prgIID[0],
0,
dwClsCtx,
actvflags,
0,
NULL,
&pUnk,
pComClassInfo);
hr = hrSave = CCGetClassObject(ap);
}
if (SUCCEEDED(hr))
{
//
// Grammatik has reference counting problems. The old class cache did
// not call AddRef or Release before returning the object to the app.
// We will special case Grammatik for the same behavior.
//
Win4Assert((pUnk != NULL) && "CCGetClassObject Succeeded but ..");
hr = pInActProperties->GetReturnActivationProperties(pUnk,ppOutActProperties);
if (!IsBrokenRefCount(pClsid))
{
// The out activation properties should have a ref on this
pUnk->Release();
}
}
ComDebOut((DEB_ACTIVATE, "CServerContextActivator::GetClassObject [OUT] hr:%x\n", hr));
if (SUCCEEDED(hr))
{
Win4Assert(SUCCEEDED(hrSave));
return hrSave;
}
else
{
return hr;
}
}
//+--------------------------------------------------------------------------
//
// Member: CServerContextActivator::CreateInstance , public
//
// Synopsis:
//
// History: 21-Feb-98 SatishT Created
// 22-Jun-98 CBiks See RAID# 164432. Added code to set
// OleStubInvoked when Wx86 is calling so
// whOleDllGetClassObject will allow
// the return of unknown interfaces.
// See RAID# 159589. Added the activation
// flags to ACTIVATION_PROPERTIES constructor.
//
//----------------------------------------------------------------------------
STDMETHODIMP CServerContextActivator::CreateInstance(
IN IUnknown *pUnkOuter,
IN IActivationPropertiesIn *pInActProperties,
OUT IActivationPropertiesOut **ppOutActProperties)
{
ComDebOut((DEB_ACTIVATE, "CServerContextActivator::CreateInstance [IN]\n"));
CLSID *pClsid = NULL;
// This does not need to be released
ActivationPropertiesIn *pActIn=NULL;
HRESULT hr = pInActProperties->QueryInterface(
CLSID_ActivationPropertiesIn,
(LPVOID*)&pActIn
);
Win4Assert((hr == S_OK) && (pActIn != NULL));
// This code checks to make sure we're not doing cross-context aggregation
hr = CheckCrossContextAggregation (pActIn, pUnkOuter);
if (FAILED (hr))
{
return hr;
}
// This does not need to be released
IComClassInfo *pComClassInfo;
pComClassInfo = pActIn->GetComClassInfo();
Win4Assert(pComClassInfo != NULL);
hr = pComClassInfo->GetConfiguredClsid(&pClsid);
CHECK_HRESULT(hr);
Win4Assert(pClsid && "Configured class id missing in class info");
IClassFactory *pCF = NULL;
IUnknown *pUnk = NULL;
DWORD dwClsCtx = 0;
DWORD actvflags;
hr = pActIn->GetActivationFlags( &actvflags );
CHECK_HRESULT(hr);
DLL_INSTANTIATION_PROPERTIES *pdip = (DLL_INSTANTIATION_PROPERTIES *)pActIn->GetDip();
if (pdip && pdip->_pDCE)
{
//
// we have the cache line already, so just activate it
//
hr = pdip->_pDCE->GetClassObject(*pClsid, IID_IClassFactory,
(IUnknown **) &pCF, dwClsCtx);
}
else
{
if (pdip)
{
dwClsCtx = ((DLL_INSTANTIATION_PROPERTIES *)pActIn->GetDip())->_dwContext;
}
else
{
hr = pInActProperties->GetClsctx(&dwClsCtx);
CHECK_HRESULT(hr);
}
// Grab the partition ID, if possible.
const GUID *pguidPartition = GetPartitionIDForClassInfo(pComClassInfo);
// This goes to the class cache to actually lookup the DPE and get the factory
ACTIVATION_PROPERTIES ap(*pClsid,
*pguidPartition,
IID_IClassFactory,
0,
dwClsCtx,
actvflags,
0,
NULL,
(IUnknown **)&pCF,
pComClassInfo);
hr = CCGetClassObject(ap);
}
if (SUCCEEDED(hr) && (NULL == pCF))
{
Win4Assert(!"Should have a pCF here but don't");
hr = E_UNEXPECTED;
}
if (SUCCEEDED(hr))
{
DWORD ulCount = 0;
IID *prgIID = NULL;
// This mysterious piece of code is here to take care of VB4 which sometimes
// produces "COM objects" that refuse to supply IUnknown when requested.
//
// jsimmons 5/21/00 -- in addition to handling buggy VB4 objects, people get
// upset when their class factory CreateInstance method is called and we don't
// ask for the same IID that was passed to CoCreateInstance.
hr = pInActProperties->GetRequestedIIDs(&ulCount, &prgIID);
if (SUCCEEDED(hr))
{
for (DWORD i=0;i<ulCount; i++)
{
//
// Actually create the object
//
hr = pCF->CreateInstance(pUnkOuter, prgIID[i], (LPVOID*)&pUnk);
if (SUCCEEDED(hr))
{
if (pUnk == NULL)
CoVrfNotifyCFSuccessWithNULL(pCF, *pClsid, prgIID[i], hr);
break;
}
}
}
}
if (SUCCEEDED(hr))
{
Win4Assert((pUnk != NULL) && "pCF->CreateInstance Succeeded but ..");
// This not only sets the object interface, it also applies any constructors that
// are required such as those involved in persistent instances
hr = pActIn->GetReturnActivationPropertiesWithCF(pUnk,
pCF,
ppOutActProperties);
// The out activation properties should have a ref on this
pUnk->Release();
}
// If Activation Succeeded, Out Actprops should have reference on this
if (pCF)
pCF->Release();
ComDebOut((DEB_ACTIVATE, "CServerContextActivator::CreateInstance [OUT] hr:%x\n", hr));
return hr;
}
HRESULT CServerContextActivator::CheckCrossContextAggregation (
IN ActivationPropertiesIn *pActIn,
IN IUnknown* pUnkOuter
)
{
CObjectContext* pCtx = NULL;
CObjectContext* pClientCtxUnk = NULL;
CObjectContext* pCurrentCtxUnk = NULL;
ContextInfo *cInfo = NULL;
CObjectContext *pContext = NULL;
HRESULT hr = S_OK, hrRet = S_OK;
// Short cut
if (pUnkOuter == NULL)
{
return S_OK;
}
// This does not need to be released
cInfo = pActIn->GetContextInfo();
Win4Assert(cInfo != NULL);
hr = cInfo->GetInternalClientContext(&pCtx);
if (SUCCEEDED(hr) && pCtx)
{
hr = pCtx->InternalQueryInterface(IID_IUnknown, (void**) &pClientCtxUnk);
pCtx->InternalRelease();
pCtx = NULL;
}
if (SUCCEEDED(hr) && pClientCtxUnk)
{
pContext = GetCurrentContext();
if (pContext)
{
hr = pContext->InternalQueryInterface(IID_IUnknown, (void**) &pCurrentCtxUnk);
pContext = NULL;
}
}
if (SUCCEEDED(hr) && pCurrentCtxUnk && pClientCtxUnk)
{
if (pClientCtxUnk != pCurrentCtxUnk)
{
hrRet = CLASS_E_NOAGGREGATION;
}
}
if (pClientCtxUnk)
{
pClientCtxUnk->InternalRelease();
pClientCtxUnk = NULL;
}
if (pCurrentCtxUnk)
{
pCurrentCtxUnk->InternalRelease();
pCurrentCtxUnk = NULL;
}
return hrRet;
}
//----------------------------------------------------------------------------
// CProcessActivator Implementation.
//----------------------------------------------------------------------------
//+--------------------------------------------------------------------------
//
// Member: CProcessActivator::GetApartmentActivator , private
//
// Synopsis: Check if a custom activator set the apartment and if not
// call the class cache to find or create the default apartment
// in which this class should run.
//
// History: 25-Feb-98 SatishT Created
// 23-Jun-98 CBiks See RAID# 169589. Added activation
// flags to NegotiateDllInstantiationProperties().
//
//----------------------------------------------------------------------------
STDMETHODIMP CProcessActivator::GetApartmentActivator(
IN ActivationPropertiesIn *pInActProperties,
OUT ISystemActivator **ppActivator)
{
HRESULT hr = E_FAIL;
IServerLocationInfo *pSrvLoc;
pSrvLoc = pInActProperties->GetServerLocationInfo();
Win4Assert(pSrvLoc != NULL);
HActivator hActivator = 0;
hr = pSrvLoc->GetApartment(&hActivator);
// HACK ALERT: This should only be entered if hActivator==0
// But in lieu of restructuring the DllCache to load the DLL in the
// server context, we currently do this for all activations to make sure
// that the DLL is actually loaded in the process and a ref is held to the
// DllPathEntry until activation is either completed or aborted
// The downsides of the hack are:
// 1. default DLL HOST based apartment created even when not needed
// 2. DLL unloading logic is broken because the DLL is validated in
// an apartment in which it may never be used
{
// none of the custom activators set the apartment
// This code will find or create the default apartment
// in which this class should run
CLSID *pClsid = NULL;
DWORD ClassContext;
HActivator hStdActivator = 0;
IComClassInfo *pComClassInfo = pInActProperties->GetComClassInfo();
Win4Assert(pComClassInfo != NULL);
hr = pComClassInfo->GetConfiguredClsid(&pClsid);
CHECK_HRESULT(hr);
Win4Assert(pClsid && "Configured class id missing in class info");
DWORD actvflags;
hr = pInActProperties->GetActivationFlags(&actvflags);
CHECK_HRESULT(hr)
DLL_INSTANTIATION_PROPERTIES *pdip =
(DLL_INSTANTIATION_PROPERTIES *) pInActProperties->GetDip();
if (!pdip)
{
//
// this can happen in a surrogate activation
//
pdip = (DLL_INSTANTIATION_PROPERTIES *) _alloca(sizeof(DLL_INSTANTIATION_PROPERTIES));
pdip->_pDCE = NULL;
hr = pInActProperties->GetClsctx(&(pdip->_dwContext));
CHECK_HRESULT(hr)
hr = CClassCache::CDllPathEntry::NegotiateDllInstantiationProperties(
pdip->_dwContext,
actvflags,
*pClsid,
*pdip,
pComClassInfo,
TRUE);
}
if (SUCCEEDED(hr))
{
// Go to the class cache for the apartment creation
hr = FindOrCreateApartment(
*pClsid,
actvflags,
pdip,
&hStdActivator
);
// this is part of the HACK ALERT above
if (SUCCEEDED(hr) && (hActivator == 0))
{
hActivator = hStdActivator;
}
}
}
if (SUCCEEDED(hr))
{
Win4Assert(hActivator != 0);
if (CURRENT_APARTMENT_TOKEN != hActivator)
{
// cross apartment activation
*ppActivator = NULL;
hr = GetInterfaceFromStdGlobal(hActivator,
IID_ISystemActivator,
(LPVOID*)ppActivator);
if (SUCCEEDED(hr))
{
// Since we are going cross apartment, the client context
// won't do as the server context, so set the flag appropriately
ContextInfo *pActCtxInfo = NULL;
pActCtxInfo = pInActProperties->GetContextInfo();
Win4Assert(pActCtxInfo != NULL);
hr = pActCtxInfo->SetClientContextNotOK();
}
}
else
{
// same apartment activation, just get the raw pointer
*ppActivator = gApartmentActivator.GetSystemActivator();
}
}
ComDebOut((DEB_ACTIVATE, "CProcessActivator::GetApartmentActivator [OUT] hr:%x\n", hr));
return hr;
}
//+--------------------------------------------------------------------------
//
// Member: CProcessActivator::GetClassObject , public
//
// Synopsis: End of the server process activation stage.
// Responsibilities:
//
// 1. Find or create apartment for activation
// 2. Find a match for the prototype context in the right
// apartment, and if none, freeze the prototype into a new
// context to be used for the class object.
//
// If we got this far with GetClassObject, the class factory will be
// born in a fixed context and all instances of the factory will most
// likely live there unless the factory does something unusual.
//
// History: 24-Feb-98 SatishT Created
// 07-Mar-98 Gopalk Fixup leaking ISystemActivator
// 01-Nov-99 a-sergiv Implemented Memory Gates
//
//----------------------------------------------------------------------------
STDMETHODIMP CProcessActivator::GetClassObject(
IN IActivationPropertiesIn *pInActProperties,
OUT IActivationPropertiesOut **ppOutActProperties)
{
ComDebOut((DEB_ACTIVATE, "CProcessActivator::GetClassObject [IN]\n"));
GETREFCOUNT(pInActProperties,__relCount__);
HRESULT hr = E_FAIL;
ActivationPropertiesIn *pActIn=NULL;
hr = pInActProperties->QueryInterface(
CLSID_ActivationPropertiesIn,
(LPVOID*)&pActIn
);
Win4Assert((hr == S_OK) && (pActIn != NULL));
// Check CreateObjectMemoryGate
hr = CheckMemoryGate(pActIn->GetComClassInfo(), CreateObjectMemoryGate);
if(FAILED(hr)) goto exit_point;
//
// We must retry for each CLSCTX separately because the handler
// case could go to a different apartment or context than the
// inproc server
//
hr = ActivateByContext(pActIn, NULL, pInActProperties,
ppOutActProperties, GCOCallback);
if (FAILED(hr)) goto exit_point;
/*
If we arrive at the end of the server process activation stage without
running into an activator that short circuits CGCO due to a desire to
intercept instance creation, do we then proceed to construct a context
for it as though it were an instance of the said class and park the
class factory in that context? Is this consistent with JIT/Pooling
and other strange activators? Even if the interface required from
the class is not a standard factory interface? There has been some
concern about object pooling in particular.
*/
exit_point:
CHECKREFCOUNT(pInActProperties,__relCount__);
ComDebOut((DEB_ACTIVATE, "CProcessActivator::GetClassObject [OUT] hr:%x\n", hr));
return hr;
}
//+--------------------------------------------------------------------------
//
// Member: CProcessActivator::CreateInstance , public
//
// Synopsis: End of the server process activation stage.
// Responsibilities:
//
// 1. Find or create apartment for activation
// 2. Find a match for the prototype context in the right
// apartment, and if none, freeze the prototype into a new
// context to be used for the instance object.
//
// History: 25-Feb-98 SatishT Created
// 07-Mar-98 Gopalk Fixup leaking ISystemActivator
// 01-Nov-99 a-sergiv Implemented Memory Gates
//
//----------------------------------------------------------------------------
STDMETHODIMP CProcessActivator::CreateInstance(
IN IUnknown *pUnkOuter,
IN IActivationPropertiesIn *pInActProperties,
OUT IActivationPropertiesOut **ppOutActProperties)
{
ComDebOut((DEB_ACTIVATE, "CProcessActivator::GetClassObject [IN]\n"));
HRESULT hr = E_FAIL;
GETREFCOUNT(pInActProperties,__relCount__);
ActivationPropertiesIn *pActIn=NULL;
hr = pInActProperties->QueryInterface(
CLSID_ActivationPropertiesIn,
(LPVOID*)&pActIn
);
Win4Assert((hr == S_OK) && (pActIn != NULL));
// Check CreateObjectMemoryGate
hr = CheckMemoryGate(pActIn->GetComClassInfo(), CreateObjectMemoryGate);
if(FAILED(hr)) goto exit_point;
hr = ActivateByContext(pActIn, pUnkOuter, pInActProperties,
ppOutActProperties, CCICallback);
if (FAILED(hr)) goto exit_point;
exit_point:
CHECKREFCOUNT(pInActProperties,__relCount__);
ComDebOut((DEB_ACTIVATE, "CProcessActivator::CreateInstance [OUT] hr:%x\n", hr));
return hr;
}
// See comments in ActivateByContext below that explain
// reason for this tiny helper function to exist.
ULONG ActErrorPriority(HRESULT hr)
{
switch (hr)
{
case CLASS_E_NOTLICENSED:
return 3;
break;
case CLASS_E_CLASSNOTAVAILABLE:
return 2;
break;
case REGDB_E_CLASSNOTREG:
return 1;
break;
default:
return 0;
break;
}
}
//+----------------------------------------------------------------------------
//
// Member: CProcessActivator::ActivateByContext
//
// Synopsis: Tries each context in the correct order.
//
// History: 27-Apr-98 MattSmit Created
// 22-Jun-98 CBiks See RAID# 169589. Fixed an order of
// operations typo the Wx86 detection
// code that resulted Wx86 never working.
// HEY MATT! == binds stronger than & !!
// 09-Oct-98 CBiks Modified the INPROCs to check for
// x86 activation first on Alpha.
//
//-----------------------------------------------------------------------------
STDMETHODIMP CProcessActivator::ActivateByContext(ActivationPropertiesIn *pActIn,
IUnknown *pUnkOuter,
IActivationPropertiesIn *pInActProperties,
IActivationPropertiesOut **ppOutActProperties,
PFNCTXACTCALLBACK pfnCtxActCallback)
{
ClsCacheDebugOut((DEB_TRACE, "CProcessActivator::ActivateByContext IN "
"pActIn:0x%x, pInActProperties:0x%x, ppOutActProperties:0x%x,"
" pfnCtxActCallback:0x%x\n", pActIn, pInActProperties,
ppOutActProperties, pfnCtxActCallback));
//
// jsimmons 09/17/2002
//
// Error handling in this function is funky. The different errors we might get
// have a certain order of precedence, borne from long experience (with regressions,
// that is).
//
// 1) CLASS_E_NOTLICENSED -- certain VB scenarios involving licensed OCX's need this behavior.
// Please see COM+ bug 20644.
//
// 2) CLASS_E_CLASSNOTAVAILABLE -- somebody forgot to replace their dll with a newer
// implementation. Note that this is more specific than REGDB_E_CLASSNOTREG, which is
// why it's in the #2 slot.
//
// 3) REGDB_E_CLASSNOTREG -- VB apps have a nice behavior where if they get this error when
// creating a dll/ocx-based object that they were compiled against, they will look in their
// current directory for the dll/ocx and use it directly. They expect this even if the
// dll exists on the machine but has been moved (see COM+ 32822), thus leaving an incorrect
// InprocServer32 entry in the registry. Sigh. What can you do?
//
// 4) other - who knows.
//
// Note that the above behavior I'm describing is not necessarily logical...but it's way,
// way too late to be considering changes. Apps (esp VB) expect certain things of us, so
// we need to try to maintain a status quo behavior.
//
HRESULT hrFinal, hrtmp;
DWORD dwContext;
BOOL triedOne = FALSE;
hrtmp = pInActProperties->GetClsctx(&dwContext);
if (FAILED(hrtmp))
return hrtmp;
hrFinal = S_OK; // overwritten by the first error, or set to CLASS_E_CLASSNOTAVAILABLE
// if none of the below cases apply (unexpected for this to happen)
hrtmp = E_FAIL;
// try an INPROC_SERVER first
if (dwContext & CLSCTX_INPROC_SERVERS)
{
if (FAILED(hrtmp))
{
hrtmp = AttemptActivation(pActIn, pUnkOuter, pInActProperties,
ppOutActProperties, pfnCtxActCallback,
dwContext & CLSCTX_INPROC_SERVERS);
if (FAILED(hrtmp))
{
if (SUCCEEDED(hrFinal))
{
hrFinal = hrtmp;
}
else
{
// Current hrFinal is failed, see which one wins
if (ActErrorPriority(hrtmp) > ActErrorPriority(hrFinal))
{
hrFinal = hrtmp;
}
}
}
else
{
hrFinal = hrtmp;
}
triedOne = TRUE;
}
}
// Try for an inproc handler
if (FAILED(hrtmp) && (dwContext & CLSCTX_INPROC_HANDLERS))
{
if (FAILED(hrtmp))
{
hrtmp = AttemptActivation(pActIn, pUnkOuter, pInActProperties,
ppOutActProperties, pfnCtxActCallback,
dwContext & CLSCTX_INPROC_HANDLERS);
if (FAILED(hrtmp))
{
if (SUCCEEDED(hrFinal))
{
hrFinal = hrtmp;
}
else
{
// Current hrFinal is failed, see which one wins
if (ActErrorPriority(hrtmp) > ActErrorPriority(hrFinal))
{
hrFinal = hrtmp;
}
}
}
else
{
hrFinal = hrtmp;
}
triedOne = TRUE;
}
}
// that didn't work, so try a LOCAL_SERVER
if (FAILED(hrtmp) && (dwContext & CLSCTX_LOCAL_SERVER))
{
// Don't need to release this
IComClassInfo *pCI = pActIn->GetComClassInfo();
Win4Assert(pCI);
DWORD stage;
BOOLEAN fComplusForSure=FALSE;
if (triedOne)
for ( stage = CLIENT_CONTEXT_STAGE;
stage <= SERVER_CONTEXT_STAGE;
stage++ )
{
DWORD cCustomActForStage = 0;
pCI->GetCustomActivatorCount((ACTIVATION_STAGE)stage,
&cCustomActForStage);
if (cCustomActForStage)
{
fComplusForSure = TRUE;
break;
}
}
// Retry only if no custom activators
if (!fComplusForSure || !triedOne)
{
hrtmp = AttemptActivation(pActIn, pUnkOuter, pInActProperties,
ppOutActProperties, pfnCtxActCallback,
CLSCTX_LOCAL_SERVER);
if (FAILED(hrtmp) && SUCCEEDED(hrFinal))
hrFinal = hrtmp;
else if (SUCCEEDED(hrtmp))
hrFinal = hrtmp;
triedOne = TRUE;
}
}
// If we never even tried one of the above, then we need to reset the hr
// to CLASS_E_CLASSNOTAVAILABLE
if (!triedOne)
{
hrFinal = CLASS_E_CLASSNOTAVAILABLE;
}
ClsCacheDebugOut((DEB_TRACE, "CProcessActivator::ActivateByContext OUT hr:0x%x\n", hrFinal));
return hrFinal;
}
//+----------------------------------------------------------------------------
//
// Member: CProcessActivator::AttemptActivation
//
// Synopsis: Attempts to activate given a CLSCTX
//
// History: 27-Apr-98 MattSmit Created
//
//-----------------------------------------------------------------------------
STDMETHODIMP CProcessActivator::AttemptActivation(ActivationPropertiesIn *pActIn,
IUnknown *pUnkOuter,
IActivationPropertiesIn *pInActProperties,
IActivationPropertiesOut **ppOutActProperties,
PFNCTXACTCALLBACK pfnCtxActCallback,
DWORD dwContext)
{
ISystemActivator *pAptActivator;
HRESULT hr;
ASSERT_ONE_CLSCTX(dwContext);
ClsCacheDebugOut((DEB_TRACE, "CProcessActivator::AttemptActivation IN dwContext:0x%x,"
" pActIn:0x%x, pInActProperties:0x%x, ppOutActProperties:0x%x\n",
dwContext, pActIn, pInActProperties, ppOutActProperties));
if (pActIn->GetDip())
{
((DLL_INSTANTIATION_PROPERTIES *)(pActIn->GetDip()))->_dwContext = dwContext;
}
hr = (this->*pfnCtxActCallback)(dwContext, pUnkOuter,
pActIn, pInActProperties,
ppOutActProperties);
ClsCacheDebugOut((DEB_TRACE, "CProcessActivator::AttemptActivation OUT hr:0x%x\n", hr));
return hr;
}
//+----------------------------------------------------------------------------
//
// Function: GCOCallback
//
// Synopsis: Call back for each context attemp
//
// History: 27-Apr-98 MattSmit Created
//
//-----------------------------------------------------------------------------
HRESULT CProcessActivator::GCOCallback(DWORD dwContext,
IUnknown *pUnkOuter,
ActivationPropertiesIn *pActIn,
IActivationPropertiesIn *pInActProperties,
IActivationPropertiesOut **ppOutActProperties)
{
ClsCacheDebugOut((DEB_TRACE, "GCOCallback IN dwContext:0x%x, pActIn:0x%x,"
" pInActProperties:0x%x, ppOutActProperties:0x%x\n",
dwContext, pActIn, pInActProperties, ppOutActProperties));
Win4Assert(pUnkOuter == NULL);
HRESULT hr;
ISystemActivator *pAptActivator;
ASSERT_ONE_CLSCTX(dwContext);
//
// get the apartment activator
//
hr = GetApartmentActivator(pActIn, &pAptActivator);
if (SUCCEEDED(hr))
{
//
// switch to the server apartment and attempt the
// activation there
//
hr = pAptActivator->GetClassObject(pInActProperties,ppOutActProperties);
pAptActivator->Release();
}
ClsCacheDebugOut((DEB_TRACE, "GCOCallback OUT hr:0x%x\n", hr));
return hr;
}
//+----------------------------------------------------------------------------
//
// Function: CCICallback
//
// Synopsis: callback for each context attempt
//
// History: 27-Apr-98 MattSmit Created
//
//-----------------------------------------------------------------------------
HRESULT CProcessActivator::CCICallback(DWORD dwContext,
IUnknown *pUnkOuter,
ActivationPropertiesIn *pActIn,
IActivationPropertiesIn *pInActProperties,
IActivationPropertiesOut **ppOutActProperties)
{
ISystemActivator *pAptActivator;
HRESULT hr;
ASSERT_ONE_CLSCTX(dwContext);
hr = GetApartmentActivator(pActIn, &pAptActivator);
if (SUCCEEDED(hr))
{
// Figure out of we have aggregation and if it is OK
// Note: if the apartment activatior is in a different
// apartment the flag should be set to false already
if (pUnkOuter)
{
ContextInfo *pActCtxInfo = NULL;
pActCtxInfo = pActIn->GetContextInfo();
Win4Assert(pActCtxInfo != NULL);
BOOL fClientContextOK;
hr = pActCtxInfo->IsClientContextOK(&fClientContextOK);
CHECK_HRESULT(hr);
if (!fClientContextOK)
{
hr = CLASS_E_NOAGGREGATION;
}
}
if (SUCCEEDED(hr))
{
hr = pAptActivator->CreateInstance(pUnkOuter,pInActProperties,ppOutActProperties);
}
pAptActivator->Release();
}
ClsCacheDebugOut((DEB_TRACE, "CCICallBack OUT hr:0x%x\n", hr));
return hr;
}
//+--------------------------------------------------------------------------
//
// Member: CApartmentActivator::ContextMaker , private
//
// Synopsis:
//
// History: 06-Mar-98 SatishT Created
//
//----------------------------------------------------------------------------
STDMETHODIMP CApartmentActivator::ContextSelector(
IN IActivationPropertiesIn *pInActProperties,
OUT BOOL &fCurrentContextOK,
OUT CObjectContext *&pContext)
{
ComDebOut((DEB_ACTIVATE, "CApartmentActivator::ContextMaker [IN]\n"));
HRESULT hr = E_FAIL;
// This is a fake QI that gives back a non-refcounted pointer to the
// actual class
ActivationPropertiesIn *pActIn=NULL;
hr = pInActProperties->QueryInterface(
CLSID_ActivationPropertiesIn,
(LPVOID*)&pActIn
);
Win4Assert((hr == S_OK) && (pActIn != NULL));
IActivationStageInfo *pStageInfo = (IActivationStageInfo*) pActIn;
hr = pStageInfo->SetStageAndIndex(SERVER_CONTEXT_STAGE,0);
CHECK_HRESULT(hr);
ContextInfo *pActCtxInfo = pActIn->GetContextInfo();
Win4Assert(pActCtxInfo != NULL);
// Check whether the target context was overridden. If it was,
// then I can tell you right now that client context is not OK.
if(pActCtxInfo->_ctxOverride != GUID_NULL)
{
// Client context is NOT OK
fCurrentContextOK = FALSE;
// Lookup the existing context
LOCK(gContextLock);
pContext = CCtxTable::LookupExistingContext(pActCtxInfo->_ctxOverride);
UNLOCK(gContextLock);
if(!pContext)
return E_UNEXPECTED;
else
pContext->InternalAddRef();
return S_OK;
}
// This initialization assumes fCurrentContextOK -- we will reset
// if we conclude later after much debate that fCurrentContextOK==FALSE
pContext = NULL;
hr = pActCtxInfo->IsClientContextOK(&fCurrentContextOK);
CHECK_HRESULT(hr);
// Pick the context we are going to use as the server context
if (!fCurrentContextOK)
{
// Note: fProtoExists does not imply !fProtoEmpty
// fProtoEmpty does not imply !fProtoExists
// !fProtoExists does imply fProtoEmpty
BOOL fProtoExists = TRUE, // was the prototype context ever created?
fProtoEmpty = TRUE; // is the theoretical prototype context empty?
CObjectContext *pProtoContext = NULL;
hr = pActCtxInfo->PrototypeExists(&fProtoExists);
CHECK_HRESULT(hr);
if (fProtoExists)
{
// we initialized fProtoEmpty to TRUE but it might be FALSE
hr = pActCtxInfo->GetInternalPrototypeContext(&pProtoContext);
CHECK_HRESULT(hr);
Win4Assert(pProtoContext);
fProtoEmpty = IsEmptyContext(pProtoContext);
}
if (fProtoEmpty)
{
// prototype context is empty -- if the current context is
// also empty we will just activate in the current context
CObjectContext *pCurrentContext = NULL;
hr = PrivGetObjectContext(IID_IStdObjectContext,
(LPVOID*)&pCurrentContext);
CHECK_HRESULT(hr);
Win4Assert(pCurrentContext);
if (pCurrentContext->GetCount() == 0)
{
fCurrentContextOK = TRUE;
}
pCurrentContext->InternalRelease();
}
// Here is where we find an existing context if possible
// This should set fCurrentContextOK if prototype is
// found to be equivalent
if (!fCurrentContextOK)
{
CObjectContext* pMatchingContext = NULL;
// Prefix says we might not have a prototype context available
// here. Should never happen with our current code, but humor
// the prefix gods anyway.
hr = E_UNEXPECTED;
Win4Assert(pProtoContext);
if (pProtoContext)
{
// Freeze the prototype context for now and forever..
hr = pProtoContext->Freeze();
if(SUCCEEDED(hr))
{
// Here is where we find an existing context if possible
ASSERT_LOCK_NOT_HELD(gContextLock);
LOCK(gContextLock);
pMatchingContext = CCtxTable::LookupExistingContext(pProtoContext);
// Release lock
UNLOCK(gContextLock);
ASSERT_LOCK_NOT_HELD(gContextLock);
if(NULL != pMatchingContext)
{
ComDebOut((DEB_ACTIVATE, "CApartmentActivator::ContextSelector found matching context %p [IN]\n", pMatchingContext));
// We found an existing context which matches the prototype context
// Discard the prototype context and use the existing context
// Lookup would have addrefed the context
pProtoContext->InternalRelease();
pProtoContext = pMatchingContext;
// Check if the client context is the same as the
// matched context
CObjectContext* pClientContext = NULL;
hr = pActIn->GetContextInfo()->GetInternalClientContext(&pClientContext);
if(SUCCEEDED(hr) && pClientContext)
{
if (pMatchingContext == pClientContext)
{
CObjectContext *pCurrentContext;
hr = PrivGetObjectContext(IID_IStdObjectContext,
(void **) &pCurrentContext);
Win4Assert(SUCCEEDED(hr));
// If the client context is the same as the
// matched context and current context
// then the current context is OK
if (pCurrentContext == pClientContext)
fCurrentContextOK = TRUE;
pCurrentContext->InternalRelease();
}
pClientContext->InternalRelease();
}
}
else
{
// Darn! We did not find an existing context matching the prototype
// context.
// Add the context to the hash table which will facilitate finding
// a matching context later
hr = CCtxTable::AddContext((CObjectContext *)pProtoContext);
}
}
}
}
if (FAILED(hr))
goto exit_point;
if(!fCurrentContextOK)
{
// Check to see if we are allowed to switch contexts
// for this requested class
IComClassInfo *pClassInfo = NULL;
//This does not need to be released
pClassInfo = pActIn->GetComClassInfo();
BOOL fCreateOnlyInCC=FALSE;
hr = pClassInfo->MustRunInClientContext(&fCreateOnlyInCC);
if (SUCCEEDED(hr) && fCreateOnlyInCC)
{
pProtoContext->InternalRelease();
hr = CO_E_ATTEMPT_TO_CREATE_OUTSIDE_CLIENT_CONTEXT;
goto exit_point;
}
pContext = pProtoContext;
}
else
{
// get rid of our reference to pProtoContext if we have one
if (pProtoContext) pProtoContext->InternalRelease();
}
}
exit_point:
// at this point we own a reference to pContext if it is not NULL
ComDebOut((DEB_ACTIVATE, "CApartmentActivator::ContextMaker [OUT] hr:%x\n", hr));
return hr;
}
//+--------------------------------------------------------------------------
//
// Member: CApartmentActivator::ContextCallHelper , private
//
// Synopsis:
//
// History: 06-Mar-98 SatishT Created
//
//----------------------------------------------------------------------------
STDMETHODIMP CApartmentActivator::ContextCallHelper(
IN IActivationPropertiesIn *pInActProperties,
OUT IActivationPropertiesOut **ppOutActProperties,
PFNCTXCALLBACK pfnCtxCallBack,
CObjectContext *pContext)
{
ComDebOut((DEB_ACTIVATE, "CApartmentActivator::ContextCallHelper [IN]\n"));
HRESULT hr = E_FAIL;
HRESULT hrSave = E_FAIL;
// Must use new since there is a constructor/destructor for one of the fields
ServerContextWorkData *pServerContextWorkData = new ServerContextWorkData;
if ( pServerContextWorkData == NULL )
{
hr = E_OUTOFMEMORY;
}
else
{
pServerContextWorkData->pInActProps = pInActProperties;
// Get inside the server context, do the work and get out with marshalled
// out activation properties -- the function parameter does CGCO or CCI
hr = hrSave = pContext->DoCallback(pfnCtxCallBack,
pServerContextWorkData,
IID_ISystemActivator,
0
);
}
// Our reference should now be released
pContext->InternalRelease();
if ( SUCCEEDED(hr) )
{
IStream *pStream = &pServerContextWorkData->xrpcOutProps;
// reset the stream to the beginning before unmarshalling
LARGE_INTEGER lSeekStart;
lSeekStart.LowPart = 0;
lSeekStart.HighPart = 0;
hr = pStream->Seek(lSeekStart, STREAM_SEEK_SET, NULL);
CHECK_HRESULT(hr);
hr = CoUnmarshalInterface(
pStream,
IID_IActivationPropertiesOut,
(LPVOID*) ppOutActProperties
);
}
if ( pServerContextWorkData != NULL)
{
delete pServerContextWorkData;
}
ComDebOut((DEB_ACTIVATE, "CApartmentActivator::ContextCallHelper [OUT] hr:%x\n", hr));
if (SUCCEEDED(hr))
{
Win4Assert(SUCCEEDED(hrSave));
if (*ppOutActProperties)
{
CHECKREFCOUNT(*ppOutActProperties,1);
}
return hrSave;
}
else
{
return hr;
}
}
//+-------------------------------------------------------------------------
//
// Implementation of callback functions for server context activation.
//
//+-------------------------------------------------------------------------
HRESULT __stdcall DoServerContextGCO(void *pv)
{
ServerContextWorkData *pData = (ServerContextWorkData*) pv;
IActivationPropertiesOut *pOutActProperties = NULL;
HRESULT hrSave;
HRESULT hr = hrSave = pData->pInActProps->DelegateGetClassObject(&pOutActProperties);
if ( SUCCEEDED(hr) )
{
hr = CoMarshalInterface(&pData->xrpcOutProps,
IID_IActivationPropertiesOut,
(IUnknown*)pOutActProperties,
MSHCTX_CROSSCTX,
NULL,
MSHLFLAGS_NORMAL);
}
// the ref is now in the marshalled packet if we had anything useful
if (pOutActProperties) pOutActProperties->Release();
if (SUCCEEDED(hr))
{
Win4Assert(SUCCEEDED(hrSave));
return hrSave;
}
else
{
return hr;
}
}
HRESULT __stdcall DoServerContextCCI(void *pv)
{
ServerContextWorkData *pData = (ServerContextWorkData*) pv;
IActivationPropertiesOut *pOutActProperties = NULL;
// Code to prevent cross-context aggregation is in CServerContextActivator::CreateInstance
HRESULT hrSave;
HRESULT hr = hrSave = pData->pInActProps->DelegateCreateInstance(NULL,&pOutActProperties);
if(SUCCEEDED(hr))
{
hr = CoMarshalInterface(&pData->xrpcOutProps,
IID_IActivationPropertiesOut,
(IUnknown*)pOutActProperties,
MSHCTX_CROSSCTX,
NULL,
MSHLFLAGS_NORMAL);
}
// the ref is now in the marshalled packet if we had anything useful
if (pOutActProperties) pOutActProperties->Release();
if (SUCCEEDED(hr))
{
Win4Assert(SUCCEEDED(hrSave));
return hrSave;
}
else
{
return hr;
}
}
//+--------------------------------------------------------------------------
//
// Member: CApartmentActivator::GetClassObject , public
//
// Synopsis:
//
// History: 06-Mar-98 SatishT Created
//
//----------------------------------------------------------------------------
STDMETHODIMP CApartmentActivator::GetClassObject(
IN IActivationPropertiesIn *pInActProperties,
OUT IActivationPropertiesOut **ppOutActProperties)
{
ComDebOut((DEB_ACTIVATE, "CApartmentActivator::GetClassObject [IN]\n"));
CObjectContext *pContext = NULL;
BOOL fCurrentContextOK = FALSE;
Win4Assert(NULL == *ppOutActProperties);
HRESULT hr = ContextSelector(
pInActProperties,
fCurrentContextOK,
pContext
);
if ( SUCCEEDED(hr) )
{
if (fCurrentContextOK)
{
Win4Assert(pContext == NULL);
// we are instantiating in the current context, so just delegate
hr = pInActProperties->DelegateGetClassObject(ppOutActProperties);
}
else
{
hr = ContextCallHelper(
pInActProperties,
ppOutActProperties,
DoServerContextGCO,
pContext
);
}
}
if (*ppOutActProperties)
{
CHECKREFCOUNT(*ppOutActProperties,1);
}
ComDebOut((DEB_ACTIVATE, "CApartmentActivator::GetClassObject [OUT] hr:%x\n", hr));
return hr;
}
STDAPI CoGetDefaultContext(APTTYPE aptType, REFIID riid, void** ppv);
//+--------------------------------------------------------------------------
//
// Member: CApartmentActivator::CreateInstance , public
//
// Synopsis:
//
// History: 06-Mar-98 SatishT Created
//
//----------------------------------------------------------------------------
STDMETHODIMP CApartmentActivator::CreateInstance(
IN IUnknown *pUnkOuter,
IN IActivationPropertiesIn *pInActProperties,
OUT IActivationPropertiesOut **ppOutActProperties)
{
ComDebOut((DEB_ACTIVATE, "CApartmentActivator::GetClassObject [IN]\n"));
Win4Assert(NULL == *ppOutActProperties);
// First, handle MustRunInDefaultContext property. This must be done
// here as it requires knowledge of object's intended apartment.
// COM Services doesn't have such knowledge, Stage-5 activators execute
// AFTER the target context is selected, so this is only logical...
IComClassInfo2 *pClassInfo2 = NULL;
HRESULT hr = pInActProperties->GetClassInfo(IID_IComClassInfo2, (void**) &pClassInfo2);
if(SUCCEEDED(hr))
{
BOOL bMustRunInDefaultContext = FALSE;
hr = pClassInfo2->MustRunInDefaultContext(&bMustRunInDefaultContext);
pClassInfo2->Release();
if(SUCCEEDED(hr) && bMustRunInDefaultContext)
{
IGetContextId *pGetCtxtId = NULL;
IOverrideTargetContext *pOverride = NULL;
GUID ctxtId;
hr = CoGetDefaultContext(APTTYPE_CURRENT, IID_IGetContextId, (void**) &pGetCtxtId);
if(FAILED(hr)) goto exit;
hr = pGetCtxtId->GetContextId(&ctxtId);
pGetCtxtId->Release();
if(FAILED(hr)) goto exit;
hr = pInActProperties->QueryInterface(IID_IOverrideTargetContext, (void**) &pOverride);
if(FAILED(hr)) goto exit;
pOverride->OverrideTargetContext(ctxtId);
pOverride->Release();
}
}
// Then go about our other business...
CObjectContext *pContext;
BOOL fCurrentContextOK;
pContext = NULL;
fCurrentContextOK = FALSE;
hr = ContextSelector(
pInActProperties,
fCurrentContextOK,
pContext
);
if ( SUCCEEDED(hr) )
{
if (fCurrentContextOK)
{
Win4Assert(pContext == NULL);
// we are instantiating in the current context, so just delegate
hr = pInActProperties->DelegateCreateInstance(pUnkOuter,ppOutActProperties);
}
else
{
hr = ContextCallHelper(
pInActProperties,
ppOutActProperties,
DoServerContextCCI,
pContext
);
}
}
if (*ppOutActProperties)
{
CHECKREFCOUNT(*ppOutActProperties,1);
}
exit:
ComDebOut((DEB_ACTIVATE, "CApartmentActivator::CreateInstance [OUT] hr:%x\n", hr));
return hr;
}
//+-------------------------------------------------------------------------
//
// Helpers related to the activator architecture.
//
//+-------------------------------------------------------------------------
//+-------------------------------------------------------------------------
//
// Helper to register apartment activator for current apartment.
// Do the registration only if the current apartment is unregistered.
//
//+-------------------------------------------------------------------------
HRESULT RegisterApartmentActivator(HActivator &hActivator)
{
CURRENT_CONTEXT_EMPTY // don't do this in a non-default context
HRESULT hr = E_FAIL;
HAPT hApt = GetCurrentApartmentId();
ApartmentEntry *pEntry = gApartmentTbl.Lookup(hApt);
if (NULL == pEntry) // the expected case
{
hr = gApartmentTbl.AddEntry(hApt,hActivator);
}
else
{
Win4Assert(0 && "RegisterApartmentActivator found existing entry");
}
return hr;
}
//+-------------------------------------------------------------------------
//
// Helper to revoke apartment activator for current apartment.
// Used in cleanup in CDllHost.
//
//+-------------------------------------------------------------------------
HRESULT RevokeApartmentActivator()
{
HRESULT hr = S_OK;
HAPT hApt = GetCurrentApartmentId();
ApartmentEntry *pEntry = gApartmentTbl.Lookup(hApt);
if (pEntry == NULL)
{
hr = E_FAIL;
}
else
{
// This call will delete the pEntry memory
hr = gApartmentTbl.ReleaseEntry(pEntry);
}
return hr;
}
// CODEWORK: These aren't the most efficient ways to do this -- we should switch
// over to agile proxies as in the previous DllHost code ASAP
//+-------------------------------------------------------------------------
//
// Helper to find or create apartment activator for current apartment.
//
//+-------------------------------------------------------------------------
HRESULT GetCurrentApartmentToken(HActivator &hActivator, BOOL fCreate)
{
HRESULT hr = E_FAIL;
HAPT hApt = GetCurrentApartmentId();
ApartmentEntry *pEntry = gApartmentTbl.Lookup(hApt);
if (NULL != pEntry) // Previously registered
{
hActivator = pEntry->hActivator;
hr = S_OK;
}
else if(fCreate) // Not yet registered
{
hr = RegisterApartmentActivator(hActivator);
}
return hr;
}
//+-------------------------------------------------------------------------
//
// Globals related to the activator architecture.
//
//+-------------------------------------------------------------------------
// The One and Only Client Context Standard Activator
CClientContextActivator gComClientCtxActivator;
// The One and Only Process Standard Activator
CProcessActivator gComProcessActivator;
// The One and Only Server Context Standard Activator
CServerContextActivator gComServerCtxActivator;
// The One and Only Apartment Activator
CApartmentActivator gApartmentActivator;
//+-------------------------------------------------------------------------
//
// Helper to find the end of delegation chain at each activation stage.
//
//+-------------------------------------------------------------------------
ISystemActivator *GetComActivatorForStage(ACTIVATION_STAGE stage)
{
switch (stage)
{
case CLIENT_CONTEXT_STAGE:
return gComClientCtxActivator.GetSystemActivator();
case CLIENT_MACHINE_STAGE:
Win4Assert(0 && "CLIENT_MACHINE_STAGE reached in OLE32");
return NULL;
case SERVER_MACHINE_STAGE:
Win4Assert(0 && "SERVER_MACHINE_STAGE reached in OLE32");
return NULL;
case SERVER_PROCESS_STAGE:
return gComProcessActivator.GetSystemActivator();
case SERVER_CONTEXT_STAGE:
return gComServerCtxActivator.GetSystemActivator();
default:
Win4Assert(0 && "Default reached in GetComActivatorForStage");
return NULL;
}
}
//+-------------------------------------------------------------------------
//
// Helper to check if a context is empty/default.
//
//+-------------------------------------------------------------------------
BOOL IsEmptyContext(CObjectContext *pContext)
{
Win4Assert(pContext && "IsEmptyContext called with NULL context");
BOOL fResult = pContext->GetCount() == 0;
return fResult;
}
//+------------------------------------------------------------------------
//
// Implementations of CApartmentHashTable methods
//
//+------------------------------------------------------------------------
//+--------------------------------------------------------------------------
//
// Member: CApartmentHashTable::AddEntry , public
//
// Synopsis: Register a new apartment activator in the global table.
//
// History: 28-Feb-98 SatishT Created
//
//----------------------------------------------------------------------------
HRESULT CApartmentHashTable::AddEntry(HAPT hApt, HActivator &hActivator)
{
ASSERT_LOCK_NOT_HELD(_mxsAptTblLock);
DWORD dwAAmshlflags = MSHLFLAGS_TABLESTRONG | MSHLFLAGS_AGILE | MSHLFLAGS_NOPING;
HRESULT hr = RegisterInterfaceInStdGlobal((IUnknown*)&gApartmentActivator,
IID_ISystemActivator,
dwAAmshlflags,
&hActivator);
if (SUCCEEDED(hr))
{
ApartmentEntry *pApartmentEntry = new ApartmentEntry;
if ( pApartmentEntry == NULL )
{
hr = E_OUTOFMEMORY;
}
else
{
pApartmentEntry->hActivator = hActivator;
ASSERT_LOCK_NOT_HELD(_mxsAptTblLock);
LOCK(_mxsAptTblLock);
_hashtbl.Add(hApt, hApt, &pApartmentEntry->node);
UNLOCK(_mxsAptTblLock);
ASSERT_LOCK_NOT_HELD(_mxsAptTblLock);
}
}
ASSERT_LOCK_NOT_HELD(_mxsAptTblLock);
return hr;
}
//+--------------------------------------------------------------------------
//
// Member: CApartmentHashTable::Lookup , public
//
// Synopsis: Lookup an apartment activator in the global table,
// given the current apartment ID.
//
// History: 28-Feb-98 SatishT Created
//
//----------------------------------------------------------------------------
ApartmentEntry *CApartmentHashTable::Lookup(HAPT hApt)
{
ASSERT_LOCK_NOT_HELD(_mxsAptTblLock);
LOCK(_mxsAptTblLock);
ApartmentEntry *pResult = (ApartmentEntry*) _hashtbl.Lookup(hApt, hApt);
UNLOCK(_mxsAptTblLock);
ASSERT_LOCK_NOT_HELD(_mxsAptTblLock);
return pResult;
}
//+--------------------------------------------------------------------------
//
// Member: CApartmentHashTable::ReleaseEntry , public
//
// Synopsis: Remove an apartment's entry in the global table,
// given the entry itself.
//
// History: 28-Feb-98 SatishT Created
//
//----------------------------------------------------------------------------
HRESULT CApartmentHashTable::ReleaseEntry(ApartmentEntry *pEntry)
{
ASSERT_LOCK_NOT_HELD(_mxsAptTblLock);
HRESULT hr = RevokeInterfaceFromStdGlobal(pEntry->hActivator);
ASSERT_LOCK_NOT_HELD(_mxsAptTblLock);
LOCK(_mxsAptTblLock);
_hashtbl.Remove(&pEntry->node.chain);
UNLOCK(_mxsAptTblLock);
ASSERT_LOCK_NOT_HELD(_mxsAptTblLock);
delete pEntry;
return hr;
}
// This is defined in ..\com\dcomrem\hash.cxx
void DummyCleanup( SHashChain *pIgnore );
//+--------------------------------------------------------------------------
//
// Member: CApartmentHashTable::Cleanup , public
//
// Synopsis: Remove an apartment's entry in the global table,
// given the entry itself.
//
// History: 28-Feb-98 SatishT Created
//
//----------------------------------------------------------------------------
void CApartmentHashTable::Cleanup()
{
ASSERT_LOCK_NOT_HELD(_mxsAptTblLock);
LOCK(_mxsAptTblLock);
if(_fTableInitialized){
_hashtbl.Cleanup(DummyCleanup);
}
UNLOCK(_mxsAptTblLock);
ASSERT_LOCK_NOT_HELD(_mxsAptTblLock);
}
//+--------------------------------------------------------------------------
//
// Member: ActivationThreadCleanup, public
//
// Synopsis: This routine is called when an apartment is being uninitialized
// It should cleanup per apartment structures
//
// History: 07-Mar-98 Gopalk Created
//
//----------------------------------------------------------------------------
void ActivationAptCleanup()
{
// Delete ObjServer
ObjactThreadUninitialize();
// Revoke apartment activator
RevokeApartmentActivator();
return;
}
//+--------------------------------------------------------------------------
//
// Member: ActivationProcessCleanup, public
//
// Synopsis: This routine is called when an process is being uninitialized
// It should cleanup per process structures
//
// History: 07-Mar-98 Gopalk Created
//
//----------------------------------------------------------------------------
void ActivationProcessCleanup()
{
// Cleanup apartment table
gApartmentTbl.Cleanup();
return;
}
//+--------------------------------------------------------------------------
//
// Member: ActivationProcessInit, public
//
// Synopsis: This routine is called when an process is being initialized
// It should initialize per process structures
//
// History: 07-Mar-98 Gopalk Created
//
//----------------------------------------------------------------------------
HRESULT ActivationProcessInit()
{
HRESULT hr = S_OK;
// Initialize apartment table
gApartmentTbl.Initialize();
return hr;
}
//+--------------------------------------------------------------------------
//
// Member: LoadPersistentObject, public
//
// Synopsis:
//
// History: 18-Mar-98 Vinaykr Created
//
//----------------------------------------------------------------------------
HRESULT LoadPersistentObject(
IUnknown *pobj,
IInstanceInfo *pInstanceInfo)
{
HRESULT hr = E_FAIL;
XIPersistStorage xipstg;
XIPersistFile xipfile;
IStorage *pstg;
hr = pInstanceInfo->GetStorage(&pstg);
if (FAILED(hr))
return hr;
// First check if storage is requested
if (pstg)
{
// Load the storage requested as a template
if ((hr = pobj->QueryInterface(IID_IPersistStorage, (void **) &xipstg))
== S_OK)
{
hr = xipstg->Load(pstg);
}
pstg->Release();
}
else // check for File
{
DWORD mode;
WCHAR *path;
pInstanceInfo->GetFile(&path, &mode);
if ((hr = pobj->QueryInterface(IID_IPersistFile, (void **) &xipfile))
== S_OK)
{
hr = xipfile->Load(path, mode);
}
}
return hr;
}
| 33.969187 | 142 | 0.501312 | [
"object"
] |
6a52525818b16318b8f526bf5b1e56ebe4baed4c | 3,621 | cpp | C++ | soapy/src/test/test_air_packet_7.cpp | siglabsoss/s-modem | 0a259b4f3207dd043c198b76a4bc18c8529bcf44 | [
"BSD-3-Clause"
] | null | null | null | soapy/src/test/test_air_packet_7.cpp | siglabsoss/s-modem | 0a259b4f3207dd043c198b76a4bc18c8529bcf44 | [
"BSD-3-Clause"
] | null | null | null | soapy/src/test/test_air_packet_7.cpp | siglabsoss/s-modem | 0a259b4f3207dd043c198b76a4bc18c8529bcf44 | [
"BSD-3-Clause"
] | null | null | null | #include <rapidcheck.h>
#include <vector>
#include <algorithm>
#include <iostream>
#include <iomanip>
#include "cpp_utils.hpp"
#include "driver/AirPacket.hpp"
#include "schifra_galois_field.hpp"
#include "schifra_galois_field_polynomial.hpp"
#include "schifra_sequential_root_generator_polynomial_creator.hpp"
#include "schifra_reed_solomon_encoder.hpp"
#include "schifra_reed_solomon_decoder.hpp"
#include "schifra_error_processes.hpp"
#include "FileUtils.hpp"
#include "VerifyHash.hpp"
#include "convert.hpp"
using namespace std;
using namespace siglabs::file;
// #include "driver/ReedSolomon.hpp"
size_t transform_words_128(size_t in) {
constexpr size_t enabled_subcarriers = 8;
size_t div = in/enabled_subcarriers;
size_t sub = (2*enabled_subcarriers)*div+(enabled_subcarriers-1);
return sub - in;
}
unsigned bit_set(uint32_t v) {
unsigned int c; // c accumulates the total bits set in v
for (c = 0; v; c++)
{
v &= v - 1; // clear the least significant bit set
}
return c;
}
bool category_1(void) {
bool pass = true;
pass &= rc::check("check pack unpack header", []() {
AirPacket ap;
const unsigned length = *rc::gen::inRange(0, 0xfffff+1);
const unsigned seq = *rc::gen::inRange(0, 0xff+1);
const unsigned flags = *rc::gen::inRange(0, 0xf+1);
auto p1 = AirPacket::packHeader(length, seq, flags);
auto unp1 = AirPacket::unpackHeader(p1);
RC_ASSERT( std::get<0>(unp1) == length );
RC_ASSERT( std::get<1>(unp1) == seq );
RC_ASSERT( std::get<2>(unp1) == flags );
});
pass &= rc::check("check one bit flip", [](const uint32_t start_word) {
std::vector<uint32_t> tun_packet;
std::vector<uint32_t> tun_packet2;
for(uint32_t i = 0; i < 1024; i++) {
tun_packet.push_back (start_word | i);
tun_packet2.push_back(start_word | i);
}
const unsigned pick = *rc::gen::inRange(0, 1024);
const unsigned bit = *rc::gen::inRange(0, 32);
uint32_t overwrite = tun_packet2[pick] | (0x00000001 << bit);
// force that we are changing a bit (We are lazy here)
RC_PRE(overwrite != tun_packet2[pick]);
// overwrite
tun_packet2[pick] = overwrite;
std::vector<uint32_t> transformed;
std::vector<uint32_t> transformed2;
new_subcarrier_data_load(transformed, tun_packet, 128);
new_subcarrier_data_load(transformed2, tun_packet2, 128);
unsigned c1 = 0;
for(auto x : tun_packet ) {
c1 += bit_set(x);
}
unsigned c2 = 0;
for(auto x : tun_packet2 ) {
c2 += bit_set(x);
}
unsigned c3 = 0;
for(auto x : transformed ) {
c3 += bit_set(x);
}
unsigned c4 = 0;
for(auto x : transformed2 ) {
c4 += bit_set(x);
}
RC_ASSERT(c1+1 == c2);
// cout << c2 - c1 << endl;
RC_ASSERT(c1 == c3);
RC_ASSERT(c2 == c4);
});
return pass;
}
int main() {
bool pass = true;
// pass &= rc::check("Testing Demod recovery when RS block fails", [&]() {
// });
pass &= rc::check("compare transforms", [](unsigned din) {
// AirPacket ap;
TransformWords128 tt;
// std::pair<bool, unsigned>
auto rett = tt.t(din);
// is valid?
RC_ASSERT(rett.first == true);
RC_ASSERT(rett.second == transform_words_128(din));
});
pass &= category_1();
return !pass;
// foo();
} | 22.079268 | 79 | 0.586854 | [
"vector"
] |
6a526c6f51b26f3c1b78f36d67a11c62d238ab1b | 7,961 | cc | C++ | chainerx_cc/chainerx/backward_builder_test.cc | zaltoprofen/chainer | 3b03f9afc80fd67f65d5e0395ef199e9506b6ee1 | [
"MIT"
] | 3,705 | 2017-06-01T07:36:12.000Z | 2022-03-30T10:46:15.000Z | chainerx_cc/chainerx/backward_builder_test.cc | zaltoprofen/chainer | 3b03f9afc80fd67f65d5e0395ef199e9506b6ee1 | [
"MIT"
] | 5,998 | 2017-06-01T06:40:17.000Z | 2022-03-08T01:42:44.000Z | chainerx_cc/chainerx/backward_builder_test.cc | zaltoprofen/chainer | 3b03f9afc80fd67f65d5e0395ef199e9506b6ee1 | [
"MIT"
] | 1,150 | 2017-06-02T03:39:46.000Z | 2022-03-29T02:29:32.000Z | #include "chainerx/backward_builder.h"
#include <utility>
#include <gtest/gtest.h>
#include "chainerx/array.h"
#include "chainerx/backward.h"
#include "chainerx/backward_context.h"
#include "chainerx/dtype.h"
#include "chainerx/macro.h"
#include "chainerx/routines/creation.h"
#include "chainerx/shape.h"
#include "chainerx/testing/array.h"
#include "chainerx/testing/array_check.h"
#include "chainerx/testing/context_session.h"
// TODO(niboshi): Move test cases related to BackwardBuilder to this file (from backward_test.cc).
namespace chainerx {
namespace {
TEST(BackwardBuilderTest, FloatToInt_NotBackproppable) {
testing::ContextSession context_session;
auto forward = [](const Array& x, Array& y1, Array& y2) {
y1 = Ones({2, 3}, Dtype::kInt32, x.device());
y2 = Ones({2, 3}, Dtype::kInt32, x.device());
BackwardBuilder bb{"forward", x, {y1, y2}};
BackwardBuilder::Target bt = bb.CreateTarget();
EXPECT_FALSE(static_cast<bool>(bt));
bb.Finalize();
};
Array x = Ones({2, 3}, Dtype::kFloat32).RequireGrad();
Array y1{};
Array y2{};
forward(x, y1, y2);
EXPECT_FALSE(y1.IsBackpropRequired());
EXPECT_FALSE(y2.IsBackpropRequired());
}
TEST(BackwardBuilderTest, FloatToInt_PartiallyBackproppable) {
testing::ContextSession context_session;
auto forward = [](const Array& x, Array& y1, Array& y2) {
y1 = Ones({2, 3}, Dtype::kInt32, x.device());
y2 = Ones({2, 3}, Dtype::kFloat32, x.device());
BackwardBuilder bb{"forward", x, {y1, y2}};
BackwardBuilder::Target bt = bb.CreateTarget();
EXPECT_TRUE(static_cast<bool>(bt));
bt.Define([](BackwardContext& bctx) {
EXPECT_EQ(bctx.input_count(), 1U);
EXPECT_EQ(bctx.output_count(), 2U);
bctx.input_grad() = *bctx.output_grad(1);
});
bb.Finalize();
};
Array x = Ones({2, 3}, Dtype::kFloat32).RequireGrad();
Array y1{};
Array y2{};
forward(x, y1, y2);
EXPECT_FALSE(y1.IsBackpropRequired());
EXPECT_TRUE(y2.IsBackpropRequired());
Backward(y2);
}
TEST(BackwardBuilderTest, FloatToInt_GetIntRetainOutputFirstParam) {
testing::ContextSession context_session;
Shape shape{2, 3};
auto forward = [shape](const Array& x, Array& y1, Array& y2) {
y1 = testing::BuildArray(shape).WithData<int32_t>({1, 2, 3, 4, 5, 6});
y2 = testing::BuildArray(shape).WithData<float>({7, 8, 9, 10, 11, 12});
BackwardBuilder bb{"forward", x, {y1, y2}};
BackwardBuilder::Target bt = bb.CreateTarget();
EXPECT_TRUE(static_cast<bool>(bt));
bt.Define([out_tok = bb.RetainOutput(0)](BackwardContext& bctx) {
const absl::optional<Array>& y1 = bctx.GetRetainedOutput(out_tok);
ASSERT_FALSE(bctx.output_grad(0).has_value());
ASSERT_TRUE(bctx.output_grad(1).has_value());
EXPECT_TRUE(y1.has_value());
bctx.input_grad() = *bctx.output_grad(1) * y1->AsType(Dtype::kFloat32);
});
bb.Finalize();
};
Array x = Ones(shape, Dtype::kFloat32).RequireGrad();
Array e = testing::BuildArray(shape).WithData<float>({4, 10, 18, 28, 40, 54});
Array y1{};
Array y2{};
forward(x, y1, y2);
EXPECT_FALSE(y1.IsBackpropRequired());
EXPECT_TRUE(y2.IsBackpropRequired());
y2.SetGrad(testing::BuildArray(shape).WithData<float>({4, 5, 6, 7, 8, 9}));
Backward(y2);
EXPECT_TRUE(x.GetGrad().has_value());
EXPECT_ARRAY_EQ(e, *x.GetGrad());
}
TEST(BackwardBuilderTest, FloatToInt_GetIntRetainOutputSecondParam) {
testing::ContextSession context_session;
Shape shape{2, 3};
auto forward = [shape](const Array& x, Array& y1, Array& y2) {
y1 = testing::BuildArray(shape).WithData<float>({1, 2, 3, 4, 5, 6});
y2 = testing::BuildArray(shape).WithData<int32_t>({7, 8, 9, 10, 11, 12});
BackwardBuilder bb{"forward", x, {y1, y2}};
BackwardBuilder::Target bt = bb.CreateTarget();
EXPECT_TRUE(static_cast<bool>(bt));
bt.Define([out_tok = bb.RetainOutput(1)](BackwardContext& bctx) {
const absl::optional<Array>& y2 = bctx.GetRetainedOutput(out_tok);
ASSERT_TRUE(bctx.output_grad(0).has_value());
ASSERT_FALSE(bctx.output_grad(1).has_value());
EXPECT_TRUE(y2.has_value());
bctx.input_grad() = *bctx.output_grad(0) * y2->AsType(Dtype::kFloat32);
});
bb.Finalize();
};
Array x = Ones(shape, Dtype::kFloat32).RequireGrad();
Array e = testing::BuildArray(shape).WithData<float>({28, 40, 54, 70, 88, 108});
Array y1{};
Array y2{};
forward(x, y1, y2);
EXPECT_TRUE(y1.IsBackpropRequired());
EXPECT_FALSE(y2.IsBackpropRequired());
y1.SetGrad(testing::BuildArray(shape).WithData<float>({4, 5, 6, 7, 8, 9}));
Backward(y1);
EXPECT_TRUE(x.GetGrad().has_value());
EXPECT_ARRAY_EQ(e, *x.GetGrad());
}
TEST(BackwardBuilderTest, FloatToInt_GetIntRetainOutputArrayBodyIsGone) {
testing::ContextSession context_session;
Shape shape{2, 3};
auto forward = [shape](const Array& x, Array& y1, Array& y2) {
y1 = testing::BuildArray(shape).WithData<float>({1, 2, 3, 4, 5, 6});
y2 = testing::BuildArray(shape).WithData<int32_t>({7, 8, 9, 10, 11, 12});
BackwardBuilder bb{"forward", x, {y1, y2}};
BackwardBuilder::Target bt = bb.CreateTarget();
EXPECT_TRUE(static_cast<bool>(bt));
bt.Define([out_tok = bb.RetainOutput(1)](BackwardContext& bctx) {
const absl::optional<Array>& y2 = bctx.GetRetainedOutput(out_tok);
ASSERT_TRUE(bctx.output_grad(0).has_value());
ASSERT_FALSE(bctx.output_grad(1).has_value());
EXPECT_TRUE(y2.has_value());
bctx.input_grad() = *bctx.output_grad(0) * y2->AsType(Dtype::kFloat32);
});
bb.Finalize();
};
Array x = Ones(shape, Dtype::kFloat32).RequireGrad();
Array e = testing::BuildArray(shape).WithData<float>({28, 40, 54, 70, 88, 108});
Array y1{};
Array z2{};
{
Array y2{};
forward(x, y1, y2);
EXPECT_TRUE(y1.IsBackpropRequired());
EXPECT_FALSE(y2.IsBackpropRequired());
z2 = y2.MakeView();
}
y1.SetGrad(testing::BuildArray(shape).WithData<float>({4, 5, 6, 7, 8, 9}));
Backward(y1);
EXPECT_TRUE(x.GetGrad().has_value());
EXPECT_ARRAY_EQ(e, *x.GetGrad());
}
TEST(BackwardBuilderTest, FloatToInt_GetIntRetainOutputArrayNodeIsGone) {
testing::ContextSession context_session;
Shape shape{2, 3};
auto forward = [shape](const Array& x, Array& y1, Array& y2) {
y1 = testing::BuildArray(shape).WithData<float>({1, 2, 3, 4, 5, 6});
y2 = testing::BuildArray(shape).WithData<int32_t>({7, 8, 9, 10, 11, 12});
BackwardBuilder bb{"forward", x, {y1, y2}};
BackwardBuilder::Target bt = bb.CreateTarget();
EXPECT_TRUE(static_cast<bool>(bt));
bt.Define([out_tok = bb.RetainOutput(1)](BackwardContext& bctx) {
const absl::optional<Array>& y2 = bctx.GetRetainedOutput(out_tok);
ASSERT_TRUE(bctx.output_grad(0).has_value());
ASSERT_FALSE(bctx.output_grad(1).has_value());
EXPECT_TRUE(y2.has_value());
bctx.input_grad() = *bctx.output_grad(0) * y2->AsType(Dtype::kFloat32);
});
bb.Finalize();
};
Array x = Ones(shape, Dtype::kFloat32).RequireGrad();
Array e = testing::BuildArray(shape).WithData<float>({28, 40, 54, 70, 88, 108});
Array y1{};
{
Array y2{};
forward(x, y1, y2);
EXPECT_TRUE(y1.IsBackpropRequired());
EXPECT_FALSE(y2.IsBackpropRequired());
}
y1.SetGrad(testing::BuildArray(shape).WithData<float>({4, 5, 6, 7, 8, 9}));
Backward(y1);
EXPECT_TRUE(x.GetGrad().has_value());
EXPECT_ARRAY_EQ(e, *x.GetGrad());
}
} // namespace
} // namespace chainerx
| 35.540179 | 98 | 0.625173 | [
"shape"
] |
6a58d0e6e3701bf9d31ad3dea385c97d84243cfa | 2,374 | cc | C++ | src/ufo/filters/obsfunctions/ObsErrorFactorTransmitTopRad.cc | rnt20/ufo | 68dab85486f5d79991956076ac6b962bc1a0c5bd | [
"Apache-2.0"
] | 1 | 2021-10-08T16:37:25.000Z | 2021-10-08T16:37:25.000Z | src/ufo/filters/obsfunctions/ObsErrorFactorTransmitTopRad.cc | rnt20/ufo | 68dab85486f5d79991956076ac6b962bc1a0c5bd | [
"Apache-2.0"
] | 9 | 2021-06-25T17:18:06.000Z | 2021-10-08T17:40:31.000Z | src/ufo/filters/obsfunctions/ObsErrorFactorTransmitTopRad.cc | rnt20/ufo | 68dab85486f5d79991956076ac6b962bc1a0c5bd | [
"Apache-2.0"
] | 31 | 2021-06-24T18:07:53.000Z | 2021-10-08T15:40:39.000Z | /*
* (C) Copyright 2019 UCAR
*
* This software is licensed under the terms of the Apache Licence Version 2.0
* which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
*/
#include "ufo/filters/obsfunctions/ObsErrorFactorTransmitTopRad.h"
#include <math.h>
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <set>
#include <string>
#include <vector>
#include "ioda/ObsDataVector.h"
#include "oops/util/IntSetParser.h"
#include "ufo/filters/Variable.h"
#include "ufo/utils/Constants.h"
namespace ufo {
static ObsFunctionMaker<ObsErrorFactorTransmitTopRad>
makerObsErrorFactorTransmitTopRad_("ObsErrorFactorTransmitTopRad");
// -----------------------------------------------------------------------------
ObsErrorFactorTransmitTopRad::ObsErrorFactorTransmitTopRad(const eckit::LocalConfiguration & conf)
: invars_() {
// Check options
options_.deserialize(conf);
// Get channels from options
std::set<int> channelset = oops::parseIntSet(options_.channelList);
std::copy(channelset.begin(), channelset.end(), std::back_inserter(channels_));
ASSERT(channels_.size() > 0);
// Include required variables from ObsDiag
invars_ += Variable("transmittances_of_atmosphere_layer@ObsDiag", channels_);
}
// -----------------------------------------------------------------------------
ObsErrorFactorTransmitTopRad::~ObsErrorFactorTransmitTopRad() {}
// -----------------------------------------------------------------------------
void ObsErrorFactorTransmitTopRad::compute(const ObsFilterData & in,
ioda::ObsDataVector<float> & out) const {
// Get dimensions
size_t nlocs = in.nlocs();
size_t nchans = channels_.size();
// Inflate obs error as a function of model top-to-spaec transmittance
std::vector<float> tao_top(nlocs);
for (size_t ich = 0; ich < nchans; ++ich) {
in.get(Variable("transmittances_of_atmosphere_layer@ObsDiag", channels_)[ich], 1, tao_top);
for (size_t iloc = 0; iloc < nlocs; ++iloc) {
out[ich][iloc] = sqrt(1.0 / tao_top[iloc]);
}
}
}
// -----------------------------------------------------------------------------
const ufo::Variables & ObsErrorFactorTransmitTopRad::requiredVariables() const {
return invars_;
}
// -----------------------------------------------------------------------------
} // namespace ufo
| 31.236842 | 98 | 0.600253 | [
"vector",
"model"
] |
6a5bcbbf39539fa4a14d1a32a85e0cc40393a343 | 6,573 | cpp | C++ | abp/Sound/BASSlib/BASS_TAGS/ORIGINAL/src/tags/keywords.cpp | pyrroman/au3-boilerplate | 596a3aa68d4d6b48dd79ed737d1e11604ac9e92f | [
"BSD-3-Clause"
] | 8 | 2019-07-02T15:59:30.000Z | 2021-07-13T05:13:43.000Z | abp/Sound/BASSlib/BASS_TAGS/ORIGINAL/src/tags/keywords.cpp | pyrroman/au3-boilerplate | 596a3aa68d4d6b48dd79ed737d1e11604ac9e92f | [
"BSD-3-Clause"
] | null | null | null | abp/Sound/BASSlib/BASS_TAGS/ORIGINAL/src/tags/keywords.cpp | pyrroman/au3-boilerplate | 596a3aa68d4d6b48dd79ed737d1e11604ac9e92f | [
"BSD-3-Clause"
] | 1 | 2019-07-02T15:59:31.000Z | 2019-07-02T15:59:31.000Z | //////////////////////////////////////////////////////////////////////////
//
// keywords.cpp - format string parser implementation
//
// Author: Wraith, 2k5-2k6
// Public domain. No warranty.
//
// (internal)
//
#include <string>
#include <vector>
#include <algorithm>
#include "simplemap.h"
#include "tags_impl.h"
#include "keywords.h"
#include <stdlib.h>
namespace parser
{
// a function, performing formatting operations like %IFV1()
typedef std::string (*keywordfunc)(sir& curr, sir last, tag_reader* reader );
// returns a formatting operation function by its name
keywordfunc get_keyword( const char* name );
namespace{
namespace err
{
const char* LP_EXP = "<***( expected! ***";
const char* CM_EXP = "<***, expected! ***";
const char* RP_EXP = "<***) expected! ***";
}
std::string trim( const std::string& str )
{
std::string ret;
if( str.empty() )
return ret;
std::string::const_iterator beg = str.begin();
std::string::const_iterator end = str.end()-1;
for(; *beg == ' ' && beg <= end; ++beg );
for(; *end == ' ' && beg <= end; --end );
ret.assign( beg, end+1 );
return ret;
}
//////////////////////////////////////////////////////////////////////////////////////
// keywords implementations...
std::string do_IFV1(sir& itor, sir last, tag_reader* reader )
{
if( *itor != '(' )
return err::LP_EXP;
++itor; // step through (
std::string x = expr( itor, last, reader );
if( *itor != ',' )
return err::CM_EXP;
++itor; // step through ,
std::string a = expr( itor, last, reader );
if( *itor != ')' )
return err::RP_EXP;
++itor; //
return x.empty() ? "" : a;
}
std::string do_IFV2(sir& itor, sir last, tag_reader* reader )
{
if( *itor != '(' )
return err::LP_EXP;
++itor; // step through (
std::string x = expr( itor, last, reader );
if( *itor != ',' )
return err::CM_EXP;
++itor; // step through first ,
std::string a = expr( itor, last, reader );
if( *itor != ',' )
return err::CM_EXP;
++itor; // step through second ,
std::string b = expr( itor, last, reader );
if( *itor != ')' )
return err::RP_EXP;
++itor; // step through )
return x.empty() ? b : a;
}
void _upc( char& t )
{
t = toupper(t);
}
void _lwc( char& t )
{
t = tolower(t);
}
// upcase
// %IUPC(foO) yields FOO
std::string do_IUPC(sir& itor, sir last, tag_reader* reader )
{
if( *itor != '(' )
return err::LP_EXP;
++itor; // step through (
std::string a = expr( itor, last, reader );
if( *itor !=')' )
return err::RP_EXP;
++itor; // step through )
// a hack here...
std::for_each( a.begin(), a.end(), _upc );
return a;
}
// lower case
// %ILWC(foO) yields foo
std::string do_ILWC(sir& itor, sir last, tag_reader* reader )
{
if( *itor != '(' )
return err::LP_EXP;
++itor;
std::string a = expr( itor, last, reader );
if( *itor !=')' )
return err::RP_EXP;
++itor;
std::for_each( a.begin(), a.end(), _lwc );
return a;
}
// capitalization:
// %ICAP(fOo) yields Foo
//
std::string do_ICAP(sir& itor, sir last, tag_reader* reader )
{
if( *itor != '(' )
return err::LP_EXP;
++itor;
std::string a = expr( itor, last, reader );
if( *itor !=')' )
return err::RP_EXP;
++itor;
for( std::string::iterator i = a.begin(); i!=a.end(); ++i )
(( i == a.begin() || !isalnum( *(i-1) ) ) ? _upc : _lwc )( *i );
return a;
}
// string trim
// %ITRM( fOo ) yields "fOo"
std::string do_ITRM(sir& itor, sir last, tag_reader* reader )
{
if( *itor != '(' )
return err::LP_EXP;
++itor;
std::string a = expr( itor, last, reader );
if( *itor !=')' )
return err::RP_EXP;
++itor;
return trim(a);
}
// UTF-8 string
// %UTF8(fOo) yields "fOo" in UTF-8 form
std::string do_UTF8(sir& itor, sir last, tag_reader* reader )
{
if( *itor != '(' )
return err::LP_EXP;
++itor;
reader->m_utf8++;
std::string a = expr( itor, last, reader );
reader->m_utf8--;
if( *itor !=')' )
return err::RP_EXP;
++itor;
return a;
}
}
std::string expr( sir& itor, sir last, tag_reader* reader ) throw()
{
std::string ret;
while( itor < last )
{
switch( *itor )
{
case '%':
{
++itor;
if( strchr("%(,)", *itor ) ) // special characters are escaped
{
ret += *itor++; break;
}
if( last < itor+4 )
{
ret += " < unexpected end-of-string.";
itor = last; // done with it
return ret;
}
std::string keyword( itor, itor+4 );
itor += 4; // and move the pointer
keywordfunc func = get_keyword( keyword.c_str() );
if( func )
ret += func( itor, last, reader );
else // can be a tag
{
try{
std::string tag = (*reader)[ keyword.c_str() ];
int p0=tag.find((char)0); // look for NULL...
if (p0>=0) tag.resize(p0); // and trim at it
int utf8=-1;
for (int a=0, b=0; a<tag.length(); a++) {
if (tag[a]&0x80) {
if (!(tag[a]&0x40)) {
if (b) {
b--;
continue;
}
utf8=0;
break;
}
if (b) break;
for (b=1; tag[a]&(0x40>>b); b++) ;
utf8=1;
} else if (b)
break;
}
if (b) utf8=0;
if (utf8>=0 && (!utf8^!reader->m_utf8)) { // needs converting
int n=MultiByteToWideChar(reader->m_utf8?CP_ACP:CP_UTF8, 0, &tag[0], -1, 0, 0);
std::vector< wchar_t > tmp( n+1 );
MultiByteToWideChar(reader->m_utf8?CP_ACP:CP_UTF8, 0, &tag[0], -1, &tmp[0], n+1);
ret += unicode_string(&tmp[0], !!reader->m_utf8);
} else
ret += tag;
}catch( const bad_ident& )
{
break; // just skip it
}
}
break;
}
case ',':
case ')':
return ret;
default:
ret += *itor++; // just let it in...
break;
}
}
return ret;
}
std::string unicode_string( const wchar_t *utext, bool utf8 )
{
int n=WideCharToMultiByte(utf8?CP_UTF8:CP_ACP, 0, utext, -1, 0, 0, 0, 0);
std::vector< char > text( n+1 );
WideCharToMultiByte(utf8?CP_UTF8:CP_ACP, 0, utext, -1, &text[0], n+1, 0, 0);
return std::string( &text[0] );
}
//////////////////////////////////////////////////////////////////////////////////
// available keywords
namespace
{
typedef tools::simplemap<const char*, keywordfunc, tools::cmp_sz > map_t;
typedef map_t::pair_type vpair;
vpair known_keywords [] =
{
vpair("IFV1", &do_IFV1),
vpair("IFV2", &do_IFV2),
vpair("IUPC", &do_IUPC),
vpair("ILWC", &do_ILWC),
vpair("ICAP", &do_ICAP),
vpair("ITRM", &do_ITRM),
vpair("UTF8", &do_UTF8)
};
map_t keyword_map(known_keywords, END_OF_ARRAY(known_keywords));
} // anon namespace
keywordfunc get_keyword( const char* name )
{
return keyword_map[name];
}
}
| 19.858006 | 88 | 0.54876 | [
"vector"
] |
6a654fc56d67ca15db26e0c676a2c93ec54b46ce | 5,870 | hpp | C++ | core/base/allocator.hpp | cho-uc/ginkgo | 8ec17e93c3fdf555edf6911fd145c0cf1c2914e9 | [
"BSD-3-Clause"
] | null | null | null | core/base/allocator.hpp | cho-uc/ginkgo | 8ec17e93c3fdf555edf6911fd145c0cf1c2914e9 | [
"BSD-3-Clause"
] | 1 | 2021-01-06T19:28:11.000Z | 2021-01-06T19:29:21.000Z | core/base/allocator.hpp | cho-uc/ginkgo | 8ec17e93c3fdf555edf6911fd145c0cf1c2914e9 | [
"BSD-3-Clause"
] | 1 | 2019-02-05T22:42:43.000Z | 2019-02-05T22:42:43.000Z | /*******************************<GINKGO LICENSE>******************************
Copyright (c) 2017-2020, the Ginkgo authors
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************<GINKGO LICENSE>*******************************/
#ifndef GKO_CORE_BASE_ALLOCATOR_HPP_
#define GKO_CORE_BASE_ALLOCATOR_HPP_
#include <map>
#include <memory>
#include <set>
#include <type_traits>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <ginkgo/core/base/executor.hpp>
namespace gko {
/**
* @internal
*
* C++ standard library-compatible allocator that uses an executor for
* allocations.
*
* @tparam T the type of the allocated elements.
*/
template <typename T>
class ExecutorAllocator {
public:
using value_type = T;
using propagate_on_container_copy_assignment = std::true_type;
using propagate_on_container_move_assignment = std::true_type;
using propagate_on_container_swap = std::true_type;
/**
* Constructs an allocator from a given executor.
*
* This function works with both const and non-const ExecType,
* as long as it is derived from gko::Executor.
* @param exec the executor
* @tparam ExecType the static type of the executor
*/
template <typename ExecType>
ExecutorAllocator(std::shared_ptr<ExecType> exec) : exec_{std::move(exec)}
{}
/**
* Constructs an allocator for another element type from a given executor.
*
* This is related to `std::allocator_traits::template rebind<U>` and its
* use in more advanced data structures.
*
* @param other the other executor
* @tparam U the element type of the allocator to be constructed.
*/
template <typename U>
ExecutorAllocator(const ExecutorAllocator<U> &other)
: exec_{other.get_executor()}
{}
/** Returns the executor used by this allocator. */
std::shared_ptr<const Executor> get_executor() const { return exec_; }
/**
* Allocates a memory area of the given size.
*
* @param n the number of elements to allocate
* @return the pointer to a newly allocated memory area of `n` elements.
*/
T *allocate(std::size_t n) const { return exec_->alloc<T>(n); }
/**
* Frees a memory area that was allocated by this allocator.
*
* @param ptr The memory area to free, previously returned by `allocate`.
*
* @note The second parameter is unused.
*/
void deallocate(T *ptr, std::size_t) const { exec_->free(ptr); }
/**
* Compares two ExecutorAllocators for equality
*
* @param l the first allocator
* @param r the second allocator
* @return true iff the two allocators use the same executor
*/
template <typename T2>
friend bool operator==(const ExecutorAllocator<T> &l,
const ExecutorAllocator<T2> &r)
{
return l.get_executor() == r.get_executor();
}
/**
* Compares two ExecutorAllocators for inequality
*
* @param l the first allocator
* @param r the second allocator
* @return true iff the two allocators use different executors
*/
template <typename T2>
friend bool operator!=(const ExecutorAllocator<T> &l,
const ExecutorAllocator<T2> &r)
{
return !(l == r);
}
private:
std::shared_ptr<const Executor> exec_;
};
// Convenience type aliases
/** std::vector using an ExecutorAllocator. */
template <typename T>
using vector = std::vector<T, ExecutorAllocator<T>>;
/** std::set using an ExecutorAllocator. */
template <typename Key>
using set = std::set<Key, std::less<Key>, gko::ExecutorAllocator<Key>>;
/** std::map using an ExecutorAllocator. */
template <typename Key, typename Value>
using map = std::map<Key, Value, std::less<Key>,
gko::ExecutorAllocator<std::pair<const Key, Value>>>;
/** std::unordered_set using an ExecutorAllocator. */
template <typename Key>
using unordered_set =
std::unordered_set<Key, std::hash<Key>, std::equal_to<Key>,
gko::ExecutorAllocator<Key>>;
/** std::unordered_map using an ExecutorAllocator. */
template <typename Key, typename Value>
using unordered_map =
std::unordered_map<Key, Value, std::hash<Key>, std::equal_to<Key>,
gko::ExecutorAllocator<std::pair<const Key, Value>>>;
} // namespace gko
#endif // GKO_CORE_BASE_ALLOCATOR_HPP_
| 33.352273 | 78 | 0.685179 | [
"vector"
] |
6a6b0cceaff1e286ab204fb0a81ad8d62aa99f76 | 471 | cc | C++ | 3_MoreBasics/Casting.cc | p62jired/UdemyC | 306abc808e90027b33cc9592bc973511028047cd | [
"MIT"
] | null | null | null | 3_MoreBasics/Casting.cc | p62jired/UdemyC | 306abc808e90027b33cc9592bc973511028047cd | [
"MIT"
] | null | null | null | 3_MoreBasics/Casting.cc | p62jired/UdemyC | 306abc808e90027b33cc9592bc973511028047cd | [
"MIT"
] | null | null | null | #include <iomanip>
#include <iostream>
// 1a. C++: static_cast<newDtype>(varName) - converts object from one type to another
// 1b. C: (newDtytpe)(varName)
int main()
{
double number = 3.13;
std::cout << std::setprecision(30) << number << std::endl;
int number2 = number;
std::cout << number2 << std::endl;
//C++ Casting:
float number5 = static_cast<float>(number);
std::cout << std::setprecision(30) << number5 << std::endl;
return 0;
}
| 27.705882 | 85 | 0.624204 | [
"object"
] |
6a6c756125d23de4917184c6c72c70122b47a3b2 | 3,210 | cpp | C++ | src/mzIMLTools/CModification.cpp | mrchipset/MyMSToolKit | 70c5a7c5a2f914b676bdd630ace3c47e4c7de36b | [
"Apache-2.0"
] | 17 | 2021-09-22T20:16:18.000Z | 2022-03-30T19:26:17.000Z | src/mzIMLTools/CModification.cpp | mrchipset/MyMSToolKit | 70c5a7c5a2f914b676bdd630ace3c47e4c7de36b | [
"Apache-2.0"
] | 12 | 2021-10-01T18:53:25.000Z | 2022-03-02T19:27:04.000Z | src/mzIMLTools/CModification.cpp | mrchipset/MyMSToolKit | 70c5a7c5a2f914b676bdd630ace3c47e4c7de36b | [
"Apache-2.0"
] | 4 | 2021-11-08T23:43:41.000Z | 2022-03-21T05:57:15.000Z | /*
Copyright 2017, Michael R. Hoopmann, Institute for Systems Biology
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 "CModification.h"
using namespace std;
CModification::CModification(){
avgMassDelta=0;
location=-1;
monoisotopicMassDelta=0;
residues.clear();
sCvParam cv;
cvParam = new vector<sCvParam>;
cvParam->push_back(cv);
}
CModification::CModification(const CModification& m){
avgMassDelta = m.avgMassDelta;
location = m.location;
monoisotopicMassDelta = m.monoisotopicMassDelta;
residues = m.residues;
size_t i;
cvParam = new vector<sCvParam>;
for (i = 0; i<m.cvParam->size(); i++) cvParam->push_back(m.cvParam->at(i));
}
CModification::~CModification(){
delete cvParam;
}
CModification& CModification::operator=(const CModification& m){
if (this != &m){
avgMassDelta = m.avgMassDelta;
location = m.location;
monoisotopicMassDelta = m.monoisotopicMassDelta;
residues = m.residues;
size_t i;
delete cvParam;
cvParam = new vector<sCvParam>;
for (i = 0; i<m.cvParam->size(); i++) cvParam->push_back(m.cvParam->at(i));
}
return *this;
}
//this is a really slow comparison; it's the nested loops...
bool CModification::operator==(const CModification& m){
if (this == &m) return true;
if (avgMassDelta!=m.avgMassDelta) return false;
if (location!=m.location) return false;
if (monoisotopicMassDelta!=m.monoisotopicMassDelta) return false;
if (residues.compare(m.residues) != 0) return false;
size_t i, j;
if (cvParam->size() != m.cvParam->size()) return false;
for (i = 0; i < cvParam->size(); i++){
for (j = 0; j < m.cvParam->size(); j++){
if (cvParam->at(i) == m.cvParam->at(j)) break;
}
if (j == m.cvParam->size()) return false;
}
return true;
}
void CModification::clear(){
delete cvParam;
avgMassDelta = 0;
location = -1;
monoisotopicMassDelta = 0;
residues.clear();
sCvParam cv;
cvParam = new vector<sCvParam>;
cvParam->push_back(cv);
}
void CModification::writeOut(FILE* f, int tabs){
int i;
size_t j;
for (i = 0; i<tabs; i++) fprintf(f, " ");
fprintf(f, "<Modification");
if (avgMassDelta>0) fprintf(f, " avgMassDelta=\"%.6lf\"",avgMassDelta);
if (location>-1) fprintf(f, " location=\"%d\"", location);
if (monoisotopicMassDelta>0) fprintf(f, " monoisotopicMassDelta=\"%.6lf\"", monoisotopicMassDelta);
if (residues.size()>0) fprintf(f, " residues=\"%s\"", &residues[0]);
fprintf(f, ">\n");
if (tabs > -1){
for (j = 0; j<cvParam->size(); j++) cvParam->at(j).writeOut(f, tabs + 1);
} else {
for (j = 0; j<cvParam->size(); j++) cvParam->at(j).writeOut(f);
}
for (i = 0; i<tabs; i++) fprintf(f, " ");
fprintf(f, "</Modification>\n");
}
| 28.40708 | 101 | 0.67134 | [
"vector"
] |
6a6faba0d1a5c7dc732b1f1654fdb890f2e0816e | 19,122 | cpp | C++ | print/src/type_printer.cpp | ember91/vrt_tools_cmd | 6c56d8d9c9d069db68f229912eb39364c4294cf2 | [
"MIT"
] | null | null | null | print/src/type_printer.cpp | ember91/vrt_tools_cmd | 6c56d8d9c9d069db68f229912eb39364c4294cf2 | [
"MIT"
] | null | null | null | print/src/type_printer.cpp | ember91/vrt_tools_cmd | 6c56d8d9c9d069db68f229912eb39364c4294cf2 | [
"MIT"
] | 1 | 2021-06-29T14:23:49.000Z | 2021-06-29T14:23:49.000Z | #include "type_printer.h"
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
#include "vrt/vrt_string.h"
#include "vrt/vrt_time.h"
#include "vrt/vrt_types.h"
#include "vrt/vrt_util.h"
#include "stringify.h"
namespace vrt::print {
/**
* Print calendar time.
*
* \param tsf Timestamp fractional.
* \param cal_time Calendar time.
* \param ind_lvl Indentation level.
*/
static void print_calendar_time(vrt_tsf tsf, const vrt_calendar_time& cal_time, unsigned int ind_lvl) {
std::stringstream ss;
ss << std::setfill('0');
ss << 1900 + cal_time.year << '-' << std::setw(2) << 1 + cal_time.mon << '-' << std::setw(2) << cal_time.mday << ' '
<< cal_time.hour << ':' << cal_time.min << ':' << cal_time.sec;
ss << std::setw(0);
if (tsf != VRT_TSF_NONE) {
ss << '.' << std::setw(12) << cal_time.ps;
}
WriteCols("(Time)", ss.str(), ind_lvl);
}
/**
* Print formatted GPS/INS geolocation.
*
* \param c IF context.
* \param sample_rate Sample rate [Hz].
* \param gps True if GPS geolocation, False otherwise.
*/
static void print_formatted_geolocation(const vrt_if_context& c, double sample_rate, bool gps) {
const vrt_formatted_geolocation& g{gps ? c.formatted_gps_geolocation : c.formatted_ins_geolocation};
std::cout << "Formatted " << (gps ? "GPS" : "INS") << " geolocation\n";
WriteCols("TSI", vrt_string_tsi(g.tsi), 1);
WriteCols("TSF", vrt_string_tsf(g.tsf), 1);
WriteCols("OUI", Uint32ToHexStr(g.oui, 6), 1);
if (g.tsi != VRT_TSI_UNDEFINED) {
WriteCols("Integer second timestamp", std::to_string(g.integer_second_timestamp), 1);
}
if (g.tsf != VRT_TSF_UNDEFINED) {
WriteCols("Fractional second timestamp", std::to_string(g.fractional_second_timestamp), 1);
}
vrt_calendar_time cal_time;
int rv;
if (gps) {
rv = vrt_time_calendar_gps_geolocation(&c, sample_rate, &cal_time);
} else {
rv = vrt_time_calendar_ins_geolocation(&c, sample_rate, &cal_time);
}
if (rv == 0) {
print_calendar_time(gps ? c.formatted_gps_geolocation.tsf : c.formatted_ins_geolocation.tsf, cal_time, 1);
}
if (g.has.latitude) {
WriteCols("Latitude [degrees]", std::to_string(g.latitude), 1);
}
if (g.has.longitude) {
WriteCols("Longitude [degrees]", std::to_string(g.longitude), 1);
}
if (g.has.altitude) {
WriteCols("Altitude [m]", std::to_string(g.altitude), 1);
}
if (g.has.speed_over_ground) {
WriteCols("Speed over ground [m/s]", std::to_string(g.speed_over_ground), 1);
}
if (g.has.heading_angle) {
WriteCols("Heading angle [degrees]", std::to_string(g.heading_angle), 1);
}
if (g.has.track_angle) {
WriteCols("Track angle [degrees]", std::to_string(g.track_angle), 1);
}
if (g.has.magnetic_variation) {
WriteCols("Magnetic variation [degrees]", std::to_string(g.magnetic_variation), 1);
}
}
/**
* Print ECEF/Relative ephemeris.
*
* \param c IF context.
* \param sample_rate Sample rate [Hz].
* \param ecef True if ECEF ephmemeris, false otherwise.
*/
static void print_ephemeris(const vrt_if_context& c, double sample_rate, bool ecef) {
const vrt_ephemeris& e{ecef ? c.ecef_ephemeris : c.relative_ephemeris};
std::cout << (ecef ? "ECEF" : "Relative") << " ephemeris\n";
WriteCols("TSI", vrt_string_tsi(e.tsi), 1);
WriteCols("TSF", vrt_string_tsf(e.tsf), 1);
WriteCols("OUI", Uint32ToHexStr(e.oui, 6), 1);
if (e.tsi != VRT_TSI_UNDEFINED) {
WriteCols("Integer second timestamp", std::to_string(e.integer_second_timestamp), 1);
}
if (e.tsf != VRT_TSF_UNDEFINED) {
WriteCols("Fractional second timestamp", std::to_string(e.fractional_second_timestamp), 1);
}
vrt_calendar_time cal_time;
int rv;
if (ecef) {
rv = vrt_time_calendar_ecef_ephemeris(&c, sample_rate, &cal_time);
} else {
rv = vrt_time_calendar_relative_ephemeris(&c, sample_rate, &cal_time);
}
if (rv == 0) {
print_calendar_time(ecef ? c.ecef_ephemeris.tsf : c.relative_ephemeris.tsf, cal_time, 1);
}
if (e.has.position_x) {
WriteCols("Position X [m]", std::to_string(e.position_x), 1);
}
if (e.has.position_y) {
WriteCols("Position Y [m]", std::to_string(e.position_y), 1);
}
if (e.has.position_z) {
WriteCols("Position Z [m]", std::to_string(e.position_z), 1);
}
if (e.has.attitude_alpha) {
WriteCols("Altitude alpha [degrees]", std::to_string(e.attitude_alpha), 1);
}
if (e.has.attitude_beta) {
WriteCols("Altitude beta [degrees]", std::to_string(e.attitude_beta), 1);
}
if (e.has.attitude_phi) {
WriteCols("Altitude phi [degrees]", std::to_string(e.attitude_phi), 1);
}
if (e.has.velocity_dx) {
WriteCols("Velocity dX [m/s]", std::to_string(e.velocity_dx), 1);
}
if (e.has.velocity_dy) {
WriteCols("Velocity dY [m/s]", std::to_string(e.velocity_dy), 1);
}
if (e.has.velocity_dz) {
WriteCols("Velocity dZ [m/s]", std::to_string(e.velocity_dz), 1);
}
}
/**
* Print header.
*
* \param packet Packet.
*/
void print_header(const vrt_packet& packet) {
const vrt_header& header{packet.header};
WriteCols("Packet type", vrt_string_packet_type(header.packet_type));
// No idea to print has.class_id and has.trailer
WriteCols("tsm", vrt_string_tsm(header.tsm));
WriteCols("TSI", vrt_string_tsi(header.tsi));
WriteCols("TSF", vrt_string_tsf(header.tsf));
WriteCols("Packet count", std::to_string(header.packet_count));
WriteCols("Packet size [words]", std::to_string(header.packet_size));
}
/**
* Print fields.
*
* \param packet Packet.
* \param sample_rate Sample rate [Hz].
*/
void print_fields(const vrt_packet& packet, double sample_rate) {
if (vrt_has_stream_id(&packet.header)) {
WriteCols("Stream ID", Uint32ToHexStr(packet.fields.stream_id));
}
if (packet.header.has.class_id) {
std::cout << "Class ID\n";
WriteCols("OUI", Uint32ToHexStr(packet.fields.class_id.oui, 6), 1);
WriteCols("Information class code", Uint32ToHexStr(packet.fields.class_id.information_class_code, 4), 1);
WriteCols("Packet class code", Uint32ToHexStr(packet.fields.class_id.packet_class_code, 4), 1);
}
if (packet.header.tsi != VRT_TSI_NONE) {
WriteCols("Integer seconds timestamp", std::to_string(packet.fields.integer_seconds_timestamp));
}
if (packet.header.tsf != VRT_TSF_NONE) {
WriteCols("Fractional seconds timestamp", std::to_string(packet.fields.fractional_seconds_timestamp));
}
vrt_calendar_time cal_time;
if (vrt_time_calendar_fields(&packet.header, &packet.fields, sample_rate, &cal_time) == 0) {
print_calendar_time(packet.header.tsf, cal_time, 1);
}
}
/**
* Print body.
*
* \param packet Packet.
*/
void print_body(const vrt_packet& packet) {
int32_t words_body{packet.words_body};
switch (packet.header.packet_type) {
case VRT_PT_IF_DATA_WITHOUT_STREAM_ID:
case VRT_PT_IF_DATA_WITH_STREAM_ID:
case VRT_PT_EXT_DATA_WITHOUT_STREAM_ID:
case VRT_PT_EXT_DATA_WITH_STREAM_ID: {
WriteCols("Body size [words]", std::to_string(words_body));
break;
}
case VRT_PT_IF_CONTEXT: {
// Do nothing
break;
}
case VRT_PT_EXT_CONTEXT: {
WriteCols("Extended context section size [words]", std::to_string(words_body));
break;
}
}
}
/**
* Print IF context.
*
* \param packet Packet.
* \param sample_rate Sample rate [Hz].
*/
void print_if_context(const vrt_packet& packet, double sample_rate) {
const vrt_if_context& if_context{packet.if_context};
if (if_context.context_field_change_indicator) {
WriteCols("Changed", BoolToStr(if_context.context_field_change_indicator));
}
if (if_context.has.reference_point_identifier) {
WriteCols("Reference point identifier", Uint32ToHexStr(if_context.reference_point_identifier));
}
if (if_context.has.bandwidth) {
WriteCols("Bandwidth [Hz]", std::to_string(if_context.bandwidth));
}
if (if_context.has.if_reference_frequency) {
WriteCols("IF reference frequency [Hz]", std::to_string(if_context.if_reference_frequency));
}
if (if_context.has.rf_reference_frequency) {
WriteCols("RF reference frequency [Hz]", std::to_string(if_context.rf_reference_frequency));
}
if (if_context.has.rf_reference_frequency_offset) {
WriteCols("RF reference frequency offset [Hz]", std::to_string(if_context.rf_reference_frequency_offset));
}
if (if_context.has.if_band_offset) {
WriteCols("IF band offset [Hz]", std::to_string(if_context.if_band_offset));
}
if (if_context.has.reference_level) {
WriteCols("Reference level [dBm]", std::to_string(if_context.reference_level));
}
if (if_context.has.gain) {
std::cout << "Gain\n";
WriteCols("Stage 1 [dB]", std::to_string(if_context.gain.stage1), 1);
WriteCols("Stage 2 [dB]", std::to_string(if_context.gain.stage2), 1);
}
if (if_context.has.over_range_count) {
WriteCols("Over-range count", std::to_string(if_context.over_range_count));
}
if (if_context.has.sample_rate) {
WriteCols("Sample rate [Hz]", std::to_string(if_context.sample_rate));
}
if (if_context.has.timestamp_adjustment) {
WriteCols("Timestamp adjustment [ps]", std::to_string(if_context.timestamp_adjustment));
}
if (if_context.has.timestamp_calibration_time) {
WriteCols("Timestamp calibration time", std::to_string(if_context.timestamp_calibration_time));
vrt_calendar_time cal_time;
if (vrt_time_calendar_calibration(&packet.header, &if_context, &cal_time) == 0) {
print_calendar_time(VRT_TSF_NONE, cal_time, 1);
}
}
if (if_context.has.temperature) {
WriteCols("Temperature [degrees C]", std::to_string(if_context.temperature));
}
if (if_context.has.device_identifier) {
std::cout << "Device identifier\n";
WriteCols("OUI", Uint32ToHexStr(if_context.device_identifier.oui, 6), 1);
WriteCols("Device code", Uint32ToHexStr(if_context.device_identifier.device_code, 4), 1);
}
if (if_context.has.state_and_event_indicators) {
std::cout << "State and event indicators\n";
if (if_context.state_and_event_indicators.has.calibrated_time) {
WriteCols("Calibrated time", BoolToStr(if_context.state_and_event_indicators.calibrated_time), 1);
}
if (if_context.state_and_event_indicators.has.valid_data) {
WriteCols("Valid data", BoolToStr(if_context.state_and_event_indicators.valid_data), 1);
}
if (if_context.state_and_event_indicators.has.reference_lock) {
WriteCols("Reference lock", BoolToStr(if_context.state_and_event_indicators.reference_lock), 1);
}
if (if_context.state_and_event_indicators.has.agc_or_mgc) {
WriteCols("AGC/MGC", vrt_string_agc_or_mgc(if_context.state_and_event_indicators.agc_or_mgc), 1);
}
if (if_context.state_and_event_indicators.has.detected_signal) {
WriteCols("Detected signal", BoolToStr(if_context.state_and_event_indicators.detected_signal), 1);
}
if (if_context.state_and_event_indicators.has.spectral_inversion) {
WriteCols("Spectral inversion", BoolToStr(if_context.state_and_event_indicators.spectral_inversion), 1);
}
if (if_context.state_and_event_indicators.has.over_range) {
WriteCols("Over-range", BoolToStr(if_context.state_and_event_indicators.over_range), 1);
}
if (if_context.state_and_event_indicators.has.sample_loss) {
WriteCols("Sample loss", BoolToStr(if_context.state_and_event_indicators.sample_loss), 1);
}
WriteCols("User defined", Uint32ToHexStr(if_context.state_and_event_indicators.user_defined, 2), 1);
}
if (if_context.has.data_packet_payload_format) {
std::cout << "Data packet payload format\n";
WriteCols("Packing method", vrt_string_packing_method(if_context.data_packet_payload_format.packing_method), 1);
WriteCols("Real/Complex", vrt_string_real_or_complex(if_context.data_packet_payload_format.real_or_complex), 1);
WriteCols("Data item format",
vrt_string_data_item_format(if_context.data_packet_payload_format.data_item_format), 1);
WriteCols("Sample component repeat", BoolToStr(if_context.data_packet_payload_format.sample_component_repeat),
1);
WriteCols("Event tag size", std::to_string(if_context.data_packet_payload_format.event_tag_size), 1);
WriteCols("Channel tag size", std::to_string(if_context.data_packet_payload_format.channel_tag_size), 1);
WriteCols("Item packing field size",
std::to_string(if_context.data_packet_payload_format.item_packing_field_size), 1);
WriteCols("Data item size", std::to_string(if_context.data_packet_payload_format.data_item_size), 1);
WriteCols("Repeat count", std::to_string(if_context.data_packet_payload_format.repeat_count), 1);
WriteCols("Vector size", std::to_string(if_context.data_packet_payload_format.vector_size), 1);
}
if (if_context.has.formatted_gps_geolocation) {
print_formatted_geolocation(if_context, sample_rate, true);
}
if (if_context.has.formatted_ins_geolocation) {
print_formatted_geolocation(if_context, sample_rate, false);
}
if (if_context.has.ecef_ephemeris) {
print_ephemeris(if_context, sample_rate, true);
}
if (if_context.has.relative_ephemeris) {
print_ephemeris(if_context, sample_rate, false);
}
if (if_context.has.ephemeris_reference_identifier) {
WriteCols("Ephemeris reference identifier", Uint32ToHexStr(if_context.ephemeris_reference_identifier));
}
if (if_context.has.gps_ascii) {
std::cout << "GPS ASCII\n";
WriteCols("OUI", Uint32ToHexStr(if_context.gps_ascii.oui, 6), 1);
WriteCols("Number of words", std::to_string(if_context.gps_ascii.number_of_words), 1);
// Get full string and print, even if it may look a bit weird. Useful for debugging.
std::string ascii_str(if_context.gps_ascii.ascii, if_context.gps_ascii.ascii +
sizeof(uint32_t) * if_context.gps_ascii.number_of_words -
if_context.gps_ascii.ascii);
WriteCols("ASCII", ascii_str, 1);
}
if (if_context.has.context_association_lists) {
std::cout << "Context association lists\n";
WriteCols("Source list size", std::to_string(if_context.context_association_lists.source_list_size), 1);
WriteCols("System list size", std::to_string(if_context.context_association_lists.system_list_size), 1);
WriteCols("Vector component list size",
std::to_string(if_context.context_association_lists.vector_component_list_size), 1);
WriteCols("Asynchronous channel list size",
std::to_string(if_context.context_association_lists.asynchronous_channel_list_size), 1);
if (if_context.context_association_lists.has.asynchronous_channel_tag_list) {
WriteCols("Asynchronous channel tag list size",
std::to_string(if_context.context_association_lists.asynchronous_channel_list_size), 1);
}
std::cout << "Source list\n";
for (uint16_t j{0}; j < if_context.context_association_lists.source_list_size; ++j) {
WriteCols("", Uint32ToHexStr(if_context.context_association_lists.source_context_association_list[j]), 2);
}
std::cout << "System list\n";
for (uint16_t j{0}; j < if_context.context_association_lists.system_list_size; ++j) {
WriteCols("", Uint32ToHexStr(if_context.context_association_lists.system_context_association_list[j]), 2);
}
std::cout << "Vector component list\n";
for (uint16_t j{0}; j < if_context.context_association_lists.vector_component_list_size; ++j) {
WriteCols("",
Uint32ToHexStr(if_context.context_association_lists.vector_component_context_association_list[j]),
2);
}
std::cout << "Asynchronous channel list\n";
for (uint16_t j{0}; j < if_context.context_association_lists.asynchronous_channel_list_size; ++j) {
WriteCols(
"",
Uint32ToHexStr(if_context.context_association_lists.asynchronous_channel_context_association_list[j]),
2);
}
if (if_context.context_association_lists.has.asynchronous_channel_tag_list) {
std::cout << "Asynchronous channel tag list\n";
for (uint16_t j{0}; j < if_context.context_association_lists.asynchronous_channel_list_size; ++j) {
WriteCols("", Uint32ToHexStr(if_context.context_association_lists.asynchronous_channel_tag_list[j]), 2);
}
}
}
}
/**
* Print trailer.
*
* \param packet Packet.
*/
void print_trailer(const vrt_packet& packet) {
const vrt_trailer& trailer{packet.trailer};
if (trailer.has.calibrated_time) {
WriteCols("Calibrated time", BoolToStr(trailer.calibrated_time));
}
if (trailer.has.valid_data) {
WriteCols("Valid data", BoolToStr(trailer.valid_data));
}
if (trailer.has.reference_lock) {
WriteCols("Reference lock", BoolToStr(trailer.reference_lock));
}
if (trailer.has.agc_or_mgc) {
WriteCols("AGC/MGC", vrt_string_agc_or_mgc(trailer.agc_or_mgc));
}
if (trailer.has.detected_signal) {
WriteCols("Detected signal", BoolToStr(trailer.detected_signal));
}
if (trailer.has.spectral_inversion) {
WriteCols("Spectral inversion", BoolToStr(trailer.spectral_inversion));
}
if (trailer.has.over_range) {
WriteCols("Over range", BoolToStr(trailer.over_range));
}
if (trailer.has.sample_loss) {
WriteCols("Sample loss", BoolToStr(trailer.sample_loss));
}
if (trailer.has.user_defined11) {
WriteCols("User defined 11", BoolToStr(trailer.user_defined11));
}
if (trailer.has.user_defined10) {
WriteCols("User defined 10", BoolToStr(trailer.user_defined10));
}
if (trailer.has.user_defined9) {
WriteCols("User defined 9", BoolToStr(trailer.user_defined9));
}
if (trailer.has.user_defined8) {
WriteCols("User defined 8", BoolToStr(trailer.user_defined8));
}
if (trailer.has.associated_context_packet_count) {
WriteCols("Associated context packet count", std::to_string(trailer.associated_context_packet_count));
}
}
} // namespace vrt::print
| 43.262443 | 120 | 0.668706 | [
"vector"
] |
6a72da0c4e31a7f685665ea89310a4daa93a9436 | 6,143 | hpp | C++ | include/Oculus/Platform/VoipPCMSourceNative.hpp | sc2ad/BeatSaber-Quest-Codegen | ba8acaae541cfe1161e05fbc3bf87f4bc46bc4ab | [
"Unlicense"
] | 23 | 2020-08-07T04:09:00.000Z | 2022-03-31T22:10:29.000Z | include/Oculus/Platform/VoipPCMSourceNative.hpp | sc2ad/BeatSaber-Quest-Codegen | ba8acaae541cfe1161e05fbc3bf87f4bc46bc4ab | [
"Unlicense"
] | 6 | 2021-09-29T23:47:31.000Z | 2022-03-30T20:49:23.000Z | include/Oculus/Platform/VoipPCMSourceNative.hpp | sc2ad/BeatSaber-Quest-Codegen | ba8acaae541cfe1161e05fbc3bf87f4bc46bc4ab | [
"Unlicense"
] | 17 | 2020-08-20T19:36:52.000Z | 2022-03-30T18:28:24.000Z | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
#include "extern/beatsaber-hook/shared/utils/byref.hpp"
// Including type: Oculus.Platform.IVoipPCMSource
#include "Oculus/Platform/IVoipPCMSource.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
#include "extern/beatsaber-hook/shared/utils/typedefs-array.hpp"
// Completed includes
// Type namespace: Oculus.Platform
namespace Oculus::Platform {
// Forward declaring type: VoipPCMSourceNative
class VoipPCMSourceNative;
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(Oculus::Platform::VoipPCMSourceNative);
DEFINE_IL2CPP_ARG_TYPE(Oculus::Platform::VoipPCMSourceNative*, "Oculus.Platform", "VoipPCMSourceNative");
// Type namespace: Oculus.Platform
namespace Oculus::Platform {
// Size: 0x18
#pragma pack(push, 1)
// Autogenerated type: Oculus.Platform.VoipPCMSourceNative
// [TokenAttribute] Offset: FFFFFFFF
class VoipPCMSourceNative : public ::Il2CppObject/*, public Oculus::Platform::IVoipPCMSource*/ {
public:
#ifdef USE_CODEGEN_FIELDS
public:
#else
protected:
#endif
// private System.UInt64 senderID
// Size: 0x8
// Offset: 0x10
uint64_t senderID;
// Field size check
static_assert(sizeof(uint64_t) == 0x8);
public:
// Creating interface conversion operator: operator Oculus::Platform::IVoipPCMSource
operator Oculus::Platform::IVoipPCMSource() noexcept {
return *reinterpret_cast<Oculus::Platform::IVoipPCMSource*>(this);
}
// Creating conversion operator: operator uint64_t
constexpr operator uint64_t() const noexcept {
return senderID;
}
// Get instance field reference: private System.UInt64 senderID
uint64_t& dyn_senderID();
// public System.Int32 GetPCM(System.Single[] dest, System.Int32 length)
// Offset: 0x25A40C4
int GetPCM(::ArrayW<float> dest, int length);
// public System.Void SetSenderID(System.UInt64 senderID)
// Offset: 0x25A4184
void SetSenderID(uint64_t senderID);
// public System.Int32 PeekSizeElements()
// Offset: 0x25A418C
int PeekSizeElements();
// public System.Void Update()
// Offset: 0x25A422C
void Update();
// public System.Void .ctor()
// Offset: 0x25A35A0
// Implemented from: System.Object
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static VoipPCMSourceNative* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("Oculus::Platform::VoipPCMSourceNative::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<VoipPCMSourceNative*, creationType>()));
}
}; // Oculus.Platform.VoipPCMSourceNative
#pragma pack(pop)
static check_size<sizeof(VoipPCMSourceNative), 16 + sizeof(uint64_t)> __Oculus_Platform_VoipPCMSourceNativeSizeCheck;
static_assert(sizeof(VoipPCMSourceNative) == 0x18);
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: Oculus::Platform::VoipPCMSourceNative::GetPCM
// Il2CppName: GetPCM
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (Oculus::Platform::VoipPCMSourceNative::*)(::ArrayW<float>, int)>(&Oculus::Platform::VoipPCMSourceNative::GetPCM)> {
static const MethodInfo* get() {
static auto* dest = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("System", "Single"), 1)->byval_arg;
static auto* length = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Oculus::Platform::VoipPCMSourceNative*), "GetPCM", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{dest, length});
}
};
// Writing MetadataGetter for method: Oculus::Platform::VoipPCMSourceNative::SetSenderID
// Il2CppName: SetSenderID
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (Oculus::Platform::VoipPCMSourceNative::*)(uint64_t)>(&Oculus::Platform::VoipPCMSourceNative::SetSenderID)> {
static const MethodInfo* get() {
static auto* senderID = &::il2cpp_utils::GetClassFromName("System", "UInt64")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Oculus::Platform::VoipPCMSourceNative*), "SetSenderID", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{senderID});
}
};
// Writing MetadataGetter for method: Oculus::Platform::VoipPCMSourceNative::PeekSizeElements
// Il2CppName: PeekSizeElements
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (Oculus::Platform::VoipPCMSourceNative::*)()>(&Oculus::Platform::VoipPCMSourceNative::PeekSizeElements)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(Oculus::Platform::VoipPCMSourceNative*), "PeekSizeElements", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: Oculus::Platform::VoipPCMSourceNative::Update
// Il2CppName: Update
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (Oculus::Platform::VoipPCMSourceNative::*)()>(&Oculus::Platform::VoipPCMSourceNative::Update)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(Oculus::Platform::VoipPCMSourceNative*), "Update", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: Oculus::Platform::VoipPCMSourceNative::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
| 51.191667 | 190 | 0.725704 | [
"object",
"vector"
] |
6a7c015a5cddf178e19dd64870d6d8207f02e616 | 9,456 | cpp | C++ | EsculptorQT/sculptor.cpp | igorsergioJS/sculptor_3.0 | 61470dfa24910dfefa9e1ebb8301150aa6b6f71d | [
"MIT"
] | null | null | null | EsculptorQT/sculptor.cpp | igorsergioJS/sculptor_3.0 | 61470dfa24910dfefa9e1ebb8301150aa6b6f71d | [
"MIT"
] | null | null | null | EsculptorQT/sculptor.cpp | igorsergioJS/sculptor_3.0 | 61470dfa24910dfefa9e1ebb8301150aa6b6f71d | [
"MIT"
] | null | null | null | #include <iostream>
#include <iomanip>
#include "sculptor.h"
#include "mainwindow.h"
#include <fstream>
#include <string>
#include <math.h>
#include <cstdlib>
using namespace std;
Sculptor::Sculptor(int _nx, int _ny, int _nz)
{
nx = _nx; ny = _ny; nz = _nz;
if(nx <= 0 || ny <= 0 || nz <= 0){
nx = ny = nz = 0;
}
v = new Voxel**[nx];
if(v == nullptr){
exit(0);
}
v[0] = new Voxel*[nx*ny];
if(v[0] == nullptr){
exit(0);
}
v[0][0] = new Voxel[nx*ny*nz];
if(v[0][0] == nullptr){
exit(0);
}
for(int i=0; i< nx; i++)
{
if (i<(nx-1))
{
v[i+1] = v[i]+ny;
}
for(int j=1; j< ny; j++)
{
v[i][j] = v[i][j-1]+nz;
if(j==ny-1 && i!=(nx-1))
{
v[i+1][0] = v[i][j]+nz;
}
}
}
for(int i = 0; i < nx; i++){
for(int j = 0; j < ny; j++){
for(int k = 0; k < nz; k++){
v[i][j][k].isOn = false;
}
}
}
}
vector<vector<Voxel>> Sculptor::readMx(int dim, int pl){
vector<vector<Voxel>> m;
vector<Voxel> l;
if (pl == XY){
l.resize(ny);
for(int i = 0; i<nx; i++){
for(int j = 0; j<ny; j++){
l[j].isOn = v[i][j][dim].isOn;
l[j].r = v[i][j][dim].r;
l[j].g = v[i][j][dim].g;
l[j].b = v[i][j][dim].b;
l[j].a = v[i][j][dim].a;
}
m.push_back(l);
}
}
if (pl == YZ){
l.resize(nz);
for(int i = 0; i<ny; i++){
for(int j = 0; j<nz; j++){
l[j].isOn = v[dim][i][j].isOn;
l[j].r = v[dim][i][j].r;
l[j].g = v[dim][i][j].g;
l[j].b = v[dim][i][j].b;
l[j].a = v[dim][i][j].a;
}
m.push_back(l);
}
}
if (pl == ZX){
l.resize(nx);
for(int i = 0; i<nz; i++){
for(int j = 0; j<nx; j++){
l[j].isOn = v[j][dim][i].isOn;
l[j].r = v[j][dim][i].r;
l[j].g = v[j][dim][i].g;
l[j].b = v[j][dim][i].b;
l[j].a = v[j][dim][i].a;
}
m.push_back(l);
}
}
l.clear();
return m;
}
Sculptor::~Sculptor()
{
// Liberação da memória alocada;
delete [] v[0][0];
delete [] v[0];
delete [] v;
}
void Sculptor::setColor(float _r, float _g, float _b, float alpha)
{
r = _r;
g = _g;
b = _b;
a = alpha;
}
void Sculptor::putVoxel(int x, int y, int z)
{
v[x][y][z].isOn = true;
if(r>=0 && r<=255)
v[x][y][z].r = r;
if(g>=0 && g<=255)
v[x][y][z].g = g;
if(b>=0 && b<=255)
v[x][y][z].b= b;
v[x][y][z].a = a;
}
void Sculptor::cutVoxel(int x, int y, int z)
{
v[x][y][z].isOn = false;
}
void Sculptor::putBox(int x0, int x1, int y0, int y1, int z0, int z1)
{
for(int i=x0;i<x1;i++)
{
for(int j=y0;j<y1;j++)
{
for(int k=z0;k<z1;k++)
{
putVoxel(i,j,k);
}
}
}
}
void Sculptor::cutBox(int x0, int x1, int y0, int y1, int z0, int z1)
{
for(int i=x0;i<x1;i++)
{
for(int j=y0;j<y1;j++)
{
for(int k=z0;k<z1;k++)
{
cutVoxel(i,j,k);
}
}
}
}
void Sculptor::putSphere(int xcenter, int ycenter, int zcenter, int radius)
{
for(int i = xcenter-radius; i<=xcenter+radius; i++)
{
for(int j = ycenter-radius; j<=ycenter+radius; j++)
{
for(int k = zcenter-radius; k<=zcenter+radius; k++)
{
if((pow((i-xcenter),2)+pow((j-ycenter),2)+pow((k-zcenter),2))<=pow(radius,2))
{
putVoxel(i,j,k);
}
}
}
}
}
void Sculptor::cutSphere(int xcenter, int ycenter, int zcenter, int radius)
{
for(int i = xcenter-radius; i<=xcenter+radius; i++)
{
for(int j = ycenter-radius; j<=ycenter+radius; j++)
{
for(int k = zcenter-radius; k<=zcenter+radius; k++)
{
if((pow((i-xcenter),2)+pow((j-ycenter),2)+pow((k-zcenter),2))<=pow(radius,2))
{
cutVoxel(i,j,k);
}
}
}
}
}
void Sculptor::putEllipsoid(int xcenter, int ycenter, int zcenter, int rx, int ry, int rz)
{
for(int i = xcenter-rx; i<=xcenter+rx; i++)
{
for(int j = ycenter-ry; j<=ycenter+ry; j++)
{
for(int k = zcenter-rz; k<=zcenter+rz; k++)
{
if(((pow((i-xcenter),2)/pow(rx,2))+(pow((j-ycenter),2)/pow(ry,2))+(pow((k-zcenter),2)/pow(rz,2)))<=1.0)
{
putVoxel(i,j,k);
}
}
}
}
}
void Sculptor::cutEllipsoid(int xcenter, int ycenter, int zcenter, int rx, int ry, int rz)
{
for(int i = xcenter-rx; i<=xcenter+rx; i++)
{
for(int j = ycenter-ry; j<=ycenter+ry; j++)
{
for(int k = zcenter-rz; k<=zcenter+rz; k++)
{
if(((pow((i-xcenter),2)/pow(rx,2))+(pow((j-ycenter),2)/pow(ry,2))+(pow((k-zcenter),2)/pow(rz,2)))<=1.0)
{
cutVoxel(i,j,k);
}
}
}
}
}
void Sculptor::writeOFF(string filename)
{
int aux = 0;
int Nface = 0;
int Nvert = 0;
ofstream arq;
arq.open(filename);
for(int i=0;i<nx;i++)
{
for(int j=0;j<ny;j++)
{
for(int k=0;k<nz;k++)
{
if(v[i][j][k].isOn && v[i][j][k].r>=0 && v[i][j][k].r<=255 && v[i][j][k].g>=0 && v[i][j][k].g<=255 && v[i][j][k].b>=0 && v[i][j][k].b<=255)
{
Nvert = Nvert+8;
Nface = Nface+6;
}
}
}
}
arq << "OFF" << endl; //Primeira linha do arquivo (obrigatória)
arq << Nvert << " " << Nface << " " << 0 << endl;
// Laço para atribuir os devidos valores dos vértices de cada voxel no arquivo
for(int i=0;i<nx;i++)
{
for(int j=0;j<ny;j++)
{
for(int k=0;k<nz;k++)
{
if(v[i][j][k].isOn && v[i][j][k].r>=0 && v[i][j][k].r<=255 && v[i][j][k].g>=0 && v[i][j][k].g<=255 && v[i][j][k].b>=0 && v[i][j][k].b<=255)
{
arq<<i-0.5<<" "<<j+0.5<<" "<<k-0.5<<endl;
arq<<i-0.5<<" "<<j-0.5<<" "<<k-0.5<<endl;
arq<<i+0.5<<" "<<j-0.5<<" "<<k-0.5<<endl;
arq<<i+0.5<<" "<<j+0.5<<" "<<k-0.5<<endl;
arq<<i-0.5<<" "<<j+0.5<<" "<<k+0.5<<endl;
arq<<i-0.5<<" "<<j-0.5<<" "<<k+0.5<<endl;
arq<<i+0.5<<" "<<j-0.5<<" "<<k+0.5<<endl;
arq<<i+0.5<<" "<<j+0.5<<" "<<k+0.5<<endl;
}
}
}
}
// Laço para atribuir o devido ordenamento das faces de cada voxel no arquivo;
for(int i=0;i<nx;i++)
{
for(int j=0;j<ny;j++)
{
for(int k=0;k<nz;k++)
{
if(v[i][j][k].isOn && v[i][j][k].r>=0 && v[i][j][k].r<=255 && v[i][j][k].g>=0 && v[i][j][k].g<=255 && v[i][j][k].b>=0 && v[i][j][k].b<=255)
{
arq << 4 << " " << aux+0 << " " << aux+3 << " " << aux+2 << " " << aux+1 << " " << v[i][j][k].r/255 << " " << v[i][j][k].g/255 << " " << v[i][j][k].b/255 << " " << v[i][j][k].a/255 << endl;
arq << 4 << " " << aux+4 << " " << aux+5 << " " << aux+6 << " " << aux+7 << " " << v[i][j][k].r/255 << " " << v[i][j][k].g/255 << " " << v[i][j][k].b/255 << " " << v[i][j][k].a/255 << endl;
arq << 4 << " " << aux+0 << " " << aux+1 << " " << aux+5 << " " << aux+4 << " " << v[i][j][k].r/255 << " " << v[i][j][k].g/255 << " " << v[i][j][k].b/255 << " " << v[i][j][k].a/255 << endl;
arq << 4 << " " << aux+0 << " " << aux+4 << " " << aux+7 << " " << aux+3 << " " << v[i][j][k].r/255 << " " << v[i][j][k].g/255 << " " << v[i][j][k].b/255 << " " << v[i][j][k].a/255 << endl;
arq << 4 << " " << aux+3 << " " << aux+7 << " " << aux+6 << " " << aux+2 << " " << v[i][j][k].r/255 << " " << v[i][j][k].g/255 << " " << v[i][j][k].b/255 << " " << v[i][j][k].a/255 << endl;
arq << 4 << " " << aux+1 << " " << aux+2 << " " << aux+6 << " " << aux+5 << " " << v[i][j][k].r/255 << " " << v[i][j][k].g/255 << " " << v[i][j][k].b/255 << " " << v[i][j][k].a/255 << endl;
aux = aux + 8;
}
}
}
}
// Verifica se o arquivo é gerado. Quando não aparece mensagem alguma, provavelmente houve alguma falha na alocação;
if(arq.is_open())
{
cout << "arquivo OFF salvo com sucesso ! "<<endl;
}
else
{
cout << "Erro ao salvar o arquivo" << endl;
}
}
| 29.55 | 208 | 0.354907 | [
"vector"
] |
6a7ed43c379922869561650e59146b420cc743b2 | 11,265 | cpp | C++ | test/c++/nda_basic.cpp | TRIQS/nda | 7256006985a8909f21b57b1c5bd7813fd7f4f7e7 | [
"Apache-2.0"
] | 3 | 2021-05-26T08:53:25.000Z | 2021-06-13T00:39:10.000Z | test/c++/nda_basic.cpp | TRIQS/nda | 7256006985a8909f21b57b1c5bd7813fd7f4f7e7 | [
"Apache-2.0"
] | 10 | 2020-08-11T21:02:47.000Z | 2022-01-26T19:21:34.000Z | test/c++/nda_basic.cpp | TRIQS/nda | 7256006985a8909f21b57b1c5bd7813fd7f4f7e7 | [
"Apache-2.0"
] | 4 | 2021-05-24T12:43:08.000Z | 2022-02-28T01:33:03.000Z | // Copyright (c) 2019-2020 Simons Foundation
//
// 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 "./test_common.hpp"
//static_assert(!std::is_pod<nda::array<long, 2>>::value, "POD pb");
static_assert(nda::is_scalar_for_v<int, matrix<std::complex<double>>> == 1, "oops");
// ==============================================================
TEST(NDA, Create1) { //NOLINT
auto A = nda::array<long, 2>(3, 3);
EXPECT_EQ(A.shape(), (nda::shape_t<2>{3, 3}));
auto B = nda::array<long, 2>(std::array{3, 3});
EXPECT_EQ(B.shape(), (nda::shape_t<2>{3, 3}));
auto C = nda::array<long, 1>(3, 3);
EXPECT_EQ(C.shape(), (nda::shape_t<1>{3}));
EXPECT_EQ(C, (3 * nda::ones<long>(3)));
}
// -------------------------------------
TEST(Assign, Contiguous) { //NOLINT
nda::array<long, 2> A{{1, 2}, {3, 4}, {5, 6}};
nda::array<long, 2> B;
B = A;
EXPECT_ARRAY_NEAR(A, B);
A(0, 1) = 87;
B = A(); // no resize
EXPECT_EQ(A.indexmap().strides(), B.indexmap().strides());
EXPECT_ARRAY_NEAR(A, B);
EXPECT_EQ(B.shape(), (nda::shape_t<2>{3, 2}));
}
// -------------------------------------
TEST(Assign, Strided) { //NOLINT
nda::array<long, 3> A(3, 5, 9);
nda::array<long, 1> B;
for (int i = 0; i < A.extent(0); ++i)
for (int j = 0; j < A.extent(1); ++j)
for (int k = 0; k < A.extent(2); ++k) A(i, j, k) = 1 + i + 10 * j + 100 * k;
NDA_PRINT(A.shape());
B = A(_, 0, 1);
for (int i = 0; i < A.extent(0); ++i) EXPECT_EQ(A(i, 0, 1), B(i));
B = A(1, _, 2);
for (int i = 0; i < A.extent(1); ++i) EXPECT_EQ(A(1, i, 2), B(i));
B = A(1, 3, _);
for (int i = 0; i < A.extent(2); ++i) EXPECT_EQ(A(1, 3, i), B(i));
// P =0 to force out of the first test of slice_layout_prop. We want to test the real algorithm
EXPECT_EQ(
nda::slice_static::slice_layout_prop(0, true, std::array<bool, 3>{1, 0, 0}, std::array<int, 3>{0, 1, 2}, nda::layout_prop_e::contiguous, 128, 0),
nda::layout_prop_e::strided_1d);
EXPECT_EQ(
nda::slice_static::slice_layout_prop(0, true, std::array<bool, 3>{0, 1, 0}, std::array<int, 3>{0, 1, 2}, nda::layout_prop_e::contiguous, 128, 0),
nda::layout_prop_e::strided_1d);
EXPECT_EQ(
nda::slice_static::slice_layout_prop(0, true, std::array<bool, 3>{0, 0, 1}, std::array<int, 3>{0, 1, 2}, nda::layout_prop_e::contiguous, 128, 0),
nda::layout_prop_e::contiguous);
static_assert(nda::get_layout_info<decltype(A(1, 3, _))>.prop == nda::layout_prop_e::contiguous);
static_assert(nda::get_layout_info<decltype(A(1, _, 2))>.prop == nda::layout_prop_e::strided_1d);
static_assert(nda::get_layout_info<decltype(A(_, 0, 1))>.prop == nda::layout_prop_e::strided_1d);
}
// -------------------------------------
TEST(Assign, Strided2) { //NOLINT
nda::array<long, 3> A(3, 5, 9);
nda::array<long, 1> B;
for (int i = 0; i < A.extent(0); ++i)
for (int j = 0; j < A.extent(1); ++j)
for (int k = 0; k < A.extent(2); ++k) A(i, j, k) = 1 + i + 10 * j + 100 * k;
B.resize(20);
B = 0;
static_assert(nda::get_layout_info<decltype(B(range(0, 2 * A.extent(0), 2)))>.prop == nda::layout_prop_e::strided_1d);
B(range(0, 2 * A.extent(0), 2)) = A(_, 0, 1);
NDA_PRINT(B);
NDA_PRINT(A(_, 0, 1));
for (int i = 0; i < A.extent(0); ++i) EXPECT_EQ(A(i, 0, 1), B(2 * i));
B(range(0, 2 * A.extent(1), 2)) = A(1, _, 2);
NDA_PRINT(B);
NDA_PRINT(A(1, _, 2));
for (int i = 0; i < A.extent(1); ++i) EXPECT_EQ(A(1, i, 2), B(2 * i));
B(range(0, 2 * A.extent(2), 2)) = A(1, 3, _);
NDA_PRINT(B);
NDA_PRINT(A(1, 3, _));
for (int i = 0; i < A.extent(2); ++i) EXPECT_EQ(A(1, 3, i), B(2 * i));
}
// -------------------------------------
TEST(NDA, Iterator1) { //NOLINT
nda::array<long, 2> A{{0, 1, 2}, {3, 4, 5}};
int i = 0;
for (auto x : A) EXPECT_EQ(x, i++);
}
// -------------------------------------
TEST(NDA, CreateResize) { //NOLINT
nda::array<long, 2> A;
A.resize({3, 3});
EXPECT_EQ(A.shape(), (nda::shape_t<2>{3, 3}));
A.resize({4, 4});
EXPECT_EQ(A.shape(), (nda::shape_t<2>{4, 4}));
nda::array<double, 2> M;
M.resize(3, 3);
EXPECT_EQ(M.shape(), (nda::shape_t<2>{3, 3}));
nda::array<long, 1> V;
V.resize(10);
EXPECT_EQ(V.shape(), (nda::shape_t<1>{10}));
}
// ==============================================================
TEST(NDA, InitList) { //NOLINT
// 1d
nda::array<double, 1> A = {1, 2, 3, 4};
EXPECT_EQ(A.shape(), (nda::shape_t<1>{4}));
for (int i = 0; i < 4; ++i) EXPECT_EQ(A(i), i + 1);
// 2d
nda::array<double, 2> B = {{1, 2}, {3, 4}, {5, 6}};
EXPECT_EQ(B.shape(), (nda::shape_t<2>{3, 2}));
for (int i = 0; i < 3; ++i)
for (int j = 0; j < 2; ++j) EXPECT_EQ(B(i, j), j + 2 * i + 1);
// 3d
nda::array<double, 3> C = {{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}, {{100, 200, 300, 400}, {500, 600, 700, 800}, {900, 1000, 1100, 1200}}};
EXPECT_EQ(C.shape(), (nda::shape_t<3>{2, 3, 4}));
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 3; ++j)
for (int k = 0; k < 4; ++k) EXPECT_EQ(C(i, j, k), (i == 0 ? 1 : 100) * (k + 4 * j + 1));
// matrix
nda::matrix<double> M = {{1, 2}, {3, 4}, {5, 6}};
EXPECT_EQ(M.shape(), (nda::shape_t<2>{3, 2}));
for (int i = 0; i < 3; ++i)
for (int j = 0; j < 2; ++j) EXPECT_EQ(M(i, j), j + 2 * i + 1);
}
// ==============================================================
TEST(NDA, InitList2) { //NOLINT
// testing more complex cases
nda::array<std::array<double, 2>, 1> aa{{0.0, 0.0}, {0.0, 1.0}, {1.0, 0.0}, {1.0, 1.0}};
EXPECT_EQ(aa(3), (std::array<double, 2>{1, 1}));
nda::array<double, 1> a{1, 2, 3.2};
EXPECT_EQ_ARRAY(a, (nda::array<double, 1>{1.0, 2.0, 3.2}));
}
// ==============================================================
TEST(NDA, MoveConstructor) { //NOLINT
nda::array<double, 1> A(3);
A() = 9;
nda::array<double, 1> B(std::move(A));
EXPECT_TRUE(A.empty());
EXPECT_EQ(B.shape(), (nda::shape_t<1>{3}));
for (int i = 0; i < 3; ++i) EXPECT_EQ(B(i), 9);
}
// ==============================================================
TEST(NDA, MoveAssignment) { //NOLINT
nda::array<double, 1> A(3);
A() = 9;
nda::array<double, 1> B;
B = std::move(A);
EXPECT_TRUE(A.empty());
EXPECT_EQ(B.shape(), (nda::shape_t<1>{3}));
for (int i = 0; i < 3; ++i) EXPECT_EQ(B(i), 9);
}
// ===================== SWAP =========================================
TEST(Swap, StdSwap) { //NOLINT
auto V = nda::array<long, 1>{3, 3, 3};
auto W = nda::array<long, 1>{4, 4, 4, 4};
std::swap(V, W);
// THIS Should not compile : deleted function
//auto VV = V(range(0, 2));
//auto WW = W(range(0, 2));
//std::swap(VV, WW);
// V , W are swapped
EXPECT_EQ(V, (nda::array<long, 1>{4, 4, 4, 4}));
EXPECT_EQ(W, (nda::array<long, 1>{3, 3, 3}));
}
// ----------------------------------
TEST(Swap, SwapView) { //NOLINT
auto V = nda::array<long, 1>{3, 3, 3};
auto W = nda::array<long, 1>{4, 4, 4, 4};
// swap the view, not the vectors. Views are pointers
// FIXME should we keep this behaviour ?
auto VV = V(range(0, 2));
auto WW = W(range(0, 2));
swap(VV, WW);
// V, W unchanged
EXPECT_EQ(V, (nda::array<long, 1>{3, 3, 3}));
EXPECT_EQ(W, (nda::array<long, 1>{4, 4, 4, 4}));
// VV, WW swapped
EXPECT_EQ(WW, (nda::array<long, 1>{3, 3}));
EXPECT_EQ(VV, (nda::array<long, 1>{4, 4}));
}
// ----------------------------------
// FIXME Rename as BLAS_SWAP (swap of blas). Only for vector of same size
TEST(Swap, DeepSwap) { //NOLINT
auto V = nda::array<long, 1>{3, 3, 3};
auto W = nda::array<long, 1>{4, 4, 4};
deep_swap(V(), W());
// V , W are swapped
EXPECT_EQ(V, (nda::array<long, 1>{4, 4, 4}));
EXPECT_EQ(W, (nda::array<long, 1>{3, 3, 3}));
}
// ----------------------------------
TEST(Swap, DeepSwapView) { //NOLINT
auto V = nda::array<long, 1>{3, 3, 3};
auto W = nda::array<long, 1>{4, 4, 4, 4};
auto VV = V(range(0, 2));
auto WW = W(range(0, 2));
deep_swap(VV, WW);
// VV, WW swapped
EXPECT_EQ(WW, (nda::array<long, 1>{3, 3}));
EXPECT_EQ(VV, (nda::array<long, 1>{4, 4}));
// V, W changed
EXPECT_EQ(V, (nda::array<long, 1>{4, 4, 3}));
EXPECT_EQ(W, (nda::array<long, 1>{3, 3, 4, 4}));
}
// ==============================================================
TEST(NDA, Print) { //NOLINT
nda::array<long, 2> A(2, 3), B;
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 3; ++j) A(i, j) = 10 * i + j;
EXPECT_PRINT("\n[[0,1,2]\n [10,11,12]]", A);
}
// =========== Cross construction ===================================================
TEST(Array, CrossConstruct1) { //NOLINT
nda::array<int, 1> Vi(3);
Vi() = 3;
nda::array<double, 1> Vd(Vi);
EXPECT_ARRAY_NEAR(Vd, Vi);
}
// ------------------
TEST(Array, CrossConstruct2) { //NOLINT
nda::array<long, 2> A(2, 3);
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 3; ++j) A(i, j) = 10 * i + j;
std::vector<nda::array<long, 2>> V(3, A);
std::vector<nda::array_view<long, 2>> W;
for (auto &x : V) W.emplace_back(x);
std::vector<nda::array_view<long, 2>> W2(W);
for (int i = 1; i < 3; ++i) V[i] *= i;
for (int i = 1; i < 3; ++i) EXPECT_ARRAY_NEAR(W2[i], i * A);
}
// ------------------
// check non ambiguity of resolution, solved by the check of value type in the constructor
struct A {};
struct B {};
std::ostream &operator<<(std::ostream &out, A) { return out; }
std::ostream &operator<<(std::ostream &out, B) { return out; }
int f1(nda::array<A, 1>) { return 1; }
int f1(nda::array<B, 1>) { return 2; }
TEST(Array, CrossConstruct3) { //NOLINT
nda::array<A, 1> a(2);
auto v = a();
EXPECT_EQ(f1(v), 1);
}
// =============================================================
TEST(NDA, ConvertibleCR) { //NOLINT
nda::array<double, 2> A(2, 2);
nda::array<dcomplex, 2> B(2, 2);
//A = B; // should not compile
B = A;
auto c = nda::array<dcomplex, 2>{A};
// can convert an array of double to an array of complex
static_assert(std::is_constructible_v<nda::array<dcomplex, 2>, nda::array<double, 2>>, "oops");
// can not do the reverse !
//static_assert(not std::is_constructible_v<nda::array<double, 2>, nda::array<dcomplex, 2>>, "oops");
}
// =============================================================
TEST(Assign, CrossStrideOrder) { //NOLINT
// check that = is ok, specially in the contiguous case where we have linear optimisation
// which should NOT be used in this case ...
nda::array<long, 3> a(2, 3, 4);
nda::array<long, 3, nda::F_layout> af(2, 3, 4);
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 3; ++j)
for (int k = 0; k < 4; ++k) { a(i, j, k) = i + 10 * j + 100 * k; }
af = a;
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 3; ++j)
for (int k = 0; k < 4; ++k) { EXPECT_EQ(af(i, j, k), i + 10 * j + 100 * k); }
}
| 28.1625 | 150 | 0.510342 | [
"shape",
"vector",
"3d"
] |
6a82583740b7df07b7e90498fcb303548b92375f | 1,040 | hpp | C++ | include/xul/net/url_session.hpp | hindsights/xul | 666ce90742a9919d538ad5c8aad618737171e93b | [
"MIT"
] | 2 | 2018-03-16T07:06:48.000Z | 2018-04-02T03:02:14.000Z | include/xul/net/url_session.hpp | hindsights/xul | 666ce90742a9919d538ad5c8aad618737171e93b | [
"MIT"
] | null | null | null | include/xul/net/url_session.hpp | hindsights/xul | 666ce90742a9919d538ad5c8aad618737171e93b | [
"MIT"
] | 1 | 2019-08-12T05:15:29.000Z | 2019-08-12T05:15:29.000Z | #pragma once
//#include <xul/net/tcp_socket.hpp>
#include <xul/lang/object.hpp>
#include <stdint.h>
namespace xul {
class tcp_socket;
class url_response;
class url_session;
class url_session_listener
{
public:
virtual void on_session_close(url_session* session) = 0;
};
/// handles a single url request from client
class url_session : public object
{
public:
virtual void close() = 0;
virtual void finish() = 0;
virtual void reset() = 0;
virtual tcp_socket* get_connection() = 0;
virtual url_response* get_response() = 0;
virtual bool send_header() = 0;
virtual bool send_data(const uint8_t* data, int size) = 0;
virtual bool is_chunked() const = 0;
virtual void set_chunked(bool enabled) = 0;
virtual bool is_finished() const = 0;
virtual bool is_keep_alive() const = 0;
virtual void set_keep_alive(bool keep_alive) = 0;
virtual void register_listener(url_session_listener* listener) = 0;
virtual void unregister_listener(url_session_listener* listener) = 0;
};
}
| 21.22449 | 73 | 0.707692 | [
"object"
] |
6a84295d70ce9b2d213de08d60b175dc7931b36f | 3,637 | cpp | C++ | FokkerPlankCPP/main.cpp | kcdodd/masters | e96fc2feaa6edffb99f90278e14a8fcdd138db75 | [
"MIT"
] | null | null | null | FokkerPlankCPP/main.cpp | kcdodd/masters | e96fc2feaa6edffb99f90278e14a8fcdd138db75 | [
"MIT"
] | null | null | null | FokkerPlankCPP/main.cpp | kcdodd/masters | e96fc2feaa6edffb99f90278e14a8fcdd138db75 | [
"MIT"
] | null | null | null | #include <iostream>
#include "dynarray.hpp"
#include "dynmatrix.hpp"
#include "LoadInelasticRates.hpp"
#include "FokkerPlanck.hpp"
#include "FokkerPlanck.cpp"
#include "SaveF.hpp"
#include <cmath>
#include "Constants.hpp"
#include <sstream>
#include <stdio.h>
#include <boost/thread/thread.hpp>
#include <boost/bind.hpp>
#include <time.h>
using namespace std;
template<class T>
class FP_Case{
private:
const std::vector<T>& m_excitation_energies;
const std::vector< dynarray<T> >& m_excitation_rates;
T m_ionization_energy;
const dynarray<T> & m_ionization_rate;
unsigned int m_num_velocities;
public:
FP_Case(
const std::vector<T>& excitation_energies,
const std::vector< dynarray<T> >& excitation_rates,
T ionization_energy,
const dynarray<T> & ionization_rate,
unsigned int num_velocities)
:
m_excitation_energies(excitation_energies),
m_excitation_rates(excitation_rates),
m_ionization_energy(ionization_energy),
m_ionization_rate(ionization_rate),
m_num_velocities(num_velocities)
{}
void run(
T Te,
T ne,
T rate_multiplier,
T dt,
string outfile,
T vth_mult)
{
double Te_eff;
double vth = sqrt(2*ELEMENTAL_CHARGE*Te/ELECTRON_MASS);
FokkerPlanck<double> solver(m_excitation_energies, m_excitation_rates, m_ionization_energy, m_ionization_rate, m_num_velocities, vth_mult*vth, Te, ne, rate_multiplier);
double equib_rate = solver.step(dt, 1000*dt, 50.0, 100E6, Te_eff);
SaveF<double> saver;
saver.save(outfile, solver.f(), Te, ne, rate_multiplier*1E17, equib_rate, Te_eff);
cout << "Completed Te_ff = " << Te_eff << ", equib_rate = " << equib_rate << ": " << outfile << endl;
}
};
int main()
{
LoadInelasticRates<double> loader("ar_inelastic_rates_1E17_640eV.txt");
std::vector<double> excitation_energies;
std::vector< dynarray<double> > excitation_rates;
double ionization_energy;
dynarray<double> ionization_rate;
loader.load(excitation_energies, excitation_rates, ionization_energy, ionization_rate);
//cout << excitation_rates[0].dx() << endl;
unsigned int num_Te = 6;
double Te[] = {0.5, 1.0, 2.0, 5.0, 10.0, 20.0};
double dt[] = {5E-14, 1E-13, 1E-13, 1E-11, 1E-11, 1E-11};
double vth_mult[] = {7, 5, 5, 5, 5, 5};
unsigned int num_ne = 8;
double ne[] = {1E16, 2E16, 5E16, 1E17, 2E17, 5E17, 1E18, 2E18};
unsigned int num_n0 = 7;
double n0[] = {1.0, 2.0, 5.0, 10.0, 20.0, 50.0, 100.0};
FP_Case<double> cases(excitation_energies, excitation_rates, ionization_energy, ionization_rate, 501);
cout << "Beginning Calculations" << endl;
boost::thread_group case_threads;
for (unsigned int Te_i = 0; Te_i < num_Te; ++Te_i)
{
for (unsigned int ne_i = 0; ne_i < num_ne; ++ne_i)
{
for (unsigned int n0_i = 0; n0_i < num_n0; ++n0_i)
{
stringstream outfile;
outfile << "output7/ar_evdf_Te" << Te_i << "_ne" << ne_i << "_n0" << n0_i << ".txt";
case_threads.create_thread(boost::bind(&FP_Case<double>::run, &cases, Te[Te_i], ne[ne_i], n0[n0_i], dt[Te_i], outfile.str(), vth_mult[Te_i]));
//cases.run(Te[Te_i], ne[ne_i], n0[n0_i], dt[Te_i], outfile.str());
} // n0
} // ne
} // Te
case_threads.join_all();
cout << "Fokker-Planck Done." << endl;
return 0;
}
| 25.256944 | 184 | 0.612868 | [
"vector"
] |
6a8904a881b1f36c7646e8cf90c691e496162429 | 2,364 | cpp | C++ | modules/task_3/loganov_a_radix_sort/main.cpp | LioBuitrago/pp_2020_autumn_informatics | 1ecc1b5dae978295778176ff11ffe42bedbc602e | [
"BSD-3-Clause"
] | null | null | null | modules/task_3/loganov_a_radix_sort/main.cpp | LioBuitrago/pp_2020_autumn_informatics | 1ecc1b5dae978295778176ff11ffe42bedbc602e | [
"BSD-3-Clause"
] | 1 | 2021-02-13T03:00:05.000Z | 2021-02-13T03:00:05.000Z | modules/task_3/loganov_a_radix_sort/main.cpp | LioBuitrago/pp_2020_autumn_informatics | 1ecc1b5dae978295778176ff11ffe42bedbc602e | [
"BSD-3-Clause"
] | 1 | 2020-10-11T09:11:57.000Z | 2020-10-11T09:11:57.000Z | // Copyright 2020 Loganov Andrei
#include <mpi.h>
#include <gtest-mpi-listener.hpp>
#include <gtest/gtest.h>
#include <vector>
#include <random>
#include <ctime>
#include <numeric>
#include "./radix.h"
TEST(TEST_PARALEL_MPI, TEST1) {
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
int n = 100;
std::vector<double> t = getRandomVector(n);
std::vector<double> lin;
std::vector<double> Par;
Par = ParallelSort(t);
if (rank == 0) {
lin = seqRadixSort(t);
ASSERT_EQ(Par, lin);
}
}
TEST(TEST_PARALEL_MPI, TEST2) {
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
int n = 221;
std::vector<double> t = getRandomVector(n);
std::vector<double> lin;
std::vector<double> Par;
Par = ParallelSort(t);
if (rank == 0) {
lin = seqRadixSort(t);
ASSERT_EQ(Par, lin);
}
}
TEST(TEST_PARALEL_MPI, TEST3) {
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
int n = 500;
std::vector<double> t = getRandomVector(n);
std::vector<double> lin;
std::vector<double> Par;
Par = ParallelSort(t);
if (rank == 0) {
lin = seqRadixSort(t);
ASSERT_EQ(Par, lin);
}
}
TEST(TEST_PARALEL_MPI, TEST4) {
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
int n = 1036;
std::vector<double> t = getRandomVector(n);
std::vector<double> lin;
std::vector<double> Par;
Par = ParallelSort(t);
if (rank == 0) {
lin = seqRadixSort(t);
ASSERT_EQ(Par, lin);
}
}
TEST(TEST_PARALEL_MPI, TEST5) {
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
int n = 1500;
std::vector<double> t = getRandomVector(n);
std::vector<double> lin;
std::vector<double> Par;
Par = ParallelSort(t);
if (rank == 0) {
lin = seqRadixSort(t);
ASSERT_EQ(Par, lin);
}
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
MPI_Init(&argc, &argv);
::testing::AddGlobalTestEnvironment(new GTestMPIListener::MPIEnvironment);
::testing::TestEventListeners& listeners =
::testing::UnitTest::GetInstance()->listeners();
listeners.Release(listeners.default_result_printer());
listeners.Release(listeners.default_xml_generator());
listeners.Append(new GTestMPIListener::MPIMinimalistPrinter);
return RUN_ALL_TESTS();
}
| 26.561798 | 78 | 0.623519 | [
"vector"
] |
6a8b2b503858f07ffeec16acc1fdd154a0792f86 | 29,020 | cpp | C++ | src/tests/accuracy_test_directed.cpp | JishinMaster/clFFT | b22bef6eab6f22ee5cd6d589177af6b829644a84 | [
"Apache-2.0"
] | null | null | null | src/tests/accuracy_test_directed.cpp | JishinMaster/clFFT | b22bef6eab6f22ee5cd6d589177af6b829644a84 | [
"Apache-2.0"
] | null | null | null | src/tests/accuracy_test_directed.cpp | JishinMaster/clFFT | b22bef6eab6f22ee5cd6d589177af6b829644a84 | [
"Apache-2.0"
] | null | null | null | /* ************************************************************************
* Copyright 2013 Advanced Micro Devices, 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 <algorithm>
#include <gtest/gtest.h>
#include <list>
#include <memory>
#include <numeric>
#include <time.h>
#include <vector>
#include "accuracy_test_common.h"
#include "clFFT.h"
#include "cl_transform.h"
#include "fftw_transform.h"
#include "test_constants.h"
#include "typedefs.h"
namespace DirectedTest {
layout::buffer_layout_t cl_layout_to_buffer_layout(clfftLayout cl_layout) {
if (cl_layout == CLFFT_REAL)
return layout::real;
else if (cl_layout == CLFFT_HERMITIAN_PLANAR)
return layout::hermitian_planar;
else if (cl_layout == CLFFT_COMPLEX_PLANAR)
return layout::complex_planar;
else if (cl_layout == CLFFT_HERMITIAN_INTERLEAVED)
return layout::hermitian_interleaved;
else if (cl_layout == CLFFT_COMPLEX_INTERLEAVED)
return layout::complex_interleaved;
else
throw std::runtime_error("invalid cl_layout");
}
struct ParametersPacked {
// directed inputs
size_t batch_size;
clfftPrecision precision;
clfftDirection direction;
clfftDim dimensions;
std::vector<size_t> lengths;
// calculated
std::vector<size_t> input_strides;
std::vector<size_t> output_strides;
size_t input_distance;
size_t output_distance;
clfftLayout input_layout;
clfftLayout output_layout;
ParametersPacked(clfftPrecision precision_in, clfftDirection direction_in,
clfftDim dimensions_in,
const std::vector<size_t> &lengths_in, size_t batch_size_in)
: precision(precision_in), direction(direction_in),
dimensions(dimensions_in), batch_size(batch_size_in) {
for (size_t i = 0; i < lengths_in.size(); i++)
lengths.push_back(lengths_in[i]);
}
};
struct ParametersPackedRealInplaceInterleaved : public ParametersPacked {
bool is_r2c() {
if (input_layout == CLFFT_REAL)
return true;
else
return false;
}
bool is_c2r() {
if (output_layout == CLFFT_REAL)
return true;
else
return false;
}
ParametersPackedRealInplaceInterleaved(clfftPrecision precision_in,
clfftDirection direction_in,
clfftDim dimensions_in,
const std::vector<size_t> &lengths_in,
size_t batch_size_in)
: ParametersPacked(precision_in, direction_in, dimensions_in, lengths_in,
batch_size_in) {
try {
input_strides.push_back(1);
output_strides.push_back(1);
if ((direction_in == CLFFT_FORWARD) || (direction_in == CLFFT_MINUS)) {
input_layout = CLFFT_REAL;
output_layout = CLFFT_HERMITIAN_INTERLEAVED;
input_distance = 2 * (1 + lengths[0] / 2);
output_distance = 1 + lengths[0] / 2;
} else {
input_layout = CLFFT_HERMITIAN_INTERLEAVED;
output_layout = CLFFT_REAL;
input_distance = 1 + lengths[0] / 2;
output_distance = 2 * (1 + lengths[0] / 2);
}
for (size_t i = 1; i < lengths.size(); i++) {
input_strides.push_back(input_distance);
output_strides.push_back(output_distance);
input_distance *= lengths[i];
output_distance *= lengths[i];
}
if (is_r2c()) {
// check for ok
if (dimensions >= 2)
if (input_strides[1] != 2 * output_strides[1])
throw std::runtime_error("invalid stride y generated for r2c");
if (dimensions >= 3)
if (input_strides[2] != 2 * output_strides[2])
throw std::runtime_error("invalid stride z generated for r2c");
if (input_distance != 2 * output_distance)
throw std::runtime_error("invalid distance generated for r2c");
}
if (is_c2r()) {
// check for ok
if (dimensions >= 2)
if (output_strides[1] != 2 * input_strides[1])
throw std::runtime_error("invalid stride y generated for c2r");
if (dimensions >= 3)
if (output_strides[2] != 2 * input_strides[2])
throw std::runtime_error("invalid stride z generated for c2r");
if (output_distance != 2 * input_distance)
throw std::runtime_error("invalid distance generated for c2r");
}
} catch (const std::exception &err) {
handle_exception(err);
}
}
}; // struct ParametersPackedRealInplaceInterleaved
struct ParametersPackedComplexInplaceInterleaved : public ParametersPacked {
ParametersPackedComplexInplaceInterleaved(
clfftPrecision precision_in, clfftDirection direction_in,
clfftDim dimensions_in, const std::vector<size_t> &lengths_in,
size_t batch_size_in)
: ParametersPacked(precision_in, direction_in, dimensions_in, lengths_in,
batch_size_in) {
try {
input_strides.push_back(1);
output_strides.push_back(1);
input_layout = CLFFT_COMPLEX_INTERLEAVED;
output_layout = CLFFT_COMPLEX_INTERLEAVED;
input_distance = lengths[0];
output_distance = lengths[0];
for (size_t i = 1; i < lengths.size(); i++) {
input_strides.push_back(input_distance);
output_strides.push_back(output_distance);
input_distance *= lengths[i];
output_distance *= lengths[i];
}
} catch (const std::exception &err) {
handle_exception(err);
}
}
}; // struct ParametersPackedComplexInplaceInterleaved
template <class ParameterType> class TestListGenerator {
protected:
std::vector<ParameterType> data_sets;
const size_t *supported_length;
size_t size_supported_length;
virtual void supported_length_data() {
// This array must be kept sorted in the ascending order
static const size_t supported_length_array[] = {
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
13, 14, 15, 16, 18, 20, 21, 22, 24, 25, 26, 27,
28, 30, 32, 33, 35, 36, 39, 40, 42, 44, 45, 48,
49, 50, 52, 54, 55, 56, 60, 63, 64, 65, 66, 70,
72, 75, 77, 78, 80, 81, 84, 88, 90, 91, 96, 98,
99, 100, 104, 105, 108, 110, 112, 117, 120, 121, 125, 126,
128, 130, 132, 135, 140, 143, 144, 147, 150, 154, 156, 160,
162, 165, 168, 169, 175, 176, 180, 182, 189, 192, 195, 196,
198, 200, 208, 210, 216, 220, 224, 225, 231, 234, 240, 242,
243, 245, 250, 252, 256, 260, 264, 270, 273, 275, 280, 286,
288, 294, 297, 300, 308, 312, 315, 320, 324, 325, 330, 336,
338, 343, 350, 351, 352, 360, 363, 364, 375, 378, 384, 385,
390, 392, 396, 400, 405, 416, 420, 429, 432, 440, 441, 448,
450, 455, 462, 468, 480, 484, 486, 490, 495, 500, 504, 507,
512, 520, 525, 528, 539, 540, 546, 550, 560, 567, 572, 576,
585, 588, 594, 600, 605, 616, 624, 625, 630, 637, 640, 648,
650, 660, 672, 675, 676, 686, 693, 700, 702, 704, 715, 720,
726, 728, 729, 735, 750, 756, 768, 770, 780, 784, 792, 800,
810, 819, 825, 832, 840, 845, 847, 858, 864, 875, 880, 882,
891, 896, 900, 910, 924, 936, 945, 960, 968, 972, 975, 980,
990, 1000, 1001, 1008, 1014, 1024, 1029, 1040, 1050, 1053, 1056, 1078,
1080, 1089, 1092, 1100, 1120, 1125, 1134, 1144, 1152, 1155, 1170, 1176,
1183, 1188, 1200, 1210, 1215, 1225, 1232, 1248, 1250, 1260, 1274, 1280,
1287, 1296, 1300, 1320, 1323, 1331, 1344, 1350, 1352, 1365, 1372, 1375,
1386, 1400, 1404, 1408, 1430, 1440, 1452, 1456, 1458, 1470, 1485, 1500,
1512, 1521, 1536, 1540, 1560, 1568, 1573, 1575, 1584, 1600, 1617, 1620,
1625, 1638, 1650, 1664, 1680, 1690, 1694, 1701, 1715, 1716, 1728, 1750,
1755, 1760, 1764, 1782, 1792, 1800, 1815, 1820, 1848, 1859, 1872, 1875,
1890, 1911, 1920, 1925, 1936, 1944, 1950, 1960, 1980, 2000, 2002, 2016,
2025, 2028, 2048, 2058, 2079, 2080, 2100, 2106, 2112, 2145, 2156, 2160,
2178, 2184, 2187, 2197, 2200, 2205, 2240, 2250, 2268, 2275, 2288, 2304,
2310, 2340, 2352, 2366, 2376, 2400, 2401, 2420, 2430, 2450, 2457, 2464,
2475, 2496, 2500, 2520, 2535, 2541, 2548, 2560, 2574, 2592, 2600, 2625,
2640, 2646, 2662, 2673, 2688, 2695, 2700, 2704, 2730, 2744, 2750, 2772,
2800, 2808, 2816, 2835, 2860, 2880, 2904, 2912, 2916, 2925, 2940, 2970,
3000, 3003, 3024, 3025, 3042, 3072, 3080, 3087, 3120, 3125, 3136, 3146,
3150, 3159, 3168, 3185, 3200, 3234, 3240, 3250, 3267, 3276, 3300, 3328,
3360, 3375, 3380, 3388, 3402, 3430, 3432, 3456, 3465, 3500, 3510, 3520,
3528, 3549, 3564, 3575, 3584, 3600, 3630, 3640, 3645, 3675, 3696, 3718,
3744, 3750, 3773, 3780, 3822, 3840, 3850, 3861, 3872, 3888, 3900, 3920,
3960, 3969, 3993, 4000, 4004, 4032, 4050, 4056, 4095, 4096};
supported_length = supported_length_array;
size_supported_length =
sizeof(supported_length_array) / sizeof(supported_length_array[0]);
}
virtual void generate_1d(clfftDirection dir, clfftPrecision precision,
size_t batch) {
for (size_t i = 0; i < size_supported_length; i++) {
std::vector<size_t> length;
length.push_back(supported_length[i]);
data_sets.push_back(
ParameterType(precision, dir, CLFFT_1D, length, batch));
}
}
virtual void generate_2d(clfftDirection dir, clfftPrecision precision,
size_t batch) {
for (size_t i = 0; i < size_supported_length; i++) {
std::vector<size_t> length;
length.push_back(supported_length[i]);
length.push_back(supported_length[i]);
data_sets.push_back(
ParameterType(precision, dir, CLFFT_2D, length, batch));
}
}
virtual void generate_3d(clfftDirection dir, clfftPrecision precision,
size_t batch) {
for (size_t i = 0; i < size_supported_length; i++) {
std::vector<size_t> length;
length.push_back(supported_length[i]);
length.push_back(supported_length[i]);
length.push_back(supported_length[i]);
data_sets.push_back(
ParameterType(precision, dir, CLFFT_3D, length, batch));
const size_t max_3d_length = 256;
if (supported_length[i] == max_3d_length)
break;
}
}
public:
TestListGenerator() : supported_length(NULL), size_supported_length(0) {}
virtual std::vector<ParameterType> ¶meter_sets(clfftDim dimension,
clfftDirection direction,
clfftPrecision precision,
size_t batch) {
supported_length_data();
switch (dimension) {
case CLFFT_1D:
generate_1d(direction, precision, batch);
break;
case CLFFT_2D:
generate_2d(direction, precision, batch);
break;
case CLFFT_3D:
generate_3d(direction, precision, batch);
break;
}
return data_sets;
}
}; // class TestListGenerator
template <class ParameterType>
class TestListGenerator_Pow2 : public TestListGenerator<ParameterType> {
protected:
virtual void supported_length_data() {
// This array must be kept sorted in the ascending order
static const size_t supported_length_array[] = {
8192, 16384, 32768, 65536, 131072,
262144, 524288, 1048576, 2097152, 4194304};
TestListGenerator<ParameterType>::supported_length = supported_length_array;
TestListGenerator<ParameterType>::size_supported_length =
sizeof(supported_length_array) / sizeof(supported_length_array[0]);
}
};
template <class ParameterType> class TestListGenerator_Large_Random {
protected:
std::vector<size_t> supported_length;
std::vector<ParameterType> data_sets;
void GenerateSizes(size_t maximum_size) {
std::list<size_t> sizes;
size_t i = 0, j = 0, k = 0, l = 0, m = 0, n = 0;
size_t sum, sumi, sumj, sumk, suml, summ, sumn;
sumi = 1;
i = 0;
while (1) {
sumj = 1;
j = 0;
while (1) {
sumk = 1;
k = 0;
while (1) {
suml = 1;
l = 0;
while (1) {
summ = 1;
m = 0;
while (1) {
sumn = 1;
n = 0;
while (1) {
sum = (sumi * sumj * sumk * suml * summ * sumn);
if (sum > maximum_size)
break;
sizes.push_back(sum);
n++;
sumn *= 2;
}
if (n == 0)
break;
m++;
summ *= 3;
}
if ((m == 0) && (n == 0))
break;
l++;
suml *= 5;
}
if ((l == 0) && (m == 0) && (n == 0))
break;
k++;
sumk *= 7;
}
if ((k == 0) && (l == 0) && (m == 0) && (n == 0))
break;
j++;
sumj *= 11;
}
if ((j == 0) && (k == 0) && (l == 0) && (m == 0) && (n == 0))
break;
i++;
sumi *= 13;
}
sizes.sort();
for (std::list<size_t>::const_iterator a = sizes.begin(); a != sizes.end();
a++)
supported_length.push_back(*a);
}
public:
virtual std::vector<ParameterType> ¶meter_sets(clfftDirection direction,
clfftPrecision precision,
size_t num_tests) {
size_t maximum_size = (precision == CLFFT_SINGLE) ? 16777216 : 4194304;
GenerateSizes(maximum_size);
assert(supported_length.size() < RAND_MAX);
for (size_t i = 0; i < num_tests; i++) {
size_t idx = 0;
// choose size that has a 11 or 13 in it
do {
// choose index randomly
idx = rand() % supported_length.size();
} while ((supported_length[idx] % 11 != 0) &&
(supported_length[idx] % 13 != 0));
std::vector<size_t> length;
length.push_back(supported_length[idx]);
size_t batch = maximum_size / supported_length[idx];
data_sets.push_back(
ParameterType(precision, direction, CLFFT_1D, length, batch));
}
return data_sets;
}
};
template <class ParameterType>
class TestListGenerator_huge_chosen : public TestListGenerator<ParameterType> {
protected:
virtual void supported_length_data() {
// This array must be kept sorted in the ascending order
static const size_t supported_length_array[] = {
25050025, 27027000, 17320303, 19487171, 4826809,
53094899, 23030293, 214358881, 62748517};
TestListGenerator<ParameterType>::supported_length = supported_length_array;
TestListGenerator<ParameterType>::size_supported_length =
sizeof(supported_length_array) / sizeof(supported_length_array[0]);
}
};
} // namespace DirectedTest
class accuracy_test_directed_base
: public ::testing::TestWithParam<DirectedTest::ParametersPacked> {
protected:
accuracy_test_directed_base() {}
virtual ~accuracy_test_directed_base() {}
virtual void SetUp() {}
virtual void TearDown() {}
public:
static void RunTest(const DirectedTest::ParametersPacked *params_ptr) {
const DirectedTest::ParametersPacked ¶ms = *params_ptr;
try {
RecordProperty("batch_size", (int)params.batch_size);
RecordProperty("precision", params.precision);
RecordProperty("direction", params.direction);
RecordProperty("dimensions", params.dimensions);
RecordProperty("length_x", (int)params.lengths[0]);
if (params.dimensions >= CLFFT_2D)
RecordProperty("length_y", (int)params.lengths[1]);
if (params.dimensions >= CLFFT_3D)
RecordProperty("length_z", (int)params.lengths[2]);
if (params.input_strides.empty()) {
RecordProperty("input_strides", 0);
} else {
RecordProperty("input_stride_x", (int)params.input_strides[0]);
if (params.dimensions >= CLFFT_2D)
RecordProperty("input_stride_y", (int)params.input_strides[1]);
if (params.dimensions >= CLFFT_3D)
RecordProperty("input_stride_z", (int)params.input_strides[2]);
}
if (params.output_strides.empty()) {
RecordProperty("output_strides", 0);
} else {
RecordProperty("output_stride_x", (int)params.output_strides[0]);
if (params.dimensions >= CLFFT_2D)
RecordProperty("output_stride_y", (int)params.output_strides[1]);
if (params.dimensions >= CLFFT_3D)
RecordProperty("output_stride_z", (int)params.output_strides[2]);
}
RecordProperty("input_distance", (int)params.input_distance);
RecordProperty("output_distance", (int)params.output_distance);
RecordProperty("input_layout", params.input_layout);
RecordProperty("output_layout", params.output_layout);
if (params.precision == CLFFT_SINGLE) {
if (params.input_layout == CLFFT_REAL) {
real_to_complex<float, cl_float, fftwf_complex>(
erratic, params.lengths, params.batch_size, params.input_strides,
params.output_strides, params.input_distance,
params.output_distance,
DirectedTest::cl_layout_to_buffer_layout(params.output_layout),
placeness::in_place);
} else if (params.output_layout == CLFFT_REAL) {
complex_to_real<float, cl_float, fftwf_complex>(
erratic, params.lengths, params.batch_size, params.input_strides,
params.output_strides, params.input_distance,
params.output_distance,
DirectedTest::cl_layout_to_buffer_layout(params.input_layout),
placeness::in_place);
} else if ((params.input_layout == CLFFT_COMPLEX_INTERLEAVED ||
params.input_layout == CLFFT_COMPLEX_PLANAR) &&
(params.output_layout == CLFFT_COMPLEX_INTERLEAVED ||
params.output_layout == CLFFT_COMPLEX_PLANAR)) {
complex_to_complex<float, cl_float, fftwf_complex>(
erratic,
params.direction == CLFFT_FORWARD ? direction::forward
: direction::backward,
params.lengths, params.batch_size, params.input_strides,
params.output_strides, params.input_distance,
params.output_distance,
DirectedTest::cl_layout_to_buffer_layout(params.input_layout),
DirectedTest::cl_layout_to_buffer_layout(params.output_layout),
placeness::in_place);
} else {
throw std::runtime_error("bad layout combination");
}
} else if (params.precision == CLFFT_DOUBLE) {
if (params.input_layout == CLFFT_REAL) {
real_to_complex<double, cl_double, fftw_complex>(
erratic, params.lengths, params.batch_size, params.input_strides,
params.output_strides, params.input_distance,
params.output_distance,
DirectedTest::cl_layout_to_buffer_layout(params.output_layout),
placeness::in_place);
} else if (params.output_layout == CLFFT_REAL) {
complex_to_real<double, cl_double, fftw_complex>(
erratic, params.lengths, params.batch_size, params.input_strides,
params.output_strides, params.input_distance,
params.output_distance,
DirectedTest::cl_layout_to_buffer_layout(params.input_layout),
placeness::in_place);
} else if ((params.input_layout == CLFFT_COMPLEX_INTERLEAVED ||
params.input_layout == CLFFT_COMPLEX_PLANAR) &&
(params.output_layout == CLFFT_COMPLEX_INTERLEAVED ||
params.output_layout == CLFFT_COMPLEX_PLANAR)) {
complex_to_complex<double, cl_double, fftw_complex>(
erratic,
params.direction == CLFFT_FORWARD ? direction::forward
: direction::backward,
params.lengths, params.batch_size, params.input_strides,
params.output_strides, params.input_distance,
params.output_distance,
DirectedTest::cl_layout_to_buffer_layout(params.input_layout),
DirectedTest::cl_layout_to_buffer_layout(params.output_layout),
placeness::in_place);
} else {
throw std::runtime_error("bad layout combination");
}
} else {
throw std::runtime_error(
"Random test: this code path should never be executed");
}
} catch (const std::exception &err) {
handle_exception(err);
}
}
};
class accuracy_test_directed_real
: public ::testing::TestWithParam<
DirectedTest::ParametersPackedRealInplaceInterleaved> {
protected:
accuracy_test_directed_real() {}
virtual ~accuracy_test_directed_real() {}
virtual void SetUp() {}
virtual void TearDown() {}
virtual void accuracy_test_directed_packed_real_inplace_interleaved() {
DirectedTest::ParametersPackedRealInplaceInterleaved params = GetParam();
accuracy_test_directed_base::RunTest(¶ms);
}
};
TEST_P(accuracy_test_directed_real, inplace_interleaved) {
accuracy_test_directed_packed_real_inplace_interleaved();
}
INSTANTIATE_TEST_CASE_P(
clfft_DirectedTest_single_1d_fwd, accuracy_test_directed_real,
::testing::ValuesIn(
DirectedTest::TestListGenerator<
DirectedTest::ParametersPackedRealInplaceInterleaved>()
.parameter_sets(CLFFT_1D, CLFFT_FORWARD, CLFFT_SINGLE, 19)));
INSTANTIATE_TEST_CASE_P(
clfft_DirectedTest_single_1d_inv, accuracy_test_directed_real,
::testing::ValuesIn(
DirectedTest::TestListGenerator<
DirectedTest::ParametersPackedRealInplaceInterleaved>()
.parameter_sets(CLFFT_1D, CLFFT_BACKWARD, CLFFT_SINGLE, 19)));
INSTANTIATE_TEST_CASE_P(
clfft_DirectedTest_double_1d_fwd, accuracy_test_directed_real,
::testing::ValuesIn(
DirectedTest::TestListGenerator<
DirectedTest::ParametersPackedRealInplaceInterleaved>()
.parameter_sets(CLFFT_1D, CLFFT_FORWARD, CLFFT_DOUBLE, 19)));
INSTANTIATE_TEST_CASE_P(
clfft_DirectedTest_double_1d_inv, accuracy_test_directed_real,
::testing::ValuesIn(
DirectedTest::TestListGenerator<
DirectedTest::ParametersPackedRealInplaceInterleaved>()
.parameter_sets(CLFFT_1D, CLFFT_BACKWARD, CLFFT_DOUBLE, 19)));
INSTANTIATE_TEST_CASE_P(
clfft_DirectedTest_single_2d_fwd, accuracy_test_directed_real,
::testing::ValuesIn(
DirectedTest::TestListGenerator<
DirectedTest::ParametersPackedRealInplaceInterleaved>()
.parameter_sets(CLFFT_2D, CLFFT_FORWARD, CLFFT_SINGLE, 3)));
INSTANTIATE_TEST_CASE_P(
clfft_DirectedTest_single_2d_inv, accuracy_test_directed_real,
::testing::ValuesIn(
DirectedTest::TestListGenerator<
DirectedTest::ParametersPackedRealInplaceInterleaved>()
.parameter_sets(CLFFT_2D, CLFFT_BACKWARD, CLFFT_SINGLE, 3)));
INSTANTIATE_TEST_CASE_P(
clfft_DirectedTest_single_3d_fwd, accuracy_test_directed_real,
::testing::ValuesIn(
DirectedTest::TestListGenerator<
DirectedTest::ParametersPackedRealInplaceInterleaved>()
.parameter_sets(CLFFT_3D, CLFFT_FORWARD, CLFFT_SINGLE, 1)));
INSTANTIATE_TEST_CASE_P(
clfft_DirectedTest_single_3d_inv, accuracy_test_directed_real,
::testing::ValuesIn(
DirectedTest::TestListGenerator<
DirectedTest::ParametersPackedRealInplaceInterleaved>()
.parameter_sets(CLFFT_3D, CLFFT_BACKWARD, CLFFT_SINGLE, 1)));
INSTANTIATE_TEST_CASE_P(
clfft_DirectedTest_Random_single_1d_fwd, accuracy_test_directed_real,
::testing::ValuesIn(
DirectedTest::TestListGenerator_Large_Random<
DirectedTest::ParametersPackedRealInplaceInterleaved>()
.parameter_sets(CLFFT_FORWARD, CLFFT_SINGLE, 200)));
INSTANTIATE_TEST_CASE_P(
clfft_DirectedTest_Random_single_1d_inv, accuracy_test_directed_real,
::testing::ValuesIn(
DirectedTest::TestListGenerator_Large_Random<
DirectedTest::ParametersPackedRealInplaceInterleaved>()
.parameter_sets(CLFFT_BACKWARD, CLFFT_SINGLE, 200)));
INSTANTIATE_TEST_CASE_P(
clfft_DirectedTest_Random_double_1d_fwd, accuracy_test_directed_real,
::testing::ValuesIn(
DirectedTest::TestListGenerator_Large_Random<
DirectedTest::ParametersPackedRealInplaceInterleaved>()
.parameter_sets(CLFFT_FORWARD, CLFFT_DOUBLE, 200)));
INSTANTIATE_TEST_CASE_P(
clfft_DirectedTest_Random_double_1d_inv, accuracy_test_directed_real,
::testing::ValuesIn(
DirectedTest::TestListGenerator_Large_Random<
DirectedTest::ParametersPackedRealInplaceInterleaved>()
.parameter_sets(CLFFT_BACKWARD, CLFFT_DOUBLE, 200)));
#if 1
INSTANTIATE_TEST_CASE_P(
clfft_DirectedTest_pow2_single_1d_fwd, accuracy_test_directed_real,
::testing::ValuesIn(
DirectedTest::TestListGenerator_Pow2<
DirectedTest::ParametersPackedRealInplaceInterleaved>()
.parameter_sets(CLFFT_1D, CLFFT_FORWARD, CLFFT_SINGLE, 3)));
INSTANTIATE_TEST_CASE_P(
clfft_DirectedTest_pow2_single_1d_inv, accuracy_test_directed_real,
::testing::ValuesIn(
DirectedTest::TestListGenerator_Pow2<
DirectedTest::ParametersPackedRealInplaceInterleaved>()
.parameter_sets(CLFFT_1D, CLFFT_BACKWARD, CLFFT_SINGLE, 3)));
INSTANTIATE_TEST_CASE_P(
clfft_DirectedTest_pow2_double_1d_fwd, accuracy_test_directed_real,
::testing::ValuesIn(
DirectedTest::TestListGenerator_Pow2<
DirectedTest::ParametersPackedRealInplaceInterleaved>()
.parameter_sets(CLFFT_1D, CLFFT_FORWARD, CLFFT_DOUBLE, 3)));
INSTANTIATE_TEST_CASE_P(
clfft_DirectedTest_pow2_double_1d_inv, accuracy_test_directed_real,
::testing::ValuesIn(
DirectedTest::TestListGenerator_Pow2<
DirectedTest::ParametersPackedRealInplaceInterleaved>()
.parameter_sets(CLFFT_1D, CLFFT_BACKWARD, CLFFT_DOUBLE, 3)));
#endif
class accuracy_test_directed_complex
: public ::testing::TestWithParam<
DirectedTest::ParametersPackedComplexInplaceInterleaved> {
protected:
accuracy_test_directed_complex() {}
virtual ~accuracy_test_directed_complex() {}
virtual void SetUp() {}
virtual void TearDown() {}
virtual void accuracy_test_directed_packed_complex_inplace_interleaved() {
DirectedTest::ParametersPackedComplexInplaceInterleaved params = GetParam();
accuracy_test_directed_base::RunTest(¶ms);
}
};
TEST_P(accuracy_test_directed_complex, inplace_interleaved) {
accuracy_test_directed_packed_complex_inplace_interleaved();
}
INSTANTIATE_TEST_CASE_P(
clfft_DirectedTest_single_1d_fwd, accuracy_test_directed_complex,
::testing::ValuesIn(
DirectedTest::TestListGenerator<
DirectedTest::ParametersPackedComplexInplaceInterleaved>()
.parameter_sets(CLFFT_1D, CLFFT_FORWARD, CLFFT_SINGLE, 101)));
INSTANTIATE_TEST_CASE_P(
clfft_DirectedTest_single_1d_inv, accuracy_test_directed_complex,
::testing::ValuesIn(
DirectedTest::TestListGenerator<
DirectedTest::ParametersPackedComplexInplaceInterleaved>()
.parameter_sets(CLFFT_1D, CLFFT_BACKWARD, CLFFT_SINGLE, 101)));
#if 0
INSTANTIATE_TEST_CASE_P(
clfft_DirectedTest_huge_chosen_single_1d_fwd,
accuracy_test_directed_complex,
::testing::ValuesIn(DirectedTest::TestListGenerator_huge_chosen<DirectedTest::ParametersPackedComplexInplaceInterleaved>().parameter_sets(CLFFT_1D, CLFFT_FORWARD, CLFFT_SINGLE, 1))
);
INSTANTIATE_TEST_CASE_P(
clfft_DirectedTest_huge_chosen_single_1d_inv,
accuracy_test_directed_complex,
::testing::ValuesIn(DirectedTest::TestListGenerator_huge_chosen<DirectedTest::ParametersPackedComplexInplaceInterleaved>().parameter_sets(CLFFT_1D, CLFFT_BACKWARD, CLFFT_SINGLE, 1))
);
#endif
| 38.744993 | 182 | 0.643832 | [
"vector"
] |
6a8c0fb835ee3903807b70c48cce9bd57a1e6def | 1,349 | hpp | C++ | hyper/console/switch.hpp | hyperlib/console | 045b36a3a1f0ad3493c7032409f1c4af156ad37a | [
"MIT"
] | null | null | null | hyper/console/switch.hpp | hyperlib/console | 045b36a3a1f0ad3493c7032409f1c4af156ad37a | [
"MIT"
] | null | null | null | hyper/console/switch.hpp | hyperlib/console | 045b36a3a1f0ad3493c7032409f1c4af156ad37a | [
"MIT"
] | null | null | null | // "command.hpp> -*- C++ -*-
/**
* Hyper
*
* (c) 2017 Axel Etcheverry
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#pragma once
#include <sstream>
#include <string>
#include <vector>
#include "option.hpp"
#include "option_value.hpp"
#include "value.hpp"
namespace hyper {
namespace console {
class Switch : public Value<bool> {
public:
Switch(): Value<bool>("", "", "", false)
{
setType(OptionValue::None);
}
Switch(const std::string& shortOption, const std::string& longOption, const std::string& description):
Value<bool>(shortOption, longOption, description, false)
{
setType(OptionValue::None);
}
virtual void parse(const std::string& whatOption, const std::string& value) {
addValue(true);
}
virtual std::string optionToString() const {
return Option::optionToString();
}
Switch& assignTo(bool* var) {
m_assign_to = var;
return *this;
}
Switch& setDefault(const bool& value) {
m_default = value;
m_has_default = true;
return *this;
}
};
} // end of console namespace
} // end of hyper namespace
| 22.114754 | 110 | 0.576723 | [
"vector"
] |
6a926b89fd6155330c009332e92ebcd63a764d66 | 3,488 | cpp | C++ | Code/Framework/AzToolsFramework/AzToolsFramework/Application/EditorEntityManager.cpp | CStudios15/o3de | 9dc85000a3ec1a6c6633d718f5c455ab11a46818 | [
"Apache-2.0",
"MIT"
] | 11 | 2021-07-08T09:58:26.000Z | 2022-03-17T17:59:26.000Z | Code/Framework/AzToolsFramework/AzToolsFramework/Application/EditorEntityManager.cpp | RoddieKieley/o3de | e804fd2a4241b039a42d9fa54eaae17dc94a7a92 | [
"Apache-2.0",
"MIT"
] | 29 | 2021-07-06T19:33:52.000Z | 2022-03-22T10:27:49.000Z | Code/Framework/AzToolsFramework/AzToolsFramework/Application/EditorEntityManager.cpp | RoddieKieley/o3de | e804fd2a4241b039a42d9fa54eaae17dc94a7a92 | [
"Apache-2.0",
"MIT"
] | 4 | 2021-07-06T19:24:43.000Z | 2022-03-31T12:42:27.000Z | /*
* 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 <AzToolsFramework/Application/EditorEntityManager.h>
#include <AzToolsFramework/API/ToolsApplicationAPI.h>
#include <AzToolsFramework/Entity/EditorEntityHelpers.h>
namespace AzToolsFramework
{
static bool AreEntitiesValidForDuplication(const EntityIdList& entityIds)
{
for (AZ::EntityId entityId : entityIds)
{
if (GetEntityById(entityId) == nullptr)
{
AZ_Error(
"Entity", false,
"Entity with id '%llu' is not found. This can happen when you try to duplicate the entity before it is created. Please "
"ensure entities are created before trying to duplicate them.",
static_cast<AZ::u64>(entityId));
return false;
}
}
return true;
}
void EditorEntityManager::Start()
{
m_prefabPublicInterface = AZ::Interface<Prefab::PrefabPublicInterface>::Get();
AZ_Assert(m_prefabPublicInterface, "EditorEntityManager - Could not retrieve instance of PrefabPublicInterface");
AZ::Interface<EditorEntityAPI>::Register(this);
}
EditorEntityManager::~EditorEntityManager()
{
// Attempting to Unregister if we never registerd (e.g. if Start() was never called) throws an error, so check that first
EditorEntityAPI* editorEntityInterface = AZ::Interface<EditorEntityAPI>::Get();
if (editorEntityInterface == this)
{
AZ::Interface<EditorEntityAPI>::Unregister(this);
}
}
void EditorEntityManager::DeleteSelected()
{
EntityIdList selectedEntities;
ToolsApplicationRequestBus::BroadcastResult(selectedEntities, &ToolsApplicationRequests::GetSelectedEntities);
m_prefabPublicInterface->DeleteEntitiesInInstance(selectedEntities);
}
void EditorEntityManager::DeleteEntityById(AZ::EntityId entityId)
{
DeleteEntities(EntityIdList{ entityId });
}
void EditorEntityManager::DeleteEntities(const EntityIdList& entities)
{
m_prefabPublicInterface->DeleteEntitiesInInstance(entities);
}
void EditorEntityManager::DeleteEntityAndAllDescendants(AZ::EntityId entityId)
{
DeleteEntitiesAndAllDescendants(EntityIdList{ entityId });
}
void EditorEntityManager::DeleteEntitiesAndAllDescendants(const EntityIdList& entities)
{
m_prefabPublicInterface->DeleteEntitiesAndAllDescendantsInInstance(entities);
}
void EditorEntityManager::DuplicateSelected()
{
EntityIdList selectedEntities;
ToolsApplicationRequestBus::BroadcastResult(selectedEntities, &ToolsApplicationRequests::GetSelectedEntities);
if (AreEntitiesValidForDuplication(selectedEntities))
{
m_prefabPublicInterface->DuplicateEntitiesInInstance(selectedEntities);
}
}
void EditorEntityManager::DuplicateEntityById(AZ::EntityId entityId)
{
DuplicateEntities(EntityIdList{ entityId });
}
void EditorEntityManager::DuplicateEntities(const EntityIdList& entities)
{
if (AreEntitiesValidForDuplication(entities))
{
m_prefabPublicInterface->DuplicateEntitiesInInstance(entities);
}
}
}
| 33.538462 | 140 | 0.69008 | [
"3d"
] |
6a9380042b6ece8eee08df7241998810430f9513 | 4,246 | cc | C++ | tmp/regex.cc | hankai17/test | 8f38d999a7c6a92eac94b4d9dc8e444619d2144f | [
"MIT"
] | 7 | 2017-07-16T15:09:26.000Z | 2021-09-01T02:13:15.000Z | tmp/regex.cc | hankai17/test | 8f38d999a7c6a92eac94b4d9dc8e444619d2144f | [
"MIT"
] | null | null | null | tmp/regex.cc | hankai17/test | 8f38d999a7c6a92eac94b4d9dc8e444619d2144f | [
"MIT"
] | 3 | 2017-09-13T09:54:49.000Z | 2019-03-18T01:29:15.000Z | #include <pcre.h>
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<string>
#include<stdlib.h>
#include <cstdio>
#include <fstream>
#include <errno.h>
class DomainRegex {
public:
DomainRegex()
: _hits(0), _rex_string(NULL), _options(0), _rex(NULL), _extra(NULL), _next(NULL), _order(0) {}
~DomainRegex() {
free(_rex_string);
if(_rex) {
pcre_free(_rex);
}
}
void initialize(const std::string& reg) {
_rex_string = strdup(reg.c_str());
}
//void increment() { ink_atomic_increment(&(_hits), 1); }
void print(int ix, int max, const char *now) {
fprintf(stderr, "[%s]: Regex %d ( %s ): %.2f%%\n", now, ix, _rex_string, 100.0 * _hits / max);
}
int compile(const char **error, int *erroffset) {
int ccount;
//printf("rex_string: %s, optino: %d\n", _rex_string, _options);
_rex = pcre_compile(_rex_string, // the pattern
_options, // options
error, // for error message
erroffset, // for error offset
NULL); // use default character tables
if (NULL == _rex) {
printf("pcre_compile return -1\n");
return -1;
}
_extra = pcre_study(_rex, 0, error);
if ((_extra == NULL) && (*error != 0)) {
printf("pcre_study return -1\n");
return -1;
}
if (pcre_fullinfo(_rex, _extra, PCRE_INFO_CAPTURECOUNT, &ccount) != 0) {
printf("pcre_fullinfo return -1\n");
return -1;
}
return 0;
}
int match(const char *str, int len, int ovector[]) {
return pcre_exec(_rex, // the compiled pattern
_extra, // Extra data from study (maybe)
str, // the subject string
len, // the length of the subject
0, // start at offset 0 in the subject
0, // default options
ovector, // output vector for substring information
30); // number of elements in the output vector
}
void set_next(DomainRegex *next) { _next = next; }
DomainRegex* next() const { return _next; }
void set_order(int order) { _order = order; }
int order() { return _order; }
char* get_regex() { return _rex_string; }
private:
int _hits;
char* _rex_string;
int _options;
pcre* _rex;
pcre_extra* _extra;
DomainRegex* _next;
int _order;
};
DomainRegex* test() {
std::ifstream f;
std::string filename = "/opt/ats/etc/trafficserver/1.conf";
size_t lineno = 0;
const char* error;
int erroffset;
DomainRegex* cur;
f.open(filename.c_str(), std::ios::in);
if(!f.is_open()) {
printf("open conf err %s\n", strerror(errno));
return NULL;
}
while (!f.eof()) {
std::string line;
getline(f, line);
++lineno;
if (line.size() == 0)
continue;
std::string::size_type pos1, pos2;
pos1 = line.find_first_not_of(" \t\n");
pos2 = line.find_first_of(" \t\n", pos1);
std::string regex = line.substr(pos1, pos2 - pos1);
printf("regex: %s\n", regex.c_str());
if(regex.empty()) {
continue;
}
cur = new DomainRegex();
cur->initialize(regex);
if(cur->compile(&error, &erroffset) < 0) {
//printf("compile err\n");
return NULL;
}
}
return cur;
}
int main() {
DomainRegex d;
const char* err;
int erroff;
int ovector[30];
std::string reg = "[a-z0-9A-Z]+\\.ifeng.com";
const char* str = "sdw.ifeng.com";
d.initialize(reg);
d.compile(&err, &erroff);
int ret = d.match(str, strlen(str), ovector);
printf("regex: %s\nstr: %s\nmatch ret: %d\n", reg.c_str(), str, ret);
printf("----------------\n");
DomainRegex* cur = test();
if(cur == NULL) {
printf("can not get cur\n");
return 0;
}
ret = cur->match(str, strlen(str), ovector);
printf("regex: %s\nstr: %s\nmatch ret: %d\n", reg.c_str(), str, ret);
return 0;
}
/*
[a-z0-9A-Z]+\.ifeng.com
*/
| 27.571429 | 103 | 0.529204 | [
"vector"
] |
6a9569477c00ed0198ff1bad9cb78534010f0d6f | 7,379 | hpp | C++ | SYCL/ESIMD/api/functional/ctors/ctor_move.hpp | tyoungsc/llvm-test-suite | 2206708dbe2829cfdd265368a5fddb5190ca83df | [
"Apache-2.0"
] | null | null | null | SYCL/ESIMD/api/functional/ctors/ctor_move.hpp | tyoungsc/llvm-test-suite | 2206708dbe2829cfdd265368a5fddb5190ca83df | [
"Apache-2.0"
] | null | null | null | SYCL/ESIMD/api/functional/ctors/ctor_move.hpp | tyoungsc/llvm-test-suite | 2206708dbe2829cfdd265368a5fddb5190ca83df | [
"Apache-2.0"
] | null | null | null | //===-- ctor_move.hpp - Functions for tests on simd vector constructor
// definition. -------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
///
/// \file
/// This file provides functions for tests on simd move constructor.
///
//===----------------------------------------------------------------------===//
#pragma once
#include "common.hpp"
#include <algorithm>
#include <cassert>
namespace esimd = sycl::ext::intel::experimental::esimd;
namespace esimd_test::api::functional::ctors {
// Uses the initializer C++ context to call simd move constructor
struct initializer {
static std::string get_description() { return "initializer"; }
template <typename SimdT, typename ActionT>
static void run(SimdT &&source, const ActionT &action) {
static_assert(
type_traits::is_nonconst_rvalue_reference_v<decltype(source)>);
const auto instance = SimdT(std::move(source));
action(instance);
}
};
// Uses the variable declaration C++ context to call simd move constructor
struct var_decl {
static std::string get_description() { return "variable declaration"; }
template <typename SimdT, typename ActionT>
static void run(SimdT &&source, const ActionT &action) {
static_assert(
type_traits::is_nonconst_rvalue_reference_v<decltype(source)>);
const auto instance(std::move(source));
action(instance);
}
};
// Uses the rvalue in expression C++ context to call simd move constructor
struct rval_in_expr {
static std::string get_description() { return "rvalue in expression"; }
template <typename SimdT, typename ActionT>
static void run(SimdT &&source, const ActionT &action) {
static_assert(
type_traits::is_nonconst_rvalue_reference_v<decltype(source)>);
SimdT instance;
instance = SimdT(std::move(source));
action(instance);
}
};
// Uses the function argument C++ context to call simd move constructor
class const_ref {
public:
static std::string get_description() { return "const reference"; }
template <typename SimdT, typename ActionT>
static void run(SimdT &&source, const ActionT &action) {
static_assert(
type_traits::is_nonconst_rvalue_reference_v<decltype(source)>);
action(SimdT(std::move(source)));
}
};
// The core test functionality.
// Runs a TestCaseT, specific for each C++ context, for a simd<DataT,NumElems>
// instance
template <typename DataT, typename DimT, typename TestCaseT> class run_test {
static constexpr int NumElems = DimT::value;
using KernelName = ctors::Kernel<DataT, NumElems, TestCaseT>;
public:
bool operator()(sycl::queue &queue, const std::string &data_type) {
bool passed = true;
bool was_moved = false;
const shared_allocator<DataT> data_allocator(queue);
const shared_allocator<int> flags_allocator(queue);
const auto reference = generate_ref_data<DataT, NumElems>();
shared_vector<DataT> input(reference.cbegin(), reference.cend(),
data_allocator);
shared_vector<DataT> result(reference.size(), data_allocator);
// We need a special handling for case of simd<T,1>, as we need to check
// more than a single data value; therefore we need to loop over the
// reference data to run test
if constexpr (NumElems == 1) {
const auto n_checks = input.size();
const sycl::range<1> range(n_checks);
// We need a separate flag per each check to have a parallel_for possible,
// because any concurrent access to the same memory location is UB, even
// in case we are updating variable to the same value in multiple threads
shared_vector<int> flags_storage(n_checks, flags_allocator);
// Run check for each of the reference elements using a single work-item
// per single element
queue.submit([&](sycl::handler &cgh) {
const DataT *const ptr_in = input.data();
const auto ptr_out = result.data();
const auto ptr_flags = flags_storage.data();
cgh.parallel_for<KernelName>(
range, [=](sycl::id<1> id) SYCL_ESIMD_KERNEL {
const auto work_item_index = id[0];
// Access a separate memory areas from each of the work items
const DataT *const in = ptr_in + work_item_index;
const auto out = ptr_out + work_item_index;
const auto was_moved_flag = ptr_flags + work_item_index;
*was_moved_flag = run_check(in, out);
});
});
queue.wait_and_throw();
// Oversafe: verify the proper signature was called for every check
was_moved = std::all_of(flags_storage.cbegin(), flags_storage.cend(),
[](int flag) { return flag; });
} else {
assert((input.size() == NumElems) &&
"Unexpected size of the input vector");
shared_vector<int> flags_storage(1, flags_allocator);
queue.submit([&](sycl::handler &cgh) {
const DataT *const in = input.data();
const auto out = result.data();
const auto was_moved_flag = flags_storage.data();
cgh.single_task<KernelName>(
[=]() SYCL_ESIMD_KERNEL { *was_moved_flag = run_check(in, out); });
});
queue.wait_and_throw();
was_moved = flags_storage[0];
}
if (!was_moved) {
passed = false;
// TODO: Make ITestDescription architecture more flexible
std::string log_msg = "Failed for simd<";
log_msg += data_type + ", " + std::to_string(NumElems) + ">";
log_msg += ", with context: " + TestCaseT::get_description();
log_msg += ". A copy constructor instead of a move constructor was used.";
log::note(log_msg);
} else {
for (size_t i = 0; i < reference.size(); ++i) {
const auto &retrieved = result[i];
const auto &expected = reference[i];
if (!are_bitwise_equal(retrieved, expected)) {
passed = false;
log::fail(ctors::TestDescription<DataT, NumElems, TestCaseT>(
i, retrieved, expected, data_type));
}
}
}
return passed;
}
private:
// The core check logic.
// Uses USM pointers for input data and to store the data from the new simd
// instance, so that we could check it later
// Returns the flag that should be true only if the move constructor was
// actually called, to differentiate with the copy constructor calls
static bool run_check(const DataT *const in, DataT *const out) {
bool was_moved = false;
// Prepare the source simd to move
esimd::simd<DataT, NumElems> source;
source.copy_from(in);
// Action to run over the simd move constructor result
const auto action = [&](const esimd::simd<DataT, NumElems> &instance) {
was_moved = instance.get_test_proxy().was_move_destination();
instance.copy_to(out);
};
// Call the move constructor in the specific context and run action
// directly over the simd move constructor result
TestCaseT::template run(std::move(source), action);
return was_moved;
}
};
} // namespace esimd_test::api::functional::ctors
| 35.138095 | 80 | 0.647378 | [
"vector"
] |
6a95e7536aa2ba595720b8ee8b3bdd2fc52f9159 | 12,649 | cpp | C++ | cpp/src/cylon/indexing/index.cpp | ahmet-uyar/cylon | 112ea97faf6e4643ae7e012078d454342a327fc3 | [
"Apache-2.0"
] | null | null | null | cpp/src/cylon/indexing/index.cpp | ahmet-uyar/cylon | 112ea97faf6e4643ae7e012078d454342a327fc3 | [
"Apache-2.0"
] | null | null | null | cpp/src/cylon/indexing/index.cpp | ahmet-uyar/cylon | 112ea97faf6e4643ae7e012078d454342a327fc3 | [
"Apache-2.0"
] | 1 | 2020-06-30T23:09:26.000Z | 2020-06-30T23:09:26.000Z | /*
* 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 <glog/logging.h>
#include <cylon/indexing/index.hpp>
#include <cylon/table.hpp>
namespace cylon {
std::unique_ptr<ArrowIndexKernel> CreateArrowHashIndexKernel(std::shared_ptr<arrow::Table> input_table,
int index_column) {
switch (input_table->column(index_column)->type()->id()) {
case arrow::Type::NA:
return nullptr;
case arrow::Type::BOOL:
return std::make_unique<BoolArrowHashIndexKernel>();
case arrow::Type::UINT8:
return std::make_unique<UInt8ArrowHashIndexKernel>();
case arrow::Type::INT8:
return std::make_unique<Int8ArrowHashIndexKernel>();
case arrow::Type::UINT16:
return std::make_unique<UInt16ArrowHashIndexKernel>();
case arrow::Type::INT16:
return std::make_unique<Int16ArrowHashIndexKernel>();
case arrow::Type::UINT32:
return std::make_unique<UInt32ArrowHashIndexKernel>();
case arrow::Type::INT32:
return std::make_unique<Int32ArrowHashIndexKernel>();
case arrow::Type::UINT64:
return std::make_unique<UInt64ArrowHashIndexKernel>();
case arrow::Type::INT64:
return std::make_unique<Int64ArrowHashIndexKernel>();
case arrow::Type::HALF_FLOAT:
return std::make_unique<HalfFloatArrowHashIndexKernel>();
case arrow::Type::FLOAT:
return std::make_unique<FloatArrowHashIndexKernel>();
case arrow::Type::DOUBLE:
return std::make_unique<DoubleArrowHashIndexKernel>();
case arrow::Type::STRING:
return std::make_unique<StringArrowHashIndexKernel>();
case arrow::Type::BINARY:
return std::make_unique<BinaryArrowHashIndexKernel>();
case arrow::Type::DATE32:
return std::make_unique<Date32ArrowHashIndexKernel>();
case arrow::Type::DATE64:
return std::make_unique<Date64ArrowHashIndexKernel>();
case arrow::Type::TIME32:
return std::make_unique<Time32ArrowHashIndexKernel>();
case arrow::Type::TIME64:
return std::make_unique<Time64ArrowHashIndexKernel>();
case arrow::Type::TIMESTAMP:
return std::make_unique<TimestampArrowHashIndexKernel>();
default:
return std::make_unique<ArrowRangeIndexKernel>();
}
}
std::unique_ptr<ArrowIndexKernel> CreateArrowIndexKernel(std::shared_ptr<arrow::Table> input_table, int index_column) {
// TODO: fix the criterion to check the kernel creation method
if (index_column == -1) {
return std::make_unique<ArrowRangeIndexKernel>();
} else {
return CreateArrowHashIndexKernel(input_table, index_column);
}
}
bool CompareArraysForUniqueness(const std::shared_ptr<arrow::Array> &index_arr) {
auto result = arrow::compute::Unique(index_arr);
if (!result.status().ok()) {
LOG(ERROR) << "Error occurred in index array unique check";
return false;
}
auto unique_arr = result.ValueOrDie();
return unique_arr->length() == index_arr->length();
}
LinearArrowIndexKernel::LinearArrowIndexKernel() {}
Status LinearArrowIndexKernel::BuildIndex(arrow::MemoryPool *pool,
std::shared_ptr<arrow::Table> &input_table,
const int index_column,
std::shared_ptr<BaseArrowIndex> &base_arrow_index) {
std::shared_ptr<arrow::Array> index_array;
if (input_table->column(0)->num_chunks() > 1) {
const arrow::Result<std::shared_ptr<arrow::Table>> &res = input_table->CombineChunks(pool);
RETURN_CYLON_STATUS_IF_ARROW_FAILED(res.status());
input_table = res.ValueOrDie();
}
index_array = cylon::util::GetChunkOrEmptyArray(input_table->column(index_column), 0);
base_arrow_index = std::make_shared<ArrowLinearIndex>(index_column, input_table->num_rows(), pool, index_array);
return cylon::Status::OK();
}
ArrowLinearIndex::ArrowLinearIndex(int col_id, int size, std::shared_ptr<CylonContext> &ctx) : BaseArrowIndex(col_id,
size,
ctx) {}
ArrowLinearIndex::ArrowLinearIndex(int col_id, int size, arrow::MemoryPool *pool) : BaseArrowIndex(col_id,
size,
pool) {}
Status ArrowLinearIndex::LocationByValue(const std::shared_ptr<arrow::Scalar> &search_param,
std::vector<int64_t> &find_index) {
auto cast_val = search_param->CastTo(index_array_->type()).ValueOrDie();
for (int64_t ix = 0; ix < index_array_->length(); ix++) {
auto val = index_array_->GetScalar(ix).ValueOrDie();
if (cast_val->Equals(val)) {
find_index.push_back(ix);
}
}
return Status::OK();
}
Status ArrowLinearIndex::LocationByValue(const std::shared_ptr<arrow::Scalar> &search_param, int64_t *find_index) {
auto cast_val = search_param->CastTo(index_array_->type()).ValueOrDie();
for (int64_t ix = 0; ix < index_array_->length(); ix++) {
auto val = index_array_->GetScalar(ix).ValueOrDie();
if (cast_val->Equals(val)) {
*find_index = ix;
break;
}
}
return Status::OK();
}
Status ArrowLinearIndex::LocationByValue(const std::shared_ptr<arrow::Scalar> &search_param,
const std::shared_ptr<arrow::Table> &input,
std::vector<int64_t> &filter_location,
std::shared_ptr<arrow::Table> &output) {
arrow::Status arrow_status;
cylon::Status status;
std::shared_ptr<arrow::Array> out_idx;
arrow::compute::ExecContext fn_ctx(GetPool());
arrow::Int64Builder idx_builder(GetPool());
RETURN_CYLON_STATUS_IF_FAILED(LocationByValue(search_param, filter_location));
RETURN_CYLON_STATUS_IF_ARROW_FAILED(idx_builder.AppendValues(filter_location));
RETURN_CYLON_STATUS_IF_ARROW_FAILED(idx_builder.Finish(&out_idx));
arrow::Result<arrow::Datum>
result = arrow::compute::Take(input, out_idx, arrow::compute::TakeOptions::Defaults(), &fn_ctx);
RETURN_CYLON_STATUS_IF_ARROW_FAILED(result.status());
output = result.ValueOrDie().table();
return Status::OK();
}
std::shared_ptr<arrow::Array> ArrowLinearIndex::GetIndexAsArray() {
return index_array_;
}
void ArrowLinearIndex::SetIndexArray(const std::shared_ptr<arrow::Array> &index_arr) {
index_array_ = index_arr;
}
std::shared_ptr<arrow::Array> ArrowLinearIndex::GetIndexArray() {
return index_array_;
}
int ArrowLinearIndex::GetColId() const {
return BaseArrowIndex::GetColId();
}
int ArrowLinearIndex::GetSize() const {
return index_array_->length();
}
IndexingType ArrowLinearIndex::GetIndexingType() {
return Linear;
}
arrow::MemoryPool *ArrowLinearIndex::GetPool() const {
return BaseArrowIndex::GetPool();
}
bool ArrowLinearIndex::IsUnique() {
const bool is_unique = CompareArraysForUniqueness(index_array_);
return is_unique;
}
Status ArrowLinearIndex::LocationByVector(const std::shared_ptr<arrow::Array> &search_param,
std::vector<int64_t> &filter_location) {
auto cast_search_param_result = arrow::compute::Cast(search_param, index_array_->type());
auto const search_param_array = cast_search_param_result.ValueOrDie().make_array();
auto const res_isin_filter = arrow::compute::IsIn(index_array_, search_param_array);
RETURN_CYLON_STATUS_IF_ARROW_FAILED(res_isin_filter.status());
auto res_isin_filter_val = res_isin_filter.ValueOrDie();
std::shared_ptr<arrow::Array> arr_isin = res_isin_filter_val.make_array();
std::shared_ptr<arrow::BooleanArray> arr_isin_bool_array = std::static_pointer_cast<arrow::BooleanArray>(arr_isin);
for (int64_t ix = 0; ix < arr_isin_bool_array->length(); ix++) {
auto val = arr_isin_bool_array->Value(ix);
if (val) {
filter_location.push_back(ix);
}
}
return Status::OK();
}
int BaseArrowIndex::GetColId() const {
return col_id_;
}
int BaseArrowIndex::GetSize() const {
return size_;
}
arrow::MemoryPool *BaseArrowIndex::GetPool() const {
return pool_;
}
Status ArrowRangeIndex::LocationByValue(const std::shared_ptr<arrow::Scalar> &search_param,
std::vector<int64_t> &find_index) {
std::shared_ptr<arrow::Int64Scalar> casted_search_param = std::static_pointer_cast<arrow::Int64Scalar>(search_param);
int64_t val = casted_search_param->value;
if (!(val >= start_ && val < end_)) {
return Status(cylon::Code::KeyError, "Invalid Key, it must be in the range of 0, num of records");
}
find_index.push_back(val);
return Status::OK();
}
Status ArrowRangeIndex::LocationByValue(const std::shared_ptr<arrow::Scalar> &search_param, int64_t *find_index) {
std::shared_ptr<arrow::Int64Scalar> casted_search_param = std::static_pointer_cast<arrow::Int64Scalar>(search_param);
int64_t val = casted_search_param->value;
if (!(val >= start_ && val < end_)) {
return Status(cylon::Code::KeyError, "Invalid Key, it must be in the range of 0, num of records");
}
*find_index = val;
return Status::OK();
}
Status ArrowRangeIndex::LocationByValue(const std::shared_ptr<arrow::Scalar> &search_param,
const std::shared_ptr<arrow::Table> &input,
std::vector<int64_t> &filter_location,
std::shared_ptr<arrow::Table> &output) {
arrow::Status arrow_status;
cylon::Status status;
std::shared_ptr<arrow::Array> out_idx;
arrow::compute::ExecContext fn_ctx(GetPool());
arrow::Int64Builder idx_builder(GetPool());
RETURN_CYLON_STATUS_IF_FAILED(LocationByValue(search_param, filter_location));
RETURN_CYLON_STATUS_IF_ARROW_FAILED(idx_builder.AppendValues(filter_location));
RETURN_CYLON_STATUS_IF_ARROW_FAILED(idx_builder.Finish(&out_idx));
arrow::Result<arrow::Datum>
result = arrow::compute::Take(input, out_idx, arrow::compute::TakeOptions::Defaults(), &fn_ctx);
RETURN_CYLON_STATUS_IF_ARROW_FAILED(result.status());
output = result.ValueOrDie().table();
return Status::OK();
}
std::shared_ptr<arrow::Array> ArrowRangeIndex::GetIndexAsArray() {
arrow::Status arrow_status;
auto pool = GetPool();
arrow::Int64Builder builder(pool);
std::vector<int64_t> vec(GetSize());
for (int64_t ix = 0; ix < GetSize(); ix += GetStep()) {
vec[ix] = ix;
}
arrow_status = builder.AppendValues(vec);
if (!arrow_status.ok()) {
LOG(ERROR) << "Error occurred when generating range index values with array builder";
}
arrow_status = builder.Finish(&index_arr_);
if (!arrow_status.ok()) {
LOG(ERROR) << "Error occurred in retrieving index";
return nullptr;
}
return index_arr_;
}
void ArrowRangeIndex::SetIndexArray(const std::shared_ptr<arrow::Array> &index_arr) {
index_arr_ = index_arr;
}
std::shared_ptr<arrow::Array> ArrowRangeIndex::GetIndexArray() {
return GetIndexAsArray();
}
int ArrowRangeIndex::GetColId() const {
return BaseArrowIndex::GetColId();
}
int ArrowRangeIndex::GetSize() const {
return end_;
}
IndexingType ArrowRangeIndex::GetIndexingType() {
return Range;
}
arrow::MemoryPool *ArrowRangeIndex::GetPool() const {
return BaseArrowIndex::GetPool();
}
bool ArrowRangeIndex::IsUnique() {
return true;
}
ArrowRangeIndex::ArrowRangeIndex(int start, int size, int step, arrow::MemoryPool *pool) : BaseArrowIndex(0,
size,
pool),
start_(start),
end_(size),
step_(step) {
}
int ArrowRangeIndex::GetStart() const {
return start_;
}
int ArrowRangeIndex::GetAnEnd() const {
return end_;
}
int ArrowRangeIndex::GetStep() const {
return step_;
}
Status ArrowRangeIndex::LocationByVector(const std::shared_ptr<arrow::Array> &search_param,
std::vector<int64_t> &filter_location) {
std::shared_ptr<arrow::Int64Array> cast_search_param = std::static_pointer_cast<arrow::Int64Array>(search_param);
for (int64_t ix = 0; ix < cast_search_param->length(); ix++) {
int64_t index_value = cast_search_param->Value(ix);
filter_location.push_back(index_value);
}
return Status::OK();
};
ArrowRangeIndexKernel::ArrowRangeIndexKernel() {
}
Status ArrowRangeIndexKernel::BuildIndex(arrow::MemoryPool *pool,
std::shared_ptr<arrow::Table> &input_table,
const int index_column,
std::shared_ptr<BaseArrowIndex> &base_arrow_index) {
base_arrow_index = std::make_shared<ArrowRangeIndex>(0, input_table->num_rows(), 1, pool);
return cylon::Status::OK();
}
}
| 35.233983 | 119 | 0.711598 | [
"vector"
] |
6a96348a68f04f60f782f5dbe94bb130a9e95f60 | 23,633 | cpp | C++ | tests/tests4.cpp | shlyamster/sqlite_orm | a6c07b588a173f93c9a818371dd07c199442791d | [
"BSD-3-Clause"
] | 1 | 2021-12-27T15:23:13.000Z | 2021-12-27T15:23:13.000Z | tests/tests4.cpp | shlyamster/sqlite_orm | a6c07b588a173f93c9a818371dd07c199442791d | [
"BSD-3-Clause"
] | null | null | null | tests/tests4.cpp | shlyamster/sqlite_orm | a6c07b588a173f93c9a818371dd07c199442791d | [
"BSD-3-Clause"
] | null | null | null | #include <sqlite_orm/sqlite_orm.h>
#include <catch2/catch.hpp>
#include <numeric>
#include <algorithm> // std::count_if
#include <iostream>
#ifdef SQLITE_ORM_OPTIONAL_SUPPORTED
#include <optional> // std::optional
#endif // SQLITE_ORM_OPTIONAL_SUPPORTED
using namespace sqlite_orm;
using std::cout;
using std::endl;
TEST_CASE("Case") {
struct User {
int id = 0;
std::string firstName;
std::string lastName;
std::string country;
};
struct Track {
int id = 0;
std::string name;
long milliseconds = 0;
};
auto storage = make_storage({},
make_table("users",
make_column("id", &User::id, autoincrement(), primary_key()),
make_column("first_name", &User::firstName),
make_column("last_name", &User::lastName),
make_column("country", &User::country)),
make_table("tracks",
make_column("trackid", &Track::id, autoincrement(), primary_key()),
make_column("name", &Track::name),
make_column("milliseconds", &Track::milliseconds)));
storage.sync_schema();
struct GradeAlias : alias_tag {
static const std::string &get() {
static const std::string res = "Grade";
return res;
}
};
{
storage.insert(User{0, "Roberto", "Almeida", "Mexico"});
storage.insert(User{0, "Julia", "Bernett", "USA"});
storage.insert(User{0, "Camille", "Bernard", "Argentina"});
storage.insert(User{0, "Michelle", "Brooks", "USA"});
storage.insert(User{0, "Robet", "Brown", "USA"});
auto rows = storage.select(
columns(case_<std::string>(&User::country).when("USA", then("Dosmetic")).else_("Foreign").end()),
multi_order_by(order_by(&User::lastName), order_by(&User::firstName)));
auto verifyRows = [&storage](auto &rows) {
REQUIRE(rows.size() == storage.count<User>());
REQUIRE(std::get<0>(rows[0]) == "Foreign");
REQUIRE(std::get<0>(rows[1]) == "Foreign");
REQUIRE(std::get<0>(rows[2]) == "Dosmetic");
REQUIRE(std::get<0>(rows[3]) == "Dosmetic");
REQUIRE(std::get<0>(rows[4]) == "Dosmetic");
};
verifyRows(rows);
rows = storage.select(
columns(as<GradeAlias>(
case_<std::string>(&User::country).when("USA", then("Dosmetic")).else_("Foreign").end())),
multi_order_by(order_by(&User::lastName), order_by(&User::firstName)));
verifyRows(rows);
}
{
storage.insert(Track{0, "For Those About To Rock", 400000});
storage.insert(Track{0, "Balls to the Wall", 500000});
storage.insert(Track{0, "Fast as a Shark", 200000});
storage.insert(Track{0, "Restless and Wild", 100000});
storage.insert(Track{0, "Princess of the Dawn", 50000});
auto rows = storage.select(
case_<std::string>()
.when(c(&Track::milliseconds) < 60000, then("short"))
.when(c(&Track::milliseconds) >= 60000 and c(&Track::milliseconds) < 300000, then("medium"))
.else_("long")
.end(),
order_by(&Track::name));
auto verifyRows = [&storage](auto &rows) {
REQUIRE(rows.size() == storage.count<Track>());
REQUIRE(rows[0] == "long");
REQUIRE(rows[1] == "medium");
REQUIRE(rows[2] == "long");
REQUIRE(rows[3] == "short");
REQUIRE(rows[4] == "medium");
};
verifyRows(rows);
rows = storage.select(
as<GradeAlias>(
case_<std::string>()
.when(c(&Track::milliseconds) < 60000, then("short"))
.when(c(&Track::milliseconds) >= 60000 and c(&Track::milliseconds) < 300000, then("medium"))
.else_("long")
.end()),
order_by(&Track::name));
verifyRows(rows);
}
}
TEST_CASE("Unique ptr in update") {
struct User {
int id = 0;
std::unique_ptr<std::string> name;
};
auto storage = make_storage(
{},
make_table("users", make_column("id", &User::id, primary_key()), make_column("name", &User::name)));
storage.sync_schema();
storage.insert(User{});
storage.insert(User{});
storage.insert(User{});
{
storage.update_all(set(assign(&User::name, std::make_unique<std::string>("Nick"))));
REQUIRE(storage.count<User>(where(is_null(&User::name))) == 0);
}
{
std::unique_ptr<std::string> ptr;
storage.update_all(set(assign(&User::name, move(ptr))));
REQUIRE(storage.count<User>(where(is_not_null(&User::name))) == 0);
}
}
#ifdef SQLITE_ORM_OPTIONAL_SUPPORTED
TEST_CASE("Optional in update") {
struct User {
int id = 0;
std::optional<int> carYear; // will be empty if user takes the bus.
};
auto storage = make_storage(
{},
make_table("users", make_column("id", &User::id, primary_key()), make_column("car_year", &User::carYear)));
storage.sync_schema();
storage.insert(User{});
storage.insert(User{});
storage.insert(User{});
storage.insert(User{0, 2006});
REQUIRE(storage.count<User>(where(is_not_null(&User::carYear))) == 1);
{
storage.update_all(set(assign(&User::carYear, std::optional<int>{})));
REQUIRE(storage.count<User>(where(is_not_null(&User::carYear))) == 0);
}
{
storage.update_all(set(assign(&User::carYear, 1994)));
REQUIRE(storage.count<User>(where(is_null(&User::carYear))) == 0);
}
{
storage.update_all(set(assign(&User::carYear, nullptr)));
REQUIRE(storage.count<User>(where(is_not_null(&User::carYear))) == 0);
}
}
#endif // SQLITE_ORM_OPTIONAL_SUPPORTED
TEST_CASE("Join") {
struct User {
int id = 0;
std::string name;
};
struct Visit {
int id = 0;
int userId = 0;
time_t date = 0;
};
auto storage =
make_storage({},
make_table("users", make_column("id", &User::id, primary_key()), make_column("name", &User::name)),
make_table("visits",
make_column("id", &Visit::id, primary_key()),
make_column("user_id", &Visit::userId),
make_column("date", &Visit::date)));
storage.sync_schema();
int id = 1;
User will{id++, "Will"};
User smith{id++, "Smith"};
User nicole{id++, "Nicole"};
storage.replace(will);
storage.replace(smith);
storage.replace(nicole);
id = 1;
storage.replace(Visit{id++, will.id, 10});
storage.replace(Visit{id++, will.id, 20});
storage.replace(Visit{id++, will.id, 30});
storage.replace(Visit{id++, smith.id, 25});
storage.replace(Visit{id++, smith.id, 35});
{
auto rows = storage.get_all<User>(left_join<Visit>(on(is_equal(&Visit::userId, 2))));
REQUIRE(rows.size() == 6);
}
{
auto rows = storage.get_all<User>(join<Visit>(on(is_equal(&Visit::userId, 2))));
REQUIRE(rows.size() == 6);
}
{
auto rows = storage.get_all<User>(left_outer_join<Visit>(on(is_equal(&Visit::userId, 2))));
REQUIRE(rows.size() == 6);
}
{
auto rows = storage.get_all<User>(inner_join<Visit>(on(is_equal(&Visit::userId, 2))));
REQUIRE(rows.size() == 6);
}
}
TEST_CASE("Storage copy") {
struct User {
int id = 0;
};
int calledCount = 0;
auto storage = make_storage({}, make_table("users", make_column("id", &User::id)));
storage.sync_schema();
storage.remove_all<User>();
storage.on_open = [&calledCount](sqlite3 *) {
++calledCount;
};
storage.on_open(nullptr);
REQUIRE(calledCount == 1);
auto storageCopy = storage;
REQUIRE(storageCopy.on_open);
REQUIRE(calledCount == 2);
storageCopy.on_open(nullptr);
REQUIRE(calledCount == 3);
storageCopy.sync_schema();
storageCopy.remove_all<User>();
}
TEST_CASE("Set null") {
struct User {
int id = 0;
std::unique_ptr<std::string> name;
};
auto storage = make_storage(
{},
make_table("users", make_column("id", &User::id, primary_key()), make_column("name", &User::name)));
storage.sync_schema();
storage.replace(User{1, std::make_unique<std::string>("Ototo")});
REQUIRE(storage.count<User>() == 1);
auto rows = storage.get_all<User>();
REQUIRE(rows.size() == 1);
REQUIRE(rows.front().name);
storage.update_all(set(assign(&User::name, nullptr)));
{
auto rows = storage.get_all<User>();
REQUIRE(rows.size() == 1);
REQUIRE(!rows.front().name);
}
storage.update_all(set(assign(&User::name, "ototo")));
{
auto rows = storage.get_all<User>();
REQUIRE(rows.size() == 1);
REQUIRE(rows.front().name);
REQUIRE(*rows.front().name == "ototo");
}
storage.update_all(set(assign(&User::name, nullptr)), where(is_equal(&User::id, 1)));
{
auto rows = storage.get_all<User>();
REQUIRE(rows.size() == 1);
REQUIRE(!rows.front().name);
}
}
TEST_CASE("Composite key column names") {
struct User {
int id = 0;
std::string name;
std::string info;
};
{
auto table = make_table("t",
make_column("id", &User::id),
make_column("name", &User::name),
make_column("info", &User::info),
primary_key(&User::id, &User::name));
auto compositeKeyColumnsNames = table.composite_key_columns_names();
std::vector<std::string> expected = {"id", "name"};
REQUIRE(std::equal(compositeKeyColumnsNames.begin(), compositeKeyColumnsNames.end(), expected.begin()));
}
{
auto table = make_table("t",
make_column("id", &User::id),
make_column("name", &User::name),
make_column("info", &User::info),
primary_key(&User::name, &User::id));
auto compositeKeyColumnsNames = table.composite_key_columns_names();
std::vector<std::string> expected = {"name", "id"};
REQUIRE(std::equal(compositeKeyColumnsNames.begin(), compositeKeyColumnsNames.end(), expected.begin()));
}
{
auto table = make_table("t",
make_column("id", &User::id),
make_column("name", &User::name),
make_column("info", &User::info),
primary_key(&User::name, &User::id, &User::info));
auto compositeKeyColumnsNames = table.composite_key_columns_names();
std::vector<std::string> expected = {"name", "id", "info"};
REQUIRE(std::equal(compositeKeyColumnsNames.begin(), compositeKeyColumnsNames.end(), expected.begin()));
}
{
auto table = make_table("t",
make_column("id", &User::id),
make_column("name", &User::name),
make_column("info", &User::info));
auto compositeKeyColumnsNames = table.composite_key_columns_names();
REQUIRE(compositeKeyColumnsNames.empty());
}
}
TEST_CASE("Not operator") {
struct Object {
int id = 0;
};
auto storage = make_storage("", make_table("objects", make_column("id", &Object::id, primary_key())));
storage.sync_schema();
storage.replace(Object{2});
auto rows = storage.select(&Object::id, where(not is_equal(&Object::id, 1)));
REQUIRE(rows.size() == 1);
REQUIRE(rows.front() == 2);
}
TEST_CASE("Between operator") {
struct Object {
int id = 0;
};
auto storage =
make_storage("", make_table("objects", make_column("id", &Object::id, autoincrement(), primary_key())));
storage.sync_schema();
storage.insert(Object{});
storage.insert(Object{});
storage.insert(Object{});
storage.insert(Object{});
storage.insert(Object{});
auto allObjects = storage.get_all<Object>();
auto rows = storage.select(&Object::id, where(between(&Object::id, 1, 3)));
REQUIRE(rows.size() == 3);
}
TEST_CASE("Exists") {
struct User {
int id = 0;
std::string name;
};
struct Visit {
int id = 0;
int userId = 0;
time_t time = 0;
};
auto storage =
make_storage("",
make_table("users", make_column("id", &User::id, primary_key()), make_column("name", &User::name)),
make_table("visits",
make_column("id", &Visit::id, primary_key()),
make_column("userId", &Visit::userId),
make_column("time", &Visit::time),
foreign_key(&Visit::userId).references(&User::id)));
storage.sync_schema();
storage.replace(User{1, "Daddy Yankee"});
storage.replace(User{2, "Don Omar"});
storage.replace(Visit{1, 1, 100000});
storage.replace(Visit{2, 1, 100001});
storage.replace(Visit{3, 1, 100002});
storage.replace(Visit{4, 1, 200000});
storage.replace(Visit{5, 2, 100000});
auto rows = storage.select(
&User::id,
where(exists(select(&Visit::id, where(c(&Visit::time) == 200000 and eq(&Visit::userId, &User::id))))));
REQUIRE(!rows.empty() == 1);
}
TEST_CASE("Iterate blob") {
struct Test {
int64_t id;
std::vector<char> key;
};
struct TestComparator {
bool operator()(const Test &lhs, const Test &rhs) const {
return lhs.id == rhs.id && lhs.key == rhs.key;
}
};
auto db =
make_storage("",
make_table("Test", make_column("key", &Test::key), make_column("id", &Test::id, primary_key())));
db.sync_schema(true);
std::vector<char> key(255);
iota(key.begin(), key.end(), 0);
Test v{5, key};
db.replace(v);
TestComparator testComparator;
for(auto &obj: db.iterate<Test>()) {
REQUIRE(testComparator(obj, v));
} // test that view_t and iterator_t compile
for(const auto &obj: db.iterate<Test>()) {
REQUIRE(testComparator(obj, v));
} // test that view_t and iterator_t compile
{
auto keysCount = db.count<Test>(where(c(&Test::key) == key));
auto keysCountRows = db.select(count<Test>(), where(c(&Test::key) == key));
REQUIRE(keysCountRows.size() == 1);
REQUIRE(keysCountRows.front() == 1);
REQUIRE(keysCount == keysCountRows.front());
REQUIRE(db.get_all<Test>(where(c(&Test::key) == key)).size() == 1);
}
{
int iterationsCount = 0;
for(auto &w: db.iterate<Test>(where(c(&Test::key) == key))) {
REQUIRE(testComparator(w, v));
++iterationsCount;
}
REQUIRE(iterationsCount == 1);
}
}
TEST_CASE("Threadsafe") {
// this code just shows this value on CI
cout << "threadsafe = " << threadsafe() << endl;
}
TEST_CASE("Different getters and setters") {
struct User {
int id;
std::string name;
int getIdByValConst() const {
return this->id;
}
void setIdByVal(int id) {
this->id = id;
}
std::string getNameByVal() {
return this->name;
}
void setNameByConstRef(const std::string &name) {
this->name = name;
}
const int &getConstIdByRefConst() const {
return this->id;
}
void setIdByRef(int &id) {
this->id = id;
}
const std::string &getConstNameByRefConst() const {
return this->name;
}
void setNameByRef(std::string &name) {
this->name = std::move(name);
}
};
auto filename = "different.sqlite";
auto storage0 = make_storage(
filename,
make_table("users", make_column("id", &User::id, primary_key()), make_column("name", &User::name)));
auto storage1 = make_storage(filename,
make_table("users",
make_column("id", &User::getIdByValConst, &User::setIdByVal, primary_key()),
make_column("name", &User::setNameByConstRef, &User::getNameByVal)));
auto storage2 =
make_storage(filename,
make_table("users",
make_column("id", &User::getConstIdByRefConst, &User::setIdByRef, primary_key()),
make_column("name", &User::getConstNameByRefConst, &User::setNameByRef)));
storage0.sync_schema();
storage0.remove_all<User>();
REQUIRE(storage0.count<User>() == 0);
REQUIRE(storage1.count<User>() == 0);
REQUIRE(storage2.count<User>() == 0);
storage0.replace(User{1, "Da buzz"});
REQUIRE(storage0.count<User>() == 1);
REQUIRE(storage1.count<User>() == 1);
REQUIRE(storage2.count<User>() == 1);
{
auto ids = storage0.select(&User::id);
REQUIRE(ids.size() == 1);
REQUIRE(ids.front() == 1);
auto ids2 = storage1.select(&User::getIdByValConst);
REQUIRE(ids == ids2);
auto ids3 = storage1.select(&User::setIdByVal);
REQUIRE(ids3 == ids2);
auto ids4 = storage2.select(&User::getConstIdByRefConst);
REQUIRE(ids4 == ids3);
auto ids5 = storage2.select(&User::setIdByRef);
REQUIRE(ids5 == ids4);
}
{
auto ids = storage0.select(&User::id, where(is_equal(&User::name, "Da buzz")));
REQUIRE(ids.size() == 1);
REQUIRE(ids.front() == 1);
auto ids2 = storage1.select(&User::getIdByValConst, where(is_equal(&User::setNameByConstRef, "Da buzz")));
REQUIRE(ids == ids2);
auto ids3 = storage1.select(&User::setIdByVal, where(is_equal(&User::getNameByVal, "Da buzz")));
REQUIRE(ids3 == ids2);
auto ids4 =
storage2.select(&User::getConstIdByRefConst, where(is_equal(&User::getConstNameByRefConst, "Da buzz")));
REQUIRE(ids4 == ids3);
auto ids5 = storage2.select(&User::setIdByRef, where(is_equal(&User::setNameByRef, "Da buzz")));
REQUIRE(ids5 == ids4);
}
{
auto ids = storage0.select(columns(&User::id), where(is_equal(&User::name, "Da buzz")));
REQUIRE(ids.size() == 1);
REQUIRE(std::get<0>(ids.front()) == 1);
auto ids2 =
storage1.select(columns(&User::getIdByValConst), where(is_equal(&User::setNameByConstRef, "Da buzz")));
REQUIRE(ids == ids2);
auto ids3 = storage1.select(columns(&User::setIdByVal), where(is_equal(&User::getNameByVal, "Da buzz")));
REQUIRE(ids3 == ids2);
auto ids4 = storage2.select(columns(&User::getConstIdByRefConst),
where(is_equal(&User::getConstNameByRefConst, "Da buzz")));
REQUIRE(ids4 == ids3);
auto ids5 = storage2.select(columns(&User::setIdByRef), where(is_equal(&User::setNameByRef, "Da buzz")));
REQUIRE(ids5 == ids4);
}
{
auto avgValue = storage0.avg(&User::id);
REQUIRE(avgValue == storage1.avg(&User::getIdByValConst));
REQUIRE(avgValue == storage1.avg(&User::setIdByVal));
REQUIRE(avgValue == storage2.avg(&User::getConstIdByRefConst));
REQUIRE(avgValue == storage2.avg(&User::setIdByRef));
}
{
auto count = storage0.count(&User::id);
REQUIRE(count == storage1.count(&User::getIdByValConst));
REQUIRE(count == storage1.count(&User::setIdByVal));
REQUIRE(count == storage2.count(&User::getConstIdByRefConst));
REQUIRE(count == storage2.count(&User::setIdByRef));
}
{
auto groupConcat = storage0.group_concat(&User::id);
REQUIRE(groupConcat == storage1.group_concat(&User::getIdByValConst));
REQUIRE(groupConcat == storage1.group_concat(&User::setIdByVal));
REQUIRE(groupConcat == storage2.group_concat(&User::getConstIdByRefConst));
REQUIRE(groupConcat == storage2.group_concat(&User::setIdByRef));
}
{
auto arg = "ototo";
auto groupConcat = storage0.group_concat(&User::id, arg);
REQUIRE(groupConcat == storage1.group_concat(&User::getIdByValConst, arg));
REQUIRE(groupConcat == storage1.group_concat(&User::setIdByVal, arg));
REQUIRE(groupConcat == storage2.group_concat(&User::getConstIdByRefConst, arg));
REQUIRE(groupConcat == storage2.group_concat(&User::setIdByRef, arg));
}
{
auto max = storage0.max(&User::id);
REQUIRE(max);
REQUIRE(*max == *storage1.max(&User::getIdByValConst));
REQUIRE(*max == *storage1.max(&User::setIdByVal));
REQUIRE(*max == *storage2.max(&User::getConstIdByRefConst));
REQUIRE(*max == *storage2.max(&User::setIdByRef));
}
{
auto min = storage0.min(&User::id);
REQUIRE(min);
REQUIRE(*min == *storage1.min(&User::getIdByValConst));
REQUIRE(*min == *storage1.min(&User::setIdByVal));
REQUIRE(*min == *storage2.min(&User::getConstIdByRefConst));
REQUIRE(*min == *storage2.min(&User::setIdByRef));
}
{
auto sum = storage0.sum(&User::id);
REQUIRE(sum);
REQUIRE(*sum == *storage1.sum(&User::getIdByValConst));
REQUIRE(*sum == *storage1.sum(&User::setIdByVal));
REQUIRE(*sum == *storage2.sum(&User::getConstIdByRefConst));
REQUIRE(*sum == *storage2.sum(&User::setIdByRef));
}
{
auto total = storage0.total(&User::id);
REQUIRE(total == storage1.total(&User::getIdByValConst));
REQUIRE(total == storage1.total(&User::setIdByVal));
REQUIRE(total == storage2.total(&User::getConstIdByRefConst));
REQUIRE(total == storage2.total(&User::setIdByRef));
}
}
#ifdef SQLITE_ORM_OPTIONAL_SUPPORTED
TEST_CASE("Dump") {
struct User {
int id = 0;
std::optional<int> carYear; // will be empty if user takes the bus.
};
auto storage = make_storage(
{},
make_table("users", make_column("id", &User::id, primary_key()), make_column("car_year", &User::carYear)));
storage.sync_schema();
auto userId_1 = storage.insert(User{0, {}});
auto userId_2 = storage.insert(User{0, 2006});
std::ignore = userId_2;
REQUIRE(storage.count<User>(where(is_not_null(&User::carYear))) == 1);
auto rows = storage.select(&User::carYear, where(is_equal(&User::id, userId_1)));
REQUIRE(rows.size() == 1);
REQUIRE(!rows.front().has_value());
auto allUsers = storage.get_all<User>();
REQUIRE(allUsers.size() == 2);
const std::string dumpUser1 = storage.dump(allUsers[0]);
REQUIRE(dumpUser1 == std::string{"{ id : '1', car_year : 'null' }"});
const std::string dumpUser2 = storage.dump(allUsers[1]);
REQUIRE(dumpUser2 == std::string{"{ id : '2', car_year : '2006' }"});
}
#endif // SQLITE_ORM_OPTIONAL_SUPPORTED
| 34.805596 | 120 | 0.557568 | [
"object",
"vector"
] |
6a9695d756ffe19d9b2c4c5fc9547f64ca07f24d | 14,363 | cpp | C++ | gensim/src/generators/ExecutionEngine/InterpEEGenerator.cpp | Linestro/Gensim_Y | 031b74234a92622cf2d2d2ebc2d5ba03ca28ecf8 | [
"MIT"
] | 10 | 2020-07-14T22:09:30.000Z | 2022-01-11T09:57:52.000Z | gensim/src/generators/ExecutionEngine/InterpEEGenerator.cpp | Linestro/Gensim_Y | 031b74234a92622cf2d2d2ebc2d5ba03ca28ecf8 | [
"MIT"
] | 6 | 2020-07-09T12:01:57.000Z | 2021-04-27T10:23:58.000Z | gensim/src/generators/ExecutionEngine/InterpEEGenerator.cpp | Linestro/Gensim_Y | 031b74234a92622cf2d2d2ebc2d5ba03ca28ecf8 | [
"MIT"
] | 10 | 2020-07-29T17:05:26.000Z | 2021-12-04T14:57:15.000Z | /* This file is Copyright University of Edinburgh 2018. For license details, see LICENSE. */
#include "arch/ArchDescription.h"
#include "isa/ISADescription.h"
#include "generators/ExecutionEngine/InterpEEGenerator.h"
#include "generators/GenCInterpreter/GenCInterpreterGenerator.h"
#include "genC/ssa/SSAContext.h"
#include "genC/ssa/SSASymbol.h"
#include "genC/ssa/SSATypeFormatter.h"
using namespace gensim::generator;
void InterpEEGenerator::Setup(GenerationSetupManager& Setup)
{
for(auto i : Manager.GetArch().ISAs) {
for(auto j : i->Instructions) {
RegisterStepInstruction(*j.second);
}
GenCInterpreterGenerator interp(Manager);
interp.RegisterHelpers(*i);
}
}
bool InterpEEGenerator::GenerateHeader(util::cppformatstream &str) const
{
str <<
"#ifndef " << Manager.GetArch().Name << "_INTERP_H\n"
"#define " << Manager.GetArch().Name << "_INTERP_H\n";
if(Manager.GetComponent(GenerationManager::FnDecode)) {
str << "#include \"decode.h\"\n";
}
str <<
"#include <interpret/Interpreter.h>\n"
"#include <core/execution/InterpreterExecutionEngine.h>\n"
"#include <cstdint>\n"
"namespace gensim {"
"namespace " << Manager.GetArch().Name << "{"
"class Interpreter : public archsim::interpret::Interpreter {"
"public:"
" virtual archsim::core::execution::ExecutionResult StepBlock(archsim::core::execution::InterpreterExecutionEngineThreadContext *thread);"
" using decode_t = gensim::" << Manager.GetArch().Name << "::Decode;"
"private:"
" gensim::DecodeContext *decode_context_;"
" uint32_t DecodeInstruction(archsim::core::execution::InterpreterExecutionEngineThreadContext *thread_ctx, decode_t *&inst);"
" archsim::core::execution::ExecutionResult StepInstruction(archsim::core::thread::ThreadInstance *thread, decode_t &inst);"
"};"
""
;
str << "}";
str << "}";
str << "#endif";
return true;
}
bool InterpEEGenerator::GenerateSource(util::cppformatstream &str) const
{
str <<
"#include \"ee_interpreter.h\"\n"
"#include \"function_header.h\"\n"
"#include \"arch.h\"\n"
"#include \"decode.h\"\n"
"#include <module/Module.h>\n"
"#include <wutils/Vector.h>\n"
"#include <translate/jit_funs.h>\n"
"#include <core/execution/InterpreterExecutionEngine.h>\n"
"#include <gensim/gensim_processor_api.h>\n"
"#include <abi/devices/Device.h>\n"
"#include <gensim/gensim_decode_context.h>\n"
"#include <cmath>\n"
;
str << "using namespace gensim::" << Manager.GetArch().Name << ";";
GenerateDecodeInstruction(str);
str << "archsim::core::execution::ExecutionResult Interpreter::StepBlock(archsim::core::execution::InterpreterExecutionEngineThreadContext *thread_ctx) { ";
str << "auto thread = thread_ctx->GetThread();";
GenerateBlockExecutor(str);
str << "}";
GenerateHelperFunctions(str);
GenerateStepInstruction(str);
GenerateBehavioursDescriptors(str);
return true;
}
static void GenerateHelperFunctionPrototype(gensim::util::cppformatstream &str, const gensim::isa::ISADescription &isa, const gensim::genc::ssa::SSAFormAction *action)
{
gensim::genc::ssa::SSATypeFormatter formatter;
formatter.SetStructPrefix("gensim::" + action->Arch->Name + "::Decode::");
str << "template<bool trace> " << action->GetPrototype().ReturnType().GetCType() << " helper_" << isa.ISAName << "_" << action->GetPrototype().GetIRSignature().GetName() << "(archsim::core::thread::ThreadInstance *thread";
for(auto i : action->ParamSymbols) {
auto type_string = formatter.FormatType(i->GetType());
str << ", " << type_string << " " << i->GetName();
}
str << ")";
}
bool InterpEEGenerator::GenerateHelperFunctions(util::cppformatstream& str) const
{
for(auto isa : Manager.GetArch().ISAs) {
for(auto action : isa->GetSSAContext().Actions()) {
if(action.second->GetPrototype().HasAttribute(gensim::genc::ActionAttribute::Helper)) {
GenerateHelperFunctionPrototype(str, *isa, static_cast<gensim::genc::ssa::SSAFormAction*>(action.second));
str << ";";
}
}
}
for(auto isa : Manager.GetArch().ISAs) {
for(auto action : isa->GetSSAContext().Actions()) {
if(action.second->GetPrototype().HasAttribute(gensim::genc::ActionAttribute::Helper)) {
GenerateHelperFunction(str, *isa, static_cast<gensim::genc::ssa::SSAFormAction*>(action.second));
}
}
}
return true;
}
bool InterpEEGenerator::GenerateHelperFunction(util::cppformatstream& str, const gensim::isa::ISADescription &isa, const gensim::genc::ssa::SSAFormAction* action) const
{
assert(action != nullptr);
GenerateHelperFunctionPrototype(str, isa, action);
str << " { ";
str << "gensim::" << Manager.GetArch().Name << "::ArchInterface interface(thread);";
gensim::generator::GenCInterpreterGenerator gci (Manager);
gci.GenerateExecuteBodyFor(str, *action);
str << " }";
return true;
}
bool InterpEEGenerator::GenerateDecodeInstruction(util::cppformatstream& str) const
{
str << "uint32_t Interpreter::DecodeInstruction(archsim::core::execution::InterpreterExecutionEngineThreadContext *thread_ctx, Interpreter::decode_t *&inst) {";
str << " auto thread = thread_ctx->GetThread();";
str << " gensim::" << Manager.GetArch().Name << "::ArchInterface interface(thread);";
str << " gensim::BaseDecode *instr;";
str << " auto result = thread_ctx->GetDC()->DecodeSync(thread->GetFetchMI(), archsim::Address(interface.read_pc()), thread->GetModeID(), instr);";
str << " inst = (Interpreter::decode_t*)instr;";
str << " return result;";
str << "}";
return true;
}
bool InterpEEGenerator::GenerateBlockExecutor(util::cppformatstream& str) const
{
str <<
"while(true) {"
" decode_t *inst_;"
" uint32_t dcode_exception = DecodeInstruction(static_cast<archsim::core::execution::InterpreterExecutionEngineThreadContext*>(thread_ctx), inst_);"
" if(thread->HasMessage()) { return thread->HandleMessage(); }"
" if(dcode_exception) { thread->TakeMemoryException(thread->GetFetchMI(), thread->GetPC()); return archsim::core::execution::ExecutionResult::Exception; }"
" if(archsim::options::InstructionTick) { thread->GetPubsub().Publish(PubSubType::InstructionExecute, nullptr); } "
" auto result = StepInstruction(thread, *inst_);"
" if(inst_->GetEndOfBlock()) { inst_->Release(); return archsim::core::execution::ExecutionResult::Continue; }"
" inst_->Release();"
" if(result != archsim::core::execution::ExecutionResult::Continue) { return result; }"
"}";
return true;
}
bool InterpEEGenerator::GenerateStepInstruction(util::cppformatstream& str) const
{
for(auto i : Manager.GetArch().ISAs) {
GenerateStepInstructionISA(str, *i);
}
str <<
"archsim::core::execution::ExecutionResult Interpreter::StepInstruction(archsim::core::thread::ThreadInstance *thread, Interpreter::decode_t &inst) {";
str << "if(archsim::options::Verbose) {";
str << "if(archsim::options::ProfilePcFreq) {thread->GetMetrics().PCHistogram.inc(thread->GetPC().Get());}";
str << "if(archsim::options::Profile) {thread->GetMetrics().OpcodeHistogram.inc(inst.Instr_Code);}";
str << "if(archsim::options::ProfileIrFreq) {thread->GetMetrics().InstructionIRHistogram.inc(inst.ir);}";
str << "thread->GetMetrics().InstructionCount++;";
str << "}";
str << "switch(thread->GetModeID()) {";
for(auto i : Manager.GetArch().ISAs) {
str << "case " << i->isa_mode_id << ": if(archsim::options::Trace) { return StepInstruction_" << i->ISAName << "<true>(thread, inst); } else { return StepInstruction_" << i->ISAName << "<false>(thread, inst); }";
}
str <<
" default: "
" LC_ERROR(LogInterpreter) << \"Unknown mode\"; break;"
" }";
str <<
" return archsim::core::execution::ExecutionResult::Abort; "
"}";
return true;
}
bool InterpEEGenerator::RegisterStepInstruction(isa::InstructionDescription& insn) const
{
std::stringstream prototype_str;
prototype_str << "template<bool trace=false> archsim::core::execution::ExecutionResult StepInstruction_" << insn.ISA.ISAName << "_" << insn.Name << "(archsim::core::thread::ThreadInstance *thread, gensim::" << Manager.GetArch().Name << "::Interpreter::decode_t &inst)";
auto action = static_cast<const gensim::genc::ssa::SSAFormAction*>(insn.ISA.GetSSAContext().GetAction(insn.BehaviourName));
util::cppformatstream body_str;
body_str << "template<bool trace> archsim::core::execution::ExecutionResult StepInstruction_" << insn.ISA.ISAName << "_" << insn.Name << "(archsim::core::thread::ThreadInstance *thread, gensim::" << Manager.GetArch().Name << "::Interpreter::decode_t &" << action->ParamSymbols.at(0)->GetName() << ")";
body_str << "{";
body_str << "gensim::" << Manager.GetArch().Name << "::ArchInterface interface(thread);";
gensim::generator::GenCInterpreterGenerator gci (Manager);
gci.GenerateExecuteBodyFor(body_str, *action);
body_str << "return archsim::core::execution::ExecutionResult::Continue;";
body_str << "}";
// specialisations
std::string spec_1 = "template archsim::core::execution::ExecutionResult StepInstruction_" + insn.ISA.ISAName + "_" + insn.Name + "<false>(archsim::core::thread::ThreadInstance *thread, gensim::" + Manager.GetArch().Name + "::Interpreter::decode_t &inst);";
std::string spec_2 = "template archsim::core::execution::ExecutionResult StepInstruction_" + insn.ISA.ISAName + "_" + insn.Name + "<true>(archsim::core::thread::ThreadInstance *thread, gensim::" + Manager.GetArch().Name + "::Interpreter::decode_t &inst);";
Manager.AddFunctionEntry(FunctionEntry(prototype_str.str(), body_str.str(), {"arch.h","ee_interpreter.h"}, {"math.h", "core/execution/ExecutionResult.h", "core/thread/ThreadInstance.h"}, {spec_1, spec_2}, true));
return true;
}
bool InterpEEGenerator::GenerateStepInstructionISA(util::cppformatstream& str, isa::ISADescription& isa) const
{
// predicate stuff
bool has_is_predicated = isa.GetSSAContext().HasAction("instruction_is_predicated");
bool has_instruction_predicate = isa.GetSSAContext().HasAction("instruction_predicate");
if(has_is_predicated != has_instruction_predicate) {
if(has_is_predicated) {
throw std::logic_error("Architecture has predicate checker but no predicate function");
} else {
throw std::logic_error("Architecture has predicate function but no predicate checker");
}
}
if(has_is_predicated) {
str << "static bool " << isa.ISAName << "_is_predicated(archsim::core::thread::ThreadInstance *thread, Interpreter::decode_t &insn) { return helper_" << isa.ISAName << "_instruction_is_predicated<false>(thread, insn); }";
}
if(has_instruction_predicate) {
str << "static bool " << isa.ISAName << "_check_predicate(archsim::core::thread::ThreadInstance *thread, Interpreter::decode_t &insn) { return helper_" << isa.ISAName << "_instruction_predicate<false>(thread, insn); }";
}
str << "template<bool trace=false> archsim::core::execution::ExecutionResult StepInstruction_" << isa.ISAName << "(archsim::core::thread::ThreadInstance *thread, Interpreter::decode_t &decode) {";
str << "gensim::" << Manager.GetArch().Name << "::ArchInterface interface(thread);";
str << "archsim::core::execution::ExecutionResult interp_result = archsim::core::execution::ExecutionResult::Continue;";
str << "bool should_execute = true;";
str << "if(trace) { if(thread->GetTraceSource() == nullptr) { throw std::logic_error(\"\"); } thread->GetTraceSource()->Trace_Insn(thread->GetPC().Get(), decode.ir, false, thread->GetModeID(), thread->GetExecutionRing(), 1); }";
// check predicate
if(has_is_predicated && has_instruction_predicate) {
str << "should_execute = !" << isa.ISAName << "_is_predicated(thread, decode) || " << isa.ISAName << "_check_predicate(thread, decode);";
}
str << "if(should_execute) {";
str << " switch(decode.Instr_Code) {";
str << " using namespace gensim::" << Manager.GetArch().Name << ";";
for(auto i : isa.Instructions) {
str << "case INST_" << isa.ISAName << "_" << i.second->Name << ": interp_result = StepInstruction_" << isa.ISAName << "_" << i.first << "<trace>(thread, decode); break;";
}
str << " default: LC_ERROR(LogInterpreter) << \"Unknown instruction at PC \" << std::hex << thread->GetPC(); return archsim::core::execution::ExecutionResult::Abort;";
str << "}";
str << "}";
str << "if(!decode.GetEndOfBlock() || !should_execute) {";
str << " interface.write_pc(interface.read_pc() + decode.Instr_Length);";
str << "}";
str << "if(trace) { thread->GetTraceSource()->Trace_End_Insn(); }";
str << "return interp_result;";
str << "}";
return true;
}
bool InterpEEGenerator::GenerateBehavioursDescriptors(util::cppformatstream& str) const
{
std::string isa_descriptors;
for(auto i : Manager.GetArch().ISAs) {
if(!isa_descriptors.empty()) {
isa_descriptors += ", ";
}
isa_descriptors += "behaviours_" + i->ISAName;
std::string behaviours_list;
for(auto action : i->GetSSAContext().Actions()) {
if(action.second->GetPrototype().HasAttribute(gensim::genc::ActionAttribute::Export)) {
if(!behaviours_list.empty()) {
behaviours_list += ", ";
}
behaviours_list += "bd_" + i->ISAName + "_" + action.first + "()";
str << "static archsim::BehaviourDescriptor bd_" << i->ISAName << "_" << action.first << "() { archsim::BehaviourDescriptor bd (\"" << action.first << "\", [](const archsim::InvocationContext &ctx){ helper_" << i->ISAName << "_" << action.first << "<false>(ctx.GetThread()";
// unpack arguments
for(size_t index = 0; index < action.second->GetPrototype().ParameterTypes().size(); ++index) {
auto &argtype = action.second->GetPrototype().ParameterTypes().at(index);
// if we're accessing a struct, assume it's a decode_t
std::string type_string;
if(argtype.Reference) {
UNIMPLEMENTED;
}
if(argtype.IsStruct()) {
UNIMPLEMENTED;
}
str << ", (" << argtype.GetCType() << ")ctx.GetArg(" << index << ")";
}
str << "); return 0; }); return bd; }";
}
}
str << "namespace " << Manager.GetArch().Name << "{";
str << "archsim::ISABehavioursDescriptor get_behaviours_" << i->ISAName << "() { static archsim::ISABehavioursDescriptor bd ({" << behaviours_list << "}); return bd; }";
str << "}";
}
return true;
}
InterpEEGenerator::~InterpEEGenerator()
{
}
DEFINE_COMPONENT(InterpEEGenerator, ee_interp)
| 40.345506 | 303 | 0.686765 | [
"vector"
] |
6a9b34730ea551f944fec432a07122eb6c08ad21 | 3,759 | cpp | C++ | src/tile.cpp | GabLeRoux/dkc2-maps | 2d8a6a587b3731be27f9571b9bf3e93132283091 | [
"MIT"
] | 9 | 2015-12-07T13:59:23.000Z | 2022-03-15T13:20:59.000Z | src/tile.cpp | GabLeRoux/dkc2-maps | 2d8a6a587b3731be27f9571b9bf3e93132283091 | [
"MIT"
] | 1 | 2019-10-14T01:51:13.000Z | 2019-10-14T01:55:45.000Z | src/tile.cpp | GabLeRoux/dkc2-maps | 2d8a6a587b3731be27f9571b9bf3e93132283091 | [
"MIT"
] | 4 | 2015-12-07T13:59:36.000Z | 2019-11-24T22:13:11.000Z |
#include "stdafx.h"
#include <vector>
#include "tile.h"
#include "bitmap.h"
TilePalette::TilePalette()
{
for (UINT i = 0; i < 16; i++) {
transparent_[i] = 0x00000000;
}
}
bool TilePalette::LoadSpriteSubPal(CartFile& cart, UINT id)
{
CartFile::Scope scope(cart);
DWORD addr;
addr = 0x003D0000;
if (!cart.Read(0x003D5FEE + (id * 2), &addr, 2)) {
return false;
}
cart.Seek(addr);
color_[0] = 0x00000000;
for (int i = 1; i < 16; i++) {
WORD color;
if (!cart.ReadWord(color)) {
return false;
}
color_[i] = color;
}
SetTransparent(0, true);
return true;
}
bool TilePalette::LoadPalette(CartFile& cart, UINT addr)
{
CartFile::Scope scope(cart);
cart.Seek(addr);
if (!cart.Read(color_, 2 * 128)) {
return false;
}
return true;
}
bool TilePalette::LoadSubPalette(CartFile& cart, UINT addr,
UINT start, UINT count)
{
CartFile::Scope scope(cart);
cart.Seek(addr);
if (start + count >= 128) {
return false;
}
if (!cart.Read(&color_[start], 2 * count)) {
return false;
}
return true;
}
void TilePalette::GetQuad(UINT index, DWORD& color) const
{
if (index >= 128) {
return ;
}
color = color_[index];
BYTE r, g, b;
r = (BYTE) ((color & 0x001F));
g = (BYTE) ((color & 0x03E0) >> 5);
b = (BYTE) ((color & 0x7C00) >> 10);
// Convert color from 5 bits to 8 bits
r = (BYTE) (r / 32.0 * 256);
g = (BYTE) (g / 32.0 * 256);
b = (BYTE) (b / 32.0 * 256);
color = MAKEQUAD(r, g, b);
}
void TilePalette::SetColor(UINT index, WORD color)
{
if (index >= 128) {
return ;
}
color_[index] = color;
}
void TilePalette::SetTransparent(UINT index, bool set)
{
if (index >= 128) {
return ;
}
UINT byte_index = index / 8,
bit_pos = index % 8;
BYTE mask = transparent_[byte_index];
if (set) {
mask |= 1 << bit_pos;
}
else {
mask &= ~(1 << bit_pos);
}
transparent_[byte_index] = mask;
}
bool TilePalette::IsTransparent(UINT index) const
{
if (index >= 128) {
return true;
}
UINT byte_index = index / 8,
bit_pos = index % 8;
return (transparent_[byte_index] & (1 << bit_pos)) != 0;
}
bool DrawTile8x8(BitmapSurface& bm, TilePalette& palette,
UINT pal_index, int x, int y, CartFile& cart,
bool flip_horz, bool flip_vert
)
{
BYTE tile_data[32];
if (!cart.Read(tile_data, 32)) {
return false;
}
DrawTile8x8(bm, palette, pal_index, x, y, tile_data,
flip_horz, flip_vert);
}
bool DrawTile8x8(BitmapSurface& bm, TilePalette& palette,
UINT pal_index, int x, int y, BYTE *data,
bool flip_horz, bool flip_vert)
{
UINT i, j, c, pix_x, pix_y;
BYTE bp1, bp2, bp3, bp4;
DWORD bmData[64];
DWORD bmMaskData[8] = {};
for (i = 0; i < 8; i++) {
bp1 = data[i * 2 + 0x00], bp2 = data[i * 2 + 0x01];
bp3 = data[i * 2 + 0x10], bp4 = data[i * 2 + 0x11];
for (j = 0; j < 8; j++) {
/* Get the color index */
c = ((bp1 & 0x80) >> 7) | ((bp2 & 0x80) >> 6) |
((bp3 & 0x80) >> 5) | ((bp4 & 0x80) >> 4);
c += pal_index;
DWORD color;
/* Get the color from index */
pix_x = (flip_horz) ? 7 - j : j;
pix_y = (flip_vert) ? 7 - i : i;
if (palette.IsTransparent(c)) {
// Pixel is transparent
bmMaskData[pix_y] |= 1 << (7 - pix_x);
bmData[(pix_y * 8) + pix_x] = 0;
}
else {
// Pixel is visible
palette.GetQuad(c, color);
bmData[(pix_y * 8) + pix_x] = color;
}
bp1 <<= 1, bp2 <<= 1, bp3 <<= 1, bp4 <<= 1;
}
}
bm.SetMaskBits(x, y, 8, 8, bmMaskData);
return bm.SetBits(x, y, 8, 8, bmData);
}
| 23.203704 | 60 | 0.54323 | [
"vector"
] |
6a9cc6a8509b1670fe35185fd89ebf458ad15329 | 50,244 | cpp | C++ | demoinfogo/demofiledump.cpp | MeyerFabian/csgo-demoinfo | 6af1d42e640d53b8314a3bbb03cf67ab8aea3ad8 | [
"BSD-2-Clause"
] | null | null | null | demoinfogo/demofiledump.cpp | MeyerFabian/csgo-demoinfo | 6af1d42e640d53b8314a3bbb03cf67ab8aea3ad8 | [
"BSD-2-Clause"
] | null | null | null | demoinfogo/demofiledump.cpp | MeyerFabian/csgo-demoinfo | 6af1d42e640d53b8314a3bbb03cf67ab8aea3ad8 | [
"BSD-2-Clause"
] | null | null | null | //====== Copyright (c) 2014, Valve Corporation, 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.
//===========================================================================//
#include "demofiledump.h"
#include "demofile.h"
#include "demofilepropdecode.h"
#include <conio.h>
#include <stdarg.h>
#include "google/protobuf/descriptor.h"
#include "google/protobuf/descriptor.pb.h"
#include "google/protobuf/reflection_ops.h"
#include "generated_proto/cstrike15_usermessages_public.pb.h"
#include "generated_proto/netmessages_public.pb.h"
// file globals
static int s_nNumStringTables;
static StringTableData_t s_StringTables[MAX_STRING_TABLES];
static int s_nServerClassBits = 0;
static std::vector<ServerClass_t> s_ServerClasses;
static std::vector<CSVCMsg_SendTable> s_DataTables;
static std::vector<ExcludeEntry> s_currentExcludes;
static std::vector<EntityEntry*> s_Entities;
static std::vector<player_info_t> s_PlayerInfos;
extern bool g_bDumpGameEvents;
extern bool g_bSupressFootstepEvents;
extern bool g_bShowExtraPlayerInfoInGameEvents;
extern bool g_bDumpDeaths;
extern bool g_bSupressWarmupDeaths;
extern bool g_bDumpStringTables;
extern bool g_bDumpDataTables;
extern bool g_bDumpPacketEntities;
extern bool g_bDumpNetMessages;
extern bool g_bDumpNades;
extern bool g_bRoundInfo;
static bool s_bMatchStartOccured = false;
static int s_nRoundCounterLastPhaseEnd = 0;
static int s_nCurrentTick = 0;
static float s_nServerTickInterval;
static int s_nRoundEndTick = 0;
static int s_nTeamAScore = 0;
static int s_nTeamBScore = 0;
EntityEntry* FindEntity(int nEntity);
player_info_t* FindPlayerByEntity(int entityID);
__declspec(noreturn) void fatal_errorf(const char* fmt, ...)
{
va_list vlist;
char buf[1024];
va_start(vlist, fmt);
vsnprintf_s(buf, sizeof(buf), fmt, vlist);
buf[sizeof(buf) - 1] = 0;
va_end(vlist);
fprintf(stderr, "\nERROR: %s\n", buf);
exit(-1);
}
bool CDemoFileDump::Open(const char* filename)
{
if (!m_demofile.Open(filename)) {
fprintf(stderr, "Couldn't open '%s'\n", filename);
return false;
}
return true;
}
void CDemoFileDump::MsgPrintf(const ::google::protobuf::Message& msg, int size, const char* fmt, ...)
{
if (g_bDumpNetMessages) {
va_list vlist;
const std::string& TypeName = msg.GetTypeName();
// Print the message type and size
printf("---- %s (%d bytes) -----------------\n", TypeName.c_str(), size);
va_start(vlist, fmt);
vprintf(fmt, vlist);
va_end(vlist);
}
}
template <class T, int msgType>
void PrintUserMessage(CDemoFileDump& Demo, const void* parseBuffer, int BufferSize)
{
T msg;
if (msg.ParseFromArray(parseBuffer, BufferSize)) {
Demo.MsgPrintf(msg, BufferSize, "%s", msg.DebugString().c_str());
}
}
void CDemoFileDump::DumpUserMessage(const void* parseBuffer, int BufferSize)
{
CSVCMsg_UserMessage userMessage;
if (userMessage.ParseFromArray(parseBuffer, BufferSize)) {
int Cmd = userMessage.msg_type();
int SizeUM = userMessage.msg_data().size();
const void* parseBufferUM = &userMessage.msg_data()[0];
switch (Cmd) {
#define HANDLE_UserMsg(_x) \
case CS_UM_##_x: \
PrintUserMessage<CCSUsrMsg_##_x, CS_UM_##_x>(*this, parseBufferUM, SizeUM); \
break
default:
// unknown user message
break;
HANDLE_UserMsg(VGUIMenu);
HANDLE_UserMsg(Geiger);
HANDLE_UserMsg(Train);
HANDLE_UserMsg(HudText);
HANDLE_UserMsg(SayText);
HANDLE_UserMsg(SayText2);
HANDLE_UserMsg(TextMsg);
HANDLE_UserMsg(HudMsg);
HANDLE_UserMsg(ResetHud);
HANDLE_UserMsg(GameTitle);
HANDLE_UserMsg(Shake);
HANDLE_UserMsg(Fade);
HANDLE_UserMsg(Rumble);
HANDLE_UserMsg(CloseCaption);
HANDLE_UserMsg(CloseCaptionDirect);
HANDLE_UserMsg(SendAudio);
HANDLE_UserMsg(RawAudio);
HANDLE_UserMsg(VoiceMask);
HANDLE_UserMsg(RequestState);
HANDLE_UserMsg(Damage);
HANDLE_UserMsg(RadioText);
HANDLE_UserMsg(HintText);
HANDLE_UserMsg(KeyHintText);
HANDLE_UserMsg(ProcessSpottedEntityUpdate);
HANDLE_UserMsg(ReloadEffect);
HANDLE_UserMsg(AdjustMoney);
HANDLE_UserMsg(StopSpectatorMode);
HANDLE_UserMsg(KillCam);
HANDLE_UserMsg(DesiredTimescale);
HANDLE_UserMsg(CurrentTimescale);
HANDLE_UserMsg(AchievementEvent);
HANDLE_UserMsg(MatchEndConditions);
HANDLE_UserMsg(DisconnectToLobby);
HANDLE_UserMsg(DisplayInventory);
HANDLE_UserMsg(WarmupHasEnded);
HANDLE_UserMsg(ClientInfo);
HANDLE_UserMsg(CallVoteFailed);
HANDLE_UserMsg(VoteStart);
HANDLE_UserMsg(VotePass);
HANDLE_UserMsg(VoteFailed);
HANDLE_UserMsg(VoteSetup);
HANDLE_UserMsg(SendLastKillerDamageToClient);
HANDLE_UserMsg(ItemPickup);
HANDLE_UserMsg(ShowMenu);
HANDLE_UserMsg(BarTime);
HANDLE_UserMsg(AmmoDenied);
HANDLE_UserMsg(MarkAchievement);
HANDLE_UserMsg(ItemDrop);
HANDLE_UserMsg(GlowPropTurnOff);
#undef HANDLE_UserMsg
}
}
}
template <class T, int msgType>
void PrintNetMessage(CDemoFileDump& Demo, const void* parseBuffer, int BufferSize)
{
T msg;
if (msg.ParseFromArray(parseBuffer, BufferSize)) {
if (msgType == svc_GameEventList) {
Demo.m_GameEventList.CopyFrom(msg);
}
if (msgType == 8) {
string tick = "tick_interval";
string server_info = msg.DebugString();
size_t found_tick_begin = server_info.find(tick) + (tick.size() + 2);
size_t found_tick_end = server_info.find('\n', found_tick_begin);
if (found_tick_begin != string::npos) {
size_t length = found_tick_end - found_tick_begin;
string tick_interval = server_info.substr(found_tick_begin, length);
s_nServerTickInterval = (float)atof(tick_interval.c_str());
}
}
Demo.MsgPrintf(msg, BufferSize, "%s", msg.DebugString().c_str());
}
}
template <>
void PrintNetMessage<CSVCMsg_UserMessage, svc_UserMessage>(CDemoFileDump& Demo, const void* parseBuffer, int BufferSize)
{
Demo.DumpUserMessage(parseBuffer, BufferSize);
}
player_info_t* FindPlayerByEntity(int entityId)
{
for (std::vector<player_info_t>::iterator j = s_PlayerInfos.begin(); j != s_PlayerInfos.end(); j++) {
if (j->entityID == entityId) {
return &(*j);
}
}
return NULL;
}
player_info_t* FindPlayerInfo(int userId)
{
for (std::vector<player_info_t>::iterator i = s_PlayerInfos.begin(); i != s_PlayerInfos.end(); i++) {
if (i->userID == userId) {
return &(*i);
}
}
return NULL;
}
const CSVCMsg_GameEventList::descriptor_t* GetGameEventDescriptor(const CSVCMsg_GameEvent& msg, CDemoFileDump& Demo)
{
int iDescriptor;
for (iDescriptor = 0; iDescriptor < Demo.m_GameEventList.descriptors().size(); iDescriptor++) {
const CSVCMsg_GameEventList::descriptor_t& Descriptor = Demo.m_GameEventList.descriptors(iDescriptor);
if (Descriptor.eventid() == msg.eventid())
break;
}
if (iDescriptor == Demo.m_GameEventList.descriptors().size()) {
if (g_bDumpGameEvents) {
printf("%s", msg.DebugString().c_str());
}
return NULL;
}
return &Demo.m_GameEventList.descriptors(iDescriptor);
}
bool HandlePlayerConnectDisconnectEvents(const CSVCMsg_GameEvent& msg, const CSVCMsg_GameEventList::descriptor_t* pDescriptor)
{
// need to handle player_connect and player_disconnect because this is the only place bots get added to our player info array
// actual players come in via string tables
bool bPlayerDisconnect = (pDescriptor->name().compare("player_disconnect") == 0);
if (pDescriptor->name().compare("player_connect") == 0 || bPlayerDisconnect) {
int numKeys = msg.keys().size();
int userid = -1;
unsigned int index = -1;
const char* name = NULL;
bool bBot = false;
const char* reason = NULL;
for (int i = 0; i < numKeys; i++) {
const CSVCMsg_GameEventList::key_t& Key = pDescriptor->keys(i);
const CSVCMsg_GameEvent::key_t& KeyValue = msg.keys(i);
if (Key.name().compare("userid") == 0) {
userid = KeyValue.val_short();
} else if (Key.name().compare("index") == 0) {
index = KeyValue.val_byte();
} else if (Key.name().compare("name") == 0) {
name = KeyValue.val_string().c_str();
} else if (Key.name().compare("networkid") == 0) {
bBot = (KeyValue.val_string().compare("BOT") == 0);
} else if (Key.name().compare("bot") == 0) {
bBot = KeyValue.val_bool();
} else if (Key.name().compare("reason") == 0) {
reason = KeyValue.val_string().c_str();
}
}
if (bPlayerDisconnect) {
if (g_bDumpGameEvents) {
printf("Player %s (id:%d) disconnected. reason:%s\n", name, userid, reason);
}
// mark the player info slot as disconnected
player_info_t* pPlayerInfo = FindPlayerInfo(userid);
if (pPlayerInfo) {
strcpy_s(pPlayerInfo->name, "disconnected");
pPlayerInfo->userID = -1;
pPlayerInfo->guid[0] = 0;
}
} else {
player_info_t newPlayer;
memset(&newPlayer, 0, sizeof(newPlayer));
newPlayer.userID = userid;
strcpy_s(newPlayer.name, name);
newPlayer.fakeplayer = bBot;
if (bBot) {
strcpy_s(newPlayer.guid, "BOT");
}
newPlayer.entityID = index;
auto existing = FindPlayerByEntity(index);
// add entity if it doesn't exist, update if it does
if (!existing) {
if (g_bDumpGameEvents) {
printf("Player %s %s (id:%d) connected.\n", newPlayer.guid, name, userid);
}
s_PlayerInfos.push_back(newPlayer);
} else {
*existing = newPlayer;
}
}
return true;
}
return false;
}
bool ShowNadeInfo(const char* pField, int nIndex)
{
player_info_t* pPlayerInfo = FindPlayerInfo(nIndex);
if (pPlayerInfo) {
printf("%s", pPlayerInfo->name);
int nEntityIndex = pPlayerInfo->entityID + 1;
EntityEntry* pEntity = FindEntity(nEntityIndex);
if (pEntity) {
PropEntry* pTeamProp = pEntity->FindProp("m_iTeamNum");
if (pTeamProp) {
printf(",%s", (pTeamProp->m_pPropValue->m_value.m_int == 2) ? "T" : "CT");
}
PropEntry* pXYProp = pEntity->FindProp("m_vecOrigin");
PropEntry* pZProp = pEntity->FindProp("m_vecOrigin[2]");
if (pXYProp && pZProp) {
printf(",setpos %f %f %f", pXYProp->m_pPropValue->m_value.m_vector.x, pXYProp->m_pPropValue->m_value.m_vector.y, pZProp->m_pPropValue->m_value.m_float);
}
PropEntry* pAngle0Prop = pEntity->FindProp("m_angEyeAngles[0]");
PropEntry* pAngle1Prop = pEntity->FindProp("m_angEyeAngles[1]");
if (pAngle0Prop && pAngle1Prop) {
printf("; setang %f %f 0.0", pAngle0Prop->m_pPropValue->m_value.m_float, pAngle1Prop->m_pPropValue->m_value.m_float);
}
}
return true;
}
return false;
}
bool ShowPlayerInfo(const char* pField, int nIndex, bool bShowDetails = true, bool bCSV = false)
{
player_info_t* pPlayerInfo = FindPlayerInfo(nIndex);
if (pPlayerInfo) {
if (bCSV) {
printf("%s, %s, %d", pField, pPlayerInfo->name, nIndex);
} else {
printf(" %s: %s (id:%d)\n", pField, pPlayerInfo->name, nIndex);
}
if (bShowDetails) {
int nEntityIndex = pPlayerInfo->entityID + 1;
EntityEntry* pEntity = FindEntity(nEntityIndex);
if (pEntity) {
PropEntry* pXYProp = pEntity->FindProp("m_vecOrigin");
PropEntry* pZProp = pEntity->FindProp("m_vecOrigin[2]");
if (pXYProp && pZProp) {
if (bCSV) {
printf(", %f, %f, %f", pXYProp->m_pPropValue->m_value.m_vector.x, pXYProp->m_pPropValue->m_value.m_vector.y, pZProp->m_pPropValue->m_value.m_float);
} else {
printf(" position: %f, %f, %f\n", pXYProp->m_pPropValue->m_value.m_vector.x, pXYProp->m_pPropValue->m_value.m_vector.y, pZProp->m_pPropValue->m_value.m_float);
}
}
PropEntry* pAngle0Prop = pEntity->FindProp("m_angEyeAngles[0]");
PropEntry* pAngle1Prop = pEntity->FindProp("m_angEyeAngles[1]");
if (pAngle0Prop && pAngle1Prop) {
if (bCSV) {
printf(", %f, %f", pAngle0Prop->m_pPropValue->m_value.m_float, pAngle1Prop->m_pPropValue->m_value.m_float);
} else {
printf(" facing: pitch:%f, yaw:%f\n", pAngle0Prop->m_pPropValue->m_value.m_float, pAngle1Prop->m_pPropValue->m_value.m_float);
}
}
PropEntry* pTeamProp = pEntity->FindProp("m_iTeamNum");
if (pTeamProp) {
if (bCSV) {
printf(", %s", (pTeamProp->m_pPropValue->m_value.m_int == 2) ? "T" : "CT");
} else {
printf(" team: %s\n", (pTeamProp->m_pPropValue->m_value.m_int == 2) ? "T" : "CT");
}
}
}
}
return true;
}
return false;
}
void PrintTime()
{
size_t ticks_round_end;
if (s_nCurrentTick > s_nRoundEndTick) {
printf("-");
ticks_round_end = s_nCurrentTick - s_nRoundEndTick;
} else {
ticks_round_end = s_nRoundEndTick - s_nCurrentTick;
}
size_t timer_to_round_end_mins = ((size_t)((float)ticks_round_end * s_nServerTickInterval) / 60) % 60;
size_t timer_to_round_end_secs = (size_t)((float)ticks_round_end * s_nServerTickInterval) % 60;
printf("%dm %ds,", timer_to_round_end_mins, timer_to_round_end_secs);
size_t time_hours = (size_t)((float)s_nCurrentTick * s_nServerTickInterval) / 3600;
size_t time_minutes = ((size_t)((float)s_nCurrentTick * s_nServerTickInterval) / 60) % 60;
size_t time_seconds = (size_t)((float)s_nCurrentTick * s_nServerTickInterval) % 60;
printf("%dh %dm %ds,", time_hours, time_minutes, time_seconds);
printf("%d,", s_nCurrentTick);
}
void HandlePlayerNade(const CSVCMsg_GameEvent& msg, const CSVCMsg_GameEventList::descriptor_t* pDescriptor)
{
int numKeys = msg.keys().size();
int userid = -1;
std::string weaponName;
for (int i = 0; i < numKeys; i++) {
const CSVCMsg_GameEventList::key_t& Key = pDescriptor->keys(i);
const CSVCMsg_GameEvent::key_t& KeyValue = msg.keys(i);
if (Key.name().compare("userid") == 0) {
userid = KeyValue.val_short();
} else if (Key.name().compare("weapon") == 0) {
weaponName = KeyValue.val_string();
}
}
if (weaponName.compare("weapon_flashbang") == 0 || weaponName.compare("weapon_molotov") == 0 || weaponName.compare("weapon_hegrenade") == 0 || weaponName.compare("weapon_smokegrenade") == 0) {
PrintTime();
printf("%s,", weaponName.c_str());
ShowNadeInfo("userid", userid);
printf("\n");
}
}
void HandleRoundStart(const CSVCMsg_GameEvent& msg, const CSVCMsg_GameEventList::descriptor_t* pDescriptor)
{
int numKeys = msg.keys().size();
// hardcoded mp_roundtime
int timelimit = 115;
s_nRoundEndTick = s_nCurrentTick + (int)((float)timelimit / s_nServerTickInterval);
PrintTime();
printf(",round_start,,\n");
}
void HandleRoundEnd(const CSVCMsg_GameEvent& msg, const CSVCMsg_GameEventList::descriptor_t* pDescriptor)
{
int numKeys = msg.keys().size();
size_t winner = -1;
size_t reason = -1;
for (int i = 0; i < numKeys; i++) {
const CSVCMsg_GameEventList::key_t& Key = pDescriptor->keys(i);
const CSVCMsg_GameEvent::key_t& KeyValue = msg.keys(i);
if (Key.name().compare("winner") == 0) {
winner = KeyValue.val_byte();
} else if (Key.name().compare("reason") == 0) {
reason = KeyValue.val_byte();
}
}
// IF NOT A DRAW
if (reason != 10) {
if (winner == 2) {
s_nTeamAScore += 1;
} else {
s_nTeamBScore += 1;
}
PrintTime();
printf("Score: %d : %d,", s_nTeamAScore, s_nTeamBScore);
printf("round_end,,\n");
}
}
void HandlePlayerDeath(const CSVCMsg_GameEvent& msg, const CSVCMsg_GameEventList::descriptor_t* pDescriptor)
{
int numKeys = msg.keys().size();
int userid = -1;
int attackerid = -1;
int assisterid = 0;
const char* pWeaponName = NULL;
bool bHeadshot = false;
for (int i = 0; i < numKeys; i++) {
const CSVCMsg_GameEventList::key_t& Key = pDescriptor->keys(i);
const CSVCMsg_GameEvent::key_t& KeyValue = msg.keys(i);
if (Key.name().compare("userid") == 0) {
userid = KeyValue.val_short();
} else if (Key.name().compare("attacker") == 0) {
attackerid = KeyValue.val_short();
} else if (Key.name().compare("assister") == 0) {
assisterid = KeyValue.val_short();
} else if (Key.name().compare("weapon") == 0) {
pWeaponName = KeyValue.val_string().c_str();
} else if (Key.name().compare("headshot") == 0) {
bHeadshot = KeyValue.val_bool();
}
}
ShowPlayerInfo("victim", userid, true, true);
printf(", ");
ShowPlayerInfo("attacker", attackerid, true, true);
printf(", %s, %s", pWeaponName, bHeadshot ? "true" : "false");
if (assisterid != 0) {
printf(", ");
ShowPlayerInfo("assister", assisterid, true, true);
}
printf("\n");
}
void HandlePhaseEnd()
{
size_t total_rounds = s_nTeamAScore + s_nTeamBScore;
// Matchmaking medic sometimes sends the phase end event so we check against score if it actually is a change.
// If a matchmaking medic happens and we already switched sides, we also check if we already did a phase end for this amount of rounds.
// This is an ugly fix and might break.
if (total_rounds != s_nRoundCounterLastPhaseEnd) {
if (total_rounds == 15) {
// Side switch regular time
std::swap(s_nTeamAScore, s_nTeamBScore);
s_nRoundCounterLastPhaseEnd = total_rounds;
PrintTime();
printf(",half_time,,\n");
} else if (total_rounds >= 30) {
// overtime
size_t total_rounds_overtime = total_rounds - 30;
if (total_rounds_overtime % 3 == 0) {
std::swap(s_nTeamAScore, s_nTeamBScore);
s_nRoundCounterLastPhaseEnd = total_rounds;
PrintTime();
printf(",");
if (total_rounds_overtime % 6 == 0) {
printf("overtime");
} else {
printf("overtime_halftime");
}
printf(",,\n");
}
}
}
}
void ParseGameEvent(const CSVCMsg_GameEvent& msg, const CSVCMsg_GameEventList::descriptor_t* pDescriptor)
{
if (pDescriptor) {
if (!(pDescriptor->name().compare("player_footstep") == 0 && g_bSupressFootstepEvents)) {
if (!HandlePlayerConnectDisconnectEvents(msg, pDescriptor)) {
if (pDescriptor->name().compare("announce_phase_end") == 0) {
HandlePhaseEnd();
}
if (pDescriptor->name().compare("round_announce_match_start") == 0) {
if (g_bRoundInfo) {
PrintTime();
printf(",match_start,,\n");
s_nTeamAScore = 0;
s_nTeamBScore = 0;
}
s_bMatchStartOccured = true;
}
bool bAllowDeathReport = !g_bSupressWarmupDeaths || s_bMatchStartOccured;
if (pDescriptor->name().compare("player_death") == 0 && g_bDumpDeaths && bAllowDeathReport) {
HandlePlayerDeath(msg, pDescriptor);
}
if (pDescriptor->name().compare("weapon_fire") == 0 && g_bDumpNades) {
HandlePlayerNade(msg, pDescriptor);
}
if (pDescriptor->name().compare("round_freeze_end") == 0 && g_bRoundInfo) {
HandleRoundStart(msg, pDescriptor);
}
if (pDescriptor->name().compare("round_end") == 0 && g_bRoundInfo) {
HandleRoundEnd(msg, pDescriptor);
}
if (g_bDumpGameEvents) {
printf("%s\n{\n", pDescriptor->name().c_str());
}
int numKeys = msg.keys().size();
for (int i = 0; i < numKeys; i++) {
const CSVCMsg_GameEventList::key_t& Key = pDescriptor->keys(i);
const CSVCMsg_GameEvent::key_t& KeyValue = msg.keys(i);
if (g_bDumpGameEvents) {
bool bHandled = false;
if (Key.name().compare("userid") == 0 || Key.name().compare("attacker") == 0 || Key.name().compare("assister") == 0) {
bHandled = ShowPlayerInfo(Key.name().c_str(), KeyValue.val_short(), g_bShowExtraPlayerInfoInGameEvents);
}
if (!bHandled) {
printf(" %s: ", Key.name().c_str());
if (KeyValue.has_val_string()) {
printf("%s ", KeyValue.val_string().c_str());
}
if (KeyValue.has_val_float()) {
printf("%f ", KeyValue.val_float());
}
if (KeyValue.has_val_long()) {
printf("%d ", KeyValue.val_long());
}
if (KeyValue.has_val_short()) {
printf("%d ", KeyValue.val_short());
}
if (KeyValue.has_val_byte()) {
printf("%d ", KeyValue.val_byte());
}
if (KeyValue.has_val_bool()) {
printf("%d ", KeyValue.val_bool());
}
if (KeyValue.has_val_uint64()) {
printf("%lld ", KeyValue.val_uint64());
}
printf("\n");
}
}
}
if (g_bDumpGameEvents) {
printf("}\n");
}
}
}
}
}
template <>
void PrintNetMessage<CSVCMsg_GameEvent, svc_GameEvent>(CDemoFileDump& Demo, const void* parseBuffer, int BufferSize)
{
CSVCMsg_GameEvent msg;
if (msg.ParseFromArray(parseBuffer, BufferSize)) {
const CSVCMsg_GameEventList::descriptor_t* pDescriptor = GetGameEventDescriptor(msg, Demo);
if (pDescriptor) {
ParseGameEvent(msg, pDescriptor);
}
}
}
template <typename T>
static void LowLevelByteSwap(T* output, const T* input)
{
T temp = *output;
for (unsigned int i = 0; i < sizeof(T); i++) {
((unsigned char*)&temp)[i] = ((unsigned char*)input)[sizeof(T) - (i + 1)];
}
memcpy(output, &temp, sizeof(T));
}
void ParseStringTableUpdate(CBitRead& buf, int entries, int nMaxEntries, int user_data_size, int user_data_size_bits, int user_data_fixed_size, bool bIsUserInfo)
{
struct StringHistoryEntry {
char string[(1 << SUBSTRING_BITS)];
};
int lastEntry = -1;
int lastDictionaryIndex = -1;
// perform integer log2() to set nEntryBits
int nTemp = nMaxEntries;
int nEntryBits = 0;
while (nTemp >>= 1)
++nEntryBits;
bool bEncodeUsingDictionaries = buf.ReadOneBit() ? true : false;
if (bEncodeUsingDictionaries) {
printf("ParseStringTableUpdate: Encoded with dictionaries, unable to decode.\n");
return;
}
std::vector<StringHistoryEntry> history;
for (int i = 0; i < entries; i++) {
int entryIndex = lastEntry + 1;
if (!buf.ReadOneBit()) {
entryIndex = buf.ReadUBitLong(nEntryBits);
}
lastEntry = entryIndex;
if (entryIndex < 0 || entryIndex >= nMaxEntries) {
printf("ParseStringTableUpdate: bogus string index %i\n", entryIndex);
return;
}
const char* pEntry = NULL;
char entry[1024];
char substr[1024];
entry[0] = 0;
if (buf.ReadOneBit()) {
bool substringcheck = buf.ReadOneBit() ? true : false;
if (substringcheck) {
int index = buf.ReadUBitLong(5);
if (size_t(index) >= history.size()) {
printf("ParseStringTableUpdate: Invalid index %d, expected < %u\n", index, (unsigned)history.size());
exit(-1);
}
int bytestocopy = buf.ReadUBitLong(SUBSTRING_BITS);
strncpy_s(entry, history[index].string, bytestocopy + 1);
buf.ReadString(substr, sizeof(substr));
strcat_s(entry, substr);
} else {
buf.ReadString(entry, sizeof(entry));
}
pEntry = entry;
}
// Read in the user data.
unsigned char tempbuf[MAX_USERDATA_SIZE];
memset(tempbuf, 0, sizeof(tempbuf));
const void* pUserData = NULL;
int nBytes = 0;
if (buf.ReadOneBit()) {
if (user_data_fixed_size) {
// Don't need to read length, it's fixed length and the length was networked down already.
nBytes = user_data_size;
assert(nBytes > 0);
tempbuf[nBytes - 1] = 0; // be safe, clear last byte
buf.ReadBits(tempbuf, user_data_size_bits);
} else {
nBytes = buf.ReadUBitLong(MAX_USERDATA_BITS);
if (nBytes > sizeof(tempbuf)) {
printf("ParseStringTableUpdate: user data too large (%d bytes).", nBytes);
return;
}
buf.ReadBytes(tempbuf, nBytes);
}
pUserData = tempbuf;
}
if (pEntry == NULL) {
pEntry = ""; // avoid crash because of NULL strings
}
if (bIsUserInfo && pUserData != NULL) {
const player_info_t* pUnswappedPlayerInfo = (const player_info_t*)pUserData;
player_info_t playerInfo = *pUnswappedPlayerInfo;
playerInfo.entityID = entryIndex;
LowLevelByteSwap(&playerInfo.xuid, &pUnswappedPlayerInfo->xuid);
LowLevelByteSwap(&playerInfo.userID, &pUnswappedPlayerInfo->userID);
LowLevelByteSwap(&playerInfo.friendsID, &pUnswappedPlayerInfo->friendsID);
bool bAdded = false;
auto existing = FindPlayerByEntity(entryIndex);
if (!existing) {
bAdded = true;
s_PlayerInfos.push_back(playerInfo);
} else {
*existing = playerInfo;
}
if (g_bDumpStringTables) {
printf("player info\n{\n %s:true\n xuid:%lld\n name:%s\n userID:%d\n guid:%s\n friendsID:%d\n friendsName:%s\n fakeplayer:%d\n ishltv:%d\n filesDownloaded:%d\n}\n",
bAdded ? "adding" : "updating", playerInfo.xuid, playerInfo.name, playerInfo.userID, playerInfo.guid, playerInfo.friendsID,
playerInfo.friendsName, playerInfo.fakeplayer, playerInfo.ishltv, playerInfo.filesDownloaded);
}
} else {
if (g_bDumpStringTables) {
printf(" %d, %s, %d, %s \n", entryIndex, pEntry, nBytes, pUserData);
}
}
if (history.size() > 31) {
history.erase(history.begin());
}
StringHistoryEntry she;
strncpy_s(she.string, pEntry, sizeof(she.string) - 1);
history.push_back(she);
}
}
template <>
void PrintNetMessage<CSVCMsg_CreateStringTable, svc_CreateStringTable>(CDemoFileDump& Demo, const void* parseBuffer, int BufferSize)
{
CSVCMsg_CreateStringTable msg;
if (msg.ParseFromArray(parseBuffer, BufferSize)) {
bool bIsUserInfo = !strcmp(msg.name().c_str(), "userinfo");
if (g_bDumpStringTables) {
printf("CreateStringTable:%s:%d:%d:%d:%d:\n", msg.name().c_str(), msg.max_entries(), msg.num_entries(), msg.user_data_size(), msg.user_data_size_bits());
}
CBitRead data(&msg.string_data()[0], msg.string_data().size());
ParseStringTableUpdate(data, msg.num_entries(), msg.max_entries(), msg.user_data_size(), msg.user_data_size_bits(), msg.user_data_fixed_size(), bIsUserInfo);
strcpy_s(s_StringTables[s_nNumStringTables].szName, msg.name().c_str());
s_StringTables[s_nNumStringTables].nMaxEntries = msg.max_entries();
s_StringTables[s_nNumStringTables].nUserDataSize = msg.user_data_size();
s_StringTables[s_nNumStringTables].nUserDataSizeBits = msg.user_data_size_bits();
s_StringTables[s_nNumStringTables].nUserDataFixedSize = msg.user_data_fixed_size();
s_nNumStringTables++;
}
}
template <>
void PrintNetMessage<CSVCMsg_UpdateStringTable, svc_UpdateStringTable>(CDemoFileDump& Demo, const void* parseBuffer, int BufferSize)
{
CSVCMsg_UpdateStringTable msg;
if (msg.ParseFromArray(parseBuffer, BufferSize)) {
CBitRead data(&msg.string_data()[0], msg.string_data().size());
if (msg.table_id() < s_nNumStringTables && s_StringTables[msg.table_id()].nMaxEntries > msg.num_changed_entries()) {
const StringTableData_t& table = s_StringTables[msg.table_id()];
bool bIsUserInfo = !strcmp(table.szName, "userinfo");
if (g_bDumpStringTables) {
printf("UpdateStringTable:%d(%s):%d:\n", msg.table_id(), table.szName, msg.num_changed_entries());
}
ParseStringTableUpdate(data, msg.num_changed_entries(), table.nMaxEntries, table.nUserDataSize, table.nUserDataSizeBits, table.nUserDataFixedSize, bIsUserInfo);
} else {
printf("Bad UpdateStringTable:%d:%d!\n", msg.table_id(), msg.num_changed_entries());
}
}
}
void RecvTable_ReadInfos(const CSVCMsg_SendTable& msg)
{
if (g_bDumpDataTables) {
printf("%s:%d\n", msg.net_table_name().c_str(), msg.props_size());
for (int iProp = 0; iProp < msg.props_size(); iProp++) {
const CSVCMsg_SendTable::sendprop_t& sendProp = msg.props(iProp);
if ((sendProp.type() == DPT_DataTable) || (sendProp.flags() & SPROP_EXCLUDE)) {
printf("%d:%06X:%s:%s%s\n", sendProp.type(), sendProp.flags(), sendProp.var_name().c_str(), sendProp.dt_name().c_str(), (sendProp.flags() & SPROP_EXCLUDE) ? " exclude" : "");
} else if (sendProp.type() == DPT_Array) {
printf("%d:%06X:%s[%d]\n", sendProp.type(), sendProp.flags(), sendProp.var_name().c_str(), sendProp.num_elements());
} else {
printf("%d:%06X:%s:%f,%f,%08X%s\n", sendProp.type(), sendProp.flags(), sendProp.var_name().c_str(), sendProp.low_value(), sendProp.high_value(), sendProp.num_bits(), (sendProp.flags() & SPROP_INSIDEARRAY) ? " inside array" : "");
}
}
}
}
template <>
void PrintNetMessage<CSVCMsg_SendTable, svc_SendTable>(CDemoFileDump& Demo, const void* parseBuffer, int BufferSize)
{
CSVCMsg_SendTable msg;
if (msg.ParseFromArray(parseBuffer, BufferSize)) {
RecvTable_ReadInfos(msg);
}
}
CSVCMsg_SendTable* GetTableByClassID(uint32 nClassID)
{
for (uint32 i = 0; i < s_ServerClasses.size(); i++) {
if (s_ServerClasses[i].nClassID == nClassID) {
return &(s_DataTables[s_ServerClasses[i].nDataTable]);
}
}
return NULL;
}
CSVCMsg_SendTable* GetTableByName(const char* pName)
{
for (unsigned int i = 0; i < s_DataTables.size(); i++) {
if (s_DataTables[i].net_table_name().compare(pName) == 0) {
return &(s_DataTables[i]);
}
}
return NULL;
}
FlattenedPropEntry* GetSendPropByIndex(uint32 uClass, uint32 uIndex)
{
if (uIndex < s_ServerClasses[uClass].flattenedProps.size()) {
return &s_ServerClasses[uClass].flattenedProps[uIndex];
}
return NULL;
}
bool IsPropExcluded(CSVCMsg_SendTable* pTable, const CSVCMsg_SendTable::sendprop_t& checkSendProp)
{
for (unsigned int i = 0; i < s_currentExcludes.size(); i++) {
if (pTable->net_table_name().compare(s_currentExcludes[i].m_pDTName) == 0 && checkSendProp.var_name().compare(s_currentExcludes[i].m_pVarName) == 0) {
return true;
}
}
return false;
}
void GatherExcludes(CSVCMsg_SendTable* pTable)
{
for (int iProp = 0; iProp < pTable->props_size(); iProp++) {
const CSVCMsg_SendTable::sendprop_t& sendProp = pTable->props(iProp);
if (sendProp.flags() & SPROP_EXCLUDE) {
s_currentExcludes.push_back(ExcludeEntry(sendProp.var_name().c_str(), sendProp.dt_name().c_str(), pTable->net_table_name().c_str()));
}
if (sendProp.type() == DPT_DataTable) {
CSVCMsg_SendTable* pSubTable = GetTableByName(sendProp.dt_name().c_str());
if (pSubTable != NULL) {
GatherExcludes(pSubTable);
}
}
}
}
void GatherProps(CSVCMsg_SendTable* pTable, int nServerClass);
void GatherProps_IterateProps(CSVCMsg_SendTable* pTable, int nServerClass, std::vector<FlattenedPropEntry>& flattenedProps)
{
for (int iProp = 0; iProp < pTable->props_size(); iProp++) {
const CSVCMsg_SendTable::sendprop_t& sendProp = pTable->props(iProp);
if ((sendProp.flags() & SPROP_INSIDEARRAY) || (sendProp.flags() & SPROP_EXCLUDE) || IsPropExcluded(pTable, sendProp)) {
continue;
}
if (sendProp.type() == DPT_DataTable) {
CSVCMsg_SendTable* pSubTable = GetTableByName(sendProp.dt_name().c_str());
if (pSubTable != NULL) {
if (sendProp.flags() & SPROP_COLLAPSIBLE) {
GatherProps_IterateProps(pSubTable, nServerClass, flattenedProps);
} else {
GatherProps(pSubTable, nServerClass);
}
}
} else {
if (sendProp.type() == DPT_Array) {
flattenedProps.push_back(FlattenedPropEntry(&sendProp, &(pTable->props(iProp - 1))));
} else {
flattenedProps.push_back(FlattenedPropEntry(&sendProp, NULL));
}
}
}
}
void GatherProps(CSVCMsg_SendTable* pTable, int nServerClass)
{
std::vector<FlattenedPropEntry> tempFlattenedProps;
GatherProps_IterateProps(pTable, nServerClass, tempFlattenedProps);
std::vector<FlattenedPropEntry>& flattenedProps = s_ServerClasses[nServerClass].flattenedProps;
for (uint32 i = 0; i < tempFlattenedProps.size(); i++) {
flattenedProps.push_back(tempFlattenedProps[i]);
}
}
void FlattenDataTable(int nServerClass)
{
CSVCMsg_SendTable* pTable = &s_DataTables[s_ServerClasses[nServerClass].nDataTable];
s_currentExcludes.clear();
GatherExcludes(pTable);
GatherProps(pTable, nServerClass);
std::vector<FlattenedPropEntry>& flattenedProps = s_ServerClasses[nServerClass].flattenedProps;
// get priorities
std::vector<uint32> priorities;
priorities.push_back(64);
for (unsigned int i = 0; i < flattenedProps.size(); i++) {
uint32 priority = flattenedProps[i].m_prop->priority();
bool bFound = false;
for (uint32 j = 0; j < priorities.size(); j++) {
if (priorities[j] == priority) {
bFound = true;
break;
}
}
if (!bFound) {
priorities.push_back(priority);
}
}
std::sort(priorities.begin(), priorities.end());
// sort flattenedProps by priority
uint32 start = 0;
for (uint32 priority_index = 0; priority_index < priorities.size(); ++priority_index) {
uint32 priority = priorities[priority_index];
while (true) {
uint32 currentProp = start;
while (currentProp < flattenedProps.size()) {
const CSVCMsg_SendTable::sendprop_t* prop = flattenedProps[currentProp].m_prop;
if (prop->priority() == priority || (priority == 64 && (SPROP_CHANGES_OFTEN & prop->flags()))) {
if (start != currentProp) {
FlattenedPropEntry temp = flattenedProps[start];
flattenedProps[start] = flattenedProps[currentProp];
flattenedProps[currentProp] = temp;
}
start++;
break;
}
currentProp++;
}
if (currentProp == flattenedProps.size())
break;
}
}
}
int ReadFieldIndex(CBitRead& entityBitBuffer, int lastIndex, bool bNewWay)
{
if (bNewWay) {
if (entityBitBuffer.ReadOneBit()) {
return lastIndex + 1;
}
}
int ret = 0;
if (bNewWay && entityBitBuffer.ReadOneBit()) {
ret = entityBitBuffer.ReadUBitLong(3); // read 3 bits
} else {
ret = entityBitBuffer.ReadUBitLong(7); // read 7 bits
switch (ret & (32 | 64)) {
case 32:
ret = (ret & ~96) | (entityBitBuffer.ReadUBitLong(2) << 5);
assert(ret >= 32);
break;
case 64:
ret = (ret & ~96) | (entityBitBuffer.ReadUBitLong(4) << 5);
assert(ret >= 128);
break;
case 96:
ret = (ret & ~96) | (entityBitBuffer.ReadUBitLong(7) << 5);
assert(ret >= 512);
break;
}
}
if (ret == 0xFFF) // end marker is 4095 for cs:go
{
return -1;
}
return lastIndex + 1 + ret;
}
bool ReadNewEntity(CBitRead& entityBitBuffer, EntityEntry* pEntity)
{
bool bNewWay = (entityBitBuffer.ReadOneBit() == 1); // 0 = old way, 1 = new way
std::vector<int> fieldIndices;
int index = -1;
do {
index = ReadFieldIndex(entityBitBuffer, index, bNewWay);
if (index != -1) {
fieldIndices.push_back(index);
}
} while (index != -1);
CSVCMsg_SendTable* pTable = GetTableByClassID(pEntity->m_uClass);
if (g_bDumpPacketEntities) {
printf("Table: %s\n", pTable->net_table_name().c_str());
}
for (unsigned int i = 0; i < fieldIndices.size(); i++) {
FlattenedPropEntry* pSendProp = GetSendPropByIndex(pEntity->m_uClass, fieldIndices[i]);
if (pSendProp) {
Prop_t* pProp = DecodeProp(entityBitBuffer, pSendProp, pEntity->m_uClass, fieldIndices[i], !g_bDumpPacketEntities);
pEntity->AddOrUpdateProp(pSendProp, pProp);
} else {
return false;
}
}
return true;
}
EntityEntry* FindEntity(int nEntity)
{
for (std::vector<EntityEntry*>::iterator i = s_Entities.begin(); i != s_Entities.end(); i++) {
if ((*i)->m_nEntity == nEntity) {
return *i;
}
}
return NULL;
}
EntityEntry* AddEntity(int nEntity, uint32 uClass, uint32 uSerialNum)
{
// if entity already exists, then replace it, else add it
EntityEntry* pEntity = FindEntity(nEntity);
if (pEntity) {
pEntity->m_uClass = uClass;
pEntity->m_uSerialNum = uSerialNum;
} else {
pEntity = new EntityEntry(nEntity, uClass, uSerialNum);
s_Entities.push_back(pEntity);
}
return pEntity;
}
void RemoveEntity(int nEntity)
{
for (std::vector<EntityEntry*>::iterator i = s_Entities.begin(); i != s_Entities.end(); i++) {
EntityEntry* pEntity = *i;
if (pEntity->m_nEntity == nEntity) {
s_Entities.erase(i);
delete pEntity;
break;
}
}
}
template <>
void PrintNetMessage<CSVCMsg_PacketEntities, svc_PacketEntities>(CDemoFileDump& Demo, const void* parseBuffer, int BufferSize)
{
CSVCMsg_PacketEntities msg;
if (msg.ParseFromArray(parseBuffer, BufferSize)) {
CBitRead entityBitBuffer(&msg.entity_data()[0], msg.entity_data().size());
bool bAsDelta = msg.is_delta();
int nHeaderCount = msg.updated_entries();
int nBaseline = msg.baseline();
bool bUpdateBaselines = msg.update_baseline();
int nHeaderBase = -1;
int nNewEntity = -1;
int UpdateFlags = 0;
UpdateType updateType = PreserveEnt;
while (updateType < Finished) {
nHeaderCount--;
bool bIsEntity = (nHeaderCount >= 0) ? true : false;
if (bIsEntity) {
UpdateFlags = FHDR_ZERO;
nNewEntity = nHeaderBase + 1 + entityBitBuffer.ReadUBitVar();
nHeaderBase = nNewEntity;
// leave pvs flag
if (entityBitBuffer.ReadOneBit() == 0) {
// enter pvs flag
if (entityBitBuffer.ReadOneBit() != 0) {
UpdateFlags |= FHDR_ENTERPVS;
}
} else {
UpdateFlags |= FHDR_LEAVEPVS;
// Force delete flag
if (entityBitBuffer.ReadOneBit() != 0) {
UpdateFlags |= FHDR_DELETE;
}
}
}
for (updateType = PreserveEnt; updateType == PreserveEnt;) {
// Figure out what kind of an update this is.
if (!bIsEntity || nNewEntity > ENTITY_SENTINEL) {
updateType = Finished;
} else {
if (UpdateFlags & FHDR_ENTERPVS) {
updateType = EnterPVS;
} else if (UpdateFlags & FHDR_LEAVEPVS) {
updateType = LeavePVS;
} else {
updateType = DeltaEnt;
}
}
switch (updateType) {
case EnterPVS: {
uint32 uClass = entityBitBuffer.ReadUBitLong(s_nServerClassBits);
uint32 uSerialNum = entityBitBuffer.ReadUBitLong(NUM_NETWORKED_EHANDLE_SERIAL_NUMBER_BITS);
if (g_bDumpPacketEntities) {
printf("Entity Enters PVS: id:%d, class:%d, serial:%d\n", nNewEntity, uClass, uSerialNum);
}
EntityEntry* pEntity = AddEntity(nNewEntity, uClass, uSerialNum);
if (!ReadNewEntity(entityBitBuffer, pEntity)) {
printf("*****Error reading entity! Bailing on this PacketEntities!\n");
return;
}
} break;
case LeavePVS: {
if (!bAsDelta) // Should never happen on a full update.
{
printf("WARNING: LeavePVS on full update");
updateType = Failed; // break out
assert(0);
} else {
if (g_bDumpPacketEntities) {
if (UpdateFlags & FHDR_DELETE) {
printf("Entity leaves PVS and is deleted: id:%d\n", nNewEntity);
} else {
printf("Entity leaves PVS: id:%d\n", nNewEntity);
}
}
RemoveEntity(nNewEntity);
}
} break;
case DeltaEnt: {
EntityEntry* pEntity = FindEntity(nNewEntity);
if (pEntity) {
if (g_bDumpPacketEntities) {
printf("Entity Delta update: id:%d, class:%d, serial:%d\n", pEntity->m_nEntity, pEntity->m_uClass, pEntity->m_uSerialNum);
}
if (!ReadNewEntity(entityBitBuffer, pEntity)) {
printf("*****Error reading entity! Bailing on this PacketEntities!\n");
return;
}
} else {
assert(0);
}
} break;
case PreserveEnt: {
if (!bAsDelta) // Should never happen on a full update.
{
printf("WARNING: PreserveEnt on full update");
updateType = Failed; // break out
assert(0);
} else {
if (nNewEntity >= MAX_EDICTS) {
printf("PreserveEnt: nNewEntity == MAX_EDICTS");
assert(0);
} else {
if (g_bDumpPacketEntities) {
printf("PreserveEnt: id:%d\n", nNewEntity);
}
}
}
} break;
default:
break;
}
}
}
}
}
static std::string GetNetMsgName(int Cmd)
{
if (NET_Messages_IsValid(Cmd)) {
return NET_Messages_Name((NET_Messages)Cmd);
} else if (SVC_Messages_IsValid(Cmd)) {
return SVC_Messages_Name((SVC_Messages)Cmd);
}
return "NETMSG_???";
}
void CDemoFileDump::DumpDemoPacket(CBitRead& buf, int length)
{
while (buf.GetNumBytesRead() < length) {
int Cmd = buf.ReadVarInt32();
int Size = buf.ReadVarInt32();
if (buf.GetNumBytesRead() + Size > length) {
const std::string& strName = GetNetMsgName(Cmd);
fatal_errorf("DumpDemoPacket()::failed parsing packet. Cmd:%d '%s' \n", Cmd, strName.c_str());
}
switch (Cmd) {
#define HANDLE_NetMsg(_x) \
case net_##_x: \
PrintNetMessage<CNETMsg_##_x, net_##_x>(*this, buf.GetBasePointer() + buf.GetNumBytesRead(), Size); \
break
#define HANDLE_SvcMsg(_x) \
case svc_##_x: \
PrintNetMessage<CSVCMsg_##_x, svc_##_x>(*this, buf.GetBasePointer() + buf.GetNumBytesRead(), Size); \
break
default:
// unknown net message
break;
HANDLE_NetMsg(NOP); // 0
HANDLE_NetMsg(Disconnect); // 1
HANDLE_NetMsg(File); // 2
HANDLE_NetMsg(Tick); // 4
HANDLE_NetMsg(StringCmd); // 5
HANDLE_NetMsg(SetConVar); // 6
HANDLE_NetMsg(SignonState); // 7
HANDLE_SvcMsg(ServerInfo); // 8
HANDLE_SvcMsg(SendTable); // 9
HANDLE_SvcMsg(ClassInfo); // 10
HANDLE_SvcMsg(SetPause); // 11
HANDLE_SvcMsg(CreateStringTable); // 12
HANDLE_SvcMsg(UpdateStringTable); // 13
HANDLE_SvcMsg(VoiceInit); // 14
HANDLE_SvcMsg(VoiceData); // 15
HANDLE_SvcMsg(Print); // 16
HANDLE_SvcMsg(Sounds); // 17
HANDLE_SvcMsg(SetView); // 18
HANDLE_SvcMsg(FixAngle); // 19
HANDLE_SvcMsg(CrosshairAngle); // 20
HANDLE_SvcMsg(BSPDecal); // 21
HANDLE_SvcMsg(UserMessage); // 23
HANDLE_SvcMsg(GameEvent); // 25
HANDLE_SvcMsg(PacketEntities); // 26
HANDLE_SvcMsg(TempEntities); // 27
HANDLE_SvcMsg(Prefetch); // 28
HANDLE_SvcMsg(Menu); // 29
HANDLE_SvcMsg(GameEventList); // 30
HANDLE_SvcMsg(GetCvarValue); // 31
#undef HANDLE_SvcMsg
#undef HANDLE_NetMsg
}
buf.SeekRelative(Size * 8);
}
}
void CDemoFileDump::HandleDemoPacket()
{
democmdinfo_t info;
int dummy;
char data[NET_MAX_PAYLOAD];
m_demofile.ReadCmdInfo(info);
m_demofile.ReadSequenceInfo(dummy, dummy);
CBitRead buf(data, NET_MAX_PAYLOAD);
int length = m_demofile.ReadRawData((char*)buf.GetBasePointer(), buf.GetNumBytesLeft());
buf.Seek(0);
DumpDemoPacket(buf, length);
}
bool ReadFromBuffer(CBitRead& buffer, void** pBuffer, int& size)
{
size = buffer.ReadVarInt32();
if (size < 0 || size > NET_MAX_PAYLOAD) {
return false;
}
// Check its valid
if (size > buffer.GetNumBytesLeft()) {
return false;
}
*pBuffer = malloc(size);
// If the read buffer is byte aligned, we can parse right out of it
if ((buffer.GetNumBitsRead() % 8) == 0) {
memcpy(*pBuffer, buffer.GetBasePointer() + buffer.GetNumBytesRead(), size);
buffer.SeekRelative(size * 8);
return true;
}
// otherwise we have to ReadBytes() it out
if (!buffer.ReadBytes(*pBuffer, size)) {
return false;
}
return true;
}
bool ParseDataTable(CBitRead& buf)
{
CSVCMsg_SendTable msg;
while (1) {
int type = buf.ReadVarInt32();
void* pBuffer = NULL;
int size = 0;
if (!ReadFromBuffer(buf, &pBuffer, size)) {
printf("ParseDataTable: ReadFromBuffer failed.\n");
return false;
}
msg.ParseFromArray(pBuffer, size);
free(pBuffer);
if (msg.is_end())
break;
RecvTable_ReadInfos(msg);
s_DataTables.push_back(msg);
}
short nServerClasses = buf.ReadShort();
assert(nServerClasses);
for (int i = 0; i < nServerClasses; i++) {
ServerClass_t entry;
entry.nClassID = buf.ReadShort();
if (entry.nClassID >= nServerClasses) {
printf("ParseDataTable: invalid class index (%d).\n", entry.nClassID);
return false;
}
int nChars;
buf.ReadString(entry.strName, sizeof(entry.strName), false, &nChars);
buf.ReadString(entry.strDTName, sizeof(entry.strDTName), false, &nChars);
// find the data table by name
entry.nDataTable = -1;
for (unsigned int j = 0; j < s_DataTables.size(); j++) {
if (strcmp(entry.strDTName, s_DataTables[j].net_table_name().c_str()) == 0) {
entry.nDataTable = j;
break;
}
}
if (g_bDumpDataTables) {
printf("class:%d:%s:%s(%d)\n", entry.nClassID, entry.strName, entry.strDTName, entry.nDataTable);
}
s_ServerClasses.push_back(entry);
}
if (g_bDumpDataTables) {
printf("Flattening data tables...");
}
for (int i = 0; i < nServerClasses; i++) {
FlattenDataTable(i);
}
if (g_bDumpDataTables) {
printf("Done.\n");
}
// perform integer log2() to set s_nServerClassBits
int nTemp = nServerClasses;
s_nServerClassBits = 0;
while (nTemp >>= 1)
++s_nServerClassBits;
s_nServerClassBits++;
return true;
}
bool DumpStringTable(CBitRead& buf, bool bIsUserInfo)
{
int numstrings = buf.ReadWord();
if (g_bDumpStringTables) {
printf("%d\n", numstrings);
}
if (bIsUserInfo) {
if (g_bDumpStringTables) {
printf("Clearing player info array.\n");
}
s_PlayerInfos.clear();
}
for (int i = 0; i < numstrings; i++) {
char stringname[4096];
buf.ReadString(stringname, sizeof(stringname));
assert(strlen(stringname) < 100);
if (buf.ReadOneBit() == 1) {
int userDataSize = (int)buf.ReadWord();
assert(userDataSize > 0);
unsigned char* data = new unsigned char[userDataSize + 4];
assert(data);
buf.ReadBytes(data, userDataSize);
if (bIsUserInfo && data != NULL) {
const player_info_t* pUnswappedPlayerInfo = (const player_info_t*)data;
player_info_t playerInfo = *pUnswappedPlayerInfo;
playerInfo.entityID = i;
LowLevelByteSwap(&playerInfo.xuid, &pUnswappedPlayerInfo->xuid);
LowLevelByteSwap(&playerInfo.userID, &pUnswappedPlayerInfo->userID);
LowLevelByteSwap(&playerInfo.friendsID, &pUnswappedPlayerInfo->friendsID);
//shouldn't ever exist, but just incase
auto existing = FindPlayerByEntity(i);
if (!existing) {
if (g_bDumpStringTables) {
printf("adding:player entity:%d info:\n xuid:%lld\n name:%s\n userID:%d\n guid:%s\n friendsID:%d\n friendsName:%s\n fakeplayer:%d\n ishltv:%d\n filesDownloaded:%d\n",
i, playerInfo.xuid, playerInfo.name, playerInfo.userID, playerInfo.guid, playerInfo.friendsID,
playerInfo.friendsName, playerInfo.fakeplayer, playerInfo.ishltv, playerInfo.filesDownloaded);
}
s_PlayerInfos.push_back(playerInfo);
} else {
*existing = playerInfo;
}
} else {
if (g_bDumpStringTables) {
printf(" %d, %s, userdata[%d] \n", i, stringname, userDataSize);
}
}
delete[] data;
assert(buf.GetNumBytesLeft() > 10);
} else {
if (g_bDumpStringTables) {
printf(" %d, %s \n", i, stringname);
}
}
}
// Client side stuff
if (buf.ReadOneBit() == 1) {
int numstrings = buf.ReadWord();
for (int i = 0; i < numstrings; i++) {
char stringname[4096];
buf.ReadString(stringname, sizeof(stringname));
if (buf.ReadOneBit() == 1) {
int userDataSize = (int)buf.ReadWord();
assert(userDataSize > 0);
unsigned char* data = new unsigned char[userDataSize + 4];
assert(data);
buf.ReadBytes(data, userDataSize);
if (i >= 2) {
if (g_bDumpStringTables) {
printf(" %d, %s, userdata[%d] \n", i, stringname, userDataSize);
}
}
delete[] data;
} else {
if (i >= 2) {
if (g_bDumpStringTables) {
printf(" %d, %s \n", i, stringname);
}
}
}
}
}
return true;
}
bool DumpStringTables(CBitRead& buf)
{
int numTables = buf.ReadByte();
for (int i = 0; i < numTables; i++) {
char tablename[256];
buf.ReadString(tablename, sizeof(tablename));
if (g_bDumpStringTables) {
printf("ReadStringTable:%s:", tablename);
}
bool bIsUserInfo = !strcmp(tablename, "userinfo");
if (!DumpStringTable(buf, bIsUserInfo)) {
printf("Error reading string table %s\n", tablename);
}
}
return true;
}
void CDemoFileDump::DoDump()
{
s_bMatchStartOccured = false;
bool demofinished = false;
while (!demofinished) {
int tick = 0;
unsigned char cmd;
unsigned char playerSlot;
m_demofile.ReadCmdHeader(cmd, tick, playerSlot);
s_nCurrentTick = tick;
// COMMAND HANDLERS
switch (cmd) {
case dem_synctick:
break;
case dem_stop: {
demofinished = true;
} break;
case dem_consolecmd: {
m_demofile.ReadRawData(NULL, 0);
} break;
case dem_datatables: {
char* data = (char*)malloc(DEMO_RECORD_BUFFER_SIZE);
CBitRead buf(data, DEMO_RECORD_BUFFER_SIZE);
m_demofile.ReadRawData((char*)buf.GetBasePointer(), buf.GetNumBytesLeft());
buf.Seek(0);
if (!ParseDataTable(buf)) {
printf("Error parsing data tables. \n");
}
free(data);
} break;
case dem_stringtables: {
char* data = (char*)malloc(DEMO_RECORD_BUFFER_SIZE);
CBitRead buf(data, DEMO_RECORD_BUFFER_SIZE);
m_demofile.ReadRawData((char*)buf.GetBasePointer(), buf.GetNumBytesLeft());
buf.Seek(0);
if (!DumpStringTables(buf)) {
printf("Error parsing string tables. \n");
}
free(data);
} break;
case dem_usercmd: {
int dummy;
m_demofile.ReadUserCmd(NULL, dummy);
} break;
case dem_signon:
case dem_packet: {
HandleDemoPacket();
} break;
default:
break;
}
if (_kbhit()) {
int ch = toupper(_getch());
if (ch == 'Q')
break;
}
}
}
| 30.432465 | 231 | 0.665313 | [
"vector"
] |
6a9d50cb30e20f1d3c230b793def9f32dc879305 | 837 | cpp | C++ | CPlusPlus-Class/ListePhrase/ListePhrase.cpp | ValentinIannantuoni/SAE921-GRP4100-CPlusPlus-Class-VIannantuoni | 019505cd24dd4d8cd7084db4a2084243d90d12e6 | [
"MIT"
] | null | null | null | CPlusPlus-Class/ListePhrase/ListePhrase.cpp | ValentinIannantuoni/SAE921-GRP4100-CPlusPlus-Class-VIannantuoni | 019505cd24dd4d8cd7084db4a2084243d90d12e6 | [
"MIT"
] | null | null | null | CPlusPlus-Class/ListePhrase/ListePhrase.cpp | ValentinIannantuoni/SAE921-GRP4100-CPlusPlus-Class-VIannantuoni | 019505cd24dd4d8cd7084db4a2084243d90d12e6 | [
"MIT"
] | null | null | null | #include<iostream>
#include <vector>
#include <list>
#include <string>
std::list<std::string> getMots(std::string sentence_, char separator_)
{
std::list<std::string> mots;
int leftPosition = 0;
int rigthposition = 0;
if (!sentence_.empty())
{
do
{
rigthposition = sentence_.find(separator_, leftPosition);
if (rigthposition != -1)
{
std::string onemots = sentence_.substr(leftPosition, rigthposition - leftPosition);
mots.push_back(oneMots);
leftPosition = rigthposition + 1;
}
} while (rigthposition != +1);
}
return mots;
}
void displayWords(std::list<std::string>) mots)
{
std::cout << "les motd son :" << std::endl;
for(auto w : mots)
}
int main()
{
std::string pharse = "Sometimes ideas are like good wine in that they just need time";
std::list<std::string> mots =
} | 15.5 | 87 | 0.657109 | [
"vector"
] |
6aa308d3c440e4e8b44aa4086be0d7f6cbe78b0e | 5,076 | hpp | C++ | include/fdc2ypos_heabang.hpp | serjinio/thesis_ana | 633a61dee56cf2cf4dcb67997ac87338537fb578 | [
"MIT"
] | null | null | null | include/fdc2ypos_heabang.hpp | serjinio/thesis_ana | 633a61dee56cf2cf4dcb67997ac87338537fb578 | [
"MIT"
] | null | null | null | include/fdc2ypos_heabang.hpp | serjinio/thesis_ana | 633a61dee56cf2cf4dcb67997ac87338537fb578 | [
"MIT"
] | null | null | null |
#include "consts.hpp"
#include "commonalg.hpp"
#include "drawing.hpp"
#include "scattyield.hpp"
#include "elacuts.hpp"
namespace s13 {
namespace ana {
class Fdc2YposHeAbangAlg : public SimpleTTreeAlgorithmBase {
using ElaCuts = s13::ana::ElasticScatteringCuts;
using Evt = s13::ana::ScatteringEvent;
static double constexpr k_fdc2_heabang_rel_npoints = 10;
static double constexpr k_fdc2_heabang_rel_min_aang = -10;
static double constexpr k_fdc2_heabang_rel_max_aang = 10;
public:
Fdc2YposHeAbangAlg(ElaCuts cuts) :
logger_{"Fdc2YposHeAbangAlg"}, cuts_{cuts} {
init_hists();
}
// no copy or move
Fdc2YposHeAbangAlg(const Fdc2YposHeAbangAlg&) = delete;
Fdc2YposHeAbangAlg(Fdc2YposHeAbangAlg&&) = delete;
Fdc2YposHeAbangAlg operator=(const Fdc2YposHeAbangAlg&) = delete;
Fdc2YposHeAbangAlg operator=(const Fdc2YposHeAbangAlg&&) = delete;
virtual void setup() {
for (auto el : ypos_hebang_hists_) {
el->Reset();
}
}
virtual void process_event(Evt& evt) {
if (cuts_.IsSignalEvent(evt)) {
ypos_heabang_relation_process_event(evt);
}
}
virtual void finalize() {
}
virtual void merge(const TTreeAlgorithmBase& other) {
auto* other_alg = static_cast<const Fdc2YposHeAbangAlg*>(&other);
assert(other_alg->ypos_hebang_hists_.size()
== ypos_hebang_hists_.size());
for (size_t i = 0; i < ypos_hebang_hists_.size(); i++) {
ypos_hebang_hists_.at(i)->Add(other_alg->ypos_hebang_hists_.at(i));
}
}
virtual Fdc2YposHeAbangAlg* clone() const {
Fdc2YposHeAbangAlg* my_clone = new Fdc2YposHeAbangAlg(cuts_);
my_clone->merge(*this);
return my_clone;
}
virtual void serialize(std::ostream& os) {
throw std::logic_error("Not implemented");
}
virtual void deserialize(std::istream& is) {
throw std::logic_error("Not implemented");
}
std::vector<TH2*>& ypos_heabang_hists() {
return ypos_hebang_hists_;
}
/*
Returns center angle of ypos_heabang histogram by its index.
*/
double ypos_heabang_hist_aang(size_t idx) {
assert(idx >= 0 && idx < ypos_hebang_hists_.size());
double bin_width = (k_fdc2_heabang_rel_max_aang - k_fdc2_heabang_rel_min_aang)
/ k_fdc2_heabang_rel_npoints;
return idx * bin_width + k_fdc2_heabang_rel_min_aang + bin_width/2;
}
void fit_ypos_heabang_hists(TString fit_fn) {
for (auto el : ypos_hebang_hists_) {
el->Fit(fit_fn);
}
}
private:
void init_hists() {
double bin_width = (k_fdc2_heabang_rel_max_aang - k_fdc2_heabang_rel_min_aang)
/ k_fdc2_heabang_rel_npoints;
for (double bin_mid_point = k_fdc2_heabang_rel_min_aang + bin_width/2;
bin_mid_point < k_fdc2_heabang_rel_max_aang;
bin_mid_point += bin_width) {
auto hist_title =
s13::ana::tstrfmt("S1DC_bang vs. FDC2_y (%.1f<S1DC_aang<%.1f)",
bin_mid_point - bin_width/2, bin_mid_point + bin_width/2);
logger_.debug("init_hists(): Initializing histogram: %s", hist_title.Data());
auto hist = s13::ana::make_th2(100, -6, 6, 100, -600, 600,
hist_title,
"S1DC_bang [deg]",
"FDC2 Y [mm]");
ypos_hebang_hists_.push_back(hist);
}
}
int fdc2ypos_heabang_hist_idx(double he_aang_rad) {
double bin_width = (k_fdc2_heabang_rel_max_aang - k_fdc2_heabang_rel_min_aang)
/ k_fdc2_heabang_rel_npoints;
// convert mrads into degrees
double aang_deg = he_aang_rad / gk_d2r;
if (aang_deg > k_fdc2_heabang_rel_min_aang
&& aang_deg < k_fdc2_heabang_rel_max_aang) { // in aang range
size_t hist_idx = (aang_deg - k_fdc2_heabang_rel_min_aang) / bin_width;
assert(hist_idx < ypos_hebang_hists_.size());
return hist_idx;
} else { // not in range
return -1;
}
}
void ypos_heabang_relation_process_event(Evt& evt) {
// only accept events with good FDC2 data
if (evt.fdc2_ypos < -9000) {
return;
}
// limit he bang to the range of interest
double abs_bang_deg = std::abs(evt.s1dc_bang) / gk_d2r;
if (abs_bang_deg > 6) {
return;
}
int hist_idx = fdc2ypos_heabang_hist_idx(evt.s1dc_aang);
if (hist_idx != -1) {
double bang_deg = evt.s1dc_bang / gk_d2r;
ypos_hebang_hists_.at(hist_idx)->Fill(bang_deg, evt.fdc2_ypos);
}
}
misc::MessageLogger logger_;
ElaCuts cuts_;
std::vector<TH2*> ypos_hebang_hists_;
};
std::shared_ptr<Fdc2YposHeAbangAlg>
make_fdc2_heabang_alg(ElasticScatteringCuts& cuts);
}
}
| 32.126582 | 88 | 0.613081 | [
"vector"
] |
6aa412002f3687dacff582c671777977244c82b3 | 11,574 | cpp | C++ | src/field3D_Tools.cpp | gatgui/Field3DMaya | c2b5fe21970b93bea73e5a1da1d3bb39d446b7f7 | [
"BSD-3-Clause"
] | null | null | null | src/field3D_Tools.cpp | gatgui/Field3DMaya | c2b5fe21970b93bea73e5a1da1d3bb39d446b7f7 | [
"BSD-3-Clause"
] | null | null | null | src/field3D_Tools.cpp | gatgui/Field3DMaya | c2b5fe21970b93bea73e5a1da1d3bb39d446b7f7 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2011 Prime Focus Film.
//
// 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 Prime Focus Film nor the
// names of its contributors may be used to endorse or promote
// products derived from this software without specific prior written
// permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.
#include "field3D_Tools.h"
using namespace Field3D ;
using namespace std ;
namespace Field3DTools {
void getFieldNames( Field3DInputFile *file, const std::string &partition, vector< string > &names)
{
// get all partition names ( should be only one present,
// since maya fluids are stored individualy) but we parse
// everyone here for the sake of genericity
names.clear();
std::vector<std::string> partitionNames;
if (partition.length() == 0)
{
file->getPartitionNames(partitionNames);
}
else
{
partitionNames.push_back(partition);
}
// loop through partition and harvest attributes names
for (std::vector<std::string>::iterator it = partitionNames.begin() ; it!= partitionNames.end() ; ++it)
{
std::vector<std::string> scalarNames;
file->getScalarLayerNames(scalarNames, *it);
std::vector<std::string> vectorNames;
file->getVectorLayerNames(vectorNames, *it);
// add it to the main names
std::copy(scalarNames.begin(), scalarNames.end(), std::back_inserter(names));
std::copy(vectorNames.begin(), vectorNames.end(), std::back_inserter(names));
}
}
void getFieldNames( Field3DInputFile *file, vector< string > &names)
{
getFieldNames( file, "", names );
}
bool getFieldsResolution(Field3D::Field3DInputFile *inFile, const std::string &partition, const std::string &name, unsigned int (&resolution)[3])
{
bool found = false;
resolution[0] = resolution[1] = resolution[2] = 0;
// take the highest resolution of all layers
// Note: don't need to check for half/float/double, readProxyLayer actually ignores the base type
// loop through scalars fields
Field3D::EmptyField<Field3D::half>::Vec scalarfields = readProxyScalarLayers<Field3D::half>(inFile, partition, name);
Field3D::EmptyField<Field3D::half>::Vec::const_iterator its = scalarfields.begin();
for (; its != scalarfields.end(); ++its)
{
resolution[0] = ( (unsigned int) (*its)->dataResolution().x > resolution[0]) ? (*its)->dataResolution().x : resolution[0];
resolution[1] = ( (unsigned int) (*its)->dataResolution().y > resolution[1]) ? (*its)->dataResolution().y : resolution[1];
resolution[2] = ( (unsigned int) (*its)->dataResolution().z > resolution[2]) ? (*its)->dataResolution().z : resolution[2];
found = true || found;
}
// loop through vector fields
Field3D::EmptyField<FIELD3D_VEC3_T<Field3D::half> >::Vec vectorfields = readProxyVectorLayers<Field3D::half>(inFile, partition, name);
Field3D::EmptyField<FIELD3D_VEC3_T<Field3D::half> >::Vec::const_iterator itv = vectorfields.begin();
for (; itv != vectorfields.end(); ++itv)
{
resolution[0] = ( (unsigned int) (*itv)->dataResolution().x > resolution[0]) ? (*itv)->dataResolution().x : resolution[0];
resolution[1] = ( (unsigned int) (*itv)->dataResolution().y > resolution[1]) ? (*itv)->dataResolution().y : resolution[1];
resolution[2] = ( (unsigned int) (*itv)->dataResolution().z > resolution[2]) ? (*itv)->dataResolution().z : resolution[2];
found = true || found;
}
return found;
}
bool getFieldsResolution(Field3D::Field3DInputFile *inFile, const std::string &name, unsigned int (&resolution)[3])
{
return getFieldsResolution(inFile, "", name, resolution);
}
bool getFieldsResolution(Field3D::Field3DInputFile *inFile, unsigned int (&resolution)[3])
{
return getFieldsResolution(inFile, "", "", resolution);
}
bool getFieldValueType( Field3DInputFile *inFile , const std::string &partition, const std::string &name, Fld &fld)
{
typedef Field3D::half half;
Field<half>::Vec hsres = readScalarLayers<half>(inFile, partition, name);
if (!hsres.empty())
{
Field3D::DenseField<half>::Ptr fieldD = Field3D::field_dynamic_cast<Field3D::DenseField<half> >(hsres[0]);
if (fieldD)
{
fld.fieldType = DenseScalarField_Half;
fld.baseField = fieldD;
fld.dhScalarField = fieldD;
return true;
}
Field3D::SparseField<half>::Ptr fieldS = Field3D::field_dynamic_cast<Field3D::SparseField<half> >(hsres[0]);
if (fieldS)
{
fld.fieldType = SparseScalarField_Half;
fld.baseField = fieldS;
fld.shScalarField = fieldS;
return true;
}
// error
ERROR( "Type of half scalar field " + name + " unknown : not a dense field nor a sparse field nor a MAC field");
fld.fieldType = TypeUnsupported;
return false;
}
Field<float>::Vec fsres = readScalarLayers<float>(inFile, partition, name);
if (!fsres.empty())
{
Field3D::DenseField<float>::Ptr fieldD = Field3D::field_dynamic_cast<Field3D::DenseField<float> >(fsres[0]);
if (fieldD)
{
fld.fieldType = DenseScalarField_Float;
fld.baseField = fieldD;
fld.dfScalarField = fieldD;
return true;
}
Field3D::SparseField<float>::Ptr fieldS = Field3D::field_dynamic_cast<Field3D::SparseField<float> >(fsres[0]);
if (fieldS)
{
fld.fieldType = SparseScalarField_Float;
fld.baseField = fieldS;
fld.sfScalarField = fieldS;
return true;
}
// error
ERROR( "Type of float scalar field " + name + " unknown : not a dense field nor a sparse field nor a MAC field");
fld.fieldType = TypeUnsupported;
return false;
}
Field<double>::Vec dsres = readScalarLayers<double>(inFile, partition, name);
if (!dsres.empty())
{
Field3D::DenseField<double>::Ptr fieldD = Field3D::field_dynamic_cast<Field3D::DenseField<double> >(dsres[0]);
if (fieldD)
{
fld.fieldType = DenseScalarField_Double;
fld.baseField = fieldD;
fld.ddScalarField = fieldD;
return true;
}
Field3D::SparseField<double>::Ptr fieldS = Field3D::field_dynamic_cast<Field3D::SparseField<double> >(dsres[0]);
if (fieldS)
{
fld.fieldType = SparseScalarField_Double;
fld.baseField = fieldS;
fld.sdScalarField = fieldS;
return true;
}
// error
ERROR( "Type of float scalar field " + name + " unknown : not a dense field nor a sparse field nor a MAC field");
fld.fieldType = TypeUnsupported;
return false;
}
Field<FIELD3D_VEC3_T<half> >::Vec hvres = readVectorLayers<half>(inFile, partition, name);
if (!hvres.empty())
{
Field3D::DenseField<Field3D::V3h>::Ptr fieldD = Field3D::field_dynamic_cast<Field3D::DenseField<Field3D::V3h> >(hvres[0]);
if (fieldD)
{
fld.fieldType = DenseVectorField_Half;
fld.baseField = fieldD;
fld.dhVectorField = fieldD;
return true;
}
Field3D::SparseField<Field3D::V3h>::Ptr fieldS = Field3D::field_dynamic_cast<Field3D::SparseField<Field3D::V3h> >(hvres[0]);
if (fieldS)
{
fld.fieldType = SparseVectorField_Half;
fld.baseField = fieldS;
fld.shVectorField = fieldS;
return true;
}
Field3D::MACField<Field3D::V3h>::Ptr fieldM = Field3D::field_dynamic_cast<Field3D::MACField<Field3D::V3h> >(hvres[0]);
if (fieldM)
{
fld.fieldType = MACField_Half;
fld.baseField = fieldM;
fld.mhField = fieldM;
return true;
}
// error
ERROR( "Type of half vector field " + name + " unknown : not a dense field nor a sparse field nor a MAC Field");
fld.fieldType = TypeUnsupported;
return false;
}
Field<FIELD3D_VEC3_T<float> >::Vec fvres = readVectorLayers<float>(inFile, partition, name);
if (!fvres.empty())
{
Field3D::DenseField<Field3D::V3f>::Ptr fieldD = Field3D::field_dynamic_cast<Field3D::DenseField<Field3D::V3f> >(fvres[0]);
if (fieldD)
{
fld.fieldType = DenseVectorField_Float;
fld.baseField = fieldD;
fld.dfVectorField = fieldD;
return true;
}
Field3D::SparseField<Field3D::V3f>::Ptr fieldS = Field3D::field_dynamic_cast<Field3D::SparseField<Field3D::V3f> >(fvres[0]);
if (fieldS)
{
fld.fieldType = SparseVectorField_Float;
fld.baseField = fieldS;
fld.sfVectorField = fieldS;
return true;
}
Field3D::MACField<Field3D::V3f>::Ptr fieldM = Field3D::field_dynamic_cast<Field3D::MACField<Field3D::V3f> >(fvres[0]);
if (fieldM)
{
fld.fieldType = MACField_Float;
fld.baseField = fieldM;
fld.mfField = fieldM;
return true;
}
// error
ERROR( "Type of float vector field " + name + " unknown : not a dense field nor a sparse field nor a MAC Field");
fld.fieldType = TypeUnsupported;
return false;
}
Field<FIELD3D_VEC3_T<double> >::Vec dvres = readVectorLayers<double>(inFile, partition, name);
if (!dvres.empty())
{
Field3D::DenseField<Field3D::V3d>::Ptr fieldD = Field3D::field_dynamic_cast< Field3D::DenseField<Field3D::V3d> >(dvres[0]);
if (fieldD)
{
fld.fieldType = DenseVectorField_Double;
fld.baseField = fieldD;
fld.ddVectorField = fieldD;
return true;
}
Field3D::SparseField<Field3D::V3d>::Ptr fieldS = Field3D::field_dynamic_cast< Field3D::SparseField<Field3D::V3d> >(dvres[0]);
if (fieldS)
{
fld.fieldType = SparseVectorField_Double;
fld.baseField = fieldS;
fld.sdVectorField = fieldS;
return true;
}
Field3D::MACField<Field3D::V3d>::Ptr fieldM = Field3D::field_dynamic_cast< Field3D::MACField<Field3D::V3d> >(dvres[0]);
if (fieldM)
{
fld.fieldType = MACField_Double;
fld.baseField = fieldM;
fld.mdField = fieldM;
return true;
}
// error
ERROR( "Type of float vector field " + name + " unknown : not a dense field nor a sparse field nor a MAC Field");
fld.fieldType = TypeUnsupported;
return false;
}
// error
ERROR( std::string("Type of data in field ") + name + " unknown : not a float field nor a half float field");
fld.fieldType = TypeUnsupported;
return false;
}
bool getFieldValueType( Field3DInputFile *inFile , const std::string &name , Fld &fld )
{
return getFieldValueType( inFile, "", name, fld );
}
}
| 33.068571 | 145 | 0.672024 | [
"vector"
] |
6aa6162e026c9d9a95e693db56d532387f60fe9e | 833 | cpp | C++ | LeetCode/186.cpp | sptuan/PAT-Practice | 68e1ca329190264fdeeef1a2a1d4c2a56caa27f6 | [
"MIT"
] | null | null | null | LeetCode/186.cpp | sptuan/PAT-Practice | 68e1ca329190264fdeeef1a2a1d4c2a56caa27f6 | [
"MIT"
] | null | null | null | LeetCode/186.cpp | sptuan/PAT-Practice | 68e1ca329190264fdeeef1a2a1d4c2a56caa27f6 | [
"MIT"
] | null | null | null | class Solution {
public:
void reverseWords(vector<char>& s) {
stack<string> st;
string temp;
for(int i=0; i<s.size(); i++){
if(s[i]==' '){
if(temp.size()!=0){
st.push(temp);
temp.clear();
}
}
else{
temp.push_back(s[i]);
}
}
if(temp.size()!=0){
st.push(temp);
temp.clear();
}
vector<char> ans;
int counter = st.size();
for(int i=0; i<counter; i++){
auto temp_top = st.top();
st.pop();
for(auto &it:temp_top){
ans.push_back(it);
}
if(i!=counter-1)
ans.push_back(' ');
}
s = ans;
}
};
| 21.921053 | 40 | 0.351741 | [
"vector"
] |
6aa6cf73012427e18f278f652530480a12113110 | 9,677 | cpp | C++ | OpenSim/Simulation/Model/PathSpring.cpp | MaartenAfschrift/OpenSim_SourceAD | e063021c44e15744cfc5438b5fe5250d02018098 | [
"Apache-2.0"
] | 2 | 2020-10-30T09:08:44.000Z | 2020-12-08T07:15:54.000Z | OpenSim/Simulation/Model/PathSpring.cpp | MaartenAfschrift/OpenSim_SourceAD | e063021c44e15744cfc5438b5fe5250d02018098 | [
"Apache-2.0"
] | null | null | null | OpenSim/Simulation/Model/PathSpring.cpp | MaartenAfschrift/OpenSim_SourceAD | e063021c44e15744cfc5438b5fe5250d02018098 | [
"Apache-2.0"
] | null | null | null | ///* -------------------------------------------------------------------------- *
// * OpenSim: PathSpring.cpp *
// * -------------------------------------------------------------------------- *
// * The OpenSim API is a toolkit for musculoskeletal modeling and simulation. *
// * See http://opensim.stanford.edu and the NOTICE file for more information. *
// * OpenSim is developed at Stanford University and supported by the US *
// * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA *
// * through the Warrior Web program. *
// * *
// * Copyright (c) 2005-2017 Stanford University and the Authors *
// * Author(s): Ajay Seth *
// * *
// * 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. *
// * -------------------------------------------------------------------------- */
//
////=============================================================================
//// INCLUDES
////=============================================================================
//#include "PathSpring.h"
//#include "GeometryPath.h"
//#include "PointForceDirection.h"
//
////=============================================================================
//// STATICS
////=============================================================================
//using namespace std;
//using namespace OpenSim;
//using SimTK::Vec3;
//
//static const Vec3 DefaultPathSpringColor(0, 1, 0); // Green for backward compatibility
//
////=============================================================================
//// CONSTRUCTOR(S) AND DESTRUCTOR
////=============================================================================
////_____________________________________________________________________________
//// Default constructor.
//PathSpring::PathSpring()
//{
// constructProperties();
//}
//
//PathSpring::PathSpring(const string& name, double restLength,
// double stiffness, double dissipation)
//{
// constructProperties();
// setName(name);
// set_resting_length(restLength);
// set_stiffness(stiffness);
// set_dissipation(dissipation);
//}
//
////_____________________________________________________________________________
///*
// * Construct and initialize the properties for the PathSpring.
// */
//void PathSpring::constructProperties()
//{
// setAuthors("Ajay Seth");
// constructProperty_GeometryPath(GeometryPath());
// constructProperty_resting_length(SimTK::NaN);
// constructProperty_stiffness(SimTK::NaN);
// constructProperty_dissipation(SimTK::NaN);
//}
//
////_____________________________________________________________________________
///*
// * Set the resting length.
// */
//void PathSpring::setRestingLength(double restingLength)
//{
// set_resting_length(restingLength);
//}
////_____________________________________________________________________________
///*
// * Set the stiffness.
// */
//void PathSpring::setStiffness(double stiffness)
//{
// set_stiffness(stiffness);
//}
////_____________________________________________________________________________
///*
// * Set the dissipation.
// */
//void PathSpring::setDissipation(double dissipation)
//{
// set_dissipation(dissipation);
//}
//
////_____________________________________________________________________________
///**
// * Perform some setup functions that happen after the
// * PathSpring has been deserialized or copied.
// *
// * @param aModel model containing this PathSpring.
// */
//void PathSpring::extendFinalizeFromProperties()
//{
// Super::extendFinalizeFromProperties();
//
// GeometryPath& path = upd_GeometryPath();
// path.setDefaultColor(DefaultPathSpringColor);
//
// OPENSIM_THROW_IF_FRMOBJ(
// (SimTK::isNaN(get_resting_length()) || get_resting_length() < 0),
// InvalidPropertyValue, getProperty_resting_length().getName());
// OPENSIM_THROW_IF_FRMOBJ(
// (SimTK::isNaN(get_stiffness()) || get_stiffness() < 0),
// InvalidPropertyValue, getProperty_stiffness().getName());
// OPENSIM_THROW_IF_FRMOBJ(
// (SimTK::isNaN(get_dissipation()) || get_dissipation() < 0),
// InvalidPropertyValue, getProperty_dissipation().getName());
//}
//
//
////=============================================================================
//// GET AND SET
////=============================================================================
////-----------------------------------------------------------------------------
//// LENGTH and SPEED
////-----------------------------------------------------------------------------
////_____________________________________________________________________________
///**
// * Get the length of the PathSpring. This is a convenience function that passes
// * the request on to the PathSpring path.
// *
// * @return Current length of the PathSpring path.
// */
//double PathSpring::getLength(const SimTK::State& s) const
//{
// return getGeometryPath().getLength(s);
//}
//
//double PathSpring::getStretch(const SimTK::State& s) const
//{
// const double& length = getLength(s);
// const double& restingLength = get_resting_length();
// return length > restingLength ? (length-restingLength) : 0.0;
//}
//
//
//double PathSpring::getLengtheningSpeed(const SimTK::State& s) const
//{
// return getGeometryPath().getLengtheningSpeed(s);
//}
//
//double PathSpring::getTension(const SimTK::State& s) const
//{
// // evaluate tension in the spring
// // note tension is positive and produces shortening
// // damping opposes lengthening, which is positive lengthening speed
// // there for stretch and lengthening speed increase tension
// return getStiffness()*getStretch(s) * //elastic force
// (1+getDissipation()*getLengtheningSpeed(s)); //dissipation
//}
//
//
////=============================================================================
//// SCALING
////=============================================================================
////_____________________________________________________________________________
///**
// * Perform computations that need to happen before the PathSpring is scaled.
// * For this object, that entails calculating and storing the
// * length in the current body position.
// *
// * @param aScaleSet XYZ scale factors for the bodies.
// */
//void PathSpring::preScale(const SimTK::State& s, const ScaleSet& aScaleSet)
//{
// updGeometryPath().preScale(s, aScaleSet);
//}
//
////_____________________________________________________________________________
//
//void PathSpring::scale(const SimTK::State& s, const ScaleSet& aScaleSet)
//{
// updGeometryPath().scale(s, aScaleSet);
//}
//
////_____________________________________________________________________________
///**
// * Perform computations that need to happen after the PathSpring is scaled.
// * For this object, that entails comparing the length before and after scaling,
// * and scaling the resting length a proportional amount.
// *
// * @param aScaleSet XYZ scale factors for the bodies.
// */
//void PathSpring::postScale(const SimTK::State& s, const ScaleSet& aScaleSet)
//{
// GeometryPath& path = updGeometryPath();
// path.postScale(s, aScaleSet);
//
// if (path.getPreScaleLength(s) > 0.0)
// {
// double scaleFactor = path.getLength(s) / path.getPreScaleLength(s);
// // Scale resting length by the same amount as the change in
// // total PathSpring length (in the current body position).
// upd_resting_length() *= scaleFactor;
//
// path.setPreScaleLength(s, 0.0);
// }
//}
//
//
////=============================================================================
//// COMPUTATION
////=============================================================================
///**
// * Compute the moment-arm of this muscle about a coordinate.
// */
//double PathSpring::computeMomentArm(const SimTK::State& s, Coordinate& aCoord) const
//{
// return getGeometryPath().computeMomentArm(s, aCoord);
//}
//
//
//
//void PathSpring::computeForce(const SimTK::State& s,
// SimTK::Vector_<SimTK::SpatialVec>& bodyForces,
// SimTK::Vector& generalizedForces) const
//{
// const GeometryPath& path = getGeometryPath();
// const double& tension = getTension(s);
//
// OpenSim::Array<PointForceDirection*> PFDs;
// path.getPointForceDirections(s, &PFDs);
//
// for (int i=0; i < PFDs.getSize(); i++) {
// applyForceToPoint(s, PFDs[i]->frame(), PFDs[i]->point(),
// tension*PFDs[i]->direction(), bodyForces);
// }
//
// for(int i=0; i < PFDs.getSize(); i++)
// delete PFDs[i];
//}
| 39.497959 | 88 | 0.556991 | [
"object",
"vector",
"model"
] |
6aaa5bf78da60974065811486d61e755fae47958 | 25,150 | cpp | C++ | hex/src/controllers/stages/DecompositionStage.cpp | KaiSut0/interactive-hex-meshing | 187c926610ca5617f569405c23ab5a62b189e100 | [
"MIT"
] | 129 | 2021-09-07T17:15:18.000Z | 2022-02-28T08:59:02.000Z | hex/src/controllers/stages/DecompositionStage.cpp | KaiSut0/interactive-hex-meshing | 187c926610ca5617f569405c23ab5a62b189e100 | [
"MIT"
] | 2 | 2021-10-03T07:30:20.000Z | 2022-01-06T16:05:41.000Z | hex/src/controllers/stages/DecompositionStage.cpp | KaiSut0/interactive-hex-meshing | 187c926610ca5617f569405c23ab5a62b189e100 | [
"MIT"
] | 11 | 2021-09-08T11:29:09.000Z | 2022-03-17T08:39:50.000Z | #include <GLFW/glfw3.h>
#include <imgui.h>
#include <vkoo/st/components/Tracing.h>
#include "DecompositionStage.h"
#include "controllers/GlobalController.h"
#include "logging.h"
#include "utility/ImGuiEx.h"
#include "vkoo/core/InputEvent.h"
namespace hex {
namespace {
const float kDuplicateOffset = 0.01f;
const float kEps = 1e-8f;
bool IsCuboidBoundsEmpty(const std::pair<Vector3f, Vector3f>& bounds) {
return !(bounds.first(0) + kEps < bounds.second(0) &&
bounds.first(1) + kEps < bounds.second(1) &&
bounds.first(2) + kEps < bounds.second(2));
}
} // namespace
DecompositionStage::DecompositionStage(GlobalController& global_controller)
: PipelineStage(global_controller, GlobalView::VisibilityDeformedMesh),
cuboid_editing_controller_{global_controller, false} {
polycube_optimizer_ =
std::make_unique<PolycubeOptimizer>(PolycubeOptimizer::Options());
}
void DecompositionStage::DrawStageWindow() {
if (!polycube_optimizer_->IsIdle()) {
return;
}
ImGui::SetNextWindowSize(ImVec2(400, 400), ImGuiCond_Once);
ImGui::Begin("Decomposition");
DrawAnchorsSdfChildWindow();
DrawPolycubeControlChildWindow();
ImGui::End();
if (cuboid_editing_controller_.GetState() !=
CuboidEditingController::State::Idle) {
CuboidEditingController::WindowState cuboid_state;
auto& polycube_info = global_controller_.GetGlobalState().GetPolycubeInfo();
cuboid_state.lock_cuboid = polycube_info.locked.at(focused_cuboid_index_);
cuboid_editing_controller_.DrawWindow(cuboid_state);
if (cuboid_state.lock_cuboid) {
// This means the button is pressed, so toggle.
polycube_info.ToggleLock(focused_cuboid_index_);
}
if (cuboid_state.delete_cuboid) {
assert(focused_cuboid_index_ != -1);
DeleteCuboid(focused_cuboid_index_);
} else if (cuboid_state.duplicate_cuboid) {
assert(focused_cuboid_index_ != -1);
DuplicateCuboid(focused_cuboid_index_);
}
} else if (subtract_editing_controller_) {
assert(subtract_editing_controller_->GetState() !=
CuboidEditingController::State::Idle);
CuboidEditingController::WindowState cuboid_state;
subtract_editing_controller_->DrawWindow(cuboid_state);
if (cuboid_state.subtract_cuboid) {
PerformSubtraction();
}
}
DrawPolycubeInfoWindow();
}
void DecompositionStage::DrawPolycubeInfoWindow() {
if (!global_controller_.GetGlobalState().HasPolycube() ||
global_controller_.GetGlobalState().GetPolycube().GetCuboidCount() == 0) {
return;
}
ImGui::SetNextWindowPos(ImVec2{100, 400}, ImGuiCond_Once);
ImGui::SetNextWindowSize(ImVec2{250, 240}, ImGuiCond_Once);
ImGui::Begin("Polycube Info");
auto& global_state = global_controller_.GetGlobalState();
auto& polycube_info = global_state.GetPolycubeInfo();
if (ImGui::Button("Up")) {
if (focused_cuboid_index_ != -1) {
polycube_info.MoveItem(focused_cuboid_index_, -1);
}
}
ImGui::SameLine();
if (ImGui::Button("Down")) {
if (focused_cuboid_index_ != -1) {
polycube_info.MoveItem(focused_cuboid_index_, 1);
}
}
ImGui::SameLine();
if (ImGui::Button("Lock/Unlock")) {
if (focused_cuboid_index_ != -1) {
polycube_info.ToggleLock(focused_cuboid_index_);
}
}
ImGui::SameLine();
ImGuiHelpMarker("Lock a cuboid to prevent it from being optimized.");
ImGui::BeginChild("CuboidList", ImVec2{0, 0}, true);
for (int i = 0; i < polycube_info.names.size(); i++) {
ImGui::PushID(i);
int j = polycube_info.ordering[i];
bool clicked = ImGui::SelectableInput(
"entry", j == focused_cuboid_index_, ImGuiSelectableFlags_None,
polycube_info.names[j].buf, IM_ARRAYSIZE(polycube_info.names[j].buf));
ImGui::SameLine(200);
ImGui::Text("%s", polycube_info.locked[j] ? "L" : " ");
if (clicked && j != focused_cuboid_index_) {
FocusCuboid(j);
}
ImGui::PopID();
}
ImGui::EndChild();
ImGui::End();
}
bool DecompositionStage::CanSwitchTo() {
auto& global_state = global_controller_.GetGlobalState();
if (!global_state.HasDeformedVolumeMesh()) {
LOGW(
"Deformed mesh is required for cuboid "
"decomposition stage!");
return false;
}
return true;
}
void DecompositionStage::SwitchTo() { PipelineStage::SwitchTo(); }
void DecompositionStage::Update([[maybe_unused]] float delta_time) {
if (polycube_optimizer_->GetStatus() == PolycubeOptimizer::Status::Running ||
polycube_optimizer_->GetStatus() ==
PolycubeOptimizer::Status::Completed) {
auto& global_state = global_controller_.GetGlobalState();
global_state.SetPolycube(
std::make_unique<Polycube>(polycube_optimizer_->GetSnapshot()));
auto& polycube_view = global_controller_.GetGlobalView().GetPolycubeView();
polycube_view.Update(global_state.GetPolycube(),
global_state.GetPolycubeInfo());
if (polycube_optimizer_->GetStatus() ==
PolycubeOptimizer::Status::Completed) {
polycube_optimizer_->SetIdle();
}
}
}
void DecompositionStage::Reoptimize(size_t num_steps) {
UnfocusCuboid();
auto& deformed_mesh =
global_controller_.GetGlobalState().GetDeformedVolumeMesh();
auto& global_state = global_controller_.GetGlobalState();
auto& polycube = global_state.GetPolycube();
auto& polycube_info = global_state.GetPolycubeInfo();
opt_thread_ = std::thread([&, num_steps]() {
polycube_optimizer_->Optimize(deformed_mesh, polycube, num_steps,
polycube_info.locked);
});
}
void DecompositionStage::SuggestNewCuboid(
PolycubeOptimizer::SuggestStrategy strategy) {
UnfocusCuboid();
auto& deformed_mesh =
global_controller_.GetGlobalState().GetDeformedVolumeMesh();
auto& polycube = global_controller_.GetGlobalState().GetPolycube();
Cuboid new_cuboid;
bool success = polycube_optimizer_->SuggestNewCuboid(deformed_mesh, polycube,
strategy, new_cuboid);
if (success) {
AddNewCuboid(new_cuboid);
} else {
LOGI("Failed to suggest a new cuboid!");
}
}
void DecompositionStage::AddNewCuboid(const Cuboid& cuboid) {
auto& global_state = global_controller_.GetGlobalState();
if (!global_state.HasPolycube()) {
LOGW("You must initialize the polycube first!");
return;
}
assert(global_state.CheckPolycubeConsistency());
auto& polycube = global_state.GetPolycube();
polycube.AddCuboid(cuboid);
auto& polycube_info = global_state.GetPolycubeInfo();
polycube_info.Push();
auto& polycube_view = global_controller_.GetGlobalView().GetPolycubeView();
polycube_view.AddCuboid(cuboid);
FocusCuboid(polycube.GetCuboidCount() - 1);
}
void DecompositionStage::DuplicateCuboid(int i) {
auto& global_state = global_controller_.GetGlobalState();
auto& polycube = global_state.GetPolycube();
Cuboid cuboid = polycube.GetCuboid(i);
// Add in slight offset.
cuboid.center += kDuplicateOffset * Vector3f::Ones();
AddNewCuboid(cuboid);
}
void DecompositionStage::DeleteCuboid(int i) {
if (i == focused_cuboid_index_) {
UnfocusCuboid();
}
auto& global_state = global_controller_.GetGlobalState();
auto& polycube = global_state.GetPolycube();
polycube.DeleteCuboid(i);
auto& polycube_info = global_state.GetPolycubeInfo();
polycube_info.Delete(i);
auto& polycube_view = global_controller_.GetGlobalView().GetPolycubeView();
polycube_view.DeleteCuboid(i);
}
void DecompositionStage::ResetPolycube() {
UnfocusCuboid();
global_controller_.GetGlobalState().SetPolycube(std::make_unique<Polycube>());
global_controller_.GetGlobalState().SetPolycubeInfo(
std::make_unique<PolycubeInfo>());
global_controller_.GetGlobalView().UpdatePolycubeView(
global_controller_.GetGlobalState());
global_controller_.GetGlobalView().SetVisibility(
GlobalView::VisibilityDeformedMesh | GlobalView::VisibilityDecomposition);
}
bool DecompositionStage::HandleInputEvent(const vkoo::InputEvent& event) {
if (!polycube_optimizer_->IsIdle()) {
return false;
}
bool handled = false;
if (cuboid_editing_controller_.GetState() !=
CuboidEditingController::State::Idle) {
handled = cuboid_editing_controller_.HandleInputEvent(event);
} else if (subtract_editing_controller_ != nullptr) {
handled = subtract_editing_controller_->HandleInputEvent(event);
} else {
if (event.GetSource() == vkoo::EventSource::Mouse) {
auto& mouse_event =
static_cast<const vkoo::MouseButtonInputEvent&>(event);
// Ray in world space.
vkoo::st::Ray world_ray =
global_controller_
.ShootRayAtMousePosition(mouse_event.GetXPos(),
mouse_event.GetYPos())
.ToGlm();
auto traceables = global_controller_.GetScene()
.GetRoot()
.GetComponentsRecursive<vkoo::st::Tracing>(true);
vkoo::st::HitRecord hit_record{};
vkoo::st::Tracing* hit_obj = nullptr;
for (auto traceable : traceables) {
vkoo::st::Ray local_ray = world_ray;
local_ray.ApplyTransform(
traceable->GetNode()->GetTransform().GetWorldToLocalMatrix());
if (traceable->GetHittable().Intersect(local_ray, hit_record)) {
hit_obj = traceable;
}
}
if (hit_obj != nullptr) {
auto& cuboid_nodes = global_controller_.GetGlobalView()
.GetPolycubeView()
.GetCuboidNodes();
// Check if hit object is a cuboid.
auto it = std::find(cuboid_nodes.begin(), cuboid_nodes.end(),
hit_obj->GetNode());
if (it != cuboid_nodes.end()) {
if (mouse_event.GetAction() == vkoo::MouseAction::Down &&
mouse_event.GetButton() == vkoo::MouseButton::Left) {
FocusCuboid(std::distance(cuboid_nodes.begin(), it));
handled = true;
}
} else {
// If anything other than a cuboid is hit, then treat as if not
// hit.
hit_obj = nullptr;
}
}
}
}
if (event.GetSource() == vkoo::EventSource::Keyboard) {
auto& key_event = static_cast<const vkoo::KeyInputEvent&>(event);
if (key_event.GetAction() == vkoo::KeyAction::Down) {
if (key_event.GetCode() == GLFW_KEY_ESCAPE) {
UnfocusCuboid();
} else if (key_event.GetCode() == GLFW_KEY_BACKSPACE) {
if (focused_cuboid_index_ != -1) {
DeleteCuboid(focused_cuboid_index_);
assert(cuboid_editing_controller_.GetState() ==
CuboidEditingController::State::Idle);
}
} else if (key_event.GetCode() == GLFW_KEY_L) {
if (focused_cuboid_index_ != -1) {
auto& polycube_info =
global_controller_.GetGlobalState().GetPolycubeInfo();
polycube_info.ToggleLock(focused_cuboid_index_);
}
}
}
}
return handled;
}
void DecompositionStage::FocusCuboid(int id) {
if (focused_cuboid_index_ != -1) {
UnfocusCuboid();
}
focused_cuboid_index_ = id;
auto& cuboid_node =
global_controller_.GetGlobalView().GetPolycubeView().GetCuboidNode(id);
cuboid_node.UpdateMode(CuboidNode::Mode::Focused);
cuboid_editing_controller_.Focus(
cuboid_node,
global_controller_.GetGlobalState().GetPolycube().GetCuboid(id));
global_controller_.GetGlobalView().AddVisibility(
GlobalView::VisibilityDecomposition);
}
void DecompositionStage::UnfocusCuboid() {
if (opt_thread_.joinable()) {
opt_thread_.join();
}
if (subtract_editing_controller_) {
subtract_editing_controller_.reset(); // destructor unfocuses automatically
// Note: deletion of tmp cuboid must happen before calling the destructor of
// subtract_editing_controller_!
global_controller_.GetGlobalView().GetPolycubeView().DeleteTmpCuboid();
}
if (focused_cuboid_index_ == -1) {
return;
}
cuboid_editing_controller_.Unfocus();
auto& cuboid_node =
global_controller_.GetGlobalView().GetPolycubeView().GetCuboidNode(
focused_cuboid_index_);
bool locked = global_controller_.GetGlobalState().GetPolycubeInfo().locked.at(
focused_cuboid_index_);
cuboid_node.UpdateMode(locked ? CuboidNode::Mode::Locked
: CuboidNode::Mode::Free);
focused_cuboid_index_ = -1;
}
DecompositionStage::~DecompositionStage() {
CuboidNode::Cleanup(); // TODO: fix this
if (opt_thread_.joinable()) {
polycube_optimizer_->Stop();
opt_thread_.join();
}
}
void DecompositionStage::SwitchFrom() {
PipelineStage::SwitchFrom();
if (opt_thread_.joinable()) {
polycube_optimizer_->Stop();
opt_thread_.join();
}
UnfocusCuboid();
}
void DecompositionStage::CreateSdfAndAnchors() {
LOGI("Creating anchors and sdf for the deformed mesh...");
auto& global_state = global_controller_.GetGlobalState();
if (!global_state.HasDeformedVolumeMesh()) {
LOGW("Cannot create anchors and sdfs without a deformed mesh!");
return;
}
// Note: order matters here; otherwise distance field will be built on a
// different set of anchors due to randomness!
global_state.GetDeformedVolumeMesh().CreateAnchors(
anchors_options_.grid_size, anchors_options_.inside_only,
anchors_options_.bbox_padding, anchors_options_.surface_samples,
anchors_options_.perturbation);
global_state.GetDeformedVolumeMesh().CreateDistanceField();
global_controller_.GetGlobalView().UpdateAnchorsView(global_state);
global_controller_.GetGlobalView().SetVisibility(
GlobalView::VisibilityDeformedMesh | GlobalView::VisibilityAnchors);
}
void DecompositionStage::DrawAnchorsSdfChildWindow() {
ImGuiTreeNodeWithTooltip(
"Anchors creation parameters", ImGuiTreeNodeFlags_None,
"Change how anchors are created. Anchors are the set of points that we "
"discretize the signed distance field on with respect to a shape (input "
"mesh or polycube)."
"A larger number will lead to slower computation time, but more "
"accurate approximation of the distance field.",
[&] {
ImGui::SetNextItemWidth(80);
{
ImGuiFrameColorGuard frame_cg{5.0f / 7.0f};
ImGui::DragInt("grid size", &anchors_options_.grid_size, 1, 4, 64,
"%d");
}
ImGui::SameLine();
ImGuiHelpMarker("Size of the uniform grid used as anchors.");
ImGui::SameLine();
ImGui::SetNextItemWidth(80);
{
ImGui::Checkbox("inside only", &anchors_options_.inside_only);
ImGui::SameLine();
ImGuiHelpMarker("Whether to create uniform grid inside the mesh.");
}
ImGui::SetNextItemWidth(80);
{
ImGuiFrameColorGuard frame_cg{4.0f / 7.0f};
ImGui::DragFloat("bbox padding", &anchors_options_.bbox_padding,
1e-3f, 0.0f, 0.5f, "%.3f");
ImGui::SameLine();
ImGuiHelpMarker(
"How much padding to add when creating the uniform grid "
"anchors.");
}
ImGui::SetNextItemWidth(80);
{
ImGuiFrameColorGuard frame_cg{4.0f / 7.0f};
ImGui::DragInt("surface samples", &anchors_options_.surface_samples,
1, 1, 100, "%d");
ImGui::SameLine();
ImGuiHelpMarker(
"A multiple of this many surface points will be included in the "
"anchors with random jittering.");
}
ImGui::SameLine();
ImGui::SetNextItemWidth(80);
{
ImGuiFrameColorGuard frame_cg{4.0f / 7.0f};
ImGui::DragFloat("jitter", &anchors_options_.perturbation, 1e-3f,
0.0f, 0.5f, "%.3f");
ImGui::SameLine();
ImGuiHelpMarker("How much do we perturb surface points?");
}
});
if (ImGui::Button("Create anchors and signed distance fields")) {
CreateSdfAndAnchors();
}
ImGui::SameLine();
ImGuiHelpMarker(
"Create anchors with prescribed parameters, and compute signed "
"distance field with respect to the input shape.");
}
void DecompositionStage::DrawPolycubeControlChildWindow() {
DrawPolycubeOptimizerTreeNode();
DrawPolycubeManipulationTreeNode();
}
void DecompositionStage::DrawPolycubeManipulationTreeNode() {
if (ImGui::TreeNodeEx("Polycube manipulation",
ImGuiTreeNodeFlags_DefaultOpen)) {
ImGui::SetNextItemWidth(100);
{
ImGuiButtonColorGuard cg{0.05f};
if (ImGui::Button("Init/Reset polycube")) {
ResetPolycube();
}
}
ImGui::SameLine();
ImGuiHelpMarker(
"Initialize/reset an empty polycube. You must initialize a polycube "
"before "
"adding cuboids!\nWARNING: this will remove all existing cuboids, so "
"save your progress first.");
if (global_controller_.GetGlobalState().HasPolycube()) {
{
const char* suggest_strat_strs[] = {"distance-based", "volume-based"};
const char* suggest_tooltips[] = {
"Put a cuboid at a point uncovered by any cuboid that is furthest "
"away "
"from any cuboid.",
"Create a cuboid that has largest volume while being inside the "
"input "
"mesh and outside of any existing cuboid."};
static int item_current = 0;
if (ImGui::Button("Add a new cuboid")) {
PolycubeOptimizer::SuggestStrategy strat;
if (item_current == 0) {
strat = PolycubeOptimizer::SuggestStrategy::Simple;
} else {
strat = PolycubeOptimizer::SuggestStrategy::Largest;
}
SuggestNewCuboid(strat);
}
ImGui::SameLine();
ImGuiHelpMarker(
"Add a new cuboid according to the strategy specified on the "
"right.");
ImGui::SameLine();
ImGui::SetNextItemWidth(140);
{
const char* combo_label = suggest_strat_strs[item_current];
if (ImGui::BeginCombo("strategy", combo_label,
ImGuiComboFlags_None)) {
for (int n = 0; n < IM_ARRAYSIZE(suggest_strat_strs); n++) {
const bool is_selected = (item_current == n);
if (ImGui::Selectable(suggest_strat_strs[n], is_selected)) {
item_current = n;
}
if (is_selected) ImGui::SetItemDefaultFocus();
ImGuiHoveredTooltip(suggest_tooltips[n]);
}
ImGui::EndCombo();
}
}
}
if (global_controller_.GetGlobalState().GetPolycube().GetCuboidCount() >
0) {
if (ImGui::Button("Subtract a cuboid")) {
StartSubtractCuboid();
}
ImGui::SameLine();
ImGuiHelpMarker(
"Subtract a cuboid from the polycube. This may break up each "
"intersecting cuboid into up to 8 new cuboids.");
}
if (global_controller_.GetGlobalState().GetPolycube().GetCuboidCount() >
0) {
bool pressed = ImGui::Button("Reoptimize");
ImGui::SameLine();
ImGuiHelpMarker(
"Optimize all unlocked cuboids' parameters jointly. You can choose "
"to lock a cuboid to prevent its parameters from being changed.");
ImGui::SameLine();
ImGui::SetNextItemWidth(120);
if (ImGui::InputInt("steps", &reoptimize_steps_)) {
if (reoptimize_steps_ < 0) {
reoptimize_steps_ = 0;
}
}
if (pressed) {
Reoptimize(reoptimize_steps_);
}
}
}
ImGui::TreePop();
}
}
void DecompositionStage::DrawPolycubeOptimizerTreeNode() {
ImGuiTreeNodeWithTooltip(
"Coverage parameters", ImGuiTreeNodeFlags_DefaultOpen,
"Tweak how much to penalize over/under coverage of input shape by "
"cuboids.",
[&] {
ImGui::SetNextItemWidth(70);
{
ImGuiFrameColorGuard frame_cg{4.5f / 7.0f};
ImGui::DragFloat("+ weight", &options_.positive_l2_weight, 1e-3f,
0.0f, 1.0f, "%.3f");
}
ImGui::SameLine();
ImGuiHelpMarker(
"Weight of the positive part of the l2 loss (i.e. integration over "
"the positive sdf region of input shape); higher value "
"disencourages over-coverage of the input shape by cuboids.");
ImGui::SameLine();
ImGui::SetNextItemWidth(70);
{
ImGuiFrameColorGuard frame_cg{6.5f / 7.0f};
ImGui::DragFloat("- weight", &options_.negative_l2_weight, 1e-3f,
0.0f, 1.0f, "%.3f");
}
ImGui::SameLine();
ImGuiHelpMarker(
"Weight of the negative part of the l2 loss (i.e. integration over "
"the positive sdf region of input shape)(i.e. integration over the "
"negative sdf region of input shape); higher value "
"disencourages under-coverage of the input shape by cuboids.");
});
DrawOptimizerOptionsNode(options_.learning_rate, options_.adam_betas,
&options_.snapshot_freq);
if (ImGui::Button("Init/Reset optimizer")) {
polycube_optimizer_ = std::make_unique<PolycubeOptimizer>(options_);
}
ImGui::SameLine();
ImGuiHelpMarker("Recreate optimizer to use the prescribed parameters.");
}
void DecompositionStage::StartSubtractCuboid() {
UnfocusCuboid();
auto& deformed_mesh =
global_controller_.GetGlobalState().GetDeformedVolumeMesh();
auto& polycube = global_controller_.GetGlobalState().GetPolycube();
subtract_cuboid_ = std::make_unique<Cuboid>();
bool success = polycube_optimizer_->SuggestSubtractCuboid(
deformed_mesh, polycube, *subtract_cuboid_);
if (success) {
subtract_editing_controller_ =
std::make_unique<CuboidEditingController>(global_controller_, true);
auto& polycube_view = global_controller_.GetGlobalView().GetPolycubeView();
polycube_view.CreateTmpCuboid(*subtract_cuboid_);
auto& cuboid_node = polycube_view.GetTmpCuboidNode();
cuboid_node.UpdateMode(CuboidNode::Mode::Subtract);
subtract_editing_controller_->Focus(cuboid_node, *subtract_cuboid_);
} else {
LOGI(
"Failed to subtract cuboid: likely the polycube is contained entirely "
"inside the input mesh!");
}
}
void DecompositionStage::PerformSubtraction() {
LOGI("Perform subtraction!");
UnfocusCuboid();
auto subtract_bounds = subtract_cuboid_->GetBound();
subtract_cuboid_.reset();
auto& global_state = global_controller_.GetGlobalState();
assert(global_state.HasPolycube());
auto& polycube = global_state.GetPolycube();
auto& polycube_info = global_state.GetPolycubeInfo();
auto& polycube_view = global_controller_.GetGlobalView().GetPolycubeView();
size_t n = polycube.GetCuboidCount();
struct ChangeEntry {
int index;
std::string name;
std::vector<Cuboid> split_cuboids;
};
std::vector<ChangeEntry> change_list;
for (size_t i = 0; i < n; i++) {
auto& cuboid = polycube.GetCuboid(i);
auto bounds = cuboid.GetBound();
auto intersection = subtract_bounds;
intersection.first = intersection.first.cwiseMax(bounds.first);
intersection.second = intersection.second.cwiseMin(bounds.second);
if (IsCuboidBoundsEmpty(intersection)) {
continue; // only add non-empty ones to change list
}
ChangeEntry entry;
entry.index = i;
entry.name = polycube_info.names[i].ToString();
// Create a most 6 non-disjoint cuboids for bounds minus intersection.
for (int k = 0; k < 3; k++) {
for (int t = 0; t <= 1; t++) {
auto new_bounds = bounds;
if (t == 0) {
new_bounds.second(k) = intersection.first(k);
} else {
new_bounds.first(k) = intersection.second(k);
}
if (!IsCuboidBoundsEmpty(new_bounds)) {
entry.split_cuboids.emplace_back(
Cuboid::FromBounds(new_bounds.first, new_bounds.second));
}
}
}
change_list.push_back(entry);
}
LOGI("Applying {} subtraction changes ...", change_list.size());
// Now apply changes to polycube, polycube info, and polycube view.
// For loop must be in reverse order to guarantee correctness!
for (int j = static_cast<int>(change_list.size()) - 1; j >= 0; j--) {
auto& entry = change_list[j];
int i = entry.index;
int old_pos = polycube_info.GetPosition(i);
polycube.DeleteCuboid(i);
polycube_info.Delete(i);
polycube_view.DeleteCuboid(i);
int move_delta = static_cast<int>(polycube_info.ordering.size()) - old_pos;
int count = 0;
for (auto& cuboid : entry.split_cuboids) {
polycube.AddCuboid(cuboid);
polycube_view.AddCuboid(cuboid);
polycube_info.Push(fmt::format("[split #{}] {}", count, entry.name));
polycube_info.MoveItem(polycube.GetCuboidCount() - 1, -move_delta);
count++;
}
}
}
} // namespace hex
// namespace hex
| 35.372714 | 80 | 0.657058 | [
"mesh",
"object",
"shape",
"vector"
] |
6aab352d4d65c3bc1e5204a0f9540c7c134bee89 | 2,755 | cpp | C++ | SPOJ/salman.cpp | a3X3k/Competitive-programing-hacktoberfest-2021 | bc3997997318af4c5eafad7348abdd9bf5067b4f | [
"Unlicense"
] | 12 | 2021-06-05T09:40:10.000Z | 2021-10-07T17:59:51.000Z | SPOJ/salman.cpp | a3X3k/Competitive-programing-hacktoberfest-2021 | bc3997997318af4c5eafad7348abdd9bf5067b4f | [
"Unlicense"
] | 21 | 2020-10-10T10:41:03.000Z | 2020-10-31T10:41:23.000Z | SPOJ/salman.cpp | a3X3k/Competitive-programing-hacktoberfest-2021 | bc3997997318af4c5eafad7348abdd9bf5067b4f | [
"Unlicense"
] | 67 | 2021-08-01T10:04:52.000Z | 2021-10-10T00:25:04.000Z | #include <bits/stdc++.h>
using namespace std;
const long long N = 1 << 19;
long long t,n,q;
vector<long long> adj[N];
long long res[N],l[N],r[N];
vector<long long> s;
struct node
{
long long mn,sum;
friend node operator+(const node &a,const node &b)
{
node ret;
ret.mn = min(a.mn,b.mn);
ret.sum = a.sum+b.sum;
return ret;
}
}tree[N << 1LL];
long long lazy[N << 1LL];
void dfs(long long u)
{
s.push_back(u);
for(long long v : adj[u]) dfs(v);
s.push_back(u);
}
void pushlz(long long l,long long r,long long idx)
{
if(!lazy[idx]) return;
tree[idx].sum+=lazy[idx]*(r-l+1LL);
tree[idx].mn+=lazy[idx];
if(l!=r) lazy[idx*2LL]+=lazy[idx],lazy[idx*2LL+1LL]+=lazy[idx];
lazy[idx] = 0LL;
}
void build(long long l,long long r,long long idx)
{
lazy[idx] = 0;
if(l==r){ tree[idx].sum = tree[idx].mn = res[s[l]]; return; }
long long m = (l+r)/2LL;
build(l,m,idx*2LL),build(m+1LL,r,idx*2LL+1LL);
tree[idx] = tree[idx*2LL]+tree[idx*2LL+1LL];
}
void update(long long l,long long r,long long idx,long long x,long long y,long long k)
{
pushlz(l,r,idx);
if(x>r or y<l) return;
if(x<=l and y>=r)
{
lazy[idx]+=k;
pushlz(l,r,idx);
return;
}
long long m = (l+r)/2LL;
update(l,m,idx*2LL,x,y,k),update(m+1LL,r,idx*2LL+1LL,x,y,k);
tree[idx] = tree[idx*2LL]+tree[idx*2LL+1LL];
}
node read(long long l,long long r,long long idx,long long x,long long y)
{
pushlz(l,r,idx);
if(x>r or y<l){ node ret = {LLONG_MAX,0LL}; return ret; }
if(x<=l and y>=r) return tree[idx];
long long m = (l+r)/2LL;
return read(l,m,idx*2LL,x,y)+read(m+1LL,r,idx*2LL+1LL,x,y);
}
int main()
{
ios_base::sync_with_stdio(0); cin.tie(0);
cin >> t;
for(long long c = 0LL;c < t;c++)
{
cin >> n >> q;
for(long long i = 1LL;i <= n;i++) adj[i].clear();
for(long long i = 1LL;i <= n;i++)
{
long long pa,x;
cin >> pa >> x;
if(pa) adj[pa].push_back(i);
res[i] = x;
}
s.clear();
dfs(1LL);
for(long long i = 1LL;i <= n;i++) l[i] = -1LL;
for(long long i = 0;i < s.size();i++){ if(l[s[i]]==-1LL) l[s[i]] = i; r[s[i]] = i; }
build(0LL,s.size()-1LL,1LL);
cout << "Case " << c+1LL << ":\n";
while(q--)
{
long long t,x;
cin >> t >> x;
if(t==1LL) cout << read(0LL,s.size()-1LL,1LL,l[x],r[x]).sum/2LL << '\n';
else
{
long long mn = read(0LL,s.size()-1LL,1LL,l[x],r[x]).mn;
mn = min(mn,1000LL);
update(0LL,s.size()-1LL,1LL,l[x],r[x],mn);
}
}
}
}
| 25.045455 | 92 | 0.49873 | [
"vector"
] |
6aaba5d7fc94b81faa49a38f7461f3cb7dbdf1a3 | 18,939 | cc | C++ | src/update_engine/payload_state_unittest.cc | flatcar-linux/update_engine | 748eb99b18b67747f2e047327e9f2a18aa09d3b5 | [
"BSD-3-Clause"
] | 4 | 2019-11-13T15:09:11.000Z | 2022-03-11T08:42:20.000Z | src/update_engine/payload_state_unittest.cc | flatcar-linux/update_engine | 748eb99b18b67747f2e047327e9f2a18aa09d3b5 | [
"BSD-3-Clause"
] | 4 | 2020-03-11T10:28:56.000Z | 2022-03-10T11:30:03.000Z | src/update_engine/payload_state_unittest.cc | flatcar-linux/update_engine | 748eb99b18b67747f2e047327e9f2a18aa09d3b5 | [
"BSD-3-Clause"
] | 1 | 2021-05-26T08:32:18.000Z | 2021-05-26T08:32:18.000Z | // Copyright (c) 2012 The Chromium OS 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 <glib.h>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "strings/string_printf.h"
#include "update_engine/omaha_request_action.h"
#include "update_engine/payload_state.h"
#include "update_engine/prefs_mock.h"
#include "update_engine/test_utils.h"
#include "update_engine/utils.h"
using std::chrono::system_clock;
using std::string;
using strings::StringPrintf;
using testing::_;
using testing::NiceMock;
using testing::Return;
using testing::SetArgumentPointee;
namespace chromeos_update_engine {
static void SetupPayloadStateWith2Urls(string hash,
PayloadState* payload_state,
OmahaResponse* response) {
response->payload_urls.clear();
response->payload_urls.push_back("http://test");
response->payload_urls.push_back("https://test");
response->size = 523456789;
response->hash = hash;
response->max_failure_count_per_url = 3;
payload_state->SetResponse(*response);
string stored_response_sign = payload_state->GetResponseSignature();
string expected_response_sign = StringPrintf(
"NumURLs = 2\n"
"Url0 = http://test\n"
"Url1 = https://test\n"
"Payload Size = 523456789\n"
"Payload Sha256 Hash = %s\n"
"Is Delta Payload = %d\n"
"Max Failure Count Per Url = %d\n"
"Disable Payload Backoff = %d\n",
hash.c_str(),
response->is_delta_payload,
response->max_failure_count_per_url,
response->disable_payload_backoff);
EXPECT_EQ(expected_response_sign, stored_response_sign);
}
class PayloadStateTest : public ::testing::Test { };
TEST(PayloadStateTest, SetResponseWorksWithEmptyResponse) {
OmahaResponse response;
NiceMock<PrefsMock> prefs;
EXPECT_CALL(prefs, SetInt64(kPrefsPayloadAttemptNumber, 0));
EXPECT_CALL(prefs, SetInt64(kPrefsBackoffExpiryTime, 0));
EXPECT_CALL(prefs, SetInt64(kPrefsCurrentUrlIndex, 0));
EXPECT_CALL(prefs, SetInt64(kPrefsCurrentUrlFailureCount, 0));
PayloadState payload_state;
EXPECT_TRUE(payload_state.Initialize(&prefs));
payload_state.SetResponse(response);
string stored_response_sign = payload_state.GetResponseSignature();
string expected_response_sign = "NumURLs = 0\n"
"Payload Size = 0\n"
"Payload Sha256 Hash = \n"
"Is Delta Payload = 0\n"
"Max Failure Count Per Url = 0\n"
"Disable Payload Backoff = 0\n";
EXPECT_EQ(expected_response_sign, stored_response_sign);
EXPECT_EQ(0, payload_state.GetUrlIndex());
EXPECT_EQ(0, payload_state.GetUrlFailureCount());
}
TEST(PayloadStateTest, SetResponseWorksWithSingleUrl) {
OmahaResponse response;
response.payload_urls.push_back("http://single.url.test");
response.size = 123456789;
response.hash = "hash";
NiceMock<PrefsMock> prefs;
EXPECT_CALL(prefs, SetInt64(kPrefsPayloadAttemptNumber, 0));
EXPECT_CALL(prefs, SetInt64(kPrefsBackoffExpiryTime, 0));
EXPECT_CALL(prefs, SetInt64(kPrefsCurrentUrlIndex, 0));
EXPECT_CALL(prefs, SetInt64(kPrefsCurrentUrlFailureCount, 0));
PayloadState payload_state;
EXPECT_TRUE(payload_state.Initialize(&prefs));
payload_state.SetResponse(response);
string stored_response_sign = payload_state.GetResponseSignature();
string expected_response_sign = "NumURLs = 1\n"
"Url0 = http://single.url.test\n"
"Payload Size = 123456789\n"
"Payload Sha256 Hash = hash\n"
"Is Delta Payload = 0\n"
"Max Failure Count Per Url = 0\n"
"Disable Payload Backoff = 0\n";
EXPECT_EQ(expected_response_sign, stored_response_sign);
EXPECT_EQ(0, payload_state.GetUrlIndex());
EXPECT_EQ(0, payload_state.GetUrlFailureCount());
}
TEST(PayloadStateTest, SetResponseWorksWithMultipleUrls) {
OmahaResponse response;
response.payload_urls.push_back("http://multiple.url.test");
response.payload_urls.push_back("https://multiple.url.test");
response.size = 523456789;
response.hash = "rhash";
NiceMock<PrefsMock> prefs;
EXPECT_CALL(prefs, SetInt64(kPrefsPayloadAttemptNumber, 0));
EXPECT_CALL(prefs, SetInt64(kPrefsBackoffExpiryTime, 0));
EXPECT_CALL(prefs, SetInt64(kPrefsCurrentUrlIndex, 0));
EXPECT_CALL(prefs, SetInt64(kPrefsCurrentUrlFailureCount, 0));
PayloadState payload_state;
EXPECT_TRUE(payload_state.Initialize(&prefs));
payload_state.SetResponse(response);
string stored_response_sign = payload_state.GetResponseSignature();
string expected_response_sign = "NumURLs = 2\n"
"Url0 = http://multiple.url.test\n"
"Url1 = https://multiple.url.test\n"
"Payload Size = 523456789\n"
"Payload Sha256 Hash = rhash\n"
"Is Delta Payload = 0\n"
"Max Failure Count Per Url = 0\n"
"Disable Payload Backoff = 0\n";
EXPECT_EQ(expected_response_sign, stored_response_sign);
EXPECT_EQ(0, payload_state.GetUrlIndex());
EXPECT_EQ(0, payload_state.GetUrlFailureCount());
}
TEST(PayloadStateTest, CanAdvanceUrlIndexCorrectly) {
OmahaResponse response;
NiceMock<PrefsMock> prefs;
PayloadState payload_state;
// Payload attempt should start with 0 and then advance to 1.
EXPECT_CALL(prefs, SetInt64(kPrefsPayloadAttemptNumber, 0)).Times(1);
EXPECT_CALL(prefs, SetInt64(kPrefsPayloadAttemptNumber, 1)).Times(1);
EXPECT_CALL(prefs, SetInt64(kPrefsBackoffExpiryTime, _)).Times(2);
// Url index should go from 0 to 1 twice.
EXPECT_CALL(prefs, SetInt64(kPrefsCurrentUrlIndex, 0)).Times(2);
EXPECT_CALL(prefs, SetInt64(kPrefsCurrentUrlIndex, 1)).Times(2);
// Failure count should be called each times url index is set, so that's
// 4 times for this test.
EXPECT_CALL(prefs, SetInt64(kPrefsCurrentUrlFailureCount, 0)).Times(4);
EXPECT_TRUE(payload_state.Initialize(&prefs));
// This does a SetResponse which causes all the states to be set to 0 for
// the first time.
SetupPayloadStateWith2Urls("Hash1235", &payload_state, &response);
EXPECT_EQ(0, payload_state.GetUrlIndex());
// Verify that on the first error, the URL index advances to 1.
ActionExitCode error = kActionCodeDownloadMetadataSignatureMismatch;
payload_state.UpdateFailed(error);
EXPECT_EQ(1, payload_state.GetUrlIndex());
// Verify that on the next error, the URL index wraps around to 0.
payload_state.UpdateFailed(error);
EXPECT_EQ(0, payload_state.GetUrlIndex());
// Verify that on the next error, it again advances to 1.
payload_state.UpdateFailed(error);
EXPECT_EQ(1, payload_state.GetUrlIndex());
}
TEST(PayloadStateTest, NewResponseResetsPayloadState) {
OmahaResponse response;
NiceMock<PrefsMock> prefs;
PayloadState payload_state;
EXPECT_TRUE(payload_state.Initialize(&prefs));
// Set the first response.
SetupPayloadStateWith2Urls("Hash5823", &payload_state, &response);
// Advance the URL index to 1 by faking an error.
ActionExitCode error = kActionCodeDownloadMetadataSignatureMismatch;
payload_state.UpdateFailed(error);
EXPECT_EQ(1, payload_state.GetUrlIndex());
// Now, slightly change the response and set it again.
SetupPayloadStateWith2Urls("Hash8225", &payload_state, &response);
// Make sure the url index was reset to 0 because of the new response.
EXPECT_EQ(0, payload_state.GetUrlIndex());
EXPECT_EQ(0, payload_state.GetUrlFailureCount());
}
TEST(PayloadStateTest, AllCountersGetUpdatedProperlyOnErrorCodesAndEvents) {
OmahaResponse response;
PayloadState payload_state;
NiceMock<PrefsMock> prefs;
EXPECT_CALL(prefs, SetInt64(kPrefsPayloadAttemptNumber, 0)).Times(2);
EXPECT_CALL(prefs, SetInt64(kPrefsPayloadAttemptNumber, 1)).Times(1);
EXPECT_CALL(prefs, SetInt64(kPrefsPayloadAttemptNumber, 2)).Times(1);
EXPECT_CALL(prefs, SetInt64(kPrefsBackoffExpiryTime, _)).Times(4);
EXPECT_CALL(prefs, SetInt64(kPrefsCurrentUrlIndex, 0)).Times(4);
EXPECT_CALL(prefs, SetInt64(kPrefsCurrentUrlIndex, 1)).Times(2);
EXPECT_CALL(prefs, SetInt64(kPrefsCurrentUrlFailureCount, 0)).Times(7);
EXPECT_CALL(prefs, SetInt64(kPrefsCurrentUrlFailureCount, 1)).Times(2);
EXPECT_CALL(prefs, SetInt64(kPrefsCurrentUrlFailureCount, 2)).Times(1);
EXPECT_TRUE(payload_state.Initialize(&prefs));
SetupPayloadStateWith2Urls("Hash5873", &payload_state, &response);
// This should advance the URL index.
payload_state.UpdateFailed(kActionCodeDownloadMetadataSignatureMismatch);
EXPECT_EQ(0, payload_state.GetPayloadAttemptNumber());
EXPECT_EQ(1, payload_state.GetUrlIndex());
EXPECT_EQ(0, payload_state.GetUrlFailureCount());
// This should advance the failure count only.
payload_state.UpdateFailed(kActionCodeDownloadTransferError);
EXPECT_EQ(0, payload_state.GetPayloadAttemptNumber());
EXPECT_EQ(1, payload_state.GetUrlIndex());
EXPECT_EQ(1, payload_state.GetUrlFailureCount());
// This should advance the failure count only.
payload_state.UpdateFailed(kActionCodeDownloadTransferError);
EXPECT_EQ(0, payload_state.GetPayloadAttemptNumber());
EXPECT_EQ(1, payload_state.GetUrlIndex());
EXPECT_EQ(2, payload_state.GetUrlFailureCount());
// This should advance the URL index as we've reached the
// max failure count and reset the failure count for the new URL index.
// This should also wrap around the URL index and thus cause the payload
// attempt number to be incremented.
payload_state.UpdateFailed(kActionCodeDownloadTransferError);
EXPECT_EQ(1, payload_state.GetPayloadAttemptNumber());
EXPECT_EQ(0, payload_state.GetUrlIndex());
EXPECT_EQ(0, payload_state.GetUrlFailureCount());
EXPECT_TRUE(payload_state.ShouldBackoffDownload());
// This should advance the URL index.
payload_state.UpdateFailed(kActionCodePayloadHashMismatchError);
EXPECT_EQ(1, payload_state.GetPayloadAttemptNumber());
EXPECT_EQ(1, payload_state.GetUrlIndex());
EXPECT_EQ(0, payload_state.GetUrlFailureCount());
EXPECT_TRUE(payload_state.ShouldBackoffDownload());
// This should advance the URL index and payload attempt number due to
// wrap-around of URL index.
payload_state.UpdateFailed(kActionCodeDownloadMetadataSignatureMissingError);
EXPECT_EQ(2, payload_state.GetPayloadAttemptNumber());
EXPECT_EQ(0, payload_state.GetUrlIndex());
EXPECT_EQ(0, payload_state.GetUrlFailureCount());
EXPECT_TRUE(payload_state.ShouldBackoffDownload());
// This HTTP error code should only increase the failure count.
payload_state.UpdateFailed(static_cast<ActionExitCode>(
kActionCodeOmahaRequestHTTPResponseBase + 404));
EXPECT_EQ(2, payload_state.GetPayloadAttemptNumber());
EXPECT_EQ(0, payload_state.GetUrlIndex());
EXPECT_EQ(1, payload_state.GetUrlFailureCount());
EXPECT_TRUE(payload_state.ShouldBackoffDownload());
// And that failure count should be reset when we download some bytes
// afterwards.
payload_state.DownloadProgress(100);
EXPECT_EQ(2, payload_state.GetPayloadAttemptNumber());
EXPECT_EQ(0, payload_state.GetUrlIndex());
EXPECT_EQ(0, payload_state.GetUrlFailureCount());
EXPECT_TRUE(payload_state.ShouldBackoffDownload());
// Now, slightly change the response and set it again.
SetupPayloadStateWith2Urls("Hash8532", &payload_state, &response);
// Make sure the url index was reset to 0 because of the new response.
EXPECT_EQ(0, payload_state.GetPayloadAttemptNumber());
EXPECT_EQ(0, payload_state.GetUrlIndex());
EXPECT_EQ(0, payload_state.GetUrlFailureCount());
EXPECT_FALSE(payload_state.ShouldBackoffDownload());
}
TEST(PayloadStateTest, PayloadAttemptNumberIncreasesOnSuccessfulDownload) {
OmahaResponse response;
PayloadState payload_state;
NiceMock<PrefsMock> prefs;
EXPECT_CALL(prefs, SetInt64(kPrefsPayloadAttemptNumber, 0)).Times(1);
EXPECT_CALL(prefs, SetInt64(kPrefsPayloadAttemptNumber, 1)).Times(1);
EXPECT_CALL(prefs, SetInt64(kPrefsBackoffExpiryTime, _)).Times(2);
EXPECT_CALL(prefs, SetInt64(kPrefsCurrentUrlIndex, 0)).Times(1);
EXPECT_CALL(prefs, SetInt64(kPrefsCurrentUrlFailureCount, 0)).Times(1);
EXPECT_TRUE(payload_state.Initialize(&prefs));
SetupPayloadStateWith2Urls("Hash8593", &payload_state, &response);
// This should just advance the payload attempt number;
EXPECT_EQ(0, payload_state.GetPayloadAttemptNumber());
payload_state.DownloadComplete();
EXPECT_EQ(1, payload_state.GetPayloadAttemptNumber());
EXPECT_EQ(0, payload_state.GetUrlIndex());
EXPECT_EQ(0, payload_state.GetUrlFailureCount());
}
TEST(PayloadStateTest, SetResponseResetsInvalidUrlIndex) {
OmahaResponse response;
PayloadState payload_state;
NiceMock<PrefsMock> prefs;
EXPECT_TRUE(payload_state.Initialize(&prefs));
SetupPayloadStateWith2Urls("Hash4427", &payload_state, &response);
// Generate enough events to advance URL index, failure count and
// payload attempt number all to 1.
payload_state.DownloadComplete();
payload_state.UpdateFailed(kActionCodeDownloadMetadataSignatureMismatch);
payload_state.UpdateFailed(kActionCodeDownloadTransferError);
EXPECT_EQ(1, payload_state.GetPayloadAttemptNumber());
EXPECT_EQ(1, payload_state.GetUrlIndex());
EXPECT_EQ(1, payload_state.GetUrlFailureCount());
// Now, simulate a corrupted url index on persisted store which gets
// loaded when update_engine restarts. Using a different prefs object
// so as to not bother accounting for the uninteresting calls above.
NiceMock<PrefsMock> prefs2;
EXPECT_CALL(prefs2, Exists(_)).WillRepeatedly(Return(true));
EXPECT_CALL(prefs2, GetInt64(kPrefsPayloadAttemptNumber, _));
EXPECT_CALL(prefs2, GetInt64(kPrefsBackoffExpiryTime, _));
EXPECT_CALL(prefs2, GetInt64(kPrefsCurrentUrlIndex, _))
.WillOnce(testing::DoAll(SetArgumentPointee<1>(2), Return(true)));
EXPECT_CALL(prefs2, GetInt64(kPrefsCurrentUrlFailureCount, _));
// Note: This will be a different payload object, but the response should
// have the same hash as before so as to not trivially reset because the
// response was different. We want to specifically test that even if the
// response is same, we should reset the state if we find it corrupted.
EXPECT_TRUE(payload_state.Initialize(&prefs2));
SetupPayloadStateWith2Urls("Hash4427", &payload_state, &response);
// Make sure all counters get reset to 0 because of the corrupted URL index
// we supplied above.
EXPECT_EQ(0, payload_state.GetPayloadAttemptNumber());
EXPECT_EQ(0, payload_state.GetUrlIndex());
EXPECT_EQ(0, payload_state.GetUrlFailureCount());
}
TEST(PayloadStateTest, NoBackoffForDeltaPayloads) {
OmahaResponse response;
response.is_delta_payload = true;
PayloadState payload_state;
NiceMock<PrefsMock> prefs;
EXPECT_TRUE(payload_state.Initialize(&prefs));
SetupPayloadStateWith2Urls("Hash6437", &payload_state, &response);
// Simulate a successful download and see that we're ready to download
// again without any backoff as this is a delta payload.
payload_state.DownloadComplete();
EXPECT_EQ(0, payload_state.GetPayloadAttemptNumber());
EXPECT_FALSE(payload_state.ShouldBackoffDownload());
// Simulate two failures (enough to cause payload backoff) and check
// again that we're ready to re-download without any backoff as this is
// a delta payload.
payload_state.UpdateFailed(kActionCodeDownloadMetadataSignatureMismatch);
payload_state.UpdateFailed(kActionCodeDownloadMetadataSignatureMismatch);
EXPECT_EQ(0, payload_state.GetUrlIndex());
EXPECT_EQ(0, payload_state.GetPayloadAttemptNumber());
EXPECT_FALSE(payload_state.ShouldBackoffDownload());
}
static void CheckPayloadBackoffState(PayloadState* payload_state,
int expected_attempt_number,
utils::days_t expected_days) {
payload_state->DownloadComplete();
EXPECT_EQ(expected_attempt_number, payload_state->GetPayloadAttemptNumber());
EXPECT_TRUE(payload_state->ShouldBackoffDownload());
auto backoff_expiry_time = payload_state->GetBackoffExpiryTime();
// Add 1 hour extra to the 6 hour fuzz check to tolerate edge cases.
std::chrono::hours max_fuzz_delta(7);
auto expected_min_time = system_clock::now() + expected_days - max_fuzz_delta;
auto expected_max_time = system_clock::now() + expected_days + max_fuzz_delta;
EXPECT_LT(system_clock::to_time_t(expected_min_time),
system_clock::to_time_t(backoff_expiry_time));
EXPECT_GT(system_clock::to_time_t(expected_max_time),
system_clock::to_time_t(backoff_expiry_time));
}
TEST(PayloadStateTest, BackoffPeriodsAreInCorrectRange) {
OmahaResponse response;
response.is_delta_payload = false;
PayloadState payload_state;
NiceMock<PrefsMock> prefs;
EXPECT_TRUE(payload_state.Initialize(&prefs));
SetupPayloadStateWith2Urls("Hash8939", &payload_state, &response);
CheckPayloadBackoffState(&payload_state, 1, utils::days_t(1));
CheckPayloadBackoffState(&payload_state, 2, utils::days_t(2));
CheckPayloadBackoffState(&payload_state, 3, utils::days_t(4));
CheckPayloadBackoffState(&payload_state, 4, utils::days_t(8));
CheckPayloadBackoffState(&payload_state, 5, utils::days_t(16));
CheckPayloadBackoffState(&payload_state, 6, utils::days_t(16));
CheckPayloadBackoffState(&payload_state, 7, utils::days_t(16));
CheckPayloadBackoffState(&payload_state, 8, utils::days_t(16));
CheckPayloadBackoffState(&payload_state, 9, utils::days_t(16));
CheckPayloadBackoffState(&payload_state, 10, utils::days_t(16));
}
TEST(PayloadStateTest, BackoffLogicCanBeDisabled) {
OmahaResponse response;
response.disable_payload_backoff = true;
PayloadState payload_state;
NiceMock<PrefsMock> prefs;
EXPECT_TRUE(payload_state.Initialize(&prefs));
SetupPayloadStateWith2Urls("Hash8939", &payload_state, &response);
// Simulate a successful download and see that we are ready to download
// again without any backoff.
payload_state.DownloadComplete();
EXPECT_EQ(1, payload_state.GetPayloadAttemptNumber());
EXPECT_FALSE(payload_state.ShouldBackoffDownload());
// Test again, this time by simulating two errors that would cause
// the payload attempt number to increment due to wrap around. And
// check that we are still ready to re-download without any backoff.
payload_state.UpdateFailed(kActionCodeDownloadMetadataSignatureMismatch);
payload_state.UpdateFailed(kActionCodeDownloadMetadataSignatureMismatch);
EXPECT_EQ(2, payload_state.GetPayloadAttemptNumber());
EXPECT_FALSE(payload_state.ShouldBackoffDownload());
}
}
| 43.043182 | 80 | 0.747558 | [
"object"
] |
6aad5b7b0a2562aa1ef32d6129ba2d40cc341600 | 22,714 | cc | C++ | src/arith/solve_linear_inequality.cc | XiaoSong9905/tvm | 48940f697e15d5b50fa1f032003e6c700ae1e423 | [
"Apache-2.0"
] | 4,640 | 2017-08-17T19:22:15.000Z | 2019-11-04T15:29:46.000Z | src/arith/solve_linear_inequality.cc | XiaoSong9905/tvm | 48940f697e15d5b50fa1f032003e6c700ae1e423 | [
"Apache-2.0"
] | 3,022 | 2020-11-24T14:02:31.000Z | 2022-03-31T23:55:31.000Z | src/arith/solve_linear_inequality.cc | XiaoSong9905/tvm | 48940f697e15d5b50fa1f032003e6c700ae1e423 | [
"Apache-2.0"
] | 1,352 | 2017-08-17T19:30:38.000Z | 2019-11-04T16:09:29.000Z | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file tvm/arith/solve_linear_inequality.cc
* \brief Solve linear inequalities.
*/
#include <tvm/arith/analyzer.h>
#include <tvm/arith/int_solver.h>
#include <tvm/arith/pattern.h>
#include <tvm/runtime/data_type.h>
#include <tvm/runtime/registry.h>
#include <tvm/tir/analysis.h>
#include <tvm/tir/expr.h>
#include <tvm/tir/op.h>
#include <tvm/tir/stmt_functor.h>
#include "int_operator.h"
namespace tvm {
namespace arith {
using namespace tvm::runtime;
using namespace tvm::tir;
struct ExprLess {
bool operator()(const PrimExpr& l, const PrimExpr& r) const {
return CalculateExprComplexity(l) < CalculateExprComplexity(r);
}
};
void DebugPrint(const std::vector<PrimExpr>& current_ineq_set,
const std::vector<PrimExpr>& next_ineq_set, const std::vector<PrimExpr>& rest,
const std::vector<std::pair<int64_t, PrimExpr>>& coef_pos,
const std::vector<std::pair<int64_t, PrimExpr>>& coef_neg) {
std::cout << "Current ineq set:\n[";
for (auto& ineq : current_ineq_set) {
std::cout << ineq << ", ";
}
std::cout << "]\n";
std::cout << "Next ineq set:\n[";
for (auto& ineq : next_ineq_set) {
std::cout << ineq << ", ";
}
std::cout << "]\n";
std::cout << "coef_pos:\n[";
for (auto& coef : coef_pos) {
std::cout << "(" << coef.first << ", " << coef.second << "), ";
}
std::cout << "]\n";
std::cout << "coef_neg:\n[";
for (auto& coef : coef_neg) {
std::cout << "(" << coef.first << ", " << coef.second << "), ";
}
std::cout << "]\n";
}
/*!
* \brief normalize to the form `expr <= 0`
*/
class NormalizeComparisons : public ExprMutator {
public:
PrimExpr VisitExpr_(const EQNode* op) override { return Make<EQ>(op->a, op->b); }
PrimExpr VisitExpr_(const NENode* op) override { return Make<NE>(op->a, op->b); }
PrimExpr VisitExpr_(const LTNode* op) override { return Make<LT>(op->a, op->b); }
PrimExpr VisitExpr_(const LENode* op) override { return Make<LE>(op->a, op->b); }
PrimExpr VisitExpr_(const GTNode* op) override { return Make<LT>(op->b, op->a); }
PrimExpr VisitExpr_(const GENode* op) override { return Make<LE>(op->b, op->a); }
private:
template <class T>
PrimExpr Make(const PrimExpr& a, const PrimExpr& b) {
// rewrite LT to LE for ints
if (std::is_same<T, LT>::value && (a.dtype().is_int() || a.dtype().is_uint())) {
return LE(analyzer_.Simplify(a - b + 1), make_zero(a.dtype()));
}
return T(analyzer_.Simplify(a - b), make_zero(a.dtype()));
}
arith::Analyzer analyzer_;
};
void AddInequality(std::vector<PrimExpr>* inequality_set, const PrimExpr& new_ineq,
Analyzer* analyzer) {
if (analyzer->CanProve(new_ineq) ||
std::find_if(inequality_set->begin(), inequality_set->end(), [&](const PrimExpr& e) {
return StructuralEqual()(e, new_ineq);
}) != inequality_set->end()) {
// redundant: follows from the vranges
// or has already been added
return;
}
if (const LENode* new_le = new_ineq.as<LENode>()) {
for (auto iter = inequality_set->begin(); iter != inequality_set->end();) {
const LENode* le = iter->as<LENode>();
if (le && analyzer->CanProve(new_le->a - le->a <= 0)) {
return;
} else if (le && analyzer->CanProve(le->a - new_le->a <= 0)) {
iter = inequality_set->erase(iter);
} else {
++iter;
}
}
}
inequality_set->push_back(new_ineq);
}
void ClassifyByPolarity(const Var& var, const std::vector<PrimExpr>& current_ineq_set,
std::vector<PrimExpr>* next_ineq_set, std::vector<PrimExpr>* rest,
std::vector<std::pair<int64_t, PrimExpr>>* coef_pos,
std::vector<std::pair<int64_t, PrimExpr>>* coef_neg, Analyzer* analyzer) {
// Take formulas from current_ineq_set and classify them according to polarity wrt var
// and store to coef_pos and coef_neg respectively.
for (const PrimExpr& ineq : current_ineq_set) {
if (const LENode* le = ineq.as<LENode>()) {
Array<PrimExpr> coef = arith::DetectLinearEquation(le->a, {var});
if (!coef.empty() && is_const_int(coef[0])) {
int64_t coef0 = *as_const_int(coef[0]);
if (coef0 == 0) {
// zero polarity, straight to next_ineq_set
AddInequality(next_ineq_set, ineq, analyzer);
} else if (coef0 > 0) {
coef_pos->push_back({coef0, coef[1]});
} else if (coef0 < 0) {
coef_neg->push_back({coef0, coef[1]});
}
continue;
}
} else if (const EQNode* eq = ineq.as<EQNode>()) {
Array<PrimExpr> coef = arith::DetectLinearEquation(eq->a, {var});
if (!coef.empty() && is_const_int(coef[0])) {
int64_t coef0 = *as_const_int(coef[0]);
if (coef0 == 0) {
// zero polarity, straight to next_ineq_set
AddInequality(next_ineq_set, ineq, analyzer);
} else if (coef0 > 0) {
// Equalities may be considered as pairs of two inequalities
coef_pos->push_back({coef0, coef[1]});
coef_neg->push_back({-coef0, -coef[1]});
} else if (coef0 < 0) {
coef_pos->push_back({-coef0, -coef[1]});
coef_neg->push_back({coef0, coef[1]});
}
continue;
}
}
// if nothing worked, put it in rest
rest->push_back(ineq);
}
}
void MoveEquality(std::vector<PrimExpr>* upper_bounds, std::vector<PrimExpr>* lower_bounds,
std::vector<PrimExpr>* equalities) {
// those exist in both upper & lower bounds will be moved to equalities
for (auto ub = upper_bounds->begin(); ub != upper_bounds->end();) {
auto lb = std::find_if(lower_bounds->begin(), lower_bounds->end(),
[&](const PrimExpr& e) { return StructuralEqual()(e, *ub); });
if (lb != lower_bounds->end()) {
equalities->push_back(*lb);
lower_bounds->erase(lb);
ub = upper_bounds->erase(ub);
} else {
++ub;
}
}
}
PartialSolvedInequalities SolveLinearInequalities(const IntConstraints& system_to_solve) {
arith::Analyzer analyzer;
analyzer.Bind(system_to_solve->ranges);
// The algorithm consists in doing the following things for each variable v
// - Take formulas from `current_ineq_set_to_solve` and
// classify them according to polarity wrt v.
// - Combine each formula of positive polarity (wrt v)
// with each formula of negative polarity.
// - Put the resulting combinations into `next_ineq_set_to_solve`
// along with unclassifiable formulas.
// - Replace `current_ineq_set_to_solve` with `next_ineq_set_to_solve`
// and move to the next variable.
// normalized inequality
std::vector<PrimExpr> current_ineq_set_to_solve;
std::vector<PrimExpr> next_ineq_set_to_solve;
// A vector of pairs (c, e), c > 0, representing formulas of the form c*v + e <= 0
std::vector<std::pair<int64_t, PrimExpr>> coef_pos;
// A vector of pairs (c, e), c < 0, representing formulas of the form c*v + e <= 0
std::vector<std::pair<int64_t, PrimExpr>> coef_neg;
// formulas we don't know what to do with
std::vector<PrimExpr> rest;
// Simplify each inequality into the form `expr <= 0` and add to current formulas
for (const PrimExpr& ineq : system_to_solve->relations) {
AddInequality(¤t_ineq_set_to_solve,
NormalizeComparisons()(analyzer.Simplify(ineq, kSimplifyRewriteCanonicalRewrite)),
&analyzer);
}
Map<Var, IntGroupBounds> res_bounds;
for (const Var& v : system_to_solve->variables) {
ICHECK(!res_bounds.count(v))
<< "Variable " << v
<< " appears more than one time in the `variables` which might be a bug";
next_ineq_set_to_solve.clear();
coef_pos.clear();
coef_neg.clear();
// Add bounds from vranges
if (system_to_solve->ranges.count(v)) {
const Range& range = system_to_solve->ranges[v];
PrimExpr range_lbound = analyzer.Simplify(range->min, kSimplifyRewriteCanonicalRewrite);
PrimExpr range_ubound =
analyzer.Simplify(range->min + range->extent - 1, kSimplifyRewriteCanonicalRewrite);
coef_neg.push_back({-1, range_lbound});
coef_pos.push_back({1, -range_ubound});
}
ClassifyByPolarity(v, current_ineq_set_to_solve, &next_ineq_set_to_solve, &rest, &coef_pos,
&coef_neg, &analyzer);
// Combine each positive inequality with each negative one (by adding them together)
int64_t gcd_x, gcd_y;
for (const auto& pos : coef_pos) {
for (const auto& neg : coef_neg) {
auto first_gcd = ExtendedEuclidean(pos.first, -neg.first, &gcd_x, &gcd_y);
PrimExpr c_pos = make_const(v.dtype(), neg.first / first_gcd);
PrimExpr c_neg = make_const(v.dtype(), pos.first / first_gcd);
// eliminate the current variable
PrimExpr new_lhs = c_neg * neg.second - c_pos * pos.second;
PrimExpr new_ineq = LE(new_lhs, make_zero(pos.second.dtype()));
// we need rewrite_simplify -> canonical_simplify -> rewrite_simplify
// to help simplify things like (((y + 10) - (-1*(y - 20))) <= 0) => y - 5 <= 0
// with steps = 2 it's (y*2) - 10 <= 0
new_ineq =
NormalizeComparisons()(analyzer.Simplify(new_ineq, kSimplifyRewriteCanonicalRewrite));
AddInequality(&next_ineq_set_to_solve, new_ineq, &analyzer);
}
}
// Now we have to generate resulting (in)equalities for the variable v
// Find the common denominator in a sense
// We will generate formulas of the form coef_lcm*v <= bound
int64_t coef_lcm = 1;
for (const auto& pos : coef_pos) {
coef_lcm = LeastCommonMultiple(coef_lcm, pos.first);
}
for (const auto& neg : coef_neg) {
coef_lcm = LeastCommonMultiple(coef_lcm, -neg.first);
}
// The resulting lower and upper bounds
std::vector<PrimExpr> upper_bounds;
std::vector<PrimExpr> lower_bounds;
upper_bounds.reserve(coef_pos.size());
lower_bounds.reserve(coef_neg.size());
for (const auto& pos : coef_pos) {
PrimExpr bound = make_const(v.dtype(), -coef_lcm / pos.first) * pos.second;
bound = analyzer.Simplify(bound, kSimplifyRewriteCanonicalRewrite);
// Don't add if any of the existing bounds is better
if (std::any_of(upper_bounds.begin(), upper_bounds.end(),
[&bound, &analyzer](const PrimExpr& o) {
return analyzer.CanProve(o - bound <= 0);
})) {
continue;
}
// Erase all worse bounds
for (auto iter = upper_bounds.begin(); iter != upper_bounds.end();) {
if (analyzer.CanProve(*iter - bound >= 0)) {
iter = upper_bounds.erase(iter);
} else {
++iter;
}
}
// Add the upper bound
upper_bounds.push_back(bound);
}
for (const auto& neg : coef_neg) {
PrimExpr bound = make_const(v.dtype(), -coef_lcm / neg.first) * neg.second;
bound = analyzer.Simplify(bound, kSimplifyRewriteCanonicalRewrite);
// Don't add if any of the existing bounds is better
if (std::any_of(lower_bounds.begin(), lower_bounds.end(),
[&bound, &analyzer](const PrimExpr& o) {
return analyzer.CanProve(o - bound >= 0);
})) {
continue;
}
// Erase all worse bounds
for (auto iter = lower_bounds.begin(); iter != lower_bounds.end();) {
if (analyzer.CanProve(*iter - bound <= 0)) {
iter = lower_bounds.erase(iter);
} else {
++iter;
}
}
// Add the lower bound
lower_bounds.push_back(bound);
}
std::vector<PrimExpr> equal;
equal.reserve(std::min(upper_bounds.size(), lower_bounds.size()));
MoveEquality(&upper_bounds, &lower_bounds, &equal);
std::vector<PrimExpr> equal_list(equal.begin(), equal.end());
std::sort(equal_list.begin(), equal_list.end(), ExprLess());
// Write it to the result.
IntGroupBounds bnds(make_const(v.dtype(), coef_lcm),
Array<PrimExpr>(lower_bounds.begin(), lower_bounds.end()),
Array<PrimExpr>(equal_list.begin(), equal_list.end()),
Array<PrimExpr>(upper_bounds.begin(), upper_bounds.end()));
res_bounds.Set(v, bnds);
std::swap(current_ineq_set_to_solve, next_ineq_set_to_solve);
}
// Everything that is left goes to res.relations
Array<PrimExpr> other_conditions;
for (const PrimExpr& e : current_ineq_set_to_solve) {
PrimExpr e_simp = analyzer.Simplify(e, kSimplifyRewriteCanonicalRewrite);
if (is_const_int(e_simp, 0)) {
// contradiction detected
other_conditions = {const_false()};
break;
} else if (is_const_int(e_simp, 1)) {
continue;
} else {
other_conditions.push_back(e_simp);
}
}
for (const PrimExpr& e : rest) {
other_conditions.push_back(e);
}
return {res_bounds, other_conditions};
}
#ifdef _MSC_VER
#pragma optimize("g", off)
#endif
IntConstraints SolveInequalitiesToRange(const IntConstraints& inequalities) {
// Resulting ranges will contain ranges for the new variables and for the variables that are
// not in the inequalities->variables but are in inequalities->ranges
// It will be useful when solving Jacobian axes jac_xxx)
Map<Var, Range> res_ranges;
// we get a set of equality, lower, upper bound of each variable.
auto solved_system = SolveLinearInequalities(inequalities);
Map<Var, IntGroupBounds> solved_bounds = solved_system.first;
Array<PrimExpr> solved_other_relations = solved_system.second;
Array<PrimExpr> res_relations;
// this keeps being updated during determining the range of each variable.
Map<Var, Range> vranges;
for (std::pair<Var, Range> vr : inequalities->ranges) {
vranges.Set(vr.first, vr.second);
}
// We process variables in the reverse direction to start with the most independent one.
// This order is needed to compute new ranges.
for (auto it = inequalities->variables.rbegin(); it != inequalities->variables.rend(); ++it) {
arith::Analyzer analyzer;
analyzer.Bind(vranges);
const Var& var = *it;
ICHECK(solved_bounds.count(var));
auto bnd = solved_bounds[var];
if (is_one(bnd->coef) && !bnd->equal.empty()) {
// There is an equation of the form `v == expr`, so this variable can be completely removed.
// Note that we use the 0-th expression because they are ordered by complexity,
// so it must be the simplest one.
// The MSVC compiler optimization must be disabled for the expression `bnd->equal[0]` which
// triggers an internal compiler error.
Range best_range(bnd->equal[0],
analyzer.Simplify(bnd->equal[0] + 1, kSimplifyRewriteCanonicalRewrite));
res_ranges.Set(var, best_range);
vranges.Set(var, best_range);
} else {
if (vranges.count(var) > 0) {
bnd = bnd + vranges[var];
}
auto best_range = bnd.FindBestRange(vranges);
if (best_range.defined()) {
if (analyzer.CanProveGreaterEqual(-best_range->extent, 0)) {
// range.extent <= 0 implies the input inequality system is unsolvable
return IntConstraints(/*variables=*/{}, /*ranges=*/{},
/*relations=*/{tir::make_zero(DataType::Bool())});
}
res_ranges.Set(var, best_range);
vranges.Set(var, best_range);
}
}
}
// Add the original conditions to the resulting conditions
arith::Analyzer analyzer;
analyzer.Bind(vranges);
for (const PrimExpr& old_cond :
AsConditions(inequalities->variables, solved_bounds, solved_other_relations)) {
if (!analyzer.CanProve(old_cond)) {
// those not represented in vranges (res_ranges)
res_relations.push_back(old_cond);
}
}
IntConstraints system(inequalities->variables, res_ranges, res_relations);
return system;
}
#ifdef _MSC_VER
#pragma optimize("g", on)
#endif
IntConstraintsTransform SolveInequalitiesDeskewRange(const IntConstraints& inequalities) {
// Resulting ranges will contain ranges for the new variables and for the variables that are
// not in the inequalities->variables but are in inequalities->ranges (jac_xxx)
Map<Var, Range> res_ranges;
// we get a set of equality, lower, upper bound of each variable.
auto solved_system = SolveLinearInequalities(inequalities);
Map<Var, IntGroupBounds> solved_bounds = solved_system.first;
Array<PrimExpr> solved_other_relations = solved_system.second;
arith::Analyzer analyzer;
Map<Var, PrimExpr> res_src_to_dst;
Map<Var, PrimExpr> res_dst_to_src;
Array<Var> res_variables;
Array<PrimExpr> res_relations;
// this keeps being updated during determining the range of each variable.
Map<Var, Range> vranges;
for (std::pair<Var, Range> vr : inequalities->ranges) {
vranges.Set(vr.first, vr.second);
}
analyzer.Bind(vranges);
// We process variables in the reverse direction to start with the most independent one.
// This order is needed to compute new ranges.
for (auto it = inequalities->variables.rbegin(); it != inequalities->variables.rend(); ++it) {
const Var& var = *it;
auto bnd = solved_bounds[var];
// Note that we replace old vars with new ones
bnd = bnd.Substitute(res_src_to_dst);
if (is_one(bnd->coef) && !bnd->equal.empty()) {
// There is an equation of the form `v == expr`,
// so this variable can be completely removed.
// Note that we use the 0-th expression because they are ordered by complexity,
// so it must be the simplest one.
res_src_to_dst.Set(var, bnd->equal[0]);
} else {
if (vranges.count(var) > 0) {
bnd = bnd + vranges[var];
}
auto best_range = bnd.FindBestRange(vranges);
Var new_var = var.copy_with_suffix(".shifted");
if (!best_range.defined()) {
res_src_to_dst.Set(var, var);
res_dst_to_src.Set(var, var);
res_variables.push_back(var);
} else if (is_const_int(best_range->extent, 1)) {
// Don't create an itervar, just replace it everywhere with its min
res_src_to_dst.Set(var, best_range->min);
} else if (analyzer.CanProveGreaterEqual(-best_range->extent, 0)) {
// range.extent <= 0 implies the input inequality system is unsolvable
return IntConstraintsTransform(inequalities,
IntConstraints(
/*variables=*/{},
/*ranges=*/{},
/*relations=*/{tir::make_zero(DataType::Bool())}),
{}, {});
} else {
// created new_var starts from 0
res_src_to_dst.Set(var, new_var + best_range->min);
// Note that we are substituting old with new, so best_range contains new var,
// that is we have to substitute new with old in best_range here
res_dst_to_src.Set(new_var,
analyzer.Simplify(var - Substitute(best_range->min, res_dst_to_src)));
// Add the new var to the resulting axis
auto range = Range(make_zero(new_var.dtype()), best_range->extent);
res_variables.push_back(new_var);
res_ranges.Set(new_var, range);
vranges.Set(new_var, range);
analyzer.Bind(new_var, range);
}
}
}
// Add the original conditions (with variables substituted) to the resulting conditions
for (const PrimExpr& old_cond :
AsConditions(inequalities->variables, solved_bounds, solved_other_relations)) {
PrimExpr new_cond = analyzer.Simplify(Substitute(old_cond, res_src_to_dst));
if (!is_const_int(new_cond, 1)) {
// those not represented in vranges (res_ranges)
res_relations.push_back(new_cond);
}
}
// Reverse the axis so that it matches the order of the original variables
res_variables = Array<Var>(res_variables.rbegin(), res_variables.rend());
IntConstraints new_inequalities(res_variables, res_ranges, res_relations);
IntConstraintsTransform transform(inequalities, new_inequalities, res_src_to_dst, res_dst_to_src);
return transform;
}
TVM_REGISTER_GLOBAL("arith.SolveInequalitiesAsCondition")
.set_body([](TVMArgs args, TVMRetValue* ret) {
IntConstraints problem;
PartialSolvedInequalities ret_ineq;
if (args.size() == 1) {
problem = args[0];
ret_ineq = SolveLinearInequalities(problem);
} else if (args.size() == 3) {
problem = IntConstraints(args[0], args[1], args[2]);
ret_ineq = SolveLinearInequalities(problem);
} else {
LOG(FATAL) << "arith.SolveInequalitiesAsCondition expects 1 or 3 arguments, gets "
<< args.size();
}
*ret = AsConditions(problem->variables, ret_ineq.first, ret_ineq.second);
});
TVM_REGISTER_GLOBAL("arith.SolveInequalitiesToRange").set_body([](TVMArgs args, TVMRetValue* ret) {
if (args.size() == 1) {
*ret = SolveInequalitiesToRange(args[0]);
} else if (args.size() == 3) {
IntConstraints problem(args[0], args[1], args[2]);
*ret = SolveInequalitiesToRange(problem);
} else {
LOG(FATAL) << "arith.SolveInequalitiesToRange expects 1 or 3 arguments, gets " << args.size();
}
});
TVM_REGISTER_GLOBAL("arith.SolveInequalitiesDeskewRange")
.set_body([](TVMArgs args, TVMRetValue* ret) {
if (args.size() == 1) {
*ret = SolveInequalitiesDeskewRange(args[0]);
} else if (args.size() == 3) {
IntConstraints problem(args[0], args[1], args[2]);
*ret = SolveInequalitiesDeskewRange(problem);
} else {
LOG(FATAL) << "arith.SolveInequalitiesDeskewRange expects 1 or 3 arguments, gets "
<< args.size();
}
});
} // namespace arith
} // namespace tvm
| 39.094664 | 100 | 0.642291 | [
"vector",
"transform"
] |
6aaea0aa20650004f02d46244203373d6f99fa6d | 899 | cpp | C++ | Sort/49_Group-Anagrams/49_Group-Anagrams.cpp | YunWGui/LeetCode | 2587eca22195ec7d9263227554467ec4010cfe05 | [
"MIT"
] | null | null | null | Sort/49_Group-Anagrams/49_Group-Anagrams.cpp | YunWGui/LeetCode | 2587eca22195ec7d9263227554467ec4010cfe05 | [
"MIT"
] | null | null | null | Sort/49_Group-Anagrams/49_Group-Anagrams.cpp | YunWGui/LeetCode | 2587eca22195ec7d9263227554467ec4010cfe05 | [
"MIT"
] | null | null | null | /******************************************************************************
* Title:
* 49. Group Anagrams
* 49. 字母异位词分组
* Address:
* https://leetcode-cn.com/problems/group-anagrams/
******************************************************************************/
#include <iostream>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;
// 方法一:排序
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
map<string, vector<string>> record;
string key = "";
for ( const string& str : strs ) {
key = str;
sort( key.begin(), key.end() );
record[key].push_back( str );
}
vector<vector<string>> ans;
for ( auto iter : record )
ans.push_back( iter.second );
return ans;
}
};
int main()
{
return 0;
} | 21.926829 | 79 | 0.447164 | [
"vector"
] |
6aafc71676d2a95c7b1accae67ab02c45ead8406 | 6,050 | cpp | C++ | kmsecure.cpp | matteofumagalli1275/kmsecure | 8f86d252e23f5100e17766ea75f516c48ca8b9a5 | [
"MIT"
] | null | null | null | kmsecure.cpp | matteofumagalli1275/kmsecure | 8f86d252e23f5100e17766ea75f516c48ca8b9a5 | [
"MIT"
] | null | null | null | kmsecure.cpp | matteofumagalli1275/kmsecure | 8f86d252e23f5100e17766ea75f516c48ca8b9a5 | [
"MIT"
] | null | null | null | /*
* KMSECURE
* The MIT License (MIT)
* Copyright (c) 2015 Matteo Fumagalli
*/
#include "kmsecure.h"
using namespace std;
kmsecure::kmsecure()
{
kmcrypto = NULL;
}
int kmsecure::get_len_padded_dim(int size)
{
int len8;
uint16_t minblk = kmcrypto->get_minimum_block_size();
int padding_length = size % minblk;
if (padding_length == 0) {
padding_length = minblk;
} else {
padding_length = minblk - padding_length;
}
len8 = size + padding_length;
return len8;
}
kmsecure::kmsecure_error kmsecure::crypt(char** buffer, int &size, kmsecure::kmsecure_info &info)
{
kmsecure_header ash;
int hoff = sizeof(kmsecure_header);
int len8;
char* buffer_dest;
int oldsize;
int px1,px2,tmpsize,tmpsize8;
if(kmcrypto == NULL)
{
printf("\nMUST INITIALIZE KMSECURE WITH KMCRYPTO\n");
return KMSERROR;
}
memcpy(&ash.code,CRYPT_HEADER_CODE,CRYPT_HEADER_CODE_SIZE);
ash.hard = info.hard;
ash.soft_point = info.soft_point;
ash.soft_perc = info.soft_perc;
ash.size_buf = size;
ash.version = KMS_VERSION;
len8 = get_len_padded_dim(size);
if(!info.hard)
{
calc_soft_points(info.soft_point,info.soft_perc,size,&px1,&px2);
tmpsize = px2 - px1;
if(tmpsize > 0)
{
tmpsize8 = get_len_padded_dim(tmpsize);
oldsize = size;
size = hoff + size + (tmpsize8 - tmpsize);
buffer_dest = new char[size];
memcpy(buffer_dest,&ash,hoff);
std::vector<char> buffer_crypted((*buffer + px1),(*buffer + px1) + tmpsize8);
buffer_crypted = kmcrypto->encrypt(buffer_crypted);
char* c_buffer = reinterpret_cast<char*>(buffer_crypted.data());
memcpy((buffer_dest + hoff + px1),c_buffer,buffer_crypted.size());
memcpy(buffer_dest + hoff,*buffer,px1);
memcpy((buffer_dest + hoff + px1) + buffer_crypted.size() ,*buffer + px2,oldsize - px2);
}
else
{
info.hard = 1;
ash.hard = info.hard;
}
}
if(info.hard)
{
buffer_dest = new char[hoff + len8];
memcpy(buffer_dest,&ash,hoff);
std::vector<char> buffer_crypted(*buffer,*buffer + size);
for(int i=0; i < (len8 - size); i++)
buffer_crypted.push_back(0);
buffer_crypted = kmcrypto->encrypt(buffer_crypted);
char* c_buffer = reinterpret_cast<char*>(buffer_crypted.data());
memcpy(buffer_dest + hoff,c_buffer,buffer_crypted.size());
size = len8 + hoff;
}
delete[] *buffer;
*buffer = buffer_dest;
return KMS_NO_ERROR;
}
kmsecure::kmsecure_error kmsecure::decrypt(char** buffer, int &size)
{
bool cryptato = false;
int len8;
char* buffer_dest;
int px1,px2,tmpsize,tmpsize8;
unsigned int total_file_size;
int hoff = sizeof(kmsecure_header);
kmsecure_header ash;
total_file_size = size;
if(total_file_size > sizeof(kmsecure_header))
{
memcpy((char*)&ash,*buffer,sizeof(kmsecure_header));
cryptato = true;
for(int k=0;k<CRYPT_HEADER_CODE_SIZE;k++)
if(ash.code[k] != CRYPT_HEADER_CODE[k])
cryptato = false;
}
else
cryptato = false;
if(cryptato == false)
{
decrypt_last_error = KMS_NO_ERROR_NO_CRYPT;
return KMS_NO_ERROR_NO_CRYPT;
}
if(kmcrypto == NULL)
{
printf("\nMUST INITIALIZE KMSECURE WITH KMCRYPTO\n");
decrypt_last_error = KMSERROR;
return KMSERROR;
}
decrypt_last_info.hard = ash.hard;
decrypt_last_info.soft_perc = ash.soft_perc;
decrypt_last_info.soft_point = ash.soft_point;
buffer_dest = new char[ash.size_buf];
memset(buffer_dest,0,ash.size_buf);
if(!ash.hard)
{
calc_soft_points(ash.soft_point,ash.soft_perc,ash.size_buf,&px1,&px2);
tmpsize = px2 - px1;
size = ash.size_buf;
if(tmpsize > 0)
{
tmpsize8 = get_len_padded_dim(tmpsize);
std::vector<char> buffer_crypt((*buffer + hoff + px1),(*buffer + hoff + px1) + tmpsize8);
buffer_crypt = kmcrypto->decrypt(buffer_crypt);
char* c_buffer = reinterpret_cast<char*>(buffer_crypt.data());
memcpy(buffer_dest,*buffer + hoff,px1);
memcpy(buffer_dest + px2,*buffer + hoff + px1 + tmpsize8,ash.size_buf - px2);
memcpy(buffer_dest + px1,c_buffer,buffer_crypt.size());
}
else
{
decrypt_last_error = KMS_NO_ERROR;
return KMS_NO_ERROR;
}
}
else
{
len8 = get_len_padded_dim(ash.size_buf);
std::vector<char> buffer_crypt(*buffer + hoff,*buffer + hoff + len8);
buffer_crypt = kmcrypto->decrypt(buffer_crypt);
buffer_crypt.resize(ash.size_buf);
char* c_buffer = reinterpret_cast<char*>(buffer_crypt.data());
memcpy(buffer_dest,c_buffer,buffer_crypt.size());
size = ash.size_buf;
}
delete[] *buffer;
*buffer = buffer_dest;
decrypt_last_error = KMS_NO_ERROR;
return KMS_NO_ERROR;
}
void kmsecure::set_crypto(ikmcrypto* kmcrypto)
{
this->kmcrypto = kmcrypto;
}
void kmsecure::calc_soft_points(int soft_point, int soft_perc, int len, int *px1, int *px2)
{
int perc_size = (int)(((float)soft_perc/100) * len);
int _point = (int)(((float)soft_point/100) * len);
int off = 0;
*px1 = _point - perc_size/2;
off = 0;
while(*px1 < 0)
{
*px1 = *px1 + 1;
off++;
}
*px2 = *px1 + ((_point + perc_size) - *px1);
off = 0;
while(*px2 > len)
{
*px2 = *px2 - 1;
off++;
}
*px1-=off;
if(*px1 < 0)
{
printf("file too small to handle this soft crypt");
exit(-99);
}
}
kmsecure::kmsecure_info kmsecure::get_last_decrypted_info()
{
return decrypt_last_info;
}
kmsecure::kmsecure_error kmsecure::get_last_decrypted_error()
{
return decrypt_last_error;
}
| 26.077586 | 101 | 0.605289 | [
"vector"
] |
6ab3e59ffb5731b668f5d8b4e4b921726516e2b3 | 1,499 | cc | C++ | net/ip-encoding_test.cc | iceb0y/trunk | 8d21be238d8478691f947ce1ecf905ac9b75787b | [
"Apache-2.0"
] | 6 | 2019-12-01T00:49:31.000Z | 2020-07-26T07:35:07.000Z | net/ip-encoding_test.cc | iceboy233/trunk | 83024a83f07a587e00a3f2e1906361de521d8f12 | [
"Apache-2.0"
] | null | null | null | net/ip-encoding_test.cc | iceboy233/trunk | 83024a83f07a587e00a3f2e1906361de521d8f12 | [
"Apache-2.0"
] | 1 | 2020-07-26T06:39:30.000Z | 2020-07-26T06:39:30.000Z | #include "net/ip-encoding.h"
#include <vector>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "net/asio.h"
namespace net {
namespace {
using ::testing::ElementsAre;
TEST(IpEncoding, encode) {
std::vector<uint8_t> bytes;
encode(make_address("127.0.0.1"), bytes);
EXPECT_THAT(bytes, ElementsAre(127, 0, 0, 1));
encode(make_address("::1"), bytes);
EXPECT_THAT(
bytes, ElementsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1));
encode(make_address_v4("127.0.0.1"), bytes);
EXPECT_THAT(bytes, ElementsAre(127, 0, 0, 1));
encode(make_address_v6("::1"), bytes);
EXPECT_THAT(
bytes, ElementsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1));
}
TEST(IpEncoding, decode) {
address address;
address_v4 address_v4;
address_v6 address_v6;
ASSERT_TRUE(decode({127, 0, 0, 1}, address));
EXPECT_EQ(address, make_address("127.0.0.1"));
ASSERT_TRUE(decode({127, 0, 0, 1}, address_v4));
EXPECT_EQ(address_v4, make_address_v4("127.0.0.1"));
ASSERT_FALSE(decode({127, 0, 0, 1}, address_v6));
ASSERT_TRUE(decode(
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, address));
EXPECT_EQ(address, make_address("::1"));
ASSERT_FALSE(decode(
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, address_v4));
ASSERT_TRUE(decode(
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, address_v6));
EXPECT_EQ(address_v6, make_address_v6("::1"));
}
} // namespace
} // namespace net
| 31.229167 | 76 | 0.594396 | [
"vector"
] |
6ab88e1c38faa0f9f5740b4a9700265d1b1c96c4 | 451 | cpp | C++ | leetcode/two_sum/leetcode_167.cpp | HuangJingGitHub/PracMakePert_C | 94e570c55d9e391913ccd9c5c72026ab926809b2 | [
"Apache-2.0"
] | null | null | null | leetcode/two_sum/leetcode_167.cpp | HuangJingGitHub/PracMakePert_C | 94e570c55d9e391913ccd9c5c72026ab926809b2 | [
"Apache-2.0"
] | null | null | null | leetcode/two_sum/leetcode_167.cpp | HuangJingGitHub/PracMakePert_C | 94e570c55d9e391913ccd9c5c72026ab926809b2 | [
"Apache-2.0"
] | null | null | null | class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
int left = 0, right = numbers.size() - 1, sum;
while (left < right) {
sum = numbers[left] + numbers[right];
if (sum > target)
right--;
else if (sum < target)
left++;
else
break;
}
return vector<int>{left + 1, right + 1};
}
};
| 25.055556 | 58 | 0.436807 | [
"vector"
] |
6ab945e2fe0de0747bb08699104811e934ebdca4 | 4,513 | hh | C++ | src/PSOEncryption.hh | clint-david/newserv | 40aa08bd4f391d8d3f6d41d3b539de5bc4c5c679 | [
"MIT"
] | null | null | null | src/PSOEncryption.hh | clint-david/newserv | 40aa08bd4f391d8d3f6d41d3b539de5bc4c5c679 | [
"MIT"
] | null | null | null | src/PSOEncryption.hh | clint-david/newserv | 40aa08bd4f391d8d3f6d41d3b539de5bc4c5c679 | [
"MIT"
] | null | null | null | #pragma once
#include <inttypes.h>
#include <stddef.h>
#include <memory>
#include <string>
#include <vector>
#include <phosg/Encoding.hh>
#include "Text.hh" // for parray
#define PC_STREAM_LENGTH 56
#define GC_STREAM_LENGTH 521
#define BB_STREAM_LENGTH 1042
class PSOEncryption {
public:
virtual ~PSOEncryption() = default;
virtual void encrypt(void* data, size_t size, bool advance = true) = 0;
virtual void decrypt(void* data, size_t size, bool advance = true);
inline void encrypt(std::string& data, bool advance = true) {
this->encrypt(data.data(), data.size(), advance);
}
inline void decrypt(std::string& data, bool advance = true) {
this->decrypt(data.data(), data.size(), advance);
}
protected:
PSOEncryption() = default;
};
class PSOPCEncryption : public PSOEncryption {
public:
explicit PSOPCEncryption(uint32_t seed);
virtual void encrypt(void* data, size_t size, bool advance = true);
protected:
void update_stream();
uint32_t next(bool advance = true);
uint32_t stream[PC_STREAM_LENGTH + 1];
uint8_t offset;
};
class PSOGCEncryption : public PSOEncryption {
public:
explicit PSOGCEncryption(uint32_t key);
virtual void encrypt(void* data, size_t size, bool advance = true);
protected:
void update_stream();
uint32_t next(bool advance = true);
uint32_t stream[GC_STREAM_LENGTH];
uint16_t offset;
};
class PSOBBEncryption : public PSOEncryption {
public:
enum Subtype : uint8_t {
STANDARD = 0x00,
MOCB1 = 0x01,
JSD1 = 0x02,
TFS1 = 0x03,
};
struct KeyFile {
// initial_keys are actually a stream of uint32_ts, but we treat them as
// bytes for code simplicity
union InitialKeys {
uint8_t jsd1_stream_offset;
parray<uint8_t, 0x48> as8;
parray<le_uint32_t, 0x12> as32;
InitialKeys() : as32() { }
InitialKeys(const InitialKeys& other) : as32(other.as32) { }
} __attribute__((packed));
union PrivateKeys {
parray<uint8_t, 0x1000> as8;
parray<le_uint32_t, 0x400> as32;
PrivateKeys() : as32() { }
PrivateKeys(const PrivateKeys& other) : as32(other.as32) { }
} __attribute__((packed));
InitialKeys initial_keys;
PrivateKeys private_keys;
Subtype subtype;
} __attribute__((packed));
PSOBBEncryption(const KeyFile& key, const void* seed, size_t seed_size);
virtual void encrypt(void* data, size_t size, bool advance = true);
virtual void decrypt(void* data, size_t size, bool advance = true);
protected:
KeyFile state;
void tfs1_scramble(uint32_t* out1, uint32_t* out2) const;
void apply_seed(const void* original_seed, size_t seed_size);
};
// The following classes provide support for multiple PSOBB private keys, and
// the ability to automatically detect which key the client is using based on
// the first 8 bytes they send.
class PSOBBMultiKeyDetectorEncryption : public PSOEncryption {
public:
PSOBBMultiKeyDetectorEncryption(
const std::vector<std::shared_ptr<const PSOBBEncryption::KeyFile>>& possible_keys,
const std::string& expected_first_data,
const void* seed,
size_t seed_size);
virtual void encrypt(void* data, size_t size, bool advance = true);
virtual void decrypt(void* data, size_t size, bool advance = true);
inline std::shared_ptr<const PSOBBEncryption::KeyFile> get_active_key() const {
return this->active_key;
}
inline const std::string& get_seed() const {
return this->seed;
}
protected:
std::vector<std::shared_ptr<const PSOBBEncryption::KeyFile>> possible_keys;
std::shared_ptr<const PSOBBEncryption::KeyFile> active_key;
std::shared_ptr<PSOBBEncryption> active_crypt;
std::string expected_first_data;
std::string seed;
};
class PSOBBMultiKeyImitatorEncryption : public PSOEncryption {
public:
PSOBBMultiKeyImitatorEncryption(
std::shared_ptr<const PSOBBMultiKeyDetectorEncryption> client_crypt,
const void* seed,
size_t seed_size,
bool jsd1_use_detector_seed);
virtual void encrypt(void* data, size_t size, bool advance = true);
virtual void decrypt(void* data, size_t size, bool advance = true);
protected:
std::shared_ptr<PSOBBEncryption> ensure_crypt();
std::shared_ptr<const PSOBBMultiKeyDetectorEncryption> detector_crypt;
std::shared_ptr<PSOBBEncryption> active_crypt;
std::string seed;
bool jsd1_use_detector_seed;
};
| 28.929487 | 89 | 0.69887 | [
"vector"
] |
6abba4e44f1ae873a04e5029f8bf5cc291210b83 | 5,503 | cpp | C++ | Directx11FPS/Help/Graphic/Base/class.HLSL.cpp | sekys/FPS | d582b6b5fb55adc88b6c4aa6a4cd2145488db31f | [
"MIT"
] | null | null | null | Directx11FPS/Help/Graphic/Base/class.HLSL.cpp | sekys/FPS | d582b6b5fb55adc88b6c4aa6a4cd2145488db31f | [
"MIT"
] | null | null | null | Directx11FPS/Help/Graphic/Base/class.HLSL.cpp | sekys/FPS | d582b6b5fb55adc88b6c4aa6a4cd2145488db31f | [
"MIT"
] | 1 | 2018-03-27T16:02:28.000Z | 2018-03-27T16:02:28.000Z | #include "class.HLSL.h"
#include <fstream>
#include <assert.h>
#include "../../../Global.h"
using namespace Shaders;
using namespace std;
HLSLBase::HLSLBase() {
m_vertexShader = 0;
m_pixelShader = 0;
m_sampleState = 0;
m_layout = 0;
}
HLSLBase::~HLSLBase() {
// Shutdown the vertex and pixel Bases as well as the related objects.
SAFE_RELEASE( m_layout )
SAFE_RELEASE( m_pixelShader )
SAFE_RELEASE( m_vertexShader )
SAFE_RELEASE( m_sampleState )
}
void HLSLBase::InitializeBase(
ID3D10Blob* vertexBaseBuffer,
ID3D10Blob* pixelBaseBuffer,
D3D11_INPUT_ELEMENT_DESC* polygonLayout,
DWORD num
) {
ID3D11Device* device = Direct()->GetDevice();
HRESULT result;
// Create the vertex HLSLBase from the buffer.
result = device->CreateVertexShader(vertexBaseBuffer->GetBufferPointer(), vertexBaseBuffer->GetBufferSize(), NULL, &m_vertexShader);
if(FAILED(result)) {
throw new exception("CreateVertexBase error.");
}
// Create the pixel HLSLBase from the buffer.
result = device->CreatePixelShader(pixelBaseBuffer->GetBufferPointer(), pixelBaseBuffer->GetBufferSize(), NULL, &m_pixelShader);
if(FAILED(result)) {
throw new exception("CreatePixelBase error.");
}
// Create the vertex input layout.
result = device->CreateInputLayout(
polygonLayout, num,
vertexBaseBuffer->GetBufferPointer(),
vertexBaseBuffer->GetBufferSize(),
&m_layout
);
if(FAILED(result)) {
throw new exception("CreateInputLayout error.");
}
// Release the vertex HLSLBase buffer and pixel HLSLBase buffer since they are no longer needed.
SAFE_RELEASE ( vertexBaseBuffer )
SAFE_RELEASE ( pixelBaseBuffer )
}
void HLSLBase::Initialize(
wstring name,
string function,
D3D11_INPUT_ELEMENT_DESC* polygonLayout,
DWORD num
) {
ID3D10Blob* vertexBaseBuffer;
ID3D10Blob* pixelBaseBuffer;
GetBuffersBySimpleName(name, function, &vertexBaseBuffer, &pixelBaseBuffer);
InitializeBase(
vertexBaseBuffer,
pixelBaseBuffer,
polygonLayout,
num
);
}
void HLSLBase::GetBuffersBySimpleName(wstring &name, string &function, ID3D10Blob** vertexBaseBuffer, ID3D10Blob** pixelBaseBuffer) {
wstring filename[2];
filename[0].append(name).append(wstring(L".vs"));
filename[1].append(name).append(wstring(L".ps"));
string functionname[2];
functionname[0].append(function).append("VertexShader");
functionname[1].append(function).append("PixelShader");
*vertexBaseBuffer = Compile(filename[0].c_str(), functionname[0].c_str(), "vs_5_0");
*pixelBaseBuffer = Compile(filename[1].c_str(), functionname[1].c_str(), "ps_5_0");
assert(*vertexBaseBuffer);
assert(*pixelBaseBuffer);
}
void HLSLBase::OutputShaderErrorMessage(ID3D10Blob* errorMessage, const WCHAR* BaseFilename)
{
char* compileErrors;
unsigned long bufferSize, i;
ofstream fout;
// Get a pointer to the error message text buffer.
compileErrors = (char*)(errorMessage->GetBufferPointer());
// Get the length of the message.
bufferSize = errorMessage->GetBufferSize();
// Open a file to write the error message to.
fout.open("HLSLBase-error.txt");
// Write out the error message.
fout << BaseFilename;
fout << endl;
for(i=0; i<bufferSize; i++) {
fout << compileErrors[i];
}
// Close the file.
fout.close();
// Release the error message.
SAFE_RELEASE( errorMessage )
}
void HLSLBase::CreateSamplerState()
{
// Create a texture sampler state description.
D3D11_SAMPLER_DESC samplerDesc;
samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
samplerDesc.MipLODBias = 0.0f;
samplerDesc.MaxAnisotropy = 1;
samplerDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS;
samplerDesc.BorderColor[0] = 0;
samplerDesc.BorderColor[1] = 0;
samplerDesc.BorderColor[2] = 0;
samplerDesc.BorderColor[3] = 0;
samplerDesc.MinLOD = 0;
samplerDesc.MaxLOD = D3D11_FLOAT32_MAX;
// Create the texture sampler state.
assert(m_sampleState == 0);
if(FAILED(Direct()->GetDevice()->CreateSamplerState(&samplerDesc, &m_sampleState) )) {
throw new exception("Error CreateSamplerState.");
}
}
ID3D10Blob* HLSLBase::Compile(const WCHAR* vsFilename, LPCSTR pFunctionName, LPCSTR pProfile) {
// Compile the vertex HLSLBase code.
ID3D10Blob* errorMessage = 0;
ID3D10Blob* BaseBuffer = 0;
if(FAILED( D3DX11CompileFromFile(
vsFilename, NULL, NULL,
pFunctionName, pProfile,
D3D10_SHADER_ENABLE_STRICTNESS, 0, NULL,
&BaseBuffer, &errorMessage, NULL) )
) {
// If the HLSLBase failed to compile it should have writen something to the error message.
if(errorMessage) {
OutputShaderErrorMessage(errorMessage, vsFilename);
throw new exception("Cant compile shader file.");
} else {
// If there was nothing in the error message then it simply could not find the HLSLBase file itself.
throw new exception("Missing shader file.");
}
}
return BaseBuffer;
}
void HLSLBase::Render()
{
ID3D11DeviceContext* deviceContext = Direct()->GetDeviceContext();
// Set the vertex input layout.
assert(m_layout);
deviceContext->IASetInputLayout(m_layout);
// Set the vertex and pixel shader that will be used to render this triangle.
deviceContext->VSSetShader(m_vertexShader, NULL, 0);
deviceContext->PSSetShader(m_pixelShader, NULL, 0);
// Set the sampler state in the pixel HLSLBase.
if(m_sampleState != NULL) {
deviceContext->PSSetSamplers(0, 1, &m_sampleState);
}
}
| 29.427807 | 133 | 0.740869 | [
"render"
] |
6abfc4ccd688e5af665fdbf8ba2d96da973c9999 | 675 | cpp | C++ | SimpleInformationRetrievalTools/SimpleInformationRetrievalTools/StaticQualityScore.cpp | smilenow/Information-Retrieval | 7d4829f4249d95a5aac46f94c9cec819d1f05901 | [
"MIT"
] | null | null | null | SimpleInformationRetrievalTools/SimpleInformationRetrievalTools/StaticQualityScore.cpp | smilenow/Information-Retrieval | 7d4829f4249d95a5aac46f94c9cec819d1f05901 | [
"MIT"
] | null | null | null | SimpleInformationRetrievalTools/SimpleInformationRetrievalTools/StaticQualityScore.cpp | smilenow/Information-Retrieval | 7d4829f4249d95a5aac46f94c9cec819d1f05901 | [
"MIT"
] | null | null | null | //
// StaticQualityScore.cpp
// SimpleInformationRetrievalTools
//
// Created by ryecao on 6/22/15.
// Copyright (c) 2015 Zhendong Cao. All rights reserved.
//
#include <string>
#include <vector>
#include <cmath>
#include <unordered_map>
#include "StaticQualityScore.h"
#include "InvertedIndex.h"
StaticQualityScore::StaticQualityScore(vector<InvertedIndex::InvertedIndexListNode>& inverted_index){
for(auto &l: inverted_index){
for(auto &n: l.value){
if (_scores.find(n.DocID) == _scores.end()){
_scores.insert(make_pair(n.DocID, n.sum));
}
else{
_scores[n.DocID] += n.sum;
}
}
}
for(auto &u: _scores){
u.second = log10(u.second)/10;
}
} | 21.774194 | 101 | 0.688889 | [
"vector"
] |
6ac2b1e472d72bae4533a3662ef4125a836e31c1 | 15,368 | cc | C++ | mysql-server/sql/sql_test.cc | silenc3502/MYSQL-Arch-Doc-Summary | fcc6bb65f72a385b9f56debc9b2c00cee5914bae | [
"MIT"
] | null | null | null | mysql-server/sql/sql_test.cc | silenc3502/MYSQL-Arch-Doc-Summary | fcc6bb65f72a385b9f56debc9b2c00cee5914bae | [
"MIT"
] | null | null | null | mysql-server/sql/sql_test.cc | silenc3502/MYSQL-Arch-Doc-Summary | fcc6bb65f72a385b9f56debc9b2c00cee5914bae | [
"MIT"
] | null | null | null | /* Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2.0,
as published by the Free Software Foundation.
This program is also distributed with certain software (including
but not limited to OpenSSL) that is licensed under separate terms,
as designated in a particular file or component or in included license
documentation. The authors of MySQL hereby grant you an additional
permission to link the program and your derivative works with the
separately licensed software that they have included with MySQL.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License, version 2.0, for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
/* Write some debug info */
#include "my_config.h"
#include <float.h>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <functional>
#include "keycache.h"
#include "lex_string.h"
#include "m_ctype.h"
#include "m_string.h"
#include "my_compiler.h"
#include "my_dbug.h"
#include "my_inttypes.h"
#include "my_io.h"
#include "my_list.h"
#include "my_macros.h"
#include "my_sys.h"
#include "my_thread_local.h"
#include "mysql/psi/mysql_mutex.h"
#include "prealloced_array.h"
#include "sql/events.h"
#include "sql/field.h"
#include "sql/item.h"
#include "sql/key.h"
#include "sql/keycaches.h"
#include "sql/mysqld.h" // LOCK_status
#include "sql/mysqld_thd_manager.h" // Global_THD_manager
#include "sql/opt_explain.h" // join_type_str
#include "sql/opt_range.h" // QUICK_SELECT_I
#include "sql/opt_trace.h"
#include "sql/opt_trace_context.h"
#include "sql/psi_memory_key.h"
#include "sql/sql_bitmap.h"
#include "sql/sql_class.h"
#include "sql/sql_const.h"
#include "sql/sql_opt_exec_shared.h"
#include "sql/sql_optimizer.h" // JOIN
#include "sql/sql_select.h"
#include "sql/sql_show.h" // calc_sum_of_all_status
#include "sql/sql_test.h"
#include "sql/system_variables.h"
#include "sql/table.h"
#include "sql/table_cache.h" // table_cache_manager
#include "sql_string.h"
#if defined(HAVE_MALLOC_INFO) && defined(HAVE_MALLOC_H)
#include <malloc.h>
#endif
const char *lock_descriptions[TL_WRITE_ONLY + 1] = {
/* TL_UNLOCK */ "No lock",
/* TL_READ_DEFAULT */ nullptr,
/* TL_READ */ "Low priority read lock",
/* TL_READ_WITH_SHARED_LOCKS */ "Shared read lock",
/* TL_READ_HIGH_PRIORITY */ "High priority read lock",
/* TL_READ_NO_INSERT */ "Read lock without concurrent inserts",
/* TL_WRITE_ALLOW_WRITE */ "Write lock that allows other writers",
/* TL_WRITE_CONCURRENT_DEFAULT*/ nullptr,
/* TL_WRITE_CONCURRENT_INSERT */ "Concurrent insert lock",
/* TL_WRITE_DEFAULT */ nullptr,
/* TL_WRITE_LOW_PRIORITY */ "Low priority write lock",
/* TL_WRITE */ "High priority write lock",
/* TL_WRITE_ONLY */ "Highest priority write lock"};
#ifndef DBUG_OFF
void print_where(const THD *thd, const Item *cond, const char *info,
enum_query_type query_type) {
char buff[256];
String str(buff, sizeof(buff), system_charset_info);
str.length(0);
if (cond) cond->print(thd, &str, query_type);
str.append('\0');
DBUG_LOCK_FILE;
(void)fprintf(DBUG_FILE, "\nWHERE:(%s) %p ", info, cond);
(void)fputs(str.ptr(), DBUG_FILE);
(void)fputc('\n', DBUG_FILE);
DBUG_UNLOCK_FILE;
}
void TEST_join(JOIN *join) {
uint i, ref;
DBUG_TRACE;
DBUG_ASSERT(!join->join_tab);
/*
Assemble results of all the calls to full_name() first,
in order not to garble the tabular output below.
*/
String ref_key_parts[MAX_TABLES];
for (i = 0; i < join->tables; i++) {
JOIN_TAB *tab = join->best_ref[i];
for (ref = 0; ref < tab->ref().key_parts; ref++) {
ref_key_parts[i].append(tab->ref().items[ref]->full_name());
ref_key_parts[i].append(" ");
}
}
DBUG_LOCK_FILE;
(void)fputs("\nInfo about JOIN\n", DBUG_FILE);
for (i = 0; i < join->tables; i++) {
JOIN_TAB *tab = join->best_ref[i];
TABLE *form = tab->table();
if (!form) continue;
char key_map_buff[128];
fprintf(DBUG_FILE,
"%-16.16s type: %-7s q_keys: %s refs: %d key: %d len: %d\n",
form->alias, join_type_str[tab->type()],
tab->keys().print(key_map_buff), tab->ref().key_parts,
tab->ref().key, tab->ref().key_length);
if (tab->quick()) {
char buf[MAX_KEY / 8 + 1];
if (tab->use_quick == QS_DYNAMIC_RANGE)
fprintf(DBUG_FILE,
" quick select checked for each record (keys: "
"%s)\n",
form->quick_keys.print(buf));
else {
fprintf(DBUG_FILE, " quick select used:\n");
tab->quick()->dbug_dump(18, false);
}
}
if (tab->ref().key_parts) {
fprintf(DBUG_FILE, " refs: %s\n",
ref_key_parts[i].ptr());
}
}
DBUG_UNLOCK_FILE;
}
#endif /* !DBUG_OFF */
void print_keyuse_array(Opt_trace_context *trace,
const Key_use_array *keyuse_array) {
if (unlikely(!trace->is_started())) return;
Opt_trace_object wrapper(trace);
Opt_trace_array trace_key_uses(trace, "ref_optimizer_key_uses");
DBUG_PRINT("opt", ("Key_use array (%zu elements)", keyuse_array->size()));
for (uint i = 0; i < keyuse_array->size(); i++) {
const Key_use &keyuse = keyuse_array->at(i);
// those are too obscure for opt trace
DBUG_PRINT("opt", ("Key_use: optimize= %d used_tables=0x%" PRIx64 " "
"ref_table_rows= %lu keypart_map= %0lx",
keyuse.optimize, keyuse.used_tables,
(ulong)keyuse.ref_table_rows, keyuse.keypart_map));
Opt_trace_object(trace)
.add_utf8_table(keyuse.table_ref)
.add_utf8("field",
(keyuse.keypart == FT_KEYPART)
? "<fulltext>"
: get_field_name_or_expression(
keyuse.table_ref->table->in_use,
keyuse.table_ref->table->key_info[keyuse.key]
.key_part[keyuse.keypart]
.field))
.add("equals", keyuse.val)
.add("null_rejecting", keyuse.null_rejecting);
}
}
#ifndef DBUG_OFF
/* purecov: begin inspected */
/**
Print the current state during query optimization.
@param join pointer to the structure providing all context
info for the query
@param idx length of the partial QEP in 'join->positions'
also an index in the array 'join->best_ref'
@param record_count estimate for the number of records returned by
the best partial plan
@param read_time the cost of the best partial plan.
If a complete plan is printed (join->best_read is
set), this argument is ignored.
@param current_read_time the accumulated cost of the current partial plan
@param info comment string to appear above the printout
@details
This function prints to the log file DBUG_FILE the members of 'join' that
are used during query optimization (join->positions, join->best_positions,
and join->best_ref) and few other related variables (read_time,
record_count).
Useful to trace query optimizer functions.
*/
void print_plan(JOIN *join, uint idx, double record_count, double read_time,
double current_read_time, const char *info) {
uint i;
POSITION pos;
JOIN_TAB *join_table;
JOIN_TAB **plan_nodes;
TABLE *table;
if (info == nullptr) info = "";
DBUG_LOCK_FILE;
if (join->best_read == DBL_MAX) {
fprintf(DBUG_FILE,
"%s; idx: %u best: DBL_MAX atime: %g itime: %g count: %g\n",
info, idx, current_read_time, read_time, record_count);
} else {
fprintf(
DBUG_FILE,
"%s; idx :%u best: %g accumulated: %g increment: %g count: %g\n",
info, idx, join->best_read, current_read_time, read_time, record_count);
}
/* Print the tables in JOIN->positions */
fputs(" POSITIONS: ", DBUG_FILE);
for (i = 0; i < idx; i++) {
pos = join->positions[i];
table = pos.table->table();
if (table) fputs(table->alias, DBUG_FILE);
fputc(' ', DBUG_FILE);
}
fputc('\n', DBUG_FILE);
/*
Print the tables in JOIN->best_positions only if at least one complete plan
has been found. An indicator for this is the value of 'join->best_read'.
*/
if (join->best_read < DBL_MAX) {
fputs("BEST_POSITIONS: ", DBUG_FILE);
for (i = 0; i < idx; i++) {
pos = join->best_positions[i];
table = pos.table->table();
if (table) fputs(table->alias, DBUG_FILE);
fputc(' ', DBUG_FILE);
}
}
fputc('\n', DBUG_FILE);
/* Print the tables in JOIN->best_ref */
fputs(" BEST_REF: ", DBUG_FILE);
for (plan_nodes = join->best_ref; *plan_nodes; plan_nodes++) {
join_table = (*plan_nodes);
fputs(join_table->table()->s->table_name.str, DBUG_FILE);
fprintf(DBUG_FILE, "(%lu,%lu,%lu)", (ulong)join_table->found_records,
(ulong)join_table->records(), (ulong)join_table->read_time);
fputc(' ', DBUG_FILE);
}
fputc('\n', DBUG_FILE);
DBUG_UNLOCK_FILE;
}
#endif /* !DBUG_OFF */
struct TABLE_LOCK_INFO {
my_thread_id thread_id;
char table_name[FN_REFLEN];
bool waiting;
const char *lock_text;
enum thr_lock_type type;
};
typedef Prealloced_array<TABLE_LOCK_INFO, 20> Saved_locks_array;
static inline int dl_compare(const TABLE_LOCK_INFO *a,
const TABLE_LOCK_INFO *b) {
if (a->thread_id > b->thread_id) return 1;
if (a->thread_id < b->thread_id) return -1;
if (a->waiting == b->waiting)
return 0;
else if (a->waiting)
return -1;
return 1;
}
class DL_commpare {
public:
bool operator()(const TABLE_LOCK_INFO &a, const TABLE_LOCK_INFO &b) {
return dl_compare(&a, &b) < 0;
}
};
#ifndef DBUG_OFF
#ifdef EXTRA_DEBUG_DUMP_TABLE_LISTS
/*
A fixed-size FIFO pointer queue that also doesn't allow one to put an
element that has previously been put into it.
There is a hard-coded limit of the total number of queue put operations.
The implementation is trivial and is intended for use in debug dumps only.
*/
template <class T>
class Unique_fifo_queue {
public:
/* Add an element to the queue */
void push_back(T *tbl) {
if (!tbl) return;
// check if we've already scheduled and/or dumped the element
for (int i = 0; i < last; i++) {
if (elems[i] == tbl) return;
}
elems[last++] = tbl;
}
bool pop_first(T **elem) {
if (first < last) {
*elem = elems[first++];
return true;
}
return false;
}
void reset() { first = last = 0; }
enum { MAX_ELEMS = 1000 };
T *elems[MAX_ELEMS];
int first; // First undumped table
int last; // Last undumped element
};
class Dbug_table_list_dumper {
FILE *out;
Unique_fifo_queue<TABLE_LIST> tables_fifo;
Unique_fifo_queue<mem_root_deque<TABLE_LIST *>> tbl_lists;
public:
void dump_one_struct(TABLE_LIST *tbl);
int dump_graph(SELECT_LEX *select_lex, TABLE_LIST *first_leaf);
};
void dump_TABLE_LIST_graph(SELECT_LEX *select_lex, TABLE_LIST *tl) {
Dbug_table_list_dumper dumper;
dumper.dump_graph(select_lex, tl);
}
/*
- Dump one TABLE_LIST objects and its outgoing edges
- Schedule that other objects seen along the edges are dumped too.
*/
void Dbug_table_list_dumper::dump_one_struct(TABLE_LIST *tbl) {
fprintf(out, "\"%p\" [\n", tbl);
fprintf(out, " label = \"%p|", tbl);
fprintf(out, "alias=%s|", tbl->alias ? tbl->alias : "NULL");
fprintf(out, "<next_leaf>next_leaf=%p|", tbl->next_leaf);
fprintf(out, "<next_local>next_local=%p|", tbl->next_local);
fprintf(out, "<next_global>next_global=%p|", tbl->next_global);
fprintf(out, "<embedding>embedding=%p", tbl->embedding);
if (tbl->nested_join)
fprintf(out, "|<nested_j>nested_j=%p", tbl->nested_join);
if (tbl->join_list) fprintf(out, "|<join_list>join_list=%p", tbl->join_list);
if (tbl->on_expr) fprintf(out, "|<on_expr>on_expr=%p", tbl->on_expr);
fprintf(out, "\"\n");
fprintf(out, " shape = \"record\"\n];\n\n");
if (tbl->next_leaf) {
fprintf(out, "\n\"%p\":next_leaf -> \"%p\"[ color = \"#000000\" ];\n", tbl,
tbl->next_leaf);
tables_fifo.push_back(tbl->next_leaf);
}
if (tbl->next_local) {
fprintf(out, "\n\"%p\":next_local -> \"%p\"[ color = \"#404040\" ];\n", tbl,
tbl->next_local);
tables_fifo.push_back(tbl->next_local);
}
if (tbl->next_global) {
fprintf(out, "\n\"%p\":next_global -> \"%p\"[ color = \"#808080\" ];\n",
tbl, tbl->next_global);
tables_fifo.push_back(tbl->next_global);
}
if (tbl->embedding) {
fprintf(out, "\n\"%p\":embedding -> \"%p\"[ color = \"#FF0000\" ];\n", tbl,
tbl->embedding);
tables_fifo.push_back(tbl->embedding);
}
if (tbl->join_list) {
fprintf(out, "\n\"%p\":join_list -> \"%p\"[ color = \"#0000FF\" ];\n", tbl,
tbl->join_list);
tbl_lists.push_back(tbl->join_list);
}
}
int Dbug_table_list_dumper::dump_graph(SELECT_LEX *select_lex,
TABLE_LIST *first_leaf) {
DBUG_TRACE;
char filename[500];
int no = 0;
do {
sprintf(filename, "tlist_tree%.3d.g", no);
if ((out = fopen(filename, "rt"))) {
/* File exists, try next name */
fclose(out);
}
no++;
} while (out);
/* Ok, found an unoccupied name, create the file */
if (!(out = fopen(filename, "wt"))) {
DBUG_PRINT("tree_dump", ("Failed to create output file"));
return 1;
}
DBUG_PRINT("tree_dump", ("dumping tree to %s", filename));
fputs("digraph g {\n", out);
fputs("graph [", out);
fputs(" rankdir = \"LR\"", out);
fputs("];", out);
TABLE_LIST *tbl;
tables_fifo.reset();
dump_one_struct(first_leaf);
while (tables_fifo.pop_first(&tbl)) {
dump_one_struct(tbl);
}
mem_root_deque<TABLE_LIST *> *plist;
tbl_lists.push_back(&select_lex->top_join_list);
while (tbl_lists.pop_first(&plist)) {
fprintf(out, "\"%p\" [\n", plist);
fprintf(out, " bgcolor = \"\"");
fprintf(out, " label = \"L %p\"", plist);
fprintf(out, " shape = \"record\"\n];\n\n");
}
fprintf(out, " { rank = same; ");
for (TABLE_LIST *tl = first_leaf; tl; tl = tl->next_leaf)
fprintf(out, " \"%p\"; ", tl);
fprintf(out, "};\n");
fputs("}", out);
fclose(out);
char filename2[500];
filename[strlen(filename) - 1] = 0;
filename[strlen(filename) - 1] = 0;
sprintf(filename2, "%s.query", filename);
if ((out = fopen(filename2, "wt"))) {
// fprintf(out, "%s", current_thd->query);
fclose(out);
}
return 0;
}
#endif
#endif
| 32.353684 | 80 | 0.626236 | [
"shape",
"3d"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.