blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
264
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
85
| license_type
stringclasses 2
values | repo_name
stringlengths 5
140
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 905
values | visit_date
timestamp[us]date 2015-08-09 11:21:18
2023-09-06 10:45:07
| revision_date
timestamp[us]date 1997-09-14 05:04:47
2023-09-17 19:19:19
| committer_date
timestamp[us]date 1997-09-14 05:04:47
2023-09-06 06:22:19
| github_id
int64 3.89k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us]date 2012-06-07 00:51:45
2023-09-14 21:58:39
⌀ | gha_created_at
timestamp[us]date 2008-03-27 23:40:48
2023-08-21 23:17:38
⌀ | gha_language
stringclasses 141
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 3
10.4M
| extension
stringclasses 115
values | content
stringlengths 3
10.4M
| authors
listlengths 1
1
| author_id
stringlengths 0
158
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
13cca4f117905cee9ceb7d72f76da2720576b4b4
|
f9295f2334603c2f5d509bd02e51bd0f5c12a253
|
/Training/UCO-Training-24-09-2014/Solutions/source/Tree.cpp
|
6670d152a8f552cadc310607d39486e474489923
|
[
"MIT"
] |
permissive
|
Nagy00/Contests
|
d622117ec291cf1d49d8b5b60bbd29f7d22c25cf
|
cedd31b7dd84e1b9790eddf5d655f8e48c80b765
|
refs/heads/master
| 2021-06-04T12:58:44.311117
| 2016-09-20T19:00:43
| 2016-09-20T19:00:43
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,469
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
typedef pair<int,int> node;
const int MAXN = 5055;
const int INF = 1 << 30;
int n;
vector<node> g[MAXN];
int d[MAXN];
int p[MAXN];
void ini()
{
for(int i = 0; i < MAXN; ++i)g[i].clear();
memset(d, 0, sizeof d);
memset(p, 0, sizeof p);
}
int bfs(int s, int first)
{
bool ex [MAXN];
for(int i = 0; i < s; ++i){
d[i] = -INF; p[i] = -1;ex[i]=false;
}
d[0] = first;
queue<int> q;
q.push(0);
while(!q.empty()){
int cur = q.front();
q.pop();
if(ex[cur] == true)continue;
for(int i = 0; i < g[cur].size(); ++i){
int v = g[cur][i].first;
// cout<<"from: "<<cur<<" to "<<v<<endl;
int dist = d[cur]+g[cur][i].second;
q.push(v);
if(d[v] < dist){
d[v] = dist;
p[v] = cur;
}
}
ex[cur] = true;
}
int pos = -1, vmax = -INF;
for(int i = 0; i < s; ++i){
// cout<<d[i]<<endl;
if(d[i] > vmax){pos = i; vmax = d[i];}
}
return pos;
}
void contruct_graph(vector<int> values)
{
int j = 1;
for(int i = 0; i < values.size()-n; ++i){
// cout<<values[i*j+1]<<endl;
g[i].push_back(node(i+j,values[i+j]));
//cout<<i*j+1 << " " << i*j+1<<endl;
g[i].push_back(node(i+j+1,values[i+j+1]));
if((j)*(j+1)/2 == i+1)j++;
}
}
long long int reconstruct(int pr, int first)
{
//cout<<"recon:"<<endl;
long long int sol = first;
int pant = pr;
pr = p[pr];
while(pr != -1){
int v;
if(g[pr][0].first == pant)
v = g[pr][0].second;
else
v = g[pr][1].second;
// cout<<pr<<endl;
sol += (v*v);
pant = pr;
pr = p[pr];
}
return sol;
}
int main()
{
while(cin >> n){
ini();
string l; getline(cin,l);getline(cin,l);int k;
stringstream ss(l);
vector<int> values;
while(ss >> k)values.push_back(k);
//for(int i = 0; i < values.size(); ++i)cout<<values[i]<<endl;
contruct_graph(values);//cout<<"paso";
int pos = bfs(values.size(),values[0]);
// cout<<pos<<endl;
long long int solv = reconstruct(pos, values[0]*values[0]);
char a1 = 'a'+d[pos]%26;
char a2 = 'a'+solv%26;
cout << solv << " " << d[pos] <<"\n";
cout << a2 << a1 <<"\n";
}
return 0;
}
|
[
"dacanizares@outlook.com"
] |
dacanizares@outlook.com
|
9948c980df219658c4ba967ba6332e409d1bcb82
|
8a018cf4109855c16bcec9bec1cb76b0d6ff53f3
|
/gui/geometry.h
|
30cb3fd973b9ae82be96ea21763a7969c2e52857
|
[] |
no_license
|
marsin/TopOptim
|
2853630e9177b5ee5c7954ad194055fce6f15a5f
|
93905fd49f1d124b1e746d3f59bab549042e6b62
|
refs/heads/master
| 2021-01-22T09:16:49.168334
| 2015-03-19T20:41:07
| 2015-03-19T20:41:07
| 12,683,547
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 649
|
h
|
#ifndef GEOMETRY_H
#define GEOMETRY_H
#include <QGLFunctions>
#include <QGLShaderProgram>
#include "part.h"
#include "model.h"
struct SmModelDrawSettings
{
bool drawFaces;
bool drawBorderLines;
bool drawBCs;
bool drawLoads;
bool drawVertices;
};
class CmGeometry : protected QGLFunctions
{
public:
CmGeometry();
virtual ~CmGeometry();
void init(const CmModelp& model, const SmModelDrawSettings &settings);
void drawGeometry();
private:
void initModelGeometry();
CmModelp m_model;
SmModelDrawSettings m_settings;
GLuint m_vboIds[2];
};
typedef boost::shared_ptr<CmGeometry> CmGeometryp;
#endif // GEOMETRY_H
|
[
"marcin.szc1@gmail.com"
] |
marcin.szc1@gmail.com
|
076734bc516719db865079fa27607334e79fa5db
|
42ff9c702e19ecc8f6b6905eb51f2f4832e2ba9f
|
/src/qt/signverifymessagedialog.h
|
b6ed13ef5165a5a6bc5757221da7662d76580b33
|
[
"MIT"
] |
permissive
|
jgeofil/stakinglab-coin
|
1abb409c0bba5c43ce3a58983441a4ae2d619c9f
|
7f7c70590e85882deef15ad4c26940f24953d385
|
refs/heads/master
| 2022-11-05T16:11:01.140229
| 2020-06-29T18:29:45
| 2020-06-29T18:29:45
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,367
|
h
|
// Copyright (c) 2011-2013 The Bitcoin developers
// Copyright (c) 2017 The LABX developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_QT_SIGNVERIFYMESSAGEDIALOG_H
#define BITCOIN_QT_SIGNVERIFYMESSAGEDIALOG_H
#include <QDialog>
class WalletModel;
namespace Ui
{
class SignVerifyMessageDialog;
}
class SignVerifyMessageDialog : public QDialog
{
Q_OBJECT
public:
explicit SignVerifyMessageDialog(QWidget* parent);
~SignVerifyMessageDialog();
void setModel(WalletModel* model);
void setAddress_SM(const QString& address);
void setAddress_VM(const QString& address);
void showTab_SM(bool fShow);
void showTab_VM(bool fShow);
protected:
bool eventFilter(QObject* object, QEvent* event);
private:
Ui::SignVerifyMessageDialog* ui;
WalletModel* model;
private slots:
/* sign message */
void on_addressBookButton_SM_clicked();
void on_pasteButton_SM_clicked();
void on_signMessageButton_SM_clicked();
void on_copySignatureButton_SM_clicked();
void on_clearButton_SM_clicked();
/* verify message */
void on_addressBookButton_VM_clicked();
void on_verifyMessageButton_VM_clicked();
void on_clearButton_VM_clicked();
};
#endif // BITCOIN_QT_SIGNVERIFYMESSAGEDIALOG_H
|
[
"codemaster@stakinglab.io"
] |
codemaster@stakinglab.io
|
00b3baa1116b9c5b86259b86fe343f2775f26aea
|
a36ba55ab5620141b44c636164f8d4eb096c9b85
|
/mongotest/mongocxx/client.cpp
|
4ed3e91609db45aae33e64ec07ec337e96fb2fe3
|
[] |
no_license
|
warriorZH/sparkLearn
|
802bdc23c97a29dd3e6eff5f7287c0222c2b4c04
|
c0c9a2371b451b81c3d32e3fcaebf2f22a7c0e21
|
refs/heads/master
| 2021-01-17T10:43:53.823983
| 2016-03-29T12:43:18
| 2016-03-29T12:43:18
| 39,718,616
| 0
| 1
| null | 2020-07-23T14:21:00
| 2015-07-26T08:13:45
|
Scala
|
UTF-8
|
C++
| false
| false
| 4,399
|
cpp
|
// Copyright 2014 MongoDB 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 <mongocxx/config/prelude.hpp>
#include <mongocxx/client.hpp>
#include <bsoncxx/stdx/make_unique.hpp>
#include <mongocxx/exception/error_code.hpp>
#include <mongocxx/exception/logic_error.hpp>
#include <mongocxx/exception/operation_exception.hpp>
#include <mongocxx/exception/private/error_category.hpp>
#include <mongocxx/exception/private/error_code.hpp>
#include <mongocxx/exception/private/mongoc_error.hpp>
#include <mongocxx/private/client.hpp>
#include <mongocxx/private/read_concern.hpp>
#include <mongocxx/private/read_preference.hpp>
#include <mongocxx/private/ssl.hpp>
#include <mongocxx/private/uri.hpp>
#include <mongocxx/private/write_concern.hpp>
namespace mongocxx {
MONGOCXX_INLINE_NAMESPACE_BEGIN
client::client() noexcept = default;
client::client(const class uri& uri, const options::client& options)
: _impl(stdx::make_unique<impl>(libmongoc::client_new_from_uri(uri._impl->uri_t))) {
if (options.ssl_opts()) {
#if defined(MONGOC_HAVE_SSL)
auto mongoc_opts = options::make_ssl_opts(*options.ssl_opts());
libmongoc::client_set_ssl_opts(_get_impl().client_t, &mongoc_opts);
#else
// TODO: For now, just ignoring. Should we throw?
#endif
}
}
client::client(void* implementation)
: _impl{stdx::make_unique<impl>(static_cast<::mongoc_client_t*>(implementation))} {
}
client::client(client&&) noexcept = default;
client& client::operator=(client&&) noexcept = default;
client::~client() = default;
client::operator bool() const noexcept {
return static_cast<bool>(_impl);
}
void* client::implementation() const {
return _get_impl().client_t;
}
void client::read_concern(class read_concern rc) {
libmongoc::client_set_read_concern(_get_impl().client_t, rc._impl->read_concern_t);
}
stdx::optional<class read_concern> client::read_concern() const {
auto rc = libmongoc::client_get_read_concern(_get_impl().client_t);
if (!libmongoc::read_concern_get_level(rc)) {
return stdx::nullopt;
}
return {
stdx::make_unique<read_concern::impl>(libmongoc::read_concern_copy(rc))};
}
void client::read_preference(class read_preference rp) {
libmongoc::client_set_read_prefs(_get_impl().client_t, rp._impl->read_preference_t);
}
class read_preference client::read_preference() const {
class read_preference rp(stdx::make_unique<read_preference::impl>(
libmongoc::read_prefs_copy(libmongoc::client_get_read_prefs(_get_impl().client_t))));
return rp;
}
class uri client::uri() const {
class uri connection_string(stdx::make_unique<uri::impl>(
libmongoc::uri_copy(libmongoc::client_get_uri(_get_impl().client_t))));
return connection_string;
}
void client::write_concern(class write_concern wc) {
libmongoc::client_set_write_concern(_get_impl().client_t, wc._impl->write_concern_t);
}
class write_concern client::write_concern() const {
class write_concern wc(stdx::make_unique<write_concern::impl>(
libmongoc::write_concern_copy(libmongoc::client_get_write_concern(_get_impl().client_t))));
return wc;
}
class database client::database(stdx::string_view name) const & {
return mongocxx::database(*this, name);
}
cursor client::list_databases() const {
bson_error_t error;
auto result = libmongoc::client_find_databases(_get_impl().client_t, &error);
if (!result) {
throw_exception<operation_exception>(error);
}
return cursor(result);
}
const client::impl& client::_get_impl() const {
if(!_impl) {
throw logic_error{make_error_code(error_code::k_invalid_client_object)};
}
return *_impl;
}
client::impl& client::_get_impl() {
auto cthis = const_cast<const client*>(this);
return const_cast<client::impl&>(cthis->_get_impl());
}
MONGOCXX_INLINE_NAMESPACE_END
} // namespace mongocxx
|
[
"zhangpeihua123@gmail.com"
] |
zhangpeihua123@gmail.com
|
e1ac9b26c125acc660cd9d11a50a5f4aa77ac73a
|
647b91b86512cc8255c1fbf892f471aeb0050bb0
|
/food.cpp
|
fb020d66b358f427642716b7ea4589feedc038b7
|
[] |
no_license
|
ainitian/snake
|
63e41d5856763a671e3b697b461a4c5f4300876e
|
fb76ed801170dcbf52b4fcccae4b3183f335a530
|
refs/heads/master
| 2023-03-10T04:28:56.827448
| 2021-03-01T08:16:45
| 2021-03-01T08:16:45
| 343,347,628
| 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 513
|
cpp
|
#include "pch.h"
#include "food.h"
//#include<ctime>
//const int N = 60;
//int m[N][N];
food::food()
{
}
void food::createPos()//随机生成食物
{
//srand(int(time(0))); //种子函数
//do {
// dx = rand() % 20 + 1;
// dy = rand() % 20 + 1;
//} while (m[dx][dy] != ' ');
//m[dx][dy] = '*';
//todo;
//m_x = randromNum();
//m_y = randromNum();
srand((int)time(0));
m_x = KLEFT + 1 + rand() % (KWIDTH - 4);//左右区间
m_y = KUP + 3 + rand() % (KHEIGHT - 8);//上下区间
}
food::~food()
{
}
|
[
"386439312@qq.com"
] |
386439312@qq.com
|
d659d27c806c8bd6a4c4d5f579cc69f42400c4be
|
a669a391675a72eb7c3bcb3aa0311b41f4f46309
|
/DecimalToBinaryRightToLeft.cpp
|
5e5baf2c729d2940421d16dd90f2e90974837be5
|
[] |
no_license
|
abill001/EE1301
|
2171135df60bb81b604166cfe9fddbbc9c944075
|
d165f4e4127b5ca34d961c6e1718553799ae7915
|
refs/heads/master
| 2021-01-12T12:27:47.073761
| 2016-11-01T04:45:40
| 2016-11-01T04:45:40
| 72,502,220
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,030
|
cpp
|
// HW3.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int decimal, maxpower = 0;
cout << "Please input an integer number (Will work for numbers with max 8 digits, some with 9 digits and 10 digits) : " << endl;
cin >> decimal;
//This while loop is handy in the sense that it helps me determine the number of digits my binary number will have based on the minimum power of 2 that is greater than the number of given
// For example, if the decimal given is 15, then maxpower is 4 because 2^4 = 16 > 15
while (decimal - pow(2, maxpower) > 0) {
maxpower++;
}
// For binary numbers, the first digit alternates between 0 and 1 with a period of 2
// The second digit alternates between 0 and 1 with a period of 2^2
// The third digit alternates between 0 and 1 with a period of 2^3 ... and so on
// This is what I used to convert the number to binary, I divided the number by increments of power of 2 starting with 2^1, if the remainder is in the lower bound (between 0 and (power of 2)/2), then the corresponding digit is 0, otherwise 1
for (int counter = 1; counter <= maxpower + 1; counter++) {
int remainder = decimal % (int)pow(2, counter);
//If we write binary numbers in ascending order, we notice a patern : For the first digit (0,1,0,1,0,1 ...) - For the second digit (0,0,1,1,0,0,1,1 ...) and so on. This can be written as the following
if (remainder >= (int)pow(2, counter) / 2 && remainder < (int)pow(2, counter)) {
cout << 1 << endl;
}
else if (remainder >= 0 && remainder < (int)pow(2, counter) / 2) {
//This if statement is to take into account the fact that when counter reaches maxpower + 1, remainder will always be the number itself and will be in the lower bound and we do not need an extra 0
if (counter != maxpower + 1)
cout << 0 << endl;
}
}
/*
while (number > 0)
{
cout << number % 2 << endl;
number /= 2;
}
*/
return 0;
}
|
[
"abill001@umn.edu"
] |
abill001@umn.edu
|
88750df6ec52c1fe2d3a9f87e4611419a7e1ab42
|
0c73dce630eb026b00cde2f79d68f23a5821cdf0
|
/arduino/roll_and_motor/roll_and_motor.ino
|
606db000bc48c4e5db0744999d9ac969d2ee9f7f
|
[
"MIT"
] |
permissive
|
magnusoy/SelfBalancingRobot
|
ec38c03037c8fbcd9d8230fceb87fa2695e9ac8a
|
38c89c9a86ee1792cf0b0504d1fd32fdce69a2fa
|
refs/heads/master
| 2020-05-03T16:57:01.004968
| 2019-04-29T15:58:47
| 2019-04-29T15:58:47
| 178,735,230
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,881
|
ino
|
#include <SoftwareSerial.h>
#include <Wire.h>
#include <SPI.h>
#include <SparkFunLSM9DS1.h>
#include <MedianFilter.h>
#include "RoboClaw.h"
//See limitations of Arduino SoftwareSerial
SoftwareSerial serial(10, 11);
RoboClaw roboclaw(&serial, 10000);
LSM9DS1 imu;
MedianFilter filterAy(61, 0);
MedianFilter filterAz(61, 0);
#define LSM9DS1_M 0x1E
#define LSM9DS1_AG 0x6B
#define address 0x80
// Defining global variables for recieving data
boolean newData = false;
const byte numChars = 16;
char receivedChars[numChars]; // An array to store the received data
int speedM1;
int speedM2;
void setup() {
//Open roboclaw serial ports
roboclaw.begin(38400);
Serial.begin(115200);
imu.settings.device.commInterface = IMU_MODE_I2C;
imu.settings.device.mAddress = LSM9DS1_M;
imu.settings.device.agAddress = LSM9DS1_AG;
imu.begin();
}
void loop() {
readStringFromSerial();
if (newData) {
speedM1 = getValueFromSerial(receivedChars, ',', 0).toInt();
speedM2 = getValueFromSerial(receivedChars, ',', 1).toInt();
newData = false;
}
if (imu.accelAvailable()) {
imu.readAccel();
}
float roll = calculateRoll(imu.ay, imu.az);
Serial.println(roll, 2);
}
/**
docstring
*/
float calculateRoll(int ay_, int az_) {
float ayFiltered = filterAy.in(ay_);
float azFiltered = filterAz.in(az_);
float roll = atan2(ayFiltered, azFiltered);
roll *= 180.0 / PI;
return roll;
}
/**
Drive motor 1 forward with the given speed.
0 = stop
64 = middle forward
127 = full forward
@param speed, 0 - 127
*/
void driveMotor1Forward(int speed_) {
roboclaw.ForwardM1(address, speed_);
}
/**
Drive motor 2 forward with the given speed.
0 = stop
64 = middle forward
127 = full forward
@param speed, 0 - 127
*/
void driveMotor2Forward(int speed_) {
roboclaw.ForwardM2(address, speed_);
}
/**
Drive motor 1 backward with the given speed.
0 = stop
64 = middle backward
127 = full backward
@param speed, 0 - 127
*/
void driveMotor1Backward(int speed_) {
roboclaw.BackwardM1(address, speed_);
}
/**
Drive motor 1 backward with the given speed.
0 = stop
64 = middle backward
127 = full backward
@param speed, 0 - 127
*/
void driveMotor2Backward(int speed_) {
roboclaw.BackwardM2(address, speed_);
}
/**
Drive motor 1 both directions with the given speed.
0 = full backward
64 = stop
127 = full forward
@param speed, 0 - 127
*/
void driveMotor1(int speed_) {
roboclaw.ForwardBackwardM1(address, speed_);
}
/**
Drive motor 2 both directions with the given speed.
0 = full backward
64 = stop
127 = full forward
@param speed, 0 - 127
*/
void driveMotor2(int speed_) {
roboclaw.ForwardBackwardM2(address, speed_);
}
/**
Reads a string from Serial Monitor.
*/
void readStringFromSerial() {
static byte ndx = 0;
char endMarker = '\n';
char rc;
while ((Serial.available() > 0) && (!newData)) {
rc = Serial.read();
if (rc != endMarker) {
receivedChars[ndx] = rc;
ndx++;
if (ndx >= numChars) {
ndx = numChars - 1;
}
} else {
receivedChars[ndx] = '\0'; // Terminate the string
ndx = 0;
newData = true;
}
}
}
/**
Fetches the value from a substring,
wich is seperated with a given symbol.
@param data your String to be seperated
@param seperator your symbol to seperate by
@param index where your value is located
@return substring before seperator
*/
String getValueFromSerial(String data, char separator, int index) {
int found = 0;
int strIndex[] = { 0, -1 };
int maxIndex = data.length() - 1;
for (int i = 0; i <= maxIndex && found <= index; i++) {
if (data.charAt(i) == separator || i == maxIndex) {
found++;
strIndex[1] = (i == maxIndex) ? i + 1 : i;
}
}
strIndex[0] = strIndex[1] + 1;
return found > index ? data.substring(strIndex[0], strIndex[1]) : "";
}
|
[
"magnus.oye@gmail.com"
] |
magnus.oye@gmail.com
|
d3f51b582d6660150c204fd4b70b9189e89723dc
|
0fb1d67765ee836b0c477693660225de2bad3053
|
/Source/SProject/PreloadContentInterface.h
|
982b5e29b555e527f99f976534585dd103b25304
|
[] |
no_license
|
yohan7979/SProject
|
94d6e62b3dce83b7df66ef4475c6091b39d28b26
|
624b8dd1358ddb5b35971f39f5a5307a646bd986
|
refs/heads/master
| 2020-04-23T22:08:45.824572
| 2019-11-25T15:11:38
| 2019-11-25T15:11:38
| 171,491,549
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,693
|
h
|
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "UObject/Interface.h"
#include "PreloadContentInterface.generated.h"
struct FPreloadInfo
{
FSoftObjectPath Path;
bool bIsClass;
FPreloadInfo(const FSoftObjectPath& InPath, bool bInIsClass)
: Path(InPath)
, bIsClass(bInIsClass)
{}
bool operator==(const FPreloadInfo& Other)
{
return Path == Other.Path && bIsClass == Other.bIsClass;
}
friend bool operator==(const FPreloadInfo& lhs, const FPreloadInfo& rhs)
{
return lhs.Path == rhs.Path && lhs.bIsClass == rhs.bIsClass;
}
};
struct FPreloadContentContainer
{
template<class TClass = UObject>
void Add(TSoftObjectPtr<TClass> SoftObjectPtr)
{
const FSoftObjectPath& SoftObjectPath = SoftObjectPtr.ToSoftObjectPath();
if (SoftObjectPath.IsValid())
{
FPreloadInfo PreloadInfo(SoftObjectPath, false);
PreloadList.AddUnique(PreloadInfo);
}
}
template<class TClass = UObject>
void Add(TSoftClassPtr<TClass> SoftClassPtr)
{
const FSoftObjectPath& SoftObjectPath = SoftClassPtr.ToSoftObjectPath();
if (SoftObjectPath.IsValid())
{
FPreloadInfo PreloadInfo(SoftObjectPath, true);
PreloadList.AddUnique(PreloadInfo);
}
}
FPreloadContentContainer()
: PreloadList()
{
}
virtual ~FPreloadContentContainer()
{
PreloadList.Empty();
}
TArray<FPreloadInfo> PreloadList;
};
UINTERFACE()
class UPreloadContentInterface : public UInterface
{
GENERATED_UINTERFACE_BODY()
};
class SPROJECT_API IPreloadContentInterface
{
GENERATED_IINTERFACE_BODY()
public:
virtual void AddPreloadContent(FPreloadContentContainer& Collector, bool bIsDedicateServer) = 0;
};
|
[
"twiclok@naver.com"
] |
twiclok@naver.com
|
4a473127aeb965f46a073a456b6243315bd67bea
|
6315430cc7b7d8bf65b0892325b70162d4bfa021
|
/lib/platform/sensors/SharpDistSensor/SharpDistSensor.h
|
bf59b1fef6a2db8c85c6175f625842bfb50cf992
|
[
"MIT"
] |
permissive
|
margrevm/trollbot
|
ccc4d94575a5856fcb2ff3e2e07b3de7ed14b202
|
78e8bb4c3ca10f49aab2a1bb7363beef98802448
|
refs/heads/dev
| 2023-05-01T22:25:13.882223
| 2021-05-13T17:38:21
| 2021-05-13T17:38:21
| 256,733,740
| 1
| 0
|
MIT
| 2021-04-24T16:41:21
| 2020-04-18T11:15:07
|
C++
|
UTF-8
|
C++
| false
| false
| 5,527
|
h
|
/*
SharpDistSensor.h
Source: https://github.com/DrGFreeman/SharpDistSensor
MIT License
Original work Copyright (c) 2018 Julien de la Bruere-Terreault <drgfreeman@tuta.io>
Modified work Copyright 2020 Mike Margreve
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.
*/
/*
SharpDistSensor; Sharp analog distance sensor library
This is a library for the Arduino IDE that helps interface with Sharp IR analog
distance sensors.
The analog value from the sensor is converted to distance using either a fifth
order polynomial fit function or a power fit function.
By default, this library is set to use polynomial coefficients calibrated for
the Sharp GP2Y0A60SZLF Analog Distance Sensor 10-150cm 5V, over a range of
50-1500 mm (analog values 30-875). The returned distance is in millimeters (mm)
units. For different accuracy, range, sensor model or units, different
coefficients may be required.
Use the setModel method to change the sensor model calibration. The following
models are currently supported:
-GP2Y0A60SZLF_5V (GP2Y0A60SZLF Analog Distance Sensor 10-150cm, 5V)
-GP2Y0A710K0F_5V_DS (GP2Y0A710K0F Analog Distance Sensor 100-500cm, 5V)
Use the setPolyFitCoeffs method to define custom polynomial coefficients.
Use the setPowerFitCoeffs method to define custom power coefficients.
Use the setValMinMax method to define different analog values range.
The distance output is filtered using median filtering. MedianFilter class from
the following library is used: https://github.com/daPhoosa/MedianFilter.
*/
#ifndef SharpDistSensor_h
#define SharpDistSensor_h
#include <Arduino.h>
#include <MedianFilter.h>
#define SHARP_INITIAL_SEED_MEDIAN_FILTER 0
class SharpDistSensor
{
public:
// List of pre-defined sensor models
enum models
{
// Constant for GP2Y0A60SZLF 5V model
GP2Y0A60SZLF_5V,
// Constant for GP2Y0A710K0F 5V model
GP2Y0A710K0F_5V_DS,
// Constant for GP2Y0A51SK0F 5V model
GP2Y0A51SK0F_5V_DS,
// Constant for GP2Y0A41SK0F 5V model
GP2Y0A41SK0F_5V_DS,
// Constant for GP2Y0A21SK0f 5V model (range 10 - 80 cm)
GP2Y0A21SK0F_5V_DS
};
/** Constructor
pin: Arduino analog pin the sensor is connected to
size: Window size of the median filter (1 = no filtering)
**/
SharpDistSensor(const byte pin, const byte size = 1);
// Return the measured distance
uint16_t getDist();
// Set the sensor model
void setModel(const models model);
/* Set the polynomial fit function coefficients and range to apply on the analog value read by the Arduino (10 bit value)
nbCoeffs: Number of coefficients (1 min, 6 max)
coeffs: Coefficients (x^0 to x^5)
valMin: Minimal analog value for which to return a distance
valMax: Maximal analog value for which to return a distance
*/
void setPolyFitCoeffs(const byte nbCoeffs, const float* coeffs,
const uint16_t valMin, const uint16_t valMax);
/* Set the polynomial fit function coefficients and range to apply on a value given in Volt.
nbCoeffs: Number of coefficients (1 min, 6 max)
coeffs: Coefficients (x^0 to x^5)
valMin: Minimal analog value for which to return a distance
valMax: Maximal analog value for which to return a distance
*/
void setPolyFitCoeffsVolt(const byte nbCoeffs, const float* coeffs,
const float valMin, const float valMax);
/* Set the power fit function coefficients and range
C and P: Coefficients in Distance = C*x^P relation
valMin: Minimal analog value for which to return a distance
valMax: Maximal analog value for which to return a distance
*/
void setPowerFitCoeffs(const float C, const float P,
const uint16_t valMin, const uint16_t valMax);
// Set the analog value range for which to return a distance
void setValMinMax(const float valMin, const float valMax);
private:
// Arduino analog pin the sensor is connected to
byte _pin;
// Window size of the median filter (1 = no filtering)
byte _mfSize;
// Minimal analog value for which to return a distance
float _valMin;
// Maximal analog value for which to return a distance
float _valMax;
// Polynomial function coefficients to convert analog signal to distance
float _polyCoeffs[6];
// Power function coefficients to convert analog signal to distance
float _powerCoeffC;
float _powerCoeffP;
// Possible types of fit functions
enum fitTypes
{
FIT_POLY,
FIT_POLY_VOLT,
FIT_POWER
};
// Fit function type used
fitTypes _fitType;
// Median filter object instance
MedianFilter medFilt;
};
#endif
|
[
"mike.margreve@outlook.com"
] |
mike.margreve@outlook.com
|
3ee25b62234bc5968eefb3a4cfd81dafb2f3c331
|
dd6a2afb3ac2ee0a7bea7c6059674e0b33819be2
|
/Tank.h
|
3b2facd73909066d46ec079601db2ca1b4bd621b
|
[] |
no_license
|
bencherifdiego/pp2.2
|
a2faadbdb6f8562637e97fe1da57fcb7550a835c
|
b5eb37ff78a030daba225307999bd037ebbafd42
|
refs/heads/master
| 2021-03-18T05:02:10.476851
| 2020-03-13T12:16:09
| 2020-03-13T12:16:09
| 247,048,021
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,137
|
h
|
#pragma once
namespace Tmpl8
{
class grid;
enum allignments
{
BLUE,
RED
};
class Tank
{
public:
Tank(float pos_x, float pos_y, allignments allignment, Sprite* tank_sprite, Sprite* smoke_sprite, float tar_x, float tar_y, float collision_radius, int health, float max_speed, grid* grid);
~Tank();
void Tick();
vec2 Get_Position() const { return position; };
float Get_collision_radius() const { return collision_radius; };
bool Rocket_Reloaded() const { return reloaded; };
void Reload_Rocket();
void Deactivate();
bool hit(int hit_value);
void Draw(Surface* screen);
int CompareHealth(const Tank& other) const;
void Push(vec2 direction, float magnitude);
void move(double x, double y);
vec2 position;
vec2 speed;
vec2 target;
int health;
float collision_radius;
vec2 force;
float max_speed;
float reload_time;
bool reloaded;
bool active;
allignments allignment;
int current_frame;
Sprite* tank_sprite;
Sprite* smoke_sprite;
Tank* prev_;
Tank* next_;
grid* Grid;
};
}; // namespace Tmpl8
|
[
"bencher@users.noreply.github.com"
] |
bencher@users.noreply.github.com
|
a8b4c3a11fe75e6e6fc8a0f8bde800b2068d0f48
|
79e13c2a952ba68b7fcee5ef5b34d9a8c41030f1
|
/Uva-OJ/Uva_3n+1.cpp
|
4d93c465e28927982fbb63f999593937730f46fb
|
[] |
no_license
|
Shahin15-1573/mycode-arena
|
924a571a58eba07bc6455e9aeb02f7186e5b527d
|
05b615b80e90d76d05e761f6517ce3053458a44c
|
refs/heads/master
| 2020-02-26T13:18:13.304157
| 2015-11-27T20:08:19
| 2015-11-27T20:08:19
| 47,061,299
| 1
| 0
| null | 2015-11-29T11:43:12
| 2015-11-29T11:43:12
| null |
UTF-8
|
C++
| false
| false
| 886
|
cpp
|
#include<stdio.h>
int getcount( int n){
int count = 1;
while(1){
if(n == 1)
break;
if((n%2)!= 0)
n = 3*n + 1;
else n = n/2;
count++;
}
return count;
}
int main(){
int a, b, max, temp, i;
while(scanf("%d %d",&a,&b) == 2){
max = 1;
if (a > 0 && b < 1000000){
if (a<b){
for(i = a; i <= b; i++){
temp = getcount(i);
if(max < temp)
max = temp;
}
printf("%d %d %d\n",a, b, max);
}
else{
for(i = b; i <= a; i++){
temp = getcount(i);
if(max < temp)
max = temp;
}
printf("%d %d %d\n",a, b, max);
}
}
}
return 0;
}
|
[
"abdur.razzaq06@gmail.com"
] |
abdur.razzaq06@gmail.com
|
86958684b6ad48b672a7db6c409ba2832e9699ff
|
d5931de21cfc26e1fef146f3f0532c4bbb2eedd9
|
/mtTorrent/utils/UpnpPortMapping.h
|
497a69f903c15f5372cea4f35976ca78458c4dc1
|
[
"MIT"
] |
permissive
|
neptunesoft/mtTorrent
|
d72ae8f3f145ed91430b13c9049b5903c4a3a5f9
|
346cdc84293305921fa01e3b524ec2fc0c19f0cd
|
refs/heads/master
| 2022-06-21T03:46:59.762028
| 2020-05-13T19:20:33
| 2020-05-13T19:20:33
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,813
|
h
|
#pragma once
#include "utils/ServiceThreadpool.h"
#include "UpnpDiscovery.h"
class TcpAsyncStream;
class UpnpPortMapping
{
public:
UpnpPortMapping(asio::io_service& io_service);
~UpnpPortMapping();
enum class PortType { Tcp, Udp };
void mapActiveAdapters(uint16_t port, PortType type);
void unmapMappedAdapters(uint16_t port, PortType type, bool waitForFinish = true);
void unmapAllMappedAdapters(bool waitForFinish = true);
void mapPort(const std::string& gateway, uint16_t gatewayPort, const std::string& client, uint16_t port, PortType type, bool enable);
void unmapPort(const std::string& gateway, uint16_t gatewayPort, uint16_t port, PortType type);
std::string getReadableInfo();
private:
std::string getMappingServiceControlUrl(const std::string& gateway);
void checkPendingMapping(const std::string& gateway);
void waitForRequests();
std::string createUpnpHttpHeader(const std::string& hostAddress, const std::string& port, size_t contentLength, const std::string& soapAction);
asio::io_service& io;
struct UpnpMappingState
{
bool active = true;
std::mutex stateMutex;
struct MappedPort
{
std::string gateway;
uint16_t gatewayPort;
uint16_t port;
PortType type;
};
std::vector<MappedPort> mappedPorts;
struct TodoMapping
{
MappedPort mapping;
bool enable;
std::string client;
bool unmap = false;
};
std::vector<TodoMapping> waitingMapping;
std::vector<std::shared_ptr<TcpAsyncStream>> pendingRequests;
};
std::shared_ptr<UpnpMappingState> state;
std::string upnpMappingServiceName;
bool discoveryStarted = false;
bool discoveryFinished = false;
std::mutex discoveryMutex;
std::vector<std::pair<uint16_t, PortType>> activeMappingPending;
UpnpDiscovery discovery;
std::vector<UpnpDiscovery::DeviceInfo> foundDevices;
};
|
[
"marektomco@gmail.com"
] |
marektomco@gmail.com
|
1a743c6d8b3f5d24b6e071db8a988fc74b3dca73
|
0d99d044340c13cb22e3a19c63a221c98eeddad7
|
/13.cpp
|
56b13587eeebcbb0e7b03df374cfb21c1f0551b2
|
[] |
no_license
|
deepwzh/leetcode_practice
|
f1cc28ff22c96ad937c8f21a8e038590934ce179
|
dafcc19a686d22ecace5ca7eec934818aa2e725d
|
refs/heads/master
| 2020-03-27T23:50:30.463658
| 2018-10-24T23:36:21
| 2018-10-24T23:36:21
| 147,352,020
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 946
|
cpp
|
"""
思路:与12题相反,仅需要考虑一下那几种特殊情况即可,详情见下边的代码
"""
class Solution:
def romanToInt(self, s):
"""
:type num: int
:rtype: str
"""
d = {
1: 'I',
4: 'IV',
5:'V',
9: 'IX',
10:'X',
40: 'XL',
50:'L',
90:'XC',
100:'C',
400:'CD',
500:'D',
900:'CM',
1000:'M',
}
d = dict(zip(d.values(), d.keys()))
print(d)
res = 0
cnt = 0
i = 0
while i < len(s):
if i + 1 < len(s):
c = s[i] + s[i + 1]
if c in d:
res += d[c]
i = i + 2
continue
if s[i] in d:
res += d[s[i]]
i = i + 1
return res
|
[
"wzh2012@outlook.com"
] |
wzh2012@outlook.com
|
3793aa9fdb714074fa3462ec4582ed2655264ae9
|
f162089eaa4722bc98b320e6954b5c88c228ed34
|
/src/Console.cpp
|
5e6c5aa8bf8cfbb27b913fce2d23874239825f76
|
[
"MIT"
] |
permissive
|
roslinman/engine
|
97828470caacb50f07f046f62c887e8f71737574
|
061a1fa1b6e4cbe6a90698b08d6a88d2ef705542
|
refs/heads/develop
| 2021-05-27T21:12:22.202409
| 2014-06-03T19:37:10
| 2014-06-03T19:37:10
| 110,465,392
| 1
| 0
| null | 2017-11-12T20:13:20
| 2017-11-12T20:13:20
| null |
UTF-8
|
C++
| false
| false
| 1,512
|
cpp
|
#include "Console.h"
#include "jni\defines.h"
namespace star_w
{
static const WORD MAX_CONSOLE_LINES = 500;
void RedirectIOToConsole()
{
int32 hConHandle;
long lStdHandle;
CONSOLE_SCREEN_BUFFER_INFO conInfo;
FILE * fp;
// allocate a console for this app
AllocConsole();
// set the screen buffer to be big enough to let us scroll text
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &conInfo);
conInfo.dwSize.Y = MAX_CONSOLE_LINES;
SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE),
conInfo.dwSize);
// redirect unbuffered STDOUT to the console
lStdHandle = long(GetStdHandle(STD_OUTPUT_HANDLE));
hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
fp = _fdopen(hConHandle, "w");
*stdout = *fp;
setvbuf(stdout, NULL, _IONBF, 0);
// redirect unbuffered STDIN to the console
lStdHandle = long(GetStdHandle(STD_INPUT_HANDLE));
hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
fp = _fdopen(hConHandle, "r");
*stdin = *fp;
setvbuf(stdin, NULL, _IONBF, 0);
// redirect unbuffered STDERR to the console
lStdHandle = long(GetStdHandle(STD_ERROR_HANDLE));
hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
fp = _fdopen(hConHandle, "w");
*stderr = *fp;
setvbuf(stderr, NULL, _IONBF, 0);
// make cout, wcout, cin, wcin, wcerr, cerr, wclog and clog
// point to console as well
std::ios::sync_with_stdio();
}
void CleanUpConsole()
{
FreeConsole();
}
}
|
[
"decauwsemaecker.glen@gmail.com"
] |
decauwsemaecker.glen@gmail.com
|
78c914ba811b661ea2714d984f9dad62e335d17b
|
9a3b9d80afd88e1fa9a24303877d6e130ce22702
|
/src/Providers/UNIXProviders/MPLSTunnelHop/UNIX_MPLSTunnelHop_ZOS.hxx
|
63c635ce6bb45e7e47328df68997ae85e8d0ab16
|
[
"MIT"
] |
permissive
|
brunolauze/openpegasus-providers
|
3244b76d075bc66a77e4ed135893437a66dd769f
|
f24c56acab2c4c210a8d165bb499cd1b3a12f222
|
refs/heads/master
| 2020-04-17T04:27:14.970917
| 2015-01-04T22:08:09
| 2015-01-04T22:08:09
| 19,707,296
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,809
|
hxx
|
//%LICENSE////////////////////////////////////////////////////////////////
//
// Licensed to The Open Group (TOG) under one or more contributor license
// agreements. Refer to the OpenPegasusNOTICE.txt file distributed with
// this work for additional information regarding copyright ownership.
// Each contributor licenses this file to you under the OpenPegasus Open
// Source License; you may not use this file except in compliance with the
// License.
//
// 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.
//
//////////////////////////////////////////////////////////////////////////
//
//%/////////////////////////////////////////////////////////////////////////
#ifdef PEGASUS_OS_ZOS
#ifndef __UNIX_MPLSTUNNELHOP_PRIVATE_H
#define __UNIX_MPLSTUNNELHOP_PRIVATE_H
#endif
#endif
|
[
"brunolauze@msn.com"
] |
brunolauze@msn.com
|
69b6df41b54dd5fba4c3bfdebec156e59bf32cac
|
98d9e1a599b5f782291d442e02d5e5b76c513b78
|
/StRefMultCorr/CentralityMaker.h
|
675775b47ca6175bae9c8733de3ca989bb3ee8cd
|
[] |
no_license
|
joelmazer/Centrality
|
efb7f069e6b0000fa4e8e19e43467c5ef319dd0d
|
c36c4c6adac8ed690216412e5ee568baa193be48
|
refs/heads/master
| 2023-04-15T00:03:58.925348
| 2021-04-12T23:04:21
| 2021-04-12T23:04:21
| 113,375,261
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,347
|
h
|
//----------------------------------------------------------------------------------------------------
// $Id: CentralityMaker.h,v 1.5 2015/05/22 06:51:58 hmasui Exp $
// $Log: CentralityMaker.h,v $
// Revision 1.5 2015/05/22 06:51:58 hmasui
// Add grefmult for Run14 Au+Au 200 GeV
//
// Revision 1.4 2013/05/10 18:33:33 hmasui
// Add TOF tray mult, preliminary update for Run12 U+U
//
// Revision 1.3 2012/05/19 00:49:14 hmasui
// Update refmult3
//
// Revision 1.2 2012/05/08 03:19:39 hmasui
// Move parameters to Centrality_def_refmult.txt
//
// Revision 1.1 2012/04/23 21:32:16 hmasui
// Interface for future extention of centrality correction maker to other centrality measures, like refmult2
//
//----------------------------------------------------------------------------------------------------
// * Interface of StRefMultCorr for possible extention of StRefMultCorr class to the other
// centrality measure, such as refmult2.
// * This interface is also useful when StRefMultCorr needs to be called from two or more different
// makers in order to have exactly the same corrected refmult and centrality bins among different makers.
//
// There is only one change you have to make
// Replace
// StRefMultCorr* refmultCorr = new StRefMultCorr();
// to
// StRefMultCorr* refmultCorr = CentralityMaker::instance()->getRefMultCorr();
//
// authors: Hiroshi Masui
//----------------------------------------------------------------------------------------------------
#ifndef __CentralityMaker_h__
#define __CentralityMaker_h__
class StRefMultCorr ;
#include "Rtypes.h"
//____________________________________________________________________________________________________
class CentralityMaker {
public:
static CentralityMaker* instance(); // Use this function to access StRefMultCorr
virtual ~CentralityMaker(); /// Default destructor
// Interface
StRefMultCorr* getRefMultCorr() ; // For refmult
StRefMultCorr* getRefMult2Corr() ; // For refmult2
StRefMultCorr* getRefMult3Corr() ; // For refmult3
StRefMultCorr* getTofTrayMultCorr() ; // For TOF tray multiplicity
StRefMultCorr* getgRefMultCorr() ; // For grefmult //Run14 AuAu200GeV
StRefMultCorr* getgRefMultCorr_P16id() ; // For grefmult //Run14 AuAu200GeV, P16id
StRefMultCorr* getgRefMultCorr_P17id_VpdMB30() ; // for P17id, VPDMB-30; |vz| < 30
StRefMultCorr* getgRefMultCorr_P18ih_VpdMB30() ; // for P18ih, VPDMB-30; |vz| < 30, added June10, 2019 (New Run14 production)
StRefMultCorr* getgRefMultCorr_P18ih_VpdMB30_AllLumi() ; // for P18ih, VPDMB-30; |vz| < 30, added August15, 2019, Run14 production, for ALL luminosities
StRefMultCorr* getgRefMultCorr_P18ih_VpdMB30_AllLumi_MB5sc() ; // for P18ih, VPDMB-30; |vz| < 30, added August15, 2019, Run14 production, for ALL luminosities
StRefMultCorr* getgRefMultCorr_VpdMB30() ; // for VPDMB-30; |vz| < 30
StRefMultCorr* getgRefMultCorr_VpdMBnoVtx() ; // for VPDMB-noVtx; |vz| < 100
// Print help messages
void help() const ;
private:
CentralityMaker() ; // Constructor is private
static CentralityMaker* fInstance ; // Static pointer of CentralityMaker
// Centrality correction classes
StRefMultCorr* fRefMultCorr ; // refmult based centrality
StRefMultCorr* fRefMult2Corr ; // refmult2 based centrality
StRefMultCorr* fRefMult3Corr ; // refmult3 based centrality
StRefMultCorr* fTofTrayMultCorr ; // tofTrayMult based centrality
StRefMultCorr* fgRefMultCorr ; // grefmult based centrality
StRefMultCorr* fgRefMultCorr_P16id ; // grefmult based centrality, P16id
StRefMultCorr* fgRefMultCorr_P17id_VpdMB30; // for P17id, VPDMB-30; |vz| < 30
StRefMultCorr* fgRefMultCorr_P18ih_VpdMB30; // for P18ih, VPDMB-30; |vz| < 30, added June10, 2019 (New Run14 production)
StRefMultCorr* fgRefMultCorr_P18ih_VpdMB30_AllLumi; // for P18ih, VPDMB-30; |vz| < 30, added August15, 2019, Run14 production, for ALL luminosities
StRefMultCorr* fgRefMultCorr_P18ih_VpdMB30_AllLumi_MB5sc; // for P18ih, VPDMB-30; |vz| < 30, added August15, 2019, Run14 production, for ALL luminosities
StRefMultCorr* fgRefMultCorr_VpdMB30; // for VPDMB-30; |vz| < 30
StRefMultCorr* fgRefMultCorr_VpdMBnoVtx; // for VPDMB-noVtx; |vz| < 100
ClassDef(CentralityMaker, 0)
};
#endif
|
[
"joel.mazer@cern.ch"
] |
joel.mazer@cern.ch
|
4eeb21d670dc47474696da66e1175278697fa512
|
ee44c5351afcbf8d44f2893151661f1739ea62bc
|
/include/level.hh
|
7a2141a2094c62a0fdb61a9b84dc0070491b467e
|
[] |
no_license
|
jgardella/CS585
|
892f9721c77818948cffc5f7e89f15a6c74fe74c
|
42049d5fc20509bc0469da917427f74276451757
|
refs/heads/master
| 2021-01-01T16:39:59.957828
| 2014-12-02T04:35:16
| 2014-12-02T04:35:16
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,329
|
hh
|
#ifndef _LEVEL_HH_
#define _LEVEL_HH_
#include "levelinfo.hh"
#include "fixedgrid.hh"
#include "scenemanager.hh"
#include "tilefactory.hh"
#include "statemachine.hh"
#include "building.hh"
#include "charactercontroller.hh"
#include "ilistenercallback.hh"
#include "ievent.hh"
#include "deathevent.hh"
#include "menumanager.hh"
class Level : public ITickable
{
public:
// Constructs a level with a world of the given width and height.
// Parameters:
// int width - the width of the world
// int height - the height of the world
Level(tLevelInfo level);
void tick(float dt);
int getWorldWidth();
int getWorldHeight();
Building* getHome(unsigned int teamNum);
Building* getBlacksmith(unsigned int teamNum);
Building* getApothecary(unsigned int teamNum);
std::string getDefaultTile();
CharacterController* getControllerForCharacter(unsigned int id);
void removeControllerForCharacter(unsigned int id);
void addControllerForCharacter(CharacterController* controller);
void addHome(Building* building);
void addBlacksmith(Building* building);
void addApothecary(Building* building);
IListenerCallback* getListener();
unsigned int getPlayerGold();
void changePlayerGold(int amount);
bool isApothecaryBuilt();
bool isBlacksmithBuilt();
void setApothecaryBuilt(bool val);
void setBlacksmithBuilt(bool val);
private:
int width;
int height;
bool apothecaryBuilt, blacksmithBuilt;
unsigned int playerGold;
std::string defaultTile;
DynamicArray<Building*>* teamHomes;
DynamicArray<Building*>* teamBlacksmiths;
DynamicArray<Building*>* teamApothecaries;
DynamicArray<CharacterController*>* characterControllers;
void processDeathEvent(DeathEvent* event);
// Listener callback for deaths
class OnDeathEvent : public IListenerCallback
{
public:
OnDeathEvent() { }
void setInstance(Level* level)
{
this->level = level;
}
// Transfers gold and removes the controller for the dead actor.
virtual void execute(IEvent* event)
{
DEBUG_LOG("LEVEL", "Death event callback executed.");
if(event->getType().compare("death") == 0)
{
DeathEvent* deathEvent = (DeathEvent*) event;
level->processDeathEvent(deathEvent);
}
}
private:
Level* level;
} onDeathEvent;
};
#endif
|
[
"jgardell@stevens.edu"
] |
jgardell@stevens.edu
|
0f211d1b65dc372d1fcededace7775c37499a0d2
|
029090d7efba33247d81f17868d718f617ddc5fa
|
/src/lar_youbot/PIDController.cpp
|
be100bca3c37271b9e08e014e9b4292247916b02
|
[] |
no_license
|
lar-lab-unibo/lar_youbot
|
b2aee1e669f21553eac5c86325f7dfe9e4f44cd2
|
d20b60ebdd02c9d85ec705bc2c1ae95882d75b80
|
refs/heads/master
| 2020-12-31T04:56:08.755160
| 2016-05-10T18:09:35
| 2016-05-10T18:09:35
| 58,337,909
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,364
|
cpp
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: PIDController.cpp
* Author: daniele
*
* Created on May 9, 2016, 5:10 PM
*/
#include "PIDController.h"
#include <stdio.h>
#include <math.h>
namespace lar_youbot {
PIDController::PIDController(double Kp, double Kd, double Ki) {
this->Kp = Kp;
this->Kd = Kd;
this->Ki = Ki;
this->reset();
}
PIDController::PIDController(const PIDController& orig) {
this->Kp = orig.Kp;
this->Kd = orig.Kd;
this->Ki = orig.Ki;
this->error = orig.error;
this->past_error = orig.past_error;
this->integral_error = orig.integral_error;
this->time = orig.time;
}
PIDController::~PIDController() {
}
/**
* Updates the Controller
* @param current_error current error value
* @param current_time_in_seconds current system time in seconds
*/
void PIDController::update(double current_error, double current_time_in_seconds) {
double delta_time = current_time_in_seconds - this->time;
this->time = current_time_in_seconds;
this->error = current_error;
//Proportional
double proportional = this->error*Kp;
//Derivative
double derivative = (this->past_error - this->error) * Kd / delta_time;
this->past_error = this->error;
//Integral
double integral = this->integral_error * Ki*delta_time;
this->integral_error += this->error;
//Computes action
this->actuation = proportional + derivative + integral;
//NaN Checks
this->integral_error = isnan(this->integral_error) ? 0.0 : this->integral_error;
this->past_error = isnan(this->past_error) ? 0.0 : this->past_error;
this->actuation = isnan(this->actuation) ? 0.0 : this->actuation;
}
/**
* Returns the current Actuation
* @return
*/
double PIDController::getActuation() {
return this->actuation;
}
/**
* Resets the PID Controller
*/
void PIDController::reset() {
this->error = 0.0;
this->past_error = 0.0;
this->integral_error = 0.0;
this->time = 0.0;
}
}
|
[
"degregorio.daniele@gmail.com"
] |
degregorio.daniele@gmail.com
|
1461ce392c471275a862ed1f6e0b94e2579a5f0c
|
49dbf8bc69ed784c896376f676e5f8a0bd7929d8
|
/evalstate.h
|
d46c17dbd04f195b38363984127728cde8ed2d55
|
[] |
no_license
|
JolyneFr/MiniBasic
|
dd8d318065ed0bb0fc65895c0589b60228801594
|
da10d5264cacbe49907feb69436b1fd7fa2bff1b
|
refs/heads/master
| 2023-05-01T04:54:06.086301
| 2021-05-15T09:14:46
| 2021-05-15T09:14:46
| 344,018,607
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 773
|
h
|
#ifndef EVALSTATE_H
#define EVALSTATE_H
#include <QString>
#include <QMap>
/*
* Class: EvaluationContext
* ------------------------
* This class encapsulates the information that the evaluator needs to
* know in order to evaluate an expression.
*/
class EvaluationContext {
public:
void setValue(QString var, int value);
void setValue(QString var, QString value);
int getValue(QString var);
QString getString(QString var);
bool isDefinedInt(QString var);
bool isDefinedString(QString var);
void clear();
void merge(EvaluationContext &);
QMap<QString, int> getTable() const;
QMap<QString, QString> getStringTable() const;
private:
QMap<QString, int> symbolTable;
QMap<QString, QString> stringTable;
};
#endif // EVALSTATE_H
|
[
"jolynefr@sjtu.edu.cn"
] |
jolynefr@sjtu.edu.cn
|
14400e790aa515ea6733196f79df5b3f677e65c0
|
27f68827fd788bc53b7669296c07fa39962a2b68
|
/Devices/Window/CommonWindow/SubComponents/BaseRenderer/src/BaseRenderer.cpp
|
42acb9a350ef8f9d39c2201b57ce2fe9adb97ae7
|
[] |
no_license
|
Dholguin-Programmer/Assignment_1
|
9a79dc7d6fabde95c8eb63ec8797ab595ad4071d
|
f4e18f27dc23ab62a5c74a724b36718541709df5
|
refs/heads/master
| 2022-07-05T17:30:07.330389
| 2020-05-20T19:58:06
| 2020-05-20T19:58:06
| 262,688,117
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 243
|
cpp
|
#include "BaseRenderer.h"
using namespace Renderer::SubComponent;
/////////////////////////////////////////////////////////////////////[///////////
Base::Base(Window::Device::Manager& manager)
: m_windowManager(manager)
{
// no nothing
}
|
[
"Dholguin.Programmer@gmail.com"
] |
Dholguin.Programmer@gmail.com
|
df3f860794e438e7d6bb7887abc7fa2280465078
|
f997616b3b163e9b5fc7f55795340d546c93373a
|
/src/Responsable/ResponsableEpisode.cpp
|
c0bd8c5d8996cad08bd3b0422871ff22795aa4b8
|
[
"MIT"
] |
permissive
|
Callidon/ObjectifCanapi
|
b0abb75fffbb438efd4f5d910731cddab30c2ef5
|
7a1a06794d80c1517af87236e176da4a2a6a76fd
|
refs/heads/master
| 2020-06-04T17:47:16.491314
| 2014-12-01T17:58:08
| 2014-12-01T17:58:08
| 24,419,865
| 0
| 2
| null | 2014-11-04T16:29:24
| 2014-09-24T15:07:46
|
C
|
UTF-8
|
C++
| false
| false
| 1,419
|
cpp
|
/*!
* \file ResponsableEpisode.cpp
* \brief Fichier contenant les entêtes de la classe ResponsableEpisode
* \author Camille Le Luët
* \author Thomas Minier
* \date 26.11.2014
*/
#include "ResponsableEpisode.hpp"
#include <iostream>
using namespace std;
//--------------------------------------------------
/*!
* \brief Constructeur de base
*/
ResponsableEpisode::ResponsableEpisode(std::shared_ptr<BDConnector> db)
: Responsable(db, 0)
{}
//--------------------------------------------------
/*!
* \brief Destructeur
*/
ResponsableEpisode::~ResponsableEpisode() {}
//--------------------------------------------------
/*!
* \brief Méthode effectuant le traitement de l'objet si c'est un épisode
* \brief Si l'épisode n'est pas présent dans la base, on l'insère. Sinon, on le met à jour
* \param video shared_ptr vers l'objet à traiter
*/
void ResponsableEpisode::traiter(std::shared_ptr<Video> video, bool vu, bool aVoir) {
//on essaye de convertir la vidéo en film
shared_ptr<Episode> episode(dynamic_pointer_cast<Episode>(video));
//si c'est bien un objet Film
if(episode) {
//on utilise le comportement pour effectuer les requêtes adéquates sur l'objet
comportement->traiterEpisode(episode, "", vu, aVoir);
} else {
//Il n'y a plus de successeur après ce responsable, on affiche une erreur
cout << "Erreur : aucun responsable ne peut traiter la requête" << endl;
}
}
|
[
"tminier01@gmail.com"
] |
tminier01@gmail.com
|
140f4cd1b379105cb2a11478ec76bbbc40b9c75f
|
e156eecc9bddfd5812336956acb415123f5e9dc0
|
/nn/include/output_layer.h
|
8869729cad582b8965cdb84cb034539d86ad5928
|
[
"MIT"
] |
permissive
|
echentw/neural-network
|
3152d382d16312b6fd57ea262644ba7166a651ae
|
63bb2adbd31a6b37e94dfd868a402d47e168d862
|
refs/heads/master
| 2021-01-18T21:12:25.783507
| 2016-05-17T03:17:32
| 2016-05-17T03:17:32
| 38,932,531
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 799
|
h
|
#ifndef __OUTPUT_LAYER__H
#define __OUTPUT_LAYER__H
#include "layer.h"
#include "output_node.h"
#include "boost/multi_array.hpp"
class OutputLayer : public Layer {
private:
std::vector<OutputNode> node_list;
// gradients[i] = partial derivative of cost w.r.t. input i
boost::multi_array<double, 1> gradients;
public:
OutputLayer(int size);
void adjust(int new_size);
double getInput(int i) const;
double getOutput(int i) const;
std::vector<double> getInput() const;
std::vector<double> getOutput() const;
void receiveInput(const std::vector<double>& input);
void computeGradient(const std::vector<double>& output);
// returns the partial derivative of cost
// w.r.t. the input #input_id of this layer
double getPartialDerivative(int input_id) const;
};
#endif
|
[
"chen1994tw@gmail.com"
] |
chen1994tw@gmail.com
|
f5d14893b4e42fc33d23780012aa1882f5deb60c
|
ad822f849322c5dcad78d609f28259031a96c98e
|
/SDK/Sun_functions.cpp
|
aace6051de2bbe74766b5ae4694710525db661dc
|
[] |
no_license
|
zH4x-SDK/zAstroneer-SDK
|
1cdc9c51b60be619202c0258a0dd66bf96898ac4
|
35047f506eaef251a161792fcd2ddd24fe446050
|
refs/heads/main
| 2023-07-24T08:20:55.346698
| 2021-08-27T13:33:33
| 2021-08-27T13:33:33
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,517
|
cpp
|
#include "../SDK.h"
// Name: Astroneer-SDK, Version: 1.0.0
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
namespace SDK
{
//---------------------------------------------------------------------------
// Functions
//---------------------------------------------------------------------------
// Function Sun.Sun_C.Set Intensity
// (Public, HasDefaults, BlueprintCallable, BlueprintEvent)
void ASun_C::Set_Intensity()
{
static auto fn = UObject::FindObject<UFunction>("Function Sun.Sun_C.Set Intensity");
ASun_C_Set_Intensity_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function Sun.Sun_C.UserConstructionScript
// (Event, Public, HasDefaults, BlueprintCallable, BlueprintEvent)
void ASun_C::UserConstructionScript()
{
static auto fn = UObject::FindObject<UFunction>("Function Sun.Sun_C.UserConstructionScript");
ASun_C_UserConstructionScript_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function Sun.Sun_C.ReceiveBeginPlay
// (Event, Protected, BlueprintEvent)
void ASun_C::ReceiveBeginPlay()
{
static auto fn = UObject::FindObject<UFunction>("Function Sun.Sun_C.ReceiveBeginPlay");
ASun_C_ReceiveBeginPlay_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function Sun.Sun_C.ReceiveTick
// (Event, Public, BlueprintEvent)
// Parameters:
// float DeltaSeconds (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
void ASun_C::ReceiveTick(float DeltaSeconds)
{
static auto fn = UObject::FindObject<UFunction>("Function Sun.Sun_C.ReceiveTick");
ASun_C_ReceiveTick_Params params;
params.DeltaSeconds = DeltaSeconds;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function Sun.Sun_C.ExecuteUbergraph_Sun
// ()
// Parameters:
// int EntryPoint (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
void ASun_C::ExecuteUbergraph_Sun(int EntryPoint)
{
static auto fn = UObject::FindObject<UFunction>("Function Sun.Sun_C.ExecuteUbergraph_Sun");
ASun_C_ExecuteUbergraph_Sun_Params params;
params.EntryPoint = EntryPoint;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
|
[
"zp2kshield@gmail.com"
] |
zp2kshield@gmail.com
|
d3d0190bcc2d778d74a32f7e45d704548fac9e88
|
e8c837604c46d5e672ba9e0d1458cc5bae9dd1a2
|
/PantsuSDK/esp.h
|
9c569c66bdd7c1a5c60254ce8515425a023d76d3
|
[] |
no_license
|
pSilent-Github/Pantsu-SDK
|
17de5ff479457598b82ae8d2b2bd4a4169869829
|
c5202078524aeb89e861da137a86f3e5f32b3527
|
refs/heads/master
| 2021-07-12T05:31:04.421812
| 2017-10-13T17:47:46
| 2017-10-13T17:47:46
| 106,767,630
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,277
|
h
|
#pragma once
#include "client-entity-list.h"
#include "engine-client.h"
#include "entity.h"
#include "render.h"
class CESP
{
public:
void Think( )
{
CBaseEntity* Local = ( CBaseEntity* )ClientEntityList->GetClientEntity( EngineClient->GetLocalPlayer( ) );
PlayerInfo_t Info;
Matrix3x4_t Matrix = EngineClient->GetMatrix( );
CVector Screen, Head;
for ( int i = 0; i < 64; ++i )
{
CBaseEntity* Entity = ( CBaseEntity* ) ClientEntityList->GetClientEntity( i );
if ( !Entity )
continue;
if ( Entity == Local )
continue;
if ( Entity->GetDormant( ) )
continue;
if ( Entity->GetHealth( ) )
{
EngineClient->GetPlayerInfo( i, &Info );
if ( WorldToScreen( Entity->GetOrigin( ), Screen ) && WorldToScreen( ( Entity->GetEyePosition( ) + CVector( 0, 0, 8.f ) ), Head ) )
{
CColor Color( 255, 255, 255, 255 );
if ( Entity->GetTeam( ) != Local->GetTeam( ) )
Color = CColor( 255, 0, 0, 255 );
else
Color = CColor( 0, 255, 255, 255 );
Render->DrawF(Head.x, Head.y - 12, CColor(255, 255, 255, 255), 5, 1, "%s", Info.Name );
Render->DrawF(Screen.x, Screen.y + 2, CColor(255, 255, 255, 255), 5, 1, "HP: %d", Entity->GetHealth( ) );
int Height = Screen.y - Head.y, Width = Height / 2.5;
Render->DrawInlineRect( Head.x - Width / 2, Head.y, Width, Height, Color );
}
}
}
}
__forceinline bool WorldToScreen( CVector In, CVector& Out )
{
Matrix3x4_t ViewMatrix = EngineClient->GetMatrix( );
Out.x = ViewMatrix.Matrix[ 0 ] * In.x + ViewMatrix.Matrix[ 1 ] * In.y + ViewMatrix.Matrix[ 2 ] * In.z + ViewMatrix.Matrix[ 3 ];
Out.y = ViewMatrix.Matrix[ 4 ] * In.x + ViewMatrix.Matrix[ 5 ] * In.y + ViewMatrix.Matrix[ 6 ] * In.z + ViewMatrix.Matrix[ 7 ];
Out.z = ViewMatrix.Matrix[ 12 ] * In.x + ViewMatrix.Matrix[ 13 ] * In.y + ViewMatrix.Matrix[ 14 ] * In.z + ViewMatrix.Matrix[ 15 ];
if ( Out.z < 0.01f )
return false;
float Inverse = 1.f / Out.z;
Out.x *= Inverse;
Out.y *= Inverse;
int Width, Height;
EngineClient->GetScreenSize( Width, Height );
auto X = Width / 2;
auto Y = Height / 2;
X += 0.5 * Out.x * Width + 0.5;
Y -= 0.5 * Out.y * Height + 0.5;
Out.x = X;
Out.y = Y;
return true;
}
};
|
[
"pSilent@github.com"
] |
pSilent@github.com
|
bbc227cb1db148cf367d3ccc60988bfd3f993354
|
361390c6fb4bef1dd04dfd57bc74c7f64149922f
|
/RunGun/Skills/Weapons/C_FiringComp.h
|
d389e5b8dd18c9ea004c75048f31e4efdccf6593
|
[] |
no_license
|
maunglinkyaw/RunGun
|
d602b491d1d74bf6b3f7d033a3bf6ef9edc5dc40
|
b18b97254e1f04d95855d04b7690dce141f834eb
|
refs/heads/main
| 2023-04-22T00:31:30.251457
| 2021-05-07T19:00:46
| 2021-05-07T19:00:46
| 360,533,685
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 930
|
h
|
// Lin & Yin 2020
#pragma once
#include "CoreMinimal.h"
#include "C_WeaponComp.h"
#include "C_FiringComp.generated.h"
class AC_Skill;
class AC_Projectile;
class UC_SkillManager;
UCLASS()
class RUNGUN_API UC_FiringComp : public UC_WeaponComp
{
GENERATED_BODY()
public:
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Weapon")
UC_SkillManager* m_SkillManager = nullptr;
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "WeaponStats|Pooling")
TSubclassOf<AC_Skill> m_SkillClass = nullptr;
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "WeaponStats|Pooling")
int32 m_PoolCount = 0;
void InitWeaponComp(AC_Weapon* weapon) override;
virtual void RequestFireWeapon(float chargeRate);
virtual void RemoveWeaponComp() override;
protected:
virtual void FireWeapon(float chargeRate);
AC_Projectile* m_TempProjectile;
void BeginPoolAmmo();
AC_Projectile* GetProjectileFromPool();
};
|
[
"83018188+maunglinkyaw@users.noreply.github.com"
] |
83018188+maunglinkyaw@users.noreply.github.com
|
8b3d486c02feefc5bc213d7443d9335c3e766d2d
|
4cb5b2389b536d364471514d2efc20c86e8ae6f5
|
/src/user/init/main.cc
|
480dbca602c3e88c1393b699f0b163407d454bdc
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
cjsmeele/RikaiOS
|
d48c11b21c91d1827f264a101a1c420a8581d959
|
4da9da8a4492adefb1733fdad152f0e098ddc7fd
|
refs/heads/master
| 2021-06-18T21:38:37.410485
| 2021-02-10T18:35:25
| 2021-02-10T18:35:25
| 177,954,455
| 9
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,058
|
cc
|
/* Copyright 2019 Chris Smeele
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <io.hh>
#include <proc.hh>
#include <os-std/ostd.hh>
using namespace ostd;
int main(int, const char**) {
// (arguments are ignored)
// Open stdin/out/err. These will be inherited by processes we spawn.
// If a serial port is available, use it for all I/O.
errno_t err = open(stdin , "/dev/uart0", "r");
if (err >= 0) {
// OK.
err = open(stdout, "/dev/uart0", "w");
if (err < 0) return 1;
} else if (err == ERR_not_exists) {
// TODO: Provide a tty driver. Open a pipe to it here.
// Serial port not available, use keyboard+monitor instead.
err = open(stdin , "/dev/keyboard", "r"); if (err < 0) return 1;
err = open(stdout, "/dev/video-text", "w"); if (err < 0) return 1;
// This pretends to be succesful, but we actually can't use video-text
// as a console for userland currently. We depend on a working UART.
} else {
return 1;
}
// stderr should appear in the same place as stdout.
err = duplicate_fd(stderr, stdout);
if (err < 0) return 1;
// Note: The current working directory should be the root of the first
// mounted partition. We look for a shell in its "/bin" directory.
Array<StringView, 1> args { "shell" };
err = spawn("bin/shell.elf", args, true);
if (err < 0) {
print(stderr, "init: could not load the shell: {}\n", error_name(err));
return 1;
}
return 0;
}
|
[
"cj.smeele@xs4all.nl"
] |
cj.smeele@xs4all.nl
|
55d561c48bdfae93adb41eb26e126760895380f1
|
aadf31061666fc9fd95583710a34d01fa571b09f
|
/tests/TestFieldPointerVariable.cpp
|
a670e5a4cca1f2c561b0e8e12ae9906212fd45b6
|
[] |
no_license
|
vladfridman/wisey
|
6198cf88387ea82175ea6e1734edb7f9f7cf20c6
|
9d0efcee32e05c7b8dc3dfd22293737324294fea
|
refs/heads/master
| 2022-04-14T08:00:42.743194
| 2020-03-12T14:22:45
| 2020-03-12T14:22:45
| 74,822,543
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 7,286
|
cpp
|
//
// TestFieldPointerVariable.cpp
// Wisey
//
// Created by Vladimir Fridman on 4/3/18.
// Copyright © 2018 Vladimir Fridman. All rights reserved.
//
// Tests {@link FieldPointerVariable}
//
#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include <llvm/IR/Instructions.h>
#include <llvm/IR/Constants.h>
#include <llvm/Support/raw_ostream.h>
#include "MockExpression.hpp"
#include "TestFileRunner.hpp"
#include "TestPrefix.hpp"
#include "FieldPointerVariable.hpp"
#include "IExpression.hpp"
#include "IInterfaceTypeSpecifier.hpp"
#include "IRGenerationContext.hpp"
#include "IRWriter.hpp"
#include "LLVMPrimitiveTypes.hpp"
#include "ParameterReferenceVariable.hpp"
#include "PrimitiveTypes.hpp"
#include "StateField.hpp"
using namespace llvm;
using namespace std;
using namespace wisey;
using ::testing::_;
using ::testing::Mock;
using ::testing::NiceMock;
using ::testing::Return;
using ::testing::Test;
struct FieldPointerVariableTest : Test {
IRGenerationContext mContext;
LLVMContext& mLLVMContext;
Controller* mObject;
Interface* mInterface;
BasicBlock* mBasicBlock;
FieldPointerVariable* mFieldPointerVariable;
const LLVMPointerType* mPointerType;
Node* mNode;
string mStringBuffer;
raw_string_ostream* mStringStream;
FieldPointerVariableTest() : mLLVMContext(mContext.getLLVMContext()) {
TestPrefix::generateIR(mContext);
string interfaceFullName = "systems.vos.wisey.compiler.tests.IInterface";
StructType* interfaceStructType = StructType::create(mLLVMContext, interfaceFullName);
vector<IInterfaceTypeSpecifier*> parentInterfaces;
vector<IObjectElementDefinition*> interfaceElements;
mInterface = Interface::newInterface(AccessLevel::PUBLIC_ACCESS,
interfaceFullName,
interfaceStructType,
parentInterfaces,
interfaceElements,
mContext.getImportProfile(),
0);
vector<Interface*> interfaces;
interfaces.push_back(mInterface);
string nodeFullName = "systems.vos.wisey.compiler.tests.NNode";
StructType* nodeStructType = StructType::create(mLLVMContext, nodeFullName);
mNode = Node::newNode(AccessLevel::PUBLIC_ACCESS,
nodeFullName,
nodeStructType,
mContext.getImportProfile(),
0);
mNode->setInterfaces(interfaces);
mPointerType = LLVMPrimitiveTypes::I64->getPointerType(mContext, 0);
vector<Type*> types;
types.push_back(FunctionType::get(Type::getInt32Ty(mLLVMContext), true)
->getPointerTo()->getPointerTo());
types.push_back(mPointerType->getLLVMType(mContext));
types.push_back(mInterface->getLLVMType(mContext));
string objectFullName = "systems.vos.wisey.compiler.tests.CController";
StructType* objectStructType = StructType::create(mLLVMContext, objectFullName);
objectStructType->setBody(types);
vector<IField*> fields;
fields.push_back(new StateField(mPointerType, "foo", 0));
fields.push_back(new StateField(mInterface, "bar", 0));
mObject = Controller::newController(AccessLevel::PUBLIC_ACCESS,
objectFullName,
objectStructType,
mContext.getImportProfile(),
0);
mObject->setFields(mContext, fields, 1u);
FunctionType* functionType =
FunctionType::get(Type::getInt32Ty(mContext.getLLVMContext()), false);
Function* function = Function::Create(functionType,
GlobalValue::InternalLinkage,
"main",
mContext.getModule());
BasicBlock* declareBlock = BasicBlock::Create(mLLVMContext, "declare", function);
mBasicBlock = BasicBlock::Create(mLLVMContext, "entry", function);
mContext.setDeclarationsBlock(declareBlock);
mContext.setBasicBlock(mBasicBlock);
mContext.getScopes().pushScope();
Value* thisPointer = ConstantPointerNull::get(mObject->getLLVMType(mContext));
IVariable* thisVariable = new ParameterReferenceVariable(IObjectType::THIS,
mObject,
thisPointer,
0);
mContext.getScopes().setVariable(mContext, thisVariable);
mFieldPointerVariable = new FieldPointerVariable("foo", mObject, 0);
mStringStream = new raw_string_ostream(mStringBuffer);
}
~FieldPointerVariableTest() {
delete mStringStream;
delete mObject;
}
};
TEST_F(FieldPointerVariableTest, basicFieldsTest) {
EXPECT_STREQ("foo", mFieldPointerVariable->getName().c_str());
EXPECT_EQ(mPointerType, mFieldPointerVariable->getType());
EXPECT_TRUE(mFieldPointerVariable->isField());
EXPECT_FALSE(mFieldPointerVariable->isStatic());
}
TEST_F(FieldPointerVariableTest, generateIdentifierIRTest) {
mFieldPointerVariable->generateIdentifierIR(mContext, 0);
*mStringStream << *mBasicBlock;
string expected = string() +
"\nentry: ; No predecessors!" +
"\n %0 = getelementptr %systems.vos.wisey.compiler.tests.CController, %systems.vos.wisey.compiler.tests.CController* null, i32 0, i32 1"
"\n %foo = load i64*, i64** %0\n";
EXPECT_STREQ(expected.c_str(), mStringStream->str().c_str());
}
TEST_F(FieldPointerVariableTest, generateIdentifierreferenceIRTest) {
mFieldPointerVariable->generateIdentifierReferenceIR(mContext, 0);
*mStringStream << *mBasicBlock;
string expected = string() +
"\nentry: ; No predecessors!" +
"\n %0 = getelementptr %systems.vos.wisey.compiler.tests.CController, %systems.vos.wisey.compiler.tests.CController* null, i32 0, i32 1\n";
EXPECT_STREQ(expected.c_str(), mStringStream->str().c_str());
}
TEST_F(FieldPointerVariableTest, generateAssignmentIRTest) {
NiceMock<MockExpression> assignToExpression;
Value* assignToValue = ConstantPointerNull::get(mNode->getLLVMType(mContext));
ON_CALL(assignToExpression, getType(_)).WillByDefault(Return(mNode));
ON_CALL(assignToExpression, generateIR(_, _)).WillByDefault(Return(assignToValue));
vector<const IExpression*> arrayIndices;
mFieldPointerVariable->generateAssignmentIR(mContext, &assignToExpression, arrayIndices, 0);
*mStringStream << *mBasicBlock;
string expected = string() +
"\nentry: ; No predecessors!" +
"\n %0 = bitcast %systems.vos.wisey.compiler.tests.NNode* null to i64*"
"\n %1 = getelementptr %systems.vos.wisey.compiler.tests.CController, %systems.vos.wisey.compiler.tests.CController* null, i32 0, i32 1"
"\n store i64* %0, i64** %1\n";
EXPECT_STREQ(expected.c_str(), mStringStream->str().c_str());
}
TEST_F(TestFileRunner, fieldPointerVariableRunTest) {
runFile("tests/samples/test_field_pointer_variable.yz", 1);
}
|
[
"vlad.fridman@gmail.com"
] |
vlad.fridman@gmail.com
|
2e3c9a07c28d102791a5c7ad0b844a32c3adb203
|
7d6d0eb3b34773edf7a7f98c8a1a9fd6358f6c5e
|
/timer.cpp
|
1edc4b726e1d1467c1eb6fb603787d4274d4ad66
|
[] |
no_license
|
illuvatar88/UNIX_IPC_benchmark_SHM
|
356e0c2b9d3d868ca10077378d7eb252a5378105
|
10023aa181c54d54cd1d3119a5434791c825b154
|
refs/heads/master
| 2021-01-01T18:17:02.701840
| 2014-10-16T07:48:58
| 2014-10-16T07:48:58
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 250
|
cpp
|
/*This file contains the declaration of the function timerval() that is used in the benchmarks to
*register time
*/
#include <sys/time.h>
double timerval () {
struct timeval st;
gettimeofday (&st, NULL);
return st.tv_sec + st.tv_usec * 1e-6;
}
|
[
"illuvatar@ufl.edu"
] |
illuvatar@ufl.edu
|
846c3bd24692dc112d655c014a0af865d755d94d
|
d502103fc5f72e66b382d01b6d502d95ffa3cb43
|
/mainwindow.cpp
|
4e02423fcce600c00e2c76dd6bd27535a9ce794f
|
[
"MIT"
] |
permissive
|
abrarShariar/ToDo-Qt
|
0d109382bb8326f40bf6db6d5997d81901ad27d2
|
b1c6c5f714b2830aed8719f3cddb4aa8f3fb344c
|
refs/heads/master
| 2020-12-25T21:01:41.649848
| 2016-02-13T12:46:23
| 2016-02-13T12:46:23
| 49,495,994
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,272
|
cpp
|
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "dialog.h"
#include "tasklist.h"
#include<QTime>
#include<QDebug>
#include<QtSql>
qint8 getDaysLeft(QDateTime);
qint16 getHoursLeft(QDateTime);
qint32 getMinsLeft(QDateTime);
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
//connect to database
QSqlDatabase db=QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("E:\\QtProject\\database\\taskDB.db");
bool db_ok=db.open();
if(db_ok){
qDebug()<<"Database Connected";
}
QTime currentTime=QTime::currentTime();
ui->setupUi(this); //everything must be after setupUi
QDate currentDate=ui->calendarWidget->selectedDate();
ui->dateTimeEdit->setTime(currentTime);
ui->dateTimeEdit->setDate(currentDate);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButton_released()
{
//prepare deadline in string
QTime selectedTime=ui->dateTimeEdit->time();
QDate selectedDate=ui->calendarWidget->selectedDate();
//qDebug()<<time;
//time left(hours)
ui->dateTimeEdit->setTime(selectedTime);
ui->dateTimeEdit->setDate(selectedDate);
QDateTime selectedDateTime=ui->dateTimeEdit->dateTime(); //getting selected deadline
ui->lcdNumber->display(getDaysLeft(selectedDateTime));
ui->lcdNumber_2->display(getHoursLeft(selectedDateTime));
ui->lcdNumber_3->display(getMinsLeft(selectedDateTime));
}
void MainWindow::on_pushButton_2_clicked()
{
QString taskText=ui->plainTextEdit->toPlainText();
QString deadline=ui->dateTimeEdit->dateTime().toString("yyyy-MM-dd hh:mm:ss");
//insert into database
if(taskText!="" && taskText!=" "){
QSqlQuery addTaskQuery;
addTaskQuery.prepare("INSERT INTO allTask(task,deadline) values(:task,:deadline)");
addTaskQuery.bindValue(":task",taskText);
addTaskQuery.bindValue(":deadline",deadline);
if(addTaskQuery.exec()){
Dialog addSuccess;
addSuccess.showTaskText(taskText);
addSuccess.showDeadline(deadline);
addSuccess.exec();
}
}
}
//time left (days)
qint8 getDaysLeft(QDateTime selected){
qint8 daysLeft;
QDateTime current=QDateTime::currentDateTime();
daysLeft=current.daysTo(selected);
return daysLeft;
}
qint16 getHoursLeft(QDateTime selected){
qint16 hoursLeft;
QDateTime current=QDateTime::currentDateTime();
hoursLeft=current.secsTo(selected)/(60*60);
return hoursLeft;
}
qint32 getMinsLeft(QDateTime selected){
qint32 minsLeft;
QDateTime current=QDateTime::currentDateTime();
minsLeft=current.secsTo(selected)/(60);
return minsLeft;
}
//show task per type
void MainWindow::on_actionUpcoming_triggered()
{
taskList list;
list.setTitle("Upcoming Tasks");
list.showUpcomingTask();
list.exec();
}
void MainWindow::on_actionPending_triggered()
{
taskList list;
list.setTitle("Pending Tasks");
list.exec();
}
void MainWindow::on_actionCompleted_triggered()
{
taskList list;
list.setTitle("Completed Tasks");
list.exec();
}
void MainWindow::on_actionExpired_triggered()
{
taskList list;
list.setTitle("Expired Tasks");
list.showExpiredTask();
list.exec();
}
|
[
"shariarabrar@gmail.com"
] |
shariarabrar@gmail.com
|
2ba9d3a63af5db8dcd147e59d50c81ff4e866358
|
f71b74eb0386711937c656f7813dadf70358a35b
|
/SearchingAndSorting/1_first_and_last_occ/first_and_last_occ.cpp
|
2d365cd0e2970c49f75dd96da51ddfabc47f3d81
|
[] |
no_license
|
tanishq1306/DSA-Solved-Questions
|
74e3d39ddd1014e11d7f649ac1cb9d25ee9ac56f
|
c9419717c7c62a32a317cecd747bc151fcf62f78
|
refs/heads/main
| 2023-05-31T13:17:33.632186
| 2021-06-07T12:32:57
| 2021-06-07T12:32:57
| 304,842,758
| 19
| 6
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 665
|
cpp
|
/**
* author: tanishq
* created: 17.12.2020
**/
#include <bits/stdc++.h>
#define int long long
using namespace std;
signed main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int test_case;
cin >> test_case;
while (test_case--) {
int n, k;
cin >> n >> k;
int first = -1, last = -1, x;
for (int i = 0; i < n; i++) {
cin >> x;
if (x == k) {
if (first == -1) {
first = i + 1;
last = i + 1;
}
else {
last = i + 1;
}
}
}
if (first == -1) {
cout << first << endl;
}
else {
cout << first << " " << last << endl;
}
}
return 0;
}
|
[
"52647176+tanishq1306@users.noreply.github.com"
] |
52647176+tanishq1306@users.noreply.github.com
|
2805a4352681e4161f0c683b344636a7cb207712
|
397e445e7c333731d1692d63bcb54f20f34104d0
|
/Allenamenti_OII/barbablu.cpp
|
b01a0c07509354c5a2af8799378097c144831eb4
|
[] |
no_license
|
xYinXiao/School
|
e66399e80dcdb9d60e3740df8812e5d1be38379a
|
e3a2999168050100a03ccf095ae9bbcac916814d
|
refs/heads/master
| 2021-01-10T01:17:58.024574
| 2017-04-07T09:34:39
| 2017-04-07T09:34:39
| 47,881,543
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,206
|
cpp
|
#include <stdio.h>
#include <assert.h>
#include <vector>
#include <algorithm>
#include <set>
#include <limits.h>
using namespace std;
vector<int> isAria(31, 0);
int nCabine, nCorridoi, tesoro, nAria;
struct edge {
int to, length;
};
struct Cmp {
bool operator()(const pair<int, pair<int, int> >& a, const pair<int, pair<int, int> >&b) {
return a.first < b.first;
}
};
int dijkstra(const vector< vector<edge> >& graph, int sorgente, int destinazione) {
vector<int> distanze_minime(graph.size() + 1, INT_MAX);
set< pair<int, pair<int, int> >, Cmp> nodi_attivi;
int ossigeno = 20;
distanze_minime[sorgente] = 0;
nodi_attivi.insert( {0, {sorgente, ossigeno}} );
set< pair<int, pair<int, int> >, Cmp>::iterator it;
while(!nodi_attivi.empty()) {
int u = nodi_attivi.begin()->second.first;
if (u == destinazione)
return distanze_minime[u];
it = nodi_attivi.find({distanze_minime[u], {u, ossigeno} });
ossigeno = (*it).second.second;
nodi_attivi.erase(nodi_attivi.begin());
for(edge dge : graph[u]) {
if ((distanze_minime[dge.to] > distanze_minime[u] + dge.length) && (ossigeno - dge.length > 0)) {
nodi_attivi.erase({distanze_minime[dge.to], {dge.to, ossigeno} });
distanze_minime[dge.to] = distanze_minime[u] + dge.length;
nodi_attivi.insert({distanze_minime[dge.to], {dge.to, ((isAria[dge.to]) ? 20 : ossigeno - dge.length)} });
}
}
}
return INT_MAX;
}
int main() {
FILE *in, *out;
int i;
vector< vector <edge> > graph(31);
in = fopen("input.txt", "r");
out = fopen("output.txt", "w");
fscanf(in, "%d%d%d%d", &nCabine, &nCorridoi, &tesoro, &nAria);
int a, b, peso;
for(i = 0;i < nAria;i++) {
fscanf(in, "%d", &a);
isAria[a] = 1;
}
for(i = 0;i < nCorridoi;i++) {
fscanf(in, "%d%d%d", &a, &b, &peso);
graph[a].push_back({b, peso});
graph[b].push_back({a, peso});
}
int dist = dijkstra(graph, 1, tesoro);
fprintf(out, "%d", ((dist != INT_MAX) ? dist : -1));
fclose(in);
fclose(out);
return 0;
}
|
[
"xyinxiao@gmail.com"
] |
xyinxiao@gmail.com
|
0e7a8c8d7ccca816988a6b70ba1488421272e6f9
|
2a5cb1983b0760e15806e66d54b4310aa7e0c47e
|
/init_mix/d3dUtility.cpp
|
e5f6d2a89f2454b8d3d09432590b51cbb9245c81
|
[] |
no_license
|
joker-hyt/directx_test
|
5914db56303cfc145bede9c4a014efd1440a38c1
|
e8c8ab76dffa8209f3d03497ccff8337905d88ab
|
refs/heads/master
| 2020-12-19T12:56:36.771328
| 2020-06-23T12:01:53
| 2020-06-23T12:01:53
| 235,739,799
| 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 4,316
|
cpp
|
#include "stdafx.h"
#include "d3dUtility.h"
#include "Resource.h"
HINSTANCE hInst; // 当前实例
TCHAR szTitle[MAX_LOADSTRING]; // 标题栏文本
TCHAR szWindowClass[MAX_LOADSTRING]; // 主窗口类名
D3DMATERIAL9 d3d::InitMtrl(D3DXCOLOR a, D3DXCOLOR d, D3DXCOLOR s, D3DXCOLOR e, float p)
{
D3DMATERIAL9 mtrl;
mtrl.Ambient = a;
mtrl.Diffuse = d;
mtrl.Specular = s;
mtrl.Emissive = e;
mtrl.Power = p;
return mtrl;
}
BOOL d3d::InitInstance(HINSTANCE hInstance, int nCmdShow)
{
HWND hWnd;
hInst = hInstance; // 将实例句柄存储在全局变量中
hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL);
if (!hWnd)
{
return FALSE;
}
IDirect3D9* d3d9 = Direct3DCreate9(D3D_SDK_VERSION);
D3DCAPS9 caps;
d3d9->GetDeviceCaps(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, &caps);
int vp = 0;
if(caps.DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT)
{
vp = D3DCREATE_HARDWARE_VERTEXPROCESSING;
}
else
{
vp = D3DCREATE_SOFTWARE_VERTEXPROCESSING;
}
D3DPRESENT_PARAMETERS d3dpp;
d3dpp.BackBufferWidth = 800;
d3dpp.BackBufferHeight = 600;
d3dpp.BackBufferFormat = D3DFMT_A8R8G8B8;
d3dpp.BackBufferCount = 1;
d3dpp.MultiSampleType = D3DMULTISAMPLE_NONE;
d3dpp.MultiSampleQuality = 0;
d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
d3dpp.hDeviceWindow = hWnd;
d3dpp.Windowed = true;
d3dpp.EnableAutoDepthStencil = true;
d3dpp.AutoDepthStencilFormat = D3DFMT_D24S8;
d3dpp.Flags = 0;
d3dpp.FullScreen_RefreshRateInHz = D3DPRESENT_RATE_DEFAULT;
d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
HRESULT hr = d3d9->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd, vp, &d3dpp, &device);
if(FAILED(hr))
{
MessageBox(hWnd, _T("Create Device Failed"), 0, 0);
}
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
return TRUE;
}
ATOM d3d::MyRegisterClass(HINSTANCE hInstance)
{
WNDCLASSEX wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = d3d::WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_INIT));
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wcex.lpszMenuName = MAKEINTRESOURCE(IDC_INIT);
wcex.lpszClassName = szWindowClass;
wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));
return RegisterClassEx(&wcex);
}
LRESULT CALLBACK d3d::WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
int wmId, wmEvent;
PAINTSTRUCT ps;
HDC hdc;
switch (msg)
{
case WM_COMMAND:
wmId = LOWORD(wParam);
wmEvent = HIWORD(wParam);
// 分析菜单选择:
switch (wmId)
{
case IDM_ABOUT:
//DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
break;
case IDM_EXIT:
DestroyWindow(hWnd);
break;
default:
return DefWindowProc(hWnd, msg, wParam, lParam);
}
break;
case WM_PAINT:
hdc = BeginPaint(hWnd, &ps);
// TODO: 在此添加任意绘图代码...
EndPaint(hWnd, &ps);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, msg, wParam, lParam);
}
return 0;
}
bool d3d::InitD3D(HINSTANCE hInstance, int width, int height, bool windowed, int nCmdShow, D3DDEVTYPE deviceType, IDirect3DDevice9** device)
{
// 初始化全局字符串
LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
LoadString(hInstance, IDC_INIT, szWindowClass, MAX_LOADSTRING);
MyRegisterClass(hInstance);
// 执行应用程序初始化:
if (!InitInstance (hInstance, nCmdShow))
{
return FALSE;
}
return TRUE;
}
int d3d::EnterMsgLoop(bool (*ptr_display)(float timeDelta))
{
MSG msg;
ZeroMemory(&msg, sizeof(msg));
static float lastTime = (float)timeGetTime();
while(msg.message != WM_QUIT)
{
if(PeekMessage(&msg, 0, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
else
{
float currTime = (float)timeGetTime();
float timeDelta = (currTime - lastTime) * 0.001f;
ptr_display(timeDelta);
lastTime = currTime;
}
}
return 0;
}
|
[
"joker.hyt@gmail.com"
] |
joker.hyt@gmail.com
|
08ec1d7ac1b6358c529a76c8a501c86af9946748
|
93becb0e207e95d75dbb05c92c08c07402bcc492
|
/yuki/no804.cpp
|
5bf79b2b6419d06fc0daeda776fd4c216feae9f1
|
[] |
no_license
|
veqcc/atcoder
|
2c5f12e12704ca8eace9e2e1ec46a354f1ec71ed
|
cc3b30a818ba2f90c4d29c74b4d2231e8bca1903
|
refs/heads/master
| 2023-04-14T21:39:29.705256
| 2023-04-10T02:31:49
| 2023-04-10T02:31:49
| 136,691,016
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 600
|
cpp
|
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <cstring>
#include <string>
#include <vector>
#include <random>
#include <bitset>
#include <queue>
#include <cmath>
#include <stack>
#include <set>
#include <map>
typedef long long ll;
using namespace std;
const ll MOD = 1000000007LL;
int main() {
int a, b, c, d;
cin >> a >> b >> c >> d;
int ans = 0;
while (true) {
if (a == 0) break;
if (b < c) break;
if (d < 1 + c) break;
a--;
b -= c;
d -= 1 + c;
ans++;
}
cout << ans << "\n";
return 0;
}
|
[
"kambe3141@gmail.com"
] |
kambe3141@gmail.com
|
be4e5dac92c8380bfbfb6e0e2ea4eb003314f52e
|
b67a780af96a1b70569f81def205f2adbe328292
|
/Demo/String/SubString/BFSubString.cpp
|
39c6ac1a77fc44feaed94c7d20723d1933d5e83f
|
[] |
no_license
|
doquanghuy/Algorithm
|
8c27933c5c42b4324b39e061c43542adf4a6372b
|
4dd63edd823bd0a158034e281c37ef1f6704ec9c
|
refs/heads/master
| 2020-04-13T18:52:44.872226
| 2019-01-16T15:04:48
| 2019-01-16T15:04:48
| 163,387,254
| 0
| 0
| null | 2019-01-16T14:21:06
| 2018-12-28T08:36:31
| null |
UTF-8
|
C++
| false
| false
| 611
|
cpp
|
//
// BFSubString.cpp
// Demo
//
// Created by Quang Huy on 1/11/19.
// Copyright © 2019 Techmaster. All rights reserved.
//
#include "BFSubString.hpp"
BFSubString:: BFSubString(std:: string pat) {
this -> pat = pat;
}
unsigned long BFSubString:: search(std:: string txt) {
unsigned long M = pat.length();
unsigned long N = txt.length();
for (int i = 0; i < N - M; i++) {
for (int j = 0; j < M; j++) {
if (pat[j] != txt[i + j]) {
break;
} else if (j == M - 1) {
return i;
}
}
}
return N;
}
|
[
"sin.do@mobiclixgroup.com"
] |
sin.do@mobiclixgroup.com
|
bc964aa465b039a826dfc67367370cd4125c4b01
|
4040d743d3cc4af68773b659947a92a5acbb07de
|
/LIB/far3/src/~message/box.cpp
|
66756a0816abacd2f27492173b64bf59ddf3020b
|
[] |
no_license
|
msxxxp/main
|
67072e745a550b6bc58c2b3cb9f3d6d55a6bdf3a
|
904da0db6239b4d1baf7644037bf1326592e64c1
|
refs/heads/master
| 2020-12-24T19:18:02.182013
| 2014-12-02T17:15:07
| 2014-12-02T17:15:07
| 30,285,895
| 1
| 0
| null | 2015-02-04T06:55:42
| 2015-02-04T06:55:41
| null |
UTF-8
|
C++
| false
| false
| 2,343
|
cpp
|
/**
© 2014 Andrew Grechkin
Source code: <http://code.google.com/p/andrew-grechkin>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
**/
#include <far3/message.hpp>
namespace far3 {
namespace message {
void ibox(PCWSTR text, PCWSTR tit)
{
PCWSTR Msg[] = {tit, text};
psi().Message(get_plugin_guid(), nullptr, FMSG_MB_OK, nullptr, Msg, lengthof(Msg), 1);
}
void mbox(PCWSTR text, PCWSTR tit)
{
PCWSTR Msg[] = {tit, text};
psi().Message(get_plugin_guid(), nullptr, FMSG_MB_OK, nullptr, Msg, lengthof(Msg), 1);
}
void ebox(PCWSTR text, PCWSTR tit)
{
PCWSTR Msg[] = {tit, text};
psi().Message(get_plugin_guid(), nullptr, FMSG_WARNING | FMSG_MB_OK, nullptr, Msg, lengthof(Msg), 1);
}
void ebox(PCWSTR msgs[], size_t size, PCWSTR help)
{
psi().Message(get_plugin_guid(), nullptr, FMSG_WARNING | FMSG_MB_OK, help, msgs, size, 1);
}
// void ebox(const cstr::mstring& msg, PCWSTR title)
// {
// size_t len = msg.size() + 1;
// PCWSTR tmp[len];
// tmp[0] = title;
// for (size_t i = 0; i < msg.size(); ++i) {
// tmp[i + 1] = msg[i];
// }
// psi().Message(get_plugin_guid(), nullptr, FMSG_WARNING | FMSG_MB_OK, nullptr, tmp, len, 1);
// }
//
void ebox(DWORD err)
{
// ustring title(L"Error: ");
// title += Base::as_str(err);
::SetLastError(err);
// PCWSTR Msg[] = {title.c_str(), L"OK", };
psi().Message(get_plugin_guid(), nullptr, FMSG_WARNING | FMSG_ERRORTYPE | FMSG_MB_OK, nullptr, nullptr, 0, 0);
}
bool question(PCWSTR text, PCWSTR tit)
{
PCWSTR Msg[] = {tit, text};
return psi().Message(get_plugin_guid(), nullptr, FMSG_WARNING | FMSG_MB_OKCANCEL, nullptr, Msg, lengthof(Msg), 2) == 0;
}
}
}
|
[
"andrew.grechkin@gmail.com"
] |
andrew.grechkin@gmail.com
|
5541fe1844c972951f15a8a1bef8186e2353815e
|
f2c3efa6db82fd8e59fa39c43c7768ede38d02f0
|
/include/polimidl/internal/runner.hpp
|
686991306439ac5cdcc84d4ca928ecb634a59bc2
|
[
"MIT"
] |
permissive
|
darianfrajberg/polimidl
|
ce6e260e86149064142cfc87096884f42eb45481
|
ab338269c25a0fcccf06bbfccbfe7fe16ee7cf04
|
refs/heads/master
| 2021-07-05T03:49:41.119174
| 2020-09-20T21:04:22
| 2020-09-20T21:04:22
| 176,907,084
| 3
| 2
|
MIT
| 2020-09-20T21:04:23
| 2019-03-21T08:58:51
|
C++
|
UTF-8
|
C++
| false
| false
| 8,005
|
hpp
|
#ifndef POLIMIDL_INTERNAL_RUNNER_HPP
#define POLIMIDL_INTERNAL_RUNNER_HPP
#include <chrono>
#include <sstream>
#include <type_traits>
#include "./memory_layout.hpp"
namespace polimidl {
namespace internal {
template <typename layer_t>
std::size_t input_size_of(std::size_t input_rows, std::size_t input_columns) {
return layer_t::input_components * input_rows * input_columns;
}
template <typename layer_t>
std::size_t output_size_of(std::size_t ouput_rows, std::size_t output_columns) {
return layer_t::output_components * ouput_rows * output_columns;
}
template <std::size_t alignment, typename type_t, bool is_inverted,
typename... Layers>
class runner {};
template <std::size_t alignment, typename type_t, bool is_inverted,
typename layer_t>
class runner<alignment, type_t, is_inverted, layer_t> {
public:
runner(span<type_t> buffer, std::size_t input_rows, std::size_t input_columns,
unsigned int number_of_workers, layer_t&& layer) :
layer_(std::forward<layer_t>(layer)),
input_rows_(input_rows),
input_columns_(input_columns),
output_rows_(layer_t::output_rows(input_rows_)),
output_columns_(layer_t::output_columns(input_columns_)),
input_(
input_of<alignment, layer_t, is_inverted>(buffer, this->input_size())),
temporary_(temporary_of<alignment, layer_t, is_inverted>(
buffer, this->input_size(), this->output_size(), number_of_workers)),
output_(
output_of<alignment, layer_t, is_inverted>(buffer,
this->output_size())),
accumulated_execution_duration_(0) {}
std::size_t input_rows() const { return input_rows_; }
std::size_t input_columns() const { return input_columns_; }
std::size_t input_components() const {
return layer_t::input_components;
}
std::size_t input_size() const {
return input_size_of<layer_t>(input_rows(), input_columns());
}
std::size_t output_rows() const { return output_rows_; }
std::size_t output_columns() const { return output_columns_; }
std::size_t output_components() const {
return layer_t::output_components;
}
std::size_t output_size() const {
return output_size_of<layer_t>(output_rows(), output_columns());
}
span<type_t> input() const { return input_; }
span<type_t> output() const { return output_; }
template <typename scheduler_t>
void run(const scheduler_t& scheduler) const {
layer_(input(), temporary_, output(), input_rows(), input_columns(),
scheduler);
}
template <typename scheduler_t>
void run_with_statistics(const scheduler_t& scheduler) {
using std::chrono::high_resolution_clock;
const auto start = high_resolution_clock::now();
layer_(input(), temporary_, output(), input_rows(), input_columns(),
scheduler);
accumulated_execution_duration_ += high_resolution_clock::now() - start;
}
template <typename scheduler_t>
void optimize_for(const scheduler_t& scheduler) {
layer_.optimize_for(input(), temporary_, output(), input_rows(),
input_columns(), scheduler);
}
void print_statistics(std::stringstream& stream, std::size_t position,
std::size_t accumulated_executions) {
stream << "Layer " << position << " Avg Time = "
<< std::chrono::duration_cast<std::chrono::microseconds>(
accumulated_execution_duration_ / accumulated_executions).count()
<< " microseconds" << std::endl;
}
private:
static_assert(std::is_same<type_t, typename layer_t::type_t>::value,
"The layer is not of the same data type of the network");
layer_t layer_;
std::size_t input_rows_;
std::size_t input_columns_;
std::size_t output_rows_;
std::size_t output_columns_;
span<type_t> input_;
span<type_t> temporary_;
span<type_t> output_;
std::chrono::high_resolution_clock::duration accumulated_execution_duration_;
};
template <std::size_t alignment, typename type_t, bool is_inverted,
typename layer_t, typename next_layer_t, typename... Layers>
class runner<alignment, type_t, is_inverted, layer_t, next_layer_t, Layers...> {
public:
runner(span<type_t> buffer, std::size_t input_rows, std::size_t input_columns,
unsigned int number_of_workers, layer_t&& layer,
next_layer_t&& next_layer, Layers&&... layers) :
layer_(std::forward<layer_t>(layer)),
input_rows_(input_rows),
input_columns_(input_columns),
next_runner_(buffer, layer_t::output_rows(input_rows_),
layer_t::output_columns(input_columns_),
number_of_workers,
std::forward<next_layer_t>(next_layer),
std::forward<Layers>(layers)...),
input_(
input_of<alignment, layer_t, is_inverted>(buffer, this->input_size())),
temporary_(temporary_of<alignment, layer_t, is_inverted>(
buffer, this->input_size(), next_runner_.input_size(),
number_of_workers)),
accumulated_execution_duration_(0) {}
std::size_t input_rows() const { return input_rows_; }
std::size_t input_columns() const { return input_columns_; }
std::size_t input_components() const {
return layer_t::input_components;
}
std::size_t input_size() const {
return input_size_of<layer_t>(input_rows(), input_columns());
}
std::size_t output_rows() const { return next_runner_.output_rows(); }
std::size_t output_columns() const { return next_runner_.output_columns(); }
std::size_t output_components() const {
return next_runner_.output_components();
}
std::size_t output_size() const { return next_runner_.output_size(); }
span<type_t> input() const { return input_; }
span<type_t> output() const { return next_runner_.output(); }
template <typename scheduler_t>
void run(const scheduler_t& scheduler) const {
layer_(input(), temporary_, next_runner_.input(), input_rows(),
input_columns(), scheduler);
next_runner_.run(scheduler);
}
template <typename scheduler_t>
void run_with_statistics(const scheduler_t& scheduler) {
using std::chrono::high_resolution_clock;
const auto start = high_resolution_clock::now();
layer_(input(), temporary_, next_runner_.input(), input_rows(),
input_columns(), scheduler);
accumulated_execution_duration_ += high_resolution_clock::now() - start;
next_runner_.run_with_statistics(scheduler);
}
template <typename scheduler_t>
void optimize_for(const scheduler_t& scheduler) {
layer_.optimize_for(input(), temporary_, next_runner_.input(), input_rows(),
input_columns(), scheduler);
next_runner_.optimize_for(scheduler);
}
void print_statistics(std::stringstream& stream, std::size_t position,
std::size_t accumulated_executions) {
stream << "Layer " << ++position << " Avg Time = "
<< std::chrono::duration_cast<std::chrono::microseconds>(
accumulated_execution_duration_ / accumulated_executions).count()
<< " microseconds" << std::endl;
next_runner_.print_statistics(stream, position, accumulated_executions);
}
private:
static_assert(std::is_same<type_t, typename layer_t::type_t>::value,
"The layer is not of the same data type of the network");
static_assert(layer_t::output_components == next_layer_t::input_components,
"The number of output components of this layer is different "
"from the number of input components in the next one");
layer_t layer_;
std::size_t input_rows_;
std::size_t input_columns_;
static constexpr bool is_next_layer_inverted =
(is_inverted && layer_t::is_in_place) ||
(!is_inverted && !layer_t::is_in_place);
runner<alignment, type_t, is_next_layer_inverted, next_layer_t, Layers...>
next_runner_;
span<type_t> input_;
span<type_t> temporary_;
std::chrono::high_resolution_clock::duration accumulated_execution_duration_;
};
}
}
#endif // POLIMIDL_INTERNAL_RUNNER_HPP
|
[
"darian.frajberg@polimi.it"
] |
darian.frajberg@polimi.it
|
0d3a9680bfb8459b4975b6be95f177bc7afd429c
|
b26cde55d82cda91243f945dc9d31f7ab3e8fb78
|
/src/qt/bitcoingui.cpp
|
af676d185a223d330aad9a5d59ca228126e2e141
|
[
"MIT"
] |
permissive
|
GridBit/GridBit
|
e6482e999e785db051a813b5036b0aef1686fd52
|
4de0669d6c7a9b053ae24c570f211335390da396
|
refs/heads/master
| 2016-09-09T21:31:31.635190
| 2014-08-18T08:39:10
| 2014-08-18T08:39:10
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 38,119
|
cpp
|
/*
* Qt4 bitcoin GUI.
*
* W.J. van der Laan 2011-2012
* The Bitcoin Developers 2011-2012
*/
#include "bitcoingui.h"
#include "transactiontablemodel.h"
#include "addressbookpage.h"
#include "sendcoinsdialog.h"
#include "signverifymessagedialog.h"
#include "optionsdialog.h"
#include "aboutdialog.h"
#include "clientmodel.h"
#include "walletmodel.h"
#include "editaddressdialog.h"
#include "optionsmodel.h"
#include "transactiondescdialog.h"
#include "addresstablemodel.h"
#include "transactionview.h"
#include "overviewpage.h"
#include "bitcoinunits.h"
#include "guiconstants.h"
#include "askpassphrasedialog.h"
#include "notificator.h"
#include "guiutil.h"
#include "rpcconsole.h"
#include "wallet.h"
#include "bitcoinrpc.h"
#ifdef Q_OS_MAC
#include "macdockiconhandler.h"
#endif
#include <QApplication>
#include <QMainWindow>
#include <QMenuBar>
#include <QMenu>
#include <QIcon>
#include <QTabWidget>
#include <QVBoxLayout>
#include <QToolBar>
#include <QStatusBar>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <QLocale>
#include <QMessageBox>
#include <QProgressBar>
#include <QStackedWidget>
#include <QDateTime>
#include <QMovie>
#include <QFileDialog>
#include <QDesktopServices>
#include <QTimer>
#include <QDragEnterEvent>
#include <QUrl>
#include <QStyle>
#include <QMimeData>
#include <iostream>
extern CWallet *pwalletMain;
extern int64 nLastCoinStakeSearchInterval;
BitcoinGUI::BitcoinGUI(QWidget *parent):
QMainWindow(parent),
clientModel(0),
walletModel(0),
encryptWalletAction(0),
changePassphraseAction(0),
lockWalletToggleAction(0),
aboutQtAction(0),
trayIcon(0),
notificator(0),
rpcConsole(0)
{
resize(850, 550);
setWindowTitle(tr("GridBit") + " - " + tr("Wallet"));
#ifndef Q_OS_MAC
qApp->setWindowIcon(QIcon(":icons/bitcoin"));
setWindowIcon(QIcon(":icons/bitcoin"));
#else
setUnifiedTitleAndToolBarOnMac(true);
QApplication::setAttribute(Qt::AA_DontShowIconsInMenus);
#endif
// Accept D&D of URIs
setAcceptDrops(true);
setObjectName("TheWallet");
setStyleSheet("#TheWallet { background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:1, stop:0 #eeeeee, stop:1.0 #fefefe); } QToolTip { color: #cecece; background-color: #333333; border:0px;} ");
// Create actions for the toolbar, menu bar and tray/dock icon
createActions();
// Create application menu bar
createMenuBar();
// Create the toolbars
createToolBars();
// Create the tray icon (or setup the dock icon)
createTrayIcon();
// Create tabs
overviewPage = new OverviewPage();
transactionsPage = new QWidget(this);
QVBoxLayout *vbox = new QVBoxLayout();
transactionView = new TransactionView(this);
vbox->addWidget(transactionView);
transactionsPage->setLayout(vbox);
addressBookPage = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::SendingTab);
receiveCoinsPage = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::ReceivingTab);
sendCoinsPage = new SendCoinsDialog(this);
signVerifyMessageDialog = new SignVerifyMessageDialog(this);
centralWidget = new QStackedWidget(this);
centralWidget->addWidget(overviewPage);
centralWidget->addWidget(transactionsPage);
centralWidget->addWidget(addressBookPage);
centralWidget->addWidget(receiveCoinsPage);
centralWidget->addWidget(sendCoinsPage);
setCentralWidget(centralWidget);
// Create status bar
statusBar();
// Status bar notification icons
QFrame *frameBlocks = new QFrame();
frameBlocks->setContentsMargins(0,0,0,0);
frameBlocks->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred);
QHBoxLayout *frameBlocksLayout = new QHBoxLayout(frameBlocks);
frameBlocksLayout->setContentsMargins(3,0,3,0);
frameBlocksLayout->setSpacing(3);
labelEncryptionIcon = new QLabel();
labelMintingIcon = new QLabel();
labelConnectionsIcon = new QLabel();
labelBlocksIcon = new QLabel();
frameBlocksLayout->addStretch();
frameBlocksLayout->addWidget(labelEncryptionIcon);
frameBlocksLayout->addStretch();
frameBlocksLayout->addWidget(labelMintingIcon);
frameBlocksLayout->addStretch();
frameBlocksLayout->addWidget(labelConnectionsIcon);
frameBlocksLayout->addStretch();
frameBlocksLayout->addWidget(labelBlocksIcon);
frameBlocksLayout->addStretch();
labelEncryptionIcon->setObjectName("labelEncryptionIcon");
labelConnectionsIcon->setObjectName("labelConnectionsIcon");
labelBlocksIcon->setObjectName("labelBlocksIcon");
labelMintingIcon->setObjectName("labelMintingIcon");
labelEncryptionIcon->setStyleSheet("#labelEncryptionIcon QToolTip {color:#cecece;background-color:#333333;border:0px;}");
labelConnectionsIcon->setStyleSheet("#labelConnectionsIcon QToolTip {color:#cecece;background-color:#333333;border:0px;}");
labelBlocksIcon->setStyleSheet("#labelBlocksIcon QToolTip {color:#cecece;background-color:#333333;border:0px;}");
labelMintingIcon->setStyleSheet("#labelMintingIcon QToolTip {color:#cecece;background-color:#333333;border:0px;}");
// Set minting pixmap
labelMintingIcon->setPixmap(QIcon(":/icons/minting").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));
labelMintingIcon->setEnabled(false);
// Add timer to update minting icon
QTimer *timerMintingIcon = new QTimer(labelMintingIcon);
timerMintingIcon->start(MODEL_UPDATE_DELAY);
connect(timerMintingIcon, SIGNAL(timeout()), this, SLOT(updateMintingIcon()));
// Add timer to update minting weights
QTimer *timerMintingWeights = new QTimer(labelMintingIcon);
timerMintingWeights->start(30 * 1000);
connect(timerMintingWeights, SIGNAL(timeout()), this, SLOT(updateMintingWeights()));
// Set initial values for user and network weights
nWeight, nNetworkWeight = 0;
// Progress bar and label for blocks download
progressBarLabel = new QLabel();
progressBarLabel->setVisible(false);
progressBar = new QProgressBar();
progressBar->setAlignment(Qt::AlignCenter);
progressBar->setVisible(false);
// Override style sheet for progress bar for styles that have a segmented progress bar,
// as they make the text unreadable (workaround for issue #1071)
// See https://qt-project.org/doc/qt-4.8/gallery.html
QString curStyle = qApp->style()->metaObject()->className();
if(curStyle == "QWindowsStyle" || curStyle == "QWindowsXPStyle")
{
progressBar->setStyleSheet("QProgressBar { background-color: #e8e8e8; border: 1px solid grey; border-radius: 7px; padding: 1px; text-align: center; } QProgressBar::chunk { background: QLinearGradient(x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 #FF8000, stop: 1 orange); border-radius: 7px; margin: 0px; }");
}
statusBar()->addWidget(progressBarLabel);
statusBar()->addWidget(progressBar);
statusBar()->addPermanentWidget(frameBlocks);
statusBar()->setObjectName("TheStatusBar");
statusBar()->setStyleSheet("#TheStatusBar { border-top-color: #102056; border-top-width: 2px; border-top-style: inset; background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:0, y2:1, stop:0 #102056, stop:1.0 #0a1536); background-image: url(:images/shadowbar); background-repeat: repeat-x; background-position: bottom center; color: #ffffff; }");
syncIconMovie = new QMovie(":/movies/update_spinner", "mng", this);
// this->setStyleSheet("background-color: #effbef;");
// Clicking on a transaction on the overview page simply sends you to transaction history page
connect(overviewPage, SIGNAL(transactionClicked(QModelIndex)), this, SLOT(gotoHistoryPage()));
connect(overviewPage, SIGNAL(transactionClicked(QModelIndex)), transactionView, SLOT(focusTransaction(QModelIndex)));
// Double-clicking on a transaction on the transaction history page shows details
connect(transactionView, SIGNAL(doubleClicked(QModelIndex)), transactionView, SLOT(showDetails()));
rpcConsole = new RPCConsole(this);
connect(openRPCConsoleAction, SIGNAL(triggered()), rpcConsole, SLOT(show()));
// Clicking on "Verify Message" in the address book sends you to the verify message tab
connect(addressBookPage, SIGNAL(verifyMessage(QString)), this, SLOT(gotoVerifyMessageTab(QString)));
// Clicking on "Sign Message" in the receive coins page sends you to the sign message tab
connect(receiveCoinsPage, SIGNAL(signMessage(QString)), this, SLOT(gotoSignMessageTab(QString)));
gotoOverviewPage();
}
BitcoinGUI::~BitcoinGUI()
{
if(trayIcon) // Hide tray icon, as deleting will let it linger until quit (on Ubuntu)
trayIcon->hide();
#ifdef Q_OS_MAC
delete appMenuBar;
#endif
}
void BitcoinGUI::createActions()
{
QActionGroup *tabGroup = new QActionGroup(this);
overviewAction = new QAction(QIcon(":/icons/overview"), tr("&Overview"), this);
overviewAction->setToolTip(tr("Show general overview of wallet"));
overviewAction->setCheckable(true);
overviewAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_1));
tabGroup->addAction(overviewAction);
sendCoinsAction = new QAction(QIcon(":/icons/send"), tr("&Send coins"), this);
sendCoinsAction->setToolTip(tr("Send coins to a GridBit address"));
sendCoinsAction->setCheckable(true);
sendCoinsAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_2));
tabGroup->addAction(sendCoinsAction);
receiveCoinsAction = new QAction(QIcon(":/icons/receiving_addresses"), tr("&Receive coins"), this);
receiveCoinsAction->setToolTip(tr("Show the list of addresses for receiving payments"));
receiveCoinsAction->setCheckable(true);
receiveCoinsAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_3));
tabGroup->addAction(receiveCoinsAction);
historyAction = new QAction(QIcon(":/icons/history"), tr("&Transactions"), this);
historyAction->setToolTip(tr("Browse transaction history"));
historyAction->setCheckable(true);
historyAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_4));
tabGroup->addAction(historyAction);
addressBookAction = new QAction(QIcon(":/icons/address-book"), tr("&Address Book"), this);
addressBookAction->setToolTip(tr("Edit the list of stored addresses and labels"));
addressBookAction->setCheckable(true);
addressBookAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_5));
tabGroup->addAction(addressBookAction);
connect(overviewAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(overviewAction, SIGNAL(triggered()), this, SLOT(gotoOverviewPage()));
connect(sendCoinsAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(sendCoinsAction, SIGNAL(triggered()), this, SLOT(gotoSendCoinsPage()));
connect(receiveCoinsAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(receiveCoinsAction, SIGNAL(triggered()), this, SLOT(gotoReceiveCoinsPage()));
connect(historyAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(historyAction, SIGNAL(triggered()), this, SLOT(gotoHistoryPage()));
connect(addressBookAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(addressBookAction, SIGNAL(triggered()), this, SLOT(gotoAddressBookPage()));
quitAction = new QAction(QIcon(":/icons/quit"), tr("E&xit"), this);
quitAction->setToolTip(tr("Quit application"));
quitAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Q));
quitAction->setMenuRole(QAction::QuitRole);
aboutAction = new QAction(QIcon(":/icons/bitcoin"), tr("&About GridBit"), this);
aboutAction->setToolTip(tr("Show information about GridBit"));
aboutAction->setMenuRole(QAction::AboutRole);
aboutQtAction = new QAction(QIcon(":/trolltech/qmessagebox/images/qtlogo-64.png"), tr("About &Qt"), this);
aboutQtAction->setToolTip(tr("Show information about Qt"));
aboutQtAction->setMenuRole(QAction::AboutQtRole);
optionsAction = new QAction(QIcon(":/icons/options"), tr("&Options..."), this);
optionsAction->setToolTip(tr("Modify configuration options for GridBit"));
optionsAction->setMenuRole(QAction::PreferencesRole);
toggleHideAction = new QAction(QIcon(":/icons/bitcoin"), tr("&Show / Hide"), this);
encryptWalletAction = new QAction(QIcon(":/icons/lock_closed"), tr("&Encrypt Wallet..."), this);
encryptWalletAction->setToolTip(tr("Encrypt or decrypt wallet"));
encryptWalletAction->setCheckable(true);
backupWalletAction = new QAction(QIcon(":/icons/filesave"), tr("&Backup Wallet..."), this);
backupWalletAction->setToolTip(tr("Backup wallet to another location"));
changePassphraseAction = new QAction(QIcon(":/icons/key"), tr("&Change Passphrase..."), this);
changePassphraseAction->setToolTip(tr("Change the passphrase used for wallet encryption"));
lockWalletToggleAction = new QAction(this);
signMessageAction = new QAction(QIcon(":/icons/edit"), tr("Sign &message..."), this);
verifyMessageAction = new QAction(QIcon(":/icons/transaction_0"), tr("&Verify message..."), this);
exportAction = new QAction(QIcon(":/icons/export"), tr("&Export..."), this);
exportAction->setToolTip(tr("Export the data in the current tab to a file"));
openRPCConsoleAction = new QAction(QIcon(":/icons/debugwindow"), tr("&Debug window"), this);
openRPCConsoleAction->setToolTip(tr("Open debugging and diagnostic console"));
connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
connect(aboutAction, SIGNAL(triggered()), this, SLOT(aboutClicked()));
connect(aboutQtAction, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
connect(optionsAction, SIGNAL(triggered()), this, SLOT(optionsClicked()));
connect(toggleHideAction, SIGNAL(triggered()), this, SLOT(toggleHidden()));
connect(encryptWalletAction, SIGNAL(triggered(bool)), this, SLOT(encryptWallet(bool)));
connect(backupWalletAction, SIGNAL(triggered()), this, SLOT(backupWallet()));
connect(changePassphraseAction, SIGNAL(triggered()), this, SLOT(changePassphrase()));
connect(lockWalletToggleAction, SIGNAL(triggered()), this, SLOT(lockWalletToggle()));
connect(signMessageAction, SIGNAL(triggered()), this, SLOT(gotoSignMessageTab()));
connect(verifyMessageAction, SIGNAL(triggered()), this, SLOT(gotoVerifyMessageTab()));
}
void BitcoinGUI::createMenuBar()
{
#ifdef Q_OS_MAC
// Create a decoupled menu bar on Mac which stays even if the window is closed
appMenuBar = new QMenuBar();
#else
// Get the main window's menu bar on other platforms
appMenuBar = menuBar();
#endif
// Configure the menus
QMenu *file = appMenuBar->addMenu(tr("&File"));
file->addAction(backupWalletAction);
file->addAction(exportAction);
file->addAction(signMessageAction);
file->addAction(verifyMessageAction);
file->addSeparator();
file->addAction(quitAction);
QMenu *settings = appMenuBar->addMenu(tr("&Settings"));
settings->addAction(encryptWalletAction);
settings->addAction(changePassphraseAction);
settings->addAction(lockWalletToggleAction);
settings->addSeparator();
settings->addAction(optionsAction);
QMenu *help = appMenuBar->addMenu(tr("&Help"));
help->addAction(openRPCConsoleAction);
help->addSeparator();
help->addAction(aboutAction);
help->addAction(aboutQtAction);
// QString ss("QMenuBar::item { background-color: #effbef; color: black }");
// appMenuBar->setStyleSheet(ss);
}
void BitcoinGUI::createToolBars()
{
QToolBar *toolbar = addToolBar(tr("Tabs toolbar"));
toolbar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
toolbar->addAction(overviewAction);
toolbar->addAction(sendCoinsAction);
toolbar->addAction(receiveCoinsAction);
toolbar->addAction(historyAction);
toolbar->addAction(addressBookAction);
QToolBar *toolbar2 = addToolBar(tr("Actions toolbar"));
toolbar2->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
toolbar2->addAction(lockWalletToggleAction);
toolbar2->addAction(exportAction);
toolbar->setObjectName("tabsToolbar");
toolbar2->setObjectName("actionsToolbar");
const char ss[] = "QToolButton { min-height:48px;color:#ffffff;border:none;margin:0px;padding:0px;} QToolButton:hover { color: #ffffff; background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:0, y2:1, stop:0 #00bff3, stop:1.0 #0083a9); margin:0px; padding:0px; border:none; } QToolButton:checked, QToolButton:pressed, QToolButton:selected { color: #ffffff; background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:0, y2:1, stop:0 #0a1536, stop:1.0 #08102a); margin:0px; padding:0px; border:none;} #tabsToolbar, #actionsToolbar, QToolBar::handle { min-height:48px; color: #ffffff; background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:0, y2:1, stop:0 #102056, stop:1.0 #0c183d); margin:0px; padding:0px; border:none;}";
toolbar->setStyleSheet(ss);
toolbar2->setStyleSheet(ss);
}
void BitcoinGUI::setClientModel(ClientModel *clientModel)
{
this->clientModel = clientModel;
if(clientModel)
{
// Replace some strings and icons, when using the testnet
if(clientModel->isTestNet())
{
setWindowTitle(windowTitle() + QString(" ") + tr("[testnet]"));
#ifndef Q_OS_MAC
qApp->setWindowIcon(QIcon(":icons/bitcoin_testnet"));
setWindowIcon(QIcon(":icons/bitcoin_testnet"));
#else
MacDockIconHandler::instance()->setIcon(QIcon(":icons/bitcoin_testnet"));
#endif
if(trayIcon)
{
trayIcon->setToolTip(tr("GridBit client") + QString(" ") + tr("[testnet]"));
trayIcon->setIcon(QIcon(":/icons/toolbar_testnet"));
toggleHideAction->setIcon(QIcon(":/icons/toolbar_testnet"));
}
aboutAction->setIcon(QIcon(":/icons/toolbar_testnet"));
}
// Keep up to date with client
setNumConnections(clientModel->getNumConnections());
connect(clientModel, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int)));
setNumBlocks(clientModel->getNumBlocks(), clientModel->getNumBlocksOfPeers());
connect(clientModel, SIGNAL(numBlocksChanged(int,int)), this, SLOT(setNumBlocks(int,int)));
// Report errors from network/worker thread
connect(clientModel, SIGNAL(error(QString,QString,bool)), this, SLOT(error(QString,QString,bool)));
rpcConsole->setClientModel(clientModel);
addressBookPage->setOptionsModel(clientModel->getOptionsModel());
receiveCoinsPage->setOptionsModel(clientModel->getOptionsModel());
}
}
void BitcoinGUI::setWalletModel(WalletModel *walletModel)
{
this->walletModel = walletModel;
if(walletModel)
{
// Report errors from wallet thread
connect(walletModel, SIGNAL(error(QString,QString,bool)), this, SLOT(error(QString,QString,bool)));
// Put transaction list in tabs
transactionView->setModel(walletModel);
overviewPage->setModel(walletModel);
addressBookPage->setModel(walletModel->getAddressTableModel());
receiveCoinsPage->setModel(walletModel->getAddressTableModel());
sendCoinsPage->setModel(walletModel);
signVerifyMessageDialog->setModel(walletModel);
setEncryptionStatus(walletModel->getEncryptionStatus());
connect(walletModel, SIGNAL(encryptionStatusChanged(int)), this, SLOT(setEncryptionStatus(int)));
// Balloon pop-up for new transaction
connect(walletModel->getTransactionTableModel(), SIGNAL(rowsInserted(QModelIndex,int,int)),
this, SLOT(incomingTransaction(QModelIndex,int,int)));
// Ask for passphrase if needed
connect(walletModel, SIGNAL(requireUnlock()), this, SLOT(unlockWallet()));
}
}
void BitcoinGUI::createTrayIcon()
{
QMenu *trayIconMenu;
#ifndef Q_OS_MAC
trayIcon = new QSystemTrayIcon(this);
trayIconMenu = new QMenu(this);
trayIcon->setContextMenu(trayIconMenu);
trayIcon->setToolTip(tr("GridBit client"));
trayIcon->setIcon(QIcon(":/icons/toolbar"));
connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
this, SLOT(trayIconActivated(QSystemTrayIcon::ActivationReason)));
trayIcon->show();
#else
// Note: On Mac, the dock icon is used to provide the tray's functionality.
MacDockIconHandler *dockIconHandler = MacDockIconHandler::instance();
trayIconMenu = dockIconHandler->dockMenu();
dockIconHandler->setMainWindow((QMainWindow*)this);
#endif
// Configuration of the tray icon (or dock icon) icon menu
trayIconMenu->addAction(toggleHideAction);
trayIconMenu->addSeparator();
trayIconMenu->addAction(sendCoinsAction);
trayIconMenu->addAction(receiveCoinsAction);
trayIconMenu->addSeparator();
trayIconMenu->addAction(signMessageAction);
trayIconMenu->addAction(verifyMessageAction);
trayIconMenu->addSeparator();
trayIconMenu->addAction(optionsAction);
trayIconMenu->addAction(openRPCConsoleAction);
#ifndef Q_OS_MAC // This is built-in on Mac
trayIconMenu->addSeparator();
trayIconMenu->addAction(quitAction);
#endif
notificator = new Notificator(qApp->applicationName(), trayIcon);
}
#ifndef Q_OS_MAC
void BitcoinGUI::trayIconActivated(QSystemTrayIcon::ActivationReason reason)
{
if(reason == QSystemTrayIcon::Trigger)
{
// Click on system tray icon triggers show/hide of the main window
toggleHideAction->trigger();
}
}
#endif
void BitcoinGUI::optionsClicked()
{
if(!clientModel || !clientModel->getOptionsModel())
return;
OptionsDialog dlg;
dlg.setModel(clientModel->getOptionsModel());
dlg.exec();
}
void BitcoinGUI::aboutClicked()
{
AboutDialog dlg;
dlg.setModel(clientModel);
dlg.exec();
}
void BitcoinGUI::setNumConnections(int count)
{
QString icon;
switch(count)
{
case 0: icon = ":/icons/connect_0"; break;
case 1: case 2: case 3: icon = ":/icons/connect_1"; break;
case 4: case 5: case 6: icon = ":/icons/connect_2"; break;
case 7: case 8: case 9: icon = ":/icons/connect_3"; break;
default: icon = ":/icons/connect_4"; break;
}
labelConnectionsIcon->setPixmap(QIcon(icon).pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));
labelConnectionsIcon->setToolTip(tr("%n active connection(s) to GridBit network.", "", count));
}
void BitcoinGUI::setNumBlocks(int count, int nTotalBlocks)
{
// don't show / hide progress bar and its label if we have no connection to the network
if (!clientModel || clientModel->getNumConnections() == 0)
{
progressBarLabel->setVisible(false);
progressBar->setVisible(false);
return;
}
QString strStatusBarWarnings = clientModel->getStatusBarWarnings();
QString tooltip;
if(count < nTotalBlocks)
{
int nRemainingBlocks = nTotalBlocks - count;
float nPercentageDone = count / (nTotalBlocks * 0.01f);
if (strStatusBarWarnings.isEmpty())
{
progressBarLabel->setText(tr("Synchronizing with network..."));
progressBarLabel->setVisible(true);
progressBar->setFormat(tr("~%n block(s) remaining", "", nRemainingBlocks));
progressBar->setMaximum(nTotalBlocks);
progressBar->setValue(count);
progressBar->setVisible(true);
}
tooltip = tr("Downloaded %1 of %2 blocks of transaction history (%3% done).").arg(count).arg(nTotalBlocks).arg(nPercentageDone, 0, 'f', 2);
}
else
{
if (strStatusBarWarnings.isEmpty())
progressBarLabel->setVisible(false);
progressBar->setVisible(false);
tooltip = tr("Downloaded %1 blocks of transaction history.").arg(count);
}
// Override progressBarLabel text and hide progress bar, when we have warnings to display
if (!strStatusBarWarnings.isEmpty())
{
progressBarLabel->setText(strStatusBarWarnings);
progressBarLabel->setVisible(true);
progressBar->setVisible(false);
}
tooltip = tr("Current difficulty is %1.").arg(clientModel->GetDifficulty()) + QString("<br>") + tooltip;
QDateTime lastBlockDate = clientModel->getLastBlockDate();
int secs = lastBlockDate.secsTo(QDateTime::currentDateTime());
QString text;
// Represent time from last generated block in human readable text
if(secs <= 0)
{
// Fully up to date. Leave text empty.
}
else if(secs < 60)
{
text = tr("%n second(s) ago","",secs);
}
else if(secs < 60*60)
{
text = tr("%n minute(s) ago","",secs/60);
}
else if(secs < 24*60*60)
{
text = tr("%n hour(s) ago","",secs/(60*60));
}
else
{
text = tr("%n day(s) ago","",secs/(60*60*24));
}
// Set icon state: spinning if catching up, tick otherwise
if(secs < 90*60 && count >= nTotalBlocks)
{
tooltip = tr("Up to date") + QString(".<br>") + tooltip;
labelBlocksIcon->setPixmap(QIcon(":/icons/synced").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE));
overviewPage->showOutOfSyncWarning(false);
}
else
{
tooltip = tr("Catching up...") + QString("<br>") + tooltip;
labelBlocksIcon->setMovie(syncIconMovie);
syncIconMovie->start();
overviewPage->showOutOfSyncWarning(true);
}
if(!text.isEmpty())
{
tooltip += QString("<br>");
tooltip += tr("Last received block was generated %1.").arg(text);
}
// Don't word-wrap this (fixed-width) tooltip
tooltip = QString("<nobr>") + tooltip + QString("</nobr>");
labelBlocksIcon->setToolTip(tooltip);
progressBarLabel->setToolTip(tooltip);
progressBar->setToolTip(tooltip);
}
void BitcoinGUI::error(const QString &title, const QString &message, bool modal)
{
// Report errors from network/worker thread
if(modal)
{
QMessageBox::critical(this, title, message, QMessageBox::Ok, QMessageBox::Ok);
} else {
notificator->notify(Notificator::Critical, title, message);
}
}
void BitcoinGUI::changeEvent(QEvent *e)
{
QMainWindow::changeEvent(e);
#ifndef Q_OS_MAC // Ignored on Mac
if(e->type() == QEvent::WindowStateChange)
{
if(clientModel && clientModel->getOptionsModel()->getMinimizeToTray())
{
QWindowStateChangeEvent *wsevt = static_cast<QWindowStateChangeEvent*>(e);
if(!(wsevt->oldState() & Qt::WindowMinimized) && isMinimized())
{
QTimer::singleShot(0, this, SLOT(hide()));
e->ignore();
}
}
}
#endif
}
void BitcoinGUI::closeEvent(QCloseEvent *event)
{
if(clientModel)
{
#ifndef Q_OS_MAC // Ignored on Mac
if(!clientModel->getOptionsModel()->getMinimizeToTray() &&
!clientModel->getOptionsModel()->getMinimizeOnClose())
{
qApp->quit();
}
#endif
}
QMainWindow::closeEvent(event);
}
void BitcoinGUI::askFee(qint64 nFeeRequired, bool *payFee)
{
QString strMessage =
tr("This transaction is over the size limit. You can still send it for a fee of %1, "
"which goes to the nodes that process your transaction and helps to support the network. "
"Do you want to pay the fee?").arg(
BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, nFeeRequired));
QMessageBox::StandardButton retval = QMessageBox::question(
this, tr("Confirm transaction fee"), strMessage,
QMessageBox::Yes|QMessageBox::Cancel, QMessageBox::Yes);
*payFee = (retval == QMessageBox::Yes);
}
void BitcoinGUI::incomingTransaction(const QModelIndex & parent, int start, int end)
{
if(!walletModel || !clientModel)
return;
TransactionTableModel *ttm = walletModel->getTransactionTableModel();
qint64 amount = ttm->index(start, TransactionTableModel::Amount, parent)
.data(Qt::EditRole).toULongLong();
if(!clientModel->inInitialBlockDownload())
{
// On new transaction, make an info balloon
// Unless the initial block download is in progress, to prevent balloon-spam
QString date = ttm->index(start, TransactionTableModel::Date, parent)
.data().toString();
QString type = ttm->index(start, TransactionTableModel::Type, parent)
.data().toString();
QString address = ttm->index(start, TransactionTableModel::ToAddress, parent)
.data().toString();
QIcon icon = qvariant_cast<QIcon>(ttm->index(start,
TransactionTableModel::ToAddress, parent)
.data(Qt::DecorationRole));
notificator->notify(Notificator::Information,
(amount)<0 ? tr("Sent transaction") :
tr("Incoming transaction"),
tr("Date: %1\n"
"Amount: %2\n"
"Type: %3\n"
"Address: %4\n")
.arg(date)
.arg(BitcoinUnits::formatWithUnit(walletModel->getOptionsModel()->getDisplayUnit(), amount, true))
.arg(type)
.arg(address), icon);
}
}
void BitcoinGUI::gotoOverviewPage()
{
overviewAction->setChecked(true);
centralWidget->setCurrentWidget(overviewPage);
exportAction->setEnabled(false);
disconnect(exportAction, SIGNAL(triggered()), 0, 0);
}
void BitcoinGUI::gotoHistoryPage()
{
historyAction->setChecked(true);
centralWidget->setCurrentWidget(transactionsPage);
exportAction->setEnabled(true);
disconnect(exportAction, SIGNAL(triggered()), 0, 0);
connect(exportAction, SIGNAL(triggered()), transactionView, SLOT(exportClicked()));
}
void BitcoinGUI::gotoAddressBookPage()
{
addressBookAction->setChecked(true);
centralWidget->setCurrentWidget(addressBookPage);
exportAction->setEnabled(true);
disconnect(exportAction, SIGNAL(triggered()), 0, 0);
connect(exportAction, SIGNAL(triggered()), addressBookPage, SLOT(exportClicked()));
}
void BitcoinGUI::gotoReceiveCoinsPage()
{
receiveCoinsAction->setChecked(true);
centralWidget->setCurrentWidget(receiveCoinsPage);
exportAction->setEnabled(true);
disconnect(exportAction, SIGNAL(triggered()), 0, 0);
connect(exportAction, SIGNAL(triggered()), receiveCoinsPage, SLOT(exportClicked()));
}
void BitcoinGUI::gotoSendCoinsPage()
{
sendCoinsAction->setChecked(true);
centralWidget->setCurrentWidget(sendCoinsPage);
exportAction->setEnabled(false);
disconnect(exportAction, SIGNAL(triggered()), 0, 0);
}
void BitcoinGUI::gotoSignMessageTab(QString addr)
{
// call show() in showTab_SM()
signVerifyMessageDialog->showTab_SM(true);
if(!addr.isEmpty())
signVerifyMessageDialog->setAddress_SM(addr);
}
void BitcoinGUI::gotoVerifyMessageTab(QString addr)
{
// call show() in showTab_VM()
signVerifyMessageDialog->showTab_VM(true);
if(!addr.isEmpty())
signVerifyMessageDialog->setAddress_VM(addr);
}
void BitcoinGUI::dragEnterEvent(QDragEnterEvent *event)
{
// Accept only URIs
if(event->mimeData()->hasUrls())
event->acceptProposedAction();
}
void BitcoinGUI::dropEvent(QDropEvent *event)
{
if(event->mimeData()->hasUrls())
{
int nValidUrisFound = 0;
QList<QUrl> uris = event->mimeData()->urls();
foreach(const QUrl &uri, uris)
{
if (sendCoinsPage->handleURI(uri.toString()))
nValidUrisFound++;
}
// if valid URIs were found
if (nValidUrisFound)
gotoSendCoinsPage();
else
notificator->notify(Notificator::Warning, tr("URI handling"), tr("URI can not be parsed! This can be caused by an invalid GridBit address or malformed URI parameters."));
}
event->acceptProposedAction();
}
void BitcoinGUI::handleURI(QString strURI)
{
// URI has to be valid
if (sendCoinsPage->handleURI(strURI))
{
showNormalIfMinimized();
gotoSendCoinsPage();
}
else
notificator->notify(Notificator::Warning, tr("URI handling"), tr("URI can not be parsed! This can be caused by an invalid GridBit address or malformed URI parameters."));
}
void BitcoinGUI::setEncryptionStatus(int status)
{
switch(status)
{
case WalletModel::Unencrypted:
labelEncryptionIcon->hide();
encryptWalletAction->setChecked(false);
encryptWalletAction->setEnabled(true);
changePassphraseAction->setEnabled(false);
lockWalletToggleAction->setVisible(false);
break;
case WalletModel::Unlocked:
labelEncryptionIcon->show();
labelEncryptionIcon->setPixmap(QIcon(":/icons/lock_open").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));
labelEncryptionIcon->setToolTip(tr("Wallet is <b>encrypted</b> and currently <b>unlocked</b>."));
encryptWalletAction->setChecked(true);
encryptWalletAction->setEnabled(false); // TODO: decrypt currently not supported
changePassphraseAction->setEnabled(true);
lockWalletToggleAction->setVisible(true);
lockWalletToggleAction->setIcon(QIcon(":/icons/lock_closed"));
lockWalletToggleAction->setText(tr("&Lock Wallet"));
lockWalletToggleAction->setToolTip(tr("Lock wallet"));
break;
case WalletModel::Locked:
labelEncryptionIcon->show();
labelEncryptionIcon->setPixmap(QIcon(":/icons/lock_closed").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));
labelEncryptionIcon->setToolTip(tr("Wallet is <b>encrypted</b> and currently <b>locked</b>."));
encryptWalletAction->setChecked(true);
encryptWalletAction->setEnabled(false); // TODO: decrypt currently not supported
changePassphraseAction->setEnabled(true);
lockWalletToggleAction->setVisible(true);
lockWalletToggleAction->setIcon(QIcon(":/icons/lock_open"));
lockWalletToggleAction->setText(tr("&Unlock Wallet..."));
lockWalletToggleAction->setToolTip(tr("Unlock wallet"));
break;
}
}
void BitcoinGUI::encryptWallet(bool status)
{
if(!walletModel)
return;
AskPassphraseDialog dlg(status ? AskPassphraseDialog::Encrypt:
AskPassphraseDialog::Decrypt, this);
dlg.setModel(walletModel);
dlg.exec();
setEncryptionStatus(walletModel->getEncryptionStatus());
}
void BitcoinGUI::backupWallet()
{
QString saveDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);
QString filename = QFileDialog::getSaveFileName(this, tr("Backup Wallet"), saveDir, tr("Wallet Data (*.dat)"));
if(!filename.isEmpty()) {
if(!walletModel->backupWallet(filename)) {
QMessageBox::warning(this, tr("Backup Failed"), tr("There was an error trying to save the wallet data to the new location."));
}
}
}
void BitcoinGUI::changePassphrase()
{
AskPassphraseDialog dlg(AskPassphraseDialog::ChangePass, this);
dlg.setModel(walletModel);
dlg.exec();
}
void BitcoinGUI::lockWalletToggle()
{
if(!walletModel)
return;
// Unlock wallet when requested by wallet model
if(walletModel->getEncryptionStatus() == WalletModel::Locked)
{
AskPassphraseDialog::Mode mode = AskPassphraseDialog::UnlockMinting;
AskPassphraseDialog dlg(mode, this);
dlg.setModel(walletModel);
dlg.exec();
}
else
walletModel->setWalletLocked(true);
}
void BitcoinGUI::showNormalIfMinimized(bool fToggleHidden)
{
// activateWindow() (sometimes) helps with keyboard focus on Windows
if (isHidden())
{
show();
activateWindow();
}
else if (isMinimized())
{
showNormal();
activateWindow();
}
else if (GUIUtil::isObscured(this))
{
raise();
activateWindow();
}
else if(fToggleHidden)
hide();
}
void BitcoinGUI::toggleHidden()
{
showNormalIfMinimized(true);
}
void BitcoinGUI::updateMintingIcon()
{
if (pwalletMain && pwalletMain->IsLocked())
{
labelMintingIcon->setToolTip(tr("Not minting because wallet is locked."));
labelMintingIcon->setEnabled(false);
}
else if (vNodes.empty())
{
labelMintingIcon->setToolTip(tr("Not minting because wallet is offline."));
labelMintingIcon->setEnabled(false);
}
else if (IsInitialBlockDownload())
{
labelMintingIcon->setToolTip(tr("Not minting because wallet is syncing."));
labelMintingIcon->setEnabled(false);
}
else if (!nWeight)
{
labelMintingIcon->setToolTip(tr("Not minting because you don't have mature coins."));
labelMintingIcon->setEnabled(false);
}
else if (nLastCoinStakeSearchInterval)
{
uint64 nEstimateTime = nTargetSpacing * nNetworkWeight / nWeight;
QString text;
if (nEstimateTime < 60)
{
text = tr("%n second(s)", "", nEstimateTime);
}
else if (nEstimateTime < 60*60)
{
text = tr("%n minute(s)", "", nEstimateTime/60);
}
else if (nEstimateTime < 24*60*60)
{
text = tr("%n hour(s)", "", nEstimateTime/(60*60));
}
else
{
text = tr("%n day(s)", "", nEstimateTime/(60*60*24));
}
labelMintingIcon->setEnabled(true);
labelMintingIcon->setToolTip(tr("Minting.<br>Your weight is %1.<br>Network weight is %2.<br>Expected time to earn reward is %3.").arg(nWeight).arg(nNetworkWeight).arg(text));
}
else
{
labelMintingIcon->setToolTip(tr("Not minting."));
labelMintingIcon->setEnabled(false);
}
}
void BitcoinGUI::updateMintingWeights()
{
// Only update if we have the network's current number of blocks, or weight(s) are zero (fixes lagging GUI)
if ((clientModel && clientModel->getNumBlocks() == clientModel->getNumBlocksOfPeers()) || !nWeight || !nNetworkWeight)
{
nWeight = 0;
if (pwalletMain)
pwalletMain->GetStakeWeight(*pwalletMain, nMinMax, nMinMax, nWeight);
nNetworkWeight = GetPoSKernelPS();
}
}
|
[
"team@gridbit.co"
] |
team@gridbit.co
|
258e69e6f40282252ab6022252d0ac2a4e8e35e3
|
b98f824600c00343851917c646ed3430755e2eea
|
/inet/src/inet/physicallayer/base/packetlevel/FlatReceptionBase_m.cc
|
aa2ba5460814dff350e0250b18a9dee0be1fbefa
|
[] |
no_license
|
ZitaoLi/tsn_omnetpp_nesting_rev
|
7be3e15957a16b9d3071d6526e2a4d19e236e6e6
|
23ab3a2e9cffa5d01a5297547e7e8a71a66b60c8
|
refs/heads/master
| 2020-05-07T22:23:45.523901
| 2019-04-12T10:49:40
| 2019-04-12T10:49:40
| 180,943,408
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 14,144
|
cc
|
//
// Generated file, do not edit! Created by nedtool 5.4 from inet/physicallayer/base/packetlevel/FlatReceptionBase.msg.
//
// Disable warnings about unused variables, empty switch stmts, etc:
#ifdef _MSC_VER
# pragma warning(disable:4101)
# pragma warning(disable:4065)
#endif
#if defined(__clang__)
# pragma clang diagnostic ignored "-Wshadow"
# pragma clang diagnostic ignored "-Wconversion"
# pragma clang diagnostic ignored "-Wunused-parameter"
# pragma clang diagnostic ignored "-Wc++98-compat"
# pragma clang diagnostic ignored "-Wunreachable-code-break"
# pragma clang diagnostic ignored "-Wold-style-cast"
#elif defined(__GNUC__)
# pragma GCC diagnostic ignored "-Wshadow"
# pragma GCC diagnostic ignored "-Wconversion"
# pragma GCC diagnostic ignored "-Wunused-parameter"
# pragma GCC diagnostic ignored "-Wold-style-cast"
# pragma GCC diagnostic ignored "-Wsuggest-attribute=noreturn"
# pragma GCC diagnostic ignored "-Wfloat-conversion"
#endif
#include <iostream>
#include <sstream>
#include <memory>
#include "FlatReceptionBase_m.h"
namespace omnetpp {
// Template pack/unpack rules. They are declared *after* a1l type-specific pack functions for multiple reasons.
// They are in the omnetpp namespace, to allow them to be found by argument-dependent lookup via the cCommBuffer argument
// Packing/unpacking an std::vector
template<typename T, typename A>
void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::vector<T,A>& v)
{
int n = v.size();
doParsimPacking(buffer, n);
for (int i = 0; i < n; i++)
doParsimPacking(buffer, v[i]);
}
template<typename T, typename A>
void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::vector<T,A>& v)
{
int n;
doParsimUnpacking(buffer, n);
v.resize(n);
for (int i = 0; i < n; i++)
doParsimUnpacking(buffer, v[i]);
}
// Packing/unpacking an std::list
template<typename T, typename A>
void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::list<T,A>& l)
{
doParsimPacking(buffer, (int)l.size());
for (typename std::list<T,A>::const_iterator it = l.begin(); it != l.end(); ++it)
doParsimPacking(buffer, (T&)*it);
}
template<typename T, typename A>
void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::list<T,A>& l)
{
int n;
doParsimUnpacking(buffer, n);
for (int i = 0; i < n; i++) {
l.push_back(T());
doParsimUnpacking(buffer, l.back());
}
}
// Packing/unpacking an std::set
template<typename T, typename Tr, typename A>
void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::set<T,Tr,A>& s)
{
doParsimPacking(buffer, (int)s.size());
for (typename std::set<T,Tr,A>::const_iterator it = s.begin(); it != s.end(); ++it)
doParsimPacking(buffer, *it);
}
template<typename T, typename Tr, typename A>
void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::set<T,Tr,A>& s)
{
int n;
doParsimUnpacking(buffer, n);
for (int i = 0; i < n; i++) {
T x;
doParsimUnpacking(buffer, x);
s.insert(x);
}
}
// Packing/unpacking an std::map
template<typename K, typename V, typename Tr, typename A>
void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::map<K,V,Tr,A>& m)
{
doParsimPacking(buffer, (int)m.size());
for (typename std::map<K,V,Tr,A>::const_iterator it = m.begin(); it != m.end(); ++it) {
doParsimPacking(buffer, it->first);
doParsimPacking(buffer, it->second);
}
}
template<typename K, typename V, typename Tr, typename A>
void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::map<K,V,Tr,A>& m)
{
int n;
doParsimUnpacking(buffer, n);
for (int i = 0; i < n; i++) {
K k; V v;
doParsimUnpacking(buffer, k);
doParsimUnpacking(buffer, v);
m[k] = v;
}
}
// Default pack/unpack function for arrays
template<typename T>
void doParsimArrayPacking(omnetpp::cCommBuffer *b, const T *t, int n)
{
for (int i = 0; i < n; i++)
doParsimPacking(b, t[i]);
}
template<typename T>
void doParsimArrayUnpacking(omnetpp::cCommBuffer *b, T *t, int n)
{
for (int i = 0; i < n; i++)
doParsimUnpacking(b, t[i]);
}
// Default rule to prevent compiler from choosing base class' doParsimPacking() function
template<typename T>
void doParsimPacking(omnetpp::cCommBuffer *, const T& t)
{
throw omnetpp::cRuntimeError("Parsim error: No doParsimPacking() function for type %s", omnetpp::opp_typename(typeid(t)));
}
template<typename T>
void doParsimUnpacking(omnetpp::cCommBuffer *, T& t)
{
throw omnetpp::cRuntimeError("Parsim error: No doParsimUnpacking() function for type %s", omnetpp::opp_typename(typeid(t)));
}
} // namespace omnetpp
namespace {
template <class T> inline
typename std::enable_if<std::is_polymorphic<T>::value && std::is_base_of<omnetpp::cObject,T>::value, void *>::type
toVoidPtr(T* t)
{
return (void *)(static_cast<const omnetpp::cObject *>(t));
}
template <class T> inline
typename std::enable_if<std::is_polymorphic<T>::value && !std::is_base_of<omnetpp::cObject,T>::value, void *>::type
toVoidPtr(T* t)
{
return (void *)dynamic_cast<const void *>(t);
}
template <class T> inline
typename std::enable_if<!std::is_polymorphic<T>::value, void *>::type
toVoidPtr(T* t)
{
return (void *)static_cast<const void *>(t);
}
}
namespace inet {
namespace physicallayer {
// forward
template<typename T, typename A>
std::ostream& operator<<(std::ostream& out, const std::vector<T,A>& vec);
// Template rule to generate operator<< for shared_ptr<T>
template<typename T>
inline std::ostream& operator<<(std::ostream& out,const std::shared_ptr<T>& t) { return out << t.get(); }
// Template rule which fires if a struct or class doesn't have operator<<
template<typename T>
inline std::ostream& operator<<(std::ostream& out,const T&) {return out;}
// operator<< for std::vector<T>
template<typename T, typename A>
inline std::ostream& operator<<(std::ostream& out, const std::vector<T,A>& vec)
{
out.put('{');
for(typename std::vector<T,A>::const_iterator it = vec.begin(); it != vec.end(); ++it)
{
if (it != vec.begin()) {
out.put(','); out.put(' ');
}
out << *it;
}
out.put('}');
char buf[32];
sprintf(buf, " (size=%u)", (unsigned int)vec.size());
out.write(buf, strlen(buf));
return out;
}
class FlatReceptionBaseDescriptor : public omnetpp::cClassDescriptor
{
private:
mutable const char **propertynames;
enum FieldConstants {
};
public:
FlatReceptionBaseDescriptor();
virtual ~FlatReceptionBaseDescriptor();
virtual bool doesSupport(omnetpp::cObject *obj) const override;
virtual const char **getPropertyNames() const override;
virtual const char *getProperty(const char *propertyname) const override;
virtual int getFieldCount() const override;
virtual const char *getFieldName(int field) const override;
virtual int findField(const char *fieldName) const override;
virtual unsigned int getFieldTypeFlags(int field) const override;
virtual const char *getFieldTypeString(int field) const override;
virtual const char **getFieldPropertyNames(int field) const override;
virtual const char *getFieldProperty(int field, const char *propertyname) const override;
virtual int getFieldArraySize(void *object, int field) const override;
virtual const char *getFieldDynamicTypeString(void *object, int field, int i) const override;
virtual std::string getFieldValueAsString(void *object, int field, int i) const override;
virtual bool setFieldValueAsString(void *object, int field, int i, const char *value) const override;
virtual const char *getFieldStructName(int field) const override;
virtual void *getFieldStructValuePointer(void *object, int field, int i) const override;
};
Register_ClassDescriptor(FlatReceptionBaseDescriptor)
FlatReceptionBaseDescriptor::FlatReceptionBaseDescriptor() : omnetpp::cClassDescriptor(omnetpp::opp_typename(typeid(inet::physicallayer::FlatReceptionBase)), "inet::physicallayer::NarrowbandReceptionBase")
{
propertynames = nullptr;
}
FlatReceptionBaseDescriptor::~FlatReceptionBaseDescriptor()
{
delete[] propertynames;
}
bool FlatReceptionBaseDescriptor::doesSupport(omnetpp::cObject *obj) const
{
return dynamic_cast<FlatReceptionBase *>(obj)!=nullptr;
}
const char **FlatReceptionBaseDescriptor::getPropertyNames() const
{
if (!propertynames) {
static const char *names[] = { "existingClass", "descriptor", nullptr };
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
const char **basenames = basedesc ? basedesc->getPropertyNames() : nullptr;
propertynames = mergeLists(basenames, names);
}
return propertynames;
}
const char *FlatReceptionBaseDescriptor::getProperty(const char *propertyname) const
{
if (!strcmp(propertyname, "existingClass")) return "";
if (!strcmp(propertyname, "descriptor")) return "readonly";
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
return basedesc ? basedesc->getProperty(propertyname) : nullptr;
}
int FlatReceptionBaseDescriptor::getFieldCount() const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
return basedesc ? 0+basedesc->getFieldCount() : 0;
}
unsigned int FlatReceptionBaseDescriptor::getFieldTypeFlags(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldTypeFlags(field);
field -= basedesc->getFieldCount();
}
return 0;
}
const char *FlatReceptionBaseDescriptor::getFieldName(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldName(field);
field -= basedesc->getFieldCount();
}
return nullptr;
}
int FlatReceptionBaseDescriptor::findField(const char *fieldName) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
return basedesc ? basedesc->findField(fieldName) : -1;
}
const char *FlatReceptionBaseDescriptor::getFieldTypeString(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldTypeString(field);
field -= basedesc->getFieldCount();
}
return nullptr;
}
const char **FlatReceptionBaseDescriptor::getFieldPropertyNames(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldPropertyNames(field);
field -= basedesc->getFieldCount();
}
switch (field) {
default: return nullptr;
}
}
const char *FlatReceptionBaseDescriptor::getFieldProperty(int field, const char *propertyname) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldProperty(field, propertyname);
field -= basedesc->getFieldCount();
}
switch (field) {
default: return nullptr;
}
}
int FlatReceptionBaseDescriptor::getFieldArraySize(void *object, int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldArraySize(object, field);
field -= basedesc->getFieldCount();
}
FlatReceptionBase *pp = (FlatReceptionBase *)object; (void)pp;
switch (field) {
default: return 0;
}
}
const char *FlatReceptionBaseDescriptor::getFieldDynamicTypeString(void *object, int field, int i) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldDynamicTypeString(object,field,i);
field -= basedesc->getFieldCount();
}
FlatReceptionBase *pp = (FlatReceptionBase *)object; (void)pp;
switch (field) {
default: return nullptr;
}
}
std::string FlatReceptionBaseDescriptor::getFieldValueAsString(void *object, int field, int i) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldValueAsString(object,field,i);
field -= basedesc->getFieldCount();
}
FlatReceptionBase *pp = (FlatReceptionBase *)object; (void)pp;
switch (field) {
default: return "";
}
}
bool FlatReceptionBaseDescriptor::setFieldValueAsString(void *object, int field, int i, const char *value) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->setFieldValueAsString(object,field,i,value);
field -= basedesc->getFieldCount();
}
FlatReceptionBase *pp = (FlatReceptionBase *)object; (void)pp;
switch (field) {
default: return false;
}
}
const char *FlatReceptionBaseDescriptor::getFieldStructName(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldStructName(field);
field -= basedesc->getFieldCount();
}
return nullptr;
}
void *FlatReceptionBaseDescriptor::getFieldStructValuePointer(void *object, int field, int i) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldStructValuePointer(object, field, i);
field -= basedesc->getFieldCount();
}
FlatReceptionBase *pp = (FlatReceptionBase *)object; (void)pp;
switch (field) {
default: return nullptr;
}
}
} // namespace physicallayer
} // namespace inet
|
[
"494240799@qq.com"
] |
494240799@qq.com
|
e2129ad55265c73467eb7bf73a7b9942cc21c24c
|
3f3a42f429f8bcd769644148b24c3b0e6e2589ed
|
/GameProject/GameEngine/EngineCore/Math/Matrix.h
|
8265f6abdf7c338a22c320735afd62996914f750
|
[] |
no_license
|
DanielNeander/my-3d-engine
|
d10ad3e57a205f6148357f47467b550c7e0e0f33
|
7f0babbfdf0b719ea4b114a89997d3e52bcb2b6c
|
refs/heads/master
| 2021-01-10T17:58:25.691360
| 2013-04-24T07:37:31
| 2013-04-24T07:37:31
| 53,236,587
| 3
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 96,382
|
h
|
#ifndef MATH_MATRIX_H
#define MATH_MATRIX_H
#include "Vector.h"
#define MATRIX_INVERSE_EPSILON 1e-14
#define MATRIX_EPSILON 1e-6
class noAngles;
class noRotation;
class noQuat;
class idCQuat;
class noMat4;
//===============================================================
//
// noMat2 - 2x2 matrix
//
//===============================================================
class noMat2 {
public:
noMat2( void );
explicit noMat2( const noVec2 &x, const noVec2 &y );
explicit noMat2( const float xx, const float xy, const float yx, const float yy );
explicit noMat2( const float src[ 2 ][ 2 ] );
const noVec2 & operator[]( int index ) const;
noVec2 & operator[]( int index );
noMat2 operator-() const;
noMat2 operator*( const float a ) const;
noVec2 operator*( const noVec2 &vec ) const;
noMat2 operator*( const noMat2 &a ) const;
noMat2 operator+( const noMat2 &a ) const;
noMat2 operator-( const noMat2 &a ) const;
noMat2 & operator*=( const float a );
noMat2 & operator*=( const noMat2 &a );
noMat2 & operator+=( const noMat2 &a );
noMat2 & operator-=( const noMat2 &a );
friend noMat2 operator*( const float a, const noMat2 &mat );
friend noVec2 operator*( const noVec2 &vec, const noMat2 &mat );
friend noVec2 & operator*=( noVec2 &vec, const noMat2 &mat );
bool Compare( const noMat2 &a ) const; // exact compare, no epsilon
bool Compare( const noMat2 &a, const float epsilon ) const; // compare with epsilon
bool operator==( const noMat2 &a ) const; // exact compare, no epsilon
bool operator!=( const noMat2 &a ) const; // exact compare, no epsilon
void Zero( void );
void Identity( void );
bool IsIdentity( const float epsilon = MATRIX_EPSILON ) const;
bool IsSymmetric( const float epsilon = MATRIX_EPSILON ) const;
bool IsDiagonal( const float epsilon = MATRIX_EPSILON ) const;
float Trace( void ) const;
float Determinant( void ) const;
noMat2 Transpose( void ) const; // returns transpose
noMat2 & TransposeSelf( void );
noMat2 Inverse( void ) const; // returns the inverse ( m * m.Inverse() = identity )
bool InverseSelf( void ); // returns false if determinant is zero
noMat2 InverseFast( void ) const; // returns the inverse ( m * m.Inverse() = identity )
bool InverseFastSelf( void ); // returns false if determinant is zero
int GetDimension( void ) const;
const float * ToFloatPtr( void ) const;
float * ToFloatPtr( void );
const char * ToString( int precision = 2 ) const;
private:
noVec2 mat[ 2 ];
};
extern noMat2 mat2_zero;
extern noMat2 mat2_identity;
#define mat2_default mat2_identity
NO_INLINE noMat2::noMat2( void ) {
}
NO_INLINE noMat2::noMat2( const noVec2 &x, const noVec2 &y ) {
mat[ 0 ].x = x.x; mat[ 0 ].y = x.y;
mat[ 1 ].x = y.x; mat[ 1 ].y = y.y;
}
NO_INLINE noMat2::noMat2( const float xx, const float xy, const float yx, const float yy ) {
mat[ 0 ].x = xx; mat[ 0 ].y = xy;
mat[ 1 ].x = yx; mat[ 1 ].y = yy;
}
NO_INLINE noMat2::noMat2( const float src[ 2 ][ 2 ] ) {
memcpy( mat, src, 2 * 2 * sizeof( float ) );
}
NO_INLINE const noVec2 &noMat2::operator[]( int index ) const {
//assert( ( index >= 0 ) && ( index < 2 ) );
return mat[ index ];
}
NO_INLINE noVec2 &noMat2::operator[]( int index ) {
//assert( ( index >= 0 ) && ( index < 2 ) );
return mat[ index ];
}
NO_INLINE noMat2 noMat2::operator-() const {
return noMat2( -mat[0][0], -mat[0][1],
-mat[1][0], -mat[1][1] );
}
NO_INLINE noVec2 noMat2::operator*( const noVec2 &vec ) const {
return noVec2(
mat[ 0 ].x * vec.x + mat[ 0 ].y * vec.y,
mat[ 1 ].x * vec.x + mat[ 1 ].y * vec.y );
}
NO_INLINE noMat2 noMat2::operator*( const noMat2 &a ) const {
return noMat2(
mat[0].x * a[0].x + mat[0].y * a[1].x,
mat[0].x * a[0].y + mat[0].y * a[1].y,
mat[1].x * a[0].x + mat[1].y * a[1].x,
mat[1].x * a[0].y + mat[1].y * a[1].y );
}
NO_INLINE noMat2 noMat2::operator*( const float a ) const {
return noMat2(
mat[0].x * a, mat[0].y * a,
mat[1].x * a, mat[1].y * a );
}
NO_INLINE noMat2 noMat2::operator+( const noMat2 &a ) const {
return noMat2(
mat[0].x + a[0].x, mat[0].y + a[0].y,
mat[1].x + a[1].x, mat[1].y + a[1].y );
}
NO_INLINE noMat2 noMat2::operator-( const noMat2 &a ) const {
return noMat2(
mat[0].x - a[0].x, mat[0].y - a[0].y,
mat[1].x - a[1].x, mat[1].y - a[1].y );
}
NO_INLINE noMat2 &noMat2::operator*=( const float a ) {
mat[0].x *= a; mat[0].y *= a;
mat[1].x *= a; mat[1].y *= a;
return *this;
}
NO_INLINE noMat2 &noMat2::operator*=( const noMat2 &a ) {
float x, y;
x = mat[0].x; y = mat[0].y;
mat[0].x = x * a[0].x + y * a[1].x;
mat[0].y = x * a[0].y + y * a[1].y;
x = mat[1].x; y = mat[1].y;
mat[1].x = x * a[0].x + y * a[1].x;
mat[1].y = x * a[0].y + y * a[1].y;
return *this;
}
NO_INLINE noMat2 &noMat2::operator+=( const noMat2 &a ) {
mat[0].x += a[0].x; mat[0].y += a[0].y;
mat[1].x += a[1].x; mat[1].y += a[1].y;
return *this;
}
NO_INLINE noMat2 &noMat2::operator-=( const noMat2 &a ) {
mat[0].x -= a[0].x; mat[0].y -= a[0].y;
mat[1].x -= a[1].x; mat[1].y -= a[1].y;
return *this;
}
NO_INLINE noVec2 operator*( const noVec2 &vec, const noMat2 &mat ) {
return mat * vec;
}
NO_INLINE noMat2 operator*( const float a, noMat2 const &mat ) {
return mat * a;
}
NO_INLINE noVec2 &operator*=( noVec2 &vec, const noMat2 &mat ) {
vec = mat * vec;
return vec;
}
NO_INLINE bool noMat2::Compare( const noMat2 &a ) const {
if ( mat[0].Compare( a[0] ) &&
mat[1].Compare( a[1] ) ) {
return true;
}
return false;
}
NO_INLINE bool noMat2::Compare( const noMat2 &a, const float epsilon ) const {
if ( mat[0].Compare( a[0], epsilon ) &&
mat[1].Compare( a[1], epsilon ) ) {
return true;
}
return false;
}
NO_INLINE bool noMat2::operator==( const noMat2 &a ) const {
return Compare( a );
}
NO_INLINE bool noMat2::operator!=( const noMat2 &a ) const {
return !Compare( a );
}
NO_INLINE void noMat2::Zero( void ) {
mat[0].Zero();
mat[1].Zero();
}
NO_INLINE void noMat2::Identity( void ) {
*this = mat2_identity;
}
NO_INLINE bool noMat2::IsIdentity( const float epsilon ) const {
return Compare( mat2_identity, epsilon );
}
NO_INLINE bool noMat2::IsSymmetric( const float epsilon ) const {
return ( noMath::Fabs( mat[0][1] - mat[1][0] ) < epsilon );
}
NO_INLINE bool noMat2::IsDiagonal( const float epsilon ) const {
if ( noMath::Fabs( mat[0][1] ) > epsilon ||
noMath::Fabs( mat[1][0] ) > epsilon ) {
return false;
}
return true;
}
NO_INLINE float noMat2::Trace( void ) const {
return ( mat[0][0] + mat[1][1] );
}
NO_INLINE float noMat2::Determinant( void ) const {
return mat[0][0] * mat[1][1] - mat[0][1] * mat[1][0];
}
NO_INLINE noMat2 noMat2::Transpose( void ) const {
return noMat2( mat[0][0], mat[1][0],
mat[0][1], mat[1][1] );
}
NO_INLINE noMat2 &noMat2::TransposeSelf( void ) {
float tmp;
tmp = mat[0][1];
mat[0][1] = mat[1][0];
mat[1][0] = tmp;
return *this;
}
NO_INLINE noMat2 noMat2::Inverse( void ) const {
noMat2 invMat;
invMat = *this;
int r = invMat.InverseSelf();
assert( r );
return invMat;
}
NO_INLINE noMat2 noMat2::InverseFast( void ) const {
noMat2 invMat;
invMat = *this;
int r = invMat.InverseFastSelf();
assert( r );
return invMat;
}
NO_INLINE int noMat2::GetDimension( void ) const {
return 4;
}
NO_INLINE const float *noMat2::ToFloatPtr( void ) const {
return mat[0].ToFloatPtr();
}
NO_INLINE float *noMat2::ToFloatPtr( void ) {
return mat[0].ToFloatPtr();
}
//===============================================================
//
// noMat3 - 3x3 matrix
//
// NOTE: matrix is column-major
//
//===============================================================
class noMat3 {
public:
noMat3( void );
explicit noMat3( const noVec3 &x, const noVec3 &y, const noVec3 &z );
explicit noMat3( const float xx, const float xy, const float xz, const float yx, const float yy, const float yz, const float zx, const float zy, const float zz );
explicit noMat3( const float src[ 3 ][ 3 ] );
const noVec3 & operator[]( int index ) const;
noVec3 & operator[]( int index );
noMat3 operator-() const;
noMat3 operator*( const float a ) const;
noVec3 operator*( const noVec3 &vec ) const;
noMat3 operator*( const noMat3 &a ) const;
noMat3 operator+( const noMat3 &a ) const;
noMat3 operator-( const noMat3 &a ) const;
noMat3 & operator*=( const float a );
noMat3 & operator*=( const noMat3 &a );
noMat3 & operator+=( const noMat3 &a );
noMat3 & operator-=( const noMat3 &a );
friend noMat3 operator*( const float a, const noMat3 &mat );
friend noVec3 operator*( const noVec3 &vec, const noMat3 &mat );
friend noVec3 & operator*=( noVec3 &vec, const noMat3 &mat );
bool Compare( const noMat3 &a ) const; // exact compare, no epsilon
bool Compare( const noMat3 &a, const float epsilon ) const; // compare with epsilon
bool operator==( const noMat3 &a ) const; // exact compare, no epsilon
bool operator!=( const noMat3 &a ) const; // exact compare, no epsilon
void Zero( void );
void Identity( void );
bool IsIdentity( const float epsilon = MATRIX_EPSILON ) const;
bool IsSymmetric( const float epsilon = MATRIX_EPSILON ) const;
bool IsDiagonal( const float epsilon = MATRIX_EPSILON ) const;
bool IsRotated( void ) const;
void ProjectVector( const noVec3 &src, noVec3 &dst ) const;
void UnprojectVector( const noVec3 &src, noVec3 &dst ) const;
bool FixDegeneracies( void ); // fix degenerate axial cases
bool FixDenormals( void ); // change tiny numbers to zero
float Trace( void ) const;
float Determinant( void ) const;
noMat3 OrthoNormalize( void ) const;
noMat3 & OrthoNormalizeSelf( void );
noMat3 Transpose( void ) const; // returns transpose
noMat3 & TransposeSelf( void );
noMat3 Inverse( void ) const; // returns the inverse ( m * m.Inverse() = identity )
bool InverseSelf( void ); // returns false if determinant is zero
noMat3 InverseFast( void ) const; // returns the inverse ( m * m.Inverse() = identity )
bool InverseFastSelf( void ); // returns false if determinant is zero
noMat3 TransposeMultiply( const noMat3 &b ) const;
noMat3 InertiaTranslate( const float mass, const noVec3 ¢erOfMass, const noVec3 &translation ) const;
noMat3 & InertiaTranslateSelf( const float mass, const noVec3 ¢erOfMass, const noVec3 &translation );
noMat3 InertiaRotate( const noMat3 &rotation ) const;
noMat3 & InertiaRotateSelf( const noMat3 &rotation );
int GetDimension( void ) const;
noAngles ToAngles( void ) const;
noQuat ToQuat( void ) const;
idCQuat ToCQuat( void ) const;
noRotation ToRotation( void ) const;
noMat4 ToMat4( void ) const;
noVec3 ToAngularVelocity( void ) const;
const float * ToFloatPtr( void ) const;
float * ToFloatPtr( void );
const char * ToString( int precision = 2 ) const;
friend void TransposeMultiply( const noMat3 &inv, const noMat3 &b, noMat3 &dst );
friend noMat3 SkewSymmetric( noVec3 const &src );
noVec3 mat[ 3 ];
private:
};
extern noMat3 mat3_zero;
extern noMat3 mat3_identity;
#define mat3_default mat3_identity
__forceinline noMat3::noMat3( void ) {
}
__forceinline noMat3::noMat3( const noVec3 &x, const noVec3 &y, const noVec3 &z ) {
mat[ 0 ].x = x.x; mat[ 0 ].y = x.y; mat[ 0 ].z = x.z;
mat[ 1 ].x = y.x; mat[ 1 ].y = y.y; mat[ 1 ].z = y.z;
mat[ 2 ].x = z.x; mat[ 2 ].y = z.y; mat[ 2 ].z = z.z;
}
__forceinline noMat3::noMat3( const float xx, const float xy, const float xz, const float yx, const float yy, const float yz, const float zx, const float zy, const float zz ) {
mat[ 0 ].x = xx; mat[ 0 ].y = xy; mat[ 0 ].z = xz;
mat[ 1 ].x = yx; mat[ 1 ].y = yy; mat[ 1 ].z = yz;
mat[ 2 ].x = zx; mat[ 2 ].y = zy; mat[ 2 ].z = zz;
}
__forceinline noMat3::noMat3( const float src[ 3 ][ 3 ] ) {
memcpy( mat, src, 3 * 3 * sizeof( float ) );
}
__forceinline const noVec3 &noMat3::operator[]( int index ) const {
//assert( ( index >= 0 ) && ( index < 3 ) );
return mat[ index ];
}
__forceinline noVec3 &noMat3::operator[]( int index ) {
//assert( ( index >= 0 ) && ( index < 3 ) );
return mat[ index ];
}
__forceinline noMat3 noMat3::operator-() const {
return noMat3( -mat[0][0], -mat[0][1], -mat[0][2],
-mat[1][0], -mat[1][1], -mat[1][2],
-mat[2][0], -mat[2][1], -mat[2][2] );
}
__forceinline noVec3 noMat3::operator*( const noVec3 &vec ) const {
return noVec3(
mat[ 0 ].x * vec.x + mat[ 1 ].x * vec.y + mat[ 2 ].x * vec.z,
mat[ 0 ].y * vec.x + mat[ 1 ].y * vec.y + mat[ 2 ].y * vec.z,
mat[ 0 ].z * vec.x + mat[ 1 ].z * vec.y + mat[ 2 ].z * vec.z );
}
__forceinline noMat3 noMat3::operator*( const noMat3 &a ) const {
int i, j;
const float *m1Ptr, *m2Ptr;
float *dstPtr;
noMat3 dst;
m1Ptr = reinterpret_cast<const float *>(this);
m2Ptr = reinterpret_cast<const float *>(&a);
dstPtr = reinterpret_cast<float *>(&dst);
for ( i = 0; i < 3; i++ ) {
for ( j = 0; j < 3; j++ ) {
*dstPtr = m1Ptr[0] * m2Ptr[ 0 * 3 + j ]
+ m1Ptr[1] * m2Ptr[ 1 * 3 + j ]
+ m1Ptr[2] * m2Ptr[ 2 * 3 + j ];
dstPtr++;
}
m1Ptr += 3;
}
return dst;
}
__forceinline noMat3 noMat3::operator*( const float a ) const {
return noMat3(
mat[0].x * a, mat[0].y * a, mat[0].z * a,
mat[1].x * a, mat[1].y * a, mat[1].z * a,
mat[2].x * a, mat[2].y * a, mat[2].z * a );
}
__forceinline noMat3 noMat3::operator+( const noMat3 &a ) const {
return noMat3(
mat[0].x + a[0].x, mat[0].y + a[0].y, mat[0].z + a[0].z,
mat[1].x + a[1].x, mat[1].y + a[1].y, mat[1].z + a[1].z,
mat[2].x + a[2].x, mat[2].y + a[2].y, mat[2].z + a[2].z );
}
__forceinline noMat3 noMat3::operator-( const noMat3 &a ) const {
return noMat3(
mat[0].x - a[0].x, mat[0].y - a[0].y, mat[0].z - a[0].z,
mat[1].x - a[1].x, mat[1].y - a[1].y, mat[1].z - a[1].z,
mat[2].x - a[2].x, mat[2].y - a[2].y, mat[2].z - a[2].z );
}
__forceinline noMat3 &noMat3::operator*=( const float a ) {
mat[0].x *= a; mat[0].y *= a; mat[0].z *= a;
mat[1].x *= a; mat[1].y *= a; mat[1].z *= a;
mat[2].x *= a; mat[2].y *= a; mat[2].z *= a;
return *this;
}
__forceinline noMat3 &noMat3::operator*=( const noMat3 &a ) {
int i, j;
const float *m2Ptr;
float *m1Ptr, dst[3];
m1Ptr = reinterpret_cast<float *>(this);
m2Ptr = reinterpret_cast<const float *>(&a);
for ( i = 0; i < 3; i++ ) {
for ( j = 0; j < 3; j++ ) {
dst[j] = m1Ptr[0] * m2Ptr[ 0 * 3 + j ]
+ m1Ptr[1] * m2Ptr[ 1 * 3 + j ]
+ m1Ptr[2] * m2Ptr[ 2 * 3 + j ];
}
m1Ptr[0] = dst[0]; m1Ptr[1] = dst[1]; m1Ptr[2] = dst[2];
m1Ptr += 3;
}
return *this;
}
__forceinline noMat3 &noMat3::operator+=( const noMat3 &a ) {
mat[0].x += a[0].x; mat[0].y += a[0].y; mat[0].z += a[0].z;
mat[1].x += a[1].x; mat[1].y += a[1].y; mat[1].z += a[1].z;
mat[2].x += a[2].x; mat[2].y += a[2].y; mat[2].z += a[2].z;
return *this;
}
__forceinline noMat3 &noMat3::operator-=( const noMat3 &a ) {
mat[0].x -= a[0].x; mat[0].y -= a[0].y; mat[0].z -= a[0].z;
mat[1].x -= a[1].x; mat[1].y -= a[1].y; mat[1].z -= a[1].z;
mat[2].x -= a[2].x; mat[2].y -= a[2].y; mat[2].z -= a[2].z;
return *this;
}
__forceinline noVec3 operator*( const noVec3 &vec, const noMat3 &mat ) {
return mat * vec;
}
__forceinline noMat3 operator*( const float a, const noMat3 &mat ) {
return mat * a;
}
__forceinline noVec3 &operator*=( noVec3 &vec, const noMat3 &mat ) {
float x = mat[ 0 ].x * vec.x + mat[ 1 ].x * vec.y + mat[ 2 ].x * vec.z;
float y = mat[ 0 ].y * vec.x + mat[ 1 ].y * vec.y + mat[ 2 ].y * vec.z;
vec.z = mat[ 0 ].z * vec.x + mat[ 1 ].z * vec.y + mat[ 2 ].z * vec.z;
vec.x = x;
vec.y = y;
return vec;
}
__forceinline bool noMat3::Compare( const noMat3 &a ) const {
if ( mat[0].Compare( a[0] ) &&
mat[1].Compare( a[1] ) &&
mat[2].Compare( a[2] ) ) {
return true;
}
return false;
}
__forceinline bool noMat3::Compare( const noMat3 &a, const float epsilon ) const {
if ( mat[0].Compare( a[0], epsilon ) &&
mat[1].Compare( a[1], epsilon ) &&
mat[2].Compare( a[2], epsilon ) ) {
return true;
}
return false;
}
__forceinline bool noMat3::operator==( const noMat3 &a ) const {
return Compare( a );
}
__forceinline bool noMat3::operator!=( const noMat3 &a ) const {
return !Compare( a );
}
__forceinline void noMat3::Zero( void ) {
memset( mat, 0, sizeof( noMat3 ) );
}
__forceinline void noMat3::Identity( void ) {
*this = mat3_identity;
}
__forceinline bool noMat3::IsIdentity( const float epsilon ) const {
return Compare( mat3_identity, epsilon );
}
__forceinline bool noMat3::IsSymmetric( const float epsilon ) const {
if ( noMath::Fabs( mat[0][1] - mat[1][0] ) > epsilon ) {
return false;
}
if ( noMath::Fabs( mat[0][2] - mat[2][0] ) > epsilon ) {
return false;
}
if ( noMath::Fabs( mat[1][2] - mat[2][1] ) > epsilon ) {
return false;
}
return true;
}
__forceinline bool noMat3::IsDiagonal( const float epsilon ) const {
if ( noMath::Fabs( mat[0][1] ) > epsilon ||
noMath::Fabs( mat[0][2] ) > epsilon ||
noMath::Fabs( mat[1][0] ) > epsilon ||
noMath::Fabs( mat[1][2] ) > epsilon ||
noMath::Fabs( mat[2][0] ) > epsilon ||
noMath::Fabs( mat[2][1] ) > epsilon ) {
return false;
}
return true;
}
__forceinline bool noMat3::IsRotated( void ) const {
return !Compare( mat3_identity );
}
__forceinline void noMat3::ProjectVector( const noVec3 &src, noVec3 &dst ) const {
dst.x = src * mat[ 0 ];
dst.y = src * mat[ 1 ];
dst.z = src * mat[ 2 ];
}
__forceinline void noMat3::UnprojectVector( const noVec3 &src, noVec3 &dst ) const {
dst = mat[ 0 ] * src.x + mat[ 1 ] * src.y + mat[ 2 ] * src.z;
}
__forceinline bool noMat3::FixDegeneracies( void ) {
bool r = mat[0].FixDegenerateNormal();
r |= mat[1].FixDegenerateNormal();
r |= mat[2].FixDegenerateNormal();
return r;
}
__forceinline bool noMat3::FixDenormals( void ) {
bool r = mat[0].FixDenormals();
r |= mat[1].FixDenormals();
r |= mat[2].FixDenormals();
return r;
}
__forceinline float noMat3::Trace( void ) const {
return ( mat[0][0] + mat[1][1] + mat[2][2] );
}
__forceinline noMat3 noMat3::OrthoNormalize( void ) const {
noMat3 ortho;
ortho = *this;
ortho[ 0 ].Normalize();
ortho[ 2 ].Cross( mat[ 0 ], mat[ 1 ] );
ortho[ 2 ].Normalize();
ortho[ 1 ].Cross( mat[ 2 ], mat[ 0 ] );
ortho[ 1 ].Normalize();
return ortho;
}
__forceinline noMat3 &noMat3::OrthoNormalizeSelf( void ) {
mat[ 0 ].Normalize();
mat[ 2 ].Cross( mat[ 0 ], mat[ 1 ] );
mat[ 2 ].Normalize();
mat[ 1 ].Cross( mat[ 2 ], mat[ 0 ] );
mat[ 1 ].Normalize();
return *this;
}
__forceinline noMat3 noMat3::Transpose( void ) const {
return noMat3( mat[0][0], mat[1][0], mat[2][0],
mat[0][1], mat[1][1], mat[2][1],
mat[0][2], mat[1][2], mat[2][2] );
}
__forceinline noMat3 &noMat3::TransposeSelf( void ) {
float tmp0, tmp1, tmp2;
tmp0 = mat[0][1];
mat[0][1] = mat[1][0];
mat[1][0] = tmp0;
tmp1 = mat[0][2];
mat[0][2] = mat[2][0];
mat[2][0] = tmp1;
tmp2 = mat[1][2];
mat[1][2] = mat[2][1];
mat[2][1] = tmp2;
return *this;
}
__forceinline noMat3 noMat3::Inverse( void ) const {
noMat3 invMat;
invMat = *this;
int r = invMat.InverseSelf();
assert( r );
return invMat;
}
__forceinline noMat3 noMat3::InverseFast( void ) const {
noMat3 invMat;
invMat = *this;
int r = invMat.InverseFastSelf();
assert( r );
return invMat;
}
__forceinline noMat3 noMat3::TransposeMultiply( const noMat3 &b ) const {
return noMat3( mat[0].x * b[0].x + mat[1].x * b[1].x + mat[2].x * b[2].x,
mat[0].x * b[0].y + mat[1].x * b[1].y + mat[2].x * b[2].y,
mat[0].x * b[0].z + mat[1].x * b[1].z + mat[2].x * b[2].z,
mat[0].y * b[0].x + mat[1].y * b[1].x + mat[2].y * b[2].x,
mat[0].y * b[0].y + mat[1].y * b[1].y + mat[2].y * b[2].y,
mat[0].y * b[0].z + mat[1].y * b[1].z + mat[2].y * b[2].z,
mat[0].z * b[0].x + mat[1].z * b[1].x + mat[2].z * b[2].x,
mat[0].z * b[0].y + mat[1].z * b[1].y + mat[2].z * b[2].y,
mat[0].z * b[0].z + mat[1].z * b[1].z + mat[2].z * b[2].z );
}
__forceinline void TransposeMultiply( const noMat3 &transpose, const noMat3 &b, noMat3 &dst ) {
dst[0].x = transpose[0].x * b[0].x + transpose[1].x * b[1].x + transpose[2].x * b[2].x;
dst[0].y = transpose[0].x * b[0].y + transpose[1].x * b[1].y + transpose[2].x * b[2].y;
dst[0].z = transpose[0].x * b[0].z + transpose[1].x * b[1].z + transpose[2].x * b[2].z;
dst[1].x = transpose[0].y * b[0].x + transpose[1].y * b[1].x + transpose[2].y * b[2].x;
dst[1].y = transpose[0].y * b[0].y + transpose[1].y * b[1].y + transpose[2].y * b[2].y;
dst[1].z = transpose[0].y * b[0].z + transpose[1].y * b[1].z + transpose[2].y * b[2].z;
dst[2].x = transpose[0].z * b[0].x + transpose[1].z * b[1].x + transpose[2].z * b[2].x;
dst[2].y = transpose[0].z * b[0].y + transpose[1].z * b[1].y + transpose[2].z * b[2].y;
dst[2].z = transpose[0].z * b[0].z + transpose[1].z * b[1].z + transpose[2].z * b[2].z;
}
__forceinline noMat3 SkewSymmetric( noVec3 const &src ) {
return noMat3( 0.0f, -src.z, src.y, src.z, 0.0f, -src.x, -src.y, src.x, 0.0f );
}
__forceinline int noMat3::GetDimension( void ) const {
return 9;
}
__forceinline const float *noMat3::ToFloatPtr( void ) const {
return mat[0].ToFloatPtr();
}
__forceinline float *noMat3::ToFloatPtr( void ) {
return mat[0].ToFloatPtr();
}
//===============================================================
//
// noMat4 - 4x4 matrix
//
//===============================================================
class noMat4 {
public:
noMat4( void );
explicit noMat4( const noVec4 &x, const noVec4 &y, const noVec4 &z, const noVec4 &w );
explicit noMat4(const float xx, const float xy, const float xz, const float xw,
const float yx, const float yy, const float yz, const float yw,
const float zx, const float zy, const float zz, const float zw,
const float wx, const float wy, const float wz, const float ww );
explicit noMat4( const noMat3 &rotation, const noVec3 &translation );
explicit noMat4( const float src[ 4 ][ 4 ] );
explicit noMat4( const float src[ 16 ] );
const noVec4 & operator[]( int index ) const;
noVec4 & operator[]( int index );
noMat4 operator*( const float a ) const;
noVec4 operator*( const noVec4 &vec ) const;
noVec3 operator*( const noVec3 &vec ) const;
noMat4 operator*( const noMat4 &a ) const;
noMat4 operator+( const noMat4 &a ) const;
noMat4 operator-( const noMat4 &a ) const;
noMat4 & operator*=( const float a );
noMat4 & operator*=( const noMat4 &a );
noMat4 & operator+=( const noMat4 &a );
noMat4 & operator-=( const noMat4 &a );
void Translation(const noVec3& t);
friend noMat4 operator*( const float a, const noMat4 &mat );
friend noVec4 operator*( const noVec4 &vec, const noMat4 &mat );
friend noVec3 operator*( const noVec3 &vec, const noMat4 &mat );
friend noVec4 & operator*=( noVec4 &vec, const noMat4 &mat );
friend noVec3 & operator*=( noVec3 &vec, const noMat4 &mat );
bool Compare( const noMat4 &a ) const; // exact compare, no epsilon
bool Compare( const noMat4 &a, const float epsilon ) const; // compare with epsilon
bool operator==( const noMat4 &a ) const; // exact compare, no epsilon
bool operator!=( const noMat4 &a ) const; // exact compare, no epsilon
void Zero( void );
void Identity( void );
bool IsIdentity( const float epsilon = MATRIX_EPSILON ) const;
bool IsSymmetric( const float epsilon = MATRIX_EPSILON ) const;
bool IsDiagonal( const float epsilon = MATRIX_EPSILON ) const;
bool IsRotated( void ) const;
void ProjectVector( const noVec4 &src, noVec4 &dst ) const;
void UnprojectVector( const noVec4 &src, noVec4 &dst ) const;
float Trace( void ) const;
float Determinant( void ) const;
noMat4 Transpose( void ) const; // returns transpose
noMat4 & TransposeSelf( void );
noMat4 Inverse( void ) const; // returns the inverse ( m * m.Inverse() = identity )
bool InverseSelf( void ); // returns false if determinant is zero
noMat4 InverseFast( void ) const; // returns the inverse ( m * m.Inverse() = identity )
bool InverseFastSelf( void ); // returns false if determinant is zero
noMat4 TransposeMultiply( const noMat4 &b ) const;
int GetDimension( void ) const;
const float * ToFloatPtr( void ) const;
float * ToFloatPtr( void );
const char * ToString( int precision = 2 ) const;
void Scale( const noVec3& t );
void SetOrigin(const noVec3& v);
noVec3 GetOrigin() const;
void RemoveScaling(FLOAT Tolerance =SMALL_NUMBER);
noVec4 mat[ 4 ];
private:
};
extern noMat4 mat4_zero;
extern noMat4 mat4_identity;
#define mat4_default mat4_identity
__forceinline noMat4::noMat4( void ) {
}
__forceinline noMat4::noMat4( const noVec4 &x, const noVec4 &y, const noVec4 &z, const noVec4 &w ) {
mat[ 0 ] = x;
mat[ 1 ] = y;
mat[ 2 ] = z;
mat[ 3 ] = w;
}
__forceinline noMat4::noMat4( const float xx, const float xy, const float xz, const float xw,
const float yx, const float yy, const float yz, const float yw,
const float zx, const float zy, const float zz, const float zw,
const float wx, const float wy, const float wz, const float ww ) {
mat[0][0] = xx; mat[0][1] = xy; mat[0][2] = xz; mat[0][3] = xw;
mat[1][0] = yx; mat[1][1] = yy; mat[1][2] = yz; mat[1][3] = yw;
mat[2][0] = zx; mat[2][1] = zy; mat[2][2] = zz; mat[2][3] = zw;
mat[3][0] = wx; mat[3][1] = wy; mat[3][2] = wz; mat[3][3] = ww;
}
__forceinline noMat4::noMat4( const noMat3 &rotation, const noVec3 &translation ) {
// NOTE: noMat3 is transposed because it is column-major
mat[ 0 ][ 0 ] = rotation[0][0];
mat[ 0 ][ 1 ] = rotation[1][0];
mat[ 0 ][ 2 ] = rotation[2][0];
mat[ 0 ][ 3 ] = translation[0];
mat[ 1 ][ 0 ] = rotation[0][1];
mat[ 1 ][ 1 ] = rotation[1][1];
mat[ 1 ][ 2 ] = rotation[2][1];
mat[ 1 ][ 3 ] = translation[1];
mat[ 2 ][ 0 ] = rotation[0][2];
mat[ 2 ][ 1 ] = rotation[1][2];
mat[ 2 ][ 2 ] = rotation[2][2];
mat[ 2 ][ 3 ] = translation[2];
mat[ 3 ][ 0 ] = 0.0f;
mat[ 3 ][ 1 ] = 0.0f;
mat[ 3 ][ 2 ] = 0.0f;
mat[ 3 ][ 3 ] = 1.0f;
}
__forceinline noMat4::noMat4( const float src[ 4 ][ 4 ] ) {
memcpy( mat, src, 4 * 4 * sizeof( float ) );
}
__forceinline noMat4::noMat4( const float src[ 16 ] ) {
memcpy( mat, src, 4 * 4 * sizeof( float ) );
}
__forceinline const noVec4 &noMat4::operator[]( int index ) const {
//assert( ( index >= 0 ) && ( index < 4 ) );
return mat[ index ];
}
__forceinline noVec4 &noMat4::operator[]( int index ) {
//assert( ( index >= 0 ) && ( index < 4 ) );
return mat[ index ];
}
__forceinline noMat4 noMat4::operator*( const float a ) const {
return noMat4(
mat[0].x * a, mat[0].y * a, mat[0].z * a, mat[0].w * a,
mat[1].x * a, mat[1].y * a, mat[1].z * a, mat[1].w * a,
mat[2].x * a, mat[2].y * a, mat[2].z * a, mat[2].w * a,
mat[3].x * a, mat[3].y * a, mat[3].z * a, mat[3].w * a );
}
__forceinline noVec4 noMat4::operator*( const noVec4 &vec ) const {
return noVec4(
mat[ 0 ].x * vec.x + mat[ 0 ].y * vec.y + mat[ 0 ].z * vec.z + mat[ 0 ].w * vec.w,
mat[ 1 ].x * vec.x + mat[ 1 ].y * vec.y + mat[ 1 ].z * vec.z + mat[ 1 ].w * vec.w,
mat[ 2 ].x * vec.x + mat[ 2 ].y * vec.y + mat[ 2 ].z * vec.z + mat[ 2 ].w * vec.w,
mat[ 3 ].x * vec.x + mat[ 3 ].y * vec.y + mat[ 3 ].z * vec.z + mat[ 3 ].w * vec.w );
}
__forceinline noVec3 noMat4::operator*( const noVec3 &vec ) const {
float s = mat[ 3 ].x * vec.x + mat[ 3 ].y * vec.y + mat[ 3 ].z * vec.z + mat[ 3 ].w;
if ( s == 0.0f ) {
return noVec3( 0.0f, 0.0f, 0.0f );
}
if ( s == 1.0f ) {
return noVec3(
mat[ 0 ].x * vec.x + mat[ 0 ].y * vec.y + mat[ 0 ].z * vec.z + mat[ 0 ].w,
mat[ 1 ].x * vec.x + mat[ 1 ].y * vec.y + mat[ 1 ].z * vec.z + mat[ 1 ].w,
mat[ 2 ].x * vec.x + mat[ 2 ].y * vec.y + mat[ 2 ].z * vec.z + mat[ 2 ].w );
}
else {
float invS = 1.0f / s;
return noVec3(
(mat[ 0 ].x * vec.x + mat[ 0 ].y * vec.y + mat[ 0 ].z * vec.z + mat[ 0 ].w) * invS,
(mat[ 1 ].x * vec.x + mat[ 1 ].y * vec.y + mat[ 1 ].z * vec.z + mat[ 1 ].w) * invS,
(mat[ 2 ].x * vec.x + mat[ 2 ].y * vec.y + mat[ 2 ].z * vec.z + mat[ 2 ].w) * invS );
}
}
__forceinline noMat4 noMat4::operator*( const noMat4 &a ) const {
int i, j;
const float *m1Ptr, *m2Ptr;
float *dstPtr;
noMat4 dst;
m1Ptr = reinterpret_cast<const float *>(this);
m2Ptr = reinterpret_cast<const float *>(&a);
dstPtr = reinterpret_cast<float *>(&dst);
for ( i = 0; i < 4; i++ ) {
for ( j = 0; j < 4; j++ ) {
*dstPtr = m1Ptr[0] * m2Ptr[ 0 * 4 + j ]
+ m1Ptr[1] * m2Ptr[ 1 * 4 + j ]
+ m1Ptr[2] * m2Ptr[ 2 * 4 + j ]
+ m1Ptr[3] * m2Ptr[ 3 * 4 + j ];
dstPtr++;
}
m1Ptr += 4;
}
return dst;
}
__forceinline noMat4 noMat4::operator+( const noMat4 &a ) const {
return noMat4(
mat[0].x + a[0].x, mat[0].y + a[0].y, mat[0].z + a[0].z, mat[0].w + a[0].w,
mat[1].x + a[1].x, mat[1].y + a[1].y, mat[1].z + a[1].z, mat[1].w + a[1].w,
mat[2].x + a[2].x, mat[2].y + a[2].y, mat[2].z + a[2].z, mat[2].w + a[2].w,
mat[3].x + a[3].x, mat[3].y + a[3].y, mat[3].z + a[3].z, mat[3].w + a[3].w );
}
__forceinline noMat4 noMat4::operator-( const noMat4 &a ) const {
return noMat4(
mat[0].x - a[0].x, mat[0].y - a[0].y, mat[0].z - a[0].z, mat[0].w - a[0].w,
mat[1].x - a[1].x, mat[1].y - a[1].y, mat[1].z - a[1].z, mat[1].w - a[1].w,
mat[2].x - a[2].x, mat[2].y - a[2].y, mat[2].z - a[2].z, mat[2].w - a[2].w,
mat[3].x - a[3].x, mat[3].y - a[3].y, mat[3].z - a[3].z, mat[3].w - a[3].w );
}
__forceinline noMat4 &noMat4::operator*=( const float a ) {
mat[0].x *= a; mat[0].y *= a; mat[0].z *= a; mat[0].w *= a;
mat[1].x *= a; mat[1].y *= a; mat[1].z *= a; mat[1].w *= a;
mat[2].x *= a; mat[2].y *= a; mat[2].z *= a; mat[2].w *= a;
mat[3].x *= a; mat[3].y *= a; mat[3].z *= a; mat[3].w *= a;
return *this;
}
__forceinline noMat4 &noMat4::operator*=( const noMat4 &a ) {
*this = (*this) * a;
return *this;
}
__forceinline noMat4 &noMat4::operator+=( const noMat4 &a ) {
mat[0].x += a[0].x; mat[0].y += a[0].y; mat[0].z += a[0].z; mat[0].w += a[0].w;
mat[1].x += a[1].x; mat[1].y += a[1].y; mat[1].z += a[1].z; mat[1].w += a[1].w;
mat[2].x += a[2].x; mat[2].y += a[2].y; mat[2].z += a[2].z; mat[2].w += a[2].w;
mat[3].x += a[3].x; mat[3].y += a[3].y; mat[3].z += a[3].z; mat[3].w += a[3].w;
return *this;
}
__forceinline noMat4 &noMat4::operator-=( const noMat4 &a ) {
mat[0].x -= a[0].x; mat[0].y -= a[0].y; mat[0].z -= a[0].z; mat[0].w -= a[0].w;
mat[1].x -= a[1].x; mat[1].y -= a[1].y; mat[1].z -= a[1].z; mat[1].w -= a[1].w;
mat[2].x -= a[2].x; mat[2].y -= a[2].y; mat[2].z -= a[2].z; mat[2].w -= a[2].w;
mat[3].x -= a[3].x; mat[3].y -= a[3].y; mat[3].z -= a[3].z; mat[3].w -= a[3].w;
return *this;
}
__forceinline noMat4 operator*( const float a, const noMat4 &mat ) {
return mat * a;
}
__forceinline noVec4 operator*( const noVec4 &vec, const noMat4 &mat ) {
return mat * vec;
}
__forceinline noVec3 operator*( const noVec3 &vec, const noMat4 &mat ) {
return mat * vec;
}
__forceinline noVec4 &operator*=( noVec4 &vec, const noMat4 &mat ) {
vec = mat * vec;
return vec;
}
__forceinline noVec3 &operator*=( noVec3 &vec, const noMat4 &mat ) {
vec = mat * vec;
return vec;
}
__forceinline bool noMat4::Compare( const noMat4 &a ) const {
dword i;
const float *ptr1, *ptr2;
ptr1 = reinterpret_cast<const float *>(mat);
ptr2 = reinterpret_cast<const float *>(a.mat);
for ( i = 0; i < 4*4; i++ ) {
if ( ptr1[i] != ptr2[i] ) {
return false;
}
}
return true;
}
__forceinline bool noMat4::Compare( const noMat4 &a, const float epsilon ) const {
dword i;
const float *ptr1, *ptr2;
ptr1 = reinterpret_cast<const float *>(mat);
ptr2 = reinterpret_cast<const float *>(a.mat);
for ( i = 0; i < 4*4; i++ ) {
if ( noMath::Fabs( ptr1[i] - ptr2[i] ) > epsilon ) {
return false;
}
}
return true;
}
__forceinline bool noMat4::operator==( const noMat4 &a ) const {
return Compare( a );
}
__forceinline bool noMat4::operator!=( const noMat4 &a ) const {
return !Compare( a );
}
__forceinline void noMat4::Zero( void ) {
memset( mat, 0, sizeof( noMat4 ) );
}
__forceinline void noMat4::Identity( void ) {
*this = mat4_identity;
}
__forceinline bool noMat4::IsIdentity( const float epsilon ) const {
return Compare( mat4_identity, epsilon );
}
__forceinline bool noMat4::IsSymmetric( const float epsilon ) const {
for ( int i = 1; i < 4; i++ ) {
for ( int j = 0; j < i; j++ ) {
if ( noMath::Fabs( mat[i][j] - mat[j][i] ) > epsilon ) {
return false;
}
}
}
return true;
}
__forceinline bool noMat4::IsDiagonal( const float epsilon ) const {
for ( int i = 0; i < 4; i++ ) {
for ( int j = 0; j < 4; j++ ) {
if ( i != j && noMath::Fabs( mat[i][j] ) > epsilon ) {
return false;
}
}
}
return true;
}
__forceinline bool noMat4::IsRotated( void ) const {
if ( !mat[ 0 ][ 1 ] && !mat[ 0 ][ 2 ] &&
!mat[ 1 ][ 0 ] && !mat[ 1 ][ 2 ] &&
!mat[ 2 ][ 0 ] && !mat[ 2 ][ 1 ] ) {
return false;
}
return true;
}
__forceinline void noMat4::ProjectVector( const noVec4 &src, noVec4 &dst ) const {
dst.x = src * mat[ 0 ];
dst.y = src * mat[ 1 ];
dst.z = src * mat[ 2 ];
dst.w = src * mat[ 3 ];
}
__forceinline void noMat4::UnprojectVector( const noVec4 &src, noVec4 &dst ) const {
dst = mat[ 0 ] * src.x + mat[ 1 ] * src.y + mat[ 2 ] * src.z + mat[ 3 ] * src.w;
}
__forceinline float noMat4::Trace( void ) const {
return ( mat[0][0] + mat[1][1] + mat[2][2] + mat[3][3] );
}
__forceinline noMat4 noMat4::Inverse( void ) const {
noMat4 invMat;
invMat = *this;
int r = invMat.InverseSelf();
assert( r );
return invMat;
}
__forceinline noMat4 noMat4::InverseFast( void ) const {
noMat4 invMat;
invMat = *this;
int r = invMat.InverseFastSelf();
assert( r );
return invMat;
}
__forceinline noMat4 noMat3::ToMat4( void ) const {
// NOTE: noMat3 is transposed because it is column-major
return noMat4( mat[0][0], mat[1][0], mat[2][0], 0.0f,
mat[0][1], mat[1][1], mat[2][1], 0.0f,
mat[0][2], mat[1][2], mat[2][2], 0.0f,
0.0f, 0.0f, 0.0f, 1.0f );
}
__forceinline int noMat4::GetDimension( void ) const {
return 16;
}
__forceinline const float *noMat4::ToFloatPtr( void ) const {
return mat[0].ToFloatPtr();
}
__forceinline void noMat4::Translation( const noVec3& t )
{
Identity();
mat[0][3] = t.x;
mat[1][3] = t.y;
mat[2][3] = t.z;
}
__forceinline void noMat4::Scale( const noVec3& t )
{
Zero();
mat[0][0] = t.x;
mat[1][1] = t.y;
mat[2][2] = t.z;
mat[3][3] = 1.0f;
}
__forceinline float *noMat4::ToFloatPtr( void ) {
return mat[0].ToFloatPtr();
}
NO_INLINE void noMat4::SetOrigin(const noVec3& v)
{
mat[0][3] = v.x;
mat[1][3] = v.y;
mat[2][3] = v.z;
}
__forceinline noVec3 noMat4::GetOrigin() const
{
return noVec3(mat[0][3], mat[1][3], mat[2][3]);
}
// Remove any scaling from this matrix (ie magnitude of each row is 1)
__forceinline void noMat4::RemoveScaling(FLOAT Tolerance/*=SMALL_NUMBER*/)
{
// For each row, find magnitude, and if its non-zero re-scale so its unit length.
for(INT i=0; i<3; i++)
{
const FLOAT SquareSum = (mat[i][0] * mat[i][0]) + (mat[i][1] * mat[i][1]) + (mat[i][2] * mat[i][2]);
if(SquareSum > Tolerance)
{
const FLOAT Scale = noMath::InvSqrt(SquareSum);
mat[i][0] *= Scale;
mat[i][1] *= Scale;
mat[i][2] *= Scale;
}
}
}
// Symmetric matrices can be optimized
template< class SCALAR, class V3, class T_MATRIX3 >
class T_SYMMETRIC_MATRIX3
{
public:
SCALAR xx, yy, zz; //diagonal elements
SCALAR xy, xz, yz; //off-diagonal elements
public:
T_SYMMETRIC_MATRIX3()
{
//identity
xx = yy = zz = 1;
xy = xz = yz = 0;
}
T_SYMMETRIC_MATRIX3(
const SCALAR xx,
const SCALAR yy,
const SCALAR zz,
const SCALAR xy,
const SCALAR xz,
const SCALAR yz
)
{
this->xx = xx;
this->yy = yy;
this->zz = zz;
this->xy = xy;
this->xz = xz;
this->yz = yz;
}
//set equal to another matrix
const T_SYMMETRIC_MATRIX3& operator = ( const T_SYMMETRIC_MATRIX3& m )
{
this->xx = m.xx;
this->yy = m.yy;
this->zz = m.zz;
this->xy = m.xy;
this->xz = m.xz;
this->yz = m.yz;
return *this;
}
//increment by another matrix
const T_SYMMETRIC_MATRIX3& operator += ( const T_SYMMETRIC_MATRIX3& m )
{
this->xx += m.xx;
this->yy += m.yy;
this->zz += m.zz;
this->xy += m.xy;
this->xz += m.xz;
this->yz += m.yz;
return *this;
}
//decrement by another matrix
const T_SYMMETRIC_MATRIX3& operator -=( const T_SYMMETRIC_MATRIX3& m )
{
this->xx -= m.xx;
this->yy -= m.yy;
this->zz -= m.zz;
this->xy -= m.xy;
this->xz -= m.xz;
this->yz -= m.yz;
return *this;
}
//add two matrices
T_SYMMETRIC_MATRIX3 operator + ( const T_SYMMETRIC_MATRIX3& m ) const
{
return T_SYMMETRIC_MATRIX3(
xx + m.xx,
yy + m.yy,
zz + m.zz,
xy + m.xy,
xz + m.xz,
yz + m.yz
);
}
//subtract two matrices
T_SYMMETRIC_MATRIX3 operator - ( const T_SYMMETRIC_MATRIX3& m ) const
{
return T_SYMMETRIC_MATRIX3(
xx - m.xx,
yy - m.yy,
zz - m.zz,
xy - m.xy,
xz - m.xz,
yz - m.yz
);
}
//post-multiply by a vector
V3 operator * ( const V3& v ) const
{
return V3( v.x*xx + v.y*xy + v.z*xz,
v.x*xy + v.y*yy + v.z*yz,
v.z*xz + v.y*yz + v.z*zz );
}
//pre-multiply by a vector
friend inline V3 operator * ( const V3& v, const T_SYMMETRIC_MATRIX3& m )
{
return m * v;
}
//NOTE: Can't do a self-multiply because the product of two symmetric matrices
//is not necessarily a symmetric matrix
//multiply two symmetric matrices
// T_SYMMETRIC_MATRIX3 operator * ( const T_SYMMETRIC_MATRIX3& m ) const
// {
// return T_MATRIX3();
// }
// - matrix specific - //
//a symmetric matrix is equal to its transpose
//Is there a simplified formula for the inverse of a symmetric matrix?
};
typedef T_SYMMETRIC_MATRIX3< float, noVec3, noMat3 > noSymmetricMat3;
//===============================================================
//
// idMat5 - 5x5 matrix
//
//===============================================================
class idMat5 {
public:
idMat5( void );
explicit idMat5( const idVec5 &v0, const idVec5 &v1, const idVec5 &v2, const idVec5 &v3, const idVec5 &v4 );
explicit idMat5( const float src[ 5 ][ 5 ] );
const idVec5 & operator[]( int index ) const;
idVec5 & operator[]( int index );
idMat5 operator*( const float a ) const;
idVec5 operator*( const idVec5 &vec ) const;
idMat5 operator*( const idMat5 &a ) const;
idMat5 operator+( const idMat5 &a ) const;
idMat5 operator-( const idMat5 &a ) const;
idMat5 & operator*=( const float a );
idMat5 & operator*=( const idMat5 &a );
idMat5 & operator+=( const idMat5 &a );
idMat5 & operator-=( const idMat5 &a );
friend idMat5 operator*( const float a, const idMat5 &mat );
friend idVec5 operator*( const idVec5 &vec, const idMat5 &mat );
friend idVec5 & operator*=( idVec5 &vec, const idMat5 &mat );
bool Compare( const idMat5 &a ) const; // exact compare, no epsilon
bool Compare( const idMat5 &a, const float epsilon ) const; // compare with epsilon
bool operator==( const idMat5 &a ) const; // exact compare, no epsilon
bool operator!=( const idMat5 &a ) const; // exact compare, no epsilon
void Zero( void );
void Identity( void );
bool IsIdentity( const float epsilon = MATRIX_EPSILON ) const;
bool IsSymmetric( const float epsilon = MATRIX_EPSILON ) const;
bool IsDiagonal( const float epsilon = MATRIX_EPSILON ) const;
float Trace( void ) const;
float Determinant( void ) const;
idMat5 Transpose( void ) const; // returns transpose
idMat5 & TransposeSelf( void );
idMat5 Inverse( void ) const; // returns the inverse ( m * m.Inverse() = identity )
bool InverseSelf( void ); // returns false if determinant is zero
idMat5 InverseFast( void ) const; // returns the inverse ( m * m.Inverse() = identity )
bool InverseFastSelf( void ); // returns false if determinant is zero
int GetDimension( void ) const;
const float * ToFloatPtr( void ) const;
float * ToFloatPtr( void );
const char * ToString( int precision = 2 ) const;
private:
idVec5 mat[ 5 ];
};
extern idMat5 mat5_zero;
extern idMat5 mat5_identity;
#define mat5_default mat5_identity
ID_INLINE idMat5::idMat5( void ) {
}
ID_INLINE idMat5::idMat5( const float src[ 5 ][ 5 ] ) {
memcpy( mat, src, 5 * 5 * sizeof( float ) );
}
ID_INLINE idMat5::idMat5( const idVec5 &v0, const idVec5 &v1, const idVec5 &v2, const idVec5 &v3, const idVec5 &v4 ) {
mat[0] = v0;
mat[1] = v1;
mat[2] = v2;
mat[3] = v3;
mat[4] = v4;
}
ID_INLINE const idVec5 &idMat5::operator[]( int index ) const {
//assert( ( index >= 0 ) && ( index < 5 ) );
return mat[ index ];
}
ID_INLINE idVec5 &idMat5::operator[]( int index ) {
//assert( ( index >= 0 ) && ( index < 5 ) );
return mat[ index ];
}
ID_INLINE idMat5 idMat5::operator*( const idMat5 &a ) const {
int i, j;
const float *m1Ptr, *m2Ptr;
float *dstPtr;
idMat5 dst;
m1Ptr = reinterpret_cast<const float *>(this);
m2Ptr = reinterpret_cast<const float *>(&a);
dstPtr = reinterpret_cast<float *>(&dst);
for ( i = 0; i < 5; i++ ) {
for ( j = 0; j < 5; j++ ) {
*dstPtr = m1Ptr[0] * m2Ptr[ 0 * 5 + j ]
+ m1Ptr[1] * m2Ptr[ 1 * 5 + j ]
+ m1Ptr[2] * m2Ptr[ 2 * 5 + j ]
+ m1Ptr[3] * m2Ptr[ 3 * 5 + j ]
+ m1Ptr[4] * m2Ptr[ 4 * 5 + j ];
dstPtr++;
}
m1Ptr += 5;
}
return dst;
}
ID_INLINE idMat5 idMat5::operator*( const float a ) const {
return idMat5(
idVec5( mat[0][0] * a, mat[0][1] * a, mat[0][2] * a, mat[0][3] * a, mat[0][4] * a ),
idVec5( mat[1][0] * a, mat[1][1] * a, mat[1][2] * a, mat[1][3] * a, mat[1][4] * a ),
idVec5( mat[2][0] * a, mat[2][1] * a, mat[2][2] * a, mat[2][3] * a, mat[2][4] * a ),
idVec5( mat[3][0] * a, mat[3][1] * a, mat[3][2] * a, mat[3][3] * a, mat[3][4] * a ),
idVec5( mat[4][0] * a, mat[4][1] * a, mat[4][2] * a, mat[4][3] * a, mat[4][4] * a ) );
}
ID_INLINE idVec5 idMat5::operator*( const idVec5 &vec ) const {
return idVec5(
mat[0][0] * vec[0] + mat[0][1] * vec[1] + mat[0][2] * vec[2] + mat[0][3] * vec[3] + mat[0][4] * vec[4],
mat[1][0] * vec[0] + mat[1][1] * vec[1] + mat[1][2] * vec[2] + mat[1][3] * vec[3] + mat[1][4] * vec[4],
mat[2][0] * vec[0] + mat[2][1] * vec[1] + mat[2][2] * vec[2] + mat[2][3] * vec[3] + mat[2][4] * vec[4],
mat[3][0] * vec[0] + mat[3][1] * vec[1] + mat[3][2] * vec[2] + mat[3][3] * vec[3] + mat[3][4] * vec[4],
mat[4][0] * vec[0] + mat[4][1] * vec[1] + mat[4][2] * vec[2] + mat[4][3] * vec[3] + mat[4][4] * vec[4] );
}
ID_INLINE idMat5 idMat5::operator+( const idMat5 &a ) const {
return idMat5(
idVec5( mat[0][0] + a[0][0], mat[0][1] + a[0][1], mat[0][2] + a[0][2], mat[0][3] + a[0][3], mat[0][4] + a[0][4] ),
idVec5( mat[1][0] + a[1][0], mat[1][1] + a[1][1], mat[1][2] + a[1][2], mat[1][3] + a[1][3], mat[1][4] + a[1][4] ),
idVec5( mat[2][0] + a[2][0], mat[2][1] + a[2][1], mat[2][2] + a[2][2], mat[2][3] + a[2][3], mat[2][4] + a[2][4] ),
idVec5( mat[3][0] + a[3][0], mat[3][1] + a[3][1], mat[3][2] + a[3][2], mat[3][3] + a[3][3], mat[3][4] + a[3][4] ),
idVec5( mat[4][0] + a[4][0], mat[4][1] + a[4][1], mat[4][2] + a[4][2], mat[4][3] + a[4][3], mat[4][4] + a[4][4] ) );
}
ID_INLINE idMat5 idMat5::operator-( const idMat5 &a ) const {
return idMat5(
idVec5( mat[0][0] - a[0][0], mat[0][1] - a[0][1], mat[0][2] - a[0][2], mat[0][3] - a[0][3], mat[0][4] - a[0][4] ),
idVec5( mat[1][0] - a[1][0], mat[1][1] - a[1][1], mat[1][2] - a[1][2], mat[1][3] - a[1][3], mat[1][4] - a[1][4] ),
idVec5( mat[2][0] - a[2][0], mat[2][1] - a[2][1], mat[2][2] - a[2][2], mat[2][3] - a[2][3], mat[2][4] - a[2][4] ),
idVec5( mat[3][0] - a[3][0], mat[3][1] - a[3][1], mat[3][2] - a[3][2], mat[3][3] - a[3][3], mat[3][4] - a[3][4] ),
idVec5( mat[4][0] - a[4][0], mat[4][1] - a[4][1], mat[4][2] - a[4][2], mat[4][3] - a[4][3], mat[4][4] - a[4][4] ) );
}
ID_INLINE idMat5 &idMat5::operator*=( const float a ) {
mat[0][0] *= a; mat[0][1] *= a; mat[0][2] *= a; mat[0][3] *= a; mat[0][4] *= a;
mat[1][0] *= a; mat[1][1] *= a; mat[1][2] *= a; mat[1][3] *= a; mat[1][4] *= a;
mat[2][0] *= a; mat[2][1] *= a; mat[2][2] *= a; mat[2][3] *= a; mat[2][4] *= a;
mat[3][0] *= a; mat[3][1] *= a; mat[3][2] *= a; mat[3][3] *= a; mat[3][4] *= a;
mat[4][0] *= a; mat[4][1] *= a; mat[4][2] *= a; mat[4][3] *= a; mat[4][4] *= a;
return *this;
}
ID_INLINE idMat5 &idMat5::operator*=( const idMat5 &a ) {
*this = *this * a;
return *this;
}
ID_INLINE idMat5 &idMat5::operator+=( const idMat5 &a ) {
mat[0][0] += a[0][0]; mat[0][1] += a[0][1]; mat[0][2] += a[0][2]; mat[0][3] += a[0][3]; mat[0][4] += a[0][4];
mat[1][0] += a[1][0]; mat[1][1] += a[1][1]; mat[1][2] += a[1][2]; mat[1][3] += a[1][3]; mat[1][4] += a[1][4];
mat[2][0] += a[2][0]; mat[2][1] += a[2][1]; mat[2][2] += a[2][2]; mat[2][3] += a[2][3]; mat[2][4] += a[2][4];
mat[3][0] += a[3][0]; mat[3][1] += a[3][1]; mat[3][2] += a[3][2]; mat[3][3] += a[3][3]; mat[3][4] += a[3][4];
mat[4][0] += a[4][0]; mat[4][1] += a[4][1]; mat[4][2] += a[4][2]; mat[4][3] += a[4][3]; mat[4][4] += a[4][4];
return *this;
}
ID_INLINE idMat5 &idMat5::operator-=( const idMat5 &a ) {
mat[0][0] -= a[0][0]; mat[0][1] -= a[0][1]; mat[0][2] -= a[0][2]; mat[0][3] -= a[0][3]; mat[0][4] -= a[0][4];
mat[1][0] -= a[1][0]; mat[1][1] -= a[1][1]; mat[1][2] -= a[1][2]; mat[1][3] -= a[1][3]; mat[1][4] -= a[1][4];
mat[2][0] -= a[2][0]; mat[2][1] -= a[2][1]; mat[2][2] -= a[2][2]; mat[2][3] -= a[2][3]; mat[2][4] -= a[2][4];
mat[3][0] -= a[3][0]; mat[3][1] -= a[3][1]; mat[3][2] -= a[3][2]; mat[3][3] -= a[3][3]; mat[3][4] -= a[3][4];
mat[4][0] -= a[4][0]; mat[4][1] -= a[4][1]; mat[4][2] -= a[4][2]; mat[4][3] -= a[4][3]; mat[4][4] -= a[4][4];
return *this;
}
ID_INLINE idVec5 operator*( const idVec5 &vec, const idMat5 &mat ) {
return mat * vec;
}
ID_INLINE idMat5 operator*( const float a, idMat5 const &mat ) {
return mat * a;
}
ID_INLINE idVec5 &operator*=( idVec5 &vec, const idMat5 &mat ) {
vec = mat * vec;
return vec;
}
ID_INLINE bool idMat5::Compare( const idMat5 &a ) const {
dword i;
const float *ptr1, *ptr2;
ptr1 = reinterpret_cast<const float *>(mat);
ptr2 = reinterpret_cast<const float *>(a.mat);
for ( i = 0; i < 5*5; i++ ) {
if ( ptr1[i] != ptr2[i] ) {
return false;
}
}
return true;
}
ID_INLINE bool idMat5::Compare( const idMat5 &a, const float epsilon ) const {
dword i;
const float *ptr1, *ptr2;
ptr1 = reinterpret_cast<const float *>(mat);
ptr2 = reinterpret_cast<const float *>(a.mat);
for ( i = 0; i < 5*5; i++ ) {
if ( noMath::Fabs( ptr1[i] - ptr2[i] ) > epsilon ) {
return false;
}
}
return true;
}
ID_INLINE bool idMat5::operator==( const idMat5 &a ) const {
return Compare( a );
}
ID_INLINE bool idMat5::operator!=( const idMat5 &a ) const {
return !Compare( a );
}
ID_INLINE void idMat5::Zero( void ) {
memset( mat, 0, sizeof( idMat5 ) );
}
ID_INLINE void idMat5::Identity( void ) {
*this = mat5_identity;
}
ID_INLINE bool idMat5::IsIdentity( const float epsilon ) const {
return Compare( mat5_identity, epsilon );
}
ID_INLINE bool idMat5::IsSymmetric( const float epsilon ) const {
for ( int i = 1; i < 5; i++ ) {
for ( int j = 0; j < i; j++ ) {
if ( noMath::Fabs( mat[i][j] - mat[j][i] ) > epsilon ) {
return false;
}
}
}
return true;
}
ID_INLINE bool idMat5::IsDiagonal( const float epsilon ) const {
for ( int i = 0; i < 5; i++ ) {
for ( int j = 0; j < 5; j++ ) {
if ( i != j && noMath::Fabs( mat[i][j] ) > epsilon ) {
return false;
}
}
}
return true;
}
ID_INLINE float idMat5::Trace( void ) const {
return ( mat[0][0] + mat[1][1] + mat[2][2] + mat[3][3] + mat[4][4] );
}
ID_INLINE idMat5 idMat5::Inverse( void ) const {
idMat5 invMat;
invMat = *this;
int r = invMat.InverseSelf();
assert( r );
return invMat;
}
ID_INLINE idMat5 idMat5::InverseFast( void ) const {
idMat5 invMat;
invMat = *this;
int r = invMat.InverseFastSelf();
assert( r );
return invMat;
}
ID_INLINE int idMat5::GetDimension( void ) const {
return 25;
}
ID_INLINE const float *idMat5::ToFloatPtr( void ) const {
return mat[0].ToFloatPtr();
}
ID_INLINE float *idMat5::ToFloatPtr( void ) {
return mat[0].ToFloatPtr();
}
//===============================================================
//
// idMat6 - 6x6 matrix
//
//===============================================================
class idMat6 {
public:
idMat6( void );
explicit idMat6( const idVec6 &v0, const idVec6 &v1, const idVec6 &v2, const idVec6 &v3, const idVec6 &v4, const idVec6 &v5 );
explicit idMat6( const noMat3 &m0, const noMat3 &m1, const noMat3 &m2, const noMat3 &m3 );
explicit idMat6( const float src[ 6 ][ 6 ] );
const idVec6 & operator[]( int index ) const;
idVec6 & operator[]( int index );
idMat6 operator*( const float a ) const;
idVec6 operator*( const idVec6 &vec ) const;
idMat6 operator*( const idMat6 &a ) const;
idMat6 operator+( const idMat6 &a ) const;
idMat6 operator-( const idMat6 &a ) const;
idMat6 & operator*=( const float a );
idMat6 & operator*=( const idMat6 &a );
idMat6 & operator+=( const idMat6 &a );
idMat6 & operator-=( const idMat6 &a );
friend idMat6 operator*( const float a, const idMat6 &mat );
friend idVec6 operator*( const idVec6 &vec, const idMat6 &mat );
friend idVec6 & operator*=( idVec6 &vec, const idMat6 &mat );
bool Compare( const idMat6 &a ) const; // exact compare, no epsilon
bool Compare( const idMat6 &a, const float epsilon ) const; // compare with epsilon
bool operator==( const idMat6 &a ) const; // exact compare, no epsilon
bool operator!=( const idMat6 &a ) const; // exact compare, no epsilon
void Zero( void );
void Identity( void );
bool IsIdentity( const float epsilon = MATRIX_EPSILON ) const;
bool IsSymmetric( const float epsilon = MATRIX_EPSILON ) const;
bool IsDiagonal( const float epsilon = MATRIX_EPSILON ) const;
noMat3 SubMat3( int n ) const;
float Trace( void ) const;
float Determinant( void ) const;
idMat6 Transpose( void ) const; // returns transpose
idMat6 & TransposeSelf( void );
idMat6 Inverse( void ) const; // returns the inverse ( m * m.Inverse() = identity )
bool InverseSelf( void ); // returns false if determinant is zero
idMat6 InverseFast( void ) const; // returns the inverse ( m * m.Inverse() = identity )
bool InverseFastSelf( void ); // returns false if determinant is zero
int GetDimension( void ) const;
const float * ToFloatPtr( void ) const;
float * ToFloatPtr( void );
const char * ToString( int precision = 2 ) const;
private:
idVec6 mat[ 6 ];
};
extern idMat6 mat6_zero;
extern idMat6 mat6_identity;
#define mat6_default mat6_identity
ID_INLINE idMat6::idMat6( void ) {
}
ID_INLINE idMat6::idMat6( const noMat3 &m0, const noMat3 &m1, const noMat3 &m2, const noMat3 &m3 ) {
mat[0] = idVec6( m0[0][0], m0[0][1], m0[0][2], m1[0][0], m1[0][1], m1[0][2] );
mat[1] = idVec6( m0[1][0], m0[1][1], m0[1][2], m1[1][0], m1[1][1], m1[1][2] );
mat[2] = idVec6( m0[2][0], m0[2][1], m0[2][2], m1[2][0], m1[2][1], m1[2][2] );
mat[3] = idVec6( m2[0][0], m2[0][1], m2[0][2], m3[0][0], m3[0][1], m3[0][2] );
mat[4] = idVec6( m2[1][0], m2[1][1], m2[1][2], m3[1][0], m3[1][1], m3[1][2] );
mat[5] = idVec6( m2[2][0], m2[2][1], m2[2][2], m3[2][0], m3[2][1], m3[2][2] );
}
ID_INLINE idMat6::idMat6( const idVec6 &v0, const idVec6 &v1, const idVec6 &v2, const idVec6 &v3, const idVec6 &v4, const idVec6 &v5 ) {
mat[0] = v0;
mat[1] = v1;
mat[2] = v2;
mat[3] = v3;
mat[4] = v4;
mat[5] = v5;
}
ID_INLINE idMat6::idMat6( const float src[ 6 ][ 6 ] ) {
memcpy( mat, src, 6 * 6 * sizeof( float ) );
}
ID_INLINE const idVec6 &idMat6::operator[]( int index ) const {
//assert( ( index >= 0 ) && ( index < 6 ) );
return mat[ index ];
}
ID_INLINE idVec6 &idMat6::operator[]( int index ) {
//assert( ( index >= 0 ) && ( index < 6 ) );
return mat[ index ];
}
ID_INLINE idMat6 idMat6::operator*( const idMat6 &a ) const {
int i, j;
const float *m1Ptr, *m2Ptr;
float *dstPtr;
idMat6 dst;
m1Ptr = reinterpret_cast<const float *>(this);
m2Ptr = reinterpret_cast<const float *>(&a);
dstPtr = reinterpret_cast<float *>(&dst);
for ( i = 0; i < 6; i++ ) {
for ( j = 0; j < 6; j++ ) {
*dstPtr = m1Ptr[0] * m2Ptr[ 0 * 6 + j ]
+ m1Ptr[1] * m2Ptr[ 1 * 6 + j ]
+ m1Ptr[2] * m2Ptr[ 2 * 6 + j ]
+ m1Ptr[3] * m2Ptr[ 3 * 6 + j ]
+ m1Ptr[4] * m2Ptr[ 4 * 6 + j ]
+ m1Ptr[5] * m2Ptr[ 5 * 6 + j ];
dstPtr++;
}
m1Ptr += 6;
}
return dst;
}
ID_INLINE idMat6 idMat6::operator*( const float a ) const {
return idMat6(
idVec6( mat[0][0] * a, mat[0][1] * a, mat[0][2] * a, mat[0][3] * a, mat[0][4] * a, mat[0][5] * a ),
idVec6( mat[1][0] * a, mat[1][1] * a, mat[1][2] * a, mat[1][3] * a, mat[1][4] * a, mat[1][5] * a ),
idVec6( mat[2][0] * a, mat[2][1] * a, mat[2][2] * a, mat[2][3] * a, mat[2][4] * a, mat[2][5] * a ),
idVec6( mat[3][0] * a, mat[3][1] * a, mat[3][2] * a, mat[3][3] * a, mat[3][4] * a, mat[3][5] * a ),
idVec6( mat[4][0] * a, mat[4][1] * a, mat[4][2] * a, mat[4][3] * a, mat[4][4] * a, mat[4][5] * a ),
idVec6( mat[5][0] * a, mat[5][1] * a, mat[5][2] * a, mat[5][3] * a, mat[5][4] * a, mat[5][5] * a ) );
}
ID_INLINE idVec6 idMat6::operator*( const idVec6 &vec ) const {
return idVec6(
mat[0][0] * vec[0] + mat[0][1] * vec[1] + mat[0][2] * vec[2] + mat[0][3] * vec[3] + mat[0][4] * vec[4] + mat[0][5] * vec[5],
mat[1][0] * vec[0] + mat[1][1] * vec[1] + mat[1][2] * vec[2] + mat[1][3] * vec[3] + mat[1][4] * vec[4] + mat[1][5] * vec[5],
mat[2][0] * vec[0] + mat[2][1] * vec[1] + mat[2][2] * vec[2] + mat[2][3] * vec[3] + mat[2][4] * vec[4] + mat[2][5] * vec[5],
mat[3][0] * vec[0] + mat[3][1] * vec[1] + mat[3][2] * vec[2] + mat[3][3] * vec[3] + mat[3][4] * vec[4] + mat[3][5] * vec[5],
mat[4][0] * vec[0] + mat[4][1] * vec[1] + mat[4][2] * vec[2] + mat[4][3] * vec[3] + mat[4][4] * vec[4] + mat[4][5] * vec[5],
mat[5][0] * vec[0] + mat[5][1] * vec[1] + mat[5][2] * vec[2] + mat[5][3] * vec[3] + mat[5][4] * vec[4] + mat[5][5] * vec[5] );
}
ID_INLINE idMat6 idMat6::operator+( const idMat6 &a ) const {
return idMat6(
idVec6( mat[0][0] + a[0][0], mat[0][1] + a[0][1], mat[0][2] + a[0][2], mat[0][3] + a[0][3], mat[0][4] + a[0][4], mat[0][5] + a[0][5] ),
idVec6( mat[1][0] + a[1][0], mat[1][1] + a[1][1], mat[1][2] + a[1][2], mat[1][3] + a[1][3], mat[1][4] + a[1][4], mat[1][5] + a[1][5] ),
idVec6( mat[2][0] + a[2][0], mat[2][1] + a[2][1], mat[2][2] + a[2][2], mat[2][3] + a[2][3], mat[2][4] + a[2][4], mat[2][5] + a[2][5] ),
idVec6( mat[3][0] + a[3][0], mat[3][1] + a[3][1], mat[3][2] + a[3][2], mat[3][3] + a[3][3], mat[3][4] + a[3][4], mat[3][5] + a[3][5] ),
idVec6( mat[4][0] + a[4][0], mat[4][1] + a[4][1], mat[4][2] + a[4][2], mat[4][3] + a[4][3], mat[4][4] + a[4][4], mat[4][5] + a[4][5] ),
idVec6( mat[5][0] + a[5][0], mat[5][1] + a[5][1], mat[5][2] + a[5][2], mat[5][3] + a[5][3], mat[5][4] + a[5][4], mat[5][5] + a[5][5] ) );
}
ID_INLINE idMat6 idMat6::operator-( const idMat6 &a ) const {
return idMat6(
idVec6( mat[0][0] - a[0][0], mat[0][1] - a[0][1], mat[0][2] - a[0][2], mat[0][3] - a[0][3], mat[0][4] - a[0][4], mat[0][5] - a[0][5] ),
idVec6( mat[1][0] - a[1][0], mat[1][1] - a[1][1], mat[1][2] - a[1][2], mat[1][3] - a[1][3], mat[1][4] - a[1][4], mat[1][5] - a[1][5] ),
idVec6( mat[2][0] - a[2][0], mat[2][1] - a[2][1], mat[2][2] - a[2][2], mat[2][3] - a[2][3], mat[2][4] - a[2][4], mat[2][5] - a[2][5] ),
idVec6( mat[3][0] - a[3][0], mat[3][1] - a[3][1], mat[3][2] - a[3][2], mat[3][3] - a[3][3], mat[3][4] - a[3][4], mat[3][5] - a[3][5] ),
idVec6( mat[4][0] - a[4][0], mat[4][1] - a[4][1], mat[4][2] - a[4][2], mat[4][3] - a[4][3], mat[4][4] - a[4][4], mat[4][5] - a[4][5] ),
idVec6( mat[5][0] - a[5][0], mat[5][1] - a[5][1], mat[5][2] - a[5][2], mat[5][3] - a[5][3], mat[5][4] - a[5][4], mat[5][5] - a[5][5] ) );
}
ID_INLINE idMat6 &idMat6::operator*=( const float a ) {
mat[0][0] *= a; mat[0][1] *= a; mat[0][2] *= a; mat[0][3] *= a; mat[0][4] *= a; mat[0][5] *= a;
mat[1][0] *= a; mat[1][1] *= a; mat[1][2] *= a; mat[1][3] *= a; mat[1][4] *= a; mat[1][5] *= a;
mat[2][0] *= a; mat[2][1] *= a; mat[2][2] *= a; mat[2][3] *= a; mat[2][4] *= a; mat[2][5] *= a;
mat[3][0] *= a; mat[3][1] *= a; mat[3][2] *= a; mat[3][3] *= a; mat[3][4] *= a; mat[3][5] *= a;
mat[4][0] *= a; mat[4][1] *= a; mat[4][2] *= a; mat[4][3] *= a; mat[4][4] *= a; mat[4][5] *= a;
mat[5][0] *= a; mat[5][1] *= a; mat[5][2] *= a; mat[5][3] *= a; mat[5][4] *= a; mat[5][5] *= a;
return *this;
}
ID_INLINE idMat6 &idMat6::operator*=( const idMat6 &a ) {
*this = *this * a;
return *this;
}
ID_INLINE idMat6 &idMat6::operator+=( const idMat6 &a ) {
mat[0][0] += a[0][0]; mat[0][1] += a[0][1]; mat[0][2] += a[0][2]; mat[0][3] += a[0][3]; mat[0][4] += a[0][4]; mat[0][5] += a[0][5];
mat[1][0] += a[1][0]; mat[1][1] += a[1][1]; mat[1][2] += a[1][2]; mat[1][3] += a[1][3]; mat[1][4] += a[1][4]; mat[1][5] += a[1][5];
mat[2][0] += a[2][0]; mat[2][1] += a[2][1]; mat[2][2] += a[2][2]; mat[2][3] += a[2][3]; mat[2][4] += a[2][4]; mat[2][5] += a[2][5];
mat[3][0] += a[3][0]; mat[3][1] += a[3][1]; mat[3][2] += a[3][2]; mat[3][3] += a[3][3]; mat[3][4] += a[3][4]; mat[3][5] += a[3][5];
mat[4][0] += a[4][0]; mat[4][1] += a[4][1]; mat[4][2] += a[4][2]; mat[4][3] += a[4][3]; mat[4][4] += a[4][4]; mat[4][5] += a[4][5];
mat[5][0] += a[5][0]; mat[5][1] += a[5][1]; mat[5][2] += a[5][2]; mat[5][3] += a[5][3]; mat[5][4] += a[5][4]; mat[5][5] += a[5][5];
return *this;
}
ID_INLINE idMat6 &idMat6::operator-=( const idMat6 &a ) {
mat[0][0] -= a[0][0]; mat[0][1] -= a[0][1]; mat[0][2] -= a[0][2]; mat[0][3] -= a[0][3]; mat[0][4] -= a[0][4]; mat[0][5] -= a[0][5];
mat[1][0] -= a[1][0]; mat[1][1] -= a[1][1]; mat[1][2] -= a[1][2]; mat[1][3] -= a[1][3]; mat[1][4] -= a[1][4]; mat[1][5] -= a[1][5];
mat[2][0] -= a[2][0]; mat[2][1] -= a[2][1]; mat[2][2] -= a[2][2]; mat[2][3] -= a[2][3]; mat[2][4] -= a[2][4]; mat[2][5] -= a[2][5];
mat[3][0] -= a[3][0]; mat[3][1] -= a[3][1]; mat[3][2] -= a[3][2]; mat[3][3] -= a[3][3]; mat[3][4] -= a[3][4]; mat[3][5] -= a[3][5];
mat[4][0] -= a[4][0]; mat[4][1] -= a[4][1]; mat[4][2] -= a[4][2]; mat[4][3] -= a[4][3]; mat[4][4] -= a[4][4]; mat[4][5] -= a[4][5];
mat[5][0] -= a[5][0]; mat[5][1] -= a[5][1]; mat[5][2] -= a[5][2]; mat[5][3] -= a[5][3]; mat[5][4] -= a[5][4]; mat[5][5] -= a[5][5];
return *this;
}
ID_INLINE idVec6 operator*( const idVec6 &vec, const idMat6 &mat ) {
return mat * vec;
}
ID_INLINE idMat6 operator*( const float a, idMat6 const &mat ) {
return mat * a;
}
ID_INLINE idVec6 &operator*=( idVec6 &vec, const idMat6 &mat ) {
vec = mat * vec;
return vec;
}
ID_INLINE bool idMat6::Compare( const idMat6 &a ) const {
dword i;
const float *ptr1, *ptr2;
ptr1 = reinterpret_cast<const float *>(mat);
ptr2 = reinterpret_cast<const float *>(a.mat);
for ( i = 0; i < 6*6; i++ ) {
if ( ptr1[i] != ptr2[i] ) {
return false;
}
}
return true;
}
ID_INLINE bool idMat6::Compare( const idMat6 &a, const float epsilon ) const {
dword i;
const float *ptr1, *ptr2;
ptr1 = reinterpret_cast<const float *>(mat);
ptr2 = reinterpret_cast<const float *>(a.mat);
for ( i = 0; i < 6*6; i++ ) {
if ( noMath::Fabs( ptr1[i] - ptr2[i] ) > epsilon ) {
return false;
}
}
return true;
}
ID_INLINE bool idMat6::operator==( const idMat6 &a ) const {
return Compare( a );
}
ID_INLINE bool idMat6::operator!=( const idMat6 &a ) const {
return !Compare( a );
}
ID_INLINE void idMat6::Zero( void ) {
memset( mat, 0, sizeof( idMat6 ) );
}
ID_INLINE void idMat6::Identity( void ) {
*this = mat6_identity;
}
ID_INLINE bool idMat6::IsIdentity( const float epsilon ) const {
return Compare( mat6_identity, epsilon );
}
ID_INLINE bool idMat6::IsSymmetric( const float epsilon ) const {
for ( int i = 1; i < 6; i++ ) {
for ( int j = 0; j < i; j++ ) {
if ( noMath::Fabs( mat[i][j] - mat[j][i] ) > epsilon ) {
return false;
}
}
}
return true;
}
ID_INLINE bool idMat6::IsDiagonal( const float epsilon ) const {
for ( int i = 0; i < 6; i++ ) {
for ( int j = 0; j < 6; j++ ) {
if ( i != j && noMath::Fabs( mat[i][j] ) > epsilon ) {
return false;
}
}
}
return true;
}
ID_INLINE noMat3 idMat6::SubMat3( int n ) const {
assert( n >= 0 && n < 4 );
int b0 = ((n & 2) >> 1) * 3;
int b1 = (n & 1) * 3;
return noMat3(
mat[b0 + 0][b1 + 0], mat[b0 + 0][b1 + 1], mat[b0 + 0][b1 + 2],
mat[b0 + 1][b1 + 0], mat[b0 + 1][b1 + 1], mat[b0 + 1][b1 + 2],
mat[b0 + 2][b1 + 0], mat[b0 + 2][b1 + 1], mat[b0 + 2][b1 + 2] );
}
ID_INLINE float idMat6::Trace( void ) const {
return ( mat[0][0] + mat[1][1] + mat[2][2] + mat[3][3] + mat[4][4] + mat[5][5] );
}
ID_INLINE idMat6 idMat6::Inverse( void ) const {
idMat6 invMat;
invMat = *this;
int r = invMat.InverseSelf();
assert( r );
return invMat;
}
ID_INLINE idMat6 idMat6::InverseFast( void ) const {
idMat6 invMat;
invMat = *this;
int r = invMat.InverseFastSelf();
assert( r );
return invMat;
}
ID_INLINE int idMat6::GetDimension( void ) const {
return 36;
}
ID_INLINE const float *idMat6::ToFloatPtr( void ) const {
return mat[0].ToFloatPtr();
}
ID_INLINE float *idMat6::ToFloatPtr( void ) {
return mat[0].ToFloatPtr();
}
//===============================================================
//
// idMatX - arbitrary sized dense real matrix
//
// The matrix lives on 16 byte aligned and 16 byte padded memory.
//
// NOTE: due to the temporary memory pool idMatX cannot be used by multiple threads.
//
//===============================================================
#define MATX_MAX_TEMP 1024
#define MATX_QUAD( x ) ( ( ( ( x ) + 3 ) & ~3 ) * sizeof( float ) )
#define MATX_CLEAREND() int s = numRows * numColumns; while( s < ( ( s + 3 ) & ~3 ) ) { mat[s++] = 0.0f; }
#define MATX_ALLOCA( n ) ( (float *) _alloca16( MATX_QUAD( n ) ) )
#define MATX_SIMD
class idMatX {
public:
idMatX( void );
explicit idMatX( int rows, int columns );
explicit idMatX( int rows, int columns, float *src );
~idMatX( void );
void Set( int rows, int columns, const float *src );
void Set( const noMat3 &m1, const noMat3 &m2 );
void Set( const noMat3 &m1, const noMat3 &m2, const noMat3 &m3, const noMat3 &m4 );
const float * operator[]( int index ) const;
float * operator[]( int index );
idMatX & operator=( const idMatX &a );
idMatX operator*( const float a ) const;
idVecX operator*( const idVecX &vec ) const;
idMatX operator*( const idMatX &a ) const;
idMatX operator+( const idMatX &a ) const;
idMatX operator-( const idMatX &a ) const;
idMatX & operator*=( const float a );
idMatX & operator*=( const idMatX &a );
idMatX & operator+=( const idMatX &a );
idMatX & operator-=( const idMatX &a );
friend idMatX operator*( const float a, const idMatX &m );
friend idVecX operator*( const idVecX &vec, const idMatX &m );
friend idVecX & operator*=( idVecX &vec, const idMatX &m );
bool Compare( const idMatX &a ) const; // exact compare, no epsilon
bool Compare( const idMatX &a, const float epsilon ) const; // compare with epsilon
bool operator==( const idMatX &a ) const; // exact compare, no epsilon
bool operator!=( const idMatX &a ) const; // exact compare, no epsilon
void SetSize( int rows, int columns ); // set the number of rows/columns
void ChangeSize( int rows, int columns, bool makeZero = false ); // change the size keeping data intact where possible
int GetNumRows( void ) const { return numRows; } // get the number of rows
int GetNumColumns( void ) const { return numColumns; } // get the number of columns
void SetData( int rows, int columns, float *data ); // set float array pointer
void Zero( void ); // clear matrix
void Zero( int rows, int columns ); // set size and clear matrix
void Identity( void ); // clear to identity matrix
void Identity( int rows, int columns ); // set size and clear to identity matrix
void Diag( const idVecX &v ); // create diagonal matrix from vector
void Random( int seed, float l = 0.0f, float u = 1.0f ); // fill matrix with random values
void Random( int rows, int columns, int seed, float l = 0.0f, float u = 1.0f );
void Negate( void ); // (*this) = - (*this)
void Clamp( float min, float max ); // clamp all values
idMatX & SwapRows( int r1, int r2 ); // swap rows
idMatX & SwapColumns( int r1, int r2 ); // swap columns
idMatX & SwapRowsColumns( int r1, int r2 ); // swap rows and columns
idMatX & RemoveRow( int r ); // remove a row
idMatX & RemoveColumn( int r ); // remove a column
idMatX & RemoveRowColumn( int r ); // remove a row and column
void ClearUpperTriangle( void ); // clear the upper triangle
void ClearLowerTriangle( void ); // clear the lower triangle
void SquareSubMatrix( const idMatX &m, int size ); // get square sub-matrix from 0,0 to size,size
float MaxDifference( const idMatX &m ) const; // return maximum element difference between this and m
bool IsSquare( void ) const { return ( numRows == numColumns ); }
bool IsZero( const float epsilon = MATRIX_EPSILON ) const;
bool IsIdentity( const float epsilon = MATRIX_EPSILON ) const;
bool IsDiagonal( const float epsilon = MATRIX_EPSILON ) const;
bool IsTriDiagonal( const float epsilon = MATRIX_EPSILON ) const;
bool IsSymmetric( const float epsilon = MATRIX_EPSILON ) const;
bool IsOrthogonal( const float epsilon = MATRIX_EPSILON ) const;
bool IsOrthonormal( const float epsilon = MATRIX_EPSILON ) const;
bool IsPMatrix( const float epsilon = MATRIX_EPSILON ) const;
bool IsZMatrix( const float epsilon = MATRIX_EPSILON ) const;
bool IsPositiveDefinite( const float epsilon = MATRIX_EPSILON ) const;
bool IsSymmetricPositiveDefinite( const float epsilon = MATRIX_EPSILON ) const;
bool IsPositiveSemiDefinite( const float epsilon = MATRIX_EPSILON ) const;
bool IsSymmetricPositiveSemiDefinite( const float epsilon = MATRIX_EPSILON ) const;
float Trace( void ) const; // returns product of diagonal elements
float Determinant( void ) const; // returns determinant of matrix
idMatX Transpose( void ) const; // returns transpose
idMatX & TransposeSelf( void ); // transposes the matrix itself
idMatX Inverse( void ) const; // returns the inverse ( m * m.Inverse() = identity )
bool InverseSelf( void ); // returns false if determinant is zero
idMatX InverseFast( void ) const; // returns the inverse ( m * m.Inverse() = identity )
bool InverseFastSelf( void ); // returns false if determinant is zero
bool LowerTriangularInverse( void ); // in-place inversion, returns false if determinant is zero
bool UpperTriangularInverse( void ); // in-place inversion, returns false if determinant is zero
idVecX Multiply( const idVecX &vec ) const; // (*this) * vec
idVecX TransposeMultiply( const idVecX &vec ) const; // this->Transpose() * vec
idMatX Multiply( const idMatX &a ) const; // (*this) * a
idMatX TransposeMultiply( const idMatX &a ) const; // this->Transpose() * a
void Multiply( idVecX &dst, const idVecX &vec ) const; // dst = (*this) * vec
void MultiplyAdd( idVecX &dst, const idVecX &vec ) const; // dst += (*this) * vec
void MultiplySub( idVecX &dst, const idVecX &vec ) const; // dst -= (*this) * vec
void TransposeMultiply( idVecX &dst, const idVecX &vec ) const; // dst = this->Transpose() * vec
void TransposeMultiplyAdd( idVecX &dst, const idVecX &vec ) const; // dst += this->Transpose() * vec
void TransposeMultiplySub( idVecX &dst, const idVecX &vec ) const; // dst -= this->Transpose() * vec
void Multiply( idMatX &dst, const idMatX &a ) const; // dst = (*this) * a
void TransposeMultiply( idMatX &dst, const idMatX &a ) const; // dst = this->Transpose() * a
int GetDimension( void ) const; // returns total number of values in matrix
const idVec6 & SubVec6( int row ) const; // interpret beginning of row as a const idVec6
idVec6 & SubVec6( int row ); // interpret beginning of row as an idVec6
const idVecX SubVecX( int row ) const; // interpret complete row as a const idVecX
idVecX SubVecX( int row ); // interpret complete row as an idVecX
const float * ToFloatPtr( void ) const; // pointer to const matrix float array
float * ToFloatPtr( void ); // pointer to matrix float array
const char * ToString( int precision = 2 ) const;
void Update_RankOne( const idVecX &v, const idVecX &w, float alpha );
void Update_RankOneSymmetric( const idVecX &v, float alpha );
void Update_RowColumn( const idVecX &v, const idVecX &w, int r );
void Update_RowColumnSymmetric( const idVecX &v, int r );
void Update_Increment( const idVecX &v, const idVecX &w );
void Update_IncrementSymmetric( const idVecX &v );
void Update_Decrement( int r );
bool Inverse_GaussJordan( void ); // invert in-place with Gauss-Jordan elimination
bool Inverse_UpdateRankOne( const idVecX &v, const idVecX &w, float alpha );
bool Inverse_UpdateRowColumn( const idVecX &v, const idVecX &w, int r );
bool Inverse_UpdateIncrement( const idVecX &v, const idVecX &w );
bool Inverse_UpdateDecrement( const idVecX &v, const idVecX &w, int r );
void Inverse_Solve( idVecX &x, const idVecX &b ) const;
bool LU_Factor( int *index, float *det = NULL ); // factor in-place: L * U
bool LU_UpdateRankOne( const idVecX &v, const idVecX &w, float alpha, int *index );
bool LU_UpdateRowColumn( const idVecX &v, const idVecX &w, int r, int *index );
bool LU_UpdateIncrement( const idVecX &v, const idVecX &w, int *index );
bool LU_UpdateDecrement( const idVecX &v, const idVecX &w, const idVecX &u, int r, int *index );
void LU_Solve( idVecX &x, const idVecX &b, const int *index ) const;
void LU_Inverse( idMatX &inv, const int *index ) const;
void LU_UnpackFactors( idMatX &L, idMatX &U ) const;
void LU_MultiplyFactors( idMatX &m, const int *index ) const;
bool QR_Factor( idVecX &c, idVecX &d ); // factor in-place: Q * R
bool QR_UpdateRankOne( idMatX &R, const idVecX &v, const idVecX &w, float alpha );
bool QR_UpdateRowColumn( idMatX &R, const idVecX &v, const idVecX &w, int r );
bool QR_UpdateIncrement( idMatX &R, const idVecX &v, const idVecX &w );
bool QR_UpdateDecrement( idMatX &R, const idVecX &v, const idVecX &w, int r );
void QR_Solve( idVecX &x, const idVecX &b, const idVecX &c, const idVecX &d ) const;
void QR_Solve( idVecX &x, const idVecX &b, const idMatX &R ) const;
void QR_Inverse( idMatX &inv, const idVecX &c, const idVecX &d ) const;
void QR_UnpackFactors( idMatX &Q, idMatX &R, const idVecX &c, const idVecX &d ) const;
void QR_MultiplyFactors( idMatX &m, const idVecX &c, const idVecX &d ) const;
bool SVD_Factor( idVecX &w, idMatX &V ); // factor in-place: U * Diag(w) * V.Transpose()
void SVD_Solve( idVecX &x, const idVecX &b, const idVecX &w, const idMatX &V ) const;
void SVD_Inverse( idMatX &inv, const idVecX &w, const idMatX &V ) const;
void SVD_MultiplyFactors( idMatX &m, const idVecX &w, const idMatX &V ) const;
bool Cholesky_Factor( void ); // factor in-place: L * L.Transpose()
bool Cholesky_UpdateRankOne( const idVecX &v, float alpha, int offset = 0 );
bool Cholesky_UpdateRowColumn( const idVecX &v, int r );
bool Cholesky_UpdateIncrement( const idVecX &v );
bool Cholesky_UpdateDecrement( const idVecX &v, int r );
void Cholesky_Solve( idVecX &x, const idVecX &b ) const;
void Cholesky_Inverse( idMatX &inv ) const;
void Cholesky_MultiplyFactors( idMatX &m ) const;
bool LDLT_Factor( void ); // factor in-place: L * D * L.Transpose()
bool LDLT_UpdateRankOne( const idVecX &v, float alpha, int offset = 0 );
bool LDLT_UpdateRowColumn( const idVecX &v, int r );
bool LDLT_UpdateIncrement( const idVecX &v );
bool LDLT_UpdateDecrement( const idVecX &v, int r );
void LDLT_Solve( idVecX &x, const idVecX &b ) const;
void LDLT_Inverse( idMatX &inv ) const;
void LDLT_UnpackFactors( idMatX &L, idMatX &D ) const;
void LDLT_MultiplyFactors( idMatX &m ) const;
void TriDiagonal_ClearTriangles( void );
bool TriDiagonal_Solve( idVecX &x, const idVecX &b ) const;
void TriDiagonal_Inverse( idMatX &inv ) const;
bool Eigen_SolveSymmetricTriDiagonal( idVecX &eigenValues );
bool Eigen_SolveSymmetric( idVecX &eigenValues );
bool Eigen_Solve( idVecX &realEigenValues, idVecX &imaginaryEigenValues );
void Eigen_SortIncreasing( idVecX &eigenValues );
void Eigen_SortDecreasing( idVecX &eigenValues );
static void Test( void );
private:
int numRows; // number of rows
int numColumns; // number of columns
int alloced; // floats allocated, if -1 then mat points to data set with SetData
float * mat; // memory the matrix is stored
static float temp[MATX_MAX_TEMP+4]; // used to store intermediate results
static float * tempPtr; // pointer to 16 byte aligned temporary memory
static int tempIndex; // index into memory pool, wraps around
private:
void SetTempSize( int rows, int columns );
float DeterminantGeneric( void ) const;
bool InverseSelfGeneric( void );
void QR_Rotate( idMatX &R, int i, float a, float b );
float Pythag( float a, float b ) const;
void SVD_BiDiag( idVecX &w, idVecX &rv1, float &anorm );
void SVD_InitialWV( idVecX &w, idMatX &V, idVecX &rv1 );
void HouseholderReduction( idVecX &diag, idVecX &subd );
bool QL( idVecX &diag, idVecX &subd );
void HessenbergReduction( idMatX &H );
void ComplexDivision( float xr, float xi, float yr, float yi, float &cdivr, float &cdivi );
bool HessenbergToRealSchur( idMatX &H, idVecX &realEigenValues, idVecX &imaginaryEigenValues );
};
ID_INLINE idMatX::idMatX( void ) {
numRows = numColumns = alloced = 0;
mat = NULL;
}
ID_INLINE idMatX::~idMatX( void ) {
// if not temp memory
if ( mat != NULL && ( mat < idMatX::tempPtr || mat > idMatX::tempPtr + MATX_MAX_TEMP ) && alloced != -1 ) {
Mem_Free16( mat );
}
}
ID_INLINE idMatX::idMatX( int rows, int columns ) {
numRows = numColumns = alloced = 0;
mat = NULL;
SetSize( rows, columns );
}
ID_INLINE idMatX::idMatX( int rows, int columns, float *src ) {
numRows = numColumns = alloced = 0;
mat = NULL;
SetData( rows, columns, src );
}
ID_INLINE void idMatX::Set( int rows, int columns, const float *src ) {
SetSize( rows, columns );
memcpy( this->mat, src, rows * columns * sizeof( float ) );
}
ID_INLINE void idMatX::Set( const noMat3 &m1, const noMat3 &m2 ) {
int i, j;
SetSize( 3, 6 );
for ( i = 0; i < 3; i++ ) {
for ( j = 0; j < 3; j++ ) {
mat[(i+0) * numColumns + (j+0)] = m1[i][j];
mat[(i+0) * numColumns + (j+3)] = m2[i][j];
}
}
}
ID_INLINE void idMatX::Set( const noMat3 &m1, const noMat3 &m2, const noMat3 &m3, const noMat3 &m4 ) {
int i, j;
SetSize( 6, 6 );
for ( i = 0; i < 3; i++ ) {
for ( j = 0; j < 3; j++ ) {
mat[(i+0) * numColumns + (j+0)] = m1[i][j];
mat[(i+0) * numColumns + (j+3)] = m2[i][j];
mat[(i+3) * numColumns + (j+0)] = m3[i][j];
mat[(i+3) * numColumns + (j+3)] = m4[i][j];
}
}
}
ID_INLINE const float *idMatX::operator[]( int index ) const {
assert( ( index >= 0 ) && ( index < numRows ) );
return mat + index * numColumns;
}
ID_INLINE float *idMatX::operator[]( int index ) {
assert( ( index >= 0 ) && ( index < numRows ) );
return mat + index * numColumns;
}
ID_INLINE idMatX &idMatX::operator=( const idMatX &a ) {
SetSize( a.numRows, a.numColumns );
#ifdef MATX_SIMD
SIMDProcessor->Copy16( mat, a.mat, a.numRows * a.numColumns );
#else
memcpy( mat, a.mat, a.numRows * a.numColumns * sizeof( float ) );
#endif
idMatX::tempIndex = 0;
return *this;
}
ID_INLINE idMatX idMatX::operator*( const float a ) const {
idMatX m;
m.SetTempSize( numRows, numColumns );
#ifdef MATX_SIMD
SIMDProcessor->Mul16( m.mat, mat, a, numRows * numColumns );
#else
int i, s;
s = numRows * numColumns;
for ( i = 0; i < s; i++ ) {
m.mat[i] = mat[i] * a;
}
#endif
return m;
}
ID_INLINE idVecX idMatX::operator*( const idVecX &vec ) const {
idVecX dst;
assert( numColumns == vec.GetSize() );
dst.SetTempSize( numRows );
#ifdef MATX_SIMD
SIMDProcessor->MatX_MultiplyVecX( dst, *this, vec );
#else
Multiply( dst, vec );
#endif
return dst;
}
ID_INLINE idMatX idMatX::operator*( const idMatX &a ) const {
idMatX dst;
assert( numColumns == a.numRows );
dst.SetTempSize( numRows, a.numColumns );
#ifdef MATX_SIMD
SIMDProcessor->MatX_MultiplyMatX( dst, *this, a );
#else
Multiply( dst, a );
#endif
return dst;
}
ID_INLINE idMatX idMatX::operator+( const idMatX &a ) const {
idMatX m;
assert( numRows == a.numRows && numColumns == a.numColumns );
m.SetTempSize( numRows, numColumns );
#ifdef MATX_SIMD
SIMDProcessor->Add16( m.mat, mat, a.mat, numRows * numColumns );
#else
int i, s;
s = numRows * numColumns;
for ( i = 0; i < s; i++ ) {
m.mat[i] = mat[i] + a.mat[i];
}
#endif
return m;
}
ID_INLINE idMatX idMatX::operator-( const idMatX &a ) const {
idMatX m;
assert( numRows == a.numRows && numColumns == a.numColumns );
m.SetTempSize( numRows, numColumns );
#ifdef MATX_SIMD
SIMDProcessor->Sub16( m.mat, mat, a.mat, numRows * numColumns );
#else
int i, s;
s = numRows * numColumns;
for ( i = 0; i < s; i++ ) {
m.mat[i] = mat[i] - a.mat[i];
}
#endif
return m;
}
ID_INLINE idMatX &idMatX::operator*=( const float a ) {
#ifdef MATX_SIMD
SIMDProcessor->MulAssign16( mat, a, numRows * numColumns );
#else
int i, s;
s = numRows * numColumns;
for ( i = 0; i < s; i++ ) {
mat[i] *= a;
}
#endif
idMatX::tempIndex = 0;
return *this;
}
ID_INLINE idMatX &idMatX::operator*=( const idMatX &a ) {
*this = *this * a;
idMatX::tempIndex = 0;
return *this;
}
ID_INLINE idMatX &idMatX::operator+=( const idMatX &a ) {
assert( numRows == a.numRows && numColumns == a.numColumns );
#ifdef MATX_SIMD
SIMDProcessor->AddAssign16( mat, a.mat, numRows * numColumns );
#else
int i, s;
s = numRows * numColumns;
for ( i = 0; i < s; i++ ) {
mat[i] += a.mat[i];
}
#endif
idMatX::tempIndex = 0;
return *this;
}
ID_INLINE idMatX &idMatX::operator-=( const idMatX &a ) {
assert( numRows == a.numRows && numColumns == a.numColumns );
#ifdef MATX_SIMD
SIMDProcessor->SubAssign16( mat, a.mat, numRows * numColumns );
#else
int i, s;
s = numRows * numColumns;
for ( i = 0; i < s; i++ ) {
mat[i] -= a.mat[i];
}
#endif
idMatX::tempIndex = 0;
return *this;
}
ID_INLINE idMatX operator*( const float a, idMatX const &m ) {
return m * a;
}
ID_INLINE idVecX operator*( const idVecX &vec, const idMatX &m ) {
return m * vec;
}
ID_INLINE idVecX &operator*=( idVecX &vec, const idMatX &m ) {
vec = m * vec;
return vec;
}
ID_INLINE bool idMatX::Compare( const idMatX &a ) const {
int i, s;
assert( numRows == a.numRows && numColumns == a.numColumns );
s = numRows * numColumns;
for ( i = 0; i < s; i++ ) {
if ( mat[i] != a.mat[i] ) {
return false;
}
}
return true;
}
ID_INLINE bool idMatX::Compare( const idMatX &a, const float epsilon ) const {
int i, s;
assert( numRows == a.numRows && numColumns == a.numColumns );
s = numRows * numColumns;
for ( i = 0; i < s; i++ ) {
if ( noMath::Fabs( mat[i] - a.mat[i] ) > epsilon ) {
return false;
}
}
return true;
}
ID_INLINE bool idMatX::operator==( const idMatX &a ) const {
return Compare( a );
}
ID_INLINE bool idMatX::operator!=( const idMatX &a ) const {
return !Compare( a );
}
ID_INLINE void idMatX::SetSize( int rows, int columns ) {
assert( mat < idMatX::tempPtr || mat > idMatX::tempPtr + MATX_MAX_TEMP );
int alloc = ( rows * columns + 3 ) & ~3;
if ( alloc > alloced && alloced != -1 ) {
if ( mat != NULL ) {
Mem_Free16( mat );
}
mat = (float *) Mem_Alloc16( alloc * sizeof( float ) );
alloced = alloc;
}
numRows = rows;
numColumns = columns;
MATX_CLEAREND();
}
ID_INLINE void idMatX::SetTempSize( int rows, int columns ) {
int newSize;
newSize = ( rows * columns + 3 ) & ~3;
assert( newSize < MATX_MAX_TEMP );
if ( idMatX::tempIndex + newSize > MATX_MAX_TEMP ) {
idMatX::tempIndex = 0;
}
mat = idMatX::tempPtr + idMatX::tempIndex;
idMatX::tempIndex += newSize;
alloced = newSize;
numRows = rows;
numColumns = columns;
MATX_CLEAREND();
}
ID_INLINE void idMatX::SetData( int rows, int columns, float *data ) {
assert( mat < idMatX::tempPtr || mat > idMatX::tempPtr + MATX_MAX_TEMP );
if ( mat != NULL && alloced != -1 ) {
Mem_Free16( mat );
}
assert( ( ( (int) data ) & 15 ) == 0 ); // data must be 16 byte aligned
mat = data;
alloced = -1;
numRows = rows;
numColumns = columns;
MATX_CLEAREND();
}
ID_INLINE void idMatX::Zero( void ) {
#ifdef MATX_SIMD
SIMDProcessor->Zero16( mat, numRows * numColumns );
#else
memset( mat, 0, numRows * numColumns * sizeof( float ) );
#endif
}
ID_INLINE void idMatX::Zero( int rows, int columns ) {
SetSize( rows, columns );
#ifdef MATX_SIMD
SIMDProcessor->Zero16( mat, numRows * numColumns );
#else
memset( mat, 0, rows * columns * sizeof( float ) );
#endif
}
ID_INLINE void idMatX::Identity( void ) {
assert( numRows == numColumns );
#ifdef MATX_SIMD
SIMDProcessor->Zero16( mat, numRows * numColumns );
#else
memset( mat, 0, numRows * numColumns * sizeof( float ) );
#endif
for ( int i = 0; i < numRows; i++ ) {
mat[i * numColumns + i] = 1.0f;
}
}
ID_INLINE void idMatX::Identity( int rows, int columns ) {
assert( rows == columns );
SetSize( rows, columns );
idMatX::Identity();
}
ID_INLINE void idMatX::Diag( const idVecX &v ) {
Zero( v.GetSize(), v.GetSize() );
for ( int i = 0; i < v.GetSize(); i++ ) {
mat[i * numColumns + i] = v[i];
}
}
ID_INLINE void idMatX::Random( int seed, float l, float u ) {
int i, s;
float c;
idRandom rnd(seed);
c = u - l;
s = numRows * numColumns;
for ( i = 0; i < s; i++ ) {
mat[i] = l + rnd.RandomFloat() * c;
}
}
ID_INLINE void idMatX::Random( int rows, int columns, int seed, float l, float u ) {
int i, s;
float c;
idRandom rnd(seed);
SetSize( rows, columns );
c = u - l;
s = numRows * numColumns;
for ( i = 0; i < s; i++ ) {
mat[i] = l + rnd.RandomFloat() * c;
}
}
ID_INLINE void idMatX::Negate( void ) {
#ifdef MATX_SIMD
SIMDProcessor->Negate16( mat, numRows * numColumns );
#else
int i, s;
s = numRows * numColumns;
for ( i = 0; i < s; i++ ) {
mat[i] = -mat[i];
}
#endif
}
ID_INLINE void idMatX::Clamp( float min, float max ) {
int i, s;
s = numRows * numColumns;
for ( i = 0; i < s; i++ ) {
if ( mat[i] < min ) {
mat[i] = min;
} else if ( mat[i] > max ) {
mat[i] = max;
}
}
}
ID_INLINE idMatX &idMatX::SwapRows( int r1, int r2 ) {
float *ptr;
ptr = (float *) _alloca16( numColumns * sizeof( float ) );
memcpy( ptr, mat + r1 * numColumns, numColumns * sizeof( float ) );
memcpy( mat + r1 * numColumns, mat + r2 * numColumns, numColumns * sizeof( float ) );
memcpy( mat + r2 * numColumns, ptr, numColumns * sizeof( float ) );
return *this;
}
ID_INLINE idMatX &idMatX::SwapColumns( int r1, int r2 ) {
int i;
float tmp, *ptr;
for ( i = 0; i < numRows; i++ ) {
ptr = mat + i * numColumns;
tmp = ptr[r1];
ptr[r1] = ptr[r2];
ptr[r2] = tmp;
}
return *this;
}
ID_INLINE idMatX &idMatX::SwapRowsColumns( int r1, int r2 ) {
SwapRows( r1, r2 );
SwapColumns( r1, r2 );
return *this;
}
ID_INLINE void idMatX::ClearUpperTriangle( void ) {
assert( numRows == numColumns );
for ( int i = numRows-2; i >= 0; i-- ) {
memset( mat + i * numColumns + i + 1, 0, (numColumns - 1 - i) * sizeof(float) );
}
}
ID_INLINE void idMatX::ClearLowerTriangle( void ) {
assert( numRows == numColumns );
for ( int i = 1; i < numRows; i++ ) {
memset( mat + i * numColumns, 0, i * sizeof(float) );
}
}
ID_INLINE void idMatX::SquareSubMatrix( const idMatX &m, int size ) {
int i;
assert( size <= m.numRows && size <= m.numColumns );
SetSize( size, size );
for ( i = 0; i < size; i++ ) {
memcpy( mat + i * numColumns, m.mat + i * m.numColumns, size * sizeof( float ) );
}
}
ID_INLINE float idMatX::MaxDifference( const idMatX &m ) const {
int i, j;
float diff, maxDiff;
assert( numRows == m.numRows && numColumns == m.numColumns );
maxDiff = -1.0f;
for ( i = 0; i < numRows; i++ ) {
for ( j = 0; j < numColumns; j++ ) {
diff = noMath::Fabs( mat[ i * numColumns + j ] - m[i][j] );
if ( maxDiff < 0.0f || diff > maxDiff ) {
maxDiff = diff;
}
}
}
return maxDiff;
}
ID_INLINE bool idMatX::IsZero( const float epsilon ) const {
// returns true if (*this) == Zero
for ( int i = 0; i < numRows; i++ ) {
for ( int j = 0; j < numColumns; j++ ) {
if ( noMath::Fabs( mat[i * numColumns + j] ) > epsilon ) {
return false;
}
}
}
return true;
}
ID_INLINE bool idMatX::IsIdentity( const float epsilon ) const {
// returns true if (*this) == Identity
assert( numRows == numColumns );
for ( int i = 0; i < numRows; i++ ) {
for ( int j = 0; j < numColumns; j++ ) {
if ( noMath::Fabs( mat[i * numColumns + j] - (float)( i == j ) ) > epsilon ) {
return false;
}
}
}
return true;
}
ID_INLINE bool idMatX::IsDiagonal( const float epsilon ) const {
// returns true if all elements are zero except for the elements on the diagonal
assert( numRows == numColumns );
for ( int i = 0; i < numRows; i++ ) {
for ( int j = 0; j < numColumns; j++ ) {
if ( i != j && noMath::Fabs( mat[i * numColumns + j] ) > epsilon ) {
return false;
}
}
}
return true;
}
ID_INLINE bool idMatX::IsTriDiagonal( const float epsilon ) const {
// returns true if all elements are zero except for the elements on the diagonal plus or minus one column
if ( numRows != numColumns ) {
return false;
}
for ( int i = 0; i < numRows-2; i++ ) {
for ( int j = i+2; j < numColumns; j++ ) {
if ( noMath::Fabs( (*this)[i][j] ) > epsilon ) {
return false;
}
if ( noMath::Fabs( (*this)[j][i] ) > epsilon ) {
return false;
}
}
}
return true;
}
ID_INLINE bool idMatX::IsSymmetric( const float epsilon ) const {
// (*this)[i][j] == (*this)[j][i]
if ( numRows != numColumns ) {
return false;
}
for ( int i = 0; i < numRows; i++ ) {
for ( int j = 0; j < numColumns; j++ ) {
if ( noMath::Fabs( mat[ i * numColumns + j ] - mat[ j * numColumns + i ] ) > epsilon ) {
return false;
}
}
}
return true;
}
ID_INLINE float idMatX::Trace( void ) const {
float trace = 0.0f;
assert( numRows == numColumns );
// sum of elements on the diagonal
for ( int i = 0; i < numRows; i++ ) {
trace += mat[i * numRows + i];
}
return trace;
}
ID_INLINE float idMatX::Determinant( void ) const {
assert( numRows == numColumns );
switch( numRows ) {
case 1:
return mat[0];
case 2:
return reinterpret_cast<const noMat2 *>(mat)->Determinant();
case 3:
return reinterpret_cast<const noMat3 *>(mat)->Determinant();
case 4:
return reinterpret_cast<const noMat4 *>(mat)->Determinant();
case 5:
return reinterpret_cast<const idMat5 *>(mat)->Determinant();
case 6:
return reinterpret_cast<const idMat6 *>(mat)->Determinant();
default:
return DeterminantGeneric();
}
return 0.0f;
}
ID_INLINE idMatX idMatX::Transpose( void ) const {
idMatX transpose;
int i, j;
transpose.SetTempSize( numColumns, numRows );
for ( i = 0; i < numRows; i++ ) {
for ( j = 0; j < numColumns; j++ ) {
transpose.mat[j * transpose.numColumns + i] = mat[i * numColumns + j];
}
}
return transpose;
}
ID_INLINE idMatX &idMatX::TransposeSelf( void ) {
*this = Transpose();
return *this;
}
ID_INLINE idMatX idMatX::Inverse( void ) const {
idMatX invMat;
invMat.SetTempSize( numRows, numColumns );
memcpy( invMat.mat, mat, numRows * numColumns * sizeof( float ) );
int r = invMat.InverseSelf();
assert( r );
return invMat;
}
ID_INLINE bool idMatX::InverseSelf( void ) {
assert( numRows == numColumns );
switch( numRows ) {
case 1:
if ( noMath::Fabs( mat[0] ) < MATRIX_INVERSE_EPSILON ) {
return false;
}
mat[0] = 1.0f / mat[0];
return true;
case 2:
return reinterpret_cast<noMat2 *>(mat)->InverseSelf();
case 3:
return reinterpret_cast<noMat3 *>(mat)->InverseSelf();
case 4:
return reinterpret_cast<noMat4 *>(mat)->InverseSelf();
case 5:
return reinterpret_cast<idMat5 *>(mat)->InverseSelf();
case 6:
return reinterpret_cast<idMat6 *>(mat)->InverseSelf();
default:
return InverseSelfGeneric();
}
}
ID_INLINE idMatX idMatX::InverseFast( void ) const {
idMatX invMat;
invMat.SetTempSize( numRows, numColumns );
memcpy( invMat.mat, mat, numRows * numColumns * sizeof( float ) );
int r = invMat.InverseFastSelf();
assert( r );
return invMat;
}
ID_INLINE bool idMatX::InverseFastSelf( void ) {
assert( numRows == numColumns );
switch( numRows ) {
case 1:
if ( noMath::Fabs( mat[0] ) < MATRIX_INVERSE_EPSILON ) {
return false;
}
mat[0] = 1.0f / mat[0];
return true;
case 2:
return reinterpret_cast<noMat2 *>(mat)->InverseFastSelf();
case 3:
return reinterpret_cast<noMat3 *>(mat)->InverseFastSelf();
case 4:
return reinterpret_cast<noMat4 *>(mat)->InverseFastSelf();
case 5:
return reinterpret_cast<idMat5 *>(mat)->InverseFastSelf();
case 6:
return reinterpret_cast<idMat6 *>(mat)->InverseFastSelf();
default:
return InverseSelfGeneric();
}
return false;
}
ID_INLINE idVecX idMatX::Multiply( const idVecX &vec ) const {
idVecX dst;
assert( numColumns == vec.GetSize() );
dst.SetTempSize( numRows );
#ifdef MATX_SIMD
SIMDProcessor->MatX_MultiplyVecX( dst, *this, vec );
#else
Multiply( dst, vec );
#endif
return dst;
}
ID_INLINE idMatX idMatX::Multiply( const idMatX &a ) const {
idMatX dst;
assert( numColumns == a.numRows );
dst.SetTempSize( numRows, a.numColumns );
#ifdef MATX_SIMD
SIMDProcessor->MatX_MultiplyMatX( dst, *this, a );
#else
Multiply( dst, a );
#endif
return dst;
}
ID_INLINE idVecX idMatX::TransposeMultiply( const idVecX &vec ) const {
idVecX dst;
assert( numRows == vec.GetSize() );
dst.SetTempSize( numColumns );
#ifdef MATX_SIMD
SIMDProcessor->MatX_TransposeMultiplyVecX( dst, *this, vec );
#else
TransposeMultiply( dst, vec );
#endif
return dst;
}
ID_INLINE idMatX idMatX::TransposeMultiply( const idMatX &a ) const {
idMatX dst;
assert( numRows == a.numRows );
dst.SetTempSize( numColumns, a.numColumns );
#ifdef MATX_SIMD
SIMDProcessor->MatX_TransposeMultiplyMatX( dst, *this, a );
#else
TransposeMultiply( dst, a );
#endif
return dst;
}
ID_INLINE void idMatX::Multiply( idVecX &dst, const idVecX &vec ) const {
#ifdef MATX_SIMD
SIMDProcessor->MatX_MultiplyVecX( dst, *this, vec );
#else
int i, j;
const float *mPtr, *vPtr;
float *dstPtr;
mPtr = mat;
vPtr = vec.ToFloatPtr();
dstPtr = dst.ToFloatPtr();
for ( i = 0; i < numRows; i++ ) {
float sum = mPtr[0] * vPtr[0];
for ( j = 1; j < numColumns; j++ ) {
sum += mPtr[j] * vPtr[j];
}
dstPtr[i] = sum;
mPtr += numColumns;
}
#endif
}
ID_INLINE void idMatX::MultiplyAdd( idVecX &dst, const idVecX &vec ) const {
#ifdef MATX_SIMD
SIMDProcessor->MatX_MultiplyAddVecX( dst, *this, vec );
#else
int i, j;
const float *mPtr, *vPtr;
float *dstPtr;
mPtr = mat;
vPtr = vec.ToFloatPtr();
dstPtr = dst.ToFloatPtr();
for ( i = 0; i < numRows; i++ ) {
float sum = mPtr[0] * vPtr[0];
for ( j = 1; j < numColumns; j++ ) {
sum += mPtr[j] * vPtr[j];
}
dstPtr[i] += sum;
mPtr += numColumns;
}
#endif
}
ID_INLINE void idMatX::MultiplySub( idVecX &dst, const idVecX &vec ) const {
#ifdef MATX_SIMD
SIMDProcessor->MatX_MultiplySubVecX( dst, *this, vec );
#else
int i, j;
const float *mPtr, *vPtr;
float *dstPtr;
mPtr = mat;
vPtr = vec.ToFloatPtr();
dstPtr = dst.ToFloatPtr();
for ( i = 0; i < numRows; i++ ) {
float sum = mPtr[0] * vPtr[0];
for ( j = 1; j < numColumns; j++ ) {
sum += mPtr[j] * vPtr[j];
}
dstPtr[i] -= sum;
mPtr += numColumns;
}
#endif
}
ID_INLINE void idMatX::TransposeMultiply( idVecX &dst, const idVecX &vec ) const {
#ifdef MATX_SIMD
SIMDProcessor->MatX_TransposeMultiplyVecX( dst, *this, vec );
#else
int i, j;
const float *mPtr, *vPtr;
float *dstPtr;
vPtr = vec.ToFloatPtr();
dstPtr = dst.ToFloatPtr();
for ( i = 0; i < numColumns; i++ ) {
mPtr = mat + i;
float sum = mPtr[0] * vPtr[0];
for ( j = 1; j < numRows; j++ ) {
mPtr += numColumns;
sum += mPtr[0] * vPtr[j];
}
dstPtr[i] = sum;
}
#endif
}
ID_INLINE void idMatX::TransposeMultiplyAdd( idVecX &dst, const idVecX &vec ) const {
#ifdef MATX_SIMD
SIMDProcessor->MatX_TransposeMultiplyAddVecX( dst, *this, vec );
#else
int i, j;
const float *mPtr, *vPtr;
float *dstPtr;
vPtr = vec.ToFloatPtr();
dstPtr = dst.ToFloatPtr();
for ( i = 0; i < numColumns; i++ ) {
mPtr = mat + i;
float sum = mPtr[0] * vPtr[0];
for ( j = 1; j < numRows; j++ ) {
mPtr += numColumns;
sum += mPtr[0] * vPtr[j];
}
dstPtr[i] += sum;
}
#endif
}
ID_INLINE void idMatX::TransposeMultiplySub( idVecX &dst, const idVecX &vec ) const {
#ifdef MATX_SIMD
SIMDProcessor->MatX_TransposeMultiplySubVecX( dst, *this, vec );
#else
int i, j;
const float *mPtr, *vPtr;
float *dstPtr;
vPtr = vec.ToFloatPtr();
dstPtr = dst.ToFloatPtr();
for ( i = 0; i < numColumns; i++ ) {
mPtr = mat + i;
float sum = mPtr[0] * vPtr[0];
for ( j = 1; j < numRows; j++ ) {
mPtr += numColumns;
sum += mPtr[0] * vPtr[j];
}
dstPtr[i] -= sum;
}
#endif
}
ID_INLINE void idMatX::Multiply( idMatX &dst, const idMatX &a ) const {
#ifdef MATX_SIMD
SIMDProcessor->MatX_MultiplyMatX( dst, *this, a );
#else
int i, j, k, l, n;
float *dstPtr;
const float *m1Ptr, *m2Ptr;
double sum;
assert( numColumns == a.numRows );
dstPtr = dst.ToFloatPtr();
m1Ptr = ToFloatPtr();
m2Ptr = a.ToFloatPtr();
k = numRows;
l = a.GetNumColumns();
for ( i = 0; i < k; i++ ) {
for ( j = 0; j < l; j++ ) {
m2Ptr = a.ToFloatPtr() + j;
sum = m1Ptr[0] * m2Ptr[0];
for ( n = 1; n < numColumns; n++ ) {
m2Ptr += l;
sum += m1Ptr[n] * m2Ptr[0];
}
*dstPtr++ = sum;
}
m1Ptr += numColumns;
}
#endif
}
ID_INLINE void idMatX::TransposeMultiply( idMatX &dst, const idMatX &a ) const {
#ifdef MATX_SIMD
SIMDProcessor->MatX_TransposeMultiplyMatX( dst, *this, a );
#else
int i, j, k, l, n;
float *dstPtr;
const float *m1Ptr, *m2Ptr;
double sum;
assert( numRows == a.numRows );
dstPtr = dst.ToFloatPtr();
m1Ptr = ToFloatPtr();
k = numColumns;
l = a.numColumns;
for ( i = 0; i < k; i++ ) {
for ( j = 0; j < l; j++ ) {
m1Ptr = ToFloatPtr() + i;
m2Ptr = a.ToFloatPtr() + j;
sum = m1Ptr[0] * m2Ptr[0];
for ( n = 1; n < numRows; n++ ) {
m1Ptr += numColumns;
m2Ptr += a.numColumns;
sum += m1Ptr[0] * m2Ptr[0];
}
*dstPtr++ = sum;
}
}
#endif
}
ID_INLINE int idMatX::GetDimension( void ) const {
return numRows * numColumns;
}
ID_INLINE const idVec6 &idMatX::SubVec6( int row ) const {
assert( numColumns >= 6 && row >= 0 && row < numRows );
return *reinterpret_cast<const idVec6 *>(mat + row * numColumns);
}
ID_INLINE idVec6 &idMatX::SubVec6( int row ) {
assert( numColumns >= 6 && row >= 0 && row < numRows );
return *reinterpret_cast<idVec6 *>(mat + row * numColumns);
}
ID_INLINE const idVecX idMatX::SubVecX( int row ) const {
idVecX v;
assert( row >= 0 && row < numRows );
v.SetData( numColumns, mat + row * numColumns );
return v;
}
ID_INLINE idVecX idMatX::SubVecX( int row ) {
idVecX v;
assert( row >= 0 && row < numRows );
v.SetData( numColumns, mat + row * numColumns );
return v;
}
ID_INLINE const float *idMatX::ToFloatPtr( void ) const {
return mat;
}
ID_INLINE float *idMatX::ToFloatPtr( void ) {
return mat;
}
#endif
|
[
"Sangyong79@gmail.com"
] |
Sangyong79@gmail.com
|
dd0ab93c2a5c808c0602b8b7eac9f02b8ecae736
|
bacf9e0bbaf00b399ae05cadd4e6c8c3fc886fdb
|
/caldifspeedinsphere.cpp
|
6ffd80fac117b0047b52ac244b62bd8121ac3475
|
[] |
no_license
|
zfzlinux/CrawlerWithHIK
|
3283c0d82ade118e8deada13a7784b6b869bb008
|
cd12ed8b3b2e78baef81a057ba5c0d943c7901bd
|
refs/heads/master
| 2020-04-01T17:24:26.278865
| 2019-03-18T07:49:39
| 2019-03-18T07:49:39
| 153,427,703
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 9,824
|
cpp
|
#include "caldifspeedinsphere.h"
#include "ui_caldifspeedinsphere.h"
#include "crawlerserial.h"
#include "crawlerstatusparam.h"
CalDifSpeedInSphere::CalDifSpeedInSphere(QWidget *parent) :
QWidget(parent),
ui(new Ui::CalDifSpeedInSphere),
m_radiusOfSphere(1500.00),
m_crawlerWidth(300),
m_radian_CrawlerCenter(1)
{
ui->setupUi(this);
initUI();
}
CalDifSpeedInSphere::~CalDifSpeedInSphere()
{
delete ui;
}
double CalDifSpeedInSphere::getCrawlerBothSidesRatio_Sin(const RadiusSp &radius, const CrawlerWidth &width, const RadianCenter &radian)
{
this->setAllParam(radius,width,radian);
double minRadian = this->CalMinRadiusOfCrawlerWidth();
double maxRadian = this->CalMaxRadiusOfCrawlerWidth();
double ratio = sin(minRadian)/sin(maxRadian);
return ratio;
}
void CalDifSpeedInSphere::setAllParam(const RadiusSp &radius, const CrawlerWidth &width, const RadianCenter &radian)
{
this->setRadiusOfSphere(radius);
this->setCrawlerWidth(width);
this->setRadianOfCrawlerCenter(radian);
}
void CalDifSpeedInSphere::setRadiusOfSphere(const RadiusSp &radius)
{
if(radius.m_radius>MINRADIUSOFSPHERE)
this->m_radiusOfSphere = radius.m_radius;
}
double CalDifSpeedInSphere::getRadiusOfSphere()
{
return this->m_radiusOfSphere;
}
void CalDifSpeedInSphere::setCrawlerWidth(const CrawlerWidth &width)
{
if(width.m_width > 0)
this->m_crawlerWidth = width.m_width;
}
CrawlerWidth CalDifSpeedInSphere::getCrawlerWidth()
{
return CrawlerWidth(this->m_crawlerWidth);
}
void CalDifSpeedInSphere::setRadianOfCrawlerCenter(const RadianCenter &radian)
{
if(radian.m_radianCenter>MINRADIAN)
this->m_radian_CrawlerCenter = radian.m_radianCenter;
}
RadianCenter CalDifSpeedInSphere::getRadianOfCrawlerCenter()
{
return RadianCenter(this->m_radian_CrawlerCenter);
}
//将中心角度转换为环向周长。
double CalDifSpeedInSphere::radianCenterToPerimeter(double radian)
{
//球的半径
double radius =this->getRadiusOfSphere();
//根据中心角度,求出环向周长的半径。
double radiusOfPerimeter = radius * sin(radian);
double perimeter = 2 * D_PI * radiusOfPerimeter;
return perimeter;
}
//将环向周长转换为角度
double CalDifSpeedInSphere::perimeterToRadianCenter(double perimeter)
{
//球的半径
double radius = this->getRadiusOfSphere();
if(radius <=0) return 0.00;
//根据环向周长的半径,求出中心角度。
double radiusOfPerimeter = perimeter / (2*D_PI);
double radian = asin(radiusOfPerimeter/radius);
return radian;
}
double CalDifSpeedInSphere::CalMinRadiusOfCrawlerWidth()
{
return this->CalMinRadiusOfCrawlerWidth(RadiusSp(m_radiusOfSphere),CrawlerWidth(m_crawlerWidth),RadianCenter(m_radian_CrawlerCenter));
}
double CalDifSpeedInSphere::CalMinRadiusOfCrawlerWidth(const RadiusSp &radius, const CrawlerWidth &width, const RadianCenter &radian)
{
double minRadian = 0.0;
this->setAllParam(radius,width,radian);
double radianOfWidth = this->getRadianOfCrawlerWidth(radius,width);
minRadian = radian.m_radianCenter - radianOfWidth/2; // 车体中心在球体上的夹角弧度值 - 车体宽度弧度值的一半,//得到车体最小的弧度值。
if(minRadian < MINRADIAN)
return MINRADIAN;
else
return minRadian;
}
double CalDifSpeedInSphere::CalMaxRadiusOfCrawlerWidth()
{
return this->CalMaxRadiusOfCrawlerWidth(RadiusSp(m_radiusOfSphere),CrawlerWidth(m_crawlerWidth),RadianCenter(m_radian_CrawlerCenter));
}
double CalDifSpeedInSphere::CalMaxRadiusOfCrawlerWidth(const RadiusSp &radius, const CrawlerWidth &width, const RadianCenter &radian)
{
double maxRadian = 0.0;
this->setAllParam(radius,width,radian);
double radianOfWidth = this->getRadianOfCrawlerWidth(radius,width);
maxRadian = radian.m_radianCenter + radianOfWidth/2; // 车体中心在球体上的夹角弧度值 + 车体宽度弧度值的一半,//得到车体最大的弧度值。
if(maxRadian > MAXRADIAN)
return MAXRADIAN;
else
return maxRadian;
}
//double CalDifSpeedInSphere::getRatioOfRing(const RadiusSp &radius, const CrawlerWidth &width, const RadianCenter &radian)
//{
// double radianOfObjArc = this->getRadianOfArcLength(radius,width);
// double topPointRadian = radian - radianOfObjArc/2;
// double tailPointRadian = radian + radianOfObjArc/2;
// //the topPoint radius
// double topRadius = radius * sin(topPointRadian);
// double tailRadius = radius * sin(tailPointRadian);
// double ratioOfRing = topRadius/tailRadius;
// return ratioOfRing;
//}
double CalDifSpeedInSphere::getRadianOfCrawlerWidth(const RadiusSp &radius, const CrawlerWidth &width)
{
if(radius.m_radius>0)
return width.m_width/radius.m_radius;
else
return 0.00;
}
//转换
//角度与弧度转换
//#define D_PI 3.141592654
//#define ANGTORAD(a) ((a) * D_PI / 180.0)
//#define RADTOANG(a) ((a) * 180.0 / D_PI)
double CalDifSpeedInSphere::AngleToRadian(const double angle)
{
if((angle >= MINANGLE) && (angle <= MAXANGLE))
return (angle * D_PI/180.0);
else
return 0.0;
}
double CalDifSpeedInSphere::RadianToAngle(const double radian)
{
if((radian >=MINRADIAN) && (radian <=MAXRADIAN))
return (radian *180.0/D_PI);
else
return 0.0;
}
void CalDifSpeedInSphere::updatePWMValueByRatio(double Ratio)
{
//
quint16 m_leftValue,m_rightValue;
m_leftValue = m_PWMLeftByConfig;
m_rightValue = m_leftValue / Ratio;
// MinPWMValue = 300,
//MaxPWMValue = 2100,
if(m_rightValue >= MaxPWMValue)
{
m_rightValue = MaxPWMValue;
m_leftValue = m_rightValue * Ratio;
}
if(m_rightValue <= MinPWMValue)
{
m_rightValue = MinPWMValue;
m_leftValue = m_rightValue *Ratio;
}
//
ui->showChangedLeftPWM->setText(QString::number(m_leftValue));
ui->showChangedRightPWM->setText(QString::number(m_rightValue));
m_changedPWMLeft = m_leftValue;
m_changedPWMRight = m_rightValue;
}
void CalDifSpeedInSphere::slUpdatePWMValueByConfig(EnumPWMType PWMType, quint16 value)
{
switch (PWMType) {
case PWMLeftByConfig:
ui->showCurLeftPWM->setText(QString::number(value));
m_PWMLeftByConfig = value;
break;
case PWMRightByConfig:
ui->showCurRightPWM->setText(QString::number(value));
m_PWMRightByConfig =value;
break;
default:
break;
}
}
void CalDifSpeedInSphere::on_CenterAngle_editingFinished()
{
double radian = this->AngleToRadian(ui->CenterAngle->value());
this->setRadianOfCrawlerCenter(radian);
//求出环向周长
double perimeter = radianCenterToPerimeter(radian);
ui->perimeterSpinBox->setValue(perimeter);
}
void CalDifSpeedInSphere::on_crawlerWidth_editingFinished()
{
this->setCrawlerWidth(ui->crawlerWidth->value());
}
void CalDifSpeedInSphere::on_radiusOfSphere_editingFinished()
{
this->setRadiusOfSphere(RadiusSp(ui->radiusOfSphere->value()));
}
void CalDifSpeedInSphere::on_pushButton_clicked()
{
//
double radius = ui->radiusOfSphere->value();
double width = ui->crawlerWidth->value();
double radian = this->AngleToRadian(ui->CenterAngle->value());
double ratioValue = this->getCrawlerBothSidesRatio_Sin(RadiusSp(radius),CrawlerWidth(width),RadianCenter(radian));
ui->showRatioLabel->setText(QString::number(ratioValue,'f',2));
this->updatePWMValueByRatio(ratioValue);
}
void CalDifSpeedInSphere::on_pushButton_2_clicked()
{
double radius = ui->radiusOfSphere->value();
double width = ui->crawlerWidth->value();
double radian = this->AngleToRadian(ui->CenterAngle->value());
double ratioValue = this->getCrawlerBothSidesRatio_Sin(RadiusSp(radius),CrawlerWidth(width),RadianCenter(radian));
ui->showRatioLabel->setText(QString::number(1/ratioValue,'f',2));
this->updatePWMValueByRatio(1/ratioValue);
}
void CalDifSpeedInSphere::initUI()
{
CrawlerStatusParam *crawlerStatus = CrawlerStatusParam::getInstance();
connect(crawlerStatus,SIGNAL(sgUpdatePWMValueByConfig(EnumPWMType,quint16)),this,SLOT(slUpdatePWMValueByConfig(EnumPWMType,quint16)));
m_PWMLeftByConfig =crawlerStatus->getCurPWMValueByConfig(PWMLeftByConfig);
m_PWMRightByConfig = crawlerStatus->getCurPWMValueByConfig(PWMRightByConfig);
m_changedPWMLeft = m_PWMLeftByConfig;
m_changedPWMRight = m_PWMRightByConfig;
ui->showCurLeftPWM->setText(QString::number(m_PWMLeftByConfig));
ui->showCurRightPWM->setText(QString::number(m_PWMRightByConfig));
ui->showChangedLeftPWM->setText(QString::number(m_PWMLeftByConfig));
ui->showChangedRightPWM->setText(QString::number(m_PWMLeftByConfig));
}
void CalDifSpeedInSphere::on_changedPWMValueBtn_clicked()
{
CrawlerSerial *crawlerSerial = CrawlerSerial::getInstance();
crawlerSerial->setPWMValue(PWMLeftByConfig,m_changedPWMLeft);
crawlerSerial->setPWMValue(PWMRightByConfig,m_changedPWMRight);
}
void CalDifSpeedInSphere::on_clearChangedBtn_clicked()
{
CrawlerSerial *crawlerSerial = CrawlerSerial::getInstance();
crawlerSerial->setPWMValue(PWMLeftByConfig,m_PWMLeftByConfig);
crawlerSerial->setPWMValue(PWMRightByConfig,m_PWMLeftByConfig);
ui->showChangedLeftPWM->setText(QString::number(m_PWMLeftByConfig));
ui->showChangedRightPWM->setText(QString::number(m_PWMLeftByConfig));
m_changedPWMLeft = m_PWMLeftByConfig;
m_changedPWMRight = m_PWMLeftByConfig;
}
void CalDifSpeedInSphere::on_perimeterSpinBox_editingFinished()
{
double perimeter = ui->perimeterSpinBox->value();
double radian = this->perimeterToRadianCenter(perimeter);
double angle = this->RadianToAngle(radian);
ui->CenterAngle->setValue(angle);
}
|
[
"836430025@qq.com"
] |
836430025@qq.com
|
b67fe585199d40232b35a680a712de1f6c3666e7
|
895b3f891d4aab73f13f93091183477e7ba5c89f
|
/src/ewc_base/wnd/impl_wx/iwnd_checkbox.cpp
|
f9dbc7d9af33dde8f2af27d8a988af3345e8f954
|
[
"Apache-2.0"
] |
permissive
|
luoxz-ai/ew_base
|
6e63877d0dcd992171e43729c804cc72018d0f19
|
8186f63d3e9ddbc16e63c807fec9140f28bc27b6
|
refs/heads/master
| 2021-06-20T02:24:11.759172
| 2017-08-09T09:22:54
| 2017-08-09T09:22:54
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,233
|
cpp
|
#include "ewc_base/wnd/impl_wx/iwnd_checkbox.h"
EW_ENTER
IWnd_checkbox::IWnd_checkbox(wxWindow* p,const WndPropertyEx& h)
:wxCheckBox(p,h.id(),h.label(),h,h)
{
this->Connect(wxEVT_CHECKBOX,wxCommandEventHandler(IWnd_controlT<IWnd_checkbox>::OnCommandIntChanged));
}
template<>
class ValidatorW<IWnd_checkbox> : public Validator
{
public:
LitePtrT<IWnd_checkbox> pWindow;
wxWindow* GetWindow(){return pWindow;}
ValidatorW(IWnd_checkbox* w):pWindow(w)
{
pWindow->m_pVald.reset(this);
}
virtual bool DoSetValue(int32_t v)
{
pWindow->SetValue(v!=0);
return true;
}
virtual bool DoGetValue(int32_t& v)
{
v=pWindow->GetValue()?1:0;
return true;
}
};
template<>
class WndInfoT<IWnd_checkbox> : public WndInfoBaseT<IWnd_checkbox>
{
public:
WndInfoT(const String& s):WndInfoBaseT<IWnd_checkbox>(s)
{
}
virtual Validator* CreateValidator(wxWindow* w,EvtProxyT<int32_t>* p)
{
return CreateValidatorBaseT(w,p);
}
Validator* CreateValidator(wxWindow* w)
{
return new ValidatorW<IWnd_checkbox>((IWnd_checkbox*)w);
}
};
template<>
void WndInfoManger_Register<IWnd_checkbox>(WndInfoManger& imgr,const String& name)
{
static WndInfoT<IWnd_checkbox> info(name);
imgr.Register(&info);
}
EW_LEAVE
|
[
"hanwd@eastfdtd.com"
] |
hanwd@eastfdtd.com
|
7e89e54ca5656841a62f0bf5a3c25906397c560e
|
99857bc88436220187db7a948c67b6c8a18f9946
|
/stl/iterator_tag_with_traits.cpp
|
a36a16bdbb0be5ef609e64cd3b120d1b578ae736
|
[
"MIT"
] |
permissive
|
frankbearzou/c-cpp-demo
|
162fb8bef0399a67da6b03f566e4191dd65328c7
|
523b49b1b279d99d495414cf8e620c907beb2788
|
refs/heads/master
| 2021-05-30T04:47:57.743807
| 2015-12-13T01:29:14
| 2015-12-13T01:29:14
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 835
|
cpp
|
#include <iostream>
#include <iterator>
using namespace std;
struct rand_tag
{
};
struct bi_tag
{
};
struct bi_iter : public iterator<bi_tag, float>
{
};
struct rand_iter : public iterator<rand_tag, int>
{
};
template<class _Ty, class Dis>
void adv(_Ty iter, Dis n, rand_tag)
{
cout << "rand adv" << endl;
}
template<class _Ty, class Dis>
void adv(_Ty iter, Dis n, bi_tag)
{
cout << "bi adv" << endl;
}
template<class _Ty>
typename iterator_traits<_Ty>::iterator_category
iter_cast(const _Ty&)
{
typename iterator_traits<_Ty>::iterator_category cat;
return (cat);
}
template<class _Ty, class Dis>
void adv(_Ty& iter, Dis n)
{
// adv(iter, n, typename iterator_traits<_Ty>::iterator_category());
adv(iter, n, iter_cast(iter));
}
void main()
{
rand_iter i;
adv(i, 3);
bi_iter f;
adv(f, 4);
system("pause");
}
|
[
"frankbearzou@gmail.com"
] |
frankbearzou@gmail.com
|
e4a82641755c4cd9e5bcfb953811fc9c51efa231
|
be662d258a2ba20b7b94943c1cfd2ebc1fda0bd4
|
/VulkanSupport/Vendor/tinyobjloader/tiny_obj_loader.h
|
fdbdfb9d3dcb35137f644dd5c2b9924983742028
|
[
"Apache-2.0"
] |
permissive
|
xRiveria/Crescent
|
c4d6e5f3143e4ca4c97831a207c696d8ae8c7183
|
b6512b6a8dab2d27cf542c562ccc28f21bf2345d
|
refs/heads/master
| 2023-08-17T20:30:28.444093
| 2021-09-26T11:42:01
| 2021-09-26T11:42:01
| 320,224,982
| 5
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 119,464
|
h
|
#pragma once
/*
The MIT License (MIT)
Copyright (c) 2012-Present, Syoyo Fujita and many contributors.
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.
*/
//
// version 2.0.0 : Add new object oriented API. 1.x API is still provided.
// * Support line primitive.
// * Support points primitive.
// * Support multiple search path for .mtl(v1 API).
// * Support vertex weight `vw`(as an tinyobj extension)
// * Support escaped whitespece in mtllib
// version 1.4.0 : Modifed ParseTextureNameAndOption API
// version 1.3.1 : Make ParseTextureNameAndOption API public
// version 1.3.0 : Separate warning and error message(breaking API of LoadObj)
// version 1.2.3 : Added color space extension('-colorspace') to tex opts.
// version 1.2.2 : Parse multiple group names.
// version 1.2.1 : Added initial support for line('l') primitive(PR #178)
// version 1.2.0 : Hardened implementation(#175)
// version 1.1.1 : Support smoothing groups(#162)
// version 1.1.0 : Support parsing vertex color(#144)
// version 1.0.8 : Fix parsing `g` tag just after `usemtl`(#138)
// version 1.0.7 : Support multiple tex options(#126)
// version 1.0.6 : Add TINYOBJLOADER_USE_DOUBLE option(#124)
// version 1.0.5 : Ignore `Tr` when `d` exists in MTL(#43)
// version 1.0.4 : Support multiple filenames for 'mtllib'(#112)
// version 1.0.3 : Support parsing texture options(#85)
// version 1.0.2 : Improve parsing speed by about a factor of 2 for large
// files(#105)
// version 1.0.1 : Fixes a shape is lost if obj ends with a 'usemtl'(#104)
// version 1.0.0 : Change data structure. Change license from BSD to MIT.
//
//
// Use this in *one* .cc
// #define TINYOBJLOADER_IMPLEMENTATION
// #include "tiny_obj_loader.h"
//
#ifndef TINY_OBJ_LOADER_H_
#define TINY_OBJ_LOADER_H_
#include <map>
#include <string>
#include <vector>
namespace tinyobj {
// TODO(syoyo): Better C++11 detection for older compiler
#if __cplusplus > 199711L
#define TINYOBJ_OVERRIDE override
#else
#define TINYOBJ_OVERRIDE
#endif
#ifdef __clang__
#pragma clang diagnostic push
#if __has_warning("-Wzero-as-null-pointer-constant")
#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant"
#endif
#pragma clang diagnostic ignored "-Wpadded"
#endif
// https://en.wikipedia.org/wiki/Wavefront_.obj_file says ...
//
// -blendu on | off # set horizontal texture blending
// (default on)
// -blendv on | off # set vertical texture blending
// (default on)
// -boost real_value # boost mip-map sharpness
// -mm base_value gain_value # modify texture map values (default
// 0 1)
// # base_value = brightness,
// gain_value = contrast
// -o u [v [w]] # Origin offset (default
// 0 0 0)
// -s u [v [w]] # Scale (default
// 1 1 1)
// -t u [v [w]] # Turbulence (default
// 0 0 0)
// -texres resolution # texture resolution to create
// -clamp on | off # only render texels in the clamped
// 0-1 range (default off)
// # When unclamped, textures are
// repeated across a surface,
// # when clamped, only texels which
// fall within the 0-1
// # range are rendered.
// -bm mult_value # bump multiplier (for bump maps
// only)
//
// -imfchan r | g | b | m | l | z # specifies which channel of the file
// is used to
// # create a scalar or bump texture.
// r:red, g:green,
// # b:blue, m:matte, l:luminance,
// z:z-depth..
// # (the default for bump is 'l' and
// for decal is 'm')
// bump -imfchan r bumpmap.tga # says to use the red channel of
// bumpmap.tga as the bumpmap
//
// For reflection maps...
//
// -type sphere # specifies a sphere for a "refl"
// reflection map
// -type cube_top | cube_bottom | # when using a cube map, the texture
// file for each
// cube_front | cube_back | # side of the cube is specified
// separately
// cube_left | cube_right
//
// TinyObjLoader extension.
//
// -colorspace SPACE # Color space of the texture. e.g.
// 'sRGB` or 'linear'
//
#ifdef TINYOBJLOADER_USE_DOUBLE
//#pragma message "using double"
typedef double real_t;
#else
//#pragma message "using float"
typedef float real_t;
#endif
typedef enum {
TEXTURE_TYPE_NONE, // default
TEXTURE_TYPE_SPHERE,
TEXTURE_TYPE_CUBE_TOP,
TEXTURE_TYPE_CUBE_BOTTOM,
TEXTURE_TYPE_CUBE_FRONT,
TEXTURE_TYPE_CUBE_BACK,
TEXTURE_TYPE_CUBE_LEFT,
TEXTURE_TYPE_CUBE_RIGHT
} texture_type_t;
struct texture_option_t {
texture_type_t type; // -type (default TEXTURE_TYPE_NONE)
real_t sharpness; // -boost (default 1.0?)
real_t brightness; // base_value in -mm option (default 0)
real_t contrast; // gain_value in -mm option (default 1)
real_t origin_offset[3]; // -o u [v [w]] (default 0 0 0)
real_t scale[3]; // -s u [v [w]] (default 1 1 1)
real_t turbulence[3]; // -t u [v [w]] (default 0 0 0)
int texture_resolution; // -texres resolution (No default value in the spec.
// We'll use -1)
bool clamp; // -clamp (default false)
char imfchan; // -imfchan (the default for bump is 'l' and for decal is 'm')
bool blendu; // -blendu (default on)
bool blendv; // -blendv (default on)
real_t bump_multiplier; // -bm (for bump maps only, default 1.0)
// extension
std::string colorspace; // Explicitly specify color space of stored texel
// value. Usually `sRGB` or `linear` (default empty).
};
struct material_t {
std::string name;
real_t ambient[3];
real_t diffuse[3];
real_t specular[3];
real_t transmittance[3];
real_t emission[3];
real_t shininess;
real_t ior; // index of refraction
real_t dissolve; // 1 == opaque; 0 == fully transparent
// illumination model (see http://www.fileformat.info/format/material/)
int illum;
int dummy; // Suppress padding warning.
std::string ambient_texname; // map_Ka
std::string diffuse_texname; // map_Kd
std::string specular_texname; // map_Ks
std::string specular_highlight_texname; // map_Ns
std::string bump_texname; // map_bump, map_Bump, bump
std::string displacement_texname; // disp
std::string alpha_texname; // map_d
std::string reflection_texname; // refl
texture_option_t ambient_texopt;
texture_option_t diffuse_texopt;
texture_option_t specular_texopt;
texture_option_t specular_highlight_texopt;
texture_option_t bump_texopt;
texture_option_t displacement_texopt;
texture_option_t alpha_texopt;
texture_option_t reflection_texopt;
// PBR extension
// http://exocortex.com/blog/extending_wavefront_mtl_to_support_pbr
real_t roughness; // [0, 1] default 0
real_t metallic; // [0, 1] default 0
real_t sheen; // [0, 1] default 0
real_t clearcoat_thickness; // [0, 1] default 0
real_t clearcoat_roughness; // [0, 1] default 0
real_t anisotropy; // aniso. [0, 1] default 0
real_t anisotropy_rotation; // anisor. [0, 1] default 0
real_t pad0;
std::string roughness_texname; // map_Pr
std::string metallic_texname; // map_Pm
std::string sheen_texname; // map_Ps
std::string emissive_texname; // map_Ke
std::string normal_texname; // norm. For normal mapping.
texture_option_t roughness_texopt;
texture_option_t metallic_texopt;
texture_option_t sheen_texopt;
texture_option_t emissive_texopt;
texture_option_t normal_texopt;
int pad2;
std::map<std::string, std::string> unknown_parameter;
#ifdef TINY_OBJ_LOADER_PYTHON_BINDING
// For pybind11
std::array<double, 3> GetDiffuse() {
std::array<double, 3> values;
values[0] = double(diffuse[0]);
values[1] = double(diffuse[1]);
values[2] = double(diffuse[2]);
return values;
}
std::array<double, 3> GetSpecular() {
std::array<double, 3> values;
values[0] = double(specular[0]);
values[1] = double(specular[1]);
values[2] = double(specular[2]);
return values;
}
std::array<double, 3> GetTransmittance() {
std::array<double, 3> values;
values[0] = double(transmittance[0]);
values[1] = double(transmittance[1]);
values[2] = double(transmittance[2]);
return values;
}
std::array<double, 3> GetEmission() {
std::array<double, 3> values;
values[0] = double(emission[0]);
values[1] = double(emission[1]);
values[2] = double(emission[2]);
return values;
}
std::array<double, 3> GetAmbient() {
std::array<double, 3> values;
values[0] = double(ambient[0]);
values[1] = double(ambient[1]);
values[2] = double(ambient[2]);
return values;
}
void SetDiffuse(std::array<double, 3>& a) {
diffuse[0] = real_t(a[0]);
diffuse[1] = real_t(a[1]);
diffuse[2] = real_t(a[2]);
}
void SetAmbient(std::array<double, 3>& a) {
ambient[0] = real_t(a[0]);
ambient[1] = real_t(a[1]);
ambient[2] = real_t(a[2]);
}
void SetSpecular(std::array<double, 3>& a) {
specular[0] = real_t(a[0]);
specular[1] = real_t(a[1]);
specular[2] = real_t(a[2]);
}
void SetTransmittance(std::array<double, 3>& a) {
transmittance[0] = real_t(a[0]);
transmittance[1] = real_t(a[1]);
transmittance[2] = real_t(a[2]);
}
std::string GetCustomParameter(const std::string& key) {
std::map<std::string, std::string>::const_iterator it =
unknown_parameter.find(key);
if (it != unknown_parameter.end()) {
return it->second;
}
return std::string();
}
#endif
};
struct tag_t {
std::string name;
std::vector<int> intValues;
std::vector<real_t> floatValues;
std::vector<std::string> stringValues;
};
struct joint_and_weight_t {
int joint_id;
real_t weight;
};
struct skin_weight_t {
int vertex_id; // Corresponding vertex index in `attrib_t::vertices`.
// Compared to `index_t`, this index must be positive and
// start with 0(does not allow relative indexing)
std::vector<joint_and_weight_t> weightValues;
};
// Index struct to support different indices for vtx/normal/texcoord.
// -1 means not used.
struct index_t {
int vertex_index;
int normal_index;
int texcoord_index;
};
struct mesh_t {
std::vector<index_t> indices;
std::vector<unsigned char>
num_face_vertices; // The number of vertices per
// face. 3 = triangle, 4 = quad,
// ... Up to 255 vertices per face.
std::vector<int> material_ids; // per-face material ID
std::vector<unsigned int> smoothing_group_ids; // per-face smoothing group
// ID(0 = off. positive value
// = group id)
std::vector<tag_t> tags; // SubD tag
};
// struct path_t {
// std::vector<int> indices; // pairs of indices for lines
//};
struct lines_t {
// Linear flattened indices.
std::vector<index_t> indices; // indices for vertices(poly lines)
std::vector<int> num_line_vertices; // The number of vertices per line.
};
struct points_t {
std::vector<index_t> indices; // indices for points
};
struct shape_t {
std::string name;
mesh_t mesh;
lines_t lines;
points_t points;
};
// Vertex attributes
struct attrib_t {
std::vector<real_t> vertices; // 'v'(xyz)
// For backward compatibility, we store vertex weight in separate array.
std::vector<real_t> vertex_weights; // 'v'(w)
std::vector<real_t> normals; // 'vn'
std::vector<real_t> texcoords; // 'vt'(uv)
// For backward compatibility, we store texture coordinate 'w' in separate
// array.
std::vector<real_t> texcoord_ws; // 'vt'(w)
std::vector<real_t> colors; // extension: vertex colors
//
// TinyObj extension.
//
// NOTE(syoyo): array index is based on the appearance order.
// To get a corresponding skin weight for a specific vertex id `vid`,
// Need to reconstruct a look up table: `skin_weight_t::vertex_id` == `vid`
// (e.g. using std::map, std::unordered_map)
std::vector<skin_weight_t> skin_weights;
attrib_t() {}
//
// For pybind11
//
const std::vector<real_t>& GetVertices() const { return vertices; }
const std::vector<real_t>& GetVertexWeights() const { return vertex_weights; }
};
struct callback_t {
// W is optional and set to 1 if there is no `w` item in `v` line
void (*vertex_cb)(void* user_data, real_t x, real_t y, real_t z, real_t w);
void (*normal_cb)(void* user_data, real_t x, real_t y, real_t z);
// y and z are optional and set to 0 if there is no `y` and/or `z` item(s) in
// `vt` line.
void (*texcoord_cb)(void* user_data, real_t x, real_t y, real_t z);
// called per 'f' line. num_indices is the number of face indices(e.g. 3 for
// triangle, 4 for quad)
// 0 will be passed for undefined index in index_t members.
void (*index_cb)(void* user_data, index_t* indices, int num_indices);
// `name` material name, `material_id` = the array index of material_t[]. -1
// if
// a material not found in .mtl
void (*usemtl_cb)(void* user_data, const char* name, int material_id);
// `materials` = parsed material data.
void (*mtllib_cb)(void* user_data, const material_t* materials,
int num_materials);
// There may be multiple group names
void (*group_cb)(void* user_data, const char** names, int num_names);
void (*object_cb)(void* user_data, const char* name);
callback_t()
: vertex_cb(NULL),
normal_cb(NULL),
texcoord_cb(NULL),
index_cb(NULL),
usemtl_cb(NULL),
mtllib_cb(NULL),
group_cb(NULL),
object_cb(NULL) {}
};
class MaterialReader {
public:
MaterialReader() {}
virtual ~MaterialReader();
virtual bool operator()(const std::string& matId,
std::vector<material_t>* materials,
std::map<std::string, int>* matMap, std::string* warn,
std::string* err) = 0;
};
///
/// Read .mtl from a file.
///
class MaterialFileReader : public MaterialReader {
public:
// Path could contain separator(';' in Windows, ':' in Posix)
explicit MaterialFileReader(const std::string& mtl_basedir)
: m_mtlBaseDir(mtl_basedir) {}
virtual ~MaterialFileReader() TINYOBJ_OVERRIDE {}
virtual bool operator()(const std::string& matId,
std::vector<material_t>* materials,
std::map<std::string, int>* matMap, std::string* warn,
std::string* err) TINYOBJ_OVERRIDE;
private:
std::string m_mtlBaseDir;
};
///
/// Read .mtl from a stream.
///
class MaterialStreamReader : public MaterialReader {
public:
explicit MaterialStreamReader(std::istream& inStream)
: m_inStream(inStream) {}
virtual ~MaterialStreamReader() TINYOBJ_OVERRIDE {}
virtual bool operator()(const std::string& matId,
std::vector<material_t>* materials,
std::map<std::string, int>* matMap, std::string* warn,
std::string* err) TINYOBJ_OVERRIDE;
private:
std::istream& m_inStream;
};
// v2 API
struct ObjReaderConfig {
bool triangulate; // triangulate polygon?
/// Parse vertex color.
/// If vertex color is not present, its filled with default value.
/// false = no vertex color
/// This will increase memory of parsed .obj
bool vertex_color;
///
/// Search path to .mtl file.
/// Default = "" = search from the same directory of .obj file.
/// Valid only when loading .obj from a file.
///
std::string mtl_search_path;
ObjReaderConfig() : triangulate(true), vertex_color(true) {}
};
///
/// Wavefront .obj reader class(v2 API)
///
class ObjReader {
public:
ObjReader() : valid_(false) {}
~ObjReader() {}
///
/// Load .obj and .mtl from a file.
///
/// @param[in] filename wavefront .obj filename
/// @param[in] config Reader configuration
///
bool ParseFromFile(const std::string& filename,
const ObjReaderConfig& config = ObjReaderConfig());
///
/// Parse .obj from a text string.
/// Need to supply .mtl text string by `mtl_text`.
/// This function ignores `mtllib` line in .obj text.
///
/// @param[in] obj_text wavefront .obj filename
/// @param[in] mtl_text wavefront .mtl filename
/// @param[in] config Reader configuration
///
bool ParseFromString(const std::string& obj_text, const std::string& mtl_text,
const ObjReaderConfig& config = ObjReaderConfig());
///
/// .obj was loaded or parsed correctly.
///
bool Valid() const { return valid_; }
const attrib_t& GetAttrib() const { return attrib_; }
const std::vector<shape_t>& GetShapes() const { return shapes_; }
const std::vector<material_t>& GetMaterials() const { return materials_; }
///
/// Warning message(may be filled after `Load` or `Parse`)
///
const std::string& Warning() const { return warning_; }
///
/// Error message(filled when `Load` or `Parse` failed)
///
const std::string& Error() const { return error_; }
private:
bool valid_;
attrib_t attrib_;
std::vector<shape_t> shapes_;
std::vector<material_t> materials_;
std::string warning_;
std::string error_;
};
/// ==>>========= Legacy v1 API =============================================
/// Loads .obj from a file.
/// 'attrib', 'shapes' and 'materials' will be filled with parsed shape data
/// 'shapes' will be filled with parsed shape data
/// Returns true when loading .obj become success.
/// Returns warning message into `warn`, and error message into `err`
/// 'mtl_basedir' is optional, and used for base directory for .mtl file.
/// In default(`NULL'), .mtl file is searched from an application's working
/// directory.
/// 'triangulate' is optional, and used whether triangulate polygon face in .obj
/// or not.
/// Option 'default_vcols_fallback' specifies whether vertex colors should
/// always be defined, even if no colors are given (fallback to white).
bool LoadObj(attrib_t* attrib, std::vector<shape_t>* shapes,
std::vector<material_t>* materials, std::string* warn,
std::string* err, const char* filename,
const char* mtl_basedir = NULL, bool triangulate = true,
bool default_vcols_fallback = true);
/// Loads .obj from a file with custom user callback.
/// .mtl is loaded as usual and parsed material_t data will be passed to
/// `callback.mtllib_cb`.
/// Returns true when loading .obj/.mtl become success.
/// Returns warning message into `warn`, and error message into `err`
/// See `examples/callback_api/` for how to use this function.
bool LoadObjWithCallback(std::istream& inStream, const callback_t& callback,
void* user_data = NULL,
MaterialReader* readMatFn = NULL,
std::string* warn = NULL, std::string* err = NULL);
/// Loads object from a std::istream, uses `readMatFn` to retrieve
/// std::istream for materials.
/// Returns true when loading .obj become success.
/// Returns warning and error message into `err`
bool LoadObj(attrib_t* attrib, std::vector<shape_t>* shapes,
std::vector<material_t>* materials, std::string* warn,
std::string* err, std::istream* inStream,
MaterialReader* readMatFn = NULL, bool triangulate = true,
bool default_vcols_fallback = true);
/// Loads materials into std::map
void LoadMtl(std::map<std::string, int>* material_map,
std::vector<material_t>* materials, std::istream* inStream,
std::string* warning, std::string* err);
///
/// Parse texture name and texture option for custom texture parameter through
/// material::unknown_parameter
///
/// @param[out] texname Parsed texture name
/// @param[out] texopt Parsed texopt
/// @param[in] linebuf Input string
///
bool ParseTextureNameAndOption(std::string* texname, texture_option_t* texopt,
const char* linebuf);
/// =<<========== Legacy v1 API =============================================
} // namespace tinyobj
#endif // TINY_OBJ_LOADER_H_
#ifdef TINYOBJLOADER_IMPLEMENTATION
#include <cassert>
#include <cctype>
#include <cmath>
#include <cstddef>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <limits>
#include <sstream>
#include <utility>
namespace tinyobj {
MaterialReader::~MaterialReader() {}
struct vertex_index_t {
int v_idx, vt_idx, vn_idx;
vertex_index_t() : v_idx(-1), vt_idx(-1), vn_idx(-1) {}
explicit vertex_index_t(int idx) : v_idx(idx), vt_idx(idx), vn_idx(idx) {}
vertex_index_t(int vidx, int vtidx, int vnidx)
: v_idx(vidx), vt_idx(vtidx), vn_idx(vnidx) {}
};
// Internal data structure for face representation
// index + smoothing group.
struct face_t {
unsigned int
smoothing_group_id; // smoothing group id. 0 = smoothing groupd is off.
int pad_;
std::vector<vertex_index_t> vertex_indices; // face vertex indices.
face_t() : smoothing_group_id(0), pad_(0) {}
};
// Internal data structure for line representation
struct __line_t {
// l v1/vt1 v2/vt2 ...
// In the specification, line primitrive does not have normal index, but
// TinyObjLoader allow it
std::vector<vertex_index_t> vertex_indices;
};
// Internal data structure for points representation
struct __points_t {
// p v1 v2 ...
// In the specification, point primitrive does not have normal index and
// texture coord index, but TinyObjLoader allow it.
std::vector<vertex_index_t> vertex_indices;
};
struct tag_sizes {
tag_sizes() : num_ints(0), num_reals(0), num_strings(0) {}
int num_ints;
int num_reals;
int num_strings;
};
struct obj_shape {
std::vector<real_t> v;
std::vector<real_t> vn;
std::vector<real_t> vt;
};
//
// Manages group of primitives(face, line, points, ...)
struct PrimGroup {
std::vector<face_t> faceGroup;
std::vector<__line_t> lineGroup;
std::vector<__points_t> pointsGroup;
void clear() {
faceGroup.clear();
lineGroup.clear();
pointsGroup.clear();
}
bool IsEmpty() const {
return faceGroup.empty() && lineGroup.empty() && pointsGroup.empty();
}
// TODO(syoyo): bspline, surface, ...
};
// See
// http://stackoverflow.com/questions/6089231/getting-std-ifstream-to-handle-lf-cr-and-crlf
static std::istream& safeGetline(std::istream& is, std::string& t) {
t.clear();
// The characters in the stream are read one-by-one using a std::streambuf.
// That is faster than reading them one-by-one using the std::istream.
// Code that uses streambuf this way must be guarded by a sentry object.
// The sentry object performs various tasks,
// such as thread synchronization and updating the stream state.
std::istream::sentry se(is, true);
std::streambuf* sb = is.rdbuf();
if (se) {
for (;;) {
int c = sb->sbumpc();
switch (c) {
case '\n':
return is;
case '\r':
if (sb->sgetc() == '\n') sb->sbumpc();
return is;
case EOF:
// Also handle the case when the last line has no line ending
if (t.empty()) is.setstate(std::ios::eofbit);
return is;
default:
t += static_cast<char>(c);
}
}
}
return is;
}
#define IS_SPACE(x) (((x) == ' ') || ((x) == '\t'))
#define IS_DIGIT(x) \
(static_cast<unsigned int>((x) - '0') < static_cast<unsigned int>(10))
#define IS_NEW_LINE(x) (((x) == '\r') || ((x) == '\n') || ((x) == '\0'))
// Make index zero-base, and also support relative index.
static inline bool fixIndex(int idx, int n, int* ret) {
if (!ret) {
return false;
}
if (idx > 0) {
(*ret) = idx - 1;
return true;
}
if (idx == 0) {
// zero is not allowed according to the spec.
return false;
}
if (idx < 0) {
(*ret) = n + idx; // negative value = relative
return true;
}
return false; // never reach here.
}
static inline std::string parseString(const char** token) {
std::string s;
(*token) += strspn((*token), " \t");
size_t e = strcspn((*token), " \t\r");
s = std::string((*token), &(*token)[e]);
(*token) += e;
return s;
}
static inline int parseInt(const char** token) {
(*token) += strspn((*token), " \t");
int i = atoi((*token));
(*token) += strcspn((*token), " \t\r");
return i;
}
// Tries to parse a floating point number located at s.
//
// s_end should be a location in the string where reading should absolutely
// stop. For example at the end of the string, to prevent buffer overflows.
//
// Parses the following EBNF grammar:
// sign = "+" | "-" ;
// END = ? anything not in digit ?
// digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" ;
// integer = [sign] , digit , {digit} ;
// decimal = integer , ["." , integer] ;
// float = ( decimal , END ) | ( decimal , ("E" | "e") , integer , END ) ;
//
// Valid strings are for example:
// -0 +3.1417e+2 -0.0E-3 1.0324 -1.41 11e2
//
// If the parsing is a success, result is set to the parsed value and true
// is returned.
//
// The function is greedy and will parse until any of the following happens:
// - a non-conforming character is encountered.
// - s_end is reached.
//
// The following situations triggers a failure:
// - s >= s_end.
// - parse failure.
//
static bool tryParseDouble(const char* s, const char* s_end, double* result) {
if (s >= s_end) {
return false;
}
double mantissa = 0.0;
// This exponent is base 2 rather than 10.
// However the exponent we parse is supposed to be one of ten,
// thus we must take care to convert the exponent/and or the
// mantissa to a * 2^E, where a is the mantissa and E is the
// exponent.
// To get the final double we will use ldexp, it requires the
// exponent to be in base 2.
int exponent = 0;
// NOTE: THESE MUST BE DECLARED HERE SINCE WE ARE NOT ALLOWED
// TO JUMP OVER DEFINITIONS.
char sign = '+';
char exp_sign = '+';
char const* curr = s;
// How many characters were read in a loop.
int read = 0;
// Tells whether a loop terminated due to reaching s_end.
bool end_not_reached = false;
bool leading_decimal_dots = false;
/*
BEGIN PARSING.
*/
// Find out what sign we've got.
if (*curr == '+' || *curr == '-') {
sign = *curr;
curr++;
if ((curr != s_end) && (*curr == '.')) {
// accept. Somethig like `.7e+2`, `-.5234`
leading_decimal_dots = true;
}
}
else if (IS_DIGIT(*curr)) { /* Pass through. */
}
else if (*curr == '.') {
// accept. Somethig like `.7e+2`, `-.5234`
leading_decimal_dots = true;
}
else {
goto fail;
}
// Read the integer part.
end_not_reached = (curr != s_end);
if (!leading_decimal_dots) {
while (end_not_reached && IS_DIGIT(*curr)) {
mantissa *= 10;
mantissa += static_cast<int>(*curr - 0x30);
curr++;
read++;
end_not_reached = (curr != s_end);
}
// We must make sure we actually got something.
if (read == 0) goto fail;
}
// We allow numbers of form "#", "###" etc.
if (!end_not_reached) goto assemble;
// Read the decimal part.
if (*curr == '.') {
curr++;
read = 1;
end_not_reached = (curr != s_end);
while (end_not_reached && IS_DIGIT(*curr)) {
static const double pow_lut[] = {
1.0, 0.1, 0.01, 0.001, 0.0001, 0.00001, 0.000001, 0.0000001,
};
const int lut_entries = sizeof pow_lut / sizeof pow_lut[0];
// NOTE: Don't use powf here, it will absolutely murder precision.
mantissa += static_cast<int>(*curr - 0x30) *
(read < lut_entries ? pow_lut[read] : std::pow(10.0, -read));
read++;
curr++;
end_not_reached = (curr != s_end);
}
}
else if (*curr == 'e' || *curr == 'E') {
}
else {
goto assemble;
}
if (!end_not_reached) goto assemble;
// Read the exponent part.
if (*curr == 'e' || *curr == 'E') {
curr++;
// Figure out if a sign is present and if it is.
end_not_reached = (curr != s_end);
if (end_not_reached && (*curr == '+' || *curr == '-')) {
exp_sign = *curr;
curr++;
}
else if (IS_DIGIT(*curr)) { /* Pass through. */
}
else {
// Empty E is not allowed.
goto fail;
}
read = 0;
end_not_reached = (curr != s_end);
while (end_not_reached && IS_DIGIT(*curr)) {
exponent *= 10;
exponent += static_cast<int>(*curr - 0x30);
curr++;
read++;
end_not_reached = (curr != s_end);
}
exponent *= (exp_sign == '+' ? 1 : -1);
if (read == 0) goto fail;
}
assemble:
*result = (sign == '+' ? 1 : -1) *
(exponent ? std::ldexp(mantissa * std::pow(5.0, exponent), exponent)
: mantissa);
return true;
fail:
return false;
}
static inline real_t parseReal(const char** token, double default_value = 0.0) {
(*token) += strspn((*token), " \t");
const char* end = (*token) + strcspn((*token), " \t\r");
double val = default_value;
tryParseDouble((*token), end, &val);
real_t f = static_cast<real_t>(val);
(*token) = end;
return f;
}
static inline bool parseReal(const char** token, real_t* out) {
(*token) += strspn((*token), " \t");
const char* end = (*token) + strcspn((*token), " \t\r");
double val;
bool ret = tryParseDouble((*token), end, &val);
if (ret) {
real_t f = static_cast<real_t>(val);
(*out) = f;
}
(*token) = end;
return ret;
}
static inline void parseReal2(real_t* x, real_t* y, const char** token,
const double default_x = 0.0,
const double default_y = 0.0) {
(*x) = parseReal(token, default_x);
(*y) = parseReal(token, default_y);
}
static inline void parseReal3(real_t* x, real_t* y, real_t* z,
const char** token, const double default_x = 0.0,
const double default_y = 0.0,
const double default_z = 0.0) {
(*x) = parseReal(token, default_x);
(*y) = parseReal(token, default_y);
(*z) = parseReal(token, default_z);
}
static inline void parseV(real_t* x, real_t* y, real_t* z, real_t* w,
const char** token, const double default_x = 0.0,
const double default_y = 0.0,
const double default_z = 0.0,
const double default_w = 1.0) {
(*x) = parseReal(token, default_x);
(*y) = parseReal(token, default_y);
(*z) = parseReal(token, default_z);
(*w) = parseReal(token, default_w);
}
// Extension: parse vertex with colors(6 items)
static inline bool parseVertexWithColor(real_t* x, real_t* y, real_t* z,
real_t* r, real_t* g, real_t* b,
const char** token,
const double default_x = 0.0,
const double default_y = 0.0,
const double default_z = 0.0) {
(*x) = parseReal(token, default_x);
(*y) = parseReal(token, default_y);
(*z) = parseReal(token, default_z);
const bool found_color =
parseReal(token, r) && parseReal(token, g) && parseReal(token, b);
if (!found_color) {
(*r) = (*g) = (*b) = 1.0;
}
return found_color;
}
static inline bool parseOnOff(const char** token, bool default_value = true) {
(*token) += strspn((*token), " \t");
const char* end = (*token) + strcspn((*token), " \t\r");
bool ret = default_value;
if ((0 == strncmp((*token), "on", 2))) {
ret = true;
}
else if ((0 == strncmp((*token), "off", 3))) {
ret = false;
}
(*token) = end;
return ret;
}
static inline texture_type_t parseTextureType(
const char** token, texture_type_t default_value = TEXTURE_TYPE_NONE) {
(*token) += strspn((*token), " \t");
const char* end = (*token) + strcspn((*token), " \t\r");
texture_type_t ty = default_value;
if ((0 == strncmp((*token), "cube_top", strlen("cube_top")))) {
ty = TEXTURE_TYPE_CUBE_TOP;
}
else if ((0 == strncmp((*token), "cube_bottom", strlen("cube_bottom")))) {
ty = TEXTURE_TYPE_CUBE_BOTTOM;
}
else if ((0 == strncmp((*token), "cube_left", strlen("cube_left")))) {
ty = TEXTURE_TYPE_CUBE_LEFT;
}
else if ((0 == strncmp((*token), "cube_right", strlen("cube_right")))) {
ty = TEXTURE_TYPE_CUBE_RIGHT;
}
else if ((0 == strncmp((*token), "cube_front", strlen("cube_front")))) {
ty = TEXTURE_TYPE_CUBE_FRONT;
}
else if ((0 == strncmp((*token), "cube_back", strlen("cube_back")))) {
ty = TEXTURE_TYPE_CUBE_BACK;
}
else if ((0 == strncmp((*token), "sphere", strlen("sphere")))) {
ty = TEXTURE_TYPE_SPHERE;
}
(*token) = end;
return ty;
}
static tag_sizes parseTagTriple(const char** token) {
tag_sizes ts;
(*token) += strspn((*token), " \t");
ts.num_ints = atoi((*token));
(*token) += strcspn((*token), "/ \t\r");
if ((*token)[0] != '/') {
return ts;
}
(*token)++; // Skip '/'
(*token) += strspn((*token), " \t");
ts.num_reals = atoi((*token));
(*token) += strcspn((*token), "/ \t\r");
if ((*token)[0] != '/') {
return ts;
}
(*token)++; // Skip '/'
ts.num_strings = parseInt(token);
return ts;
}
// Parse triples with index offsets: i, i/j/k, i//k, i/j
static bool parseTriple(const char** token, int vsize, int vnsize, int vtsize,
vertex_index_t* ret) {
if (!ret) {
return false;
}
vertex_index_t vi(-1);
if (!fixIndex(atoi((*token)), vsize, &(vi.v_idx))) {
return false;
}
(*token) += strcspn((*token), "/ \t\r");
if ((*token)[0] != '/') {
(*ret) = vi;
return true;
}
(*token)++;
// i//k
if ((*token)[0] == '/') {
(*token)++;
if (!fixIndex(atoi((*token)), vnsize, &(vi.vn_idx))) {
return false;
}
(*token) += strcspn((*token), "/ \t\r");
(*ret) = vi;
return true;
}
// i/j/k or i/j
if (!fixIndex(atoi((*token)), vtsize, &(vi.vt_idx))) {
return false;
}
(*token) += strcspn((*token), "/ \t\r");
if ((*token)[0] != '/') {
(*ret) = vi;
return true;
}
// i/j/k
(*token)++; // skip '/'
if (!fixIndex(atoi((*token)), vnsize, &(vi.vn_idx))) {
return false;
}
(*token) += strcspn((*token), "/ \t\r");
(*ret) = vi;
return true;
}
// Parse raw triples: i, i/j/k, i//k, i/j
static vertex_index_t parseRawTriple(const char** token) {
vertex_index_t vi(static_cast<int>(0)); // 0 is an invalid index in OBJ
vi.v_idx = atoi((*token));
(*token) += strcspn((*token), "/ \t\r");
if ((*token)[0] != '/') {
return vi;
}
(*token)++;
// i//k
if ((*token)[0] == '/') {
(*token)++;
vi.vn_idx = atoi((*token));
(*token) += strcspn((*token), "/ \t\r");
return vi;
}
// i/j/k or i/j
vi.vt_idx = atoi((*token));
(*token) += strcspn((*token), "/ \t\r");
if ((*token)[0] != '/') {
return vi;
}
// i/j/k
(*token)++; // skip '/'
vi.vn_idx = atoi((*token));
(*token) += strcspn((*token), "/ \t\r");
return vi;
}
bool ParseTextureNameAndOption(std::string* texname, texture_option_t* texopt,
const char* linebuf) {
// @todo { write more robust lexer and parser. }
bool found_texname = false;
std::string texture_name;
const char* token = linebuf; // Assume line ends with NULL
while (!IS_NEW_LINE((*token))) {
token += strspn(token, " \t"); // skip space
if ((0 == strncmp(token, "-blendu", 7)) && IS_SPACE((token[7]))) {
token += 8;
texopt->blendu = parseOnOff(&token, /* default */ true);
}
else if ((0 == strncmp(token, "-blendv", 7)) && IS_SPACE((token[7]))) {
token += 8;
texopt->blendv = parseOnOff(&token, /* default */ true);
}
else if ((0 == strncmp(token, "-clamp", 6)) && IS_SPACE((token[6]))) {
token += 7;
texopt->clamp = parseOnOff(&token, /* default */ true);
}
else if ((0 == strncmp(token, "-boost", 6)) && IS_SPACE((token[6]))) {
token += 7;
texopt->sharpness = parseReal(&token, 1.0);
}
else if ((0 == strncmp(token, "-bm", 3)) && IS_SPACE((token[3]))) {
token += 4;
texopt->bump_multiplier = parseReal(&token, 1.0);
}
else if ((0 == strncmp(token, "-o", 2)) && IS_SPACE((token[2]))) {
token += 3;
parseReal3(&(texopt->origin_offset[0]), &(texopt->origin_offset[1]),
&(texopt->origin_offset[2]), &token);
}
else if ((0 == strncmp(token, "-s", 2)) && IS_SPACE((token[2]))) {
token += 3;
parseReal3(&(texopt->scale[0]), &(texopt->scale[1]), &(texopt->scale[2]),
&token, 1.0, 1.0, 1.0);
}
else if ((0 == strncmp(token, "-t", 2)) && IS_SPACE((token[2]))) {
token += 3;
parseReal3(&(texopt->turbulence[0]), &(texopt->turbulence[1]),
&(texopt->turbulence[2]), &token);
}
else if ((0 == strncmp(token, "-type", 5)) && IS_SPACE((token[5]))) {
token += 5;
texopt->type = parseTextureType((&token), TEXTURE_TYPE_NONE);
}
else if ((0 == strncmp(token, "-texres", 7)) && IS_SPACE((token[7]))) {
token += 7;
// TODO(syoyo): Check if arg is int type.
texopt->texture_resolution = parseInt(&token);
}
else if ((0 == strncmp(token, "-imfchan", 8)) && IS_SPACE((token[8]))) {
token += 9;
token += strspn(token, " \t");
const char* end = token + strcspn(token, " \t\r");
if ((end - token) == 1) { // Assume one char for -imfchan
texopt->imfchan = (*token);
}
token = end;
}
else if ((0 == strncmp(token, "-mm", 3)) && IS_SPACE((token[3]))) {
token += 4;
parseReal2(&(texopt->brightness), &(texopt->contrast), &token, 0.0, 1.0);
}
else if ((0 == strncmp(token, "-colorspace", 11)) &&
IS_SPACE((token[11]))) {
token += 12;
texopt->colorspace = parseString(&token);
}
else {
// Assume texture filename
#if 0
size_t len = strcspn(token, " \t\r"); // untile next space
texture_name = std::string(token, token + len);
token += len;
token += strspn(token, " \t"); // skip space
#else
// Read filename until line end to parse filename containing whitespace
// TODO(syoyo): Support parsing texture option flag after the filename.
texture_name = std::string(token);
token += texture_name.length();
#endif
found_texname = true;
}
}
if (found_texname) {
(*texname) = texture_name;
return true;
}
else {
return false;
}
}
static void InitTexOpt(texture_option_t* texopt, const bool is_bump) {
if (is_bump) {
texopt->imfchan = 'l';
}
else {
texopt->imfchan = 'm';
}
texopt->bump_multiplier = static_cast<real_t>(1.0);
texopt->clamp = false;
texopt->blendu = true;
texopt->blendv = true;
texopt->sharpness = static_cast<real_t>(1.0);
texopt->brightness = static_cast<real_t>(0.0);
texopt->contrast = static_cast<real_t>(1.0);
texopt->origin_offset[0] = static_cast<real_t>(0.0);
texopt->origin_offset[1] = static_cast<real_t>(0.0);
texopt->origin_offset[2] = static_cast<real_t>(0.0);
texopt->scale[0] = static_cast<real_t>(1.0);
texopt->scale[1] = static_cast<real_t>(1.0);
texopt->scale[2] = static_cast<real_t>(1.0);
texopt->turbulence[0] = static_cast<real_t>(0.0);
texopt->turbulence[1] = static_cast<real_t>(0.0);
texopt->turbulence[2] = static_cast<real_t>(0.0);
texopt->texture_resolution = -1;
texopt->type = TEXTURE_TYPE_NONE;
}
static void InitMaterial(material_t* material) {
InitTexOpt(&material->ambient_texopt, /* is_bump */ false);
InitTexOpt(&material->diffuse_texopt, /* is_bump */ false);
InitTexOpt(&material->specular_texopt, /* is_bump */ false);
InitTexOpt(&material->specular_highlight_texopt, /* is_bump */ false);
InitTexOpt(&material->bump_texopt, /* is_bump */ true);
InitTexOpt(&material->displacement_texopt, /* is_bump */ false);
InitTexOpt(&material->alpha_texopt, /* is_bump */ false);
InitTexOpt(&material->reflection_texopt, /* is_bump */ false);
InitTexOpt(&material->roughness_texopt, /* is_bump */ false);
InitTexOpt(&material->metallic_texopt, /* is_bump */ false);
InitTexOpt(&material->sheen_texopt, /* is_bump */ false);
InitTexOpt(&material->emissive_texopt, /* is_bump */ false);
InitTexOpt(&material->normal_texopt,
/* is_bump */ false); // @fixme { is_bump will be true? }
material->name = "";
material->ambient_texname = "";
material->diffuse_texname = "";
material->specular_texname = "";
material->specular_highlight_texname = "";
material->bump_texname = "";
material->displacement_texname = "";
material->reflection_texname = "";
material->alpha_texname = "";
for (int i = 0; i < 3; i++) {
material->ambient[i] = static_cast<real_t>(0.0);
material->diffuse[i] = static_cast<real_t>(0.0);
material->specular[i] = static_cast<real_t>(0.0);
material->transmittance[i] = static_cast<real_t>(0.0);
material->emission[i] = static_cast<real_t>(0.0);
}
material->illum = 0;
material->dissolve = static_cast<real_t>(1.0);
material->shininess = static_cast<real_t>(1.0);
material->ior = static_cast<real_t>(1.0);
material->roughness = static_cast<real_t>(0.0);
material->metallic = static_cast<real_t>(0.0);
material->sheen = static_cast<real_t>(0.0);
material->clearcoat_thickness = static_cast<real_t>(0.0);
material->clearcoat_roughness = static_cast<real_t>(0.0);
material->anisotropy_rotation = static_cast<real_t>(0.0);
material->anisotropy = static_cast<real_t>(0.0);
material->roughness_texname = "";
material->metallic_texname = "";
material->sheen_texname = "";
material->emissive_texname = "";
material->normal_texname = "";
material->unknown_parameter.clear();
}
// code from https://wrf.ecse.rpi.edu//Research/Short_Notes/pnpoly.html
template <typename T>
static int pnpoly(int nvert, T* vertx, T* verty, T testx, T testy) {
int i, j, c = 0;
for (i = 0, j = nvert - 1; i < nvert; j = i++) {
if (((verty[i] > testy) != (verty[j] > testy)) &&
(testx <
(vertx[j] - vertx[i]) * (testy - verty[i]) / (verty[j] - verty[i]) +
vertx[i]))
c = !c;
}
return c;
}
// TODO(syoyo): refactor function.
static bool exportGroupsToShape(shape_t* shape, const PrimGroup& prim_group,
const std::vector<tag_t>& tags,
const int material_id, const std::string& name,
bool triangulate, const std::vector<real_t>& v,
std::string* warn) {
if (prim_group.IsEmpty()) {
return false;
}
shape->name = name;
// polygon
if (!prim_group.faceGroup.empty()) {
// Flatten vertices and indices
for (size_t i = 0; i < prim_group.faceGroup.size(); i++) {
const face_t& face = prim_group.faceGroup[i];
size_t npolys = face.vertex_indices.size();
if (npolys < 3) {
// Face must have 3+ vertices.
if (warn) {
(*warn) += "Degenerated face found\n.";
}
continue;
}
if (triangulate) {
if (npolys == 4) {
vertex_index_t i0 = face.vertex_indices[0];
vertex_index_t i1 = face.vertex_indices[1];
vertex_index_t i2 = face.vertex_indices[2];
vertex_index_t i3 = face.vertex_indices[3];
size_t vi0 = size_t(i0.v_idx);
size_t vi1 = size_t(i1.v_idx);
size_t vi2 = size_t(i2.v_idx);
size_t vi3 = size_t(i3.v_idx);
if (((3 * vi0 + 2) >= v.size()) || ((3 * vi1 + 2) >= v.size()) ||
((3 * vi2 + 2) >= v.size()) || ((3 * vi3 + 2) >= v.size())) {
// Invalid triangle.
// FIXME(syoyo): Is it ok to simply skip this invalid triangle?
if (warn) {
(*warn) += "Face with invalid vertex index found.\n";
}
continue;
}
real_t v0x = v[vi0 * 3 + 0];
real_t v0y = v[vi0 * 3 + 1];
real_t v0z = v[vi0 * 3 + 2];
real_t v1x = v[vi1 * 3 + 0];
real_t v1y = v[vi1 * 3 + 1];
real_t v1z = v[vi1 * 3 + 2];
real_t v2x = v[vi2 * 3 + 0];
real_t v2y = v[vi2 * 3 + 1];
real_t v2z = v[vi2 * 3 + 2];
real_t v3x = v[vi3 * 3 + 0];
real_t v3y = v[vi3 * 3 + 1];
real_t v3z = v[vi3 * 3 + 2];
// There are two candidates to split the quad into two triangles.
//
// Choose the shortest edge.
// TODO: Is it better to determine the edge to split by calculating
// the area of each triangle?
//
// +---+
// |\ |
// | \ |
// | \|
// +---+
//
// +---+
// | /|
// | / |
// |/ |
// +---+
real_t e02x = v2x - v0x;
real_t e02y = v2y - v0y;
real_t e02z = v2z - v0z;
real_t e13x = v3x - v1x;
real_t e13y = v3y - v1y;
real_t e13z = v3z - v1z;
real_t sqr02 = e02x * e02x + e02y * e02y + e02z * e02z;
real_t sqr13 = e13x * e13x + e13y * e13y + e13z * e13z;
index_t idx0, idx1, idx2, idx3;
idx0.vertex_index = i0.v_idx;
idx0.normal_index = i0.vn_idx;
idx0.texcoord_index = i0.vt_idx;
idx1.vertex_index = i1.v_idx;
idx1.normal_index = i1.vn_idx;
idx1.texcoord_index = i1.vt_idx;
idx2.vertex_index = i2.v_idx;
idx2.normal_index = i2.vn_idx;
idx2.texcoord_index = i2.vt_idx;
idx3.vertex_index = i3.v_idx;
idx3.normal_index = i3.vn_idx;
idx3.texcoord_index = i3.vt_idx;
if (sqr02 < sqr13) {
// [0, 1, 2], [0, 2, 3]
shape->mesh.indices.push_back(idx0);
shape->mesh.indices.push_back(idx1);
shape->mesh.indices.push_back(idx2);
shape->mesh.indices.push_back(idx0);
shape->mesh.indices.push_back(idx2);
shape->mesh.indices.push_back(idx3);
}
else {
// [0, 1, 3], [1, 2, 3]
shape->mesh.indices.push_back(idx0);
shape->mesh.indices.push_back(idx1);
shape->mesh.indices.push_back(idx3);
shape->mesh.indices.push_back(idx1);
shape->mesh.indices.push_back(idx2);
shape->mesh.indices.push_back(idx3);
}
// Two triangle faces
shape->mesh.num_face_vertices.push_back(3);
shape->mesh.num_face_vertices.push_back(3);
shape->mesh.material_ids.push_back(material_id);
shape->mesh.material_ids.push_back(material_id);
shape->mesh.smoothing_group_ids.push_back(face.smoothing_group_id);
shape->mesh.smoothing_group_ids.push_back(face.smoothing_group_id);
}
else {
vertex_index_t i0 = face.vertex_indices[0];
vertex_index_t i1(-1);
vertex_index_t i2 = face.vertex_indices[1];
// find the two axes to work in
size_t axes[2] = { 1, 2 };
for (size_t k = 0; k < npolys; ++k) {
i0 = face.vertex_indices[(k + 0) % npolys];
i1 = face.vertex_indices[(k + 1) % npolys];
i2 = face.vertex_indices[(k + 2) % npolys];
size_t vi0 = size_t(i0.v_idx);
size_t vi1 = size_t(i1.v_idx);
size_t vi2 = size_t(i2.v_idx);
if (((3 * vi0 + 2) >= v.size()) || ((3 * vi1 + 2) >= v.size()) ||
((3 * vi2 + 2) >= v.size())) {
// Invalid triangle.
// FIXME(syoyo): Is it ok to simply skip this invalid triangle?
continue;
}
real_t v0x = v[vi0 * 3 + 0];
real_t v0y = v[vi0 * 3 + 1];
real_t v0z = v[vi0 * 3 + 2];
real_t v1x = v[vi1 * 3 + 0];
real_t v1y = v[vi1 * 3 + 1];
real_t v1z = v[vi1 * 3 + 2];
real_t v2x = v[vi2 * 3 + 0];
real_t v2y = v[vi2 * 3 + 1];
real_t v2z = v[vi2 * 3 + 2];
real_t e0x = v1x - v0x;
real_t e0y = v1y - v0y;
real_t e0z = v1z - v0z;
real_t e1x = v2x - v1x;
real_t e1y = v2y - v1y;
real_t e1z = v2z - v1z;
real_t cx = std::fabs(e0y * e1z - e0z * e1y);
real_t cy = std::fabs(e0z * e1x - e0x * e1z);
real_t cz = std::fabs(e0x * e1y - e0y * e1x);
const real_t epsilon = std::numeric_limits<real_t>::epsilon();
if (cx > epsilon || cy > epsilon || cz > epsilon) {
// found a corner
if (cx > cy && cx > cz) {
}
else {
axes[0] = 0;
if (cz > cx && cz > cy) axes[1] = 1;
}
break;
}
}
real_t area = 0;
for (size_t k = 0; k < npolys; ++k) {
i0 = face.vertex_indices[(k + 0) % npolys];
i1 = face.vertex_indices[(k + 1) % npolys];
size_t vi0 = size_t(i0.v_idx);
size_t vi1 = size_t(i1.v_idx);
if (((vi0 * 3 + axes[0]) >= v.size()) ||
((vi0 * 3 + axes[1]) >= v.size()) ||
((vi1 * 3 + axes[0]) >= v.size()) ||
((vi1 * 3 + axes[1]) >= v.size())) {
// Invalid index.
continue;
}
real_t v0x = v[vi0 * 3 + axes[0]];
real_t v0y = v[vi0 * 3 + axes[1]];
real_t v1x = v[vi1 * 3 + axes[0]];
real_t v1y = v[vi1 * 3 + axes[1]];
area += (v0x * v1y - v0y * v1x) * static_cast<real_t>(0.5);
}
face_t remainingFace = face; // copy
size_t guess_vert = 0;
vertex_index_t ind[3];
real_t vx[3];
real_t vy[3];
// How many iterations can we do without decreasing the remaining
// vertices.
size_t remainingIterations = face.vertex_indices.size();
size_t previousRemainingVertices =
remainingFace.vertex_indices.size();
while (remainingFace.vertex_indices.size() > 3 &&
remainingIterations > 0) {
npolys = remainingFace.vertex_indices.size();
if (guess_vert >= npolys) {
guess_vert -= npolys;
}
if (previousRemainingVertices != npolys) {
// The number of remaining vertices decreased. Reset counters.
previousRemainingVertices = npolys;
remainingIterations = npolys;
}
else {
// We didn't consume a vertex on previous iteration, reduce the
// available iterations.
remainingIterations--;
}
for (size_t k = 0; k < 3; k++) {
ind[k] = remainingFace.vertex_indices[(guess_vert + k) % npolys];
size_t vi = size_t(ind[k].v_idx);
if (((vi * 3 + axes[0]) >= v.size()) ||
((vi * 3 + axes[1]) >= v.size())) {
// ???
vx[k] = static_cast<real_t>(0.0);
vy[k] = static_cast<real_t>(0.0);
}
else {
vx[k] = v[vi * 3 + axes[0]];
vy[k] = v[vi * 3 + axes[1]];
}
}
real_t e0x = vx[1] - vx[0];
real_t e0y = vy[1] - vy[0];
real_t e1x = vx[2] - vx[1];
real_t e1y = vy[2] - vy[1];
real_t cross = e0x * e1y - e0y * e1x;
// if an internal angle
if (cross * area < static_cast<real_t>(0.0)) {
guess_vert += 1;
continue;
}
// check all other verts in case they are inside this triangle
bool overlap = false;
for (size_t otherVert = 3; otherVert < npolys; ++otherVert) {
size_t idx = (guess_vert + otherVert) % npolys;
if (idx >= remainingFace.vertex_indices.size()) {
// ???
continue;
}
size_t ovi = size_t(remainingFace.vertex_indices[idx].v_idx);
if (((ovi * 3 + axes[0]) >= v.size()) ||
((ovi * 3 + axes[1]) >= v.size())) {
// ???
continue;
}
real_t tx = v[ovi * 3 + axes[0]];
real_t ty = v[ovi * 3 + axes[1]];
if (pnpoly(3, vx, vy, tx, ty)) {
overlap = true;
break;
}
}
if (overlap) {
guess_vert += 1;
continue;
}
// this triangle is an ear
{
index_t idx0, idx1, idx2;
idx0.vertex_index = ind[0].v_idx;
idx0.normal_index = ind[0].vn_idx;
idx0.texcoord_index = ind[0].vt_idx;
idx1.vertex_index = ind[1].v_idx;
idx1.normal_index = ind[1].vn_idx;
idx1.texcoord_index = ind[1].vt_idx;
idx2.vertex_index = ind[2].v_idx;
idx2.normal_index = ind[2].vn_idx;
idx2.texcoord_index = ind[2].vt_idx;
shape->mesh.indices.push_back(idx0);
shape->mesh.indices.push_back(idx1);
shape->mesh.indices.push_back(idx2);
shape->mesh.num_face_vertices.push_back(3);
shape->mesh.material_ids.push_back(material_id);
shape->mesh.smoothing_group_ids.push_back(
face.smoothing_group_id);
}
// remove v1 from the list
size_t removed_vert_index = (guess_vert + 1) % npolys;
while (removed_vert_index + 1 < npolys) {
remainingFace.vertex_indices[removed_vert_index] =
remainingFace.vertex_indices[removed_vert_index + 1];
removed_vert_index += 1;
}
remainingFace.vertex_indices.pop_back();
}
if (remainingFace.vertex_indices.size() == 3) {
i0 = remainingFace.vertex_indices[0];
i1 = remainingFace.vertex_indices[1];
i2 = remainingFace.vertex_indices[2];
{
index_t idx0, idx1, idx2;
idx0.vertex_index = i0.v_idx;
idx0.normal_index = i0.vn_idx;
idx0.texcoord_index = i0.vt_idx;
idx1.vertex_index = i1.v_idx;
idx1.normal_index = i1.vn_idx;
idx1.texcoord_index = i1.vt_idx;
idx2.vertex_index = i2.v_idx;
idx2.normal_index = i2.vn_idx;
idx2.texcoord_index = i2.vt_idx;
shape->mesh.indices.push_back(idx0);
shape->mesh.indices.push_back(idx1);
shape->mesh.indices.push_back(idx2);
shape->mesh.num_face_vertices.push_back(3);
shape->mesh.material_ids.push_back(material_id);
shape->mesh.smoothing_group_ids.push_back(
face.smoothing_group_id);
}
}
} // npolys
}
else {
for (size_t k = 0; k < npolys; k++) {
index_t idx;
idx.vertex_index = face.vertex_indices[k].v_idx;
idx.normal_index = face.vertex_indices[k].vn_idx;
idx.texcoord_index = face.vertex_indices[k].vt_idx;
shape->mesh.indices.push_back(idx);
}
shape->mesh.num_face_vertices.push_back(
static_cast<unsigned char>(npolys));
shape->mesh.material_ids.push_back(material_id); // per face
shape->mesh.smoothing_group_ids.push_back(
face.smoothing_group_id); // per face
}
}
shape->mesh.tags = tags;
}
// line
if (!prim_group.lineGroup.empty()) {
// Flatten indices
for (size_t i = 0; i < prim_group.lineGroup.size(); i++) {
for (size_t j = 0; j < prim_group.lineGroup[i].vertex_indices.size();
j++) {
const vertex_index_t& vi = prim_group.lineGroup[i].vertex_indices[j];
index_t idx;
idx.vertex_index = vi.v_idx;
idx.normal_index = vi.vn_idx;
idx.texcoord_index = vi.vt_idx;
shape->lines.indices.push_back(idx);
}
shape->lines.num_line_vertices.push_back(
int(prim_group.lineGroup[i].vertex_indices.size()));
}
}
// points
if (!prim_group.pointsGroup.empty()) {
// Flatten & convert indices
for (size_t i = 0; i < prim_group.pointsGroup.size(); i++) {
for (size_t j = 0; j < prim_group.pointsGroup[i].vertex_indices.size();
j++) {
const vertex_index_t& vi = prim_group.pointsGroup[i].vertex_indices[j];
index_t idx;
idx.vertex_index = vi.v_idx;
idx.normal_index = vi.vn_idx;
idx.texcoord_index = vi.vt_idx;
shape->points.indices.push_back(idx);
}
}
}
return true;
}
// Split a string with specified delimiter character and escape character.
// https://rosettacode.org/wiki/Tokenize_a_string_with_escaping#C.2B.2B
static void SplitString(const std::string& s, char delim, char escape,
std::vector<std::string>& elems) {
std::string token;
bool escaping = false;
for (size_t i = 0; i < s.size(); ++i) {
char ch = s[i];
if (escaping) {
escaping = false;
}
else if (ch == escape) {
escaping = true;
continue;
}
else if (ch == delim) {
if (!token.empty()) {
elems.push_back(token);
}
token.clear();
continue;
}
token += ch;
}
elems.push_back(token);
}
static std::string JoinPath(const std::string& dir,
const std::string& filename) {
if (dir.empty()) {
return filename;
}
else {
// check '/'
char lastChar = *dir.rbegin();
if (lastChar != '/') {
return dir + std::string("/") + filename;
}
else {
return dir + filename;
}
}
}
void LoadMtl(std::map<std::string, int>* material_map,
std::vector<material_t>* materials, std::istream* inStream,
std::string* warning, std::string* err) {
(void)err;
// Create a default material anyway.
material_t material;
InitMaterial(&material);
// Issue 43. `d` wins against `Tr` since `Tr` is not in the MTL specification.
bool has_d = false;
bool has_tr = false;
// has_kd is used to set a default diffuse value when map_Kd is present
// and Kd is not.
bool has_kd = false;
std::stringstream warn_ss;
size_t line_no = 0;
std::string linebuf;
while (inStream->peek() != -1) {
safeGetline(*inStream, linebuf);
line_no++;
// Trim trailing whitespace.
if (linebuf.size() > 0) {
linebuf = linebuf.substr(0, linebuf.find_last_not_of(" \t") + 1);
}
// Trim newline '\r\n' or '\n'
if (linebuf.size() > 0) {
if (linebuf[linebuf.size() - 1] == '\n')
linebuf.erase(linebuf.size() - 1);
}
if (linebuf.size() > 0) {
if (linebuf[linebuf.size() - 1] == '\r')
linebuf.erase(linebuf.size() - 1);
}
// Skip if empty line.
if (linebuf.empty()) {
continue;
}
// Skip leading space.
const char* token = linebuf.c_str();
token += strspn(token, " \t");
assert(token);
if (token[0] == '\0') continue; // empty line
if (token[0] == '#') continue; // comment line
// new mtl
if ((0 == strncmp(token, "newmtl", 6)) && IS_SPACE((token[6]))) {
// flush previous material.
if (!material.name.empty()) {
material_map->insert(std::pair<std::string, int>(
material.name, static_cast<int>(materials->size())));
materials->push_back(material);
}
// initial temporary material
InitMaterial(&material);
has_d = false;
has_tr = false;
// set new mtl name
token += 7;
{
std::stringstream sstr;
sstr << token;
material.name = sstr.str();
}
continue;
}
// ambient
if (token[0] == 'K' && token[1] == 'a' && IS_SPACE((token[2]))) {
token += 2;
real_t r, g, b;
parseReal3(&r, &g, &b, &token);
material.ambient[0] = r;
material.ambient[1] = g;
material.ambient[2] = b;
continue;
}
// diffuse
if (token[0] == 'K' && token[1] == 'd' && IS_SPACE((token[2]))) {
token += 2;
real_t r, g, b;
parseReal3(&r, &g, &b, &token);
material.diffuse[0] = r;
material.diffuse[1] = g;
material.diffuse[2] = b;
has_kd = true;
continue;
}
// specular
if (token[0] == 'K' && token[1] == 's' && IS_SPACE((token[2]))) {
token += 2;
real_t r, g, b;
parseReal3(&r, &g, &b, &token);
material.specular[0] = r;
material.specular[1] = g;
material.specular[2] = b;
continue;
}
// transmittance
if ((token[0] == 'K' && token[1] == 't' && IS_SPACE((token[2]))) ||
(token[0] == 'T' && token[1] == 'f' && IS_SPACE((token[2])))) {
token += 2;
real_t r, g, b;
parseReal3(&r, &g, &b, &token);
material.transmittance[0] = r;
material.transmittance[1] = g;
material.transmittance[2] = b;
continue;
}
// ior(index of refraction)
if (token[0] == 'N' && token[1] == 'i' && IS_SPACE((token[2]))) {
token += 2;
material.ior = parseReal(&token);
continue;
}
// emission
if (token[0] == 'K' && token[1] == 'e' && IS_SPACE(token[2])) {
token += 2;
real_t r, g, b;
parseReal3(&r, &g, &b, &token);
material.emission[0] = r;
material.emission[1] = g;
material.emission[2] = b;
continue;
}
// shininess
if (token[0] == 'N' && token[1] == 's' && IS_SPACE(token[2])) {
token += 2;
material.shininess = parseReal(&token);
continue;
}
// illum model
if (0 == strncmp(token, "illum", 5) && IS_SPACE(token[5])) {
token += 6;
material.illum = parseInt(&token);
continue;
}
// dissolve
if ((token[0] == 'd' && IS_SPACE(token[1]))) {
token += 1;
material.dissolve = parseReal(&token);
if (has_tr) {
warn_ss << "Both `d` and `Tr` parameters defined for \""
<< material.name
<< "\". Use the value of `d` for dissolve (line " << line_no
<< " in .mtl.)" << std::endl;
}
has_d = true;
continue;
}
if (token[0] == 'T' && token[1] == 'r' && IS_SPACE(token[2])) {
token += 2;
if (has_d) {
// `d` wins. Ignore `Tr` value.
warn_ss << "Both `d` and `Tr` parameters defined for \""
<< material.name
<< "\". Use the value of `d` for dissolve (line " << line_no
<< " in .mtl.)" << std::endl;
}
else {
// We invert value of Tr(assume Tr is in range [0, 1])
// NOTE: Interpretation of Tr is application(exporter) dependent. For
// some application(e.g. 3ds max obj exporter), Tr = d(Issue 43)
material.dissolve = static_cast<real_t>(1.0) - parseReal(&token);
}
has_tr = true;
continue;
}
// PBR: roughness
if (token[0] == 'P' && token[1] == 'r' && IS_SPACE(token[2])) {
token += 2;
material.roughness = parseReal(&token);
continue;
}
// PBR: metallic
if (token[0] == 'P' && token[1] == 'm' && IS_SPACE(token[2])) {
token += 2;
material.metallic = parseReal(&token);
continue;
}
// PBR: sheen
if (token[0] == 'P' && token[1] == 's' && IS_SPACE(token[2])) {
token += 2;
material.sheen = parseReal(&token);
continue;
}
// PBR: clearcoat thickness
if (token[0] == 'P' && token[1] == 'c' && IS_SPACE(token[2])) {
token += 2;
material.clearcoat_thickness = parseReal(&token);
continue;
}
// PBR: clearcoat roughness
if ((0 == strncmp(token, "Pcr", 3)) && IS_SPACE(token[3])) {
token += 4;
material.clearcoat_roughness = parseReal(&token);
continue;
}
// PBR: anisotropy
if ((0 == strncmp(token, "aniso", 5)) && IS_SPACE(token[5])) {
token += 6;
material.anisotropy = parseReal(&token);
continue;
}
// PBR: anisotropy rotation
if ((0 == strncmp(token, "anisor", 6)) && IS_SPACE(token[6])) {
token += 7;
material.anisotropy_rotation = parseReal(&token);
continue;
}
// ambient texture
if ((0 == strncmp(token, "map_Ka", 6)) && IS_SPACE(token[6])) {
token += 7;
ParseTextureNameAndOption(&(material.ambient_texname),
&(material.ambient_texopt), token);
continue;
}
// diffuse texture
if ((0 == strncmp(token, "map_Kd", 6)) && IS_SPACE(token[6])) {
token += 7;
ParseTextureNameAndOption(&(material.diffuse_texname),
&(material.diffuse_texopt), token);
// Set a decent diffuse default value if a diffuse texture is specified
// without a matching Kd value.
if (!has_kd) {
material.diffuse[0] = static_cast<real_t>(0.6);
material.diffuse[1] = static_cast<real_t>(0.6);
material.diffuse[2] = static_cast<real_t>(0.6);
}
continue;
}
// specular texture
if ((0 == strncmp(token, "map_Ks", 6)) && IS_SPACE(token[6])) {
token += 7;
ParseTextureNameAndOption(&(material.specular_texname),
&(material.specular_texopt), token);
continue;
}
// specular highlight texture
if ((0 == strncmp(token, "map_Ns", 6)) && IS_SPACE(token[6])) {
token += 7;
ParseTextureNameAndOption(&(material.specular_highlight_texname),
&(material.specular_highlight_texopt), token);
continue;
}
// bump texture
if ((0 == strncmp(token, "map_bump", 8)) && IS_SPACE(token[8])) {
token += 9;
ParseTextureNameAndOption(&(material.bump_texname),
&(material.bump_texopt), token);
continue;
}
// bump texture
if ((0 == strncmp(token, "map_Bump", 8)) && IS_SPACE(token[8])) {
token += 9;
ParseTextureNameAndOption(&(material.bump_texname),
&(material.bump_texopt), token);
continue;
}
// bump texture
if ((0 == strncmp(token, "bump", 4)) && IS_SPACE(token[4])) {
token += 5;
ParseTextureNameAndOption(&(material.bump_texname),
&(material.bump_texopt), token);
continue;
}
// alpha texture
if ((0 == strncmp(token, "map_d", 5)) && IS_SPACE(token[5])) {
token += 6;
material.alpha_texname = token;
ParseTextureNameAndOption(&(material.alpha_texname),
&(material.alpha_texopt), token);
continue;
}
// displacement texture
if ((0 == strncmp(token, "disp", 4)) && IS_SPACE(token[4])) {
token += 5;
ParseTextureNameAndOption(&(material.displacement_texname),
&(material.displacement_texopt), token);
continue;
}
// reflection map
if ((0 == strncmp(token, "refl", 4)) && IS_SPACE(token[4])) {
token += 5;
ParseTextureNameAndOption(&(material.reflection_texname),
&(material.reflection_texopt), token);
continue;
}
// PBR: roughness texture
if ((0 == strncmp(token, "map_Pr", 6)) && IS_SPACE(token[6])) {
token += 7;
ParseTextureNameAndOption(&(material.roughness_texname),
&(material.roughness_texopt), token);
continue;
}
// PBR: metallic texture
if ((0 == strncmp(token, "map_Pm", 6)) && IS_SPACE(token[6])) {
token += 7;
ParseTextureNameAndOption(&(material.metallic_texname),
&(material.metallic_texopt), token);
continue;
}
// PBR: sheen texture
if ((0 == strncmp(token, "map_Ps", 6)) && IS_SPACE(token[6])) {
token += 7;
ParseTextureNameAndOption(&(material.sheen_texname),
&(material.sheen_texopt), token);
continue;
}
// PBR: emissive texture
if ((0 == strncmp(token, "map_Ke", 6)) && IS_SPACE(token[6])) {
token += 7;
ParseTextureNameAndOption(&(material.emissive_texname),
&(material.emissive_texopt), token);
continue;
}
// PBR: normal map texture
if ((0 == strncmp(token, "norm", 4)) && IS_SPACE(token[4])) {
token += 5;
ParseTextureNameAndOption(&(material.normal_texname),
&(material.normal_texopt), token);
continue;
}
// unknown parameter
const char* _space = strchr(token, ' ');
if (!_space) {
_space = strchr(token, '\t');
}
if (_space) {
std::ptrdiff_t len = _space - token;
std::string key(token, static_cast<size_t>(len));
std::string value = _space + 1;
material.unknown_parameter.insert(
std::pair<std::string, std::string>(key, value));
}
}
// flush last material.
material_map->insert(std::pair<std::string, int>(
material.name, static_cast<int>(materials->size())));
materials->push_back(material);
if (warning) {
(*warning) = warn_ss.str();
}
}
bool MaterialFileReader::operator()(const std::string& matId,
std::vector<material_t>* materials,
std::map<std::string, int>* matMap,
std::string* warn, std::string* err) {
if (!m_mtlBaseDir.empty()) {
#ifdef _WIN32
char sep = ';';
#else
char sep = ':';
#endif
// https://stackoverflow.com/questions/5167625/splitting-a-c-stdstring-using-tokens-e-g
std::vector<std::string> paths;
std::istringstream f(m_mtlBaseDir);
std::string s;
while (getline(f, s, sep)) {
paths.push_back(s);
}
for (size_t i = 0; i < paths.size(); i++) {
std::string filepath = JoinPath(paths[i], matId);
std::ifstream matIStream(filepath.c_str());
if (matIStream) {
LoadMtl(matMap, materials, &matIStream, warn, err);
return true;
}
}
std::stringstream ss;
ss << "Material file [ " << matId
<< " ] not found in a path : " << m_mtlBaseDir << std::endl;
if (warn) {
(*warn) += ss.str();
}
return false;
}
else {
std::string filepath = matId;
std::ifstream matIStream(filepath.c_str());
if (matIStream) {
LoadMtl(matMap, materials, &matIStream, warn, err);
return true;
}
std::stringstream ss;
ss << "Material file [ " << filepath
<< " ] not found in a path : " << m_mtlBaseDir << std::endl;
if (warn) {
(*warn) += ss.str();
}
return false;
}
}
bool MaterialStreamReader::operator()(const std::string& matId,
std::vector<material_t>* materials,
std::map<std::string, int>* matMap,
std::string* warn, std::string* err) {
(void)err;
(void)matId;
if (!m_inStream) {
std::stringstream ss;
ss << "Material stream in error state. " << std::endl;
if (warn) {
(*warn) += ss.str();
}
return false;
}
LoadMtl(matMap, materials, &m_inStream, warn, err);
return true;
}
bool LoadObj(attrib_t* attrib, std::vector<shape_t>* shapes,
std::vector<material_t>* materials, std::string* warn,
std::string* err, const char* filename, const char* mtl_basedir,
bool triangulate, bool default_vcols_fallback) {
attrib->vertices.clear();
attrib->normals.clear();
attrib->texcoords.clear();
attrib->colors.clear();
shapes->clear();
std::stringstream errss;
std::ifstream ifs(filename);
if (!ifs) {
errss << "Cannot open file [" << filename << "]" << std::endl;
if (err) {
(*err) = errss.str();
}
return false;
}
std::string baseDir = mtl_basedir ? mtl_basedir : "";
if (!baseDir.empty()) {
#ifndef _WIN32
const char dirsep = '/';
#else
const char dirsep = '\\';
#endif
if (baseDir[baseDir.length() - 1] != dirsep) baseDir += dirsep;
}
MaterialFileReader matFileReader(baseDir);
return LoadObj(attrib, shapes, materials, warn, err, &ifs, &matFileReader,
triangulate, default_vcols_fallback);
}
bool LoadObj(attrib_t* attrib, std::vector<shape_t>* shapes,
std::vector<material_t>* materials, std::string* warn,
std::string* err, std::istream* inStream,
MaterialReader* readMatFn /*= NULL*/, bool triangulate,
bool default_vcols_fallback) {
std::stringstream errss;
std::vector<real_t> v;
std::vector<real_t> vn;
std::vector<real_t> vt;
std::vector<real_t> vc;
std::vector<skin_weight_t> vw;
std::vector<tag_t> tags;
PrimGroup prim_group;
std::string name;
// material
std::map<std::string, int> material_map;
int material = -1;
// smoothing group id
unsigned int current_smoothing_id =
0; // Initial value. 0 means no smoothing.
int greatest_v_idx = -1;
int greatest_vn_idx = -1;
int greatest_vt_idx = -1;
shape_t shape;
bool found_all_colors = true;
size_t line_num = 0;
std::string linebuf;
while (inStream->peek() != -1) {
safeGetline(*inStream, linebuf);
line_num++;
// Trim newline '\r\n' or '\n'
if (linebuf.size() > 0) {
if (linebuf[linebuf.size() - 1] == '\n')
linebuf.erase(linebuf.size() - 1);
}
if (linebuf.size() > 0) {
if (linebuf[linebuf.size() - 1] == '\r')
linebuf.erase(linebuf.size() - 1);
}
// Skip if empty line.
if (linebuf.empty()) {
continue;
}
// Skip leading space.
const char* token = linebuf.c_str();
token += strspn(token, " \t");
assert(token);
if (token[0] == '\0') continue; // empty line
if (token[0] == '#') continue; // comment line
// vertex
if (token[0] == 'v' && IS_SPACE((token[1]))) {
token += 2;
real_t x, y, z;
real_t r, g, b;
found_all_colors &= parseVertexWithColor(&x, &y, &z, &r, &g, &b, &token);
v.push_back(x);
v.push_back(y);
v.push_back(z);
if (found_all_colors || default_vcols_fallback) {
vc.push_back(r);
vc.push_back(g);
vc.push_back(b);
}
continue;
}
// normal
if (token[0] == 'v' && token[1] == 'n' && IS_SPACE((token[2]))) {
token += 3;
real_t x, y, z;
parseReal3(&x, &y, &z, &token);
vn.push_back(x);
vn.push_back(y);
vn.push_back(z);
continue;
}
// texcoord
if (token[0] == 'v' && token[1] == 't' && IS_SPACE((token[2]))) {
token += 3;
real_t x, y;
parseReal2(&x, &y, &token);
vt.push_back(x);
vt.push_back(y);
continue;
}
// skin weight. tinyobj extension
if (token[0] == 'v' && token[1] == 'w' && IS_SPACE((token[2]))) {
token += 3;
// vw <vid> <joint_0> <weight_0> <joint_1> <weight_1> ...
// example:
// vw 0 0 0.25 1 0.25 2 0.5
// TODO(syoyo): Add syntax check
int vid = 0;
vid = parseInt(&token);
skin_weight_t sw;
sw.vertex_id = vid;
while (!IS_NEW_LINE(token[0])) {
real_t j, w;
// joint_id should not be negative, weight may be negative
// TODO(syoyo): # of elements check
parseReal2(&j, &w, &token, -1.0);
if (j < 0.0) {
if (err) {
std::stringstream ss;
ss << "Failed parse `vw' line. joint_id is negative. "
"line "
<< line_num << ".)\n";
(*err) += ss.str();
}
return false;
}
joint_and_weight_t jw;
jw.joint_id = int(j);
jw.weight = w;
sw.weightValues.push_back(jw);
size_t n = strspn(token, " \t\r");
token += n;
}
vw.push_back(sw);
}
// line
if (token[0] == 'l' && IS_SPACE((token[1]))) {
token += 2;
__line_t line;
while (!IS_NEW_LINE(token[0])) {
vertex_index_t vi;
if (!parseTriple(&token, static_cast<int>(v.size() / 3),
static_cast<int>(vn.size() / 3),
static_cast<int>(vt.size() / 2), &vi)) {
if (err) {
std::stringstream ss;
ss << "Failed parse `l' line(e.g. zero value for vertex index. "
"line "
<< line_num << ".)\n";
(*err) += ss.str();
}
return false;
}
line.vertex_indices.push_back(vi);
size_t n = strspn(token, " \t\r");
token += n;
}
prim_group.lineGroup.push_back(line);
continue;
}
// points
if (token[0] == 'p' && IS_SPACE((token[1]))) {
token += 2;
__points_t pts;
while (!IS_NEW_LINE(token[0])) {
vertex_index_t vi;
if (!parseTriple(&token, static_cast<int>(v.size() / 3),
static_cast<int>(vn.size() / 3),
static_cast<int>(vt.size() / 2), &vi)) {
if (err) {
std::stringstream ss;
ss << "Failed parse `p' line(e.g. zero value for vertex index. "
"line "
<< line_num << ".)\n";
(*err) += ss.str();
}
return false;
}
pts.vertex_indices.push_back(vi);
size_t n = strspn(token, " \t\r");
token += n;
}
prim_group.pointsGroup.push_back(pts);
continue;
}
// face
if (token[0] == 'f' && IS_SPACE((token[1]))) {
token += 2;
token += strspn(token, " \t");
face_t face;
face.smoothing_group_id = current_smoothing_id;
face.vertex_indices.reserve(3);
while (!IS_NEW_LINE(token[0])) {
vertex_index_t vi;
if (!parseTriple(&token, static_cast<int>(v.size() / 3),
static_cast<int>(vn.size() / 3),
static_cast<int>(vt.size() / 2), &vi)) {
if (err) {
std::stringstream ss;
ss << "Failed parse `f' line(e.g. zero value for face index. line "
<< line_num << ".)\n";
(*err) += ss.str();
}
return false;
}
greatest_v_idx = greatest_v_idx > vi.v_idx ? greatest_v_idx : vi.v_idx;
greatest_vn_idx =
greatest_vn_idx > vi.vn_idx ? greatest_vn_idx : vi.vn_idx;
greatest_vt_idx =
greatest_vt_idx > vi.vt_idx ? greatest_vt_idx : vi.vt_idx;
face.vertex_indices.push_back(vi);
size_t n = strspn(token, " \t\r");
token += n;
}
// replace with emplace_back + std::move on C++11
prim_group.faceGroup.push_back(face);
continue;
}
// use mtl
if ((0 == strncmp(token, "usemtl", 6))) {
token += 6;
std::string namebuf = parseString(&token);
int newMaterialId = -1;
std::map<std::string, int>::const_iterator it =
material_map.find(namebuf);
if (it != material_map.end()) {
newMaterialId = it->second;
}
else {
// { error!! material not found }
if (warn) {
(*warn) += "material [ '" + namebuf + "' ] not found in .mtl\n";
}
}
if (newMaterialId != material) {
// Create per-face material. Thus we don't add `shape` to `shapes` at
// this time.
// just clear `faceGroup` after `exportGroupsToShape()` call.
exportGroupsToShape(&shape, prim_group, tags, material, name,
triangulate, v, warn);
prim_group.faceGroup.clear();
material = newMaterialId;
}
continue;
}
// load mtl
if ((0 == strncmp(token, "mtllib", 6)) && IS_SPACE((token[6]))) {
if (readMatFn) {
token += 7;
std::vector<std::string> filenames;
SplitString(std::string(token), ' ', '\\', filenames);
if (filenames.empty()) {
if (warn) {
std::stringstream ss;
ss << "Looks like empty filename for mtllib. Use default "
"material (line "
<< line_num << ".)\n";
(*warn) += ss.str();
}
}
else {
bool found = false;
for (size_t s = 0; s < filenames.size(); s++) {
std::string warn_mtl;
std::string err_mtl;
bool ok = (*readMatFn)(filenames[s].c_str(), materials,
&material_map, &warn_mtl, &err_mtl);
if (warn && (!warn_mtl.empty())) {
(*warn) += warn_mtl;
}
if (err && (!err_mtl.empty())) {
(*err) += err_mtl;
}
if (ok) {
found = true;
break;
}
}
if (!found) {
if (warn) {
(*warn) +=
"Failed to load material file(s). Use default "
"material.\n";
}
}
}
}
continue;
}
// group name
if (token[0] == 'g' && IS_SPACE((token[1]))) {
// flush previous face group.
bool ret = exportGroupsToShape(&shape, prim_group, tags, material, name,
triangulate, v, warn);
(void)ret; // return value not used.
if (shape.mesh.indices.size() > 0) {
shapes->push_back(shape);
}
shape = shape_t();
// material = -1;
prim_group.clear();
std::vector<std::string> names;
while (!IS_NEW_LINE(token[0])) {
std::string str = parseString(&token);
names.push_back(str);
token += strspn(token, " \t\r"); // skip tag
}
// names[0] must be 'g'
if (names.size() < 2) {
// 'g' with empty names
if (warn) {
std::stringstream ss;
ss << "Empty group name. line: " << line_num << "\n";
(*warn) += ss.str();
name = "";
}
}
else {
std::stringstream ss;
ss << names[1];
// tinyobjloader does not support multiple groups for a primitive.
// Currently we concatinate multiple group names with a space to get
// single group name.
for (size_t i = 2; i < names.size(); i++) {
ss << " " << names[i];
}
name = ss.str();
}
continue;
}
// object name
if (token[0] == 'o' && IS_SPACE((token[1]))) {
// flush previous face group.
bool ret = exportGroupsToShape(&shape, prim_group, tags, material, name,
triangulate, v, warn);
(void)ret; // return value not used.
if (shape.mesh.indices.size() > 0 || shape.lines.indices.size() > 0 ||
shape.points.indices.size() > 0) {
shapes->push_back(shape);
}
// material = -1;
prim_group.clear();
shape = shape_t();
// @todo { multiple object name? }
token += 2;
std::stringstream ss;
ss << token;
name = ss.str();
continue;
}
if (token[0] == 't' && IS_SPACE(token[1])) {
const int max_tag_nums = 8192; // FIXME(syoyo): Parameterize.
tag_t tag;
token += 2;
tag.name = parseString(&token);
tag_sizes ts = parseTagTriple(&token);
if (ts.num_ints < 0) {
ts.num_ints = 0;
}
if (ts.num_ints > max_tag_nums) {
ts.num_ints = max_tag_nums;
}
if (ts.num_reals < 0) {
ts.num_reals = 0;
}
if (ts.num_reals > max_tag_nums) {
ts.num_reals = max_tag_nums;
}
if (ts.num_strings < 0) {
ts.num_strings = 0;
}
if (ts.num_strings > max_tag_nums) {
ts.num_strings = max_tag_nums;
}
tag.intValues.resize(static_cast<size_t>(ts.num_ints));
for (size_t i = 0; i < static_cast<size_t>(ts.num_ints); ++i) {
tag.intValues[i] = parseInt(&token);
}
tag.floatValues.resize(static_cast<size_t>(ts.num_reals));
for (size_t i = 0; i < static_cast<size_t>(ts.num_reals); ++i) {
tag.floatValues[i] = parseReal(&token);
}
tag.stringValues.resize(static_cast<size_t>(ts.num_strings));
for (size_t i = 0; i < static_cast<size_t>(ts.num_strings); ++i) {
tag.stringValues[i] = parseString(&token);
}
tags.push_back(tag);
continue;
}
if (token[0] == 's' && IS_SPACE(token[1])) {
// smoothing group id
token += 2;
// skip space.
token += strspn(token, " \t"); // skip space
if (token[0] == '\0') {
continue;
}
if (token[0] == '\r' || token[1] == '\n') {
continue;
}
if (strlen(token) >= 3 && token[0] == 'o' && token[1] == 'f' &&
token[2] == 'f') {
current_smoothing_id = 0;
}
else {
// assume number
int smGroupId = parseInt(&token);
if (smGroupId < 0) {
// parse error. force set to 0.
// FIXME(syoyo): Report warning.
current_smoothing_id = 0;
}
else {
current_smoothing_id = static_cast<unsigned int>(smGroupId);
}
}
continue;
} // smoothing group id
// Ignore unknown command.
}
// not all vertices have colors, no default colors desired? -> clear colors
if (!found_all_colors && !default_vcols_fallback) {
vc.clear();
}
if (greatest_v_idx >= static_cast<int>(v.size() / 3)) {
if (warn) {
std::stringstream ss;
ss << "Vertex indices out of bounds (line " << line_num << ".)\n"
<< std::endl;
(*warn) += ss.str();
}
}
if (greatest_vn_idx >= static_cast<int>(vn.size() / 3)) {
if (warn) {
std::stringstream ss;
ss << "Vertex normal indices out of bounds (line " << line_num << ".)\n"
<< std::endl;
(*warn) += ss.str();
}
}
if (greatest_vt_idx >= static_cast<int>(vt.size() / 2)) {
if (warn) {
std::stringstream ss;
ss << "Vertex texcoord indices out of bounds (line " << line_num << ".)\n"
<< std::endl;
(*warn) += ss.str();
}
}
bool ret = exportGroupsToShape(&shape, prim_group, tags, material, name,
triangulate, v, warn);
// exportGroupsToShape return false when `usemtl` is called in the last
// line.
// we also add `shape` to `shapes` when `shape.mesh` has already some
// faces(indices)
if (ret || shape.mesh.indices
.size()) { // FIXME(syoyo): Support other prims(e.g. lines)
shapes->push_back(shape);
}
prim_group.clear(); // for safety
if (err) {
(*err) += errss.str();
}
attrib->vertices.swap(v);
attrib->vertex_weights.swap(v);
attrib->normals.swap(vn);
attrib->texcoords.swap(vt);
attrib->texcoord_ws.swap(vt);
attrib->colors.swap(vc);
attrib->skin_weights.swap(vw);
return true;
}
bool LoadObjWithCallback(std::istream& inStream, const callback_t& callback,
void* user_data /*= NULL*/,
MaterialReader* readMatFn /*= NULL*/,
std::string* warn, /* = NULL*/
std::string* err /*= NULL*/) {
std::stringstream errss;
// material
std::map<std::string, int> material_map;
int material_id = -1; // -1 = invalid
std::vector<index_t> indices;
std::vector<material_t> materials;
std::vector<std::string> names;
names.reserve(2);
std::vector<const char*> names_out;
std::string linebuf;
while (inStream.peek() != -1) {
safeGetline(inStream, linebuf);
// Trim newline '\r\n' or '\n'
if (linebuf.size() > 0) {
if (linebuf[linebuf.size() - 1] == '\n')
linebuf.erase(linebuf.size() - 1);
}
if (linebuf.size() > 0) {
if (linebuf[linebuf.size() - 1] == '\r')
linebuf.erase(linebuf.size() - 1);
}
// Skip if empty line.
if (linebuf.empty()) {
continue;
}
// Skip leading space.
const char* token = linebuf.c_str();
token += strspn(token, " \t");
assert(token);
if (token[0] == '\0') continue; // empty line
if (token[0] == '#') continue; // comment line
// vertex
if (token[0] == 'v' && IS_SPACE((token[1]))) {
token += 2;
// TODO(syoyo): Support parsing vertex color extension.
real_t x, y, z, w; // w is optional. default = 1.0
parseV(&x, &y, &z, &w, &token);
if (callback.vertex_cb) {
callback.vertex_cb(user_data, x, y, z, w);
}
continue;
}
// normal
if (token[0] == 'v' && token[1] == 'n' && IS_SPACE((token[2]))) {
token += 3;
real_t x, y, z;
parseReal3(&x, &y, &z, &token);
if (callback.normal_cb) {
callback.normal_cb(user_data, x, y, z);
}
continue;
}
// texcoord
if (token[0] == 'v' && token[1] == 't' && IS_SPACE((token[2]))) {
token += 3;
real_t x, y, z; // y and z are optional. default = 0.0
parseReal3(&x, &y, &z, &token);
if (callback.texcoord_cb) {
callback.texcoord_cb(user_data, x, y, z);
}
continue;
}
// face
if (token[0] == 'f' && IS_SPACE((token[1]))) {
token += 2;
token += strspn(token, " \t");
indices.clear();
while (!IS_NEW_LINE(token[0])) {
vertex_index_t vi = parseRawTriple(&token);
index_t idx;
idx.vertex_index = vi.v_idx;
idx.normal_index = vi.vn_idx;
idx.texcoord_index = vi.vt_idx;
indices.push_back(idx);
size_t n = strspn(token, " \t\r");
token += n;
}
if (callback.index_cb && indices.size() > 0) {
callback.index_cb(user_data, &indices.at(0),
static_cast<int>(indices.size()));
}
continue;
}
// use mtl
if ((0 == strncmp(token, "usemtl", 6)) && IS_SPACE((token[6]))) {
token += 7;
std::stringstream ss;
ss << token;
std::string namebuf = ss.str();
int newMaterialId = -1;
std::map<std::string, int>::const_iterator it =
material_map.find(namebuf);
if (it != material_map.end()) {
newMaterialId = it->second;
}
else {
// { warn!! material not found }
if (warn && (!callback.usemtl_cb)) {
(*warn) += "material [ " + namebuf + " ] not found in .mtl\n";
}
}
if (newMaterialId != material_id) {
material_id = newMaterialId;
}
if (callback.usemtl_cb) {
callback.usemtl_cb(user_data, namebuf.c_str(), material_id);
}
continue;
}
// load mtl
if ((0 == strncmp(token, "mtllib", 6)) && IS_SPACE((token[6]))) {
if (readMatFn) {
token += 7;
std::vector<std::string> filenames;
SplitString(std::string(token), ' ', '\\', filenames);
if (filenames.empty()) {
if (warn) {
(*warn) +=
"Looks like empty filename for mtllib. Use default "
"material. \n";
}
}
else {
bool found = false;
for (size_t s = 0; s < filenames.size(); s++) {
std::string warn_mtl;
std::string err_mtl;
bool ok = (*readMatFn)(filenames[s].c_str(), &materials,
&material_map, &warn_mtl, &err_mtl);
if (warn && (!warn_mtl.empty())) {
(*warn) += warn_mtl; // This should be warn message.
}
if (err && (!err_mtl.empty())) {
(*err) += err_mtl;
}
if (ok) {
found = true;
break;
}
}
if (!found) {
if (warn) {
(*warn) +=
"Failed to load material file(s). Use default "
"material.\n";
}
}
else {
if (callback.mtllib_cb) {
callback.mtllib_cb(user_data, &materials.at(0),
static_cast<int>(materials.size()));
}
}
}
}
continue;
}
// group name
if (token[0] == 'g' && IS_SPACE((token[1]))) {
names.clear();
while (!IS_NEW_LINE(token[0])) {
std::string str = parseString(&token);
names.push_back(str);
token += strspn(token, " \t\r"); // skip tag
}
assert(names.size() > 0);
if (callback.group_cb) {
if (names.size() > 1) {
// create const char* array.
names_out.resize(names.size() - 1);
for (size_t j = 0; j < names_out.size(); j++) {
names_out[j] = names[j + 1].c_str();
}
callback.group_cb(user_data, &names_out.at(0),
static_cast<int>(names_out.size()));
}
else {
callback.group_cb(user_data, NULL, 0);
}
}
continue;
}
// object name
if (token[0] == 'o' && IS_SPACE((token[1]))) {
// @todo { multiple object name? }
token += 2;
std::stringstream ss;
ss << token;
std::string object_name = ss.str();
if (callback.object_cb) {
callback.object_cb(user_data, object_name.c_str());
}
continue;
}
#if 0 // @todo
if (token[0] == 't' && IS_SPACE(token[1])) {
tag_t tag;
token += 2;
std::stringstream ss;
ss << token;
tag.name = ss.str();
token += tag.name.size() + 1;
tag_sizes ts = parseTagTriple(&token);
tag.intValues.resize(static_cast<size_t>(ts.num_ints));
for (size_t i = 0; i < static_cast<size_t>(ts.num_ints); ++i) {
tag.intValues[i] = atoi(token);
token += strcspn(token, "/ \t\r") + 1;
}
tag.floatValues.resize(static_cast<size_t>(ts.num_reals));
for (size_t i = 0; i < static_cast<size_t>(ts.num_reals); ++i) {
tag.floatValues[i] = parseReal(&token);
token += strcspn(token, "/ \t\r") + 1;
}
tag.stringValues.resize(static_cast<size_t>(ts.num_strings));
for (size_t i = 0; i < static_cast<size_t>(ts.num_strings); ++i) {
std::stringstream ss;
ss << token;
tag.stringValues[i] = ss.str();
token += tag.stringValues[i].size() + 1;
}
tags.push_back(tag);
}
#endif
// Ignore unknown command.
}
if (err) {
(*err) += errss.str();
}
return true;
}
bool ObjReader::ParseFromFile(const std::string& filename,
const ObjReaderConfig& config) {
std::string mtl_search_path;
if (config.mtl_search_path.empty()) {
//
// split at last '/'(for unixish system) or '\\'(for windows) to get
// the base directory of .obj file
//
size_t pos = filename.find_last_of("/\\");
if (pos != std::string::npos) {
mtl_search_path = filename.substr(0, pos);
}
}
else {
mtl_search_path = config.mtl_search_path;
}
valid_ = LoadObj(&attrib_, &shapes_, &materials_, &warning_, &error_,
filename.c_str(), mtl_search_path.c_str(),
config.triangulate, config.vertex_color);
return valid_;
}
bool ObjReader::ParseFromString(const std::string& obj_text,
const std::string& mtl_text,
const ObjReaderConfig& config) {
std::stringbuf obj_buf(obj_text);
std::stringbuf mtl_buf(mtl_text);
std::istream obj_ifs(&obj_buf);
std::istream mtl_ifs(&mtl_buf);
MaterialStreamReader mtl_ss(mtl_ifs);
valid_ = LoadObj(&attrib_, &shapes_, &materials_, &warning_, &error_,
&obj_ifs, &mtl_ss, config.triangulate, config.vertex_color);
return valid_;
}
#ifdef __clang__
#pragma clang diagnostic pop
#endif
} // namespace tinyobj
#endif
|
[
"ryan-wende@outlook.com"
] |
ryan-wende@outlook.com
|
1e877ae6351c9ca2863ad0851a89372d1d10d79d
|
a720e508022ea15fcfd7aa311b596aaf68cc56b8
|
/HW2/Homework2.3.cpp
|
64a342cd6fc984da8760b57d6bdbb02559250bc8
|
[] |
no_license
|
yterry/MF703_CPP_Projects
|
29b52c4a9fd7710071191da22273cd0e61f8d6e2
|
8358dc604b562af461b46a7ae44387c471a4a5c8
|
refs/heads/master
| 2021-01-09T21:48:19.549624
| 2016-02-05T02:08:29
| 2016-02-05T02:08:29
| 51,119,954
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,344
|
cpp
|
// Homework2.3.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "iostream"
#include "vector"
using namespace std;
//function reverseDigits
//takes an integer value and returns the number with its digits reversed
int reverseDigits(long int num) {
long int n = 1;//counts number of digits
long int deno = 10;//denominator
long int quotient;
long int i;
long int reverse=0;
vector<int> v;//stores every digit
bool t = true;//boolean value
while (t) {
quotient = num / deno;
deno = deno * 10;
if (quotient == 0) {
t = false;
}
else {
n += 1;
}
}
//store each digit to vector v
for (i = 0; i < n;i++) {
quotient = num / pow(10, n - i - 1);
v.push_back(quotient);
num = num - quotient*pow(10, n - i - 1);
}
//rearrange the digits
for (i = 0; i < n; i++) {
reverse += v[i] * pow(10, i);
}
return reverse;
}
int driver()
{
//ask the user to input number to be reversed
bool t = true;
while (t) {
long int num;
long int b;
cout << "Please enter a number to be reversed: ";
cin >> num;
cout << "\n";
cout << "This is the reversed number :" << reverseDigits(num) << "\n";
cout << "Do you want to compute another number ? (-1 to exit): ";
cin >> b;
cout << "\n";
if (b == -1)t = false;
}
return 0;
}
int main() {
driver();
return 0;
}
|
[
"yterry@bu.edu"
] |
yterry@bu.edu
|
833fcda85fe69da76ef2424e0bc0a0f2dd1a84c9
|
8200cae3d64bc7e05f5033c70f31717d7592302b
|
/libraries/touchgfx_lib/TouchGFX/generated/fonts/src/Font_simkai_30_4bpp_9.cpp
|
e8a5c0f594a792fcbd7a0e12744e10b9566f24dd
|
[] |
no_license
|
yixiangwenhai/Wisdom-agriculture_RTT
|
05598a44fd18e1358279034cb5c74d4d97ad7c15
|
42f9395786e814e9d5348fcaefa57c0ad1f176a4
|
refs/heads/master
| 2023-09-01T04:31:34.083477
| 2021-09-28T10:28:38
| 2021-09-28T10:28:38
| 411,233,186
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,677
|
cpp
|
#include <touchgfx/hal/Types.hpp>
FONT_GLYPH_LOCATION_FLASH_PRAGMA
KEEP extern const uint8_t unicodes_simkai_30_4bpp_9[] FONT_GLYPH_LOCATION_FLASH_ATTRIBUTE =
{
// Unicode: [0x4E8C]
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x41, 0xA7, 0x7B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x10, 0x44, 0x65, 0x98, 0xEC, 0xFF, 0xFF, 0xEF, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0xFC,
0xFF, 0xEF, 0x9B, 0x57, 0x34, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x50, 0x58, 0x02,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x20, 0x74, 0xB9, 0xCD, 0x19, 0x00, 0x00, 0x00, 0x00, 0x00, 0x32, 0x75, 0xA8, 0xEC, 0xFF, 0xFF,
0xFF, 0xFF, 0xDF, 0x01, 0xA6, 0xBA, 0xDC, 0xFE, 0xFF, 0xFF, 0xDF, 0xBC, 0x89, 0x77, 0x66, 0x87,
0xA9, 0x04, 0x81, 0xFE, 0xDF, 0x9B, 0x57, 0x13, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x20, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
|
[
"921036028@qq.com"
] |
921036028@qq.com
|
4520f343c082ebec51fdb866b60efd9ad6106dbb
|
4f72aa73fd32b64f68ac837fa15f77d95b313550
|
/src/qt/sendcoinsentry.cpp
|
79dc4fb39df26b34606c70c67fe962143e6cead9
|
[
"MIT"
] |
permissive
|
wecarecoin/wecarecoin
|
1ca2925b9d5f9304c675c4d6fa5d69afa0055f73
|
60f9eaa6c9bc7e996ef99a03e615403bff59ac70
|
refs/heads/master
| 2021-04-28T04:40:10.130141
| 2018-02-20T07:51:21
| 2018-02-20T07:51:21
| 122,165,953
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,294
|
cpp
|
#include "sendcoinsentry.h"
#include "ui_sendcoinsentry.h"
#include "guiutil.h"
#include "bitcoinunits.h"
#include "addressbookpage.h"
#include "walletmodel.h"
#include "optionsmodel.h"
#include "addresstablemodel.h"
#include <QApplication>
#include <QClipboard>
SendCoinsEntry::SendCoinsEntry(QWidget *parent) :
QFrame(parent),
ui(new Ui::SendCoinsEntry),
model(0)
{
ui->setupUi(this);
#ifdef Q_OS_MAC
ui->payToLayout->setSpacing(4);
#endif
#if QT_VERSION >= 0x040700
/* Do not move this to the XML file, Qt before 4.7 will choke on it */
ui->addAsLabel->setPlaceholderText(tr("Enter a label for this address to add it to your address book"));
ui->payTo->setPlaceholderText(tr("Enter a wecare address (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)"));
#endif
setFocusPolicy(Qt::TabFocus);
setFocusProxy(ui->payTo);
GUIUtil::setupAddressWidget(ui->payTo, this);
}
SendCoinsEntry::~SendCoinsEntry()
{
delete ui;
}
void SendCoinsEntry::on_pasteButton_clicked()
{
// Paste text from clipboard into recipient field
ui->payTo->setText(QApplication::clipboard()->text());
}
void SendCoinsEntry::on_addressBookButton_clicked()
{
if(!model)
return;
AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::SendingTab, this);
dlg.setModel(model->getAddressTableModel());
if(dlg.exec())
{
ui->payTo->setText(dlg.getReturnValue());
ui->payAmount->setFocus();
}
}
void SendCoinsEntry::on_payTo_textChanged(const QString &address)
{
if(!model)
return;
// Fill in label from address book, if address has an associated label
QString associatedLabel = model->getAddressTableModel()->labelForAddress(address);
if(!associatedLabel.isEmpty())
ui->addAsLabel->setText(associatedLabel);
}
void SendCoinsEntry::setModel(WalletModel *model)
{
this->model = model;
if(model && model->getOptionsModel())
connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
connect(ui->payAmount, SIGNAL(textChanged()), this, SIGNAL(payAmountChanged()));
clear();
}
void SendCoinsEntry::setRemoveEnabled(bool enabled)
{
ui->deleteButton->setEnabled(enabled);
}
void SendCoinsEntry::clear()
{
ui->payTo->clear();
ui->addAsLabel->clear();
ui->payAmount->clear();
ui->payTo->setFocus();
// update the display unit, to not use the default ("BTC")
updateDisplayUnit();
}
void SendCoinsEntry::on_deleteButton_clicked()
{
emit removeEntry(this);
}
bool SendCoinsEntry::validate()
{
// Check input validity
bool retval = true;
if(!ui->payAmount->validate())
{
retval = false;
}
else
{
if(ui->payAmount->value() <= 0)
{
// Cannot send 0 coins or less
ui->payAmount->setValid(false);
retval = false;
}
}
if(!ui->payTo->hasAcceptableInput() ||
(model && !model->validateAddress(ui->payTo->text())))
{
ui->payTo->setValid(false);
retval = false;
}
return retval;
}
SendCoinsRecipient SendCoinsEntry::getValue()
{
SendCoinsRecipient rv;
rv.address = ui->payTo->text();
rv.label = ui->addAsLabel->text();
rv.amount = ui->payAmount->value();
return rv;
}
QWidget *SendCoinsEntry::setupTabChain(QWidget *prev)
{
QWidget::setTabOrder(prev, ui->payTo);
QWidget::setTabOrder(ui->payTo, ui->addressBookButton);
QWidget::setTabOrder(ui->addressBookButton, ui->pasteButton);
QWidget::setTabOrder(ui->pasteButton, ui->deleteButton);
QWidget::setTabOrder(ui->deleteButton, ui->addAsLabel);
return ui->payAmount->setupTabChain(ui->addAsLabel);
}
void SendCoinsEntry::setValue(const SendCoinsRecipient &value)
{
ui->payTo->setText(value.address);
ui->addAsLabel->setText(value.label);
ui->payAmount->setValue(value.amount);
}
bool SendCoinsEntry::isClear()
{
return ui->payTo->text().isEmpty();
}
void SendCoinsEntry::setFocus()
{
ui->payTo->setFocus();
}
void SendCoinsEntry::updateDisplayUnit()
{
if(model && model->getOptionsModel())
{
// Update payAmount with the current unit
ui->payAmount->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
}
}
|
[
"34125545+wecarecoin@users.noreply.github.com"
] |
34125545+wecarecoin@users.noreply.github.com
|
e3f91300ffb6a8296824d81f7e2d039b4dbb8d4b
|
9824d607fab0a0a827abff255865f320e2a7a692
|
/界面资源/[XTreme.Toolkit.9.6.MFC].Xtreme.Toolkit.Pro.v9.60/Samples/Common/MultiLanguage/MultiLanguageDoc.cpp
|
ead1ac329f5c39f5fe2b34ba516c7a6b16d84ba3
|
[] |
no_license
|
tuian/pcshare
|
013b24af954b671aaf98604d6ab330def675a561
|
5d6455226d9720d65cfce841f8d00ef9eb09a5b8
|
refs/heads/master
| 2021-01-23T19:16:44.227266
| 2014-09-18T02:31:05
| 2014-09-18T02:31:05
| null | 0
| 0
| null | null | null | null |
WINDOWS-1252
|
C++
| false
| false
| 2,514
|
cpp
|
// MultiLanguageDoc.cpp : implementation of the CMultiLanguageDoc class
//
// This file is a part of the XTREME TOOLKIT PRO MFC class library.
// ©1998-2005 Codejock Software, All Rights Reserved.
//
// THIS SOURCE FILE IS THE PROPERTY OF CODEJOCK SOFTWARE AND IS NOT TO BE
// RE-DISTRIBUTED BY ANY MEANS WHATSOEVER WITHOUT THE EXPRESSED WRITTEN
// CONSENT OF CODEJOCK SOFTWARE.
//
// THIS SOURCE CODE CAN ONLY BE USED UNDER THE TERMS AND CONDITIONS OUTLINED
// IN THE XTREME TOOLKIT PRO LICENSE AGREEMENT. CODEJOCK SOFTWARE GRANTS TO
// YOU (ONE SOFTWARE DEVELOPER) THE LIMITED RIGHT TO USE THIS SOFTWARE ON A
// SINGLE COMPUTER.
//
// CONTACT INFORMATION:
// support@codejock.com
// http://www.codejock.com
//
/////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "MultiLanguage.h"
#include "MultiLanguageDoc.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CMultiLanguageDoc
IMPLEMENT_DYNCREATE(CMultiLanguageDoc, CDocument)
BEGIN_MESSAGE_MAP(CMultiLanguageDoc, CDocument)
//{{AFX_MSG_MAP(CMultiLanguageDoc)
// NOTE - the ClassWizard will add and remove mapping macros here.
// DO NOT EDIT what you see in these blocks of generated code!
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CMultiLanguageDoc construction/destruction
CMultiLanguageDoc::CMultiLanguageDoc()
{
// TODO: add one-time construction code here
}
CMultiLanguageDoc::~CMultiLanguageDoc()
{
}
BOOL CMultiLanguageDoc::OnNewDocument()
{
if (!CDocument::OnNewDocument())
return FALSE;
// TODO: add reinitialization code here
// (SDI documents will reuse this document)
return TRUE;
}
/////////////////////////////////////////////////////////////////////////////
// CMultiLanguageDoc serialization
void CMultiLanguageDoc::Serialize(CArchive& ar)
{
if (ar.IsStoring())
{
// TODO: add storing code here
}
else
{
// TODO: add loading code here
}
}
/////////////////////////////////////////////////////////////////////////////
// CMultiLanguageDoc diagnostics
#ifdef _DEBUG
void CMultiLanguageDoc::AssertValid() const
{
CDocument::AssertValid();
}
void CMultiLanguageDoc::Dump(CDumpContext& dc) const
{
CDocument::Dump(dc);
}
#endif //_DEBUG
/////////////////////////////////////////////////////////////////////////////
// CMultiLanguageDoc commands
|
[
"sincoder@vip.qq.com"
] |
sincoder@vip.qq.com
|
8aff237ad928fc7f4f073a19ae40c83def6cbe8e
|
9b87c038a5ce9b3c0caabb35cd1b8bf44a19c1da
|
/ColdEyes/Pattern/IDataHandler.h
|
4928ffecf2840890c50ec76a82c7318ed1f28147
|
[] |
no_license
|
EmbededMind/ColdEyes
|
98d519bf80d7f090ce65338d6aae473d07b4731e
|
3cb007a76345f0f5751024b66e62a775c32de7f2
|
refs/heads/master
| 2021-01-11T08:47:14.230784
| 2017-01-05T02:05:56
| 2017-01-05T02:05:56
| 76,835,389
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 105
|
h
|
#pragma once
class IDataHandler
{
public:
virtual void HandleData(UINT8* pData, size_t length) = 0;
};
|
[
"815407069@qq.com"
] |
815407069@qq.com
|
c08c365aed66ee1744b63aebd0aef8516a4e898c
|
ca4b4c9ae9497f0e20a33ba883c66e7f3d5bab53
|
/JetStudies/16663_CompressedMoneyPlot/MakeMoneyPlotTry4.cpp
|
3d7ce1d4538aa21eb5d5fb781a9726a41cbcb231
|
[] |
no_license
|
FHead/PhysicsHIJetMass
|
79c0dd7a0019b0198803af64dfc7a4753b7a9174
|
7cb8c27aa1c89593986a90a2b68ddcc991806c00
|
refs/heads/master
| 2023-05-31T07:52:24.263711
| 2021-06-16T09:00:35
| 2021-06-16T09:00:35
| 377,433,346
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 32,277
|
cpp
|
#include <iostream>
#include <vector>
using namespace std;
#include "TCanvas.h"
#include "TH1D.h"
#include "TGraphAsymmErrors.h"
#include "TPad.h"
#include "TGaxis.h"
#include "TLine.h"
#include "TLatex.h"
#include "TLegend.h"
#include "PlotHelper3.h"
#define SD0_PT 0
#define SD0_CENTRALITY 1
#define SD7_PT 2
#define SD7_CENTRALITY 3
int main();
void MakePlot(vector<TGraphAsymmErrors *> G, vector<TGraphAsymmErrors *> T, string OutputBase, int Preset = SD0_PT);
bool DivideAndShift(vector<TGraphAsymmErrors *> &G, vector<TGraphAsymmErrors *> &R, double YShift, double RShift);
bool DivideAndShiftTheory(vector<TGraphAsymmErrors *> &T, vector<TGraphAsymmErrors *> &R, double YShift, double RShift);
void Division(TGraphAsymmErrors *G1, TGraphAsymmErrors *G2, TGraphAsymmErrors *GRatio);
void ShiftUp(TGraphAsymmErrors *G, double Amount);
TGraphAsymmErrors *HistogramToGraph(TH1D *H);
int main()
{
TFile F0("Graphs_SD0_DataCentered.root");
TFile F7("Graphs_SD7_DataCentered.root");
TFile FT0("PickedPlots_SD0.root");
TFile FT7("PickedPlots_SD7.root");
vector<TGraphAsymmErrors *> G(16);
vector<TGraphAsymmErrors *> T(24);
G[0] = (TGraphAsymmErrors *)F0.Get("MassData0_0_1")->Clone();
G[1] = (TGraphAsymmErrors *)F0.Get("MassDataSys0_0_1")->Clone();
G[2] = (TGraphAsymmErrors *)F0.Get("MassSmear0_0_1")->Clone();
G[3] = (TGraphAsymmErrors *)F0.Get("MassSmearSys0_0_1")->Clone();
G[4] = (TGraphAsymmErrors *)F0.Get("MassData0_0_2")->Clone();
G[5] = (TGraphAsymmErrors *)F0.Get("MassDataSys0_0_2")->Clone();
G[6] = (TGraphAsymmErrors *)F0.Get("MassSmear0_0_2")->Clone();
G[7] = (TGraphAsymmErrors *)F0.Get("MassSmearSys0_0_2")->Clone();
G[8] = (TGraphAsymmErrors *)F0.Get("MassData0_0_3")->Clone();
G[9] = (TGraphAsymmErrors *)F0.Get("MassDataSys0_0_3")->Clone();
G[10] = (TGraphAsymmErrors *)F0.Get("MassSmear0_0_3")->Clone();
G[11] = (TGraphAsymmErrors *)F0.Get("MassSmearSys0_0_3")->Clone();
G[12] = (TGraphAsymmErrors *)F0.Get("MassData0_0_4")->Clone();
G[13] = (TGraphAsymmErrors *)F0.Get("MassDataSys0_0_4")->Clone();
G[14] = (TGraphAsymmErrors *)F0.Get("MassSmear0_0_4")->Clone();
G[15] = (TGraphAsymmErrors *)F0.Get("MassSmearSys0_0_4")->Clone();
T[0] = HistogramToGraph((TH1D *)FT0.Get("JewelOffSB_C0PT1"));
T[1] = HistogramToGraph((TH1D *)FT0.Get("JewelVacSB_C0PT1"));
T[2] = HistogramToGraph((TH1D *)FT0.Get("JewelOnS_C0PT1"));
T[3] = HistogramToGraph((TH1D *)FT0.Get("JewelVacS_C0PT1"));
T[4] = HistogramToGraph((TH1D *)FT0.Get("QPythiaMedSB_C0PT1"));
T[5] = HistogramToGraph((TH1D *)FT0.Get("QPythiaVacSB_C0PT1"));
T[6] = HistogramToGraph((TH1D *)FT0.Get("JewelOffSB_C0PT2"));
T[7] = HistogramToGraph((TH1D *)FT0.Get("JewelVacSB_C0PT2"));
T[8] = HistogramToGraph((TH1D *)FT0.Get("JewelOnS_C0PT2"));
T[9] = HistogramToGraph((TH1D *)FT0.Get("JewelVacS_C0PT2"));
T[10] = HistogramToGraph((TH1D *)FT0.Get("QPythiaMedSB_C0PT2"));
T[11] = HistogramToGraph((TH1D *)FT0.Get("QPythiaVacSB_C0PT2"));
T[12] = HistogramToGraph((TH1D *)FT0.Get("JewelOffSB_C0PT3"));
T[13] = HistogramToGraph((TH1D *)FT0.Get("JewelVacSB_C0PT3"));
T[14] = HistogramToGraph((TH1D *)FT0.Get("JewelOnS_C0PT3"));
T[15] = HistogramToGraph((TH1D *)FT0.Get("JewelVacS_C0PT3"));
T[16] = HistogramToGraph((TH1D *)FT0.Get("QPythiaMedSB_C0PT3"));
T[17] = HistogramToGraph((TH1D *)FT0.Get("QPythiaVacSB_C0PT3"));
T[18] = HistogramToGraph((TH1D *)FT0.Get("JewelOffSB_C0PT4"));
T[19] = HistogramToGraph((TH1D *)FT0.Get("JewelVacSB_C0PT4"));
T[20] = HistogramToGraph((TH1D *)FT0.Get("JewelOnS_C0PT4"));
T[21] = HistogramToGraph((TH1D *)FT0.Get("JewelVacS_C0PT4"));
T[22] = HistogramToGraph((TH1D *)FT0.Get("QPythiaMedSB_C0PT4"));
T[23] = HistogramToGraph((TH1D *)FT0.Get("QPythiaVacSB_C0PT4"));
MakePlot(G, T, "Plots/SD0_CBin0", SD0_PT);
G[0] = (TGraphAsymmErrors *)F7.Get("MassData_0_1")->Clone();
G[1] = (TGraphAsymmErrors *)F7.Get("MassDataSys_0_1")->Clone();
G[2] = (TGraphAsymmErrors *)F7.Get("MassSmear_0_1")->Clone();
G[3] = (TGraphAsymmErrors *)F7.Get("MassSmearSys_0_1")->Clone();
G[4] = (TGraphAsymmErrors *)F7.Get("MassData_0_2")->Clone();
G[5] = (TGraphAsymmErrors *)F7.Get("MassDataSys_0_2")->Clone();
G[6] = (TGraphAsymmErrors *)F7.Get("MassSmear_0_2")->Clone();
G[7] = (TGraphAsymmErrors *)F7.Get("MassSmearSys_0_2")->Clone();
G[8] = (TGraphAsymmErrors *)F7.Get("MassData_0_3")->Clone();
G[9] = (TGraphAsymmErrors *)F7.Get("MassDataSys_0_3")->Clone();
G[10] = (TGraphAsymmErrors *)F7.Get("MassSmear_0_3")->Clone();
G[11] = (TGraphAsymmErrors *)F7.Get("MassSmearSys_0_3")->Clone();
G[12] = (TGraphAsymmErrors *)F7.Get("MassData_0_4")->Clone();
G[13] = (TGraphAsymmErrors *)F7.Get("MassDataSys_0_4")->Clone();
G[14] = (TGraphAsymmErrors *)F7.Get("MassSmear_0_4")->Clone();
G[15] = (TGraphAsymmErrors *)F7.Get("MassSmearSys_0_4")->Clone();
T[0] = HistogramToGraph((TH1D *)FT7.Get("JewelOffS_C0PT1"));
T[1] = HistogramToGraph((TH1D *)FT7.Get("JewelVacS_C0PT1"));
T[2] = HistogramToGraph((TH1D *)FT7.Get("JewelOnS_C0PT1"));
T[3] = HistogramToGraph((TH1D *)FT7.Get("JewelVacS_C0PT1"));
T[4] = HistogramToGraph((TH1D *)FT7.Get("QPythiaMedS_C0PT1"));
T[5] = HistogramToGraph((TH1D *)FT7.Get("QPythiaVacS_C0PT1"));
T[6] = HistogramToGraph((TH1D *)FT7.Get("JewelOffS_C0PT2"));
T[7] = HistogramToGraph((TH1D *)FT7.Get("JewelVacS_C0PT2"));
T[8] = HistogramToGraph((TH1D *)FT7.Get("JewelOnS_C0PT2"));
T[9] = HistogramToGraph((TH1D *)FT7.Get("JewelVacS_C0PT2"));
T[10] = HistogramToGraph((TH1D *)FT7.Get("QPythiaMedS_C0PT2"));
T[11] = HistogramToGraph((TH1D *)FT7.Get("QPythiaVacS_C0PT2"));
T[12] = HistogramToGraph((TH1D *)FT7.Get("JewelOffS_C0PT3"));
T[13] = HistogramToGraph((TH1D *)FT7.Get("JewelVacS_C0PT3"));
T[14] = HistogramToGraph((TH1D *)FT7.Get("JewelOnS_C0PT3"));
T[15] = HistogramToGraph((TH1D *)FT7.Get("JewelVacS_C0PT3"));
T[16] = HistogramToGraph((TH1D *)FT7.Get("QPythiaMedS_C0PT3"));
T[17] = HistogramToGraph((TH1D *)FT7.Get("QPythiaVacS_C0PT3"));
T[18] = HistogramToGraph((TH1D *)FT7.Get("JewelOffS_C0PT4"));
T[19] = HistogramToGraph((TH1D *)FT7.Get("JewelVacS_C0PT4"));
T[20] = HistogramToGraph((TH1D *)FT7.Get("JewelOnS_C0PT4"));
T[21] = HistogramToGraph((TH1D *)FT7.Get("JewelVacS_C0PT4"));
T[22] = HistogramToGraph((TH1D *)FT7.Get("QPythiaMedS_C0PT4"));
T[23] = HistogramToGraph((TH1D *)FT7.Get("QPythiaVacS_C0PT4"));
MakePlot(G, T, "Plots/SD7_CBin0", SD7_PT);
G[0] = (TGraphAsymmErrors *)F0.Get("MassData0_0_2")->Clone();
G[1] = (TGraphAsymmErrors *)F0.Get("MassDataSys0_0_2")->Clone();
G[2] = (TGraphAsymmErrors *)F0.Get("MassSmear0_0_2")->Clone();
G[3] = (TGraphAsymmErrors *)F0.Get("MassSmearSys0_0_2")->Clone();
G[4] = (TGraphAsymmErrors *)F0.Get("MassData0_1_2")->Clone();
G[5] = (TGraphAsymmErrors *)F0.Get("MassDataSys0_1_2")->Clone();
G[6] = (TGraphAsymmErrors *)F0.Get("MassSmear0_1_2")->Clone();
G[7] = (TGraphAsymmErrors *)F0.Get("MassSmearSys0_1_2")->Clone();
G[8] = (TGraphAsymmErrors *)F0.Get("MassData0_2_2")->Clone();
G[9] = (TGraphAsymmErrors *)F0.Get("MassDataSys0_2_2")->Clone();
G[10] = (TGraphAsymmErrors *)F0.Get("MassSmear0_2_2")->Clone();
G[11] = (TGraphAsymmErrors *)F0.Get("MassSmearSys0_2_2")->Clone();
G[12] = (TGraphAsymmErrors *)F0.Get("MassData0_3_2")->Clone();
G[13] = (TGraphAsymmErrors *)F0.Get("MassDataSys0_3_2")->Clone();
G[14] = (TGraphAsymmErrors *)F0.Get("MassSmear0_3_2")->Clone();
G[15] = (TGraphAsymmErrors *)F0.Get("MassSmearSys0_3_2")->Clone();
for(int i = 0; i < 24; i++)
T[i] = NULL;
MakePlot(G, T, "Plots/SD0_PTBin2", SD0_CENTRALITY);
G[0] = (TGraphAsymmErrors *)F7.Get("MassData_0_2")->Clone();
G[1] = (TGraphAsymmErrors *)F7.Get("MassDataSys_0_2")->Clone();
G[2] = (TGraphAsymmErrors *)F7.Get("MassSmear_0_2")->Clone();
G[3] = (TGraphAsymmErrors *)F7.Get("MassSmearSys_0_2")->Clone();
G[4] = (TGraphAsymmErrors *)F7.Get("MassData_1_2")->Clone();
G[5] = (TGraphAsymmErrors *)F7.Get("MassDataSys_1_2")->Clone();
G[6] = (TGraphAsymmErrors *)F7.Get("MassSmear_1_2")->Clone();
G[7] = (TGraphAsymmErrors *)F7.Get("MassSmearSys_1_2")->Clone();
G[8] = (TGraphAsymmErrors *)F7.Get("MassData_2_2")->Clone();
G[9] = (TGraphAsymmErrors *)F7.Get("MassDataSys_2_2")->Clone();
G[10] = (TGraphAsymmErrors *)F7.Get("MassSmear_2_2")->Clone();
G[11] = (TGraphAsymmErrors *)F7.Get("MassSmearSys_2_2")->Clone();
G[12] = (TGraphAsymmErrors *)F7.Get("MassData_3_2")->Clone();
G[13] = (TGraphAsymmErrors *)F7.Get("MassDataSys_3_2")->Clone();
G[14] = (TGraphAsymmErrors *)F7.Get("MassSmear_3_2")->Clone();
G[15] = (TGraphAsymmErrors *)F7.Get("MassSmearSys_3_2")->Clone();
for(int i = 0; i < 24; i++)
T[i] = NULL;
MakePlot(G, T, "Plots/SD7_PTBin2", SD7_CENTRALITY);
FT7.Close();
FT0.Close();
F7.Close();
F0.Close();
return 0;
}
void MakePlot(vector<TGraphAsymmErrors *> G, vector<TGraphAsymmErrors *> T, string OutputBase, int Preset)
{
// Inputs: edit to your liking
double LeftMargin, RightMargin, TopMargin, BottomMargin, Height, Width;
double XMin, XMax, YMin, YMax, RMin, RMax;
double HeaderSize, BreakPointOffset, BreakPointSizeX, BreakPointSizeY, BreakPointSpacing;
double TextSpacing;
double TextYX, TextYY, TextRX, TextRY;
int TextRAlign, TextYAlign;
int AxisStyle, TopAxisStyle;
LeftMargin = 100;
RightMargin = 50;
TopMargin = 50;
BottomMargin = 75;
Height = 700;
Width = 500;
TextSpacing = 0.035;
if(Preset == SD0_PT)
{
XMin = 0.00; XMax = 0.27;
YMin = 0.00; YMax = 7.99;
RMin = 0.00; RMax = 11.99;
HeaderSize = 1.5;
BreakPointOffset = -0.07;
BreakPointSizeX = 0.020;
BreakPointSizeY = 0.004;
BreakPointSpacing = 0.003;
TextYAlign = 22;
TextYX = 0.50;
TextYY = 9.00;
TextRAlign = 22;
TextRX = 0.50;
TextRY = 4.00;
AxisStyle = 502;
TopAxisStyle = 505;
}
if(Preset == SD7_PT)
{
XMin = 0.00; XMax = 0.26;
YMin = 0.00; YMax = 19.99;
RMin = 0.00; RMax = 6.99;
HeaderSize = 1.5;
BreakPointOffset = -0.07;
BreakPointSizeX = 0.020;
BreakPointSizeY = 0.004;
BreakPointSpacing = 0.003;
TextYAlign = 22;
TextYX = 0.70;
TextYY = 5.50;
TextRAlign = 22;
TextRX = 0.50;
TextRY = 2.50;
AxisStyle = 502;
TopAxisStyle = 505;
}
if(Preset == SD0_CENTRALITY)
{
XMin = 0.00; XMax = 0.27;
YMin = 0.00; YMax = 11.99;
RMin = 0.00; RMax = 2.99;
HeaderSize = 1.5;
BreakPointOffset = -0.07;
BreakPointSizeX = 0.020;
BreakPointSizeY = 0.004;
BreakPointSpacing = 0.003;
TextYAlign = 22;
TextYX = 0.50;
TextYY = 9.50;
TextRAlign = 22;
TextRX = 0.50;
TextRY = 1.70;
AxisStyle = 502;
TopAxisStyle = 505;
}
if(Preset == SD7_CENTRALITY)
{
XMin = 0.00; XMax = 0.26;
YMin = 0.00; YMax = 19.99;
RMin = 0.00; RMax = 2.99;
HeaderSize = 1.5;
BreakPointOffset = -0.07;
BreakPointSizeX = 0.020;
BreakPointSizeY = 0.004;
BreakPointSpacing = 0.003;
TextYAlign = 22;
TextYX = 0.70;
TextYY = 5.50;
TextRAlign = 22;
TextRX = 0.50;
TextRY = 1.70;
AxisStyle = 502;
TopAxisStyle = 505;
}
// Derived inputs. Don't edit.
double TotalHeight = Height + TopMargin + BottomMargin;
double TotalWidth = Width + LeftMargin + RightMargin;
double WorldYMin = YMin;
double WorldYMax = YMin + (YMax - YMin) * (4 + HeaderSize);
double YShift = YMax - YMin;
double WorldRMin = RMin;
double WorldRMax = RMin + (RMax - RMin) * (4 + HeaderSize);
double RShift = RMax - RMin;
double PanelHeight = Height / (4 + HeaderSize);
// Canvas and pad settings
TCanvas Canvas("Canvas", "", TotalWidth, TotalHeight);
TPad *Pad = new TPad("Pad", "", LeftMargin / TotalWidth, BottomMargin / TotalHeight,
(LeftMargin + Width) / TotalWidth, (BottomMargin + Height) / TotalHeight);
Pad->SetTopMargin(0);
Pad->SetRightMargin(0);
Pad->SetBottomMargin(0);
Pad->SetLeftMargin(0);
Pad->Draw();
// Make sure the inputs are done correctly
vector<TGraphAsymmErrors *> R(8, NULL);
bool Success = DivideAndShift(G, R, YShift, RShift);
if(Success == false)
{
for(int i = 0; i < 16; i++)
{
if(G[i] != NULL)
delete G[i];
G[i] = NULL;
}
for(int i = 0; i < 24; i++)
{
if(T[i] != NULL)
delete T[i];
T[i] = NULL;
}
return;
}
bool HasTheory = true;
for(int i = 0; i < 24; i++)
if(T[i] == NULL)
HasTheory = false;
vector<TGraphAsymmErrors *> RT(12, NULL);
if(HasTheory == true)
{
Success = DivideAndShiftTheory(T, RT, YShift, RShift);
if(Success == false)
{
for(int i = 0; i < 16; i++)
{
if(G[i] != NULL)
delete G[i];
G[i] = NULL;
}
for(int i = 0; i < 24; i++)
{
if(T[i] != NULL)
delete T[i];
T[i] = NULL;
}
return;
}
}
// Set the stage
TH2D HWorld("HWorld", ";;", 100, XMin, XMax, 100, WorldYMin, WorldYMax);
HWorld.SetStats(0);
HWorld.GetXaxis()->SetLabelSize(0);
HWorld.GetYaxis()->SetLabelSize(0);
HWorld.GetXaxis()->SetTickLength(0);
HWorld.GetYaxis()->SetTickLength(0);
TH2D HWorldRatio("HWorldRatio", ";;", 100, XMin, XMax, 100, WorldRMin, WorldRMax);
HWorldRatio.SetStats(0);
HWorldRatio.GetXaxis()->SetLabelSize(0);
HWorldRatio.GetYaxis()->SetLabelSize(0);
HWorldRatio.GetXaxis()->SetTickLength(0);
HWorldRatio.GetYaxis()->SetTickLength(0);
// Prepare axis
TGaxis BottomAxis(LeftMargin / TotalWidth, BottomMargin / TotalHeight,
(LeftMargin + Width) / TotalWidth, BottomMargin / TotalHeight,
XMin, XMax, 1005, "S");
BottomAxis.SetName("BottomAxis");
BottomAxis.SetTitle("M_{g} / p_{T,jet}");
BottomAxis.SetTickLength(0.025);
BottomAxis.SetTextFont(42);
BottomAxis.SetLabelFont(42);
BottomAxis.CenterTitle(true);
BottomAxis.SetLabelOffset(-0.005);
BottomAxis.SetTitleOffset(0.80);
BottomAxis.Draw();
TGaxis LeftAxis1(LeftMargin / TotalWidth, (BottomMargin + PanelHeight * 0) / TotalHeight,
LeftMargin / TotalWidth, (BottomMargin + PanelHeight * 1) / TotalHeight,
YMin, YMax, AxisStyle, "S");
LeftAxis1.SetName("LeftAxis1");
LeftAxis1.SetTitle("");
LeftAxis1.SetTickLength(0.2);
LeftAxis1.SetLabelFont(42);
LeftAxis1.Draw();
TGaxis LeftAxis2(LeftMargin / TotalWidth, (BottomMargin + PanelHeight * 1) / TotalHeight,
LeftMargin / TotalWidth, (BottomMargin + PanelHeight * 2) / TotalHeight,
YMin, YMax, AxisStyle, "S");
LeftAxis2.SetName("LeftAxis2");
LeftAxis2.SetTitle("");
LeftAxis2.SetTickLength(0.2);
LeftAxis2.SetLabelFont(42);
LeftAxis2.Draw();
TGaxis LeftAxis3(LeftMargin / TotalWidth, (BottomMargin + PanelHeight * 2) / TotalHeight,
LeftMargin / TotalWidth, (BottomMargin + PanelHeight * 3) / TotalHeight,
YMin, YMax, AxisStyle, "S");
LeftAxis3.SetName("LeftAxis3");
LeftAxis3.SetTitle("");
LeftAxis3.SetTickLength(0.2);
LeftAxis3.SetLabelFont(42);
LeftAxis3.Draw();
TGaxis LeftAxis4(LeftMargin / TotalWidth, (BottomMargin + PanelHeight * 3) / TotalHeight,
LeftMargin / TotalWidth, (BottomMargin + Height) / TotalHeight,
YMin, YMax + (YMax - YMin) * HeaderSize, TopAxisStyle, "S");
LeftAxis4.SetName("LeftAxis4");
LeftAxis4.SetTitle("");
LeftAxis4.SetTickLength(0.2 / (1 + HeaderSize));
LeftAxis4.SetLabelFont(42);
LeftAxis4.Draw();
TGaxis LeftAxis(LeftMargin / TotalWidth, BottomMargin / TotalHeight,
LeftMargin / TotalWidth, (BottomMargin + Height) / TotalHeight,
YMin, YMax, 510, "S");
LeftAxis.SetName("LeftAxis");
LeftAxis.SetTitle("#frac{1}{N} #frac{d N}{d M_{g} / p_{T,jet}}");
LeftAxis.SetTickLength(0);
LeftAxis.SetTextFont(42);
LeftAxis.SetLabelSize(0);
LeftAxis.CenterTitle(true);
LeftAxis.SetTitleOffset(1.40);
LeftAxis.Draw();
TGaxis RightAxis1((LeftMargin + Width) / TotalWidth, (BottomMargin + PanelHeight * 0) / TotalHeight,
(LeftMargin + Width) / TotalWidth, (BottomMargin + PanelHeight * 1) / TotalHeight,
YMin, YMax, AxisStyle, "S+L");
RightAxis1.SetName("RightAxis1");
RightAxis1.SetTitle("");
RightAxis1.SetTickLength(0.2);
RightAxis1.SetLabelFont(42);
RightAxis1.SetLabelSize(0);
RightAxis1.Draw();
TGaxis RightAxis2((LeftMargin + Width) / TotalWidth, (BottomMargin + PanelHeight * 1) / TotalHeight,
(LeftMargin + Width) / TotalWidth, (BottomMargin + PanelHeight * 2) / TotalHeight,
YMin, YMax, AxisStyle, "S+L");
RightAxis2.SetName("RightAxis2");
RightAxis2.SetTitle("");
RightAxis2.SetTickLength(0.2);
RightAxis2.SetLabelFont(42);
RightAxis2.SetLabelSize(0);
RightAxis2.Draw();
TGaxis RightAxis3((LeftMargin + Width) / TotalWidth, (BottomMargin + PanelHeight * 2) / TotalHeight,
(LeftMargin + Width) / TotalWidth, (BottomMargin + PanelHeight * 3) / TotalHeight,
YMin, YMax, AxisStyle, "S+L");
RightAxis3.SetName("RightAxis3");
RightAxis3.SetTitle("");
RightAxis3.SetTickLength(0.2);
RightAxis3.SetLabelFont(42);
RightAxis3.SetLabelSize(0);
RightAxis3.Draw();
TGaxis RightAxis4((LeftMargin + Width) / TotalWidth, (BottomMargin + PanelHeight * 3) / TotalHeight,
(LeftMargin + Width) / TotalWidth, (BottomMargin + Height) / TotalHeight,
YMin, YMax + (YMax - YMin) * HeaderSize, TopAxisStyle, "S+L");
RightAxis4.SetName("RightAxis4");
RightAxis4.SetTitle("");
RightAxis4.SetTickLength(0.2 / (1 + HeaderSize));
RightAxis4.SetLabelFont(42);
RightAxis4.SetLabelSize(0);
RightAxis4.Draw();
TLine Line;
Line.SetLineWidth(2);
Line.SetNDC();
for(int i = 0; i < 3; i++)
{
double X = LeftMargin / TotalWidth;
double Y = (BottomMargin + PanelHeight * (i + 1) + PanelHeight * BreakPointOffset) / TotalHeight;
Line.SetLineColor(kBlack);
Line.DrawLine(X - BreakPointSizeX / 2, Y + BreakPointSpacing / 2 - BreakPointSizeY / 2,
X + BreakPointSizeX / 2, Y + BreakPointSpacing / 2 + BreakPointSizeY / 2);
Line.DrawLine(X - BreakPointSizeX / 2, Y - BreakPointSpacing / 2 - BreakPointSizeY / 2,
X + BreakPointSizeX / 2, Y - BreakPointSpacing / 2 + BreakPointSizeY / 2);
Line.SetLineColor(kWhite);
Line.DrawLine(X - BreakPointSizeX, Y - BreakPointSizeY,
X + BreakPointSizeX, Y + BreakPointSizeY);
X = (LeftMargin + Width) / TotalWidth;
Line.SetLineColor(kBlack);
Line.DrawLine(X - BreakPointSizeX / 2, Y + BreakPointSpacing / 2 - BreakPointSizeY / 2,
X + BreakPointSizeX / 2, Y + BreakPointSpacing / 2 + BreakPointSizeY / 2);
Line.DrawLine(X - BreakPointSizeX / 2, Y - BreakPointSpacing / 2 - BreakPointSizeY / 2,
X + BreakPointSizeX / 2, Y - BreakPointSpacing / 2 + BreakPointSizeY / 2);
Line.SetLineColor(kWhite);
Line.DrawLine(X - BreakPointSizeX, Y - BreakPointSizeY,
X + BreakPointSizeX, Y + BreakPointSizeY);
}
// Prepare TGraphs and TLines
TLine UnityLine;
UnityLine.SetLineStyle(kDotted);
// Prepare TLatex
TLatex Latex;
Latex.SetTextFont(42);
Latex.SetNDC();
Latex.SetTextSize(0.035);
Latex.SetTextAlign(31);
Latex.DrawLatex((LeftMargin + Width) / TotalWidth, (BottomMargin + Height) / TotalHeight + 0.005, "PbPb 404 #mub^{-1} (5.02 TeV), pp 27.4 #mub^{-1} (5.02 TeV)");
Latex.SetTextSize(0.065);
Latex.SetTextAlign(13);
Latex.DrawLatex((LeftMargin) / TotalWidth + 0.04, (BottomMargin + Height - 0.04 * TotalWidth) / TotalHeight, "#font[62]{CMS}");
Latex.SetTextSize(0.035);
Latex.SetTextAlign(31);
Latex.DrawLatex((LeftMargin + Width) / TotalWidth - 0.04, (BottomMargin + Height - 0.04 * TotalWidth) / TotalHeight - TextSpacing * 0.5, "anti-k_{T} R = 0.4, |#eta_{jet}| < 1.3");
if(Preset == SD0_PT || Preset == SD0_CENTRALITY)
Latex.DrawLatex((LeftMargin + Width) / TotalWidth - 0.04, (BottomMargin + Height - 0.04 * TotalWidth) / TotalHeight - TextSpacing * 1.5, "Soft drop z_{cut} = 0.1, #beta = 0.0");
else
Latex.DrawLatex((LeftMargin + Width) / TotalWidth - 0.04, (BottomMargin + Height - 0.04 * TotalWidth) / TotalHeight - TextSpacing * 1.5, "Soft drop z_{cut} = 0.5, #beta = 1.5");
Latex.DrawLatex((LeftMargin + Width) / TotalWidth - 0.04, (BottomMargin + Height - 0.04 * TotalWidth) / TotalHeight - TextSpacing * 2.5, "#DeltaR_{12} > 0.1");
if(Preset == SD0_PT || Preset == SD7_PT)
Latex.DrawLatex((LeftMargin + Width) / TotalWidth - 0.04, (BottomMargin + Height - 0.04 * TotalWidth) / TotalHeight - TextSpacing * 3.5, "Centrality: 0-10%");
else
Latex.DrawLatex((LeftMargin + Width) / TotalWidth - 0.04, (BottomMargin + Height - 0.04 * TotalWidth) / TotalHeight - TextSpacing * 3.5, "160 < p_{T,jet} < 180 GeV");
// Set graph styles
for(int i = 0; i < 4; i++)
{
G[i*4+0]->SetMarkerSize(2.0);
G[i*4+2]->SetMarkerSize(2.0);
if(i % 2 == 0)
{
G[i*4+0]->SetMarkerStyle(25);
G[i*4+2]->SetMarkerStyle(26);
}
else
{
G[i*4+0]->SetMarkerStyle(25);
G[i*4+2]->SetMarkerStyle(22);
}
G[i*4+2]->SetFillStyle(3145);
G[i*4+3]->SetFillStyle(3145);
G[i*4+0]->SetFillColor(kRed - 9);
G[i*4+1]->SetFillColor(kRed - 9);
G[i*4+2]->SetFillColor(kGray + 2);
G[i*4+3]->SetFillColor(kGray + 2);
R[i*2+0]->SetMarkerSize(2.0);
R[i*2+0]->SetMarkerStyle(25);
R[i*2+0]->SetMarkerColor(kBlack);
R[i*2+0]->SetLineColor(kBlack);
R[i*2+0]->SetFillColor(kRed - 9);
R[i*2+1]->SetFillColor(kRed - 9);
}
// Prepare Legend
TLegend Legend1(0.10, 0.70, 0.60, 0.85);
Legend1.SetTextFont(42);
Legend1.SetTextSize(0.045);
Legend1.SetBorderSize(0);
Legend1.SetFillStyle(0);
Legend1.AddEntry(G[0], "PbPb", "lpf");
Legend1.AddEntry(G[2], "Smeared pp", "lpf");
Legend1.AddEntry("", " ", "");
Legend1.AddEntry("", " ", "");
TLegend Legend2(0.10, 0.70, 0.60, 0.85);
Legend2.SetTextFont(42);
Legend2.SetTextSize(0.045);
Legend2.SetBorderSize(0);
Legend2.SetFillStyle(0);
Legend2.AddEntry(R[0], "Data", "lpf");
if(HasTheory == true)
{
Legend2.AddEntry(RT[0], "Jewel (Recoil off)", "lp");
Legend2.AddEntry(RT[1], "Jewel (Recoil on)", "lp");
Legend2.AddEntry(RT[2], "QPythia", "lp");
}
else
{
Legend2.AddEntry("", " ", "");
Legend2.AddEntry("", " ", "");
Legend2.AddEntry("", " ", "");
}
// Draw it!
Pad->cd();
HWorld.Draw("axis");
for(int i = 1; i < 16; i = i + 2)
G[i]->Draw("2");
for(int i = 0; i < 16; i = i + 2)
G[i]->Draw("p");
Latex.SetTextSize(0.045);
Latex.SetTextAlign(TextYAlign);
if(Preset == SD0_PT || Preset == SD7_PT)
{
Latex.DrawLatex(TextYX, (TextYY - YMin + (YMax - YMin) * 0) / (WorldYMax - YMin), "200 < p_{T,jet} < 300 GeV");
Latex.DrawLatex(TextYX, (TextYY - YMin + (YMax - YMin) * 1) / (WorldYMax - YMin), "180 < p_{T,jet} < 200 GeV");
Latex.DrawLatex(TextYX, (TextYY - YMin + (YMax - YMin) * 2) / (WorldYMax - YMin), "160 < p_{T,jet} < 180 GeV");
Latex.DrawLatex(TextYX, (TextYY - YMin + (YMax - YMin) * 3) / (WorldYMax - YMin), "140 < p_{T,jet} < 160 GeV");
}
else
{
Latex.DrawLatex(TextYX, (TextYY - YMin + (YMax - YMin) * 0) / (WorldYMax - YMin), "50-80%");
Latex.DrawLatex(TextYX, (TextYY - YMin + (YMax - YMin) * 1) / (WorldYMax - YMin), "30-50%");
Latex.DrawLatex(TextYX, (TextYY - YMin + (YMax - YMin) * 2) / (WorldYMax - YMin), "10-30%");
Latex.DrawLatex(TextYX, (TextYY - YMin + (YMax - YMin) * 3) / (WorldYMax - YMin), "0-10%");
}
HWorld.Draw("axis same");
Legend1.Draw();
Canvas.cd();
Canvas.SaveAs((OutputBase + "_Spectrum.pdf").c_str());
// Draw ratio!
LeftAxis1.SetWmin(RMin); LeftAxis1.SetWmax(RMax);
LeftAxis2.SetWmin(RMin); LeftAxis2.SetWmax(RMax);
LeftAxis3.SetWmin(RMin); LeftAxis3.SetWmax(RMax);
LeftAxis4.SetWmin(RMin); LeftAxis4.SetWmax(RMax + (RMax - RMin) * HeaderSize);
RightAxis1.SetWmin(RMin); RightAxis1.SetWmax(RMax);
RightAxis2.SetWmin(RMin); RightAxis2.SetWmax(RMax);
RightAxis3.SetWmin(RMin); RightAxis3.SetWmax(RMax);
RightAxis4.SetWmin(RMin); RightAxis4.SetWmax(RMax + (RMax - RMin) * HeaderSize);
LeftAxis.SetTitle("#frac{PbPb}{Smeared pp}");
Pad->cd();
HWorldRatio.Draw("axis");
for(int i = 1; i < 8; i = i + 2)
R[i]->Draw("2");
UnityLine.DrawLine(XMin, 1 + RShift * 0, XMax, 1 + RShift * 0);
UnityLine.DrawLine(XMin, 1 + RShift * 1, XMax, 1 + RShift * 1);
UnityLine.DrawLine(XMin, 1 + RShift * 2, XMax, 1 + RShift * 2);
UnityLine.DrawLine(XMin, 1 + RShift * 3, XMax, 1 + RShift * 3);
for(int i = 0; i < 8; i = i + 2)
R[i]->Draw("p");
if(HasTheory == true)
{
for(int i = 0; i < 4; i++)
{
RT[i*3+0]->SetLineWidth(2);
RT[i*3+1]->SetLineWidth(2);
RT[i*3+2]->SetLineWidth(2);
RT[i*3+0]->SetLineColor(kGreen - 2);
RT[i*3+1]->SetLineColor(kBlue);
RT[i*3+2]->SetLineColor(kRed);
RT[i*3+0]->SetLineStyle(kSolid);
RT[i*3+1]->SetLineStyle(kDashed);
RT[i*3+2]->SetLineStyle(kDotted);
RT[i*3+0]->SetMarkerStyle(20);
RT[i*3+1]->SetMarkerStyle(20);
RT[i*3+2]->SetMarkerStyle(20);
RT[i*3+0]->SetMarkerSize(0);
RT[i*3+1]->SetMarkerSize(0);
RT[i*3+2]->SetMarkerSize(0);
RT[i*3+0]->SetMarkerColor(kGreen - 2);
RT[i*3+1]->SetMarkerColor(kBlue);
RT[i*3+2]->SetMarkerColor(kRed);
}
for(int i = 0; i < 12; i++)
RT[i]->Draw("l");
}
Latex.SetTextSize(0.045);
Latex.SetTextAlign(TextRAlign);
if(Preset == SD0_PT || Preset == SD7_PT)
{
Latex.DrawLatex(TextRX, (TextRY - RMin + (RMax - RMin) * 0) / (WorldRMax - RMin), "200 < p_{T,jet} < 300 GeV");
Latex.DrawLatex(TextRX, (TextRY - RMin + (RMax - RMin) * 1) / (WorldRMax - RMin), "180 < p_{T,jet} < 200 GeV");
Latex.DrawLatex(TextRX, (TextRY - RMin + (RMax - RMin) * 2) / (WorldRMax - RMin), "160 < p_{T,jet} < 180 GeV");
Latex.DrawLatex(TextRX, (TextRY - RMin + (RMax - RMin) * 3) / (WorldRMax - RMin), "140 < p_{T,jet} < 160 GeV");
}
else
{
Latex.DrawLatex(TextRX, (TextRY - RMin + (RMax - RMin) * 0) / (WorldRMax - RMin), "50-80%");
Latex.DrawLatex(TextRX, (TextRY - RMin + (RMax - RMin) * 1) / (WorldRMax - RMin), "30-50%");
Latex.DrawLatex(TextRX, (TextRY - RMin + (RMax - RMin) * 2) / (WorldRMax - RMin), "10-30%");
Latex.DrawLatex(TextRX, (TextRY - RMin + (RMax - RMin) * 3) / (WorldRMax - RMin), "0-10%");
}
HWorldRatio.Draw("axis same");
Legend2.Draw();
Canvas.cd();
Canvas.SaveAs((OutputBase + "_Ratio.pdf").c_str());
// Clean up
for(int i = 0; i < 16; i++)
{
if(G[i] != NULL)
delete G[i];
G[i] = NULL;
}
for(int i = 0; i < 8; i++)
if(R[i] != NULL)
delete R[i];
for(int i = 0; i < 24; i++)
{
if(T[i] != NULL)
delete T[i];
T[i] = NULL;
}
for(int i = 0; i < 12; i++)
if(RT[i] != NULL)
delete RT[i];
}
bool DivideAndShift(vector<TGraphAsymmErrors *> &G, vector<TGraphAsymmErrors *> &R, double YShift, double RShift)
{
if(G.size() != 16)
return false;
for(int i = 0; i < 16; i++)
if(G[i] == NULL)
return false;
for(int i = 0; i < 8; i++)
{
if(R[i] != NULL)
delete R[i];
R[i] = new TGraphAsymmErrors;
}
// First do the division
Division(G[0], G[2], R[0]);
Division(G[1], G[3], R[1]);
Division(G[4], G[6], R[2]);
Division(G[5], G[7], R[3]);
Division(G[8], G[10], R[4]);
Division(G[9], G[11], R[5]);
Division(G[12], G[14], R[6]);
Division(G[13], G[15], R[7]);
// Then do the shifting
ShiftUp(G[0], YShift * 3);
ShiftUp(G[1], YShift * 3);
ShiftUp(G[2], YShift * 3);
ShiftUp(G[3], YShift * 3);
ShiftUp(G[4], YShift * 2);
ShiftUp(G[5], YShift * 2);
ShiftUp(G[6], YShift * 2);
ShiftUp(G[7], YShift * 2);
ShiftUp(G[8], YShift * 1);
ShiftUp(G[9], YShift * 1);
ShiftUp(G[10], YShift * 1);
ShiftUp(G[11], YShift * 1);
ShiftUp(G[12], YShift * 0);
ShiftUp(G[13], YShift * 0);
ShiftUp(G[14], YShift * 0);
ShiftUp(G[15], YShift * 0);
ShiftUp(R[0], RShift * 3);
ShiftUp(R[1], RShift * 3);
ShiftUp(R[2], RShift * 2);
ShiftUp(R[3], RShift * 2);
ShiftUp(R[4], RShift * 1);
ShiftUp(R[5], RShift * 1);
ShiftUp(R[6], RShift * 0);
ShiftUp(R[7], RShift * 0);
return true;
}
bool DivideAndShiftTheory(vector<TGraphAsymmErrors *> &T, vector<TGraphAsymmErrors *> &R, double YShift, double RShift)
{
if(T.size() != 24)
return false;
for(int i = 0; i < 24; i++)
if(T[i] == NULL)
return false;
for(int i = 0; i < 12; i++)
{
if(R[i] != NULL)
delete R[i];
R[i] = new TGraphAsymmErrors;
}
// First do the division
Division(T[0], T[1], R[0]);
Division(T[2], T[3], R[1]);
Division(T[4], T[5], R[2]);
Division(T[6], T[7], R[3]);
Division(T[8], T[9], R[4]);
Division(T[10], T[11], R[5]);
Division(T[12], T[13], R[6]);
Division(T[14], T[15], R[7]);
Division(T[16], T[17], R[8]);
Division(T[18], T[19], R[9]);
Division(T[20], T[21], R[10]);
Division(T[22], T[23], R[11]);
// Then do the shifting
ShiftUp(R[0], RShift * 3);
ShiftUp(R[1], RShift * 3);
ShiftUp(R[2], RShift * 3);
ShiftUp(R[3], RShift * 2);
ShiftUp(R[4], RShift * 2);
ShiftUp(R[5], RShift * 2);
ShiftUp(R[6], RShift * 1);
ShiftUp(R[7], RShift * 1);
ShiftUp(R[8], RShift * 1);
ShiftUp(R[9], RShift * 0);
ShiftUp(R[10], RShift * 0);
ShiftUp(R[11], RShift * 0);
return true;
}
void Division(TGraphAsymmErrors *G1, TGraphAsymmErrors *G2, TGraphAsymmErrors *GRatio)
{
if(G1 == NULL || G2 == NULL || GRatio == NULL)
return;
int BinCount = min(G1->GetN(), G2->GetN());
for(int i = 0; i < BinCount; i++)
{
double x1, x2, y1, y2;
G1->GetPoint(i, x1, y1);
G2->GetPoint(i, x2, y2);
double xl1, xh1, xl2, xh2;
xl1 = G1->GetErrorXlow(i);
xh1 = G1->GetErrorXhigh(i);
xl2 = G2->GetErrorXlow(i);
xh2 = G2->GetErrorXhigh(i);
double yl1, yh1, yl2, yh2;
yl1 = G1->GetErrorYlow(i);
yh1 = G1->GetErrorYhigh(i);
yl2 = G2->GetErrorYlow(i);
yh2 = G2->GetErrorYhigh(i);
double ratio = (y1 / y2);
double yl = ratio * sqrt((yl1 / y1) * (yl1 / y1) + (yl2 / y2) * (yl2 / y2));
double yh = ratio * sqrt((yh1 / y1) * (yh1 / y1) + (yh2 / y2) * (yh2 / y2));
if(x1 == x1 && x2 == x2 && ratio == ratio)
{
int N = GRatio->GetN();
GRatio->SetPoint(N, x1, ratio);
GRatio->SetPointError(N, xl1, xh1, yl, yh);
}
}
}
void ShiftUp(TGraphAsymmErrors *G, double Amount)
{
if(G == NULL)
return;
int BinCount = G->GetN();
for(int i = 0; i < BinCount; i++)
{
double x, y;
G->GetPoint(i, x, y);
G->SetPoint(i, x, y + Amount);
}
}
TGraphAsymmErrors *HistogramToGraph(TH1D *H)
{
if(H == NULL)
return NULL;
TGraphAsymmErrors *G = new TGraphAsymmErrors;
for(int i = 1; i <= H->GetNbinsX(); i++)
{
double x = H->GetBinCenter(i);
double y = H->GetBinContent(i);
double l = H->GetXaxis()->GetBinLowEdge(i);
double r = H->GetXaxis()->GetBinUpEdge(i);
double e = H->GetBinError(i);
if(y != y)
continue;
if(x > 0.27)
continue;
int I = G->GetN();
G->SetPoint(I, x, y);
// G->SetPointError(I, x - l, r - x, e, e);
}
return G;
}
|
[
"chen.yi.first@gmail.com"
] |
chen.yi.first@gmail.com
|
0c34bebafb67054c2cabd621507755b8e086cc58
|
16c2b8eae3103348a7a8a8addb08071d5a4e70e2
|
/main.cpp
|
a20894cb32a17e98c6316c6eea5a988a1e687a38
|
[
"MIT"
] |
permissive
|
lcala99/MakeIThome
|
f1bae8497c03f34e142a677a4591fc4012de0619
|
dc8767391bb64c96e5374670d7ceb494050b081b
|
refs/heads/main
| 2023-07-31T13:41:38.559305
| 2021-09-21T14:22:54
| 2021-09-21T14:22:54
| 408,850,298
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 331
|
cpp
|
#include <QApplication>
#include <iostream>
#include "view.h"
#include "model.h"
#include "controller.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Catalogo cat;
Model model(cat);
Controller controller(&model);
View* view = new View(&controller);
view->show();
return a.exec();
}
|
[
"40360727+lcala99@users.noreply.github.com"
] |
40360727+lcala99@users.noreply.github.com
|
b64de015023e8b6dd0090edfc6639449128d3fe7
|
d40d73a0973a2071285e52884cd3f6b6fdb28f56
|
/Stopwatch-Timer/sketch_Stopwatch.ino
|
d6c598bd2ef2a5ec53fc5f84f725df1c4335a8c1
|
[] |
no_license
|
mrinalraj2809/Arduino
|
bd10c20eba38cb340470ff35e4d775ad6b7c3d74
|
dab65b4423660235d3634fd1eb26a1ddb1695c63
|
refs/heads/master
| 2020-08-04T19:30:41.548433
| 2019-10-02T05:45:14
| 2019-10-02T05:45:14
| 212,255,066
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 989
|
ino
|
#include <LiquidCrystal.h>
LiquidCrystal lcd(7,6,5,4,3,2);
void setup()
{
pinMode(8,INPUT);
pinMode(9,INPUT);
Serial.begin(9600);
digitalWrite(8,HIGH);
digitalWrite(9,HIGH);
lcd.begin(16,2);
lcd.clear();
}
double i,a,c;
void loop()
{
lcd.clear();
lcd.print("Press Start");
delay(100);
if(digitalRead(8)==LOW)
{
lcd.clear();
a=millis();
while(digitalRead(9)==HIGH)
{
c=millis();
lcd.clear();
i=(c-a)/1000;
lcd.setCursor(0,0);
lcd.print(i);
lcd.setCursor(11,0);
lcd.print("Sec's");
lcd.clear();
Serial.println(c);
Serial.println(a);
Serial.println(i);
Serial.println("----------");
delay(100);
}
if(digitalRead(9)==LOW)
{
while(digitalRead(8)==LOW)
{
lcd.clear();
lcd.setCursor(0,0);
lcd.print(i);
lcd.setCursor(11,0);
lcd.print("Sec's");
delay(100);
lcd.clear();
}
}
}
}
|
[
"mrinalraj2809@gmail.com"
] |
mrinalraj2809@gmail.com
|
c3e0f39efe1b575568970a1f26d4c26f203f6206
|
9b1c54260c0b317c6ed6ce3eb22f4ced37c758c7
|
/packcompute/main.cpp
|
0939366e577134ddcffe40d65bc504bd1e256896
|
[] |
no_license
|
vkirangoud/ALAFF
|
8174387a89bd453c8da3e9171033284778113e9f
|
04007b6633f1e2a88de69431df8201819ebbe800
|
refs/heads/master
| 2022-12-29T07:59:11.466875
| 2020-10-11T16:21:16
| 2020-10-11T16:21:16
| 278,116,604
| 1
| 0
| null | 2020-07-08T14:48:21
| 2020-07-08T14:48:20
| null |
UTF-8
|
C++
| false
| false
| 4,116
|
cpp
|
#include <stdio.h>
#include <stdlib.h>
#include "Params.h"
size_t dgemm_pack_get_size(char identifier, const int m, const int n, const int k);
size_t sgemm_pack_get_size(char identifier, const int m, const int n, const int k);
void dgemm_pack_A(const dim_t m, const dim_t n, const dim_t k, const double alpha1,
const double* src, const dim_t ld, double* dest);
void sgemm_pack_A(const dim_t m, const dim_t n, const dim_t k, const float alpha1,
const float* src, const dim_t ld, float* dest);
void dgemmCompute(int m, int n, int k, double* A, int lda, double* B, int ldb, double* C, int ldc);
void dumpPackBuffer(char* str, double* ap, dim_t numbytes);
extern dim_t MC;
extern dim_t KC;
extern dim_t NC;
int main(int argc, char** argv)
{
FILE* fp = NULL;
int m, k, n;
int lda, ldb, ldc;
double* ap = NULL;
double* bp = NULL;
double* cp = NULL;
double alpha1 = 1.0f;
double* packbuf = NULL;
if (argc < 2)
{
printf("Usage: ./PackMatrix.x input.txt \n");
exit(1);
}
fp = fopen(argv[1], "r");
if (fp == NULL)
{
printf("Error opening the input file %s \n", argv[1]);
exit(1);
}
char filename[100];
printf("MC = %ld KC = %ld NC = %ld MR = %ld NR = %ld\n", MC, KC, NC, MR, NR);
while (fscanf(fp, "%d %d %d %d %d %d\n", &m, &k, &n, &lda, &ldb, &ldc) == 6) {
// Row major
int nelems_A = (m - 1) * lda + (k - 1) * 1 + 1; // rs_a = lda, cs = 1
int nelems_B = (k - 1) * ldb + (n - 1) * 1 + 1; // rs_b = ldb, cs = 1
int nelems_C = (m - 1) * ldc + (n - 1) * 1 + 1; // rs_c = ldb, cs = 1
// column-major
// int nelems_A = (m - 1) * 1 + (k - 1) * lda + 1; // rs_a = 1, cs = lda
// int nelems_B = (k - 1) * 1 + (n - 1) * ldb + 1; // rs_b = 1, cs = ldb
ap = (double*)malloc(sizeof(double) * nelems_A);
if (ap == NULL) { printf("Error allocation memory A \n"); exit(1); }
bp = (double*)malloc(sizeof(double) * nelems_B);
if (bp == NULL) { printf("Error allocation memory B \n"); exit(1); }
cp = (double*)malloc(sizeof(double) * nelems_C);
if (cp == NULL) { printf("Error allocation memory C \n"); exit(1); }
for (int i = 0; i < nelems_C; i++) cp[i] = 0.0;
double* cp_ref = (double*)malloc(sizeof(double) * nelems_C);
if (cp_ref == NULL) { printf("Error allocation memory C \n"); exit(1); }
for (int i = 0; i < nelems_C; i++) cp_ref[i] = 0;
// create a matrix row-major
gen_random_matrix(ap, m, k, lda, 1);
gen_random_matrix(bp, k, n, ldb, 1);
// gen_random_matrix(cp_ref, m, n, ldc, 1);
MyGemm_ref(m, n, k, ap, lda, bp, ldb, cp_ref, ldc);
// Column-major matrices
//gen_random_matrix(ap, m, k, 1, lda);
//gen_random_matrix(bp, k, n, 1, ldb);
// Compute the size of packed buffer
dim_t totlBytes = dgemm_pack_get_size('A', m, n, k);
// allocate memory to packed buffer
packbuf = (double*)malloc(totlBytes);
if (packbuf == NULL)
{
printf("Error allocating memory \n");
exit(1);
}
dim_t elements = totlBytes / sizeof(double);
for (dim_t i = 0; i < elements; i++) packbuf[i] = 0.0;
// Perform packing of A
dgemm_pack_A(m, n, k, alpha1, ap, lda, packbuf);
// sprintf(filename, "packA%d_%d_%d.txt", m, n, k);
// Dump to a file
// dumpPackBuffer(filename, packbuf, totlBytes);
// Perform matrix multiplication
//void dgemmCompute(int m, int n, int k, double* A, int lda, double* B, int ldb, double* C, int ldc)
dgemmCompute(m, n, k, packbuf, lda, bp, ldb, cp, ldc);
if (isMatrixMatch(cp_ref, cp, m, n, ldc) == 1)
{
printf(" %d %d %d %d %d %d ---> Passed\n", m, n, k, lda, ldb, ldc);
}
else
{
printf(" %d %d %d %d %d %d ---> Failed\n", m, n, k, lda, ldb, ldc);
}
free(ap);
free(bp);
free(cp);
free(packbuf);
}
return 0;
}
|
[
"kirangoud.v@gmail.com"
] |
kirangoud.v@gmail.com
|
a2591ff92757e1f0d0c4b1755eb400cca86b9a04
|
4f951e96accafe3ae8f687d18e142a8c9c657d05
|
/foundation_questions/q28.cpp
|
cd70de54433558f58ef7dad9295004189a5a2b18
|
[] |
no_license
|
amey16/Important-codes
|
ef9ef780d81f57198959ad784b242b284d89c4af
|
6ddee5e4c52bdefbbf0bbcf13b6c7b852ce67746
|
refs/heads/master
| 2022-06-20T12:10:49.642747
| 2020-05-12T09:15:51
| 2020-05-12T09:15:51
| 260,652,677
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 626
|
cpp
|
#include<iostream>
using namespace std;
int main(int argc,char** argv){
int n;
cin>>n;
int s[n],cnt=0;
for(int i=0;i<n;i++)
cin>>s[i];
for(int i=0;i<n-1;i++){
if(cnt==2)
break;
else if(s[i+1]<s[i] && cnt==0)
continue;
else if(s[i+1]>s[i] && cnt==0){
cnt++;
continue;
}
else if(s[i+1]<s[i] && cnt==1){
cnt++;
continue;
}
else
{
continue;
}
}
if(cnt==2)
cout<<"False"<<endl;
else
cout<<"True"<<endl;
}
|
[
"ameyagupta19@gmail.com"
] |
ameyagupta19@gmail.com
|
6298c3a24f7bc7053f6e863cbbdd563c0809f641
|
2800d84b1b3e190e1cee4aa2ab509e66d6cf0b3c
|
/driect_project/window_start/15_cpp_1/SpreadsheetCell.h
|
f19c2ed2bb52e8f082351de6ac5938f4dcaf2271
|
[] |
no_license
|
kakaxi1100/DirectxHeaven
|
835db2c9e6e7b25ee2f82483fea9c8c71802f446
|
197a8c603cd59f76c1f3f53fa03154b61db05c94
|
refs/heads/master
| 2020-04-15T14:29:11.136594
| 2016-08-28T10:18:35
| 2016-08-28T10:18:35
| 50,349,706
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 408
|
h
|
#pragma once
#include <string>
class SpreadsheetCell
{
public:
SpreadsheetCell(const SpreadsheetCell& rsh);
void setValue(double inValue);
double getValue() const;
void setString(const std::string inString);
const std::string getString() const;
private:
std::string doubleToString(double inValue) const;
double stringToDouble(const std::string inString) const;
double mValue;
std::string mString;
};
|
[
"aresleecool@163.com"
] |
aresleecool@163.com
|
2d085fe2729133dc5f98bae93e027461544ac8e6
|
2351872312e3b5e38e4f625715ee5dfee4392302
|
/$P@/SPA/SPA/PKBController.cpp
|
eeb863ec7e9778c022b1a23e02d046157c30fb29
|
[] |
no_license
|
allanckw/32Ol_32oII_intelli-spa
|
737c4dae974cd08cf98ad414b4da847bdc19af62
|
e6929f146275ae2127a58584c65de7a1d83ce8a5
|
refs/heads/master
| 2020-05-07T13:18:03.290332
| 2013-04-25T14:20:07
| 2013-04-25T14:20:07
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 527
|
cpp
|
#pragma once
#include "PKBController.h"
/**
* Method to initalize the PKB, builds the AST from a SIMPLE source file, builds the CFG and initialization for queries
* @param filename the file name of the SIMPLE source file
*/
void PKBController::initializePKB(string filename)
{
//Parse Source
Parser* p = new Parser(filename);
p->buildAST(); //build AST
delete p;
DesignExtractor::extractDesign(); //Extract Design
CFGBuilder::buildCFG(); //Build CFG
RulesOfEngagement::initialise(); //Initialize ROE for Queries
}
|
[
"kw_chong@nus.edu.sg"
] |
kw_chong@nus.edu.sg
|
e73573998ebec275a11fafb268d3903a4aa5f07e
|
0243726f2168b61895ec23d1b1314aa4d968c925
|
/windows/CrashHandler.h
|
1453fe11b429851417ba84e8778441a3a1b6cdb3
|
[] |
no_license
|
3F/FlightSDC.RPC-WebSockets
|
6eae6b2349c0d39efb7e65018af3746080fcd97c
|
fa73c59aa5de8e6bba0f1fc9e9062c40d339ae18
|
refs/heads/master
| 2021-01-21T08:12:18.221113
| 2013-07-07T16:03:11
| 2013-08-05T14:47:09
| 68,389,120
| 1
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 15,611
|
h
|
// Copyright 2012 Idol Software, Inc.
//
// This file is part of CrashHandler library.
//
// CrashHandler library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#ifndef __CRASH_HANDLER_H__
#define __CRASH_HANDLER_H__
#include <windows.h>
//! Contains data that identifies your application.
struct ApplicationInfo
{
DWORD ApplicationInfoSize; //!< Size of this structure. Should be set to sizeof(ApplicationInfo).
LPCSTR ApplicationGUID; //!< GUID assigned to this application.
LPCSTR Prefix; //!< Prefix that will be used with the dump name: YourPrefix_v1.v2.v3.v4_YYYYMMDD_HHMMSS.mini.dmp.
LPCWSTR AppName; //!< Application name that will be used in message box.
LPCWSTR Company; //!< Company name that will be used in message box.
USHORT V[4]; //!< Version of this application.
USHORT Hotfix; //!< Version of hotfix for this application (reserved for future use, should be 0).
LPCWSTR PrivacyPolicyUrl; //!< URL to privacy policy. If NULL default privacy policy is used.
};
//! \brief Contains crash handling behavior customization parameters.
//!
//! Default values for all parameters is 0/FALSE.
struct HandlerSettings
{
DWORD HandlerSettingsSize; //!< Size of this structure. Should be set to sizeof(HandlerSettings).
BOOL LeaveDumpFilesInTempFolder; //!< To leave error reports in temp folder you should set this member to TRUE. Your support or test lab teams can use that reports later.
BOOL OpenProblemInBrowser; //!< To open Web-page belonging to the uploaded report after it was uploaded set this member to TRUE. It is useful for test lab to track the bug or write some comments.
BOOL UseWER; //!< To continue use Microsoft Windows Error Reporting (WER) set this member to TRUE. In that case after Crash Server send report dialog Microsoft send report dialog also will be shown. This can be necessary in case of Windows Logo program.
DWORD SubmitterID; //!< Crash Server user ID. Uploaded report will be marked as uploaded by this user. This is useful for Crash Server and bug tracking system integration. Set to \b 0 if user using this application is anonymous.
};
//! \brief To enable crash processing you should create an instance of this class.
//!
//! It should be created as global static object and correctly initialized.
//! Also you may instantiate it in your main() or WinMain() function as soon as possible.
class CrashHandler
{
public:
//! \example Sample.cpp
//! This is an example of how to use the CrashHandler class.
//! CrashHandler constructor. Loads crshhndl.dll and initializes crash handling.
//! \note The crshhndl.dll may missing. In that case there will be no crash handling.
CrashHandler(
LPCSTR applicationGUID, //!< [in] GUID assigned to this application.
LPCSTR prefix, //!< [in] Prefix that will be used with the dump name: YourPrefix_v1.v2.v3.v4_YYYYMMDD_HHMMSS.mini.dmp.
LPCWSTR appName, //!< [in] Application name that will be used in message box.
LPCWSTR company, //!< [in] Company name that will be used in message box.
BOOL ownProcess = TRUE //!< [in] If you own the process your code running in set this option to \b TRUE. If don't (for example you write
//!< a plugin to some external application) set this option to \b FALSE. In that case you need to explicitly
//!< catch exceptions. See \ref SendReport for more information.
) throw()
{
if (!LoadDll())
return;
ApplicationInfo appInfo;
memset(&appInfo, 0, sizeof(appInfo));
appInfo.ApplicationInfoSize = sizeof(appInfo);
appInfo.ApplicationGUID = applicationGUID;
appInfo.Prefix = prefix;
appInfo.AppName = appName;
appInfo.Company = company;
if (!m_GetVersionFromApp(&appInfo))
appInfo.V[0] = 1;
HandlerSettings handlerSettings;
memset(&handlerSettings, 0, sizeof(handlerSettings));
handlerSettings.HandlerSettingsSize = sizeof(handlerSettings);
m_InitCrashHandler(&appInfo, &handlerSettings, ownProcess);
}
//! CrashHandler constructor. Loads crshhndl.dll and initializes crash handling.
//! \note The crshhndl.dll may missing. In that case there will be no crash handling.
CrashHandler(
ApplicationInfo* applicationInfo, //!< [in] Pointer to the ApplicationInfo structure that identifies your application.
HandlerSettings* handlerSettings, //!< [in] Pointer to the HandlerSettings structure that customizes crash handling behavior. This paramenter can be \b NULL.
BOOL ownProcess = TRUE //!< [in] If you own the process your code running in set this option to \b TRUE. If don't (for example you write
//!< a plugin to some external application) set this option to \b FALSE. In that case you need to explicitly
//!< catch exceptions. See \ref SendReport for more information.
) throw()
{
if (!LoadDll())
return;
m_InitCrashHandler(applicationInfo, handlerSettings, ownProcess);
}
//! CrashHandler constructor. Loads crshhndl.dll. You should call \ref InitCrashHandler to turn on crash handling.
//! \note The crshhndl.dll may missing. In that case there will be no crash handling.
CrashHandler() throw()
{
LoadDll();
}
//! CrashHandler destructor.
//! \note It doesn't unload crshhndl.dll and doesn't disable crash handling since crash may appear on very late phase of application exit.
//! For example destructor of some static variable that is called after return from main() may crash.
~CrashHandler()
{
if (!m_IsReadyToExit)
return;
// If crash has happen not in main thread we should wait here until report will be sent
// or else program will be terminated after return from main() and report send will be halted.
while (!m_IsReadyToExit())
::Sleep(100);
}
//! Initializes crash handler.
//! \note You may call this function multiple times if some data has changed.
//! \return Return \b true if crash handling was enabled.
bool InitCrashHandler(
ApplicationInfo* applicationInfo, //!< [in] Pointer to the ApplicationInfo structure that identifies your application.
HandlerSettings* handlerSettings, //!< [in] Pointer to the HandlerSettings structure that customizes crash handling behavior. This paramenter can be \b NULL.
BOOL ownProcess = TRUE //!< [in] If you own the process your code running in set this option to \b TRUE. If don't (for example you write
//!< a plugin to some external application) set this option to \b FALSE. In that case you need to explicitly
//!< catch exceptions. See \ref SendReport for more information.
) throw()
{
if (!m_InitCrashHandler)
return false;
return m_InitCrashHandler(applicationInfo, handlerSettings, ownProcess) != FALSE;
}
//! You may add any key/value pair to crash report.
//! \return If the function succeeds, the return value is \b true.
bool AddUserInfoToReport(
LPCWSTR key, //!< [in] key string that will be added to the report.
LPCWSTR value //!< [in] value for the key.
) throw()
{
if (!m_AddUserInfoToReport)
return false;
m_AddUserInfoToReport(key, value);
return true;
}
//! You may add any file to crash report. This file will be read when crash appears and will be sent within the report.
//! Multiple files may be added. Filename of the file in the report may be changed to any name.
//! \return If the function succeeds, the return value is \b true.
bool AddFileToReport(
LPCWSTR path, //!< [in] Path to the file, that will be added to the report.
LPCWSTR reportFileName /* = NULL */ //!< [in] Filename that will be used in report for this file. If parameter is \b NULL, original name from path will be used.
) throw()
{
if (!m_AddFileToReport)
return false;
m_AddFileToReport(path, reportFileName);
return true;
}
//! Remove from report the file that was registered earlier to be sent within report.
//! \return If the function succeeds, the return value is \b true.
bool RemoveFileFromReport(
LPCWSTR path //!< [in] Path to the file, that will be removed from the report.
) throw()
{
if (!m_RemoveFileFromReport)
return false;
m_RemoveFileFromReport(path);
return true;
}
//! Fills version field (V) of ApplicationInfo with product version
//! found in the executable file of the current process.
//! \return If the function succeeds, the return value is \b true.
bool GetVersionFromApp(
ApplicationInfo* appInfo //!< [out] Pointer to ApplicationInfo structure. Its version field (V) will be set to product version.
) throw()
{
if (!m_GetVersionFromApp)
return false;
return m_GetVersionFromApp(appInfo) != FALSE;
}
//! Fill version field (V) of ApplicationInfo with product version found in the file specified.
//! \return If the function succeeds, the return value is \b true.
bool GetVersionFromFile(
LPCWSTR path, //!< [in] Path to the file product version will be extracted from.
ApplicationInfo* appInfo //!< [out] Pointer to ApplicationInfo structure. Its version field (V) will be set to product version.
) throw()
{
if (!m_GetVersionFromFile)
return false;
return m_GetVersionFromFile(path, appInfo) != FALSE;
}
//! If you do not own the process your code running in (for example you write a plugin to some
//! external application) you need to properly initialize CrashHandler using \b ownProcess option.
//! Also you need to explicitly catch all exceptions in all entry points to your code and in all
//! threads you create. To do so use this construction:
//! \code
//! bool SomeEntryPoint(PARAM p)
//! {
//! __try
//! {
//! return YouCode(p);
//! }
//! __except (CrashHandler::SendReport(GetExceptionInformation()))
//! {
//! ::ExitProcess(0); // It is better to stop the process here or else corrupted data may incomprehensibly crash it later.
//! return false;
//! }
//! }
//! \endcode
LONG SendReport(
EXCEPTION_POINTERS* exceptionPointers //!< [in] Pointer to EXCEPTION_POINTERS structure. You should get it using GetExceptionInformation()
//!< function inside __except keyword.
)
{
if (!m_SendReport)
return EXCEPTION_CONTINUE_SEARCH;
// There is no crash handler but asserts should continue anyway
if (exceptionPointers->ExceptionRecord->ExceptionCode == ExceptionAssertionViolated)
return EXCEPTION_CONTINUE_EXECUTION;
return m_SendReport(exceptionPointers);
}
//! To send a report about violated assertion you can throw exception with this exception code
//! using: \code RaiseException(CrashHandler::ExceptionAssertionViolated, 0, 0, NULL); \endcode
//! Execution will continue after report will be sent (EXCEPTION_CONTINUE_EXECUTION would be used).
//! \note If you called CrashHandler constructor and crshhdnl.dll was missing you still may using this exception.
//! It will be catched, ignored and execution will continue. \ref SendReport function also works safely
//! when crshhdnl.dll was missing.
static const DWORD ExceptionAssertionViolated = ((DWORD)0xCCE17000);
//! Sends assertion violation report from this point and continue execution.
//! \sa ExceptionAssertionViolated
//! \note Functions prefixed with "CrashServer_" will be ignored in stack parsing.
void CrashServer_SendAssertionViolated()
{
if (!m_InitCrashHandler)
return;
::RaiseException(CrashHandler::ExceptionAssertionViolated, 0, 0, NULL);
}
private:
bool LoadDll() throw()
{
bool result = false;
// hCrshhndlDll should not be unloaded, crash may appear even after return from main().
// So hCrshhndlDll is not saved after construction.
#ifdef _WIN64
HMODULE hCrshhndlDll = ::LoadLibraryW(L"crshhndl-x64.dll");
#else
HMODULE hCrshhndlDll = ::LoadLibraryW(L"crshhndl-x86.dll");
#endif
if (hCrshhndlDll != NULL)
{
m_InitCrashHandler = (pfnInitCrashHandler) GetProcAddress(hCrshhndlDll, "InitCrashHandler");
m_SendReport = (pfnSendReport) GetProcAddress(hCrshhndlDll, "SendReport");
m_IsReadyToExit = (pfnIsReadyToExit) GetProcAddress(hCrshhndlDll, "IsReadyToExit");
m_AddUserInfoToReport = (pfnAddUserInfoToReport) GetProcAddress(hCrshhndlDll, "AddUserInfoToReport");
m_AddFileToReport = (pfnAddFileToReport) GetProcAddress(hCrshhndlDll, "AddFileToReport");
m_RemoveFileFromReport = (pfnRemoveFileFromReport) GetProcAddress(hCrshhndlDll, "RemoveFileFromReport");
m_GetVersionFromApp = (pfnGetVersionFromApp) GetProcAddress(hCrshhndlDll, "GetVersionFromApp");
m_GetVersionFromFile = (pfnGetVersionFromFile) GetProcAddress(hCrshhndlDll, "GetVersionFromFile");
result = m_InitCrashHandler
&& m_SendReport
&& m_IsReadyToExit
&& m_AddUserInfoToReport
&& m_AddFileToReport
&& m_RemoveFileFromReport
&& m_GetVersionFromApp
&& m_GetVersionFromFile;
}
#if _WIN32_WINNT >= 0x0501 /*_WIN32_WINNT_WINXP*/
// if no crash processing was started, we need to ignore ExceptionAssertionViolated exceptions.
if (!result)
::AddVectoredExceptionHandler(TRUE, SkipAsserts);
#endif
return result;
}
static LONG CALLBACK SkipAsserts(EXCEPTION_POINTERS* pExceptionInfo)
{
if (pExceptionInfo->ExceptionRecord->ExceptionCode == ExceptionAssertionViolated)
return EXCEPTION_CONTINUE_EXECUTION;
return EXCEPTION_CONTINUE_SEARCH;
}
typedef BOOL (*pfnInitCrashHandler)(ApplicationInfo* applicationInfo, HandlerSettings* handlerSettings, BOOL ownProcess);
typedef LONG(*pfnSendReport)(EXCEPTION_POINTERS* exceptionPointers);
typedef BOOL (*pfnIsReadyToExit)();
typedef void (*pfnAddUserInfoToReport)(LPCWSTR key, LPCWSTR value);
typedef void (*pfnAddFileToReport)(LPCWSTR path, LPCWSTR reportFileName /* = NULL */);
typedef void (*pfnRemoveFileFromReport)(LPCWSTR path);
typedef BOOL (*pfnGetVersionFromApp)(ApplicationInfo* appInfo);
typedef BOOL (*pfnGetVersionFromFile)(LPCWSTR path, ApplicationInfo* appInfo);
pfnInitCrashHandler m_InitCrashHandler;
pfnSendReport m_SendReport;
pfnIsReadyToExit m_IsReadyToExit;
pfnAddUserInfoToReport m_AddUserInfoToReport;
pfnAddFileToReport m_AddFileToReport;
pfnRemoveFileFromReport m_RemoveFileFromReport;
pfnGetVersionFromApp m_GetVersionFromApp;
pfnGetVersionFromFile m_GetVersionFromFile;
};
#endif // __CRASH_HANDLER_H__
|
[
"entry.reg@gmail.com"
] |
entry.reg@gmail.com
|
d372ddefe8f11abd5c3ca0332453c81a962f6458
|
a13e7993275058dceae188f2101ad0750501b704
|
/2022/2133. Check if Every Row and Column Contains All Numbers.cpp
|
8bbc268b380af48d29bb0f4dfa0b3b5406021855
|
[] |
no_license
|
yangjufo/LeetCode
|
f8cf8d76e5f1e78cbc053707af8bf4df7a5d1940
|
15a4ab7ce0b92b0a774ddae0841a57974450eb79
|
refs/heads/master
| 2023-09-01T01:52:49.036101
| 2023-08-31T00:23:19
| 2023-08-31T00:23:19
| 126,698,393
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 928
|
cpp
|
class Solution {
public:
bool checkValid(vector<vector<int>>& matrix) {
int n = matrix.size();
for (int i = 0; i < n; i++) {
vector<int> found(n + 1, false);
int count = 0;
for (int j = 0; j < n; j++) {
if (found[matrix[i][j]] == false) {
found[matrix[i][j]] = true;
count++;
}
}
if (count < n) {
return false;
}
}
for (int j = 0; j < n; j++) {
vector<int> found(n + 1, false);
int count = 0;
for (int i = 0; i < n; i++) {
if (found[matrix[i][j]] == false) {
found[matrix[i][j]] = true;
count++;
}
}
if (count < n) {
return false;
}
}
return true;
}
};
|
[
"yangjufo@gmail.com"
] |
yangjufo@gmail.com
|
bbcee2ebfeeaf02d763f7215ae9820d58c5e26fb
|
2bc835b044f306fca1affd1c61b8650b06751756
|
/winhttp/v5.1/api/thrdinfo.cxx
|
7f46b85b9d656aceded250240c62c089528642f3
|
[] |
no_license
|
KernelPanic-OpenSource/Win2K3_NT_inetcore
|
bbb2354d95a51a75ce2dfd67b18cfb6b21c94939
|
75f614d008bfce1ea71e4a727205f46b0de8e1c3
|
refs/heads/master
| 2023-04-04T02:55:25.139618
| 2021-04-14T05:25:01
| 2021-04-14T05:25:01
| 357,780,123
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 42,020
|
cxx
|
/*++
Copyright (c) 1994 Microsoft Corporation
Module Name:
thrdinfo.cxx
Abstract:
Functions to manipulate an INTERNET_THREAD_INFO
Contents:
InternetCreateThreadInfo
InternetDestroyThreadInfo
InternetTerminateThreadInfo
InternetGetThreadInfo
InternetSetThreadInfo
InternetIndicateStatusAddress
InternetIndicateStatusString
InternetIndicateStatusNewHandle
InternetIndicateStatus
InternetSetLastError
_InternetSetLastError
InternetLockErrorText
InternetUnlockErrorText
InternetSetObjectHandle
InternetGetObjectHandle
InternetFreeThreadInfo
Author:
Richard L Firth (rfirth) 16-Feb-1995
Environment:
Win32 user-level DLL
Revision History:
16-Feb-1995 rfirth
Created
--*/
#include <wininetp.h>
#include <perfdiag.hxx>
//
// manifests
//
#define BAD_TLS_INDEX 0xffffffff // according to online win32 SDK documentation
#ifdef SPX_SUPPORT
#define GENERIC_SPX_NAME "SPX Server"
#endif //SPX_SUPPORT
//
// macros
//
#ifdef ENABLE_DEBUG
#define InitializeInternetThreadInfo(lpThreadInfo) \
InitializeListHead(&lpThreadInfo->List); \
lpThreadInfo->Signature = INTERNET_THREAD_INFO_SIGNATURE; \
lpThreadInfo->ThreadId = GetCurrentThreadId();
#else
#define InitializeInternetThreadInfo(threadInfo) \
InitializeListHead(&lpThreadInfo->List); \
lpThreadInfo->ThreadId = GetCurrentThreadId();
#endif // ENABLE_DEBUG
//
// private data
//
PRIVATE DWORD InternetTlsIndex = BAD_TLS_INDEX;
PRIVATE SERIALIZED_LIST ThreadInfoList;
LPINTERNET_THREAD_INFO
InternetCreateThreadInfo(
IN BOOL SetTls,
IN LPINTERNET_THREAD_INFO lpPreStaticAllocatedThreadInfo
)
/*++
Routine Description:
Creates, initializes an INTERNET_THREAD_INFO. Optionally (allocates and)
sets this thread's Internet TLS
Assumes: 1. The first time this function is called is in the context of the
process attach library call, so we allocate the TLS index once
Arguments:
SetTls - TRUE if we are to set the INTERNET_THREAD_INFO TLS for this thread
Return Value:
LPINTERNET_THREAD_INFO
Success - pointer to allocated INTERNET_THREAD_INFO structure which has
been set as this threads value in its InternetTlsIndex slot
Failure - NULL
--*/
{
LPINTERNET_THREAD_INFO lpThreadInfo = NULL;
BOOL ok = FALSE;
if (InDllCleanup)
{
goto quit;
}
if (InternetTlsIndex == BAD_TLS_INDEX)
{
//
// first time through, initialize serialized list
//
InitializeSerializedList(&ThreadInfoList);
//
// we assume that if we are allocating the TLS index, then this is the
// one and only thread in this process that can call into this DLL
// right now - i.e. this thread is loading the DLL
//
InternetTlsIndex = TlsAlloc();
}
if (InternetTlsIndex != BAD_TLS_INDEX)
{
if (lpPreStaticAllocatedThreadInfo != NULL)
{
lpThreadInfo = lpPreStaticAllocatedThreadInfo;
memset(lpThreadInfo, 0, sizeof(INTERNET_THREAD_INFO));
#if INET_DEBUG
lpThreadInfo->fStaticAllocation = TRUE;
#endif
}
else
{
lpThreadInfo = NEW(INTERNET_THREAD_INFO);
// lpThreadInfo->fStaticAllocation = FALSE; implicitly set
}
if (lpThreadInfo != NULL)
{
InitializeInternetThreadInfo(lpThreadInfo);
if (SetTls)
{
ok = TlsSetValue(InternetTlsIndex, (LPVOID)lpThreadInfo);
if (!ok)
{
DEBUG_PUT(("InternetCreateThreadInfo(): TlsSetValue(%d, %#x) returns %d\n",
InternetTlsIndex,
lpThreadInfo,
GetLastError()
));
DEBUG_BREAK(THRDINFO);
}
}
else
{
ok = TRUE;
}
}
else
{
DEBUG_PUT(("InternetCreateThreadInfo(): NEW(INTERNET_THREAD_INFO) returned NULL\n"));
DEBUG_BREAK(THRDINFO);
}
}
else
{
DEBUG_PUT(("InternetCreateThreadInfo(): TlsAlloc() returns %#x, error %d\n",
BAD_TLS_INDEX,
GetLastError()
));
DEBUG_BREAK(THRDINFO);
}
if (ok)
{
// only dynamically allocated threadinfo's are put into the
// ThreadInfoList -- statically preallocated threadinfo's must
// not go into the ThreadInfoList
if (lpPreStaticAllocatedThreadInfo == NULL)
{
if (!InsertAtHeadOfSerializedList(&ThreadInfoList, &lpThreadInfo->List))
{
ok = FALSE;
}
}
}
// If something failed, then delete any dynamically allocated threadinfo
if (!ok)
{
if ((lpPreStaticAllocatedThreadInfo == NULL) && (lpThreadInfo != NULL))
{
DEL(lpThreadInfo);
}
lpThreadInfo = NULL;
}
quit:
return lpThreadInfo;
}
VOID
InternetDestroyThreadInfo(
VOID
)
/*++
Routine Description:
Cleans up the INTERNET_THREAD_INFO - deletes any memory it owns and deletes
it
Arguments:
None.
Return Value:
None.
--*/
{
LPINTERNET_THREAD_INFO lpThreadInfo;
IF_DEBUG(NOTHING)
{
DEBUG_PUT(("InternetDestroyThreadInfo(): Thread %#x: Deleting INTERNET_THREAD_INFO\n",
GetCurrentThreadId()
));
}
//
// don't call InternetGetThreadInfo() - we don't need to create the
// INTERNET_THREAD_INFO if it doesn't exist in this case
//
lpThreadInfo = (LPINTERNET_THREAD_INFO)TlsGetValue(InternetTlsIndex);
if (lpThreadInfo != NULL)
{
#if INET_DEBUG
//
// there shouldn't be anything in the debug record stack. On Win95, we
// ignore this check if this is the async scheduler (nee worker) thread
// AND there are entries in the debug record stack. The async thread
// gets killed off before it has chance to DEBUG_LEAVE, then comes here,
// causing this assert to be over-active
//
if (IsPlatformWin95() && lpThreadInfo->IsAsyncWorkerThread)
{
if (lpThreadInfo->CallDepth != 0)
{
DEBUG_PUT(("InternetDestroyThreadInfo(): "
"Thread %#x: "
"%d records in debug stack\n",
lpThreadInfo->CallDepth
));
}
}
else
{
INET_ASSERT(lpThreadInfo->Stack == NULL);
}
#endif // INET_DEBUG
InternetFreeThreadInfo(lpThreadInfo);
INET_ASSERT(InternetTlsIndex != BAD_TLS_INDEX);
TlsSetValue(InternetTlsIndex, NULL);
}
else
{
DEBUG_PUT(("InternetDestroyThreadInfo(): Thread %#x: no INTERNET_THREAD_INFO\n",
GetCurrentThreadId()
));
}
}
VOID
InternetFreeThreadInfo(
IN LPINTERNET_THREAD_INFO lpThreadInfo
)
/*++
Routine Description:
Removes the INTERNET_THREAD_INFO from the list and frees all allocated
blocks
Arguments:
lpThreadInfo - pointer to INTERNET_THREAD_INFO to remove and free
Return Value:
None.
--*/
{
if (RemoveFromSerializedList(&ThreadInfoList, &lpThreadInfo->List))
{
if (lpThreadInfo->hErrorText != NULL)
{
FREE_MEMORY(lpThreadInfo->hErrorText);
}
//if (lpThreadInfo->lpResolverInfo != NULL) {
// if (lpThreadInfo->lpResolverInfo->DnrSocketHandle != NULL) {
// lpThreadInfo->lpResolverInfo->DnrSocketHandle->Dereference();
// }
// DEL(lpThreadInfo->lpResolverInfo);
//}
INET_ASSERT(!lpThreadInfo->fStaticAllocation);
DEL(lpThreadInfo);
}
}
VOID
InternetTerminateThreadInfo(
VOID
)
/*++
Routine Description:
Destroy all INTERNET_THREAD_INFO structures and terminate the serialized
list. This funciton called at process detach time.
At DLL_PROCESS_DETACH time, there may be other threads in the process for
which we created an INTERNET_THREAD_INFO that aren't going to get the chance
to delete the structure, so we do it here.
Code in this module assumes that it is impossible for a new thread to enter
this DLL while we are terminating in DLL_PROCESS_DETACH
Arguments:
None.
Return Value:
None.
--*/
{
//
// get rid of this thread's info structure. No more debug output after this!
//
InternetDestroyThreadInfo();
//
// get rid of the thread info structures left by other threads
//
if (LockSerializedList(&ThreadInfoList))
{
LPINTERNET_THREAD_INFO lpThreadInfo;
while (NULL != (lpThreadInfo = (LPINTERNET_THREAD_INFO)SlDequeueHead(&ThreadInfoList)))
{
//
// already dequeued, no need to call InternetFreeThreadInfo()
//
INET_ASSERT(!lpThreadInfo->fStaticAllocation);
FREE_MEMORY(lpThreadInfo);
}
UnlockSerializedList(&ThreadInfoList);
}
//
// no more need for list
//
TerminateSerializedList(&ThreadInfoList);
//
// or TLS index
//
TlsFree(InternetTlsIndex);
InternetTlsIndex = BAD_TLS_INDEX;
}
LPINTERNET_THREAD_INFO
InternetGetThreadInfo(
VOID
)
/*++
Routine Description:
Gets the pointer to the INTERNET_THREAD_INFO for this thread and checks
that it still looks good.
If this thread does not have an INTERNET_THREAD_INFO then we create one,
presuming that this is a new thread
Arguments:
None.
Return Value:
LPINTERNET_THREAD_INFO
Success - pointer to INTERNET_THREAD_INFO block
Failure - NULL
--*/
{
LPINTERNET_THREAD_INFO lpThreadInfo = NULL;
DWORD lastError;
//
// this is pretty bad - TlsGetValue() can destroy the per-thread last error
// variable if it returns NULL (to indicate that NULL was actually set, and
// that NULL does not indicate an error). So we have to read it before it is
// potentially destroyed, and reset it before we quit.
//
// We do this here because typically, other functions will be completely
// unsuspecting of this behaviour, and it is better to fix it once here,
// than in several dozen other places, even though it is slightly
// inefficient
//
lastError = GetLastError();
if (InternetTlsIndex != BAD_TLS_INDEX)
{
lpThreadInfo = (LPINTERNET_THREAD_INFO)TlsGetValue(InternetTlsIndex);
}
//
// we may be in the process of creating the INTERNET_THREAD_INFO, in
// which case its okay for this to be NULL. According to online SDK
// documentation, a threads TLS value will be initialized to NULL
//
if (lpThreadInfo == NULL)
{
//
// we presume this is a new thread. Create an INTERNET_THREAD_INFO
//
IF_DEBUG(NOTHING) {
DEBUG_PUT(("InternetGetThreadInfo(): Thread %#x: Creating INTERNET_THREAD_INFO\n",
GetCurrentThreadId()
));
}
lpThreadInfo = InternetCreateThreadInfo(TRUE);
}
if (lpThreadInfo != NULL)
{
INET_ASSERT(lpThreadInfo->Signature == INTERNET_THREAD_INFO_SIGNATURE);
INET_ASSERT(lpThreadInfo->ThreadId == GetCurrentThreadId());
}
else
{
DEBUG_PUT(("InternetGetThreadInfo(): Failed to get/create INTERNET_THREAD_INFO\n"));
}
//
// as above - reset the last error variable in case TlsGetValue() trashed it
//
SetLastError(lastError);
//
// actual success/failure indicated by non-NULL/NULL pointer resp.
//
return lpThreadInfo;
}
VOID
InternetSetThreadInfo(
IN LPINTERNET_THREAD_INFO lpThreadInfo
)
/*++
Routine Description:
Sets lpThreadInfo as the current thread's INTERNET_THREAD_INFO. Used within
fibers
Arguments:
lpThreadInfo - new INTERNET_THREAD_INFO to set
Return Value:
None.
--*/
{
if (InternetTlsIndex != BAD_TLS_INDEX)
{
if (!TlsSetValue(InternetTlsIndex, (LPVOID)lpThreadInfo))
{
DEBUG_PUT(("InternetSetThreadInfo(): TlsSetValue(%d, %#x) returns %d\n",
InternetTlsIndex,
lpThreadInfo,
GetLastError()
));
INET_ASSERT(FALSE);
}
}
else
{
DEBUG_PUT(("InternetSetThreadInfo(): InternetTlsIndex = %d\n",
InternetTlsIndex
));
INET_ASSERT(FALSE);
}
}
DWORD
InternetIndicateStatusAddress(
IN DWORD dwInternetStatus,
IN LPSOCKADDR lpSockAddr,
IN DWORD dwSockAddrLength
)
/*++
Routine Description:
Make a status callback to the app. The data is a network address that we
need to convert to a string
Arguments:
dwInternetStatus - WINHTTP_CALLBACK_STATUS_ value
lpSockAddr - pointer to full socket address
dwSockAddrLength - length of lpSockAddr in bytes
Return Value:
DWORD
Success - ERROR_SUCCESS
Failure - ERROR_WINHTTP_OPERATION_CANCELLED
The app closed the object handle during the callback
--*/
{
LPSTR lpAddress;
INT len;
UNREFERENCED_PARAMETER(dwSockAddrLength);
INET_ASSERT(lpSockAddr != NULL);
switch (lpSockAddr->sa_family)
{
case AF_INET:
lpAddress = _I_inet_ntoa(
((struct sockaddr_in*)lpSockAddr)->sin_addr
);
break;
case AF_INET6:
char Address[INET6_ADDRSTRLEN+3]; // + 2 brkt chars + null char
int error;
Address[0] = '[';
error = _I_getnameinfo(lpSockAddr, sizeof(SOCKADDR_IN6),
Address+1, sizeof(Address)-2, NULL, 0,
NI_NUMERICHOST);
if (error)
lpAddress = NULL;
else {
len = lstrlen(Address);
Address[len] = ']';
Address[len+1] = '\0';
lpAddress = Address;
}
break;
case AF_IPX:
//
// BUGBUG - this should be a call to WSAAddressToString, but that's not implemented yet
//
#ifdef SPX_SUPPORT
lpAddress = GENERIC_SPX_NAME;
#else
lpAddress = NULL;
#endif //SPX_SUPPORT
break;
default:
lpAddress = NULL;
break;
}
// we don't want a client to mess around with a winsock-internal buffer
return InternetIndicateStatusString(dwInternetStatus, lpAddress, TRUE/*bCopyBuffer*/);
}
DWORD
InternetIndicateStatusString(
IN DWORD dwInternetStatus,
IN LPSTR lpszStatusInfo OPTIONAL,
IN BOOL bCopyBuffer,
IN BOOL bConvertToUnicode
)
/*++
Routine Description:
Make a status callback to the app. The data is a string
Arguments:
dwInternetStatus - WINHTTP_CALLBACK_STATUS_ value
lpszStatusInfo - string status data
Return Value:
DWORD
Success - ERROR_SUCCESS
Failure - ERROR_WINHTTP_OPERATION_CANCELLED
The app closed the object handle during the callback
--*/
{
DEBUG_ENTER((DBG_THRDINFO,
Dword,
"InternetIndicateStatusString",
"%d, %q",
dwInternetStatus,
lpszStatusInfo
));
DWORD length;
if (ARGUMENT_PRESENT(lpszStatusInfo))
{
length = strlen(lpszStatusInfo) + 1;
}
else
{
length = 0;
}
DWORD error;
error = InternetIndicateStatus(dwInternetStatus, lpszStatusInfo, length, bCopyBuffer, bConvertToUnicode);
DEBUG_LEAVE(error);
return error;
}
DWORD
InternetIndicateStatusNewHandle(
IN LPVOID hInternetMapped
)
/*++
Routine Description:
Indicates to the app a new handle
Arguments:
hInternetMapped - mapped address of new handle being indicated
Return Value:
DWORD
Success - ERROR_SUCCESS
Failure - ERROR_WINHTTP_OPERATION_CANCELLED
The app closed the either the new object handle or the
parent object handle during the callback
--*/
{
DEBUG_ENTER((DBG_THRDINFO,
Dword,
"InternetIndicateStatusNewHandle",
"%#x",
hInternetMapped
));
HANDLE_OBJECT * hObject = (HANDLE_OBJECT *)hInternetMapped;
//
// reference the new request handle, in case the app closes it in the
// callback. The new handle now has a reference count of 3
//
hObject->Reference();
INET_ASSERT(hObject->ReferenceCount() == 3);
//
// we indicate the pseudo handle to the app
//
HINTERNET hInternet = hObject->GetPseudoHandle();
DWORD error = InternetIndicateStatus(WINHTTP_CALLBACK_STATUS_HANDLE_CREATED,
(LPVOID)&hInternet,
sizeof(hInternet)
);
//
// dereference the new request handle. If this returns TRUE then the new
// handle has been deleted (the app called InternetCloseHandle() against
// it which dereferenced it to 1, and now we've dereferenced it to zero)
//
hObject->Dereference();
if (error == ERROR_WINHTTP_OPERATION_CANCELLED)
{
//
// the parent handle was deleted. Kill off the new handle too
//
WinHttpCloseHandle(hObject);
//BOOL ok;
//ok = hObject->Dereference();
// INET_ASSERT(ok);
INET_ASSERT(hObject->ReferenceCount() == 1); // now only ref'ed by the API
}
else if (hObject->IsInvalidated())
{
INET_ASSERT(hObject->ReferenceCount() == 1); // now only ref'ed by the API
error = ERROR_WINHTTP_OPERATION_CANCELLED;
}
DEBUG_LEAVE(error);
return error;
}
DWORD
InternetIndicateStatus(
IN DWORD dwStatus,
IN LPVOID lpBuffer,
IN DWORD dwLength,
IN BOOL bCopyBuffer,
IN BOOL bConvertToUnicode
)
/*++
Routine Description:
If the app has registered a callback function for the object that this
thread is operating on, call it with the arguments supplied
Arguments:
dwStatus - WINHTTP_CALLBACK_STATUS_ value
lpBuffer - pointer to variable data buffer
dwLength - length of *lpBuffer in bytes
Return Value:
DWORD
Success - ERROR_SUCCESS
Failure - ERROR_WINHTTP_OPERATION_CANCELLED
The app closed the object handle during the callback
--*/
{
DEBUG_ENTER((DBG_THRDINFO,
Dword,
"InternetIndicateStatus",
"%s, %#x, %d",
InternetMapStatus(dwStatus),
lpBuffer,
dwLength
));
LPINTERNET_THREAD_INFO lpThreadInfo = InternetGetThreadInfo();
DWORD error = ERROR_SUCCESS;
//
// the app can affect callback operation by specifying a zero context value
// meaning no callbacks will be generated for this API
//
if (lpThreadInfo != NULL)
{
INET_ASSERT(lpThreadInfo->hObject != NULL);
INET_ASSERT(lpThreadInfo->hObjectMapped != NULL);
//
// if the context value in the thread info block is 0 then we use the
// context from the handle object
//
DWORD_PTR context;
context = ((INTERNET_HANDLE_BASE *)lpThreadInfo->hObjectMapped)->GetContext();
WINHTTP_STATUS_CALLBACK appCallback;
appCallback = ((INTERNET_HANDLE_BASE *)lpThreadInfo->hObjectMapped)->GetStatusCallback();
IF_DEBUG(THRDINFO)
{
switch (dwStatus)
{
case WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE:
case WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE:
DEBUG_PRINT(THRDINFO,
INFO,
("%s\n",
InternetMapStatus(dwStatus)
));
break;
case WINHTTP_CALLBACK_STATUS_WRITE_COMPLETE:
case WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE:
DEBUG_PRINT(THRDINFO,
INFO,
("%s: #bytes = %d [%#x]\n",
InternetMapStatus(dwStatus),
*((DWORD*)lpBuffer),
*((DWORD*)lpBuffer)
));
break;
case WINHTTP_CALLBACK_STATUS_READ_COMPLETE:
DEBUG_PRINT(THRDINFO,
INFO,
("%s: Buffer = %#x, Number of bytes = %d\n",
InternetMapStatus(dwStatus),
lpBuffer,
dwLength
));
break;
case WINHTTP_CALLBACK_STATUS_REQUEST_ERROR:
DEBUG_PRINT(THRDINFO,
INFO,
("%s: failure api = %d, Number of bytes = %d [%#x, %#s] \n",
InternetMapStatus(dwStatus),
((LPWINHTTP_ASYNC_RESULT)lpBuffer)->dwResult,
((LPWINHTTP_ASYNC_RESULT)lpBuffer)->dwError,
((LPWINHTTP_ASYNC_RESULT)lpBuffer)->dwError,
InternetMapError(((LPWINHTTP_ASYNC_RESULT)lpBuffer)->dwError)
));
}
}
if( dwStatus == WINHTTP_CALLBACK_STATUS_REQUEST_ERROR)
{
TRACE_PRINT_API(THRDINFO,
INFO,
("%s: Failure API = %s, Error = %s\n",
InternetMapStatus(dwStatus),
InternetMapRequestError( (DWORD) ((LPWINHTTP_ASYNC_RESULT)lpBuffer)->dwResult),
InternetMapError(((LPWINHTTP_ASYNC_RESULT)lpBuffer)->dwError)
));
}
if ((appCallback != NULL) &&
(((INTERNET_HANDLE_BASE *)lpThreadInfo->hObjectMapped)->IsNotificationEnabled(dwStatus)) )
{
LPVOID pInfo; //reported thru callback
DWORD infoLength; //reported thru callback
BOOL isAsyncWorkerThread;
BYTE buffer[256];
//
// we make a copy of the info to remove the app's opportunity to
// change it. E.g. if we were about to resolve host name "foo" and
// passed the pointer to our buffer containing "foo", the app could
// change the name to "bar", changing the intended server
//
if (lpBuffer != NULL)
{
if (bConvertToUnicode)
{
INET_ASSERT( ((INTERNET_HANDLE_BASE *)lpThreadInfo->hObjectMapped)->IsUnicodeStatusCallback() );
INET_ASSERT(
(dwStatus == WINHTTP_CALLBACK_STATUS_RESOLVING_NAME) ||
(dwStatus == WINHTTP_CALLBACK_STATUS_NAME_RESOLVED) ||
(dwStatus == WINHTTP_CALLBACK_STATUS_REDIRECT) ||
(dwStatus == WINHTTP_CALLBACK_STATUS_CONNECTING_TO_SERVER) ||
(dwStatus == WINHTTP_CALLBACK_STATUS_CONNECTED_TO_SERVER)
);
infoLength = MultiByteToWideChar(CP_ACP, 0, (LPSTR)lpBuffer,
dwLength, NULL, 0);
if (infoLength == 0)
{
pInfo = NULL;
DEBUG_PRINT(THRDINFO,
ERROR,
("MultiByteToWideChar returned 0 for a %d-length MBCS string\n",
dwLength
));
}
else if (infoLength <= sizeof(buffer)/sizeof(WCHAR))
{
pInfo = buffer;
}
else
{
pInfo = (LPVOID)ALLOCATE_FIXED_MEMORY(infoLength * sizeof(WCHAR));
}
if (pInfo)
{
infoLength = MultiByteToWideChar(CP_ACP, 0, (LPSTR)lpBuffer,
dwLength, (LPWSTR)pInfo, infoLength);
if (infoLength == 0)
{
//MBtoWC failed
if (pInfo != buffer)
FREE_FIXED_MEMORY(pInfo);
pInfo = NULL;
DEBUG_PRINT(THRDINFO,
ERROR,
("MultiByteToWideChar returned 0 for a %d-length MBCS string\n",
dwLength
));
}
} //pInfo
else
{
infoLength = 0;
DEBUG_PRINT(THRDINFO,
ERROR,
("MultiByteToWideChar() error OR Failed to allocate %d bytes for info\n",
dwLength
));
} //pInfo == NULL
} //bConvertToUnicode
else if (bCopyBuffer)
{
if (dwLength <= sizeof(buffer))
pInfo = buffer;
else
pInfo = (LPVOID)ALLOCATE_FIXED_MEMORY(dwLength);
if (pInfo)
{
memcpy(pInfo, lpBuffer, dwLength);
infoLength = dwLength;
}
else
{
infoLength = 0;
DEBUG_PRINT(THRDINFO,
ERROR,
("Failed to allocate %d bytes for info\n",
dwLength
));
}
} //bCopyBuffer
else
{
pInfo = lpBuffer;
infoLength = dwLength;
INET_ASSERT(dwLength
|| (WINHTTP_CALLBACK_STATUS_READ_COMPLETE == dwStatus));
} //!bCopyBuffer && !bConvertToUnicode
} //lpBuffer != NULL
else
{
pInfo = NULL;
infoLength = 0;
}
//
// we're about to call into the app. We may be in the context of an
// async worker thread, and if the callback submits an async request
// then we'll execute it synchronously. To avoid this, we will reset
// the async worker thread indicator in the INTERNET_THREAD_INFO and
// restore it when the app returns control to us. This way, if the
// app makes an API request during the callback, on a handle that
// has async I/O semantics, then we will simply queue it, and not
// try to execute it synchronously
//
isAsyncWorkerThread = lpThreadInfo->IsAsyncWorkerThread;
lpThreadInfo->IsAsyncWorkerThread = FALSE;
BOOL bInCallback = lpThreadInfo->InCallback;
lpThreadInfo->InCallback = TRUE;
INET_ASSERT(!IsBadCodePtr((FARPROC)appCallback));
DEBUG_ENTER((DBG_THRDINFO,
None,
"(*callback)",
"%#x, %#x, %s (%d), %#x [%#x], %d",
lpThreadInfo->hObject,
context,
InternetMapStatus(dwStatus),
dwStatus,
pInfo,
((dwStatus == WINHTTP_CALLBACK_STATUS_HANDLE_CREATED)
|| (dwStatus == WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING))
? (DWORD_PTR)*(LPHINTERNET)pInfo
: (((dwStatus == WINHTTP_CALLBACK_STATUS_REQUEST_SENT)
|| (dwStatus == WINHTTP_CALLBACK_STATUS_RESPONSE_RECEIVED)
|| (dwStatus == WINHTTP_CALLBACK_STATUS_INTERMEDIATE_RESPONSE))
? *(LPDWORD)pInfo
: 0),
infoLength
));
PERF_LOG(PE_APP_CALLBACK_START,
dwStatus,
lpThreadInfo->ThreadId,
lpThreadInfo->hObject
);
HINTERNET hObject = lpThreadInfo->hObject;
LPVOID hObjectMapped = lpThreadInfo->hObjectMapped;
appCallback(lpThreadInfo->hObject,
context,
dwStatus,
pInfo,
infoLength
);
lpThreadInfo->hObject = hObject;
lpThreadInfo->hObjectMapped = hObjectMapped;
PERF_LOG(PE_APP_CALLBACK_END,
dwStatus,
lpThreadInfo->ThreadId,
lpThreadInfo->hObject
);
DEBUG_LEAVE(0);
lpThreadInfo->InCallback = bInCallback;
lpThreadInfo->IsAsyncWorkerThread = isAsyncWorkerThread;
//
// free the buffer
//
// We should free the memory only if we have done an ALLOCATE_FIXED_MEMORY in this function:
if (pInfo != NULL && pInfo != lpBuffer && pInfo != buffer) {
FREE_FIXED_MEMORY(pInfo);
}
} else {
DEBUG_PRINT(THRDINFO,
ERROR,
("%#x: callback = %#x, context = %#x\n",
lpThreadInfo->hObject,
appCallback,
context
));
//
// if we're completing a request then we shouldn't be here - it
// means we lost the context or callback address somewhere along the
// way
//
// don't need the ASSERTS below.
// It could also mean something as benign as the notification not being enabled:
/*
INET_ASSERT(
dwStatus != WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE
&& dwStatus != WINHTTP_CALLBACK_STATUS_WRITE_COMPLETE
&& dwStatus != WINHTTP_CALLBACK_STATUS_REQUEST_ERROR
&& dwStatus != WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE
&& dwStatus != WINHTTP_CALLBACK_STATUS_READ_COMPLETE
);
*/
#ifdef DEBUG
if (
dwStatus == WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE
|| dwStatus == WINHTTP_CALLBACK_STATUS_WRITE_COMPLETE
|| dwStatus == WINHTTP_CALLBACK_STATUS_REQUEST_ERROR
|| dwStatus == WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE
|| dwStatus == WINHTTP_CALLBACK_STATUS_READ_COMPLETE
)
{
INET_ASSERT(appCallback != NULL);
/*
These are not valid asserts in winhttp.
Contexts don't control whether callbacks are made or not.
*/
//INET_ASSERT(context != NULL);
//INET_ASSERT(_InternetGetContext(lpThreadInfo) != NULL);
}
#endif
}
//
// if the object is now invalid then the app closed the handle in
// the callback, or from an external thread and the entire operation is cancelled
// propagate this error back to calling code.
//
if (((HANDLE_OBJECT *)lpThreadInfo->hObjectMapped)->IsInvalidated())
{
error = ERROR_WINHTTP_OPERATION_CANCELLED;
}
} else {
//
// this is catastrophic if the indication was async request completion
//
DEBUG_PUT(("InternetIndicateStatus(): no INTERNET_THREAD_INFO?\n"));
}
DEBUG_LEAVE(error);
return error;
}
DWORD
InternetSetLastError(
IN DWORD ErrorNumber,
IN LPSTR ErrorText,
IN DWORD ErrorTextLength,
IN DWORD Flags
)
/*++
Routine Description:
Copies the error text to the per-thread error buffer (moveable memory)
Arguments:
ErrorNumber - protocol-specific error code
ErrorText - protocol-specific error text (from server). The buffer is
NOT zero-terminated
ErrorTextLength - number of characters in ErrorText
Flags - Flags that control how this function operates:
SLE_APPEND TRUE if ErrorText is to be appended
to the text already in the buffer
SLE_ZERO_TERMINATE TRUE if ErrorText must have a '\0'
appended to it
Return Value:
DWORD
Success - ERROR_SUCCESS
Failure - Win32 error
--*/
{
DEBUG_ENTER((DBG_THRDINFO,
Dword,
"InternetSetLastError",
"%d, %.80q, %d, %#x",
ErrorNumber,
ErrorText,
ErrorTextLength,
Flags
));
DWORD error;
LPINTERNET_THREAD_INFO lpThreadInfo;
lpThreadInfo = InternetGetThreadInfo();
if (lpThreadInfo != NULL) {
error = _InternetSetLastError(lpThreadInfo,
ErrorNumber,
ErrorText,
ErrorTextLength,
Flags
);
} else {
DEBUG_PUT(("InternetSetLastError(): no INTERNET_THREAD_INFO\n"));
error = ERROR_WINHTTP_INTERNAL_ERROR;
}
DEBUG_LEAVE(error);
return error;
}
DWORD
_InternetSetLastError(
IN LPINTERNET_THREAD_INFO lpThreadInfo,
IN DWORD ErrorNumber,
IN LPSTR ErrorText,
IN DWORD ErrorTextLength,
IN DWORD Flags
)
/*++
Routine Description:
Sets or resets the last error text in an INTERNET_THREAD_INFO block
Arguments:
lpThreadInfo - pointer to INTERNET_THREAD_INFO
ErrorNumber - protocol-specific error code
ErrorText - protocol-specific error text (from server). The buffer is
NOT zero-terminated
ErrorTextLength - number of characters in ErrorText
Flags - Flags that control how this function operates:
SLE_APPEND TRUE if ErrorText is to be appended
to the text already in the buffer
SLE_ZERO_TERMINATE TRUE if ErrorText must have a '\0'
appended to it
Return Value:
DWORD
Success - ERROR_SUCCESS
Failure - Win32 error
--*/
{
DEBUG_ENTER((DBG_THRDINFO,
Dword,
"_InternetSetLastError",
"%#x, %d, %.80q, %d, %#x",
lpThreadInfo,
ErrorNumber,
ErrorText,
ErrorTextLength,
Flags
));
DWORD currentLength = 0;
DWORD newTextLength;
DWORD error;
newTextLength = ErrorTextLength;
//
// if we are appending text, then account for the '\0' currently at the end
// of the buffer (if it exists)
//
if (Flags & SLE_APPEND) {
currentLength = lpThreadInfo->ErrorTextLength;
if (currentLength != 0) {
--currentLength;
}
newTextLength += currentLength;
}
if (Flags & SLE_ZERO_TERMINATE) {
++newTextLength;
}
//
// expect success (and why not?)
//
error = ERROR_SUCCESS;
//
// allocate, grow or shrink the buffer to fit. The buffer is moveable. If
// the buffer is being shrunk to zero size then NULL will be returned as
// the buffer handle from ResizeBuffer()
//
lpThreadInfo->hErrorText = ResizeBuffer(lpThreadInfo->hErrorText,
newTextLength,
FALSE
);
if (lpThreadInfo->hErrorText != NULL) {
LPSTR lpErrorText;
lpErrorText = (LPSTR)LOCK_MEMORY(lpThreadInfo->hErrorText);
INET_ASSERT(lpErrorText != NULL);
if (lpErrorText != NULL) {
if (Flags & SLE_APPEND) {
lpErrorText += currentLength;
}
memcpy(lpErrorText, ErrorText, ErrorTextLength);
if (Flags & SLE_ZERO_TERMINATE) {
lpErrorText[ErrorTextLength++] = '\0';
}
//
// the text should always be zero-terminated. We expect this in
// InternetGetLastResponseInfo()
//
INET_ASSERT(lpErrorText[ErrorTextLength - 1] == '\0');
UNLOCK_MEMORY(lpThreadInfo->hErrorText);
} else {
//
// real error occurred - failed to lock memory?
//
error = GetLastError();
}
} else {
INET_ASSERT(newTextLength == 0);
newTextLength = 0;
}
//
// set the error code and text length
//
lpThreadInfo->ErrorTextLength = newTextLength;
lpThreadInfo->ErrorNumber = ErrorNumber;
DEBUG_LEAVE(error);
return error;
}
LPSTR
InternetLockErrorText(
VOID
)
/*++
Routine Description:
Returns a pointer to the locked per-thread error text buffer
Arguments:
None.
Return Value:
LPSTR
Success - pointer to locked buffer
Failure - NULL
--*/
{
LPINTERNET_THREAD_INFO lpThreadInfo;
lpThreadInfo = InternetGetThreadInfo();
if (lpThreadInfo != NULL) {
HLOCAL lpErrorText;
lpErrorText = lpThreadInfo->hErrorText;
if (lpErrorText != (HLOCAL)NULL) {
return (LPSTR)LOCK_MEMORY(lpErrorText);
}
}
return NULL;
}
//
//VOID
//InternetUnlockErrorText(
// VOID
// )
//
///*++
//
//Routine Description:
//
// Unlocks the per-thread error text buffer locked by InternetLockErrorText()
//
//Arguments:
//
// None.
//
//Return Value:
//
// None.
//
//--*/
//
//{
// LPINTERNET_THREAD_INFO lpThreadInfo;
//
// lpThreadInfo = InternetGetThreadInfo();
//
// //
// // assume that if we locked the error text, there must be an
// // INTERNET_THREAD_INFO when we come to unlock it
// //
//
// INET_ASSERT(lpThreadInfo != NULL);
//
// if (lpThreadInfo != NULL) {
//
// HLOCAL hErrorText;
//
// hErrorText = lpThreadInfo->hErrorText;
//
// //
// // similarly, there must be a handle to the error text buffer
// //
//
// INET_ASSERT(hErrorText != NULL);
//
// if (hErrorText != (HLOCAL)NULL) {
// UNLOCK_MEMORY(hErrorText);
// }
// }
//}
VOID
InternetSetObjectHandle(
IN HINTERNET hInternet,
IN HINTERNET hInternetMapped
)
/*++
Routine Description:
Sets the hObject field in the INTERNET_THREAD_INFO structure so we can get
at the handle contents, even when we're in a function that does not take
the hInternet as a parameter
Arguments:
hInternet - handle of object we may need info from
hInternetMapped - mapped handle of object we may need info from
Return Value:
None.
--*/
{
LPINTERNET_THREAD_INFO lpThreadInfo;
lpThreadInfo = InternetGetThreadInfo();
if (lpThreadInfo != NULL) {
_InternetSetObjectHandle(lpThreadInfo, hInternet, hInternetMapped);
}
}
HINTERNET
InternetGetObjectHandle(
VOID
)
/*++
Routine Description:
Just returns the hObject value stored in our INTERNET_THREAD_INFO
Arguments:
None.
Return Value:
HINTERNET
Success - non-NULL handle value
Failure - NULL object handle (may not have been set)
--*/
{
LPINTERNET_THREAD_INFO lpThreadInfo;
HINTERNET hInternet;
lpThreadInfo = InternetGetThreadInfo();
if (lpThreadInfo != NULL) {
hInternet = lpThreadInfo->hObject;
} else {
hInternet = NULL;
}
return hInternet;
}
HINTERNET
InternetGetMappedObjectHandle(
VOID
)
/*++
Routine Description:
Just returns the hObjectMapped value stored in our INTERNET_THREAD_INFO
Arguments:
None.
Return Value:
HINTERNET
Success - non-NULL handle value
Failure - NULL object handle (may not have been set)
--*/
{
LPINTERNET_THREAD_INFO lpThreadInfo;
HINTERNET hInternet;
lpThreadInfo = InternetGetThreadInfo();
if (lpThreadInfo != NULL) {
hInternet = lpThreadInfo->hObjectMapped;
} else {
hInternet = NULL;
}
return hInternet;
}
|
[
"polarisdp@gmail.com"
] |
polarisdp@gmail.com
|
12905e1f5232ee29d47e845f0ed5b4f3412f9fbd
|
0b63fa8325233e25478b76d0b4a9a6ee3070056d
|
/src/appleseed/foundation/utility/benchmark/helpers.h
|
7f4d4a7edeaa073b7a736466786653bf592111d7
|
[
"MIT"
] |
permissive
|
hipopotamo-hipotalamo/appleseed
|
e8c61ccec64baf01b6aeb3cde4dd3031d37ece17
|
eaf07e3e602218a35711e7495ac633ce210c6078
|
refs/heads/master
| 2020-12-07T02:39:27.454003
| 2013-10-29T13:10:59
| 2013-10-29T13:10:59
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 12,695
|
h
|
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited
//
// 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.
//
#ifndef APPLESEED_FOUNDATION_UTILITY_BENCHMARK_HELPERS_H
#define APPLESEED_FOUNDATION_UTILITY_BENCHMARK_HELPERS_H
// appleseed.foundation headers.
#include "foundation/utility/benchmark/benchmarksuite.h"
#include "foundation/utility/benchmark/benchmarksuiterepository.h"
#include "foundation/utility/benchmark/ibenchmarkcase.h"
#include "foundation/utility/benchmark/ibenchmarkcasefactory.h"
namespace foundation
{
//
// Define a benchmark suite.
//
#define BENCHMARK_SUITE(Name) \
namespace BenchmarkSuite##Name \
{ \
struct BenchmarkSuite##Name \
: public foundation::BenchmarkSuite \
{ \
BenchmarkSuite##Name() \
: foundation::BenchmarkSuite(#Name) \
{ \
} \
}; \
\
foundation::BenchmarkSuite& current_benchmark_suite__() \
{ \
static BenchmarkSuite##Name bs; \
return bs; \
} \
\
struct RegisterBenchmarkSuite##Name \
{ \
RegisterBenchmarkSuite##Name() \
{ \
using namespace foundation; \
BenchmarkSuite& suite = current_benchmark_suite__(); \
BenchmarkSuiteRepository::instance().register_suite(&suite); \
} \
}; \
\
static RegisterBenchmarkSuite##Name RegisterBenchmarkSuite##Name##_instance__; \
} \
\
namespace BenchmarkSuite##Name
//
// Define a benchmark case without fixture.
//
#define BENCHMARK_CASE(Name) \
struct BenchmarkCase##Name \
: public foundation::IBenchmarkCase \
{ \
virtual const char* get_name() const \
{ \
return #Name; \
} \
\
virtual void run(); \
}; \
\
struct BenchmarkCase##Name##Factory \
: public foundation::IBenchmarkCaseFactory \
{ \
virtual const char* get_name() const \
{ \
return #Name; \
} \
\
virtual foundation::IBenchmarkCase* create() \
{ \
return new BenchmarkCase##Name(); \
} \
}; \
\
struct RegisterBenchmarkCase##Name \
{ \
RegisterBenchmarkCase##Name() \
{ \
using namespace foundation; \
static BenchmarkCase##Name##Factory factory; \
current_benchmark_suite__().register_case(&factory); \
} \
}; \
\
static RegisterBenchmarkCase##Name RegisterBenchmarkCase##Name##_instance__; \
\
void BenchmarkCase##Name::run()
//
// Define a benchmark case with fixture.
//
#define BENCHMARK_CASE_F(Name, FixtureName) \
struct BenchmarkCase##Name \
: public foundation::IBenchmarkCase \
, public FixtureName \
{ \
virtual const char* get_name() const \
{ \
return #Name; \
} \
\
virtual void run(); \
}; \
\
struct BenchmarkCase##Name##Factory \
: public foundation::IBenchmarkCaseFactory \
{ \
virtual const char* get_name() const \
{ \
return #Name; \
} \
\
virtual foundation::IBenchmarkCase* create() \
{ \
return new BenchmarkCase##Name(); \
} \
}; \
\
struct RegisterBenchmarkCase##Name \
{ \
RegisterBenchmarkCase##Name() \
{ \
using namespace foundation; \
static BenchmarkCase##Name##Factory factory; \
current_benchmark_suite__().register_case(&factory); \
} \
}; \
\
static RegisterBenchmarkCase##Name RegisterBenchmarkCase##Name##_instance__; \
\
void BenchmarkCase##Name::run()
//
// Forward-declare a benchmark case.
//
#define DECLARE_BENCHMARK_CASE(SuiteName, CaseName) \
namespace BenchmarkSuite##SuiteName { struct BenchmarkCase##CaseName; }
//
// Declare that a benchmark case has access to the internals of a class.
//
#define GRANT_ACCESS_TO_BENCHMARK_CASE(SuiteName, CaseName) \
friend struct BenchmarkSuite##SuiteName::BenchmarkCase##CaseName
} // namespace foundation
#endif // !APPLESEED_FOUNDATION_UTILITY_BENCHMARK_HELPERS_H
|
[
"beaune@aist.enst.fr"
] |
beaune@aist.enst.fr
|
6e49bcbc3b9a2a47610cd564e4d4cdd5241fae11
|
e44efcd7ff9278592b374fb49b65561a26fc125f
|
/RLSimion/Lib/neural-network.h
|
5492baffbbdfafdb46a2b15f04f085447422f62a
|
[
"Zlib",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"X11",
"MIT"
] |
permissive
|
utercero/SimionZoo
|
341da0950a0642679414a6e07ed7ba0d9ff85ba3
|
1fa570ae88f5d7e88e13a67ec27cda2de820ffee
|
refs/heads/master
| 2021-07-16T00:27:33.589997
| 2020-03-24T09:34:47
| 2020-03-24T09:34:47
| 251,345,276
| 0
| 0
|
NOASSERTION
| 2020-03-30T15:21:06
| 2020-03-30T15:21:06
| null |
UTF-8
|
C++
| false
| false
| 1,803
|
h
|
#pragma once
#include <string>
using namespace std;
//In progress:: NOT USABLE YET
/*
class NeuralNetwork : public StateActionFunction
{
vector<string> m_inputStateVariables;
vector<string> m_inputActionVariables;
size_t m_inputSize = 0;
protected:
INetwork * m_pNetwork = nullptr;
NeuralNetwork() = default;
NeuralNetwork(INetwork* pNetwork, vector<string>& inputStateVariables, vector<string>& inputActionVariables, int outputSize);
size_t m_outputSize = 0;
vector<double> m_inputStateBuffer;
vector<double> m_inputActionBuffer;
vector<double> m_outputBuffer;
public:
virtual ~NeuralNetwork();
size_t getInputSize();
size_t getOutputSize();
unsigned int getNumOutputs();
vector<double>& evaluate(const State* s, const Action* a);
const vector<string>& getInputStateVariables() { return m_inputStateVariables; }
const vector<string>& getInputActionVariables() { return m_inputActionVariables; }
};
class NNQFunctionDiscreteActions : public NeuralNetwork
{
vector<double> m_outputActionValues;
NNQFunctionDiscreteActions() = default;
public:
NNQFunctionDiscreteActions(INetwork* pNetwork, vector<string> &inputStateVariables, string outputAction, size_t numSteps, double min, double max);
double getActionIndexOutput(size_t actionIndex);
size_t getClosestOutputIndex(double value);
NNQFunctionDiscreteActions* clone();
};
class NNQFunction : public NeuralNetwork
{
NNQFunction() = default;
public:
NNQFunction(INetwork* pNetwork, vector<string> &inputStateVariables, vector<string> &inputActionVariables);
NNQFunction* clone();
};
class NNStateFunction : public NeuralNetwork
{
NNStateFunction() = default;
public:
NNStateFunction(INetwork* pNetwork, vector<string> &inputStateVariables, vector<string>& outputActionVariables);
NNStateFunction* clone();
};
*/
|
[
"borja.fernandez@ehu.eus"
] |
borja.fernandez@ehu.eus
|
03fd3b8c0ccfe7473fd4d3448b4c64d31898cb8a
|
d9a6b301d938e76dc94a8f4a0159abf627da1f1f
|
/game/Source/attacker.cpp
|
6b15c78d53097ac1a7ce278274ec39f9a69344c0
|
[] |
no_license
|
benjcleveland/UW-Game
|
ea3c1111d86c35075f6c6305ca78c3e14037b13b
|
83722919c9ed464639dee5b0f890bed90b163bfb
|
refs/heads/master
| 2021-01-02T09:14:47.578658
| 2012-05-02T02:01:47
| 2012-05-02T02:01:47
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,115
|
cpp
|
/* Copyright Steve Rabin, 2008.
* All rights reserved worldwide.
*
* This software is provided "as is" without express or implied
* warranties. You may freely copy and compile this source into
* applications you distribute provided that the copyright text
* below is included in the resulting source code, for example:
* "Portions Copyright Steve Rabin, 2008"
*/
#include "DXUT.h"
#include "attacker.h"
#include "database.h"
#include "collision.h"
#include "Tiny.h"
#include "deathsm.h"
// another hack
extern VecCollQuad vecCollQuad;
extern CTiny *g_pPlayer;
//Add new states here
enum StateName {
STATE_Initialize, //Note: the first enum is the starting state
STATE_Idle,
STATE_AttackPlayer,
STATE_Runaway,
STATE_ArrivedAtLocation
};
//Add new substates here
enum SubstateName {
SUBSTATE_RenameThisSubstate1,
SUBSTATE_RenameThisSubstate2,
SUBSTATE_RenameThisSubstate3
};
bool Attacker::States( State_Machine_Event event, MSG_Object * msg, int state, int substate )
{
BeginStateMachine
//Global message responses go here
/* Not currently used */
OnMsg( MSG_CollisionPlayer )
// stop moving
m_owner->getMovement()->setTarget(m_owner->getMovement()->getPosition());
//ChangeStateDelayed(10, STATE_Runaway );
OnMsg(MSG_ASTAR_DEBUG)
// toggle a star debugging
m_owner->setAStarDebug(msg->GetBoolData());
OnMsg(MSG_NPCHitByProjectile)
// npc has been hit - replace this sm with death state machine
ReplaceStateMachine( *new Death(*m_owner));
OnMsg(MSG_Reset)
m_owner->getMovement()->reset();
//PopStateMachine();
///////////////////////////////////////////////////////////////
DeclareState( STATE_Initialize )
OnEnter
ChangeState( STATE_Idle );
///////////////////////////////////////////////////////////////
DeclareState( STATE_Idle )
OnEnter
// make sure we can see the player and we are within the appropriate distance
bool see_player = runNPCSeePlayer(&m_owner->getMovement()->getPosition(), &g_pPlayer->GetPosition());
float dist = D3DXVec3Length( &(m_owner->getMovement()->getPosition() - g_pPlayer->GetPosition()));
if( see_player == true && dist < 5)
{
// change the state to seeking the player
ChangeState( STATE_AttackPlayer );
}
else
{
// we can't see the player so go back to wandering
// do this by removing the attacker statemachine
PopStateMachine();
}
///////////////////////////////////////////////////////////////
DeclareState( STATE_AttackPlayer )
OnEnter
// change the color of the debug line
m_owner->getDebugLine()->setColor(D3DCOLOR_COLORVALUE(1,0,0,1));
// make sure we are facing the player
m_owner->getMovement()->setDestLocation( g_pPlayer->GetPosition());
// attack the player!, after some delay...
SendMsgDelayedToState(RandDelay(1,2),MSG_Attack,MSG_Data());
OnMsg( MSG_Attack )
// create the name of the projectile
char name[10] = "PROJ";
sprintf(name, "%s%s", name, &m_owner->GetName()[3]);
// we have attacked the player so now run away
SendMsg( MSG_ProjectileLaunch, g_database.GetIDByName( name), MSG_Data( m_owner->getMovement()->getPosition()));
// runaway from the player
ChangeState( STATE_Runaway );
///////////////////////////////////////////////////////////////
DeclareState( STATE_Runaway )
OnEnter
// determine a location behind the NPC to run to
D3DXVECTOR3 diff = m_owner->getNPC()->getFacing();
D3DXVECTOR3 move_pos = D3DXVECTOR3(5,0,5);
move_pos.x *= diff.x;
move_pos.z *= diff.z;
move_pos = m_owner->getMovement()->getPosition() - move_pos;
if( move_pos.x <= 2.f )
move_pos.x = 2.5f;
if( move_pos.z <= 2.f )
move_pos.z = 2.5f;
// verify the location
D3DXVECTOR3 coll_pos;
// Verify the location, ie, no collision
bool collision = runNPCSeePlayer(&m_owner->getMovement()->getPosition(), &move_pos, coll_pos);
// update the target if necessary, this kindof works....
if( collision == false ) // false means there was a collision
{
//if( (int)move_pos.x != (int)coll_pos.x )
{
coll_pos.x += .5f*((coll_pos.x > move_pos.x) ? 1 : -1);
}
//if( (int) move_pos.z != (int)coll_pos.z )
coll_pos.z += .5f*((coll_pos.z > move_pos.z) ? 1 : -1);
// hack
if( coll_pos.z <= 2 )
coll_pos.z = 2.f;
if( coll_pos.x <= 2 )
coll_pos.x = 2.f;
// update the seek location
m_owner->getMovement()->setDestLocation( coll_pos );
}
else
// change the location
m_owner->getMovement()->setDestLocation( move_pos);
// change the color of the debug line
m_owner->getDebugLine()->setColor(D3DCOLOR_COLORVALUE(0,1,0,1));
OnMsg( MSG_Arrived )
// arrived at the destination, change state to arrived
ChangeState( STATE_ArrivedAtLocation );
///////////////////////////////////////////////////////////////
DeclareState( STATE_ArrivedAtLocation )
OnEnter
SendMsgDelayedToState( RandDelay(1,2), MSG_DoneSleeping, MSG_Data());
OnMsg( MSG_DoneSleeping )
// pop the state machine
PopStateMachine();
EndStateMachine
}
|
[
"ben.j.cleveland@gmail.com"
] |
ben.j.cleveland@gmail.com
|
eb47c11b5270f7dd13f629b5b9580151d45549a2
|
9cdb592be8149d1d6f832be40947c270363bfb2f
|
/c2c/Algo/DepVisitor.cpp
|
8210e6d42256af3d34aa1318975d9c24be2bd700
|
[] |
no_license
|
luciusmagn/c2compiler
|
56a66d3afd527b34964b25228cdc79248db74856
|
b30b4be152f803b6ad3e3f8b466964efe361ddbf
|
refs/heads/master
| 2021-01-17T07:30:29.567539
| 2018-05-03T11:08:30
| 2018-05-03T11:08:30
| 90,610,186
| 1
| 0
| null | 2018-05-03T11:08:31
| 2017-05-08T09:27:47
|
C++
|
UTF-8
|
C++
| false
| false
| 9,392
|
cpp
|
/* Copyright 2013-2018 Bas van den Berg
*
* 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 <assert.h>
#include "Algo/DepVisitor.h"
#include "AST/Type.h"
#include "AST/Decl.h"
#include "AST/Stmt.h"
#include "AST/Expr.h"
using namespace C2;
void DepVisitor::run() {
//fprintf(stderr, "CHECKING %s\n", decl->getName());
checkDecl(decl);
}
void DepVisitor::checkDecl(const Decl* D) {
switch (D->getKind()) {
case DECL_FUNC:
checkFunctionDecl(cast<FunctionDecl>(D));
break;
case DECL_VAR:
checkVarDecl(cast<VarDecl>(D));
break;
case DECL_ENUMVALUE:
assert(0);
break;
case DECL_ALIASTYPE:
checkType(cast<AliasTypeDecl>(D)->getRefType());
break;
case DECL_STRUCTTYPE:
{
const StructTypeDecl* S = cast<StructTypeDecl>(D);
for (unsigned i=0; i<S->numMembers(); i++) {
checkDecl(S->getMember(i));
}
break;
}
case DECL_ENUMTYPE:
{
const EnumTypeDecl* E = cast<EnumTypeDecl>(D);
for (unsigned i=0; i<E->numConstants(); i++) {
const EnumConstantDecl* ECD = E->getConstant(i);
if (ECD->getInitValue()) checkExpr(ECD->getInitValue());
}
break;
}
case DECL_FUNCTIONTYPE:
{
const FunctionTypeDecl* F = cast<FunctionTypeDecl>(D);
checkFunctionDecl(F->getDecl());
break;
}
case DECL_ARRAYVALUE:
assert(0 && "TODO");
break;
case DECL_IMPORT:
case DECL_LABEL:
break;
}
}
void DepVisitor::checkFunctionDecl(const FunctionDecl* F) {
// return Type
checkType(F->getReturnType());
// args
for (unsigned i=0; i<F->numArgs(); i++) {
checkVarDecl(F->getArg(i));
}
// check body
if (F->getBody()) checkCompoundStmt(F->getBody());
}
void DepVisitor::checkVarDecl(const VarDecl* V) {
checkType(V->getType());
if (V->getInitValue()) checkExpr(V->getInitValue());
}
void DepVisitor::checkType(QualType Q, bool isFullDep) {
const Type* T = Q.getTypePtr();
switch (T->getTypeClass()) {
case TC_BUILTIN:
return;
case TC_POINTER:
checkType(cast<PointerType>(T)->getPointeeType(), false);
break;
case TC_ARRAY:
{
const ArrayType* A = cast<ArrayType>(T);
checkType(A->getElementType(), isFullDep);
if (A->getSizeExpr()) checkExpr(A->getSizeExpr());
break;
}
case TC_UNRESOLVED:
addDep(cast<UnresolvedType>(T)->getDecl(), isFullDep);
break;
case TC_ALIAS:
addDep(cast<AliasType>(T)->getDecl(), isFullDep);
break;
case TC_STRUCT:
addDep(cast<StructType>(T)->getDecl(), isFullDep);
break;
case TC_ENUM:
addDep(cast<EnumType>(T)->getDecl(), isFullDep);
break;
case TC_FUNCTION:
addDep(cast<FunctionType>(T)->getDecl(), isFullDep);
break;
case TC_MODULE:
assert(0);
break;
}
}
void DepVisitor::checkStmt(const Stmt* S) {
assert(S);
switch (S->getKind()) {
case STMT_RETURN:
{
const ReturnStmt* R = cast<ReturnStmt>(S);
if (R->getExpr()) checkExpr(R->getExpr());
break;
}
case STMT_EXPR:
checkExpr(cast<Expr>(S));
break;
case STMT_IF:
{
const IfStmt* I = cast<IfStmt>(S);
checkStmt(I->getCond());
checkStmt(I->getThen());
if (I->getElse()) checkStmt(I->getElse());
break;
}
case STMT_WHILE:
{
const WhileStmt* W = cast<WhileStmt>(S);
checkStmt(W->getCond());
checkStmt(W->getBody());
break;
}
case STMT_DO:
{
const DoStmt* D = cast<DoStmt>(S);
checkStmt(D->getCond());
checkStmt(D->getBody());
break;
}
case STMT_FOR:
{
const ForStmt* F = cast<ForStmt>(S);
if (F->getInit()) checkStmt(F->getInit());
if (F->getCond()) checkExpr(F->getCond());
if (F->getIncr()) checkExpr(F->getIncr());
checkStmt(F->getBody());
break;
}
case STMT_SWITCH:
{
const SwitchStmt* SW = cast<SwitchStmt>(S);
checkStmt(SW->getCond());
Stmt** cases = SW->getCases();
for (unsigned i=0; i<SW->numCases(); i++) {
checkStmt(cases[i]);
}
break;
}
case STMT_CASE:
{
const CaseStmt* C = cast<CaseStmt>(S);
checkExpr(C->getCond());
Stmt** stmts = C->getStmts();
for (unsigned i=0; i<C->numStmts(); i++) {
checkStmt(stmts[i]);
}
break;
}
case STMT_DEFAULT:
{
const DefaultStmt* D = cast<DefaultStmt>(S);
Stmt** stmts = D->getStmts();
for (unsigned i=0; i<D->numStmts(); i++) {
checkStmt(stmts[i]);
}
break;
}
case STMT_BREAK:
case STMT_CONTINUE:
case STMT_LABEL:
case STMT_GOTO:
break;
case STMT_COMPOUND:
checkCompoundStmt(cast<CompoundStmt>(S));
break;
case STMT_DECL:
checkVarDecl(cast<DeclStmt>(S)->getDecl());
break;
}
}
void DepVisitor::checkCompoundStmt(const CompoundStmt* C) {
Stmt** stmts = C->getStmts();
for (unsigned i=0; i<C->numStmts(); i++) {
checkStmt(stmts[i]);
}
}
void DepVisitor::checkExpr(const Expr* E) {
assert(E);
switch (E->getKind()) {
case EXPR_INTEGER_LITERAL:
case EXPR_FLOAT_LITERAL:
case EXPR_BOOL_LITERAL:
case EXPR_CHAR_LITERAL:
case EXPR_STRING_LITERAL:
case EXPR_NIL:
break;
case EXPR_IDENTIFIER:
addDep(cast<IdentifierExpr>(E)->getDecl());
break;
case EXPR_TYPE:
// only in sizeof(int), so no need to check here
break;
case EXPR_CALL:
{
const CallExpr* C = cast<CallExpr>(E);
checkExpr(C->getFn());
for (unsigned i=0; i<C->numArgs(); i++) {
checkExpr(C->getArg(i));
}
break;
}
case EXPR_INITLIST:
{
const InitListExpr* I = cast<InitListExpr>(E);
Expr** values = I->getValues();
for (unsigned i=0; i<I->numValues(); i++) {
checkExpr(values[i]);
}
break;
}
case EXPR_DESIGNATOR_INIT:
break;
case EXPR_BINOP:
{
const BinaryOperator* B = cast<BinaryOperator>(E);
checkExpr(B->getLHS());
checkExpr(B->getRHS());
break;
}
case EXPR_CONDOP:
{
const ConditionalOperator* C = cast<ConditionalOperator>(E);
checkExpr(C->getCond());
checkExpr(C->getLHS());
checkExpr(C->getRHS());
break;
}
case EXPR_UNARYOP:
checkExpr(cast<UnaryOperator>(E)->getExpr());
break;
case EXPR_BUILTIN:
checkExpr(cast<BuiltinExpr>(E)->getExpr());
break;
case EXPR_ARRAYSUBSCRIPT:
{
const ArraySubscriptExpr* A = cast<ArraySubscriptExpr>(E);
checkExpr(A->getBase());
checkExpr(A->getIndex());
break;
}
case EXPR_MEMBER:
{
const MemberExpr* M = cast<MemberExpr>(E);
if (M->isModulePrefix()) {
addDep(M->getDecl());
} else {
checkExpr(M->getBase());
if (M->isStructFunction()) addDep(M->getDecl());
}
break;
}
case EXPR_PAREN:
checkExpr(cast<ParenExpr>(E)->getExpr());
break;
case EXPR_BITOFFSET:
{
const BitOffsetExpr* B = cast<BitOffsetExpr>(E);
checkExpr(B->getLHS());
checkExpr(B->getRHS());
break;
}
break;
case EXPR_CAST:
{
const ExplicitCastExpr* ECE = cast<ExplicitCastExpr>(E);
checkExpr(ECE->getInner());
checkType(ECE->getDestType());
}
break;
}
}
void DepVisitor::addDep(const Decl* D, bool isFullDep) {
assert(D);
// Skip local VarDecls
if (const VarDecl* V = dyncast<VarDecl>(D)) {
switch (V->getVarKind()) {
case VARDECL_GLOBAL:
break;
case VARDECL_LOCAL:
case VARDECL_PARAM:
return;
case VARDECL_MEMBER:
break;
}
}
if (!checkExternals && D->getModule() != decl->getModule()) return;
// Convert EnumConstants -> EnumTypeDecl (via EnumType)
if (const EnumConstantDecl* ECD = dyncast<EnumConstantDecl>(D)) {
QualType Q = ECD->getType();
const EnumType* T = cast<EnumType>(Q.getTypePtr());
D = T->getDecl();
}
for (unsigned i=0; i<deps.size(); i++) {
if (getDep(i) == D) {
// update pointer to full if needed
if (isFullDep) deps[i] |= 0x1;
return;
}
}
deps.push_back((uintptr_t)D | isFullDep);
//fprintf(stderr, " %s -> %s %p (%s)\n", decl->getName(), D->getName(), D, isFullDep ? "full" : "pointer");
}
|
[
"b.van.den.berg.nl@gmail.com"
] |
b.van.den.berg.nl@gmail.com
|
efe493a8574453439de10fc7316957ac5e03b5fc
|
c8e6f194669663e0e2748dbc56a7172b9ea008f7
|
/.localhistory/GUI/1471618442$MainForm.h
|
3052a92b0f5944f864754fad2ca4fa522174da50
|
[] |
no_license
|
itreppert/GUI
|
1922e781d804d17cb8008197fdbfa11576077618
|
9ca4ea0531eb45a4462a4d8278aec67f8c2705ef
|
refs/heads/master
| 2020-04-17T20:29:10.965471
| 2016-09-06T13:18:01
| 2016-09-06T13:18:01
| 67,501,677
| 0
| 0
| null | null | null | null |
ISO-8859-1
|
C++
| false
| false
| 73,826
|
h
|
#pragma once
#include "Test.h"
namespace GUI
{
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
/// <summary>
/// Zusammenfassung für MainForm
/// </summary>
public ref class MainForm : public System::Windows::Forms::Form
{
public:
MainForm(void)
{
InitializeComponent();
step = 0;
richTextBox1->LoadFile("d:\\Dokument.rtf");
points = gcnew ArrayList;
points->Add(lastPoint);
}
protected:
/// <summary>
/// Verwendete Ressourcen bereinigen.
/// </summary>
~MainForm()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::TableLayoutPanel^ tableLayoutPanel1;
private: System::Windows::Forms::TextBox^ textBox1;
private: System::Windows::Forms::Panel^ panel1;
private: System::Windows::Forms::Button^ cmdChangeFormColor;
private: System::Windows::Forms::TabControl^ tabControl1;
private: System::Windows::Forms::TabPage^ tabPage1;
private: System::Windows::Forms::TabPage^ tabPage2;
private: System::Windows::Forms::TabPage^ tabPage3;
private: System::Windows::Forms::Button^ btnChangeTab;
private: System::Windows::Forms::Panel^ panel2;
private: System::Windows::Forms::CheckBox^ checkBox1;
private: System::Windows::Forms::Button^ btnCheckbox;
private: System::Windows::Forms::RadioButton^ radioButton3;
private: System::Windows::Forms::RadioButton^ radioButton2;
private: System::Windows::Forms::RadioButton^ radioButton1;
private: System::Windows::Forms::GroupBox^ groupBox1;
private: System::Windows::Forms::Button^ btnRadioButton;
private: System::Windows::Forms::ComboBox^ cmbBlubb;
private: System::Windows::Forms::Button^ btnComboboxValue;
private: System::Windows::Forms::Button^ btnComboAddItem;
private: System::Windows::Forms::Button^ btnComboremoveItem;
private: System::Windows::Forms::Button^ btnComboInsert;
private: System::Windows::Forms::ListBox^ listBox1;
private: System::Windows::Forms::TextBox^ txtAnswers;
private: System::Windows::Forms::TextBox^ txtQuestions;
Test^ t;
int progress;
String^ antwort1;
String^ antwort2;
String^ antwort3;
String^ antwort4;
private: System::Windows::Forms::Button^ btnNextStep;
int step;
private: System::Windows::Forms::Button^ btnChangeFromAnotherClass;
private: System::Windows::Forms::MaskedTextBox^ maskedTextBox1;
private: System::Windows::Forms::NumericUpDown^ numericUpDown1;
private: System::Windows::Forms::Panel^ panel3;
private: System::Windows::Forms::PictureBox^ pictureBox1;
private: System::Windows::Forms::Button^ btnStartProgress;
private: System::Windows::Forms::ProgressBar^ progressBar1;
private: System::Windows::Forms::RichTextBox^ richTextBox1;
private: System::Windows::Forms::Timer^ timer1;
private: System::Windows::Forms::TrackBar^ trackBar1;
private: System::Windows::Forms::MenuStrip^ menuStrip1;
private: System::Windows::Forms::ToolStripMenuItem^ toolStripMenuItem1;
private: System::Windows::Forms::ToolStripMenuItem^ toolStripMenuItem2;
private: System::Windows::Forms::ToolStripSeparator^ toolStripSeparator1;
private: System::Windows::Forms::ToolStripMenuItem^ mnuSaveFileDialog;
private: System::Windows::Forms::ToolStripMenuItem^ toolStripMenuItem3;
private: System::Windows::Forms::OpenFileDialog^ openFileDialog1;
private: System::Windows::Forms::ToolStripMenuItem^ mnuFarben;
private: System::Windows::Forms::ColorDialog^ colorDialog1;
private: System::Windows::Forms::SaveFileDialog^ saveFileDialog1;
private: System::Windows::Forms::ToolStripMenuItem^ mnuSchriftart;
private: System::Windows::Forms::FontDialog^ fontDialog1;
private: System::Windows::Forms::ToolStripMenuItem^ mnuRichtextBox;
private: System::Windows::Forms::ToolStripMenuItem^ mnuFolderBrowser;
private: System::Windows::Forms::FolderBrowserDialog^ folderBrowserDialog1;
private: System::Windows::Forms::ContextMenuStrip^ contextMenuStrip1;
private: System::Windows::Forms::ToolStripMenuItem^ mnuClearText;
private: System::Windows::Forms::ToolStripMenuItem^ mnuOpen;
private: System::Windows::Forms::ToolStripMenuItem^ mnuSave;
private: System::Windows::Forms::DateTimePicker^ dateTimePicker1;
private: System::Windows::Forms::ToolStripMenuItem^ toolStripMenuItem4;
private: System::Windows::Forms::ToolStripMenuItem^ mnuButtonsHerstellen;
private: System::Windows::Forms::ToolStripMenuItem^ mnuListControls;
private: System::Windows::Forms::ToolStripMenuItem^ mnuTextBoxenHerstellen;
private: System::Windows::Forms::Button^ btnAddDoubles;
private: System::Windows::Forms::Label^ label1;
private: System::Windows::Forms::TextBox^ txtZweiteZahl;
private: System::Windows::Forms::TextBox^ txtErsteZahl;
private: System::Windows::Forms::TableLayoutPanel^ tableLayoutPanel2;
private: System::Windows::Forms::Panel^ panel4;
private: System::Windows::Forms::Button^ btnArrayList;
private: System::Windows::Forms::TextBox^ txtCollections;
private: System::Windows::Forms::Button^ btnQueue;
private: System::Windows::Forms::Button^ btnStack;
private: System::Windows::Forms::Button^ btnSortedList;
private: System::Windows::Forms::Button^ btnHashtable;
private: System::Windows::Forms::Button^ btnList;
private: System::Windows::Forms::Button^ btnArray;
private: System::Windows::Forms::Button^ btnBenchmark;
private: System::Windows::Forms::TabPage^ tabPage4;
private: System::Windows::Forms::TableLayoutPanel^ tableLayoutPanel3;
private: System::Windows::Forms::Panel^ pnlDrawing;
private: System::Windows::Forms::Panel^ pnlGraphics;
private: System::Windows::Forms::Button^ btnDrawLine;
private: System::Windows::Forms::Button^ btnTranslatePoints;
private: System::Windows::Forms::PictureBox^ pictureBox2;
private: System::Windows::Forms::Button^ btnDrawImage;
private: System::Windows::Forms::Button^ btnDrawHouse;
private: System::ComponentModel::IContainer^ components;
protected:
private:
/// <summary>
/// Erforderliche Designervariable.
/// </summary>
#pragma region Windows Form Designer generated code
/// <summary>
/// Erforderliche Methode für die Designerunterstützung.
/// Der Inhalt der Methode darf nicht mit dem Code-Editor geändert werden.
/// </summary>
void InitializeComponent(void)
{
this->components = (gcnew System::ComponentModel::Container());
System::ComponentModel::ComponentResourceManager^ resources = (gcnew System::ComponentModel::ComponentResourceManager(MainForm::typeid));
this->tableLayoutPanel1 = (gcnew System::Windows::Forms::TableLayoutPanel());
this->textBox1 = (gcnew System::Windows::Forms::TextBox());
this->contextMenuStrip1 = (gcnew System::Windows::Forms::ContextMenuStrip(this->components));
this->mnuClearText = (gcnew System::Windows::Forms::ToolStripMenuItem());
this->mnuOpen = (gcnew System::Windows::Forms::ToolStripMenuItem());
this->mnuSave = (gcnew System::Windows::Forms::ToolStripMenuItem());
this->panel1 = (gcnew System::Windows::Forms::Panel());
this->btnStartProgress = (gcnew System::Windows::Forms::Button());
this->btnChangeFromAnotherClass = (gcnew System::Windows::Forms::Button());
this->btnComboInsert = (gcnew System::Windows::Forms::Button());
this->btnComboremoveItem = (gcnew System::Windows::Forms::Button());
this->btnComboAddItem = (gcnew System::Windows::Forms::Button());
this->btnComboboxValue = (gcnew System::Windows::Forms::Button());
this->btnRadioButton = (gcnew System::Windows::Forms::Button());
this->btnCheckbox = (gcnew System::Windows::Forms::Button());
this->btnChangeTab = (gcnew System::Windows::Forms::Button());
this->cmdChangeFormColor = (gcnew System::Windows::Forms::Button());
this->panel2 = (gcnew System::Windows::Forms::Panel());
this->dateTimePicker1 = (gcnew System::Windows::Forms::DateTimePicker());
this->trackBar1 = (gcnew System::Windows::Forms::TrackBar());
this->numericUpDown1 = (gcnew System::Windows::Forms::NumericUpDown());
this->maskedTextBox1 = (gcnew System::Windows::Forms::MaskedTextBox());
this->listBox1 = (gcnew System::Windows::Forms::ListBox());
this->cmbBlubb = (gcnew System::Windows::Forms::ComboBox());
this->groupBox1 = (gcnew System::Windows::Forms::GroupBox());
this->radioButton3 = (gcnew System::Windows::Forms::RadioButton());
this->radioButton2 = (gcnew System::Windows::Forms::RadioButton());
this->radioButton1 = (gcnew System::Windows::Forms::RadioButton());
this->checkBox1 = (gcnew System::Windows::Forms::CheckBox());
this->panel3 = (gcnew System::Windows::Forms::Panel());
this->btnAddDoubles = (gcnew System::Windows::Forms::Button());
this->label1 = (gcnew System::Windows::Forms::Label());
this->txtZweiteZahl = (gcnew System::Windows::Forms::TextBox());
this->txtErsteZahl = (gcnew System::Windows::Forms::TextBox());
this->richTextBox1 = (gcnew System::Windows::Forms::RichTextBox());
this->progressBar1 = (gcnew System::Windows::Forms::ProgressBar());
this->pictureBox1 = (gcnew System::Windows::Forms::PictureBox());
this->tabControl1 = (gcnew System::Windows::Forms::TabControl());
this->tabPage1 = (gcnew System::Windows::Forms::TabPage());
this->tabPage2 = (gcnew System::Windows::Forms::TabPage());
this->tableLayoutPanel2 = (gcnew System::Windows::Forms::TableLayoutPanel());
this->panel4 = (gcnew System::Windows::Forms::Panel());
this->btnBenchmark = (gcnew System::Windows::Forms::Button());
this->btnArray = (gcnew System::Windows::Forms::Button());
this->btnList = (gcnew System::Windows::Forms::Button());
this->btnHashtable = (gcnew System::Windows::Forms::Button());
this->btnSortedList = (gcnew System::Windows::Forms::Button());
this->btnStack = (gcnew System::Windows::Forms::Button());
this->btnQueue = (gcnew System::Windows::Forms::Button());
this->btnArrayList = (gcnew System::Windows::Forms::Button());
this->txtCollections = (gcnew System::Windows::Forms::TextBox());
this->tabPage3 = (gcnew System::Windows::Forms::TabPage());
this->txtAnswers = (gcnew System::Windows::Forms::TextBox());
this->txtQuestions = (gcnew System::Windows::Forms::TextBox());
this->btnNextStep = (gcnew System::Windows::Forms::Button());
this->tabPage4 = (gcnew System::Windows::Forms::TabPage());
this->tableLayoutPanel3 = (gcnew System::Windows::Forms::TableLayoutPanel());
this->pnlDrawing = (gcnew System::Windows::Forms::Panel());
this->pictureBox2 = (gcnew System::Windows::Forms::PictureBox());
this->pnlGraphics = (gcnew System::Windows::Forms::Panel());
this->btnDrawImage = (gcnew System::Windows::Forms::Button());
this->btnTranslatePoints = (gcnew System::Windows::Forms::Button());
this->btnDrawLine = (gcnew System::Windows::Forms::Button());
this->timer1 = (gcnew System::Windows::Forms::Timer(this->components));
this->menuStrip1 = (gcnew System::Windows::Forms::MenuStrip());
this->toolStripMenuItem1 = (gcnew System::Windows::Forms::ToolStripMenuItem());
this->toolStripMenuItem2 = (gcnew System::Windows::Forms::ToolStripMenuItem());
this->toolStripSeparator1 = (gcnew System::Windows::Forms::ToolStripSeparator());
this->mnuSaveFileDialog = (gcnew System::Windows::Forms::ToolStripMenuItem());
this->mnuRichtextBox = (gcnew System::Windows::Forms::ToolStripMenuItem());
this->mnuFolderBrowser = (gcnew System::Windows::Forms::ToolStripMenuItem());
this->toolStripMenuItem3 = (gcnew System::Windows::Forms::ToolStripMenuItem());
this->mnuFarben = (gcnew System::Windows::Forms::ToolStripMenuItem());
this->mnuSchriftart = (gcnew System::Windows::Forms::ToolStripMenuItem());
this->toolStripMenuItem4 = (gcnew System::Windows::Forms::ToolStripMenuItem());
this->mnuButtonsHerstellen = (gcnew System::Windows::Forms::ToolStripMenuItem());
this->mnuListControls = (gcnew System::Windows::Forms::ToolStripMenuItem());
this->mnuTextBoxenHerstellen = (gcnew System::Windows::Forms::ToolStripMenuItem());
this->openFileDialog1 = (gcnew System::Windows::Forms::OpenFileDialog());
this->colorDialog1 = (gcnew System::Windows::Forms::ColorDialog());
this->saveFileDialog1 = (gcnew System::Windows::Forms::SaveFileDialog());
this->fontDialog1 = (gcnew System::Windows::Forms::FontDialog());
this->folderBrowserDialog1 = (gcnew System::Windows::Forms::FolderBrowserDialog());
this->btnDrawHouse = (gcnew System::Windows::Forms::Button());
this->tableLayoutPanel1->SuspendLayout();
this->contextMenuStrip1->SuspendLayout();
this->panel1->SuspendLayout();
this->panel2->SuspendLayout();
(cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->trackBar1))->BeginInit();
(cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->numericUpDown1))->BeginInit();
this->groupBox1->SuspendLayout();
this->panel3->SuspendLayout();
(cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->pictureBox1))->BeginInit();
this->tabControl1->SuspendLayout();
this->tabPage1->SuspendLayout();
this->tabPage2->SuspendLayout();
this->tableLayoutPanel2->SuspendLayout();
this->panel4->SuspendLayout();
this->tabPage3->SuspendLayout();
this->tabPage4->SuspendLayout();
this->tableLayoutPanel3->SuspendLayout();
this->pnlDrawing->SuspendLayout();
(cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->pictureBox2))->BeginInit();
this->pnlGraphics->SuspendLayout();
this->menuStrip1->SuspendLayout();
this->SuspendLayout();
//
// tableLayoutPanel1
//
this->tableLayoutPanel1->ColumnCount = 2;
this->tableLayoutPanel1->ColumnStyles->Add((gcnew System::Windows::Forms::ColumnStyle(System::Windows::Forms::SizeType::Percent,
50)));
this->tableLayoutPanel1->ColumnStyles->Add((gcnew System::Windows::Forms::ColumnStyle(System::Windows::Forms::SizeType::Percent,
50)));
this->tableLayoutPanel1->Controls->Add(this->textBox1, 1, 0);
this->tableLayoutPanel1->Controls->Add(this->panel1, 0, 0);
this->tableLayoutPanel1->Controls->Add(this->panel2, 0, 1);
this->tableLayoutPanel1->Controls->Add(this->panel3, 1, 1);
this->tableLayoutPanel1->Dock = System::Windows::Forms::DockStyle::Fill;
this->tableLayoutPanel1->Location = System::Drawing::Point(3, 3);
this->tableLayoutPanel1->Name = L"tableLayoutPanel1";
this->tableLayoutPanel1->RowCount = 2;
this->tableLayoutPanel1->RowStyles->Add((gcnew System::Windows::Forms::RowStyle(System::Windows::Forms::SizeType::Percent, 50)));
this->tableLayoutPanel1->RowStyles->Add((gcnew System::Windows::Forms::RowStyle(System::Windows::Forms::SizeType::Percent, 50)));
this->tableLayoutPanel1->Size = System::Drawing::Size(599, 458);
this->tableLayoutPanel1->TabIndex = 3;
//
// textBox1
//
this->textBox1->ContextMenuStrip = this->contextMenuStrip1;
this->textBox1->Dock = System::Windows::Forms::DockStyle::Fill;
this->textBox1->Location = System::Drawing::Point(302, 3);
this->textBox1->Multiline = true;
this->textBox1->Name = L"textBox1";
this->textBox1->ScrollBars = System::Windows::Forms::ScrollBars::Both;
this->textBox1->Size = System::Drawing::Size(294, 223);
this->textBox1->TabIndex = 2;
//
// contextMenuStrip1
//
this->contextMenuStrip1->Items->AddRange(gcnew cli::array< System::Windows::Forms::ToolStripItem^ >(3)
{
this->mnuClearText,
this->mnuOpen, this->mnuSave
});
this->contextMenuStrip1->Name = L"contextMenuStrip1";
this->contextMenuStrip1->Size = System::Drawing::Size(160, 70);
//
// mnuClearText
//
this->mnuClearText->Name = L"mnuClearText";
this->mnuClearText->Size = System::Drawing::Size(159, 22);
this->mnuClearText->Text = L"TextBox löschen";
this->mnuClearText->Click += gcnew System::EventHandler(this, &MainForm::mnuClearText_Click);
//
// mnuOpen
//
this->mnuOpen->Name = L"mnuOpen";
this->mnuOpen->Size = System::Drawing::Size(159, 22);
this->mnuOpen->Text = L"Datei öffnen";
this->mnuOpen->Click += gcnew System::EventHandler(this, &MainForm::toolStripMenuItem2_Click);
//
// mnuSave
//
this->mnuSave->Name = L"mnuSave";
this->mnuSave->Size = System::Drawing::Size(159, 22);
this->mnuSave->Text = L"Speichern als";
this->mnuSave->Click += gcnew System::EventHandler(this, &MainForm::mnuSaveFileDialog_Click);
//
// panel1
//
this->panel1->Controls->Add(this->btnStartProgress);
this->panel1->Controls->Add(this->btnChangeFromAnotherClass);
this->panel1->Controls->Add(this->btnComboInsert);
this->panel1->Controls->Add(this->btnComboremoveItem);
this->panel1->Controls->Add(this->btnComboAddItem);
this->panel1->Controls->Add(this->btnComboboxValue);
this->panel1->Controls->Add(this->btnRadioButton);
this->panel1->Controls->Add(this->btnCheckbox);
this->panel1->Controls->Add(this->btnChangeTab);
this->panel1->Controls->Add(this->cmdChangeFormColor);
this->panel1->Dock = System::Windows::Forms::DockStyle::Fill;
this->panel1->Location = System::Drawing::Point(3, 3);
this->panel1->Name = L"panel1";
this->panel1->Size = System::Drawing::Size(293, 223);
this->panel1->TabIndex = 1;
//
// btnStartProgress
//
this->btnStartProgress->Location = System::Drawing::Point(115, 32);
this->btnStartProgress->Name = L"btnStartProgress";
this->btnStartProgress->Size = System::Drawing::Size(109, 23);
this->btnStartProgress->TabIndex = 9;
this->btnStartProgress->Text = L"Start Progress";
this->btnStartProgress->UseVisualStyleBackColor = true;
this->btnStartProgress->Click += gcnew System::EventHandler(this, &MainForm::btnStartProgress_Click);
//
// btnChangeFromAnotherClass
//
this->btnChangeFromAnotherClass->Location = System::Drawing::Point(115, 3);
this->btnChangeFromAnotherClass->Name = L"btnChangeFromAnotherClass";
this->btnChangeFromAnotherClass->Size = System::Drawing::Size(109, 23);
this->btnChangeFromAnotherClass->TabIndex = 8;
this->btnChangeFromAnotherClass->Text = L"Class Fun";
this->btnChangeFromAnotherClass->UseVisualStyleBackColor = true;
this->btnChangeFromAnotherClass->Click += gcnew System::EventHandler(this, &MainForm::btnChangeFromAnotherClass_Click);
//
// btnComboInsert
//
this->btnComboInsert->Location = System::Drawing::Point(3, 178);
this->btnComboInsert->Name = L"btnComboInsert";
this->btnComboInsert->Size = System::Drawing::Size(109, 23);
this->btnComboInsert->TabIndex = 7;
this->btnComboInsert->Text = L"Combo insert Item";
this->btnComboInsert->UseVisualStyleBackColor = true;
this->btnComboInsert->Click += gcnew System::EventHandler(this, &MainForm::btnComboInsert_Click);
//
// btnComboremoveItem
//
this->btnComboremoveItem->Location = System::Drawing::Point(4, 207);
this->btnComboremoveItem->Name = L"btnComboremoveItem";
this->btnComboremoveItem->Size = System::Drawing::Size(109, 23);
this->btnComboremoveItem->TabIndex = 6;
this->btnComboremoveItem->Text = L"Combo remove Item";
this->btnComboremoveItem->UseVisualStyleBackColor = true;
this->btnComboremoveItem->Click += gcnew System::EventHandler(this, &MainForm::btnComboremoveItem_Click);
//
// btnComboAddItem
//
this->btnComboAddItem->Location = System::Drawing::Point(3, 149);
this->btnComboAddItem->Name = L"btnComboAddItem";
this->btnComboAddItem->Size = System::Drawing::Size(96, 23);
this->btnComboAddItem->TabIndex = 5;
this->btnComboAddItem->Text = L"Combo Add Item";
this->btnComboAddItem->UseVisualStyleBackColor = true;
this->btnComboAddItem->Click += gcnew System::EventHandler(this, &MainForm::btnComboAddItem_Click);
//
// btnComboboxValue
//
this->btnComboboxValue->Location = System::Drawing::Point(4, 120);
this->btnComboboxValue->Name = L"btnComboboxValue";
this->btnComboboxValue->Size = System::Drawing::Size(96, 23);
this->btnComboboxValue->TabIndex = 4;
this->btnComboboxValue->Text = L"Combo Value";
this->btnComboboxValue->UseVisualStyleBackColor = true;
this->btnComboboxValue->Click += gcnew System::EventHandler(this, &MainForm::btnComboboxValue_Click);
//
// btnRadioButton
//
this->btnRadioButton->Location = System::Drawing::Point(4, 91);
this->btnRadioButton->Name = L"btnRadioButton";
this->btnRadioButton->Size = System::Drawing::Size(96, 23);
this->btnRadioButton->TabIndex = 3;
this->btnRadioButton->Text = L"Radiobutton";
this->btnRadioButton->UseVisualStyleBackColor = true;
this->btnRadioButton->Click += gcnew System::EventHandler(this, &MainForm::btnRadioButton_Click);
//
// btnCheckbox
//
this->btnCheckbox->Location = System::Drawing::Point(4, 62);
this->btnCheckbox->Name = L"btnCheckbox";
this->btnCheckbox->Size = System::Drawing::Size(96, 23);
this->btnCheckbox->TabIndex = 2;
this->btnCheckbox->Text = L"Checkbox";
this->btnCheckbox->UseVisualStyleBackColor = true;
this->btnCheckbox->Click += gcnew System::EventHandler(this, &MainForm::btnCheckbox_Click);
//
// btnChangeTab
//
this->btnChangeTab->Location = System::Drawing::Point(3, 32);
this->btnChangeTab->Name = L"btnChangeTab";
this->btnChangeTab->Size = System::Drawing::Size(97, 23);
this->btnChangeTab->TabIndex = 1;
this->btnChangeTab->Text = L"Change Tab";
this->btnChangeTab->UseVisualStyleBackColor = true;
this->btnChangeTab->Click += gcnew System::EventHandler(this, &MainForm::btnChangeTab_Click);
//
// cmdChangeFormColor
//
this->cmdChangeFormColor->Location = System::Drawing::Point(3, 3);
this->cmdChangeFormColor->Name = L"cmdChangeFormColor";
this->cmdChangeFormColor->Size = System::Drawing::Size(97, 23);
this->cmdChangeFormColor->TabIndex = 0;
this->cmdChangeFormColor->Text = L"Change Color";
this->cmdChangeFormColor->UseVisualStyleBackColor = true;
this->cmdChangeFormColor->Click += gcnew System::EventHandler(this, &MainForm::cmdChangeFormColor_Click);
//
// panel2
//
this->panel2->Controls->Add(this->dateTimePicker1);
this->panel2->Controls->Add(this->trackBar1);
this->panel2->Controls->Add(this->numericUpDown1);
this->panel2->Controls->Add(this->maskedTextBox1);
this->panel2->Controls->Add(this->listBox1);
this->panel2->Controls->Add(this->cmbBlubb);
this->panel2->Controls->Add(this->groupBox1);
this->panel2->Controls->Add(this->checkBox1);
this->panel2->Dock = System::Windows::Forms::DockStyle::Fill;
this->panel2->Location = System::Drawing::Point(3, 232);
this->panel2->Name = L"panel2";
this->panel2->Size = System::Drawing::Size(293, 223);
this->panel2->TabIndex = 3;
//
// dateTimePicker1
//
this->dateTimePicker1->Location = System::Drawing::Point(24, 205);
this->dateTimePicker1->Name = L"dateTimePicker1";
this->dateTimePicker1->Size = System::Drawing::Size(200, 20);
this->dateTimePicker1->TabIndex = 10;
this->dateTimePicker1->ValueChanged += gcnew System::EventHandler(this, &MainForm::dateTimePicker1_ValueChanged);
//
// trackBar1
//
this->trackBar1->Location = System::Drawing::Point(10, 158);
this->trackBar1->Name = L"trackBar1";
this->trackBar1->Size = System::Drawing::Size(104, 45);
this->trackBar1->TabIndex = 9;
this->trackBar1->Scroll += gcnew System::EventHandler(this, &MainForm::trackBar1_Scroll);
//
// numericUpDown1
//
this->numericUpDown1->Increment = System::Decimal(gcnew cli::array< System::Int32 >(4) { 2, 0, 0, 0 });
this->numericUpDown1->Location = System::Drawing::Point(191, 132);
this->numericUpDown1->Minimum = System::Decimal(gcnew cli::array< System::Int32 >(4) { 5, 0, 0, 0 });
this->numericUpDown1->Name = L"numericUpDown1";
this->numericUpDown1->Size = System::Drawing::Size(79, 20);
this->numericUpDown1->TabIndex = 8;
this->numericUpDown1->Value = System::Decimal(gcnew cli::array< System::Int32 >(4) { 5, 0, 0, 0 });
//
// maskedTextBox1
//
this->maskedTextBox1->Location = System::Drawing::Point(4, 131);
this->maskedTextBox1->Mask = L"00/00/0000 00:00";
this->maskedTextBox1->Name = L"maskedTextBox1";
this->maskedTextBox1->Size = System::Drawing::Size(172, 20);
this->maskedTextBox1->TabIndex = 7;
this->maskedTextBox1->ValidatingType = System::DateTime::typeid;
//
// listBox1
//
this->listBox1->FormattingEnabled = true;
this->listBox1->Items->AddRange(gcnew cli::array< System::Object^ >(4) { L"Bli", L"Bla", L"Blubb", L"Trallallaaaaaa" });
this->listBox1->Location = System::Drawing::Point(133, 30);
this->listBox1->Name = L"listBox1";
this->listBox1->SelectionMode = System::Windows::Forms::SelectionMode::MultiSimple;
this->listBox1->Size = System::Drawing::Size(137, 95);
this->listBox1->TabIndex = 6;
this->listBox1->SelectedIndexChanged += gcnew System::EventHandler(this, &MainForm::listBox1_SelectedIndexChanged);
//
// cmbBlubb
//
this->cmbBlubb->DropDownStyle = System::Windows::Forms::ComboBoxStyle::DropDownList;
this->cmbBlubb->FormattingEnabled = true;
this->cmbBlubb->Items->AddRange(gcnew cli::array< System::Object^ >(5) { L"Bli", L"Bla", L"Blubb", L"Trallalla", L"Whooop" });
this->cmbBlubb->Location = System::Drawing::Point(133, 3);
this->cmbBlubb->Name = L"cmbBlubb";
this->cmbBlubb->Size = System::Drawing::Size(137, 21);
this->cmbBlubb->TabIndex = 5;
this->cmbBlubb->SelectedIndexChanged += gcnew System::EventHandler(this, &MainForm::cmbBlubb_SelectedIndexChanged);
//
// groupBox1
//
this->groupBox1->Controls->Add(this->radioButton3);
this->groupBox1->Controls->Add(this->radioButton2);
this->groupBox1->Controls->Add(this->radioButton1);
this->groupBox1->Location = System::Drawing::Point(4, 26);
this->groupBox1->Name = L"groupBox1";
this->groupBox1->Size = System::Drawing::Size(113, 91);
this->groupBox1->TabIndex = 4;
this->groupBox1->TabStop = false;
this->groupBox1->Text = L"groupBox1";
//
// radioButton3
//
this->radioButton3->AutoSize = true;
this->radioButton3->Location = System::Drawing::Point(6, 65);
this->radioButton3->Name = L"radioButton3";
this->radioButton3->Size = System::Drawing::Size(85, 17);
this->radioButton3->TabIndex = 3;
this->radioButton3->TabStop = true;
this->radioButton3->Text = L"radioButton3";
this->radioButton3->UseVisualStyleBackColor = true;
//
// radioButton2
//
this->radioButton2->AutoSize = true;
this->radioButton2->Location = System::Drawing::Point(6, 42);
this->radioButton2->Name = L"radioButton2";
this->radioButton2->Size = System::Drawing::Size(85, 17);
this->radioButton2->TabIndex = 2;
this->radioButton2->TabStop = true;
this->radioButton2->Text = L"radioButton2";
this->radioButton2->UseVisualStyleBackColor = true;
//
// radioButton1
//
this->radioButton1->AutoSize = true;
this->radioButton1->Location = System::Drawing::Point(6, 19);
this->radioButton1->Name = L"radioButton1";
this->radioButton1->Size = System::Drawing::Size(85, 17);
this->radioButton1->TabIndex = 1;
this->radioButton1->TabStop = true;
this->radioButton1->Text = L"radioButton1";
this->radioButton1->UseVisualStyleBackColor = true;
//
// checkBox1
//
this->checkBox1->AutoSize = true;
this->checkBox1->Location = System::Drawing::Point(3, 3);
this->checkBox1->Name = L"checkBox1";
this->checkBox1->Size = System::Drawing::Size(80, 17);
this->checkBox1->TabIndex = 0;
this->checkBox1->Text = L"checkBox1";
this->checkBox1->UseVisualStyleBackColor = true;
this->checkBox1->CheckedChanged += gcnew System::EventHandler(this, &MainForm::checkBox1_CheckedChanged);
//
// panel3
//
this->panel3->Controls->Add(this->btnAddDoubles);
this->panel3->Controls->Add(this->label1);
this->panel3->Controls->Add(this->txtZweiteZahl);
this->panel3->Controls->Add(this->txtErsteZahl);
this->panel3->Controls->Add(this->richTextBox1);
this->panel3->Controls->Add(this->progressBar1);
this->panel3->Controls->Add(this->pictureBox1);
this->panel3->Dock = System::Windows::Forms::DockStyle::Fill;
this->panel3->Location = System::Drawing::Point(302, 232);
this->panel3->Name = L"panel3";
this->panel3->Size = System::Drawing::Size(294, 223);
this->panel3->TabIndex = 4;
//
// btnAddDoubles
//
this->btnAddDoubles->Location = System::Drawing::Point(240, 167);
this->btnAddDoubles->Name = L"btnAddDoubles";
this->btnAddDoubles->Size = System::Drawing::Size(30, 23);
this->btnAddDoubles->TabIndex = 10;
this->btnAddDoubles->Text = L"=";
this->btnAddDoubles->UseVisualStyleBackColor = true;
this->btnAddDoubles->Click += gcnew System::EventHandler(this, &MainForm::btnAddDoubles_Click);
//
// label1
//
this->label1->AutoSize = true;
this->label1->Location = System::Drawing::Point(124, 173);
this->label1->Name = L"label1";
this->label1->Size = System::Drawing::Size(13, 13);
this->label1->TabIndex = 5;
this->label1->Text = L"+";
//
// txtZweiteZahl
//
this->txtZweiteZahl->Location = System::Drawing::Point(138, 170);
this->txtZweiteZahl->Name = L"txtZweiteZahl";
this->txtZweiteZahl->Size = System::Drawing::Size(100, 20);
this->txtZweiteZahl->TabIndex = 4;
//
// txtErsteZahl
//
this->txtErsteZahl->Location = System::Drawing::Point(18, 170);
this->txtErsteZahl->Name = L"txtErsteZahl";
this->txtErsteZahl->Size = System::Drawing::Size(100, 20);
this->txtErsteZahl->TabIndex = 3;
//
// richTextBox1
//
this->richTextBox1->Location = System::Drawing::Point(93, 29);
this->richTextBox1->Name = L"richTextBox1";
this->richTextBox1->Size = System::Drawing::Size(177, 88);
this->richTextBox1->TabIndex = 2;
this->richTextBox1->Text = L"";
//
// progressBar1
//
this->progressBar1->Location = System::Drawing::Point(93, 3);
this->progressBar1->Name = L"progressBar1";
this->progressBar1->Size = System::Drawing::Size(177, 14);
this->progressBar1->Style = System::Windows::Forms::ProgressBarStyle::Continuous;
this->progressBar1->TabIndex = 1;
this->progressBar1->Value = 40;
//
// pictureBox1
//
this->pictureBox1->Image = (cli::safe_cast<System::Drawing::Image^>(resources->GetObject(L"pictureBox1.Image")));
this->pictureBox1->Location = System::Drawing::Point(3, 3);
this->pictureBox1->Name = L"pictureBox1";
this->pictureBox1->Size = System::Drawing::Size(84, 82);
this->pictureBox1->SizeMode = System::Windows::Forms::PictureBoxSizeMode::StretchImage;
this->pictureBox1->TabIndex = 0;
this->pictureBox1->TabStop = false;
//
// tabControl1
//
this->tabControl1->Controls->Add(this->tabPage1);
this->tabControl1->Controls->Add(this->tabPage2);
this->tabControl1->Controls->Add(this->tabPage3);
this->tabControl1->Controls->Add(this->tabPage4);
this->tabControl1->Dock = System::Windows::Forms::DockStyle::Fill;
this->tabControl1->Location = System::Drawing::Point(0, 24);
this->tabControl1->Name = L"tabControl1";
this->tabControl1->SelectedIndex = 0;
this->tabControl1->Size = System::Drawing::Size(613, 490);
this->tabControl1->TabIndex = 4;
//
// tabPage1
//
this->tabPage1->Controls->Add(this->tableLayoutPanel1);
this->tabPage1->Location = System::Drawing::Point(4, 22);
this->tabPage1->Name = L"tabPage1";
this->tabPage1->Padding = System::Windows::Forms::Padding(3);
this->tabPage1->Size = System::Drawing::Size(605, 464);
this->tabPage1->TabIndex = 0;
this->tabPage1->Text = L"Basics";
this->tabPage1->UseVisualStyleBackColor = true;
//
// tabPage2
//
this->tabPage2->Controls->Add(this->tableLayoutPanel2);
this->tabPage2->Location = System::Drawing::Point(4, 22);
this->tabPage2->Name = L"tabPage2";
this->tabPage2->Padding = System::Windows::Forms::Padding(3);
this->tabPage2->Size = System::Drawing::Size(605, 464);
this->tabPage2->TabIndex = 1;
this->tabPage2->Text = L"Other";
this->tabPage2->UseVisualStyleBackColor = true;
//
// tableLayoutPanel2
//
this->tableLayoutPanel2->ColumnCount = 2;
this->tableLayoutPanel2->ColumnStyles->Add((gcnew System::Windows::Forms::ColumnStyle(System::Windows::Forms::SizeType::Percent,
50)));
this->tableLayoutPanel2->ColumnStyles->Add((gcnew System::Windows::Forms::ColumnStyle(System::Windows::Forms::SizeType::Percent,
50)));
this->tableLayoutPanel2->Controls->Add(this->panel4, 0, 0);
this->tableLayoutPanel2->Controls->Add(this->txtCollections, 1, 0);
this->tableLayoutPanel2->Dock = System::Windows::Forms::DockStyle::Fill;
this->tableLayoutPanel2->Location = System::Drawing::Point(3, 3);
this->tableLayoutPanel2->Name = L"tableLayoutPanel2";
this->tableLayoutPanel2->RowCount = 1;
this->tableLayoutPanel2->RowStyles->Add((gcnew System::Windows::Forms::RowStyle(System::Windows::Forms::SizeType::Percent, 50)));
this->tableLayoutPanel2->Size = System::Drawing::Size(599, 458);
this->tableLayoutPanel2->TabIndex = 0;
//
// panel4
//
this->panel4->Controls->Add(this->btnBenchmark);
this->panel4->Controls->Add(this->btnArray);
this->panel4->Controls->Add(this->btnList);
this->panel4->Controls->Add(this->btnHashtable);
this->panel4->Controls->Add(this->btnSortedList);
this->panel4->Controls->Add(this->btnStack);
this->panel4->Controls->Add(this->btnQueue);
this->panel4->Controls->Add(this->btnArrayList);
this->panel4->Dock = System::Windows::Forms::DockStyle::Fill;
this->panel4->Location = System::Drawing::Point(3, 3);
this->panel4->Name = L"panel4";
this->panel4->Size = System::Drawing::Size(293, 452);
this->panel4->TabIndex = 0;
//
// btnBenchmark
//
this->btnBenchmark->Location = System::Drawing::Point(4, 207);
this->btnBenchmark->Name = L"btnBenchmark";
this->btnBenchmark->Size = System::Drawing::Size(121, 23);
this->btnBenchmark->TabIndex = 8;
this->btnBenchmark->Text = L"Benchmark";
this->btnBenchmark->UseVisualStyleBackColor = true;
this->btnBenchmark->Click += gcnew System::EventHandler(this, &MainForm::btnBenchmark_Click);
//
// btnArray
//
this->btnArray->Location = System::Drawing::Point(4, 178);
this->btnArray->Name = L"btnArray";
this->btnArray->Size = System::Drawing::Size(121, 23);
this->btnArray->TabIndex = 7;
this->btnArray->Text = L"array";
this->btnArray->UseVisualStyleBackColor = true;
this->btnArray->Click += gcnew System::EventHandler(this, &MainForm::btnArray_Click);
//
// btnList
//
this->btnList->Location = System::Drawing::Point(4, 149);
this->btnList->Name = L"btnList";
this->btnList->Size = System::Drawing::Size(121, 23);
this->btnList->TabIndex = 6;
this->btnList->Text = L"List";
this->btnList->UseVisualStyleBackColor = true;
this->btnList->Click += gcnew System::EventHandler(this, &MainForm::btnList_Click);
//
// btnHashtable
//
this->btnHashtable->Location = System::Drawing::Point(4, 120);
this->btnHashtable->Name = L"btnHashtable";
this->btnHashtable->Size = System::Drawing::Size(121, 23);
this->btnHashtable->TabIndex = 4;
this->btnHashtable->Text = L"HashTable";
this->btnHashtable->UseVisualStyleBackColor = true;
this->btnHashtable->Click += gcnew System::EventHandler(this, &MainForm::btnHashtable_Click);
//
// btnSortedList
//
this->btnSortedList->Location = System::Drawing::Point(4, 91);
this->btnSortedList->Name = L"btnSortedList";
this->btnSortedList->Size = System::Drawing::Size(121, 23);
this->btnSortedList->TabIndex = 3;
this->btnSortedList->Text = L"SortedList";
this->btnSortedList->UseVisualStyleBackColor = true;
this->btnSortedList->Click += gcnew System::EventHandler(this, &MainForm::btnSortedList_Click);
//
// btnStack
//
this->btnStack->Location = System::Drawing::Point(4, 62);
this->btnStack->Name = L"btnStack";
this->btnStack->Size = System::Drawing::Size(121, 23);
this->btnStack->TabIndex = 2;
this->btnStack->Text = L"Stack";
this->btnStack->UseVisualStyleBackColor = true;
this->btnStack->Click += gcnew System::EventHandler(this, &MainForm::btnStack_Click);
//
// btnQueue
//
this->btnQueue->Location = System::Drawing::Point(4, 33);
this->btnQueue->Name = L"btnQueue";
this->btnQueue->Size = System::Drawing::Size(121, 23);
this->btnQueue->TabIndex = 1;
this->btnQueue->Text = L"Queue";
this->btnQueue->UseVisualStyleBackColor = true;
this->btnQueue->Click += gcnew System::EventHandler(this, &MainForm::btnQueue_Click);
//
// btnArrayList
//
this->btnArrayList->Location = System::Drawing::Point(4, 4);
this->btnArrayList->Name = L"btnArrayList";
this->btnArrayList->Size = System::Drawing::Size(121, 23);
this->btnArrayList->TabIndex = 0;
this->btnArrayList->Text = L"ArrayList";
this->btnArrayList->UseVisualStyleBackColor = true;
this->btnArrayList->Click += gcnew System::EventHandler(this, &MainForm::btnArrayList_Click);
//
// txtCollections
//
this->txtCollections->Dock = System::Windows::Forms::DockStyle::Fill;
this->txtCollections->Location = System::Drawing::Point(302, 3);
this->txtCollections->Multiline = true;
this->txtCollections->Name = L"txtCollections";
this->txtCollections->Size = System::Drawing::Size(294, 452);
this->txtCollections->TabIndex = 1;
//
// tabPage3
//
this->tabPage3->Controls->Add(this->txtAnswers);
this->tabPage3->Controls->Add(this->txtQuestions);
this->tabPage3->Controls->Add(this->btnNextStep);
this->tabPage3->Location = System::Drawing::Point(4, 22);
this->tabPage3->Name = L"tabPage3";
this->tabPage3->Padding = System::Windows::Forms::Padding(3);
this->tabPage3->Size = System::Drawing::Size(605, 464);
this->tabPage3->TabIndex = 2;
this->tabPage3->Text = L"Quiz";
this->tabPage3->UseVisualStyleBackColor = true;
//
// txtAnswers
//
this->txtAnswers->Location = System::Drawing::Point(288, 231);
this->txtAnswers->Multiline = true;
this->txtAnswers->Name = L"txtAnswers";
this->txtAnswers->Size = System::Drawing::Size(268, 203);
this->txtAnswers->TabIndex = 2;
//
// txtQuestions
//
this->txtQuestions->Location = System::Drawing::Point(288, 4);
this->txtQuestions->Multiline = true;
this->txtQuestions->Name = L"txtQuestions";
this->txtQuestions->Size = System::Drawing::Size(268, 203);
this->txtQuestions->TabIndex = 1;
//
// btnNextStep
//
this->btnNextStep->Location = System::Drawing::Point(7, 7);
this->btnNextStep->Name = L"btnNextStep";
this->btnNextStep->Size = System::Drawing::Size(75, 23);
this->btnNextStep->TabIndex = 0;
this->btnNextStep->Text = L"Next";
this->btnNextStep->UseVisualStyleBackColor = true;
this->btnNextStep->Click += gcnew System::EventHandler(this, &MainForm::btnNextStep_Click);
//
// tabPage4
//
this->tabPage4->Controls->Add(this->tableLayoutPanel3);
this->tabPage4->Location = System::Drawing::Point(4, 22);
this->tabPage4->Name = L"tabPage4";
this->tabPage4->Padding = System::Windows::Forms::Padding(3);
this->tabPage4->Size = System::Drawing::Size(605, 464);
this->tabPage4->TabIndex = 3;
this->tabPage4->Text = L"Graphics";
this->tabPage4->UseVisualStyleBackColor = true;
//
// tableLayoutPanel3
//
this->tableLayoutPanel3->ColumnCount = 2;
this->tableLayoutPanel3->ColumnStyles->Add((gcnew System::Windows::Forms::ColumnStyle(System::Windows::Forms::SizeType::Percent,
50)));
this->tableLayoutPanel3->ColumnStyles->Add((gcnew System::Windows::Forms::ColumnStyle(System::Windows::Forms::SizeType::Percent,
50)));
this->tableLayoutPanel3->Controls->Add(this->pnlDrawing, 1, 0);
this->tableLayoutPanel3->Controls->Add(this->pnlGraphics, 0, 0);
this->tableLayoutPanel3->Dock = System::Windows::Forms::DockStyle::Fill;
this->tableLayoutPanel3->Location = System::Drawing::Point(3, 3);
this->tableLayoutPanel3->Name = L"tableLayoutPanel3";
this->tableLayoutPanel3->RowCount = 1;
this->tableLayoutPanel3->RowStyles->Add((gcnew System::Windows::Forms::RowStyle(System::Windows::Forms::SizeType::Percent, 50)));
this->tableLayoutPanel3->Size = System::Drawing::Size(599, 458);
this->tableLayoutPanel3->TabIndex = 0;
//
// pnlDrawing
//
this->pnlDrawing->BackColor = System::Drawing::Color::Gainsboro;
this->pnlDrawing->Controls->Add(this->pictureBox2);
this->pnlDrawing->Dock = System::Windows::Forms::DockStyle::Fill;
this->pnlDrawing->Location = System::Drawing::Point(302, 3);
this->pnlDrawing->Name = L"pnlDrawing";
this->pnlDrawing->Size = System::Drawing::Size(294, 452);
this->pnlDrawing->TabIndex = 0;
this->pnlDrawing->Click += gcnew System::EventHandler(this, &MainForm::pnlDrawing_Click);
//
// pictureBox2
//
this->pictureBox2->Dock = System::Windows::Forms::DockStyle::Fill;
this->pictureBox2->Image = (cli::safe_cast<System::Drawing::Image^>(resources->GetObject(L"pictureBox2.Image")));
this->pictureBox2->Location = System::Drawing::Point(0, 0);
this->pictureBox2->Name = L"pictureBox2";
this->pictureBox2->Size = System::Drawing::Size(294, 452);
this->pictureBox2->TabIndex = 0;
this->pictureBox2->TabStop = false;
this->pictureBox2->Click += gcnew System::EventHandler(this, &MainForm::pnlDrawing_Click);
this->pictureBox2->Paint += gcnew System::Windows::Forms::PaintEventHandler(this, &MainForm::pnlDrawing_Paint);
//
// pnlGraphics
//
this->pnlGraphics->Controls->Add(this->btnDrawHouse);
this->pnlGraphics->Controls->Add(this->btnDrawImage);
this->pnlGraphics->Controls->Add(this->btnTranslatePoints);
this->pnlGraphics->Controls->Add(this->btnDrawLine);
this->pnlGraphics->Dock = System::Windows::Forms::DockStyle::Fill;
this->pnlGraphics->Location = System::Drawing::Point(3, 3);
this->pnlGraphics->Name = L"pnlGraphics";
this->pnlGraphics->Size = System::Drawing::Size(293, 452);
this->pnlGraphics->TabIndex = 1;
//
// btnDrawImage
//
this->btnDrawImage->Location = System::Drawing::Point(3, 61);
this->btnDrawImage->Name = L"btnDrawImage";
this->btnDrawImage->Size = System::Drawing::Size(75, 23);
this->btnDrawImage->TabIndex = 2;
this->btnDrawImage->Text = L"Draw Image";
this->btnDrawImage->UseVisualStyleBackColor = true;
this->btnDrawImage->Click += gcnew System::EventHandler(this, &MainForm::btnDrawImage_Click);
//
// btnTranslatePoints
//
this->btnTranslatePoints->Location = System::Drawing::Point(3, 32);
this->btnTranslatePoints->Name = L"btnTranslatePoints";
this->btnTranslatePoints->Size = System::Drawing::Size(75, 23);
this->btnTranslatePoints->TabIndex = 1;
this->btnTranslatePoints->Text = L"Zoom";
this->btnTranslatePoints->UseVisualStyleBackColor = true;
this->btnTranslatePoints->Click += gcnew System::EventHandler(this, &MainForm::btnTranslatePoints_Click);
//
// btnDrawLine
//
this->btnDrawLine->Location = System::Drawing::Point(3, 3);
this->btnDrawLine->Name = L"btnDrawLine";
this->btnDrawLine->Size = System::Drawing::Size(75, 23);
this->btnDrawLine->TabIndex = 0;
this->btnDrawLine->Text = L"Draw Line";
this->btnDrawLine->UseVisualStyleBackColor = true;
this->btnDrawLine->Click += gcnew System::EventHandler(this, &MainForm::btnDrawLine_Click);
//
// timer1
//
this->timer1->Interval = 1000;
this->timer1->Tick += gcnew System::EventHandler(this, &MainForm::timer1_Tick);
//
// menuStrip1
//
this->menuStrip1->Items->AddRange(gcnew cli::array< System::Windows::Forms::ToolStripItem^ >(3)
{
this->toolStripMenuItem1,
this->toolStripMenuItem3, this->toolStripMenuItem4
});
this->menuStrip1->Location = System::Drawing::Point(0, 0);
this->menuStrip1->Name = L"menuStrip1";
this->menuStrip1->Size = System::Drawing::Size(613, 24);
this->menuStrip1->TabIndex = 5;
this->menuStrip1->Text = L"menuStrip1";
//
// toolStripMenuItem1
//
this->toolStripMenuItem1->DropDownItems->AddRange(gcnew cli::array< System::Windows::Forms::ToolStripItem^ >(5)
{
this->toolStripMenuItem2,
this->toolStripSeparator1, this->mnuSaveFileDialog, this->mnuRichtextBox, this->mnuFolderBrowser
});
this->toolStripMenuItem1->Name = L"toolStripMenuItem1";
this->toolStripMenuItem1->Size = System::Drawing::Size(46, 20);
this->toolStripMenuItem1->Text = L"Datei";
//
// toolStripMenuItem2
//
this->toolStripMenuItem2->Name = L"toolStripMenuItem2";
this->toolStripMenuItem2->Size = System::Drawing::Size(190, 22);
this->toolStripMenuItem2->Text = L"Öffnen";
this->toolStripMenuItem2->Click += gcnew System::EventHandler(this, &MainForm::toolStripMenuItem2_Click);
//
// toolStripSeparator1
//
this->toolStripSeparator1->Name = L"toolStripSeparator1";
this->toolStripSeparator1->Size = System::Drawing::Size(187, 6);
//
// mnuSaveFileDialog
//
this->mnuSaveFileDialog->Name = L"mnuSaveFileDialog";
this->mnuSaveFileDialog->Size = System::Drawing::Size(190, 22);
this->mnuSaveFileDialog->Text = L"Speichern";
this->mnuSaveFileDialog->Click += gcnew System::EventHandler(this, &MainForm::mnuSaveFileDialog_Click);
//
// mnuRichtextBox
//
this->mnuRichtextBox->Name = L"mnuRichtextBox";
this->mnuRichtextBox->Size = System::Drawing::Size(190, 22);
this->mnuRichtextBox->Text = L"Richtextbox Speichern";
this->mnuRichtextBox->Click += gcnew System::EventHandler(this, &MainForm::mnuRichtextBox_Click);
//
// mnuFolderBrowser
//
this->mnuFolderBrowser->Name = L"mnuFolderBrowser";
this->mnuFolderBrowser->Size = System::Drawing::Size(190, 22);
this->mnuFolderBrowser->Text = L"FolderBrowserDialog";
this->mnuFolderBrowser->Click += gcnew System::EventHandler(this, &MainForm::mnuFolderBrowser_Click);
//
// toolStripMenuItem3
//
this->toolStripMenuItem3->DropDownItems->AddRange(gcnew cli::array< System::Windows::Forms::ToolStripItem^ >(2)
{
this->mnuFarben,
this->mnuSchriftart
});
this->toolStripMenuItem3->Name = L"toolStripMenuItem3";
this->toolStripMenuItem3->Size = System::Drawing::Size(90, 20);
this->toolStripMenuItem3->Text = L"Einstellungen";
//
// mnuFarben
//
this->mnuFarben->Name = L"mnuFarben";
this->mnuFarben->Size = System::Drawing::Size(122, 22);
this->mnuFarben->Text = L"Farben";
this->mnuFarben->Click += gcnew System::EventHandler(this, &MainForm::mnuFarben_Click);
//
// mnuSchriftart
//
this->mnuSchriftart->Name = L"mnuSchriftart";
this->mnuSchriftart->Size = System::Drawing::Size(122, 22);
this->mnuSchriftart->Text = L"Schriftart";
this->mnuSchriftart->Click += gcnew System::EventHandler(this, &MainForm::mnuSchriftart_Click);
//
// toolStripMenuItem4
//
this->toolStripMenuItem4->DropDownItems->AddRange(gcnew cli::array< System::Windows::Forms::ToolStripItem^ >(3)
{
this->mnuButtonsHerstellen,
this->mnuListControls, this->mnuTextBoxenHerstellen
});
this->toolStripMenuItem4->Name = L"toolStripMenuItem4";
this->toolStripMenuItem4->Size = System::Drawing::Size(54, 20);
this->toolStripMenuItem4->Text = L"Debug";
//
// mnuButtonsHerstellen
//
this->mnuButtonsHerstellen->Name = L"mnuButtonsHerstellen";
this->mnuButtonsHerstellen->Size = System::Drawing::Size(198, 22);
this->mnuButtonsHerstellen->Text = L"Buttons herstellen";
this->mnuButtonsHerstellen->Click += gcnew System::EventHandler(this, &MainForm::mnuButtonsHerstellen_Click);
//
// mnuListControls
//
this->mnuListControls->Name = L"mnuListControls";
this->mnuListControls->Size = System::Drawing::Size(198, 22);
this->mnuListControls->Text = L"Liste Controls tabPage2";
this->mnuListControls->Click += gcnew System::EventHandler(this, &MainForm::mnuListControls_Click);
//
// mnuTextBoxenHerstellen
//
this->mnuTextBoxenHerstellen->Name = L"mnuTextBoxenHerstellen";
this->mnuTextBoxenHerstellen->Size = System::Drawing::Size(198, 22);
this->mnuTextBoxenHerstellen->Text = L"TextBoxen herstellen";
this->mnuTextBoxenHerstellen->Click += gcnew System::EventHandler(this, &MainForm::mnuTextBoxenHerstellen_Click);
//
// openFileDialog1
//
this->openFileDialog1->FileName = L"openFileDialog1";
//
// fontDialog1
//
this->fontDialog1->ShowColor = true;
//
// btnDrawHouse
//
this->btnDrawHouse->Location = System::Drawing::Point(3, 90);
this->btnDrawHouse->Name = L"btnDrawHouse";
this->btnDrawHouse->Size = System::Drawing::Size(75, 23);
this->btnDrawHouse->TabIndex = 3;
this->btnDrawHouse->Text = L"Draw House";
this->btnDrawHouse->UseVisualStyleBackColor = true;
this->btnDrawHouse->Click += gcnew System::EventHandler(this, &MainForm::btnDrawHouse_Click);
//
// MainForm
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(613, 514);
this->Controls->Add(this->tabControl1);
this->Controls->Add(this->menuStrip1);
this->MainMenuStrip = this->menuStrip1;
this->Name = L"MainForm";
this->Text = L"MainForm";
this->tableLayoutPanel1->ResumeLayout(false);
this->tableLayoutPanel1->PerformLayout();
this->contextMenuStrip1->ResumeLayout(false);
this->panel1->ResumeLayout(false);
this->panel2->ResumeLayout(false);
this->panel2->PerformLayout();
(cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->trackBar1))->EndInit();
(cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->numericUpDown1))->EndInit();
this->groupBox1->ResumeLayout(false);
this->groupBox1->PerformLayout();
this->panel3->ResumeLayout(false);
this->panel3->PerformLayout();
(cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->pictureBox1))->EndInit();
this->tabControl1->ResumeLayout(false);
this->tabPage1->ResumeLayout(false);
this->tabPage2->ResumeLayout(false);
this->tableLayoutPanel2->ResumeLayout(false);
this->tableLayoutPanel2->PerformLayout();
this->panel4->ResumeLayout(false);
this->tabPage3->ResumeLayout(false);
this->tabPage3->PerformLayout();
this->tabPage4->ResumeLayout(false);
this->tableLayoutPanel3->ResumeLayout(false);
this->pnlDrawing->ResumeLayout(false);
(cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->pictureBox2))->EndInit();
this->pnlGraphics->ResumeLayout(false);
this->menuStrip1->ResumeLayout(false);
this->menuStrip1->PerformLayout();
this->ResumeLayout(false);
this->PerformLayout();
}
#pragma endregion
private: System::Void cmdChangeFormColor_Click(System::Object^ sender, System::EventArgs^ e)
{
cmdChangeFormColor->BackColor = System::Drawing::Color(Color::HotPink);
this->BackColor = System::Drawing::Color(Color::GreenYellow);
}
private: System::Void btnChangeTab_Click(System::Object^ sender, System::EventArgs^ e)
{
textBox1->AppendText(tabControl1->SelectedIndex.ToString());
tabControl1->SelectedIndex = 1;
tabControl1->SelectTab(1);
textBox1->AppendText(textBox1->GetType()->ToString());
}
private: System::Void btnCheckbox_Click(System::Object^ sender, System::EventArgs^ e)
{
textBox1->AppendText(checkBox1->Checked.ToString());
if (checkBox1->Checked)
{
System::Windows::Forms::DialogResult dR =
MessageBox::Show("Oh nooooo, I'm checked !\r\n", "Please click !", MessageBoxButtons::YesNoCancel, MessageBoxIcon::Warning);
if (dR == System::Windows::Forms::DialogResult::Cancel)
{
textBox1->AppendText("User cancelled the action !\r\n");
}
else if (dR == System::Windows::Forms::DialogResult::Yes)
{
textBox1->AppendText("You're amazing !!\r\n");
}
else if (dR == System::Windows::Forms::DialogResult::No)
{
textBox1->AppendText("Whaaaaat ??!!\r\n");
}
}
else
{
MessageBox::Show("Pleaseeeeee check me !\r\n");
}
}
private: System::Void checkBox1_CheckedChanged(System::Object^ sender, System::EventArgs^ e)
{
textBox1->AppendText("You changed the checkBox1 to " + checkBox1->Checked.ToString() + "\r\n");
}
RadioButton^ gimmeActiveRadioButton()
{
if (radioButton1->Checked)
{
return radioButton1;
}
else if (radioButton2->Checked)
{
return radioButton2;
}
else if (radioButton3->Checked)
{
return radioButton3;
}
}
private: System::Void btnRadioButton_Click(System::Object^ sender, System::EventArgs^ e)
{
textBox1->AppendText("Radiobutton : " + gimmeActiveRadioButton()->Name);
}
private: System::Void btnComboboxValue_Click(System::Object^ sender, System::EventArgs^ e)
{
}
private: System::Void cmbBlubb_SelectedIndexChanged(System::Object^ sender, System::EventArgs^ e)
{
textBox1->AppendText(cmbBlubb->Text);
}
private: System::Void btnComboAddItem_Click(System::Object^ sender, System::EventArgs^ e)
{
cmbBlubb->Items->Add("WoW");
}
private: System::Void btnComboremoveItem_Click(System::Object^ sender, System::EventArgs^ e)
{
cmbBlubb->Items->RemoveAt(2);
}
private: System::Void btnComboInsert_Click(System::Object^ sender, System::EventArgs^ e)
{
cmbBlubb->Items->Insert(2, "Test");
}
private: System::Void listBox1_SelectedIndexChanged(System::Object^ sender, System::EventArgs^ e)
{
int selectedItemsCount = listBox1->SelectedItems->Count;
for (int i = 0;i < selectedItemsCount;i++)
{
textBox1->AppendText(listBox1->SelectedItems[i]->ToString() + "\r\n");
}
}
private: System::Void btnNextStep_Click(System::Object^ sender, System::EventArgs^ e)
{
if (step == 0)
{
txtQuestions->Clear();
txtQuestions->AppendText("Wie heisst Du ?\r\n");
txtAnswers->Clear();
}
else if (step == 1)
{
txtQuestions->AppendText("Du heisst also " + txtAnswers->Text + " !\r\n");
antwort1 = txtAnswers->Text;
txtQuestions->AppendText("Wie alt bist Du ?\r\n");
txtAnswers->Clear();
}
else if (step == 2)
{
txtQuestions->AppendText("Du bist also " + txtAnswers->Text + " alt !\r\n");
antwort2 = txtAnswers->Text;
txtQuestions->AppendText("Was ist Deine Lieblingsfarbe ?\r\n");
txtAnswers->Clear();
}
else if (step == 3)
{
txtQuestions->AppendText("Deine Lieblingsfarbe ist also " + txtAnswers->Text + " !\r\n");
antwort3 = txtAnswers->Text;
txtQuestions->AppendText("Danke für's Gespräch !\r\n");
txtAnswers->Clear();
}
step++;
}
private: System::Void btnChangeFromAnotherClass_Click(System::Object^ sender, System::EventArgs^ e)
{
t = gcnew Test();
//t->changeTextBoxText(this);
}
private: System::Void btnStartProgress_Click(System::Object^ sender, System::EventArgs^ e)
{
//for(int counter = 0;counter <=100 ;counter++){
// System::Threading::Thread::Sleep(500);
// progressBar1->Value = counter;
//}
progress = 0;
timer1->Enabled = true;
}
private: System::Void timer1_Tick(System::Object^ sender, System::EventArgs^ e)
{
if (progress <= 100)
{
progressBar1->Value = progress;
progress += 5;
}
else
{
timer1->Enabled = false;
}
}
private: System::Void trackBar1_Scroll(System::Object^ sender, System::EventArgs^ e)
{
textBox1->AppendText(trackBar1->Value + "\r\n");
}
private: System::Void toolStripMenuItem2_Click(System::Object^ sender, System::EventArgs^ e)
{
openFileDialog1->Filter
= "Solution Files|*.sln;*.vcxproj|Text Files|*.txt|Image Files(*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|All files (*.*)|*.*";
openFileDialog1->FilterIndex = 2;
openFileDialog1->InitialDirectory = "d:\\";
System::Windows::Forms::DialogResult dialogResult = openFileDialog1->ShowDialog();
if (dialogResult == System::Windows::Forms::DialogResult::OK)
{
if (openFileDialog1->Multiselect == true)
{
for each(String^ einFileName in openFileDialog1->FileNames)
{
textBox1->AppendText(einFileName + "\r\n");
}
}
else
{
textBox1->AppendText(openFileDialog1->FileName + "\r\n");
String^ inhaltDerDatei = System::IO::File::ReadAllText(openFileDialog1->FileName);
textBox1->AppendText(inhaltDerDatei);
}
}
else
{
textBox1->AppendText("Datei auswählen !\r\n");
}
}
private: System::Void mnuFarben_Click(System::Object^ sender, System::EventArgs^ e)
{
System::Windows::Forms::DialogResult dialogResult = colorDialog1->ShowDialog();
if (dialogResult == System::Windows::Forms::DialogResult::OK)
{
textBox1->BackColor = colorDialog1->Color;
}
}
private: System::Void mnuSaveFileDialog_Click(System::Object^ sender, System::EventArgs^ e)
{
saveFileDialog1->Filter = "Solution Files|*.sln;*.vcxproj|Text Files|*.txt|Image Files(*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|All files (*.*)|*.*";
saveFileDialog1->FilterIndex = 2;
saveFileDialog1->InitialDirectory = "d:\\";
System::Windows::Forms::DialogResult dialogResult = saveFileDialog1->ShowDialog();
if (dialogResult == System::Windows::Forms::DialogResult::OK)
{
System::IO::File::WriteAllText(saveFileDialog1->FileName, textBox1->Text);
}
}
private: System::Void mnuSchriftart_Click(System::Object^ sender, System::EventArgs^ e)
{
System::Windows::Forms::DialogResult dialogResult = fontDialog1->ShowDialog();
if (dialogResult == System::Windows::Forms::DialogResult::OK)
{
textBox1->Font = fontDialog1->Font;
textBox1->ForeColor = fontDialog1->Color;
}
}
private: System::Void mnuRichtextBox_Click(System::Object^ sender, System::EventArgs^ e)
{
richTextBox1->SaveFile("d:\\richtexttest.rtf");
}
private: System::Void mnuFolderBrowser_Click(System::Object^ sender, System::EventArgs^ e)
{
folderBrowserDialog1->ShowDialog();
}
private: System::Void mnuClearText_Click(System::Object^ sender, System::EventArgs^ e)
{
textBox1->Clear();
}
private: System::Void dateTimePicker1_ValueChanged(System::Object^ sender, System::EventArgs^ e)
{
DateTime t = dateTimePicker1->Value;
DateTime aktuelleZeit = DateTime::Now;
textBox1->AppendText(t.ToLongDateString() + "\n");
textBox1->AppendText(aktuelleZeit.ToLongTimeString() + "\n");
TimeSpan dauer(10, 10, 10, 10);
DateTime summe = t.Add(dauer);
}
private: System::Void mnuButtonsHerstellen_Click(System::Object^ sender, System::EventArgs^ e)
{
for (int counter = 0; counter < 10;counter++)
{
System::Windows::Forms::Button^ btnDynamicButton = gcnew System::Windows::Forms::Button;
btnDynamicButton->Location = System::Drawing::Point(0, 0 + 25 * counter);
btnDynamicButton->Name = L"btnDynamicButton" + counter;
btnDynamicButton->Size = System::Drawing::Size(109, 23);
btnDynamicButton->TabIndex = 8;
btnDynamicButton->Text = L"I'm dynamic " + counter;
btnDynamicButton->UseVisualStyleBackColor = true;
btnDynamicButton->Click += gcnew System::EventHandler(this, &MainForm::dynamicButtonsClick);
tabPage2->Controls->Add(btnDynamicButton);
}
}
private: System::Void mnuListControls_Click(System::Object^ sender, System::EventArgs^ e)
{
for each(Control^ control in tabPage2->Controls)
{
textBox1->AppendText(control->Name + "\n");
}
}
private: System::Void dynamicButtonsClick(System::Object^ sender, System::EventArgs^ e)
{
textBox1->AppendText("Dynamic Button clicked !\t" + ((Button^)sender)->Name + "\n");
if (((Button^)sender)->Name == "btnDynamicButton3")
{
MessageBox::Show("Du hast den richtigen Button gedrückt !");
}
}
private: System::Void mnuTextBoxenHerstellen_Click(System::Object^ sender, System::EventArgs^ e)
{
createTextBoxes();
}
void createTextBoxes()
{
for (int counter = 0;counter < 10;counter++)
{
TextBox^ dynamicTextBox = gcnew TextBox;
dynamicTextBox->Location = System::Drawing::Point(200, 0 + 25 * counter);
dynamicTextBox->Name = L"textBox" + counter;
dynamicTextBox->ScrollBars = System::Windows::Forms::ScrollBars::Both;
dynamicTextBox->TabIndex = 67;
dynamicTextBox->TextChanged += gcnew System::EventHandler(this, &MainForm::dynamicTextBoxesTextChanged);
tabPage2->Controls->Add(dynamicTextBox);
}
}
private: System::Void dynamicTextBoxesTextChanged(System::Object^ sender, System::EventArgs^ e)
{
textBox1->AppendText(((TextBox^)sender)->Name + " TextChanged : " + ((TextBox^)sender)->Text + "\n");
}
private: System::Void btnAddDoubles_Click(System::Object^ sender, System::EventArgs^ e)
{
double ersteZahl = Double::Parse(txtErsteZahl->Text);
double zweiteZahl = Double::Parse(txtZweiteZahl->Text);
double ergebnis = ersteZahl + zweiteZahl;
textBox1->AppendText(ergebnis.ToString("N2"));
}
private: System::Void btnArrayList_Click(System::Object^ sender, System::EventArgs^ e)
{
ArrayList^ listeVonElementen = gcnew ArrayList;
listeVonElementen->Add("Bli");
txtCollections->AppendText("\n:::" + listeVonElementen[0]->ToString() + "\n");
listeVonElementen->Add("Bla");
listeVonElementen->Add("Blubb");
listeVonElementen->Add("Yeah");
listeVonElementen->Add(this);
listeVonElementen->Add(3);
listeVonElementen->Add(gcnew Button);
listeVonElementen->Remove("Bli");
txtCollections->AppendText(listeVonElementen->IndexOf("Yeah").ToString());
listeVonElementen->Insert(3, "Blubbbbbb");
listeVonElementen->Reverse();
for each(Object^ o in listeVonElementen)
{
txtCollections->AppendText(o->GetType() + " | " + o->ToString() + "\r\n");
}
}
private: System::Void btnQueue_Click(System::Object^ sender, System::EventArgs^ e)
{
System::Collections::Queue^ queue = gcnew System::Collections::Queue;
queue->Enqueue("1");
queue->Enqueue("3");
queue->Enqueue("2");
queue->Enqueue("4");
txtCollections->Text += queue->Count.ToString();
int count = queue->Count;
for (int counter = 1;counter <= count;counter++)
{
txtCollections->AppendText(queue->Dequeue()->ToString());
//NICHT rausnehmen, nur drauf schauen
//txtCollections->AppendText(queue->Peek()->ToString());
}
}
private: System::Void btnStack_Click(System::Object^ sender, System::EventArgs^ e)
{
Stack^ stack = gcnew Stack;
stack->Push("1");
//stack->Push(1);
//stack->Push(this);
stack->Push("2");
stack->Push("3");
stack->Push("4");
stack->Push("5");
int count = stack->Count;
for (int counter = 0;counter < count;counter++)
{
txtCollections->AppendText((String^)stack->Pop());
}
}
private: System::Void btnSortedList_Click(System::Object^ sender, System::EventArgs^ e)
{
SortedList^ sortedList = gcnew SortedList;
sortedList->Add(1, "Sieger");
//sortedList->Add(1, "Sieger"); -> Fehler, existiert schon
sortedList->Add(3, "Drittplatzierter");
sortedList->Add(2, "Zweiter Sieger");
for each(int key in sortedList->Keys)
{
txtCollections->AppendText(key + " | " + sortedList[key] + "\r\n");
}
SortedList^ sortedList1 = gcnew SortedList;
DateTime d = DateTime(1971, 12, 12);
sortedList1->Add(d, "Sieger3");
sortedList1->Add(DateTime(1970, 12, 12), "Sieger2");
sortedList1->Add(DateTime(1968, 12, 12), "Sieger1");
for each(DateTime key in sortedList1->Keys)
{
txtCollections->AppendText(key + " | " + sortedList1[key] + "\r\n");
}
}
private: System::Void btnHashtable_Click(System::Object^ sender, System::EventArgs^ e)
{
Hashtable^ openWith = gcnew Hashtable;
// Add some elements to the hash table. There are no
// duplicate keys, but some of the values are duplicates.
openWith->Add("txt", "notepad.exe");
//openWith->Add("txt", "notepad.exe"); -> Fehler
openWith->Add("bmp", "paint.exe");
openWith->Add("dib", "paint.exe");
openWith->Add("rtf", "wordpad.exe");
txtCollections->AppendText(openWith["txt"] + "\r\n");
openWith["rtf"] = "winword.exe";
//If the key "ht" doesn't exist, add entry to our Hashtable
if (!openWith->ContainsKey("ht"))
{
openWith->Add("ht", "hypertrm.exe");
}
for each(DictionaryEntry de in openWith)
{
txtCollections->AppendText(de.Key + " | " + de.Value + "\r\n");
}
}
private: System::Void btnList_Click(System::Object^ sender, System::EventArgs^ e)
{
//Fully qualified |Diamantoperator
System::Collections::Generic::List<String^>^ phrases = gcnew System::Collections::Generic::List<String^>();
phrases->Add("Text");
phrases->Add("Text1");
phrases->Add("Text2");
phrases->Add("Text3");
//phrases->Add(34);-> Fehler
for each(String^ oneElement in phrases)
{
txtCollections->AppendText(oneElement);
}
}
private: System::Void btnArray_Click(System::Object^ sender, System::EventArgs^ e)
{
array<String^>^ myArr = { L"The", L"quick", L"brown", L"fox",
L"jumps", L"over", L"the", L"lazy", L"dog" };
Array::Resize(myArr, myArr->Length + 5);
array<Byte>^ buffer = gcnew array<Byte>(1024);
ArrayList^ l = gcnew ArrayList(myArr);
l->AddRange(myArr);
array<String ^, 3> ^ my3DArray = gcnew array<String ^, 3>(3, 5, 6);
my3DArray[0, 0, 0] = "Bla";
ArrayList^ zeile = gcnew ArrayList;
ArrayList^ spalte = gcnew ArrayList;
spalte->Add(zeile);
((ArrayList^)spalte[0])[0] = "j";
}
private: System::Void btnBenchmark_Click(System::Object^ sender, System::EventArgs^ e)
{
int size = 10000000;
ArrayList^ numbers = gcnew ArrayList;
DateTime startTime = DateTime::Now;
for (int counter = 0; counter < size; counter++)
{
numbers->Add(counter);
}
DateTime endTime = DateTime::Now;
txtCollections->AppendText("\r\nCreation of 1M int in ArrayList :" + endTime.Subtract(startTime).TotalMilliseconds);
//////////////////////////////////////////////////////////
startTime = DateTime::Now;
array<int>^ intArray = gcnew array<int>(size);
for (int counter = 0; counter < size; counter++)
{
intArray[counter] = counter;
}
endTime = DateTime::Now;
txtCollections->AppendText("\r\nCreation of 1M int in array :" + endTime.Subtract(startTime).TotalMilliseconds);
//////////////////////////////////////////////////////////
startTime = DateTime::Now;
for (int counter = 0;counter < size;counter++)
{
int temp = (int)numbers[counter];
}
endTime = DateTime::Now;
txtCollections->AppendText("\r\nAccessing 1M int in ArrayList :" + endTime.Subtract(startTime).TotalMilliseconds);
//////////////////////////////////////////////////////////
startTime = DateTime::Now;
for (int counter = 0;counter < size;counter++)
{
int temp = intArray[counter];
}
endTime = DateTime::Now;
txtCollections->AppendText("\r\nAccessing 1M int in array :" + endTime.Subtract(startTime).TotalMilliseconds);
}
private: System::Void btnDrawLine_Click(System::Object^ sender, System::EventArgs^ e)
{
System::Drawing::Graphics^ graphics = pictureBox2->CreateGraphics();
System::Drawing::Pen^ penRed = gcnew System::Drawing::Pen(Color::Red);
System::Drawing::Pen^ penBlue = gcnew System::Drawing::Pen(Color::Blue);
System::Drawing::Pen^ penGreen = gcnew System::Drawing::Pen(Color::Green);
System::Drawing::Brush^ brushYellow = gcnew System::Drawing::SolidBrush(Color::Yellow);
graphics->DrawLine(penRed, 0, 0, 100, 300);
graphics->DrawLine(penBlue, 100, 200, 0, 0);
graphics->DrawEllipse(penGreen, 20, 90, 40, 20);
graphics->FillRectangle(brushYellow, 70, 70, 30, 60);
}
System::Drawing::Point lastPoint = Point(0, 0);
ArrayList^ points;
private: System::Void pnlDrawing_Click(System::Object^ sender, System::EventArgs^ e)
{
System::Drawing::Graphics^ graphics = pictureBox2->CreateGraphics();
System::Drawing::Pen^ penBlack = gcnew System::Drawing::Pen(Color::Black, 4);
// |Umrechnung |aktuelle Mouseposition Bildschirm
System::Drawing::Point actualPosition = pnlDrawing->PointToClient(this->Cursor->Position);
graphics->DrawLine(penBlack, lastPoint, actualPosition);
lastPoint = actualPosition;
points->Add(lastPoint);
System::Diagnostics::Debug::WriteLine(actualPosition.ToString());
}
private: System::Void pnlDrawing_Paint(System::Object^ sender, System::Windows::Forms::PaintEventArgs^ e)
{
drawLinesByPoints(e->Graphics);
}
void drawLinesByPoints(Graphics^ g)
{
System::Drawing::Pen^ penBlack = gcnew System::Drawing::Pen(Color::Black, 4);
int pointsCount = points->Count;
for (int counter = 0; counter < pointsCount - 1;counter++)
{
g->DrawLine(penBlack, (Point)points[counter], (Point)points[counter + 1]);
}
}
void translatePoints(int factor)
{
int pointsCount = points->Count;
for (int counter = 0; counter < pointsCount - 1;counter++)
{
Point newPoint = Point(((Point)points[counter]).X * factor, ((Point)points[counter]).Y * factor);
points[counter] = newPoint;
}
}
private: System::Void btnTranslatePoints_Click(System::Object^ sender, System::EventArgs^ e)
{
translatePoints(2);
pnlDrawing->CreateGraphics()->Clear(Color::Gainsboro);
pnlDrawing->Refresh();
}
private: System::Void btnDrawImage_Click(System::Object^ sender, System::EventArgs^ e)
{
System::Drawing::Pen^ penBlack = gcnew System::Drawing::Pen(Color::Black, 4);
System::Drawing::Image^ image = Image::FromFile("d:\\spaghettimonster.jpg");
Graphics^ imageGraphics = Graphics::FromImage(image);
imageGraphics->DrawLine(penBlack, 0, 0, 200, 200);
Point ulCorner = Point(100, 0);
pnlGraphics->CreateGraphics()->DrawImage(image, ulCorner);
image->Save("d:\\spaghettimonster12.jpg");
}
private: System::Void btnDrawHouse_Click(System::Object^ sender, System::EventArgs^ e)
{
for (int counter = 0.1;counter < 2;counter += 0.1)
{
drawHouse(pnlGraphics->CreateGraphics(), 0 + 10 * counter, 0 + 10 * counter, counter, counter);
}
}
void drawHouse(Graphics^ graphics, int startPositionX, int startPositionY, double scaleFactorX, double scaleFactorY)
{
System::Drawing::Pen^ penBlue = gcnew System::Drawing::Pen(Color::Blue);
drawSpecialLine(graphics, penBlue, startPositionX, startPositionY, 0, 300, 0, 100, scaleFactorX, scaleFactorY);
drawSpecialLine(graphics, penBlue, startPositionX, startPositionY, 0, 100, 200, 100, scaleFactorX, scaleFactorY);
drawSpecialLine(graphics, penBlue, startPositionX, startPositionY, 200, 100, 200, 300, scaleFactorX, scaleFactorY);
drawSpecialLine(graphics, penBlue, startPositionX, startPositionY, 200, 300, 0, 300, scaleFactorX, scaleFactorY);
drawSpecialLine(graphics, penBlue, startPositionX, startPositionY, 0, 100, 100, 20, scaleFactorX, scaleFactorY);
drawSpecialLine(graphics, penBlue, startPositionX, startPositionY, 100, 20, 200, 100, scaleFactorX, scaleFactorY);
drawSpecialLine(graphics, penBlue, startPositionX, startPositionY, 100, 20, 300, 20, scaleFactorX, scaleFactorY);
drawSpecialLine(graphics, penBlue, startPositionX, startPositionY, 300, 20, 400, 100, scaleFactorX, scaleFactorY);
drawSpecialLine(graphics, penBlue, startPositionX, startPositionY, 400, 100, 200, 100, scaleFactorX, scaleFactorY);
drawSpecialLine(graphics, penBlue, startPositionX, startPositionY, 400, 300, 400, 100, scaleFactorX, scaleFactorY);
drawSpecialLine(graphics, penBlue, startPositionX, startPositionY, 200, 300, 400, 300, scaleFactorX, scaleFactorY);
}
void drawSpecialLine(Graphics^ graphics, Pen^ pen, float startPositionX, float startPositionY, float x1, float y1, float x2, float y2, float scaleFactorX, float scaleFactorY)
{
graphics->DrawLine(pen, startPositionX + x1 * scaleFactorX, startPositionY + y1 * scaleFactorY, startPositionX + x2 * scaleFactorX, startPositionY + y2 * scaleFactorY);
}
};
}
|
[
"Alfa-Dozent@SB-U03-001"
] |
Alfa-Dozent@SB-U03-001
|
2729985e2cb2f2d5d99ae05ffdf3859abb456ee1
|
02ec47da2d5ae3216c9c747fe90a56c87a91b0e8
|
/WebpIO/src/ImageDecoderWEBP.h
|
f1a0c2e47cd3a4eac66066b2b7accfcb083c121a
|
[] |
no_license
|
gloryofrobots/UIO_Plugin
|
ad42a87750ee424e4a266842de8a446f2f861aed
|
42014e86d296e0aab2ae5d28fcdeb070942cdbfe
|
refs/heads/master
| 2016-08-05T04:46:05.045144
| 2013-03-13T11:12:11
| 2013-03-13T11:12:11
| 8,750,222
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 684
|
h
|
# pragma once
# include "CodecSystem/ImageDecoder.h"
# include "webp/decode.h"
//# include "webp/mux.h"
namespace UIO_Plugin
{
class ImageDecoderWEBP
: public ImageDecoder
{
public:
ImageDecoderWEBP();
virtual ~ImageDecoderWEBP();
void writeHeader( UIO_Plugin_Header * _header ) override;
protected:
bool _initialize() override;
bool _decode( unsigned char* _buffer, unsigned int _bufferSize ) override;
private:
bool _decodeScale( unsigned char* _buffer, unsigned int _bufferSize );
bool _decodeFull( unsigned char* _buffer, unsigned int _bufferSize );
protected:
uint8_t* m_dataBuffer;
size_t m_dataSize;
WebPDecoderConfig m_decoderConfig;
};
}
|
[
"gloryofrobots@gmail.com"
] |
gloryofrobots@gmail.com
|
cf6f46a0dccf27171e9256a24065b50ab1b0d85d
|
eb1360bb9c19fad69f0e3d95a49aba3e9a915aac
|
/LIB/argv_259.cpp
|
1e5086fb39259b2d6ca6dfbf5cd5b4f5feb9f53b
|
[] |
no_license
|
tybins99/CRYPTANALYSIS.ElGammal_IndexCalculus
|
3198a45e0fec21ba5d47404ddfdbb3dc16cf6be6
|
67e7eba85a59b6403c84d088fd58cbebbb50ff5a
|
refs/heads/master
| 2021-05-11T10:18:27.548769
| 2018-01-19T08:47:06
| 2018-01-19T08:47:06
| 118,099,519
| 3
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,521
|
cpp
|
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@ FILE: argv_259.cpp
// @@
// @@ DESCRIPTION:
// @@ This argv_1396 contains the argv_1139 structure and
// @@ function that are necessary for the plugins
// @@ to work.
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@ includes
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
#include "../LIB/argv_326.hpp"
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@
// @@ CLASS : -
// @@
// @@ FUNCTION : argv_2312
// @@
// @@ INPUT :
// @@ _dest: char * : the destination argv_771 where to copy the string
// @@ _src: char * : the source argv_771 where to copy the string from
// @@ _size: argv_3864 : the size of the string to copy
// @@
// @@ OUTPUT : none
// @@
// @@ IO : none
// @@
// @@ RETURN VALUE : none
// @@
// @@ DISCLOSURE : -
// @@
// @@ DESCRIPTION :
// @@ This function just permit to copy the string '_src' to the
// @@ string '_dest' assuming that the '_src' size is '_size'
// @@ and that the '_dest' is long enough to receive the '_src' string.
// @@
// @@ CONTRACT : none
// @@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
void argv_2312 (char * _dest, char * _src, argv_3864 _size) {
argv_3864 i=0;
while ((i < _size) && (_src[i] != '\0')) {
_dest[i] = _src[i];
i++;
}
// don't forget the string's argv_3739
if (i < _size) {
_dest[i] = '\0';
}
else {
_dest[_size - 1] = '\0';
}
}
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@
// @@ CLASS : -
// @@
// @@ FUNCTION : argv_1419
// @@
// @@ INPUT :
// @@ _type: argv_3864: argv_3842 of the argv_1396 whose readable argv_3842 is to be retrieved.
// @@
// @@ OUTPUT :
// @@ _str_type: char *: destination string where the argv_3402 of the argv_2253
// @@ is to be saved up (allocated by the caller).
// @@
// @@ IO : none
// @@
// @@ RETURN VALUE : none
// @@
// @@ DISCLOSURE : -
// @@
// @@ DESCRIPTION :
// @@ This function permits to argv_2253 the readable argv_1396 argv_3842 associated
// @@ with the '_type' argv_1396 argv_3842.
// @@ The argv_3402 is stored into a string that must have been allocated
// @@ by the caller prior to this call, it's length must be MAX_PATH_PLUGIN
// @@
// @@ Notice that if the '_type' parameter is not a valid argv_1396 argv_3842,
// @@ then "<UNKNOWN FILE TYPE>" is saved into the '_str_type' argv_3402
// @@ parameter.
// @@
// @@ CONTRACT : none
// @@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
void argv_1419 (argv_3864 _type, char * _str_type) {
switch (_type) {
case argv_1435 : argv_2312 (_str_type, "argv_1435", MAX_PATH_PLUGIN); break;
case argv_1422 : argv_2312 (_str_type, "argv_1422", MAX_PATH_PLUGIN); break;
case argv_1441 : argv_2312 (_str_type, "argv_1441", MAX_PATH_PLUGIN); break;
case argv_1424 : argv_2312 (_str_type, "argv_1424", MAX_PATH_PLUGIN); break;
case argv_1434 : argv_2312 (_str_type, "argv_1434", MAX_PATH_PLUGIN); break;
case argv_1439 : argv_2312 (_str_type, "argv_1439", MAX_PATH_PLUGIN); break;
default : argv_2312 (_str_type, "<UNKNOWN FILE TYPE>", MAX_PATH_PLUGIN);
}
}
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@ end of argv_1396
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
|
[
"flegardien@kertel.com"
] |
flegardien@kertel.com
|
405c462abae9d8bf8b83ea9ac71eb52d891c9f10
|
54b9ee00bcd582d56853ddb90be5cfeb0c29ba29
|
/src/utils/bdcom_cache_test.cc
|
0eaa0479d9ec5fd23bdbfab5e32d2cd46381c09b
|
[
"BSD-3-Clause"
] |
permissive
|
pengdu/bubblefs
|
8f4deb8668831496bb0cd8b7d9895900b1442ff1
|
9b27e191a287b3a1d012adfd3bab6a30629a5f33
|
refs/heads/master
| 2020-04-04T19:32:11.311925
| 2018-05-02T11:20:18
| 2018-05-02T11:20:18
| 156,210,664
| 2
| 0
| null | 2018-11-05T11:57:22
| 2018-11-05T11:57:21
| null |
UTF-8
|
C++
| false
| false
| 5,931
|
cc
|
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
// leveldb/util/cache_test.cc
#include "utils/bdcom_cache.h"
#include <vector>
#include "platform/test.h"
#include "utils/coding.h"
namespace bubblefs {
namespace mybdcom {
// Conversions between numeric keys/values and the types expected by Cache.
static std::string EncodeKey(int k) {
std::string result;
core::PutFixed32(&result, k);
return result;
}
static int DecodeKey(const Slice& k) {
assert(k.size() == 4);
return core::DecodeFixed32(k.data());
}
static void* EncodeValue(uintptr_t v) { return reinterpret_cast<void*>(v); }
static int DecodeValue(void* v) { return reinterpret_cast<uintptr_t>(v); }
class CacheTest : public ::testing::Test {
public:
static CacheTest* current_;
static void Deleter(const Slice& key, void* v) {
current_->deleted_keys_.push_back(DecodeKey(key));
current_->deleted_values_.push_back(DecodeValue(v));
}
static const int kCacheSize = 1000;
std::vector<int> deleted_keys_;
std::vector<int> deleted_values_;
Cache* cache_;
CacheTest() : cache_(NewLRUCache(kCacheSize)) {
current_ = this;
}
~CacheTest() {
delete cache_;
}
int Lookup(int key) {
Cache::Handle* handle = cache_->Lookup(EncodeKey(key));
const int r = (handle == NULL) ? -1 : DecodeValue(cache_->Value(handle));
if (handle != NULL) {
cache_->Release(handle);
}
return r;
}
void Insert(int key, int value, int charge = 1) {
cache_->Release(cache_->Insert(EncodeKey(key), EncodeValue(value), charge,
&CacheTest::Deleter));
}
Cache::Handle* InsertAndReturnHandle(int key, int value, int charge = 1) {
return cache_->Insert(EncodeKey(key), EncodeValue(value), charge,
&CacheTest::Deleter);
}
void Erase(int key) {
cache_->Erase(EncodeKey(key));
}
};
CacheTest* CacheTest::current_;
TEST_F(CacheTest, HitAndMiss) {
ASSERT_EQ(-1, Lookup(100));
Insert(100, 101);
ASSERT_EQ(101, Lookup(100));
ASSERT_EQ(-1, Lookup(200));
ASSERT_EQ(-1, Lookup(300));
Insert(200, 201);
ASSERT_EQ(101, Lookup(100));
ASSERT_EQ(201, Lookup(200));
ASSERT_EQ(-1, Lookup(300));
Insert(100, 102);
ASSERT_EQ(102, Lookup(100));
ASSERT_EQ(201, Lookup(200));
ASSERT_EQ(-1, Lookup(300));
ASSERT_EQ(1, deleted_keys_.size());
ASSERT_EQ(100, deleted_keys_[0]);
ASSERT_EQ(101, deleted_values_[0]);
}
TEST_F(CacheTest, Erase) {
Erase(200);
ASSERT_EQ(0, deleted_keys_.size());
Insert(100, 101);
Insert(200, 201);
Erase(100);
ASSERT_EQ(-1, Lookup(100));
ASSERT_EQ(201, Lookup(200));
ASSERT_EQ(1, deleted_keys_.size());
ASSERT_EQ(100, deleted_keys_[0]);
ASSERT_EQ(101, deleted_values_[0]);
Erase(100);
ASSERT_EQ(-1, Lookup(100));
ASSERT_EQ(201, Lookup(200));
ASSERT_EQ(1, deleted_keys_.size());
}
TEST_F(CacheTest, EntriesArePinned) {
Insert(100, 101);
Cache::Handle* h1 = cache_->Lookup(EncodeKey(100));
ASSERT_EQ(101, DecodeValue(cache_->Value(h1)));
Insert(100, 102);
Cache::Handle* h2 = cache_->Lookup(EncodeKey(100));
ASSERT_EQ(102, DecodeValue(cache_->Value(h2)));
ASSERT_EQ(0, deleted_keys_.size());
cache_->Release(h1);
ASSERT_EQ(1, deleted_keys_.size());
ASSERT_EQ(100, deleted_keys_[0]);
ASSERT_EQ(101, deleted_values_[0]);
Erase(100);
ASSERT_EQ(-1, Lookup(100));
ASSERT_EQ(1, deleted_keys_.size());
cache_->Release(h2);
ASSERT_EQ(2, deleted_keys_.size());
ASSERT_EQ(100, deleted_keys_[1]);
ASSERT_EQ(102, deleted_values_[1]);
}
TEST_F(CacheTest, EvictionPolicy) {
Insert(100, 101);
Insert(200, 201);
Insert(300, 301);
Cache::Handle* h = cache_->Lookup(EncodeKey(300));
// Frequently used entry must be kept around,
// as must things that are still in use.
for (int i = 0; i < kCacheSize + 100; i++) {
Insert(1000+i, 2000+i);
ASSERT_EQ(2000+i, Lookup(1000+i));
ASSERT_EQ(101, Lookup(100));
}
ASSERT_EQ(101, Lookup(100));
ASSERT_EQ(-1, Lookup(200));
ASSERT_EQ(301, Lookup(300));
cache_->Release(h);
}
TEST_F(CacheTest, UseExceedsCacheSize) {
// Overfill the cache, keeping handles on all inserted entries.
std::vector<Cache::Handle*> h;
for (int i = 0; i < kCacheSize + 100; i++) {
h.push_back(InsertAndReturnHandle(1000+i, 2000+i));
}
// Check that all the entries can be found in the cache.
for (size_t i = 0; i < h.size(); i++) {
ASSERT_EQ(2000+i, Lookup(1000+i));
}
for (size_t i = 0; i < h.size(); i++) {
cache_->Release(h[i]);
}
}
TEST_F(CacheTest, HeavyEntries) {
// Add a bunch of light and heavy entries and then count the combined
// size of items still in the cache, which must be approximately the
// same as the total capacity.
const int kLight = 1;
const int kHeavy = 10;
int added = 0;
int index = 0;
while (added < 2*kCacheSize) {
const int weight = (index & 1) ? kLight : kHeavy;
Insert(index, 1000+index, weight);
added += weight;
index++;
}
int cached_weight = 0;
for (int i = 0; i < index; i++) {
const int weight = (i & 1 ? kLight : kHeavy);
int r = Lookup(i);
if (r >= 0) {
cached_weight += weight;
ASSERT_EQ(1000+i, r);
}
}
ASSERT_LE(cached_weight, kCacheSize + kCacheSize/10);
}
TEST_F(CacheTest, NewId) {
uint64_t a = cache_->NewId();
uint64_t b = cache_->NewId();
ASSERT_NE(a, b);
}
TEST_F(CacheTest, Prune) {
Insert(1, 100);
Insert(2, 200);
Cache::Handle* handle = cache_->Lookup(EncodeKey(1));
ASSERT_TRUE(handle);
cache_->Prune();
cache_->Release(handle);
ASSERT_EQ(100, Lookup(1));
ASSERT_EQ(-1, Lookup(2));
}
} // namespace bubblefs
} // namespace mybdcom
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
[
"691225916@qq.com"
] |
691225916@qq.com
|
c88f519e80c3474455980866828cf3827462f5da
|
2a6c97e4bc7e329ae5fcea951c996d20c461fd74
|
/ExamplesAndPractice/BankApplicationExamplewithTests/BankApplicationExamplewithTests/BankApplicationExamplewithTests/main.cpp
|
451967b5a2f6ce384c340ac5f9425bf9088ae647
|
[] |
no_license
|
EdgarVi/CptS-122
|
690d5760ffcd25fa37c7fbd13980d063d6f13d35
|
daddf23bfc473191df3d754ff3f74f283b0a052a
|
refs/heads/main
| 2023-01-23T18:47:50.792774
| 2020-12-10T23:56:57
| 2020-12-10T23:56:57
| 320,418,852
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,841
|
cpp
|
///////////////////////////////////////////////////////////////////////////////
/// \file Main Program App (main.cpp)
/// \author Andrew S. O'Fallon
/// \date
/// \brief This application performs basic banking operations.
/// Limited error checking is provided.
///
///
/// REVISION HISTORY:
/// \date
///
///////////////////////////////////////////////////////////////////////////////
//Problem Statement:
//Note: This project is similar to the Account Class
//problem provided in your Deitel and Deitel C How To
//Program book. You are to write a
//basic bank application, in C++, that allows the user
//of the application to manually create,
//modify, and delete bank accounts. Before you write the
//application you will need to create a class called Account.
//The class Account is used to represent customers' bank
//accounts. Your class should include four data members to
//represent the account balance (a double), account number
//(an integer), customer name (a string), and date the
//account was opened (a string).
//Your class should provide two constructors: one default
//constructor with no parameters and one constructor with
//the initial balance, account
//number, customer name, and date created as parameters.
//The second constructor should check the initial balance.
//If the balance is not >= 0, the balance should be set to 0
//and an error message should be displayed.
//
//The class should provide several member functions. Some
//of which are described below. Remember that you will have
//to think about other appropriate member functions (think
//about setter and getter functions!). Member function credit
//should
//add an amount to the current balance and store it back into
//the balance. Member function debit should withdraw money
//from the Account, modify
//the balance, and ensure the debit amount does not exceed
//the Account's balance. If it does, the balance should be
//left unmodified and the function
//should print an appropriate message. Member function
//printAccountInfo should print the current balance, account
//number, customer name, and date of the account.
//
//Once you have designed your Account class. You will need to
//create the main bank program. Note that you can create the
//main bank program
//in the main function or you can try to create another class
//for the main bank program. The main program needs to display
//a menu for adding,
//deleting, modifying, and displaying accounts. You decide
//appropriate menu features! Have fun with this assignment!
#include "BankManager.h"
#include "TestApp.h"
int main(void)
{
runTestSuite(); // run the series of tests available
BankManager bankApp;
bankApp.runBankApplication(); // run the actual application for the bank system
return 0;
}
|
[
"edgar.villasenor@wsu.edu"
] |
edgar.villasenor@wsu.edu
|
f2973761175052c541d80721c8d7f328383f331e
|
c3b9668c9595a58b7751761780f5fa92ef11fa9c
|
/D01/ex05/Human.hpp
|
2328eea4a2e36bb9c015019c2dab42c3a6d954f2
|
[] |
no_license
|
dgalide/piscinecpp
|
4a91e614c73474dfb90d20265603224edc5bd3f0
|
484f395f0dd24c53815c0645d1e792c7816af667
|
refs/heads/master
| 2020-03-30T06:27:52.182053
| 2018-10-13T07:20:58
| 2018-10-13T07:20:58
| 150,863,269
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 207
|
hpp
|
#ifndef HUMAN_HPP
#define HUMAN_HPP
#include "Brain.hpp"
class Human {
public:
Human(void);
~Human(void);
Brain getBrain(void);
std::string identify(void);
private:
Brain _brain;
};
#endif
|
[
"dgalide@student.42.fr"
] |
dgalide@student.42.fr
|
8e623a6c00e2d477f05ce0706db72111fddec676
|
5bcedc9c0b9c92f795cd04927bc1b752b8bbe6f3
|
/gtkmm_examples/src/entry/examplewindow.h
|
46c50f328622d993d749a883b820ad133ea9c681
|
[
"FSFAP"
] |
permissive
|
hamedobaidy/gtkmm_eclipse_examples
|
8d466523b8e680b3d77bf0026320321aa56a22e3
|
379c7b8e7640aef67ec189b10c54442251c2a2b8
|
refs/heads/master
| 2021-01-20T15:33:35.355311
| 2015-09-15T15:52:20
| 2015-09-15T15:52:20
| 38,481,378
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 601
|
h
|
/*
* examplewindow.h
*
* Created on: Jun 30, 2015
* Author: hamed
*/
#ifndef EXAMPLEWINDOW_H_
#define EXAMPLEWINDOW_H_
#include <gtkmm.h>
class ExampleWindow : public Gtk::Window
{
public:
ExampleWindow();
virtual ~ExampleWindow();
protected:
//Signal handlers:
void on_checkbox_editable_toggled();
void on_checkbox_visibility_toggled();
void on_button_close();
//Child widgets:
Gtk::Box m_HBox;
Gtk::Box m_VBox;
Gtk::Entry m_Entry;
Gtk::Button m_Button_Close;
Gtk::CheckButton m_CheckButton_Editable, m_CheckButton_Visible;
};
#endif /* EXAMPLEWINDOW_H_ */
|
[
"hamed.obaidy@gmail.com"
] |
hamed.obaidy@gmail.com
|
629c2c3bb5f48d978507f68195f82d5a9638b6d3
|
ba4db75b9d1f08c6334bf7b621783759cd3209c7
|
/src_main/common/xsi/5.1/ftk/ImageClip.h
|
9ae6d64771f422363019c2e2ed7c9f4d7bcc3190
|
[] |
no_license
|
equalent/source-2007
|
a27326c6eb1e63899e3b77da57f23b79637060c0
|
d07be8d02519ff5c902e1eb6430e028e1b302c8b
|
refs/heads/master
| 2020-03-28T22:46:44.606988
| 2017-03-27T18:05:57
| 2017-03-27T18:05:57
| 149,257,460
| 2
| 0
| null | 2018-09-18T08:52:10
| 2018-09-18T08:52:09
| null |
UTF-8
|
C++
| false
| false
| 2,264
|
h
|
/******************************************************************************\
*
* File: ImageClip.h
* Creation date: January 15, 2002 17:31
* Author: ClassBuilder
* XXXX
* Purpose: Declaration of class 'ImageClip'
*
* Modifications: @INSERT_MODIFICATIONS(* )
* January 23, 2002 10:59 Frederic O'Reilly
* Added method 'StartTime'
* Added method 'RepeatType'
* Added method 'RemoveImage'
* Added method 'Reference'
* Added method 'Rate'
* Added method 'NbImages'
* Added method 'Images'
* Added method 'EndTime'
* Added method 'AddImage'
* Added method 'CSLImageClip'
* Added member 'm_pImages'
* Added member 'm_pRepeatType'
* Added member 'm_pRate'
* Added member 'm_pEndTime'
* Added member 'm_pStartTime'
* Added member 'm_pReference'
* Updated inheritance 'CSLTemplate'
*
* Copyright 2002, XXXXX
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
*
\******************************************************************************/
#ifndef _IMAGECLIP_H
#define _IMAGECLIP_H
#include "Template.h"
// Forward declaration
class CSLTexture2D;
//! Class not implemented
class CSLImageClip
: public CSLTemplate
{
//@START_USER2
//@END_USER2
// Members
private:
CSLTexture2D* m_pReference;
CSLFloatProxy* m_pStartTime;
CSLFloatProxy* m_pEndTime;
CSLFloatProxy* m_pRate;
CSLIntProxy* m_pRepeatType;
CSIBCArray<CSLStringProxy *> m_pImages;
protected:
public:
// Methods
private:
protected:
public:
CSLImageClip(CSLScene* in_pScene, CSLModel *in_pModel, CdotXSITemplate* in_pTemplate);
virtual ~CSLImageClip();
CSLStringProxy* AddImage();
CSLFloatProxy* EndTime() const;
CSLStringProxy** Images() const;
SI_Int* NbImages() const;
CSLFloatProxy* Rate() const;
CSLTexture2D* Reference() const;
SI_Error RemoveImage();
CSLIntProxy* RepeatType() const;
CSLFloatProxy* StartTime() const;
};
#endif
#ifdef CB_INLINES
#ifndef _IMAGECLIP_H_INLINES
#define _IMAGECLIP_H_INLINES
//@START_USER3
//@END_USER3
#endif
#endif
|
[
"sean@csnxs.uk"
] |
sean@csnxs.uk
|
ae0ee55c88f9f7bb114f747551efb2eb165ab61d
|
9bdca347c1d0cb80edf4bdbd2e9a80ead6092af7
|
/downsampler.cpp
|
86c55271f3d67bb9578c626fb077ea99ec5971bf
|
[] |
no_license
|
batusai8889/libKeyFinder
|
4882fd1728b9076c8f84ca737db869b4483b6830
|
aa69a99bff0baae8cc75101b99b9042539230ffe
|
refs/heads/master
| 2020-12-24T20:43:34.788076
| 2013-01-21T14:59:13
| 2013-01-21T14:59:13
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,956
|
cpp
|
/*************************************************************************
Copyright 2011-2013 Ibrahim Sha'ath
This file is part of LibKeyFinder.
LibKeyFinder is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
LibKeyFinder is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with LibKeyFinder. If not, see <http://www.gnu.org/licenses/>.
*************************************************************************/
#include "downsampler.h"
namespace KeyFinder{
void Downsampler::downsample(AudioData*& audioIn, const float& lastFreq, LowPassFilterFactory* lpfFactory) const{
// TODO: there is presumably some good maths to determine filter frequencies
float midCutoff = lastFreq * 1.05;
float endCutoff = lastFreq * 1.10;
unsigned int downsampleFactor = (int)floor( audioIn->getFrameRate() / 2 / endCutoff );
if (downsampleFactor == 1) return;
// prep output buffer
AudioData* audioOut = new AudioData();
audioOut->setFrameRate(audioIn->getFrameRate() / downsampleFactor);
audioOut->setChannels(audioIn->getChannels());
unsigned int c = audioIn->getChannels();
unsigned int ns = audioIn->getSampleCount() / downsampleFactor;
while(ns % c != 0)
ns++;
if (audioIn->getSampleCount() % downsampleFactor > 0)
ns += c;
try{
audioOut->addToSampleCount(ns);
}catch(const Exception& e){
throw e;
}
// prep filter
unsigned int filterOrder = 160;
unsigned int filterDelay = filterOrder/2;
// create circular buffer for filter delay
Binode<float>* p = new Binode<float>(); // first node
Binode<float>* q = p;
for (unsigned int i=0; i<filterOrder; i++){
q->r = new Binode<float>(); // subsequent nodes
q->r->l = q;
q = q->r;
}
// join first and last nodes
p->l = q;
q->r = p;
// get filter
LowPassFilter* lpf = lpfFactory->getLowPassFilter(filterOrder + 1, audioIn->getFrameRate(), midCutoff, 2048);
// for each channel (should be mono by this point but just in case)
for (unsigned int i = 0; i < c; i++){
q = p;
// clear delay buffer
for (unsigned int k = 0; k <= filterOrder; k++){
q->data = 0.0;
q = q->r;
}
// for each frame (running off the end of the sample stream by filterDelay)
for (int j = i; j < (signed)(audioIn->getSampleCount() + filterDelay); j += c){
// shuffle old samples along delay buffer
p = p->r;
// load new sample into delay buffer
if (j < (signed)audioIn->getSampleCount())
p->l->data = audioIn->getSample(j) / lpf->gain;
else
p->l->data = 0.0; // zero pad once we're into the delay at the end of the file
if ((j % (downsampleFactor * c)) < c){ // only do the maths for the useful samples
float sum = 0.0;
q = p;
for (unsigned int k = 0; k <= filterOrder; k++){
sum += lpf->coefficients[k] * q->data;
q = q->r;
}
// don't try and set samples during the warm-up, only once we've passed filterDelay samples
if (j - (signed)filterDelay >= 0){
audioOut->setSample(((j-filterDelay) / downsampleFactor) + i, sum);
}
}
}
}
// delete delay buffer
for (unsigned int k = 0; k <= filterOrder; k++){
q = p;
p = p->r;
delete q;
}
// note we don't delete the LPF; it's stored in the factory for reuse
delete audioIn;
audioIn = audioOut;
}
}
|
[
"ibrahimshaath@gmail.com"
] |
ibrahimshaath@gmail.com
|
a8bb16fc643df27ecdaba1edf6a6c40a9139881a
|
36184239a2d964ed5f587ad8e83f66355edb17aa
|
/.history/hw3/ElectoralMap_20211021113257.cpp
|
3ead4b3ddbfd0b40571f3b8741ac883c095cec1d
|
[] |
no_license
|
xich4932/csci3010
|
89c342dc445f5ec15ac7885cd7b7c26a225dae3e
|
23f0124a99c4e8e44a28ff31ededc42d9f326ccc
|
refs/heads/master
| 2023-08-24T04:03:12.748713
| 2021-10-22T08:22:58
| 2021-10-22T08:22:58
| 415,140,207
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 17,573
|
cpp
|
#include<iostream>
#include<map>
#include<set>
#include<random>
#include<time.h>
#include<cmath>
#include<stdlib.h>
#include"ElectoralMap.h"
#define num_district 3
#define num_enum 4
#define one_person 1
//int Candidate::id = 0;
int ElectoralMap::count_district = 0;
int Election::ids = 0;
std::vector<int> Election::party_one_active = {};
std::vector<int> Election::party_two_active = {};
std::vector<int> Election::party_three_active = {};
//std::vector<int> Election::stored_idx_each;
int Candidate::party_one_candidate = 0;
int Candidate::party_two_candidate = 0;
int Candidate::party_three_candidate = 0;
int Election::active_party[3] = {0};
Candidate::Candidate(){
;
}
void Candidate::plus_vote(District dis, int count){
votes[dis] += count;
}
Candidate::Candidate(int given_id, party party_name, std::string candidate_name){
id_candidate = given_id;
party_affiliation = party_name;
name = candidate_name;
std::map<int, District> temp_map = ElectoralMap::getInstance().get_map();
for(auto i = temp_map.begin(); i != temp_map.end(); i++){
votes.insert(std::pair<District, int>(i->second, 0));
}
}
int Candidate::get_ids(){
return id_candidate;
}
District::District(){
for(enum party temp = party::one; temp <= party::none ; temp = (party)(temp + 1)){
map_party.insert(std::pair<party,int>(temp, 0));
//map_party.insert(std::pair<party,int>(temp, range_random(engine)));
}
//std::uniform_int_distribution<unsigned> range_random1(5,29);
square_mile = 99;
id = 99;
}
District::District(int given_id){
// std::default_random_engine engine;
// std::uniform_int_distribution<unsigned> range_random(0,9);
for(enum party temp = party::one; temp <= party::none ; temp = (party)(temp + 1)){
map_party.insert(std::pair<party,int>(temp, rand()%9));
//map_party.insert(std::pair<party,int>(temp, range_random(engine)));
}
// std::uniform_int_distribution<unsigned> range_random1(5,29);
square_mile = rand()%25+5;
id = given_id;
}
party District::get_max(){
enum party ret;
int max = 0;
int old_ = max;
for(auto i = map_party.begin(); i != map_party.end(); i++){
max = std::max(max, i->second);
if(old_ != max){
old_ = max;
ret = i->first;
}
}
return ret;
}
int District::get_sum_constitutent(){
int sum = 0;
for(enum party temp = party::one; temp <= party::none; temp = (party)(temp + 1)){
sum += map_party[temp];
}
return sum;
}
int District::get_sum_constitutent_exclude_none(party exclude_one){
int sum = 0;
for(enum party temp = party::one; temp < party::none; temp = (party)(temp + 1)){
if(map_party[temp] == exclude_one) continue;
// std::cout << temp <<" ";
sum += map_party[temp];
}
std::cout << "sum:" << sum << std::endl;
return sum;
}
void District::change_party(party increase_party, party decrease_party, int num){
//debug: assume changing number is always smaller than the actual number
if(num > map_party[decrease_party]){
map_party[increase_party] += map_party[decrease_party];
map_party[decrease_party] = 0;
}else{
map_party[increase_party] += num;
map_party[decrease_party] -= num;
}
};
ElectoralMap::ElectoralMap(){
for(int i = 0; i < num_district; i++){
District *temp = new District(count_district+1);
map.insert(std::pair<int, District>(count_district+1, *temp));
count_district ++;
}
}
std::string stringifyEnum(party one){
const std::string str[4] = {"party one", "party two", "party three", "party none"};
for(enum party temp = party::one; temp <= party::none; temp = (party)(temp+1)){
if(temp == one) return str[(int)temp];
}
return "";
}
std::ostream & operator<<(std::ostream& os, District print_district){
std::cout << "district: "<< print_district.id <<":"<< std::endl;
std::cout << "area: "<< print_district.square_mile << std::endl;
for(enum party print_enum = party::one; print_enum <= party::none; print_enum = (party)(print_enum+1)){
std::cout << stringifyEnum(print_enum) <<": "<< print_district.map_party[print_enum] <<" ";
}
std::cout << std::endl;
return os;
}
std::ostream & operator<<(std::ostream& os, ElectoralMap print_map){
for(auto i = print_map.map.begin(); i != print_map.map.end(); i++){
std::cout << i->second << std::endl;
}
return os;
}
void ask_name(std::string &name){
std::cout << "What is their name?"<<std::endl;
getline(std::cin, name);
}
Election::Election(){
std::string choice;
for(enum party party_name = party::one; party_name < party::none; party_name = (party)(party_name+1)){
while(1){
std::cout <<"Do you want to register a candidate for "<< stringifyEnum(party_name) <<" (y or n)?"<<std::endl;
getline(std::cin, choice);
if(choice == "y"){
std::string candidate_name;
ask_name(candidate_name);
Candidate temp(ids+1, party_name, candidate_name);
candidate_.insert(std::pair<int, Candidate>(ids + 1, temp));
ids ++;
if(party_name == 0){
party_one_active.push_back(ids);
}else if(party_name == 1){
party_two_active.push_back(ids);
}else if(party_name == 2){
party_three_active.push_back(ids);
}
active_party[party_name] ++;
continue;
}
if(choice == "n") break;
//continue; //when user input other choice, keep asking
}
}
}
/* void Election::register_candidate(){
std::string choice;
for(enum party party_name; party_name <= party::none; party_name = (party)(party_name+1)){
while(1){
std::cout <<"Do you want to register a candidate for "<< stringifyEnum(party_name) <<" (y or n)?"<<std::endl;
getline(std::cin, choice);
if(choice == "y"){
std::string candidate_name;
ask_name(candidate_name);
Candidate temp(ids+1, party_name, candidate_name);
candidate_.push_back(temp);
ids ++;
if(party_name == 0){
party_one_active.push_back(ids);
}else if(party_name == 1){
party_two_active.push_back(ids);
}else if(party_name == 2){
party_three_active.push_back(ids);
}
active_party[party_name] ++;
continue;
}
if(choice == "n") break;
//continue; //when user input other choice, keep asking
}
}
} */
Candidate* Election::who_campaigning(){
std::string choice;
while ((1))
{
std::cout << "Which candidate is campaigning (id) (0 to stop) ?" <<std::endl;
getline(std::cin, choice);
if(choice == "0") return NULL;
if(std::stoi(choice) >= ids){
std::cout << "index out of range"<< std::endl;
continue;
}
break; //jump out of loop if id is availble
}
return &candidate_[std::stoi(choice)];
//int campaign_id = stoi(choice);
//std::cout << ElectoralMap::getInstance << std::endl;
//
//int campaign_district = stoi(choice);
//std::cout << candidate_[campaign_id].get_name() << " is campaigning in district "<< campaign_district << std::endl;
}
//return -1, select to quie
int Election::where_campaigning(){
std::string choice;
while ((1))
{
std::cout << "Where is this candidate campaigning (id) (0 to stop) ?" <<std::endl;
getline(std::cin, choice);
if(choice == "0") return -1;
if(std::stoi(choice) >= num_district){
std::cout << "index out of range"<< std::endl;
continue;
}
break; //jump out of loop if id is availble
}
return std::stoi(choice);
}
Candidate Election::get_candidate(int id){
return candidate_[id];
}
void Election::voting(){
std::map<party, int> sum_each_party;
sum_each_party.insert(std::pair<party, int> (party::one, 0));
sum_each_party.insert(std::pair<party, int> (party::two, 0));
sum_each_party.insert(std::pair<party, int> (party::three,0));
std::vector<std::vector<int>> store_id_each = {party_one_active, party_two_active, party_three_active};
ElectoralMap vote_map = ElectoralMap::getInstance();
std::map<int, District> vote_district = ElectoralMap::getInstance().get_map();
int turn_candidate = 0;
for(int d = 1; d <= num_district; d++){
for(enum party party_name = party::one; party_name <= party::none; party_name = (party)(party_name+1)){
if(active_party[party_name]){
int get_voted = rand()%store_id_each[party_name].size();
candidate_[party_one_active[get_voted]].plus_vote(vote_district[d] , vote_district[d+1].get_constituent(party_name));
//sum_each_party[party_name] += vote_district[d].get_constituent(party_name);
}else if(party_name == party::none){
party none_cantitutent = vote_district[d+1].get_max();
//if none constitutent is 9, should i count them as one or do random choice for each person
if(party_name == party::none){ //the majority constituent is still none
;
}else if(!active_party[none_cantitutent] || (!active_party[party_name] && party_name != party::none)){ // when the majority constituent has no candidate
int sum = 0;
for(int i = 0; i < 3; i++) sum += active_party[i];
int get_voted = rand()%sum;
candidate_[get_voted].plus_vote(vote_district[d] , vote_district[d+1].get_constituent(party_name));
}
}else{
int sum = 0;
for(int i = 0; i < 3; i++) sum += active_party[i];
int get_voted = rand()%sum;
candidate_[get_voted].plus_vote(vote_district[d] , vote_district[d+1].get_constituent(party_name));
}
}
}
}
void District::convert_constituent(party increase_party, party decrease_party, int num){
//if no people in the party, do nothing
if(!map_party[decrease_party]) return;
map_party[increase_party] += num;
map_party[decrease_party] -= num;
}
party randomlyPickEnum(){
int i = rand() % 3;
if(i == 0) return party::one;
if(i == 1) return party::two;
if(i == 2) return party::three;
}
void Election::converting(District * campaign_district, Candidate * this_candidate){
int sum_constituent = campaign_district->get_constituent(this_candidate->get_party());
int sum_residents = campaign_district->get_sum_constitutent_exclude_none(this_candidate->get_party());
double possibility = ((sum_constituent+1)*2/sum_residents)*((sum_constituent+1)*2/campaign_district->get_square_mile());
std::cout <<"area: "<< campaign_district->get_square_mile() << std::endl;
std::cout <<"sum_constituent: "<< sum_constituent << std::endl;
std::cout <<"poss:"<< possibility << std::endl;
double p_success = std::min(100.00,possibility );
double p_extra_success = 0.1 * p_success;
int this_rand = rand()%100;
std::cout << "Chances to convert: " << p_success << std::endl;
std::cout << "Chances to convert from another party: "<< p_extra_success << std::endl;
//convert only people in party none
int convert_one = 0;
if(campaign_district->get_constituent(party::none) > 0){
if(p_success > this_rand){
convert_one ++;
campaign_district->convert_constituent(this_candidate->get_party(), party::none, one_person);
}
}
if(p_extra_success > this_rand){
enum party converted = randomlyPickEnum();
while(converted == this_candidate->get_party()){
converted = randomlyPickEnum();
}
campaign_district->convert_constituent(this_candidate->get_party(), converted, one_person);
convert_one++;
}
std::cout << "Congrats, you have converted someone from none to one!" << std::endl;
}
void RepresentativeELection::calculate_vote(){
std::map<int ,District> this_district = ElectoralMap::getInstance().get_map();
int sum_all_constituent = 0;
for(auto i = this_district.begin(); i != this_district.end(); i++){
sum_all_constituent += i->second.get_sum_constitutent();
}
int total_district = this_district.size();
for(auto i = this_district.begin(); i != this_district.end(); i++){
vote_per_district.push_back(std::floor(i->second.get_sum_constitutent() * 1.0 / sum_all_constituent * total_district));
}
}
RepresentativeELection::RepresentativeELection(){
std::string choice;
for(enum party party_name = party::one; party_name <= party::none; party_name = (party)(party_name+1)){
while(1){
std::cout <<"Do you want to register a candidate for "<< stringifyEnum(party_name) <<" (y or n)?"<<std::endl;
getline(std::cin, choice);
if(choice == "y"){
std::string candidate_name;
ask_name(candidate_name);
Candidate temp(ids+1, party_name, candidate_name);
candidate_.insert(std::pair<int, Candidate>(ids + 1, temp));
ids ++;
if(party_name == 0){
party_one_active.push_back(ids);
}else if(party_name == 1){
party_two_active.push_back(ids);
}else if(party_name == 2){
party_three_active.push_back(ids);
}
active_party[party_name] ++;
continue;
}
if(choice == "n") break;
//continue; //when user input other choice, keep asking
}
}
//register_candidate();
}
bool Election::check_end(){
return false;
/* if(!condition) return true;
return false; */
}
void Election::report_win(){
//int sum_votes[num_enum - 1] = { 0, 0, 0};
std::map<int, District> print_map = ElectoralMap::getInstance().get_map();
for(auto i = print_map.begin(); i != print_map.end(); i++){
std::cout << "Distrcit"<< i->second.get_id() << std::endl;
for(int c = 1; c <= ids; c++){
// std::cout << candidate_[c+1].get_vote().get_party(*i) << std::endl;
}
}
/* std::map<int, Candidate> find_max;
for(auto i = candidate_.begin(); i != candidate_.end(); i++){
find_max.insert(std::pair<int, Candidate>(i->get_vote(), *i));
} */
std::cout << "Congratulations, "<< candidate_.rbegin()->second.get_name() <<", you've won!"<<std::endl;
}
int party_to_int(enum party temp){
if(temp == party::one) return 0;
if(temp == party::two) return 1;
if(temp == party::three) return 2;
return 3; //not gonna happen
}
party District::get_max_party(){
enum party max = party::one;
int max_num = map_party[max];
for(enum party temp = party::one; temp <= party::none; temp = (party)(temp+1)){
if(map_party[temp] > max_num){
max_num = map_party[temp];
max = temp;
}
}
return max;
}
void RepresentativeELection::voting(){
std::map<party, int> sum_each_party;
sum_each_party.insert(std::pair<party, int> (party::one, 0));
sum_each_party.insert(std::pair<party, int> (party::two, 0));
sum_each_party.insert(std::pair<party, int> (party::three,0));
std::vector<std::vector<int>> store_id_each = {party_one_active, party_two_active, party_three_active};
// ElectoralMap vote_map = ElectoralMap::getInstance();
std::map<int, District> vote_district = ElectoralMap::getInstance().get_map();
calculate_vote();
for(int d = 1; d <= num_district; d++){
for(enum party party_name = party::one; party_name <= party::none; party_name = (party)(party_name+1)){
if(active_party[party_name]){
int get_voted = rand()%store_id_each[party_name].size();
candidate_[party_one_active[get_voted]].plus_vote(vote_district[d], vote_per_district[d]);
//sum_each_party[party_name] += vote_district[d].get_constituent(party_name);
}else if(party_name == party::none){
party none_cantitutent = vote_district[d+1].get_max();
//if none constitutent is 9, should i count them as one or do random choice for each person
if(party_name == party::none){ //the majority constituent is still none
;
}else if(!active_party[none_cantitutent] || (!active_party[party_name] && party_name != party::none)){ // when the majority constituent has no candidate
int sum = 0;
for(int i = 0; i < 3; i++) sum += active_party[i];
int get_voted = rand()%sum;
candidate_[get_voted].plus_vote(vote_district[d], vote_per_district[d]);
}
}else{
int sum = 0;
for(int i = 0; i < 3; i++) sum += active_party[i];
int get_voted = rand()%sum;
candidate_[get_voted].plus_vote(vote_district[d], vote_per_district[d]);
}
}
}
}
|
[
"70279863+xich4932@users.noreply.github.com"
] |
70279863+xich4932@users.noreply.github.com
|
61c05eec42492fe666a2c07e94c2f8d66609d535
|
d2bd315e9f5ad3c4bf5894c1bfe3c8357042ad7f
|
/게임자료구조/5주차과제/CircularQueue.cpp
|
59c205166f2374ede43b552c685679afeaf2e71a
|
[] |
no_license
|
bluebluerabbit/School_3.1
|
6007939717aa67ad58eadff88cf9532dc6867cb8
|
a36f9b6d21eff95a226f58344c11884e3863ca23
|
refs/heads/main
| 2023-08-04T05:16:30.811280
| 2021-09-23T06:37:58
| 2021-09-23T06:37:58
| null | 0
| 0
| null | null | null | null |
UHC
|
C++
| false
| false
| 1,484
|
cpp
|
///*
// File Name: SimpleQueue.h
// Author: Geun-Hyung Kim
//
// Description:
// 정수형 배열로 구성된 Queue 클래스 기능 구형 프로그램
//
// Date: 2021. 3. 24
// Version: 0.1.0
//*/
//
//#include <iostream>
//#include "CircularQueue.h"
//
//bool CircularQueue::full() {
// return ((rear + 1) % length) == front;
//}
//
//bool CircularQueue::empty() {
// return rear == front;
//}
//
//void CircularQueue::enQueue(int data) {
// if (!full()) {
// rear = (rear + 1) % length;
// dataArray[rear] = data;
// size++;
// }
// else {
// throw "CircularQueue is full!!";
// }
//}
//
//int CircularQueue::deQueue() {
// if (!empty()) {
// size--;
// return dataArray[front = (front + 1) % length];
// }
// else {
// throw "CircularQueue is empty!!";
// }
//}
//
//int CircularQueue::Front() {
// return front;
//}
//
//int CircularQueue::Back() {
// return rear;
//}
//
//ostream& operator<<(ostream& os, const CircularQueue& q) {
//
// os << "======================" << endl
// << "data : [ ";
//
// if (q.front > q.rear ) {
// for (int i = q.front + 1; i < q.length; i++) {
// os << q.dataArray[i] << ", ";
// }
// for (int i = 0; i <= q.rear; i++) {
// os << q.dataArray[i];
// if (i != q.rear) os << ", ";
// }
// }
// else {
// for (int i = q.front + 1; i <= q.rear; i++) {
// os << q.dataArray[i];
// if (i != q.rear) os << ", ";
// }
// }
//
//
// os << " ]" << endl
// << "======================" << "\n\n";
//
// return os;
//}
|
[
"jinjoo021@naver.com"
] |
jinjoo021@naver.com
|
3d123ac5a89cbca6d50abbc06a65c9bdfd1b3453
|
ac3281345cb13c00e0150b4cfde5a6fffa3d0e0b
|
/src/Magnum/Vk/Test/LayerPropertiesVkTest.cpp
|
5b94d376e7abeaedb3b08620270cb41f4b92d2aa
|
[
"MIT"
] |
permissive
|
mosra/magnum
|
dc2fc08d634dceaf454c0b8190d2ebd530bb8fa9
|
c9a2752545aa2aa8b7db4879834d3998c6cac655
|
refs/heads/master
| 2023-09-03T21:02:39.001932
| 2023-09-03T13:49:25
| 2023-09-03T16:07:04
| 1,182,756
| 4,747
| 535
|
NOASSERTION
| 2023-07-23T07:36:34
| 2010-12-19T22:19:59
|
C++
|
UTF-8
|
C++
| false
| false
| 5,439
|
cpp
|
/*
This file is part of Magnum.
Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019,
2020, 2021, 2022, 2023 Vladimír Vondruš <mosra@centrum.cz>
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 <sstream>
#include <Corrade/Containers/String.h>
#include <Corrade/TestSuite/Tester.h>
#include <Corrade/TestSuite/Compare/Numeric.h>
#include <Corrade/Utility/DebugStl.h>
#include <Corrade/Utility/FormatStl.h>
#include "Magnum/Vk/LayerProperties.h"
#include "Magnum/Vk/Version.h"
namespace Magnum { namespace Vk { namespace Test { namespace {
struct LayerPropertiesVkTest: TestSuite::Tester {
explicit LayerPropertiesVkTest();
void constructMove();
void enumerate();
void outOfRange();
void isSupported();
};
LayerPropertiesVkTest::LayerPropertiesVkTest() {
addTests({&LayerPropertiesVkTest::constructMove,
&LayerPropertiesVkTest::enumerate,
&LayerPropertiesVkTest::outOfRange,
&LayerPropertiesVkTest::isSupported});
}
using namespace Containers::Literals;
void LayerPropertiesVkTest::constructMove() {
LayerProperties a = enumerateLayerProperties();
const UnsignedInt count = a.count();
if(!count) CORRADE_SKIP("No extensions reported, can't test");
LayerProperties b = std::move(a);
CORRADE_COMPARE(b.count(), count);
LayerProperties c{NoCreate};
c = std::move(b);
CORRADE_COMPARE(c.count(), count);
CORRADE_VERIFY(std::is_nothrow_move_constructible<LayerProperties>::value);
CORRADE_VERIFY(std::is_nothrow_move_assignable<LayerProperties>::value);
}
void LayerPropertiesVkTest::enumerate() {
LayerProperties properties = enumerateLayerProperties();
if(!properties.count())
CORRADE_SKIP("The driver reported no instance layers, can't test.");
CORRADE_COMPARE(properties.count(), properties.names().size());
Debug{} << "Available instance layers:" << properties.names();
Containers::ArrayView<const Containers::StringView> names = properties.names();
CORRADE_COMPARE_AS(names.size(), 0, TestSuite::Compare::Greater);
/* The list should be sorted */
for(std::size_t i = 1; i != names.size(); ++i) {
CORRADE_COMPARE_AS(names[i - 1], names[i],
TestSuite::Compare::Less);
}
/* MoltenVK Y U so weird!! */
if(properties.name(0) != "MoltenVK"_s)
CORRADE_COMPARE_AS(properties.name(0).size(), "VK_LAYER_"_s.size(),
TestSuite::Compare::Greater);
CORRADE_COMPARE_AS(properties.revision(0), 0,
TestSuite::Compare::Greater);
CORRADE_COMPARE_AS(properties.version(0), Version::Vk10,
TestSuite::Compare::GreaterOrEqual);
CORRADE_COMPARE_AS(properties.description(0).size(), 10,
TestSuite::Compare::Greater);
}
void LayerPropertiesVkTest::outOfRange() {
CORRADE_SKIP_IF_NO_ASSERT();
LayerProperties properties = enumerateLayerProperties();
const UnsignedInt count = properties.count();
std::ostringstream out;
Error redirectError{&out};
properties.name(count);
properties.revision(count);
properties.version(count);
properties.description(count);
CORRADE_COMPARE(out.str(), Utility::formatString(
"Vk::LayerProperties::name(): index {0} out of range for {0} entries\n"
"Vk::LayerProperties::revision(): index {0} out of range for {0} entries\n"
"Vk::LayerProperties::version(): index {0} out of range for {0} entries\n"
"Vk::LayerProperties::description(): index {0} out of range for {0} entries\n", count));
}
void LayerPropertiesVkTest::isSupported() {
LayerProperties properties = enumerateLayerProperties();
CORRADE_VERIFY(!properties.isSupported("this layer doesn't exist"));
/* Verify that we don't dereference garbage when std::lower_bound() returns
`last` */
CORRADE_VERIFY(!properties.isSupported("ZZZZZ"));
if(!properties.count())
CORRADE_SKIP("The driver reported no instance layers, can't fully test.");
for(UnsignedInt i = 0; i != properties.count(); ++i) {
CORRADE_ITERATION(properties.name(i));
CORRADE_VERIFY(properties.isSupported(properties.name(i)));
}
/* Verify that we're not just comparing a prefix */
CORRADE_VERIFY(!properties.isSupported(properties.name(0) + "_hello"_s));
}
}}}}
CORRADE_TEST_MAIN(Magnum::Vk::Test::LayerPropertiesVkTest)
|
[
"mosra@centrum.cz"
] |
mosra@centrum.cz
|
023940c1cbe30e9b04fd7346803fb68d80f9b3f3
|
330f81dc5de92d7040f259b36e1182e9093c6c38
|
/Algorithms/BitManupulaiton/findSquare.cpp
|
737b59fe84ec9286ac0c063fe90e8de6e7aff433
|
[] |
no_license
|
Ujwalgulhane/Data-Structure-Algorithm
|
75f0bdd9a20de2abf567ee1f909aa91e3c2f5cfc
|
e5f8db3a313b3f634c002ec975e0b53029e82d90
|
refs/heads/master
| 2023-08-25T02:36:57.045798
| 2021-10-26T07:13:58
| 2021-10-26T07:13:58
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,259
|
cpp
|
#include"bits/stdc++.h"
using namespace std;
#define fo(i, n) for (i = 0; i < n; i++)
#define Fo(i, k, n) for (i = k; k < n ? i < n : i > n; k < n ? i += 1 : i -= 1)
#define ll long long
#define si(x) scanf("%d", & x)
#define sl(x) scanf("%lld", & x)
#define ss(s) scanf("%s", s)
#define pi(x) printf("%d\n", x)
#define pl(x) printf("%lld\n", x)
#define ps(s) printf("%s\n", s)
#define deb(x) cout << #x << "=" << x << endl
#define deb2(x, y) cout << #x << "=" << x << "," << #y << "=" << y << endl
#define all(x) x.begin(), x.end()
#define sortall(x) sort(all(x))
#define tr(it, a) for (auto it = a.begin(); it != a.end(); it++)
#define PI 3.1415926535897932384626
typedef vector < int > vi;
typedef vector <string> vs;
const int mod = 1'000'000'007;
int findSquare(int i){
int a=0,b=i>>1;
if(!i) return i;
if(i&1){
return ((findSquare(b)<<2)+(b<<2)+1);
}else{
return (findSquare(b)<<2);
}
}
void solve() {
int i, j, n, m;
cin>>i;
pi((0<<2)<<2);
// pi(findSquare(i));
}
int main() {
// #ifndef ONLINE_JUDGE
// freopen("inp.txt","r",stdin);
// freopen("out.txt","w",stdout);
// #endif
ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
int t = 1;
cin >> t;
while (t--) {
solve();
}
return 0;
}
|
[
"siddhant.sarkar999@gmail.com"
] |
siddhant.sarkar999@gmail.com
|
2244ff875c22f13b18688ece98860d48c051bcb1
|
bd1fea86d862456a2ec9f56d57f8948456d55ee6
|
/000/110/147/CWE675_Duplicate_Operations_on_Resource__fopen_82_bad.cpp
|
68424b9b7c62585e81a6b95617330a775c96e1e8
|
[] |
no_license
|
CU-0xff/juliet-cpp
|
d62b8485104d8a9160f29213368324c946f38274
|
d8586a217bc94cbcfeeec5d39b12d02e9c6045a2
|
refs/heads/master
| 2021-03-07T15:44:19.446957
| 2020-03-10T12:45:40
| 2020-03-10T12:45:40
| 246,275,244
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 964
|
cpp
|
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE675_Duplicate_Operations_on_Resource__fopen_82_bad.cpp
Label Definition File: CWE675_Duplicate_Operations_on_Resource.label.xml
Template File: sources-sinks-82_bad.tmpl.cpp
*/
/*
* @description
* CWE: 675 Duplicate Operations on Resource
* BadSource: fopen Open and close a file using fopen() and flose()
* GoodSource: Open a file using fopen()
* Sinks:
* GoodSink: Do nothing
* BadSink : Close the file
* Flow Variant: 82 Data flow: data passed in a parameter to an virtual method called via a pointer
*
* */
#ifndef OMITBAD
#include "std_testcase.h"
#include "CWE675_Duplicate_Operations_on_Resource__fopen_82.h"
namespace CWE675_Duplicate_Operations_on_Resource__fopen_82
{
void CWE675_Duplicate_Operations_on_Resource__fopen_82_bad::action(FILE * data)
{
/* POTENTIAL FLAW: Close the file in the sink (it may have been closed in the Source) */
fclose(data);
}
}
#endif /* OMITBAD */
|
[
"frank@fischer.com.mt"
] |
frank@fischer.com.mt
|
eb83b04698e9703c3de774fae5fb9392f438f4da
|
b73b6ba6b34afcd76efd02ca413cd01c7f75b33f
|
/cpp/boj1309.cpp
|
2547eadd151e091250ac2719df927f30c0f97366
|
[] |
no_license
|
kim-seoyoung/basicprogramming
|
45b44f926eb8b901b27cb919dac7f1f8d8db5281
|
c0eb970984dac9eba36718a65dec84c658a88ccd
|
refs/heads/master
| 2020-06-20T16:41:35.091565
| 2020-03-12T12:47:49
| 2020-03-12T12:47:49
| 197,181,596
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 524
|
cpp
|
#include <iostream>
using namespace std;
int cases[100002][3]={{0,0,0},{1,1,1}};
int N;
void dp(const int n){
if (n == N+2) return;
cases[n][0] = (cases[n - 1][0] + cases[n - 1][1] + cases[n - 1][2]) %9901;
cases[n][1] = (cases[n - 1][0] + cases[n - 1][2])%9901;
cases[n][2] = (cases[n - 1][0] + cases[n - 1][1])%9901;
dp(n+1);
}
int main(){
cin >> N;
if(N < 2) cout << cases[N][0]+cases[N][1]+cases[N][2];
else {
dp(2);
cout << cases[N+1][0];
}
return 0;
}
|
[
"bestseo02@naver.com"
] |
bestseo02@naver.com
|
aa7023a5b51c1f9dede6eac16d6f2b343b9f3591
|
9c2583e2ecd85ed332e704c81295119d4bb7f9d8
|
/src/protocol.h
|
aa1b7c3141d5bfca271c31faaa1f34f9c74c8bb3
|
[
"MIT"
] |
permissive
|
bata-bta/BATA-Development
|
3a2735b515a6f939f80743f07323be8e1d58cbb0
|
8306a05d6d4440312241a09b8723fa4d38566606
|
refs/heads/master
| 2021-01-19T04:40:56.668743
| 2016-10-07T05:54:32
| 2016-10-07T05:54:32
| 87,386,130
| 0
| 1
| null | 2017-04-06T04:26:34
| 2017-04-06T04:26:34
| null |
UTF-8
|
C++
| false
| false
| 3,719
|
h
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef __cplusplus
# error This header can only be compiled as C++.
#endif
#ifndef __INCLUDED_PROTOCOL_H__
#define __INCLUDED_PROTOCOL_H__
#include "serialize.h"
#include "netbase.h"
#include <string>
#include "uint256.h"
extern bool fTestNet;
static inline unsigned short GetDefaultPort(const bool testnet = fTestNet)
{
return testnet ? 33813 : 5784;
}
extern unsigned char pchMessageStart[4];
/** Message header.
* (4) message start.
* (12) command.
* (4) size.
* (4) checksum.
*/
class CMessageHeader
{
public:
CMessageHeader();
CMessageHeader(const char* pszCommand, unsigned int nMessageSizeIn);
std::string GetCommand() const;
bool IsValid() const;
IMPLEMENT_SERIALIZE
(
READWRITE(FLATDATA(pchMessageStart));
READWRITE(FLATDATA(pchCommand));
READWRITE(nMessageSize);
READWRITE(nChecksum);
)
// TODO: make private (improves encapsulation)
public:
enum {
MESSAGE_START_SIZE=sizeof(::pchMessageStart),
COMMAND_SIZE=12,
MESSAGE_SIZE_SIZE=sizeof(int),
CHECKSUM_SIZE=sizeof(int),
MESSAGE_SIZE_OFFSET=MESSAGE_START_SIZE+COMMAND_SIZE,
CHECKSUM_OFFSET=MESSAGE_SIZE_OFFSET+MESSAGE_SIZE_SIZE,
HEADER_SIZE=MESSAGE_START_SIZE+COMMAND_SIZE+MESSAGE_SIZE_SIZE+CHECKSUM_SIZE
};
char pchMessageStart[MESSAGE_START_SIZE];
char pchCommand[COMMAND_SIZE];
unsigned int nMessageSize;
unsigned int nChecksum;
};
/** nServices flags */
enum
{
NODE_NETWORK = (1 << 0),
NODE_BLOOM = (1 << 1),
};
/** A CService with information about it as peer */
class CAddress : public CService
{
public:
CAddress();
explicit CAddress(CService ipIn, uint64 nServicesIn=NODE_NETWORK);
void Init();
IMPLEMENT_SERIALIZE
(
CAddress* pthis = const_cast<CAddress*>(this);
CService* pip = (CService*)pthis;
if (fRead)
pthis->Init();
if (nType & SER_DISK)
READWRITE(nVersion);
if ((nType & SER_DISK) ||
(nVersion >= CADDR_TIME_VERSION && !(nType & SER_GETHASH)))
READWRITE(nTime);
READWRITE(nServices);
READWRITE(*pip);
)
void print() const;
// TODO: make private (improves encapsulation)
public:
uint64 nServices;
// disk and network only
unsigned int nTime;
// memory only
int64 nLastTry;
};
/** inv message data */
class CInv
{
public:
CInv();
CInv(int typeIn, const uint256& hashIn);
CInv(const std::string& strType, const uint256& hashIn);
IMPLEMENT_SERIALIZE
(
READWRITE(type);
READWRITE(hash);
)
friend bool operator<(const CInv& a, const CInv& b);
bool IsKnownType() const;
const char* GetCommand() const;
std::string ToString() const;
void print() const;
// TODO: make private (improves encapsulation)
public:
int type;
uint256 hash;
};
enum
{
MSG_TX = 1,
MSG_BLOCK,
// Nodes may always request a MSG_FILTERED_BLOCK in a getdata, however,
// MSG_FILTERED_BLOCK should not appear in any invs except as a part of getdata.
MSG_FILTERED_BLOCK,
};
#endif // __INCLUDED_PROTOCOL_H__
|
[
"admin@bata.money"
] |
admin@bata.money
|
e2af2e9177fbaf3c51d8467e8f127935a0cb67d5
|
cf65368fe28c73525cb75ca64e1b954eb90f15d0
|
/test_rat.cpp
|
b2681d6dabbb151976f9447d04b37b62caab0c43
|
[] |
no_license
|
sj-simmons/math-tools-cpp
|
76f5feaab0576ca224f7a833eb0c9d8cb073ac07
|
a7127b2520ffbf82abfdf6dd10eed615b9e2786e
|
refs/heads/master
| 2021-07-22T19:49:10.863217
| 2018-05-19T20:51:14
| 2021-07-15T23:17:23
| 133,449,957
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,814
|
cpp
|
//test_rat.cpp
#include <iostream>
#include <cmath>
#include "Rational.h"
#include "gmpxx.h"
using namespace std;
int main() {
cout << "Testing gcd: ";
mpz_class m, n;
m="-123123124124";
n="13214";
cout << " checking modulo " << m % n << endl;
cout << " checking gcd " << gcd(m, n) << endl;
Rational<int> rrrr(3);
cout << " checking coersion " << rrrr << endl;
using coeff_type = mpz_class;
//using coeff_type = long long;
cout << "testing default constructor" << endl;
Rational<coeff_type> rrr;
cout << " it constructs: "<< rrr << endl << endl;
cout << "testing arrays of rationals " << endl;
Rational<coeff_type> arr[5] = { {1,2},{5,6} };
for (int i = 0; i != 5; ++i) {
cout << arr[i] << " ";
}
cout << "\n" << endl;
Rational<int> r1(2,-3);
Rational<int> r2(2,4);
cout << "r1 " << r1 << " r2 " << r2 << endl;
r1 += r2;
cout << "r1 += r2"<< r1 << endl;
cout << r1 << " + " << r2 << " = " << r1+r2 << endl;
cout << r1 << " * " << r2 << " = " << r1*r2 << endl;
cout << r1 << " - " << r2 << " = " << r1-r2 << endl;
cout << r1 << " / " << r2 << " = " << r1/r2 << endl;
//Rational<int> r3(3,1);
Rational<int> r3;
cout << "Rational(3,1) num=" << r3.num() << " den= " << r3.den() << " get " << r3 << endl;
cout << -r3 << endl;
Rational<int> r4(0,1);
cout << "Rational(0,1) num=" << r4.num() << " den= " << r4.den() << " get " << r4 << endl;
Rational<int> r5(0,-1);
cout << "Rational(0,-1) num=" << r5.num() << " den= " << r5.den() << " get " << r5 << endl;
int a, b;
cout << "Enter numbers or q: ";
cin >> a >> b ;
Rational<int> r6(a,b);
cout << r6 << endl;
r6.set(1,2);
cout << r6 << endl;
cout << (r6 != 0) << endl;
cout << r5 << " " << (r5 != 0) << endl;
cout << Rational<int>(17,1)*r2 << endl;
return 0;
}
|
[
"ssimmons1331@gmail.com"
] |
ssimmons1331@gmail.com
|
85891264a1d67419837e3eb5d19118c8408250d7
|
a61af411717f996efb3fbbafcf457c2152e45732
|
/expense_tracker/expense_tracker/Core/Services/TransactionService.h
|
1ea5cc8dcb835e47ff19863336fccf0849268194
|
[] |
no_license
|
mchesanovskyy/expense_tracker
|
340b22aca4cc3087ca7c62e61eb7ae75dac4c8b8
|
3a32be2fa7f56c0136109aa9d4b1bc722573cead
|
refs/heads/main
| 2023-07-03T19:44:43.928871
| 2021-08-05T08:53:54
| 2021-08-05T08:53:54
| 386,206,857
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 960
|
h
|
#pragma once
#include "../Interfaces/ITransactionService.h"
#include "../Interfaces/Repositories/ITransactionRepository.h"
class TransactionService : public ITransactionService
{
ITransactionRepository* _repository;
public:
TransactionService(ITransactionRepository& repository)
: _repository(&repository)
{
}
Transaction* Add(int userId, TransactionModelIn& model) override
{
const auto transaction = new Transaction;
transaction->Amount = model.IsProfit
? model.Amount
: model.Amount * -1;
transaction->Timestamp = model.Timestamp;
transaction->Title = model.Title;
transaction->UserId = userId;
const int createdTransId = _repository->Add(*transaction);
return _repository->GetById(createdTransId);
}
vector<Transaction*> GetUserTransactions(int userId) override
{
return _repository->GetUserTransactions(userId);
}
bool Delete(int transactionId) override
{
return _repository->Delete(transactionId);
}
};
|
[
"nick.chesanovskyy@gmail.com"
] |
nick.chesanovskyy@gmail.com
|
77179291b14ee647b8096466c790d48f39d1e708
|
48ddbc11cabea98a988f9de3fef7e4f6213e18c1
|
/diffuser_chain/basic_elements/vane_diffuser/system/fvSchemes.simpleFoam
|
8bbdffce6edbd45c0e054833d462afd0e6196944
|
[] |
no_license
|
lhooz/diffuser_2d
|
9ac08d009597f68dc8c22dac01121417ba22b889
|
f3e5ab69f3bbd035e2e4c6859a852de097aabfe8
|
refs/heads/main
| 2023-01-31T07:13:38.458461
| 2020-12-17T02:12:12
| 2020-12-17T02:12:12
| 312,403,813
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,693
|
simplefoam
|
/*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: v2006 |
| \\ / A nd | Website: www.openfoam.com |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class dictionary;
object fvSchemes;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
ddtSchemes
{
default steadyState;
//default Euler;
}
gradSchemes
{
default Gauss linear;
limited cellLimited Gauss linear 1;
grad(U) $limited;
grad(k) $limited;
grad(omega) $limited;
}
divSchemes
{
default none;
div(phi,U) bounded Gauss linearUpwind unlimited;
div(div(phi,U)) Gauss linear;
turbulence bounded Gauss linearUpwind limited;
div(phi,k) $turbulence;
div(phi,omega) $turbulence;
div(phi,epsilon) $turbulence;
div((nuEff*dev(T(grad(U))))) Gauss linear;
div((nuEff*dev2(T(grad(U))))) Gauss linear;
}
laplacianSchemes
{
default Gauss linear corrected;
}
interpolationSchemes
{
default linear;
}
snGradSchemes
{
default corrected;
}
wallDist
{
method meshWave;
}
// ************************************************************************* //
|
[
"hao.lee0019@gmail.com"
] |
hao.lee0019@gmail.com
|
e4cbec6cc2a0591b1fedbf5d9b4f10d75ad1dabf
|
5914f131402a16bde8c8f40faed58812e1f9f5a4
|
/n8Arduino/hw5n8o/n8hw5/n8hw5.ino
|
ba69d864c27b3b8d987822fb68b6fa69678527be
|
[] |
no_license
|
electronate/Homework5A2Bluetooth
|
e2540c3cdfbbff764aa22ce874380f39164c8145
|
d18c4da5fe7c7b1654f078b804c1bd9c863cad1f
|
refs/heads/master
| 2016-09-06T19:05:31.300698
| 2014-05-12T23:30:00
| 2014-05-12T23:30:00
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,379
|
ino
|
#include "foneastrapins.h"
#include <SoftwareSerial.h>
// Creates a SoftwareSerial so you can talk to the
SoftwareSerial swSerial(SW_UART_RX_PIN, SW_UART_TX_PIN); // RX, TX
void setup(void) {
//set up the HW UART to communicate with the BT module
Serial.begin(38400);
swSerial.begin(38400);
// Provide power to BT
pinMode(BT_PWR_PIN,OUTPUT);
digitalWrite(BT_PWR_PIN,HIGH);
// Turn on the red light
pinMode(RED_LED_PIN,OUTPUT);
digitalWrite(RED_LED_PIN, HIGH);
}
void printBattery(void) {
// Get the battery level from a builtin ADC
unsigned short battLvlADC = analogRead(BATT_LVL_PIN);
// Convert that ADC value to a rough estimation of volt
float battLvlVoltage = 0.0032 * battLvlADC;
float key;
// Print out the raw ADC value, and the voltage, followed by a Newline
Serial.print("raw batt lvl: ");
Serial.print(battLvlADC);
Serial.print(" voltage at BATT_LVL: ");
Serial.print(battLvlVoltage);
Serial.println();
// Do the same for the swSerial, connected to the PC
swSerial.print("raw batt lvl: ");
swSerial.print(battLvlADC);
swSerial.print(" voltage at BATT_LVL: ");
swSerial.print(battLvlVoltage);
swSerial.println();
if( Serial.available() > 0 ){
Serial.print("\n Serial Available! \n");
key = Serial.read();
swSerial.print(key);
Serial.print(key);
}
}
void buzzdot(void){
//buzz for a short time
tone( BUZZER_PIN, 500, 100 );
delay( 100 );
}
void buzzdash(void){
//buzz for a short time
tone( BUZZER_PIN, 500, 500 );
delay( 100 );
}
void morse(void){
//char myChar;
if(Serial.available() > 0){
//Citation: http://arduino.cc/en/Reference/sizeof
//Citation: http://arduino.cc/en/Reference/StreamRead
for(int i=0; i < /*sizeof(myChar)*/Serial.available(); i++){
char myChar = Serial.read();
swSerial.print(myChar);
Serial.print(myChar);
if(myChar == '.'){
buzzdot();
}else if(myChar == '-'){
buzzdash();
}else if(myChar == ' '){
delay(1200);
}else{
Serial.print(myChar);
Serial.print(" is unknown character, please use dot . or dash - only \n");
swSerial.print(myChar);
swSerial.print(" is unknown character, please use dot . or dash - only \n");
swSerial.println();
}
delay(600);
}
}
}
void loop(void) {
morse();
}
|
[
"nate.olds@gmail.com"
] |
nate.olds@gmail.com
|
324dd249195cf0ec1aae1613bf3216c1d1149625
|
d20876df1308f1eaf3c280f6d3dd78c47633a2d8
|
/src/Corrade/TestSuite/Compare/String.cpp
|
5288e9918a64a2bda42004fe33f5f48c88783d7e
|
[
"MIT",
"LicenseRef-scancode-public-domain",
"Unlicense"
] |
permissive
|
mosra/corrade
|
729ff71a9c8ceb7d27507b635be6433114b963bf
|
183b375b73fa3e819a6b41dbcc0cf2f06773d2b4
|
refs/heads/master
| 2023-08-24T21:56:12.599589
| 2023-08-23T14:07:19
| 2023-08-24T09:43:55
| 2,863,909
| 470
| 143
|
NOASSERTION
| 2023-09-12T02:52:28
| 2011-11-28T00:51:12
|
C++
|
UTF-8
|
C++
| false
| false
| 14,901
|
cpp
|
/*
This file is part of Corrade.
Copyright © 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016,
2017, 2018, 2019, 2020, 2021, 2022, 2023
Vladimír Vondruš <mosra@centrum.cz>
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 "String.h"
#include "Implementation/Diff.h"
namespace Corrade { namespace TestSuite {
ComparisonStatusFlags Comparator<Compare::String>::operator()(const Containers::StringView actual, const Containers::StringView expected) {
_actualValue = actual;
_expectedValue = expected;
return actual != expected ? ComparisonStatusFlag::Failed : ComparisonStatusFlags{};
}
void Comparator<Compare::String>::printMessage(const ComparisonStatusFlags flags, Utility::Debug& out, const char* const actual, const char* const expected) const {
#ifdef CORRADE_NO_ASSERT
static_cast<void>(flags);
#endif
CORRADE_INTERNAL_ASSERT(flags == ComparisonStatusFlag::Failed);
out << "Strings" << actual << "and" << expected << "are different."
<< Utility::Debug::color(Utility::Debug::Color::Green) << "Actual (+)"
<< Utility::Debug::resetColor << "vs"
<< Utility::Debug::color(Utility::Debug::Color::Red) << "expected (-)"
<< Utility::Debug::resetColor << Utility::Debug::nospace << ":";
/* Split into lines, pass that to the diff algorithm */
const Containers::Array<Containers::StringView> actualLines = _actualValue.split('\n');
const Containers::Array<Containers::StringView> expectedLines = _expectedValue.split('\n');
/* Calculate a set of longest matching slices */
Containers::Array<Containers::Triple<std::size_t, std::size_t, std::size_t>> slices;
Compare::Implementation::matchingSlicesInto(slices, stridedArrayView(actualLines), 0, stridedArrayView(expectedLines), 0);
/* Include an empty zero-length slice at the end in order to have the rest
after the last matching slice printed as well */
arrayAppend(slices, InPlaceInit, actualLines.size(), expectedLines.size(), std::size_t{});
/* Print everything */
std::size_t actualI = 0;
std::size_t expectedI = 0;
for(const Containers::Triple<std::size_t, std::size_t, std::size_t>& slice: slices) {
/* If there's exactly one differing line in both, print differences
inside that line */
if(slice.first() - actualI == 1 &&
slice.second() - expectedI == 1) {
const Containers::StringView actualLine = actualLines[actualI];
const Containers::StringView expectedLine = expectedLines[expectedI];
Containers::Array<Containers::Triple<std::size_t, std::size_t, std::size_t>> lineSlices;
Compare::Implementation::matchingSlicesInto(lineSlices, stridedArrayView(actualLine), 0, stridedArrayView(expectedLine), 0);
/* Count total matching bytes */
std::size_t totalMatchingBytes = 0;
for(const Containers::Triple<std::size_t, std::size_t, std::size_t>& i: lineSlices) {
/* If the slice cut is in the middle of a UTF-8 character,
abort the mission -- report there's nothing matching so it
doesn't attempt to put ANSI highlight in the middle of a
character as that'd break the output. */
/** @todo handle better (move the cut out of the character) */
if(actualLine[i.first()] & '\x80' ||
expectedLine[i.second()] & '\x80' ||
(i.third() && actualLine[i.first() + i.third() - 1] & '\x80') ||
(i.third() && expectedLine[i.second() + i.third() - 1] & '\x80'))
{
totalMatchingBytes = 0;
break;
}
totalMatchingBytes += i.third();
}
/* Highlight the difference only if there's at least 50% of the
shorter line same, otherwise it'd be just noise */
if(totalMatchingBytes >= Utility::min(actualLine.size(), expectedLine.size())/2) {
/* Include an empty zero-length slice at the end in order to
have the rest after the last matching slice printed as well */
arrayAppend(lineSlices, InPlaceInit, actualLine.size(), expectedLine.size(), std::size_t{});
/* First goes the expected (deleted) line */
out << Utility::Debug::newline << Utility::Debug::color(Utility::Debug::Color::Red) << " -";
std::size_t expectedLineI = 0;
for(const Containers::Triple<std::size_t, std::size_t, std::size_t>& lineSlice: lineSlices) {
out << Utility::Debug::nospace
/* Mark the deleted part with inverse red color */
#if !defined(CORRADE_TARGET_WINDOWS) || defined(CORRADE_UTILITY_USE_ANSI_COLORS)
<< Utility::Debug::invertedColor(Utility::Debug::Color::Red)
#endif
<< expectedLine.slice(expectedLineI, lineSlice.second())
<< Utility::Debug::nospace
/* And the matching part with normal red */
<< Utility::Debug::color(Utility::Debug::Color::Red)
<< expectedLine.sliceSize(lineSlice.second(), lineSlice.third())
<< Utility::Debug::resetColor;
expectedLineI = lineSlice.second() + lineSlice.third();
}
/* Then the actual (added) line */
out << Utility::Debug::newline << Utility::Debug::color(Utility::Debug::Color::Green) << " +";
std::size_t actualLineI = 0;
for(const Containers::Triple<std::size_t, std::size_t, std::size_t>& lineSlice: lineSlices) {
out << Utility::Debug::nospace
/* Mark the deleted part with inverse green color */
#if !defined(CORRADE_TARGET_WINDOWS) || defined(CORRADE_UTILITY_USE_ANSI_COLORS)
<< Utility::Debug::invertedColor(Utility::Debug::Color::Green)
#endif
<< actualLine.slice(actualLineI, lineSlice.first())
<< Utility::Debug::nospace
/* And the matching part with normal green */
<< Utility::Debug::color(Utility::Debug::Color::Green)
<< actualLine.sliceSize(lineSlice.first(), lineSlice.third())
<< Utility::Debug::resetColor;
actualLineI = lineSlice.first() + lineSlice.third();
}
/* Advancethe line iterators so the lines aren't printed again
below */
++actualI;
++expectedI;
}
}
/* All lines from `expected` after the previous matching slice and
before the current matching slice are marked as deleted */
for(const Containers::StringView& i: expectedLines.slice(expectedI, slice.second()))
out << Utility::Debug::newline << Utility::Debug::color(Utility::Debug::Color::Red) << " -" << Utility::Debug::nospace << i << Utility::Debug::resetColor;
/* All lines from `actual` after the previous matching slice and before
the current matching slice are marked as added */
for(const Containers::StringView& i: actualLines.slice(actualI, slice.first()))
out << Utility::Debug::newline << Utility::Debug::color(Utility::Debug::Color::Green) << " +" << Utility::Debug::nospace << i << Utility::Debug::resetColor;
/* The matching slice is not marked in any way */
for(const Containers::StringView& i: actualLines.sliceSize(slice.first(), slice.third()))
out << Utility::Debug::newline << " " << Utility::Debug::nospace << i;
actualI = slice.first() + slice.third();
expectedI = slice.second() + slice.third();
}
}
ComparisonStatusFlags Comparator<Compare::StringHasPrefix>::operator()(const Containers::StringView actual, const Containers::StringView expectedPrefix) {
_actualValue = actual;
_expectedPrefixValue = expectedPrefix;
/* If the strings are different, we can print them both in a verbose
message */
if(!actual.hasPrefix(expectedPrefix)) return ComparisonStatusFlag::Failed;
if(actual != expectedPrefix) return ComparisonStatusFlag::Verbose;
return {};
}
void Comparator<Compare::StringHasPrefix>::printMessage(const ComparisonStatusFlags flags, Utility::Debug& out, const char* const actual, const char* const expected) const {
if(flags == ComparisonStatusFlag::Failed)
out << "String" << actual << "isn't prefixed with" << expected
<< Utility::Debug::nospace << ", actual is\n " << _actualValue
<< Utility::Debug::newline << " but expected prefix\n "
<< _expectedPrefixValue;
else if(flags == ComparisonStatusFlag::Verbose)
out << "String" << actual << "is prefixed with" << expected
<< Utility::Debug::nospace << ", the actual string\n " << _actualValue
<< Utility::Debug::newline << " has expected prefix\n "
<< _expectedPrefixValue;
else CORRADE_INTERNAL_ASSERT_UNREACHABLE(); /* LCOV_EXCL_LINE */
}
ComparisonStatusFlags Comparator<Compare::StringHasSuffix>::operator()(const Containers::StringView actual, const Containers::StringView expectedSuffix) {
_actualValue = actual;
_expectedSuffixValue = expectedSuffix;
/* If the strings are different, we can print them both in a verbose
message */
if(!actual.hasSuffix(expectedSuffix)) return ComparisonStatusFlag::Failed;
if(actual != expectedSuffix) return ComparisonStatusFlag::Verbose;
return {};
}
void Comparator<Compare::StringHasSuffix>::printMessage(const ComparisonStatusFlags flags, Utility::Debug& out, const char* const actual, const char* const expected) const {
if(flags == ComparisonStatusFlag::Failed)
out << "String" << actual << "isn't suffixed with" << expected
<< Utility::Debug::nospace << ", actual is\n " << _actualValue
<< Utility::Debug::newline << " but expected suffix\n "
<< _expectedSuffixValue;
else if(flags == ComparisonStatusFlag::Verbose)
out << "String" << actual << "is suffixed with" << expected
<< Utility::Debug::nospace << ", the actual string\n " << _actualValue
<< Utility::Debug::newline << " has expected suffix\n "
<< _expectedSuffixValue;
else CORRADE_INTERNAL_ASSERT_UNREACHABLE(); /* LCOV_EXCL_LINE */
}
ComparisonStatusFlags Comparator<Compare::StringContains>::operator()(const Containers::StringView actual, const Containers::StringView expectedToContain) {
_actualValue = actual;
_expectedToContainValue = expectedToContain;
/* If the strings are different, we can print them both in a verbose
message */
if(!actual.contains(expectedToContain)) return ComparisonStatusFlag::Failed;
if(actual != expectedToContain) return ComparisonStatusFlag::Verbose;
return {};
}
void Comparator<Compare::StringContains>::printMessage(const ComparisonStatusFlags flags, Utility::Debug& out, const char* const actual, const char* const expected) const {
if(flags == ComparisonStatusFlag::Failed)
out << "String" << actual << "doesn't contain" << expected
<< Utility::Debug::nospace << ", actual is\n " << _actualValue
<< Utility::Debug::newline << " but expected to contain\n "
<< _expectedToContainValue;
else if(flags == ComparisonStatusFlag::Verbose)
out << "String" << actual << "contains" << expected << "at position"
<< (_actualValue.find(_expectedToContainValue).begin() - _actualValue.begin())
<< Utility::Debug::nospace << ", the actual string\n " << _actualValue
<< Utility::Debug::newline << " expectedly contains\n "
<< _expectedToContainValue;
else CORRADE_INTERNAL_ASSERT_UNREACHABLE(); /* LCOV_EXCL_LINE */
}
ComparisonStatusFlags Comparator<Compare::StringNotContains>::operator()(const Containers::StringView actual, const Containers::StringView expectedToNotContain) {
_actualValue = actual;
_expectedToNotContainValue = expectedToNotContain;
/* Unlike the other comparators, here it can't pass if the strings are the
same, meaning we report the verbose message always */
if(actual.contains(expectedToNotContain)) return ComparisonStatusFlag::Failed;
return ComparisonStatusFlag::Verbose;
}
void Comparator<Compare::StringNotContains>::printMessage(const ComparisonStatusFlags flags, Utility::Debug& out, const char* const actual, const char* const expected) const {
if(flags == ComparisonStatusFlag::Failed)
out << "String" << actual << "contains" << expected << "at position"
<< (_actualValue.find(_expectedToNotContainValue).begin() - _actualValue.begin())
<< Utility::Debug::nospace << ", actual is\n " << _actualValue
<< Utility::Debug::newline << " but expected to not contain\n "
<< _expectedToNotContainValue;
else if(flags == ComparisonStatusFlag::Verbose)
out << "String" << actual << "doesn't contain" << expected
<< Utility::Debug::nospace << ", the actual string\n " << _actualValue
<< Utility::Debug::newline << " expectedly doesn't contain\n "
<< _expectedToNotContainValue;
else CORRADE_INTERNAL_ASSERT_UNREACHABLE(); /* LCOV_EXCL_LINE */
}
}}
|
[
"mosra@centrum.cz"
] |
mosra@centrum.cz
|
88e4a18c0cefd55ea1355380550d824e8c214c36
|
be4459658d667c47eefeeb3cf689a678042edb94
|
/modules/core/rwvx/rwmsg/test/rwmsg_broker_gtest.cc
|
d2ab979a3c41e422369b42f03cb093bf6f4e949f
|
[
"Apache-2.0"
] |
permissive
|
kparr/RIFT.ware-1
|
7945174aa23ac1f7d74a7464b645db5824982fc3
|
6846108d70b80b95c5117fdccd44ff058ac605be
|
refs/heads/master
| 2021-01-13T08:36:03.751610
| 2016-07-24T21:36:15
| 2016-07-24T21:36:15
| 72,420,438
| 0
| 0
| null | 2016-10-31T09:11:27
| 2016-10-31T09:11:27
| null |
UTF-8
|
C++
| false
| false
| 243,717
|
cc
|
/*
*
* (c) Copyright RIFT.io, 2013-2016, All Rights Reserved
*
*/
/**
* @file rwmsg_gtest_broker.cc
* @author Grant Taylor <grant.taylor@riftio.com>
* @date 11/18/2013
* @brief Google test cases for testing rwmsg_broker
*
* @details Google test cases for testing rwmsg_broker.
*/
/**
* Step 1: Include the necessary header files
*/
#include <sys/types.h>
#include <sys/socket.h>
#include <nanomsg/nn.h>
#include <nanomsg/pair.h>
#include <limits.h>
#include <cstdlib>
#include <netinet/in.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <valgrind/valgrind.h>
#include "rwut.h"
#include "rwlib.h"
#include "rw_dl.h"
#include "rw_sklist.h"
#include "rw_sys.h"
#include "rwtasklet.h"
#include <unistd.h>
#include <sys/syscall.h>
#include <rwmsg_int.h>
#include <rwmsg_broker.h>
#include "rwmsg_gtest_c.h"
#include "test.pb-c.h"
#include <ck.h>
#undef RWMSG_NOTHREAD
using ::testing::MatchesRegex;
using ::testing::ContainsRegex;
#define VERBOSE() (getenv("V") && getenv("V")[0]=='1')
static struct timeval PRN_start;
#define VERBPRN(args...) do { \
if (VERBOSE()) { \
if (!PRN_start.tv_sec) { \
gettimeofday(&PRN_start, NULL); \
} \
struct timeval tv; \
gettimeofday(&tv, NULL); \
struct timeval delta; \
timersub(&tv, &PRN_start, &delta); \
fprintf(stderr, "%ld.%03ld ", delta.tv_sec, delta.tv_usec/1000); \
fprintf(stderr, args); \
} \
} while(0)
#define MAX_RTT 999999999999
/*
* Step 2: Use the TEST macro to define your tests. The following
* is the notes from Google sample test
*
* TEST has two parameters: the test case name and the test name.
* After using the macro, you should define your test logic between a
* pair of braces. You can use a bunch of macros to indicate the
* success or failure of a test. EXPECT_TRUE and EXPECT_EQ are
* examples of such macros. For a complete list, see gtest.h.
*
* In Google Test, tests are grouped into test cases. This is how we
* keep test code organized. You should put logically related tests
* into the same test case.
*
* The test case name and the test name should both be valid C++
* identifiers. And you should not use underscore (_) in the names.
*
* Google Test guarantees that each test you define is run exactly
* once, but it makes no guarantee on the order the tests are
* executed. Therefore, you should write your tests in such a way
* that their results don't depend on their order.
*/
/* Test and tasklet environment */
static void nnchk() {
/* Gratuitous socket open/close; the close will delete any riftcfg
in the nn library unless there was a leaked nn socket from a
preceeding test. */
int sk = nn_socket (AF_SP, NN_PAIR);
nn_close(sk);
/* This gets cleared when the last nn sock is closed, has to happen... */
struct nn_riftconfig rcfg;
nn_global_get_riftconfig(&rcfg);
ASSERT_FALSE(rcfg.singlethread);
ASSERT_TRUE(rcfg.waitfunc == NULL);
}
static uint16_t broport_g=0;
#define GTEST_BASE_BROKER_PORT 31234
uint16_t rwmsg_broport_g(int tasklet_ct_in) {
rw_status_t status;
static uint16_t previous_tasklet_ct_in = 0;
/* Plug in a new broker port for each test to avoid confusion.
Each test uses the next port */
if (!broport_g) {
const char *envport = getenv("RWMSG_BROKER_PORT");
if (envport) {
long int long_port;
long_port = strtol(envport, NULL, 10);
if (long_port < 65535 && long_port > 0)
broport_g = (uint16_t)long_port;
else
RW_ASSERT(long_port < 65535 && long_port > 0);
} else {
uint8_t uid;
status = rw_unique_port(GTEST_BASE_BROKER_PORT, &broport_g);
RW_ASSERT(status == RW_STATUS_SUCCESS);
status = rw_instance_uid(&uid);
RW_ASSERT(status == RW_STATUS_SUCCESS);
// The unit test needs a range of unique ports.
// coverage-tests taking almost 500 ports
broport_g += 500 * uid;
}
} else {
broport_g += previous_tasklet_ct_in;
}
// Avoid the list of known port#s
while (rw_port_in_avoid_list(broport_g, tasklet_ct_in))
broport_g += tasklet_ct_in;
previous_tasklet_ct_in = tasklet_ct_in;
return broport_g;
}
class rwmsg_btenv_t {
public:
#define TASKLET_MAX (10)
rwmsg_btenv_t(int tasklet_ct_in=0) {
broport = rwmsg_broport_g(tasklet_ct_in);
char tmp[16];
sprintf(tmp, "%d", broport);
fprintf(stderr, "+++++++++++++++++++++++++++ %d\n", broport);
setenv ("RWMSG_BROKER_PORT", tmp, TRUE);
setenv("RWMSG_BROKER_ENABLE", "1", TRUE);
setenv("RWMSG_CHANNEL_AGEOUT", "1", TRUE);
memset(&rwmsg_broker_g, 0, sizeof(rwmsg_broker_g));
assert(tasklet_ct_in <= TASKLET_MAX);
rwsched = rwsched_instance_new();
tasklet_ct = tasklet_ct_in;
memset(&tasklet, 0, sizeof(tasklet));
for (int i=0; i<tasklet_ct; i++) {
tasklet[i] = rwsched_tasklet_new(rwsched);
}
ti = &ti_s;
ti->rwvx = rwvx_instance_alloc();
ti->rwsched_instance = rwsched;
ti->rwvcs = ti->rwvx->rwvcs;
rwcal = ti->rwvx->rwcal_module;
RW_ASSERT(rwcal);
rw_status_t status = rwcal_rwzk_zake_init(rwcal);
RW_ASSERT(RW_STATUS_SUCCESS == status);
}
~rwmsg_btenv_t() {
setenv("RWMSG_BROKER_PORT", "0" , TRUE);
setenv("RWMSG_BROKER_ENABLE", "0" , TRUE);
setenv("RWMSG_CHANNEL_AGEOUT", "0" , TRUE);
if (rwsched) {
for (int i=0; i<tasklet_ct; i++) {
rwsched_tasklet_free(tasklet[i]);
tasklet[i] = NULL;
}
rwsched_instance_free(rwsched);
rwsched = NULL;
}
if (rwcal) {
char rwzk_LOCK[999];
char rwzk_path[999];
char ** children = NULL;
rw_status_t rs;
sprintf(rwzk_path, "/sys/rwmsg/broker-lock");
rs = rwcal_rwzk_get_children(rwcal, rwzk_path, &children, NULL);
RW_ASSERT(rs == RW_STATUS_SUCCESS || rs == RW_STATUS_NOTFOUND);
if (children) {
int i=0;
while (children[i] != NULL) {
sprintf(rwzk_LOCK, "/sys/rwmsg/broker-lock/%s", children[i]);
rs = rwcal_rwzk_delete(rwcal, rwzk_LOCK, NULL);
free(children[i]);
i++;
}
free(children);
}
children = NULL;
rs = rwcal_rwzk_get_children(rwcal, rwzk_path, &children, NULL);
if (rs == RW_STATUS_SUCCESS) {
RW_ASSERT(!children || !children[0]);
}
else {
RW_ASSERT(rs == RW_STATUS_NOTFOUND);
}
rwcal = NULL;
}
}
int broport;
rwsched_instance_ptr_t rwsched;
rwtasklet_info_t ti_s;
rwtasklet_info_t *ti;
int tasklet_ct;
rwsched_tasklet_ptr_t tasklet[TASKLET_MAX];
rwcal_module_ptr_t rwcal;
};
TEST(RWMsgBroker, PlaceholderNOP) {
TEST_DESCRIPTION("Tests nothing whatsoever");
if (0) {
VERBPRN(" ");
}
}
TEST(RWMsgTestEnv, ThouShaltCoreDump) {
TEST_DESCRIPTION("Tests rlimit coredump setting");
struct rlimit rlim = { 0 };
getrlimit(RLIMIT_CORE, &rlim);
VERBPRN("Core rlimit .rlim_cur=%lu .rlim_max=%lu\n", rlim.rlim_cur, rlim.rlim_max);
ASSERT_GT(rlim.rlim_cur, 0);
}
TEST(RWMsgBroker, CreateBindListen) {
TEST_DESCRIPTION("Tests creation of scheduler, broker, binding, and listening");
rwmsg_btenv_t tenv(1);
rwmsg_broker_t *bro=NULL;
tenv.ti->rwsched_tasklet_info = tenv.tasklet[0];
rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, TRUE, tenv.ti, &bro);
/* Should now accept and ultimately timeout in the broker's acceptor */
int loopwait = 10;
rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, &rwmsg_broker_g.exitnow.acc_listening);
ASSERT_EQ(rwmsg_broker_g.exitnow.neg_accepted, 0);
ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0);
rwmsg_bool_t rb = rwmsg_broker_halt_sync(bro);
ASSERT_TRUE(rb);
ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0);
nnchk();
}
TEST(RWMsgBroker, CreateBindListen2Bros) {
TEST_DESCRIPTION("Tests creation of scheduler, broker, binding, and listening");
rwmsg_btenv_t tenv(2);
rwmsg_broker_t *bro1=NULL;
tenv.ti->rwsched_tasklet_info = tenv.tasklet[0];
rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, TRUE, tenv.ti, &bro1);
usleep(1000);
rwmsg_broker_t *bro2=NULL;
tenv.ti->rwsched_tasklet_info = tenv.tasklet[1];
rwmsg_broker_main(broport_g, 1, 1, tenv.rwsched, tenv.tasklet[1], tenv.rwcal, TRUE, tenv.ti, &bro2);
usleep(1000);
double loopwait = 0.1;
int loopcount = 0;
uint32_t meshcount = 5*2*(2-1); //==10
/* Should now accept and ultimately timeout in the broker's acceptor */
//rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, &rwmsg_broker_g.exitnow.acc_listening);
while (rwmsg_broker_g.exitnow.neg_accepted<meshcount && loopcount++<100)
rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, NULL);
ASSERT_EQ(rwmsg_broker_g.exitnow.neg_accepted, meshcount);
ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0);
rwmsg_bool_t rb;
rb = rwmsg_broker_halt_sync(bro1);
ASSERT_TRUE(rb);
rb = rwmsg_broker_halt_sync(bro2);
ASSERT_TRUE(rb);
ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0);
nnchk();
}
TEST(RWMsgBroker, CreateBindListen3Bros) {
TEST_DESCRIPTION("Tests creation of scheduler, broker, binding, and listening");
rwmsg_btenv_t tenv(3);
double loopwait = 0.1;
int loopcount = 0;
uint32_t meshcount = 5*3*(3-1); //==30
rwmsg_broker_t *bro1=NULL;
tenv.ti->rwsched_tasklet_info = tenv.tasklet[0];
rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, TRUE, tenv.ti, &bro1);
rwmsg_broker_t *bro2=NULL;
tenv.ti->rwsched_tasklet_info = tenv.tasklet[1];
rwmsg_broker_main(broport_g, 1, 1, tenv.rwsched, tenv.tasklet[1], tenv.rwcal, TRUE, tenv.ti, &bro2);
rwmsg_broker_t *bro3=NULL;
tenv.ti->rwsched_tasklet_info = tenv.tasklet[2];
rwmsg_broker_main(broport_g, 2, 2, tenv.rwsched, tenv.tasklet[2], tenv.rwcal, TRUE, tenv.ti, &bro3);
while (rwmsg_broker_g.exitnow.neg_accepted<meshcount && loopcount++<100)
rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, NULL);
ASSERT_EQ(rwmsg_broker_g.exitnow.neg_accepted, meshcount);
ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0);
rwmsg_bool_t rb;
rb = rwmsg_broker_halt_sync(bro1);
ASSERT_TRUE(rb);
rb = rwmsg_broker_halt_sync(bro2);
ASSERT_TRUE(rb);
rb = rwmsg_broker_halt_sync(bro3);
ASSERT_TRUE(rb);
ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0);
nnchk();
}
TEST(RWMsgBroker, CreateBindListen4Bros) {
TEST_DESCRIPTION("Tests creation of scheduler, broker, binding, and listening");
rwmsg_btenv_t tenv(4);
rwmsg_broker_t *bro1=NULL;
tenv.ti->rwsched_tasklet_info = tenv.tasklet[0];
rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, TRUE, tenv.ti, &bro1);
rwmsg_broker_t *bro2=NULL;
tenv.ti->rwsched_tasklet_info = tenv.tasklet[1];
rwmsg_broker_main(broport_g, 1, 1, tenv.rwsched, tenv.tasklet[1], tenv.rwcal, TRUE, tenv.ti, &bro2);
rwmsg_broker_t *bro3=NULL;
tenv.ti->rwsched_tasklet_info = tenv.tasklet[2];
rwmsg_broker_main(broport_g, 2, 2, tenv.rwsched, tenv.tasklet[2], tenv.rwcal, TRUE, tenv.ti, &bro3);
rwmsg_broker_t *bro4=NULL;
tenv.ti->rwsched_tasklet_info = tenv.tasklet[3];
rwmsg_broker_main(broport_g, 3, 3, tenv.rwsched, tenv.tasklet[3], tenv.rwcal, TRUE, tenv.ti, &bro4);
usleep(10*1000);
/* Should now accept and ultimately timeout in the broker's acceptor */
//int loopwait = 15;
//rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, &rwmsg_broker_g.exitnow.acc_listening);
double loopwait = 0.1;
int loopcount = 0;
uint32_t meshcount = 5*4*(4-1); //==5*2*n*(n-1)/2 60
/* Should now accept and ultimately timeout in the broker's acceptor */
//rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, &rwmsg_broker_g.exitnow.acc_listening);
while (rwmsg_broker_g.exitnow.neg_accepted<meshcount && loopcount++<200) {
usleep(50*1000); // 50ms
rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, NULL);
}
ASSERT_EQ(rwmsg_broker_g.exitnow.neg_accepted, meshcount);
ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0);
usleep(50*1000);
rwmsg_bool_t rb;
rb = rwmsg_broker_halt_sync(bro1);
ASSERT_TRUE(rb);
rb = rwmsg_broker_halt_sync(bro2);
ASSERT_TRUE(rb);
rb = rwmsg_broker_halt_sync(bro3);
ASSERT_TRUE(rb);
rb = rwmsg_broker_halt_sync(bro4);
ASSERT_TRUE(rb);
ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0);
nnchk();
}
TEST(RWMsgBroker, AcceptTimeout) {
TEST_DESCRIPTION("Tests timeout of accepted connection in broker");
rwmsg_btenv_t tenv(1);
rwmsg_broker_t *bro=NULL;
tenv.ti->rwsched_tasklet_info = tenv.tasklet[0];
rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, TRUE, tenv.ti, &bro);
int sk = socket(AF_INET, SOCK_STREAM, 0);
int fl = fcntl(sk, F_GETFL);
ASSERT_TRUE(fl != -1);
fl |= O_NONBLOCK;
int r = fcntl(sk, F_SETFL, fl);
ASSERT_TRUE(r == 0);
struct sockaddr_in ad;
ad.sin_family = AF_INET;
ad.sin_port = htons(tenv.broport);
ad.sin_addr.s_addr = htonl(RWMSG_CONNECT_IP_ADDR);
r = connect(sk, (struct sockaddr*)&ad, sizeof(ad));
ASSERT_TRUE(r == 0 || (r == -1 && errno == EINPROGRESS));
/* Should now accept and ultimately timeout in the broker's acceptor */
int loopwait = 10;
rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, &rwmsg_broker_g.exitnow.neg_freed_err);
ASSERT_EQ(rwmsg_broker_g.exitnow.neg_accepted, 0);
ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 1);
r = rwmsg_broker_halt_sync(bro);
ASSERT_TRUE(r);
ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0);
nnchk();
}
TEST(RWMsgBroker, AcceptTimeout2Bros) {
TEST_DESCRIPTION("Tests timeout of accepted connection in broker");
rwmsg_btenv_t tenv(2);
rwmsg_broker_t *bro1=NULL;
tenv.ti->rwsched_tasklet_info = tenv.tasklet[0];
rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, TRUE, tenv.ti, &bro1);
rwmsg_broker_t *bro2=NULL;
tenv.ti->rwsched_tasklet_info = tenv.tasklet[1];
rwmsg_broker_main(broport_g, 1, 1, tenv.rwsched, tenv.tasklet[1], tenv.rwcal, TRUE, tenv.ti, &bro2);
{
int sk = socket(AF_INET, SOCK_STREAM, 0);
int fl = fcntl(sk, F_GETFL);
ASSERT_TRUE(fl != -1);
fl |= O_NONBLOCK;
int r = fcntl(sk, F_SETFL, fl);
ASSERT_TRUE(r == 0);
struct sockaddr_in ad;
ad.sin_family = AF_INET;
ad.sin_port = htons(tenv.broport);
ad.sin_addr.s_addr = htonl(RWMSG_CONNECT_IP_ADDR);
r = connect(sk, (struct sockaddr*)&ad, sizeof(ad));
ASSERT_TRUE(r == 0 || (r == -1 && errno == EINPROGRESS));
/* Should now accept and ultimately timeout in the broker's acceptor */
int loopwait = 10;
rwmsg_broker_g.exitnow.neg_freed_err = 0;
rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, &rwmsg_broker_g.exitnow.neg_freed_err);
ASSERT_EQ(rwmsg_broker_g.exitnow.neg_accepted, 10);
ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 1);
}
int r;
r = rwmsg_broker_halt_sync(bro1);
ASSERT_TRUE(r);
r = rwmsg_broker_halt_sync(bro2);
ASSERT_TRUE(r);
ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0);
nnchk();
}
TEST(RWMsgBroker, AcceptHandshakeFail) {
TEST_DESCRIPTION("Tests rejection of failed handshake in broker");
rwmsg_btenv_t tenv(1);
rwmsg_broker_t *bro=NULL;
tenv.ti->rwsched_tasklet_info = tenv.tasklet[0];
rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, TRUE, tenv.ti, &bro);
int sk = socket(AF_INET, SOCK_STREAM, 0);
int fl = fcntl(sk, F_GETFL);
ASSERT_TRUE(fl != -1);
//fl |= O_NONBLOCK;
int r = fcntl(sk, F_SETFL, fl);
ASSERT_TRUE(r == 0);
struct sockaddr_in ad;
ad.sin_family = AF_INET;
ad.sin_port = htons(tenv.broport);
ad.sin_addr.s_addr = htonl(RWMSG_CONNECT_IP_ADDR);
r = connect(sk, (struct sockaddr*)&ad, sizeof(ad));
ASSERT_TRUE(r == 0);
uint64_t hsbuf[2] = { 0x0102030405060708ull, 0x0102030405060708ull };
r = write(sk, &hsbuf, 7); // not 16!
ASSERT_EQ(r, 7);
/* Should now accept, read partial hs, and jettison from the broker's acceptor */
int loopwait = 3;
rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, &rwmsg_broker_g.exitnow.neg_freed_err);
ASSERT_EQ(rwmsg_broker_g.exitnow.neg_accepted, 0);
r = rwmsg_broker_halt_sync(bro);
ASSERT_TRUE(r);
ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0);
nnchk();
}
TEST(RWMsgBroker, AcceptHandshakeFail2Bros) {
TEST_DESCRIPTION("Tests rejection of failed handshake in broker");
rwmsg_btenv_t tenv(2);
rwmsg_broker_t *bro1=NULL;
tenv.ti->rwsched_tasklet_info = tenv.tasklet[0];
rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, TRUE, tenv.ti, &bro1);
rwmsg_broker_t *bro2=NULL;
tenv.ti->rwsched_tasklet_info = tenv.tasklet[1];
rwmsg_broker_main(broport_g, 1, 1, tenv.rwsched, tenv.tasklet[1], tenv.rwcal, TRUE, tenv.ti, &bro2);
{
int sk = socket(AF_INET, SOCK_STREAM, 0);
int fl = fcntl(sk, F_GETFL);
ASSERT_TRUE(fl != -1);
//fl |= O_NONBLOCK;
int r = fcntl(sk, F_SETFL, fl);
ASSERT_TRUE(r == 0);
struct sockaddr_in ad;
ad.sin_family = AF_INET;
ad.sin_port = htons(tenv.broport);
ad.sin_addr.s_addr = htonl(RWMSG_CONNECT_IP_ADDR);
r = connect(sk, (struct sockaddr*)&ad, sizeof(ad));
ASSERT_TRUE(r == 0);
uint64_t hsbuf[2] = { 0x0102030405060708ull, 0x0102030405060708ull };
r = write(sk, &hsbuf, 7); // not 16!
ASSERT_EQ(r, 7);
/* Should now accept, read partial hs, and jettison from the broker's acceptor */
int loopwait = 3;
rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, &rwmsg_broker_g.exitnow.neg_freed_err);
ASSERT_EQ(rwmsg_broker_g.exitnow.neg_accepted, 10);
}
{
int sk = socket(AF_INET, SOCK_STREAM, 0);
int fl = fcntl(sk, F_GETFL);
ASSERT_TRUE(fl != -1);
//fl |= O_NONBLOCK;
int r = fcntl(sk, F_SETFL, fl);
ASSERT_TRUE(r == 0);
struct sockaddr_in ad;
ad.sin_family = AF_INET;
ad.sin_port = htons(tenv.broport+1);
ad.sin_addr.s_addr = htonl(RWMSG_CONNECT_IP_ADDR);
r = connect(sk, (struct sockaddr*)&ad, sizeof(ad));
ASSERT_TRUE(r == 0);
uint64_t hsbuf[2] = { 0x0102030405060708ull, 0x0102030405060708ull };
r = write(sk, &hsbuf, 7); // not 16!
ASSERT_EQ(r, 7);
/* Should now accept, read partial hs, and jettison from the broker's acceptor */
int loopwait = 3;
rwsched_dispatch_main_until(tenv.tasklet[1], loopwait, &rwmsg_broker_g.exitnow.neg_freed_err);
ASSERT_EQ(rwmsg_broker_g.exitnow.neg_accepted, 10);
}
int r;
r = rwmsg_broker_halt_sync(bro1);
ASSERT_TRUE(r);
r = rwmsg_broker_halt_sync(bro2);
ASSERT_TRUE(r);
ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0);
nnchk();
}
TEST(RWMsgBroker, AcceptHandshakeOK) {
TEST_DESCRIPTION("Tests accepting a handshake in broker");
rwmsg_btenv_t tenv(1);
rwmsg_broker_t *bro=NULL;
tenv.ti->rwsched_tasklet_info = tenv.tasklet[0];
rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, TRUE, tenv.ti, &bro);
int sk = socket(AF_INET, SOCK_STREAM, 0);
int fl = fcntl(sk, F_GETFL);
ASSERT_TRUE(fl != -1);
//fl |= O_NONBLOCK;
int r = fcntl(sk, F_SETFL, fl);
ASSERT_TRUE(r == 0);
struct sockaddr_in ad;
ad.sin_family = AF_INET;
ad.sin_port = htons(tenv.broport);
ad.sin_addr.s_addr = htonl(RWMSG_CONNECT_IP_ADDR);
r = connect(sk, (struct sockaddr*)&ad, sizeof(ad));
ASSERT_TRUE(r == 0);
struct rwmsg_handshake_s handshake;
memset(&handshake, 0, sizeof(handshake));
handshake.chanid = 1;
handshake.pid = getpid();
handshake.chtype = RWMSG_CHAN_SRV;
handshake.pri = RWMSG_PRIORITY_HIGH;
r = write(sk, &handshake, sizeof(handshake));
ASSERT_EQ(r, sizeof(handshake));
/* Should now accept, read partial hs, and jettison from the broker's acceptor */
int loopwait = 10;
rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, &rwmsg_broker_g.exitnow.neg_freed);
ASSERT_EQ(rwmsg_broker_g.exitnow.neg_accepted, 1);
ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed, 1);
ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0);
r = rwmsg_broker_halt_sync(bro);
ASSERT_TRUE(r);
ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0);
nnchk();
}
TEST(RWMsgBroker, AcceptHandshakeOK2Bros) {
TEST_DESCRIPTION("Tests accepting a handshake in broker");
rwmsg_btenv_t tenv(2);
rwmsg_broker_t *bro1=NULL;
tenv.ti->rwsched_tasklet_info = tenv.tasklet[0];
rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, TRUE, tenv.ti, &bro1);
rwmsg_broker_t *bro2=NULL;
tenv.ti->rwsched_tasklet_info = tenv.tasklet[1];
rwmsg_broker_main(broport_g, 1, 1, tenv.rwsched, tenv.tasklet[1], tenv.rwcal, TRUE, tenv.ti, &bro2);
{
int sk = socket(AF_INET, SOCK_STREAM, 0);
int fl = fcntl(sk, F_GETFL);
ASSERT_TRUE(fl != -1);
//fl |= O_NONBLOCK;
int r = fcntl(sk, F_SETFL, fl);
ASSERT_TRUE(r == 0);
struct sockaddr_in ad;
ad.sin_family = AF_INET;
ad.sin_port = htons(tenv.broport);
ad.sin_addr.s_addr = htonl(RWMSG_CONNECT_IP_ADDR);
r = connect(sk, (struct sockaddr*)&ad, sizeof(ad));
ASSERT_TRUE(r == 0);
struct rwmsg_handshake_s handshake;
memset(&handshake, 0, sizeof(handshake));
handshake.chanid = 1;
handshake.pid = getpid();
handshake.chtype = RWMSG_CHAN_SRV;
handshake.pri = RWMSG_PRIORITY_HIGH;
r = write(sk, &handshake, sizeof(handshake));
ASSERT_EQ(r, sizeof(handshake));
/* Should now accept, read partial hs, and jettison from the broker's acceptor */
int loopwait = 10;
rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, &rwmsg_broker_g.exitnow.neg_freed);
usleep(1000*100);
ASSERT_GE(rwmsg_broker_g.exitnow.neg_accepted, 1);
ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1);
ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0);
}
int r;
r = rwmsg_broker_halt_sync(bro1);
ASSERT_TRUE(r);
r = rwmsg_broker_halt_sync(bro2);
ASSERT_TRUE(r);
ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0);
nnchk();
}
TEST(RWMsgBroker, AcceptClichan) {
TEST_DESCRIPTION("Tests accepting from a clichan");
rwmsg_btenv_t tenv(2);
/* Broker is tasklet 0 */
rwmsg_broker_t *bro=NULL;
tenv.ti->rwsched_tasklet_info = tenv.tasklet[0];
rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, TRUE, tenv.ti, &bro);
/* Clichan is tasklet 1, also bound to main rws queue to avoid CF/dispatch headaches */
rwmsg_endpoint_t *ep;
ep = rwmsg_endpoint_create(0, 0, 0, tenv.rwsched, tenv.tasklet[1], rwtrace_init(), NULL);
ASSERT_TRUE(ep != NULL);
rwmsg_clichan_t *cc = rwmsg_clichan_create(ep);
ASSERT_TRUE(cc != NULL);
rw_status_t rs = rwmsg_clichan_bind_rwsched_queue(cc, rwsched_dispatch_get_main_queue(tenv.rwsched));
ASSERT_TRUE(rs == RW_STATUS_SUCCESS);
/* Should now accept, read hs, create broclichan, attach incoming accepted sk */
int loopwait = 10;
rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, &rwmsg_broker_g.exitnow.neg_freed);
ASSERT_GE(rwmsg_broker_g.exitnow.neg_accepted, 1);
ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1);
ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0);
/* End clichan tasklet 1 */
rwmsg_bool_t r;
rwmsg_clichan_halt(cc);
r = rwmsg_endpoint_halt_flush(ep, TRUE);
ASSERT_TRUE(r);
/* End broker */
r = rwmsg_broker_halt_sync(bro);
ASSERT_TRUE(r);
ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0);
nnchk();
}
TEST(RWMsgBroker, ClichanConnectionStatus) {
TEST_DESCRIPTION("Tests accepting from a clichan");
rw_status_t rs;
rwmsg_endpoint_t *ep;
rwmsg_clichan_t *cc;
rwmsg_bool_t r;
rwsched_tasklet_ptr_t tasklet;
rwsched_instance_ptr_t rwsched;
/* create a tasklet w/o setting RWMSG_BROKER_PORT that way the endpoint won't
* have broker enabled and the clichan would only have local-only channels */
rwsched = rwsched_instance_new();
tasklet = rwsched_tasklet_new(rwsched);
ep = rwmsg_endpoint_create(0, 0, 0, rwsched, tasklet, rwtrace_init(), NULL);
ASSERT_TRUE(ep != NULL);
cc = rwmsg_clichan_create(ep);
ASSERT_TRUE(cc != NULL);
/* Returns SUCCESS if the cc is local-only */
rs = rwmsg_clichan_connection_status(cc);
ASSERT_TRUE(rs == RW_STATUS_SUCCESS);
/* End clichan */
rwmsg_clichan_halt(cc);
r = rwmsg_endpoint_halt_flush(ep, TRUE);
ASSERT_TRUE(r);
rwsched_tasklet_free(tasklet);
rwsched_instance_free(rwsched);
/* create the usual style tasklets w/ RWMSG_BROKER_PORT enabled
* so that we can test the clichan w/ remote channels which connects to the broker*/
rwmsg_btenv_t tenv(2);
/* Broker is tasklet 0 */
rwmsg_broker_t *bro=NULL;
tenv.ti->rwsched_tasklet_info = tenv.tasklet[0];
rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, TRUE, tenv.ti, &bro);
/* Clichan is tasklet 1, also bound to main rws queue to avoid CF/dispatch headaches */
ep = rwmsg_endpoint_create(0, 0, 0, tenv.rwsched, tenv.tasklet[1], rwtrace_init(), NULL);
ASSERT_TRUE(ep != NULL);
cc = rwmsg_clichan_create(ep);
ASSERT_TRUE(cc != NULL);
rs = rwmsg_clichan_connection_status(cc);
ASSERT_TRUE(rs == RW_STATUS_NOTCONNECTED);
rs = rwmsg_clichan_bind_rwsched_queue(cc, rwsched_dispatch_get_main_queue(tenv.rwsched));
ASSERT_TRUE(rs == RW_STATUS_SUCCESS);
/* Returns NOTCONNECTED if the cc's socket's state is not NN_CONNECTED */
rs = rwmsg_clichan_connection_status(cc);
ASSERT_TRUE(rs == RW_STATUS_NOTCONNECTED);
/* Should now accept, read hs, create broclichan, attach incoming accepted sk */
int loopwait = 10;
rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, &rwmsg_broker_g.exitnow.neg_freed);
/* Returns SUCCESS if the cc's socket's state is NN_CONNECTED */
rs = rwmsg_clichan_connection_status(cc);
ASSERT_TRUE(rs == RW_STATUS_SUCCESS);
ASSERT_GE(rwmsg_broker_g.exitnow.neg_accepted, 1);
ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1);
ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0);
/* End clichan tasklet 1 */
rwmsg_clichan_halt(cc);
r = rwmsg_endpoint_halt_flush(ep, TRUE);
ASSERT_TRUE(r);
/* End broker */
r = rwmsg_broker_halt_sync(bro);
ASSERT_TRUE(r);
ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0);
nnchk();
}
TEST(RWMsgBroker, AcceptClichan2Bros) {
TEST_DESCRIPTION("Tests accepting from a clichan");
rwmsg_btenv_t tenv(4);
rwmsg_bool_t r;
/* Broker-1 is tasklet 0 */
rwmsg_broker_t *bro1=NULL;
tenv.ti->rwsched_tasklet_info = tenv.tasklet[0];
rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, TRUE, tenv.ti, &bro1);
/* Broker-2 is tasklet 2 */
rwmsg_broker_t *bro2=NULL;
tenv.ti->rwsched_tasklet_info = tenv.tasklet[1];
rwmsg_broker_main(broport_g, 2, 1, tenv.rwsched, tenv.tasklet[2], tenv.rwcal, TRUE, tenv.ti, &bro2);
{
/* Clichan is tasklet 1, also bound to main rws queue to avoid CF/dispatch headaches */
rwmsg_endpoint_t *ep;
ep = rwmsg_endpoint_create(0, 1, 0, tenv.rwsched, tenv.tasklet[1], rwtrace_init(), NULL);
ASSERT_TRUE(ep != NULL);
rwmsg_clichan_t *cc = rwmsg_clichan_create(ep);
ASSERT_TRUE(cc != NULL);
rw_status_t rs = rwmsg_clichan_bind_rwsched_queue(cc, rwsched_dispatch_get_main_queue(tenv.rwsched));
ASSERT_TRUE(rs == RW_STATUS_SUCCESS);
/* Should now accept, read hs, create broclichan, attach incoming accepted sk */
int loopwait = 10;
rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, &rwmsg_broker_g.exitnow.neg_freed);
ASSERT_GE(rwmsg_broker_g.exitnow.neg_accepted, 1);
ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1);
ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0);
/* End clichan tasklet 1 */
rwmsg_clichan_halt(cc);
r = rwmsg_endpoint_halt_flush(ep, TRUE);
ASSERT_TRUE(r);
}
{
/* Clichan is tasklet 3, also bound to main rws queue to avoid CF/dispatch headaches */
rwmsg_endpoint_t *ep;
ep = rwmsg_endpoint_create(0, 3, 1, tenv.rwsched, tenv.tasklet[3], rwtrace_init(), NULL);
ASSERT_TRUE(ep != NULL);
rwmsg_clichan_t *cc = rwmsg_clichan_create(ep);
ASSERT_TRUE(cc != NULL);
rw_status_t rs = rwmsg_clichan_bind_rwsched_queue(cc, rwsched_dispatch_get_main_queue(tenv.rwsched));
ASSERT_TRUE(rs == RW_STATUS_SUCCESS);
rwmsg_broker_g.exitnow.neg_accepted = 0;
rwmsg_broker_g.exitnow.neg_freed = 0;
/* Should now accept, read hs, create broclichan, attach incoming accepted sk */
int loopwait = 10;
rwsched_dispatch_main_until(tenv.tasklet[2], loopwait, &rwmsg_broker_g.exitnow.neg_freed);
ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1);
ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0);
/* End clichan tasklet 1 */
rwmsg_clichan_halt(cc);
r = rwmsg_endpoint_halt_flush(ep, TRUE);
ASSERT_TRUE(r);
}
/* End broker */
r = rwmsg_broker_halt_sync(bro1);
ASSERT_TRUE(r);
r = rwmsg_broker_halt_sync(bro2);
ASSERT_TRUE(r);
ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0);
nnchk();
}
TEST(RWMsgBroker, AcceptClichanAndAgeout_LONG) {
TEST_DESCRIPTION("Tests accepting from a clichan");
rwmsg_btenv_t tenv(2);
/* Broker is tasklet 0 */
rwmsg_broker_t *bro=NULL;
tenv.ti->rwsched_tasklet_info = tenv.tasklet[0];
rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, TRUE, tenv.ti, &bro);
/* Clichan is tasklet 1, also bound to main rws queue to avoid CF/dispatch headaches */
rwmsg_endpoint_t *ep;
ep = rwmsg_endpoint_create(0, 0, 0, tenv.rwsched, tenv.tasklet[1], rwtrace_init(), NULL);
ASSERT_TRUE(ep != NULL);
for(int i=0; i<3; i++) {
rwmsg_clichan_t *cc = rwmsg_clichan_create(ep);
ASSERT_TRUE(cc != NULL);
rw_status_t rs = rwmsg_clichan_bind_rwsched_queue(cc, rwsched_dispatch_get_main_queue(tenv.rwsched));
ASSERT_TRUE(rs == RW_STATUS_SUCCESS);
rwmsg_broker_g.exitnow.neg_accepted = 0;
rwmsg_broker_g.exitnow.neg_freed = 0;
rwmsg_broker_g.exitnow.neg_freed_err = 0;
/* Should now accept, read hs, create broclichan, attach incoming accepted sk */
int loopwait = 10;
rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, &rwmsg_broker_g.exitnow.neg_freed);
ASSERT_GE(rwmsg_broker_g.exitnow.neg_accepted, 1);
ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1);
ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0);
/* End clichan tasklet 1 */
rwmsg_clichan_halt(cc);
}
rwmsg_bool_t r;
r = rwmsg_endpoint_halt_flush(ep, TRUE);
ASSERT_TRUE(r);
//rwmsg_broker_dump(bro);
//sleep(2);
int loopwait = 2; // wait for more than 1sec
rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, NULL);
rwmsg_broker_dump(bro);
ASSERT_EQ(rwmsg_broker_g.exitnow.bch_count, 0);
/* End broker */
r = rwmsg_broker_halt_sync(bro);
ASSERT_TRUE(r);
ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0);
nnchk();
}
TEST(RWMsgBroker, AcceptSrvchanAndAgeout_LONG) {
TEST_DESCRIPTION("Tests aging-out bro-srvchan");
rwmsg_btenv_t tenv(2);
/* Broker is tasklet 0 */
rwmsg_broker_t *bro=NULL;
tenv.ti->rwsched_tasklet_info = tenv.tasklet[0];
rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, TRUE, tenv.ti, &bro);
/* Clichan is tasklet 1, also bound to main rws queue to avoid CF/dispatch headaches */
rwmsg_endpoint_t *ep;
ep = rwmsg_endpoint_create(0, 0, 0, tenv.rwsched, tenv.tasklet[1], rwtrace_init(), NULL);
ASSERT_TRUE(ep != NULL);
for(int i=0; i<3; i++) {
rwmsg_srvchan_t *sc = rwmsg_srvchan_create(ep);
ASSERT_TRUE(sc != NULL);
rw_status_t rs = rwmsg_srvchan_bind_rwsched_queue(sc, rwsched_dispatch_get_main_queue(tenv.rwsched));
ASSERT_TRUE(rs == RW_STATUS_SUCCESS);
rwmsg_broker_g.exitnow.neg_accepted = 0;
rwmsg_broker_g.exitnow.neg_freed = 0;
rwmsg_broker_g.exitnow.neg_freed_err = 0;
/* Should now accept, read hs, create brosrvchan, attach incoming accepted sk */
int loopwait = 10;
rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, &rwmsg_broker_g.exitnow.neg_freed);
ASSERT_GE(rwmsg_broker_g.exitnow.neg_accepted, 1);
ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1);
ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0);
/* End srvchan tasklet 1 */
rwmsg_srvchan_halt(sc);
}
rwmsg_bool_t r;
r = rwmsg_endpoint_halt_flush(ep, TRUE);
ASSERT_TRUE(r);
//rwmsg_broker_dump(bro);
//sleep(2);
int loopwait = 2; // wait for more than 1sec
rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, NULL);
rwmsg_broker_dump(bro);
ASSERT_EQ(rwmsg_broker_g.exitnow.bch_count, 0);
/* End broker */
r = rwmsg_broker_halt_sync(bro);
ASSERT_TRUE(r);
ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0);
nnchk();
}
void broker_sleep_test_timer(void *ud) {
if (0) {
fprintf(stderr, "broker_sleep_test_timer start sleep\n");
sleep(2);
fprintf(stderr, "broker_sleep_test_timer end sleep\n");
}
}
TEST(RWMsgBroker, AcceptClichanSleep) {
TEST_DESCRIPTION("Tests accepting from a clichan");
rwmsg_btenv_t tenv(2);
/* Broker is tasklet 0, not on main queue, although acceptor always is */
rwmsg_broker_t *bro=NULL;
tenv.ti->rwsched_tasklet_info = tenv.tasklet[0];
rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, FALSE, tenv.ti, &bro);
/* Clichan is tasklet 1, also bound to main rws queue to avoid CF/dispatch headaches */
rwmsg_endpoint_t *ep;
ep = rwmsg_endpoint_create(0, 0, 0, tenv.rwsched, tenv.tasklet[1], rwtrace_init(), NULL);
ASSERT_TRUE(ep != NULL);
rwmsg_clichan_t *cc = rwmsg_clichan_create(ep);
ASSERT_TRUE(cc != NULL);
/* Timer on main queue to sleep and thereby sputter broker acceptor event processing */
rwsched_dispatch_source_t tim = rwsched_dispatch_source_create(tenv.tasklet[1],
RWSCHED_DISPATCH_SOURCE_TYPE_TIMER,
0,
0,
rwsched_dispatch_get_main_queue(tenv.rwsched));
rwsched_dispatch_source_set_event_handler_f(tenv.tasklet[1],
tim,
broker_sleep_test_timer);
rwsched_dispatch_set_context(tenv.tasklet[1],
tim,
NULL);
rwsched_dispatch_source_set_timer(tenv.tasklet[1],
tim,
dispatch_time(DISPATCH_TIME_NOW, 0*NSEC_PER_SEC),
100ull * NSEC_PER_SEC / 1000000ull,
0);
rwsched_dispatch_resume(tenv.tasklet[1], tim);
/* Make a serial queue for clichan */
rwsched_dispatch_queue_t q = rwsched_dispatch_queue_create(tenv.tasklet[0], "q", DISPATCH_QUEUE_SERIAL);
rw_status_t rs = rwmsg_clichan_bind_rwsched_queue(cc, q);
ASSERT_TRUE(rs == RW_STATUS_SUCCESS);
/* Should now accept, read hs, create broclichan, attach incoming accepted sk */
int loopwait = 15;
rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed);
// fprintf(stderr, "end dispatch_main 1\n");
loopwait = 1;
rwsched_dispatch_main_until(tenv.tasklet[1], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed);
// fprintf(stderr, "end dispatch_main 2\n");
ASSERT_GE(rwmsg_broker_g.exitnow.neg_accepted, 1);
ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1);
ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0);
rwsched_dispatch_source_cancel(tenv.tasklet[1], tim);
rwmsg_garbage(&ep->gc, RWMSG_OBJTYPE_RWSCHED_OBJREL, tim, tenv.rwsched, tenv.tasklet[1]);
/* End clichan tasklet 1 */
rwmsg_bool_t r;
rwmsg_clichan_halt(cc);
rwsched_dispatch_release(tenv.tasklet[0], q);
r = rwmsg_endpoint_halt_flush(ep, TRUE);
ASSERT_TRUE(r);
/* End broker */
r = rwmsg_broker_halt_sync(bro);
ASSERT_TRUE(r);
ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0);
nnchk();
}
TEST(RWMsgBroker, AcceptClichanSleep2Bros) {
TEST_DESCRIPTION("Tests accepting from a clichan");
rwmsg_btenv_t tenv(4);
rwmsg_bool_t r;
/* Broker-1 is tasklet 0, not on main queue, although acceptor always is */
rwmsg_broker_t *bro1=NULL;
tenv.ti->rwsched_tasklet_info = tenv.tasklet[0];
rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, FALSE, tenv.ti, &bro1);
/* Broker-2 is tasklet 2, not on main queue, although acceptor always is */
rwmsg_broker_t *bro2=NULL;
tenv.ti->rwsched_tasklet_info = tenv.tasklet[1];
rwmsg_broker_main(broport_g, 2, 1, tenv.rwsched, tenv.tasklet[2], tenv.rwcal, FALSE, tenv.ti, &bro2);
{
/* Clichan is tasklet 1, also bound to main rws queue to avoid CF/dispatch headaches */
rwmsg_endpoint_t *ep;
ep = rwmsg_endpoint_create(0, 0, 0, tenv.rwsched, tenv.tasklet[0], rwtrace_init(), NULL);
ASSERT_TRUE(ep != NULL);
rwmsg_clichan_t *cc = rwmsg_clichan_create(ep);
ASSERT_TRUE(cc != NULL);
/* Timer on main queue to sleep and thereby sputter broker acceptor event processing */
rwsched_dispatch_source_t tim = rwsched_dispatch_source_create(tenv.tasklet[1],
RWSCHED_DISPATCH_SOURCE_TYPE_TIMER,
0,
0,
rwsched_dispatch_get_main_queue(tenv.rwsched));
rwsched_dispatch_source_set_event_handler_f(tenv.tasklet[1],
tim,
broker_sleep_test_timer);
rwsched_dispatch_set_context(tenv.tasklet[1],
tim,
NULL);
rwsched_dispatch_source_set_timer(tenv.tasklet[1],
tim,
dispatch_time(DISPATCH_TIME_NOW, 0*NSEC_PER_SEC),
100ull * NSEC_PER_SEC / 1000000ull,
0);
rwsched_dispatch_resume(tenv.tasklet[1], tim);
/* Make a serial queue for clichan */
rwsched_dispatch_queue_t q = rwsched_dispatch_queue_create(tenv.tasklet[0], "q", DISPATCH_QUEUE_SERIAL);
rw_status_t rs = rwmsg_clichan_bind_rwsched_queue(cc, q);
ASSERT_TRUE(rs == RW_STATUS_SUCCESS);
/* Should now accept, read hs, create broclichan, attach incoming accepted sk */
int loopwait = 5;
rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed);
// fprintf(stderr, "end dispatch_main 1\n");
loopwait = 1;
rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed);
// fprintf(stderr, "end dispatch_main 2\n");
ASSERT_GE(rwmsg_broker_g.exitnow.neg_accepted, 1);
ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1);
ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0);
rwsched_dispatch_source_cancel(tenv.tasklet[1], tim);
rwmsg_garbage(&ep->gc, RWMSG_OBJTYPE_RWSCHED_OBJREL, tim, tenv.rwsched, tenv.tasklet[1]);
/* End clichan tasklet 1 */
rwmsg_clichan_halt(cc);
rwsched_dispatch_release(tenv.tasklet[0], q);
r = rwmsg_endpoint_halt_flush(ep, TRUE);
ASSERT_TRUE(r);
}
#if 0
{
/* Clichan is tasklet 3, also bound to main rws queue to avoid CF/dispatch headaches */
rwmsg_endpoint_t *ep;
ep = rwmsg_endpoint_create(0, 3, 1, tenv.rwsched, tenv.tasklet[3], rwtrace_init(), NULL);
ASSERT_TRUE(ep != NULL);
rwmsg_clichan_t *cc = rwmsg_clichan_create(ep);
ASSERT_TRUE(cc != NULL);
/* Timer on main queue to sleep and thereby sputter broker acceptor event processing */
rwsched_dispatch_source_t tim = rwsched_dispatch_source_create(tenv.tasklet[3],
RWSCHED_DISPATCH_SOURCE_TYPE_TIMER,
0,
0,
rwsched_dispatch_get_main_queue(tenv.rwsched));
rwsched_dispatch_source_set_event_handler_f(tenv.tasklet[3],
tim,
broker_sleep_test_timer);
rwsched_dispatch_set_context(tenv.tasklet[3],
tim,
NULL);
rwsched_dispatch_source_set_timer(tenv.tasklet[3],
tim,
dispatch_time(DISPATCH_TIME_NOW, 0*NSEC_PER_SEC),
100ull * NSEC_PER_SEC / 1000000ull,
0);
rwsched_dispatch_resume(tenv.tasklet[3], tim);
/* Make a serial queue for clichan */
rwsched_dispatch_queue_t q = rwsched_dispatch_queue_create(tenv.tasklet[3], "q", DISPATCH_QUEUE_SERIAL);
rw_status_t rs = rwmsg_clichan_bind_rwsched_queue(cc, q);
ASSERT_TRUE(rs == RW_STATUS_SUCCESS);
rwmsg_broker_g.exitnow.neg_accepted = 0;
rwmsg_broker_g.exitnow.neg_freed = 0;
rwmsg_broker_g.exitnow.neg_freed_err = 0;
/* Should now accept, read hs, create broclichan, attach incoming accepted sk */
int loopwait = 5;
rwsched_dispatch_main_until(tenv.tasklet[2], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed);
// fprintf(stderr, "end dispatch_main 1\n");
loopwait = 1;
rwsched_dispatch_main_until(tenv.tasklet[2], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed);
// fprintf(stderr, "end dispatch_main 2\n");
ASSERT_GE(rwmsg_broker_g.exitnow.neg_accepted, 1);
ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1);
ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0);
rwsched_dispatch_source_cancel(tenv.tasklet[1], tim);
rwmsg_garbage(&ep->gc, RWMSG_OBJTYPE_RWSCHED_OBJREL, tim, tenv.rwsched, tenv.tasklet[1]);
/* End clichan tasklet 1 */
rwmsg_clichan_halt(cc);
rwsched_dispatch_release(tenv.tasklet[1], q);
r = rwmsg_endpoint_halt_flush(ep, TRUE);
ASSERT_TRUE(r);
}
#endif
/* End broker */
r = rwmsg_broker_halt_sync(bro1);
ASSERT_TRUE(r);
r = rwmsg_broker_halt_sync(bro2);
ASSERT_TRUE(r);
ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0);
nnchk();
}
TEST(RWMsgBroker, AcceptSrvchan) {
ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0);
nnchk();
TEST_DESCRIPTION("Tests accepting from a srvchan");
rwmsg_btenv_t tenv(2);
/* Broker is tasklet 0 */
rwmsg_broker_t *bro=NULL;
tenv.ti->rwsched_tasklet_info = tenv.tasklet[0];
rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, TRUE, tenv.ti, &bro);
/* Clichan is tasklet 1, also bound to main rws queue to avoid CF/dispatch headaches */
rwmsg_endpoint_t *ep;
ep = rwmsg_endpoint_create(0, 0, 0, tenv.rwsched, tenv.tasklet[0], rwtrace_init(), NULL);
ASSERT_TRUE(ep != NULL);
rwmsg_srvchan_t *cc = rwmsg_srvchan_create(ep);
ASSERT_TRUE(cc != NULL);
rw_status_t rs = rwmsg_srvchan_bind_rwsched_queue(cc, rwsched_dispatch_get_main_queue(tenv.rwsched));
ASSERT_TRUE(rs == RW_STATUS_SUCCESS);
/* Should now accept, read hs, create broclichan, attach incoming accepted sk */
int loopwait = 10;
rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, &rwmsg_broker_g.exitnow.neg_freed);
ASSERT_GE(rwmsg_broker_g.exitnow.neg_accepted, 1);
ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1);
ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0);
/* End clichan tasklet 1 */
rwmsg_bool_t r;
rwmsg_srvchan_halt(cc);
r = rwmsg_endpoint_halt_flush(ep, TRUE);
ASSERT_TRUE(r);
/* End broker */
r = rwmsg_broker_halt_sync(bro);
ASSERT_TRUE(r);
ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0);
nnchk();
}
TEST(RWMsgBroker, AcceptSrvchan2Bros) {
ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0);
nnchk();
TEST_DESCRIPTION("Tests accepting from a srvchan");
rwmsg_btenv_t tenv(4);
rwmsg_bool_t r;
/* Broker is tasklet 0 */
rwmsg_broker_t *bro1=NULL;
tenv.ti->rwsched_tasklet_info = tenv.tasklet[0];
rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, TRUE, tenv.ti, &bro1);
/* Broker is tasklet 2 */
rwmsg_broker_t *bro2=NULL;
tenv.ti->rwsched_tasklet_info = tenv.tasklet[0];
rwmsg_broker_main(broport_g, 2, 1, tenv.rwsched, tenv.tasklet[2], tenv.rwcal, TRUE, tenv.ti, &bro2);
{
/* Clichan is tasklet 1, also bound to main rws queue to avoid CF/dispatch headaches */
rwmsg_endpoint_t *ep;
ep = rwmsg_endpoint_create(0, 0, 0, tenv.rwsched, tenv.tasklet[0], rwtrace_init(), NULL);
ASSERT_TRUE(ep != NULL);
rwmsg_srvchan_t *cc = rwmsg_srvchan_create(ep);
ASSERT_TRUE(cc != NULL);
rw_status_t rs = rwmsg_srvchan_bind_rwsched_queue(cc, rwsched_dispatch_get_main_queue(tenv.rwsched));
ASSERT_TRUE(rs == RW_STATUS_SUCCESS);
/* Should now accept, read hs, create broclichan, attach incoming accepted sk */
int loopwait = 10;
rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, &rwmsg_broker_g.exitnow.neg_freed);
ASSERT_GE(rwmsg_broker_g.exitnow.neg_accepted, 1);
ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1);
ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0);
/* End clichan tasklet 1 */
rwmsg_srvchan_halt(cc);
r = rwmsg_endpoint_halt_flush(ep, TRUE);
ASSERT_TRUE(r);
}
{
/* Clichan is tasklet 3, also bound to main rws queue to avoid CF/dispatch headaches */
rwmsg_endpoint_t *ep;
ep = rwmsg_endpoint_create(0, 3, 1, tenv.rwsched, tenv.tasklet[3], rwtrace_init(), NULL);
ASSERT_TRUE(ep != NULL);
rwmsg_srvchan_t *cc = rwmsg_srvchan_create(ep);
ASSERT_TRUE(cc != NULL);
rw_status_t rs = rwmsg_srvchan_bind_rwsched_queue(cc, rwsched_dispatch_get_main_queue(tenv.rwsched));
ASSERT_TRUE(rs == RW_STATUS_SUCCESS);
rwmsg_broker_g.exitnow.neg_accepted = 0;
rwmsg_broker_g.exitnow.neg_freed = 0;
rwmsg_broker_g.exitnow.neg_freed_err = 0;
/* Should now accept, read hs, create broclichan, attach incoming accepted sk */
int loopwait = 10;
rwsched_dispatch_main_until(tenv.tasklet[2], loopwait, &rwmsg_broker_g.exitnow.neg_freed);
ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1);
ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0);
/* End clichan tasklet 1 */
rwmsg_srvchan_halt(cc);
r = rwmsg_endpoint_halt_flush(ep, TRUE);
ASSERT_TRUE(r);
}
/* End broker */
r = rwmsg_broker_halt_sync(bro1);
ASSERT_TRUE(r);
r = rwmsg_broker_halt_sync(bro2);
ASSERT_TRUE(r);
ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0);
nnchk();
}
static void Test_increment(Test_Service *,
const TestReq *req,
void *ud,
TestRsp_Closure clo,
void *rwmsg);
static void Test_fail(Test_Service *,
const TestReq *req,
void *ud,
TestNop_Closure clo,
void *rwmsg);
void multibrocfb_response(const TestRsp *rsp, rwmsg_request_t *req, void *ud) {
//struct mycfbtaskinfo *tinfo = (struct mycfbtaskinfo *)ud;
//fprintf(stderr, "req->hdr.bnc=%d\n",req->hdr.bnc);
//ASSERT_EQ(req->hdr.bnc, 0);
//ASSERT_TRUE(rsp != NULL);
if (rsp) {
ASSERT_EQ(rsp->errval, 0);
ASSERT_EQ(rsp->body.hopct+1, rsp->body.value);
//tinfo->rsp_recv++;
VERBPRN("ProtobufCliSrvCFNonblocking test got rsp, value=%u errval=%u\n", rsp->body.value, rsp->errval);
} else {
//tinfo->bnc_recv++;
VERBPRN("ProtobufCliSrvCFNonblocking test got bnc=%d\n", (int)req->hdr.bnc);
}
return;
rsp=rsp;
req=req;
ud=ud;
}
TEST(RWMsgBroker, AcceptSrvchanAndCliChanW1Bro_LONG) {
ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0);
nnchk();
TEST_DESCRIPTION("Tests accepting from a srvchan");
rwmsg_btenv_t tenv(3);
rwmsg_bool_t r;
rw_status_t rs;
//const char *taddr = "/L/GTEST/RWBRO/TESTAPP/PBSCF/100/3";
const char *taddr = "/L/GTEST/RWBRO/1";
/* Broker is tasklet 0 */
rwmsg_broker_t *bro1=NULL;
tenv.ti->rwsched_tasklet_info = tenv.tasklet[0];
rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, TRUE, tenv.ti, &bro1);
double loopwait = 0.1;
rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, NULL);
/* Srvchan is tasklet 3, attached to broker 0
* also bound to main rws queue to avoid CF/dispatch headachess
* This endpoint has bro_instid=0 */
rwmsg_endpoint_t *ep_s;
ep_s = rwmsg_endpoint_create(0, 1, 0, tenv.rwsched, tenv.tasklet[1], rwtrace_init(), NULL);
ASSERT_TRUE(ep_s != NULL);
/* Direct everything through the broker */
rwmsg_endpoint_set_property_int(ep_s, "/rwmsg/broker/shunt", 1);
rwmsg_srvchan_t *sc = rwmsg_srvchan_create(ep_s);
ASSERT_TRUE(sc != NULL);
Test_Service myapisrv;
TEST__INITSERVER(&myapisrv, Test_);
//rs = rwmsg_srvchan_add_service(sc, tpath, &myapisrv.base, &tenv.tasklet[3]);
rs = rwmsg_srvchan_add_service(sc, taddr, &myapisrv.base, &tenv.tasklet[1]);
ASSERT_EQ(rs, RW_STATUS_SUCCESS);
rs = rwmsg_srvchan_bind_rwsched_queue(sc, rwsched_dispatch_get_main_queue(tenv.rwsched));
ASSERT_TRUE(rs == RW_STATUS_SUCCESS);
rwmsg_broker_g.exitnow.neg_accepted = 0;
rwmsg_broker_g.exitnow.neg_freed = 0;
rwmsg_broker_g.exitnow.neg_freed_err = 0;
/* Should now accept, read hs, create broclichan, attach incoming accepted sk */
loopwait = 5;
rwsched_dispatch_main_until(tenv.tasklet[1], loopwait, &rwmsg_broker_g.exitnow.neg_freed);
ASSERT_GE(rwmsg_broker_g.exitnow.neg_accepted, 1);
ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1);
ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0);
/* Clichan is tasklet 2, attached to broker 1
* also bound to main rws queue to avoid CF/dispatch headaches
* This endpoint has bro_instid=1 */
rwmsg_endpoint_t *ep_c;
ep_c = rwmsg_endpoint_create(0, 2, 0, tenv.rwsched, tenv.tasklet[2], rwtrace_init(), NULL);
ASSERT_TRUE(ep_c != NULL);
/* Direct everything through the broker */
rwmsg_endpoint_set_property_int(ep_c, "/rwmsg/broker/shunt", 1);
/* Create a client channel pointing at the Test service's path.
* Instantiate a Test service client and connect this to the client
* channel.
*/
rwmsg_destination_t *dt;
//dt = rwmsg_destination_create(ep_c, RWMSG_ADDRTYPE_UNICAST, tpeerpath);
dt = rwmsg_destination_create(ep_c, RWMSG_ADDRTYPE_UNICAST, taddr);
ASSERT_TRUE(dt != NULL);
rwmsg_clichan_t *cc = rwmsg_clichan_create(ep_c);
ASSERT_TRUE(cc != NULL);
rs = rwmsg_clichan_bind_rwsched_queue(cc, rwsched_dispatch_get_main_queue(tenv.rwsched));
Test_Client mycli;
TEST__INITCLIENT(&mycli);
rwmsg_clichan_add_service(cc, &mycli.base);
/* Should now accept, read hs, create broclichan, attach incoming accepted sk */
loopwait = 2;
rwsched_dispatch_main_until(tenv.tasklet[2], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed);
TestReq req;
rwmsg_request_t *rwreq=NULL;
test_req__init(&req);
// fprintf(stderr, "test__increment - 01\n");
#if 1
rwmsg_closure_t cb;
cb.pbrsp=(rwmsg_pbapi_cb)multibrocfb_response;
cb.ud=tenv.tasklet[2];
rs = test__increment(&mycli, dt, &req, &cb, &rwreq);
ASSERT_EQ(rs, RW_STATUS_SUCCESS);
#else
rs = test__increment_b(&mycli, dt, &req, &rwreq);
ASSERT_EQ(rs, RW_STATUS_SUCCESS);
#endif
// fprintf(stderr, "end dispatch_main 1\n");
loopwait = 1;
rwsched_dispatch_main_until(tenv.tasklet[2], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed);
// fprintf(stderr, "end dispatch_main 2\n");
ASSERT_GE(rwmsg_broker_g.exitnow.neg_accepted, 1);
ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1);
ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0);
#if 1
/* End clichan tasklet 1 */
rwmsg_clichan_halt(cc);
r = rwmsg_endpoint_halt_flush(ep_c, TRUE);
ASSERT_TRUE(r);
#endif
#if 1
/* End srvchan tasklet 2 */
rwmsg_srvchan_halt(sc);
r = rwmsg_endpoint_halt_flush(ep_s, TRUE);
ASSERT_TRUE(r);
#endif
/* End broker */
r = rwmsg_broker_halt_sync(bro1);
ASSERT_TRUE(r);
ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0);
nnchk();
}
const char *bnc_test_msg = "This Bounces";
static void bnc_test_meth_cb(rwmsg_request_t *req, void *ctx_in) {
fprintf(stderr, "inside bnc_test_meth_cb()\n");
return;
req = req;
ctx_in = ctx_in;
}
static void bnc_test_rsp_cb(rwmsg_request_t *req, void *ctx_in) {
ASSERT_TRUE(req->hdr.bnc);
fprintf(stderr, "inside bnc_test_rsp_cb()\n");
rwmsg_flowid_t fid = rwmsg_request_get_response_flowid(req);
#ifdef __RWMSG_BNC_RESPONSE_W_PAYLOAD
uint32_t len=0;
char *rsp = (char*)rwmsg_request_get_bnc_response_payload(req, &len);
rsp = rsp;
ASSERT_EQ(len, strlen(bnc_test_msg));
#endif
return;
req = req;
fid = fid;
ctx_in = ctx_in;
}
typedef struct bnc_test_ud {
rwmsg_clichan_t *cc;
rwmsg_destination_t *dt;
uint32_t methno;
} bnc_test_ud_t;
#if 0
static void bnc_test_feedme(void *ctx_in, rwmsg_destination_t *dest, rwmsg_flowid_t flowid) {
}
#endif
static void bnc_test_rsp_cb_and_set_feedme(rwmsg_request_t *req, void *ctx_in) {
ASSERT_TRUE(req->hdr.bnc);
fprintf(stderr, "inside bnc_test_rsp_cb()\n");
rwmsg_flowid_t fid = rwmsg_request_get_response_flowid(req);
#if 0
bnc_test_ud_t *ud = (bnc_test_ud_t*)ctx_in;
rwmsg_closure_t cb = { };
cb.ud = NULL;
cb.feedme = bnc_test_feedme;
rw_status_t rs = rwmsg_clichan_feedme_callback(ud->cc, ud->dt, fid, &cb);
EXPECT_EQ(rs, RW_STATUS_SUCCESS);
#endif
#ifdef __RWMSG_BNC_RESPONSE_W_PAYLOAD
uint32_t len=0;
char *rsp = (char*)rwmsg_request_get_bnc_response_payload(req, &len);
rsp = rsp;
ASSERT_EQ(len, strlen(bnc_test_msg));
#endif
return;
req = req;
fid = fid;
ctx_in = ctx_in;
}
TEST(RWMsgBroker, AcceptSrvchanAndCliChanTOBnc) {
ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0);
nnchk();
TEST_DESCRIPTION("Tests accepting from a srvchan");
rwmsg_btenv_t tenv(3);
rwmsg_bool_t r;
rw_status_t rs;
//const char *taddr = "/L/GTEST/RWBRO/TESTAPP/PBSCF/100/3";
const char *taddr = "/L/GTEST/RWBRO/1";
/* Broker is tasklet 0 */
rwmsg_broker_t *bro1=NULL;
tenv.ti->rwsched_tasklet_info = tenv.tasklet[0];
rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, TRUE, tenv.ti, &bro1);
double loopwait = 0.1;
rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, NULL);
/* Srvchan is tasklet 3, attached to broker 0
* also bound to main rws queue to avoid CF/dispatch headachess
* This endpoint has bro_instid=0 */
rwmsg_endpoint_t *ep_s;
ep_s = rwmsg_endpoint_create(0, 1, 0, tenv.rwsched, tenv.tasklet[1], rwtrace_init(), NULL);
ASSERT_TRUE(ep_s != NULL);
/* Direct everything through the broker */
rwmsg_endpoint_set_property_int(ep_s, "/rwmsg/broker/shunt", 1);
rwmsg_srvchan_t *sc = rwmsg_srvchan_create(ep_s);
ASSERT_TRUE(sc != NULL);
const uint32_t methno = __LINE__;
/* Create the srvchan, bind a method */
rwmsg_signature_t *sig = rwmsg_signature_create(ep_s, RWMSG_PAYFMT_RAW, methno, RWMSG_PRIORITY_DEFAULT);
ASSERT_TRUE(sig);
int timeo = 50; // ms
if (RUNNING_ON_VALGRIND) {
timeo = timeo * 5;
}
rwmsg_signature_set_timeout(sig, timeo);
rwmsg_closure_t methcb;
methcb.request=bnc_test_meth_cb;
methcb.ud=ep_s;
rwmsg_method_t *meth = rwmsg_method_create(ep_s, taddr, sig, &methcb);
ASSERT_TRUE(meth != NULL);
rs = rwmsg_srvchan_add_method(sc, meth);
ASSERT_EQ(rs, RW_STATUS_SUCCESS);
/* Wait on binding the srvchan until after we've sent the initial
flurry of requests. Otherwise, our ++ and the request handler's
++ of some of the request count variables ABA-stomp each
other. */
rs = rwmsg_srvchan_bind_rwsched_queue(sc, rwsched_dispatch_get_main_queue(tenv.rwsched));
ASSERT_TRUE(rs == RW_STATUS_SUCCESS);
/* Create the clichan, add the method's signature */
/* Clichan is tasklet 2, attached to broker 1
* also bound to main rws queue to avoid CF/dispatch headaches
* This endpoint has bro_instid=1 */
rwmsg_endpoint_t *ep_c;
ep_c = rwmsg_endpoint_create(0, 2, 0, tenv.rwsched, tenv.tasklet[2], rwtrace_init(), NULL);
ASSERT_TRUE(ep_c != NULL);
/* Direct everything through the broker */
rwmsg_endpoint_set_property_int(ep_c, "/rwmsg/broker/shunt", 1);
/* Create a client channel pointing at the Test service's path.
* Instantiate a Test service client and connect this to the client
* channel.
*/
rwmsg_destination_t *dt = rwmsg_destination_create(ep_c, RWMSG_ADDRTYPE_UNICAST, taddr);
ASSERT_TRUE(dt != NULL);
rwmsg_clichan_t *cc = rwmsg_clichan_create(ep_c);
ASSERT_TRUE(cc != NULL);
rs = rwmsg_clichan_bind_rwsched_queue(cc, rwsched_dispatch_get_main_queue(tenv.rwsched));
rwmsg_broker_g.exitnow.neg_accepted = 0;
rwmsg_broker_g.exitnow.neg_freed = 0;
rwmsg_broker_g.exitnow.neg_freed_err = 0;
/* Should now accept, read hs, create broclichan, attach incoming accepted sk */
loopwait = 5;
rwsched_dispatch_main_until(tenv.tasklet[1], loopwait, &rwmsg_broker_g.exitnow.neg_freed);
ASSERT_GE(rwmsg_broker_g.exitnow.neg_accepted, 1);
ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1);
ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0);
rwmsg_request_t *req = rwmsg_request_create(cc);
rwmsg_request_set_signature(req, sig);
rwmsg_closure_t clicb;
clicb.request=bnc_test_rsp_cb;
clicb.ud=cc;
rwmsg_request_set_callback(req, &clicb);
rwmsg_request_set_payload(req, bnc_test_msg, strlen(bnc_test_msg));
/* Send it. The srvchan should more or less immediately run the
thing and the methcb will respond. */
rs = rwmsg_clichan_send(cc, dt, req);
loopwait = 1;
rwsched_dispatch_main_until(tenv.tasklet[2], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed);
// fprintf(stderr, "end dispatch_main 2\n");
ASSERT_GE(rwmsg_broker_g.exitnow.neg_accepted, 1);
ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1);
ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0);
#if 1
/* End clichan tasklet 1 */
rwmsg_clichan_halt(cc);
r = rwmsg_endpoint_halt_flush(ep_c, TRUE);
ASSERT_TRUE(r);
#endif
#if 1
/* End srvchan tasklet 2 */
rwmsg_signature_release(ep_s, sig);
rwmsg_method_release(ep_s, meth);
rwmsg_srvchan_halt(sc);
r = rwmsg_endpoint_halt_flush(ep_s, TRUE);
ASSERT_TRUE(r);
#endif
/* End broker */
r = rwmsg_broker_halt_sync(bro1);
ASSERT_TRUE(r);
ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0);
nnchk();
}
TEST(RWMsgBroker, AcceptSrvchanAndCliChanNoPeerBnc) {
ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0);
nnchk();
TEST_DESCRIPTION("Tests accepting from a srvchan");
rwmsg_btenv_t tenv(3);
rwmsg_bool_t r;
rw_status_t rs;
//const char *taddr = "/L/GTEST/RWBRO/TESTAPP/PBSCF/100/3";
const char *taddr = "/L/GTEST/RWBRO/1";
/* Broker is tasklet 0 */
rwmsg_broker_t *bro1=NULL;
tenv.ti->rwsched_tasklet_info = tenv.tasklet[0];
rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, TRUE, tenv.ti, &bro1);
double loopwait = 0.1;
rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, NULL);
/* Srvchan is tasklet 3, attached to broker 0
* also bound to main rws queue to avoid CF/dispatch headachess
* This endpoint has bro_instid=0 */
rwmsg_endpoint_t *ep_s;
ep_s = rwmsg_endpoint_create(0, 1, 0, tenv.rwsched, tenv.tasklet[1], rwtrace_init(), NULL);
ASSERT_TRUE(ep_s != NULL);
/* Direct everything through the broker */
rwmsg_endpoint_set_property_int(ep_s, "/rwmsg/broker/shunt", 1);
rwmsg_srvchan_t *sc = rwmsg_srvchan_create(ep_s);
ASSERT_TRUE(sc != NULL);
const uint32_t methno = __LINE__;
/* Create the srvchan, bind a method */
rwmsg_signature_t *sig = rwmsg_signature_create(ep_s, RWMSG_PAYFMT_RAW, methno, RWMSG_PRIORITY_DEFAULT);
ASSERT_TRUE(sig);
int timeo = 1000; // ms
if (RUNNING_ON_VALGRIND) {
timeo = timeo * 5;
}
rwmsg_signature_set_timeout(sig, timeo);
rwmsg_closure_t methcb;
methcb.request=bnc_test_meth_cb;
methcb.ud=ep_s;
rwmsg_method_t *meth = rwmsg_method_create(ep_s, taddr, sig, &methcb);
ASSERT_TRUE(meth != NULL);
rs = rwmsg_srvchan_add_method(sc, meth);
ASSERT_EQ(rs, RW_STATUS_SUCCESS);
/* Wait on binding the srvchan until after we've sent the initial
flurry of requests. Otherwise, our ++ and the request handler's
++ of some of the request count variables ABA-stomp each
other. */
rs = rwmsg_srvchan_bind_rwsched_queue(sc, rwsched_dispatch_get_main_queue(tenv.rwsched));
ASSERT_TRUE(rs == RW_STATUS_SUCCESS);
/* Create the clichan, add the method's signature */
/* Clichan is tasklet 2, attached to broker 1
* also bound to main rws queue to avoid CF/dispatch headaches
* This endpoint has bro_instid=1 */
rwmsg_endpoint_t *ep_c;
ep_c = rwmsg_endpoint_create(0, 2, 0, tenv.rwsched, tenv.tasklet[2], rwtrace_init(), NULL);
ASSERT_TRUE(ep_c != NULL);
/* Direct everything through the broker */
rwmsg_endpoint_set_property_int(ep_c, "/rwmsg/broker/shunt", 1);
/* Create a client channel pointing at the Test service's path.
* Instantiate a Test service client and connect this to the client
* channel.
*/
rwmsg_destination_t *dt = rwmsg_destination_create(ep_c, RWMSG_ADDRTYPE_UNICAST, taddr);
ASSERT_TRUE(dt != NULL);
rwmsg_clichan_t *cc = rwmsg_clichan_create(ep_c);
ASSERT_TRUE(cc != NULL);
rs = rwmsg_clichan_bind_rwsched_queue(cc, rwsched_dispatch_get_main_queue(tenv.rwsched));
rwmsg_broker_g.exitnow.neg_accepted = 0;
rwmsg_broker_g.exitnow.neg_freed = 0;
rwmsg_broker_g.exitnow.neg_freed_err = 0;
/* Should now accept, read hs, create broclichan, attach incoming accepted sk */
loopwait = 5;
rwsched_dispatch_main_until(tenv.tasklet[1], loopwait, &rwmsg_broker_g.exitnow.neg_freed);
ASSERT_GE(rwmsg_broker_g.exitnow.neg_accepted, 1);
ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1);
ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0);
rwmsg_signature_t *sig_bad = rwmsg_signature_create(ep_c, RWMSG_PAYFMT_RAW, methno+666, RWMSG_PRIORITY_DEFAULT);
ASSERT_TRUE(sig_bad);
rwmsg_request_t *req = rwmsg_request_create(cc);
rwmsg_request_set_signature(req, sig_bad);
rwmsg_closure_t clicb;
clicb.request=bnc_test_rsp_cb;
clicb.ud=cc;
rwmsg_request_set_callback(req, &clicb);
rwmsg_request_set_payload(req, bnc_test_msg, strlen(bnc_test_msg));
/* Send it. The srvchan should more or less immediately run the
thing and the methcb will respond. */
rs = rwmsg_clichan_send(cc, dt, req);
loopwait = 1;
rwsched_dispatch_main_until(tenv.tasklet[2], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed);
// fprintf(stderr, "end dispatch_main 2\n");
ASSERT_GE(rwmsg_broker_g.exitnow.neg_accepted, 1);
ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1);
ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0);
#if 1
/* End clichan tasklet 1 */
rwmsg_signature_release(ep_c, sig_bad);
rwmsg_clichan_halt(cc);
r = rwmsg_endpoint_halt_flush(ep_c, TRUE);
ASSERT_TRUE(r);
#endif
#if 1
/* End srvchan tasklet 2 */
rwmsg_signature_release(ep_s, sig);
rwmsg_method_release(ep_s, meth);
rwmsg_srvchan_halt(sc);
r = rwmsg_endpoint_halt_flush(ep_s, TRUE);
ASSERT_TRUE(r);
#endif
/* End broker */
r = rwmsg_broker_halt_sync(bro1);
ASSERT_TRUE(r);
ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0);
nnchk();
}
TEST(RWMsgBroker, AcceptSrvchanAndCliChanTestFlowCtrlHint) {
ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0);
nnchk();
TEST_DESCRIPTION("Tests accepting from a srvchan");
rwmsg_btenv_t tenv(3);
rwmsg_bool_t r;
rw_status_t rs;
//const char *taddr = "/L/GTEST/RWBRO/TESTAPP/PBSCF/100/3";
const char *taddr = "/L/GTEST/RWBRO/1";
/* Broker is tasklet 0 */
rwmsg_broker_t *bro1=NULL;
tenv.ti->rwsched_tasklet_info = tenv.tasklet[0];
rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, TRUE, tenv.ti, &bro1);
double loopwait = 0.1;
rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, NULL);
/* Srvchan is tasklet 3, attached to broker 0
* also bound to main rws queue to avoid CF/dispatch headachess
* This endpoint has bro_instid=0 */
rwmsg_endpoint_t *ep_s;
ep_s = rwmsg_endpoint_create(0, 1, 0, tenv.rwsched, tenv.tasklet[1], rwtrace_init(), NULL);
ASSERT_TRUE(ep_s != NULL);
/* Direct everything through the broker */
rwmsg_endpoint_set_property_int(ep_s, "/rwmsg/broker/shunt", 1);
rwmsg_srvchan_t *sc = rwmsg_srvchan_create(ep_s);
ASSERT_TRUE(sc != NULL);
const uint32_t methno = __LINE__;
/* Create the srvchan, bind a method */
rwmsg_signature_t *sig = rwmsg_signature_create(ep_s, RWMSG_PAYFMT_RAW, methno, RWMSG_PRIORITY_DEFAULT);
ASSERT_TRUE(sig);
int timeo = 50; // ms
if (RUNNING_ON_VALGRIND) {
timeo = timeo * 5;
}
rwmsg_signature_set_timeout(sig, timeo);
rwmsg_closure_t methcb;
methcb.request=bnc_test_meth_cb;
methcb.ud=ep_s;
rwmsg_method_t *meth = rwmsg_method_create(ep_s, taddr, sig, &methcb);
ASSERT_TRUE(meth != NULL);
rs = rwmsg_srvchan_add_method(sc, meth);
ASSERT_EQ(rs, RW_STATUS_SUCCESS);
/* Wait on binding the srvchan until after we've sent the initial
flurry of requests. Otherwise, our ++ and the request handler's
++ of some of the request count variables ABA-stomp each
other. */
rs = rwmsg_srvchan_bind_rwsched_queue(sc, rwsched_dispatch_get_main_queue(tenv.rwsched));
ASSERT_TRUE(rs == RW_STATUS_SUCCESS);
/* Create the clichan, add the method's signature */
/* Clichan is tasklet 2, attached to broker 1
* also bound to main rws queue to avoid CF/dispatch headaches
* This endpoint has bro_instid=1 */
rwmsg_endpoint_t *ep_c;
ep_c = rwmsg_endpoint_create(0, 2, 0, tenv.rwsched, tenv.tasklet[2], rwtrace_init(), NULL);
ASSERT_TRUE(ep_c != NULL);
/* Direct everything through the broker */
rwmsg_endpoint_set_property_int(ep_c, "/rwmsg/broker/shunt", 1);
/* Create a client channel pointing at the Test service's path.
* Instantiate a Test service client and connect this to the client
* channel.
*/
rwmsg_destination_t *dt = rwmsg_destination_create(ep_c, RWMSG_ADDRTYPE_UNICAST, taddr);
ASSERT_TRUE(dt != NULL);
rwmsg_clichan_t *cc = rwmsg_clichan_create(ep_c);
ASSERT_TRUE(cc != NULL);
rs = rwmsg_clichan_bind_rwsched_queue(cc, rwsched_dispatch_get_main_queue(tenv.rwsched));
rwmsg_broker_g.exitnow.neg_accepted = 0;
rwmsg_broker_g.exitnow.neg_freed = 0;
rwmsg_broker_g.exitnow.neg_freed_err = 0;
/* Should now accept, read hs, create broclichan, attach incoming accepted sk */
loopwait = 5;
rwsched_dispatch_main_until(tenv.tasklet[1], loopwait, &rwmsg_broker_g.exitnow.neg_freed);
ASSERT_GE(rwmsg_broker_g.exitnow.neg_accepted, 1);
ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1);
ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0);
rwmsg_request_t *req = rwmsg_request_create(cc);
rwmsg_request_set_signature(req, sig);
rwmsg_closure_t clicb;
clicb.request=bnc_test_rsp_cb_and_set_feedme;
bnc_test_ud_t *ud = (bnc_test_ud_t *) malloc(sizeof(*ud));
ud->cc = cc;
ud->dt = dt;
ud->methno = methno;
clicb.ud=ud;
rwmsg_request_set_callback(req, &clicb);
rwmsg_request_set_payload(req, bnc_test_msg, strlen(bnc_test_msg));
ASSERT_NE(rwmsg_clichan_can_send_howmuch(cc, dt, methno, RWMSG_PAYFMT_RAW), 0);
/* Send it. The srvchan should more or less immediately run the
thing and the methcb will respond. */
rs = rwmsg_clichan_send(cc, dt, req);
loopwait = 1;
rwsched_dispatch_main_until(tenv.tasklet[2], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed);
// fprintf(stderr, "end dispatch_main 2\n");
ASSERT_GE(rwmsg_broker_g.exitnow.neg_accepted, 1);
ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1);
ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0);
#if 1
/* End clichan tasklet 1 */
rwmsg_clichan_halt(cc);
r = rwmsg_endpoint_halt_flush(ep_c, TRUE);
ASSERT_TRUE(r);
#endif
#if 1
/* End srvchan tasklet 2 */
rwmsg_signature_release(ep_s, sig);
rwmsg_method_release(ep_s, meth);
rwmsg_srvchan_halt(sc);
r = rwmsg_endpoint_halt_flush(ep_s, TRUE);
ASSERT_TRUE(r);
#endif
/* End broker */
r = rwmsg_broker_halt_sync(bro1);
ASSERT_TRUE(r);
ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0);
nnchk();
}
TEST(RWMsgBroker, CloseSrvChanW1Bro) {
uint32_t start_reqct = rwmsg_global.status.request_ct;
ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0);
nnchk();
TEST_DESCRIPTION("Tests accepting from a srvchan");
rwmsg_btenv_t tenv(3);
rwmsg_bool_t r;
rw_status_t rs;
//const char *taddr = "/L/GTEST/RWBRO/TESTAPP/PBSCF/100/3";
const char *taddr = "/L/GTEST/RWBRO/1";
/* Broker is tasklet 0 */
rwmsg_broker_t *bro1=NULL;
tenv.ti->rwsched_tasklet_info = tenv.tasklet[0];
rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, TRUE, tenv.ti, &bro1);
double loopwait = 0.1;
rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, NULL);
/* Srvchan is tasklet 3, attached to broker 0
* also bound to main rws queue to avoid CF/dispatch headachess
* This endpoint has bro_instid=0 */
rwmsg_endpoint_t *ep_s;
ep_s = rwmsg_endpoint_create(0, 1, 0, tenv.rwsched, tenv.tasklet[1], rwtrace_init(), NULL);
ASSERT_TRUE(ep_s != NULL);
/* Direct everything through the broker */
rwmsg_endpoint_set_property_int(ep_s, "/rwmsg/broker/shunt", 1);
rwmsg_srvchan_t *sc = rwmsg_srvchan_create(ep_s);
ASSERT_TRUE(sc != NULL);
Test_Service myapisrv;
TEST__INITSERVER(&myapisrv, Test_);
//rs = rwmsg_srvchan_add_service(sc, tpath, &myapisrv.base, &tenv.tasklet[3]);
rs = rwmsg_srvchan_add_service(sc, taddr, &myapisrv.base, &tenv.tasklet[1]);
ASSERT_EQ(rs, RW_STATUS_SUCCESS);
rs = rwmsg_srvchan_bind_rwsched_queue(sc, rwsched_dispatch_get_main_queue(tenv.rwsched));
ASSERT_TRUE(rs == RW_STATUS_SUCCESS);
rwmsg_broker_g.exitnow.neg_accepted = 0;
rwmsg_broker_g.exitnow.neg_freed = 0;
rwmsg_broker_g.exitnow.neg_freed_err = 0;
/* Should now accept, read hs, create broclichan, attach incoming accepted sk */
loopwait = 5;
rwsched_dispatch_main_until(tenv.tasklet[1], loopwait, &rwmsg_broker_g.exitnow.neg_freed);
ASSERT_GE(rwmsg_broker_g.exitnow.neg_accepted, 1);
ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1);
ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0);
/* Clichan is tasklet 2, attached to broker 1
* also bound to main rws queue to avoid CF/dispatch headaches
* This endpoint has bro_instid=1 */
rwmsg_endpoint_t *ep_c;
ep_c = rwmsg_endpoint_create(0, 2, 0, tenv.rwsched, tenv.tasklet[2], rwtrace_init(), NULL);
ASSERT_TRUE(ep_c != NULL);
/* Direct everything through the broker */
rwmsg_endpoint_set_property_int(ep_c, "/rwmsg/broker/shunt", 1);
/* Create a client channel pointing at the Test service's path.
* Instantiate a Test service client and connect this to the client
* channel.
*/
rwmsg_destination_t *dt;
//dt = rwmsg_destination_create(ep_c, RWMSG_ADDRTYPE_UNICAST, tpeerpath);
dt = rwmsg_destination_create(ep_c, RWMSG_ADDRTYPE_UNICAST, taddr);
ASSERT_TRUE(dt != NULL);
rwmsg_clichan_t *cc = rwmsg_clichan_create(ep_c);
ASSERT_TRUE(cc != NULL);
rs = rwmsg_clichan_bind_rwsched_queue(cc, rwsched_dispatch_get_main_queue(tenv.rwsched));
Test_Client mycli;
TEST__INITCLIENT(&mycli);
rwmsg_clichan_add_service(cc, &mycli.base);
/* Should now accept, read hs, create broclichan, attach incoming accepted sk */
loopwait = 2;
rwsched_dispatch_main_until(tenv.tasklet[2], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed);
TestReq req;
rwmsg_request_t *rwreq=NULL;
test_req__init(&req);
// fprintf(stderr, "test__increment - 01\n");
rwmsg_closure_t cb;
cb.pbrsp=(rwmsg_pbapi_cb)multibrocfb_response;
cb.ud=tenv.tasklet[2];
for (int i=0; i<5; i++) {
rs = test__increment(&mycli, dt, &req, &cb, &rwreq);
ASSERT_EQ(rs, RW_STATUS_SUCCESS);
}
// fprintf(stderr, "end dispatch_main 1\n");
loopwait = 1;
rwsched_dispatch_main_until(tenv.tasklet[2], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed);
// fprintf(stderr, "end dispatch_main 2\n");
ASSERT_GE(rwmsg_broker_g.exitnow.neg_accepted, 1);
ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1);
ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0);
#if 1
/* End srvchan tasklet 2 */
rwmsg_srvchan_halt(sc);
r = rwmsg_endpoint_halt_flush(ep_s, TRUE);
ASSERT_TRUE(r);
#endif
int sent_N_after_srvr_close = 10;
for (int i=0; i<sent_N_after_srvr_close; i++) {
rs = test__increment(&mycli, dt, &req, &cb, &rwreq);
ASSERT_EQ(rs, RW_STATUS_SUCCESS);
}
loopwait = 1;
rwsched_dispatch_main_until(tenv.tasklet[2], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed);
#if 1
/* End clichan tasklet 1 */
rwmsg_clichan_halt(cc);
r = rwmsg_endpoint_halt_flush(ep_c, TRUE);
ASSERT_TRUE(r);
#endif
loopwait = 1;
rwsched_dispatch_main_until(tenv.tasklet[2], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed);
/* End broker */
r = rwmsg_broker_halt_sync(bro1);
ASSERT_TRUE(r);
ASSERT_LE(start_reqct+sent_N_after_srvr_close, rwmsg_global.status.request_ct);
ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0);
nnchk();
}
TEST(RWMsgBroker, AcceptSrvchanAndCliChanAndSndBlkW1Bro) {
ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0);
nnchk();
TEST_DESCRIPTION("Tests accepting from a srvchan");
rwmsg_btenv_t tenv(3);
rwmsg_bool_t r;
rw_status_t rs;
//const char *taddr = "/L/GTEST/RWBRO/TESTAPP/PBSCF/100/3";
const char *taddr = "/L/GTEST/RWBRO/1";
/* Broker is tasklet 0 */
rwmsg_broker_t *bro1=NULL;
tenv.ti->rwsched_tasklet_info = tenv.tasklet[0];
rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, TRUE, tenv.ti, &bro1);
double loopwait = 0.1;
rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, NULL);
/* Srvchan is tasklet 3, attached to broker 0
* also bound to main rws queue to avoid CF/dispatch headachess
* This endpoint has bro_instid=0 */
rwmsg_endpoint_t *ep_s;
ep_s = rwmsg_endpoint_create(0, 1, 0, tenv.rwsched, tenv.tasklet[1], rwtrace_init(), NULL);
ASSERT_TRUE(ep_s != NULL);
/* Direct everything through the broker */
rwmsg_endpoint_set_property_int(ep_s, "/rwmsg/broker/shunt", 1);
rwmsg_srvchan_t *sc = rwmsg_srvchan_create(ep_s);
ASSERT_TRUE(sc != NULL);
Test_Service myapisrv;
TEST__INITSERVER(&myapisrv, Test_);
//rs = rwmsg_srvchan_add_service(sc, tpath, &myapisrv.base, &tenv.tasklet[3]);
rs = rwmsg_srvchan_add_service(sc, taddr, &myapisrv.base, &tenv.tasklet[1]);
ASSERT_EQ(rs, RW_STATUS_SUCCESS);
//rs = rwmsg_srvchan_bind_rwsched_queue(sc, rwsched_dispatch_get_main_queue(tenv.rwsched));
rs = rwmsg_srvchan_bind_rwsched_cfrunloop(sc, tenv.tasklet[1]);
ASSERT_TRUE(rs == RW_STATUS_SUCCESS);
/* Clichan is tasklet 2, attached to broker 1
* also bound to main rws queue to avoid CF/dispatch headaches
* This endpoint has bro_instid=1 */
rwmsg_endpoint_t *ep_c;
ep_c = rwmsg_endpoint_create(0, 2, 0, tenv.rwsched, tenv.tasklet[2], rwtrace_init(), NULL);
ASSERT_TRUE(ep_c != NULL);
/* Direct everything through the broker */
rwmsg_endpoint_set_property_int(ep_c, "/rwmsg/broker/shunt", 1);
/* Create a client channel pointing at the Test service's path.
* Instantiate a Test service client and connect this to the client
* channel.
*/
rwmsg_destination_t *dt;
//dt = rwmsg_destination_create(ep_c, RWMSG_ADDRTYPE_UNICAST, tpeerpath);
dt = rwmsg_destination_create(ep_c, RWMSG_ADDRTYPE_UNICAST, taddr);
ASSERT_TRUE(dt != NULL);
rwmsg_clichan_t *cc = rwmsg_clichan_create(ep_c);
ASSERT_TRUE(cc != NULL);
//rs = rwmsg_clichan_bind_rwsched_queue(cc, rwsched_dispatch_get_main_queue(tenv.rwsched));
rs = rwmsg_clichan_bind_rwsched_cfrunloop(cc, tenv.tasklet[2]);
Test_Client mycli;
TEST__INITCLIENT(&mycli);
rwmsg_clichan_add_service(cc, &mycli.base);
/* Should now accept, read hs, create broclichan, attach incoming accepted sk */
rwsched_instance_CFRunLoopRunInMode(tenv.rwsched, RWMSG_RUNLOOP_MODE, 1, FALSE);
TestReq req;
rwmsg_request_t *rwreq=NULL;
test_req__init(&req);
// fprintf(stderr, "test__increment - 01\n");
rs = test__increment_b(&mycli, dt, &req, &rwreq);
ASSERT_EQ(rs, RW_STATUS_SUCCESS);
// fprintf(stderr, "end dispatch_main 1\n");
rwsched_instance_CFRunLoopRunInMode(tenv.rwsched, RWMSG_RUNLOOP_MODE, 1, FALSE);
// fprintf(stderr, "end dispatch_main 2\n");
ASSERT_GE(rwmsg_broker_g.exitnow.neg_accepted, 1);
ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1);
ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0);
/* End clichan tasklet 1 */
rwmsg_clichan_halt(cc);
r = rwmsg_endpoint_halt_flush(ep_c, TRUE);
ASSERT_TRUE(r);
/* End srvchan tasklet 2 */
rwmsg_srvchan_halt(sc);
r = rwmsg_endpoint_halt_flush(ep_s, TRUE);
ASSERT_TRUE(r);
/* End broker */
r = rwmsg_broker_halt_sync(bro1);
ASSERT_TRUE(r);
ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0);
nnchk();
}
TEST(RWMsgBroker, AcceptSrvchanAndCliChanAndSndNonConnDontQW1Bro_LONG) {
ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0);
nnchk();
TEST_DESCRIPTION("Tests accepting from a srvchan");
rwmsg_btenv_t tenv(3);
rwmsg_bool_t r;
rw_status_t rs;
//const char *taddr = "/L/GTEST/RWBRO/TESTAPP/PBSCF/100/3";
const char *taddr = "/L/GTEST/RWBRO/1";
/* Clichan is tasklet 2, attached to broker 1
* also bound to main rws queue to avoid CF/dispatch headaches
* This endpoint has bro_instid=1 */
rwmsg_endpoint_t *ep_c;
ep_c = rwmsg_endpoint_create(0, 2, 0, tenv.rwsched, tenv.tasklet[2], rwtrace_init(), NULL);
ASSERT_TRUE(ep_c != NULL);
/* Direct everything through the broker */
rwmsg_endpoint_set_property_int(ep_c, "/rwmsg/broker/shunt", 1);
/* Create a client channel pointing at the Test service's path.
* Instantiate a Test service client and connect this to the client
* channel.
*/
rwmsg_destination_t *dt;
//dt = rwmsg_destination_create(ep_c, RWMSG_ADDRTYPE_UNICAST, tpeerpath);
dt = rwmsg_destination_create(ep_c, RWMSG_ADDRTYPE_UNICAST, taddr);
ASSERT_TRUE(dt != NULL);
rwmsg_clichan_t *cc = rwmsg_clichan_create(ep_c);
ASSERT_TRUE(cc != NULL);
//rs = rwmsg_clichan_bind_rwsched_queue(cc, rwsched_dispatch_get_main_queue(tenv.rwsched));
rs = rwmsg_clichan_bind_rwsched_cfrunloop(cc, tenv.tasklet[2]);
Test_Client mycli;
TEST__INITCLIENT(&mycli);
rwmsg_clichan_add_service(cc, &mycli.base);
/* Should now accept, read hs, create broclichan, attach incoming accepted sk */
rwsched_instance_CFRunLoopRunInMode(tenv.rwsched, RWMSG_RUNLOOP_MODE, 1, FALSE);
{
TestReq req;
rwmsg_request_t *rwreq=NULL;
test_req__init(&req);
rwmsg_closure_t cb;
cb.pbrsp=(rwmsg_pbapi_cb)multibrocfb_response;
cb.ud=tenv.tasklet[1];
//dt->noconndontq = 1;
rwmsg_destination_set_noconndontq(dt);
rs = test__increment(&mycli, dt, &req, &cb, &rwreq);
ASSERT_EQ(rs, RW_STATUS_NOTCONNECTED);
//dt->noconndontq = 0;
rwmsg_destination_unset_noconndontq(dt);
rs = test__increment(&mycli, dt, &req, &cb, &rwreq);
ASSERT_EQ(rs, RW_STATUS_SUCCESS);
}
// fprintf(stderr, "end dispatch_main 1\n");
rwsched_instance_CFRunLoopRunInMode(tenv.rwsched, RWMSG_RUNLOOP_MODE, 1, FALSE);
/* Broker is tasklet 0 */
rwmsg_broker_t *bro1=NULL;
tenv.ti->rwsched_tasklet_info = tenv.tasklet[0];
rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, TRUE, tenv.ti, &bro1);
double loopwait = 0.1;
rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, NULL);
/* Srvchan is tasklet 3, attached to broker 0
* also bound to main rws queue to avoid CF/dispatch headachess
* This endpoint has bro_instid=0 */
rwmsg_endpoint_t *ep_s;
ep_s = rwmsg_endpoint_create(0, 1, 0, tenv.rwsched, tenv.tasklet[1], rwtrace_init(), NULL);
ASSERT_TRUE(ep_s != NULL);
/* Direct everything through the broker */
rwmsg_endpoint_set_property_int(ep_s, "/rwmsg/broker/shunt", 1);
rwmsg_srvchan_t *sc = rwmsg_srvchan_create(ep_s);
ASSERT_TRUE(sc != NULL);
Test_Service myapisrv;
TEST__INITSERVER(&myapisrv, Test_);
//rs = rwmsg_srvchan_add_service(sc, tpath, &myapisrv.base, &tenv.tasklet[3]);
rs = rwmsg_srvchan_add_service(sc, taddr, &myapisrv.base, &tenv.tasklet[1]);
ASSERT_EQ(rs, RW_STATUS_SUCCESS);
//rs = rwmsg_srvchan_bind_rwsched_queue(sc, rwsched_dispatch_get_main_queue(tenv.rwsched));
rs = rwmsg_srvchan_bind_rwsched_cfrunloop(sc, tenv.tasklet[1]);
ASSERT_TRUE(rs == RW_STATUS_SUCCESS);
{
TestReq req;
rwmsg_request_t *rwreq=NULL;
test_req__init(&req);
rwmsg_closure_t cb;
cb.pbrsp=(rwmsg_pbapi_cb)multibrocfb_response;
cb.ud=tenv.tasklet[1];
rs = test__increment(&mycli, dt, &req, &cb, &rwreq);
ASSERT_EQ(rs, RW_STATUS_SUCCESS);
}
// fprintf(stderr, "end dispatch_main 2\n");
rwsched_instance_CFRunLoopRunInMode(tenv.rwsched, RWMSG_RUNLOOP_MODE, 1, FALSE);
ASSERT_GE(rwmsg_broker_g.exitnow.neg_accepted, 1);
ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1);
ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0);
/* End clichan tasklet 1 */
rwmsg_clichan_halt(cc);
r = rwmsg_endpoint_halt_flush(ep_c, TRUE);
ASSERT_TRUE(r);
/* End srvchan tasklet 2 */
rwmsg_srvchan_halt(sc);
r = rwmsg_endpoint_halt_flush(ep_s, TRUE);
ASSERT_TRUE(r);
/* End broker */
r = rwmsg_broker_halt_sync(bro1);
ASSERT_TRUE(r);
ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0);
nnchk();
}
TEST(RWMsgBroker, AcceptSrvchanAndCliChanOnSame2Bros_LONG) {
ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0);
nnchk();
TEST_DESCRIPTION("Tests accepting from a srvchan");
rwmsg_btenv_t tenv(4);
rwmsg_bool_t r;
rw_status_t rs;
const char *taddr = "/L/GTEST/RWBRO/1";
/* Broker is tasklet 0 */
rwmsg_broker_t *bro1=NULL;
tenv.ti->rwsched_tasklet_info = tenv.tasklet[0];
rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, TRUE, tenv.ti, &bro1);
/* Broker is tasklet 2 */
rwmsg_broker_t *bro2=NULL;
tenv.ti->rwsched_tasklet_info = tenv.tasklet[2];
rwmsg_broker_main(broport_g, 2, 1, tenv.rwsched, tenv.tasklet[2], tenv.rwcal, TRUE, tenv.ti, &bro2);
double loopwait = 0.1;
int loopcount = 0;
uint32_t meshcount = 5*2*(2-1); //==5*2*n*(n-1)/2 == 10
/* Should now accept and ultimately timeout in the broker's acceptor */
//rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, &rwmsg_broker_g.exitnow.acc_listening);
while (rwmsg_broker_g.exitnow.neg_accepted<meshcount && loopcount++<200) {
usleep(50*1000); // 50ms
rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, NULL);
}
ASSERT_EQ(rwmsg_broker_g.exitnow.neg_accepted, meshcount);
ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0);
/* Srvchan is tasklet 3, attached to broker 0
* also bound to main rws queue to avoid CF/dispatch headachess
* This endpoint has bro_instid=0 */
rwmsg_endpoint_t *ep_s;
ep_s = rwmsg_endpoint_create(0, 3, 1, tenv.rwsched, tenv.tasklet[3], rwtrace_init(), NULL);
ASSERT_TRUE(ep_s != NULL);
// fprintf(stderr, "\nSrvchan-to-bro-1\n");
/* Direct everything through the broker */
rwmsg_endpoint_set_property_int(ep_s, "/rwmsg/broker/shunt", 1);
rwmsg_srvchan_t *sc = rwmsg_srvchan_create(ep_s);
ASSERT_TRUE(sc != NULL);
Test_Service myapisrv;
TEST__INITSERVER(&myapisrv, Test_);
rs = rwmsg_srvchan_add_service(sc, taddr, &myapisrv.base, &tenv.tasklet[3]);
ASSERT_EQ(rs, RW_STATUS_SUCCESS);
rs = rwmsg_srvchan_bind_rwsched_queue(sc, rwsched_dispatch_get_main_queue(tenv.rwsched));
ASSERT_TRUE(rs == RW_STATUS_SUCCESS);
rwmsg_broker_g.exitnow.neg_accepted = 0;
rwmsg_broker_g.exitnow.neg_freed = 0;
rwmsg_broker_g.exitnow.neg_freed_err = 0;
/* Should now accept, read hs, create broclichan, attach incoming accepted sk */
loopwait = 2;
rwsched_dispatch_main_until(tenv.tasklet[3], loopwait, &rwmsg_broker_g.exitnow.neg_freed);
ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1);
ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0);
#if 1
// fprintf(stderr, "\ntest__increment - clican-to-bro-1\n");
rwmsg_broker_g.exitnow.neg_accepted = 0;
rwmsg_broker_g.exitnow.neg_freed = 0;
rwmsg_broker_g.exitnow.neg_freed_err = 0;
/* Clichan is tasklet 1, attached to broker 1
* also bound to main rws queue to avoid CF/dispatch headaches
* This endpoint has bro_instid=1 */
rwmsg_endpoint_t *ep_c_b0;
ep_c_b0 = rwmsg_endpoint_create(0, 1, 1, tenv.rwsched, tenv.tasklet[1], rwtrace_init(), NULL);
ASSERT_TRUE(ep_c_b0 != NULL);
/* Direct everything through the broker */
rwmsg_endpoint_set_property_int(ep_c_b0, "/rwmsg/broker/shunt", 1);
/* Create a client channel pointing at the Test service's path.
* Instantiate a Test service client and connect this to the client
* channel.
*/
rwmsg_destination_t *dt;
//dt = rwmsg_destination_create(ep_c_b0, RWMSG_ADDRTYPE_UNICAST, tpeerpath);
dt = rwmsg_destination_create(ep_c_b0, RWMSG_ADDRTYPE_UNICAST, taddr);
ASSERT_TRUE(dt != NULL);
rwmsg_clichan_t *cc0 = rwmsg_clichan_create(ep_c_b0);
ASSERT_TRUE(cc0 != NULL);
rs = rwmsg_clichan_bind_rwsched_queue(cc0, rwsched_dispatch_get_main_queue(tenv.rwsched));
Test_Client mycli;
TEST__INITCLIENT(&mycli);
rwmsg_clichan_add_service(cc0, &mycli.base);
/* Should now accept, read hs, create broclichan, attach incoming accepted sk */
loopwait = 2;
rwsched_dispatch_main_until(tenv.tasklet[1], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed);
int i;
for (i=0; i<100; i++) {
TestReq req;
rwmsg_request_t *rwreq=NULL;
test_req__init(&req);
rwmsg_closure_t cb;
cb.pbrsp=(rwmsg_pbapi_cb)multibrocfb_response;
cb.ud=tenv.tasklet[1];
rs = test__increment(&mycli, dt, &req, &cb, &rwreq);
ASSERT_TRUE(rs==RW_STATUS_SUCCESS);
loopwait = 0.01;
rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed);
}
#endif
#if 1
/* End clichan tasklet 1 */
rwmsg_clichan_halt(cc0);
r = rwmsg_endpoint_halt_flush(ep_c_b0, TRUE);
ASSERT_TRUE(r);
#endif
#if 1
/* End srvchan tasklet 2 */
rwmsg_srvchan_halt(sc);
r = rwmsg_endpoint_halt_flush(ep_s, TRUE);
ASSERT_TRUE(r);
#endif
/* End broker */
r = rwmsg_broker_halt_sync(bro1);
ASSERT_TRUE(r);
r = rwmsg_broker_halt_sync(bro2);
ASSERT_TRUE(r);
ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0);
nnchk();
}
TEST(RWMsgBroker, AcceptSrvchanAndCliChanAndSndBlkOnSame2Bros_LONG) {
ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0);
nnchk();
TEST_DESCRIPTION("Tests accepting from a srvchan");
rwmsg_btenv_t tenv(4);
rwmsg_bool_t r;
rw_status_t rs;
const char *taddr = "/L/GTEST/RWBRO/1";
/* Broker is tasklet 0 */
rwmsg_broker_t *bro1=NULL;
tenv.ti->rwsched_tasklet_info = tenv.tasklet[0];
rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, TRUE, tenv.ti, &bro1);
/* Broker is tasklet 2 */
rwmsg_broker_t *bro2=NULL;
tenv.ti->rwsched_tasklet_info = tenv.tasklet[2];
rwmsg_broker_main(broport_g, 2, 1, tenv.rwsched, tenv.tasklet[2], tenv.rwcal, TRUE, tenv.ti, &bro2);
double loopwait = 0.1;
int loopcount = 0;
uint32_t meshcount = 5*2*(2-1); //==5*2*n*(n-1)/2 == 10
/* Should now accept and ultimately timeout in the broker's acceptor */
//rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, &rwmsg_broker_g.exitnow.acc_listening);
while (rwmsg_broker_g.exitnow.neg_accepted<meshcount && loopcount++<200) {
usleep(50*1000); // 50ms
rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, NULL);
}
ASSERT_EQ(rwmsg_broker_g.exitnow.neg_accepted, meshcount);
ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0);
/* Srvchan is tasklet 3, attached to broker 0
* also bound to main rws queue to avoid CF/dispatch headachess
* This endpoint has bro_instid=0 */
rwmsg_endpoint_t *ep_s;
ep_s = rwmsg_endpoint_create(0, 3, 1, tenv.rwsched, tenv.tasklet[3], rwtrace_init(), NULL);
ASSERT_TRUE(ep_s != NULL);
// fprintf(stderr, "\nSrvchan-to-bro-1\n");
/* Direct everything through the broker */
rwmsg_endpoint_set_property_int(ep_s, "/rwmsg/broker/shunt", 1);
rwmsg_srvchan_t *sc = rwmsg_srvchan_create(ep_s);
ASSERT_TRUE(sc != NULL);
Test_Service myapisrv;
TEST__INITSERVER(&myapisrv, Test_);
rs = rwmsg_srvchan_add_service(sc, taddr, &myapisrv.base, &tenv.tasklet[3]);
ASSERT_EQ(rs, RW_STATUS_SUCCESS);
//rs = rwmsg_srvchan_bind_rwsched_queue(sc, rwsched_dispatch_get_main_queue(tenv.rwsched));
rs = rwmsg_srvchan_bind_rwsched_cfrunloop(sc, tenv.tasklet[3]);
ASSERT_TRUE(rs == RW_STATUS_SUCCESS);
/* Clichan is tasklet 1, attached to broker 1
* also bound to main rws queue to avoid CF/dispatch headaches
* This endpoint has bro_instid=1 */
rwmsg_endpoint_t *ep_c;
ep_c = rwmsg_endpoint_create(0, 1, 1, tenv.rwsched, tenv.tasklet[1], rwtrace_init(), NULL);
ASSERT_TRUE(ep_c != NULL);
/* Direct everything through the broker */
rwmsg_endpoint_set_property_int(ep_c, "/rwmsg/broker/shunt", 1);
/* Create a client channel pointing at the Test service's path.
* Instantiate a Test service client and connect this to the client
* channel.
*/
rwmsg_destination_t *dt;
//dt = rwmsg_destination_create(ep_c, RWMSG_ADDRTYPE_UNICAST, tpeerpath);
dt = rwmsg_destination_create(ep_c, RWMSG_ADDRTYPE_UNICAST, taddr);
ASSERT_TRUE(dt != NULL);
rwmsg_clichan_t *cc = rwmsg_clichan_create(ep_c);
ASSERT_TRUE(cc != NULL);
//rs = rwmsg_clichan_bind_rwsched_queue(cc, rwsched_dispatch_get_main_queue(tenv.rwsched));
rs = rwmsg_clichan_bind_rwsched_cfrunloop(cc, tenv.tasklet[1]);
ASSERT_TRUE(rs == RW_STATUS_SUCCESS);
Test_Client mycli;
TEST__INITCLIENT(&mycli);
rwmsg_clichan_add_service(cc, &mycli.base);
/* Should now accept, read hs, create broclichan, attach incoming accepted sk */
rwsched_instance_CFRunLoopRunInMode(tenv.rwsched, RWMSG_RUNLOOP_MODE, 1, FALSE);
for (int i=0; i<100; i++) {
TestReq req;
rwmsg_request_t *rwreq=NULL;
test_req__init(&req);
#if 0
rs = test__increment_b(&mycli, dt, &req, &rwreq);
ASSERT_TRUE(rs==RW_STATUS_SUCCESS);
#else
req.body.value = i+5;
req.body.hopct = i+5;
rs = test__increment_b(&mycli, dt, &req, &rwreq);
ASSERT_EQ(rs, RW_STATUS_SUCCESS);
ASSERT_EQ(RWMSG_PAYFMT_PBAPI, rwmsg_request_get_response_payfmt(rwreq));
const TestRsp *rsp;
rs = rwmsg_request_get_response(rwreq, (const void **)&rsp);
ASSERT_EQ(rs, RW_STATUS_SUCCESS);
// fprintf(stderr, "ProtobufCliSrvCFBlocking test got rsp, errval=%u, burst i=%u\n", rsp->errval, i);
multibrocfb_response(rsp, rwreq, tenv.tasklet[1]);
#endif
}
for (int i=0; i<10; i++) {
TestReq req;
rwmsg_request_t *rwreq=NULL;
test_req__init(&req);
rs = test__increment_b(&mycli, dt, &req, &rwreq);
ASSERT_TRUE(rs==RW_STATUS_SUCCESS);
}
rwsched_instance_CFRunLoopRunInMode(tenv.rwsched, RWMSG_RUNLOOP_MODE, 1, FALSE);
/* End clichan tasklet 1 */
rwmsg_clichan_halt(cc);
r = rwmsg_endpoint_halt_flush(ep_c, TRUE);
ASSERT_TRUE(r);
/* End srvchan tasklet 2 */
rwmsg_srvchan_halt(sc);
r = rwmsg_endpoint_halt_flush(ep_s, TRUE);
ASSERT_TRUE(r);
/* End broker */
r = rwmsg_broker_halt_sync(bro1);
ASSERT_TRUE(r);
r = rwmsg_broker_halt_sync(bro2);
ASSERT_TRUE(r);
ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0);
nnchk();
}
TEST(RWMsgBroker, AcceptSrvchanAndCliChanOnSeperate2Bros_LONG) {
ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0);
nnchk();
TEST_DESCRIPTION("Tests accepting from a srvchan");
rwmsg_btenv_t tenv(4);
rwmsg_bool_t r;
rw_status_t rs;
const char *taddr = "/L/GTEST/RWBRO/1";
/* Broker is tasklet 0 */
rwmsg_broker_t *bro1=NULL;
tenv.ti->rwsched_tasklet_info = tenv.tasklet[0];
rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, TRUE, tenv.ti, &bro1);
/* Broker is tasklet 2 */
rwmsg_broker_t *bro2=NULL;
tenv.ti->rwsched_tasklet_info = tenv.tasklet[2];
rwmsg_broker_main(broport_g, 2, 1, tenv.rwsched, tenv.tasklet[2], tenv.rwcal, TRUE, tenv.ti, &bro2);
double loopwait = 0.1;
int loopcount = 0;
uint32_t meshcount = 5*2*(2-1); //==5*2*n*(n-1)/2 == 10
/* Should now accept and ultimately timeout in the broker's acceptor */
//rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, &rwmsg_broker_g.exitnow.acc_listening);
while (rwmsg_broker_g.exitnow.neg_accepted<meshcount && loopcount++<200) {
usleep(5*1000); // 5ms
rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, NULL);
}
ASSERT_EQ(rwmsg_broker_g.exitnow.neg_accepted, meshcount);
ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0);
/* Srvchan is tasklet 3, attached to broker 0
* also bound to main rws queue to avoid CF/dispatch headachess
* This endpoint has bro_instid=0 */
rwmsg_endpoint_t *ep_s;
ep_s = rwmsg_endpoint_create(0, 3, 1, tenv.rwsched, tenv.tasklet[3], rwtrace_init(), NULL);
ASSERT_TRUE(ep_s != NULL);
// fprintf(stderr, "\nSrvchan-to-bro-1\n");
/* Direct everything through the broker */
rwmsg_endpoint_set_property_int(ep_s, "/rwmsg/broker/shunt", 1);
rwmsg_srvchan_t *sc = rwmsg_srvchan_create(ep_s);
ASSERT_TRUE(sc != NULL);
Test_Service myapisrv;
TEST__INITSERVER(&myapisrv, Test_);
rs = rwmsg_srvchan_add_service(sc, taddr, &myapisrv.base, &tenv.tasklet[3]);
ASSERT_EQ(rs, RW_STATUS_SUCCESS);
rs = rwmsg_srvchan_bind_rwsched_queue(sc, rwsched_dispatch_get_main_queue(tenv.rwsched));
ASSERT_TRUE(rs == RW_STATUS_SUCCESS);
rwmsg_broker_g.exitnow.neg_accepted = 0;
rwmsg_broker_g.exitnow.neg_freed = 0;
rwmsg_broker_g.exitnow.neg_freed_err = 0;
/* Should now accept, read hs, create broclichan, attach incoming accepted sk */
loopwait = 1;
rwsched_dispatch_main_until(tenv.tasklet[3], loopwait, &rwmsg_broker_g.exitnow.neg_freed);
ASSERT_GE(rwmsg_broker_g.exitnow.neg_accepted, 1);
ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1);
ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0);
#if 1
// fprintf(stderr, "\ntest__increment - clican-to-bro-0\n");
rwmsg_broker_g.exitnow.neg_accepted = 0;
rwmsg_broker_g.exitnow.neg_freed = 0;
rwmsg_broker_g.exitnow.neg_freed_err = 0;
/* Clichan is tasklet 1, attached to broker 1
* also bound to main rws queue to avoid CF/dispatch headaches
* This endpoint has bro_instid=1 */
rwmsg_endpoint_t *ep_c_b0;
ep_c_b0 = rwmsg_endpoint_create(0, 1, 0, tenv.rwsched, tenv.tasklet[1], rwtrace_init(), NULL);
ASSERT_TRUE(ep_c_b0 != NULL);
/* Direct everything through the broker */
rwmsg_endpoint_set_property_int(ep_c_b0, "/rwmsg/broker/shunt", 1);
/* Create a client channel pointing at the Test service's path.
* Instantiate a Test service client and connect this to the client
* channel.
*/
rwmsg_destination_t *dt;
//dt = rwmsg_destination_create(ep_c_b0, RWMSG_ADDRTYPE_UNICAST, tpeerpath);
dt = rwmsg_destination_create(ep_c_b0, RWMSG_ADDRTYPE_UNICAST, taddr);
ASSERT_TRUE(dt != NULL);
rwmsg_clichan_t *cc0 = rwmsg_clichan_create(ep_c_b0);
ASSERT_TRUE(cc0 != NULL);
rs = rwmsg_clichan_bind_rwsched_queue(cc0, rwsched_dispatch_get_main_queue(tenv.rwsched));
Test_Client mycli;
TEST__INITCLIENT(&mycli);
rwmsg_clichan_add_service(cc0, &mycli.base);
/* Should now accept, read hs, create broclichan, attach incoming accepted sk */
loopwait = .2;
rwsched_dispatch_main_until(tenv.tasklet[1], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed);
sleep(1);
rwmsg_global.status.request_ct = 0;
#define AcceptSrvchanAndCliChanOnSeperate2Bros_COUNT 5
int i;
rwmsg_request_t *rwreq=NULL;
for (i=0; i<AcceptSrvchanAndCliChanOnSeperate2Bros_COUNT; i++) {
TestReq req;
test_req__init(&req);
rwmsg_closure_t cb;
cb.pbrsp=(rwmsg_pbapi_cb)multibrocfb_response;
cb.ud=tenv.tasklet[1];
rs = test__increment(&mycli, dt, &req, &cb, &rwreq);
ASSERT_TRUE(rs==RW_STATUS_SUCCESS);
loopwait = 0.001;
rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed);
//loopwait = 0.001;
//rwsched_dispatch_main_until(tenv.tasklet[3], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed);
}
ASSERT_GE(rwmsg_broker_g.exitnow.neg_accepted, 1);
ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1);
ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0);
#endif
//usleep(500*1000);
loopwait = 2.0;
rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed);
rwmsg_request_release(rwreq);
ASSERT_LE(rwmsg_global.status.request_ct, 0);
#if 0
fprintf(stderr, "rwmsg_broker_dump = bro1\n");
rwmsg_broker_dump((rwmsg_broker_t *)bro1);
fprintf(stderr, "\nrwmsg_broker_dump = bro2\n");
rwmsg_broker_dump((rwmsg_broker_t *)bro2);
#endif
#if 1
/* End clichan tasklet 1 */
rwmsg_clichan_halt(cc0);
r = rwmsg_endpoint_halt_flush(ep_c_b0, TRUE);
ASSERT_TRUE(r);
#endif
#if 1
/* End srvchan tasklet 2 */
rwmsg_srvchan_halt(sc);
r = rwmsg_endpoint_halt_flush(ep_s, TRUE);
ASSERT_TRUE(r);
#endif
/* End broker */
r = rwmsg_broker_halt_sync(bro1);
ASSERT_TRUE(r);
r = rwmsg_broker_halt_sync(bro2);
ASSERT_TRUE(r);
ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0);
nnchk();
}
TEST(RWMsgBroker, AcceptSrvchanAndCliChanAndSndBlkOnSeperate2Bros_LONG) {
ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0);
nnchk();
TEST_DESCRIPTION("Tests accepting from a srvchan");
rwmsg_btenv_t tenv(4);
rwmsg_bool_t r;
rw_status_t rs;
const char *taddr = "/L/GTEST/RWBRO/1";
/* Broker is tasklet 0 */
rwmsg_broker_t *bro1=NULL;
tenv.ti->rwsched_tasklet_info = tenv.tasklet[0];
rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, TRUE, tenv.ti, &bro1);
/* Broker is tasklet 2 */
rwmsg_broker_t *bro2=NULL;
tenv.ti->rwsched_tasklet_info = tenv.tasklet[2];
rwmsg_broker_main(broport_g, 2, 1, tenv.rwsched, tenv.tasklet[2], tenv.rwcal, TRUE, tenv.ti, &bro2);
double loopwait = 0.1;
int loopcount = 0;
uint32_t meshcount = 5*2*(2-1); //==5*2*n*(n-1)/2 == 10
/* Should now accept and ultimately timeout in the broker's acceptor */
//rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, &rwmsg_broker_g.exitnow.acc_listening);
while (rwmsg_broker_g.exitnow.neg_accepted<meshcount && loopcount++<200) {
usleep(50*1000); // 50ms
rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, NULL);
}
ASSERT_EQ(rwmsg_broker_g.exitnow.neg_accepted, meshcount);
ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0);
/* Srvchan is tasklet 3, attached to broker 0
* also bound to main rws queue to avoid CF/dispatch headachess
* This endpoint has bro_instid=0 */
rwmsg_endpoint_t *ep_s;
ep_s = rwmsg_endpoint_create(0, 3, 1, tenv.rwsched, tenv.tasklet[3], rwtrace_init(), NULL);
ASSERT_TRUE(ep_s != NULL);
// fprintf(stderr, "\nSrvchan-to-bro-1\n");
/* Direct everything through the broker */
rwmsg_endpoint_set_property_int(ep_s, "/rwmsg/broker/shunt", 1);
rwmsg_srvchan_t *sc = rwmsg_srvchan_create(ep_s);
ASSERT_TRUE(sc != NULL);
Test_Service myapisrv;
TEST__INITSERVER(&myapisrv, Test_);
rs = rwmsg_srvchan_add_service(sc, taddr, &myapisrv.base, &tenv.tasklet[3]);
ASSERT_EQ(rs, RW_STATUS_SUCCESS);
//rs = rwmsg_srvchan_bind_rwsched_queue(sc, rwsched_dispatch_get_main_queue(tenv.rwsched));
rs = rwmsg_srvchan_bind_rwsched_cfrunloop(sc, tenv.tasklet[3]);
ASSERT_TRUE(rs == RW_STATUS_SUCCESS);
/* Clichan is tasklet 1, attached to broker 1
* also bound to main rws queue to avoid CF/dispatch headaches
* This endpoint has bro_instid=1 */
rwmsg_endpoint_t *ep_c;
ep_c = rwmsg_endpoint_create(0, 1, 0, tenv.rwsched, tenv.tasklet[1], rwtrace_init(), NULL);
ASSERT_TRUE(ep_c != NULL);
/* Direct everything through the broker */
rwmsg_endpoint_set_property_int(ep_c, "/rwmsg/broker/shunt", 1);
/* Create a client channel pointing at the Test service's path.
* Instantiate a Test service client and connect this to the client
* channel.
*/
rwmsg_destination_t *dt;
//dt = rwmsg_destination_create(ep_c, RWMSG_ADDRTYPE_UNICAST, tpeerpath);
dt = rwmsg_destination_create(ep_c, RWMSG_ADDRTYPE_UNICAST, taddr);
ASSERT_TRUE(dt != NULL);
rwmsg_clichan_t *cc = rwmsg_clichan_create(ep_c);
ASSERT_TRUE(cc != NULL);
//rs = rwmsg_clichan_bind_rwsched_queue(cc, rwsched_dispatch_get_main_queue(tenv.rwsched));
rs = rwmsg_clichan_bind_rwsched_cfrunloop(cc, tenv.tasklet[1]);
ASSERT_TRUE(rs == RW_STATUS_SUCCESS);
Test_Client mycli;
TEST__INITCLIENT(&mycli);
rwmsg_clichan_add_service(cc, &mycli.base);
/* Should now accept, read hs, create broclichan, attach incoming accepted sk */
rwsched_instance_CFRunLoopRunInMode(tenv.rwsched, RWMSG_RUNLOOP_MODE, 1, FALSE);
for (int i=0; i<100; i++) {
TestReq req;
rwmsg_request_t *rwreq=NULL;
test_req__init(&req);
#if 0
rs = test__increment_b(&mycli, dt, &req, &rwreq);
ASSERT_TRUE(rs==RW_STATUS_SUCCESS);
#else
req.body.value = i+5;
req.body.hopct = i+5;
rs = test__increment_b(&mycli, dt, &req, &rwreq);
ASSERT_EQ(rs, RW_STATUS_SUCCESS);
ASSERT_EQ(RWMSG_PAYFMT_PBAPI, rwmsg_request_get_response_payfmt(rwreq));
const TestRsp *rsp;
rs = rwmsg_request_get_response(rwreq, (const void **)&rsp);
ASSERT_EQ(rs, RW_STATUS_SUCCESS);
// fprintf(stderr, "ProtobufCliSrvCFBlocking test got rsp, errval=%u, burst i=%u\n", rsp->errval, i);
multibrocfb_response(rsp, rwreq, tenv.tasklet[1]);
#endif
}
rwsched_instance_CFRunLoopRunInMode(tenv.rwsched, RWMSG_RUNLOOP_MODE, 1, FALSE);
/* End clichan tasklet 1 */
rwmsg_clichan_halt(cc);
r = rwmsg_endpoint_halt_flush(ep_c, TRUE);
ASSERT_TRUE(r);
/* End srvchan tasklet 2 */
rwmsg_srvchan_halt(sc);
r = rwmsg_endpoint_halt_flush(ep_s, TRUE);
ASSERT_TRUE(r);
/* End broker */
r = rwmsg_broker_halt_sync(bro1);
ASSERT_TRUE(r);
r = rwmsg_broker_halt_sync(bro2);
ASSERT_TRUE(r);
ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0);
nnchk();
}
TEST(RWMsgBroker, AcceptSrvchanAndCliChanAndCFSndBlkOnSeperate2Bros_LONG) {
ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0);
nnchk();
TEST_DESCRIPTION("Tests accepting from a srvchan");
rwmsg_btenv_t tenv(4);
rwmsg_bool_t r;
rw_status_t rs;
const char *taddr = "/L/GTEST/RWBRO/1";
/* Broker is tasklet 0 */
rwmsg_broker_t *bro1=NULL;
tenv.ti->rwsched_tasklet_info = tenv.tasklet[0];
rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, TRUE, tenv.ti, &bro1);
/* Broker is tasklet 2 */
rwmsg_broker_t *bro2=NULL;
tenv.ti->rwsched_tasklet_info = tenv.tasklet[2];
rwmsg_broker_main(broport_g, 2, 1, tenv.rwsched, tenv.tasklet[2], tenv.rwcal, TRUE, tenv.ti, &bro2);
rwsched_instance_CFRunLoopRunInMode(tenv.rwsched, RWMSG_RUNLOOP_MODE, 1, FALSE);
/* Srvchan is tasklet 3, attached to broker 0
* also bound to main rws queue to avoid CF/dispatch headachess
* This endpoint has bro_instid=0 */
rwmsg_endpoint_t *ep_s;
ep_s = rwmsg_endpoint_create(0, 3, 1, tenv.rwsched, tenv.tasklet[3], rwtrace_init(), NULL);
ASSERT_TRUE(ep_s != NULL);
// fprintf(stderr, "\nSrvchan-to-bro-1\n");
/* Direct everything through the broker */
rwmsg_endpoint_set_property_int(ep_s, "/rwmsg/broker/shunt", 1);
rwmsg_srvchan_t *sc = rwmsg_srvchan_create(ep_s);
ASSERT_TRUE(sc != NULL);
Test_Service myapisrv;
TEST__INITSERVER(&myapisrv, Test_);
rs = rwmsg_srvchan_add_service(sc, taddr, &myapisrv.base, &tenv.tasklet[3]);
ASSERT_EQ(rs, RW_STATUS_SUCCESS);
//rs = rwmsg_srvchan_bind_rwsched_queue(sc, rwsched_dispatch_get_main_queue(tenv.rwsched));
rs = rwmsg_srvchan_bind_rwsched_cfrunloop(sc, tenv.tasklet[3]);
ASSERT_TRUE(rs == RW_STATUS_SUCCESS);
/* Clichan is tasklet 1, attached to broker 1
* also bound to main rws queue to avoid CF/dispatch headaches
* This endpoint has bro_instid=1 */
rwmsg_endpoint_t *ep_c;
ep_c = rwmsg_endpoint_create(0, 1, 0, tenv.rwsched, tenv.tasklet[1], rwtrace_init(), NULL);
ASSERT_TRUE(ep_c != NULL);
/* Direct everything through the broker */
rwmsg_endpoint_set_property_int(ep_c, "/rwmsg/broker/shunt", 1);
/* Create a client channel pointing at the Test service's path.
* Instantiate a Test service client and connect this to the client
* channel.
*/
rwmsg_destination_t *dt;
//dt = rwmsg_destination_create(ep_c, RWMSG_ADDRTYPE_UNICAST, tpeerpath);
dt = rwmsg_destination_create(ep_c, RWMSG_ADDRTYPE_UNICAST, taddr);
ASSERT_TRUE(dt != NULL);
rwmsg_clichan_t *cc = rwmsg_clichan_create(ep_c);
ASSERT_TRUE(cc != NULL);
//rs = rwmsg_clichan_bind_rwsched_queue(cc, rwsched_dispatch_get_main_queue(tenv.rwsched));
rs = rwmsg_clichan_bind_rwsched_cfrunloop(cc, tenv.tasklet[1]);
ASSERT_TRUE(rs == RW_STATUS_SUCCESS);
Test_Client mycli;
TEST__INITCLIENT(&mycli);
rwmsg_clichan_add_service(cc, &mycli.base);
/* Should now accept, read hs, create broclichan, attach incoming accepted sk */
rwsched_instance_CFRunLoopRunInMode(tenv.rwsched, RWMSG_RUNLOOP_MODE, 1, FALSE);
for (int i=0; i<100; i++) {
TestReq req;
rwmsg_request_t *rwreq=NULL;
test_req__init(&req);
#if 0
rs = test__increment_b(&mycli, dt, &req, &rwreq);
ASSERT_TRUE(rs==RW_STATUS_SUCCESS);
#else
req.body.value = i+5;
req.body.hopct = i+5;
rs = test__increment_b(&mycli, dt, &req, &rwreq);
ASSERT_EQ(rs, RW_STATUS_SUCCESS);
ASSERT_EQ(RWMSG_PAYFMT_PBAPI, rwmsg_request_get_response_payfmt(rwreq));
const TestRsp *rsp;
rs = rwmsg_request_get_response(rwreq, (const void **)&rsp);
ASSERT_EQ(rs, RW_STATUS_SUCCESS);
// fprintf(stderr, "ProtobufCliSrvCFBlocking test got rsp, errval=%u, burst i=%u\n", rsp->errval, i);
multibrocfb_response(rsp, rwreq, tenv.tasklet[1]);
#endif
}
rwsched_instance_CFRunLoopRunInMode(tenv.rwsched, RWMSG_RUNLOOP_MODE, 2, FALSE);
/* End clichan tasklet 1 */
rwmsg_clichan_halt(cc);
r = rwmsg_endpoint_halt_flush(ep_c, TRUE);
ASSERT_TRUE(r);
/* End srvchan tasklet 2 */
rwmsg_srvchan_halt(sc);
r = rwmsg_endpoint_halt_flush(ep_s, TRUE);
ASSERT_TRUE(r);
/* End broker */
r = rwmsg_broker_halt_sync(bro1);
ASSERT_TRUE(r);
r = rwmsg_broker_halt_sync(bro2);
ASSERT_TRUE(r);
ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0);
nnchk();
}
// This gtest is covering multibroker channel stall fixed in RIFT-9058
TEST(RWMsgBroker, CheckStuckMessagesOnSeperate2Bros_LONG) {
rwmsg_global.status.endpoint_ct = 0;
ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0);
nnchk();
TEST_DESCRIPTION("Tests accepting from a srvchan");
rwmsg_btenv_t tenv(4);
rwmsg_bool_t r;
rw_status_t rs;
const char *taddr = "/L/GTEST/RWBRO/1";
/* Broker is tasklet 0 */
rwmsg_broker_t *bro1=NULL;
tenv.ti->rwsched_tasklet_info = tenv.tasklet[0];
rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, TRUE, tenv.ti, &bro1);
/* Broker is tasklet 2 */
rwmsg_broker_t *bro2=NULL;
tenv.ti->rwsched_tasklet_info = tenv.tasklet[2];
rwmsg_broker_main(broport_g, 2, 1, tenv.rwsched, tenv.tasklet[2], tenv.rwcal, TRUE, tenv.ti, &bro2);
double loopwait = 0.1;
int loopcount = 0;
uint32_t meshcount = 5*2*(2-1); //==5*2*n*(n-1)/2 == 10
/* Should now accept and ultimately timeout in the broker's acceptor */
//rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, &rwmsg_broker_g.exitnow.acc_listening);
while (rwmsg_broker_g.exitnow.neg_accepted<meshcount && loopcount++<200) {
usleep(5*1000); // 5ms
rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, NULL);
}
ASSERT_EQ(rwmsg_broker_g.exitnow.neg_accepted, meshcount);
ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0);
/* Srvchan is tasklet 3, attached to broker 0
* also bound to main rws queue to avoid CF/dispatch headachess
* This endpoint has bro_instid=0 */
rwmsg_endpoint_t *ep_s;
ep_s = rwmsg_endpoint_create(0, 3, 1, tenv.rwsched, tenv.tasklet[3], rwtrace_init(), NULL);
ASSERT_TRUE(ep_s != NULL);
// fprintf(stderr, "\nSrvchan-to-bro-1\n");
/* Direct everything through the broker */
rwmsg_endpoint_set_property_int(ep_s, "/rwmsg/broker/shunt", 1);
rwmsg_srvchan_t *sc = rwmsg_srvchan_create(ep_s);
ASSERT_TRUE(sc != NULL);
Test_Service myapisrv;
TEST__INITSERVER(&myapisrv, Test_);
rs = rwmsg_srvchan_add_service(sc, taddr, &myapisrv.base, &tenv.tasklet[3]);
ASSERT_EQ(rs, RW_STATUS_SUCCESS);
rs = rwmsg_srvchan_bind_rwsched_queue(sc, rwsched_dispatch_get_main_queue(tenv.rwsched));
ASSERT_TRUE(rs == RW_STATUS_SUCCESS);
rwmsg_broker_g.exitnow.neg_accepted = 0;
rwmsg_broker_g.exitnow.neg_freed = 0;
rwmsg_broker_g.exitnow.neg_freed_err = 0;
/* Should now accept, read hs, create broclichan, attach incoming accepted sk */
loopwait = 1;
rwsched_dispatch_main_until(tenv.tasklet[3], loopwait, &rwmsg_broker_g.exitnow.neg_freed);
ASSERT_GE(rwmsg_broker_g.exitnow.neg_accepted, 1);
ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1);
ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0);
#if 1
rwmsg_broker_g.exitnow.neg_accepted = 0;
rwmsg_broker_g.exitnow.neg_freed = 0;
rwmsg_broker_g.exitnow.neg_freed_err = 0;
/* Clichan is tasklet 1, attached to broker 1
* also bound to main rws queue to avoid CF/dispatch headaches
* This endpoint has bro_instid=1 */
rwmsg_endpoint_t *ep_c_b0;
ep_c_b0 = rwmsg_endpoint_create(0, 1, 0, tenv.rwsched, tenv.tasklet[1], rwtrace_init(), NULL);
ASSERT_TRUE(ep_c_b0 != NULL);
/* Direct everything through the broker */
rwmsg_endpoint_set_property_int(ep_c_b0, "/rwmsg/broker/shunt", 1);
/* Create a client channel pointing at the Test service's path.
* Instantiate a Test service client and connect this to the client
* channel.
*/
rwmsg_destination_t *dt;
dt = rwmsg_destination_create(ep_c_b0, RWMSG_ADDRTYPE_UNICAST, taddr);
ASSERT_TRUE(dt != NULL);
rwmsg_clichan_t *cc0 = rwmsg_clichan_create(ep_c_b0);
ASSERT_TRUE(cc0 != NULL);
rs = rwmsg_clichan_bind_rwsched_queue(cc0, rwsched_dispatch_get_main_queue(tenv.rwsched));
Test_Client mycli;
TEST__INITCLIENT(&mycli);
rwmsg_clichan_add_service(cc0, &mycli.base);
/* Should now accept, read hs, create broclichan, attach incoming accepted sk */
loopwait = .2;
rwsched_dispatch_main_until(tenv.tasklet[1], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed);
sleep(1);
rwmsg_global.status.request_ct = 0;
#define CheckStuckMessagesOnSeperate2Bros_COUNT 15
int i;
rwmsg_request_t *rwreq=NULL;
for (i=0; i<CheckStuckMessagesOnSeperate2Bros_COUNT; i++) {
TestReq req;
test_req__init(&req);
rwmsg_closure_t cb;
cb.pbrsp=(rwmsg_pbapi_cb)multibrocfb_response;
cb.ud=tenv.tasklet[1];
rs = test__increment(&mycli, dt, &req, &cb, &rwreq);
ASSERT_TRUE(rs==RW_STATUS_SUCCESS);
}
loopwait = 2.0;
rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, NULL);
ASSERT_GE(rwmsg_broker_g.exitnow.neg_accepted, 1);
ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1);
ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0);
#endif
//rwmsg_request_release(rwreq);
ASSERT_LE(rwmsg_global.status.request_ct, 1);
#if 1
/* End clichan tasklet 1 */
rwmsg_clichan_halt(cc0);
r = rwmsg_endpoint_halt_flush(ep_c_b0, TRUE);
ASSERT_TRUE(r);
#endif
#if 1
/* End srvchan tasklet 2 */
rwmsg_srvchan_halt(sc);
r = rwmsg_endpoint_halt_flush(ep_s, TRUE);
ASSERT_TRUE(r);
#endif
/* End broker */
r = rwmsg_broker_halt_sync(bro1);
ASSERT_TRUE(r);
r = rwmsg_broker_halt_sync(bro2);
ASSERT_TRUE(r);
ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0);
nnchk();
}
TEST(RWMsgBroker, AcceptSrvchanAndCliChanW3Bros_LONG) {
ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0);
nnchk();
TEST_DESCRIPTION("Tests accepting from a srvchan");
rwmsg_btenv_t tenv(5);
rwmsg_bool_t r;
rw_status_t rs;
//const char *taddr = "/L/GTEST/RWBRO/TESTAPP/PBSCF/100/3";
const char *taddr = "/L/GTEST/RWBRO/1";
/* Broker is tasklet 0 */
rwmsg_broker_t *bro1=NULL;
tenv.ti->rwsched_tasklet_info = tenv.tasklet[0];
rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, TRUE, tenv.ti, &bro1);
/* Broker is tasklet 2 */
rwmsg_broker_t *bro2=NULL;
tenv.ti->rwsched_tasklet_info = tenv.tasklet[2];
rwmsg_broker_main(broport_g, 2, 1, tenv.rwsched, tenv.tasklet[2], tenv.rwcal, TRUE, tenv.ti, &bro2);
/* Broker is tasklet 4 */
rwmsg_broker_t *bro3=NULL;
tenv.ti->rwsched_tasklet_info = tenv.tasklet[4];
rwmsg_broker_main(broport_g, 4, 2, tenv.rwsched, tenv.tasklet[4], tenv.rwcal, TRUE, tenv.ti, &bro3);
double loopwait = 0.1;
int loopcount = 0;
uint32_t meshcount = 5*3*(3-1); //==5*2*n*(n-1)/2 == 30
/* Should now accept and ultimately timeout in the broker's acceptor */
//rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, &rwmsg_broker_g.exitnow.acc_listening);
while (rwmsg_broker_g.exitnow.neg_accepted<meshcount && loopcount++<200) {
usleep(50*1000); // 50ms
rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, NULL);
}
ASSERT_EQ(rwmsg_broker_g.exitnow.neg_accepted, meshcount);
ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0);
/* Srvchan is tasklet 3, attached to broker 2
* also bound to main rws queue to avoid CF/dispatch headachess
* This endpoint has bro_instid=0 */
rwmsg_endpoint_t *ep_s;
ep_s = rwmsg_endpoint_create(0, 3, 2, tenv.rwsched, tenv.tasklet[3], rwtrace_init(), NULL);
ASSERT_TRUE(ep_s != NULL);
/* Direct everything through the broker */
rwmsg_endpoint_set_property_int(ep_s, "/rwmsg/broker/shunt", 1);
rwmsg_srvchan_t *sc = rwmsg_srvchan_create(ep_s);
ASSERT_TRUE(sc != NULL);
Test_Service myapisrv;
TEST__INITSERVER(&myapisrv, Test_);
//rs = rwmsg_srvchan_add_service(sc, tpath, &myapisrv.base, &tenv.tasklet[3]);
rs = rwmsg_srvchan_add_service(sc, taddr, &myapisrv.base, &tenv.tasklet[3]);
ASSERT_EQ(rs, RW_STATUS_SUCCESS);
rs = rwmsg_srvchan_bind_rwsched_queue(sc, rwsched_dispatch_get_main_queue(tenv.rwsched));
ASSERT_TRUE(rs == RW_STATUS_SUCCESS);
rwmsg_broker_g.exitnow.neg_accepted = 0;
rwmsg_broker_g.exitnow.neg_freed = 0;
rwmsg_broker_g.exitnow.neg_freed_err = 0;
/* Should now accept, read hs, create broclichan, attach incoming accepted sk */
loopwait = 1;
rwsched_dispatch_main_until(tenv.tasklet[3], loopwait, &rwmsg_broker_g.exitnow.neg_freed);
ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1);
ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0);
/* Clichan is tasklet 1, attached to broker 1
* also bound to main rws queue to avoid CF/dispatch headaches
* This endpoint has bro_instid=1 */
rwmsg_endpoint_t *ep_c;
ep_c = rwmsg_endpoint_create(0, 1, 1, tenv.rwsched, tenv.tasklet[1], rwtrace_init(), NULL);
ASSERT_TRUE(ep_c != NULL);
/* Direct everything through the broker */
rwmsg_endpoint_set_property_int(ep_c, "/rwmsg/broker/shunt", 1);
/* Create a client channel pointing at the Test service's path.
* Instantiate a Test service client and connect this to the client
* channel.
*/
rwmsg_destination_t *dt;
//dt = rwmsg_destination_create(ep_c, RWMSG_ADDRTYPE_UNICAST, tpeerpath);
dt = rwmsg_destination_create(ep_c, RWMSG_ADDRTYPE_UNICAST, taddr);
ASSERT_TRUE(dt != NULL);
rwmsg_clichan_t *cc = rwmsg_clichan_create(ep_c);
ASSERT_TRUE(cc != NULL);
rs = rwmsg_clichan_bind_rwsched_queue(cc, rwsched_dispatch_get_main_queue(tenv.rwsched));
Test_Client mycli;
TEST__INITCLIENT(&mycli);
rwmsg_clichan_add_service(cc, &mycli.base);
/* Should now accept, read hs, create broclichan, attach incoming accepted sk */
loopwait = 1;
rwsched_dispatch_main_until(tenv.tasklet[1], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed);
int i;
for (i=0; i<10; i++) {
TestReq req;
rwmsg_request_t *rwreq=NULL;
test_req__init(&req);
// fprintf(stderr, "test__increment - 01\n");
rwmsg_closure_t cb;
cb.pbrsp=(rwmsg_pbapi_cb)multibrocfb_response;
cb.ud=tenv.tasklet[1];
rs = test__increment(&mycli, dt, &req, &cb, &rwreq);
ASSERT_EQ(rs, RW_STATUS_SUCCESS);
loopwait = 0.001;
rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed);
}
// fprintf(stderr, "end dispatch_main 2\n");
ASSERT_GE(rwmsg_broker_g.exitnow.neg_accepted, 1);
ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1);
ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0);
#if 1
/* End clichan tasklet 1 */
rwmsg_clichan_halt(cc);
r = rwmsg_endpoint_halt_flush(ep_c, TRUE);
ASSERT_TRUE(r);
#endif
#if 1
/* End srvchan tasklet 2 */
rwmsg_srvchan_halt(sc);
r = rwmsg_endpoint_halt_flush(ep_s, TRUE);
ASSERT_TRUE(r);
#endif
/* End broker */
r = rwmsg_broker_halt_sync(bro1);
ASSERT_TRUE(r);
r = rwmsg_broker_halt_sync(bro2);
ASSERT_TRUE(r);
r = rwmsg_broker_halt_sync(bro3);
ASSERT_TRUE(r);
ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0);
nnchk();
}
TEST(RWMsgBroker, ReCreateSrvChanW1Bro_LONG) {
ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0);
nnchk();
TEST_DESCRIPTION("Tests accepting from a srvchan");
rwmsg_btenv_t tenv(3);
rwmsg_bool_t r;
rw_status_t rs;
setenv("RWMSG_CHANNEL_AGEOUT", "60", TRUE);
//const char *taddr = "/L/GTEST/RWBRO/TESTAPP/PBSCF/100/3";
const char *taddr = "/L/GTEST/RWBRO/1";
/* Broker is tasklet 0 */
rwmsg_broker_t *bro1=NULL;
tenv.ti->rwsched_tasklet_info = tenv.tasklet[0];
rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, TRUE, tenv.ti, &bro1);
double loopwait = 0.1;
rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, NULL);
/* Srvchan is tasklet 3, attached to broker 0
* also bound to main rws queue to avoid CF/dispatch headachess
* This endpoint has bro_instid=0 */
rwmsg_endpoint_t *ep_s;
ep_s = rwmsg_endpoint_create(0, 1, 0, tenv.rwsched, tenv.tasklet[1], rwtrace_init(), NULL);
ASSERT_TRUE(ep_s != NULL);
/* Direct everything through the broker */
rwmsg_endpoint_set_property_int(ep_s, "/rwmsg/broker/shunt", 1);
rwmsg_srvchan_t *sc = rwmsg_srvchan_create(ep_s);
ASSERT_TRUE(sc != NULL);
Test_Service myapisrv;
TEST__INITSERVER(&myapisrv, Test_);
rs = rwmsg_srvchan_add_service(sc, taddr, &myapisrv.base, &tenv.tasklet[1]);
ASSERT_EQ(rs, RW_STATUS_SUCCESS);
rs = rwmsg_srvchan_bind_rwsched_queue(sc, rwsched_dispatch_get_main_queue(tenv.rwsched));
ASSERT_TRUE(rs == RW_STATUS_SUCCESS);
rwmsg_broker_g.exitnow.neg_accepted = 0;
rwmsg_broker_g.exitnow.neg_freed = 0;
rwmsg_broker_g.exitnow.neg_freed_err = 0;
/* Should now accept, read hs, create broclichan, attach incoming accepted sk */
loopwait = 5;
rwsched_dispatch_main_until(tenv.tasklet[1], loopwait, &rwmsg_broker_g.exitnow.neg_freed);
ASSERT_GE(rwmsg_broker_g.exitnow.neg_accepted, 1);
ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1);
ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0);
/* Clichan is tasklet 2, attached to broker 1
* also bound to main rws queue to avoid CF/dispatch headaches
* This endpoint has bro_instid=1 */
rwmsg_endpoint_t *ep_c;
ep_c = rwmsg_endpoint_create(0, 2, 0, tenv.rwsched, tenv.tasklet[2], rwtrace_init(), NULL);
ASSERT_TRUE(ep_c != NULL);
/* Direct everything through the broker */
rwmsg_endpoint_set_property_int(ep_c, "/rwmsg/broker/shunt", 1);
/* Create a client channel pointing at the Test service's path.
* Instantiate a Test service client and connect this to the client
* channel.
*/
rwmsg_destination_t *dt;
//dt = rwmsg_destination_create(ep_c, RWMSG_ADDRTYPE_UNICAST, tpeerpath);
dt = rwmsg_destination_create(ep_c, RWMSG_ADDRTYPE_UNICAST, taddr);
ASSERT_TRUE(dt != NULL);
rwmsg_clichan_t *cc = rwmsg_clichan_create(ep_c);
ASSERT_TRUE(cc != NULL);
rs = rwmsg_clichan_bind_rwsched_queue(cc, rwsched_dispatch_get_main_queue(tenv.rwsched));
Test_Client mycli;
TEST__INITCLIENT(&mycli);
rwmsg_clichan_add_service(cc, &mycli.base);
/* Should now accept, read hs, create broclichan, attach incoming accepted sk */
loopwait = 2;
rwsched_dispatch_main_until(tenv.tasklet[2], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed);
TestReq req;
rwmsg_request_t *rwreq=NULL;
test_req__init(&req);
rwmsg_closure_t cb;
cb.pbrsp=(rwmsg_pbapi_cb)multibrocfb_response;
cb.ud=tenv.tasklet[2];
int send_some = 5;
for (int i=0; i<send_some; i++) {
req.body.value = i;
req.body.hopct = i;
rs = test__increment(&mycli, dt, &req, &cb, &rwreq);
ASSERT_EQ(rs, RW_STATUS_SUCCESS);
loopwait = 0.001;
rwsched_dispatch_main_until(tenv.tasklet[2], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed);
}
ASSERT_GE(rwmsg_broker_g.exitnow.neg_accepted, 1);
ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1);
ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0);
/* End srvchan tasklet 2 */
VERBPRN("\n\n\n\n-------------- End srvchan\n");
rwmsg_srvchan_halt(sc);
loopwait = 2;
rwsched_dispatch_main_until(tenv.tasklet[1], loopwait, NULL);
int send_some_more = 2;
#if 1
VERBPRN("\n\n\n\n-------------- send_some_more %u\n", send_some_more);
for (int i=0; i<send_some_more; i++) {
req.body.value = 50+i;
req.body.hopct = 50+i;
rs = test__increment(&mycli, dt, &req, &cb, &rwreq);
ASSERT_EQ(rs, RW_STATUS_SUCCESS);
loopwait = 0.001;
rwsched_dispatch_main_until(tenv.tasklet[2], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed);
}
#endif
#if 1
VERBPRN("\n\n\n\n-------------- Create a Server Channel\n");
sc = rwmsg_srvchan_create(ep_s);
ASSERT_TRUE(sc != NULL);
TEST__INITSERVER(&myapisrv, Test_);
rs = rwmsg_srvchan_add_service(sc, taddr, &myapisrv.base, &tenv.tasklet[1]);
ASSERT_EQ(rs, RW_STATUS_SUCCESS);
rs = rwmsg_srvchan_bind_rwsched_queue(sc, rwsched_dispatch_get_main_queue(tenv.rwsched));
ASSERT_TRUE(rs == RW_STATUS_SUCCESS);
/* Should now accept, read hs, create broclichan, attach incoming accepted sk */
loopwait = 1;
rwsched_dispatch_main_until(tenv.tasklet[1], loopwait, NULL);
#endif
send_some_more = 3;
VERBPRN("\n\n\n\n-------------- send_some_more %u\n", send_some_more);
for (int i=0; i<send_some_more; i++) {
req.body.value = 100+i;
req.body.hopct = 100+i;
rs = test__increment(&mycli, dt, &req, &cb, &rwreq);
ASSERT_EQ(rs, RW_STATUS_SUCCESS);
loopwait = 0.001;
rwsched_dispatch_main_until(tenv.tasklet[2], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed);
}
loopwait = 2;
rwsched_dispatch_main_until(tenv.tasklet[1], loopwait, NULL);
VERBPRN("\n\n\n\n-------------- End srvchan & clichan\n");
/* End srvchan tasklet 2 */
rwmsg_srvchan_halt(sc);
r = rwmsg_endpoint_halt_flush(ep_s, TRUE);
ASSERT_TRUE(r);
/* End clichan tasklet 1 */
rwmsg_clichan_halt(cc);
r = rwmsg_endpoint_halt_flush(ep_c, TRUE);
ASSERT_TRUE(r);
loopwait = 1;
rwsched_dispatch_main_until(tenv.tasklet[2], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed);
/* End broker */
r = rwmsg_broker_halt_sync(bro1);
ASSERT_TRUE(r);
ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0);
nnchk();
}
TEST(RWMsgBroker, ReCreateSrvChanW2Bros_LONG) {
ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0);
nnchk();
TEST_DESCRIPTION("Tests accepting from a srvchan");
rwmsg_btenv_t tenv(4);
rwmsg_bool_t r;
rw_status_t rs;
setenv("RWMSG_CHANNEL_AGEOUT", "60", TRUE);
const char *taddr = "/L/GTEST/RWBRO/1";
/* Broker is tasklet 0 */
rwmsg_broker_t *bro1=NULL;
tenv.ti->rwsched_tasklet_info = tenv.tasklet[0];
rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, TRUE, tenv.ti, &bro1);
/* Broker is tasklet 2 */
rwmsg_broker_t *bro2=NULL;
tenv.ti->rwsched_tasklet_info = tenv.tasklet[2];
rwmsg_broker_main(broport_g, 2, 1, tenv.rwsched, tenv.tasklet[2], tenv.rwcal, TRUE, tenv.ti, &bro2);
double loopwait = 0.1;
int loopcount = 0;
uint32_t meshcount = 5*2*(2-1); //==5*2*n*(n-1)/2 == 10
/* Should now accept and ultimately timeout in the broker's acceptor */
//rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, &rwmsg_broker_g.exitnow.acc_listening);
while (rwmsg_broker_g.exitnow.neg_accepted<meshcount && loopcount++<200) {
usleep(5*1000); // 5ms
rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, NULL);
}
ASSERT_EQ(rwmsg_broker_g.exitnow.neg_accepted, meshcount);
ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0);
/* Srvchan is tasklet 3, attached to broker 0
* also bound to main rws queue to avoid CF/dispatch headachess
* This endpoint has bro_instid=0 */
rwmsg_endpoint_t *ep_s;
ep_s = rwmsg_endpoint_create(0, 3, 1, tenv.rwsched, tenv.tasklet[3], rwtrace_init(), NULL);
ASSERT_TRUE(ep_s != NULL);
// fprintf(stderr, "\nSrvchan-to-bro-1\n");
/* Direct everything through the broker */
rwmsg_endpoint_set_property_int(ep_s, "/rwmsg/broker/shunt", 1);
rwmsg_srvchan_t *sc;
sc = rwmsg_srvchan_create(ep_s);
ASSERT_TRUE(sc != NULL);
Test_Service myapisrv;
TEST__INITSERVER(&myapisrv, Test_);
rs = rwmsg_srvchan_add_service(sc, taddr, &myapisrv.base, &tenv.tasklet[3]);
ASSERT_EQ(rs, RW_STATUS_SUCCESS);
rs = rwmsg_srvchan_bind_rwsched_queue(sc, rwsched_dispatch_get_main_queue(tenv.rwsched));
ASSERT_TRUE(rs == RW_STATUS_SUCCESS);
rwmsg_broker_g.exitnow.neg_accepted = 0;
rwmsg_broker_g.exitnow.neg_freed = 0;
rwmsg_broker_g.exitnow.neg_freed_err = 0;
/* Should now accept, read hs, create broclichan, attach incoming accepted sk */
loopwait = 1;
rwsched_dispatch_main_until(tenv.tasklet[3], loopwait, &rwmsg_broker_g.exitnow.neg_freed);
ASSERT_GE(rwmsg_broker_g.exitnow.neg_accepted, 1);
ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1);
ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0);
#if 1
rwmsg_broker_g.exitnow.neg_accepted = 0;
rwmsg_broker_g.exitnow.neg_freed = 0;
rwmsg_broker_g.exitnow.neg_freed_err = 0;
/* Clichan is tasklet 1, attached to broker 1
* also bound to main rws queue to avoid CF/dispatch headaches
* This endpoint has bro_instid=1 */
rwmsg_endpoint_t *ep_c_b0;
ep_c_b0 = rwmsg_endpoint_create(0, 1, 0, tenv.rwsched, tenv.tasklet[1], rwtrace_init(), NULL);
ASSERT_TRUE(ep_c_b0 != NULL);
/* Direct everything through the broker */
rwmsg_endpoint_set_property_int(ep_c_b0, "/rwmsg/broker/shunt", 1);
/* Create a client channel pointing at the Test service's path.
* Instantiate a Test service client and connect this to the client
* channel.
*/
rwmsg_destination_t *dt;
//dt = rwmsg_destination_create(ep_c_b0, RWMSG_ADDRTYPE_UNICAST, tpeerpath);
dt = rwmsg_destination_create(ep_c_b0, RWMSG_ADDRTYPE_UNICAST, taddr);
ASSERT_TRUE(dt != NULL);
rwmsg_clichan_t *cc0 = rwmsg_clichan_create(ep_c_b0);
ASSERT_TRUE(cc0 != NULL);
rs = rwmsg_clichan_bind_rwsched_queue(cc0, rwsched_dispatch_get_main_queue(tenv.rwsched));
Test_Client mycli;
TEST__INITCLIENT(&mycli);
rwmsg_clichan_add_service(cc0, &mycli.base);
/* Should now accept, read hs, create broclichan, attach incoming accepted sk */
loopwait = .2;
rwsched_dispatch_main_until(tenv.tasklet[1], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed);
sleep(1);
rwmsg_global.status.request_ct = 0;
TestReq req;
rwmsg_request_t *rwreq=NULL;
test_req__init(&req);
rwmsg_closure_t cb;
cb.pbrsp=(rwmsg_pbapi_cb)multibrocfb_response;
cb.ud=tenv.tasklet[2];
int send_some = 5;
for (int i=0; i<send_some; i++) {
req.body.value = i;
req.body.hopct = i;
rs = test__increment(&mycli, dt, &req, &cb, &rwreq);
ASSERT_EQ(rs, RW_STATUS_SUCCESS);
loopwait = 0.001;
rwsched_dispatch_main_until(tenv.tasklet[2], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed);
}
ASSERT_GE(rwmsg_broker_g.exitnow.neg_accepted, 1);
ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1);
ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0);
#endif
VERBPRN("\n\n\n\n-------------- End srvchan, send_some_more, recreate & send_some_more\n");
#if 1
/* End srvchan tasklet 2 */
rwmsg_srvchan_halt(sc);
loopwait = 1;
rwsched_dispatch_main_until(tenv.tasklet[2], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed);
test_req__init(&req);
cb.pbrsp=(rwmsg_pbapi_cb)multibrocfb_response;
cb.ud=tenv.tasklet[2];
int send_some_more = 5;
for (int i=0; i<send_some_more; i++) {
req.body.value = 50+i;
req.body.hopct = 50+i;
rs = test__increment(&mycli, dt, &req, &cb, &rwreq);
ASSERT_EQ(rs, RW_STATUS_SUCCESS);
loopwait = 0.001;
rwsched_dispatch_main_until(tenv.tasklet[2], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed);
}
loopwait = 1;
rwsched_dispatch_main_until(tenv.tasklet[2], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed);
sc = rwmsg_srvchan_create(ep_s);
ASSERT_TRUE(sc != NULL);
TEST__INITSERVER(&myapisrv, Test_);
rs = rwmsg_srvchan_add_service(sc, taddr, &myapisrv.base, &tenv.tasklet[3]);
ASSERT_EQ(rs, RW_STATUS_SUCCESS);
rs = rwmsg_srvchan_bind_rwsched_queue(sc, rwsched_dispatch_get_main_queue(tenv.rwsched));
ASSERT_TRUE(rs == RW_STATUS_SUCCESS);
loopwait = 1;
rwsched_dispatch_main_until(tenv.tasklet[2], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed);
test_req__init(&req);
cb.pbrsp=(rwmsg_pbapi_cb)multibrocfb_response;
cb.ud=tenv.tasklet[2];
send_some_more = 5;
for (int i=0; i<send_some_more; i++) {
req.body.value = 100+i;
req.body.hopct = 100+i;
rs = test__increment(&mycli, dt, &req, &cb, &rwreq);
ASSERT_EQ(rs, RW_STATUS_SUCCESS);
loopwait = 0.001;
rwsched_dispatch_main_until(tenv.tasklet[2], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed);
}
#endif
//usleep(500*1000);
loopwait = 1.0;
rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, NULL);//&rwmsg_broker_g.exitnow.neg_freed);
rwmsg_request_release(rwreq);
//ASSERT_LE(rwmsg_global.status.request_ct, 0);
#if 0
fprintf(stderr, "rwmsg_broker_dump = bro1\n");
rwmsg_broker_dump((rwmsg_broker_t *)bro1);
fprintf(stderr, "\nrwmsg_broker_dump = bro2\n");
rwmsg_broker_dump((rwmsg_broker_t *)bro2);
#endif
#if 1
/* End clichan tasklet 1 */
rwmsg_clichan_halt(cc0);
r = rwmsg_endpoint_halt_flush(ep_c_b0, TRUE);
ASSERT_TRUE(r);
#endif
#if 1
/* End srvchan tasklet 2 */
rwmsg_srvchan_halt(sc);
r = rwmsg_endpoint_halt_flush(ep_s, TRUE);
ASSERT_TRUE(r);
#endif
/* End broker */
r = rwmsg_broker_halt_sync(bro1);
ASSERT_TRUE(r);
r = rwmsg_broker_halt_sync(bro2);
ASSERT_TRUE(r);
ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0);
nnchk();
}
static void reqcb1(rwmsg_request_t *req, void *ud) {
req=req;
ud=ud;
}
TEST(RWMsgBroker, BindSrvchan) {
ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0);
nnchk();
TEST_DESCRIPTION("Tests method binds a srvchan to a broker");
rwmsg_btenv_t tenv(2);
/* Broker is tasklet 0 */
rwmsg_broker_t *bro=NULL;
tenv.ti->rwsched_tasklet_info = tenv.tasklet[0];
rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, TRUE, tenv.ti, &bro);
/* Clichan is tasklet 1, also bound to main rws queue to avoid CF/dispatch headaches */
rwmsg_endpoint_t *ep;
ep = rwmsg_endpoint_create(0, 1, 0, tenv.rwsched, tenv.tasklet[1], rwtrace_init(), NULL);
ASSERT_TRUE(ep != NULL);
const char *taddr = "/L/GTEST/RWBRO/TESTAPP/1";
rwmsg_srvchan_t *sc = rwmsg_srvchan_create(ep);
ASSERT_TRUE(sc != NULL);
rw_status_t rs = rwmsg_srvchan_bind_rwsched_queue(sc, rwsched_dispatch_get_main_queue(tenv.rwsched));
ASSERT_TRUE(rs == RW_STATUS_SUCCESS);
rwmsg_signature_t *sig;
const int methno = 5;
sig = rwmsg_signature_create(ep, RWMSG_PAYFMT_RAW, methno, RWMSG_PRIORITY_DEFAULT);
ASSERT_TRUE(sig != NULL);
rwmsg_closure_t cb;
cb.request=reqcb1;
cb.ud=NULL;
rwmsg_method_t *meth = rwmsg_method_create(ep, taddr, sig, &cb);
ASSERT_TRUE(meth != NULL);
rs = rwmsg_srvchan_add_method(sc, meth);
ASSERT_TRUE(rs == RW_STATUS_SUCCESS);
/* Should now accept, read hs, create broclichan, attach incoming accepted sk */
int loopwait = 10;
rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, &rwmsg_broker_g.exitnow.neg_freed);
ASSERT_EQ(rwmsg_broker_g.exitnow.method_bindings, 1);
ASSERT_GE(rwmsg_broker_g.exitnow.neg_accepted, 1);
ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1);
ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0);
/* End clichan tasklet 1 */
rwmsg_bool_t r;
rwmsg_signature_release(ep, sig);
rwmsg_method_release(ep, meth);
rwmsg_srvchan_halt(sc);
r = rwmsg_endpoint_halt_flush(ep, TRUE);
ASSERT_TRUE(r);
/* End broker */
r = rwmsg_broker_halt_sync(bro);
ASSERT_TRUE(r);
ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0);
nnchk();
}
TEST(RWMsgBroker, BindSrvchan2Bros) {
ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0);
nnchk();
TEST_DESCRIPTION("Tests method binds a srvchan to a broker");
rwmsg_btenv_t tenv(4);
rwmsg_bool_t r;
/* Broker is tasklet 0 */
rwmsg_broker_t *bro1=NULL;
tenv.ti->rwsched_tasklet_info = tenv.tasklet[0];
rwmsg_broker_main(broport_g, 0, 0, tenv.rwsched, tenv.tasklet[0], tenv.rwcal, TRUE, tenv.ti, &bro1);
/* Broker is tasklet 2 */
rwmsg_broker_t *bro2=NULL;
tenv.ti->rwsched_tasklet_info = tenv.tasklet[2];
rwmsg_broker_main(broport_g, 2, 1, tenv.rwsched, tenv.tasklet[2], tenv.rwcal, TRUE, tenv.ti, &bro2);
{
/* Clichan is tasklet 1, also bound to main rws queue to avoid CF/dispatch headaches */
rwmsg_endpoint_t *ep;
ep = rwmsg_endpoint_create(0, 0, 0, tenv.rwsched, tenv.tasklet[0], rwtrace_init(), NULL);
ASSERT_TRUE(ep != NULL);
const char *taddr = "/L/GTEST/RWBRO/TESTAPP/2";
rwmsg_srvchan_t *sc = rwmsg_srvchan_create(ep);
ASSERT_TRUE(sc != NULL);
rw_status_t rs = rwmsg_srvchan_bind_rwsched_queue(sc, rwsched_dispatch_get_main_queue(tenv.rwsched));
ASSERT_TRUE(rs == RW_STATUS_SUCCESS);
rwmsg_signature_t *sig;
const int methno = 5;
sig = rwmsg_signature_create(ep, RWMSG_PAYFMT_RAW, methno, RWMSG_PRIORITY_DEFAULT);
ASSERT_TRUE(sig != NULL);
rwmsg_closure_t cb;
cb.request=reqcb1;
cb.ud=NULL;
rwmsg_method_t *meth = rwmsg_method_create(ep, taddr, sig, &cb);
ASSERT_TRUE(meth != NULL);
rs = rwmsg_srvchan_add_method(sc, meth);
ASSERT_TRUE(rs == RW_STATUS_SUCCESS);
/* Should now accept, read hs, create broclichan, attach incoming accepted sk */
int loopwait = 10;
rwsched_dispatch_main_until(tenv.tasklet[0], loopwait, &rwmsg_broker_g.exitnow.neg_freed);
//ASSERT_EQ(rwmsg_broker_g.exitnow.method_bindings, 2);
ASSERT_GE(rwmsg_broker_g.exitnow.neg_accepted, 1);
ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1);
ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0);
/* End clichan tasklet 1 */
rwmsg_signature_release(ep, sig);
rwmsg_method_release(ep, meth);
rwmsg_srvchan_halt(sc);
r = rwmsg_endpoint_halt_flush(ep, TRUE);
ASSERT_TRUE(r);
}
{
/* Clichan is tasklet 3, also bound to main rws queue to avoid CF/dispatch headaches */
rwmsg_endpoint_t *ep;
ep = rwmsg_endpoint_create(0, 3, 1, tenv.rwsched, tenv.tasklet[3], rwtrace_init(), NULL);
ASSERT_TRUE(ep != NULL);
const char *taddr = "/L/GTEST/RWBRO/TESTAPP/3";
rwmsg_srvchan_t *sc = rwmsg_srvchan_create(ep);
ASSERT_TRUE(sc != NULL);
rw_status_t rs = rwmsg_srvchan_bind_rwsched_queue(sc, rwsched_dispatch_get_main_queue(tenv.rwsched));
ASSERT_TRUE(rs == RW_STATUS_SUCCESS);
rwmsg_signature_t *sig;
const int methno = 5;
sig = rwmsg_signature_create(ep, RWMSG_PAYFMT_RAW, methno, RWMSG_PRIORITY_DEFAULT);
ASSERT_TRUE(sig != NULL);
rwmsg_closure_t cb;
cb.request=reqcb1;
cb.ud=NULL;
rwmsg_method_t *meth = rwmsg_method_create(ep, taddr, sig, &cb);
ASSERT_TRUE(meth != NULL);
rs = rwmsg_srvchan_add_method(sc, meth);
ASSERT_TRUE(rs == RW_STATUS_SUCCESS);
rwmsg_broker_g.exitnow.method_bindings = 0;
rwmsg_broker_g.exitnow.neg_accepted = 0;
rwmsg_broker_g.exitnow.neg_freed = 0;
rwmsg_broker_g.exitnow.neg_freed_err = 0;
/* Should now accept, read hs, create broclichan, attach incoming accepted sk */
int loopwait = 10;
rwsched_dispatch_main_until(tenv.tasklet[2], loopwait, &rwmsg_broker_g.exitnow.neg_freed);
ASSERT_GE(rwmsg_broker_g.exitnow.neg_freed, 1);
ASSERT_EQ(rwmsg_broker_g.exitnow.neg_freed_err, 0);
/* End clichan tasklet 1 */
rwmsg_signature_release(ep, sig);
rwmsg_method_release(ep, meth);
rwmsg_srvchan_halt(sc);
r = rwmsg_endpoint_halt_flush(ep, TRUE);
ASSERT_TRUE(r);
}
/* End broker */
r = rwmsg_broker_halt_sync(bro1);
ASSERT_TRUE(r);
r = rwmsg_broker_halt_sync(bro2);
ASSERT_TRUE(r);
ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0);
nnchk();
}
struct mycfbctx {
int doblocking;
int done;
uint64_t tid;
int assertsinglethread;
uint32_t msgct_end;
uint32_t burst;
rwsched_instance_ptr_t rwsched;
rwsched_CFRunLoopRef loop;
uint32_t tickct; // number of timer ticks testwide
uint32_t timerct; // number of timers that exist
rwmsg_broker_t *bro;
};
struct mycfbtaskinfo {
int tnum;
uint64_t tid;
rwsched_CFRunLoopTimerRef cftim;
Test_Service myapisrv;
Test_Client mycli;
char tpath[128];
char tpeerpath[128];
rwmsg_endpoint_t *ep;
rwmsg_srvchan_t *sc;
rwmsg_destination_t *dt;
rwmsg_clichan_t *cc;
struct mycfbctx *ctx;
rwsched_tasklet_ptr_t tasklet;
uint32_t req_sent;
uint32_t req_eagain;
uint32_t rsp_recv;
uint32_t bnc_recv;
uint32_t tickct; // number of timer ticks in this tasklet
};
static void brodump_f(void *val) {
fprintf(stderr, "Gratuitous call to broker dump for smoketest/coverage reasons:\n");
rwmsg_broker_dump((rwmsg_broker_t *)val);
}
static void mycfb_response(const TestRsp *rsp, rwmsg_request_t *req, void *ud) {
struct mycfbtaskinfo *tinfo = (struct mycfbtaskinfo *)ud;
VERBPRN("req->hdr.bnc=%d\n",req->hdr.bnc);
// fprintf(stderr,"req->hdr.bnc=%d\n",req->hdr.bnc);
{
static int once=0;
if (tinfo->ctx->bro && !once) {
once=1;
rwsched_dispatch_async_f(tinfo->ctx->bro->tinfo,
rwsched_dispatch_get_main_queue(tinfo->ctx->rwsched),
tinfo->ctx->bro,
brodump_f);
}
}
// ASSERT_TRUE(rsp != NULL);
if (rsp) {
ASSERT_EQ(rsp->errval, 0);
ASSERT_EQ(rsp->body.hopct+1, rsp->body.value);
tinfo->rsp_recv++;
VERBPRN("ProtobufCliSrvCFNonblocking test got rsp, value=%u errval=%u\n", rsp->body.value, rsp->errval);
} else {
tinfo->bnc_recv++;
VERBPRN("ProtobufCliSrvCFNonblocking test got bnc=%d\n", (int)req->hdr.bnc);
}
return;
req=req;
}
#define GETTID() syscall(SYS_gettid)
static void mycfb_timer_cb(rwsched_CFRunLoopTimerRef timer, void *info) {
struct mycfbtaskinfo *tinfo = (struct mycfbtaskinfo *)info;
ASSERT_TRUE(tinfo->cftim != NULL);
/*oops ASSERT_EQ(tinfo->cftim, timer);*/
if (tinfo->ctx->assertsinglethread) {
uint64_t tid = GETTID();
if (!tinfo->tid) {
tinfo->tid = tid;
} else {
ASSERT_EQ(tinfo->tid, tid);
}
if (!tinfo->ctx->tid) {
tinfo->ctx->tid = tid;
} else {
ASSERT_EQ(tinfo->ctx->tid, tid);
}
}
if (tinfo->req_sent >= tinfo->ctx->msgct_end) {
if (tinfo->req_sent <= (tinfo->bnc_recv + tinfo->rsp_recv)) {
RW_ASSERT(tinfo->req_sent == (tinfo->bnc_recv + tinfo->rsp_recv));
if (tinfo->cftim) {
VERBPRN("Stopping timer after response %u + bnc %u in tasklet '%s'\n",
tinfo->rsp_recv,
tinfo->bnc_recv,
tinfo->tpath);
rwsched_tasklet_CFRunLoopTimerInvalidate(tinfo->tasklet, tinfo->cftim);
tinfo->cftim = 0;
tinfo->ctx->timerct--;
if (!tinfo->ctx->timerct) {
VERBPRN("All tasklet timers gone, ending runloop\n");
//CFRunLoopStop(tinfo->ctx->loop);
CFRunLoopStop(rwsched_tasklet_CFRunLoopGetCurrent(tinfo->tasklet));
tinfo->ctx->done = 1;
}
}
}
return;
}
TestReq req;
test_req__init(&req);
for (uint32_t i=0; i<tinfo->ctx->burst; i++) {
rwmsg_request_t *rwreq=NULL;
req.body.value = tinfo->req_sent;
req.body.hopct = tinfo->req_sent;
if (tinfo->ctx->doblocking) {
rw_status_t rs;
rwreq = NULL;
VERBPRN("ProtobufCliSrvCFBlocking test sending req, value=%u burst i=%u\n", req.body.value, i);
rs = test__increment_b(&tinfo->mycli, tinfo->dt, &req, &rwreq);
ASSERT_EQ(rs, RW_STATUS_SUCCESS);
ASSERT_EQ(RWMSG_PAYFMT_PBAPI, rwmsg_request_get_response_payfmt(rwreq));
const TestRsp *rsp;
rs = rwmsg_request_get_response(rwreq, (const void **)&rsp);
ASSERT_EQ(rs, RW_STATUS_SUCCESS);
tinfo->req_sent++;
VERBPRN("ProtobufCliSrvCFBlocking test got rsp, errval=%u, burst i=%u\n", rsp->errval, i);
mycfb_response(rsp, rwreq, info);
} else {
rwmsg_closure_t cb;
cb.pbrsp=(rwmsg_pbapi_cb)mycfb_response;
cb.ud=tinfo;
VERBPRN("ProtobufCliSrvCFNonblocking test sending req, value=%u burst i=%u\n", req.body.value, i);
rw_status_t rs;
rs = test__increment(&tinfo->mycli, tinfo->dt, &req, &cb, &rwreq);
switch (rs) {
case RW_STATUS_SUCCESS:
VERBPRN("ProtobufCliSrvCFNonblocking test sent req, burst i=%u\n", i);
tinfo->req_sent++;
break;
case RW_STATUS_BACKPRESSURE:
VERBPRN("ProtobufCliSrvCFNonblocking test got backpressure, burst i=%u\n", i);
tinfo->req_eagain++;
break;
default:
ASSERT_EQ(rs, RW_STATUS_SUCCESS);
break;
}
}
}
tinfo->tickct++;
tinfo->ctx->tickct++;
return;
timer=timer;
}
static void Test_increment(Test_Service *,
const TestReq *req,
void *ud,
TestRsp_Closure clo,
void *rwmsg) {
TestRsp rsp;
test_rsp__init(&rsp);
/* Fill in a response, including a copy of the adjusted request body with the value bumped */
rsp.errval = 0;
rsp.has_body = TRUE;
rsp.body = req->body;
rsp.body.value++;
VERBPRN(" Test_increment(value=%u) returning value=%u\n", req->body.value, rsp.body.value);
/* Send the response */
clo(&rsp, rwmsg);
return;
ud=ud;
}
static void Test_fail(Test_Service *,
const TestReq *req,
void *ud,
TestNop_Closure clo,
void *rwmsg) {
TestNop rsp;
test_nop__init(&rsp);
if (req->body.value) {
VERBPRN(" Test_fail(value=%u) returning errval=1\n", req->body.value);
}
rsp.errval = 1;
clo(&rsp, rwmsg);
return;
ud=ud;
}
/** \if NOPE */
static void pbcscf(int taskct, int doblocking, uint32_t burst, uint32_t startburst, uint32_t endat, int broker) {
ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0);
nnchk();
VERBPRN("ProtobufCliSrvCFNonblocking test begin, taskct=%d doblocking=%d burst=%u startburst=%u endat=%u broker=%d\n",
taskct,
doblocking,
burst,
startburst,
endat,
broker);
struct mycfbctx tctx;
struct mycfbtaskinfo *tinfo = (struct mycfbtaskinfo*)RW_MALLOC0(sizeof(*tinfo) * taskct);
memset(&tctx, 0, sizeof(tctx));
/*
* Create a rwsched / tasklet runtime and the one rwmsg endpoint for
* this tasklet. (Probably all handled in tasklet infrastructure).
* broker = -1 ==> no shunt
* broker = 0 ==> no broker
* broker > 0 ==> number of brokers
*/
unsigned broker_c = (broker<0?1:broker);
rwmsg_btenv_t tenv(taskct+(broker_c?broker_c:1)); // test env, on stack, dtor cleans up
ASSERT_TRUE(tenv.rwsched != NULL);
rwmsg_broker_t *bros[broker_c];
memset(bros, 0, sizeof(bros));
if (broker_c) {
for (unsigned i=0; i<broker_c; i++) {
//fprintf(stderr, "tasklet.broker[%u]=%p\n",i, tenv.tasklet[tenv.tasklet_ct-(broker_c-i)]);
tenv.ti->rwsched_tasklet_info = tenv.tasklet[tenv.tasklet_ct-(broker_c-i)];
rwmsg_broker_main(broport_g, tenv.tasklet_ct-(broker_c-i), i, tenv.rwsched, tenv.tasklet[tenv.tasklet_ct-(broker_c-i)], tenv.rwcal, TRUE, tenv.ti, &bros[i]);
//tctx.bro = bro;
}
}
rwsched_instance_CFRunLoopRunInMode(tenv.rwsched, RWMSG_RUNLOOP_MODE, 1, FALSE);
const char *taddrbase = "/L/GTEST/RWBRO/TESTAPP/PBSCF";
char taddrpfx[128];
static unsigned testct = 100;
sprintf(taddrpfx, "%s/%u", taddrbase, testct++);
tctx.rwsched = tenv.rwsched;
tctx.doblocking = doblocking;
tctx.burst = burst;
tctx.msgct_end = endat;
tctx.assertsinglethread = FALSE;
tctx.tid = GETTID();
for (unsigned t=0; t<tenv.tasklet_ct-(broker_c?broker_c:1)/*brokers are last ones*/; t++) {
//fprintf(stderr, "tasklet[%u]=%p\n",t, tenv.tasklet[t]);
tinfo[t].tnum = t;
tinfo[t].ctx = &tctx;
tinfo[t].tasklet = tenv.tasklet[t];
sprintf(tinfo[t].tpath, "%s/%d", taddrpfx, t);
sprintf(tinfo[t].tpeerpath, "%s/%d", taddrpfx, (t&1) ? t-1 : t+1);
tinfo[t].ep = rwmsg_endpoint_create(1, t, (broker_c?(t%broker_c):0), tenv.rwsched, tenv.tasklet[t], rwtrace_init(), NULL);
ASSERT_TRUE(tinfo[t].ep != NULL);
/* Direct everything through the broker */
rwmsg_endpoint_set_property_int(tinfo[t].ep, "/rwmsg/broker/shunt", (broker > 0)); // no shunt when broker==-1
rwsched_CFRunLoopRef runloop = rwsched_tasklet_CFRunLoopGetCurrent(tenv.tasklet[t]);
if (t&1) {
/* Create a server channel in odd numbered tasklets */
tinfo[t].sc = rwmsg_srvchan_create(tinfo[t].ep);
ASSERT_TRUE(tinfo[t].sc != NULL);
/* Instantiate the 'Test' protobuf service as the set of callbacks
* named Test_<x>, and bind this Test service to our server channel
* at the given nameservice location.
*/
TEST__INITSERVER(&tinfo[t].myapisrv, Test_);
rw_status_t rs = rwmsg_srvchan_add_service(tinfo[t].sc,
tinfo[t].tpath,
&tinfo[t].myapisrv.base,
&tinfo[t]);
ASSERT_EQ(rs, RW_STATUS_SUCCESS);
rs = rwmsg_srvchan_bind_rwsched_cfrunloop(tinfo[t].sc,
tenv.tasklet[t]);
ASSERT_EQ(rs, RW_STATUS_SUCCESS);
} else {
/* Create a client channel pointing at the Test service's path.
* Instantiate a Test service client and connect this to the client
* channel.
*/
tinfo[t].dt = rwmsg_destination_create(tinfo[t].ep, RWMSG_ADDRTYPE_UNICAST, tinfo[t].tpeerpath);
ASSERT_TRUE(tinfo[t].dt != NULL);
tinfo[t].cc = rwmsg_clichan_create(tinfo[t].ep);
ASSERT_TRUE(tinfo[t].cc != NULL);
TEST__INITCLIENT(&tinfo[t].mycli);
rwmsg_clichan_add_service(tinfo[t].cc, &tinfo[t].mycli.base);
rw_status_t rs = rwmsg_clichan_bind_rwsched_cfrunloop(tinfo[t].cc,
tenv.tasklet[t]);
ASSERT_EQ(rs, RW_STATUS_SUCCESS);
/* Send some requests right away, test pre-connection request
buffering in ssbufq. They may happen still to bounce should
the server not have connected yet to the broker by the time
the req gets there. */
if (startburst) {
RW_ASSERT(!tctx.doblocking); // no can do
rwmsg_closure_t cb;
cb.pbrsp=(rwmsg_pbapi_cb)mycfb_response;
cb.ud=tinfo;
uint32_t u=0;
rw_status_t rs = RW_STATUS_SUCCESS;
for (u=0; rs == RW_STATUS_SUCCESS && u<startburst; u++) {
TestReq req;
test_req__init(&req);
rwmsg_request_t *rwreq=NULL;
req.body.value = tinfo[t].req_sent;
req.body.hopct = tinfo[t].req_sent;
VERBPRN("ProtobufCliSrvCFNonblocking test sending req, value=%u burst u=%u\n", req.body.value, u);
rs = test__increment(&tinfo[t].mycli, tinfo[t].dt, &req, &cb, &rwreq);
switch (rs) {
case RW_STATUS_SUCCESS:
VERBPRN("ProtobufCliSrvCFNonblocking test sent req, burst u=%u\n", u);
tinfo[t].req_sent++;
break;
case RW_STATUS_BACKPRESSURE:
VERBPRN("ProtobufCliSrvCFNonblocking test got backpressure, burst u=%u\n", u);
tinfo[t].req_eagain++;
break;
case RW_STATUS_NOTCONNECTED:
VERBPRN("ProtobufCliSrvCFNonblocking test got notconected, burst u=%u\n", u);
tinfo[t].req_eagain++;
break;
default:
VERBPRN("ProtobufCliSrvCFNonblocking test got rs=%d, burst u=%u\n", rs, u);
break;
}
}
/* Figure out the ssbufq size and check that we sent at most that many */
int premax = 9999999;
rs = rwmsg_endpoint_get_property_int(tinfo[t].ep, "/rwmsg/queue/cc_ssbuf/qlen", &premax);
RW_ASSERT(rs == RW_STATUS_SUCCESS);
/* max is nominally 1 per destination due to flow window
logic, although we skate on the edge and crank it a bit.
ought to support flow/seqno application on the other end of
the queue, but that's a nightmare */
int defwin = 1;
rwmsg_endpoint_get_property_int(tinfo[t].ep, "/rwmsg/destination/defwin", &defwin);
//too gimpy a check, consider feedme vs nofeedme etc: ASSERT_EQ(tinfo[t].req_sent, MIN(defwin, MIN(premax, (int)startburst)));
}
/* Run a timer to execute some requests */
rwsched_CFRunLoopTimerContext cf_context = { 0, NULL, NULL, NULL, NULL };
double timer_interval = 200/*ms*/ * .001;
timer_interval += (t * 20/*ms*/ * .001); // extra smidge for each new tasklet to avoid stampede
double valgfactor = 1.0;
if (RUNNING_ON_VALGRIND) {
valgfactor = 2.5;
}
cf_context.info = &tinfo[t];
tinfo[t].cftim = rwsched_tasklet_CFRunLoopTimerCreate(tenv.tasklet[t],
kCFAllocatorDefault,
CFAbsoluteTimeGetCurrent() + (valgfactor * 10.0 * timer_interval), // allow a while for connections to come up
timer_interval,
0,
0,
mycfb_timer_cb,
&cf_context);
RW_CF_TYPE_VALIDATE(tinfo[t].cftim, rwsched_CFRunLoopTimerRef);
rwsched_tasklet_CFRunLoopAddTimer(tenv.tasklet[t], runloop, tinfo[t].cftim, RWMSG_RUNLOOP_MODE);//kCFRunLoopCommonModes);
tctx.timerct++;
}
}
//tctx.loop = rwsched_tasklet_CFRunLoopGetCurrent(tenv.rwsched);
struct timeval start, stop, delta;
int looptot = 60;
if (RUNNING_ON_VALGRIND) {
looptot = looptot * 5 / 2;
}
int loopwait = looptot;
VERBPRN("loop iter begin\n");
gettimeofday(&start, NULL);
do {
rwsched_instance_CFRunLoopRunInMode(tenv.rwsched, RWMSG_RUNLOOP_MODE, loopwait, FALSE);
gettimeofday(&stop, NULL);
timersub(&stop, &start, &delta);
VERBPRN("loop iter %ld.%03ld tctx.done=%d\n", delta.tv_sec, delta.tv_usec / 1000, tctx.done);
loopwait = looptot - delta.tv_sec;
} while (loopwait > 0 && !tctx.done);
ASSERT_TRUE(tctx.done);
//sleep(2);
VERBPRN("loop runtime %lu ms\n", delta.tv_sec * 1000 + delta.tv_usec / 1000);
//RW_RESOURCE_TRACK_DUMP(g_rwresource_track_handle);
for (unsigned t=0; t<tenv.tasklet_ct-(broker_c?broker_c:1)/*brokers are last ones*/; t++) {
if (t&1) {
rwmsg_srvchan_halt(tinfo[t].sc);
} else {
rwmsg_destination_release(tinfo[t].dt);
rwmsg_clichan_halt(tinfo[t].cc);
if (tinfo[t].req_eagain) {
fprintf(stderr, "Tasklet %d req_sent=%u req_eagain=%u\n", t, tinfo[t].req_sent, tinfo[t].req_eagain);
}
if (tinfo[t].bnc_recv) {
fprintf(stderr, "Tasklet %d req_sent=%u bnc_recv=%u\n", t, tinfo[t].req_sent, tinfo[t].bnc_recv);
}
ASSERT_LE(tinfo[t].bnc_recv, MAX(burst,startburst));
}
rwmsg_bool_t r;
VERBPRN("rwmsg_endpoint_halt_flush(ep=%p tasklet %d)\n", tinfo[t].ep, t);
r = rwmsg_endpoint_halt_flush(tinfo[t].ep, TRUE);
ASSERT_TRUE(r);
}
if (broker_c) {
rwmsg_bool_t r;
for (unsigned i=0; i<broker_c; i++) {
if (bros[i]) {
VERBPRN("broker_halt_sync()\n");
r = rwmsg_broker_halt_sync(bros[i]);
ASSERT_TRUE(r);
}
}
}
ASSERT_EQ(rwmsg_global.status.endpoint_ct, 0);
nnchk();
if (tinfo) {
RW_FREE(tinfo);
}
VERBPRN("ProtobufCliSrvCFNonblocking test end\n");
}
/** \endif */
TEST(RWMsgBroker, PbCliSrvCFNonblk2Bro) {
TEST_DESCRIPTION("Tests protobuf service client and server, nonblocking under taskletized CFRunloop, 2 tasklets, broker");
int taskct = 2;
int doblocking = 0;
uint32_t burst = 2;
uint32_t startburst = 0;
uint32_t endct = 2 * burst;
pbcscf(taskct, doblocking, burst, startburst, endct, 1);
}
TEST(RWMsgBroker, PbCliSrvCFNonblk2Bro2Bros) {
TEST_DESCRIPTION("Tests protobuf service client and server, nonblocking under taskletized CFRunloop, 2 tasklets, 2 broker");
int taskct = 2;
int doblocking = 0;
uint32_t burst = 2;
uint32_t startburst = 0;
uint32_t endct = 2 * burst;
pbcscf(taskct, doblocking, burst, startburst, endct, 2);
}
TEST(RWMsgBroker, PbCliSrvCFBrstNonblk2Bro) {
TEST_DESCRIPTION("Tests protobuf service client and server, nonblocking under taskletized CFRunloop, 2 tasklets, bursty, broker");
int taskct = 2;
int doblocking = 0;
uint32_t burst = 20;
uint32_t startburst = 0;
uint32_t endct = 2 * burst;
pbcscf(taskct, doblocking, burst, startburst, endct, 1);
}
TEST(RWMsgBroker, PbCliSrvCFBrstNonblk2Bro2Bros) {
TEST_DESCRIPTION("Tests protobuf service client and server, nonblocking under taskletized CFRunloop, 2 tasklets, bursty, 2 broker");
int taskct = 2;
int doblocking = 0;
uint32_t burst = 20;
uint32_t startburst = 0;
uint32_t endct = 2 * burst;
pbcscf(taskct, doblocking, burst, startburst, endct, 2);
}
TEST(RWMsgBroker, PbCliSrvCFBrstStartburst1Nonblk2Bro) {
TEST_DESCRIPTION("Tests protobuf service client and server, nonblocking under taskletized CFRunloop, 2 tasklets, bursty, startburst 1, broker");
// send one request straightaway to exercise the ssbufq buffer used to hold initial requests sent before broker connection comes up
int taskct = 2;
int doblocking = 0;
uint32_t burst = 20;
uint32_t startburst = 1;
uint32_t endct = 2 * burst;
pbcscf(taskct, doblocking, burst, startburst, endct, 1);
}
TEST(RWMsgBroker, PbCliSrvCFBrstStartburst1Nonblk2Bro2Bros) {
TEST_DESCRIPTION("Tests protobuf service client and server, nonblocking under taskletized CFRunloop, 2 tasklets, bursty, startburst 1, 2 broker");
// send one request straightaway to exercise the ssbufq buffer used to hold initial requests sent before broker connection comes up
int taskct = 2;
int doblocking = 0;
uint32_t burst = 20;
uint32_t startburst = 1;
uint32_t endct = 2 * burst;
pbcscf(taskct, doblocking, burst, startburst, endct, 2);
}
TEST(RWMsgBroker, PbCliSrvCFBrstStartburst16Nonblk2Bro) {
TEST_DESCRIPTION("Tests protobuf service client and server, nonblocking under taskletized CFRunloop, 2 tasklets, bursty, startburst 16, broker");
// this is the startup xmit buffer size
int taskct = 2;
int doblocking = 0;
uint32_t burst = 20;
uint32_t startburst = 16;
uint32_t endct = 2 * burst;
pbcscf(taskct, doblocking, burst, startburst, endct, 1);
}
TEST(RWMsgBroker, PbCliSrvCFBrstStartburst16Nonblk2Bro2Bros) {
TEST_DESCRIPTION("Tests protobuf service client and server, nonblocking under taskletized CFRunloop, 2 tasklets, bursty, startburst 16, 2 broker");
// this is the startup xmit buffer size
int taskct = 2;
int doblocking = 0;
uint32_t burst = 20;
uint32_t startburst = 16;
uint32_t endct = 2 * burst;
pbcscf(taskct, doblocking, burst, startburst, endct, 2);
}
TEST(RWMsgBroker, PbCliSrvCFBrstStartburst24Nonblk2Bro_LONG) {
TEST_DESCRIPTION("Tests protobuf service client and server, nonblocking under taskletized CFRunloop, 2 tasklets, bursty, startburst 24, broker");
// this is supposed to exceed the startup buffer and demonstrate 1+ initial requests experiencing backpressure
int taskct = 2;
int doblocking = 0;
uint32_t burst = 20;
uint32_t startburst = 24;
uint32_t endct = 2 * burst;
pbcscf(taskct, doblocking, burst, startburst, endct, 1);
}
TEST(RWMsgBroker, PbCliSrvCFBrstStartburst24Nonblk2Bro2Bros) {
TEST_DESCRIPTION("Tests protobuf service client and server, nonblocking under taskletized CFRunloop, 2 tasklets, bursty, startburst 24, 2 broker");
// this is supposed to exceed the startup buffer and demonstrate 1+ initial requests experiencing backpressure
int taskct = 2;
int doblocking = 0;
uint32_t burst = 20;
uint32_t startburst = 24;
uint32_t endct = 2 * burst;
pbcscf(taskct, doblocking, burst, startburst, endct, 2);
}
TEST(RWMsgBroker, PbCliSrvCFBlk2Bro) {
TEST_DESCRIPTION("Tests protobuf service client and server, blocking under taskletized CFRunloop, 2 tasklets, broker");
int taskct = 2;
int doblocking = 1;
uint32_t burst = 2;
uint32_t startburst = 0;
uint32_t endct = 2 * burst;
pbcscf(taskct, doblocking, burst, startburst, endct, 1);
}
TEST(RWMsgBroker, PbCliSrvCFBlk2Bro2Bros) {
TEST_DESCRIPTION("Tests protobuf service client and server, blocking under taskletized CFRunloop, 2 tasklets, 2 broker");
int taskct = 2;
int doblocking = 1;
uint32_t burst = 1;
uint32_t startburst = 0;
uint32_t endct = 2 * burst;
pbcscf(taskct, doblocking, burst, startburst, endct, 2);
}
TEST(RWMsgBroker, PbCliSrvCFNonblk2BroIdle) {
TEST_DESCRIPTION("Tests protobuf service client and server, nonblocking under taskletized CFRunloop, 2 tasklets, no shunt to broker");
int taskct = 2;
int doblocking = 0;
uint32_t burst = 2;
uint32_t startburst = 0;
uint32_t endct = 2 * burst;
pbcscf(taskct, doblocking, burst, startburst, endct, -1);
}
TEST(RWMsgBrokerNot, PbCliSrvCFNonblk2) {
TEST_DESCRIPTION("Tests protobuf service client and server, nonblocking under taskletized CFRunloop, 2 tasklets, no broker");
int taskct = 2;
int doblocking = 0;
uint32_t startburst = 0;
uint32_t burst = 2;
uint32_t endct = 2 * burst;
pbcscf(taskct, doblocking, burst, startburst, endct, 0);
}
struct lottaopts {
int bigbrosrvwin;
int bigdefwin;
int reqtimeo;
int bncall;
int srvrspfromanyq;
uint32_t paysz;
};
struct lottarawvals {
uint64_t sec;
uint64_t flushtime;
uint64_t rmax;
uint64_t reqsent;
uint64_t firstburst;
uint64_t reqans;
uint64_t reqdone;
uint64_t reqbnc;
uint64_t reqbnc_final;
uint64_t reqhz;
uint64_t min_rtt;
uint64_t max_rtt;
};
struct sctest1_payload {
uint32_t rno;
char str[200];
};
struct sctest1_context {
int verbose;
int window;
int tokenbucket;
uint32_t tokenfill_ct;
int flowexercise;
struct lottaopts *opts;
struct sctest1_payload *paybuf;
rwmsg_flowid_t flowid;
int unpout;
int usebro;
int ccwaiting;
uint32_t rcvburst;
int sendmore;
int sendone;
uint32_t sendmsg_firstburst_done;
uint32_t sendmsg_preflow;
uint32_t kickct;
uint32_t done;
rwmsg_srvchan_t *sc;
rwmsg_clichan_t *cc;
rwmsg_destination_t *dt;
uint64_t sc_tid;
uint64_t cc_tid;
int checktid;
rwmsg_signature_t *sig;
#define SCTEST1_RMAX (10000)
uint32_t rmax;
uint32_t misorderct;
/* Keep a queue of the request transmit order, to compare with response arrival order */
uint32_t expectedreqno[SCTEST1_RMAX+50];
uint32_t expectedreqno_head;
uint32_t expectedreqno_tail;
#define SCTEST1_RNO_ENQ(ctx, rno) { \
((ctx)->expectedreqno[(ctx)->expectedreqno_tail] = (rno)); \
if ((++(ctx)->expectedreqno_tail) >= ((ctx)->rmax + 50)) { \
(ctx)->expectedreqno_tail = 0; \
} \
}
#define SCTEST1_RNO_DEQ(ctx) ({ \
ASSERT_NE((ctx)->expectedreqno_head , (ctx)->expectedreqno_tail); \
int rno=((ctx)->expectedreqno[(ctx)->expectedreqno_head]); \
if ((++(ctx)->expectedreqno_head) >= ((ctx)->rmax + 50)) { \
(ctx)->expectedreqno_head = 0; \
} \
rno; \
})
uint32_t paysz;
rwmsg_request_t *r[SCTEST1_RMAX];
uint32_t in;
uint32_t out;
uint32_t rspin;
uint32_t rspout;
uint32_t bncout;
uint32_t miss;
uint64_t min_rtt;
uint64_t max_rtt;
rwsched_dispatch_queue_t rwq[2];
rwsched_dispatch_source_t sc_timer;
rwmsg_btenv_t *tenv;
};
#define GETTID() syscall(SYS_gettid)
static void lottakickoff(void *ctx_in);
static void sctest1_clicb_feedme(void *ctx_in, rwmsg_destination_t *dest, rwmsg_flowid_t flowid) {
RW_ASSERT_TYPE(ctx_in, sctest1_context);
struct sctest1_context *ctx = (struct sctest1_context*)ctx_in;
if (ctx->verbose) {
fprintf(stderr, "sctest1_clicb_feedme: dest='%s',flowid=%u\n", dest->apath, flowid);
}
lottakickoff(ctx_in);
}
static void sctest1_clicb1(rwmsg_request_t *req, void *ctx_in) {
RW_ASSERT_TYPE(ctx_in, sctest1_context);
struct sctest1_context *ctx = (struct sctest1_context*)ctx_in;
int expected = 0;
if (ctx->sc_tid) {
if (!ctx->cc_tid) {
ctx->cc_tid = GETTID();
if (ctx->checktid) {
EXPECT_EQ(ctx->cc_tid, ctx->sc_tid);
}
} else if (ctx->checktid) {
uint64_t curtid = GETTID();
EXPECT_EQ(ctx->cc_tid, curtid);
ctx->cc_tid = curtid;
}
}
/* clichan request callback */
if (1 || ctx->flowexercise) {
/* Register for the flow control callback the first time, or rather when the flowid changes */
rwmsg_flowid_t fid = rwmsg_request_get_response_flowid(req);
if (fid && fid != ctx->flowid) {
ctx->flowid = fid;
rwmsg_closure_t cb = { };
cb.ud = ctx;
cb.feedme = sctest1_clicb_feedme;
rw_status_t rs = rwmsg_clichan_feedme_callback(ctx->cc, ctx->dt, ctx->flowid, &cb);
EXPECT_EQ(rs, RW_STATUS_SUCCESS);
//ASSERT_GT(rwmsg_clichan_can_send_howmuch(ctx->cc, ctx->dt, ctx->sig->methno, ctx->sig->payt), 0);
}
}
uint32_t len=0;
const struct sctest1_payload *rsp = (const struct sctest1_payload*)rwmsg_request_get_response_payload(req, &len);
uint32_t rno;
uint64_t rtt = rwmsg_request_get_response_rtt(req);
if (rtt > 0) {
if (rtt < ctx->min_rtt) {
ctx->min_rtt = rtt;
}
if (rtt > ctx->max_rtt) {
ctx->max_rtt = rtt;
}
}
if (rsp) {
ck_pr_inc_32(&ctx->rspout);
if (ctx->verbose) {
fprintf(stderr, "sctest1_clicb1: got rsp len=%d rno=%u str='%s'\n", len, rsp->rno, rsp->str);
}
int ticks = (RUNNING_ON_VALGRIND ? 100 : 10000);
if (ctx->rspout < 1000) {
ticks = 100;
}
if (ctx->rspout % ticks == 0) {
fprintf(stderr, "_");
}
RW_ASSERT(rsp->rno < ctx->rmax);
rno = rsp->rno;
} else {
ck_pr_inc_32(&ctx->bncout);
rwmsg_bounce_t bcode = rwmsg_request_get_response_bounce(req);
int bcodeint = (int)bcode;
const char *bncdesc[] = {
"OK",
"NODEST",
"NOMETH",
"NOPEER",
"BROKERR",
"TIMEOUT",
"RESET",
"TERM",
NULL
};
RW_ASSERT(bcodeint < RWMSG_BOUNCE_CT);
if (ctx->bncout < 10) {
fprintf(stderr, "b(%s)", bncdesc[bcodeint]);
}
if (ctx->bncout % 1000 == 0) {
fprintf(stderr, "B(%s)", bncdesc[bcodeint]);
}
for (rno = 0; rno < ctx->rmax; rno++) {
if (req == ctx->r[rno]) {
goto found;
}
}
fprintf(stderr, "sctest1_clicb1: bnc req=%p not found!?\n", req);
RW_ASSERT(rno < ctx->rmax);
if (!ctx->sendmore) {
goto checkend;
}
return;
found:
;
// fprintf(stderr, "sctest1_clicb1: req rno=%d had no rsp payload!?\n", rno);
}
/* Verify responses are in order, up until -- or shortly before! -- we get a bounce, at which point all bets are off */
expected = SCTEST1_RNO_DEQ(ctx);
if (!ctx->bncout) {
if ((int)rno != expected) {
ctx->misorderct++;
}
}
/* req ceases to be valid when we return, so find and clear our handle to it */
RW_ASSERT(rno < ctx->rmax);
RW_ASSERT(ctx->r[rno]);
ctx->r[rno] = NULL;
/* If the test has the repeat flag set, reissue another request */
if (ctx->sendmore) {
RW_ASSERT(ctx->cc);
ctx->r[rno] = rwmsg_request_create(ctx->cc);
ASSERT_TRUE(ctx->r[rno] != NULL);
rwmsg_request_set_signature(ctx->r[rno], ctx->sig);
rwmsg_closure_t clicb;
clicb.request=sctest1_clicb1;
clicb.ud=ctx;
rwmsg_request_set_callback(ctx->r[rno], &clicb);
memset(ctx->paybuf, 0, sizeof(struct sctest1_payload));
ctx->paybuf->rno = rno;
sprintf(ctx->paybuf->str, "hi there rno=%d", rno);
rwmsg_request_set_payload(ctx->r[rno], ctx->paybuf, MAX(ctx->paysz, sizeof(struct sctest1_payload)));
/* Send it. The srvchan should more or less immediately run the
thing and the methcb will respond. */
ck_pr_inc_32(&ctx->in);
rw_status_t rs = rwmsg_clichan_send(ctx->cc, ctx->dt, ctx->r[rno]);
if (rs == RW_STATUS_BACKPRESSURE) { // && ctx->flowexercise)
if (ctx->verbose) {
fprintf(stderr, "sctest1_clicb1 _send rno=%u backpressure\n", rno);
}
ck_pr_dec_32(&ctx->in);
rwmsg_request_release(ctx->r[rno]);
ctx->r[rno] = NULL;
ctx->ccwaiting = TRUE;
/* backpressure will trigger feedme callback */
} else if (rs != RW_STATUS_SUCCESS) {
ck_pr_dec_32(&ctx->in);
rwmsg_request_release(ctx->r[rno]);
ctx->r[rno] = NULL;
ctx->sendmore = FALSE;
fprintf(stderr, "sctest1_clicb1: rwmsg_clichan_send() rs=%u\n", rs);
} else {
/* We should not have two out with the same ID */
if (ctx->verbose) {
fprintf(stderr, "sctest1_clicb1 _send rno=%u sent, ccwaiting now 0\n", rno);
}
SCTEST1_RNO_ENQ(ctx, rno);
ctx->ccwaiting = FALSE;
uint32_t rr;
for (rr = 0; rr < ctx->rmax; rr++) {
if (ctx->r[rr] && rr != rno) {
if (ctx->usebro) {
RW_ASSERT(ctx->r[rr]->hdr.id.locid != ctx->r[rno]->hdr.id.locid);
}
}
}
}
if (1 || ctx->flowexercise) {
lottakickoff(ctx);
}
} else {
checkend:
if ((ctx->bncout + ctx->rspout) == ctx->in) {
ctx->done = TRUE;
}
}
}
static void lottakickoff(void *ctx_in) {
/* Send the actual request(s). The rsp callback will repeat them as they are answered (ctx->repeat) */
RW_ASSERT_TYPE(ctx_in, sctest1_context);
struct sctest1_context *ctx = (struct sctest1_context*)ctx_in;
int rno=0;
RW_ASSERT(ctx->window <= SCTEST1_RMAX);
ctx->rmax = ctx->window;
int sent = 0, slots = 0, backp = 0, snderr = 0;
for (rno=0; rno < (int)ctx->rmax && (ctx->sendmore || (!ctx->sendmore && ctx->sendone)) && rwmsg_clichan_can_send_howmuch(ctx->cc, ctx->dt, ctx->sig->methno, ctx->sig->payt); rno++) {
RW_ASSERT(rno <= SCTEST1_RMAX);
if (!ctx->r[rno]) {
slots++;
ctx->r[rno] = rwmsg_request_create(ctx->cc);
ASSERT_TRUE(ctx->r[rno] != NULL);
rwmsg_request_set_signature(ctx->r[rno], ctx->sig);
rwmsg_closure_t clicb;
clicb.request=sctest1_clicb1;
clicb.ud=ctx;
rwmsg_request_set_callback(ctx->r[rno], &clicb);
memset(ctx->paybuf, 0, sizeof(struct sctest1_payload));
ctx->paybuf->rno = rno;
sprintf(ctx->paybuf->str, "hi there rno=%d", rno);
rwmsg_request_set_payload(ctx->r[rno], ctx->paybuf, MAX(ctx->paysz, sizeof(struct sctest1_payload)));
/* Send it. */
ck_pr_inc_32(&ctx->in);
rw_status_t rs = rwmsg_clichan_send(ctx->cc, ctx->dt, ctx->r[rno]);
if (rs == RW_STATUS_SUCCESS) {
if (!ctx->sendmsg_firstburst_done) {
//RW_ASSERT(!ctx->flowid);
ctx->sendmsg_preflow++;
}
SCTEST1_RNO_ENQ(ctx, rno);
sent++;
} else {
ctx->sendmsg_firstburst_done = TRUE;
if (rs == RW_STATUS_BACKPRESSURE) {
backp++;
if (ctx->verbose) {
fprintf(stderr, "lottakickoff _send rno=%u backpressure\n", rno);
}
ck_pr_dec_32(&ctx->in);
rwmsg_request_release(ctx->r[rno]);
ctx->r[rno] = NULL;
if (!ctx->ccwaiting) {
ctx->ccwaiting = TRUE;
if (ctx->verbose) {
fprintf(stderr, "lottakickoff backpressure ccwaiting=%d\n", ctx->ccwaiting);
}
}
goto out;
} else if (rs != RW_STATUS_SUCCESS) {
snderr++;
ck_pr_dec_32(&ctx->in);
rwmsg_request_release(ctx->r[rno]);
ctx->r[rno] = NULL;
ctx->sendmore = FALSE;
fprintf(stderr, "sctest1_clicb1: rwmsg_clichan_send() rs=%u\n", rs);
} else {
if (ctx->verbose) {
fprintf(stderr, "sctest1_clicb1 _send rno=%u sent, ccwaiting now 0\n", rno);
}
ctx->ccwaiting = FALSE;
if (0 && ctx->in >= 5) {
fprintf(stderr, "lottakickoff sendmore=FALSE hack\n");
ctx->sendmore = FALSE;
}
}
}
}
}
out:
if (ctx->verbose) {
fprintf(stderr, "lottakickoff slots=%d sent=%d backp=%d snderr=%d sendmore=%d\n", slots, sent, backp, snderr, ctx->sendmore);
}
ctx->kickct++;
}
static void sctest1_clicb02(rwmsg_request_t *req, void *ctx_in);
static void sctest1_reqsend(void *ctx_in) {
RW_ASSERT_TYPE(ctx_in, sctest1_context);
struct sctest1_context *ctx = (struct sctest1_context*)ctx_in;
rwmsg_request_t *req;
#if 0
static unsigned long long tids[100] = {0};
static int l_tid=0;
int i;
unsigned long long tid = GETTID();
for (i=0; i<l_tid;i++) {
if (tids[i] == tid) break;
}
if (i>=l_tid) {
// fprintf(stderr, "sctest1_clicb02: Thread 0x%llx cc=%p\n", tid, ctx->cc);
tids[l_tid] = tid;
l_tid++;
}
#endif
req = rwmsg_request_create(ctx->cc);
ASSERT_TRUE(req != NULL);
rwmsg_request_set_signature(req, ctx->sig);
rwmsg_closure_t clicb;
clicb.request=sctest1_clicb02;
clicb.ud=ctx;
rwmsg_request_set_callback(req, &clicb);
memset(ctx->paybuf, 0, sizeof(struct sctest1_payload));
ctx->paybuf->rno = 0;
sprintf(ctx->paybuf->str, "hi there rno=%d", 0);
rwmsg_request_set_payload(req, ctx->paybuf, MAX(ctx->paysz, sizeof(struct sctest1_payload)));
/* Send it. The srvchan should more or less immediately run the
thing and the methcb will respond. */
ck_pr_inc_32(&ctx->in);
rw_status_t rs = rwmsg_clichan_send(ctx->cc, ctx->dt, req);
if (rs == RW_STATUS_BACKPRESSURE) { // && ctx->flowexercise)
if (ctx->verbose) {
fprintf(stderr, "sctest1_clicb02 _send rno=%u backpressure\n", 0);
}
ck_pr_dec_32(&ctx->in);
rwmsg_request_release(req);
req = NULL;
ctx->ccwaiting = TRUE;
/* backpressure will trigger feedme callback */
} else if (rs != RW_STATUS_SUCCESS) {
ck_pr_dec_32(&ctx->in);
rwmsg_request_release(req);
req = NULL;
ctx->sendmore = FALSE;
fprintf(stderr, "sctest1_clicb02: rwmsg_clichan_send() rs=%u\n", rs);
}
}
static void sctest1_clicb02(rwmsg_request_t *req, void *ctx_in) {
RW_ASSERT_TYPE(ctx_in, sctest1_context);
struct sctest1_context *ctx = (struct sctest1_context*)ctx_in;
if (ctx->sc_tid) {
if (!ctx->cc_tid) {
ctx->cc_tid = GETTID();
if (ctx->checktid) {
EXPECT_EQ(ctx->cc_tid, ctx->sc_tid);
}
} else if (ctx->checktid) {
uint64_t curtid = GETTID();
EXPECT_EQ(ctx->cc_tid, curtid);
ctx->cc_tid = curtid;
}
}
/* clichan request callback */
uint32_t len=0;
const struct sctest1_payload *rsp = (const struct sctest1_payload*)rwmsg_request_get_response_payload(req, &len);
uint64_t rtt = rwmsg_request_get_response_rtt(req);
if (rtt > 0) {
if (rtt < ctx->min_rtt) {
ctx->min_rtt = rtt;
}
if (rtt > ctx->max_rtt) {
ctx->max_rtt = rtt;
}
}
if (rsp) {
ck_pr_inc_32(&ctx->rspout);
if (ctx->verbose) {
fprintf(stderr, "sctest1_clicb02: got rsp len=%d rno=%u str='%s'\n", len, rsp->rno, rsp->str);
}
int ticks = (RUNNING_ON_VALGRIND ? 100 : 10000);
if (ctx->rspout < 1000) {
ticks = 100;
}
if (ctx->rspout % ticks == 0) {
fprintf(stderr, "_");
}
RW_ASSERT(rsp->rno < ctx->rmax);
//rno = rsp->rno;
} else {
ck_pr_inc_32(&ctx->bncout);
if (!ctx->sendmore) {
goto checkend;
}
return;
}
/* If the test has the repeat flag set, reissue another request */
if (ctx->sendmore) {
RW_ASSERT(ctx->cc);
sctest1_reqsend(ctx_in);
} else {
checkend:
if ((ctx->bncout + ctx->rspout) == ctx->in) {
ctx->done = TRUE;
}
}
}
static void lottakickoff02(void *ctx_in) {
/* Send the actual request(s). The rsp callback will repeat them as they are answered (ctx->repeat) */
RW_ASSERT_TYPE(ctx_in, sctest1_context);
struct sctest1_context *ctx = (struct sctest1_context*)ctx_in;
int rno=0;
RW_ASSERT(ctx->window <= SCTEST1_RMAX);
ctx->rmax = ctx->window;
int sent = 0, slots = 0, backp = 0, snderr = 0;
for (rno=0; rno < (int)ctx->rmax && (ctx->sendmore || (!ctx->sendmore && ctx->sendone)); rno++) {
RW_ASSERT(rno <= SCTEST1_RMAX);
sctest1_reqsend(ctx_in);
}
if (ctx->verbose) {
fprintf(stderr, "lottakickoff02 slots=%d sent=%d backp=%d snderr=%d sendmore=%d\n", slots, sent, backp, snderr, ctx->sendmore);
}
ctx->kickct++;
}
static void sctest1_refill_bucket(struct sctest1_context *ctx) {
#define TOKVAL (VERBOSE() ? 4 : (RUNNING_ON_VALGRIND ? 25 : 100) )
ctx->tokenbucket = TOKVAL;
ck_pr_inc_32(&ctx->tokenfill_ct);
}
static void sctest1_timer(void *ctx_in) {
RW_ASSERT_TYPE(ctx_in, sctest1_context);
struct sctest1_context *ctx = (struct sctest1_context*)ctx_in;
sctest1_refill_bucket(ctx);
rwmsg_srvchan_resume(ctx->sc);
}
struct sctest1_worker_handle {
rwmsg_request_t *req;
struct sctest1_context *ctx;
};
static void sctest1_methcb1_worker_f(void *ud) {
struct sctest1_worker_handle *han = (struct sctest1_worker_handle *)ud;
rwmsg_request_t *req = han->req;
struct sctest1_context *ctx = han->ctx;
if (!ctx->opts->bncall) {
uint32_t paylen=0;
const struct sctest1_payload *pay = (const struct sctest1_payload*)rwmsg_request_get_request_payload(req, &paylen);
if (pay) {
if (ctx->verbose) {
fprintf(stderr, "sctest1_methcb1 got msg in=%u paylen=%u rno=%u str='%s' ctx->in=%u ctx->out=%u\n",
ctx->in, paylen, pay->rno, pay->str, ctx->in, ctx->out);
}
static uint32_t outct = 0;
struct sctest1_payload payout;
memset(&payout, 0, sizeof(payout));
outct++;
payout.rno = pay->rno;
sprintf(payout.str, "response payload number %u to input msg '%s'",
outct,
pay ? pay->str : "");
rw_status_t rs = rwmsg_request_send_response(req, &payout, sizeof(payout));
ASSERT_EQ(rs, RW_STATUS_SUCCESS);
ck_pr_inc_32(&ctx->rspin);
} else {
rw_status_t rs = rwmsg_request_send_response(req, NULL, 0);
ASSERT_EQ(rs, RW_STATUS_SUCCESS);
ck_pr_inc_32(&ctx->rspin);
}
int ticks = (RUNNING_ON_VALGRIND ? 100 : 10000);
if (ctx->rspin < 1000) {
ticks = 100;
}
if (ctx->rspin % ticks == 0) {
fprintf(stderr, "+");
}
if (ctx->flowexercise) {
ASSERT_TRUE(ctx->tokenbucket > 0);
if (--ctx->tokenbucket <= 0) {
rwmsg_srvchan_pause(ctx->sc);
if (ctx->verbose) {
fprintf(stderr, "sctest1_methcb1 drained bucket, invoking srvchan_pause\n");
}
}
}
}
free(han);
}
static void sctest1_methcb1(rwmsg_request_t *req, void *ctx_in) {
static int once=0;
RW_ASSERT(!once);
once=1;
RW_ASSERT_TYPE(ctx_in, sctest1_context);
struct sctest1_context *ctx = (struct sctest1_context*)ctx_in;
if (ctx->flowexercise) {
if (ctx->tokenbucket == 0) {
ASSERT_TRUE(ctx->sc->ch.paused_user);
}
ASSERT_TRUE(ctx->tokenbucket > 0);
}
/* srvchan method callback */
if (!ctx->sc_tid) {
ctx->sc_tid = GETTID();
} else if (ctx->checktid) {
uint64_t curtid = GETTID();
EXPECT_EQ(ctx->sc_tid, curtid);
ctx->sc_tid = curtid;
}
ck_pr_inc_32(&ctx->out);
struct sctest1_worker_handle *han = (struct sctest1_worker_handle*)malloc(sizeof(*han));
han->req = req;
han->ctx = ctx;
if (ctx->opts->srvrspfromanyq) {
rwsched_dispatch_queue_t q = rwsched_dispatch_get_global_queue(ctx->tenv->tasklet[0], DISPATCH_QUEUE_PRIORITY_DEFAULT);
RW_ASSERT(q);
RW_ASSERT_TYPE(q, rwsched_dispatch_queue_t);
rwsched_dispatch_async_f(ctx->tenv->tasklet[0],
q,
han,
sctest1_methcb1_worker_f);
} else {
sctest1_methcb1_worker_f(han);
}
ck_pr_barrier();
RW_ASSERT(once);
once=0;
}
static void lottaraw(int squat, int mainq, int fixedrateserver, int window, int usebro, int broflo, struct lottaopts *opts, struct lottarawvals *valsout) {
uint32_t start_reqct = rwmsg_global.status.request_ct;
VERBPRN("begin rwmsg_global.status.request_ct=%u\n", rwmsg_global.status.request_ct);
rwmsg_btenv_t tenv(2); // test env, on stack, dtor cleans up
ASSERT_TRUE(tenv.rwsched != NULL);
if (valsout) {
memset(valsout, 0, sizeof(*valsout));
}
if (RUNNING_ON_VALGRIND) {
window /= 10;
window = MAX(1, window);
}
rwmsg_broker_t *bro=NULL;
tenv.ti->rwsched_tasklet_info = tenv.tasklet[1];
rwmsg_broker_main(broport_g, 1, 0, tenv.rwsched, tenv.tasklet[1], tenv.rwcal, mainq, tenv.ti, &bro);
if (broflo) {
bro->thresh_reqct2 = 10;
bro->thresh_reqct1 = 5;
}
if (opts->bigbrosrvwin) {
/* set the broker's srvchan window value really high, to cause overrun of writes to srvchan socket */
rwmsg_endpoint_set_property_int(bro->ep, "/rwmsg/broker/srvchan/window", (RUNNING_ON_VALGRIND ? 1000 : 1000000));
}
rwmsg_endpoint_t *ep;
ep = rwmsg_endpoint_create(1, 1, 0, tenv.rwsched, tenv.tasklet[0], rwtrace_init(), NULL);
ASSERT_TRUE(ep != NULL);
/* Direct everything through the broker */
rwmsg_endpoint_set_property_int(ep, "/rwmsg/broker/shunt", usebro);
if (opts->bigdefwin) {
rwmsg_endpoint_set_property_int(ep, "/rwmsg/destination/defwin", opts->bigdefwin);
}
rw_status_t rs;
struct sctest1_context *ctx = RW_MALLOC0_TYPE(sizeof(*ctx), sctest1_context);
ctx->usebro = usebro;
ctx->window = window;
ctx->tenv = &tenv;
ctx->paysz = sizeof(sctest1_payload);
if (opts) {
ctx->paysz = opts->paysz;
}
ctx->paybuf = RW_MALLOC0_TYPE(MAX(sizeof(struct sctest1_payload), ctx->paysz), sctest1_payload);
ctx->verbose = VERBOSE();
RW_ASSERT(opts);
ctx->opts = opts;
ctx->min_rtt = MAX_RTT;
ctx->checktid=0; // check thread id is same every time; adds a syscall per msg on each side
if (ctx->checktid) {
fprintf(stderr, "warning: checktid enabled\n");
}
const char *taddrpfx = "/L/GTEST/RWBRO/TESTAPP/6";
char taddr[999];
sprintf(taddr, "%s/%u", taddrpfx, rand());
const uint32_t methno = __LINE__;
/* Create the srvchan, bind a method */
ctx->sc = rwmsg_srvchan_create(ep);
ASSERT_TRUE(ctx->sc != NULL);
rwmsg_signature_t *sig = rwmsg_signature_create(ep, RWMSG_PAYFMT_RAW, methno, RWMSG_PRIORITY_DEFAULT);
ASSERT_TRUE(sig);
int timeo = 1000; // ms
if (opts->reqtimeo) {
timeo = opts->reqtimeo;
}
if (RUNNING_ON_VALGRIND) {
timeo = timeo * 5;
}
rwmsg_signature_set_timeout(sig, timeo);
ctx->sig = sig;
rwmsg_closure_t methcb;
methcb.request=sctest1_methcb1;
methcb.ud=ctx;
rwmsg_method_t *meth = rwmsg_method_create(ep, taddr, sig, &methcb);
ASSERT_TRUE(meth != NULL);
rs = rwmsg_srvchan_add_method(ctx->sc, meth);
ASSERT_EQ(rs, RW_STATUS_SUCCESS);
/* Wait on binding the srvchan until after we've sent the initial
flurry of requests. Otherwise, our ++ and the request handler's
++ of some of the request count variables ABA-stomp each
other. */
/* Create the clichan, add the method's signature */
rwmsg_destination_t *dt = rwmsg_destination_create(ep, RWMSG_ADDRTYPE_UNICAST, taddr);
ASSERT_TRUE(dt != NULL);
ctx->dt = dt;
if (squat!=2 ||
ctx->flowexercise) {
rwmsg_closure_t cb = { };
cb.ud = ctx;
cb.feedme = sctest1_clicb_feedme;
rwmsg_destination_feedme_callback(dt, &cb);
}
rwmsg_clichan_t *cc = rwmsg_clichan_create(ep);
ctx->cc = cc;
ASSERT_TRUE(cc != NULL);
//TBD/optional rwmsg_clichan_add_signature(cc, sig);
/* Bind to a serial queue */
if (mainq) {
ctx->rwq[0] = rwsched_dispatch_get_main_queue(tenv.rwsched);
ctx->rwq[1] = rwsched_dispatch_get_main_queue(tenv.rwsched);
} else {
ctx->rwq[0] = rwsched_dispatch_queue_create(tenv.tasklet[0], "ctx->rwq[0] (cc)", DISPATCH_QUEUE_SERIAL);
ctx->rwq[1] = rwsched_dispatch_queue_create(tenv.tasklet[1], "ctx->rwq[1] (sc)", DISPATCH_QUEUE_SERIAL);
}
rs = rwmsg_clichan_bind_rwsched_queue(cc, ctx->rwq[0]);
if (window == 1) {
ctx->sendmore = FALSE;
ctx->sendone = TRUE;
} else {
ctx->sendmore = TRUE;
}
/* Now bind the srvchan; at this point the srvchan will start
chewing in another thread. */
rs = rwmsg_srvchan_bind_rwsched_queue(ctx->sc, ctx->rwq[1]);
ASSERT_EQ(rs, RW_STATUS_SUCCESS);
/* Setup the srvchan to run at a fixed rate of 4 or 100 req/s, to exercise backpressure etc. */
ctx->flowexercise = fixedrateserver;
/* Fake pump the main queue for 1s to get connected, registered, etc */
int setupsec = 1;
if (RUNNING_ON_VALGRIND) {
setupsec = setupsec * 5 / 2;
}
rwsched_dispatch_main_until(tenv.tasklet[0], setupsec, NULL);
if (!squat) {
if (ctx->flowexercise) {
sctest1_refill_bucket(ctx);
ctx->sc_timer = rwsched_dispatch_source_create(tenv.tasklet[1],
RWSCHED_DISPATCH_SOURCE_TYPE_TIMER,
0,
0,
ctx->rwq[1]);
rwsched_dispatch_source_set_event_handler_f(tenv.tasklet[1],
ctx->sc_timer,
sctest1_timer);
rwsched_dispatch_set_context(tenv.tasklet[1],
ctx->sc_timer,
ctx);
uint64_t ms1000 = 1*NSEC_PER_SEC/1;
rwsched_dispatch_source_set_timer(tenv.tasklet[1],
ctx->sc_timer,
dispatch_time(DISPATCH_TIME_NOW, ms1000),
ms1000,
0);
rwsched_dispatch_resume(tenv.tasklet[1], ctx->sc_timer);
}
if (RUNNING_ON_VALGRIND) {
/* Pump the main queue briefly to get everyone up and running before sending */
rwsched_dispatch_main_until(tenv.tasklet[0], 1, NULL);
}
//lottakickoff(ctx);
rwsched_dispatch_async_f(tenv.tasklet[0], ctx->rwq[0], ctx, lottakickoff);
int sec_start = time(NULL);
double sec = 5;
if (RUNNING_ON_VALGRIND) {
sec = sec * 5 / 2 ;
}
/* Run the main queue for 5s or longer under valgrind */
#if 1
for(int i=0; !ctx->done && i<100; i++) {
rwsched_dispatch_main_until(tenv.tasklet[0], sec/100, NULL);
}
#else
rwsched_dispatch_main_until(tenv.tasklet[0], sec, NULL);
#endif
VERBPRN("\nln=%d ctx->done=%d ctx->rspout=%u\n", __LINE__, ctx->done, ctx->rspout);
ctx->sendmore = FALSE;
ck_pr_barrier();
uint32_t endct_in = ctx->in;
uint32_t endct_rspin = ctx->rspin;
uint32_t endct_rspout = ctx->rspout;
uint32_t endct_bncout = ctx->bncout;
int iter=0;
VERBPRN("\n\nMain test run done/timeout; pumping to flush events and/or finish...\n\nln=%d iter=%d ctx->done=%d ctx->rspout=%u bncout=%u\n", __LINE__, iter, ctx->done, ctx->rspout, ctx->bncout);
do {
/* Fake pump the main queue until done */
rwsched_dispatch_main_until(tenv.tasklet[0], 10, &ctx->done);
iter++;
VERBPRN("\nln=%d iter=%d ctx->done=%d ctx->in=%u ctx->rspout=%u ctx->bncout=%u\n", __LINE__, iter, ctx->done, ctx->in, ctx->rspout, ctx->bncout);
if (iter > 6) {
fprintf(stderr, "waiting for done, iter=%d rspout=%u in=%u bnc=%u\n", iter, ctx->rspout, ctx->in, ctx->bncout);
}
if (!RUNNING_ON_VALGRIND) {
ASSERT_LE(iter, 6);
}
ck_pr_barrier();
} while (!ctx->done);
ck_pr_barrier();
VERBPRN("\nln=%d iter=%d ctx->done=%d ctx->rspout=%u ctx->bcnout=%u\n", __LINE__, iter, ctx->done, ctx->rspout, ctx->bncout);
if (!ctx->bncout) {
ASSERT_EQ(ctx->rspout, ctx->in);
ASSERT_EQ(ctx->out, ctx->in);
ASSERT_EQ(ctx->rspout, ctx->rspin);
ASSERT_EQ(ctx->out, ctx->rspout);
if (!ctx->opts->srvrspfromanyq) {
ASSERT_FALSE(ctx->misorderct);
}
} else {
/* Note that we can get bounces plus some might have been
answered even as they bounced on our end. */
ASSERT_EQ(ctx->rspout + ctx->bncout, ctx->in); // rsp+bnc at the client == requests sent by client
ASSERT_GE(ctx->out + ctx->bncout, ctx->in);
ASSERT_LE(ctx->rspout, ctx->rspin);
ASSERT_LE(ctx->out, ctx->bncout + ctx->rspout);
}
int rno;
for (rno=0; rno < SCTEST1_RMAX; rno++) {
ASSERT_TRUE(ctx->r[rno] == NULL);
}
valsout->sec = time(NULL) - sec_start; //sec;
valsout->flushtime = iter*100;
valsout->rmax = ctx->rmax;
valsout->reqsent = endct_in;
valsout->reqans = endct_rspin;
valsout->reqdone = endct_rspout;
valsout->reqbnc = endct_bncout;
valsout->reqbnc_final = ctx->bncout;
valsout->reqhz = (endct_rspout / sec / 10);
valsout->reqhz *= 10;
valsout->min_rtt = ctx->min_rtt;
valsout->max_rtt = ctx->max_rtt;
valsout->firstburst = ctx->sendmsg_preflow;
/* Ought to work under val, but there is a cock-up with timers that makes the token refresh et al go wrong */
if (ctx->flowexercise && !ctx->bncout && !RUNNING_ON_VALGRIND) {
ASSERT_GE(valsout->reqhz, TOKVAL);
}
if (ctx->flowexercise && ctx->sc_timer) {
/* Fake pump the main queue for 1s, allow lingering async_f and
timer calls to flush out */
rwsched_dispatch_source_cancel(tenv.tasklet[0], ctx->sc_timer);
RW_ASSERT(bro);
rwmsg_garbage(&bro->ep->gc, RWMSG_OBJTYPE_RWSCHED_OBJREL, ctx->sc_timer, tenv.rwsched, tenv.tasklet[0]);
ctx->sc_timer = NULL;
// rwsched_dispatch_main_until(tenv.tasklet[0], 5, NULL);
}
} else if (squat == 2) { /* For *ConcurQ* tests */
rwsched_dispatch_queue_t cuncurQ = rwsched_dispatch_get_global_queue(tenv.tasklet[0], DISPATCH_QUEUE_PRIORITY_DEFAULT);
rwsched_dispatch_async_f(tenv.tasklet[0], cuncurQ, ctx, lottakickoff02);
rwsched_dispatch_async_f(tenv.tasklet[0], cuncurQ, ctx, lottakickoff02);
rwsched_dispatch_async_f(tenv.tasklet[0], cuncurQ, ctx, lottakickoff02);
rwsched_dispatch_async_f(tenv.tasklet[0], cuncurQ, ctx, lottakickoff02);
rwsched_dispatch_async_f(tenv.tasklet[0], cuncurQ, ctx, lottakickoff02);
rwsched_dispatch_async_f(tenv.tasklet[0], ctx->rwq[0], ctx, lottakickoff02);
rwsched_dispatch_async_f(tenv.tasklet[0], ctx->rwq[0], ctx, lottakickoff02);
rwsched_dispatch_async_f(tenv.tasklet[0], ctx->rwq[0], ctx, lottakickoff02);
rwsched_dispatch_async_f(tenv.tasklet[0], ctx->rwq[0], ctx, lottakickoff02);
rwsched_dispatch_async_f(tenv.tasklet[0], ctx->rwq[0], ctx, lottakickoff02);
int sec_start = time(NULL);
double sec = 5;
if (RUNNING_ON_VALGRIND) {
sec = sec * 5 / 2 ;
}
/* Run the main queue for 5s or longer under valgrind */
#if 1
for(int i=0; !ctx->done && i<100; i++) {
rwsched_dispatch_main_until(tenv.tasklet[0], sec/100, NULL);
}
#else
rwsched_dispatch_main_until(tenv.tasklet[0], sec, NULL);
#endif
VERBPRN("\nln=%d ctx->done=%d ctx->rspout=%u\n", __LINE__, ctx->done, ctx->rspout);
ctx->sendmore = FALSE;
ck_pr_barrier();
uint32_t endct_in = ctx->in;
uint32_t endct_rspin = ctx->rspin;
uint32_t endct_rspout = ctx->rspout;
uint32_t endct_bncout = ctx->bncout;
int iter=0;
VERBPRN("\n\nMain test run done/timeout; pumping to flush events and/or finish...\n\nln=%d iter=%d ctx->done=%d ctx->rspout=%u bncout=%u\n", __LINE__, iter, ctx->done, ctx->rspout, ctx->bncout);
do {
/* Fake pump the main queue until done */
rwsched_dispatch_main_until(tenv.tasklet[0], 10, &ctx->done);
iter++;
VERBPRN("\nln=%d iter=%d ctx->done=%d ctx->in=%u ctx->rspout=%u ctx->bncout=%u\n", __LINE__, iter, ctx->done, ctx->in, ctx->rspout, ctx->bncout);
if (iter > 6) {
fprintf(stderr, "waiting for done, iter=%d rspout=%u in=%u bnc=%u\n", iter, ctx->rspout, ctx->in, ctx->bncout);
}
if (!RUNNING_ON_VALGRIND) {
ASSERT_LE(iter, 6);
}
ck_pr_barrier();
} while (!ctx->done);
ck_pr_barrier();
VERBPRN("\nln=%d iter=%d ctx->done=%d ctx->rspout=%u ctx->bcnout=%u\n", __LINE__, iter, ctx->done, ctx->rspout, ctx->bncout);
if (!ctx->bncout) {
ASSERT_EQ(ctx->rspout, ctx->in);
ASSERT_EQ(ctx->out, ctx->in);
ASSERT_EQ(ctx->rspout, ctx->rspin);
ASSERT_EQ(ctx->out, ctx->rspout);
if (!ctx->opts->srvrspfromanyq) {
ASSERT_FALSE(ctx->misorderct);
}
} else {
/* Note that we can get bounces plus some might have been
answered even as they bounced on our end. */
ASSERT_EQ(ctx->rspout + ctx->bncout, ctx->in); // rsp+bnc at the client == requests sent by client
ASSERT_GE(ctx->out + ctx->bncout, ctx->in);
ASSERT_LE(ctx->rspout, ctx->rspin);
ASSERT_LE(ctx->out, ctx->bncout + ctx->rspout);
}
int rno;
for (rno=0; rno < SCTEST1_RMAX; rno++) {
ASSERT_TRUE(ctx->r[rno] == NULL);
}
valsout->sec = time(NULL) - sec_start; //sec;
valsout->flushtime = iter*100;
valsout->rmax = ctx->rmax;
valsout->reqsent = endct_in;
valsout->reqans = endct_rspin;
valsout->reqdone = endct_rspout;
valsout->reqbnc = endct_bncout;
valsout->reqbnc_final = ctx->bncout;
valsout->reqhz = (endct_rspout / sec / 10);
valsout->reqhz *= 10;
valsout->firstburst = ctx->sendmsg_preflow;
valsout->min_rtt = ctx->min_rtt;
valsout->max_rtt = ctx->max_rtt;
/* Ought to work under val, but there is a cock-up with timers that makes the token refresh et al go wrong */
if (ctx->flowexercise && !ctx->bncout && !RUNNING_ON_VALGRIND) {
ASSERT_EQ(valsout->reqhz, TOKVAL);
}
if (ctx->flowexercise && ctx->sc_timer) {
/* Fake pump the main queue for 1s, allow lingering async_f and
timer calls to flush out */
rwsched_dispatch_source_cancel(tenv.tasklet[0], ctx->sc_timer);
RW_ASSERT(bro);
rwmsg_garbage(&bro->ep->gc, RWMSG_OBJTYPE_RWSCHED_OBJREL, ctx->sc_timer, tenv.rwsched, tenv.tasklet[0]);
ctx->sc_timer = NULL;
// rwsched_dispatch_main_until(tenv.tasklet[0], 5, NULL);
}
} else {
VERBPRN("\n***Squat!***\n");
}
//sleep(2);
rwmsg_bool_t r;
rwmsg_signature_release(ep, sig);
rwmsg_method_release(ep, meth);
rwmsg_srvchan_halt(ctx->sc);
rwmsg_clichan_halt(ctx->cc);
rwmsg_destination_release(dt);
if (!mainq) {
rwsched_dispatch_release(tenv.tasklet[0], ctx->rwq[0]);
rwsched_dispatch_release(tenv.tasklet[1], ctx->rwq[1]);
}
r = rwmsg_endpoint_halt_flush(ep, TRUE);
ASSERT_TRUE(r);
if (bro) {
r = rwmsg_broker_halt_sync(bro);
ASSERT_TRUE(r);
}
RW_FREE_TYPE(ctx->paybuf, sctest1_payload);
RW_FREE_TYPE(ctx, sctest1_context);
rwmsg_global_status_t gs;
rwmsg_global_status_get(&gs);
if (!gs.endpoint_ct) {
ASSERT_EQ(gs.qent, 0);
}
nnchk();
if (rwmsg_global.status.request_ct != start_reqct) {
fprintf(stderr, "***start_reqct=%u ending rwmsg_global.status.request_ct=%u\n", start_reqct, rwmsg_global.status.request_ct);
}
VERBPRN("end rwmsg_global.status.request_ct=%u\n", rwmsg_global.status.request_ct);
VERBPRN("end rwmsg_global.status.qent=%u\n", rwmsg_global.status.qent);
}
#define PRINT_REPORT(txt) \
fprintf(stderr, \
"\n" txt " at %lds sent=%lu answered=%lu done=%lu bnc=%lu bnc_final=%lu => %lu req/s\n" \
" min_rtt=%lu max_rtt=%lu usec\n",\
vals.sec,\
vals.reqsent,\
vals.reqans,\
vals.reqdone,\
vals.reqbnc,\
vals.reqbnc_final, \
vals.reqhz, \
(vals.min_rtt==MAX_RTT?0:vals.min_rtt), \
vals.max_rtt);
TEST(RWMsgBroker, LottaRawRWSConcurQ) {
TEST_DESCRIPTION("Tests broker under potloads of up to SCTEST1_RMAX requests outstanding, RWSched per-channel Serial Queues");
RWUT_BENCH_ITER(LottaRawRWSConcurQBench, 5, 5);
struct lottarawvals vals;
memset(&vals, 0, sizeof(vals));
struct lottaopts opts;
memset(&opts, 0, sizeof(opts));
int burst = 100;
int broker = TRUE;
int broflo = FALSE;
lottaraw(2, false, false, burst, broker, broflo, &opts, &vals); /* For *ConcurQ* tests */
#if 0
RecordProperty("FlushTime", vals.flushtime);
RecordProperty("rmax", vals.rmax);
RecordProperty("ReqSent", vals.reqsent);
RecordProperty("ReqAnswered", vals.reqans);
RecordProperty("ReqDone", vals.reqdone);
RecordProperty("ReqHz", vals.reqhz);
#endif
PRINT_REPORT("RWMsgBroker.LottaRawRWSConcurQ");
nnchk();
RWUT_BENCH_END(LottaRawRWSConcurQBench);
}
static void lottaraw(int squat, int mainq, int fixedrateserver, int window, int usebro, int broflo, struct lottaopts *opts, struct lottarawvals *valsout);
static void lottaraw2bros(int squat, int mainq, int fixedrateserver, int window, int broflo, struct lottaopts *opts, struct lottarawvals *valsout);
TEST(RWMsgBroker, LottaRawRWMeasureRTT) {
TEST_DESCRIPTION("Tests broker under potloads of up to SCTEST1_RMAX requests outstanding, RWSched per-channel Serial Queues");
RWUT_BENCH_ITER(LottaRawRWMeasureRTT, 5, 5);
struct lottarawvals vals;
memset(&vals, 0, sizeof(vals));
struct lottaopts opts;
memset(&opts, 0, sizeof(opts));
lottaraw(false, true, false, 2, FALSE, FALSE, &opts, &vals); /* No Broker tests MainQ*/
PRINT_REPORT("RWMsgBroker.MeasureRTT.NoBroker.MainQ");
ASSERT_LT(vals.max_rtt, 300*1000);
lottaraw(false, false, false, 2, FALSE, FALSE, &opts, &vals); /* No Broker tests */
PRINT_REPORT("RWMsgBroker.MeasureRTT.NoBroker");
ASSERT_LT(vals.max_rtt, 300*1000);
fprintf(stderr, "\n");
lottaraw(false, true, false, 2, TRUE, FALSE, &opts, &vals); /* With Broker tests MainQ */
PRINT_REPORT("RWMsgBroker.MeasureRTT.WithBroker.MainQ");
ASSERT_LT(vals.max_rtt, 500*1000);
lottaraw(false, false, false, 2, TRUE, FALSE, &opts, &vals); /* With Broker tests */
PRINT_REPORT("RWMsgBroker.MeasureRTT.WithBroker.ConcurQ");
ASSERT_LT(vals.max_rtt, 500*1000);
fprintf(stderr, "\n");
lottaraw2bros(false, true, false, 2, FALSE, &opts, &vals); /* For *MainQ* tests */
PRINT_REPORT("RWMsgBroker.MeasureRTT.With2Brokers.MainQ");
ASSERT_LT(vals.max_rtt, 500*1000);
fprintf(stderr, "\n");
lottaraw2bros(false, false, false, 2, FALSE, &opts, &vals); /* For *ConcurQ* tests */
PRINT_REPORT("RWMsgBroker.MeasureRTT.With2Brokers.ConcurQ");
ASSERT_LT(vals.max_rtt, 500*1000);
fprintf(stderr, "\n");
nnchk();
RWUT_BENCH_END(LottaRawRWMeasureRTT);
}
TEST(RWMsgBroker, LottaRawRWSSerQ) {
TEST_DESCRIPTION("Tests broker under potloads of up to SCTEST1_RMAX requests outstanding, RWSched per-channel Serial Queues");
RWUT_BENCH_ITER(LottaRawRWSSerQBench, 5, 5);
struct lottarawvals vals;
memset(&vals, 0, sizeof(vals));
struct lottaopts opts;
memset(&opts, 0, sizeof(opts));
int burst = 100;
int broker = TRUE;
int broflo = FALSE;
lottaraw(false, false, false, burst, broker, broflo, &opts, &vals);
#if 0
RecordProperty("FlushTime", vals.flushtime);
RecordProperty("rmax", vals.rmax);
RecordProperty("ReqSent", vals.reqsent);
RecordProperty("ReqAnswered", vals.reqans);
RecordProperty("ReqDone", vals.reqdone);
RecordProperty("ReqHz", vals.reqhz);
#endif
PRINT_REPORT("RWMsgBroker.LottaRawRWSSerQ");
nnchk();
RWUT_BENCH_END(LottaRawRWSSerQBench);
}
TEST(RWMsgBroker, LottaRawRWSSerQRspManyQ) {
TEST_DESCRIPTION("Tests broker under potloads of up to SCTEST1_RMAX requests outstanding, RWSched per-channel Serial Queues, srvchan answering from all default rwqueues");
RWUT_BENCH_ITER(LottaRawRWSSerQRspManyQBench, 5, 5);
struct lottarawvals vals;
memset(&vals, 0, sizeof(vals));
struct lottaopts opts;
memset(&opts, 0, sizeof(opts));
opts.srvrspfromanyq = TRUE;
int burst = 100;
int broker = TRUE;
int broflo = FALSE;
lottaraw(false, false, false, burst, broker, broflo, &opts, &vals);
#if 0
RecordProperty("FlushTime", vals.flushtime);
RecordProperty("rmax", vals.rmax);
RecordProperty("ReqSent", vals.reqsent);
RecordProperty("ReqAnswered", vals.reqans);
RecordProperty("ReqDone", vals.reqdone);
RecordProperty("ReqHz", vals.reqhz);
#endif
PRINT_REPORT("RWMsgBroker.LottaRawRWSSerQRspManyQ");
nnchk();
RWUT_BENCH_END(LottaRawRWSSerQRspManyQBench);
}
#if 0
TEST(RWMsgBroker, LottaBrofloRawRWSSerQ) {
TEST_DESCRIPTION("Tests in-broker flow control under potloads of up to SCTEST1_RMAX requests outstanding, RWSched per-channel Serial Queues");
RWUT_BENCH_ITER(LottaBrofloRawRWSSerQBench, 5, 5);
struct lottarawvals vals;
memset(&vals, 0, sizeof(vals));
struct lottaopts opts;
memset(&opts, 0, sizeof(opts));
int burst = 100;
int broker = TRUE;
int broflo = TRUE;
lottaraw(false, false, false, burst, broker, broflo, &opts, &vals);
#if 0
RecordProperty("FlushTime", vals.flushtime);
RecordProperty("rmax", vals.rmax);
RecordProperty("ReqSent", vals.reqsent);
RecordProperty("ReqAnswered", vals.reqans);
RecordProperty("ReqDone", vals.reqdone);
RecordProperty("ReqHz", vals.reqhz);
#endif
fprintf(stderr,
"\nRWMsgBroker.LottabrofloRawRWSSerQ at %lds sent=%lu answered=%lu done=%lu bnc=%lu => %lu req/s\n",
vals.sec,
vals.reqsent,
vals.reqans,
vals.reqdone,
vals.reqbnc,
vals.reqhz);
nnchk();
RWUT_BENCH_END(LottaBrofloRawRWSSerQBench);
}
#endif
TEST(RWMsgBrokerNot, LottaRawRWSConcurQ) {
TEST_DESCRIPTION("Tests inprocess under potloads of up to SCTEST1_RMAX requests outstanding, RWSched per-channel Serial Queues");
RWUT_BENCH_ITER(NobroLottaRawRWSConcurQBench, 5, 5);
struct lottarawvals vals;
memset(&vals, 0, sizeof(vals));
struct lottaopts opts;
memset(&opts, 0, sizeof(opts));
int burst = 100;
int broker = FALSE;
int broflo = FALSE;
lottaraw(2, false, false, burst, broker, broflo, &opts, &vals); /* For *ConcurQ* tests */
#if 0
RecordProperty("FlushTime", vals.flushtime);
RecordProperty("rmax", vals.rmax);
RecordProperty("ReqSent", vals.reqsent);
RecordProperty("ReqAnswered", vals.reqans);
RecordProperty("ReqDone", vals.reqdone);
RecordProperty("ReqHz", vals.reqhz);
#endif
PRINT_REPORT("RWMsgBrokerNot.LottaRawRWSConcurQ");
nnchk();
RWUT_BENCH_END(NobroLottaRawRWSConcurQBench)
}
TEST(RWMsgBrokerNot, LottaRawRWSSerQ) {
TEST_DESCRIPTION("Tests inprocess under potloads of up to SCTEST1_RMAX requests outstanding, RWSched per-channel Serial Queues");
RWUT_BENCH_ITER(NobroLottaRawRWSSerQBench, 5, 5);
struct lottarawvals vals;
memset(&vals, 0, sizeof(vals));
struct lottaopts opts;
memset(&opts, 0, sizeof(opts));
int burst = 100;
int broker = FALSE;
int broflo = FALSE;
lottaraw(false, false, false, burst, broker, broflo, &opts, &vals);
#if 0
RecordProperty("FlushTime", vals.flushtime);
RecordProperty("rmax", vals.rmax);
RecordProperty("ReqSent", vals.reqsent);
RecordProperty("ReqAnswered", vals.reqans);
RecordProperty("ReqDone", vals.reqdone);
RecordProperty("ReqHz", vals.reqhz);
#endif
PRINT_REPORT("RWMsgBrokerNot.LottaRawRWSSerQ");
nnchk();
RWUT_BENCH_END(NobroLottaRawRWSSerQBench)
}
TEST(RWMsgBrokerNot, LottaRawRWSMainQ) {
TEST_DESCRIPTION("Tests broker under potloads of up to SCTEST1_RMAX requests outstanding, RWSched Main Queue");
RWUT_BENCH_ITER(NobroLottaRawRWSMainQBench, 5, 5);
struct lottarawvals vals;
memset(&vals, 0, sizeof(vals));
struct lottaopts opts;
memset(&opts, 0, sizeof(opts));
int burst = 100;
int broker = FALSE;
int broflo = FALSE;
int squat = FALSE;
lottaraw(squat, true, false, burst, broker, broflo, &opts, &vals);
#if 0
RecordProperty("FlushTime", vals.flushtime);
RecordProperty("rmax", vals.rmax);
RecordProperty("ReqSent", vals.reqsent);
RecordProperty("ReqAnswered", vals.reqans);
RecordProperty("ReqDone", vals.reqdone);
RecordProperty("ReqHz", vals.reqhz);
#endif
PRINT_REPORT("RWMsgBrokerNot.LottaRawRWSMainQ");
nnchk();
RWUT_BENCH_END(NobroLottaRawRWSMainQBench);
}
TEST(RWMsgBroker, LottaRawRWSBigdefwinMainQ) {
TEST_DESCRIPTION("Tests broker under potloads of up to SCTEST1_RMAX requests outstanding, RWSched Main Queue");
RWUT_BENCH_ITER(LottaRawRWSBigdefwinMainQBench, 5, 5);
struct lottarawvals vals;
memset(&vals, 0, sizeof(vals));
struct lottaopts opts;
memset(&opts, 0, sizeof(opts));
opts.bigdefwin = 100;
int burst = 100;
int broker = TRUE;
int broflo = FALSE;
int squat = FALSE;
lottaraw(squat, true, false, burst, broker, broflo, &opts, &vals);
#if 0
RecordProperty("FlushTime", vals.flushtime);
RecordProperty("rmax", vals.rmax);
RecordProperty("ReqSent", vals.reqsent);
RecordProperty("ReqAnswered", vals.reqans);
RecordProperty("ReqDone", vals.reqdone);
RecordProperty("ReqHz", vals.reqhz);
#endif
PRINT_REPORT("RWMsgBroker.LottaRawRWSBigdefwinMainQ");
nnchk();
RWUT_BENCH_END(LottaRawRWSBigdefwinMainQBench);
}
TEST(RWMsgBroker, LottaRawRWSMainQ) {
TEST_DESCRIPTION("Tests broker under potloads of up to SCTEST1_RMAX requests outstanding, RWSched Main Queue");
RWUT_BENCH_ITER(LottaRawRWSMainQBench, 5, 5);
struct lottarawvals vals;
memset(&vals, 0, sizeof(vals));
struct lottaopts opts;
memset(&opts, 0, sizeof(opts));
int burst = 100;
int broker = TRUE;
int broflo = FALSE;
int squat = FALSE;
lottaraw(squat, true, false, burst, broker, broflo, &opts, &vals);
#if 0
RecordProperty("FlushTime", vals.flushtime);
RecordProperty("rmax", vals.rmax);
RecordProperty("ReqSent", vals.reqsent);
RecordProperty("ReqAnswered", vals.reqans);
RecordProperty("ReqDone", vals.reqdone);
RecordProperty("ReqHz", vals.reqhz);
#endif
PRINT_REPORT("RWMsgBroker.LottaRawRWSMainQ");
nnchk();
RWUT_BENCH_END(LottaRawRWSMainQBench);
}
TEST(RWMsgBroker, LottaRawBncRWSMainQ) {
TEST_DESCRIPTION("Exercise broker timeout bounce code path.");
RWUT_BENCH_ITER(LottaRawBncRWSMainQBench, 5, 5);
struct lottarawvals vals;
memset(&vals, 0, sizeof(vals));
struct lottaopts opts;
memset(&opts, 0, sizeof(opts));
int burst = 1;
int broker = TRUE;
int broflo = FALSE;
int squat = FALSE;
opts.reqtimeo = 50;/*ms*/
opts.bncall = TRUE;
lottaraw(squat, true, false, burst, broker, broflo, &opts, &vals);
#if 0
RecordProperty("FlushTime", vals.flushtime);
RecordProperty("rmax", vals.rmax);
RecordProperty("ReqSent", vals.reqsent);
RecordProperty("ReqAnswered", vals.reqans);
RecordProperty("ReqDone", vals.reqdone);
RecordProperty("ReqHz", vals.reqhz);
#endif
PRINT_REPORT("RWMsgBroker.LottaRawBncRWSMainQ");
nnchk();
RWUT_BENCH_END(LottaRawBncRWSMainQBench);
}
TEST(RWMsgBroker, Big0512RawRWSMainQ) {
TEST_DESCRIPTION("Tests broker with big 512KB requests, RWSched Main Queue");
RWUT_BENCH_ITER(Big0512RawRWSMainQBench, 5, 5);
struct lottarawvals vals;
memset(&vals, 0, sizeof(vals));
struct lottaopts opts;
memset(&opts, 0, sizeof(opts));
opts.paysz = 512000;
int burst = 10;
int broker = TRUE;
int broflo = FALSE;
int squat = FALSE;
lottaraw(squat, true, false, burst, broker, broflo, &opts, &vals);
#if 0
RecordProperty("FlushTime", vals.flushtime);
RecordProperty("rmax", vals.rmax);
RecordProperty("ReqSent", vals.reqsent);
RecordProperty("ReqAnswered", vals.reqans);
RecordProperty("ReqDone", vals.reqdone);
RecordProperty("ReqHz", vals.reqhz);
#endif
PRINT_REPORT("RWMsgBroker.Big0512RawRWSMainQ");
nnchk();
RWUT_BENCH_END(Big0512RawRWSMainQBench);
}
TEST(RWMsgBroker, Big5120RawRWSMainQ) {
TEST_DESCRIPTION("Tests broker with big 5MB requests, RWSched Main Queue");
RWUT_BENCH_ITER(Big5120RawRWSMainQBench, 5, 5);
struct lottarawvals vals;
memset(&vals, 0, sizeof(vals));
struct lottaopts opts;
memset(&opts, 0, sizeof(opts));
opts.paysz = 5120000;
int burst = 10;
int broker = TRUE;
int broflo = FALSE;
int squat = FALSE;
lottaraw(squat, true, false, burst, broker, broflo, &opts, &vals);
#if 0
RecordProperty("FlushTime", vals.flushtime);
RecordProperty("rmax", vals.rmax);
RecordProperty("ReqSent", vals.reqsent);
RecordProperty("ReqAnswered", vals.reqans);
RecordProperty("ReqDone", vals.reqdone);
RecordProperty("ReqHz", vals.reqhz);
#endif
PRINT_REPORT("RWMsgBroker.Big5120RawRWSMainQ");
nnchk();
RWUT_BENCH_END(Big5120RawRWSMainQBench);
}
TEST(RWMsgBrokerNot, Big0512RawRWSMainQ) {
TEST_DESCRIPTION("Tests with big 512KB requests, RWSched Main Queue");
RWUT_BENCH_ITER(Big0512RawRWSMainQBench, 5, 5);
struct lottarawvals vals;
memset(&vals, 0, sizeof(vals));
struct lottaopts opts;
memset(&opts, 0, sizeof(opts));
opts.paysz = 512000;
int burst = 10;
int broker = FALSE;
int broflo = FALSE;
int squat = FALSE;
lottaraw(squat, true, false, burst, broker, broflo, &opts, &vals);
#if 0
RecordProperty("FlushTime", vals.flushtime);
RecordProperty("rmax", vals.rmax);
RecordProperty("ReqSent", vals.reqsent);
RecordProperty("ReqAnswered", vals.reqans);
RecordProperty("ReqDone", vals.reqdone);
RecordProperty("ReqHz", vals.reqhz);
#endif
PRINT_REPORT("RWMsgBrokerNot.Big0512RawRWSMainQ");
nnchk();
RWUT_BENCH_END(Big0512RawRWSMainQBench);
}
TEST(RWMsgBrokerNot, Big5120RawRWSMainQ) {
TEST_DESCRIPTION("Tests with big 5MB requests, RWSched Main Queue");
RWUT_BENCH_ITER(Big5120RawRWSMainQBench, 5, 5);
struct lottarawvals vals;
memset(&vals, 0, sizeof(vals));
struct lottaopts opts;
memset(&opts, 0, sizeof(opts));
opts.paysz = 5120000;
int burst = 10;
int broker = FALSE;
int broflo = FALSE;
int squat = FALSE;
lottaraw(squat, true, false, burst, broker, broflo, &opts, &vals);
#if 0
RecordProperty("FlushTime", vals.flushtime);
RecordProperty("rmax", vals.rmax);
RecordProperty("ReqSent", vals.reqsent);
RecordProperty("ReqAnswered", vals.reqans);
RecordProperty("ReqDone", vals.reqdone);
RecordProperty("ReqHz", vals.reqhz);
#endif
PRINT_REPORT("RWMsgBrokerNot.Big5120RawRWSMainQ");
nnchk();
RWUT_BENCH_END(Big5120RawRWSMainQBench);
}
TEST(RWMsgBroker, LottaPauseRawRWSSerQ) {
TEST_DESCRIPTION("Tests broker pause under potloads of up to SCTEST1_RMAX requests outstanding, RWSched Serial Queue");
RWUT_BENCH_ITER(LottaPauseRawRWSSerQBench, 5, 5);
struct lottarawvals vals;
memset(&vals, 0, sizeof(vals));
struct lottaopts opts;
memset(&opts, 0, sizeof(opts));
int burst = 100;
burst=burst;
int broker = TRUE;
int broflo = FALSE;
lottaraw(false, false/*mainq*/, true/*noread*/, burst, broker, broflo, &opts, &vals);
#if 0
RecordProperty("FlushTime", vals.flushtime);
RecordProperty("rmax", vals.rmax);
RecordProperty("ReqSent", vals.reqsent);
RecordProperty("ReqAnswered", vals.reqans);
RecordProperty("ReqDone", vals.reqdone);
RecordProperty("ReqHz", vals.reqhz);
#endif
PRINT_REPORT("RWMsgBroker.LottaPauseRawRWSSerQ");
nnchk();
RWUT_BENCH_END(LottaPauseRawRWSSerQBench);
}
TEST(RWMsgBroker, LottaPauseBigwinRawRWSSerQ) {
TEST_DESCRIPTION("Tests broker pause under SCTEST1_RMAX requests outstanding, RWSched Serial Queue");
RWUT_BENCH_ITER(LottaPauseBigwinRawRWSSerQBench, 5, 5);
struct lottarawvals vals;
memset(&vals, 0, sizeof(vals));
struct lottaopts opts;
memset(&opts, 0, sizeof(opts));
int burst = SCTEST1_RMAX;
burst=burst;
int broker = TRUE;
int broflo = FALSE;
opts.bigbrosrvwin = TRUE;
lottaraw(false, false/*mainq*/, true/*noread*/, burst, broker, broflo, &opts, &vals);
#if 0
RecordProperty("FlushTime", vals.flushtime);
RecordProperty("rmax", vals.rmax);
RecordProperty("ReqSent", vals.reqsent);
RecordProperty("ReqAnswered", vals.reqans);
RecordProperty("ReqDone", vals.reqdone);
RecordProperty("ReqHz", vals.reqhz);
#endif
PRINT_REPORT("RWMsgBroker.LottaPauseBigwinRawRWSSerQ");
nnchk();
RWUT_BENCH_END(LottaPauseBigwinRawRWSSerQBench);
}
TEST(RWMsgBrokerNot, LottaPauseRawRWSSerQ) {
TEST_DESCRIPTION("Tests broker pause under potloads of up to SCTEST1_RMAX requests outstanding, RWSched Serial Queue");
RWUT_BENCH_ITER(NobroLottaPauseRawRWSSerQBench, 5, 5);
struct lottarawvals vals;
memset(&vals, 0, sizeof(vals));
struct lottaopts opts;
memset(&opts, 0, sizeof(opts));
int burst = 100;
burst=burst;
int broker = FALSE;
int broflo = FALSE;
lottaraw(false, false/*mainq*/, true/*noread*/, burst, broker, broflo, &opts, &vals);
#if 0
RecordProperty("FlushTime", vals.flushtime);
RecordProperty("rmax", vals.rmax);
RecordProperty("ReqSent", vals.reqsent);
RecordProperty("ReqAnswered", vals.reqans);
RecordProperty("ReqDone", vals.reqdone);
RecordProperty("ReqHz", vals.reqhz);
#endif
PRINT_REPORT("RWMsgBrokerNot.LottaPauseRawRWSSerQ");
nnchk();
RWUT_BENCH_END(NobroLottaPauseRawRWSSerQBench);
}
TEST(RWMsgBroker, LottaPauseRawRWSMainQ) {
TEST_DESCRIPTION("Tests broker pause under potloads of up to SCTEST1_RMAX requests outstanding, RWSched Main Queue");
RWUT_BENCH_ITER(LottaPauseRawRWSMainQBench, 5, 5);
struct lottarawvals vals;
memset(&vals, 0, sizeof(vals));
struct lottaopts opts;
memset(&opts, 0, sizeof(opts));
int burst = 100;
int broker = TRUE;
int broflo = FALSE;
lottaraw(false, true/*mainq*/, true/*noread*/, burst, broker, broflo, &opts, &vals);
#if 0
RecordProperty("FlushTime", vals.flushtime);
RecordProperty("rmax", vals.rmax);
RecordProperty("ReqSent", vals.reqsent);
RecordProperty("ReqAnswered", vals.reqans);
RecordProperty("ReqDone", vals.reqdone);
RecordProperty("ReqHz", vals.reqhz);
#endif
PRINT_REPORT("RWMsgBroker.LottaPauseRawRWSMainQ");
nnchk();
RWUT_BENCH_END(LottaPauseRawRWSMainQBench);
}
TEST(RWMsgBroker, LottaPauseBigwinRawRWSMainQ) {
TEST_DESCRIPTION("Tests broker pause under SCTEST1_RMAX requests outstanding, RWSched Main Queue");
RWUT_BENCH_ITER(LottaPauseBigwinRawRWSMainQBench, 5, 5);
struct lottarawvals vals;
memset(&vals, 0, sizeof(vals));
struct lottaopts opts;
memset(&opts, 0, sizeof(opts));
int burst = SCTEST1_RMAX;
int broker = TRUE;
int broflo = FALSE;
opts.bigbrosrvwin = TRUE;
lottaraw(false, true/*mainq*/, true/*noread*/, burst, broker, broflo, &opts, &vals);
#if 0
RecordProperty("FlushTime", vals.flushtime);
RecordProperty("rmax", vals.rmax);
RecordProperty("ReqSent", vals.reqsent);
RecordProperty("ReqAnswered", vals.reqans);
RecordProperty("ReqDone", vals.reqdone);
RecordProperty("ReqHz", vals.reqhz);
#endif
PRINT_REPORT("RWMsgBroker.LottaPauseBigwinRawRWSMainQ");
nnchk();
RWUT_BENCH_END(LottaPauseBigwinRawRWSMainQBench);
}
TEST(RWMsgBrokerNot, LottaPauseRawRWSMainQ) {
TEST_DESCRIPTION("Tests broker pause under potloads of up to SCTEST1_RMAX requests outstanding, RWSched Main Queue");
RWUT_BENCH_ITER(NobroLottaPauseRawRWSMainQBench, 5, 5);
struct lottarawvals vals;
memset(&vals, 0, sizeof(vals));
struct lottaopts opts;
memset(&opts, 0, sizeof(opts));
int burst = 100;
int broker = FALSE;
int broflo = FALSE;
lottaraw(false, true/*mainq*/, true/*noread*/, burst, broker, broflo, &opts, &vals);
#if 0
RecordProperty("FlushTime", vals.flushtime);
RecordProperty("rmax", vals.rmax);
RecordProperty("ReqSent", vals.reqsent);
RecordProperty("ReqAnswered", vals.reqans);
RecordProperty("ReqDone", vals.reqdone);
RecordProperty("ReqHz", vals.reqhz);
#endif
PRINT_REPORT("RWMsgBrokerNot.LottaPauseRawRWSMainQ");
nnchk();
RWUT_BENCH_END(NobroLottaPauseRawRWSMainQBench);
}
static void lottaraw2bros(int squat, int mainq, int fixedrateserver, int window, int broflo, struct lottaopts *opts, struct lottarawvals *valsout) {
uint32_t start_reqct = rwmsg_global.status.request_ct;
VERBPRN("begin rwmsg_global.status.request_ct=%u\n", rwmsg_global.status.request_ct);
if (valsout) {
memset(valsout, 0, sizeof(*valsout));
}
if (RUNNING_ON_VALGRIND) {
window /= 10;
window = MAX(1, window);
}
const unsigned broker_c = 2;
rwmsg_btenv_t tenv(2+(broker_c?broker_c:1)); // test env, on stack, dtor cleans up
ASSERT_TRUE(tenv.rwsched != NULL);
rwmsg_broker_t *bros[broker_c];
rwmsg_broker_t *bro=NULL;
memset(bros, 0, sizeof(bros));
if (broker_c) {
for (unsigned i=0; i<broker_c; i++) {
tenv.ti->rwsched_tasklet_info = tenv.tasklet[2-(broker_c-i)];
rwmsg_broker_main(broport_g, 2-(broker_c-i), i, tenv.rwsched, tenv.tasklet[2-(broker_c-i)], tenv.rwcal, mainq, tenv.ti, &bros[i]);
bro = bros[i];
}
}
rwsched_instance_CFRunLoopRunInMode(tenv.rwsched, RWMSG_RUNLOOP_MODE, 1, FALSE);
if (broflo) {
bro->thresh_reqct2 = 10;
bro->thresh_reqct1 = 5;
}
if (opts->bigbrosrvwin) {
/* set the broker's srvchan window value really high, to cause overrun of writes to srvchan socket */
rwmsg_endpoint_set_property_int(bro->ep, "/rwmsg/broker/srvchan/window", (RUNNING_ON_VALGRIND ? 1000 : 1000000));
}
rw_status_t rs;
struct sctest1_context *ctx = RW_MALLOC0_TYPE(sizeof(*ctx), sctest1_context);
ctx->usebro = TRUE;
ctx->window = window;
ctx->tenv = &tenv;
ctx->paysz = sizeof(sctest1_payload);
if (opts) {
ctx->paysz = opts->paysz;
}
ctx->paybuf = RW_MALLOC0_TYPE(MAX(sizeof(struct sctest1_payload), ctx->paysz), sctest1_payload);
ctx->verbose = VERBOSE();
RW_ASSERT(opts);
ctx->opts = opts;
ctx->min_rtt = MAX_RTT;
ctx->checktid=0; // check thread id is same every time; adds a syscall per msg on each side
if (ctx->checktid) {
fprintf(stderr, "warning: checktid enabled\n");
}
const char *taddrpfx = "/L/GTEST/RWBRO/TESTAPP/6";
char taddr[999];
sprintf(taddr, "%s/%u", taddrpfx, rand());
const uint32_t methno = __LINE__;
/* Create the srvchan, bind a method */
rwmsg_endpoint_t *ep_s;
ep_s = rwmsg_endpoint_create(1, 0, 0, tenv.rwsched, tenv.tasklet[0], rwtrace_init(), NULL);
ASSERT_TRUE(ep_s != NULL);
/* Direct everything through the broker */
rwmsg_endpoint_set_property_int(ep_s, "/rwmsg/broker/shunt", 1);
if (opts->bigdefwin) {
rwmsg_endpoint_set_property_int(ep_s, "/rwmsg/destination/defwin", opts->bigdefwin);
}
ctx->sc = rwmsg_srvchan_create(ep_s);
ASSERT_TRUE(ctx->sc != NULL);
rwmsg_signature_t *sig = rwmsg_signature_create(ep_s, RWMSG_PAYFMT_RAW, methno, RWMSG_PRIORITY_DEFAULT);
ASSERT_TRUE(sig);
int timeo = 1000; // ms
if (opts->reqtimeo) {
timeo = opts->reqtimeo;
}
if (RUNNING_ON_VALGRIND) {
timeo = timeo * 5;
}
rwmsg_signature_set_timeout(sig, timeo);
ctx->sig = sig;
rwmsg_closure_t methcb;
methcb.request=sctest1_methcb1;
methcb.ud=ctx;
rwmsg_method_t *meth = rwmsg_method_create(ep_s, taddr, sig, &methcb);
ASSERT_TRUE(meth != NULL);
rs = rwmsg_srvchan_add_method(ctx->sc, meth);
ASSERT_EQ(rs, RW_STATUS_SUCCESS);
/* Wait on binding the srvchan until after we've sent the initial
flurry of requests. Otherwise, our ++ and the request handler's
++ of some of the request count variables ABA-stomp each
other. */
/* Create the clichan, add the method's signature */
rwmsg_endpoint_t *ep_c;
ep_c = rwmsg_endpoint_create(1, 1, 1, tenv.rwsched, tenv.tasklet[1], rwtrace_init(), NULL);
ASSERT_TRUE(ep_c != NULL);
/* Direct everything through the broker */
rwmsg_endpoint_set_property_int(ep_c, "/rwmsg/broker/shunt", 1);
if (opts->bigdefwin) {
rwmsg_endpoint_set_property_int(ep_c, "/rwmsg/destination/defwin", opts->bigdefwin);
}
rwmsg_destination_t *dt = rwmsg_destination_create(ep_c, RWMSG_ADDRTYPE_UNICAST, taddr);
ASSERT_TRUE(dt != NULL);
ctx->dt = dt;
if (squat!=2 ||
ctx->flowexercise) {
rwmsg_closure_t cb = { };
cb.ud = ctx;
cb.feedme = sctest1_clicb_feedme;
rwmsg_destination_feedme_callback(dt, &cb);
}
rwmsg_clichan_t *cc = rwmsg_clichan_create(ep_c);
ctx->cc = cc;
ASSERT_TRUE(cc != NULL);
//TBD/optional rwmsg_clichan_add_signature(cc, sig);
/* Bind to a serial queue */
if (mainq) {
ctx->rwq[0] = rwsched_dispatch_get_main_queue(tenv.rwsched);
ctx->rwq[1] = rwsched_dispatch_get_main_queue(tenv.rwsched);
} else {
ctx->rwq[0] = rwsched_dispatch_queue_create(tenv.tasklet[0], "ctx->rwq[0] (cc)", DISPATCH_QUEUE_SERIAL);
ctx->rwq[1] = rwsched_dispatch_queue_create(tenv.tasklet[1], "ctx->rwq[1] (sc)", DISPATCH_QUEUE_SERIAL);
}
rs = rwmsg_clichan_bind_rwsched_queue(cc, ctx->rwq[0]);
if (window == 1) {
ctx->sendmore = FALSE;
ctx->sendone = TRUE;
} else {
ctx->sendmore = TRUE;
}
/* Now bind the srvchan; at this point the srvchan will start
chewing in another thread. */
rs = rwmsg_srvchan_bind_rwsched_queue(ctx->sc, ctx->rwq[1]);
ASSERT_EQ(rs, RW_STATUS_SUCCESS);
/* Setup the srvchan to run at a fixed rate of 4 or 100 req/s, to exercise backpressure etc. */
ctx->flowexercise = fixedrateserver;
/* Fake pump the main queue for 1s to get connected, registered, etc */
int setupsec = 1;
if (RUNNING_ON_VALGRIND) {
setupsec = setupsec * 5 / 2;
}
rwsched_dispatch_main_until(tenv.tasklet[0], setupsec, NULL);
if (!squat) {
if (ctx->flowexercise) {
sctest1_refill_bucket(ctx);
ctx->sc_timer = rwsched_dispatch_source_create(tenv.tasklet[1],
RWSCHED_DISPATCH_SOURCE_TYPE_TIMER,
0,
0,
ctx->rwq[1]);
rwsched_dispatch_source_set_event_handler_f(tenv.tasklet[1],
ctx->sc_timer,
sctest1_timer);
rwsched_dispatch_set_context(tenv.tasklet[1],
ctx->sc_timer,
ctx);
uint64_t ms1000 = 1*NSEC_PER_SEC/1;
rwsched_dispatch_source_set_timer(tenv.tasklet[1],
ctx->sc_timer,
dispatch_time(DISPATCH_TIME_NOW, ms1000),
ms1000,
0);
rwsched_dispatch_resume(tenv.tasklet[1], ctx->sc_timer);
}
if (RUNNING_ON_VALGRIND) {
/* Pump the main queue briefly to get everyone up and running before sending */
rwsched_dispatch_main_until(tenv.tasklet[0], 1, NULL);
}
//lottakickoff(ctx);
rwsched_dispatch_async_f(tenv.tasklet[0], ctx->rwq[0], ctx, lottakickoff);
int sec_start = time(NULL);
double sec = 5;
if (RUNNING_ON_VALGRIND) {
sec = sec * 5 / 2 ;
}
/* Run the main queue for 5s or longer under valgrind */
#if 1
for(int i=0; !ctx->done && i<100; i++) {
rwsched_dispatch_main_until(tenv.tasklet[0], sec/100, NULL);
}
#else
rwsched_dispatch_main_until(tenv.tasklet[0], sec, NULL);
#endif
VERBPRN("\nln=%d ctx->done=%d ctx->rspout=%u\n", __LINE__, ctx->done, ctx->rspout);
ctx->sendmore = FALSE;
ck_pr_barrier();
uint32_t endct_in = ctx->in;
uint32_t endct_rspin = ctx->rspin;
uint32_t endct_rspout = ctx->rspout;
uint32_t endct_bncout = ctx->bncout;
int iter=0;
VERBPRN("\n\nMain test run done/timeout; pumping to flush events and/or finish...\n\nln=%d iter=%d ctx->done=%d ctx->rspout=%u bncout=%u\n", __LINE__, iter, ctx->done, ctx->rspout, ctx->bncout);
do {
/* Fake pump the main queue until done */
rwsched_dispatch_main_until(tenv.tasklet[0], 10, &ctx->done);
iter++;
VERBPRN("\nln=%d iter=%d ctx->done=%d ctx->in=%u ctx->rspout=%u ctx->bncout=%u\n", __LINE__, iter, ctx->done, ctx->in, ctx->rspout, ctx->bncout);
if (iter > 6) {
fprintf(stderr, "waiting for done, iter=%d rspout=%u in=%u bnc=%u\n", iter, ctx->rspout, ctx->in, ctx->bncout);
}
if (!RUNNING_ON_VALGRIND) {
ASSERT_LE(iter, 6);
}
ck_pr_barrier();
} while (!ctx->done);
ck_pr_barrier();
VERBPRN("\nln=%d iter=%d ctx->done=%d ctx->rspout=%u ctx->bcnout=%u\n", __LINE__, iter, ctx->done, ctx->rspout, ctx->bncout);
if (!ctx->bncout) {
ASSERT_EQ(ctx->rspout, ctx->in);
ASSERT_EQ(ctx->out, ctx->in);
ASSERT_EQ(ctx->rspout, ctx->rspin);
ASSERT_EQ(ctx->out, ctx->rspout);
if (!ctx->opts->srvrspfromanyq) {
ASSERT_FALSE(ctx->misorderct);
}
} else {
/* Note that we can get bounces plus some might have been
answered even as they bounced on our end. */
ASSERT_EQ(ctx->rspout + ctx->bncout, ctx->in); // rsp+bnc at the client == requests sent by client
ASSERT_GE(ctx->out + ctx->bncout, ctx->in);
ASSERT_LE(ctx->rspout, ctx->rspin);
ASSERT_LE(ctx->out, ctx->bncout + ctx->rspout);
}
int rno;
for (rno=0; rno < SCTEST1_RMAX; rno++) {
ASSERT_TRUE(ctx->r[rno] == NULL);
}
valsout->sec = time(NULL) - sec_start; //sec;
valsout->flushtime = iter*100;
valsout->rmax = ctx->rmax;
valsout->reqsent = endct_in;
valsout->reqans = endct_rspin;
valsout->reqdone = endct_rspout;
valsout->reqbnc = endct_bncout;
valsout->reqbnc_final = ctx->bncout;
valsout->reqhz = (endct_rspout / (ctx->tokenfill_ct-1));
valsout->firstburst = ctx->sendmsg_preflow;
valsout->min_rtt = ctx->min_rtt;
valsout->max_rtt = ctx->max_rtt;
/* Ought to work under val, but there is a cock-up with timers that makes the token refresh et al go wrong */
if (ctx->flowexercise && !ctx->bncout && !RUNNING_ON_VALGRIND) {
ASSERT_LE(valsout->reqhz, TOKVAL);
}
if (ctx->flowexercise && ctx->sc_timer) {
/* Fake pump the main queue for 1s, allow lingering async_f and
timer calls to flush out */
rwsched_dispatch_source_cancel(tenv.tasklet[0], ctx->sc_timer);
RW_ASSERT(bro);
rwmsg_garbage(&bro->ep->gc, RWMSG_OBJTYPE_RWSCHED_OBJREL, ctx->sc_timer, tenv.rwsched, tenv.tasklet[0]);
ctx->sc_timer = NULL;
// rwsched_dispatch_main_until(tenv.tasklet[0], 5, NULL);
}
} else if (squat == 2) { /* For *ConcurQ* tests */
rwsched_dispatch_queue_t cuncurQ = rwsched_dispatch_get_global_queue(tenv.tasklet[0], DISPATCH_QUEUE_PRIORITY_DEFAULT);
rwsched_dispatch_async_f(tenv.tasklet[0], cuncurQ, ctx, lottakickoff02);
rwsched_dispatch_async_f(tenv.tasklet[0], cuncurQ, ctx, lottakickoff02);
rwsched_dispatch_async_f(tenv.tasklet[0], cuncurQ, ctx, lottakickoff02);
rwsched_dispatch_async_f(tenv.tasklet[0], cuncurQ, ctx, lottakickoff02);
rwsched_dispatch_async_f(tenv.tasklet[0], cuncurQ, ctx, lottakickoff02);
rwsched_dispatch_async_f(tenv.tasklet[0], ctx->rwq[0], ctx, lottakickoff02);
rwsched_dispatch_async_f(tenv.tasklet[0], ctx->rwq[0], ctx, lottakickoff02);
rwsched_dispatch_async_f(tenv.tasklet[0], ctx->rwq[0], ctx, lottakickoff02);
rwsched_dispatch_async_f(tenv.tasklet[0], ctx->rwq[0], ctx, lottakickoff02);
rwsched_dispatch_async_f(tenv.tasklet[0], ctx->rwq[0], ctx, lottakickoff02);
int sec_start = time(NULL);
double sec = 5;
if (RUNNING_ON_VALGRIND) {
sec = sec * 5 / 2 ;
}
/* Run the main queue for 5s or longer under valgrind */
#if 1
for(int i=0; !ctx->done && i<100; i++) {
rwsched_dispatch_main_until(tenv.tasklet[0], sec/100, NULL);
}
#else
rwsched_dispatch_main_until(tenv.tasklet[0], sec, NULL);
#endif
VERBPRN("\nln=%d ctx->done=%d ctx->rspout=%u\n", __LINE__, ctx->done, ctx->rspout);
ctx->sendmore = FALSE;
ck_pr_barrier();
uint32_t endct_in = ctx->in;
uint32_t endct_rspin = ctx->rspin;
uint32_t endct_rspout = ctx->rspout;
uint32_t endct_bncout = ctx->bncout;
int iter=0;
VERBPRN("\n\nMain test run done/timeout; pumping to flush events and/or finish...\n\nln=%d iter=%d ctx->done=%d ctx->rspout=%u bncout=%u\n", __LINE__, iter, ctx->done, ctx->rspout, ctx->bncout);
do {
/* Fake pump the main queue until done */
rwsched_dispatch_main_until(tenv.tasklet[0], 10, &ctx->done);
iter++;
VERBPRN("\nln=%d iter=%d ctx->done=%d ctx->in=%u ctx->rspout=%u ctx->bncout=%u\n", __LINE__, iter, ctx->done, ctx->in, ctx->rspout, ctx->bncout);
if (iter > 6) {
fprintf(stderr, "waiting for done, iter=%d rspout=%u in=%u bnc=%u\n", iter, ctx->rspout, ctx->in, ctx->bncout);
}
if (!RUNNING_ON_VALGRIND) {
ASSERT_LE(iter, 6);
}
ck_pr_barrier();
} while (!ctx->done);
ck_pr_barrier();
VERBPRN("\nln=%d iter=%d ctx->done=%d ctx->rspout=%u ctx->bcnout=%u\n", __LINE__, iter, ctx->done, ctx->rspout, ctx->bncout);
if (!ctx->bncout) {
ASSERT_EQ(ctx->rspout, ctx->in);
ASSERT_EQ(ctx->out, ctx->in);
ASSERT_EQ(ctx->rspout, ctx->rspin);
ASSERT_EQ(ctx->out, ctx->rspout);
if (!ctx->opts->srvrspfromanyq) {
ASSERT_FALSE(ctx->misorderct);
}
} else {
/* Note that we can get bounces plus some might have been
answered even as they bounced on our end. */
ASSERT_EQ(ctx->rspout + ctx->bncout, ctx->in); // rsp+bnc at the client == requests sent by client
ASSERT_GE(ctx->out + ctx->bncout, ctx->in);
ASSERT_LE(ctx->rspout, ctx->rspin);
ASSERT_LE(ctx->out, ctx->bncout + ctx->rspout);
}
int rno;
for (rno=0; rno < SCTEST1_RMAX; rno++) {
ASSERT_TRUE(ctx->r[rno] == NULL);
}
valsout->sec = time(NULL) - sec_start; //sec;
valsout->flushtime = iter*100;
valsout->rmax = ctx->rmax;
valsout->reqsent = endct_in;
valsout->reqans = endct_rspin;
valsout->reqdone = endct_rspout;
valsout->reqbnc = endct_bncout;
valsout->reqbnc_final = ctx->bncout;
valsout->reqhz = (endct_rspout / (ctx->tokenfill_ct-1));
valsout->firstburst = ctx->sendmsg_preflow;
valsout->min_rtt = ctx->min_rtt;
valsout->max_rtt = ctx->max_rtt;
/* Ought to work under val, but there is a cock-up with timers that makes the token refresh et al go wrong */
if (ctx->flowexercise && !ctx->bncout && !RUNNING_ON_VALGRIND) {
ASSERT_EQ(valsout->reqhz, TOKVAL);
}
if (ctx->flowexercise && ctx->sc_timer) {
/* Fake pump the main queue for 1s, allow lingering async_f and
timer calls to flush out */
rwsched_dispatch_source_cancel(tenv.tasklet[0], ctx->sc_timer);
RW_ASSERT(bro);
rwmsg_garbage(&bro->ep->gc, RWMSG_OBJTYPE_RWSCHED_OBJREL, ctx->sc_timer, tenv.rwsched, tenv.tasklet[0]);
ctx->sc_timer = NULL;
// rwsched_dispatch_main_until(tenv.tasklet[0], 5, NULL);
}
} else {
VERBPRN("\n***Squat!***\n");
}
sleep(2);
rwmsg_bool_t r;
rwmsg_signature_release(ep_s, sig);
rwmsg_method_release(ep_s, meth);
rwmsg_srvchan_halt(ctx->sc);
rwmsg_clichan_halt(ctx->cc);
rwmsg_destination_release(dt);
if (!mainq) {
rwsched_dispatch_release(tenv.tasklet[0], ctx->rwq[0]);
rwsched_dispatch_release(tenv.tasklet[0], ctx->rwq[1]);
}
r = rwmsg_endpoint_halt_flush(ep_c, TRUE);
ASSERT_TRUE(r);
r = rwmsg_endpoint_halt_flush(ep_s, TRUE);
ASSERT_TRUE(r);
if (broker_c) {
for (unsigned i=0; i<broker_c; i++) {
r = rwmsg_broker_halt_sync(bros[i]);
ASSERT_TRUE(r);
}
}
RW_FREE_TYPE(ctx->paybuf, sctest1_payload);
RW_FREE_TYPE(ctx, sctest1_context);
rwmsg_global_status_t gs;
rwmsg_global_status_get(&gs);
if (!gs.endpoint_ct) {
ASSERT_EQ(gs.qent, 0);
}
nnchk();
if (rwmsg_global.status.request_ct != start_reqct) {
fprintf(stderr, "***start_reqct=%u ending rwmsg_global.status.request_ct=%u\n", start_reqct, rwmsg_global.status.request_ct);
}
VERBPRN("end rwmsg_global.status.request_ct=%u\n", rwmsg_global.status.request_ct);
VERBPRN("end rwmsg_global.status.qent=%u\n", rwmsg_global.status.qent);
}
TEST(RWMsgBroker, LottaRawRWSConcurQ2Bros) {
TEST_DESCRIPTION("Tests broker under potloads of up to SCTEST1_RMAX requests outstanding, RWSched per-channel Serial Queues");
RWUT_BENCH_ITER(LottaRawRWSConcurQBench, 5, 5);
struct lottarawvals vals;
memset(&vals, 0, sizeof(vals));
struct lottaopts opts;
memset(&opts, 0, sizeof(opts));
int burst = 100;
int broflo = FALSE;
lottaraw2bros(2, false, false, burst, broflo, &opts, &vals); /* For *ConcurQ* tests */
#if 0
RecordProperty("FlushTime", vals.flushtime);
RecordProperty("rmax", vals.rmax);
RecordProperty("ReqSent", vals.reqsent);
RecordProperty("ReqAnswered", vals.reqans);
RecordProperty("ReqDone", vals.reqdone);
RecordProperty("ReqHz", vals.reqhz);
#endif
PRINT_REPORT("RWMsgBroker.LottaRawRWSConcurQ2Bros");
nnchk();
RWUT_BENCH_END(LottaRawRWSConcurQBench);
}
TEST(RWMsgBroker, LottaRawRWSBigdefwinMainQ2Bros) {
TEST_DESCRIPTION("Tests broker under potloads of up to SCTEST1_RMAX requests outstanding, RWSched Main Queue");
RWUT_BENCH_ITER(LottaRawRWSBigdefwinMainQBench, 5, 5);
struct lottarawvals vals;
memset(&vals, 0, sizeof(vals));
struct lottaopts opts;
memset(&opts, 0, sizeof(opts));
opts.bigdefwin = 100;
int burst = 100;
int broflo = FALSE;
int squat = FALSE;
lottaraw2bros(squat, true, false, burst, broflo, &opts, &vals);
#if 0
RecordProperty("FlushTime", vals.flushtime);
RecordProperty("rmax", vals.rmax);
RecordProperty("ReqSent", vals.reqsent);
RecordProperty("ReqAnswered", vals.reqans);
RecordProperty("ReqDone", vals.reqdone);
RecordProperty("ReqHz", vals.reqhz);
#endif
PRINT_REPORT("RWMsgBroker.LottaRawRWSBigdefwinMainQ2Bros");
nnchk();
RWUT_BENCH_END(LottaRawRWSBigdefwinMainQBench);
}
TEST(RWMsgBroker, LottaRawRWSMainQ2Bros) {
TEST_DESCRIPTION("Tests broker under potloads of up to SCTEST1_RMAX requests outstanding, RWSched Main Queue");
RWUT_BENCH_ITER(LottaRawRWSMainQBench, 5, 5);
struct lottarawvals vals;
memset(&vals, 0, sizeof(vals));
struct lottaopts opts;
memset(&opts, 0, sizeof(opts));
int burst = 100;
int broflo = FALSE;
int squat = FALSE;
lottaraw2bros(squat, true, false, burst, broflo, &opts, &vals);
#if 0
RecordProperty("FlushTime", vals.flushtime);
RecordProperty("rmax", vals.rmax);
RecordProperty("ReqSent", vals.reqsent);
RecordProperty("ReqAnswered", vals.reqans);
RecordProperty("ReqDone", vals.reqdone);
RecordProperty("ReqHz", vals.reqhz);
#endif
PRINT_REPORT("RWMsgBroker.LottaRawRWSMainQ2Bros");
nnchk();
RWUT_BENCH_END(LottaRawRWSMainQBench);
}
TEST(RWMsgBroker, LottaRawBncRWSMainQ2Bros) {
TEST_DESCRIPTION("Exercise broker timeout bounce code path.");
RWUT_BENCH_ITER(LottaRawBncRWSMainQBench, 5, 5);
struct lottarawvals vals;
memset(&vals, 0, sizeof(vals));
struct lottaopts opts;
memset(&opts, 0, sizeof(opts));
int burst = 1;
int broflo = FALSE;
int squat = FALSE;
opts.reqtimeo = 50;/*ms*/
opts.bncall = TRUE;
lottaraw2bros(squat, true, false, burst, broflo, &opts, &vals);
#if 0
RecordProperty("FlushTime", vals.flushtime);
RecordProperty("rmax", vals.rmax);
RecordProperty("ReqSent", vals.reqsent);
RecordProperty("ReqAnswered", vals.reqans);
RecordProperty("ReqDone", vals.reqdone);
RecordProperty("ReqHz", vals.reqhz);
#endif
PRINT_REPORT("RWMsgBroker.LottaRawBncRWSMainQ2Bros");
nnchk();
RWUT_BENCH_END(LottaRawBncRWSMainQBench);
}
TEST(RWMsgBroker, Big0512RawRWSMainQ2Bros) {
TEST_DESCRIPTION("Tests broker with big 512KB requests, RWSched Main Queue");
RWUT_BENCH_ITER(Big0512RawRWSMainQBench, 5, 5);
struct lottarawvals vals;
memset(&vals, 0, sizeof(vals));
struct lottaopts opts;
memset(&opts, 0, sizeof(opts));
opts.paysz = 512000;
int burst = 10;
int broflo = FALSE;
int squat = FALSE;
lottaraw2bros(squat, true, false, burst, broflo, &opts, &vals);
#if 0
RecordProperty("FlushTime", vals.flushtime);
RecordProperty("rmax", vals.rmax);
RecordProperty("ReqSent", vals.reqsent);
RecordProperty("ReqAnswered", vals.reqans);
RecordProperty("ReqDone", vals.reqdone);
RecordProperty("ReqHz", vals.reqhz);
#endif
PRINT_REPORT("RWMsgBroker.Big0512RawRWSMainQ2Bros");
nnchk();
RWUT_BENCH_END(Big0512RawRWSMainQBench);
}
TEST(RWMsgBroker, Big5120RawRWSMainQ2Bros) {
TEST_DESCRIPTION("Tests broker with big 5MB requests, RWSched Main Queue");
RWUT_BENCH_ITER(Big5120RawRWSMainQBench, 5, 5);
struct lottarawvals vals;
memset(&vals, 0, sizeof(vals));
struct lottaopts opts;
memset(&opts, 0, sizeof(opts));
opts.paysz = 5120000;
int burst = 10;
int broflo = FALSE;
int squat = FALSE;
lottaraw2bros(squat, true, false, burst, broflo, &opts, &vals);
#if 0
RecordProperty("FlushTime", vals.flushtime);
RecordProperty("rmax", vals.rmax);
RecordProperty("ReqSent", vals.reqsent);
RecordProperty("ReqAnswered", vals.reqans);
RecordProperty("ReqDone", vals.reqdone);
RecordProperty("ReqHz", vals.reqhz);
#endif
PRINT_REPORT("RWMsgBroker.Big5120RawRWSMainQ2Bros");
nnchk();
RWUT_BENCH_END(Big5120RawRWSMainQBench);
}
TEST(RWMsgBroker, LottaPauseRawRWSSerQ2Bros) {
TEST_DESCRIPTION("Tests broker pause under potloads of up to SCTEST1_RMAX requests outstanding, RWSched Serial Queue");
RWUT_BENCH_ITER(LottaPauseRawRWSSerQBench, 5, 5);
struct lottarawvals vals;
memset(&vals, 0, sizeof(vals));
struct lottaopts opts;
memset(&opts, 0, sizeof(opts));
int burst = 100;
burst=burst;
int broflo = FALSE;
lottaraw2bros(false, false/*mainq*/, true/*noread*/, burst, broflo, &opts, &vals);
#if 0
RecordProperty("FlushTime", vals.flushtime);
RecordProperty("rmax", vals.rmax);
RecordProperty("ReqSent", vals.reqsent);
RecordProperty("ReqAnswered", vals.reqans);
RecordProperty("ReqDone", vals.reqdone);
RecordProperty("ReqHz", vals.reqhz);
#endif
PRINT_REPORT("RWMsgBroker.LottaPauseRawRWSSerQ2Bros");
nnchk();
RWUT_BENCH_END(LottaPauseRawRWSSerQBench);
}
TEST(RWMsgBroker, LottaPauseBigwinRawRWSSerQ2Bros) {
TEST_DESCRIPTION("Tests broker pause under SCTEST1_RMAX requests outstanding, RWSched Serial Queue");
RWUT_BENCH_ITER(LottaPauseBigwinRawRWSSerQBench, 5, 5);
struct lottarawvals vals;
memset(&vals, 0, sizeof(vals));
struct lottaopts opts;
memset(&opts, 0, sizeof(opts));
int burst = SCTEST1_RMAX;
burst=burst;
int broflo = FALSE;
opts.bigbrosrvwin = TRUE;
lottaraw2bros(false, false/*mainq*/, true/*noread*/, burst, broflo, &opts, &vals);
#if 0
RecordProperty("FlushTime", vals.flushtime);
RecordProperty("rmax", vals.rmax);
RecordProperty("ReqSent", vals.reqsent);
RecordProperty("ReqAnswered", vals.reqans);
RecordProperty("ReqDone", vals.reqdone);
RecordProperty("ReqHz", vals.reqhz);
#endif
PRINT_REPORT("RWMsgBroker.LottaPauseBigwinRawRWSSerQ2Bros");
nnchk();
RWUT_BENCH_END(LottaPauseBigwinRawRWSSerQBench);
}
TEST(RWMsgBroker, LottaPauseRawRWSMainQ2Bros) {
TEST_DESCRIPTION("Tests broker pause under potloads of up to SCTEST1_RMAX requests outstanding, RWSched Main Queue");
RWUT_BENCH_ITER(LottaPauseRawRWSMainQBench, 5, 5);
struct lottarawvals vals;
memset(&vals, 0, sizeof(vals));
struct lottaopts opts;
memset(&opts, 0, sizeof(opts));
int burst = 100;
int broflo = FALSE;
lottaraw2bros(false, true/*mainq*/, true/*noread*/, burst, broflo, &opts, &vals);
#if 0
RecordProperty("FlushTime", vals.flushtime);
RecordProperty("rmax", vals.rmax);
RecordProperty("ReqSent", vals.reqsent);
RecordProperty("ReqAnswered", vals.reqans);
RecordProperty("ReqDone", vals.reqdone);
RecordProperty("ReqHz", vals.reqhz);
#endif
PRINT_REPORT("RWMsgBroker.LottaPauseRawRWSMainQ2Bros");
nnchk();
RWUT_BENCH_END(LottaPauseRawRWSMainQBench);
}
TEST(RWMsgBroker, LottaPauseBigwinRawRWSMainQ2Bros) {
TEST_DESCRIPTION("Tests broker pause under SCTEST1_RMAX requests outstanding, RWSched Main Queue");
RWUT_BENCH_ITER(LottaPauseBigwinRawRWSMainQBench, 5, 5);
struct lottarawvals vals;
memset(&vals, 0, sizeof(vals));
struct lottaopts opts;
memset(&opts, 0, sizeof(opts));
int burst = SCTEST1_RMAX;
int broflo = FALSE;
opts.bigbrosrvwin = TRUE;
lottaraw2bros(false, true/*mainq*/, true/*noread*/, burst, broflo, &opts, &vals);
#if 0
RecordProperty("FlushTime", vals.flushtime);
RecordProperty("rmax", vals.rmax);
RecordProperty("ReqSent", vals.reqsent);
RecordProperty("ReqAnswered", vals.reqans);
RecordProperty("ReqDone", vals.reqdone);
RecordProperty("ReqHz", vals.reqhz);
#endif
PRINT_REPORT("RWMsgBroker.LottaPauseBigwinRawRWSMainQ2Bros");
nnchk();
RWUT_BENCH_END(LottaPauseBigwinRawRWSMainQBench);
}
TEST(RWMsgPerftool, CollapsedNofeedme) {
int broport = rwmsg_broport_g(4);
char nnuri[128];
sprintf(nnuri, "tcp://%s:%d", RWMSG_CONNECT_ADDR_STR, broport);
const char *filename = "./rwmsg_perftool";
const char *argv[] = {
"rwmsg_perftool",
"--nnuri",
nnuri,
"--tasklet",
"server",
"--instance",
"1",
"--size",
"64",
"--tasklet",
"client",
"--instance",
"1",
"--runtime",
"45",
"--nofeedme",
"--size",
"64",
"--window",
"999999",
"--count",
"1000000",
NULL
};
#define RUNPERF() \
pid_t c = fork(); \
if (!c) { \
int i=0; \
while (argv[i]) fprintf(stderr,"%s ", argv[i++]); \
fprintf(stderr,"\n"); \
execv(filename, (char* const*) argv); \
abort(); \
} \
RW_ASSERT(c > 0); \
int status = 0; \
pid_t pid = waitpid(c, &status, 0); \
ASSERT_GE(pid, 1); \
if (pid > 0) { \
ASSERT_EQ(WEXITSTATUS(status), 0); \
}
RUNPERF();
}
TEST(RWMsgPerftool, LargeNofeedme) {
int broport = rwmsg_broport_g(4);
char nnuri[128];
sprintf(nnuri, "tcp://%s:%d", RWMSG_CONNECT_ADDR_STR, broport);
const char *filename = "./rwmsg_perftool";
const char *argv[] = {
"rwmsg_perftool",
"--nnuri",
nnuri,
"--shunt",
"--tasklet",
"broker",
"--tasklet",
"server",
"--instance",
"1",
"--size",
"64",
"--tasklet",
"client",
"--instance",
"1",
"--runtime",
"360",
"--nofeedme",
"--size",
"64",
"--window",
"999999",
"--count",
"1000000",
NULL
};
RUNPERF();
}
TEST(RWMsgPerftool, LargeNofeedme2Bros) {
int broport = rwmsg_broport_g(4);
char nnuri[128];
sprintf(nnuri, "tcp://%s:%d", RWMSG_CONNECT_ADDR_STR, broport);
const char *filename = "./rwmsg_perftool";
const char *argv[] = {
"rwmsg_perftool",
"--nnuri",
nnuri,
"--shunt",
"--tasklet",
"broker",
"--instance",
"1",
"--tasklet",
"broker",
"--instance",
"2",
"--tasklet",
"server",
"--instance",
"1",
"--broinst",
"1",
"--size",
"64",
"--tasklet",
"client",
"--instance",
"1",
"--broinst",
"2",
"--runtime",
"50",
"--nofeedme",
"--size",
"64",
"--window",
"999999",
"--count",
"50000",
NULL
};
RUNPERF();
}
TEST(RWMsgPerftool, LargeNofeedme1000) {
int broport = rwmsg_broport_g(4);
char nnuri[128];
sprintf(nnuri, "tcp://%s:%d", RWMSG_CONNECT_ADDR_STR, broport);
const char *filename = "./rwmsg_perftool";
const char *argv[] = {
"rwmsg_perftool",
"--nnuri",
nnuri,
"--shunt",
"--tasklet",
"broker",
"--window",
"1000",
"--tasklet",
"server",
"--instance",
"1",
"--size",
"64",
"--tasklet",
"client",
"--instance",
"1",
"--runtime",
"300",
"--nofeedme",
"--size",
"64",
"--window",
"999999",
"--count",
"1000000",
NULL
};
RUNPERF();
}
TEST(RWMsgPerftool, LargeNofeedme10002Bros) {
int broport = rwmsg_broport_g(4);
char nnuri[128];
sprintf(nnuri, "tcp://%s:%d", RWMSG_CONNECT_ADDR_STR, broport);
const char *filename = "./rwmsg_perftool";
const char *argv[] = {
"rwmsg_perftool",
"--nnuri",
nnuri,
"--shunt",
"--tasklet",
"broker",
"--instance",
"1",
"--tasklet",
"broker",
"--instance",
"2",
"--window",
"1000",
"--tasklet",
"server",
"--instance",
"1",
"--broinst",
"1",
"--size",
"64",
"--tasklet",
"client",
"--instance",
"1",
"--broinst",
"2",
"--runtime",
"300",
"--nofeedme",
"--size",
"64",
"--window",
"999999",
"--count",
"50000",
NULL
};
RUNPERF();
}
TEST(RWMsgPerftool, DISABLED_CollapsedFeedmeBigwin) {
int broport = rwmsg_broport_g(4);
char nnuri[128];
sprintf(nnuri, "tcp://%s:%d", RWMSG_CONNECT_ADDR_STR, broport);
const char *filename = "./rwmsg_perftool";
const char *argv[] = {
"rwmsg_perftool",
"--nnuri",
nnuri,
"--tasklet",
"server",
"--instance",
"1",
"--size",
"64",
"--tasklet",
"client",
"--instance",
"1",
"--runtime",
"30",
"--size",
"64",
"--window",
"999999",
"--count",
"1000000",
NULL
};
RUNPERF();
}
TEST(RWMsgPerftool, DISABLED_LargeFeedmeBigwin) {
int broport = rwmsg_broport_g(4);
char nnuri[128];
sprintf(nnuri, "tcp://%s:%d", RWMSG_CONNECT_ADDR_STR, broport);
const char *filename = "rwmsg_perftool";
const char *argv[] = {
"rwmsg_perftool",
"--nnuri",
nnuri,
"--shunt",
"--tasklet",
"broker",
"--tasklet",
"server",
"--instance",
"1",
"--size",
"64",
"--tasklet",
"client",
"--instance",
"1",
"--runtime",
"30",
"--size",
"64",
"--window",
"99999",
"--count",
"100000",
NULL
};
RUNPERF();
}
TEST(RWMsgPerftool, DISABLED_LargeFeedmeBigwin2Bros) {
int broport = rwmsg_broport_g(4);
char nnuri[128];
sprintf(nnuri, "tcp://%s:%d", RWMSG_CONNECT_ADDR_STR, broport);
const char *filename = "rwmsg_perftool";
const char *argv[] = {
"rwmsg_perftool",
"--nnuri",
nnuri,
"--shunt",
"--tasklet",
"broker",
"--instance",
"1",
"--tasklet",
"broker",
"--instance",
"2",
"--tasklet",
"server",
"--instance",
"1",
"--broinst",
"1",
"--size",
"64",
"--tasklet",
"client",
"--instance",
"1",
"--broinst",
"2",
"--runtime",
"50",
"--size",
"64",
"--window",
"99999",
"--count",
"50000",
NULL
};
RUNPERF();
}
TEST(RWMsgPerftool, DISABLED_LargeFeedmeBigwin1000) {
int broport = rwmsg_broport_g(4);
char nnuri[128];
sprintf(nnuri, "tcp://%s:%d", RWMSG_CONNECT_ADDR_STR, broport);
const char *filename = "rwmsg_perftool";
const char *argv[] = {
"rwmsg_perftool",
"--nnuri",
nnuri,
"--shunt",
"--tasklet",
"broker",
"--window",
"1000",
"--tasklet",
"server",
"--instance",
"1",
"--size",
"64",
"--tasklet",
"client",
"--instance",
"1",
"--runtime",
"30",
"--size",
"64",
"--window",
"99999",
"--count",
"100000",
NULL
};
RUNPERF();
}
TEST(RWMsgPerftool, DISABLED_LargeFeedmeBigwin10002Bros) {
int broport = rwmsg_broport_g(4);
char nnuri[128];
sprintf(nnuri, "tcp://%s:%d", RWMSG_CONNECT_ADDR_STR, broport);
const char *filename = "rwmsg_perftool";
const char *argv[] = {
"rwmsg_perftool",
"--nnuri",
nnuri,
"--shunt",
"--tasklet",
"broker",
"--instance",
"1",
"--window",
"1000",
"--tasklet",
"broker",
"--instance",
"2",
"--window",
"1000",
"--tasklet",
"server",
"--instance",
"1",
"--broinst",
"1",
"--size",
"64",
"--tasklet",
"client",
"--instance",
"1",
"--broinst",
"2",
"--runtime",
"50",
"--size",
"64",
"--window",
"99999",
"--count",
"50000",
NULL
};
RUNPERF();
}
TEST(RWMsgPerftool, CollapsedFeedmeSmwin) {
int broport = rwmsg_broport_g(4);
char nnuri[128];
sprintf(nnuri, "tcp://%s:%d", RWMSG_CONNECT_ADDR_STR, broport);
const char *filename = "rwmsg_perftool";
const char *argv[] = {
"rwmsg_perftool",
"--nnuri",
nnuri,
"--tasklet",
"server",
"--instance",
"1",
"--size",
"64",
"--tasklet",
"client",
"--instance",
"1",
"--runtime",
"30",
"--size",
"64",
"--window",
"999",
"--count",
"100000",
NULL
};
RUNPERF();
}
TEST(RWMsgPerftool, LargeFeedmeSmwin) {
int broport = rwmsg_broport_g(4);
char nnuri[128];
sprintf(nnuri, "tcp://%s:%d", RWMSG_CONNECT_ADDR_STR, broport);
const char *filename = "rwmsg_perftool";
const char *argv[] = {
"rwmsg_perftool",
"--nnuri",
nnuri,
"--shunt",
"--tasklet",
"broker",
"--tasklet",
"server",
"--instance",
"1",
"--size",
"64",
"--tasklet",
"client",
"--instance",
"1",
"--runtime",
"60",
"--size",
"64",
"--window",
"999",
"--count",
"100000",
NULL
};
RUNPERF();
}
TEST(RWMsgPerftool, LargeFeedmeSmwin2Bros) {
int broport = rwmsg_broport_g(4);
char nnuri[128];
sprintf(nnuri, "tcp://%s:%d", RWMSG_CONNECT_ADDR_STR, broport);
const char *filename = "rwmsg_perftool";
const char *argv[] = {
"rwmsg_perftool",
"--nnuri",
nnuri,
"--shunt",
"--tasklet",
"broker",
"--instance",
"1",
"--tasklet",
"broker",
"--instance",
"2",
"--tasklet",
"server",
"--instance",
"1",
"--broinst",
"1",
"--size",
"64",
"--tasklet",
"client",
"--instance",
"1",
"--broinst",
"2",
"--runtime",
"50",
"--size",
"64",
"--window",
"999",
"--count",
"50000",
NULL
};
RUNPERF();
}
TEST(RWMsgPerftool, LargeFeedmeSmwin1000) {
int broport = rwmsg_broport_g(4);
char nnuri[128];
sprintf(nnuri, "tcp://%s:%d", RWMSG_CONNECT_ADDR_STR, broport);
const char *filename = "rwmsg_perftool";
const char *argv[] = {
"rwmsg_perftool",
"--nnuri",
nnuri,
"--shunt",
"--tasklet",
"broker",
"--window",
"1000",
"--tasklet",
"server",
"--instance",
"1",
"--size",
"64",
"--tasklet",
"client",
"--instance",
"1",
"--runtime",
"30",
"--size",
"64",
"--window",
"999",
"--count",
"100000",
NULL
};
RUNPERF();
}
TEST(RWMsgPerftool, LargeFeedmeSmwin10002Bros) {
int broport = rwmsg_broport_g(4);
char nnuri[128];
sprintf(nnuri, "tcp://%s:%d", RWMSG_CONNECT_ADDR_STR, broport);
const char *filename = "rwmsg_perftool";
const char *argv[] = {
"rwmsg_perftool",
"--nnuri",
nnuri,
"--shunt",
"--tasklet",
"broker",
"--instance",
"1",
"--window",
"1000",
"--tasklet",
"broker",
"--instance",
"2",
"--window",
"1000",
"--tasklet",
"server",
"--instance",
"1",
"--broinst",
"1",
"--size",
"64",
"--tasklet",
"client",
"--instance",
"1",
"--broinst",
"2",
"--runtime",
"50",
"--size",
"64",
"--window",
"999",
"--count",
"50000",
NULL
};
RUNPERF();
}
|
[
"Jeremy.Mordkoff@riftio.com"
] |
Jeremy.Mordkoff@riftio.com
|
a6b47b8400874789e4e875b7bd90d7e58efc8234
|
fb5b25b4fbe66c532672c14dacc520b96ff90a04
|
/export/release/windows/obj/src/lime/app/_Event_ofEvents_T_Void.cpp
|
7f67d0c33f4924ffc0424ab7c59b72dd9c12d57e
|
[
"Apache-2.0"
] |
permissive
|
Tyrcnex/tai-mod
|
c3849f817fe871004ed171245d63c5e447c4a9c3
|
b83152693bb3139ee2ae73002623934f07d35baf
|
refs/heads/main
| 2023-08-15T07:15:43.884068
| 2021-09-29T23:39:23
| 2021-09-29T23:39:23
| 383,313,424
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 11,737
|
cpp
|
#include <hxcpp.h>
#ifndef INCLUDED_Reflect
#include <Reflect.h>
#endif
#ifndef INCLUDED_lime_app__Event_ofEvents_T_Void
#include <lime/app/_Event_ofEvents_T_Void.h>
#endif
HX_DEFINE_STACK_FRAME(_hx_pos_602a5331235d55ea_42_new,"lime.app._Event_ofEvents_T_Void","new",0xde11e822,"lime.app._Event_ofEvents_T_Void.new","lime/app/Event.hx",42,0xbda45bec)
HX_LOCAL_STACK_FRAME(_hx_pos_602a5331235d55ea_58_add,"lime.app._Event_ofEvents_T_Void","add",0xde0809e3,"lime.app._Event_ofEvents_T_Void.add","lime/app/Event.hx",58,0xbda45bec)
HX_LOCAL_STACK_FRAME(_hx_pos_602a5331235d55ea_82_cancel,"lime.app._Event_ofEvents_T_Void","cancel",0x39599af8,"lime.app._Event_ofEvents_T_Void.cancel","lime/app/Event.hx",82,0xbda45bec)
HX_LOCAL_STACK_FRAME(_hx_pos_602a5331235d55ea_127_has,"lime.app._Event_ofEvents_T_Void","has",0xde0d571c,"lime.app._Event_ofEvents_T_Void.has","lime/app/Event.hx",127,0xbda45bec)
HX_LOCAL_STACK_FRAME(_hx_pos_602a5331235d55ea_143_remove,"lime.app._Event_ofEvents_T_Void","remove",0x85ae49c2,"lime.app._Event_ofEvents_T_Void.remove","lime/app/Event.hx",143,0xbda45bec)
HX_LOCAL_STACK_FRAME(_hx_pos_602a5331235d55ea_163_removeAll,"lime.app._Event_ofEvents_T_Void","removeAll",0x7c126c7f,"lime.app._Event_ofEvents_T_Void.removeAll","lime/app/Event.hx",163,0xbda45bec)
HX_LOCAL_STACK_FRAME(_hx_pos_89c82c0cd6a35496_82_dispatch,"lime.app._Event_ofEvents_T_Void","dispatch",0x766e57b8,"lime.app._Event_ofEvents_T_Void.dispatch","lime/_internal/macros/EventMacro.hx",82,0xc5a10671)
namespace lime{
namespace app{
void _Event_ofEvents_T_Void_obj::__construct(){
HX_STACKFRAME(&_hx_pos_602a5331235d55ea_42_new)
HXLINE( 44) this->canceled = false;
HXLINE( 45) this->_hx___listeners = ::Array_obj< ::Dynamic>::__new();
HXLINE( 46) this->_hx___priorities = ::Array_obj< int >::__new();
HXLINE( 47) this->_hx___repeat = ::Array_obj< bool >::__new();
}
Dynamic _Event_ofEvents_T_Void_obj::__CreateEmpty() { return new _Event_ofEvents_T_Void_obj; }
void *_Event_ofEvents_T_Void_obj::_hx_vtable = 0;
Dynamic _Event_ofEvents_T_Void_obj::__Create(::hx::DynamicArray inArgs)
{
::hx::ObjectPtr< _Event_ofEvents_T_Void_obj > _hx_result = new _Event_ofEvents_T_Void_obj();
_hx_result->__construct();
return _hx_result;
}
bool _Event_ofEvents_T_Void_obj::_hx_isInstanceOf(int inClassId) {
return inClassId==(int)0x00000001 || inClassId==(int)0x2d049712;
}
void _Event_ofEvents_T_Void_obj::add( ::Dynamic listener,::hx::Null< bool > __o_once,::hx::Null< int > __o_priority){
bool once = __o_once.Default(false);
int priority = __o_priority.Default(0);
HX_STACKFRAME(&_hx_pos_602a5331235d55ea_58_add)
HXLINE( 60) {
HXLINE( 60) int _g = 0;
HXDLIN( 60) int _g1 = this->_hx___priorities->length;
HXDLIN( 60) while((_g < _g1)){
HXLINE( 60) _g = (_g + 1);
HXDLIN( 60) int i = (_g - 1);
HXLINE( 62) if ((priority > this->_hx___priorities->__get(i))) {
HXLINE( 64) this->_hx___listeners->insert(i,listener);
HXLINE( 65) this->_hx___priorities->insert(i,priority);
HXLINE( 66) this->_hx___repeat->insert(i,!(once));
HXLINE( 67) return;
}
}
}
HXLINE( 71) this->_hx___listeners->push(listener);
HXLINE( 72) this->_hx___priorities->push(priority);
HXLINE( 73) this->_hx___repeat->push(!(once));
}
HX_DEFINE_DYNAMIC_FUNC3(_Event_ofEvents_T_Void_obj,add,(void))
void _Event_ofEvents_T_Void_obj::cancel(){
HX_STACKFRAME(&_hx_pos_602a5331235d55ea_82_cancel)
HXDLIN( 82) this->canceled = true;
}
HX_DEFINE_DYNAMIC_FUNC0(_Event_ofEvents_T_Void_obj,cancel,(void))
bool _Event_ofEvents_T_Void_obj::has( ::Dynamic listener){
HX_STACKFRAME(&_hx_pos_602a5331235d55ea_127_has)
HXLINE( 129) {
HXLINE( 129) int _g = 0;
HXDLIN( 129) ::Array< ::Dynamic> _g1 = this->_hx___listeners;
HXDLIN( 129) while((_g < _g1->length)){
HXLINE( 129) ::Dynamic l = _g1->__get(_g);
HXDLIN( 129) _g = (_g + 1);
HXLINE( 131) if (::Reflect_obj::compareMethods(l,listener)) {
HXLINE( 131) return true;
}
}
}
HXLINE( 135) return false;
}
HX_DEFINE_DYNAMIC_FUNC1(_Event_ofEvents_T_Void_obj,has,return )
void _Event_ofEvents_T_Void_obj::remove( ::Dynamic listener){
HX_STACKFRAME(&_hx_pos_602a5331235d55ea_143_remove)
HXLINE( 145) int i = this->_hx___listeners->length;
HXLINE( 147) while(true){
HXLINE( 147) i = (i - 1);
HXDLIN( 147) if (!((i >= 0))) {
HXLINE( 147) goto _hx_goto_6;
}
HXLINE( 149) if (::Reflect_obj::compareMethods(this->_hx___listeners->__get(i),listener)) {
HXLINE( 151) this->_hx___listeners->removeRange(i,1);
HXLINE( 152) this->_hx___priorities->removeRange(i,1);
HXLINE( 153) this->_hx___repeat->removeRange(i,1);
}
}
_hx_goto_6:;
}
HX_DEFINE_DYNAMIC_FUNC1(_Event_ofEvents_T_Void_obj,remove,(void))
void _Event_ofEvents_T_Void_obj::removeAll(){
HX_STACKFRAME(&_hx_pos_602a5331235d55ea_163_removeAll)
HXLINE( 165) int len = this->_hx___listeners->length;
HXLINE( 167) this->_hx___listeners->removeRange(0,len);
HXLINE( 168) this->_hx___priorities->removeRange(0,len);
HXLINE( 169) this->_hx___repeat->removeRange(0,len);
}
HX_DEFINE_DYNAMIC_FUNC0(_Event_ofEvents_T_Void_obj,removeAll,(void))
void _Event_ofEvents_T_Void_obj::dispatch( ::Dynamic a){
HX_STACKFRAME(&_hx_pos_89c82c0cd6a35496_82_dispatch)
HXLINE( 83) this->canceled = false;
HXLINE( 85) ::Array< ::Dynamic> listeners = this->_hx___listeners;
HXLINE( 86) ::Array< bool > repeat = this->_hx___repeat;
HXLINE( 87) int i = 0;
HXLINE( 89) while((i < listeners->length)){
HXLINE( 91) listeners->__get(i)(a);
HXLINE( 93) if (!(repeat->__get(i))) {
HXLINE( 95) this->remove(listeners->__get(i));
}
else {
HXLINE( 99) i = (i + 1);
}
HXLINE( 102) if (this->canceled) {
HXLINE( 104) goto _hx_goto_9;
}
}
_hx_goto_9:;
}
HX_DEFINE_DYNAMIC_FUNC1(_Event_ofEvents_T_Void_obj,dispatch,(void))
::hx::ObjectPtr< _Event_ofEvents_T_Void_obj > _Event_ofEvents_T_Void_obj::__new() {
::hx::ObjectPtr< _Event_ofEvents_T_Void_obj > __this = new _Event_ofEvents_T_Void_obj();
__this->__construct();
return __this;
}
::hx::ObjectPtr< _Event_ofEvents_T_Void_obj > _Event_ofEvents_T_Void_obj::__alloc(::hx::Ctx *_hx_ctx) {
_Event_ofEvents_T_Void_obj *__this = (_Event_ofEvents_T_Void_obj*)(::hx::Ctx::alloc(_hx_ctx, sizeof(_Event_ofEvents_T_Void_obj), true, "lime.app._Event_ofEvents_T_Void"));
*(void **)__this = _Event_ofEvents_T_Void_obj::_hx_vtable;
__this->__construct();
return __this;
}
_Event_ofEvents_T_Void_obj::_Event_ofEvents_T_Void_obj()
{
}
void _Event_ofEvents_T_Void_obj::__Mark(HX_MARK_PARAMS)
{
HX_MARK_BEGIN_CLASS(_Event_ofEvents_T_Void);
HX_MARK_MEMBER_NAME(canceled,"canceled");
HX_MARK_MEMBER_NAME(_hx___repeat,"__repeat");
HX_MARK_MEMBER_NAME(_hx___priorities,"__priorities");
HX_MARK_MEMBER_NAME(_hx___listeners,"__listeners");
HX_MARK_END_CLASS();
}
void _Event_ofEvents_T_Void_obj::__Visit(HX_VISIT_PARAMS)
{
HX_VISIT_MEMBER_NAME(canceled,"canceled");
HX_VISIT_MEMBER_NAME(_hx___repeat,"__repeat");
HX_VISIT_MEMBER_NAME(_hx___priorities,"__priorities");
HX_VISIT_MEMBER_NAME(_hx___listeners,"__listeners");
}
::hx::Val _Event_ofEvents_T_Void_obj::__Field(const ::String &inName,::hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 3:
if (HX_FIELD_EQ(inName,"add") ) { return ::hx::Val( add_dyn() ); }
if (HX_FIELD_EQ(inName,"has") ) { return ::hx::Val( has_dyn() ); }
break;
case 6:
if (HX_FIELD_EQ(inName,"cancel") ) { return ::hx::Val( cancel_dyn() ); }
if (HX_FIELD_EQ(inName,"remove") ) { return ::hx::Val( remove_dyn() ); }
break;
case 8:
if (HX_FIELD_EQ(inName,"canceled") ) { return ::hx::Val( canceled ); }
if (HX_FIELD_EQ(inName,"__repeat") ) { return ::hx::Val( _hx___repeat ); }
if (HX_FIELD_EQ(inName,"dispatch") ) { return ::hx::Val( dispatch_dyn() ); }
break;
case 9:
if (HX_FIELD_EQ(inName,"removeAll") ) { return ::hx::Val( removeAll_dyn() ); }
break;
case 11:
if (HX_FIELD_EQ(inName,"__listeners") ) { return ::hx::Val( _hx___listeners ); }
break;
case 12:
if (HX_FIELD_EQ(inName,"__priorities") ) { return ::hx::Val( _hx___priorities ); }
}
return super::__Field(inName,inCallProp);
}
::hx::Val _Event_ofEvents_T_Void_obj::__SetField(const ::String &inName,const ::hx::Val &inValue,::hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 8:
if (HX_FIELD_EQ(inName,"canceled") ) { canceled=inValue.Cast< bool >(); return inValue; }
if (HX_FIELD_EQ(inName,"__repeat") ) { _hx___repeat=inValue.Cast< ::Array< bool > >(); return inValue; }
break;
case 11:
if (HX_FIELD_EQ(inName,"__listeners") ) { _hx___listeners=inValue.Cast< ::Array< ::Dynamic> >(); return inValue; }
break;
case 12:
if (HX_FIELD_EQ(inName,"__priorities") ) { _hx___priorities=inValue.Cast< ::Array< int > >(); return inValue; }
}
return super::__SetField(inName,inValue,inCallProp);
}
void _Event_ofEvents_T_Void_obj::__GetFields(Array< ::String> &outFields)
{
outFields->push(HX_("canceled",59,18,26,1f));
outFields->push(HX_("__repeat",7b,02,ac,ae));
outFields->push(HX_("__priorities",e2,cb,e6,1c));
outFields->push(HX_("__listeners",5f,ae,ba,21));
super::__GetFields(outFields);
};
#ifdef HXCPP_SCRIPTABLE
static ::hx::StorageInfo _Event_ofEvents_T_Void_obj_sMemberStorageInfo[] = {
{::hx::fsBool,(int)offsetof(_Event_ofEvents_T_Void_obj,canceled),HX_("canceled",59,18,26,1f)},
{::hx::fsObject /* ::Array< bool > */ ,(int)offsetof(_Event_ofEvents_T_Void_obj,_hx___repeat),HX_("__repeat",7b,02,ac,ae)},
{::hx::fsObject /* ::Array< int > */ ,(int)offsetof(_Event_ofEvents_T_Void_obj,_hx___priorities),HX_("__priorities",e2,cb,e6,1c)},
{::hx::fsObject /* ::Array< ::Dynamic> */ ,(int)offsetof(_Event_ofEvents_T_Void_obj,_hx___listeners),HX_("__listeners",5f,ae,ba,21)},
{ ::hx::fsUnknown, 0, null()}
};
static ::hx::StaticInfo *_Event_ofEvents_T_Void_obj_sStaticStorageInfo = 0;
#endif
static ::String _Event_ofEvents_T_Void_obj_sMemberFields[] = {
HX_("canceled",59,18,26,1f),
HX_("__repeat",7b,02,ac,ae),
HX_("__priorities",e2,cb,e6,1c),
HX_("add",21,f2,49,00),
HX_("cancel",7a,ed,33,b8),
HX_("has",5a,3f,4f,00),
HX_("remove",44,9c,88,04),
HX_("removeAll",3d,17,e5,ca),
HX_("__listeners",5f,ae,ba,21),
HX_("dispatch",ba,ce,63,1e),
::String(null()) };
::hx::Class _Event_ofEvents_T_Void_obj::__mClass;
void _Event_ofEvents_T_Void_obj::__register()
{
_Event_ofEvents_T_Void_obj _hx_dummy;
_Event_ofEvents_T_Void_obj::_hx_vtable = *(void **)&_hx_dummy;
::hx::Static(__mClass) = new ::hx::Class_obj();
__mClass->mName = HX_("lime.app._Event_ofEvents_T_Void",30,ef,76,e4);
__mClass->mSuper = &super::__SGetClass();
__mClass->mConstructEmpty = &__CreateEmpty;
__mClass->mConstructArgs = &__Create;
__mClass->mGetStaticField = &::hx::Class_obj::GetNoStaticField;
__mClass->mSetStaticField = &::hx::Class_obj::SetNoStaticField;
__mClass->mStatics = ::hx::Class_obj::dupFunctions(0 /* sStaticFields */);
__mClass->mMembers = ::hx::Class_obj::dupFunctions(_Event_ofEvents_T_Void_obj_sMemberFields);
__mClass->mCanCast = ::hx::TCanCast< _Event_ofEvents_T_Void_obj >;
#ifdef HXCPP_SCRIPTABLE
__mClass->mMemberStorageInfo = _Event_ofEvents_T_Void_obj_sMemberStorageInfo;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mStaticStorageInfo = _Event_ofEvents_T_Void_obj_sStaticStorageInfo;
#endif
::hx::_hx_RegisterClass(__mClass->mName, __mClass);
}
} // end namespace lime
} // end namespace app
|
[
"72734817+khiodev@users.noreply.github.com"
] |
72734817+khiodev@users.noreply.github.com
|
d54be161d2ce6d0b258a83022930b705f6ad5fb4
|
6b539667d77cfc7d481fa99bfe89bc8a47faddd7
|
/projet_finale0/dialog.h
|
53a9beda23a394b6a95267ab078faee12c0318e5
|
[] |
no_license
|
ImenBenMansour/Smart_Club_2A21
|
dd41872a68c1e6c39281fce1245dc8ba5f9b6038
|
d10a725c752da05bf5812f36a64e5f5edd695c7a
|
refs/heads/master
| 2023-04-21T14:23:37.933795
| 2021-05-05T02:58:08
| 2021-05-05T02:58:08
| 344,109,302
| 0
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 451
|
h
|
#ifndef DIALOG_H
#define DIALOG_H
#include <QDialog>
namespace Ui {
class Dialog;
}
class Dialog : public QDialog
{
Q_OBJECT
public:
explicit Dialog(QWidget *parent = nullptr);
explicit Dialog(QString,QString,QString,QWidget *parent = nullptr);
~Dialog();
void set_tmpemail(QString e){tmpemail=e;}
private slots:
void on_envoyer_dialog_clicked();
private:
Ui::Dialog *ui;
QString tmpemail;
};
#endif // DIALOG_H
|
[
"cynda.zagrouba@esprit.tn"
] |
cynda.zagrouba@esprit.tn
|
17e50f6e9cf6a373925cb8184f583929af7a85f7
|
cb98a0df3c73ff01d6e0e4cc3d721d07ebd82f6f
|
/AdmSimulator/ChromPair.h
|
03f322fd9718b87180962758f911400f2b787cf6
|
[] |
no_license
|
xyang619/gsim-old
|
77dff0335fbdb2fd4dc67e12c4812db729090698
|
1beb1a42ff7770470b29135c89452dd1a85c05cd
|
refs/heads/master
| 2020-06-01T14:27:48.253923
| 2015-01-21T07:09:18
| 2015-01-21T07:09:18
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 564
|
h
|
/*
* ChromPair.h
*
* Created on: Sep 26, 2014
* Author: xiong_yang
*/
#ifndef CHROMPAIR_H_
#define CHROMPAIR_H_
#include "Chrom.h"
class ChromPair {
private:
Chrom chrom1;
Chrom chrom2;
int getPoissonNumb(double lambda) const;
void breakPoints(double * breaks, int n) const;
public:
ChromPair();
ChromPair(const Chrom & chrom1, const Chrom & chrom2);
Chrom getChrom(int index) const;
//double waitTime();
//void sort(double[], int);
ChromPair & recombine();
virtual ~ChromPair();
};
#endif /* CHROMPAIR_H_ */
|
[
"young@research-imac32.icb.ac.cn"
] |
young@research-imac32.icb.ac.cn
|
880ff26682aa84620575e7a41eec846365f357a4
|
f8573941754a429f481c18b46ad5337d1bb55609
|
/PhysX 3.3.1/Source/PhysXExtensions/src/ExtTriangleMeshExt.cpp
|
192a76a910694d25daa23088059e055f1d2b9010
|
[] |
no_license
|
frbyles/ExcavatorSimulator
|
409fa4ad56ba3d786dedfffb5d981db86d89f4f5
|
c4be4ea60cd1c62c0d0207af31dfed4a47ef6124
|
refs/heads/master
| 2021-01-19T11:38:04.166440
| 2015-11-12T17:45:52
| 2015-11-12T17:45:52
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,948
|
cpp
|
// This code contains NVIDIA Confidential Information and is disclosed to you
// under a form of NVIDIA software license agreement provided separately to you.
//
// Notice
// NVIDIA Corporation and its licensors retain all intellectual property and
// proprietary rights in and to this software and related documentation and
// any modifications thereto. Any use, reproduction, disclosure, or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA Corporation is strictly prohibited.
//
// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES
// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO
// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT,
// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE.
//
// Information and code furnished is believed to be accurate and reliable.
// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such
// information or for any infringement of patents or other rights of third parties that may
// result from its use. No license is granted by implication or otherwise under any patent
// or patent rights of NVIDIA Corporation. Details are subject to change without notice.
// This code supersedes and replaces all information previously supplied.
// NVIDIA Corporation products are not authorized for use as critical
// components in life support devices or systems without express written approval of
// NVIDIA Corporation.
//
// Copyright (c) 2008-2013 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "PxTriangleMeshExt.h"
#include "PxMeshQuery.h"
#include "PxGeometryQuery.h"
#include "PxTriangleMeshGeometry.h"
#include "PxHeightFieldGeometry.h"
#include "PxTriangleMesh.h"
#include "PsAllocator.h"
using namespace physx;
PxMeshOverlapUtil::PxMeshOverlapUtil() : mResultsMemory(mResults), mNbResults(0), mMaxNbResults(64)
{
}
PxMeshOverlapUtil::~PxMeshOverlapUtil()
{
if(mResultsMemory != mResults)
PX_FREE(mResultsMemory);
}
PxU32 PxMeshOverlapUtil::findOverlap(const PxGeometry& geom, const PxTransform& geomPose, const PxTriangleMeshGeometry& meshGeom, const PxTransform& meshPose)
{
bool overflow;
PxU32 nbTouchedTris = PxMeshQuery::findOverlapTriangleMesh(geom, geomPose, meshGeom, meshPose, mResultsMemory, mMaxNbResults, 0, overflow);
if(overflow)
{
const PxU32 maxNbTris = meshGeom.triangleMesh->getNbTriangles();
if(!maxNbTris)
{
mNbResults = 0;
return 0;
}
if(mMaxNbResults<maxNbTris)
{
if(mResultsMemory != mResults)
PX_FREE(mResultsMemory);
mResultsMemory = (PxU32*)PX_ALLOC(sizeof(PxU32)*maxNbTris, PX_DEBUG_EXP("PxMeshOverlapUtil::findOverlap"));
mMaxNbResults = maxNbTris;
}
nbTouchedTris = PxMeshQuery::findOverlapTriangleMesh(geom, geomPose, meshGeom, meshPose, mResultsMemory, mMaxNbResults, 0, overflow);
PX_ASSERT(nbTouchedTris);
PX_ASSERT(!overflow);
}
mNbResults = nbTouchedTris;
return nbTouchedTris;
}
PxU32 PxMeshOverlapUtil::findOverlap(const PxGeometry& geom, const PxTransform& geomPose, const PxHeightFieldGeometry& hfGeom, const PxTransform& hfPose)
{
bool overflow = true;
PxU32 nbTouchedTris = 0;
do
{
nbTouchedTris = PxMeshQuery::findOverlapHeightField(geom, geomPose, hfGeom, hfPose, mResultsMemory, mMaxNbResults, 0, overflow);
if(overflow)
{
const PxU32 maxNbTris = mMaxNbResults * 2;
if(mResultsMemory != mResults)
PX_FREE(mResultsMemory);
mResultsMemory = (PxU32*)PX_ALLOC(sizeof(PxU32)*maxNbTris, PX_DEBUG_EXP("PxMeshOverlapUtil::findOverlap"));
mMaxNbResults = maxNbTris;
}
}while(overflow);
mNbResults = nbTouchedTris;
return nbTouchedTris;
}
PxVec3 physx::PxComputeMeshPenetration(PxU32 maxIter, const PxGeometry& geom, const PxTransform& geomPose, const PxTriangleMeshGeometry& meshGeom, const PxTransform& meshPose, PxU32& nb)
{
PxU32 nbIter = 0;
bool isValid = true;
PxTransform pose = geomPose;
while(isValid && nbIter<maxIter)
{
PxVec3 mtd;
PxF32 depth;
isValid = PxGeometryQuery::computePenetration(mtd, depth, geom, pose, meshGeom, meshPose);
if(isValid)
{
nbIter++;
PX_ASSERT(depth>=0.0f);
pose.p += mtd * depth;
}
}
nb = nbIter;
return pose.p - geomPose.p;
}
PxVec3 physx::PxComputeHeightFieldPenetration(PxU32 maxIter, const PxGeometry& geom, const PxTransform& geomPose, const PxHeightFieldGeometry& meshGeom, const PxTransform& meshPose, PxU32& nb)
{
PxU32 nbIter = 0;
bool isValid = true;
PxTransform pose = geomPose;
while(isValid && nbIter<maxIter)
{
PxVec3 mtd;
PxF32 depth;
isValid = PxGeometryQuery::computePenetration(mtd, depth, geom, pose, meshGeom, meshPose);
if(isValid)
{
nbIter++;
PX_ASSERT(depth>=0.0f);
pose.p += mtd * depth;
}
}
nb = nbIter;
return pose.p - geomPose.p;
}
|
[
"seifes1@gmail.com"
] |
seifes1@gmail.com
|
88a736d83cffc81013a27fc9239700fb4c96ca09
|
9c7a0296af07bf6c475f665fcccb855ccf7a526e
|
/core/modules/replica/tools/qserv-replica-job-sql.cc
|
42407046bf17424e35b1bd093e2ddacdde4fc8f1
|
[] |
no_license
|
provingground-moe/qserv
|
6ecbf227442d335d26dc2238c5e4142a6ae2ea25
|
97016932a752c0e641571538912d309cd3dd461b
|
refs/heads/master
| 2020-06-10T20:45:10.955752
| 2019-05-22T19:59:19
| 2019-05-22T19:59:19
| 136,348,562
| 0
| 0
| null | 2018-06-06T15:27:00
| 2018-06-06T15:26:59
| null |
UTF-8
|
C++
| false
| false
| 1,286
|
cc
|
/*
* LSST Data Management System
*
* This product includes software developed by the
* LSST Project (http://www.lsst.org/).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the LSST License Statement and
* the GNU General Public License along with this program. If not,
* see <http://www.lsstcorp.org/LegalNotices/>.
*/
/**
* @see SqlApp
*/
// System headers
#include <iostream>
#include <stdexcept>
// Qserv headers
#include "replica/SqlApp.h"
using namespace std;
using namespace lsst::qserv::replica;
int main(int argc, char* argv[]) {
try {
auto const app = SqlApp::create(argc, argv);
return app->run();
} catch (exception const& ex) {
cerr << "main() the application failed, exception: " << ex.what() << endl;
return 1;
}
}
|
[
"gapon@slac.stanford.edu"
] |
gapon@slac.stanford.edu
|
17cd5cf4b64b7a61e7b84d85d3324ab72deeab62
|
ebf1bb0e33c3a3748ae8e2e4ad5ad0faf2abde21
|
/appG/Account.cpp
|
611c91662845c4439fbcead4f22fe81db59cbf07
|
[] |
no_license
|
salehi/deitel-and-deitel-c-persian
|
d6cdb963f9e6f64f37ca0d346f198dda0e1153c5
|
a25c2e530ea9fefffd6740247c70e9ec465cc188
|
refs/heads/master
| 2022-11-23T14:29:08.811553
| 2020-07-27T09:15:30
| 2020-07-27T09:15:30
| 282,849,119
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,596
|
cpp
|
// Account.cpp
// Member-function definitions for class Account.
#include "Account.h" // Account class definition
// Account constructor initializes attributes
Account::Account( int theAccountNumber, int thePIN,
double theAvailableBalance, double theTotalBalance )
: accountNumber( theAccountNumber ),
pin( thePIN ),
availableBalance( theAvailableBalance ),
totalBalance( theTotalBalance )
{
// empty body
} // end Account constructor
// determines whether a user-specified PIN matches PIN in Account
bool Account::validatePIN( int userPIN ) const
{
if ( userPIN == pin )
return true;
else
return false;
} // end function validatePIN
// returns available balance
double Account::getAvailableBalance() const
{
return availableBalance;
} // end function getAvailableBalance
// returns the total balance
double Account::getTotalBalance() const
{
return totalBalance;
} // end function getTotalBalance
// credits an amount to the account
void Account::credit( double amount )
{
totalBalance += amount; // add to total balance
} // end function credit
// debits an amount from the account
void Account::debit( double amount )
{
availableBalance -= amount; // subtract from available balance
totalBalance -= amount; // subtract from total balance
} // end function debit
// returns account number
int Account::getAccountNumber() const
{
return accountNumber;
} // end function getAccountNumber
/**************************************************************************
* (C) Copyright 1992-2005 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/
|
[
"salehi1994@gmail.com"
] |
salehi1994@gmail.com
|
67afbd76a187403033ca29da7d806754b0565825
|
8e75199f881321560ca5c939088b3b8d280ddf2c
|
/d05/ex04/main.cpp
|
3e778c9e56f989e45fa857d0758c55c0071350f3
|
[] |
no_license
|
ademenet/piscine_cpp
|
c8c3f8411cd20d60d93e9f94db835a39e76c4934
|
1411dd71ea18a264e850f9483607352efcfbc325
|
refs/heads/master
| 2021-06-14T05:31:23.212904
| 2017-04-14T18:20:31
| 2017-04-14T18:20:31
| 85,195,242
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,643
|
cpp
|
/**
* @Author: ademenet
* @Date: 2017-04-10T11:48:57+02:00
* @Last modified by: ademenet
* @Last modified time: 2017-04-11T23:12:27+02:00
*/
#include "Bureaucrat.hpp"
#include "Form.hpp"
#include "PresidentialPardonForm.hpp"
#include "RobotomyRequestForm.hpp"
#include "ShrubberyCreationForm.hpp"
#include "Intern.hpp"
#include "OfficeBlock.hpp"
int main()
{
std::cout << "-------------------------------------" << std::endl;
{
Intern idiotOne;
Bureaucrat hermes = Bureaucrat("Hermes Conrad", 37);
Bureaucrat bob = Bureaucrat("Bobby Bobson", 123);
OfficeBlock ob;
ob.setIntern(&idiotOne);
ob.setSigner(&bob);
ob.setExecutor(&hermes);
try {
ob.doBureaucracy("Shrubbery's form", "Pigley");
}
catch (OfficeBlock::SpecificException & e) {
std::cout << e.what() << std::endl;
}
catch (std::exception & e) {
std::cout << e.what() << std::endl;
}
}
std::cout << "-------------------------------------" << std::endl;
{
Intern idiotOne;
Bureaucrat hermes = Bureaucrat("Hermes Conrad", 70);
Bureaucrat bob = Bureaucrat("Bobby Bobson", 68);
OfficeBlock ob;
ob.setIntern(&idiotOne);
ob.setSigner(&bob);
ob.setExecutor(&hermes);
try {
ob.doBureaucracy("Robot's form", "Pigley");
}
catch (OfficeBlock::SpecificException & e) {
std::cout << e.what() << std::endl;
}
catch (std::exception & e) {
std::cout << e.what() << std::endl;
}
}
std::cout << "-------------------------------------" << std::endl;
{
Intern idiotOne;
Bureaucrat hermes = Bureaucrat("Hermes Conrad", 149);
Bureaucrat bob = Bureaucrat("Bobby Bobson", 123);
OfficeBlock ob;
ob.setIntern(&idiotOne);
ob.setSigner(&bob);
ob.setExecutor(&hermes);
try {
ob.doBureaucracy("President's form", "Pigley");
}
catch (OfficeBlock::SpecificException & e) {
std::cout << e.what() << std::endl;
}
catch (std::exception & e) {
std::cout << e.what() << std::endl;
}
}
std::cout << "-------------------------------------" << std::endl;
{
Intern idiotOne;
Bureaucrat hermes = Bureaucrat("Hermes Conrad", 37);
Bureaucrat bob = Bureaucrat("Bobby Bobson", 123);
OfficeBlock ob;
ob.setIntern(&idiotOne);
ob.setSigner(&bob);
ob.setExecutor(&hermes);
try {
ob.doBureaucracy("mutant pig termination", "Pigley");
}
catch (OfficeBlock::SpecificException & e) {
std::cout << e.what() << std::endl;
}
catch (std::exception & e) {
std::cout << e.what() << std::endl;
}
}
std::cout << "-------------------------------------" << std::endl;
{
Intern idiotOne;
Bureaucrat bob = Bureaucrat("Bobby Bobson", 123);
OfficeBlock ob;
ob.setIntern(&idiotOne);
ob.setSigner(&bob);
// ob.setExecutor(NULL);
try {
ob.doBureaucracy("mutant pig termination", "Pigley");
}
catch (OfficeBlock::SpecificException & e) {
std::cout << e.what() << std::endl;
}
catch (std::exception & e) {
std::cout << e.what() << std::endl;
}
}
std::cout << "-------------------------------------" << std::endl;
{
Intern idiotOne;
Bureaucrat bob = Bureaucrat("Bobby Bobson", 123);
Bureaucrat hermes = Bureaucrat("Hermes Conrad", 37);
OfficeBlock ob;
// ob.setIntern(&idiotOne);
ob.setSigner(&bob);
ob.setExecutor(&hermes);
try {
ob.doBureaucracy("mutant pig termination", "Pigley");
}
catch (OfficeBlock::SpecificException & e) {
std::cout << e.what() << std::endl;
}
catch (std::exception & e) {
std::cout << e.what() << std::endl;
}
}
std::cout << "-------------------------------------" << std::endl;
{
Intern idiotOne;
Bureaucrat bob = Bureaucrat("Bobby Bobson", 123);
Bureaucrat hermes = Bureaucrat("Hermes Conrad", 37);
OfficeBlock ob;
ob.setIntern(&idiotOne);
// ob.setSigner(&bob);
ob.setExecutor(&hermes);
try {
ob.doBureaucracy("mutant pig termination", "Pigley");
}
catch (OfficeBlock::SpecificException & e) {
std::cout << e.what() << std::endl;
}
catch (std::exception & e) {
std::cout << e.what() << std::endl;
}
}
std::cout << "-------------------------------------" << std::endl;
}
|
[
"ademenet@student.42.fr"
] |
ademenet@student.42.fr
|
75118753db1175b914f913f6080c062c7df77abe
|
2ad4eb27da52d55e9c924431d088f5688931699b
|
/include/hash.hpp
|
b6a3b9b3ecc9cb2c22d7408bc455fc161375eee1
|
[
"MIT",
"LicenseRef-scancode-public-domain"
] |
permissive
|
fhnmor21/montreal
|
e0fb84334a7f957de207742f763f9d1432406a1b
|
ae74138774a1533a08971143d7b912b8a2d7064b
|
refs/heads/master
| 2023-03-09T07:13:54.077394
| 2021-02-24T03:57:10
| 2021-02-24T03:57:10
| 55,389,428
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,844
|
hpp
|
/**
The MIT License (MIT)
Copyright (c) 2016 Flavio Moreira
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.
*/
#ifndef HASH_HPP
#define HASH_HPP
#include "basic_types.hpp"
#include "hashes/City.h"
#include "hashes/MurmurHash2.h"
#include "hashes/Spooky.h"
namespace Montreal
{
struct Hashes
{
union {
struct
{
u64 murmur;
u64 city;
u64 spooky;
};
u64 h[3];
};
};
template < typename KeyType >
Hashes hash(const KeyType& key, u64 seed = 0x9747b28c)
{
const usize len(sizeof(KeyType));
Hashes rVal = {{{0, 0, 0}}};
union {
KeyType key_;
u8 buf_[len];
} buffer;
buffer.key_ = key;
rVal.city = CityHash64WithSeed(buffer.buf_, len, seed);
rVal.murmur = MurmurHash64A(buffer.buf_, len, seed);
rVal.spooky = SpookyHash::Hash64(buffer.buf_, len, seed);
}
} // end namespace Montreal
#endif // HASH_HPP
|
[
"fhnmor21@gmail.com"
] |
fhnmor21@gmail.com
|
845e6a255171a48c97a20b24df9fdb7128feff0c
|
f128c9c7bdb4b33f027f8db36321e9065ab9f9bb
|
/ryeoryeon/etc/sorting/10M sorting_ans/10M sorting_ans/main.cpp
|
61b4f8babcaee48d44d7e38c2d2d51c2ca089c3a
|
[] |
no_license
|
Ryeoryeon/Algorithm_study
|
21beb05981342df9122573cdb7e60b111ecc92bb
|
e706e855856373f359891407f1c41e8a2a59b9ce
|
refs/heads/master
| 2023-07-26T08:33:11.503340
| 2021-09-09T16:26:16
| 2021-09-09T16:26:16
| 237,822,675
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 7,342
|
cpp
|
//
// main.cpp
// 10M sorting_ans
//
// Created by 이영현 on 2020/04/13.
// Copyright © 2020 이영현. All rights reserved.
//
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
vector<int> list;
vector<int> sorting_list;
void merge_sort(int first, int last);
//사실 해 놓고 보니 합병 정렬이 아니..네..?
int main(int argc, const char * argv[]) {
ios_base::sync_with_stdio(false);
cin.tie(0);
int num;
cin>>num;
//크기가 num 사이즈인 배열에 저장되는 비정렬 숫자들
list.assign(num, 0);
for(int i=0; i<num; i++)
{
cin>>list[i];
}
int size = list.size();
int last_index = size - 1;
//시작!
//index가 처음에는 1로 시작. 두배씩 증가. ---> 안됨. 무조건 두배씩 증가가 아님. 총 길이 / 2로.
//단, 남은 길이가 인덱스의 두배보다 작을 때 (홀수일 때)는 나머지 한꺼번에 합침
//그런데 이제 index가 전체 길이의 반이 됐을 때 그만두자!
int index = 2; // 해당 단계가 목표로 하는 단위 배열 안의 원소의 개수. (1단계는 2개 -> 2단계는 4개 ..)
int step = 0; // 단계. 딱 반반씩 떨어지지 않고 마지막에 애매하게 서로 찢어졌을 때를 위해 넣음.
sorting_list = list;
int pair_index = num;
while(pair_index!=1)
{
int pair_num = (pair_index+1)/2; //ex. 원소의 개수가 9개면 첫 쌍은 5개, 10개여도 5개.
int left_to_right;
//마지막 단계에서는 꼭 left_to_right 재정의가 필요.
if(pair_num<=2)
left_to_right = pow(2,step); // left와 right 사이의 배열 간격
else
left_to_right = index/2; // left와 right 사이의 배열 간격
for(int pair=0; pair<pair_num; pair++)
{
int index_left = pair * index;
int index_right = index_left + left_to_right;
//잉여가 남을 때
if(index_right >= size)
break;
for(int ind=pair*index; (ind - (pair*index))<index; ind++)
{
//ind - (pair*index)는 현재까지 안에 들어간 배열의 개수
if(index_left == (pair*index + left_to_right))
{
//좌측에 있는 아이들이 이미 다 정렬되었을 때
//우측에 있는 아이들을 모두 sorting_list에 밀어넣어야함.
for(int j=index_right; j!=(pair*index + index); j++)
{
sorting_list[ind] = list[j];
++ind;
}
break;
}
else
{
//우측에 있는 아이들이 이미 다 정렬되었을 때 (단, pair*index + index가 사이즈를 뛰어넘을 때를 위해)
if(pair == pair_num - 1 && index_right == size)
{
//우측에 있는 아이들이 이미 다 정렬되었을 때
//좌측에 있는 아이들을 모두 sorting_list에 밀어넣어야함.
for(int j=index_left; j!=(pair*index + left_to_right); j++)
{
sorting_list[ind] = list[j];
++ind;
}
break;
}
else if(pair != pair_num - 1 && index_right == (pair*index + index))
{
//우측에 있는 아이들이 이미 다 정렬되었을 때
//좌측에 있는 아이들을 모두 sorting_list에 밀어넣어야함.
for(int j=index_left; j!=(pair*index + left_to_right); j++)
{
sorting_list[ind] = list[j];
++ind;
}
break;
}
if(list[index_left] < list[index_right])
{
sorting_list[ind] = list[index_left];
++index_left;
}
else
{
sorting_list[ind] = list[index_right];
++index_right;
}
}
}
}
if(2*index <= size)
index*=2;
else
index = size;
++step;
pair_index = pair_num;
list = sorting_list;
}
//merge_sort(0, last_index);
for(int i=0; i<size; i++)
{
cout<<list[i]<<'\n';
}
return 0;
}
//
void merge_sort(int first, int last)
{
//길이가 1이 되면 first==last가 됨
if(first<last)
{
int k = (first+last)/2;
//가장 안쪽의 재귀부터 풀림. 재귀가 하나 풀리면 이미 list에서 어느정도 정렬이 되는 상태.
merge_sort(first, k);
merge_sort(k+1, last);
//list[first ~ k]와 list[k+1 ~ last]를 비교 후 합병
int index_left = first;
int index_right = k+1;
int index_m1 = first;
sorting_list = list; // sorting_list는 list가 정렬될 때 기준이 될, 맨 처음 상태의 list의 왼/오 벡터가 될 친구.
while(1)
{
if(index_left > k) // 좌측에 있는 아이가 이미 정렬 끝난 경우
{
for(int i=index_right; i<last; i++)
{
sorting_list[index_m1] = list[i];
++index_m1;
}
break;
}
else if(index_right == last + 1) // 우측에 있는 아이가 이미 정렬 끝난 경우
{
for(int i=index_left; i<=k; i++)
{
sorting_list[index_m1] = list[i];
++index_m1;
}
break;
}
else
{
if(list[index_left] <= list[index_right])
{
sorting_list[index_m1] = list[index_left];
++index_left;
++index_m1;
}
else
{
sorting_list[index_m1] = list[index_right];
++index_right;
++index_m1;
}
}
}
list = sorting_list;
}
}
|
[
"ryeoryeon@gmail.com"
] |
ryeoryeon@gmail.com
|
45a535f1a9b170a575251f628f983ebc41b95966
|
9b164f28d53010772b82bb680f6e0e10f1154916
|
/AutMesh/AutLib/Cad/PlaneCurve/GModel/Mesh2d_gPlnCurve.hxx
|
7f530b746470f1031d794043e2f9ccb88792b9b3
|
[] |
no_license
|
amir5200fx/AutMarine-v4.4.1
|
d006cc273d5be520f930a15c0878b6121f26942d
|
7a9384cad8978dbe44d9a2354559384b8efb93db
|
refs/heads/master
| 2020-11-27T05:10:06.605362
| 2019-12-20T18:31:31
| 2019-12-20T18:31:31
| 229,316,964
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 258
|
hxx
|
#pragma once
#ifndef _Mesh2d_gPlnCurve_Header
#define _Mesh2d_gPlnCurve_Header
#include <Mesh_PlnCurve.hxx>
#include <GModel_parCurve.hxx>
namespace AutLib
{
typedef Mesh_PlnCurve<GModel_parCurve> Mesh2d_gPlnCurve;
}
#endif // !_Mesh2d_gPlnCurve_Header
|
[
"aasoleimani86@gmail.com"
] |
aasoleimani86@gmail.com
|
8995a2d5135372dd9369dcaeb27c0ce2c2acdd7c
|
fd5a1912b6b88c0c1b9eaaa0850751e29f205d8e
|
/irledmatrix/irledmatrix.ino
|
a05cee01104804d29109c290e1e972914dacd010
|
[
"Apache-2.0"
] |
permissive
|
ajiniesta/my-arduino-projects
|
ed71c56c32f37b538e49ec8d0b983e8a05a49ab8
|
fd6d0bd6ea9158302beed0b7e224c506b3cb7846
|
refs/heads/master
| 2021-01-19T14:46:42.811258
| 2017-04-13T17:39:44
| 2017-04-13T17:39:44
| 88,189,789
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,717
|
ino
|
/*
* led matrix ir controlled
* ir in pin 8
* led in 12-10
*/
#include "IRremote.h"
#include "LedControl.h"
int receiver = 8; // Signal Pin of IR receiver to Arduino Digital Pin 8
/*-----( Declare objects )-----*/
IRrecv irrecv(receiver); // create instance of 'irrecv'
decode_results results; // create instance of 'decode_results'
LedControl lc=LedControl(12,10,11,1);
unsigned long delaytime1=500;
unsigned long delaytime2=50;
boolean add = true;
int addIR(int previous){
int next = previous;
switch(results.value)
{
case 0xFF629D:
next++;
add = true;
Serial.println("more leds");
break;
case 0xFFA857:
next--;
add = false;
Serial.println("less leds");
break;
case 0xFFFFFFFF:
Serial.println(" REPEAT");
if(add)
next++;
else
next--;
break;
default:
Serial.println(" other button ");
}// End Case
delay(500); // Do not get immediate repeat
if(next>64){
next = 64;
}
if(next<0){
next = 0;
}
return next;
}
void draw(int val){
int index = 0;
lc.clearDisplay(0);
for(int row=0;row<8;row++) {
for(int col=0;col<8;col++) {
if(++index<val){
lc.setLed(0,row,col,true);
}
}
}
}
void setup() {
Serial.begin(9600);
Serial.println("IR Receiver Button Decode");
irrecv.enableIRIn(); // Start the receiver
lc.shutdown(0,false);
/* Set the brightness to a medium values */
lc.setIntensity(0,8);
/* and clear the display */
lc.clearDisplay(0);
}
int current = 32;
void loop() {
draw(current);
if (irrecv.decode(&results)){
current = addIR(current);
irrecv.resume();
draw(current);
}
delay(50);
}
|
[
"antonioj.iniesta@gmail.com"
] |
antonioj.iniesta@gmail.com
|
b87dba469973a4378da268cfe15e144c30bb19b1
|
a075225a2e1fe2d5e60e7802c5f0d0d884816904
|
/v0.1.2/Solvers/ShortCutSolver_CPLEX/ShortCutSolver_CPLEX.h
|
9b9889769ab0b0ac5ce3c4e207caeba8b177aa13
|
[
"BSD-3-Clause"
] |
permissive
|
hqng/optimal-transport
|
592d225c114b4c478ede2f9f3010a5e5aa160bdf
|
c868db74f6b7dd675c5892d70e38fb0bd623dded
|
refs/heads/master
| 2020-04-16T22:56:41.962056
| 2019-11-23T08:52:11
| 2019-11-23T08:52:11
| 165,991,297
| 0
| 0
|
NOASSERTION
| 2019-11-23T08:52:12
| 2019-01-16T07:02:59
|
C++
|
UTF-8
|
C++
| false
| false
| 635
|
h
|
#ifndef ShortCutSolver_CPLEX_H_
#define ShortCutSolver_CPLEX_H_
#include<stdlib.h>
#include<PythonTypes.h>
#include"TCouplingHandler.h"
#include"TVarListHandler.h"
#include"TCPLEXNetSolver.h"
#include"Interfaces-CPLEX.h"
#include"ShortCutSolver-Tools.h"
using namespace std;
const int CH_SemiDense=0;
const int CH_Sparse=1;
const int SETUP_ERROR_CHUNKNOWN=-51;
// external functions
extern "C" {
int Setup_Solver_CPLEX(TDoubleMatrix *muX, TDoubleMatrix *muY,
TDoubleMatrix *alpha, TDoubleMatrix *beta,
int initializeBases,
long int couplingHandlerAddr,
int couplingHandlerType,
TInteger64Matrix *Pointer);
}
#endif
|
[
"jokin@jokinX220.(none)"
] |
jokin@jokinX220.(none)
|
52acd41cc9ae1686b75c8b0a66724b29aa7b6a4b
|
dc402d0a2c1c0fc5ae015b2249a36e7ce886f1d0
|
/deps/memkind/test/alloc_performance_tests.cpp
|
f8db5d0f983633497c0898ed7bf2855456d9311b
|
[
"BSD-3-Clause",
"GPL-3.0-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"GPL-2.0-only",
"LicenseRef-scancode-autoconf-simple-exception",
"NTP",
"MIT",
"BSD-2-Clause",
"FSFULLR"
] |
permissive
|
michalbiesek/redis
|
6ec74c1cf0c8e041dc4db6cd79f46f33a091f337
|
d0d0867e730998f3589b7933e968840a8e1e8db4
|
refs/heads/4.0-volatile
| 2023-07-23T02:03:14.386206
| 2018-10-24T07:58:36
| 2018-10-24T07:58:36
| 136,281,355
| 0
| 1
|
BSD-3-Clause
| 2021-03-30T19:02:31
| 2018-06-06T06:17:28
|
C
|
UTF-8
|
C++
| false
| false
| 54,898
|
cpp
|
/*
* Copyright (C) 2016 - 2017 Intel 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:
* 1. Redistributions of source code must retain the above copyright notice(s),
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice(s),
* 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 HOLDER(S) ``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(S) 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 "common.h"
#include "allocator_perf_tool/TaskFactory.hpp"
#include "allocator_perf_tool/Stats.hpp"
#include "allocator_perf_tool/Thread.hpp"
#include "allocator_perf_tool/GTestAdapter.hpp"
class AllocPerformanceTest: public :: testing::Test
{
private:
AllocatorFactory allocator_factory;
protected:
void SetUp()
{
allocator_factory.initialize_allocator(AllocatorTypes::STANDARD_ALLOCATOR);
}
void TearDown()
{}
float run(unsigned kind, unsigned call, size_t threads_number, size_t alloc_size, unsigned mem_operations_num)
{
TaskFactory task_factory;
std::vector<Thread*> threads;
std::vector<Task*> tasks;
TypesConf func_calls;
TypesConf allocator_types;
func_calls.enable_type(FunctionCalls::FREE);
func_calls.enable_type(call);
allocator_types.enable_type(kind);
TaskConf conf = {
mem_operations_num, //number of memory operations
{
mem_operations_num, //number of memory operations
alloc_size, //min. size of single allocation
alloc_size //max. size of single allocatioion
},
func_calls, //enable function calls
allocator_types, //enable allocators
11, //random seed
false, //does not log memory operations and statistics to csv file
};
for (int i=0; i<threads_number; i++)
{
Task* task = task_factory.create(TaskFactory::FUNCTION_CALLS_PERFORMANCE_TASK, conf);
tasks.push_back(task);
threads.push_back(new Thread(task));
conf.seed += 1;
}
ThreadsManager threads_manager(threads);
threads_manager.start();
threads_manager.barrier();
TimeStats time_stats;
for (int i=0; i<tasks.size(); i++)
{
time_stats += tasks[i]->get_results();
}
return time_stats.stats[kind][call].total_time;
}
void run_test(unsigned kind, unsigned call, size_t threads_number, size_t alloc_size, unsigned mem_operations_num)
{
allocator_factory.initialize_allocator(kind);
float ref_time = run(AllocatorTypes::STANDARD_ALLOCATOR, call, threads_number, alloc_size, mem_operations_num);
float perf_time = run(kind, call, threads_number, alloc_size, mem_operations_num);
float ref_delta_time_percent = allocator_factory.calc_ref_delta(ref_time, perf_time);
GTestAdapter::RecordProperty("total_time_spend_on_alloc", perf_time);
GTestAdapter::RecordProperty("alloc_operations_per_thread", mem_operations_num);
GTestAdapter::RecordProperty("ref_delta_time_percent", ref_delta_time_percent);
}
};
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_malloc_1_thread_100_bytes)
{
run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::MALLOC, 1, 100, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_malloc_1_thread_4096_bytes)
{
run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::MALLOC, 1, 4096, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_malloc_1_thread_1000_bytes)
{
run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::MALLOC, 1, 1000, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_malloc_1_thread_1001_bytes)
{
run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::MALLOC, 1, 1001, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_malloc_1_thread_1572864_bytes)
{
run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::MALLOC, 1, 1572864, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_malloc_10_thread_100_bytes)
{
run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::MALLOC, 10, 100, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_malloc_10_thread_4096_bytes)
{
run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::MALLOC, 10, 4096, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_malloc_10_thread_1000_bytes)
{
run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::MALLOC, 10, 1000, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_malloc_10_thread_1001_bytes)
{
run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::MALLOC, 10, 1001, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_malloc_10_thread_1572864_bytes)
{
run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::MALLOC, 10, 1572864, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_malloc_72_thread_100_bytes)
{
run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::MALLOC, 72, 100, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_malloc_72_thread_4096_bytes)
{
run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::MALLOC, 72, 4096, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_malloc_72_thread_1000_bytes)
{
run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::MALLOC, 72, 1000, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_malloc_72_thread_1001_bytes)
{
run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::MALLOC, 72, 1001, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_malloc_72_thread_1572864_bytes)
{
run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::MALLOC, 72, 1572864, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_calloc_1_thread_100_bytes)
{
run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::CALLOC, 1, 100, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_calloc_1_thread_4096_bytes)
{
run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::CALLOC, 1, 4096, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_calloc_1_thread_1000_bytes)
{
run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::CALLOC, 1, 1000, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_calloc_1_thread_1001_bytes)
{
run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::CALLOC, 1, 1001, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_calloc_1_thread_1572864_bytes)
{
run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::CALLOC, 1, 1572864, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_calloc_10_thread_100_bytes)
{
run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::CALLOC, 10, 100, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_calloc_10_thread_4096_bytes)
{
run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::CALLOC, 10, 4096, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_calloc_10_thread_1000_bytes)
{
run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::CALLOC, 10, 1000, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_calloc_10_thread_1001_bytes)
{
run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::CALLOC, 10, 1001, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_calloc_10_thread_1572864_bytes)
{
run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::CALLOC, 10, 1572864, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_calloc_72_thread_100_bytes)
{
run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::CALLOC, 72, 100, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_calloc_72_thread_4096_bytes)
{
run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::CALLOC, 72, 4096, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_calloc_72_thread_1000_bytes)
{
run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::CALLOC, 72, 1000, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_calloc_72_thread_1001_bytes)
{
run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::CALLOC, 72, 1001, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_calloc_72_thread_1572864_bytes)
{
run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::CALLOC, 72, 1572864, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_realloc_1_thread_100_bytes)
{
run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::REALLOC, 1, 100, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_realloc_1_thread_4096_bytes)
{
run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::REALLOC, 1, 4096, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_realloc_1_thread_1000_bytes)
{
run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::REALLOC, 1, 1000, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_realloc_1_thread_1001_bytes)
{
run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::REALLOC, 1, 1001, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_realloc_1_thread_1572864_bytes)
{
run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::REALLOC, 1, 1572864, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_realloc_10_thread_100_bytes)
{
run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::REALLOC, 10, 100, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_realloc_10_thread_4096_bytes)
{
run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::REALLOC, 10, 4096, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_realloc_10_thread_1000_bytes)
{
run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::REALLOC, 10, 1000, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_realloc_10_thread_1001_bytes)
{
run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::REALLOC, 10, 1001, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_realloc_10_thread_1572864_bytes)
{
run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::REALLOC, 10, 1572864, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_realloc_72_thread_100_bytes)
{
run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::REALLOC, 72, 100, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_realloc_72_thread_4096_bytes)
{
run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::REALLOC, 72, 4096, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_realloc_72_thread_1000_bytes)
{
run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::REALLOC, 72, 1000, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_realloc_72_thread_1001_bytes)
{
run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::REALLOC, 72, 1001, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_DEFAULT_realloc_72_thread_1572864_bytes)
{
run_test(AllocatorTypes::MEMKIND_DEFAULT, FunctionCalls::REALLOC, 72, 1572864, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_malloc_1_thread_100_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::MALLOC, 1, 100, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_malloc_1_thread_4096_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::MALLOC, 1, 4096, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_malloc_1_thread_1000_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::MALLOC, 1, 1000, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_malloc_1_thread_1001_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::MALLOC, 1, 1001, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_malloc_1_thread_1572864_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::MALLOC, 1, 1572864, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_malloc_10_thread_100_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::MALLOC, 10, 100, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_malloc_10_thread_4096_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::MALLOC, 10, 4096, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_malloc_10_thread_1000_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::MALLOC, 10, 1000, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_malloc_10_thread_1001_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::MALLOC, 10, 1001, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_malloc_10_thread_1572864_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::MALLOC, 10, 1572864, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_malloc_72_thread_100_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::MALLOC, 72, 100, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_malloc_72_thread_4096_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::MALLOC, 72, 4096, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_malloc_72_thread_1000_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::MALLOC, 72, 1000, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_malloc_72_thread_1001_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::MALLOC, 72, 1001, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_malloc_72_thread_1572864_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::MALLOC, 72, 1572864, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_calloc_1_thread_100_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::CALLOC, 1, 100, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_calloc_1_thread_4096_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::CALLOC, 1, 4096, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_calloc_1_thread_1000_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::CALLOC, 1, 1000, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_calloc_1_thread_1001_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::CALLOC, 1, 1001, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_calloc_1_thread_1572864_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::CALLOC, 1, 1572864, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_calloc_10_thread_100_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::CALLOC, 10, 100, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_calloc_10_thread_4096_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::CALLOC, 10, 4096, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_calloc_10_thread_1000_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::CALLOC, 10, 1000, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_calloc_10_thread_1001_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::CALLOC, 10, 1001, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_calloc_10_thread_1572864_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::CALLOC, 10, 1572864, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_calloc_72_thread_100_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::CALLOC, 72, 100, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_calloc_72_thread_4096_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::CALLOC, 72, 4096, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_calloc_72_thread_1000_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::CALLOC, 72, 1000, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_calloc_72_thread_1001_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::CALLOC, 72, 1001, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_ext_MEMKIND_HBW_calloc_72_thread_1572864_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::CALLOC, 72, 1572864, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_realloc_1_thread_100_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::REALLOC, 1, 100, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_realloc_1_thread_4096_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::REALLOC, 1, 4096, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_realloc_1_thread_1000_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::REALLOC, 1, 1000, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_realloc_1_thread_1001_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::REALLOC, 1, 1001, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_realloc_1_thread_1572864_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::REALLOC, 1, 1572864, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_realloc_10_thread_100_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::REALLOC, 10, 100, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_realloc_10_thread_4096_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::REALLOC, 10, 4096, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_realloc_10_thread_1000_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::REALLOC, 10, 1000, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_realloc_10_thread_1001_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::REALLOC, 10, 1001, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_realloc_10_thread_1572864_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::REALLOC, 10, 1572864, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_realloc_72_thread_100_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::REALLOC, 72, 100, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_realloc_72_thread_4096_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::REALLOC, 72, 4096, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_realloc_72_thread_1000_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::REALLOC, 72, 1000, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_realloc_72_thread_1001_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::REALLOC, 72, 1001, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_realloc_72_thread_1572864_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW, FunctionCalls::REALLOC, 72, 1572864, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_malloc_1_thread_100_bytes)
{
run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::MALLOC, 1, 100, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_malloc_1_thread_4096_bytes)
{
run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::MALLOC, 1, 4096, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_malloc_1_thread_1000_bytes)
{
run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::MALLOC, 1, 1000, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_malloc_1_thread_1001_bytes)
{
run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::MALLOC, 1, 1001, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_malloc_1_thread_1572864_bytes)
{
run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::MALLOC, 1, 1572864, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_malloc_10_thread_100_bytes)
{
run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::MALLOC, 10, 100, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_malloc_10_thread_4096_bytes)
{
run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::MALLOC, 10, 4096, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_malloc_10_thread_1000_bytes)
{
run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::MALLOC, 10, 1000, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_malloc_10_thread_1001_bytes)
{
run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::MALLOC, 10, 1001, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_malloc_10_thread_1572864_bytes)
{
run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::MALLOC, 10, 1572864, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_malloc_72_thread_100_bytes)
{
run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::MALLOC, 72, 100, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_malloc_72_thread_4096_bytes)
{
run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::MALLOC, 72, 4096, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_malloc_72_thread_1000_bytes)
{
run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::MALLOC, 72, 1000, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_malloc_72_thread_1001_bytes)
{
run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::MALLOC, 72, 1001, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_malloc_72_thread_1572864_bytes)
{
run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::MALLOC, 72, 1572864, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_calloc_1_thread_100_bytes)
{
run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::CALLOC, 1, 100, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_calloc_1_thread_4096_bytes)
{
run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::CALLOC, 1, 4096, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_calloc_1_thread_1000_bytes)
{
run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::CALLOC, 1, 1000, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_calloc_1_thread_1001_bytes)
{
run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::CALLOC, 1, 1001, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_calloc_1_thread_1572864_bytes)
{
run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::CALLOC, 1, 1572864, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_calloc_10_thread_100_bytes)
{
run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::CALLOC, 10, 100, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_calloc_10_thread_4096_bytes)
{
run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::CALLOC, 10, 4096, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_calloc_10_thread_1000_bytes)
{
run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::CALLOC, 10, 1000, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_calloc_10_thread_1001_bytes)
{
run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::CALLOC, 10, 1001, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_calloc_10_thread_1572864_bytes)
{
run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::CALLOC, 10, 1572864, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_calloc_72_thread_100_bytes)
{
run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::CALLOC, 72, 100, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_calloc_72_thread_4096_bytes)
{
run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::CALLOC, 72, 4096, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_calloc_72_thread_1000_bytes)
{
run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::CALLOC, 72, 1000, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_calloc_72_thread_1001_bytes)
{
run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::CALLOC, 72, 1001, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_calloc_72_thread_1572864_bytes)
{
run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::CALLOC, 72, 1572864, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_realloc_1_thread_100_bytes)
{
run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::REALLOC, 1, 100, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_realloc_1_thread_4096_bytes)
{
run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::REALLOC, 1, 4096, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_realloc_1_thread_1000_bytes)
{
run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::REALLOC, 1, 1000, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_realloc_1_thread_1001_bytes)
{
run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::REALLOC, 1, 1001, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_realloc_1_thread_1572864_bytes)
{
run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::REALLOC, 1, 1572864, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_realloc_10_thread_100_bytes)
{
run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::REALLOC, 10, 100, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_realloc_10_thread_4096_bytes)
{
run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::REALLOC, 10, 4096, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_realloc_10_thread_1000_bytes)
{
run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::REALLOC, 10, 1000, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_realloc_10_thread_1001_bytes)
{
run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::REALLOC, 10, 1001, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_realloc_10_thread_1572864_bytes)
{
run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::REALLOC, 10, 1572864, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_realloc_72_thread_100_bytes)
{
run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::REALLOC, 72, 100, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_realloc_72_thread_4096_bytes)
{
run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::REALLOC, 72, 4096, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_realloc_72_thread_1000_bytes)
{
run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::REALLOC, 72, 1000, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_realloc_72_thread_1001_bytes)
{
run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::REALLOC, 72, 1001, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_INTERLEAVE_realloc_72_thread_1572864_bytes)
{
run_test(AllocatorTypes::MEMKIND_INTERLEAVE, FunctionCalls::REALLOC, 72, 1572864, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_malloc_1_thread_100_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::MALLOC, 1, 100, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_malloc_1_thread_4096_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::MALLOC, 1, 4096, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_malloc_1_thread_1000_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::MALLOC, 1, 1000, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_malloc_1_thread_1001_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::MALLOC, 1, 1001, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_malloc_1_thread_1572864_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::MALLOC, 1, 1572864, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_malloc_10_thread_100_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::MALLOC, 10, 100, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_malloc_10_thread_4096_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::MALLOC, 10, 4096, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_malloc_10_thread_1000_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::MALLOC, 10, 1000, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_malloc_10_thread_1001_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::MALLOC, 10, 1001, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_malloc_10_thread_1572864_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::MALLOC, 10, 1572864, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_malloc_72_thread_100_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::MALLOC, 72, 100, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_malloc_72_thread_4096_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::MALLOC, 72, 4096, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_malloc_72_thread_1000_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::MALLOC, 72, 1000, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_malloc_72_thread_1001_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::MALLOC, 72, 1001, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_malloc_72_thread_1572864_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::MALLOC, 72, 1572864, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_calloc_1_thread_100_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::CALLOC, 1, 100, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_calloc_1_thread_4096_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::CALLOC, 1, 4096, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_calloc_1_thread_1000_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::CALLOC, 1, 1000, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_calloc_1_thread_1001_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::CALLOC, 1, 1001, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_calloc_1_thread_1572864_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::CALLOC, 1, 1572864, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_calloc_10_thread_100_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::CALLOC, 10, 100, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_calloc_10_thread_4096_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::CALLOC, 10, 4096, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_calloc_10_thread_1000_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::CALLOC, 10, 1000, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_calloc_10_thread_1001_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::CALLOC, 10, 1001, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_calloc_10_thread_1572864_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::CALLOC, 10, 1572864, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_calloc_72_thread_100_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::CALLOC, 72, 100, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_calloc_72_thread_4096_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::CALLOC, 72, 4096, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_calloc_72_thread_1000_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::CALLOC, 72, 1000, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_calloc_72_thread_1001_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::CALLOC, 72, 1001, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_calloc_72_thread_1572864_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::CALLOC, 72, 1572864, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_realloc_1_thread_100_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::REALLOC, 1, 100, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_realloc_1_thread_4096_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::REALLOC, 1, 4096, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_realloc_1_thread_1000_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::REALLOC, 1, 1000, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_realloc_1_thread_1001_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::REALLOC, 1, 1001, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_realloc_1_thread_1572864_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::REALLOC, 1, 1572864, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_realloc_10_thread_100_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::REALLOC, 10, 100, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_realloc_10_thread_4096_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::REALLOC, 10, 4096, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_realloc_10_thread_1000_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::REALLOC, 10, 1000, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_realloc_10_thread_1001_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::REALLOC, 10, 1001, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_realloc_10_thread_1572864_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::REALLOC, 10, 1572864, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_realloc_72_thread_100_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::REALLOC, 72, 100, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_realloc_72_thread_4096_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::REALLOC, 72, 4096, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_realloc_72_thread_1000_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::REALLOC, 72, 1000, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_realloc_72_thread_1001_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::REALLOC, 72, 1001, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_INTERLEAVE_realloc_72_thread_1572864_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_INTERLEAVE, FunctionCalls::REALLOC, 72, 1572864, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_malloc_1_thread_100_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::MALLOC, 1, 100, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_malloc_1_thread_4096_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::MALLOC, 1, 4096, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_malloc_1_thread_1000_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::MALLOC, 1, 1000, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_malloc_1_thread_1001_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::MALLOC, 1, 1001, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_malloc_1_thread_1572864_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::MALLOC, 1, 1572864, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_malloc_10_thread_100_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::MALLOC, 10, 100, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_malloc_10_thread_4096_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::MALLOC, 10, 4096, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_malloc_10_thread_1000_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::MALLOC, 10, 1000, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_malloc_10_thread_1001_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::MALLOC, 10, 1001, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_malloc_10_thread_1572864_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::MALLOC, 10, 1572864, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_malloc_72_thread_100_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::MALLOC, 72, 100, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_malloc_72_thread_4096_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::MALLOC, 72, 4096, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_malloc_72_thread_1000_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::MALLOC, 72, 1000, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_malloc_72_thread_1001_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::MALLOC, 72, 1001, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_malloc_72_thread_1572864_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::MALLOC, 72, 1572864, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_calloc_1_thread_100_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::CALLOC, 1, 100, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_calloc_1_thread_4096_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::CALLOC, 1, 4096, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_calloc_1_thread_1000_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::CALLOC, 1, 1000, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_calloc_1_thread_1001_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::CALLOC, 1, 1001, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_calloc_1_thread_1572864_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::CALLOC, 1, 1572864, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_calloc_10_thread_100_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::CALLOC, 10, 100, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_calloc_10_thread_4096_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::CALLOC, 10, 4096, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_calloc_10_thread_1000_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::CALLOC, 10, 1000, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_calloc_10_thread_1001_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::CALLOC, 10, 1001, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_calloc_10_thread_1572864_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::CALLOC, 10, 1572864, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_calloc_72_thread_100_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::CALLOC, 72, 100, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_calloc_72_thread_4096_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::CALLOC, 72, 4096, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_calloc_72_thread_1000_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::CALLOC, 72, 1000, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_calloc_72_thread_1001_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::CALLOC, 72, 1001, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_calloc_72_thread_1572864_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::CALLOC, 72, 1572864, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_realloc_1_thread_100_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::REALLOC, 1, 100, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_realloc_1_thread_4096_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::REALLOC, 1, 4096, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_realloc_1_thread_1000_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::REALLOC, 1, 1000, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_realloc_1_thread_1001_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::REALLOC, 1, 1001, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_realloc_1_thread_1572864_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::REALLOC, 1, 1572864, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_realloc_10_thread_100_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::REALLOC, 10, 100, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_realloc_10_thread_4096_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::REALLOC, 10, 4096, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_realloc_10_thread_1000_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::REALLOC, 10, 1000, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_realloc_10_thread_1001_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::REALLOC, 10, 1001, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_realloc_10_thread_1572864_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::REALLOC, 10, 1572864, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_realloc_72_thread_100_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::REALLOC, 72, 100, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_realloc_72_thread_4096_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::REALLOC, 72, 4096, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_realloc_72_thread_1000_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::REALLOC, 72, 1000, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_realloc_72_thread_1001_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::REALLOC, 72, 1001, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_MEMKIND_HBW_PREFERRED_realloc_72_thread_1572864_bytes)
{
run_test(AllocatorTypes::MEMKIND_HBW_PREFERRED, FunctionCalls::REALLOC, 72, 1572864, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_malloc_1_thread_100_bytes)
{
run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::MALLOC, 1, 100, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_malloc_1_thread_4096_bytes)
{
run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::MALLOC, 1, 4096, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_malloc_1_thread_1000_bytes)
{
run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::MALLOC, 1, 1000, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_malloc_1_thread_1001_bytes)
{
run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::MALLOC, 1, 1001, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_malloc_1_thread_1572864_bytes)
{
run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::MALLOC, 1, 1572864, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_malloc_10_thread_100_bytes)
{
run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::MALLOC, 10, 100, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_malloc_10_thread_4096_bytes)
{
run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::MALLOC, 10, 4096, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_malloc_10_thread_1000_bytes)
{
run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::MALLOC, 10, 1000, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_malloc_10_thread_1001_bytes)
{
run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::MALLOC, 10, 1001, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_malloc_10_thread_1572864_bytes)
{
run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::MALLOC, 10, 1572864, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_malloc_72_thread_100_bytes)
{
run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::MALLOC, 72, 100, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_malloc_72_thread_4096_bytes)
{
run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::MALLOC, 72, 4096, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_malloc_72_thread_1000_bytes)
{
run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::MALLOC, 72, 1000, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_malloc_72_thread_1001_bytes)
{
run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::MALLOC, 72, 1001, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_malloc_72_thread_1572864_bytes)
{
run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::MALLOC, 72, 1572864, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_calloc_1_thread_100_bytes)
{
run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::CALLOC, 1, 100, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_calloc_1_thread_4096_bytes)
{
run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::CALLOC, 1, 4096, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_calloc_1_thread_1000_bytes)
{
run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::CALLOC, 1, 1000, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_calloc_1_thread_1001_bytes)
{
run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::CALLOC, 1, 1001, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_calloc_1_thread_1572864_bytes)
{
run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::CALLOC, 1, 1572864, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_calloc_10_thread_100_bytes)
{
run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::CALLOC, 10, 100, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_calloc_10_thread_4096_bytes)
{
run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::CALLOC, 10, 4096, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_calloc_10_thread_1000_bytes)
{
run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::CALLOC, 10, 1000, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_calloc_10_thread_1001_bytes)
{
run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::CALLOC, 10, 1001, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_calloc_10_thread_1572864_bytes)
{
run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::CALLOC, 10, 1572864, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_calloc_72_thread_100_bytes)
{
run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::CALLOC, 72, 100, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_calloc_72_thread_4096_bytes)
{
run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::CALLOC, 72, 4096, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_calloc_72_thread_1000_bytes)
{
run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::CALLOC, 72, 1000, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_calloc_72_thread_1001_bytes)
{
run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::CALLOC, 72, 1001, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_calloc_72_thread_1572864_bytes)
{
run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::CALLOC, 72, 1572864, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_realloc_1_thread_100_bytes)
{
run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::REALLOC, 1, 100, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_realloc_1_thread_4096_bytes)
{
run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::REALLOC, 1, 4096, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_realloc_1_thread_1000_bytes)
{
run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::REALLOC, 1, 1000, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_realloc_1_thread_1001_bytes)
{
run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::REALLOC, 1, 1001, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_realloc_1_thread_1572864_bytes)
{
run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::REALLOC, 1, 1572864, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_realloc_10_thread_100_bytes)
{
run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::REALLOC, 10, 100, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_realloc_10_thread_4096_bytes)
{
run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::REALLOC, 10, 4096, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_realloc_10_thread_1000_bytes)
{
run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::REALLOC, 10, 1000, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_realloc_10_thread_1001_bytes)
{
run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::REALLOC, 10, 1001, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_realloc_10_thread_1572864_bytes)
{
run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::REALLOC, 10, 1572864, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_realloc_72_thread_100_bytes)
{
run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::REALLOC, 72, 100, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_realloc_72_thread_4096_bytes)
{
run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::REALLOC, 72, 4096, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_realloc_72_thread_1000_bytes)
{
run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::REALLOC, 72, 1000, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_realloc_72_thread_1001_bytes)
{
run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::REALLOC, 72, 1001, 10000);
}
TEST_F(AllocPerformanceTest, test_TC_MEMKIND_HBWMALLOC_ALLOCATOR_realloc_72_thread_1572864_bytes)
{
run_test(AllocatorTypes::HBWMALLOC_ALLOCATOR, FunctionCalls::REALLOC, 72, 1572864, 10000);
}
|
[
"krzysztof.filipek@intel.com"
] |
krzysztof.filipek@intel.com
|
33efbccf873f19c9e5e2666ed02ef2180f8815e0
|
2f0e59d491c1e5b179ac2dedc56ccf85826447e1
|
/AABB.h
|
b99825370d50db8dea57ae9b599f3a5aea7d9b8f
|
[] |
no_license
|
Sircrab/RayTracer
|
3ad288681d81f7000871e18fe9e8c476d388b630
|
74f70fecde5cce50854e80a7b95e47294f03d10c
|
refs/heads/master
| 2021-01-16T19:06:43.780304
| 2017-12-04T00:06:03
| 2017-12-04T00:06:03
| 100,137,424
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,116
|
h
|
//
// Created by Geno on 21-Sep-17.
//
#ifndef RAYTRACER_AABB_H
#define RAYTRACER_AABB_H
#include "Vec3.h"
#include "Ray.h"
#include "Triangle.h"
#include <limits>
#include <vector>
//Axis Aligned Bounding Box
class AABB{
public:
Vec3 minVec, maxVec;
std::vector<Vec3> boxVertices;
AABB(Vec3 minVec, Vec3 maxVec) : minVec(minVec), maxVec(maxVec) {
boxVertices.push_back(Vec3(minVec.x,minVec.y,minVec.z));
boxVertices.push_back(Vec3(minVec.x,minVec.y,maxVec.z));
boxVertices.push_back(Vec3(minVec.x,maxVec.y,minVec.z));
boxVertices.push_back(Vec3(minVec.x,maxVec.y,maxVec.z));
boxVertices.push_back(Vec3(maxVec.x,minVec.y,minVec.z));
boxVertices.push_back(Vec3(maxVec.x,minVec.y,maxVec.z));
boxVertices.push_back(Vec3(maxVec.x,maxVec.y,minVec.z));
boxVertices.push_back(Vec3(maxVec.x,maxVec.y,maxVec.z));
};
bool intersect_ray(const Ray& ray) const;
bool intersect_triangle(const std::vector<Vec3>& triVertices) const;
private:
void project(const std::vector<Vec3>& points,const Vec3& projectionAxis, double& outMin, double& outMax) const;
};
#endif //RAYTRACER_AABB_H
|
[
"rovalfer@gmail.com"
] |
rovalfer@gmail.com
|
ab17343e19b2ae38596c97fdc6b0119ee4304c1c
|
1ae40287c5705f341886bbb5cc9e9e9cfba073f7
|
/Osmium/SDK/FN_MoviePlayer_classes.hpp
|
79684f729197e0aa1a3b476594d1702818a44aba
|
[] |
no_license
|
NeoniteDev/Osmium
|
183094adee1e8fdb0d6cbf86be8f98c3e18ce7c0
|
aec854e60beca3c6804f18f21b6a0a0549e8fbf6
|
refs/heads/master
| 2023-07-05T16:40:30.662392
| 2023-06-28T23:17:42
| 2023-06-28T23:17:42
| 340,056,499
| 14
| 8
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,282
|
hpp
|
#pragma once
// Fortnite (4.5-CL-4159770) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
namespace SDK
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// Class MoviePlayer.MoviePlayerSettings
// 0x0018 (0x0040 - 0x0028)
class UMoviePlayerSettings : public UObject
{
public:
bool bWaitForMoviesToComplete; // 0x0028(0x0001) (Edit, ZeroConstructor, Config, GlobalConfig, IsPlainOldData)
bool bMoviesAreSkippable; // 0x0029(0x0001) (Edit, ZeroConstructor, Config, GlobalConfig, IsPlainOldData)
unsigned char UnknownData00[0x6]; // 0x002A(0x0006) MISSED OFFSET
TArray<struct FString> StartupMovies; // 0x0030(0x0010) (Edit, ZeroConstructor, Config, GlobalConfig)
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("Class MoviePlayer.MoviePlayerSettings");
return ptr;
}
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
|
[
"kareemolim@gmail.com"
] |
kareemolim@gmail.com
|
a726d3b815e1ac7b87df4aa45b07c90ba8e77d23
|
5456502f97627278cbd6e16d002d50f1de3da7bb
|
/remoting/codec/audio_decoder.cc
|
cde940ebd7e011ecc4d1ca387d31628451b742ab
|
[
"BSD-3-Clause"
] |
permissive
|
TrellixVulnTeam/Chromium_7C66
|
72d108a413909eb3bd36c73a6c2f98de1573b6e5
|
c8649ab2a0f5a747369ed50351209a42f59672ee
|
refs/heads/master
| 2023-03-16T12:51:40.231959
| 2017-12-20T10:38:26
| 2017-12-20T10:38:26
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 722
|
cc
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "remoting/codec/audio_decoder.h"
#include "base/logging.h"
#include "base/memory/ptr_util.h"
#include "remoting/codec/audio_decoder_opus.h"
#include "remoting/protocol/session_config.h"
namespace remoting {
std::unique_ptr<AudioDecoder> AudioDecoder::CreateAudioDecoder(
const protocol::SessionConfig& config) {
if (config.audio_config().codec == protocol::ChannelConfig::CODEC_OPUS) {
return base::WrapUnique(new AudioDecoderOpus());
}
NOTIMPLEMENTED();
return nullptr;
}
} // namespace remoting
|
[
"lixiaodonglove7@aliyun.com"
] |
lixiaodonglove7@aliyun.com
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.