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 986
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 23
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 145
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 122
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
5ac23c2fef68f7b95ca7c8a92f08efc11f13f95b | 60689b9ba2a4eb03885140700b160dcdec491211 | /chapter02/EX2.41(P67).cpp | 800685c44a97dcc21cab99f2a5697f9baa23c49f | [] | no_license | nideng/Cpp_Primer_5th_edition | af1e99f935ceb1245acb468d5fe3c519cff6b464 | 8a5067358dc4969dd408e623e78265996a096824 | refs/heads/master | 2021-01-14T15:00:14.943025 | 2020-04-01T01:36:28 | 2020-04-01T01:36:28 | 242,653,119 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 3,277 | cpp | #ifndef SALES_DATA_H
#define SALES_DATA_H
#include<string>
#include<iostream>
using namespace std;
class Sales_data
{
public:
Sales_data() :bookNo(""), bookName(""), units_sold(0), cost(0), price(0) {};
Sales_data(const string&, const string&, unsigned, double, double);
Sales_data(istream&);
Sales_data(const Sales_data&);
~Sales_data();
Sales_data& operator+=(const Sales_data&);
friend Sales_data operator+(const Sales_data&, const Sales_data&);
friend ostream& operator<<(ostream&, const Sales_data&);
friend istream& operator>>(istream&, Sales_data&);
inline const string& isbn() const { return bookNo; }
inline double revenue() const { return units_sold * (price - cost); }
private:
string bookNo;//book number
string bookName;
unsigned units_sold;
double cost;//book cost
double price;
};
Sales_data::Sales_data(const string& s1, const string& s2, unsigned sell, double co, double pr)
:bookNo(s1), bookName(s2), units_sold(sell), cost(co), price(pr) {}
istream& operator>>(istream& is, Sales_data& s)
{
is >> s.bookNo >> s.bookName >> s.units_sold >> s.cost >> s.price;
return is;
}
ostream& operator<<(ostream& os, const Sales_data& s)
{
os << s.bookNo << '\t' << s.bookName << endl;
os << s.units_sold << '\t' << s.price << '\t' << s.revenue() << endl;
return os;
}
Sales_data::Sales_data(istream& cin)
{
cin >> *this;
}
Sales_data& Sales_data::operator+=(const Sales_data& s1)
{
price = (s1.price * s1.units_sold + price * units_sold) / (units_sold + s1.units_sold);
cost = (s1.cost * s1.units_sold + cost * units_sold) / (units_sold + s1.units_sold);
units_sold += s1.units_sold;
return *this;
}
Sales_data operator+(const Sales_data& s1, const Sales_data& s2)
{
Sales_data s3(s1);
s3 += s2;
return s3;
}
Sales_data::Sales_data(const Sales_data& s)
{
bookNo = s.bookNo;
bookName = s.bookName;
units_sold = s.units_sold;
cost = s.cost;
price = s.price;
}
Sales_data::~Sales_data()
{
}
#endif
/*
#include<iostream>
#include"EX2.40(P65).h"
int main()
{
Sales_data book;
std::cin >> book;
std::cout << book << std::endl;
return 0;
}
*/
/*
#include<iostream>
#include"EX2.40(P65).h"
int main()
{
Sales_data item1, item2;
std::cin >> item1 >> item2;
if (item1.isbn() == item2.isbn())
{
std::cout << item1 + item2 << std::endl;
return 0;
}
else
{
std::cerr << "Data must refer to same ISBN"
<< std::endl;
return -1;
}
}
*/
/*
#include<iostream>
#include"EX2.40(P65).h"
using std::cout;
using std::cin;
using std::endl;
int main()
{
int Cnt = 1;
Sales_data item1;
if (cin >> item1)
{
Sales_data item2;
while (cin >> item2)
{
if (item1.isbn() == item2.isbn())
++Cnt;
else
{
cout << item1 << " occurs " << Cnt << " times" << endl;
//这种统计方式要求同一ISBN的记录必须聚在一起输入,待改进
item1 = item2;
Cnt = 1;
}
}
cout << item1 << " occurs " << Cnt << " times" << endl;
}
return 0;
}
*/
int main()
{
Sales_data item1, item2;
if (std::cin >> item1)
{
while (std::cin >> item2)
{
if (item1.isbn() == item2.isbn())
item1 += item2;
else
{
std::cout << item1 << std::endl;
item1 = item2;
}
}
std::cout << item1 << std::endl;
}
else
{
std::cerr << "No data?!" << std::endl;
return -1;
}
return 0;
}
| [
"nideng@live.cn"
] | nideng@live.cn |
9007e90880526620c7a12b44e434d4a92cd1fbb6 | a1e78a1d0372c36bdbe3c4b10f5cbb786d8b1e23 | /Button.cpp | a0959b2b2ccb64b58288dccac7ab3d188902a3b4 | [] | no_license | kakigori12345/My-Creating-Games | 229feef1ed41f514835877ef937de4367abb8e6c | 0308398ce44d727a8d49c180157cf5ce71fef757 | refs/heads/master | 2021-04-10T04:12:54.342202 | 2020-04-04T15:16:20 | 2020-04-04T15:16:20 | 248,909,606 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 3,215 | cpp | #include "Button.h"
#include "GameLib/GameLib.h"
#include "GameLib/Input/Manager.h"
#include "GameLib/Input/Keyboard.h"
#include "SoundGenerator.h"
using namespace GameLib::Input;
Button* Button::mInstance = 0;
Button::Button():demoPlay(false) {}
Button::~Button() {}
void Button::create() {
ASSERT(!mInstance);
mInstance = new Button();
}
void Button::destroy() {
ASSERT(mInstance);
SAFE_DELETE(mInstance);
}
Button* Button::instance() {
return mInstance;
}
bool Button::isOn(Button::Key key) const {
bool r = false;
Keyboard k = Manager::instance().keyboard();
char c = 0;
Keyboard::Key in;
bool flag = false;//入力2種類の判別
switch (key) {
case KEY_W: c = 'w'; break;
case KEY_A: c = 'a'; break;
case KEY_S: c = 's'; break;
case KEY_D: c = 'd'; break;
case KEY_O: c = 'o'; break;
case KEY_P: c = 'p'; break;
case KEY_R: c = 'r'; break;
case KEY_SPACE: c = ' '; break;
case KEY_LEFT: in = Keyboard::Key::KEY_LEFT; flag = true; break;
case KEY_RIGHT: in = Keyboard::Key::KEY_RIGHT; flag = true; break;
case KEY_SHIFT: in = Keyboard::Key::KEY_SHIFT; flag = true; break;
default: ASSERT(false); break;
}
if (flag)
r = k.isOn(in);
else
r = k.isOn(c);
return r;
}
bool Button::isTriggered(Button::Key key) const {
//Seを管理するための変数
SoundGenerator::Se se = SoundGenerator::Se::SE_INVALID;
//判定用変数
bool r = false;
Keyboard k = Manager::instance().keyboard();
char c = 0;
Keyboard::Key in;
bool flag = false;//入力2種類の判別
switch (key) {
case KEY_W: c = 'w'; se = SoundGenerator::Se::SELECT_CURSOR_MOVE; break;
case KEY_A: c = 'a'; se = SoundGenerator::Se::SELECT_CURSOR_MOVE; break;
case KEY_S: c = 's'; se = SoundGenerator::Se::SELECT_CURSOR_MOVE; break;
case KEY_D: c = 'd'; se = SoundGenerator::Se::SELECT_CURSOR_MOVE; break;
case KEY_O: c = 'o'; se = SoundGenerator::Se::SELECT_FINISH; break;
case KEY_P: c = 'p'; se = SoundGenerator::Se::SELECT_FINISH; break;
case KEY_R: c = 'r'; se = SoundGenerator::Se::SELECT_FINISH; break;
case KEY_SPACE: c = ' '; se = SoundGenerator::Se::SELECT_FINISH; break;
case KEY_LEFT: in = Keyboard::Key::KEY_LEFT; flag = true; break;
case KEY_RIGHT: in = Keyboard::Key::KEY_RIGHT; flag = true; break;
case KEY_SHIFT: in = Keyboard::Key::KEY_SHIFT; se = SoundGenerator::Se::SELECT_FINISH; flag = true; break;
default: ASSERT(false); break;
}
if (flag)
r = k.isTriggered(in);
else
r = k.isTriggered(c);
if (c == ' ' && demoPlay)
r = true;
//Seを鳴らすかどうか
if (r) {
switch (se) {
case SoundGenerator::Se::SELECT_CURSOR_MOVE:
SoundGenerator::instance()->playSe(SoundGenerator::Se::SELECT_CURSOR_MOVE);
break;
case SoundGenerator::Se::SELECT_FINISH:
SoundGenerator::instance()->playSe(SoundGenerator::Se::SELECT_FINISH);
break;
case SoundGenerator::Se::SE_INVALID:
break;
default:
HALT("File:Button.cpp [isTriggered()] switch's Se Error");
}
}
return r;
}
void Button::thisGameIsDemo()
{
demoPlay = true;
}
void Button::resetDemo()
{
demoPlay = false;
}
bool Button::demo() const
{
return demoPlay;
} | [
"noreply@github.com"
] | kakigori12345.noreply@github.com |
6114c8301ed3aef775a9891e1e479c1594ba7da5 | b90f153ab09eb6b29388409de7893cf110007219 | /common/shader.cpp | 32106ed48ba2cdea7011cd28a4a7aca2f275cc0a | [] | no_license | jwoogerd/magical-particles | e4aaeebddbdc6b0fb3c396a097e9e4fdb4fdd55c | 865d9d09ca083320cdd396cde6be8803b1b25d03 | refs/heads/master | 2020-05-31T07:30:36.090247 | 2014-08-06T23:35:33 | 2014-08-06T23:35:33 | 19,400,875 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,914 | cpp | #include "shader.h"
#include <iostream>
#include <fstream>
#include <vector>
Shader::Shader(void) {}
Shader::~Shader(void) {}
// read a file and return as a string
string Shader::readFile(const char* path) {
string content;
ifstream fileStream(path, ios::in);
if (!fileStream.is_open()) {
cerr << "File could not be opened" << endl;
return "";
}
string line = "";
while (!fileStream.eof()) {
getline(fileStream, line);
content.append(line + "\n");
}
fileStream.close();
return content;
}
GLuint Shader::loadShader(const char* vertPath, const char* fragPath) {
//generate shader names
GLuint vertShader = glCreateShader(GL_VERTEX_SHADER);
GLuint fragShader = glCreateShader(GL_FRAGMENT_SHADER);
//get shader src
string vertShaderStr = readFile(vertPath);
string fragShaderStr = readFile(fragPath);
const char* vertShaderSrc = vertShaderStr.c_str();
const char* fragShaderSrc = fragShaderStr.c_str();
GLint result = GL_FALSE;
//compile vertex shader
glShaderSource(vertShader, 1, &vertShaderSrc, NULL);
glCompileShader(vertShader);
char error[1024];
glGetShaderInfoLog(vertShader, 1024, NULL, error);
cout << "Compiler errors: \n" << error << endl;
//compile fragment shader
glShaderSource(fragShader, 1, &fragShaderSrc, NULL);
glCompileShader(fragShader);
glGetShaderInfoLog(fragShader, 1024, NULL, error);
cout << "Compiler errors: \n" << error << endl;
//link the program
GLuint program = glCreateProgram();
glAttachShader(program, vertShader);
glAttachShader(program, fragShader);
glLinkProgram(program);
glGetProgramiv(program, GL_LINK_STATUS, &result);
glGetProgramInfoLog(program, 1024, NULL, error);
cout << error << endl;
glDeleteShader(vertShader);
glDeleteShader(fragShader);
return program;
} | [
"jayme.woogerd@tufts.edu"
] | jayme.woogerd@tufts.edu |
07881a6c9a1914d68076e2853bc42a08c92df7bf | 77013b8303a10d0c937c9ca2bbba20dd35d53bbf | /Math/gcd.cpp | 56e1d89b6c46383172e3b118572e2c5eee4ba683 | [
"MIT"
] | permissive | aneesh001/InterviewBit | 9d10febfcace743b2335acdfcca0f2265c647d8d | fcbac096fd8e9554a52db10dc9e5a88cb8a83ef3 | refs/heads/master | 2020-03-18T06:05:36.438449 | 2018-07-01T06:02:57 | 2018-07-01T06:02:57 | 134,376,158 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 143 | cpp | #include <bits/stdc++.h>
using namespace std;
int gcd(int A, int B) {
if(B == 0) return A;
else return gcd(B, A % B);
}
int main(void) {
} | [
"aneeshd00812@gmail.com"
] | aneeshd00812@gmail.com |
3ded8ff09b3759baa49bf473fd4b7e29a90d34fa | 6b342e06bf8ec9bf89af44eb96bb716240947981 | /380.cpp | c53144a44ce74d887c6113a731d8ee40b6192c3e | [] | no_license | githubcai/leetcode | d822198f07db33ffbb1bc98813e5cd332be56562 | 4b63186b522cb80a0bc4939a89f5b6294c1b11ca | refs/heads/master | 2021-01-13T03:32:38.704206 | 2017-03-14T02:06:35 | 2017-03-14T02:06:35 | 77,529,061 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,174 | cpp | class RandomizedSet {
unordered_map<int, int> ref;
vector<int> nums;
public:
/** Initialize your data structure here. */
RandomizedSet() {
}
/** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
bool insert(int val) {
if(ref.find(val) != ref.end()) return false;
ref[val] = nums.size();
nums.push_back(val);
return true;
}
/** Removes a value from the set. Returns true if the set contained the specified element. */
bool remove(int val) {
auto iter = ref.find(val);
if(iter == ref.end()) return false;
nums[iter->second] = nums.back();
ref[nums.back()] = iter->second;
nums.pop_back();
ref.erase(iter);
return true;
}
/** Get a random element from the set. */
int getRandom() {
return nums[rand() % nums.size()];
}
};
/**
* Your RandomizedSet object will be instantiated and called as such:
* RandomizedSet obj = new RandomizedSet();
* bool param_1 = obj.insert(val);
* bool param_2 = obj.remove(val);
* int param_3 = obj.getRandom();
*/
| [
"2468085704@qq.com"
] | 2468085704@qq.com |
87c5ff622e086e6fec034d0de46ce9ddf9350eb1 | 1a5a3b9f8675000cf94b1a6797a909e1a0fcc40e | /src/client/src/Util/CRandom.h | 5eacfea5522927ef249058cadb0c2498ea5e6d6e | [] | no_license | Davidixx/client | f57e0d82b4aeec75394b453aa4300e3dd022d5d7 | 4c0c1c0106c081ba9e0306c14607765372d6779c | refs/heads/main | 2023-07-29T19:10:20.011837 | 2021-08-11T20:40:39 | 2021-08-11T20:40:39 | 403,916,993 | 0 | 0 | null | 2021-09-07T09:21:40 | 2021-09-07T09:21:39 | null | UTF-8 | C++ | false | false | 840 | h | #ifndef __CRANDOM_H
#define __CRANDOM_H
#include "LIB_Util.h"
//-------------------------------------------------------------------------------------------------
#define MAX_RANDOM_FUNC 4
#define CRandom CR001
#define AcRANDOM R_AC
#define BcRANDOM R_BC
#define VcRANDOM R_VC
#define MyRANDOM R_MY
class CR001 {
private:
DWORD m_dwVcCallCnt;
DWORD m_dwBcCallCnt;
DWORD m_dwAcCallCnt;
DWORD m_dwMyCallCnt;
BYTE m_btType;
int m_iVcSeed;
int m_iBcSeed;
int m_iAcSeed;
int m_iMySeed;
// DECLARE_INSTANCE( CR001 )
public :
void Init(DWORD dwSeed);
void SetType(BYTE btRandTYPE);
int Get();
int R_AC();
int R_BC();
int R_VC();
int R_MY();
};
//-------------------------------------------------------------------------------------------------
#endif
| [
"ralphminderhoud@gmail.com"
] | ralphminderhoud@gmail.com |
b48866513c4f541a250b2a2a844d90722c0274ba | a787a0b9859be15e838e29215cb77543b995c826 | /C++ projects/Maze Solver/kruskalishmaze.cpp | 7b41f774787379e765dcf95e3c87c977e038775f | [] | no_license | AdamMoffitt/portfolio | 675e46f0b308ad06a095a4b0cdb28d4694fe7782 | 198d88c13eff4f7579863cc5a0e2d02f756f2647 | refs/heads/master | 2023-01-13T12:09:01.052253 | 2020-04-29T15:31:44 | 2020-04-29T15:31:44 | 56,955,304 | 2 | 1 | null | 2023-01-09T12:17:06 | 2016-04-24T05:13:08 | HTML | UTF-8 | C++ | false | false | 2,850 | cpp | #include "kruskalishmaze.h"
#include "ufds.h"
#include <cstdlib>
#include <time.h>
KruskalishMaze::KruskalishMaze(int numRows, int numCols, int startX, int startY, int goalX, int goalY, bool simple)
: Maze(numRows, numCols, startX, startY, goalX, goalY), _maze(numRows)
{
for (int i=0; i < numRows; i++)
{
_maze[i].resize( numCols );
}
createMaze(simple);
}
bool KruskalishMaze::canTravel(Direction d, int row, int col) const
{
return ! _maze[row][col].walls[d];
}
void KruskalishMaze::destroyWall(Direction d, int row, int col)
{
_maze[row][col].walls[d] = false;
}
Direction randdir()
{
switch( rand() % 4 )
{
case 0: return UP;
case 1: return DOWN;
case 2: return LEFT;
default: return RIGHT;
}
}
/*
* Creates a Maze where any two squares have a unique path between them
in a Kruskalish fashion.
*/
void KruskalishMaze::createMaze(bool simpleMaze)
{
long seed = time(NULL);
srand(seed);
int rows = numRows();
int cols = numCols();
UnionFind uf(rows * cols);
int numComponents = rows * cols;
int row, col, otherrow, othercol, component1, component2;
Direction dir, otherdir;
while( numComponents > 1 )
{
row = otherrow = rand() % numRows();
col = othercol = rand() % numCols();
dir = randdir();
switch(dir)
{
case UP: otherrow--; otherdir = DOWN; break;
case DOWN: otherrow++; otherdir = UP; break;
case LEFT: othercol--; otherdir = RIGHT; break;
case RIGHT: othercol++; otherdir = LEFT; break;
}
component1 = row * numRows() + col;
component2 = otherrow * numRows() + othercol;
if( otherrow >= 0 && otherrow < numRows()
&& othercol >= 0 && othercol < numCols()
&& ! uf.same(component1, component2) )
{
destroyWall(dir, row, col);
destroyWall(otherdir, otherrow, othercol);
uf.merge(component1, component2);
numComponents--;
}
}
// The maze now has a unique solution. That's a simple maze.
// If we don't want a simple maze, let's destroy some interior walls.
if( ! simpleMaze )
{
const int WALLS_TO_DESTROY = numRows() * numCols() / 10;
for( int i=0; i < WALLS_TO_DESTROY; i++)
{
row = otherrow = rand() % numRows();
col = othercol = rand() % numCols();
dir = randdir();
switch(dir)
{
case UP: otherrow--; otherdir = DOWN; break;
case DOWN: otherrow++; otherdir = UP; break;
case LEFT: othercol--; otherdir = RIGHT; break;
case RIGHT: othercol++; otherdir = LEFT; break;
}
if( otherrow >= 0 && otherrow < numRows()
&& othercol >= 0 && othercol < numCols() )
{
destroyWall(dir, row, col);
destroyWall(otherdir, otherrow, othercol);
}
else
i--;
}
}
}
| [
"admoffit@"
] | admoffit@ |
a300ce80f3b5e654a30a0ee06e32752651ec07f4 | 54c6b0665b0aab3734a85b4603994a7f5672a51d | /Source/AndroidBluetooth/AndroidBluetooth.cpp | d2786c3a750b056efee43edc0f14c94d173f125c | [
"Apache-2.0"
] | permissive | DMcKay711/UnrealBluetoothPlugin | 3b0c50f81e0e11ea0c5e4a81b0cb6a50cdcf5eeb | c61fafdf18d938713af9f9276e470ae62e08e21a | refs/heads/master | 2020-05-16T02:02:28.615141 | 2017-06-18T12:21:42 | 2017-06-18T12:21:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 241 | cpp | // Fill out your copyright notice in the Description page of Project Settings.
#include "AndroidBluetooth.h"
#include "Modules/ModuleManager.h"
IMPLEMENT_PRIMARY_GAME_MODULE( FDefaultGameModuleImpl, AndroidBluetooth, "AndroidBluetooth" );
| [
"rlatkdgus500@gmail.com"
] | rlatkdgus500@gmail.com |
062e87dabe36887d973b823c56fb62787e847386 | 21bb96380bf47a5938675191d4fd650402737f19 | /TestGeometryHandler.cpp | f0999dab21d003568e6267e58892ff672bcef42c | [] | no_license | YSPersonal/LabDX9 | 652058f5b6b459b6353b17610d54a83d91326ce2 | 80895916e0f32554de7bae914a66e314b46dc17f | refs/heads/master | 2021-01-23T06:50:19.086770 | 2017-03-29T15:19:54 | 2017-03-29T15:19:54 | 86,404,751 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,311 | cpp | #include "DXUT.h"
#include "TestGeometryHandler.h"
HRESULT CALLBACK TestGeometryHandler::OnD3D9CreateDevice(IDirect3DDevice9* pd3dDevice,
const D3DSURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext) {
HRESULT hr;
D3DXCreateTeapot(pd3dDevice, &mesh, NULL);
return S_OK;
}
void CALLBACK TestGeometryHandler::OnD3D9FrameRender(IDirect3DDevice9* pd3dDevice, double fTime, float fElapsedTime, void* pUserContext) {
HRESULT hr;
// Clear the render target and the zbuffer
V(pd3dDevice->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_ARGB(0, 45, 50, 170), 1.0f, 0));
pd3dDevice->SetRenderState(D3DRS_LIGHTING, FALSE);
pd3dDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
// Render the scene
if (SUCCEEDED(pd3dDevice->BeginScene()))
{
mesh->DrawSubset(0);
V(pd3dDevice->EndScene());
}
}
void CALLBACK TestGeometryHandler::OnD3D9DestroyDevice(void* pUserContext)
{
SAFE_RELEASE(mesh);
}
TestGeometryHandler::TestGeometryHandler()
{
}
TestGeometryHandler::~TestGeometryHandler()
{
}
//#include "DXUTApplication.h"
//#include "SurroundCameraHandler.h"
//
//int main() {
//
// DXUTApplication::Instance()->AddHandler(new SurroundCameraHandler);
// DXUTApplication::Instance()->AddHandler(new TestGeometryHandler);
// DXUTApplication::Run();
//
// return 0;
//} | [
"Ethan@BAKA"
] | Ethan@BAKA |
bb1ec243d4e441725ed5b109e1cfdcc1f70a0491 | cf8ddfc720bf6451c4ef4fa01684327431db1919 | /SDK/ARKSurvivalEvolved_TPV_MiningDrill_HF_AnimBP_functions.cpp | 578265efe582e3e8b1bb8742f8ed901f9648b19b | [
"MIT"
] | permissive | git-Charlie/ARK-SDK | 75337684b11e7b9f668da1f15e8054052a3b600f | c38ca9925309516b2093ad8c3a70ed9489e1d573 | refs/heads/master | 2023-06-20T06:30:33.550123 | 2021-07-11T13:41:45 | 2021-07-11T13:41:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,753 | cpp | // ARKSurvivalEvolved (329.9) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_TPV_MiningDrill_HF_AnimBP_parameters.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Functions
//---------------------------------------------------------------------------
// Function TPV_MiningDrill_HF_AnimBP.TPV_MiningDrill_HF_AnimBP_C.BlueprintUpdateAnimation
// ()
// Parameters:
// float* DeltaTimeX (Parm, ZeroConstructor, IsPlainOldData)
void UTPV_MiningDrill_HF_AnimBP_C::BlueprintUpdateAnimation(float* DeltaTimeX)
{
static auto fn = UObject::FindObject<UFunction>("Function TPV_MiningDrill_HF_AnimBP.TPV_MiningDrill_HF_AnimBP_C.BlueprintUpdateAnimation");
UTPV_MiningDrill_HF_AnimBP_C_BlueprintUpdateAnimation_Params params;
params.DeltaTimeX = DeltaTimeX;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function TPV_MiningDrill_HF_AnimBP.TPV_MiningDrill_HF_AnimBP_C.ExecuteUbergraph_TPV_MiningDrill_HF_AnimBP
// ()
// Parameters:
// int EntryPoint (Parm, ZeroConstructor, IsPlainOldData)
void UTPV_MiningDrill_HF_AnimBP_C::ExecuteUbergraph_TPV_MiningDrill_HF_AnimBP(int EntryPoint)
{
static auto fn = UObject::FindObject<UFunction>("Function TPV_MiningDrill_HF_AnimBP.TPV_MiningDrill_HF_AnimBP_C.ExecuteUbergraph_TPV_MiningDrill_HF_AnimBP");
UTPV_MiningDrill_HF_AnimBP_C_ExecuteUbergraph_TPV_MiningDrill_HF_AnimBP_Params params;
params.EntryPoint = EntryPoint;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"sergey.2bite@gmail.com"
] | sergey.2bite@gmail.com |
be711758e93fe6692f76ff6d5babeacc65be0545 | afb2fd9af5fd0f7fc9bf5cbd51b6c7d637296957 | /include/nakama-cpp/realtime/NRtClientDisconnectInfo.h | 956efbcb946ff1a28f5e5dba34b3e3454a3e9453 | [
"Apache-2.0"
] | permissive | lineCode/nakama-cpp | c10510d974e1d33cfabb3d0dc4a0c66096db2f77 | 45746b46bfb8655593efbb0d86b153a060e59bc9 | refs/heads/master | 2020-05-26T20:14:03.041475 | 2019-05-19T20:35:10 | 2019-05-19T20:35:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 996 | h | /*
* Copyright 2019 The Nakama Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include "nakama-cpp/NTypes.h"
namespace Nakama {
struct NAKAMA_API NRtClientDisconnectInfo
{
/// close code.
/// https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent
uint16_t code;
/// close reason. Optional.
std::string reason;
/// true if close was initiated by server.
bool remote = false;
};
}
| [
"kdl.dima@gmail.com"
] | kdl.dima@gmail.com |
2e6835584355e3555ecda2affcd157722571209b | 8d0dd5c468965138fc5b8b95b25dd1817c205c9c | /src/qt/askpassphrasedialog.cpp | e3447a10c1c4d56ec458105f0148600445e86631 | [
"MIT"
] | permissive | ezaruba/unitcurrency | 5a5bd2c4bca81ae7d528ecb6ba406463347514c8 | 600da535414c061ff00ece3fb34eb1ecfac12b50 | refs/heads/master | 2021-08-19T14:36:57.380924 | 2017-11-26T17:01:03 | 2017-11-26T17:01:03 | 120,983,998 | 1 | 0 | null | 2018-02-10T04:30:11 | 2018-02-10T04:30:11 | null | UTF-8 | C++ | false | false | 10,009 | cpp | #include "askpassphrasedialog.h"
#include "ui_askpassphrasedialog.h"
#include "guiconstants.h"
#include "walletmodel.h"
#include <QMessageBox>
#include <QPushButton>
#include <QKeyEvent>
extern bool fWalletUnlockStakingOnly;
AskPassphraseDialog::AskPassphraseDialog(Mode mode, QWidget *parent) :
QDialog(parent),
ui(new Ui::AskPassphraseDialog),
mode(mode),
model(0),
fCapsLock(false)
{
ui->setupUi(this);
ui->passEdit1->setMaxLength(MAX_PASSPHRASE_SIZE);
ui->passEdit2->setMaxLength(MAX_PASSPHRASE_SIZE);
ui->passEdit3->setMaxLength(MAX_PASSPHRASE_SIZE);
// Setup Caps Lock detection.
ui->passEdit1->installEventFilter(this);
ui->passEdit2->installEventFilter(this);
ui->passEdit3->installEventFilter(this);
switch(mode)
{
case Encrypt: // Ask passphrase x2
ui->passLabel1->hide();
ui->passEdit1->hide();
ui->warningLabel->setText(tr("Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>."));
setWindowTitle(tr("Encrypt wallet"));
break;
case UnlockStaking:
ui->stakingCheckBox->setChecked(true);
ui->stakingCheckBox->show();
// fallthru
case Unlock: // Ask passphrase
ui->warningLabel->setText(tr("This operation needs your wallet passphrase to unlock the wallet."));
ui->passLabel2->hide();
ui->passEdit2->hide();
ui->passLabel3->hide();
ui->passEdit3->hide();
setWindowTitle(tr("Unlock wallet"));
break;
case Decrypt: // Ask passphrase
ui->warningLabel->setText(tr("This operation needs your wallet passphrase to decrypt the wallet."));
ui->passLabel2->hide();
ui->passEdit2->hide();
ui->passLabel3->hide();
ui->passEdit3->hide();
setWindowTitle(tr("Decrypt wallet"));
break;
case ChangePass: // Ask old passphrase + new passphrase x2
setWindowTitle(tr("Change passphrase"));
ui->warningLabel->setText(tr("Enter the old and new passphrase to the wallet."));
break;
}
textChanged();
connect(ui->passEdit1, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
connect(ui->passEdit2, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
connect(ui->passEdit3, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
}
AskPassphraseDialog::~AskPassphraseDialog()
{
// Attempt to overwrite text so that they do not linger around in memory
ui->passEdit1->setText(QString(" ").repeated(ui->passEdit1->text().size()));
ui->passEdit2->setText(QString(" ").repeated(ui->passEdit2->text().size()));
ui->passEdit3->setText(QString(" ").repeated(ui->passEdit3->text().size()));
delete ui;
}
void AskPassphraseDialog::setModel(WalletModel *model)
{
this->model = model;
}
void AskPassphraseDialog::accept()
{
SecureString oldpass, newpass1, newpass2;
if(!model)
return;
oldpass.reserve(MAX_PASSPHRASE_SIZE);
newpass1.reserve(MAX_PASSPHRASE_SIZE);
newpass2.reserve(MAX_PASSPHRASE_SIZE);
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make this input mlock()'d to begin with.
oldpass.assign(ui->passEdit1->text().toStdString().c_str());
newpass1.assign(ui->passEdit2->text().toStdString().c_str());
newpass2.assign(ui->passEdit3->text().toStdString().c_str());
switch(mode)
{
case Encrypt: {
if(newpass1.empty() || newpass2.empty())
{
// Cannot encrypt with empty passphrase
break;
}
QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm wallet encryption"),
tr("Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR COINS</b>!") + "<br><br>" + tr("Are you sure you wish to encrypt your wallet?"),
QMessageBox::Yes|QMessageBox::Cancel,
QMessageBox::Cancel);
if(retval == QMessageBox::Yes)
{
if(newpass1 == newpass2)
{
if(model->setWalletEncrypted(true, newpass1))
{
QMessageBox::warning(this, tr("Wallet encrypted"),
"<qt>" +
tr("UniversalCurrency will close now to finish the encryption process. "
"Remember that encrypting your wallet cannot fully protect "
"your coins from being stolen by malware infecting your computer.") +
"<br><br><b>" +
tr("IMPORTANT: Any previous backups you have made of your wallet file "
"should be replaced with the newly generated, encrypted wallet file. "
"For security reasons, previous backups of the unencrypted wallet file "
"will become useless as soon as you start using the new, encrypted wallet.") +
"</b></qt>");
QApplication::quit();
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("Wallet encryption failed due to an internal error. Your wallet was not encrypted."));
}
QDialog::accept(); // Success
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The supplied passphrases do not match."));
}
}
else
{
QDialog::reject(); // Cancelled
}
} break;
case UnlockStaking:
case Unlock:
if(!model->setWalletLocked(false, oldpass))
{
QMessageBox::critical(this, tr("Wallet unlock failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
}
else
{
fWalletUnlockStakingOnly = ui->stakingCheckBox->isChecked();
QDialog::accept(); // Success
}
break;
case Decrypt:
if(!model->setWalletEncrypted(false, oldpass))
{
QMessageBox::critical(this, tr("Wallet decryption failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
}
else
{
QDialog::accept(); // Success
}
break;
case ChangePass:
if(newpass1 == newpass2)
{
if(model->changePassphrase(oldpass, newpass1))
{
QMessageBox::information(this, tr("Wallet encrypted"),
tr("Wallet passphrase was successfully changed."));
QDialog::accept(); // Success
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
}
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The supplied passphrases do not match."));
}
break;
}
}
void AskPassphraseDialog::textChanged()
{
// Validate input, set Ok button to enabled when acceptable
bool acceptable = false;
switch(mode)
{
case Encrypt: // New passphrase x2
acceptable = !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();
break;
case UnlockStaking:
case Unlock: // Old passphrase x1
case Decrypt:
acceptable = !ui->passEdit1->text().isEmpty();
break;
case ChangePass: // Old passphrase x1, new passphrase x2
acceptable = !ui->passEdit1->text().isEmpty() && !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();
break;
}
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(acceptable);
}
bool AskPassphraseDialog::event(QEvent *event)
{
// Detect Caps Lock key press.
if (event->type() == QEvent::KeyPress) {
QKeyEvent *ke = static_cast<QKeyEvent *>(event);
if (ke->key() == Qt::Key_CapsLock) {
fCapsLock = !fCapsLock;
}
if (fCapsLock) {
ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!"));
} else {
ui->capsLabel->clear();
}
}
return QWidget::event(event);
}
bool AskPassphraseDialog::eventFilter(QObject *object, QEvent *event)
{
/* Detect Caps Lock.
* There is no good OS-independent way to check a key state in Qt, but we
* can detect Caps Lock by checking for the following condition:
* Shift key is down and the result is a lower case character, or
* Shift key is not down and the result is an upper case character.
*/
if (event->type() == QEvent::KeyPress) {
QKeyEvent *ke = static_cast<QKeyEvent *>(event);
QString str = ke->text();
if (str.length() != 0) {
const QChar *psz = str.unicode();
bool fShift = (ke->modifiers() & Qt::ShiftModifier) != 0;
if ((fShift && psz->isLower()) || (!fShift && psz->isUpper())) {
fCapsLock = true;
ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!"));
} else if (psz->isLetter()) {
fCapsLock = false;
ui->capsLabel->clear();
}
}
}
return QDialog::eventFilter(object, event);
}
| [
"root@explorer.unitcurrency.ccom"
] | root@explorer.unitcurrency.ccom |
7eec52dc823a3b09082b2d3aa1144beaed4e7d92 | f44e4e15f6b17078c8fec27b71c0d48e63b3d531 | /Desktop/C++/CD Burner Sample Important Parts/BurnCD.cpp | 288f338f9f2b47c3df6a8d30e188e2d339b70e63 | [] | no_license | SherwinKP/CodeSamplesFromDifferentProjects | 21e2afe317e2166ce2f41b9beeb91e1428196f87 | 12c1afb55bc53e85c09078a9fe9d164dc046233d | refs/heads/master | 2020-04-22T03:10:22.898681 | 2012-10-05T23:53:48 | 2012-10-05T23:53:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,597 | cpp | // BurnCD.cpp : Defines the class behaviors for the application.
//
#include "stdafx.h"
#include "BurnCD.h"
#include "BurnCDDlg.h"
#include <string>
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CBurnCDApp
BEGIN_MESSAGE_MAP(CBurnCDApp, CWinApp)
ON_COMMAND(ID_HELP, &CWinApp::OnHelp)
END_MESSAGE_MAP()
// CBurnCDApp construction
CBurnCDApp::CBurnCDApp()
{
// TODO: add construction code here,
// Place all significant initialization in InitInstance
}
// The one and only CBurnCDApp object
CBurnCDApp theApp;
// CBurnCDApp initialization
BOOL CBurnCDApp::InitInstance()
{
//std::wstring str = L"C:/willwriten/CER-CT#D:/AKGUN/AKPACSCC/AKPACS/PACSVIEWERV3/UserInterface/UserInterface/MediaWriter/AkpacsDicomViewerCdVersion#D:/AKGUN/AKPACSCC/AKPACS/PACSVIEWERV3/UserInterface/UserInterface/MediaWriter/autorun.inf#";
//m_lpCmdLine = (LPTSTR)str.c_str();
//if (m_lpCmdLine[0] != _T('\0'))
//{
//MessageBox(NULL,m_lpCmdLine,NULL,0);
// InitCommonControlsEx() is required on Windows XP if an application
// manifest specifies use of ComCtl32.dll version 6 or later to enable
// visual styles. Otherwise, any window creation will fail.
INITCOMMONCONTROLSEX InitCtrls;
InitCtrls.dwSize = sizeof(InitCtrls);
// Set this to include all the common control classes you want to use
// in your application.
InitCtrls.dwICC = ICC_WIN95_CLASSES;
InitCommonControlsEx(&InitCtrls);
CWinApp::InitInstance();
AfxEnableControlContainer();
// Standard initialization
// If you are not using these features and wish to reduce the size
// of your final executable, you should remove from the following
// the specific initialization routines you do not need
// Change the registry key under which our settings are stored
// TODO: You should modify this string to be something appropriate
// such as the name of your company or organization
SetRegistryKey(_T("Akpacs CDBurner"));
::CoInitializeEx(NULL, COINIT_MULTITHREADED);
CBurnCDDlg *dlg = new CBurnCDDlg(NULL, m_lpCmdLine);
m_pMainWnd = dlg;
INT_PTR nResponse = dlg->DoModal();
if (nResponse == IDOK)
{
// TODO: Place code here to handle when the dialog is
// dismissed with OK
}
else if (nResponse == IDCANCEL)
{
// TODO: Place code here to handle when the dialog is
// dismissed with Cancel
}
::CoUninitialize();
// Since the dialog has been closed, return FALSE so that we exit the
// application, rather than start the application's message pump.
return FALSE;
//}
}
| [
"circass@gmail.com"
] | circass@gmail.com |
7fd05418b937c1d335df84a277cdc7dc2d39aaad | f757c0ccaca9535169902455b2a6b974614397c7 | /108598007-HW4_FileSystem/108598007_hw4(精簡版)/test/ut_main.cpp | 53feb6ca4cb900b74c32f8a3d8f2b548c1fbbb39 | [] | no_license | qseft0402/2019_POSD | 0908efd4d4a933dc807026db5b46624fd352c0e1 | f254d704ef67756a41d38d99d5fd4c50dcc36b42 | refs/heads/master | 2020-08-21T10:13:56.017590 | 2020-01-05T03:02:51 | 2020-01-05T03:02:51 | 216,137,563 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 152 | cpp | #include <gtest/gtest.h>
#include "ut_node.h"
int main(int argc, char ** argv)
{
testing::InitGoogleTest(&argc, argv) ;
return RUN_ALL_TESTS() ;
}
| [
"qseft0402@gmail.com"
] | qseft0402@gmail.com |
e12c251146640e4eac6ebd41a53b7c3b8d022649 | 5f6cb9d4bd12d27dd66cc5bb29fda97ab4b97134 | /examples/datestuff.cpp | 857c2f6a04d276c14fda30c6bfd0f12f7153599e | [] | no_license | g-harinen/csis352 | acca14edec17300f15ac3735f155d6d8b5dfb843 | 5a2b45e9ea062f2d1c840d8e8808f97a83e9ad9f | refs/heads/master | 2022-04-10T19:52:39.757847 | 2020-01-27T21:59:54 | 2020-01-27T21:59:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,197 | cpp | #include <ctime>
#include <iostream>
using namespace std;
bool leapyear(int year)
{
return year % 400 == 0 || year % 4 == 0 && year % 100 != 0;
}
int main()
{
// this section gets and output the current date and time
tm *current;
time_t lt;
lt = time(0);
current = localtime(<);
int year = current->tm_year + 1900;
int month = current->tm_mon+1;
int day = current->tm_mday;
int hour = current->tm_hour;
int minute = current->tm_min;
int second = current->tm_sec;
cout << "current year: " << year << endl;
cout << "current month: " << month << endl;
cout << "current day: " << day << endl;
cout << "current hour: " << hour << endl;
cout << "current minute: " << minute << endl;
cout << "current second: " << second << endl;
// this section gets and outputs the day of the week for the current date
// (or whatever date that would be stored in month, day, and year)
// The algorithm is valid for the Gregorian calendar which was adopted
// in September 1752.
int centuries;
int months;
int dayofweek;
centuries = (3-year/100%4)*2;
switch (month)
{
case 1 : if (leapyear(year))
months = 6;
else
months = 0;
break;
case 2 : if (leapyear(year))
months = 2;
else
months = 3;
break;
case 3 : months = 3; break;
case 4 : months = 6; break;
case 5 : months = 1; break;
case 6 : months = 4; break;
case 7 : months = 6; break;
case 8 : months = 2; break;
case 9 : months = 5; break;
case 10 : months = 0; break;
case 11 : months = 3; break;
case 12 : months = 5; break;
}
dayofweek = (centuries+year%100+year%100/4+months+day)%7;
cout << "today is ";
switch (dayofweek)
{
case 0 : cout << "Sunday\n"; break;
case 1 : cout << "Monday\n"; break;
case 2 : cout << "Tuesday\n"; break;
case 3 : cout << "Wednesday\n"; break;
case 4 : cout << "Thursday\n"; break;
case 5 : cout << "Friday\n"; break;
case 6 : cout << "Saturday\n"; break;
}
return 0;
}
| [
"chenan@mnstate.edu"
] | chenan@mnstate.edu |
f46d56a0c3c15ec222ff1c4df92c7cfe8ea7dd57 | 9445ccc40e8518c35924e40815fdf616d4d5e9ad | /URI1074.cpp | 803dd53525622da39320921021f3fd8551feefd8 | [] | no_license | brunoalvaro130/URI-C-plus | 74a384c140574fcf138e64b214992ce2eb64e455 | d4771bec5f05aec7a9db0f9556bd787bec8c7ea4 | refs/heads/master | 2022-11-26T03:14:13.825476 | 2020-07-30T18:49:25 | 2020-07-30T18:49:25 | 283,567,299 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 460 | cpp | #include <iostream>
using namespace std;
int main(int argc, char** argv)
{
int n, x;
cin >> n;
for(int i = 0; i < n;i++){
cin >> x;
if(x%2 != 0){
if(x < 0){
cout << "ODD NEGATIVE" << endl;
} else {
cout << "ODD POSITIVE" << endl;
}
} else if (x%2 == 0){
if(x < 0){
cout << "EVEN NEGATIVE" << endl;
} else if (x > 0){
cout << "EVEN POSITIVE" << endl;
} else{
cout << "NULL" << endl;
}
}
}
return 0;
} | [
"brunoalvaro130@gmail.com"
] | brunoalvaro130@gmail.com |
ee0f9be00b730f85e596335a9fe6aa1b08ed8540 | bb6ebff7a7f6140903d37905c350954ff6599091 | /v8/src/contexts.cc | cb5e852d7d669c07c8d8b950016defff1572f49c | [
"BSD-3-Clause",
"bzip2-1.0.6"
] | permissive | PDi-Communication-Systems-Inc/lollipop_external_chromium_org | faa6602bd6bfd9b9b6277ce3cd16df0bd26e7f2f | ccadf4e63dd34be157281f53fe213d09a8c66d2c | refs/heads/master | 2022-12-23T18:07:04.568931 | 2016-04-11T16:03:36 | 2016-04-11T16:03:36 | 53,677,925 | 0 | 1 | BSD-3-Clause | 2022-12-09T23:46:46 | 2016-03-11T15:49:07 | C++ | UTF-8 | C++ | false | false | 12,281 | cc | // Copyright 2011 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/v8.h"
#include "src/bootstrapper.h"
#include "src/debug.h"
#include "src/scopeinfo.h"
namespace v8 {
namespace internal {
Context* Context::declaration_context() {
Context* current = this;
while (!current->IsFunctionContext() && !current->IsNativeContext()) {
current = current->previous();
ASSERT(current->closure() == closure());
}
return current;
}
JSBuiltinsObject* Context::builtins() {
GlobalObject* object = global_object();
if (object->IsJSGlobalObject()) {
return JSGlobalObject::cast(object)->builtins();
} else {
ASSERT(object->IsJSBuiltinsObject());
return JSBuiltinsObject::cast(object);
}
}
Context* Context::global_context() {
Context* current = this;
while (!current->IsGlobalContext()) {
current = current->previous();
}
return current;
}
Context* Context::native_context() {
// Fast case: the global object for this context has been set. In
// that case, the global object has a direct pointer to the global
// context.
if (global_object()->IsGlobalObject()) {
return global_object()->native_context();
}
// During bootstrapping, the global object might not be set and we
// have to search the context chain to find the native context.
ASSERT(this->GetIsolate()->bootstrapper()->IsActive());
Context* current = this;
while (!current->IsNativeContext()) {
JSFunction* closure = JSFunction::cast(current->closure());
current = Context::cast(closure->context());
}
return current;
}
JSObject* Context::global_proxy() {
return native_context()->global_proxy_object();
}
void Context::set_global_proxy(JSObject* object) {
native_context()->set_global_proxy_object(object);
}
Handle<Object> Context::Lookup(Handle<String> name,
ContextLookupFlags flags,
int* index,
PropertyAttributes* attributes,
BindingFlags* binding_flags) {
Isolate* isolate = GetIsolate();
Handle<Context> context(this, isolate);
bool follow_context_chain = (flags & FOLLOW_CONTEXT_CHAIN) != 0;
*index = -1;
*attributes = ABSENT;
*binding_flags = MISSING_BINDING;
if (FLAG_trace_contexts) {
PrintF("Context::Lookup(");
name->ShortPrint();
PrintF(")\n");
}
do {
if (FLAG_trace_contexts) {
PrintF(" - looking in context %p", reinterpret_cast<void*>(*context));
if (context->IsNativeContext()) PrintF(" (native context)");
PrintF("\n");
}
// 1. Check global objects, subjects of with, and extension objects.
if (context->IsNativeContext() ||
context->IsWithContext() ||
(context->IsFunctionContext() && context->has_extension())) {
Handle<JSReceiver> object(
JSReceiver::cast(context->extension()), isolate);
// Context extension objects needs to behave as if they have no
// prototype. So even if we want to follow prototype chains, we need
// to only do a local lookup for context extension objects.
if ((flags & FOLLOW_PROTOTYPE_CHAIN) == 0 ||
object->IsJSContextExtensionObject()) {
*attributes = JSReceiver::GetOwnPropertyAttributes(object, name);
} else {
*attributes = JSReceiver::GetPropertyAttributes(object, name);
}
if (isolate->has_pending_exception()) return Handle<Object>();
if (*attributes != ABSENT) {
if (FLAG_trace_contexts) {
PrintF("=> found property in context object %p\n",
reinterpret_cast<void*>(*object));
}
return object;
}
}
// 2. Check the context proper if it has slots.
if (context->IsFunctionContext() || context->IsBlockContext()) {
// Use serialized scope information of functions and blocks to search
// for the context index.
Handle<ScopeInfo> scope_info;
if (context->IsFunctionContext()) {
scope_info = Handle<ScopeInfo>(
context->closure()->shared()->scope_info(), isolate);
} else {
scope_info = Handle<ScopeInfo>(
ScopeInfo::cast(context->extension()), isolate);
}
VariableMode mode;
InitializationFlag init_flag;
int slot_index =
ScopeInfo::ContextSlotIndex(scope_info, name, &mode, &init_flag);
ASSERT(slot_index < 0 || slot_index >= MIN_CONTEXT_SLOTS);
if (slot_index >= 0) {
if (FLAG_trace_contexts) {
PrintF("=> found local in context slot %d (mode = %d)\n",
slot_index, mode);
}
*index = slot_index;
// Note: Fixed context slots are statically allocated by the compiler.
// Statically allocated variables always have a statically known mode,
// which is the mode with which they were declared when added to the
// scope. Thus, the DYNAMIC mode (which corresponds to dynamically
// declared variables that were introduced through declaration nodes)
// must not appear here.
switch (mode) {
case INTERNAL: // Fall through.
case VAR:
*attributes = NONE;
*binding_flags = MUTABLE_IS_INITIALIZED;
break;
case LET:
*attributes = NONE;
*binding_flags = (init_flag == kNeedsInitialization)
? MUTABLE_CHECK_INITIALIZED : MUTABLE_IS_INITIALIZED;
break;
case CONST_LEGACY:
*attributes = READ_ONLY;
*binding_flags = (init_flag == kNeedsInitialization)
? IMMUTABLE_CHECK_INITIALIZED : IMMUTABLE_IS_INITIALIZED;
break;
case CONST:
*attributes = READ_ONLY;
*binding_flags = (init_flag == kNeedsInitialization)
? IMMUTABLE_CHECK_INITIALIZED_HARMONY :
IMMUTABLE_IS_INITIALIZED_HARMONY;
break;
case MODULE:
*attributes = READ_ONLY;
*binding_flags = IMMUTABLE_IS_INITIALIZED_HARMONY;
break;
case DYNAMIC:
case DYNAMIC_GLOBAL:
case DYNAMIC_LOCAL:
case TEMPORARY:
UNREACHABLE();
break;
}
return context;
}
// Check the slot corresponding to the intermediate context holding
// only the function name variable.
if (follow_context_chain && context->IsFunctionContext()) {
VariableMode mode;
int function_index = scope_info->FunctionContextSlotIndex(*name, &mode);
if (function_index >= 0) {
if (FLAG_trace_contexts) {
PrintF("=> found intermediate function in context slot %d\n",
function_index);
}
*index = function_index;
*attributes = READ_ONLY;
ASSERT(mode == CONST_LEGACY || mode == CONST);
*binding_flags = (mode == CONST_LEGACY)
? IMMUTABLE_IS_INITIALIZED : IMMUTABLE_IS_INITIALIZED_HARMONY;
return context;
}
}
} else if (context->IsCatchContext()) {
// Catch contexts have the variable name in the extension slot.
if (String::Equals(name, handle(String::cast(context->extension())))) {
if (FLAG_trace_contexts) {
PrintF("=> found in catch context\n");
}
*index = Context::THROWN_OBJECT_INDEX;
*attributes = NONE;
*binding_flags = MUTABLE_IS_INITIALIZED;
return context;
}
}
// 3. Prepare to continue with the previous (next outermost) context.
if (context->IsNativeContext()) {
follow_context_chain = false;
} else {
context = Handle<Context>(context->previous(), isolate);
}
} while (follow_context_chain);
if (FLAG_trace_contexts) {
PrintF("=> no property/slot found\n");
}
return Handle<Object>::null();
}
void Context::AddOptimizedFunction(JSFunction* function) {
ASSERT(IsNativeContext());
#ifdef ENABLE_SLOW_ASSERTS
if (FLAG_enable_slow_asserts) {
Object* element = get(OPTIMIZED_FUNCTIONS_LIST);
while (!element->IsUndefined()) {
CHECK(element != function);
element = JSFunction::cast(element)->next_function_link();
}
}
// Check that the context belongs to the weak native contexts list.
bool found = false;
Object* context = GetHeap()->native_contexts_list();
while (!context->IsUndefined()) {
if (context == this) {
found = true;
break;
}
context = Context::cast(context)->get(Context::NEXT_CONTEXT_LINK);
}
CHECK(found);
#endif
// If the function link field is already used then the function was
// enqueued as a code flushing candidate and we remove it now.
if (!function->next_function_link()->IsUndefined()) {
CodeFlusher* flusher = GetHeap()->mark_compact_collector()->code_flusher();
flusher->EvictCandidate(function);
}
ASSERT(function->next_function_link()->IsUndefined());
function->set_next_function_link(get(OPTIMIZED_FUNCTIONS_LIST));
set(OPTIMIZED_FUNCTIONS_LIST, function);
}
void Context::RemoveOptimizedFunction(JSFunction* function) {
ASSERT(IsNativeContext());
Object* element = get(OPTIMIZED_FUNCTIONS_LIST);
JSFunction* prev = NULL;
while (!element->IsUndefined()) {
JSFunction* element_function = JSFunction::cast(element);
ASSERT(element_function->next_function_link()->IsUndefined() ||
element_function->next_function_link()->IsJSFunction());
if (element_function == function) {
if (prev == NULL) {
set(OPTIMIZED_FUNCTIONS_LIST, element_function->next_function_link());
} else {
prev->set_next_function_link(element_function->next_function_link());
}
element_function->set_next_function_link(GetHeap()->undefined_value());
return;
}
prev = element_function;
element = element_function->next_function_link();
}
UNREACHABLE();
}
void Context::SetOptimizedFunctionsListHead(Object* head) {
ASSERT(IsNativeContext());
set(OPTIMIZED_FUNCTIONS_LIST, head);
}
Object* Context::OptimizedFunctionsListHead() {
ASSERT(IsNativeContext());
return get(OPTIMIZED_FUNCTIONS_LIST);
}
void Context::AddOptimizedCode(Code* code) {
ASSERT(IsNativeContext());
ASSERT(code->kind() == Code::OPTIMIZED_FUNCTION);
ASSERT(code->next_code_link()->IsUndefined());
code->set_next_code_link(get(OPTIMIZED_CODE_LIST));
set(OPTIMIZED_CODE_LIST, code);
}
void Context::SetOptimizedCodeListHead(Object* head) {
ASSERT(IsNativeContext());
set(OPTIMIZED_CODE_LIST, head);
}
Object* Context::OptimizedCodeListHead() {
ASSERT(IsNativeContext());
return get(OPTIMIZED_CODE_LIST);
}
void Context::SetDeoptimizedCodeListHead(Object* head) {
ASSERT(IsNativeContext());
set(DEOPTIMIZED_CODE_LIST, head);
}
Object* Context::DeoptimizedCodeListHead() {
ASSERT(IsNativeContext());
return get(DEOPTIMIZED_CODE_LIST);
}
Handle<Object> Context::ErrorMessageForCodeGenerationFromStrings() {
Isolate* isolate = GetIsolate();
Handle<Object> result(error_message_for_code_gen_from_strings(), isolate);
if (!result->IsUndefined()) return result;
return isolate->factory()->NewStringFromStaticAscii(
"Code generation from strings disallowed for this context");
}
#ifdef DEBUG
bool Context::IsBootstrappingOrValidParentContext(
Object* object, Context* child) {
// During bootstrapping we allow all objects to pass as
// contexts. This is necessary to fix circular dependencies.
if (child->GetIsolate()->bootstrapper()->IsActive()) return true;
if (!object->IsContext()) return false;
Context* context = Context::cast(object);
return context->IsNativeContext() || context->IsGlobalContext() ||
context->IsModuleContext() || !child->IsModuleContext();
}
bool Context::IsBootstrappingOrGlobalObject(Isolate* isolate, Object* object) {
// During bootstrapping we allow all objects to pass as global
// objects. This is necessary to fix circular dependencies.
return isolate->heap()->gc_state() != Heap::NOT_IN_GC ||
isolate->bootstrapper()->IsActive() ||
object->IsGlobalObject();
}
#endif
} } // namespace v8::internal
| [
"mrobbeloth@pdiarm.com"
] | mrobbeloth@pdiarm.com |
6e39e1515832b0908222d7de95cf75794aeda6d3 | 0bbae4660f0601ff4861389690f4df4812184ed7 | /usrp_mkid.cpp | 9eda1af2b682ca7015a75e4ca04d729fd270c914 | [] | no_license | WanduiAlbert/usrp_mkid | 8e873e1e715ed646377de99aa7a410fbe890a357 | 7faa3ee1196d32028cc7f2af4a81a43e371f0ef2 | refs/heads/master | 2020-03-13T01:52:24.234427 | 2018-04-25T21:49:46 | 2018-04-25T21:49:46 | 130,913,244 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,402 | cpp | #include <stdio.h>
#include <boost/program_options.hpp>
#include <boost/thread/thread.hpp>
#include <csignal>
#include "H5Cpp.h"
#include "usrp_mkid.h"
#include "radio.h"
#include "lobank.h"
#include "outputfile.h"
using namespace std;
namespace po = boost::program_options;
static int stop_signal_called;
void sig_int_handler(int arg)
{
(void)arg;
stop_signal_called = true;
}
RXTX::RXTX(Radio::sptr _radio, FIRDecimate::sptr _fir, size_t _nch, int *_stop_signal)
: radio(_radio), nch(_nch), stop_signal(_stop_signal), lobank_rx(new LOBank(nch)), lobank_tx(new LOBank(nch)), fir(_fir),
channelizer(fir), channel_queue(nch)
{
channelizer.set_lobank(lobank_rx);
radio->check_lock();
radio->zero_time();
}
void RXTX::multi_thread()
{
boost::thread transmit_thread(&RXTX::transmit_thread,this);
receive_thread();
transmit_thread.join();
}
void RXTX::receive_thread()
{
radio->init_receive();
while(not *stop_signal) {
cout << "receiving block...";
radio->receive(recv_queue);
cout << "ok" << endl;
channelizer.channelize(recv_queue,channel_queue);
}
radio->receive_stop();
}
void RXTX::transmit_thread()
{
while(not *stop_signal) {
lobank_tx->get_sample_tx(radio->tx_buf);
radio->transmit();
}
radio->transmit_stop();
}
int main(int argc, char **argv)
{
double rf_freq, dsp_freq, dsp_rate;
size_t nch;
string tone_config, fir_config;
po::options_description desc("Allowed options");
stop_signal_called = false;
desc.add_options()
("help","help message")
("lo-freq", po::value<double>(&rf_freq)->default_value(200e6), "LO frequency")
("dsp_freq", po::value<double>(&dsp_freq)->default_value(10e6), "DSP frequency")
("dsp-rate", po::value<double>(&dsp_rate)->default_value(1e6), "DSP sample rate")
("nchannel", po::value<size_t>(&nch)->default_value(1),"Number of channels")
("fir-config",po::value<string>(&fir_config)->default_value("fir.cfg"),"FIR configuration file")
;
po::variables_map vm;
po::store(po::parse_command_line(argc,argv,desc),vm);
po::notify(vm);
Radio::sptr radio(new Radio(&stop_signal_called));
radio->set_rf_frequency(rf_freq);
radio->set_dsp_frequency(dsp_freq);
radio->set_dsp_rate(dsp_rate);
FIRDecimate::sptr fir(new FIRDecimate(fir_config));
std::signal(SIGINT,&sig_int_handler);
cout << "Press ctrl+c to stop streaming..." << endl;
RXTX rxtx(radio,fir,nch,&stop_signal_called);
rxtx.multi_thread();
}
| [
"albertkamau16@gmail.com"
] | albertkamau16@gmail.com |
b501bfa8fcbc3654e8696760211c7196106fbf4a | 04befb4e55a11d7d0c574da2482672b66fcbd8e4 | /src/rpcmisc.cpp | 54a3bd30454334dff129dd61403501615b74e0b5 | [
"MIT"
] | permissive | Socialtraders/STRD | 57c255cc66ad374ab11dfc7ec20b57997556acf2 | f8724bb4418e877049e9432ab2cf98c046f61083 | refs/heads/master | 2020-03-28T06:27:37.923923 | 2018-09-07T14:40:58 | 2018-09-07T14:40:58 | 147,123,462 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 24,035 | cpp | // Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The PIVX developers
// Copyright (c) 2018 The SocialTraders developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "base58.h"
#include "clientversion.h"
#include "init.h"
#include "main.h"
#include "masternode-sync.h"
#include "net.h"
#include "netbase.h"
#include "rpcserver.h"
#include "spork.h"
#include "timedata.h"
#include "util.h"
#ifdef ENABLE_WALLET
#include "wallet.h"
#include "walletdb.h"
#endif
#include <stdint.h>
#include "json/json_spirit_utils.h"
#include "json/json_spirit_value.h"
#include <boost/assign/list_of.hpp>
using namespace boost;
using namespace boost::assign;
using namespace json_spirit;
using namespace std;
/**
* @note Do not add or change anything in the information returned by this
* method. `getinfo` exists for backwards-compatibility only. It combines
* information from wildly different sources in the program, which is a mess,
* and is thus planned to be deprecated eventually.
*
* Based on the source of the information, new information should be added to:
* - `getblockchaininfo`,
* - `getnetworkinfo` or
* - `getwalletinfo`
*
* Or alternatively, create a specific query method for the information.
**/
Value getinfo(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getinfo\n"
"Returns an object containing various state info.\n"
"\nResult:\n"
"{\n"
" \"version\": xxxxx, (numeric) the server version\n"
" \"protocolversion\": xxxxx, (numeric) the protocol version\n"
" \"walletversion\": xxxxx, (numeric) the wallet version\n"
" \"balance\": xxxxxxx, (numeric) the total socialtraders balance of the wallet\n"
" \"obfuscation_balance\": xxxxxx, (numeric) the anonymized socialtraders balance of the wallet\n"
" \"blocks\": xxxxxx, (numeric) the current number of blocks processed in the server\n"
" \"timeoffset\": xxxxx, (numeric) the time offset\n"
" \"connections\": xxxxx, (numeric) the number of connections\n"
" \"proxy\": \"host:port\", (string, optional) the proxy used by the server\n"
" \"difficulty\": xxxxxx, (numeric) the current difficulty\n"
" \"testnet\": true|false, (boolean) if the server is using testnet or not\n"
" \"keypoololdest\": xxxxxx, (numeric) the timestamp (seconds since GMT epoch) of the oldest pre-generated key in the key pool\n"
" \"keypoolsize\": xxxx, (numeric) how many new keys are pre-generated\n"
" \"unlocked_until\": ttt, (numeric) the timestamp in seconds since epoch (midnight Jan 1 1970 GMT) that the wallet is unlocked for transfers, or 0 if the wallet is locked\n"
" \"paytxfee\": x.xxxx, (numeric) the transaction fee set in socialtraders/kb\n"
" \"relayfee\": x.xxxx, (numeric) minimum relay fee for non-free transactions in socialtraders/kb\n"
" \"staking status\": true|false, (boolean) if the wallet is staking or not\n"
" \"errors\": \"...\" (string) any error messages\n"
"}\n"
"\nExamples:\n" +
HelpExampleCli("getinfo", "") + HelpExampleRpc("getinfo", ""));
proxyType proxy;
GetProxy(NET_IPV4, proxy);
Object obj;
obj.push_back(Pair("version", CLIENT_VERSION));
obj.push_back(Pair("protocolversion", PROTOCOL_VERSION));
#ifdef ENABLE_WALLET
if (pwalletMain) {
obj.push_back(Pair("walletversion", pwalletMain->GetVersion()));
obj.push_back(Pair("balance", ValueFromAmount(pwalletMain->GetBalance())));
if (!fLiteMode)
obj.push_back(Pair("obfuscation_balance", ValueFromAmount(pwalletMain->GetAnonymizedBalance())));
}
#endif
obj.push_back(Pair("blocks", (int)chainActive.Height()));
obj.push_back(Pair("timeoffset", GetTimeOffset()));
obj.push_back(Pair("connections", (int)vNodes.size()));
obj.push_back(Pair("proxy", (proxy.IsValid() ? proxy.ToStringIPPort() : string())));
obj.push_back(Pair("difficulty", (double)GetDifficulty()));
obj.push_back(Pair("testnet", Params().TestnetToBeDeprecatedFieldRPC()));
#ifdef ENABLE_WALLET
if (pwalletMain) {
obj.push_back(Pair("keypoololdest", pwalletMain->GetOldestKeyPoolTime()));
obj.push_back(Pair("keypoolsize", (int)pwalletMain->GetKeyPoolSize()));
}
if (pwalletMain && pwalletMain->IsCrypted())
obj.push_back(Pair("unlocked_until", nWalletUnlockTime));
obj.push_back(Pair("paytxfee", ValueFromAmount(payTxFee.GetFeePerK())));
#endif
obj.push_back(Pair("relayfee", ValueFromAmount(::minRelayTxFee.GetFeePerK())));
bool nStaking = false;
if (mapHashedBlocks.count(chainActive.Tip()->nHeight))
nStaking = true;
else if (mapHashedBlocks.count(chainActive.Tip()->nHeight - 1) && nLastCoinStakeSearchInterval)
nStaking = true;
obj.push_back(Pair("staking status", (nStaking ? "Staking Active" : "Staking Not Active")));
obj.push_back(Pair("errors", GetWarnings("statusbar")));
return obj;
}
Value mnsync(const Array& params, bool fHelp)
{
std::string strMode;
if (params.size() == 1)
strMode = params[0].get_str();
if (fHelp || params.size() != 1 || (strMode != "status" && strMode != "reset")) {
throw runtime_error(
"mnsync \"status|reset\"\n"
"\nReturns the sync status or resets sync.\n"
"\nArguments:\n"
"1. \"mode\" (string, required) either 'status' or 'reset'\n"
"\nResult ('status' mode):\n"
"{\n"
" \"IsBlockchainSynced\": true|false, (boolean) 'true' if blockchain is synced\n"
" \"lastMasternodeList\": xxxx, (numeric) Timestamp of last MN list message\n"
" \"lastMasternodeWinner\": xxxx, (numeric) Timestamp of last MN winner message\n"
" \"lastBudgetItem\": xxxx, (numeric) Timestamp of last MN budget message\n"
" \"lastFailure\": xxxx, (numeric) Timestamp of last failed sync\n"
" \"nCountFailures\": n, (numeric) Number of failed syncs (total)\n"
" \"sumMasternodeList\": n, (numeric) Number of MN list messages (total)\n"
" \"sumMasternodeWinner\": n, (numeric) Number of MN winner messages (total)\n"
" \"sumBudgetItemProp\": n, (numeric) Number of MN budget messages (total)\n"
" \"sumBudgetItemFin\": n, (numeric) Number of MN budget finalization messages (total)\n"
" \"countMasternodeList\": n, (numeric) Number of MN list messages (local)\n"
" \"countMasternodeWinner\": n, (numeric) Number of MN winner messages (local)\n"
" \"countBudgetItemProp\": n, (numeric) Number of MN budget messages (local)\n"
" \"countBudgetItemFin\": n, (numeric) Number of MN budget finalization messages (local)\n"
" \"RequestedMasternodeAssets\": n, (numeric) Status code of last sync phase\n"
" \"RequestedMasternodeAttempt\": n, (numeric) Status code of last sync attempt\n"
"}\n"
"\nResult ('reset' mode):\n"
"\"status\" (string) 'success'\n"
"\nExamples:\n" +
HelpExampleCli("mnsync", "\"status\"") + HelpExampleRpc("mnsync", "\"status\""));
}
if (strMode == "status") {
Object obj;
obj.push_back(Pair("IsBlockchainSynced", masternodeSync.IsBlockchainSynced()));
obj.push_back(Pair("lastMasternodeList", masternodeSync.lastMasternodeList));
obj.push_back(Pair("lastMasternodeWinner", masternodeSync.lastMasternodeWinner));
obj.push_back(Pair("lastBudgetItem", masternodeSync.lastBudgetItem));
obj.push_back(Pair("lastFailure", masternodeSync.lastFailure));
obj.push_back(Pair("nCountFailures", masternodeSync.nCountFailures));
obj.push_back(Pair("sumMasternodeList", masternodeSync.sumMasternodeList));
obj.push_back(Pair("sumMasternodeWinner", masternodeSync.sumMasternodeWinner));
obj.push_back(Pair("sumBudgetItemProp", masternodeSync.sumBudgetItemProp));
obj.push_back(Pair("sumBudgetItemFin", masternodeSync.sumBudgetItemFin));
obj.push_back(Pair("countMasternodeList", masternodeSync.countMasternodeList));
obj.push_back(Pair("countMasternodeWinner", masternodeSync.countMasternodeWinner));
obj.push_back(Pair("countBudgetItemProp", masternodeSync.countBudgetItemProp));
obj.push_back(Pair("countBudgetItemFin", masternodeSync.countBudgetItemFin));
obj.push_back(Pair("RequestedMasternodeAssets", masternodeSync.RequestedMasternodeAssets));
obj.push_back(Pair("RequestedMasternodeAttempt", masternodeSync.RequestedMasternodeAttempt));
return obj;
}
if (strMode == "reset") {
masternodeSync.Reset();
return "success";
}
return "failure";
}
#ifdef ENABLE_WALLET
class DescribeAddressVisitor : public boost::static_visitor<Object>
{
private:
isminetype mine;
public:
DescribeAddressVisitor(isminetype mineIn) : mine(mineIn) {}
Object operator()(const CNoDestination& dest) const { return Object(); }
Object operator()(const CKeyID& keyID) const
{
Object obj;
CPubKey vchPubKey;
obj.push_back(Pair("isscript", false));
if (mine == ISMINE_SPENDABLE) {
pwalletMain->GetPubKey(keyID, vchPubKey);
obj.push_back(Pair("pubkey", HexStr(vchPubKey)));
obj.push_back(Pair("iscompressed", vchPubKey.IsCompressed()));
}
return obj;
}
Object operator()(const CScriptID& scriptID) const
{
Object obj;
obj.push_back(Pair("isscript", true));
if (mine != ISMINE_NO) {
CScript subscript;
pwalletMain->GetCScript(scriptID, subscript);
std::vector<CTxDestination> addresses;
txnouttype whichType;
int nRequired;
ExtractDestinations(subscript, whichType, addresses, nRequired);
obj.push_back(Pair("script", GetTxnOutputType(whichType)));
obj.push_back(Pair("hex", HexStr(subscript.begin(), subscript.end())));
Array a;
BOOST_FOREACH (const CTxDestination& addr, addresses)
a.push_back(CBitcoinAddress(addr).ToString());
obj.push_back(Pair("addresses", a));
if (whichType == TX_MULTISIG)
obj.push_back(Pair("sigsrequired", nRequired));
}
return obj;
}
};
#endif
/*
Used for updating/reading spork settings on the network
*/
Value spork(const Array& params, bool fHelp)
{
if (params.size() == 1 && params[0].get_str() == "show") {
Object ret;
for (int nSporkID = SPORK_START; nSporkID <= SPORK_END; nSporkID++) {
if (sporkManager.GetSporkNameByID(nSporkID) != "Unknown")
ret.push_back(Pair(sporkManager.GetSporkNameByID(nSporkID), GetSporkValue(nSporkID)));
}
return ret;
} else if (params.size() == 1 && params[0].get_str() == "active") {
Object ret;
for (int nSporkID = SPORK_START; nSporkID <= SPORK_END; nSporkID++) {
if (sporkManager.GetSporkNameByID(nSporkID) != "Unknown")
ret.push_back(Pair(sporkManager.GetSporkNameByID(nSporkID), IsSporkActive(nSporkID)));
}
return ret;
} else if (params.size() == 2) {
int nSporkID = sporkManager.GetSporkIDByName(params[0].get_str());
if (nSporkID == -1) {
return "Invalid spork name";
}
// SPORK VALUE
int64_t nValue = params[1].get_int();
//broadcast new spork
if (sporkManager.UpdateSpork(nSporkID, nValue)) {
ExecuteSpork(nSporkID, nValue);
return "success";
} else {
return "failure";
}
}
throw runtime_error(
"spork <name> [<value>]\n"
"<name> is the corresponding spork name, or 'show' to show all current spork settings, active to show which sporks are active"
"<value> is a epoch datetime to enable or disable spork" +
HelpRequiringPassphrase());
}
Value validateaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"validateaddress \"socialtradersaddress\"\n"
"\nReturn information about the given socialtraders address.\n"
"\nArguments:\n"
"1. \"socialtradersaddress\" (string, required) The socialtraders address to validate\n"
"\nResult:\n"
"{\n"
" \"isvalid\" : true|false, (boolean) If the address is valid or not. If not, this is the only property returned.\n"
" \"address\" : \"socialtradersaddress\", (string) The socialtraders address validated\n"
" \"ismine\" : true|false, (boolean) If the address is yours or not\n"
" \"isscript\" : true|false, (boolean) If the key is a script\n"
" \"pubkey\" : \"publickeyhex\", (string) The hex value of the raw public key\n"
" \"iscompressed\" : true|false, (boolean) If the address is compressed\n"
" \"account\" : \"account\" (string) The account associated with the address, \"\" is the default account\n"
"}\n"
"\nExamples:\n" +
HelpExampleCli("validateaddress", "\"1PSSGeFHDnKNxiEyFrD1wcEaHr9hrQDDWc\"") + HelpExampleRpc("validateaddress", "\"1PSSGeFHDnKNxiEyFrD1wcEaHr9hrQDDWc\""));
CBitcoinAddress address(params[0].get_str());
bool isValid = address.IsValid();
Object ret;
ret.push_back(Pair("isvalid", isValid));
if (isValid) {
CTxDestination dest = address.Get();
string currentAddress = address.ToString();
ret.push_back(Pair("address", currentAddress));
#ifdef ENABLE_WALLET
isminetype mine = pwalletMain ? IsMine(*pwalletMain, dest) : ISMINE_NO;
ret.push_back(Pair("ismine", (mine & ISMINE_SPENDABLE) ? true : false));
if (mine != ISMINE_NO) {
ret.push_back(Pair("iswatchonly", (mine & ISMINE_WATCH_ONLY) ? true : false));
Object detail = boost::apply_visitor(DescribeAddressVisitor(mine), dest);
ret.insert(ret.end(), detail.begin(), detail.end());
}
if (pwalletMain && pwalletMain->mapAddressBook.count(dest))
ret.push_back(Pair("account", pwalletMain->mapAddressBook[dest].name));
#endif
}
return ret;
}
/**
* Used by addmultisigaddress / createmultisig:
*/
CScript _createmultisig_redeemScript(const Array& params)
{
int nRequired = params[0].get_int();
const Array& keys = params[1].get_array();
// Gather public keys
if (nRequired < 1)
throw runtime_error("a multisignature address must require at least one key to redeem");
if ((int)keys.size() < nRequired)
throw runtime_error(
strprintf("not enough keys supplied "
"(got %u keys, but need at least %d to redeem)",
keys.size(), nRequired));
if (keys.size() > 16)
throw runtime_error("Number of addresses involved in the multisignature address creation > 16\nReduce the number");
std::vector<CPubKey> pubkeys;
pubkeys.resize(keys.size());
for (unsigned int i = 0; i < keys.size(); i++) {
const std::string& ks = keys[i].get_str();
#ifdef ENABLE_WALLET
// Case 1: socialtraders address and we have full public key:
CBitcoinAddress address(ks);
if (pwalletMain && address.IsValid()) {
CKeyID keyID;
if (!address.GetKeyID(keyID))
throw runtime_error(
strprintf("%s does not refer to a key", ks));
CPubKey vchPubKey;
if (!pwalletMain->GetPubKey(keyID, vchPubKey))
throw runtime_error(
strprintf("no full public key for address %s", ks));
if (!vchPubKey.IsFullyValid())
throw runtime_error(" Invalid public key: " + ks);
pubkeys[i] = vchPubKey;
}
// Case 2: hex public key
else
#endif
if (IsHex(ks)) {
CPubKey vchPubKey(ParseHex(ks));
if (!vchPubKey.IsFullyValid())
throw runtime_error(" Invalid public key: " + ks);
pubkeys[i] = vchPubKey;
} else {
throw runtime_error(" Invalid public key: " + ks);
}
}
CScript result = GetScriptForMultisig(nRequired, pubkeys);
if (result.size() > MAX_SCRIPT_ELEMENT_SIZE)
throw runtime_error(
strprintf("redeemScript exceeds size limit: %d > %d", result.size(), MAX_SCRIPT_ELEMENT_SIZE));
return result;
}
Value createmultisig(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 2) {
string msg = "createmultisig nrequired [\"key\",...]\n"
"\nCreates a multi-signature address with n signature of m keys required.\n"
"It returns a json object with the address and redeemScript.\n"
"\nArguments:\n"
"1. nrequired (numeric, required) The number of required signatures out of the n keys or addresses.\n"
"2. \"keys\" (string, required) A json array of keys which are socialtraders addresses or hex-encoded public keys\n"
" [\n"
" \"key\" (string) socialtraders address or hex-encoded public key\n"
" ,...\n"
" ]\n"
"\nResult:\n"
"{\n"
" \"address\":\"multisigaddress\", (string) The value of the new multisig address.\n"
" \"redeemScript\":\"script\" (string) The string value of the hex-encoded redemption script.\n"
"}\n"
"\nExamples:\n"
"\nCreate a multisig address from 2 addresses\n" +
HelpExampleCli("createmultisig", "2 \"[\\\"16sSauSf5pF2UkUwvKGq4qjNRzBZYqgEL5\\\",\\\"171sgjn4YtPu27adkKGrdDwzRTxnRkBfKV\\\"]\"") +
"\nAs a json rpc call\n" + HelpExampleRpc("createmultisig", "2, \"[\\\"16sSauSf5pF2UkUwvKGq4qjNRzBZYqgEL5\\\",\\\"171sgjn4YtPu27adkKGrdDwzRTxnRkBfKV\\\"]\"");
throw runtime_error(msg);
}
// Construct using pay-to-script-hash:
CScript inner = _createmultisig_redeemScript(params);
CScriptID innerID(inner);
CBitcoinAddress address(innerID);
Object result;
result.push_back(Pair("address", address.ToString()));
result.push_back(Pair("redeemScript", HexStr(inner.begin(), inner.end())));
return result;
}
Value verifymessage(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 3)
throw runtime_error(
"verifymessage \"socialtradersaddress\" \"signature\" \"message\"\n"
"\nVerify a signed message\n"
"\nArguments:\n"
"1. \"socialtradersaddress\" (string, required) The socialtraders address to use for the signature.\n"
"2. \"signature\" (string, required) The signature provided by the signer in base 64 encoding (see signmessage).\n"
"3. \"message\" (string, required) The message that was signed.\n"
"\nResult:\n"
"true|false (boolean) If the signature is verified or not.\n"
"\nExamples:\n"
"\nUnlock the wallet for 30 seconds\n" +
HelpExampleCli("walletpassphrase", "\"mypassphrase\" 30") +
"\nCreate the signature\n" + HelpExampleCli("signmessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\" \"my message\"") +
"\nVerify the signature\n" + HelpExampleCli("verifymessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\" \"signature\" \"my message\"") +
"\nAs json rpc\n" + HelpExampleRpc("verifymessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\", \"signature\", \"my message\""));
string strAddress = params[0].get_str();
string strSign = params[1].get_str();
string strMessage = params[2].get_str();
CBitcoinAddress addr(strAddress);
if (!addr.IsValid())
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address");
CKeyID keyID;
if (!addr.GetKeyID(keyID))
throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key");
bool fInvalid = false;
vector<unsigned char> vchSig = DecodeBase64(strSign.c_str(), &fInvalid);
if (fInvalid)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Malformed base64 encoding");
CHashWriter ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << strMessage;
CPubKey pubkey;
if (!pubkey.RecoverCompact(ss.GetHash(), vchSig))
return false;
return (pubkey.GetID() == keyID);
}
Value setmocktime(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"setmocktime timestamp\n"
"\nSet the local time to given timestamp (-regtest only)\n"
"\nArguments:\n"
"1. timestamp (integer, required) Unix seconds-since-epoch timestamp\n"
" Pass 0 to go back to using the system time.");
if (!Params().MineBlocksOnDemand())
throw runtime_error("setmocktime for regression testing (-regtest mode) only");
RPCTypeCheck(params, boost::assign::list_of(int_type));
SetMockTime(params[0].get_int64());
return Value::null;
}
#ifdef ENABLE_WALLET
Value getstakingstatus(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getstakingstatus\n"
"Returns an object containing various staking information.\n"
"\nResult:\n"
"{\n"
" \"validtime\": true|false, (boolean) if the chain tip is within staking phases\n"
" \"haveconnections\": true|false, (boolean) if network connections are present\n"
" \"walletunlocked\": true|false, (boolean) if the wallet is unlocked\n"
" \"mintablecoins\": true|false, (boolean) if the wallet has mintable coins\n"
" \"enoughcoins\": true|false, (boolean) if available coins are greater than reserve balance\n"
" \"mnsync\": true|false, (boolean) if masternode data is synced\n"
" \"staking status\": true|false, (boolean) if the wallet is staking or not\n"
"}\n"
"\nExamples:\n" +
HelpExampleCli("getstakingstatus", "") + HelpExampleRpc("getstakingstatus", ""));
Object obj;
obj.push_back(Pair("validtime", chainActive.Tip()->nTime > 1471482000));
obj.push_back(Pair("haveconnections", !vNodes.empty()));
if (pwalletMain) {
obj.push_back(Pair("walletunlocked", !pwalletMain->IsLocked()));
obj.push_back(Pair("mintablecoins", pwalletMain->MintableCoins()));
obj.push_back(Pair("enoughcoins", nReserveBalance <= pwalletMain->GetBalance()));
}
obj.push_back(Pair("mnsync", masternodeSync.IsSynced()));
bool nStaking = false;
if (mapHashedBlocks.count(chainActive.Tip()->nHeight))
nStaking = true;
else if (mapHashedBlocks.count(chainActive.Tip()->nHeight - 1) && nLastCoinStakeSearchInterval)
nStaking = true;
obj.push_back(Pair("staking status", nStaking));
return obj;
}
#endif // ENABLE_WALLET
| [
"skyler@ruffa-karting.fr"
] | skyler@ruffa-karting.fr |
f8718b83e034497e502ea8f96915ac03e8ee0562 | fa3b89c5ead0d403f7db4be81f791a272f4fe62e | /alg/poj/archive/2253/7313099_AC_16MS_552K.cpp | f608133d67a0ca178762bc8e5a35f8eeee38890d | [] | no_license | ruleless/programming | aa32e916a5b3792ead2a6d48ab924d3554cd085f | c381d1ef7b1c7c0aff17603484e19a027593429b | refs/heads/master | 2022-11-14T02:07:47.443657 | 2022-11-03T23:47:32 | 2022-11-03T23:47:32 | 86,163,253 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,478 | cpp | #include <iostream>
#include <cstdio>
#include <cmath>
#include <queue>
using namespace std;
struct Point
{
double x,y;
}p[205];
#define MAX 10e20
double edge[205][205],closedge[205];
bool vis[205];
int n;
struct Node
{
int u;
double d;
bool operator<(const struct Node a)const
{
return d>a.d;
}
}t1,t2;
priority_queue<struct Node>que;
double prim()
{
int i,j;
double k=0;
while(!que.empty())
{
que.pop();
}
for(i=1;i<=n;i++)
{
closedge[i]=MAX;
}
closedge[1]=0;
memset(vis,0,sizeof(vis));
t1.u=1;
t1.d=0;
que.push(t1);
while(!que.empty())
{
t1=que.top();
que.pop();
int u=t1.u;
if(vis[u])
{
continue;
}
vis[u]=true;
if(closedge[u]>k)
{
k=closedge[u];
}
if(u==2)
{
return k;
}
for(i=1;i<=n;i++)
{
if(!vis[i]&&edge[u][i]<closedge[i])
{
closedge[i]=edge[u][i];
t2.u=i;
t2.d=closedge[i];
que.push(t2);
}
}
}
}
void solve(int cse)
{
int i,j,k;
printf("Scenario #%d\nFrog Distance = %.3lf\n\n",cse,prim());
}
int main()
{
// freopen("in.txt","r",stdin);
int i,j,k=0;
while(scanf("%d",&n)!=EOF&&n)
{
k++;
for(i=1;i<=n;i++)
{
scanf("%lf%lf",&p[i].x,&p[i].y);
}
for(i=1;i<=n;i++)
{
for(j=i+1;j<=n;j++)
{
edge[i][j]=sqrt( (p[i].x-p[j].x)*(p[i].x-p[j].x)+(p[i].y-p[j].y)*(p[i].y-p[j].y) );
edge[j][i]=edge[i][j];
}
}
solve(k);
}
return 0;
} | [
"ruleless@126.com"
] | ruleless@126.com |
bfeb4d418f80d4bb99aa9515c9ffcea4eadd6ed8 | d375044c336585980b2a6b2e2bf6a3fe10d72fe2 | /Controller/HikerController/PlayerHikerController.cpp | 40487677dfa6630f016612c4af3f088e41833b7d | [] | no_license | Cbcasper/TurboHiker | 5a7cabcd4772343a782fe6371e52eac7dce8c3cf | 8329ec967725235e35c690bfbf63acd0581f65f1 | refs/heads/main | 2023-02-19T18:59:06.527995 | 2021-01-17T22:50:06 | 2021-01-17T22:50:06 | 320,257,426 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,682 | cpp | //
// Created by Casper De Smet on 20/12/2020.
//
#include "PlayerHikerController.h"
#include "../World.h"
using namespace std;
namespace turboHiker
{
// The player hiker is not halted at the start
PlayerHikerController::PlayerHikerController(const std::weak_ptr<World>& world, int index): HikerController(world, index), halted(false)
{
}
void PlayerHikerController::live()
{
while (living)
{
// Raise event to move the hiker forward
if (moving)
world.lock()->handleEvent(make_shared<Event>(Event::MoveForward, hikerIndex));
// If the hiker is halted, it is not on time out so it doesn't need to handle the time out logic
else if (!halted)
{
// Be on time out
if (onTimeOutFor < timeOut)
onTimeOutFor += interval;
else
{
// Reset time out and start moving again
onTimeOutFor = 0;
moving = true;
world.lock()->handleEvent(make_shared<Event>(Event::StartMoving, hikerIndex));
}
}
this_thread::sleep_for(chrono::milliseconds(interval));
}
}
void PlayerHikerController::handleEvent(const shared_ptr<Event>& event)
{
HikerController::handleEvent(event);
switch (event->eventType)
{
// Set halted accordingly
case Event::HaltHiker: halted = true; break;
case Event::LetGoHiker: halted = false; break;
default: break;
}
}
} | [
"casper.desmet@student.uantwerpen.be"
] | casper.desmet@student.uantwerpen.be |
3565de8ce03b6245cc37d6d589e13aa881df884b | cf5f24e5a32f8cafe90d4253d727b1c0457da6a4 | /algorithm/boj_14729.cpp | 6cc804ba5873fa8d0843f992e0c477d2162c5545 | [] | no_license | seoljeongwoo/learn | 537659ca942875f6846646c2e21e1e9f2e5b811e | 5b423e475c8f2bc47cb6dee09b8961d83ab08568 | refs/heads/main | 2023-05-04T18:07:27.592058 | 2021-05-05T17:32:50 | 2021-05-05T17:32:50 | 324,725,000 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 367 | cpp | #include <iostream>
using namespace std;
int n ,t , a[105][2],dp[10005];
int main(){
ios_base::sync_with_stdio(false);
cin.tie(0);
cin >> n >> t;
for(int i=1; i<=n; i++){
cin >> a[i][0] >> a[i][1];
}
for(int i=1; i<=n; i++){
for(int j=t; j>=a[i][0];j--) dp[j] = max(dp[j] , dp[j-a[i][0]] + a[i][1]);
}
cout << dp[t];
} | [
"noreply@github.com"
] | seoljeongwoo.noreply@github.com |
5982563093d2fa8a4627b3554def2e633fcb3255 | f8c74e42ce654749f854c8e80572ea345728675b | /assignment_4/8_1/main.cpp | 0006b58680258bcc1634e9b572ef68453f727d5e | [] | no_license | SVizor42/made_2019_algo | b12a75019fa0bfbf88a78c4929a1b392353636e6 | 36f100645e4233968e8b2c7cb3ae0ffcdcc4ee65 | refs/heads/master | 2020-09-07T01:18:52.983106 | 2019-12-30T14:18:14 | 2019-12-30T14:18:14 | 220,606,023 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,135 | cpp | /*
8. Хеш-таблица
Реализуйте структуру данных типа “множество строк” на основе динамической хеш-таблицы с открытой адресацией. Хранимые строки непустые и состоят из строчных латинских букв. Хеш-функция строки должна быть реализована с помощью вычисления значения многочлена методом Горнера. Начальный размер таблицы должен быть равным 8-ми. Перехеширование выполняйте при добавлении элементов в случае, когда коэффициент заполнения таблицы достигает 3/4. Структура данных должна поддерживать операции добавления строки в множество, удаления строки из множества и проверки принадлежности данной строки множеству.
1_1. Для разрешения коллизий используйте квадратичное пробирование. i-ая проба g(k, i)=g(k, i-1) + i (mod m). m - степень двойки.
*/
#include <assert.h>
#include <iostream>
#include <string>
#include <vector>
const size_t a = 31;
struct Hash {
size_t operator()(const std::string& key, size_t size) {
size_t hash = 0;
for (char sym: key) {
hash = (hash * a + sym) % size;
}
return hash;
}
};
template <class T, class THash>
class HashTable {
public:
explicit HashTable(size_t initial_size, T init_empty, T init_deleted);
HashTable(const HashTable&) = delete;
HashTable(HashTable&&) = delete;
HashTable& operator=(const HashTable&) = delete;
HashTable& operator=(HashTable&&) = delete;
bool Has(const T& key) const;
bool Add(const T& key);
bool Remove(const T& key);
private:
void Rehash();
std::vector<T> table;
size_t table_size = 0;
T empty;
T deleted;
};
template <class T, class THash>
HashTable<T, THash>::HashTable(size_t initial_size, T init_empty, T init_deleted)
: empty(init_empty)
, deleted(init_deleted)
{
table = std::vector<T>(initial_size, empty);
}
template <class T, class THash>
bool HashTable<T, THash>::Has(const T& key) const {
assert(key != empty);
THash hash_func;
size_t hash = hash_func(key, table.size()), iter = 0;
while (table[hash] != empty && table[hash] != deleted) {
if (table[hash] == key)
return true;
iter++;
hash = (hash + iter + 1) % table.size();
}
return false;
}
template <class T, class THash>
bool HashTable<T, THash>::Add(const T& key) {
assert(key != empty);
if (key == deleted)
return false;
if (4 * table_size >= 3 * table.size())
Rehash();
THash hash_func;
size_t hash = hash_func(key, table.size()), iter = 0;
int index = -1;
while (iter < table.size()) {
if (table[hash] == empty) {
table[hash] = key;
table_size++;
return true;
}
if (table[hash] == key)
return false;
if (table[hash] == deleted && index < 0)
index = hash;
iter++;
hash = (hash + iter + 1) % table.size();
}
if (index >= 0) {
table[hash] = key;
table_size++;
return true;
}
return false;
}
template <class T, class THash>
bool HashTable<T, THash>::Remove(const T& key) {
assert(key != empty);
if (key == deleted)
return false;
THash hash_func;
size_t hash = hash_func(key, table.size()), iter = 0;
while (table[hash] != empty) {
if (table[hash] == key) {
table[hash] = deleted;
table_size--;
return true;
}
iter++;
hash = (hash + iter + 1) % table.size();
}
return false;
}
template <class T, class THash>
void HashTable<T, THash>::Rehash() {
HashTable new_table(2 * table.size(), empty, deleted);
for (size_t i = 0; i < table.size(); i++) {
if (table[i] != empty && table[i] != deleted)
new_table.Add(table[i]);
}
this->table = std::move(new_table.table);
this->table_size = new_table.table_size;
}
int main() {
HashTable<std::string, Hash> table(8, "", "Deleted");
char command = ' ';
std::string value;
while (std::cin >> command >> value) {
switch (command) {
case '?':
std::cout << (table.Has(value) ? "OK" : "FAIL") << std::endl;
break;
case '+':
std::cout << (table.Add(value) ? "OK" : "FAIL") << std::endl;
break;
case '-':
std::cout << (table.Remove(value) ? "OK" : "FAIL") << std::endl;
break;
}
}
return 0;
}
| [
"noreply@github.com"
] | SVizor42.noreply@github.com |
b7a8371375d3464162ccedcd392b75ca5f0802dd | 9f106e650913d490743630f48f4110879302f0e0 | /OgreView/OgreCharacterView.h | f1c9234ff87250d4e13681f6fe159d996aac067e | [
"MIT"
] | permissive | sereslorant/ninja_killer | 8d13c8ae2a19935545650f35b377544303e03300 | 7a4def966720eb9b396f3424f8a536a14e61e41d | refs/heads/master | 2021-08-30T08:11:47.475730 | 2017-12-16T23:54:39 | 2017-12-16T23:54:39 | 111,324,247 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,534 | h | #ifndef OGRE_CHARACTER_VIEW_H
#define OGRE_CHARACTER_VIEW_H
#include <GameLogic/IGameObserver.h>
#include "OgreEntityRepository.h"
#include <OGRE/OgreEntity.h>
#include <OGRE/OgreSceneNode.h>
#include "OgreAnimation/CharacterAnimator.h"
#include "AnimationState/CompositeAnimationState.h"
#include "AnimationState/PrimitiveAnimationState.h"
class OgreCharacterView : public ICharacterObserver
{
private:
OgreEntityRepository &entity_repository;
bool initialized = false;
Ogre::Entity *character_entity = nullptr;
Ogre::SceneNode *character_entity_node = nullptr;
Ogre::SceneNode &entity_node;
CharacterAnimator leg_animator;
std::list<std::unique_ptr<IAnimationState> > leg_children;
IAnimationState *leg_root;
CharacterAnimator up_animator;
std::list<std::unique_ptr<IAnimationState> > up_children;
IAnimationState *up_root;
public:
virtual void OnLabelChanged(const std::string &name) override
{
initialized = false;
if(character_entity != nullptr && character_entity_node != nullptr)
{
entity_node.removeChild(character_entity_node);
entity_repository.DestroyEntity(character_entity_node,character_entity);
}
initialized = false;
std::tie(character_entity_node,character_entity) = entity_repository.CreateEntity(name);
character_entity->getSkeleton()->setBlendMode(Ogre::SkeletonAnimationBlendMode::ANIMBLEND_CUMULATIVE);
entity_node.addChild(character_entity_node);
leg_animator = entity_repository.GetLegAnimator(name);
up_animator = entity_repository.GetBodyAnimator(name);
leg_children.clear();
up_children.clear();
auto leg_anim_state = entity_repository.GetLegAnimState(name);
if(leg_anim_state != nullptr)
{
leg_root = leg_anim_state->Clone(leg_children);
}
else
{
leg_root = nullptr;
}
auto up_anim_state = entity_repository.GetBodyAnimState(name);
if(up_anim_state != nullptr)
{
up_root = up_anim_state->Clone(up_children);
}
else
{
up_root = nullptr;
}
}
virtual void OnPositionChanged(float x,float y,float z) override
{
entity_node.setPosition(x,y,z);
}
virtual void OnOrientationChanged(float w,float x,float y,float z) override
{
entity_node.setOrientation(w,x,y,z);
}
virtual void OnStanding() override
{
if(leg_root != nullptr)
{leg_root->UpdateState("OnStanding");}
if(up_root != nullptr)
{up_root->UpdateState("OnStanding");}
}
virtual void OnMoving() override
{
if(leg_root != nullptr)
{leg_root->UpdateState("OnMoving");}
if(up_root != nullptr)
{up_root->UpdateState("OnMoving");}
}
virtual void OnAiming() override
{
if(leg_root != nullptr)
{leg_root->UpdateState("OnAiming");}
if(up_root != nullptr)
{up_root->UpdateState("OnAiming");}
}
virtual void OnAimReleased() override
{
if(leg_root != nullptr)
{leg_root->UpdateState("OnAimReleased");}
if(up_root != nullptr)
{up_root->UpdateState("OnAimReleased");}
}
virtual void OnMelee() override
{
if(leg_root != nullptr)
{leg_root->UpdateState("OnMelee");}
if(up_root != nullptr)
{up_root->UpdateState("OnMelee");}
}
virtual void OnMeleeReleased() override
{
if(leg_root != nullptr)
{leg_root->UpdateState("OnMeleeReleased");}
if(up_root != nullptr)
{up_root->UpdateState("OnMeleeReleased");}
}
virtual void OnShooting() override
{
if(leg_root != nullptr)
{leg_root->UpdateState("OnShooting");}
if(up_root != nullptr)
{up_root->UpdateState("OnShooting");}
/*
if(leg_root != nullptr)
{leg_root->UpdateState("OnDying");}
if(up_root != nullptr)
{up_root->UpdateState("OnDying");}
*/
}
virtual void OnShootingReleased() override
{
if(leg_root != nullptr)
{leg_root->UpdateState("OnShootingReleased");}
if(up_root != nullptr)
{up_root->UpdateState("OnShootingReleased");}
}
virtual void OnDying() override
{
if(leg_root != nullptr)
{leg_root->UpdateState("OnDying");}
if(up_root != nullptr)
{up_root->UpdateState("OnDying");}
}
void Update()
{
if(leg_root != nullptr)
{
leg_animator.Visit(*leg_root,character_entity);
leg_animator.Animate(character_entity);
}
if(up_root != nullptr)
{
up_animator.Visit(*up_root,character_entity);
up_animator.Animate(character_entity);
}
}
OgreCharacterView(OgreEntityRepository &p_entity_repository,Ogre::SceneNode &p_entity_node)
:entity_repository(p_entity_repository),entity_node(p_entity_node)
{}
virtual ~OgreCharacterView() override
{}
};
#endif // OGRE_CHARACTER_VIEW_H
| [
"sereslorant@gmail.com"
] | sereslorant@gmail.com |
d860729491bfd2800bd168a5aad604e2f25b29f5 | 4d815360a103946d046998458292ac50edd024e9 | /Networking/Server.cpp | d3e84ce541fe694de862bd9309b0d4a6a33a209c | [] | no_license | KingFroz/CodeSnippets | d535160b54888ad9dbf8b2895aa757100ce6bfbe | 54d1eb2fb502819b6b4e76033be0b46b3c4a49e0 | refs/heads/master | 2021-04-12T07:27:21.408941 | 2018-07-17T15:04:42 | 2018-07-17T15:04:42 | 94,508,851 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,696 | cpp | // Server.cpp : Contains all functions of the server.
#include "Server.h"
// Initializes the server. (NOTE: Does not wait for player connections!)
int Server::init(uint16_t port)
{
initState();
// TODO:
// 1) Set up a socket for listening.
// 2) Mark the server as active.
svSocket = INVALID_SOCKET;
svSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (svSocket == INVALID_SOCKET)
return SETUP_ERROR;
sockaddr_in sA;
sA.sin_family = AF_INET;
sA.sin_port = htons(port);
sA.sin_addr.S_un.S_addr = INADDR_ANY;
if (sA.sin_addr.S_un.S_addr == INADDR_NONE)
return ADDRESS_ERROR;
if (bind(svSocket, (sockaddr*)&sA, sizeof(sA)) == SOCKET_ERROR)
return BIND_ERROR;
if (ioctlsocket(svSocket, FIONBIO, &lock))
return SETUP_ERROR;
bool active = true;
clientSequence = 0;
return SUCCESS;
}
// Updates the server; called each game "tick".
int Server::update()
{
// TODO:
// 1) Get player input and process it.
// 2) If any player's timer exceeds 50, "disconnect" the player.
// 3) Update the state and send the current snapshot to each player.
NetworkMessage msg(_INPUT);
sockaddr_in getAddr;
int Hresult = recvfromNetMessage(svSocket, msg, &getAddr);
if (Hresult <= 0)
{
if (WSAGetLastError() != EWOULDBLOCK)
return SHUTDOWN;
}
else
{
parseMessage(getAddr, msg);
}
for (int i = 0; i < noOfPlayers; i++)
{
if (playerTimer[i] > 50)
{
disconnectClient(i);
}
}
updateState();
sendState();
return SUCCESS;
}
// Stops the server.
void Server::stop()
{
// TODO:
// 1) Sends a "close" message to each client.
// 2) Shuts down the server gracefully (update method should exit with SHUTDOWN code.)
sendClose();
shutdown(svSocket, SD_BOTH);
closesocket(svSocket);
}
// Parses a message and responds if necessary. (private, suggested)
int Server::parseMessage(sockaddr_in& source, NetworkMessage& message)
{
// TODO: Parse a message from client "source."
NetworkMessage output(_OUTPUT);
uint8_t keyUp;
uint8_t keyDown;
uint8_t user;
int player = 0;
if (source.sin_port == playerAddress[0].sin_port && playerAddress[0].sin_addr.S_un.S_addr == source.sin_addr.S_un.S_addr)
{
player = 0;
}
else if (source.sin_port == playerAddress[1].sin_port && playerAddress[0].sin_addr.S_un.S_addr == source.sin_addr.S_un.S_addr)
{
player = 1;
}
char type = message.readByte();
switch (type)
{
case CL_CONNECT:
if (noOfPlayers < 2)
{
sendOkay(source);
user = message.readByte();
connectClient(user, source);
}
else
{
sendFull(source);
}
break;
case CL_KEYS:
keyUp = message.readByte();
keyDown = message.readByte();
if (player == 0)
{
state.player0.keyUp = keyUp;
state.player0.keyDown = keyDown;
}
else if (player == 1)
{
state.player1.keyUp = keyUp;
state.player1.keyDown = keyDown;
}
break;
case CL_ALIVE:
if (player == 0)
playerTimer[player] = 0;
else if (player == 1)
{
playerTimer[player] = 0;
}
break;
case SV_CL_CLOSE:
disconnectClient(player);
break;
}
return SUCCESS;
}
// Sends the "SV_OKAY" message to destination. (private, suggested)
int Server::sendOkay(sockaddr_in& destination)
{
// TODO: Send "SV_OKAY" to the destination.
NetworkMessage output(_OUTPUT);
output.writeShort(clientSequence);
output.writeByte(SV_OKAY);
int iResult = sendMessage(destination, output);
return SUCCESS;
}
// Sends the "SV_FULL" message to destination. (private, suggested)
int Server::sendFull(sockaddr_in& destination)
{
// TODO: Send "SV_FULL" to the destination.
NetworkMessage output(_OUTPUT);
output.writeShort(clientSequence);
output.writeByte(SV_FULL);
int iResult = sendMessage(destination, output);
return SUCCESS;
}
// Sends the current snapshot to all players. (private, suggested)
int Server::sendState()
{
// TODO: Send the game state to each client.
for (int i = 0; i < noOfPlayers; i++)
{
uint8_t type = SV_SNAPSHOT;
uint8_t phase = state.gamePhase;
int16_t ballX = state.ballX;
int16_t ballY = state.ballY;
int16_t p0_y = state.player0.y;
int16_t p0_Score = state.player0.score;
int16_t p1_y = state.player1.y;
int16_t p1_Score = state.player1.score;
NetworkMessage output(_OUTPUT);
output.writeShort(clientSequence);
output.writeByte(type);
output.writeByte(phase);
output.writeShort(ballX);
output.writeShort(ballY);
output.writeShort(p0_y);
output.writeShort(p0_Score);
output.writeShort(p1_y);
output.writeShort(p1_Score);
int iResult = sendMessage(playerAddress[i], output);
}
return SUCCESS;
}
// Sends the "SV_CL_CLOSE" message to all clients. (private, suggested)
void Server::sendClose()
{
// TODO: Send the "SV_CL_CLOSE" message to each client
for (int i = 0; i < noOfPlayers; i++)
{
NetworkMessage output(_OUTPUT);
output.writeShort(clientSequence);
output.writeByte(SV_CL_CLOSE);
int iResult = sendMessage(playerAddress[i], output);
}
}
// Server message-sending helper method. (private, suggested)
int Server::sendMessage(sockaddr_in& destination, NetworkMessage& message)
{
// TODO: Send the message in the buffer to the destination.
if (sendtoNetMessage(svSocket, message, &destination) <= 0) { return MESSAGE_ERROR; }
clientSequence++;
return SUCCESS;
}
// Marks a client as connected and adjusts the game state.
void Server::connectClient(int player, sockaddr_in& source)
{
playerAddress[player] = source;
playerTimer[player] = 0;
noOfPlayers++;
if (noOfPlayers == 1)
state.gamePhase = WAITING;
else
state.gamePhase = RUNNING;
}
// Marks a client as disconnected and adjusts the game state.
void Server::disconnectClient(int player)
{
playerAddress[player].sin_addr.s_addr = INADDR_NONE;
playerAddress[player].sin_port = 0;
noOfPlayers--;
if (noOfPlayers == 1)
state.gamePhase = WAITING;
else
state.gamePhase = DISCONNECTED;
}
// Updates the state of the game.
void Server::updateState()
{
// Tick counter.
static int timer = 0;
// Update the tick counter.
timer++;
// Next, update the game state.
if (state.gamePhase == RUNNING)
{
// Update the player tick counters (for ALIVE messages.)
playerTimer[0]++;
playerTimer[1]++;
// Update the positions of the player paddles
if (state.player0.keyUp)
state.player0.y--;
if (state.player0.keyDown)
state.player0.y++;
if (state.player1.keyUp)
state.player1.y--;
if (state.player1.keyDown)
state.player1.y++;
// Make sure the paddle new positions are within the bounds.
if (state.player0.y < 0)
state.player0.y = 0;
else if (state.player0.y > FIELDY - PADDLEY)
state.player0.y = FIELDY - PADDLEY;
if (state.player1.y < 0)
state.player1.y = 0;
else if (state.player1.y > FIELDY - PADDLEY)
state.player1.y = FIELDY - PADDLEY;
//just in case it get stuck...
if (ballVecX)
storedBallVecX = ballVecX;
else
ballVecX = storedBallVecX;
if (ballVecY)
storedBallVecY = ballVecY;
else
ballVecY = storedBallVecY;
state.ballX += ballVecX;
state.ballY += ballVecY;
// Check for paddle collisions & scoring
if (state.ballX < PADDLEX)
{
// If the ball has struck the paddle...
if (state.ballY + BALLY > state.player0.y && state.ballY < state.player0.y + PADDLEY)
{
state.ballX = PADDLEX;
ballVecX *= -1;
}
// Otherwise, the second player has scored.
else
{
newBall();
state.player1.score++;
ballVecX *= -1;
}
}
else if (state.ballX >= FIELDX - PADDLEX - BALLX)
{
// If the ball has struck the paddle...
if (state.ballY + BALLY > state.player1.y && state.ballY < state.player1.y + PADDLEY)
{
state.ballX = FIELDX - PADDLEX - BALLX - 1;
ballVecX *= -1;
}
// Otherwise, the first player has scored.
else
{
newBall();
state.player0.score++;
ballVecX *= -1;
}
}
// Check for Y position "bounce"
if (state.ballY < 0)
{
state.ballY = 0;
ballVecY *= -1;
}
else if (state.ballY >= FIELDY - BALLY)
{
state.ballY = FIELDY - BALLY - 1;
ballVecY *= -1;
}
}
// If the game is over...
if ((state.player0.score > 10 || state.player1.score > 10) && state.gamePhase == RUNNING)
{
state.gamePhase = GAMEOVER;
timer = 0;
}
if (state.gamePhase == GAMEOVER)
{
if (timer > 30)
{
initState();
state.gamePhase = RUNNING;
}
}
}
// Initializes the state of the game.
void Server::initState()
{
playerAddress[0].sin_addr.s_addr = INADDR_NONE;
playerAddress[1].sin_addr.s_addr = INADDR_NONE;
playerTimer[0] = playerTimer[1] = 0;
noOfPlayers = 0;
state.gamePhase = DISCONNECTED;
state.player0.y = 0;
state.player1.y = FIELDY - PADDLEY - 1;
state.player0.score = state.player1.score = 0;
state.player0.keyUp = state.player0.keyDown = false;
state.player1.keyUp = state.player1.keyDown = false;
newBall(); // Get new random ball position
// Get a new random ball vector that is reasonable
ballVecX = (rand() % 10) - 5;
if ((ballVecX >= 0) && (ballVecX < 2))
ballVecX = 2;
if ((ballVecX < 0) && (ballVecX > -2))
ballVecX = -2;
ballVecY = (rand() % 10) - 5;
if ((ballVecY >= 0) && (ballVecY < 2))
ballVecY = 2;
if ((ballVecY < 0) && (ballVecY > -2))
ballVecY = -2;
}
// Places the ball randomly within the middle half of the field.
void Server::newBall()
{
// (randomly in 1/2 playable area) + (1/4 playable area) + (left buffer) + (half ball)
state.ballX = (rand() % ((FIELDX - 2 * PADDLEX - BALLX) / 2)) +
((FIELDX - 2 * PADDLEX - BALLX) / 4) + PADDLEX + (BALLX / 2);
// (randomly in 1/2 playable area) + (1/4 playable area) + (half ball)
state.ballY = (rand() % ((FIELDY - BALLY) / 2)) + ((FIELDY - BALLY) / 4) + (BALLY / 2);
}
| [
"lvharding@fullsail.edu"
] | lvharding@fullsail.edu |
209b1e6a9b094257383871a1ec123b1f2ab7bd08 | 382399c7d31febd04c0344202550c3b574bd4891 | /BeyondNaos/BeyondNaos/PurpleHeart.h | 3e1bba48ba6d2e02ab6b46b68e6ea6535a620bb5 | [] | no_license | m-murtaza75/LIT-Year3-BeyondNaos | a35fa7f134e8803f97d282d23313f7474d9c8c68 | 773db43973ca74ef994496aed6100618589a1f3e | refs/heads/main | 2022-12-25T08:02:17.046804 | 2020-10-05T19:01:20 | 2020-10-05T19:01:20 | 301,465,232 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 282 | h | #pragma once
#include "MapObject.h"
class PurpleHeart : public MapObject
{
public:
PurpleHeart(TileMap& tm);
void Update(float frametime);
void Draw(sf::RenderWindow *window);
private:
std::vector<sf::IntRect*> sprites;
sf::Texture *t;
sf::Sprite *s;
sf::IntRect *rect;
}; | [
"m.murt75@gmail.com"
] | m.murt75@gmail.com |
3bba7d0ba6a1b7f12a84e6aeee2eb5b2b6e9f367 | 672a3c9372c8e6c1c38c272404ddb12ec0bc0a1d | /semestre_03/SCC0210_algoritmos_avancados/2020_contest_b2w_semcomp/B.cpp | 08cfc813ae8474762a878d364395272b51948e3e | [] | no_license | GabrielVanLoon/Graduacao_BCC | 084de6ba4d374fae98548e503bbe38411b8a53b2 | fb078bdce3aafdc76ecc42a8725ce53cee6bdb1e | refs/heads/master | 2023-08-30T05:43:55.055216 | 2021-11-18T18:59:25 | 2021-11-18T18:59:25 | 171,961,616 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 268 | cpp | #include <cstdio>
#include <iostream>
#include <cstring>
using namespace std;
int main(){
string a;
cin >> a;
int count = 0;
for(int i = 0, j = a.length() - 1; i < j; i++, j--) count += a[i] != a[j];
cout << count << endl;
return 0;
} | [
"gabriel.vl.rojas@gmail.com"
] | gabriel.vl.rojas@gmail.com |
9b78677debe0eca1a93c5872acebfa3188b0973d | cb3f96fe38ff599c381efd69eb2db19b39202248 | /lexer/MiscTextUtil.cpp | 2ce5dd753e49504f6ae53bfcf3cb332813a43124 | [] | no_license | CollinReeser/ParsingLanguage | d23111c6bbcbefe1f3f8e3fb6f1acb475011e425 | 9989042a833170eb83db6b5decf1affd9c3ff344 | refs/heads/master | 2021-01-10T18:36:59.206596 | 2012-09-14T08:08:30 | 2012-09-14T08:08:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,015 | cpp |
#include "SimpleTextUtil.h"
bool SimpleTextUtil::isOperatorT( char operatorCandidate )
{
switch ( operatorCandidate )
{
//case '+':
//case '-':
case '*':
//case '/':
case '=':
case '(':
case ')':
//case '<':
case '>':
case ';':
case '"':
case '%':
case '&':
case '\'':
case '.':
case '[':
case ']':
case '{':
case '}':
case '|':
case '^':
//case '~':
case ':':
case ',':
case '@':
case '#':
case '!':
return true;
default:
return false;
}
}
std::string SimpleTextUtil::stripWhitespace(std::string str)
{
for ( int i = 0; i < str.size(); i++ )
{
if ( str.at(i) == ' ' || str.at(i) == '\t' || str.at(i) == '\n' ||
str.at(i) == '\r' )
{
str.erase( str.begin() + i );
i--;
}
else
{
break;
}
}
for ( int i = str.size() - 1; i > -1; i-- )
{
if ( str.at(i) == ' ' || str.at(i) == '\t' || str.at(i) == '\n' ||
str.at(i) == '\r')
{
str.erase( str.end() - i );
i--;
}
else
{
break;
}
}
return str;
}
| [
"collin.reeser@gmail.com"
] | collin.reeser@gmail.com |
44dbb6a2297d39838140134917e137807bb6ce34 | e54f183bc12485af1c74f9ce862aa884587305d7 | /Cpp_Tut/Hello_World/Hello_World/Eingabe.cpp | 0d7d18d04732c6303596fdf16aae55c37ebf2b0f | [] | no_license | Genotic/Cpp_Tutorial | 8f58443fc70b002558752dfa994ba14551b193e5 | 1da7d8b2bb4c461eeb3b440eb547047269abf3c8 | refs/heads/master | 2020-03-28T17:04:18.607932 | 2018-10-01T09:33:12 | 2018-10-01T09:33:12 | 148,755,737 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 312 | cpp |
#include "pch.h"
#include <iostream>
#include <string>
int main()
{
std::string vorname;
std::string nachname;
std::cout << "Bitt geben Sie Ihren Vor- und Nachnamen ein!" << std::endl;
std::cin >> vorname;
std::cin >> nachname;
std::cout << "Sie heissen " << vorname << " " << nachname << std::endl;
} | [
"Genotic@gmx.de"
] | Genotic@gmx.de |
059efe18aedf181304302e9801fef541f23985b3 | 2639807d92c8ecd54b6e135660752a922a1b6e10 | /branches/stefanvt/Fog/Fog/Core/Char.h | 1fdaa8980dcb1b3f7901809d7f948ed4819f982f | [
"LicenseRef-scancode-boost-original",
"LicenseRef-scancode-public-domain",
"BSD-3-Clause",
"MIT",
"X11",
"HPND"
] | permissive | prepare/fog | b9fe3e5d409790ad49760901787d29a9a9195eed | a554c3dd422ee34130be9c5edfb521ec940ef139 | refs/heads/master | 2020-07-18T11:33:23.604140 | 2016-11-16T13:06:53 | 2016-11-16T13:06:53 | 73,920,391 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 11,207 | h | // [Fog-Core Library - Public API]
//
// [License]
// MIT, See COPYING file in package
// [Guard]
#ifndef _FOG_CORE_CHAR_H
#define _FOG_CORE_CHAR_H
// [Dependencies]
#include <Fog/Build/Build.h>
#include <Fog/Core/Assert.h>
#include <Fog/Core/CharUtil.h>
#include <Fog/Core/Memory.h>
#include <Fog/Core/TypeInfo.h>
//! @defgroup Core
//! @{
namespace Fog {
// ============================================================================
// [Fog::Char]
// ============================================================================
#include <Fog/Core/Compiler/PackByte.h>
//! @brief 16-bit unicode character.
struct FOG_HIDDEN Char
{
// [Construction / Destruction]
FOG_INLINE Char() {}
FOG_INLINE Char(const Char& c) : _ch(c._ch) {}
FOG_INLINE explicit Char(char c) : _ch((uint8_t)c) {}
FOG_INLINE explicit Char(uint8_t c) : _ch(c) {}
FOG_INLINE explicit Char(int16_t c) : _ch((uint16_t)c) {}
FOG_INLINE explicit Char(uint16_t c) : _ch(c) {}
FOG_INLINE explicit Char(int32_t c) : _ch((uint16_t)(uint32_t)c) {}
FOG_INLINE explicit Char(uint32_t c) : _ch((uint16_t)c) {}
// [Character]
//! @brief Return 16-bit character value.
FOG_INLINE uint16_t ch() const { return _ch; }
// [Char::operator=]
FOG_INLINE Char& operator=(const char& ch) { _ch = (uint8_t )ch ; return *this; }
FOG_INLINE Char& operator=(const uint8_t& ch) { _ch = ch ; return *this; }
FOG_INLINE Char& operator=(const int16_t& ch) { _ch = (uint16_t)ch ; return *this; }
FOG_INLINE Char& operator=(const uint16_t& ch) { _ch = ch ; return *this; }
FOG_INLINE Char& operator=(const int32_t& ch) { _ch = (uint16_t)(uint32_t)ch; return *this; }
FOG_INLINE Char& operator=(const uint32_t& ch) { _ch = (uint16_t)ch ; return *this; }
FOG_INLINE Char& operator=(const Char& ch) { _ch = ch._ch ; return *this; }
// [Implicit Conversion]
FOG_INLINE operator bool() const { return _ch != 0; }
FOG_INLINE operator int16_t() const { return (int16_t)_ch; }
FOG_INLINE operator uint16_t() const { return (uint16_t)_ch; }
FOG_INLINE operator int32_t() const { return (int32_t)_ch; }
FOG_INLINE operator uint32_t() const { return (uint32_t)_ch; }
// [Ascii CTypes]
FOG_INLINE bool isAsciiAlpha() const { return CharUtil::isAsciiAlpha(_ch); }
FOG_INLINE bool isAsciiAlnum() const { return CharUtil::isAsciiAlnum(_ch); }
FOG_INLINE bool isAsciiLower() const { return CharUtil::isAsciiLower(_ch); }
FOG_INLINE bool isAsciiUpper() const { return CharUtil::isAsciiUpper(_ch); }
FOG_INLINE bool isAsciiDigit() const { return CharUtil::isAsciiDigit(_ch); }
FOG_INLINE bool isAsciiXDigit()const { return CharUtil::isAsciiXDigit(_ch); }
FOG_INLINE bool isAsciiSpace() const { return CharUtil::isAsciiSpace(_ch); }
FOG_INLINE bool isAsciiBlank() const { return CharUtil::isAsciiSpace(_ch); }
FOG_INLINE bool isAsciiPunct() const { return CharUtil::isAsciiPunct(_ch); }
FOG_INLINE bool isAsciiGraph() const { return CharUtil::isAsciiGraph(_ch); }
FOG_INLINE bool isAsciiPrint() const { return CharUtil::isAsciiPrint(_ch); }
FOG_INLINE Char toAsciiLower() const { return Char(CharUtil::toAsciiLower(_ch)); }
FOG_INLINE Char toAsciiUpper() const { return Char(CharUtil::toAsciiUpper(_ch)); }
// Statics.
static FOG_INLINE bool isAsciiAlpha(uint16_t ch) { return CharUtil::isAsciiAlpha(ch); }
static FOG_INLINE bool isAsciiAlnum(uint16_t ch) { return CharUtil::isAsciiAlnum(ch); }
static FOG_INLINE bool isAsciiLower(uint16_t ch) { return CharUtil::isAsciiLower(ch); }
static FOG_INLINE bool isAsciiUpper(uint16_t ch) { return CharUtil::isAsciiUpper(ch); }
static FOG_INLINE bool isAsciiDigit(uint16_t ch) { return CharUtil::isAsciiDigit(ch); }
static FOG_INLINE bool isAsciiXDigit(uint16_t ch){ return CharUtil::isAsciiXDigit(ch); }
static FOG_INLINE bool isAsciiSpace(uint16_t ch) { return CharUtil::isAsciiSpace(ch); }
static FOG_INLINE bool isAsciiBlank(uint16_t ch) { return CharUtil::isAsciiSpace(ch); }
static FOG_INLINE bool isAsciiPunct(uint16_t ch) { return CharUtil::isAsciiPunct(ch); }
static FOG_INLINE bool isAsciiGraph(uint16_t ch) { return CharUtil::isAsciiGraph(ch); }
static FOG_INLINE bool isAsciiPrint(uint16_t ch) { return CharUtil::isAsciiPrint(ch); }
static FOG_INLINE Char toAsciiLower(uint16_t ch) { return Char(CharUtil::toAsciiLower(ch)); }
static FOG_INLINE Char toAsciiUpper(uint16_t ch) { return Char(CharUtil::toAsciiUpper(ch)); }
// [Unicode CTypes]
FOG_INLINE bool isAlpha() const { return CharUtil::isAlpha(_ch); }
FOG_INLINE bool isLower() const { return CharUtil::isLower(_ch); }
FOG_INLINE bool isUpper() const { return CharUtil::isUpper(_ch); }
FOG_INLINE Char toLower() const { return Char(CharUtil::toLower(_ch)); }
FOG_INLINE Char toUpper() const { return Char(CharUtil::toUpper(_ch)); }
FOG_INLINE Char toAscii() const { return Char(CharUtil::toAscii(_ch)); }
FOG_INLINE bool isSpace() const { return CharUtil::isSpace(_ch); }
FOG_INLINE bool isBlank() const { return CharUtil::isBlank(_ch); }
FOG_INLINE bool isDigit() const { return CharUtil::isDigit(_ch); }
FOG_INLINE bool isAlnum() const { return CharUtil::isAlnum(_ch); }
FOG_INLINE bool isXDigit() const { return CharUtil::isXDigit(_ch); }
FOG_INLINE bool isPunct() const { return CharUtil::isPunct(_ch); }
FOG_INLINE bool isGraph() const { return CharUtil::isGraph(_ch); }
FOG_INLINE bool isPrint() const { return CharUtil::isPrint(_ch); }
FOG_INLINE bool isCntrl() const { return CharUtil::isCntrl(_ch); }
// Statics.
static FOG_INLINE bool isAlpha(uint16_t ch) { return CharUtil::isAlpha(ch); }
static FOG_INLINE bool isLower(uint16_t ch) { return CharUtil::isLower(ch); }
static FOG_INLINE bool isUpper(uint16_t ch) { return CharUtil::isUpper(ch); }
static FOG_INLINE uint16_t toLower(uint16_t ch) { return CharUtil::toLower(ch); }
static FOG_INLINE uint16_t toUpper(uint16_t ch) { return CharUtil::toUpper(ch); }
static FOG_INLINE uint16_t toAscii(uint16_t ch) { return CharUtil::toAscii(ch); }
static FOG_INLINE bool isSpace(uint16_t ch) { return CharUtil::isSpace(ch); }
static FOG_INLINE bool isBlank(uint16_t ch) { return CharUtil::isBlank(ch); }
static FOG_INLINE bool isDigit(uint16_t ch) { return CharUtil::isDigit(ch); }
static FOG_INLINE bool isAlnum(uint16_t ch) { return CharUtil::isAlnum(ch); }
static FOG_INLINE bool isXDigit(uint16_t ch) { return CharUtil::isXDigit(ch); }
static FOG_INLINE bool isPunct(uint16_t ch) { return CharUtil::isPunct(ch); }
static FOG_INLINE bool isGraph(uint16_t ch) { return CharUtil::isGraph(ch); }
static FOG_INLINE bool isPrint(uint16_t ch) { return CharUtil::isPrint(ch); }
static FOG_INLINE bool isCntrl(uint16_t ch) { return CharUtil::isCntrl(ch); }
// [Unicode Helpers]
FOG_INLINE bool isLeadSurrogate() const { return isLeadSurrogate(_ch); }
FOG_INLINE bool isTrailSurrogate() const { return isTrailSurrogate(_ch); }
FOG_INLINE bool isSurrogatePair() const { return isSurrogatePair(_ch); }
FOG_INLINE bool isValid() const { return isValid(_ch); }
// Statics.
static FOG_INLINE bool isLeadSurrogate(uint16_t ch) { return (ch & UTF16_LEAD_SURROGATE_MASK) == UTF16_LEAD_SURROGATE_BASE; }
static FOG_INLINE bool isTrailSurrogate(uint16_t ch) { return (ch & UTF16_TRAIL_SURROGATE_MASK) == UTF16_TRAIL_SURROGATE_BASE; }
static FOG_INLINE bool isSurrogatePair(uint16_t ch) { return (ch & UTF16_SURROGATE_PAIR_MASK) == UTF16_SURROGATE_PAIR_BASE; }
static FOG_INLINE bool isValid(uint16_t ch) { return (ch < 0xFFFE); }
// [BOM / BSwap]
FOG_INLINE bool isBom() const { return _ch == UTF16_BOM; }
FOG_INLINE bool isBomSwapped() const { return _ch == UTF16_BOM_Swapped; }
FOG_INLINE Char& bswap() { _ch = Memory::bswap16(_ch); return *this; }
// Statics.
static FOG_INLINE bool isBom(uint16_t ch) { return ch == UTF16_BOM; }
static FOG_INLINE bool isBomSwapped(uint16_t ch) { return ch == UTF16_BOM_Swapped; }
static FOG_INLINE uint16_t bswap(uint16_t ch) { return Memory::bswap16(ch); }
// [Combine]
static FOG_INLINE Char combine(Char ch, Char comb) { return Char((uint16_t)unicodeCombine(ch._ch, comb._ch)); }
// [Surrogates]
static FOG_INLINE uint32_t fromSurrogate(uint16_t uc0, uint16_t uc1)
{
return (uint32_t)(
0x10000U + (((uint32_t)uc0 - UTF16_LEAD_SURROGATE_MIN) << 10) +
( (uint32_t)uc1 - (UTF16_LEAD_SURROGATE_MAX + 1U)));
}
static FOG_INLINE void toSurrogatePair(uint32_t uc, uint16_t* uc0, uint16_t* uc1)
{
FOG_ASSERT(uc >= 0x10000);
uint32_t ch = uc - 0x10000;
*uc0 = (uint16_t)((ch >> 10) + 0xD800);
*uc1 = (uint16_t)((ch & 0x03FF) + 0xDC00);
}
// [Members]
//! @brief 16-bit unicode character value.
uint16_t _ch;
};
#include <Fog/Core/Compiler/PackRestore.h>
} // Fog namespace
// [Overloads]
#define __FOG_CHAR_MAKE_COMPARE_OVERLOAD(TYPE_A, GET_A, TYPE_B, GET_B) \
static FOG_INLINE bool operator==(TYPE_A, TYPE_B) { return GET_A == GET_B; } \
static FOG_INLINE bool operator!=(TYPE_A, TYPE_B) { return GET_A != GET_B; } \
static FOG_INLINE bool operator<=(TYPE_A, TYPE_B) { return GET_A <= GET_B; } \
static FOG_INLINE bool operator>=(TYPE_A, TYPE_B) { return GET_A >= GET_B; } \
static FOG_INLINE bool operator< (TYPE_A, TYPE_B) { return GET_A < GET_B; } \
static FOG_INLINE bool operator> (TYPE_A, TYPE_B) { return GET_A > GET_B; }
__FOG_CHAR_MAKE_COMPARE_OVERLOAD(const Fog::Char& a, a._ch, const Fog::Char& b, b._ch)
__FOG_CHAR_MAKE_COMPARE_OVERLOAD(const Fog::Char& a, a._ch, char b, (uint8_t)b)
__FOG_CHAR_MAKE_COMPARE_OVERLOAD(char a, (uint8_t)a, const Fog::Char& b, b._ch)
__FOG_CHAR_MAKE_COMPARE_OVERLOAD(const Fog::Char& a, a._ch, uint8_t b, b)
__FOG_CHAR_MAKE_COMPARE_OVERLOAD(uint8_t a, a, const Fog::Char& b, b._ch)
__FOG_CHAR_MAKE_COMPARE_OVERLOAD(const Fog::Char& a, a._ch, int16_t b, (uint16_t)b)
__FOG_CHAR_MAKE_COMPARE_OVERLOAD(int16_t a, (uint16_t)a, const Fog::Char& b, b._ch)
__FOG_CHAR_MAKE_COMPARE_OVERLOAD(const Fog::Char& a, a._ch, uint16_t b, b)
__FOG_CHAR_MAKE_COMPARE_OVERLOAD(uint16_t a, a, const Fog::Char& b, b._ch)
#undef __FOG_CHAR_MAKE_COMPARE_OVERLOAD
#define __FOG_CHAR_MAKE_ARITH_OVERLOAD(TYPE_A, GET_A, TYPE_B, GET_B) \
static FOG_INLINE Fog::Char operator+(TYPE_A, TYPE_B) { return Fog::Char(GET_A + GET_B); } \
static FOG_INLINE Fog::Char operator-(TYPE_A, TYPE_B) { return Fog::Char(GET_A - GET_B); }
__FOG_CHAR_MAKE_ARITH_OVERLOAD(const Fog::Char& a, a._ch, const Fog::Char& b, b._ch)
__FOG_CHAR_MAKE_ARITH_OVERLOAD(const Fog::Char& a, a._ch, char b, (uint16_t)(uint8_t)b)
__FOG_CHAR_MAKE_ARITH_OVERLOAD(char a, (uint16_t)(uint8_t)a, const Fog::Char& b, b._ch)
__FOG_CHAR_MAKE_ARITH_OVERLOAD(const Fog::Char& a, a._ch, int16_t b, (uint16_t)b)
__FOG_CHAR_MAKE_ARITH_OVERLOAD(int16_t a, (uint16_t)a, const Fog::Char& b, b._ch)
#undef __FOG_CHAR_MAKE_ARITH_OVERLOAD
//! @}
// ============================================================================
// [Fog::TypeInfo<>]
// ============================================================================
FOG_DECLARE_TYPEINFO(Fog::Char, Fog::TYPEINFO_PRIMITIVE)
#endif // _FOG_CORE_CHAR_H
| [
"wintercoredev@gmail.com"
] | wintercoredev@gmail.com |
c49bfd914f5bafe7892c52828bae34e6abc9a4f3 | 5a50292784431caf002ef38a401a98f69328e5b7 | /SyncQueue/SyncQueue/CSyncQueue.h | 6a1ca44e80a4594fee29e5792608c6eb741616e6 | [] | no_license | Boialex/Parallel | df0117f41bedd2ba5785439b025a2db5e60c9bfc | 4f2769ef1e6196a641946edba78dfa795ddd09d4 | refs/heads/master | 2021-01-13T00:59:35.083316 | 2016-05-09T23:00:39 | 2016-05-09T23:00:39 | 53,613,918 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,261 | h | #include <thread>
#include <mutex>
#include <condition_variable>
template<typename ARRAY>
struct isContainer {
private:
static int check(...);
template<typename T>
static decltype(std::declval<T>().pop()) check(const T&);
public:
static constexpr
bool value = !(std::is_same<void, decltype(check(std::declval<ARRAY>()))>::value);
};
template<typename ARRAY>
struct isStack {
private:
static void check(...);
template<typename T>
static decltype(std::declval<T>().top()) check(const T&);
public:
static constexpr
bool value = !(std::is_same<void, decltype(check(std::declval<ARRAY>()))>::value);
};
template <class ARRAY>
class CSyncContainer {
typedef typename ARRAY::value_type value_type;
public:
CSyncContainer() : final(false) {};
CSyncContainer(int size) : data(size), final(false) {};
/*
value_type& popOrWait()
{
std::unique_lock<std::mutex> locker(mutex);
while (data.empty() && !final) {
cond_var.wait(locker);
}
if (data.empty())
return;
value_type item = data.front();
data.pop_front();
return item;
}
*/
bool popNoWait(value_type& item)
{
std::unique_lock<std::mutex> locker(mutex);
if (data.empty())
{
locker.unlock();
return false;
}
item = std::move(getData(typeOfArray<isContainer<ARRAY>::value, isStack<ARRAY>::value>()));
popData(typeOfArray<isContainer<ARRAY>::value, isStack<ARRAY>::value>());
return true;
}
bool popOrWait(value_type& item)
{
std::unique_lock<std::mutex> locker(mutex);
while (data.empty() && !final)
{
cond_var.wait(locker);
}
if (data.empty())
return false;
item = std::move(getData(typeOfArray<isContainer<ARRAY>::value, isStack<ARRAY>::value>()));
popData(typeOfArray<isContainer<ARRAY>::value, isStack<ARRAY>::value>());
return true;
}
void push(const value_type& item)
{
std::unique_lock<std::mutex> locker(mutex);
pushData(typeOfArray<isContainer<ARRAY>::value, isStack<ARRAY>::value>(), item);
locker.unlock();
cond_var.notify_one();
}
void push(value_type&& item)
{
std::unique_lock<std::mutex> locker(mutex);
pushData(typeOfArray<isContainer<ARRAY>::value, isStack<ARRAY>::value>(), std::move(item));
locker.unlock();
cond_var.notify_one();
}
void finalize()
{
final = true;
cond_var.notify_all();
}
int size()
{
return data.size();
}
private:
ARRAY data;
std::mutex mutex;
std::condition_variable cond_var;
bool final = false;
template<bool isContainer, bool isStack>
struct typeOfArray {};
template<bool isContainer, bool isStack>
value_type& getData(typeOfArray<isContainer, isStack>);
value_type& getData(typeOfArray<true, false>) {return data.back();}
value_type& getData(typeOfArray<false, false>) {return data.back();}
value_type& getData(typeOfArray<false, true>) {return data.top();}
template<bool isContainer, bool isStack>
void popData(typeOfArray<isContainer, isStack>);
void popData(typeOfArray<true, false>) {data.pop_back();}
void popData(typeOfArray<false, false>) {data.pop();}
void popData(typeOfArray<false, true>) {data.pop();}
template<bool isContainer, bool isStack>
void pushData(typeOfArray<isContainer, isStack>, const value_type& item);
void pushData(typeOfArray<true, false>, const value_type& time) {data.push_back(item);}
void pushData(typeOfArray<false, false>, const value_type& item) {data.push(item);}
void pushData(typeOfArray<false, true>, const value_type& item) {data.push(item);}
template<bool isContainer, bool isStack>
void pushData(typeOfArray<isContainer, isStack>, value_type&& item);
void pushData(typeOfArray<true, false>, value_type&& item) {data.push_back(std::move(item));}
void pushData(typeOfArray<false, false>, value_type&& item) {data.push(std::move(item));}
void pushData(typeOfArray<false, true>, value_type&& item) {data.push(std::move(item));}
}; | [
"xdr007@gmail.com"
] | xdr007@gmail.com |
68e0a1b2b8a632d65ce4beed42c9c0aa8c409baa | b85b494c0e8c1776d7b4643553693c1563df4b0b | /Chapter 7/task4.cpp | 9c21d3e44085f3e8bc8e99b9c50c46f55c7c4397 | [] | no_license | lut1y/Stephen_Prata_Ansi_C_plusplus-6thE-Code-Example-and-Answers | c9d1f79b66ac7ed7f48b3ce85de3c7ae9337cb58 | e14dd78639b1016ed8f842e8adaa597347c4446e | refs/heads/master | 2023-07-05T13:08:51.860207 | 2021-08-12T16:02:34 | 2021-08-12T16:02:34 | 393,147,210 | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 1,033 | cpp | #include <iostream>
const int MAIN_FIELD = 47;
const int MEGA_FIELD = 27;
// Примечание: некоторые реализации требуют применения double вместо long double
long double probability4(unsigned numbers, unsigned picks);
int task4()
{
using namespace std;
long double choices = probability4(MAIN_FIELD, 5);
long double megaNum = probability4(MEGA_FIELD, 1);
cout << "Chance to win is " << choices * megaNum << endl;
cout << "bye\n";
// cin.get();
// cin.get();
return 0;
}
// Следующая функция вычисляет вероятность правильного
// угадывания picks чисел из numbers возможных
long double probability4(unsigned numbers, unsigned picks)
{
long double result = 1.0; // несколько локальных переменных
long double n;
unsigned p;
for (n = numbers, p = picks; p > 0; n--, p--)
result = result * n / p ;
return result;
}
| [
"lut1y@mail.ru"
] | lut1y@mail.ru |
942ece1adb10993307c71ccfa96cf45cc1fbd5d9 | d09945668f19bb4bc17087c0cb8ccbab2b2dd688 | /atcoder/abc001-040/abc030/a.cpp | ea83e8ba98175528bac2f72102152f1909174394 | [] | no_license | kmjp/procon | 27270f605f3ae5d80fbdb28708318a6557273a57 | 8083028ece4be1460150aa3f0e69bdb57e510b53 | refs/heads/master | 2023-09-04T11:01:09.452170 | 2023-09-03T15:25:21 | 2023-09-03T15:25:21 | 30,825,508 | 23 | 2 | null | 2023-08-18T14:02:07 | 2015-02-15T11:25:23 | C++ | UTF-8 | C++ | false | false | 862 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef signed long long ll;
#undef _P
#define _P(...) (void)printf(__VA_ARGS__)
#define FOR(x,to) for(x=0;x<to;x++)
#define FORR(x,arr) for(auto& x:arr)
#define ITR(x,c) for(__typeof(c.begin()) x=c.begin();x!=c.end();x++)
#define ALL(a) (a.begin()),(a.end())
#define ZERO(a) memset(a,0,sizeof(a))
#define MINUS(a) memset(a,0xff,sizeof(a))
//-------------------------------------------------------
int A,B,C,D;
void solve() {
int i,j,k,l,r,x,y; string s;
cin>>A>>B>>C>>D;
if(B*C<A*D) cout<<"AOKI"<<endl;
else if(B*C>A*D) cout<<"TAKAHASHI"<<endl;
else cout<<"DRAW"<<endl;
}
int main(int argc,char** argv){
string s;int i;
if(argc==1) ios::sync_with_stdio(false);
FOR(i,argc-1) s+=argv[i+1],s+='\n';
FOR(i,s.size()) ungetc(s[s.size()-1-i],stdin);
solve(); return 0;
}
| [
"kmjp@users.noreply.github.com"
] | kmjp@users.noreply.github.com |
93397c25aae316a83aff3e8fc332f0e4a309a696 | 31d21ba58bed636c15cddb991e470fa68258b2f2 | /TWS API/samples/TestConnectionVerify/ConnectionVerifyTest.cpp | 8b40eb7fd301b5b1f469f5c358370e64a3b65101 | [] | no_license | sergiovvfm/trading | 2149cb5998d8fb25234e96ce8694f34bc25b80a6 | 796443430a3ca7297e8ac3bae77984b05e109072 | refs/heads/master | 2021-01-01T18:23:02.190928 | 2014-09-23T12:42:59 | 2014-09-23T12:42:59 | 24,096,385 | 0 | 2 | null | 2014-09-18T14:55:15 | 2014-09-16T11:11:30 | C++ | UTF-8 | C++ | false | false | 16,461 | cpp | /* Copyright (C) 2013 Interactive Brokers LLC. All rights reserved. This code is subject to the terms
* and conditions of the IB API Non-Commercial License or the IB API Commercial License, as applicable. */
#include "ConnectionVerifyTest.h"
#include "EPosixClientSocket.h"
#include "EPosixClientSocketPlatform.h"
#include <assert.h>
const int PING_DEADLINE = 2; // seconds
const int SLEEP_BETWEEN_PINGS = 30; // seconds
///////////////////////////////////////////////////////////
// member funcs
ConnectionVerifyTest::ConnectionVerifyTest(const char * apiName, const char * apiVersion)
: m_pClient(new EPosixClientSocket(this))
, m_state(ST_CONNECT)
, m_sleepDeadline(0)
, m_apiData("")
, m_apiName(apiName)
, m_apiVersion(apiVersion)
, m_rsa(NULL)
{
}
ConnectionVerifyTest::~ConnectionVerifyTest()
{
if (m_rsa)
RSA_free(m_rsa);
}
bool ConnectionVerifyTest::connect(const char *host, unsigned int port, int clientId)
{
assert (m_state == ST_CONNECT);
// trying to connect
printf( "Connecting to %s:%d clientId:%d\n", !( host && *host) ? "127.0.0.1" : host, port, clientId);
bool bRes = m_pClient->eConnect( host, port, clientId, /* extraAuth */ true);
if (bRes) {
printf( "Connected to %s:%d clientId:%d\n", !( host && *host) ? "127.0.0.1" : host, port, clientId);
m_state = ST_VERIFYREQUEST;
}
else
printf( "Cannot connect to %s:%d clientId:%d\n", !( host && *host) ? "127.0.0.1" : host, port, clientId);
return bRes;
}
void ConnectionVerifyTest::disconnect()
{
m_pClient->eDisconnect();
m_state = ST_CONNECT;
m_sleepDeadline = 0;
m_apiData = "";
printf ( "Disconnected\n");
}
bool ConnectionVerifyTest::isConnected() const
{
return m_pClient->isConnected();
}
void ConnectionVerifyTest::processMessages()
{
fd_set readSet, writeSet, errorSet;
struct timeval tval;
tval.tv_usec = 0;
tval.tv_sec = 0;
time_t now = time(NULL);
switch (m_state) {
case ST_VERIFYREQUEST:
verifyRequest();
break;
case ST_VERIFYREQUEST_ACK:
break;
case ST_VERIFYMESSAGE:
verifyMessage();
break;
case ST_VERIFYMESSAGE_ACK:
break;
case ST_PING:
reqCurrentTime();
break;
case ST_PING_ACK:
if( m_sleepDeadline < now) {
disconnect();
return;
}
break;
case ST_IDLE:
if( m_sleepDeadline < now) {
m_state = ST_PING;
return;
}
break;
}
if( m_sleepDeadline > 0) {
// initialize timeout with m_sleepDeadline - now
tval.tv_sec = m_sleepDeadline - now;
}
if( m_pClient->fd() >= 0 ) {
FD_ZERO( &readSet);
errorSet = writeSet = readSet;
FD_SET( m_pClient->fd(), &readSet);
if( !m_pClient->isOutBufferEmpty())
FD_SET( m_pClient->fd(), &writeSet);
FD_SET( m_pClient->fd(), &errorSet);
int ret = select( m_pClient->fd() + 1, &readSet, &writeSet, &errorSet, &tval);
if( ret == 0) { // timeout
return;
}
if( ret < 0) { // error
disconnect();
return;
}
if( m_pClient->fd() < 0)
return;
if( FD_ISSET( m_pClient->fd(), &errorSet)) {
// error on socket
m_pClient->onError();
}
if( m_pClient->fd() < 0)
return;
if( FD_ISSET( m_pClient->fd(), &writeSet)) {
// socket is ready for writing
m_pClient->onSend();
}
if( m_pClient->fd() < 0)
return;
if( FD_ISSET( m_pClient->fd(), &readSet)) {
// socket is ready for reading
m_pClient->onReceive();
}
}
}
//////////////////////////////////////////////////////////////////
// methods
void ConnectionVerifyTest::reqCurrentTime()
{
printf( "Requesting Current Time\n");
// set ping deadline to "now + n seconds"
m_sleepDeadline = time( NULL) + PING_DEADLINE;
m_state = ST_PING_ACK;
m_pClient->reqCurrentTime();
}
void ConnectionVerifyTest::verifyRequest()
{
printf( "verifyRequest sent: apiName=%s apiVersion=%s\n", m_apiName, m_apiVersion);
m_state = ST_VERIFYREQUEST_ACK;
m_pClient->verifyRequest( m_apiName, m_apiVersion);
}
void ConnectionVerifyTest::verifyMessage()
{
printf( "verifyMessage sent: apiData=%s\n", m_apiData.c_str());
m_state = ST_VERIFYMESSAGE_ACK;
m_pClient->verifyMessage( m_apiData);
}
///////////////////////////////////////////////////////////////////
// events
void ConnectionVerifyTest::verifyMessageAPI( const IBString& apiData)
{
m_apiData = apiData;
printf( "verifyMessageAPI is received: apiData=%s\n", m_apiData.c_str());
// 1. base64-decode data (m_apiData)
printf( "Started base64 decoding of API data: %s\n", m_apiData.c_str());
m_apiData = base64_decode(m_apiData);
if (IsEmpty(m_apiData)){
// error during base64 decoding - disconnecting
disconnect();
return;
}
printf( "API data is base64 decoded: %s\n", m_apiData.c_str());
// 2. calculate SHA1 signature of data (m_apiData) using OpenSSL
printf( "Started to calculate SHA1 signature of API data: %s\n", m_apiData.c_str());
m_apiData = calculateSHA1Signature(m_apiData);
if (IsEmpty(m_apiData)){
// error during sha1 calculation - disconnecting
disconnect();
return;
}
// 3. sign data using the private key by using RSA_sign function of Open SSL on SHA1 signature of the data
printf( "Signing API data using RSA_sign function ...\n");
m_apiData = signDataWithPrivateKey(m_apiData);
if (IsEmpty(m_apiData)){
// error during RSA signing - disconnecting
disconnect();
return;
}
printf( "API data was signed.\n");
// 4. base64-encode the resulting byte stream
printf( "Started base64 encoding of signed API data ...\n");
m_apiData = base64_encode(m_apiData);
if (IsEmpty(m_apiData)){
// error during base64 encoding - disconnecting
disconnect();
return;
}
printf( "API data is base64 encoded.\n");
if( m_state == ST_VERIFYREQUEST_ACK)
m_state = ST_VERIFYMESSAGE;
}
void ConnectionVerifyTest::verifyCompleted( bool isSuccessful, const IBString& errorText)
{
printf( "verifyCompleted is received: isSuccessful=%s errorText=%s\n", isSuccessful ? "true" : "false", errorText.c_str());
if( m_state == ST_VERIFYMESSAGE_ACK)
m_state = ST_PING;
}
void ConnectionVerifyTest::currentTime( long time)
{
if ( m_state == ST_PING_ACK) {
time_t t = ( time_t)time;
struct tm * timeinfo = localtime ( &t);
printf( "The current date/time is: %s", asctime( timeinfo));
time_t now = ::time(NULL);
m_sleepDeadline = now + SLEEP_BETWEEN_PINGS;
m_state = ST_IDLE;
}
}
void ConnectionVerifyTest::error(const int id, const int errorCode, const IBString errorString)
{
printf( "Error id=%d, errorCode=%d, msg=%s\n", id, errorCode, errorString.c_str());
if( id == -1 && errorCode == 1100) // if "Connectivity between IB and TWS has been lost"
disconnect();
}
void ConnectionVerifyTest::nextValidId( OrderId orderId) {}
void ConnectionVerifyTest::tickPrice( TickerId tickerId, TickType field, double price, int canAutoExecute) {}
void ConnectionVerifyTest::tickSize( TickerId tickerId, TickType field, int size) {}
void ConnectionVerifyTest::tickOptionComputation( TickerId tickerId, TickType tickType, double impliedVol, double delta,
double optPrice, double pvDividend,
double gamma, double vega, double theta, double undPrice) {}
void ConnectionVerifyTest::tickGeneric(TickerId tickerId, TickType tickType, double value) {}
void ConnectionVerifyTest::tickString(TickerId tickerId, TickType tickType, const IBString& value) {}
void ConnectionVerifyTest::tickEFP(TickerId tickerId, TickType tickType, double basisPoints, const IBString& formattedBasisPoints,
double totalDividends, int holdDays, const IBString& futureExpiry, double dividendImpact, double dividendsToExpiry) {}
void ConnectionVerifyTest::orderStatus( OrderId orderId, const IBString &status, int filled,
int remaining, double avgFillPrice, int permId, int parentId,
double lastFillPrice, int clientId, const IBString& whyHeld) {}
void ConnectionVerifyTest::openOrder( OrderId orderId, const Contract&, const Order&, const OrderState& ostate) {}
void ConnectionVerifyTest::openOrderEnd() {}
void ConnectionVerifyTest::winError( const IBString &str, int lastError) {}
void ConnectionVerifyTest::connectionClosed() {}
void ConnectionVerifyTest::updateAccountValue(const IBString& key, const IBString& val,
const IBString& currency, const IBString& accountName) {}
void ConnectionVerifyTest::updatePortfolio(const Contract& contract, int position,
double marketPrice, double marketValue, double averageCost,
double unrealizedPNL, double realizedPNL, const IBString& accountName){}
void ConnectionVerifyTest::updateAccountTime(const IBString& timeStamp) {}
void ConnectionVerifyTest::accountDownloadEnd(const IBString& accountName) {}
void ConnectionVerifyTest::contractDetails( int reqId, const ContractDetails& contractDetails) {}
void ConnectionVerifyTest::bondContractDetails( int reqId, const ContractDetails& contractDetails) {}
void ConnectionVerifyTest::contractDetailsEnd( int reqId) {}
void ConnectionVerifyTest::execDetails( int reqId, const Contract& contract, const Execution& execution) {}
void ConnectionVerifyTest::execDetailsEnd( int reqId) {}
void ConnectionVerifyTest::updateMktDepth(TickerId id, int position, int operation, int side,
double price, int size) {}
void ConnectionVerifyTest::updateMktDepthL2(TickerId id, int position, IBString marketMaker, int operation,
int side, double price, int size) {}
void ConnectionVerifyTest::updateNewsBulletin(int msgId, int msgType, const IBString& newsMessage, const IBString& originExch) {}
void ConnectionVerifyTest::managedAccounts( const IBString& accountsList) {}
void ConnectionVerifyTest::receiveFA(faDataType pFaDataType, const IBString& cxml) {}
void ConnectionVerifyTest::historicalData(TickerId reqId, const IBString& date, double open, double high,
double low, double close, int volume, int barCount, double WAP, int hasGaps) {}
void ConnectionVerifyTest::scannerParameters(const IBString &xml) {}
void ConnectionVerifyTest::scannerData(int reqId, int rank, const ContractDetails &contractDetails,
const IBString &distance, const IBString &benchmark, const IBString &projection,
const IBString &legsStr) {}
void ConnectionVerifyTest::scannerDataEnd(int reqId) {}
void ConnectionVerifyTest::realtimeBar(TickerId reqId, long time, double open, double high, double low, double close,
long volume, double wap, int count) {}
void ConnectionVerifyTest::fundamentalData(TickerId reqId, const IBString& data) {}
void ConnectionVerifyTest::deltaNeutralValidation(int reqId, const UnderComp& underComp) {}
void ConnectionVerifyTest::tickSnapshotEnd(int reqId) {}
void ConnectionVerifyTest::marketDataType(TickerId reqId, int marketDataType) {}
void ConnectionVerifyTest::commissionReport( const CommissionReport& commissionReport) {}
void ConnectionVerifyTest::position( const IBString& account, const Contract& contract, int position, double avgCost) {}
void ConnectionVerifyTest::positionEnd() {}
void ConnectionVerifyTest::accountSummary( int reqId, const IBString& account, const IBString& tag, const IBString& value, const IBString& curency) {}
void ConnectionVerifyTest::accountSummaryEnd( int reqId) {}
void ConnectionVerifyTest::displayGroupList( int reqId, const IBString& groups) {}
void ConnectionVerifyTest::displayGroupUpdated( int reqId, const IBString& contractInfo) {}
//////////////////////////////////////////////////////////////////////////
//
// calculate SHA1 signature of data string using OpenSSL
//
//////////////////////////////////////////////////////////////////////////
IBString ConnectionVerifyTest::calculateSHA1Signature(const IBString& dataString)
{
unsigned char digest[SHA_DIGEST_LENGTH];
SHA_CTX ctx;
// init SHA1 digest calculator
if (SHA1_Init(&ctx) <= 0){
print_ssl_error("Error during SHA1_Init() call.\n");
return IBString();
}
// update SHA1 digest value
if (SHA1_Update(&ctx, dataString.data(), dataString.size()) <= 0){
print_ssl_error("Error during SHA1_Update() call.\n");
return IBString();
}
// destroy SHA1 digest calculator
if (SHA1_Final(digest, &ctx) <= 0){
print_ssl_error("Error during SHA1_Final() call.\n");
return IBString();
}
return IBString((const char*)digest, SHA_DIGEST_LENGTH);
}
//////////////////////////////////////////////////////////////////////////
//
// base64 encode of data string using OpenSSL
//
//////////////////////////////////////////////////////////////////////////
IBString ConnectionVerifyTest::base64_encode(IBString& input_string)
{
const char * input = input_string.c_str();
int length = input_string.size();
BIO * bmem = NULL;
BIO * b64 = NULL;
BUF_MEM * bptr = NULL;
// create new BIO object
b64 = BIO_new( BIO_f_base64());
if (b64 == NULL){
print_ssl_error("Error during BIO_new() call.\n");
return IBString();
}
// create new BIO object
bmem = BIO_new( BIO_s_mem());
if (bmem == NULL){
print_ssl_error("Error during BIO_new() call.\n");
BIO_free_all( b64);
return IBString();
}
// set flag to encode all data in single line
BIO_set_flags( b64, BIO_FLAGS_BASE64_NO_NL);
// append bmem to b64
b64 = BIO_push( b64, bmem);
if (b64 == NULL){
print_ssl_error("Error during BIO_push() call.\n");
BIO_free_all( bmem);
return IBString();
}
// write 'length' bytes of data from input to b64
if (BIO_write( b64, input, length) <= 0){
print_ssl_error("Error during BIO_write() call.\n");
BIO_free_all( b64);
return IBString();
}
if (BIO_flush( b64) <= 0){
print_ssl_error("Error during BIO_flush() call.\n");
BIO_free_all( b64);
return IBString();
}
BIO_get_mem_ptr( b64, &bptr);
if (bptr == NULL){
print_ssl_error("Error during BIO_get_mem_ptr() call.\n");
BIO_free_all( b64);
return IBString();
}
IBString output_string(bptr->data, bptr->length);
BIO_free_all( b64);
return output_string;
}
//////////////////////////////////////////////////////////////////////////
//
// base64 decode of data string using OpenSSL
//
//////////////////////////////////////////////////////////////////////////
IBString ConnectionVerifyTest::base64_decode(IBString& input_string)
{
const char * input = input_string.c_str();
int length = input_string.size();
BIO *bmem;
BIO *b64;
IBString output_string;
output_string.resize(length);
b64 = BIO_new( BIO_f_base64());
if (b64 == NULL){
print_ssl_error("Error during BIO_push() call.\n");
return IBString();
}
BIO_set_flags( b64, BIO_FLAGS_BASE64_NO_NL);
bmem = BIO_new_mem_buf( (void *)input, length);
if (bmem == NULL){
print_ssl_error("Error during BIO_new_mem_buf() call.\n");
BIO_free_all( b64);
return IBString();
}
bmem = BIO_push( b64, bmem);
if (bmem == NULL){
print_ssl_error("Error during BIO_push() call.\n");
BIO_free_all( bmem);
return IBString();
}
length = BIO_read( bmem, &output_string[0], length);
BIO_free_all( bmem);
if (length <= 0){
print_ssl_error("Error during BIO_read() call.\n");
return IBString();
}
output_string.resize(length);
return output_string;
}
//////////////////////////////////////////////////////////////////////////
//
// signing data string with private key using OpenSSL and SHA1 algorithm
//
//////////////////////////////////////////////////////////////////////////
IBString ConnectionVerifyTest::signDataWithPrivateKey(const IBString& apiData)
{
IBString sig;
sig.resize(RSA_size(m_rsa));
unsigned sig_len = 0;
if (!RSA_sign(NID_sha1, (const unsigned char*)apiData.data(), apiData.size(), (unsigned char*)&sig[0], &sig_len, m_rsa)){
print_ssl_error("Unable to sign data using RSA_sign method.\n");
return IBString();
}
if (sig_len != sig.size())
sig.resize(sig_len);
return sig;
}
//////////////////////////////////////////////////////////////////////////
//
// initializing private key
//
//////////////////////////////////////////////////////////////////////////
bool ConnectionVerifyTest::initPrivateKey(const char * fileName)
{
assert (!m_rsa);
FILE* fp = fopen(fileName, "r");
if (!fp){
printf( "Error: can't open private key file: %s\n", fileName);
return false;
}
if ((PEM_read_RSAPrivateKey(fp, &m_rsa, NULL, NULL)) == NULL){
printf( "Error: can't load private key from file: %s\n", fileName);
fclose(fp);
return false;
}
printf( "Private key is initialized from %s\n", fileName);
fclose(fp);
fp = NULL;
return true;
}
void ConnectionVerifyTest::print_ssl_error(const char * message)
{
printf(message);
printf("Error: %s\n", ERR_reason_error_string(ERR_get_error()));
printf("Error: %s\n", ERR_error_string(ERR_get_error(), NULL));
}
| [
"sergiovvfm@gmail.com"
] | sergiovvfm@gmail.com |
81f271b018c474401c0af41355483264a8be1941 | 40ca1563d309e596530f7ed53627d7d0f2ed7871 | /source/extensions/filters/udp/dns_filter/dns_filter.h | d1ccbd18e207e79a1d9ebfbc3506d1e51e82296a | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | dengyijia/envoy-wasm | e226fa24b1e54b51f8927cacf81c480adadd64b9 | 6563e8cf2b38a0fd3238983b0ecea2d14cdea0c4 | refs/heads/master | 2022-12-06T11:26:04.848714 | 2020-08-10T19:46:25 | 2020-08-10T19:46:25 | 278,214,986 | 1 | 0 | Apache-2.0 | 2020-08-10T20:18:15 | 2020-07-08T23:26:40 | C++ | UTF-8 | C++ | false | false | 12,914 | h | #pragma once
#include "envoy/event/file_event.h"
#include "envoy/extensions/filters/udp/dns_filter/v3alpha/dns_filter.pb.h"
#include "envoy/network/dns.h"
#include "envoy/network/filter.h"
#include "common/buffer/buffer_impl.h"
#include "common/common/matchers.h"
#include "common/config/config_provider_impl.h"
#include "common/network/utility.h"
#include "extensions/filters/udp/dns_filter/dns_filter_resolver.h"
#include "extensions/filters/udp/dns_filter/dns_parser.h"
#include "absl/container/flat_hash_set.h"
namespace Envoy {
namespace Extensions {
namespace UdpFilters {
namespace DnsFilter {
/**
* All DNS Filter stats. @see stats_macros.h
*/
#define ALL_DNS_FILTER_STATS(COUNTER, HISTOGRAM) \
COUNTER(a_record_queries) \
COUNTER(aaaa_record_queries) \
COUNTER(cluster_a_record_answers) \
COUNTER(cluster_aaaa_record_answers) \
COUNTER(cluster_unsupported_answers) \
COUNTER(downstream_rx_errors) \
COUNTER(downstream_rx_invalid_queries) \
COUNTER(downstream_rx_queries) \
COUNTER(external_a_record_queries) \
COUNTER(external_a_record_answers) \
COUNTER(external_aaaa_record_answers) \
COUNTER(external_aaaa_record_queries) \
COUNTER(external_unsupported_answers) \
COUNTER(external_unsupported_queries) \
COUNTER(externally_resolved_queries) \
COUNTER(known_domain_queries) \
COUNTER(local_a_record_answers) \
COUNTER(local_aaaa_record_answers) \
COUNTER(local_unsupported_answers) \
COUNTER(unanswered_queries) \
COUNTER(unsupported_queries) \
COUNTER(downstream_tx_responses) \
COUNTER(query_buffer_underflow) \
COUNTER(query_parsing_failure) \
COUNTER(record_name_overflow) \
HISTOGRAM(downstream_rx_bytes, Bytes) \
HISTOGRAM(downstream_rx_query_latency, Milliseconds) \
HISTOGRAM(downstream_tx_bytes, Bytes)
/**
* Struct definition for all DNS Filter stats. @see stats_macros.h
*/
struct DnsFilterStats {
ALL_DNS_FILTER_STATS(GENERATE_COUNTER_STRUCT, GENERATE_HISTOGRAM_STRUCT)
};
struct DnsEndpointConfig {
absl::optional<AddressConstPtrVec> address_list;
absl::optional<std::string> cluster_name;
};
using DnsVirtualDomainConfig = absl::flat_hash_map<std::string, DnsEndpointConfig>;
/**
* DnsFilter configuration class abstracting access to data necessary for the filter's operation
*/
class DnsFilterEnvoyConfig : public Logger::Loggable<Logger::Id::filter> {
public:
DnsFilterEnvoyConfig(
Server::Configuration::ListenerFactoryContext& context,
const envoy::extensions::filters::udp::dns_filter::v3alpha::DnsFilterConfig& config);
DnsFilterStats& stats() const { return stats_; }
const DnsVirtualDomainConfig& domains() const { return virtual_domains_; }
const std::vector<Matchers::StringMatcherPtr>& knownSuffixes() const { return known_suffixes_; }
const absl::flat_hash_map<std::string, std::chrono::seconds>& domainTtl() const {
return domain_ttl_;
}
const AddressConstPtrVec& resolvers() const { return resolvers_; }
bool forwardQueries() const { return forward_queries_; }
const std::chrono::milliseconds resolverTimeout() const { return resolver_timeout_; }
Upstream::ClusterManager& clusterManager() const { return cluster_manager_; }
uint64_t retryCount() const { return retry_count_; }
Runtime::RandomGenerator& random() const { return random_; }
uint64_t maxPendingLookups() const { return max_pending_lookups_; }
private:
static DnsFilterStats generateStats(const std::string& stat_prefix, Stats::Scope& scope) {
const auto final_prefix = absl::StrCat("dns_filter.", stat_prefix);
return {ALL_DNS_FILTER_STATS(POOL_COUNTER_PREFIX(scope, final_prefix),
POOL_HISTOGRAM_PREFIX(scope, final_prefix))};
}
bool loadServerConfig(const envoy::extensions::filters::udp::dns_filter::v3alpha::
DnsFilterConfig::ServerContextConfig& config,
envoy::data::dns::v3::DnsTable& table);
Stats::Scope& root_scope_;
Upstream::ClusterManager& cluster_manager_;
Network::DnsResolverSharedPtr resolver_;
Api::Api& api_;
mutable DnsFilterStats stats_;
DnsVirtualDomainConfig virtual_domains_;
std::vector<Matchers::StringMatcherPtr> known_suffixes_;
absl::flat_hash_map<std::string, std::chrono::seconds> domain_ttl_;
bool forward_queries_;
uint64_t retry_count_;
AddressConstPtrVec resolvers_;
std::chrono::milliseconds resolver_timeout_;
Runtime::RandomGenerator& random_;
uint64_t max_pending_lookups_;
};
using DnsFilterEnvoyConfigSharedPtr = std::shared_ptr<const DnsFilterEnvoyConfig>;
enum class DnsLookupResponseCode { Success, Failure, External };
/**
* This class is responsible for handling incoming DNS datagrams and responding to the queries.
* The filter will attempt to resolve the query via its configuration or direct to an external
* resolver when necessary
*/
class DnsFilter : public Network::UdpListenerReadFilter, Logger::Loggable<Logger::Id::filter> {
public:
DnsFilter(Network::UdpReadFilterCallbacks& callbacks,
const DnsFilterEnvoyConfigSharedPtr& config);
// Network::UdpListenerReadFilter callbacks
void onData(Network::UdpRecvData& client_request) override;
void onReceiveError(Api::IoError::IoErrorCode error_code) override;
/**
* @return bool true if the domain_name is a known domain for which we respond to queries
*/
bool isKnownDomain(const absl::string_view domain_name);
private:
/**
* Prepare the response buffer and send it to the client
*
* @param context contains the data necessary to create a response and send it to a client
*/
void sendDnsResponse(DnsQueryContextPtr context);
/**
* @brief Encapsulates all of the logic required to find an answer for a DNS query
*
* @return DnsLookupResponseCode indicating whether we were able to respond to the query or send
* the query to an external resolver
*/
DnsLookupResponseCode getResponseForQuery(DnsQueryContextPtr& context);
/**
* @return std::chrono::seconds retrieves the configured per domain TTL to be inserted into answer
* records
*/
std::chrono::seconds getDomainTTL(const absl::string_view domain);
/**
* @brief Resolves the supplied query from configured clusters
*
* @param context object containing the query context
* @param query query object containing the name to be resolved
* @return bool true if the requested name matched a cluster and an answer record was constructed
*/
bool resolveViaClusters(DnsQueryContextPtr& context, const DnsQueryRecord& query);
/**
* @brief Resolves the supplied query from configured hosts
*
* @param context object containing the query context
* @param query query object containing the name to be resolved
* @return bool true if the requested name matches a configured domain and answer records can be
* constructed
*/
bool resolveViaConfiguredHosts(DnsQueryContextPtr& context, const DnsQueryRecord& query);
/**
* @brief Increment the counter for the given query type for external queries
*
* @param query_type indicate the type of record being resolved (A, AAAA, or other).
*/
void incrementExternalQueryTypeCount(const uint16_t query_type) {
switch (query_type) {
case DNS_RECORD_TYPE_A:
config_->stats().external_a_record_queries_.inc();
break;
case DNS_RECORD_TYPE_AAAA:
config_->stats().external_aaaa_record_queries_.inc();
break;
default:
config_->stats().external_unsupported_queries_.inc();
break;
}
}
/**
* @brief Increment the counter for the parsed query type
*
* @param queries a vector of all the incoming queries received from a client
*/
void incrementQueryTypeCount(const DnsQueryPtrVec& queries) {
for (const auto& query : queries) {
incrementQueryTypeCount(query->type_);
}
}
/**
* @brief Increment the counter for the given query type.
*
* @param query_type indicate the type of record being resolved (A, AAAA, or other).
*/
void incrementQueryTypeCount(const uint16_t query_type) {
switch (query_type) {
case DNS_RECORD_TYPE_A:
config_->stats().a_record_queries_.inc();
break;
case DNS_RECORD_TYPE_AAAA:
config_->stats().aaaa_record_queries_.inc();
break;
default:
config_->stats().unsupported_queries_.inc();
break;
}
}
/**
* @brief Increment the counter for answers for the given query type resolved via cluster names
*
* @param query_type indicate the type of answer record returned to the client
*/
void incrementClusterQueryTypeAnswerCount(const uint16_t query_type) {
switch (query_type) {
case DNS_RECORD_TYPE_A:
config_->stats().cluster_a_record_answers_.inc();
break;
case DNS_RECORD_TYPE_AAAA:
config_->stats().cluster_aaaa_record_answers_.inc();
break;
default:
config_->stats().cluster_unsupported_answers_.inc();
break;
}
}
/**
* @brief Increment the counter for answers for the given query type resolved from the local
* configuration.
*
* @param query_type indicate the type of answer record returned to the client
*/
void incrementLocalQueryTypeAnswerCount(const uint16_t query_type) {
switch (query_type) {
case DNS_RECORD_TYPE_A:
config_->stats().local_a_record_answers_.inc();
break;
case DNS_RECORD_TYPE_AAAA:
config_->stats().local_aaaa_record_answers_.inc();
break;
default:
config_->stats().local_unsupported_answers_.inc();
break;
}
}
/**
* @brief Increment the counter for answers for the given query type resolved via an external
* resolver
*
* @param query_type indicate the type of answer record returned to the client
*/
void incrementExternalQueryTypeAnswerCount(const uint16_t query_type) {
switch (query_type) {
case DNS_RECORD_TYPE_A:
config_->stats().external_a_record_answers_.inc();
break;
case DNS_RECORD_TYPE_AAAA:
config_->stats().external_aaaa_record_answers_.inc();
break;
default:
config_->stats().external_unsupported_answers_.inc();
break;
}
}
/**
* @brief Helper function to retrieve the Endpoint configuration for a requested domain
*/
const DnsEndpointConfig* getEndpointConfigForDomain(const absl::string_view domain);
/**
* @brief Helper function to retrieve the Address List for a requested domain
*/
const AddressConstPtrVec* getAddressListForDomain(const absl::string_view domain);
/**
* @brief Helper function to retrieve a cluster name that a domain may be redirected towards
*/
const absl::string_view getClusterNameForDomain(const absl::string_view domain);
const DnsFilterEnvoyConfigSharedPtr config_;
Network::UdpListener& listener_;
Upstream::ClusterManager& cluster_manager_;
DnsMessageParser message_parser_;
DnsFilterResolverPtr resolver_;
Network::Address::InstanceConstSharedPtr local_;
Network::Address::InstanceConstSharedPtr peer_;
DnsFilterResolverCallback resolver_callback_;
};
} // namespace DnsFilter
} // namespace UdpFilters
} // namespace Extensions
} // namespace Envoy
| [
"noreply@github.com"
] | dengyijia.noreply@github.com |
0ecf8b46b6eba1671b6893fd3cf8e15f33aad66a | d4f6b1093120a25a1163cbd665cb169d46882756 | /std_lib_facilities.h | 99265e39681ffd576e3b079325946ea380bf70e7 | [] | no_license | egxperience/CppSandBox | 2a38a792a17d245fc287205b0fbb32f73d93f006 | 7c57be3f981c3b88e53339ef3d455b73414c75b1 | refs/heads/master | 2020-12-04T16:42:04.207756 | 2020-01-04T23:44:39 | 2020-01-04T23:44:39 | 231,840,908 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,654 | h | /*
std_lib_facilities.h
*/
/*
simple "Programming: Principles and Practice using C++ (second edition)" course header to
be used for the first few weeks.
It provides the most common standard headers (in the global namespace)
and minimal exception/error support.
Students: please don't try to understand the details of headers just yet.
All will be explained. This header is primarily used so that you don't have
to understand every concept all at once.
By Chapter 10, you don't need this file and after Chapter 21, you'll understand it
Revised April 25, 2010: simple_error() added
Revised November 25 2013: remove support for pre-C++11 compilers, use C++11: <chrono>
Revised November 28 2013: add a few container algorithms
Revised June 8 2014: added #ifndef to workaround Microsoft C++11 weakness
Revised Febrary 2 2015: randint() can now be seeded (see exercise 5.13).
Revised June 15 for defaultfloat hack for older GCCs
*/
#ifndef H112
#define H112 020215L
#include<iostream>
#include<iomanip>
#include<fstream>
#include<sstream>
#include<cmath>
#include<cstdlib>
#include<string>
#include<list>
#include <forward_list>
#include<vector>
#include<unordered_map>
#include<algorithm>
#include <array>
#include <regex>
#include<random>
#include<stdexcept>
//------------------------------------------------------------------------------
#if __GNUC__ && __GNUC__ < 5
inline ios_base& defaultfloat(ios_base& b) // to augment fixed and scientific as in C++11
{
b.setf(ios_base::fmtflags(0), ios_base::floatfield);
return b;
}
#endif
//------------------------------------------------------------------------------
using Unicode = long;
//------------------------------------------------------------------------------
using namespace std;
template<class T> string to_string(const T& t)
{
ostringstream os;
os << t;
return os.str();
}
struct Range_error : out_of_range { // enhanced vector range error reporting
int index;
Range_error(int i) :out_of_range("Range error: " + to_string(i)), index(i) { }
};
// trivially range-checked vector (no iterator checking):
template< class T> struct Vector : public std::vector<T> {
using size_type = typename std::vector<T>::size_type;
#ifdef _MSC_VER
// microsoft doesn't yet support C++11 inheriting constructors
Vector() { }
explicit Vector(size_type n) :std::vector<T>(n) {}
Vector(size_type n, const T& v) :std::vector<T>(n, v) {}
template <class I>
Vector(I first, I last) : std::vector<T>(first, last) {}
Vector(initializer_list<T> list) : std::vector<T>(list) {}
#else
using std::vector<T>::vector; // inheriting constructor
#endif
T& operator[](unsigned int i) // rather than return at(i);
{
if (i < 0 || this->size() <= i) throw Range_error(i);
return std::vector<T>::operator[](i);
}
const T& operator[](unsigned int i) const
{
if (i < 0 || this->size() <= i) throw Range_error(i);
return std::vector<T>::operator[](i);
}
};
// disgusting macro hack to get a range checked vector:
#define vector Vector
// trivially range-checked string (no iterator checking):
struct String : std::string {
using size_type = std::string::size_type;
// using string::string;
char& operator[](unsigned int i) // rather than return at(i);
{
if (i < 0 || size() <= i) throw Range_error(i);
return std::string::operator[](i);
}
const char& operator[](unsigned int i) const
{
if (i < 0 || size() <= i) throw Range_error(i);
return std::string::operator[](i);
}
};
namespace std {
template<> struct hash<String>
{
size_t operator()(const String& s) const
{
return hash<std::string>()(s);
}
};
} // of namespace std
struct Exit : runtime_error {
Exit() : runtime_error("Exit") {}
};
// error() simply disguises throws:
inline void error(const string& s)
{
throw runtime_error(s);
}
inline void error(const string& s, const string& s2)
{
error(s + s2);
}
inline void error(const string& s, int i)
{
ostringstream os;
os << s << ": " << i;
error(os.str());
}
template<class T> char* as_bytes(T& i) // needed for binary I/O
{
void* addr = &i; // get the address of the first byte
// of memory used to store the object
return static_cast<char*>(addr); // treat that memory as bytes
}
inline void keep_window_open()
{
cin.clear();
cout << "Please enter a character to exit\n";
char ch;
cin >> ch;
return;
}
inline void keep_window_open(string s)
{
if (s == "") return;
cin.clear();
cin.ignore(120, '\n');
for (;;) {
cout << "Please enter " << s << " to exit\n";
string ss;
while (cin >> ss && ss != s)
cout << "Please enter " << s << " to exit\n";
return;
}
}
// error function to be used (only) until error() is introduced in Chapter 5:
inline void simple_error(string s) // write ``error: s and exit program
{
cerr << "error: " << s << '\n';
keep_window_open(); // for some Windows environments
exit(1);
}
// make std::min() and std::max() accessible on systems with antisocial macros:
#undef min
#undef max
// run-time checked narrowing cast (type conversion). See ???.
template<class R, class A> R narrow_cast(const A& a)
{
R r = R(a);
if (A(r) != a) error(string("info loss"));
return r;
}
// random number generators. See 24.7.
default_random_engine& get_rand()
{
static default_random_engine ran;
return ran;
};
void seed_randint(int s) { get_rand().seed(s); }
inline int randint(int min, int max) { return uniform_int_distribution<>{min, max}(get_rand()); }
inline int randint(int max) { return randint(0, max); }
//inline double sqrt(int x) { return sqrt(double(x)); } // to match C++0x
// container algorithms. See 21.9.
template<typename C>
using Value_type = typename C::value_type;
template<typename C>
using Iterator = typename C::iterator;
template<typename C>
// requires Container<C>()
void sort(C& c)
{
std::sort(c.begin(), c.end());
}
template<typename C, typename Pred>
// requires Container<C>() && Binary_Predicate<Value_type<C>>()
void sort(C& c, Pred p)
{
std::sort(c.begin(), c.end(), p);
}
template<typename C, typename Val>
// requires Container<C>() && Equality_comparable<C,Val>()
Iterator<C> find(C& c, Val v)
{
return std::find(c.begin(), c.end(), v);
}
template<typename C, typename Pred>
// requires Container<C>() && Predicate<Pred,Value_type<C>>()
Iterator<C> find_if(C& c, Pred p)
{
return std::find_if(c.begin(), c.end(), p);
}
#endif //H112#pragma once
| [
"noreply@github.com"
] | egxperience.noreply@github.com |
c94766dceb58ee43ab139a34579a66482f157fcf | 5838cf8f133a62df151ed12a5f928a43c11772ed | /NT/net/homenet/alg/exe/collectionalgmodules.cpp | 66d3c203d04eddbe31f1823f74a0d1ded16eed57 | [] | no_license | proaholic/Win2K3 | e5e17b2262f8a2e9590d3fd7a201da19771eb132 | 572f0250d5825e7b80920b6610c22c5b9baaa3aa | refs/heads/master | 2023-07-09T06:15:54.474432 | 2021-08-11T09:09:14 | 2021-08-11T09:09:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,053 | cpp | /*++
Copyright (c) 2000, Microsoft Corporation
Module Name:
CollectionAlgModules.cpp
Abstract:
Implement a thread safe collection of CAlgModules
Author:
JP Duplessis (jpdup) 2000.01.19
Revision History:
--*/
#include "PreComp.h"
#include "CollectionAlgModules.h"
#include "AlgController.h"
CCollectionAlgModules::~CCollectionAlgModules()
{
MYTRACE_ENTER("CCollectionAlgModules::~CCollectionAlgModules()");
Unload();
}
//
// Add a new ALG Module only if it's uniq meaning that if it's alread in the collection
// it will return the one found and not add a new one
//
CAlgModule*
CCollectionAlgModules::AddUniqueAndStart(
CRegKey& KeyEnumISV,
LPCTSTR pszAlgID
)
{
try
{
ENTER_AUTO_CS
MYTRACE_ENTER("CCollectionAlgModules::AddUniqueAndStart");
//
// Is it already in the collection ?
//
for ( LISTOF_ALGMODULE::iterator theIterator = m_ThisCollection.begin();
theIterator != m_ThisCollection.end();
theIterator++
)
{
if ( _wcsicmp( (*theIterator)->m_szID, pszAlgID) == 0 )
{
//
// Found it already
//
MYTRACE("Already loaded nothing to do");
return (*theIterator);
}
}
//
// At this point we know that it's not in the collection
//
//
// Get more information on the ALG module
//
CRegKey RegAlg;
RegAlg.Open(KeyEnumISV, pszAlgID, KEY_QUERY_VALUE);
TCHAR szFriendlyName[MAX_PATH];
DWORD dwSize = MAX_PATH;
RegAlg.QueryValue(szFriendlyName, TEXT("Product"), &dwSize);
//
// Stuff in a CAlgModule that will be added to the collection
//
CAlgModule* pAlg = new CAlgModule(pszAlgID, szFriendlyName);
if ( !pAlg )
return NULL;
HRESULT hr = pAlg->Start();
if ( FAILED(hr) )
{
delete pAlg;
}
//
// Now we know this is a valid and trouble free ALG plug-in we can safely cache it to our collection
//
try
{
m_ThisCollection.push_back(pAlg);
}
catch(...)
{
MYTRACE_ERROR("Had problem adding the ALG plun-in to the collection", 0);
pAlg->Stop();
delete pAlg;
return NULL;
}
return pAlg;
}
catch(...)
{
return NULL;
}
return NULL;
}
//
// Remove a AlgModule from the list (Thead safe)
//
HRESULT CCollectionAlgModules::Remove(
CAlgModule* pAlgToRemove
)
{
try
{
ENTER_AUTO_CS
MYTRACE_ENTER("CCollectionAlgModules::Remove");
LISTOF_ALGMODULE::iterator theIterator = std::find(
m_ThisCollection.begin(),
m_ThisCollection.end(),
pAlgToRemove
);
if ( *theIterator )
{
m_ThisCollection.erase(theIterator);
}
}
catch(...)
{
return E_FAIL;
}
return S_OK;
}
//
// return TRUE is the ALG Module specified by pszAlgProgID
// is currently marked as "Enable"
//
bool
IsAlgModuleEnable(
CRegKey& RegKeyISV,
LPCTSTR pszAlgID
)
{
DWORD dwSize = MAX_PATH;
TCHAR szState[MAX_PATH];
LONG nRet = RegKeyISV.QueryValue(
szState,
pszAlgID,
&dwSize
);
if ( ERROR_SUCCESS != nRet )
return false;
if ( dwSize == 0 )
return false;
return ( _wcsicmp(szState, L"Enable") == 0);
};
//
//
//
HRESULT
CCollectionAlgModules::UnloadDisabledModule()
{
try
{
ENTER_AUTO_CS
MYTRACE_ENTER("CCollectionAlgModules::UnloadDisabledModule()");
CRegKey KeyEnumISV;
LONG nError = KeyEnumISV.Open(HKEY_LOCAL_MACHINE, REGKEY_ALG_ISV, KEY_READ);
bool bAllEnable = false;
//
// The total of item in the collectio is the maximum time we should attempt
// to verify and unload Alg Module that are disable
//
int nPassAttemp = m_ThisCollection.size();
while ( !bAllEnable && nPassAttemp > 0 )
{
bAllEnable = true;
//
// For all Module unload if not mark as "ENABLE"
//
for ( LISTOF_ALGMODULE::iterator theIterator = m_ThisCollection.begin();
theIterator != m_ThisCollection.end();
theIterator++
)
{
if ( IsAlgModuleEnable(KeyEnumISV, (*theIterator)->m_szID) )
{
MYTRACE("ALG Module %S is ENABLE", (*theIterator)->m_szFriendlyName);
}
else
{
MYTRACE("ALG Module %S is DISABLE", (*theIterator)->m_szFriendlyName);
//
// Stop/Release/Unload this module it's not enabled
//
delete (*theIterator);
m_ThisCollection.erase(theIterator);
bAllEnable = false;
break;
}
}
nPassAttemp--; // Ok one pass done
}
}
catch(...)
{
return E_FAIL;
}
return S_OK;
}
//
//
// Enumared the regsitry for all ALG-ISV module and verify that they are sign and CoCreates them and call there Initialise method
//
//
int // Returns the total number of ISV ALG loaded or -1 for error or 0 is none where setup
CCollectionAlgModules::Load()
{
MYTRACE_ENTER("CAlgController::LoadAll()");
int nValidAlgLoaded = 0;
CRegKey KeyEnumISV;
LONG nError = KeyEnumISV.Open(HKEY_LOCAL_MACHINE, REGKEY_ALG_ISV, KEY_READ|KEY_ENUMERATE_SUB_KEYS);
if ( ERROR_SUCCESS != nError )
{
MYTRACE_ERROR("Could not open RegKey 'HKLM\\SOFTWARE\\Microsoft\\ALG\\ISV'",nError);
return nError;
}
DWORD dwIndex=0;
TCHAR szID_AlgToLoad[256];
DWORD dwKeyNameSize;
LONG nRet;
do
{
dwKeyNameSize = 256;
nRet = RegEnumKeyEx(
KeyEnumISV.m_hKey, // handle to key to enumerate
dwIndex, // subkey index
szID_AlgToLoad, // subkey name
&dwKeyNameSize, // size of subkey buffer
NULL, // reserved
NULL, // class string buffer
NULL, // size of class string buffer
NULL // last write time
);
dwIndex++;
if ( ERROR_NO_MORE_ITEMS == nRet )
break; // All items are enumerated we are done here
if ( ERROR_SUCCESS == nRet )
{
//
// Must be flag as enable under the main ALG/ISV hive to be loaded
//
if ( IsAlgModuleEnable(KeyEnumISV, szID_AlgToLoad) )
{
MYTRACE("* %S Is 'ENABLE' make sure it's loaded", szID_AlgToLoad);
AddUniqueAndStart(KeyEnumISV, szID_AlgToLoad);
}
else
{
MYTRACE("* %S Is 'DISABLE' will not be loaded", szID_AlgToLoad);
}
}
else
{
MYTRACE_ERROR("RegEnumKeyEx", nRet);
}
} while ( ERROR_SUCCESS == nRet );
return nValidAlgLoaded;
}
//
// For all loaded ALG moudles calls the STOP method and release any resources
//
HRESULT
CCollectionAlgModules::Unload()
{
try
{
ENTER_AUTO_CS
MYTRACE_ENTER("CCollectionAlgModules::Unload ***");
MYTRACE("Colletion size is %d", m_ThisCollection.size());
HRESULT hr;
LISTOF_ALGMODULE::iterator theIterator;
while ( m_ThisCollection.size() > 0 )
{
theIterator = m_ThisCollection.begin();
delete (*theIterator);
m_ThisCollection.erase(theIterator);
}
}
catch(...)
{
return E_FAIL;
}
return S_OK;
}
| [
"blindtiger@foxmail.com"
] | blindtiger@foxmail.com |
e573ad88d944a1aee0d68041256d1d2b77a63467 | f2f6ba510a9e100ce791dc4398aad889751aec98 | /introduction_Cpp/graph_tests/GPrc23_compiletest/wgraph.h~ | 5fc722ebbe98829c4d706aaafd8479e3b5c6b64c | [] | no_license | davidbp/computer_science_basics | 0fd1a64d6f2b1457c94c0ab94c87ea248bbebaa8 | 69804ef146ac50e6e3e02781c02f5c4cdc1d298d | refs/heads/master | 2021-07-23T18:11:29.615023 | 2021-06-29T13:49:39 | 2021-06-29T13:49:39 | 134,683,909 | 0 | 1 | null | 2019-10-15T13:10:44 | 2018-05-24T08:17:25 | C++ | UTF-8 | C++ | false | false | 956 | #include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
typedef size_t vertex;
typedef size_t edge;
typedef size_t index;
typedef size_t degree;
typedef unsigned int component;
typedef unsigned int weight;
typedef vector<vector<pair<vertex,weight>> > wgraph;
wgraph wgraph_complete( index n, weight Mw );
wgraph wgraph_bipartite_complete(index n1, index n2, weight Mw);
wgraph wgraph_cycle(index n, weight Mw);
wgraph wgraph_star(index n, weight Mw);
wgraph wgraph_wheel(index n, weight Mw);
wgraph wgraph_read( string fname );
void wgraph_write( wgraph& G, ofstream& fout );
weight Dijkstra( wgraph &G, vertex sv, vertex tv );
weight Diameter( wgraph &G );
void Dijkstra( wgraph &G, vertex sv, ofstream& fout );
void DijkstraTree( wgraph &G, vertex sv, ofstream& fout );
weight KruskalTrees( wgraph &G, ofstream& fout );
weight PrimTrees( wgraph &G, ofstream& fout ); | [
"davidbuchaca@gmail.com"
] | davidbuchaca@gmail.com | |
55907b7628ee12ee7c4b989f635344c4ea4d6575 | 82c47f014e622395c649fbe383309a87414ff46a | /1-Introduction/1.4-Ad_Hoc_Problems/01-Game_(Card)/vitorvgc/12247.cpp | 549120d3ed05d8dd7d924663ad78eac4da67c5a3 | [
"MIT"
] | permissive | IFCE-CP/CP3-solutions | c2313abc34ee67a301fbf8429527257eed4b151e | 1abcabd9a06968184a55d3b0414637019014694c | refs/heads/master | 2018-07-09T02:06:47.263749 | 2018-06-01T03:56:11 | 2018-06-01T03:56:11 | 110,758,240 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 848 | cpp | #include <bits/stdc++.h>
using namespace std;
bool used[60];
int main() {
int a[3], b[2];
while(scanf("%d %d %d %d %d", &a[0], &a[1], &a[2], &b[0], &b[1]) && a[0]) {
int wins = 0;
memset(used, 0, sizeof used);
used[a[0]] = used[a[1]] = used[a[2]] = used[b[0]] = used[b[1]] = true;
vector<int> c(a, a+3);
sort(c.begin(), c.end());
sort(b, b+2);
for(int i = 0; i < 2; ++i) {
auto it = upper_bound(c.begin(), c.end(), b[i]);
if(it == c.end()) it = c.begin(), ++wins;
c.erase(it);
}
int ans;
if(wins == 2) ans = 1;
else if(wins == 1) ans = c[0] + 1;
else ans = -1;
for(; ans != -1 && used[ans]; ++ans);
if(ans > 52) ans = -1;
printf("%d\n", ans);
}
return 0;
}
| [
"vitorvgc07@gmail.com"
] | vitorvgc07@gmail.com |
f0e59451bcd9d79eedabb3a9a617521e96fe7a83 | 64d7cc6e293d9f06f4f31f444a64d74420ef7b65 | /inet/src/networklayer/diffserv/DiffservUtil.h | b12fe8b2eb5e6643faa8f20d6d35c633303ac4a5 | [] | no_license | floxyz/veins-lte | 73ab1a1034c4f958177f72849ebd5b5ef6e5e4db | 23c9aa10aa5e31c6c61a0d376b380566e594b38d | refs/heads/master | 2021-01-18T02:19:59.365549 | 2020-11-16T06:05:49 | 2020-11-16T06:05:49 | 27,383,107 | 19 | 12 | null | 2016-10-26T06:05:52 | 2014-12-01T14:31:19 | C++ | UTF-8 | C++ | false | false | 3,936 | h | //
// Copyright (C) 2012 Opensim Ltd.
// Author: Tamas Borbely
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public License
// as published by the Free Software Foundation; either version 2
// 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 __INET_DIFFSERVQUEUE_H
#define __INET_DIFFSERVQUEUE_H
#include "INETDefs.h"
namespace DiffservUtil
{
// colors for naming the output of meters
enum Color {GREEN, YELLOW, RED};
/**
* Returns true, if the string is empty (NULL or "");
*/
inline bool isEmpty(const char *str) { return !str || !(*str); }
/**
* Returns the value of the named attribute of the XML element,
* or throws an exception if not found.
*/
const char *getRequiredAttribute(cXMLElement *element, const char *attrName);
/**
* Parses the information rate parameter (bits/sec).
* Supported formats:
* - absolute (e.g. 10Mbps)
* - relative to the datarate of the interface (e.g. 10%)
*/
double parseInformationRate(const char *attrValue, const char *attrName, cSimpleModule &owner, int defaultValue);
/**
* Parses an integer attribute.
* Supports decimal, octal ("0" prefix), hexadecimal ("0x" prefix), and binary ("0b" prefix) bases.
*/
int parseIntAttribute(const char *attrValue, const char *attrName, bool isOptional = true);
/**
* Parses an IP protocol number.
* Recognizes the names defined in IPProtocolId.msg (e.g. "UDP", "udp", "Tcp"),
* and accepts decimal/octal/hex/binary numbers.
*/
int parseProtocol(const char *attrValue, const char *attrName);
/**
* Parses a Diffserv code point.
* Recognizes the names defined in DSCP.msg (e.g. "BE", "AF11"),
* and accepts decimal/octal/hex/binary numbers.
*/
int parseDSCP(const char *attrValue, const char *attrName);
/**
* Parses a space separated list of DSCP values and puts them into the result vector.
* "*" is interpreted as all possible DSCP values (i.e. the 0..63 range).
*/
void parseDSCPs(const char *attrValue, const char *attrName, std::vector<int> &result);
/**
* Returns the string representation of the given DSCP value.
* Values defined in DSCP.msg are returned as "BE", "AF11", etc.,
* others are returned as a decimal number.
*/
std::string dscpToString(int dscp);
/**
* Returns the string representation of the given color.
* For values defined in IMeter.h it returns their name,
* other values are returned as decimal constants.
*/
std::string colorToString(int color);
/**
* Returns the datarate of the interface containing the given module.
* Returns -1, if the interface entry not found.
*/
double getInterfaceDatarate(cSimpleModule *interfaceModule);
/**
* Returns the IP datagram encapsulated inside packet, or
* the packet itself if it is an IPv4/IPv6 datagram.
* Returns NULL, if there is no IP datagram in the packet.
*/
cPacket *findIPDatagramInPacket(cPacket *packet);
/**
* Returns the color of the packet.
* The color was set by a previous meter component.
* Returns -1, if the color was not set.
*/
int getColor(cPacket *packet);
/**
* Sets the color of the packet.
* The color is stored in the parlist of the cPacket object.
*/
void setColor(cPacket *packet, int color);
}
#endif
| [
"tomi.borbely@gmail.com"
] | tomi.borbely@gmail.com |
f97577f33bbb28b5e6e61c971fd8ff86aebb948d | 879681c994f1ca9c8d2c905a4e5064997ad25a27 | /root-2.3.0/run/tutorials/multiphase/twoPhaseEulerFoam/RAS/fluidisedBed/1.82/p | 373f1ba780d397ffc05cb11ccbf647113840874d | [] | no_license | MizuhaWatanabe/OpenFOAM-2.3.0-with-Ubuntu | 3828272d989d45fb020e83f8426b849e75560c62 | daeb870be81275e8a81f5cbac4ca1906a9bc69c0 | refs/heads/master | 2020-05-17T16:36:41.848261 | 2015-04-18T09:29:48 | 2015-04-18T09:29:48 | 34,159,882 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 46,714 | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: 2.3.0 |
| \\ / A nd | Web: www.OpenFOAM.org |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volScalarField;
location "1.82";
object p;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [1 -1 -2 0 0 0 0];
internalField nonuniform List<scalar>
6000
(
105355
105352
105348
105345
105340
105340
105341
105341
105341
105343
105345
105346
105349
105361
105383
105412
105447
105491
105528
105515
105455
105423
105446
105479
105497
105510
105518
105521
105523
105523
105291
105285
105281
105282
105285
105285
105286
105287
105287
105289
105292
105298
105305
105313
105328
105349
105374
105399
105417
105401
105372
105365
105366
105396
105423
105434
105441
105448
105457
105464
105241
105240
105242
105244
105247
105249
105250
105252
105255
105258
105261
105265
105271
105281
105294
105310
105330
105346
105351
105343
105326
105321
105317
105337
105376
105396
105400
105407
105418
105430
105203
105206
105208
105210
105212
105214
105216
105218
105221
105224
105227
105231
105237
105247
105259
105271
105283
105291
105294
105296
105283
105276
105273
105283
105320
105350
105358
105362
105369
105381
105175
105178
105177
105176
105177
105179
105180
105183
105186
105189
105192
105196
105202
105212
105223
105232
105237
105239
105241
105246
105235
105228
105225
105227
105260
105298
105316
105317
105320
105328
105150
105151
105148
105144
105144
105144
105145
105147
105150
105153
105157
105162
105167
105174
105182
105188
105188
105187
105188
105191
105184
105179
105177
105176
105200
105241
105268
105272
105273
105278
105124
105124
105119
105113
105110
105109
105110
105111
105114
105118
105123
105128
105132
105137
105140
105139
105135
105132
105130
105131
105133
105133
105133
105135
105150
105186
105216
105228
105229
105233
105095
105095
105090
105081
105076
105074
105074
105075
105079
105083
105089
105096
105100
105101
105097
105088
105080
105073
105070
105072
105086
105090
105095
105101
105110
105137
105168
105185
105187
105189
105062
105061
105058
105049
105041
105038
105037
105039
105043
105049
105057
105065
105069
105064
105050
105031
105021
105016
105020
105029
105043
105051
105060
105069
105078
105096
105124
105143
105147
105147
105020
105019
105020
105015
105006
105001
105000
105002
105007
105015
105025
105032
105033
105019
104992
104973
104969
104972
104982
104995
105007
105017
105026
105038
105047
105059
105080
105099
105106
105106
104966
104966
104973
104977
104969
104963
104960
104963
104970
104982
104992
104994
104987
104967
104948
104941
104942
104946
104955
104966
104976
104985
104994
105006
105012
105019
105032
105049
105061
105062
104895
104900
104915
104931
104931
104923
104918
104921
104933
104948
104953
104949
104942
104931
104925
104923
104923
104927
104933
104940
104947
104954
104962
104970
104972
104972
104978
104990
105005
105004
104813
104821
104841
104869
104885
104880
104872
104875
104893
104906
104903
104901
104903
104907
104909
104907
104905
104906
104909
104914
104919
104924
104930
104932
104927
104920
104917
104921
104931
104925
104710
104726
104754
104786
104817
104826
104817
104818
104834
104836
104839
104847
104859
104877
104889
104890
104887
104885
104885
104888
104892
104895
104898
104893
104878
104862
104849
104838
104831
104824
104594
104620
104658
104692
104719
104738
104737
104734
104734
104743
104765
104783
104804
104828
104853
104867
104868
104864
104862
104864
104866
104868
104865
104850
104823
104794
104766
104734
104705
104700
104526
104537
104568
104600
104607
104612
104625
104623
104612
104642
104685
104716
104741
104768
104796
104825
104841
104841
104840
104842
104843
104840
104827
104800
104759
104713
104659
104616
104600
104597
104492
104494
104504
104516
104513
104512
104523
104529
104531
104557
104601
104643
104674
104704
104735
104767
104799
104813
104816
104819
104817
104805
104780
104739
104685
104620
104578
104566
104563
104561
104469
104469
104468
104466
104460
104461
104467
104474
104484
104504
104533
104571
104605
104638
104671
104704
104738
104768
104782
104786
104778
104756
104721
104674
104612
104564
104551
104548
104547
104545
104450
104451
104445
104436
104428
104427
104429
104433
104447
104461
104476
104505
104537
104569
104603
104635
104666
104699
104724
104728
104716
104692
104659
104615
104563
104543
104539
104536
104535
104533
104431
104430
104421
104408
104398
104393
104391
104395
104404
104402
104410
104436
104467
104499
104531
104560
104586
104616
104640
104648
104642
104627
104603
104570
104540
104530
104527
104525
104523
104521
104404
104398
104386
104374
104365
104360
104356
104354
104341
104317
104326
104359
104395
104429
104458
104483
104506
104533
104557
104570
104574
104569
104558
104540
104523
104518
104516
104513
104511
104509
104353
104342
104332
104329
104328
104324
104316
104295
104255
104233
104244
104274
104321
104355
104385
104406
104431
104460
104484
104500
104509
104514
104516
104516
104507
104504
104502
104500
104498
104496
104271
104264
104261
104265
104273
104266
104244
104213
104194
104191
104195
104216
104257
104292
104315
104337
104369
104396
104415
104429
104442
104455
104470
104488
104486
104484
104483
104482
104481
104481
104173
104172
104175
104180
104187
104178
104166
104162
104164
104168
104171
104181
104205
104235
104256
104285
104314
104333
104344
104354
104365
104382
104407
104443
104454
104454
104454
104456
104457
104458
104115
104116
104118
104121
104125
104128
104132
104138
104144
104149
104153
104159
104174
104198
104218
104239
104258
104266
104267
104269
104275
104291
104319
104363
104400
104407
104409
104414
104418
104420
104097
104098
104099
104101
104105
104111
104117
104123
104129
104133
104137
104142
104152
104167
104191
104195
104198
104191
104180
104169
104167
104176
104202
104248
104307
104331
104339
104347
104354
104358
104091
104092
104092
104094
104098
104102
104107
104111
104115
104119
104123
104127
104134
104144
104150
104143
104127
104104
104074
104047
104031
104032
104057
104104
104166
104215
104237
104250
104260
104264
104086
104086
104087
104089
104091
104094
104097
104100
104103
104105
104108
104111
104118
104126
104107
104083
104048
104001
103947
103891
103856
103861
103895
103948
104010
104068
104107
104129
104143
104148
104080
104080
104081
104082
104083
104085
104087
104089
104091
104092
104093
104095
104098
104098
104061
104016
103957
103884
103791
103687
103663
103694
103742
103798
103860
103920
103966
103997
104016
104024
104072
104072
104073
104074
104075
104076
104077
104078
104078
104078
104077
104075
104073
104061
104008
103941
103857
103747
103631
103574
103563
103576
103612
103662
103723
103782
103832
103866
103887
103898
104063
104063
104064
104064
104065
104066
104066
104066
104065
104063
104058
104049
104035
104011
103946
103862
103748
103625
103556
103534
103528
103525
103529
103550
103593
103653
103708
103744
103763
103771
104053
104053
104054
104054
104054
104054
104054
104053
104051
104045
104033
104012
103980
103941
103878
103782
103669
103572
103530
103514
103506
103499
103494
103494
103506
103543
103597
103634
103646
103645
104042
104042
104042
104043
104042
104042
104041
104039
104033
104022
103999
103962
103913
103857
103793
103712
103624
103548
103510
103493
103484
103478
103474
103471
103471
103482
103513
103540
103538
103518
104030
104030
104030
104030
104030
104029
104027
104022
104011
103989
103952
103901
103843
103782
103719
103653
103586
103525
103486
103468
103460
103457
103455
103454
103454
103457
103467
103467
103440
103417
104016
104016
104016
104016
104015
104013
104008
103999
103978
103942
103892
103836
103776
103718
103662
103606
103551
103498
103457
103440
103435
103435
103435
103436
103438
103440
103439
103425
103389
103378
104000
104000
103999
103999
103996
103992
103983
103965
103931
103883
103829
103773
103717
103664
103613
103563
103514
103465
103423
103409
103410
103412
103414
103417
103421
103423
103412
103385
103367
103364
103979
103979
103978
103976
103971
103963
103946
103915
103871
103821
103768
103714
103663
103614
103566
103520
103474
103426
103388
103381
103385
103389
103393
103398
103404
103402
103385
103362
103356
103356
103952
103951
103949
103944
103935
103919
103891
103851
103806
103758
103708
103658
103610
103563
103518
103474
103429
103381
103352
103355
103360
103366
103372
103379
103385
103380
103360
103348
103347
103348
103914
103912
103908
103899
103883
103857
103822
103782
103739
103694
103648
103601
103555
103510
103466
103422
103377
103333
103322
103330
103337
103344
103351
103359
103364
103356
103340
103338
103340
103340
103860
103856
103848
103834
103812
103783
103749
103712
103673
103631
103587
103543
103498
103454
103409
103363
103318
103294
103297
103306
103314
103322
103330
103337
103340
103334
103328
103330
103332
103333
103787
103781
103772
103756
103734
103707
103677
103644
103608
103569
103527
103484
103440
103395
103349
103303
103272
103266
103273
103282
103291
103300
103308
103314
103318
103317
103319
103322
103325
103326
103705
103700
103691
103676
103657
103634
103607
103578
103545
103507
103468
103426
103383
103338
103292
103254
103238
103241
103250
103259
103269
103280
103289
103295
103301
103306
103311
103315
103318
103320
103626
103622
103613
103600
103584
103564
103542
103516
103485
103449
103411
103370
103329
103286
103245
103217
103209
103215
103224
103235
103248
103261
103272
103281
103290
103298
103303
103307
103311
103312
103554
103550
103542
103531
103517
103500
103481
103458
103428
103394
103357
103318
103278
103239
103204
103184
103181
103187
103197
103209
103224
103240
103255
103268
103280
103290
103296
103300
103302
103302
103487
103483
103477
103468
103456
103441
103424
103402
103375
103342
103307
103269
103232
103196
103165
103148
103150
103156
103166
103179
103195
103213
103231
103248
103265
103278
103285
103287
103284
103284
103424
103421
103416
103408
103397
103384
103368
103348
103323
103293
103260
103225
103190
103155
103127
103114
103118
103123
103131
103141
103153
103170
103192
103214
103233
103248
103256
103253
103247
103248
103364
103361
103356
103349
103339
103327
103312
103294
103273
103248
103218
103185
103152
103120
103095
103085
103087
103090
103093
103096
103101
103112
103134
103159
103178
103193
103200
103201
103198
103198
103306
103303
103299
103292
103282
103271
103257
103242
103225
103205
103178
103149
103119
103090
103069
103061
103059
103058
103055
103052
103048
103050
103063
103088
103113
103132
103144
103148
103144
103143
103251
103248
103243
103237
103228
103218
103207
103195
103181
103164
103142
103116
103090
103066
103048
103039
103035
103029
103023
103014
103005
102997
102995
103012
103047
103077
103097
103100
103091
103088
103200
103197
103192
103186
103178
103170
103161
103151
103140
103126
103108
103087
103065
103044
103029
103020
103013
103006
102998
102988
102978
102970
102966
102968
102985
103026
103052
103058
103052
103050
103152
103149
103145
103139
103133
103125
103117
103109
103100
103090
103077
103061
103043
103024
103011
103004
102995
102988
102981
102973
102965
102959
102956
102954
102958
102975
103011
103025
103028
103028
103104
103103
103099
103095
103090
103083
103076
103069
103062
103055
103046
103035
103022
103007
102991
102987
102977
102971
102966
102960
102955
102952
102949
102948
102947
102953
102975
102998
103007
103011
103055
103055
103053
103050
103046
103042
103037
103032
103027
103021
103015
103007
102997
102983
102967
102966
102959
102955
102951
102948
102945
102942
102941
102941
102941
102941
102952
102972
102982
102988
103004
103004
103003
103001
102999
102997
102995
102993
102990
102987
102982
102974
102963
102947
102935
102937
102941
102939
102937
102935
102933
102932
102932
102933
102934
102933
102936
102948
102956
102960
102953
102953
102952
102951
102950
102949
102949
102948
102948
102948
102945
102941
102933
102923
102915
102915
102921
102923
102923
102922
102922
102921
102923
102925
102926
102925
102925
102927
102931
102934
102902
102901
102901
102900
102900
102901
102902
102903
102906
102908
102910
102911
102912
102911
102904
102902
102905
102908
102909
102909
102909
102909
102912
102915
102916
102916
102913
102910
102909
102911
102851
102850
102850
102850
102851
102853
102855
102859
102863
102869
102875
102882
102891
102898
102894
102892
102893
102895
102896
102896
102895
102896
102900
102903
102904
102903
102899
102893
102890
102890
102797
102797
102798
102799
102801
102804
102808
102814
102821
102829
102840
102853
102869
102883
102883
102881
102880
102881
102882
102881
102881
102882
102886
102889
102889
102887
102881
102875
102870
102870
102740
102741
102742
102745
102748
102753
102760
102768
102777
102789
102804
102823
102846
102866
102871
102868
102867
102867
102866
102866
102866
102867
102869
102871
102871
102867
102860
102854
102851
102849
102678
102680
102682
102686
102691
102698
102707
102718
102732
102748
102769
102794
102822
102848
102857
102855
102853
102852
102851
102850
102850
102850
102852
102851
102850
102845
102839
102833
102830
102829
102614
102616
102619
102623
102630
102639
102650
102664
102682
102704
102731
102762
102795
102828
102841
102841
102838
102837
102835
102834
102834
102834
102833
102831
102828
102823
102817
102812
102809
102808
102550
102551
102555
102560
102568
102578
102592
102608
102628
102654
102686
102724
102764
102804
102824
102827
102824
102822
102820
102819
102818
102818
102816
102813
102809
102803
102796
102790
102788
102787
102486
102488
102492
102498
102507
102519
102534
102551
102571
102597
102633
102677
102728
102778
102806
102812
102810
102808
102806
102805
102804
102804
102802
102799
102793
102783
102774
102768
102765
102763
102425
102427
102432
102440
102452
102467
102486
102506
102525
102546
102574
102621
102682
102747
102788
102798
102797
102795
102793
102792
102791
102790
102789
102787
102777
102762
102751
102743
102739
102737
102366
102370
102377
102388
102405
102427
102451
102475
102494
102509
102525
102559
102624
102704
102769
102784
102785
102783
102781
102780
102780
102779
102777
102774
102756
102736
102722
102714
102708
102706
102310
102315
102326
102342
102363
102387
102416
102450
102477
102487
102490
102505
102559
102649
102737
102769
102773
102771
102770
102770
102769
102767
102764
102756
102726
102701
102687
102678
102673
102670
102256
102263
102277
102297
102321
102346
102372
102400
102432
102457
102455
102455
102491
102577
102683
102748
102761
102761
102759
102760
102759
102755
102746
102725
102682
102655
102643
102637
102633
102632
102201
102210
102226
102244
102260
102277
102297
102322
102356
102397
102401
102398
102418
102492
102606
102707
102741
102746
102745
102745
102742
102732
102710
102664
102627
102607
102596
102588
102587
102593
102142
102150
102159
102168
102178
102191
102207
102232
102268
102311
102323
102324
102338
102399
102508
102625
102700
102717
102715
102708
102697
102679
102643
102605
102583
102571
102562
102558
102557
102562
102072
102074
102078
102081
102086
102093
102107
102133
102170
102212
102231
102239
102256
102307
102404
102518
102617
102657
102654
102637
102619
102601
102580
102564
102553
102545
102539
102535
102534
102537
101991
101991
101990
101987
101983
101989
102004
102030
102071
102106
102130
102150
102173
102219
102303
102410
102512
102573
102579
102566
102554
102543
102535
102530
102525
102521
102518
102517
102517
102515
101905
101903
101897
101889
101887
101897
101919
101945
101974
102006
102034
102061
102092
102135
102209
102307
102409
102488
102513
102509
102502
102498
102497
102498
102498
102497
102496
102495
102493
102488
101817
101813
101808
101811
101820
101831
101849
101872
101897
101922
101948
101979
102015
102054
102120
102209
102308
102399
102448
102457
102454
102454
102460
102465
102466
102464
102461
102457
102447
102433
101727
101732
101740
101754
101769
101782
101794
101807
101824
101845
101872
101904
101939
101974
102033
102114
102206
102298
102368
102395
102401
102407
102416
102420
102415
102407
102396
102380
102364
102353
101643
101665
101684
101706
101724
101736
101742
101749
101760
101777
101798
101820
101844
101881
101940
102018
102105
102193
102266
102308
102327
102340
102345
102340
102326
102310
102294
102279
102266
102257
101581
101602
101633
101656
101672
101683
101688
101691
101696
101703
101710
101710
101719
101762
101832
101916
102005
102089
102158
102197
102218
102229
102222
102216
102206
102192
102179
102169
102162
102158
101549
101554
101569
101591
101606
101612
101612
101611
101612
101609
101601
101590
101599
101642
101713
101806
101906
101992
102057
102088
102099
102091
102083
102084
102081
102071
102063
102058
102056
102063
101533
101532
101533
101536
101539
101540
101541
101540
101538
101534
101531
101533
101541
101562
101608
101697
101812
101906
101971
102000
102008
102000
101996
101991
101985
101983
101982
101982
101982
101987
101524
101523
101520
101517
101515
101513
101512
101510
101508
101507
101508
101512
101518
101529
101554
101622
101734
101836
101905
101936
101947
101949
101949
101944
101943
101945
101947
101949
101950
101951
101517
101516
101514
101512
101509
101507
101505
101503
101501
101500
101501
101504
101507
101513
101529
101580
101681
101784
101857
101890
101905
101915
101919
101921
101923
101926
101929
101932
101934
101935
101510
101509
101508
101506
101504
101502
101500
101499
101498
101497
101497
101498
101499
101502
101512
101553
101642
101745
101822
101854
101871
101886
101895
101902
101907
101911
101915
101918
101921
101925
101504
101504
101503
101501
101499
101497
101495
101494
101493
101492
101492
101492
101492
101492
101497
101530
101609
101709
101791
101822
101840
101857
101871
101882
101890
101896
101901
101906
101910
101914
101499
101498
101497
101495
101493
101491
101489
101488
101487
101486
101486
101486
101485
101482
101483
101507
101576
101669
101753
101789
101807
101825
101842
101856
101868
101877
101883
101889
101893
101892
101493
101492
101491
101489
101487
101485
101483
101482
101481
101481
101480
101479
101478
101475
101473
101487
101543
101627
101706
101749
101769
101788
101807
101823
101837
101847
101855
101860
101857
101850
101487
101486
101485
101483
101481
101479
101478
101477
101476
101475
101474
101473
101472
101470
101467
101472
101508
101583
101657
101699
101725
101746
101766
101782
101795
101805
101810
101808
101803
101796
101481
101480
101479
101477
101475
101473
101472
101471
101471
101470
101469
101468
101468
101466
101464
101463
101481
101540
101605
101645
101676
101700
101719
101734
101744
101751
101753
101751
101745
101738
101475
101474
101473
101471
101469
101468
101467
101466
101466
101465
101465
101464
101464
101463
101462
101459
101466
101499
101550
101592
101626
101651
101669
101682
101691
101696
101697
101695
101689
101684
101470
101469
101467
101466
101464
101463
101463
101462
101461
101461
101460
101460
101460
101459
101459
101457
101459
101474
101510
101549
101580
101603
101620
101632
101641
101645
101646
101645
101641
101639
101464
101463
101462
101461
101460
101459
101458
101458
101457
101457
101457
101456
101456
101456
101455
101454
101454
101463
101486
101515
101542
101563
101577
101588
101595
101600
101601
101601
101602
101599
101459
101459
101458
101456
101456
101455
101455
101454
101454
101453
101453
101453
101452
101452
101451
101451
101450
101453
101468
101491
101513
101530
101541
101550
101557
101562
101563
101563
101563
101563
101455
101454
101454
101453
101452
101452
101451
101451
101450
101450
101450
101449
101449
101448
101448
101447
101446
101444
101454
101473
101490
101503
101511
101517
101522
101526
101529
101531
101531
101533
101451
101451
101450
101449
101449
101449
101448
101448
101447
101447
101446
101446
101445
101445
101444
101443
101442
101439
101446
101459
101471
101479
101486
101492
101495
101497
101500
101502
101504
101511
101448
101447
101447
101446
101446
101446
101445
101445
101444
101444
101443
101443
101442
101442
101441
101440
101439
101437
101439
101447
101455
101462
101468
101472
101476
101477
101479
101482
101486
101494
101444
101444
101443
101443
101443
101443
101443
101442
101442
101441
101440
101440
101439
101439
101438
101437
101436
101435
101434
101439
101443
101448
101452
101456
101459
101460
101461
101465
101472
101476
101441
101440
101440
101440
101440
101440
101440
101440
101439
101438
101437
101437
101436
101435
101435
101434
101434
101433
101432
101435
101435
101437
101439
101441
101441
101441
101444
101450
101456
101460
101437
101437
101437
101437
101437
101437
101437
101437
101436
101435
101435
101434
101433
101432
101432
101432
101431
101431
101430
101431
101430
101429
101428
101427
101425
101426
101431
101437
101442
101445
101433
101433
101433
101433
101433
101434
101434
101433
101433
101432
101432
101431
101430
101429
101429
101429
101428
101428
101428
101428
101427
101423
101420
101417
101415
101417
101422
101426
101431
101432
101429
101429
101429
101429
101430
101430
101430
101430
101430
101429
101428
101428
101427
101426
101426
101426
101426
101426
101425
101425
101426
101421
101415
101411
101410
101411
101414
101418
101421
101421
101424
101424
101425
101425
101426
101426
101426
101426
101426
101425
101425
101424
101423
101423
101423
101423
101423
101423
101423
101423
101425
101421
101412
101408
101406
101406
101407
101409
101410
101411
101418
101418
101419
101421
101422
101422
101422
101422
101422
101421
101421
101420
101420
101419
101419
101420
101420
101421
101422
101421
101422
101422
101411
101406
101403
101401
101400
101400
101399
101399
101412
101412
101413
101415
101416
101418
101418
101418
101417
101417
101416
101416
101416
101415
101416
101416
101417
101418
101419
101419
101420
101422
101413
101406
101401
101397
101394
101391
101390
101389
101405
101405
101406
101408
101410
101412
101414
101414
101413
101412
101411
101411
101411
101411
101412
101412
101413
101414
101416
101417
101417
101418
101413
101404
101397
101391
101386
101381
101379
101378
101399
101397
101397
101399
101402
101405
101408
101409
101408
101407
101406
101406
101406
101407
101407
101408
101409
101411
101412
101412
101411
101409
101406
101396
101388
101381
101373
101366
101362
101358
101392
101391
101388
101389
101392
101397
101401
101403
101403
101402
101401
101401
101402
101402
101403
101404
101405
101407
101408
101407
101402
101395
101385
101376
101368
101360
101352
101343
101337
101333
101384
101382
101381
101381
101383
101388
101393
101397
101398
101396
101396
101396
101397
101397
101398
101399
101401
101402
101402
101399
101391
101381
101369
101356
101345
101334
101324
101316
101309
101307
101369
101372
101373
101374
101376
101380
101386
101391
101391
101391
101390
101391
101392
101393
101393
101394
101396
101396
101395
101390
101378
101364
101350
101336
101322
101309
101297
101288
101281
101279
101349
101356
101363
101367
101370
101374
101380
101385
101385
101385
101386
101386
101387
101388
101389
101390
101391
101390
101387
101380
101365
101346
101328
101312
101297
101282
101270
101260
101253
101250
101332
101340
101348
101355
101362
101369
101375
101379
101379
101380
101381
101381
101382
101383
101384
101385
101386
101385
101380
101369
101350
101326
101303
101285
101268
101253
101240
101230
101223
101221
101320
101321
101330
101343
101353
101362
101370
101373
101374
101375
101376
101377
101378
101379
101380
101381
101382
101380
101374
101357
101331
101303
101277
101255
101237
101222
101210
101200
101193
101191
101307
101309
101316
101328
101341
101353
101363
101367
101369
101371
101372
101373
101374
101374
101375
101376
101377
101376
101367
101344
101311
101278
101249
101225
101205
101189
101177
101167
101161
101158
101296
101299
101304
101315
101329
101343
101355
101362
101365
101367
101368
101369
101370
101370
101371
101372
101372
101369
101355
101324
101288
101254
101222
101195
101173
101156
101142
101132
101126
101122
101286
101289
101295
101305
101319
101335
101348
101357
101361
101363
101364
101365
101366
101366
101367
101368
101367
101361
101340
101301
101260
101222
101189
101161
101137
101119
101104
101094
101087
101083
101273
101277
101285
101296
101310
101327
101342
101352
101357
101360
101361
101361
101362
101362
101363
101363
101361
101352
101324
101275
101224
101180
101144
101116
101094
101076
101062
101052
101045
101041
101258
101262
101272
101285
101300
101319
101334
101345
101352
101356
101357
101358
101358
101359
101359
101359
101356
101343
101304
101239
101177
101127
101090
101064
101046
101030
101016
101006
101000
100996
101238
101244
101254
101270
101289
101309
101324
101336
101345
101351
101354
101354
101355
101356
101357
101356
101352
101333
101268
101189
101118
101065
101033
101013
100998
100983
100969
100959
100953
100950
101214
101220
101231
101249
101271
101295
101310
101322
101335
101345
101350
101351
101352
101353
101354
101353
101345
101305
101215
101127
101058
101013
100989
100972
100957
100939
100923
100913
100906
100903
101185
101191
101204
101222
101246
101273
101287
101299
101316
101333
101344
101347
101348
101350
101351
101348
101325
101246
101152
101072
101015
100980
100956
100935
100915
100897
100882
100869
100861
100857
101151
101157
101171
101190
101214
101241
101254
101267
101285
101308
101328
101338
101341
101344
101344
101328
101260
101160
101077
101015
100975
100947
100923
100900
100877
100856
100840
100825
100815
100811
101111
101118
101133
101153
101178
101201
101215
101228
101245
101267
101294
101314
101324
101328
101316
101251
101143
101046
100975
100926
100896
100880
100871
100859
100839
100815
100796
100781
100770
100764
101065
101075
101090
101112
101138
101157
101172
101186
101202
101220
101242
101267
101286
101281
101218
101104
100990
100896
100835
100804
100789
100785
100788
100790
100791
100775
100753
100736
100724
100717
101028
101033
101045
101066
101092
101110
101128
101144
101158
101173
101189
101208
101214
101159
101051
100926
100802
100706
100664
100652
100655
100670
100687
100704
100719
100727
100714
100696
100682
100673
101002
101002
101007
101021
101040
101062
101082
101100
101114
101127
101139
101142
101097
100994
100869
100733
100613
100552
100529
100523
100526
100542
100573
100603
100629
100650
100661
100657
100642
100630
100984
100980
100980
100985
100996
101016
101036
101053
101067
101078
101080
101044
100943
100822
100688
100562
100480
100458
100450
100446
100444
100447
100461
100492
100526
100554
100577
100590
100595
100585
100968
100963
100961
100960
100965
100975
100988
101001
101012
101014
100984
100893
100777
100651
100528
100438
100397
100393
100396
100397
100392
100386
100384
100394
100419
100451
100479
100503
100519
100527
100946
100943
100940
100937
100935
100936
100941
100946
100945
100916
100838
100732
100612
100489
100389
100336
100324
100331
100345
100352
100348
100339
100330
100324
100328
100345
100375
100408
100432
100443
100897
100910
100910
100907
100900
100895
100893
100886
100857
100788
100691
100577
100451
100335
100256
100229
100244
100267
100290
100299
100299
100291
100279
100266
100255
100247
100263
100309
100342
100357
100826
100843
100855
100859
100853
100845
100835
100810
100749
100660
100553
100430
100302
100202
100157
100151
100165
100195
100224
100237
100240
100235
100223
100207
100188
100174
100183
100209
100252
100275
100755
100766
100779
100785
100785
100777
100759
100712
100634
100539
100426
100298
100185
100134
100122
100121
100125
100136
100158
100173
100180
100177
100167
100152
100138
100135
100139
100152
100176
100202
100687
100693
100700
100703
100701
100690
100664
100606
100526
100429
100311
100194
100130
100114
100113
100113
100113
100114
100119
100126
100131
100130
100124
100119
100116
100117
100121
100127
100138
100151
100620
100625
100626
100623
100616
100601
100567
100507
100429
100332
100221
100142
100113
100109
100110
100110
100108
100106
100104
100105
100106
100107
100106
100106
100107
100110
100112
100115
100119
100127
100556
100559
100557
100549
100537
100516
100478
100419
100345
100258
100170
100120
100107
100106
100107
100106
100105
100102
100100
100098
100098
100099
100100
100101
100104
100105
100106
100107
100106
100110
100499
100499
100494
100482
100465
100440
100400
100344
100275
100205
100140
100107
100101
100102
100103
100102
100101
100099
100098
100097
100097
100097
100098
100099
100100
100101
100102
100101
100097
100097
100448
100443
100435
100420
100400
100373
100334
100280
100220
100161
100115
100097
100097
100098
100098
100098
100097
100096
100095
100095
100095
100095
100096
100097
100097
100098
100098
100097
100090
100089
100392
100389
100380
100364
100344
100316
100278
100228
100175
100128
100098
100092
100093
100094
100094
100094
100093
100093
100093
100093
100093
100093
100093
100094
100094
100095
100095
100093
100086
100085
100332
100332
100328
100315
100295
100268
100232
100187
100141
100105
100090
100089
100090
100090
100090
100090
100090
100090
100090
100090
100091
100091
100091
100091
100092
100092
100092
100090
100085
100085
100286
100286
100286
100274
100255
100230
100196
100156
100117
100093
100085
100086
100087
100087
100087
100087
100087
100087
100088
100088
100088
100088
100089
100089
100089
100089
100089
100088
100087
100089
100254
100252
100254
100242
100225
100202
100169
100133
100102
100087
100083
100084
100084
100084
100084
100084
100085
100085
100085
100086
100086
100086
100086
100087
100087
100087
100087
100087
100088
100090
100228
100226
100224
100217
100202
100180
100148
100115
100092
100082
100080
100081
100081
100081
100082
100082
100082
100083
100083
100084
100084
100084
100084
100084
100085
100085
100085
100085
100089
100088
100205
100203
100198
100192
100183
100161
100130
100102
100086
100078
100078
100079
100079
100079
100079
100080
100080
100081
100081
100081
100082
100082
100082
100082
100083
100083
100084
100083
100087
100086
100184
100182
100179
100173
100166
100144
100115
100091
100080
100075
100076
100076
100076
100077
100077
100078
100078
100079
100079
100079
100080
100080
100080
100080
100081
100081
100082
100083
100088
100085
100164
100163
100161
100158
100148
100127
100102
100081
100073
100072
100073
100074
100074
100075
100075
100076
100076
100076
100077
100077
100078
100078
100078
100079
100079
100079
100080
100085
100088
100086
100145
100145
100145
100143
100131
100112
100091
100076
100069
100070
100071
100071
100072
100072
100073
100073
100074
100075
100075
100075
100076
100076
100076
100077
100077
100077
100079
100087
100091
100088
100128
100128
100129
100128
100117
100099
100080
100071
100067
100068
100068
100069
100069
100070
100071
100071
100072
100073
100073
100074
100074
100074
100075
100075
100075
100075
100077
100088
100098
100099
100112
100112
100113
100113
100105
100089
100073
100066
100065
100065
100066
100066
100067
100068
100068
100069
100070
100070
100071
100072
100072
100072
100073
100073
100073
100073
100075
100084
100108
100104
100097
100097
100098
100099
100096
100081
100070
100062
100062
100063
100063
100064
100065
100065
100066
100066
100067
100068
100069
100069
100070
100070
100070
100071
100071
100071
100072
100077
100091
100098
100084
100082
100084
100085
100085
100073
100063
100060
100060
100060
100061
100061
100062
100062
100063
100064
100064
100065
100066
100067
100067
100068
100068
100068
100068
100069
100070
100072
100079
100084
100072
100069
100070
100072
100072
100065
100058
100056
100057
100057
100058
100058
100059
100059
100060
100061
100061
100062
100063
100064
100064
100065
100065
100066
100066
100066
100067
100069
100072
100075
100061
100057
100059
100060
100061
100056
100053
100053
100053
100054
100055
100055
100056
100056
100057
100057
100058
100059
100060
100060
100061
100062
100062
100063
100063
100063
100064
100065
100067
100069
100049
100048
100049
100051
100053
100050
100048
100049
100050
100051
100051
100052
100053
100053
100054
100054
100055
100056
100056
100057
100058
100059
100059
100059
100060
100060
100060
100061
100061
100062
100038
100039
100040
100043
100047
100045
100044
100045
100046
100047
100048
100049
100049
100050
100050
100051
100052
100052
100053
100054
100055
100055
100056
100056
100056
100057
100056
100056
100055
100056
100029
100029
100032
100037
100044
100041
100041
100042
100043
100044
100044
100045
100046
100047
100047
100048
100048
100049
100050
100051
100051
100052
100052
100053
100053
100053
100052
100051
100049
100050
100022
100023
100027
100034
100041
100037
100037
100038
100039
100040
100041
100042
100043
100043
100044
100045
100045
100046
100047
100047
100048
100049
100049
100049
100049
100049
100048
100045
100043
100043
100018
100019
100023
100033
100036
100034
100035
100035
100036
100037
100038
100039
100040
100040
100041
100042
100042
100043
100044
100044
100045
100045
100046
100046
100045
100045
100044
100040
100035
100036
100017
100018
100024
100033
100031
100031
100032
100033
100034
100034
100035
100036
100037
100038
100038
100039
100040
100040
100041
100041
100042
100042
100042
100042
100041
100040
100039
100034
100029
100029
100021
100022
100028
100031
100029
100029
100029
100030
100031
100032
100032
100033
100034
100035
100036
100037
100037
100038
100038
100038
100038
100038
100038
100037
100035
100034
100032
100026
100022
100020
100019
100021
100025
100025
100025
100026
100027
100028
100028
100029
100030
100030
100031
100032
100033
100034
100034
100034
100034
100034
100034
100033
100031
100029
100027
100023
100017
100012
100011
100008
100014
100014
100016
100019
100022
100023
100024
100025
100026
100026
100027
100027
100028
100029
100029
100029
100029
100029
100028
100027
100026
100023
100021
100018
100015
100010
100006
100005
100005
100005
100011
100011
100011
100014
100017
100019
100020
100022
100023
100023
100024
100024
100024
100024
100024
100023
100023
100021
100019
100017
100014
100011
100009
100008
100006
100005
100004
100004
100004
100004
100009
100009
100009
100010
100012
100014
100015
100016
100018
100019
100019
100019
100018
100018
100017
100016
100014
100012
100010
100008
100006
100004
100004
100004
100004
100004
100004
100004
100004
100004
100008
100008
100007
100007
100008
100009
100010
100011
100012
100013
100013
100013
100012
100011
100010
100009
100008
100006
100005
100004
100003
100003
100003
100003
100004
100004
100004
100004
100004
100004
100007
100007
100007
100006
100006
100006
100006
100007
100007
100008
100008
100008
100007
100007
100006
100005
100005
100004
100004
100004
100004
100004
100004
100004
100004
100004
100004
100004
100004
100004
100006
100006
100006
100006
100006
100005
100005
100005
100005
100005
100005
100005
100005
100005
100005
100005
100005
100004
100004
100004
100004
100004
100003
100003
100003
100004
100004
100004
100004
100004
100006
100006
100006
100006
100006
100005
100005
100005
100005
100005
100005
100005
100005
100005
100005
100005
100004
100004
100004
100004
100003
100003
100003
100003
100003
100003
100003
100003
100003
100003
100006
100006
100006
100006
100006
100005
100005
100005
100005
100005
100005
100005
100005
100005
100005
100004
100004
100004
100004
100003
100003
100003
100003
100003
100003
100003
100003
100003
100003
100003
100006
100006
100006
100006
100005
100005
100005
100005
100005
100005
100004
100004
100004
100004
100004
100004
100004
100004
100003
100003
100003
100003
100003
100003
100003
100003
100003
100003
100003
100003
100006
100006
100006
100005
100005
100005
100005
100005
100005
100004
100004
100004
100004
100004
100003
100003
100003
100003
100003
100003
100003
100003
100003
100003
100003
100003
100003
100003
100003
100003
100005
100005
100005
100005
100005
100005
100005
100004
100004
100004
100004
100004
100004
100003
100003
100003
100003
100003
100003
100003
100003
100003
100003
100003
100003
100003
100002
100002
100002
100002
100005
100005
100005
100005
100005
100005
100004
100004
100004
100004
100004
100004
100003
100003
100003
100002
100002
100002
100002
100002
100002
100003
100003
100003
100002
100002
100002
100002
100002
100002
100005
100005
100005
100005
100004
100004
100004
100004
100004
100004
100004
100003
100003
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100004
100004
100004
100004
100004
100004
100004
100004
100004
100004
100003
100003
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100001
100001
100001
100001
100001
100004
100004
100004
100004
100004
100004
100004
100004
100003
100003
100003
100002
100002
100002
100002
100002
100002
100001
100001
100001
100002
100002
100002
100001
100001
100001
100001
100001
100001
100001
100003
100003
100003
100003
100003
100003
100003
100003
100003
100003
100003
100002
100002
100002
100002
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100003
100002
100002
100003
100003
100003
100003
100003
100003
100002
100002
100002
100002
100002
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100000
100000
100000
100001
100001
100001
100001
100001
100001
100002
100001
100001
100001
100001
100001
100002
100002
100002
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100000
100000
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100001
100001
100000
100000
100000
100000
100000
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100001
100001
100001
100001
100001
100001
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100001
100001
100001
100001
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
)
;
boundaryField
{
inlet
{
type fixedFluxPressure;
gradient nonuniform List<scalar>
30
(
51.3127
52.1937
53.3685
48.0116
30.0548
36.8929
36.8912
36.9284
45.8549
51.5181
49.598
34.5272
32.8777
45.8917
59.4762
67.9693
81.5838
118.286
145.065
148.1
88.8221
39.6536
90.1582
89.3317
80.8646
81.1256
80.8633
79.2901
71.0301
64.3062
)
;
value nonuniform List<scalar>
30
(
105355
105353
105348
105346
105340
105340
105341
105341
105341
105343
105345
105346
105350
105361
105383
105412
105447
105491
105528
105516
105455
105423
105446
105479
105498
105511
105518
105522
105523
105524
)
;
}
outlet
{
type fixedValue;
value uniform 100000;
}
walls
{
type fixedFluxPressure;
gradient uniform 0;
value nonuniform List<scalar>
400
(
105355
105291
105241
105203
105175
105150
105124
105095
105062
105020
104966
104895
104813
104710
104594
104526
104492
104469
104450
104431
104404
104353
104271
104173
104115
104097
104091
104086
104080
104072
104063
104053
104042
104030
104016
104000
103979
103952
103914
103860
103787
103705
103626
103554
103487
103424
103364
103306
103251
103200
103152
103104
103055
103004
102953
102902
102851
102797
102740
102678
102614
102550
102486
102425
102366
102310
102256
102201
102142
102072
101991
101905
101817
101727
101643
101581
101549
101533
101524
101517
101510
101504
101499
101493
101487
101481
101475
101470
101464
101459
101455
101451
101448
101444
101441
101437
101433
101429
101424
101418
101412
101405
101399
101392
101384
101369
101349
101332
101320
101307
101296
101286
101273
101258
101238
101214
101185
101151
101111
101065
101028
101002
100984
100968
100946
100897
100826
100755
100687
100620
100556
100499
100448
100392
100332
100286
100254
100228
100205
100184
100164
100145
100128
100112
100097
100084
100072
100061
100049
100038
100029
100022
100018
100017
100021
100019
100014
100011
100009
100008
100007
100006
100006
100006
100006
100006
100005
100005
100005
100004
100004
100003
100003
100002
100002
100001
100001
100001
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
105523
105464
105430
105381
105328
105278
105233
105189
105147
105106
105062
105004
104925
104824
104700
104597
104561
104545
104533
104521
104509
104496
104481
104458
104420
104358
104264
104148
104024
103898
103771
103645
103518
103417
103378
103364
103356
103348
103340
103333
103326
103320
103312
103302
103284
103248
103198
103143
103088
103050
103028
103011
102988
102960
102934
102911
102890
102870
102849
102829
102808
102787
102763
102737
102706
102670
102632
102593
102562
102537
102515
102488
102433
102353
102257
102158
102063
101987
101951
101935
101925
101914
101892
101850
101796
101738
101684
101639
101599
101563
101533
101511
101494
101476
101460
101445
101432
101421
101411
101399
101389
101378
101358
101333
101307
101279
101250
101221
101191
101158
101122
101083
101041
100996
100950
100903
100857
100811
100764
100717
100673
100630
100585
100527
100443
100357
100275
100202
100151
100127
100110
100097
100089
100085
100085
100089
100090
100088
100086
100085
100086
100088
100099
100104
100098
100084
100075
100069
100062
100056
100050
100043
100036
100029
100020
100008
100005
100004
100004
100004
100004
100004
100003
100003
100003
100003
100002
100002
100002
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
)
;
}
frontAndBackPlanes
{
type empty;
}
}
// ************************************************************************* //
| [
"mizuha.watanabe@gmail.com"
] | mizuha.watanabe@gmail.com | |
b9b790d66a7918596cb29c187ecdde1f25576fd0 | bdc0b8809d52933c10f8eb77442bd0b4453f28f9 | /build/sensor_msgs/rosidl_typesupport_cpp/sensor_msgs/msg/fluid_pressure__type_support.cpp | 4ef7012e389dbdbaebece1e89b526a4d8805f7fc | [] | no_license | ClaytonCalabrese/BuiltRos2Eloquent | 967f688bbca746097016dbd34563716bd98379e3 | 76bca564bfd73ef73485e5c7c48274889032e408 | refs/heads/master | 2021-03-27T22:42:12.976367 | 2020-03-17T14:24:07 | 2020-03-17T14:24:07 | 247,810,969 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,396 | cpp | // generated from rosidl_typesupport_cpp/resource/idl__type_support.cpp.em
// with input from sensor_msgs:msg/FluidPressure.idl
// generated code does not contain a copyright notice
#include "cstddef"
#include "rosidl_generator_c/message_type_support_struct.h"
#include "sensor_msgs/msg/fluid_pressure__struct.hpp"
#include "rosidl_typesupport_cpp/identifier.hpp"
#include "rosidl_typesupport_cpp/message_type_support.hpp"
#include "rosidl_typesupport_cpp/message_type_support_dispatch.hpp"
#include "rosidl_typesupport_cpp/type_support_map.h"
#include "rosidl_typesupport_cpp/visibility_control.h"
#include "rosidl_typesupport_interface/macros.h"
namespace sensor_msgs
{
namespace msg
{
namespace rosidl_typesupport_cpp
{
typedef struct _FluidPressure_type_support_ids_t
{
const char * typesupport_identifier[2];
} _FluidPressure_type_support_ids_t;
static const _FluidPressure_type_support_ids_t _FluidPressure_message_typesupport_ids = {
{
"rosidl_typesupport_fastrtps_cpp", // ::rosidl_typesupport_fastrtps_cpp::typesupport_identifier,
"rosidl_typesupport_introspection_cpp", // ::rosidl_typesupport_introspection_cpp::typesupport_identifier,
}
};
typedef struct _FluidPressure_type_support_symbol_names_t
{
const char * symbol_name[2];
} _FluidPressure_type_support_symbol_names_t;
#define STRINGIFY_(s) #s
#define STRINGIFY(s) STRINGIFY_(s)
static const _FluidPressure_type_support_symbol_names_t _FluidPressure_message_typesupport_symbol_names = {
{
STRINGIFY(ROSIDL_TYPESUPPORT_INTERFACE__MESSAGE_SYMBOL_NAME(rosidl_typesupport_fastrtps_cpp, sensor_msgs, msg, FluidPressure)),
STRINGIFY(ROSIDL_TYPESUPPORT_INTERFACE__MESSAGE_SYMBOL_NAME(rosidl_typesupport_introspection_cpp, sensor_msgs, msg, FluidPressure)),
}
};
typedef struct _FluidPressure_type_support_data_t
{
void * data[2];
} _FluidPressure_type_support_data_t;
static _FluidPressure_type_support_data_t _FluidPressure_message_typesupport_data = {
{
0, // will store the shared library later
0, // will store the shared library later
}
};
static const type_support_map_t _FluidPressure_message_typesupport_map = {
2,
"sensor_msgs",
&_FluidPressure_message_typesupport_ids.typesupport_identifier[0],
&_FluidPressure_message_typesupport_symbol_names.symbol_name[0],
&_FluidPressure_message_typesupport_data.data[0],
};
static const rosidl_message_type_support_t FluidPressure_message_type_support_handle = {
::rosidl_typesupport_cpp::typesupport_identifier,
reinterpret_cast<const type_support_map_t *>(&_FluidPressure_message_typesupport_map),
::rosidl_typesupport_cpp::get_message_typesupport_handle_function,
};
} // namespace rosidl_typesupport_cpp
} // namespace msg
} // namespace sensor_msgs
namespace rosidl_typesupport_cpp
{
template<>
ROSIDL_TYPESUPPORT_CPP_PUBLIC
const rosidl_message_type_support_t *
get_message_type_support_handle<sensor_msgs::msg::FluidPressure>()
{
return &::sensor_msgs::msg::rosidl_typesupport_cpp::FluidPressure_message_type_support_handle;
}
#ifdef __cplusplus
extern "C"
{
#endif
ROSIDL_TYPESUPPORT_CPP_PUBLIC
const rosidl_message_type_support_t *
ROSIDL_TYPESUPPORT_INTERFACE__MESSAGE_SYMBOL_NAME(rosidl_typesupport_cpp, sensor_msgs, msg, FluidPressure)() {
return get_message_type_support_handle<sensor_msgs::msg::FluidPressure>();
}
#ifdef __cplusplus
}
#endif
} // namespace rosidl_typesupport_cpp
| [
"calabreseclayton@gmail.com"
] | calabreseclayton@gmail.com |
f904282e1bdf6e6905d3e88a896b7d9c3fa43d4d | 56c1a3fa0f0c14a10730f963db1c8619a0b12e0a | /Busca.cpp | ce0ea0ea7ba0da0b1f0b99b2fd6fd5bc9b5a167b | [] | no_license | gellyviana/ProjectsEDBAndLP | 1d706b5e4bd8dc369bdfd7beaf96e0c77fca4c77 | aae1b13c53ee4a751181a591cf36819548e9470d | refs/heads/master | 2021-06-08T20:03:35.633021 | 2016-12-02T15:18:29 | 2016-12-02T15:18:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,966 | cpp | #include <iostream>
#include <iomanip>
#include "Dependencies/Headers/Arquivo.h"
#include "Dependencies/Headers/ControladorArquivos.h"
#include "Dependencies/Headers/Auxiliares.h"
#include "Dependencies/Headers/Entrada.h"
#include "Dependencies/Headers/Timer.h"
using namespace std;
int main(int argc, char* argv[]){
//Primeira linha do Main, para garantir que não teremos falha de segmentação
//Carrega todos os arquivos que foram inseridos (apenas o nome do arquivo e o caminho)
//preto.txt|Arquivos TXT/preto.txt
LinkedList<Arquivo> arquivos = ControladorArquivos::LerArquivo(DADOS_ARQUIVOS);
HashTable<string>* table = new HashTable<string>(3);
table->DeserializarDoArquivo(DADOS_PALAVRAS);
ControladorArquivos::GarantirBaseDeDados();
Timer* timer = new Timer();
timer->Start();
Entrada* entrada = new Entrada();
entrada->ProcessarParametrosBusca(argc, argv);
LinkedList<string> retorno;
switch(entrada->GetTipoFuncao())
{
case FUNC_AND:
{
int index = 0;
entrada->GetParametros().ForEach([&](string* parametro)->bool
{
LinkedList<string> tempRetorno = table->Buscar(Auxiliares::ToLowerCase(*parametro));
if(index == 0)
{
retorno = tempRetorno;
}
else
{
LinkedList<string>* tempList = new LinkedList<string>();
retorno.ForEach([&](string* indexPalavra)->bool
{
bool contains = tempRetorno.Any([&](string* dado) { return strcmp(dado->c_str(), indexPalavra->c_str()) == 0; });
if(contains)
{
tempList->Inserir(indexPalavra);
}
});
retorno = *tempList;
}
index++;
});
break;
}
case FUNC_OR:
{
int index = 0;
entrada->GetParametros().ForEach([&](string* parametro)->bool
{
LinkedList<string> tempRetorno = table->Buscar(Auxiliares::ToLowerCase(*parametro));
if(index == 0)
{
retorno = tempRetorno;
}
tempRetorno.ForEach([&](string* indexPalavra)->bool
{
bool contains = retorno.Any([&](string* dado) { return strcmp(dado->c_str(), indexPalavra->c_str()) == 0; });
if(!contains)
{
retorno.Inserir(indexPalavra);
}
});
index++;
});
break;
}
default:
break;
}
// LinkedList<string> retorno = table->Buscar(argv[1]);
//Uso do & é para pegar a variável arquivos que está acima e fora do escopo do ForEach
bool wasRasult = false;
retorno.ForEach([&](string* item) -> bool
{
wasRasult = true;
//abaixo eu pego o índice do arquivo onde existe ocorrência da palavra
int indexArquivo = stoi(*Auxiliares::Split(";", *item).FirstOrDefault());
int indexLinha = stoi(*Auxiliares::Split(";", *item).LastOrDefault());
//É criado um objeto chamado arquivo que rece
Arquivo* arquivo = arquivos.GetElementAtIndex(indexArquivo);
if(arquivo == NULL)
{
cout << "ARQUIVO NAO ENCONTRADO ";
}
else
{
// string textoLinha = ControladorArquivos::LerLinha(arquivo->caminho, indexLinha);
cout << arquivo->nome << ": Linha " << indexLinha << endl;
}
});
if(!wasRasult)
{
cout << "Não houve ocorrencia das palavras nos arquivos" << endl;
}
timer->Stop();
timer->GetTimePrint();
return 0;
} | [
"gellyviana@outlook.com"
] | gellyviana@outlook.com |
4ade1946bb208470af204e25e3d5698543bf710a | be71a73dff6f5cd86d615266dd45ed575b2ac4d0 | /project-solutions/section 11/11-02-Aliens/Alien.cpp | b9c688de40015e513e1ddbddf29bfc115eb7ea74 | [] | no_license | goyeer/complete-cpp-developer-course | abe064e4ffd6b7bd0a137ec041588f81f2b070c2 | 7930c52d40fd29280ef37f89798074e4882582d5 | refs/heads/master | 2023-08-15T19:54:43.136412 | 2021-09-27T06:09:52 | 2021-09-27T06:09:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,658 | cpp | #include "Alien.h"
#include <cstdlib>
#include <ctime>
using namespace std;
Alien::Alien(int weight, int height, char gender)
{
this->weight = weight;
this->height = height;
this->gender = gender;
}
int Alien::getWeight() const
{
return weight;
}
int Alien::getHeight() const
{
return height;
}
char Alien::getGender() const
{
return gender;
}
int Alien::getPrestige() const
{
int genderValue;
if (gender == 'M')
{
genderValue = 2;
}
else
{
genderValue = 3;
}
return weight * height * genderValue;
}
bool Alien::operator==(Alien& other) const
{
return getPrestige() == other.getPrestige();
}
bool Alien::operator!=(Alien& other) const
{
return getPrestige() != other.getPrestige();
}
bool Alien::operator>(Alien& other) const
{
return getPrestige() > other.getPrestige();
}
bool Alien::operator>=(Alien& other) const
{
return getPrestige() >= other.getPrestige();
}
bool Alien::operator<(Alien& other) const
{
return getPrestige() < other.getPrestige();
}
bool Alien::operator<=(Alien& other) const
{
return getPrestige() <= other.getPrestige();
}
Alien Alien::operator+(Alien& other) const
{
srand(time(nullptr));
int randNum = rand() % 10 + 1; //1-10 inclusive
char newGender;
int newWeight = (weight + other.weight) / 2;
int newHeight = (height + other.height) / 2;
if (randNum < 4)
{
newGender = 'F';
}
else
{
newGender = 'M';
}
return Alien(newWeight, newHeight, newGender);
}
void Alien::operator=(Alien& other)
{
weight = other.weight;
height = other.height;
gender = other.gender;
} | [
"noreply@github.com"
] | goyeer.noreply@github.com |
fe935b5448dd4bbb2a7e36f3f935472489a24e96 | b1e730e22510b7d296f372de39c2ffda44d1001b | /705A-Hulk.cpp | 3f3467d87879d87eeeff383c54269ab94ef03224 | [] | no_license | KieranHorgan/Codeforces-Problems | 7f28ed654a7b142086bb25c2f8b98fc2c66bf7a2 | 9e87ccea355208044343be857b005530f228a445 | refs/heads/master | 2021-01-19T19:44:35.895339 | 2017-05-09T20:12:02 | 2017-05-09T20:12:02 | 88,438,604 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 605 | cpp | #include <bits/stdc++.h>
using namespace std;
#define ll long long
#define MAX 100000
typedef vector<int> vi;
ll n, m, ans;
string s;
pair<int, int> a[105];
ll dp[MAX];
bool visited[MAX];
ll summedTable[MAX];
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin >> n;
string y = "I hate ", x = "I love ";
for(int i = 0; i < n; i++) {
if(i%2 == 0) {
cout << y;
} else {
cout << x;
}
if(i == n-1) cout << "it";
else cout << "that ";
}
return 0;
}
| [
"kieranhorganmallow@gmail.com"
] | kieranhorganmallow@gmail.com |
5e2df600f82aa2b0f7aaf2d783801bb1f9f625b4 | d3e5d5d08e11f0107e51ecfc14176b0416f94c85 | /Dojo/Structured Parallel Programming/code/src/cholesky/common/blas_leaf.h | 7c6c16fa7f5cb6795b24e96315410f08e468c6dd | [
"MIT"
] | permissive | miguelraz/PathToPerformance | d99625477679d3d88c789dd2835afa945a9d8619 | 4f098e55023007e62c338d31a7ed2a46a3c99752 | refs/heads/master | 2021-01-22T20:50:47.017079 | 2020-05-19T04:14:40 | 2020-05-19T04:14:40 | 85,366,992 | 9 | 0 | null | 2017-09-28T23:45:20 | 2017-03-18T01:13:30 | Jupyter Notebook | UTF-8 | C++ | false | false | 2,952 | h | // leaf_... routines provide overload interface MKL routines so that templates can call them for both float and double.
// Default arguments generally follow the Fortran95 conventions
#ifndef leaf_blas_H
#define leaf_blas_H
#include "mkl.h"
inline void leaf_gemm( int m, int n, int k, const float a[], int lda, const float b[], int ldb, float c[], int ldc, char transa='N', char transb='N', float alpha=1, float beta=1 ) {
sgemm( &transa, &transb, &m, &n, &k, &alpha, a, &lda, b, &ldb, &beta, c, &ldc );
}
inline void leaf_gemm( int m, int n, int k, const double a[], int lda, const double b[], int ldb, double c[], int ldc, char transa='N', char transb='N', double alpha=1, double beta=1 ) {
dgemm( &transa, &transb, &m, &n, &k, &alpha, a, &lda, b, &ldb, &beta, c, &ldc );
}
inline void leaf_trsm(int m, int n, const float b[], int ldb, float a[], int lda, char side='L', char transa='N', char diag='N', float alpha=1 ) {
strsm(&side, "Lower", &transa, &diag, &m, &n, &alpha, b, &ldb, a, &lda);
}
inline void leaf_trsm(int m, int n, const double b[], int ldb, double a[], int lda, char side='L', char transa='N', char diag='N', double alpha=1 ) {
dtrsm(&side, "Lower", &transa, &diag, &m, &n, &alpha, b, &ldb, a, &lda);
}
inline void leaf_getrf( int m, int n, float a[], int lda, int ipiv[], int* info ) {
sgetrf(&m,&n,a,&lda,ipiv,info);
}
inline void leaf_getrf( int m, int n, double a[], int lda, int ipiv[], int* info ) {
dgetrf(&m,&n,a,&lda,ipiv,info);
}
inline void leaf_syrk( int n, int k, const float a[], int lda, float c[], int ldc, float alpha=-1, float beta=1 ) {
ssyrk( "Lower", "No transpose", &n, &k, &alpha, a, &lda, &beta, c, &ldc );
}
inline void leaf_syrk( int n, int k, const double a[], int lda, double c[], int ldc, double alpha=-1, double beta=1 ) {
dsyrk( "Lower", "No transpose", &n, &k, &alpha, a, &lda, &beta, c, &ldc );
}
inline void leaf_potf2( int n, float a[], int lda, int* info, char uplo='L' ) {
spotf2( &uplo, &n, a, &lda, info );
}
inline void leaf_potf2( int n, double a[], int lda, int* info, char uplo='L' ) {
dpotf2( &uplo, &n, a, &lda, info );
}
inline void leaf_potrf( int n, float a[], int lda, int* info, char uplo='L' ) {
spotrf( &uplo, &n, a, &lda, info );
}
inline void leaf_potrf( int n, double a[], int lda, int* info, char uplo='L' ) {
dpotrf( &uplo, &n, a, &lda, info );
}
template<typename T>
inline void leaf_potf2( int n, T a[], int lda ) { // Version without "info" argument.
int tmp;
leaf_potrf( n, a, lda, &tmp );
}
// Utility function for getting pointer to op(a)(i,j) where op is usual BLAS transa parameter for a.
template<typename T>
inline T* at( char transa, int i, int j, T a[], int lda ) {
assert( transa=='N'||transa=='n'||transa=='T'||transa=='t' );
return transa=='T'||transa=='t' ? a+j+i*lda : a+i+j*lda;
}
#endif /* leaf_blas_H */ | [
"miguelraz@ciencias.unam.mx"
] | miguelraz@ciencias.unam.mx |
74c62941c214868f7855589327b960901e6ed561 | c591b56220405b715c1aaa08692023fca61f22d4 | /Aayushi/milestone 1/4. check for postive negative or 0.cpp | 1fa446eb0b133360e65ca96e948549e6f1b7177f | [] | no_license | Girl-Code-It/Beginner-CPP-Submissions | ea99a2bcf8377beecba811d813dafc2593ea0ad9 | f6c80a2e08e2fe46b2af1164189272019759935b | refs/heads/master | 2022-07-24T22:37:18.878256 | 2021-11-16T04:43:08 | 2021-11-16T04:43:08 | 263,825,293 | 37 | 105 | null | 2023-06-05T09:16:10 | 2020-05-14T05:39:40 | C++ | UTF-8 | C++ | false | false | 426 | cpp | //Write a program to check whether a number is negative, zero, positive
#include <iostream>
using namespace std;
int main()
{
int num;
cout<< "please enter the number :";
cin >> num;
if (num > 0)
cout << "the number is positive integer" << endl;
else if (num < 0)
cout << "the number is a negative integer" << endl;
else
cout << "the number is zero"<<endl;
return 0;
}
| [
"manvityagi770@gmail.com"
] | manvityagi770@gmail.com |
b7f28576fa583b3022f781588f2189fec6e9b6eb | c5e26167d000f9d52db0a1491c7995d0714f8714 | /白马湖OJ/1430.cpp | 0c27543799ab5c925062d9ef6a981321fb194cef | [] | no_license | memset0/OI-Code | 48d0970685a62912409d75e1183080ec0c243e21 | 237e66d21520651a87764c385345e250f73b245c | refs/heads/master | 2020-03-24T21:23:04.692539 | 2019-01-05T12:38:28 | 2019-01-05T12:38:28 | 143,029,281 | 18 | 1 | null | null | null | null | GB18030 | C++ | false | false | 1,046 | cpp | #include <bits/stdc++.h>
#define each lalala001
#define sum lalala002
#define ans lalala003
using namespace std;
int n, each, a[25], b[10000], sum[10];
bool ans = false;
void DFS(int u)
{
//判断
printf("!");
if ((sum[1] == each) && (sum[2] == each) && (sum[3] == each) && (sum[4] == each) == 3)
{
ans = true;
}
//DFS
for (int i = 1; i <= 4; i++)
if (sum[i] + a[u] <= each)
{
int sum_back = sum[0];
sum[i] += a[u];
if (sum[i] == each) sum[0]++;
DFS(u + 1);
sum[0] = sum_back;
sum[i] -= a[u];
}
}
int main()
{
//初始化
memset(sum, 0, sizeof(sum));
memset(a, 0, sizeof(a));
//输入
scanf("%d", &n);
for (int i = 1; i <= n; i++)
scanf("%d", &a[i]);
for (int i = 1; i <= n; i++)
{
sum[0] += a[i];
b[a[i]]++;
}
for (int i = 10000; i >= 1; i--)
while (b[i]) a[++a[0]] = i, b[i] -= 1;
if ((sum[0] % 4) != 0)
{
//肯定不能拼成正方形
printf("no\n");
return 0;
}
else each = sum[0] / 4;
//DFS
DFS(1);
//输出
if (ans) printf("yes\n");
else printf("no\n");
return 0;
}
| [
"memset0@outlook.com"
] | memset0@outlook.com |
a87b103bc548db7b072b56740b119125d3651f9b | 676a84034edec9578c0d290b73699da2e9d71c77 | /src/qt/bitcoinunits.cpp | 571a74b9c0bc23b991211b6f710d861cea49d0f6 | [
"MIT"
] | permissive | MrSilver6666/CB | d54981cc572578fa5f948e5189f06ead66205f9a | bb9f68cae7267395c0f2cd1fd4ac8d660ecd5ca1 | refs/heads/master | 2016-09-06T13:01:59.529982 | 2014-11-14T09:00:35 | 2014-11-14T09:00:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,296 | cpp | #include "bitcoinunits.h"
#include <QStringList>
BitcoinUnits::BitcoinUnits(QObject *parent):
QAbstractListModel(parent),
unitlist(availableUnits())
{
}
QList<BitcoinUnits::Unit> BitcoinUnits::availableUnits()
{
QList<BitcoinUnits::Unit> unitlist;
unitlist.append(BTC);
unitlist.append(mBTC);
unitlist.append(uBTC);
return unitlist;
}
bool BitcoinUnits::valid(int unit)
{
switch(unit)
{
case BTC:
case mBTC:
case uBTC:
return true;
default:
return false;
}
}
QString BitcoinUnits::name(int unit)
{
switch(unit)
{
case BTC: return QString("CRB");
case mBTC: return QString("mCRB");
case uBTC: return QString::fromUtf8("μCRB");
default: return QString("???");
}
}
QString BitcoinUnits::description(int unit)
{
switch(unit)
{
case BTC: return QString("CryptoBancors");
case mBTC: return QString("Milli-CryptoBancors (1 / 1,000)");
case uBTC: return QString("Micro-CryptoBancors (1 / 1,000,000)");
default: return QString("???");
}
}
qint64 BitcoinUnits::factor(int unit)
{
switch(unit)
{
case BTC: return 100000000;
case mBTC: return 100000;
case uBTC: return 100;
default: return 100000000;
}
}
int BitcoinUnits::amountDigits(int unit)
{
switch(unit)
{
case BTC: return 8; // 21,000,000 (# digits, without commas)
case mBTC: return 11; // 21,000,000,000
case uBTC: return 14; // 21,000,000,000,000
default: return 0;
}
}
int BitcoinUnits::decimals(int unit)
{
switch(unit)
{
case BTC: return 8;
case mBTC: return 5;
case uBTC: return 2;
default: return 0;
}
}
QString BitcoinUnits::format(int unit, qint64 n, bool fPlus)
{
// Note: not using straight sprintf here because we do NOT want
// localized number formatting.
if(!valid(unit))
return QString(); // Refuse to format invalid unit
qint64 coin = factor(unit);
int num_decimals = decimals(unit);
qint64 n_abs = (n > 0 ? n : -n);
qint64 quotient = n_abs / coin;
qint64 remainder = n_abs % coin;
QString quotient_str = QString::number(quotient);
QString remainder_str = QString::number(remainder).rightJustified(num_decimals, '0');
// Right-trim excess zeros after the decimal point
int nTrim = 0;
for (int i = remainder_str.size()-1; i>=2 && (remainder_str.at(i) == '0'); --i)
++nTrim;
remainder_str.chop(nTrim);
if (n < 0)
quotient_str.insert(0, '-');
else if (fPlus && n > 0)
quotient_str.insert(0, '+');
return quotient_str + QString(".") + remainder_str;
}
QString BitcoinUnits::formatWithUnit(int unit, qint64 amount, bool plussign)
{
return format(unit, amount, plussign) + QString(" ") + name(unit);
}
bool BitcoinUnits::parse(int unit, const QString &value, qint64 *val_out)
{
if(!valid(unit) || value.isEmpty())
return false; // Refuse to parse invalid unit or empty string
int num_decimals = decimals(unit);
QStringList parts = value.split(".");
if(parts.size() > 2)
{
return false; // More than one dot
}
QString whole = parts[0];
QString decimals;
if(parts.size() > 1)
{
decimals = parts[1];
}
if(decimals.size() > num_decimals)
{
return false; // Exceeds max precision
}
bool ok = false;
QString str = whole + decimals.leftJustified(num_decimals, '0');
if(str.size() > 18)
{
return false; // Longer numbers will exceed 63 bits
}
qint64 retvalue = str.toLongLong(&ok);
if(val_out)
{
*val_out = retvalue;
}
return ok;
}
int BitcoinUnits::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return unitlist.size();
}
QVariant BitcoinUnits::data(const QModelIndex &index, int role) const
{
int row = index.row();
if(row >= 0 && row < unitlist.size())
{
Unit unit = unitlist.at(row);
switch(role)
{
case Qt::EditRole:
case Qt::DisplayRole:
return QVariant(name(unit));
case Qt::ToolTipRole:
return QVariant(description(unit));
case UnitRole:
return QVariant(static_cast<int>(unit));
}
}
return QVariant();
}
| [
"CB"
] | CB |
ab5517590baec6c1b2816471706fa31c4c761388 | 24ab4757b476a29439ae9f48de3e85dc5195ea4a | /lib/magma-2.2.0/testing/testing_zhetrd_gpu.cpp | 40902ffc68095cc39ab982f89f532eb27f60f00a | [] | no_license | caomw/cuc_double | 6025d2005a7bfde3372ebf61cbd14e93076e274e | 99db19f7cb56c0e3345a681b2c103ab8c88e491f | refs/heads/master | 2021-01-17T05:05:07.006372 | 2017-02-10T10:29:51 | 2017-02-10T10:29:51 | 83,064,594 | 10 | 2 | null | 2017-02-24T17:09:11 | 2017-02-24T17:09:11 | null | UTF-8 | C++ | false | false | 8,605 | cpp | /*
-- MAGMA (version 2.2.0) --
Univ. of Tennessee, Knoxville
Univ. of California, Berkeley
Univ. of Colorado, Denver
@date November 2016
@author Raffaele Solca
@author Stan Tomov
@author Azzam Haidar
@author Mark Gates
@precisions normal z -> s d c
*/
// includes, system
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
// includes, project
#include "flops.h"
#include "magma_v2.h"
#include "magma_lapack.h"
#include "testings.h"
#define COMPLEX
/* ////////////////////////////////////////////////////////////////////////////
-- Testing zhetrd_gpu
*/
int main( int argc, char** argv)
{
TESTING_CHECK( magma_init() );
magma_print_environment();
real_Double_t gflops, gpu_perf, cpu_perf, gpu_time, cpu_time;
double eps;
magmaDoubleComplex *h_A, *h_R, *h_Q, *h_work, *work;
magmaDoubleComplex_ptr d_R, dwork;
magmaDoubleComplex *tau;
double *diag, *offdiag;
double result[2] = {0., 0.};
magma_int_t N, n2, lda, ldda, lwork, info, nb, ldwork;
magma_int_t ione = 1;
magma_int_t itwo = 2;
magma_int_t ithree = 3;
magma_int_t ISEED[4] = {0,0,0,1};
int status = 0;
#ifdef COMPLEX
double *rwork;
#endif
eps = lapackf77_dlamch( "E" );
magma_opts opts;
opts.parse_opts( argc, argv );
double tol = opts.tolerance * lapackf77_dlamch("E");
printf("%% Available versions (specify with --version):\n");
printf("%% 1 - magma_zhetrd_gpu: uses ZHEMV from CUBLAS (default)\n");
printf("%% 2 - magma_zhetrd2_gpu: uses ZHEMV from MAGMA BLAS that requires extra space\n\n");
printf("%% uplo = %s, version %lld\n", lapack_uplo_const(opts.uplo), (long long) opts.version);
printf("%% N CPU Gflop/s (sec) GPU Gflop/s (sec) |A-QHQ^H|/N|A| |I-QQ^H|/N\n");
printf("%%==========================================================================\n");
for( int itest = 0; itest < opts.ntest; ++itest ) {
for( int iter = 0; iter < opts.niter; ++iter ) {
N = opts.nsize[itest];
lda = N;
ldda = magma_roundup( N, opts.align ); // multiple of 32 by default
n2 = lda*N;
nb = magma_get_zhetrd_nb(N);
lwork = N*nb; /* We suppose the magma nb is bigger than lapack nb */
gflops = FLOPS_ZHETRD( N ) / 1e9;
ldwork = ldda*magma_ceildiv(N,64) + 2*ldda*nb;
TESTING_CHECK( magma_zmalloc_cpu( &h_A, lda*N ));
TESTING_CHECK( magma_zmalloc_cpu( &tau, N ));
TESTING_CHECK( magma_dmalloc_cpu( &diag, N ));
TESTING_CHECK( magma_dmalloc_cpu( &offdiag, N-1 ));
TESTING_CHECK( magma_zmalloc_pinned( &h_R, lda*N ));
TESTING_CHECK( magma_zmalloc_pinned( &h_work, lwork ));
TESTING_CHECK( magma_zmalloc( &d_R, ldda*N ));
TESTING_CHECK( magma_zmalloc( &dwork, ldwork ));
/* ====================================================================
Initialize the matrix
=================================================================== */
lapackf77_zlarnv( &ione, ISEED, &n2, h_A );
magma_zmake_hermitian( N, h_A, lda );
magma_zsetmatrix( N, N, h_A, lda, d_R, ldda, opts.queue );
/* ====================================================================
Performs operation using MAGMA
=================================================================== */
gpu_time = magma_wtime();
if (opts.version == 1) {
magma_zhetrd_gpu( opts.uplo, N, d_R, ldda, diag, offdiag,
tau, h_R, lda, h_work, lwork, &info );
}
else {
magma_zhetrd2_gpu( opts.uplo, N, d_R, ldda, diag, offdiag,
tau, h_R, lda, h_work, lwork, dwork, ldwork, &info );
}
gpu_time = magma_wtime() - gpu_time;
gpu_perf = gflops / gpu_time;
if (info != 0) {
printf("magma_zhetrd_gpu returned error %lld: %s.\n",
(long long) info, magma_strerror( info ));
}
/* =====================================================================
Check the factorization
=================================================================== */
if ( opts.check ) {
TESTING_CHECK( magma_zmalloc_cpu( &h_Q, lda*N ));
TESTING_CHECK( magma_zmalloc_cpu( &work, 2*N*N ));
#ifdef COMPLEX
TESTING_CHECK( magma_dmalloc_cpu( &rwork, N ));
#endif
magma_zgetmatrix( N, N, d_R, ldda, h_R, lda, opts.queue );
magma_zgetmatrix( N, N, d_R, ldda, h_Q, lda, opts.queue );
lapackf77_zungtr( lapack_uplo_const(opts.uplo), &N, h_Q, &lda, tau, h_work, &lwork, &info );
lapackf77_zhet21( &itwo, lapack_uplo_const(opts.uplo), &N, &ione,
h_A, &lda, diag, offdiag,
h_Q, &lda, h_R, &lda,
tau, work,
#ifdef COMPLEX
rwork,
#endif
&result[0] );
lapackf77_zhet21( &ithree, lapack_uplo_const(opts.uplo), &N, &ione,
h_A, &lda, diag, offdiag,
h_Q, &lda, h_R, &lda,
tau, work,
#ifdef COMPLEX
rwork,
#endif
&result[1] );
result[0] *= eps;
result[1] *= eps;
magma_free_cpu( h_Q );
magma_free_cpu( work );
#ifdef COMPLEX
magma_free_cpu( rwork );
#endif
}
/* =====================================================================
Performs operation using LAPACK
=================================================================== */
if ( opts.lapack ) {
cpu_time = magma_wtime();
lapackf77_zhetrd( lapack_uplo_const(opts.uplo), &N, h_A, &lda, diag, offdiag, tau,
h_work, &lwork, &info );
cpu_time = magma_wtime() - cpu_time;
cpu_perf = gflops / cpu_time;
if (info != 0) {
printf("lapackf77_zhetrd returned error %lld: %s.\n",
(long long) info, magma_strerror( info ));
}
}
/* =====================================================================
Print performance and error.
=================================================================== */
if ( opts.lapack ) {
printf("%5lld %7.2f (%7.2f) %7.2f (%7.2f)",
(long long) N, cpu_perf, cpu_time, gpu_perf, gpu_time );
} else {
printf("%5lld --- ( --- ) %7.2f (%7.2f)",
(long long) N, gpu_perf, gpu_time );
}
if ( opts.check ) {
printf(" %8.2e %8.2e %s\n", result[0], result[1],
((result[0] < tol && result[1] < tol) ? "ok" : "failed") );
status += ! (result[0] < tol && result[1] < tol);
} else {
printf(" --- ---\n");
}
magma_free_cpu( h_A );
magma_free_cpu( tau );
magma_free_cpu( diag );
magma_free_cpu( offdiag );
magma_free_pinned( h_R );
magma_free_pinned( h_work );
magma_free( d_R );
magma_free( dwork );
fflush( stdout );
}
if ( opts.niter > 1 ) {
printf( "\n" );
}
}
opts.cleanup();
TESTING_CHECK( magma_finalize() );
return status;
}
| [
"policmic@fel.cvut.cz"
] | policmic@fel.cvut.cz |
5988d2211b1478fc1308cfdf036649cc1ae6497b | 8d06f1f690fd4e61556cae7ae5322bcad1e833f5 | /ServerTool/ontinueTime.cpp | b61ee96a3e58b58927a727a16483560f9d9111df | [] | no_license | chuyiwen/Tool | c450750749c451b43b9f5211a4510b66f407c3e1 | 158459d57fdb6a2f6b5e3baecc836f7224714b43 | refs/heads/master | 2021-01-23T23:45:56.701134 | 2018-02-24T11:22:15 | 2018-02-24T11:22:15 | 122,734,127 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 3,366 | cpp | // ontinueTime.cpp : 实现文件
//
#include "stdafx.h"
#include "ServerTool.h"
#include "ontinueTime.h"
#include "NetSession.h"
// ContinueTime 对话框
IMPLEMENT_DYNAMIC(ContinueTime, CDialog)
ContinueTime::ContinueTime(CWnd* pParent /*=NULL*/)
: CDialog(ContinueTime::IDD, pParent)
{
mCheck[0] = false;
mCheck[1] = false;
mCheck[2] = false;
}
ContinueTime::~ContinueTime()
{
}
void ContinueTime::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Control(pDX, IDC_EDIT1, mT);
DDX_Control(pDX, IDC_CHECK1, mCk);
DDX_Control(pDX, IDC_EDIT2, mFromHour);
DDX_Control(pDX, IDC_EDIT3, mFromMinute);
DDX_Control(pDX, IDC_EDIT4, mToHour);
DDX_Control(pDX, IDC_EDIT5, mToMinute);
}
BEGIN_MESSAGE_MAP(ContinueTime, CDialog)
ON_BN_CLICKED(IDOK, &ContinueTime::OnBnClickedOk)
ON_BN_CLICKED(IDC_CHECK1, &ContinueTime::OnBnClickedCheck1)
ON_BN_CLICKED(IDCANCEL, &ContinueTime::OnBnClickedCancel)
END_MESSAGE_MAP()
// ContinueTime 消息处理程序
void ContinueTime::OnBnClickedOk()
{
// TODO: 在此添加控件通知处理程序代码
mFromHour.GetWindowText(temp[index]);
mFromMinute.GetWindowText(temp1[index]);
mToHour.GetWindowText(temp2[index]);
mToMinute.GetWindowText(temp3[index]);
mCheck[index] = mCk.GetCheck();
CString str;
mT.GetWindowText(str);
int mini = _wtoi(str.GetBuffer());
if(mini<=0||mini>=60*24*7)
{
net_session::instance2()->continueTime = 0;
::MessageBox(0 , _T("input time is invalid") , _T("error") , 0);
}
net_session::instance2()->continueTime = mini*60;
OnOK();
}
void ContinueTime::OnBnClickedCheck1()
{
// TODO: 在此添加控件通知处理程序代码
bool check = mCk.GetCheck();
if(check)
{
for(int i = 0 ; i < servernamelist.size() ; ++i)
{
mFromHour.GetWindowText(temp[index]);
int hs = _wtoi(temp[index].GetBuffer());
net_session::instance2()->mDoublePolicy[servernamelist[i]].hourStart[index] = hs;
mFromMinute.GetWindowText(temp1[index]);
int ms = _wtoi(temp1[index].GetBuffer());
net_session::instance2()->mDoublePolicy[servernamelist[i]].minuteStart[index] = ms;
mToHour.GetWindowText(temp2[index]);
int he = _wtoi(temp2[index].GetBuffer());
net_session::instance2()->mDoublePolicy[servernamelist[i]].hourEnd[index] = he;
mToMinute.GetWindowText(temp3[index]);
int me = _wtoi(temp3[index].GetBuffer());
net_session::instance2()->mDoublePolicy[servernamelist[i]].minuteEnd[index] = me;
net_session::instance2()->mDoublePolicy[servernamelist[i]].continueMinutes[index] =
(he - hs)*60 + me - ms;
}
mCheck[index] = true;
}
else
mCheck[index] = false;
}
void ContinueTime::OnBnClickedCancel()
{
// TODO: 在此添加控件通知处理程序代码
net_session::instance2()->continueTime = 0;
mFromHour.GetWindowText(temp[index]);
mFromMinute.GetWindowText(temp1[index]);
mToHour.GetWindowText(temp2[index]);
mToMinute.GetWindowText(temp3[index]);
mCheck[index] = mCk.GetCheck();
OnCancel();
}
BOOL ContinueTime::OnInitDialog()
{
CDialog::OnInitDialog();
// TODO: 在此添加额外的初始化
mFromHour.SetWindowText(temp[index]);
mFromMinute.SetWindowText(temp1[index]);
mToHour.SetWindowText(temp2[index]);
mToMinute.SetWindowText(temp3[index]);
mCk.SetCheck(mCheck[index]);
return TRUE; // return TRUE unless you set the focus to a control
// 异常: OCX 属性页应返回 FALSE
}
| [
"chuyiwen1988@gmail.com"
] | chuyiwen1988@gmail.com |
0b2f23cdaaea380d0a351f8bc5429ae63761102f | 0f8594c7fadedb0c9f1e447d3d19a2f3276b4975 | /Client/librpg/Role/RoleModel.cpp | 41aba99135a82e52f108575db89231eea619cd2d | [] | no_license | SmallRaindrop/LocatorApp | 37c427dd1e4cb7376cd5688ab7921b9f1490ac45 | 8212b1ec32b964e61e886bbbea8d26392e2b25d8 | refs/heads/master | 2021-01-09T22:49:02.586485 | 2015-10-14T04:55:44 | 2015-10-14T04:55:44 | 42,594,771 | 1 | 2 | null | 2015-09-16T15:19:42 | 2015-09-16T15:08:22 | null | UTF-8 | C++ | false | false | 321 | cpp | #include "RoleModel.h"
RoleModel::RoleModel()
{
}
RoleModel::~RoleModel()
{
}
bool RoleModel::init()
{
changeDir(DIR_S);
setScale(2.5f);
return true;
}
void RoleModel::setAppearance(EquipmentID armorID,EquipmentID weaponID,EquipmentID wingID)
{
equipWeapon(weaponID);
equipArmor(armorID);
equipWing(wingID);
} | [
"191511706@qq.com"
] | 191511706@qq.com |
55da347aea55b124a4895572cbc53f86ec45f46b | 09d887ffcfb59cff2aed7a2f78e19b2f9fb60459 | /src/Component.hpp | 69828a7d3edbe5b217158da2296958c851de52ae | [] | no_license | FH-Muenster-Studium/circuit | d6383b90c14aea66f3f340213b45ae23f2f5bec9 | e849a557c5be9ae4bffbd87386e3b44975e7ecc8 | refs/heads/main | 2023-04-25T23:17:38.414702 | 2021-06-09T12:04:28 | 2021-06-09T12:04:28 | 366,065,348 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 703 | hpp | #pragma once
#include <string>
#include <memory>
/**
* Component that has a name and a resistance.
*/
class Component {
private:
std::string name;
public:
/**
* Creates a component.
*
* @param name name of the component.
*/
explicit Component(std::string name);
/**
* Get the name of the component.
*
* @return the name of the component.
*/
[[nodiscard]] std::string get_name() const;
/**
* Get the resistance of the component.
*
* @return the resistance of the component.
*/
[[nodiscard]] virtual double get_resistance() const = 0;
[[nodiscard]] virtual std::shared_ptr<Component> clone() const = 0;
}; | [
"fabian.terhorst@gmail.com"
] | fabian.terhorst@gmail.com |
77df0940df77107d41b8c754724f154c705dd13a | cc098f0392187b992672c8cc9a050e933f476ef2 | /graduation/graduation/CmdServer.cpp | 403c4ec78da2056fca3c84a74a77f5e1db945509 | [] | no_license | yufeixuancplus/trojan | 8a5a737d160eff405867c77331fa94f2f2d6f222 | 29b20a91579217155eaeace6dd9c6c8d9a6a9608 | refs/heads/master | 2021-01-08T04:03:58.273900 | 2018-05-06T07:29:38 | 2018-05-06T07:29:38 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,305 | cpp | #include "stdafx.h"
#include "CmdServer.h"
HANDLE g_OnExit = NULL;
int sendCmd(int port) {
WSADATA WSADa; //这个结构被用来存储被WSAStartup函数调用后返回的Windows Sockets数据。后面的基本上差不多就不解释,不懂请大家自行百度
sockaddr_in SockAddrIn;
SOCKET CSocket, SSocket;
int iAddrSize;
PROCESS_INFORMATION ProcessInfo;
STARTUPINFO StartupInfo;
WCHAR szCMDPath[255] = L"C:\\Windows\\System32\\cmd.exe";
//分配内存,初始化数据
ZeroMemory(&ProcessInfo, sizeof(PROCESS_INFORMATION));
ZeroMemory(&StartupInfo, sizeof(STARTUPINFO));
ZeroMemory(&WSADa, sizeof(WSADATA));
//获取cmd路径
GetEnvironmentVariable(L"COMSPEG", szCMDPath, sizeof(szCMDPath));
//加载ws2_32.dll
WSAStartup(0x0202, &WSADa);
//设置本地信息和绑定协议,建立socket,代码如下:
SockAddrIn.sin_family = AF_INET;
SockAddrIn.sin_addr.s_addr = INADDR_ANY;
SockAddrIn.sin_port = htons(port);
CSocket = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, 0);
//设置绑定端口
bind(CSocket, (sockaddr *)&SockAddrIn, sizeof(SockAddrIn));
//设置服务器端监听端口
listen(CSocket, 1);
iAddrSize = sizeof(SockAddrIn);
//开始连接远程服务器,并配置隐藏窗口结构体
SSocket = accept(CSocket, (sockaddr *)&SockAddrIn, &iAddrSize);
StartupInfo.cb = sizeof(STARTUPINFO);
StartupInfo.wShowWindow = SW_HIDE;
StartupInfo.dwFlags = STARTF_USESTDHANDLES |
STARTF_USESHOWWINDOW;
StartupInfo.hStdInput = (HANDLE)SSocket;
StartupInfo.hStdOutput = (HANDLE)SSocket;
StartupInfo.hStdError = (HANDLE)SSocket;
//创建匿名管道:
CreateProcess(NULL, szCMDPath, NULL, NULL, TRUE, 0, NULL, NULL, &StartupInfo, &ProcessInfo);
WaitForSingleObject(ProcessInfo.hProcess, INFINITE);
CloseHandle(ProcessInfo.hProcess);
CloseHandle(ProcessInfo.hThread);
//关闭进程句柄:
closesocket(CSocket);
closesocket(SSocket);
WSACleanup();
return 0;
}
DWORD WINAPI ThreadFun(LPVOID pM)
{
while (1)
if (sendCmd(*(int*)pM)) break;
return 0;
}
CmdServer::CmdServer(int port)
{
MasterPort = port;
}
CmdServer::~CmdServer()
{
}
int CmdServer::listen()
{
HANDLE handle = CreateThread(NULL, 0, ThreadFun, &MasterPort, 0, NULL);
if (handle) {
WaitForSingleObject(g_OnExit, INFINITE);
}
return 0;
}
| [
"qq898141731@outlook.com"
] | qq898141731@outlook.com |
be0237fcb05464e8468c9f306224483ede1754d4 | a7517ba7578d9fac002dfc21ee113da531b82635 | /CSet/stdafx.cpp | 27e668a54342c32f91945045f7ed4559d6debe8c | [
"MIT"
] | permissive | miguelmartins1987/cset | bdb1428b85aecbbf76f64b6b3598f2c129f85215 | 2689f98444b6cd9b267568d8ec7e1678a496f267 | refs/heads/master | 2020-04-20T12:35:16.305945 | 2019-02-12T19:30:52 | 2019-02-12T19:30:52 | 168,847,091 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 283 | cpp | // stdafx.cpp : source file that includes just the standard includes
// CSet.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
| [
"miguel.martins.gama@gmail.com"
] | miguel.martins.gama@gmail.com |
ca097dc9afe6915fb2c327092c946ce73bcd584c | 054ca25534a37efa81175f443f8d2107b3c327ca | /abc159/c.cpp | f85af18dece89afd5e4f7841ec056d78d2a5a6b8 | [] | no_license | srj31/upsolve | e7b7c7c857966ff50d3ea94b00a891a19dfa9a34 | 6976688fd9f98bd0bed5b3a01a45bad0496dd0dc | refs/heads/master | 2022-10-01T09:57:14.598565 | 2020-06-05T13:58:51 | 2020-06-05T13:58:51 | 260,141,799 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 182 | cpp | #include<bits/stdc++.h>
using namespace std;
int main(){
long double l;
cin >> l;
long double ans = (l/3.0)*(l/3.0) * (l/3.0);
cout << fixed << setprecision(9) << ans << endl;
} | [
"sourabhrj31@gmail.com"
] | sourabhrj31@gmail.com |
ad7155185f8bd2444804bb86915382391959a5d0 | 3cc5f2629eeb7122865258561c6e3dec9307af25 | /findsize.cpp | 61e53c491e81035d1ea23599abc66f517b1b1891 | [] | no_license | sakshimohan1320/FindSize | f5aa837dad3ca6240c5a2a7e8930de917f24f3f3 | 59d8eafdfd9f706b62b7cbb9dd6160f4a985cbe5 | refs/heads/master | 2022-11-16T01:22:33.636298 | 2020-07-10T14:15:03 | 2020-07-10T14:15:03 | 278,648,769 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 369 | cpp | #include <iostream.h>
int main()
{
cout << "Size of int: " << sizeof(int) << " bytes" << endl;
cout << "Size of float: " << sizeof(float) << " bytes" << endl;
cout << "Size of double: " << sizeof(double) << " bytes" << endl;
cout << "Size of float: " << sizeof(float) << " bytes" << endl;
cout << "Size of double: " << sizeof(double) << " bytes" << endl;
return 0;
}
| [
"noreply@github.com"
] | sakshimohan1320.noreply@github.com |
461fd3c0fdb1d568c0263a0168a0b2839d0726bc | 2de8f5ba729a846f8ad5630272dd5b1f3b7b6e44 | /src/Core/Cpackets/LS/CGUnburrow.h | db68bedba2ad5028cde69df757cc127342d623b3 | [] | no_license | najosky/darkeden-v2-serverfiles | dc0f90381404953e3716bf71320a619eb10c3825 | 6e0015f5b8b658697228128543ea145a1fc4c559 | refs/heads/master | 2021-10-09T13:01:42.843224 | 2018-12-24T15:01:52 | 2018-12-24T15:01:52 | null | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 2,994 | h | //////////////////////////////////////////////////////////////////////
//
// Filename : CGUnburrow.h
// Written By : crazydog
// Description :
//
//////////////////////////////////////////////////////////////////////
#ifndef __CG_UNBURROW_H__
#define __CG_UNBURROW_H__
// include files
#include "Packet.h"
#include "PacketFactory.h"
//////////////////////////////////////////////////////////////////////
//
// class CGUnburrow;
//
//////////////////////////////////////////////////////////////////////
class CGUnburrow : public Packet {
public:
// 입력스트림(버퍼)으로부터 데이타를 읽어서 패킷을 초기화한다.
void read(SocketInputStream & iStream) throw(ProtocolException, Error);
// 출력스트림(버퍼)으로 패킷의 바이너리 이미지를 보낸다.
void write(SocketOutputStream & oStream) const throw(ProtocolException, Error);
// execute packet's handler
void execute(Player* pPlayer) throw(ProtocolException, Error);
// get packet id
PacketID_t getPacketID() const throw() { return PACKET_CG_UNBURROW; }
// get packet's body size
// *OPTIMIZATION HINT*
// const static CGUnburrowPacketSize 를 정의해서 리턴하라.
PacketSize_t getPacketSize() const throw() { return szCoord + szCoord + szDir; }
// get packet name
string getPacketName() const throw() { return "CGUnburrow"; }
// get packet's debug string
string toString() const throw();
public:
// get/set X Coordicate
Coord_t getX() const throw() { return m_X; }
void setX(Coord_t x) throw() { m_X = x; }
// get/set Y Coordicate
Coord_t getY() const throw() { return m_Y; }
void setY(Coord_t y) throw() { m_Y = y; }
// get/set Direction
Dir_t getDir() const throw() { return m_Dir; }
void setDir(Dir_t dir) throw() { m_Dir = dir; }
private :
Coord_t m_X; // X 좌표
Coord_t m_Y; // Y 좌표
Dir_t m_Dir; // 방향
};
//////////////////////////////////////////////////////////////////////
//
// class CGUnburrowFactory;
//
// Factory for CGUnburrow
//
//////////////////////////////////////////////////////////////////////
class CGUnburrowFactory : public PacketFactory {
public:
// create packet
Packet* createPacket() throw() { return new CGUnburrow(); }
// get packet name
string getPacketName() const throw() { return "CGUnburrow"; }
// get packet id
PacketID_t getPacketID() const throw() { return Packet::PACKET_CG_UNBURROW; }
// get packet's max body size
// *OPTIMIZATION HINT*
// const static CGUnburrowPacketSize 를 정의해서 리턴하라.
PacketSize_t getPacketMaxSize() const throw() { return szCoord + szCoord + szDir; }
};
//////////////////////////////////////////////////////////////////////
//
// class CGUnburrowHandler;
//
//////////////////////////////////////////////////////////////////////
class CGUnburrowHandler {
public:
// execute packet's handler
static void execute(CGUnburrow* pPacket, Player* player) throw(ProtocolException, Error);
};
#endif
| [
"paulomatew@gmail.com"
] | paulomatew@gmail.com |
f18d0c9453174657f004938f7108dbe7e25d2e3f | cd0aad09231a5e06168f51f1d9a763b1c75f8cae | /program.cpp | d42dbf2916f61a37354c686f4b7382568fa8050c | [] | no_license | BillyJue/model-View | a355356d88dfb55abd34f33c823388fa9b3ac7fc | 6bf517897c651638911142f767cdc8023471f8b4 | refs/heads/main | 2023-02-11T17:22:08.374817 | 2020-12-31T01:34:34 | 2020-12-31T01:34:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,430 | cpp | #include "mainwindow.h"
#include "program.h"
#include <QApplication>
#include <QDesktopWidget>
#include <QProcess>
time_t GetTime()
{
time_t t;
std::time(&t);
return t;
}
bool QCopyFile(const QString &src, const QString &desDir, bool cover)
{
if(src == desDir)
return true;
if(!QFile::exists(src))
return false;
return QFile::copy(src, desDir);
}
QRect GetRectFrom2Point(const QPoint &p1, const QPoint &p2)
{
auto px = std::minmax(p1.x(), p2.x());
auto py = std::minmax(p1.y(), p2.y());
return QRect(QPoint(px.first, py.first), QPoint(px.second, py.second));
}
QRect InterSection2Rect(const QRect &r1, const QRect &r2)
{
int xmax = std::max(r1.x(), r2.x());
int ymax = std::max(r1.y(), r2.y());
int xmin = std::min(r1.x() + r1.width(), r2.x() + r2.width());
int ymin = std::min(r1.y() + r1.height(), r2.y() + r2.height());
if(xmax <= xmin && ymax <= ymin)
return QRect(xmax, ymax, xmin - xmax, ymin - ymax);
return QRect();
}
QString UuidToStringEx()
{
QString s = QUuid::createUuid().toString();
s = s.remove("{").remove("}");
return s;
}
void SetWidgetCentral(QWidget *w)
{
w->move((qApp->desktop()->availableGeometry().width() - w->width()) / 2 + qApp->desktop()->availableGeometry().x(),
(qApp->desktop()->availableGeometry().height() - w->height()) / 2 + qApp->desktop()->availableGeometry().y());
}
| [
"1245410016@qq.com"
] | 1245410016@qq.com |
54b424d799861db7a9d8d8c074c7a4f40cd47716 | bfc3b327a3eb35f89bfb96159ed33fcd5cb874d6 | /cdal/source/CDAL.h | a7ef6e82f5fe01a132b94822cad233b48428d1f8 | [] | no_license | juan-nunez/Chains | 98d40d341bbe83b94d8bb9d516dce32ff41410a0 | c11ee131abda1a8e57b5ed95f913843de26372ec | refs/heads/master | 2021-05-29T04:35:48.923715 | 2015-01-01T22:46:09 | 2015-01-01T22:46:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,410 | h | #ifndef CDAL_H
#define CDAL_H
#include <iostream>
#include <exception>
#include <stdexcept>
using namespace std;
template <typename T>
class CDAL{
struct node{
node(){
arr = new T[50];
}
node* next;
T *arr;
};
public:
class CDAL_ITER {
private:
node* myNode;
T *ptr;
int index;
int count;
public:
typedef T value_type;
typedef std::ptrdiff_t difference_type;
typedef T& reference;
typedef T* pointer;
typedef std::forward_iterator_tag iterator_category;
typedef CDAL_ITER self_type;
typedef CDAL_ITER& self_reference;
explicit CDAL_ITER(node *n, T *p, int k){
myNode = n;
ptr = p;
index = k;
count = 0;
int i = 0;
while (i != index){
++ptr;
i++;
}
}
CDAL_ITER(const CDAL_ITER& src){
myNode = src.myNode;
}
pointer operator->(){
return myNode;
}
reference operator *(){
return *ptr;
}
self_reference operator++(){
if (count==49){
myNode = myNode->next;
ptr = &myNode->arr[0];
count = 0;
}
else{
++ptr;
++count;
}
return *this;
}
self_type operator++(int){
CDAL_ITER l = *this;
if (count==49){
myNode = myNode->next;
ptr = &myNode->arr[0];
count = 0;
}
else{
++ptr;
++count;
}
return l;
}
bool operator ==(CDAL_ITER &rhs){
return ptr == rhs.ptr;
}
bool operator!=(CDAL_ITER &rhs){
return ptr != rhs.ptr;
}
self_reference operator=(CDAL_ITER &rhs){
return this->myNode = rhs;
}
ostream &operator<<(ostream &obj) {
obj << this.myNode->data<<endl;
return obj;
}
};
public:
class CDAL_Const_ITER {
private:
const node* myNode;
const T *ptr;
int index;
int count;
public:
typedef T value_type;
typedef std::ptrdiff_t difference_type;
typedef const T& reference;
typedef const T* pointer;
typedef std::forward_iterator_tag iterator_category;
typedef CDAL_Const_ITER self_type;
typedef CDAL_Const_ITER& self_reference;
explicit CDAL_Const_ITER(node *n, T *p, int k){
myNode = n;
ptr = p;
index = k;
count = 0;
int i = 0;
while (i != index){
++ptr;
i++;
}
}
CDAL_Const_ITER(const CDAL_Const_ITER& src){
myNode = src.myNode;
}
pointer operator->(){
return myNode;
}
reference operator *(){
return *ptr;
}
self_reference operator++(){
if (count==49){
myNode = myNode->next;
ptr = &myNode->arr[0];
count = 0;
}
else{
++ptr;
++count;
}
return *this;
}
self_type operator++(int){
CDAL_Const_ITER l = *this;
if (count==49){
myNode = myNode->next;
ptr = &myNode->arr[0];
count = 0;
}
else{
++ptr;
++count;
}
return l;
}
bool operator ==(CDAL_Const_ITER &rhs){
return ptr == rhs.ptr;
}
bool operator!=(CDAL_Const_ITER &rhs){
return ptr != rhs.ptr;
}
self_reference operator=(CDAL_Const_ITER &rhs){
return this->myNode = rhs;
}
ostream &operator<<(ostream &obj) {
obj << this.myNode->data<<endl;
return obj;
}
};
public:
CDAL();
~CDAL();
CDAL( const CDAL& src ){
head=src.head;
tail=src.tail;
index=src.index;
amtNodes=src.amtNodes;
count=src.count;
}
CDAL &operator=(const CDAL &src){
if (&src == this)
return *this;
}
typedef std::size_t size_t;
typedef T value_type;
typedef CDAL_ITER iterator;
typedef CDAL_Const_ITER const_iterator;
T replace(T e, int position);
void insert(T e, int position);
void push_front(T e);
void push_back(T e);
T pop_front();
T pop_back();
T remove(int position);
T itemAt(int position);
bool isEmpty();
int size();
void clear();
bool contains(T e, bool equals_function);
bool equals_function(T e);
const ostream &print(ostream &out);
CDAL_ITER begin();
CDAL_ITER end();
CDAL_Const_ITER begin() const;
CDAL_Const_ITER end() const;
T &operator[](int k){
node *current = head;
if(k<50){
return current->arr[k];
}
else{
while (current != NULL){
for (int i = 0; i < 50; i++){
if(i==k){
return current->arr[k];
}
}
k=k-50;
if(k<0){
k=0;
}
current = current->next;
}
}
}
T const &operator[](int k) const{
node *current = head;
if(k<50){
return current->arr[k];
}
else{
while (current != NULL){
for (int i = 0; i < 50; i++){
if(i==k){
return current->arr[k];
}
}
k=k-50;
if(k<0){
k=0;
}
current = current->next;
}
}
}
private:
node* head;
node* tail;
size_t count;
int amtNodes;
int index;
void shift(node *current);
void allocNode(T e);
void indexConvert();
void insertHelper(node* current, int position, int nodeNumber);
};
template <typename T>
CDAL<T>::CDAL(){
head = NULL;
tail = NULL;
count = 0;
int amtNodes = 0;
index = 0;
}
template <typename T>
CDAL<T>::~CDAL(){
}
template <typename T>
void CDAL<T>::indexConvert(){
if (index == 50){
index = 0;
}
else{
index++;
}
}
template <typename T>
void CDAL<T>::shift(node *current){
T temp = 0;
T temp1 = 0;
node *trail = NULL;
int nodeNumber = 0;
while (current != NULL){
temp = current->arr[49];
for (int i = 49; i != 0; i--){
current->arr[i] = current->arr[i - 1];
}
trail = current;
nodeNumber++;
current = current->next;
if (nodeNumber != 1 && nodeNumber - 1 != amtNodes){
trail->arr[0] = temp1;
}
if (index == 50 && nodeNumber == amtNodes){
allocNode(temp);
}
temp1 = temp;
}
}
template <typename T>
void CDAL<T>::insertHelper(node* current, int position, int nodeNumber){
T temp = 0;
T temp1 = 0;
node *trail = NULL;
int check = nodeNumber;
while (current != NULL){
temp = current->arr[49];
for (int i = 49; i != position - 1; i--){
current->arr[i] = current->arr[i - 1];
}
position = 1;
trail = current;
nodeNumber++;
current = current->next;
if (nodeNumber - 1 != check && nodeNumber - 1 != amtNodes){
trail->arr[0] = temp1;
}
if (index == 50 && nodeNumber == amtNodes){
allocNode(temp);
}
temp1 = temp;
}
}
template <typename T>
void CDAL<T>::allocNode(T e){
node* newNode = new node();
newNode->next = NULL;
tail->next = newNode;
index = 0;
newNode->arr[index] = e;
tail = newNode;
amtNodes++;
count++;
}
template <typename T>
void CDAL<T>::insert(T e, int position){
if (position < 0 || position > size() ){
throw out_of_range("Invalid Position");
}
node *current = head;
int loops = 0;
if (position == 0){
push_front(e);
}
else if (position == size()){
push_back(e);
}
else{
int at = position / 50;
int mod = position % 50;
for (int i = 0; i < at; i++){
current = current->next;
loops++;
}
insertHelper(current, mod, loops);
current->arr[mod] = e;
indexConvert();
}
}
template <typename T>
T CDAL<T>::replace(T e, int position){
if (position < 0 || position > size()){
throw out_of_range("Invalid Position");
}
node *current = head;
int at = position / 50;
int mod = position % 50;
for (int i = 0; i < at; i++){
current = current->next;
}
T temp = current->arr[mod - 1];
current->arr[mod] = e;
return temp;
}
template <typename T>
void CDAL<T>::push_front(T e){
if (head == NULL){
node *newNode = new node();
newNode->arr[count] = e;
newNode->next = NULL;
head = newNode;
tail = newNode;
count++;
index++;
amtNodes++;
}
else{
node* current = head;
if (amtNodes > 1 || index == 50){
shift(current);
indexConvert();
count++;
}
else{
for (int i = 49; i != 0; i--){
head->arr[i] = head->arr[i - 1];
}
indexConvert();
count++;
}
head->arr[0] = e;
}
}
template <typename T>
void CDAL<T>::push_back(T e){
if (head == NULL){
node *newNode = new node();
newNode->arr[count] = e;
newNode->next = NULL;
head = newNode;
tail = newNode;
count++;
index++;
amtNodes++;
}
else{
if (index == 50){
allocNode(e);
indexConvert();
}
else{
tail->arr[index] = e;
count++;
indexConvert();
}
}
}
template <typename T>
T CDAL<T>::pop_front(){
if (isEmpty()){
throw logic_error("List is Empty");
}
node *current = head;
T temp = current->arr[0];
current->arr[0] = NULL;
T temp1 = 0;
T temp2 = 0;
if (amtNodes > 1){
node *current = head;
bool flag = false;
if (index == 1){
//index = 5;
flag = true;
}
while (current != NULL){
if (current->next != NULL){
temp1 = current->next->arr[0];
}
for (int i = 1; i <= 50; i++){
current->arr[i - 1] = current->arr[i];
}
if (current->next == NULL && index == 5){
current->arr[49] = temp2;
}
if (temp1 != 0){
current->arr[49] = temp1;
}
current = current->next;
temp1 = 0;
}
index--;
if (flag == true){
tail->next = NULL;
index = 50;
}
}
else{
for (int i = 1; i <= 50; i++){
head->arr[i - 1] = head->arr[i];
}
index--;
}
count--;
return temp;
}
template <typename T>
T CDAL<T>::pop_back(){
if (isEmpty()){
throw logic_error("List is Empty");
}
T temp = 0;
if (index == 0 && amtNodes>1){
node* current = head;
while (current->next->next != NULL){
current = current->next;
}
tail = current;
amtNodes--;
index = 50;
}
temp = tail->arr[index - 1];
tail->arr[index - 1] = NULL;
index--;
count--;
return temp;
}
template <typename T>
T CDAL<T>::remove(int position){
if (isEmpty()){
throw logic_error("List is Empty");
}
if (position < 0 || position > size()){
throw out_of_range("Invalid Position");
}
bool flag = false;
int temp = 0;
int temp1 = 0;
node *current = head;
node *trail = NULL;
if (position == 0){
pop_front();
}
else if(position==size()-1){
pop_back();
}
else{
int nodeNumber = 0;
int at = position / 50;
int mod = position % 50;
for (int i = 0; i < at; i++){
current = current->next;
nodeNumber++;
}
temp = current->arr[mod];
if (nodeNumber == at){
for (int i = mod+1; i < index; i++){
current->arr[i - 1] = current->arr[i];
}
}
else{
while (current != NULL){
for (int i = mod; i < 50; i++){
current->arr[i - 1] = current->arr[i];
}
mod = 0;
if (current->next != NULL){
temp1 = current->next->arr[0];
current->arr[49] = temp1;
}
if (index == 50){
current->arr[49] = NULL;
flag = true;
}
if (index == 1 && nodeNumber == amtNodes){
index = 50;
delete current->next;
tail = trail;
}
nodeNumber++;
trail = current;
current = current->next;
}
}
}
if (flag == true){
index--;
}
return temp;
}
template <typename T>
T CDAL<T>::itemAt(int position){
if (position < 0 || position > size()+1){
throw out_of_range("Invalid Position");
}
node *current = head;
int at = position / 50;
int mod = position % 50;
for (int i = 0; i < at; i++){
current = current->next;
}
return current->arr[mod];
}
template <typename T>
bool CDAL<T>::isEmpty(){
if (head == NULL){
return true;
}
return false;
}
template <typename T>
int CDAL<T>::size(){
return count;
}
template <typename T>
void CDAL<T>::clear(){
node *current = head;
while (current != NULL){
delete current->arr;
head=head->next;
current=current->next;
}
}
template <typename T>
bool CDAL<T>::equals_function(T e){
node *current = head;
int i = 0;
while (current != NULL){
if (current->arr[i] == e){
return true;
}
i++;
if (i == 50){
i = 0;
current = current->next;
}
}
return false;
}
template <typename T>
bool CDAL<T>::contains(T e, bool equals_function) {
return CDAL<T>::equals_function(e);
}
template <typename T>
const ostream& CDAL<T>::print(ostream &out) {
int c = 0;
node *current = head;
if (isEmpty() == true){
out << "<Empty>" << endl;
}
else{
out << "[";
while (current != NULL){
for (int i = 0; i < 50; i++){
if (i != size()-1){
out << current->arr[i] << ",";
}
else{
out<<current->arr[i]<<"]";
}
c++;
}
current = current->next;
}
}
return out;
}
template <typename T>
typename CDAL<T>::CDAL_ITER CDAL<T>::begin(){
return CDAL_ITER(head, head->arr, 0);
}
template <typename T>
typename CDAL<T>::CDAL_ITER CDAL<T>::end(){
return CDAL_ITER(tail, tail->arr, index);
}
template <typename T>
typename CDAL<T>::CDAL_Const_ITER CDAL<T>::begin() const{
return CDAL_Const_ITER(head, head->arr, 0);
}
template <typename T>
typename CDAL<T>::CDAL_Const_ITER CDAL<T>::end() const{
return CDAL_Const_ITER(tail, tail->arr, index);
}
#endif | [
"njuan1993@yahoo.com"
] | njuan1993@yahoo.com |
0e3ba64b4463f6b00a8bc699445c4c6bb84d4198 | f1d683230aa059e77f886efb0b10e64e45d7b98b | /dmtest/Dtmf8870.h | 2c99539d706b9e531d4c5cd8425e6773cba8a2e3 | [] | no_license | aniline/arduino-sketchbook | c035627fac9af8d3bea193ad53041333732b2537 | 9e6d0649a7fcfb07ab537424ddef90e935bbad65 | refs/heads/master | 2020-12-24T14:01:45.443226 | 2016-03-12T16:48:04 | 2016-03-12T16:48:04 | 29,747,234 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 659 | h | #ifndef _Dtmf8870_H
#define _Dtmf8870_H
#define DTMF_IDLE 0
#define DTMF_TONE_READ 1
#define DTMF_NUMBERS_LATCHED 2
#define MAX_CLI_DIGITS 16
typedef void (*Dtmf8870_handler)(int, char, char*);
class Dtmf8870 {
private:
Dtmf8870_handler handler;
int cli_clk;
int cli_loaded;
int cli_number_timeout;
int cli_last_digit_time;
int time_counter_ams;
int time_counter_s;
char number[MAX_CLI_DIGITS +1];
byte number_ptr;
boolean number_valid;
public:
Dtmf8870();
void setup (int number_timeout, Dtmf8870_handler handler);
void loop ();
int counter_ms();
int counter_s();
byte second_ticked();
};
#endif
| [
"anilknyn@yahoo.com"
] | anilknyn@yahoo.com |
e745fe5ac9df0eb08de925d8d429a61d710ce15e | e6f2a9df841fedfa34f90fa2e1bb773de2120d19 | /proj.wp8/ProjectF.h | 579efd3c3cf318787a54f91e368555cb09bebf18 | [] | no_license | crazychucky/ProjectF | 5b0fe0950d33c863ba036512a544c9feb82e9329 | c913af679e80cf8f1300d8752d9c194e1f0f9f88 | refs/heads/master | 2016-09-05T15:22:09.437440 | 2015-02-11T10:32:42 | 2015-02-11T10:32:42 | 23,489,843 | 0 | 0 | null | 2014-08-30T13:29:47 | 2014-08-30T10:53:41 | C++ | UTF-8 | C++ | false | false | 1,716 | h | #pragma once
#include "../Classes/AppDelegate.h"
ref class ProjectF sealed : public Windows::ApplicationModel::Core::IFrameworkView
{
public:
ProjectF();
// IFrameworkView Methods.
virtual void Initialize(Windows::ApplicationModel::Core::CoreApplicationView^ applicationView);
virtual void SetWindow(Windows::UI::Core::CoreWindow^ window);
virtual void Load(Platform::String^ entryPoint);
virtual void Run();
virtual void Uninitialize();
protected:
// Event Handlers.
void OnActivated(Windows::ApplicationModel::Core::CoreApplicationView^ applicationView, Windows::ApplicationModel::Activation::IActivatedEventArgs^ args);
void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ args);
void OnResuming(Platform::Object^ sender, Platform::Object^ args);
void OnWindowClosed(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::CoreWindowEventArgs^ args);
void OnVisibilityChanged(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::VisibilityChangedEventArgs^ args);
void OnPointerPressed(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::PointerEventArgs^ args);
void OnPointerMoved(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::PointerEventArgs^ args);
void OnPointerReleased(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::PointerEventArgs^ args);
void OnBackButtonPressed(Platform::Object^ sender, Windows::Phone::UI::Input::BackPressedEventArgs^ args);
private:
// The AppDelegate for the Cocos2D app
AppDelegate app;
};
ref class Direct3DApplicationSource sealed : Windows::ApplicationModel::Core::IFrameworkViewSource
{
public:
virtual Windows::ApplicationModel::Core::IFrameworkView^ CreateView();
}; | [
"yuanlixiao@live.cn"
] | yuanlixiao@live.cn |
e8aa2b39c9ecbcff231b0ee2b1a2d24c1ac0eb89 | 59fe87dd0313e801eb627655d18b3ed9bb9991f4 | /PotreeConverter/include/PotreeConverter.h | b403d3fc564fbfc12369b32372061cb79a7afab7 | [
"BSD-2-Clause-Views"
] | permissive | imclab/PotreeConverter | 06afd674444fcdc61c75cfbefc61908104915df3 | 734685eceb2859fff8dc7910a9b1373bb3af8f76 | refs/heads/master | 2020-12-11T07:19:48.688244 | 2014-04-06T15:40:34 | 2014-04-06T15:40:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 844 | h |
#ifndef POTREE_CONVERTER_H
#define POTREE_CONVERTER_H
#define POTREE_FORMAT_VERSION "1.0"
#include "AABB.h"
#include "PointReader.h"
#include <string>
#include <vector>
#include <sstream>
using std::vector;
using std::string;
using std::stringstream;
class PotreeConverter{
private:
PointReader *reader;
AABB aabb;
string fData;
string workDir;
float minGap;
stringstream cloudJs;
int maxDepth;
string format;
float range;
char *buffer;
public:
PotreeConverter(string fData, string workDir, float minGap, int maxDepth, string format, float range);
void convert(int numPoints);
void convert();
void initReader();
/**
* converts points in fData
*
* @returns a list of indices of the octree nodes that were created
*/
vector<int> process(string source, string target, AABB aabb, int depth);
};
#endif | [
"markus_schuetz@gmx.at"
] | markus_schuetz@gmx.at |
befe4e3746a122a2ee70ed1eedd956e16832180a | 4c9abddbe8ec3c0f4b36af5d07976234eb802fa1 | /montecarlo/src/monte_carlo/temp/particle.cpp | d8523d0594c7e4eb517f8cfe3ea098b7a16301cb | [
"MIT"
] | permissive | li779/DECaNT | 9ca4d8b844e81c5435790cd7ee2278ca692b684f | 8fe0faedd372a8214f1bd475eb7451d2eee1ca56 | refs/heads/main | 2023-06-20T09:08:30.720923 | 2021-07-23T19:10:36 | 2021-07-23T19:10:36 | 303,280,053 | 11 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,039 | cpp | #include <iostream>
#include <limits>
#include "./particle.h"
namespace mc
{
// perform free flight within the simulation domain
void particle::fly(double dt, const std::vector<scatterer>& s_list) {
if (_scat_ptr->left<0 && _scat_ptr->right<0)
return;
int next;
while (true){
// determine next scatterer
if (_heading_right) {
if (_scat_ptr->right>-1){
next = _scat_ptr->right;
} else {
next = _scat_ptr->left;
}
} else {
if (_scat_ptr->left>-1) {
next = _scat_ptr->left;
} else {
next = _scat_ptr->right;
}
}
// determine the movement direction
if (next==_scat_ptr->right)
_heading_right = true;
else
_heading_right = false;
arma::vec t = s_list[next].pos();
double dist = arma::norm(_pos - t);
if (dist / _velocity < dt) {
_pos = s_list[next].pos();
_scat_ptr = &(s_list[next]);
dt -= dist / _velocity;
} else {
arma::vec d = arma::normalise(s_list[next].pos() - _pos);
_pos += (_velocity * dt * d);
return;
}
}
}
// step particle state for dt in time
void particle::step(double dt, const std::vector<scatterer>& s_list, const double& max_hop_radius) {
_old_pos = _pos;
const scatterer* new_scat_ptr = nullptr;
if(disolved())
return;
while (_ff_time <= dt) {
dt -= _ff_time;
fly(_ff_time, s_list);
if(_scat_ptr->check_quenching(max_hop_radius)){
set_disolved();
update_diff_len();
return;
}
new_scat_ptr = _scat_ptr->update_state(max_hop_radius);
if (new_scat_ptr!=_scat_ptr){
_scat_ptr = new_scat_ptr;
_pos = _scat_ptr->pos();
}
_ff_time = _scat_ptr->ff_time();
}
fly(dt, s_list);
_ff_time -= dt;
};
} // mc namespace
| [
"noreply@github.com"
] | li779.noreply@github.com |
5348f28f084531f40c533c54c79bef3c1764c78e | 5f049707f53dc31ee4a74c4b2d3a7ed610e29a13 | /Programmers/cpp/_20.10.17(토)_쿼드압축_후_개수_세기.cpp | 5a2c2efe9bca6f8531fea5b9ab9d957000553061 | [] | no_license | oleeyoung520/coding_test_practice | 41e8bc1b641d6daca18c05322ca9674092d4cf35 | 18b873930e1cc208272c5c6792960a5667812b1f | refs/heads/master | 2023-01-23T11:59:05.092161 | 2020-11-30T17:26:15 | 2020-11-30T17:26:15 | 303,244,103 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,180 | cpp | #include <string>
#include <vector>
#include <map>
//#include <iostream>
using namespace std;
vector<int> solution(vector<vector<int>> arr) {
vector<int> answer(2, 0);
int len = arr.size();
while (len > 1) {
vector<vector<map<int, int>>> newMapArr(len / 2, vector<map<int, int>>(len / 2));
vector<vector<int>> newArr(len / 2, vector<int>(len / 2, 0));
for (int i = 0; i < len; i++) {
for (int j = 0; j < len; j++) {
newMapArr[i / 2][j / 2][arr[i][j]]++;
}
}
for (int i = 0; i < len / 2; i++) {
for (int j = 0; j < len / 2; j++) {
if (newMapArr[i][j].size() > 1) {
answer[0] += newMapArr[i][j][0];
answer[1] += newMapArr[i][j][1];
newArr[i][j] = -1;
} else if (newMapArr[i][j].size() == 1) {
newArr[i][j] = (newMapArr[i][j].begin()->first);
}
}
}
arr = newArr;
len /= 2;
}
if (arr[0][0] == 0) {
answer[0] += 1;
} else if (arr[0][0] == 1) {
answer[1] += 1;
}
return answer;
} | [
"2015147520@yonsei.ac.kr"
] | 2015147520@yonsei.ac.kr |
79909b2562a210f119ee993e3b598df46207919f | f7df6576f641633ffa1290969e7b6da48ee3c26d | /src/OrbitQt/CutoutWidget.h | 2fdaf2d2cea8b1bfd9b4086ef495a8a699588293 | [
"BSD-2-Clause",
"LicenseRef-scancode-free-unknown"
] | permissive | beckerhe/orbitprofiler | 96fa8466dac647618e42ff45319d70aceb4505cc | 56541e1e53726f9f824e8216fdcbd4e7b1178965 | refs/heads/main | 2023-06-06T01:08:10.490090 | 2021-12-10T13:31:51 | 2021-12-10T13:31:51 | 235,291,165 | 2 | 0 | BSD-2-Clause | 2021-12-10T13:31:51 | 2020-01-21T08:32:27 | C++ | UTF-8 | C++ | false | false | 906 | h | // Copyright (c) 2020 The Orbit Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef ORBIT_QT_CUTOUT_WIDGET_
#define ORBIT_QT_CUTOUT_WIDGET_
#include <QLabel>
/**
Used by the TutorialOverlay widget (TutorialOverlay.h).
This widget does not provide any functionality on top of QLabel, so there is no
reason to use it except in cases explicitely stated in the documentation of
TutorialOverlay.
CutoutWidget merely provides a semantic difference when placed inside the TutorialOverlay
widget, as TutorialOverlay is looking for instances of this class to determine
the "area of interest" in each tutorial step.
**/
class CutoutWidget : public QLabel {
Q_OBJECT
public:
explicit CutoutWidget(QWidget* parent = nullptr) : QLabel{parent} {
setAttribute(Qt::WA_TransparentForMouseEvents, true);
}
};
#endif
| [
"63750742+reichlfl@users.noreply.github.com"
] | 63750742+reichlfl@users.noreply.github.com |
4bad4cc0c0b492da19be159dd68c2ea74e030ec0 | f18afd0f25affc61bd29a2272710f4dcb749b17d | /source/LibFgBase/src/FgMap.hpp | 67a0fb43a5481384f6ae8411be61a52318884fd4 | [
"MIT"
] | permissive | SingularInversions/FaceGenBaseLibrary | 42fdd8002ba8cf35f4a45b1b30cb3f179225017e | 77985787f9139f3c8e70e69ce6037e8fb56d8e0e | refs/heads/master | 2023-04-27T13:12:49.632730 | 2023-04-26T01:17:31 | 2023-04-26T01:17:31 | 42,960,301 | 47 | 29 | MIT | 2020-12-01T08:00:39 | 2015-09-22T20:54:46 | C++ | UTF-8 | C++ | false | false | 1,856 | hpp | //
// Copyright (c) 2023 Singular Inversions Inc. (facegen.com)
// Use, modification and distribution is subject to the MIT License,
// see accompanying file LICENSE.txt or facegen.com/base_library_license.txt
//
// An associative container alternative to std::Map for small collections:
// * based on std::vector
// * higher-level interface than iterators
// * without the implicit insertion semantics of std::map
// * the collections are assumed small enough that no sorting is done and lookup is O(n).
// * key type must support operator==
// * Looked at loki::AssocVector but didn't like the implicit insertion and OOPy, template-complex design.
//
#ifndef FGMAP_HPP
#define FGMAP_HPP
#include "FgSerial.hpp"
namespace Fg {
template<typename K,typename V>
struct Map
{
Svec<std::pair<K,V>> map;
const V & operator[](const K & k) const // No implicit insertion - throws if key not found
{
for (const std::pair<K,V> & p : map)
if (p.first == k)
return p.second;
FGASSERT_FALSE;
return map[0].second; // Avoid warning
}
Opt<V> find(const K & k) const
{
for (size_t ii=0; ii<map.size(); ++ii)
if (map[ii].first == k)
return map[ii].second;
return {};
}
void insert(const K & k,const V & v) // Throws if key already in use
{
for (const std::pair<K,V> & p : map)
FGASSERT(!(k == p.first));
map.push_back(std::make_pair(k,v));
}
};
template<typename K,typename V>
bool contains(const Map<K,V> & map,const K & key)
{
for (const std::pair<K,V> & p : map.map)
if (p.first == key)
return true;
return false;
}
}
#endif
| [
"abeatty@facegen.com"
] | abeatty@facegen.com |
cb65e370e113509aa4cb00d4095e9d59320b450c | 582fa22af8a99af3ab742fa6af30787d0cefd795 | /practiceAlgorithm2/vectorErase.cpp | 30b3b13220a5e60119b67be54a2ee9dcf55ae6d1 | [] | no_license | iluvdadong/algorithm | 066dae08e77c876d593601ba57223ce6eb28997c | 94eec003ac95aa9a82be946d23eddbef8e1a8478 | refs/heads/master | 2020-07-28T21:40:51.100288 | 2019-11-05T05:08:39 | 2019-11-05T05:08:39 | 209,547,188 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 254 | cpp | #include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> v = { 1,2,3,4,5 };
cout << v[0] << endl; //1출력
v.erase(v.begin() + 0);
cout << v[0] << endl; //1이 없어지므로서 2가 맨 앞으로 와서 2가 출력
} | [
"dh77dh77@gmail.com"
] | dh77dh77@gmail.com |
c888f1efc4ad0cc13ff6727d143e402080cc8de0 | 36f494f472b66887e11e46409da519c4cfe00aeb | /Assignment3/BlueMen.cpp | 6dbeec9007c7fdf83893e98290a472df5fd889a7 | [] | no_license | chermaine/CPP-Projects | a0bd3774e4f7d23db7514e9209ebc2b61d542b5e | 5d9ea4f3b3b63f2f4db92964bee972e33c9fc671 | refs/heads/master | 2021-06-26T11:32:48.477781 | 2017-09-12T01:19:57 | 2017-09-12T01:19:57 | 74,237,271 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,609 | cpp | /*******************************************************************************
* Name: Chermaine Cheang
* Date: May 3, 2016
* Description: BlueMen class specification file
* ****************************************************************************/
#include "BlueMen.hpp"
#include <cstdlib>
/*******************************************************************************
* Function: BlueMen()
* Description: BlueMen class default constructor
* Post-condition: BlueMen object is created with basic information
* ****************************************************************************/
BlueMen::BlueMen():Creature()
{
this->defPoint = 3;
this->armor = 3;
this->strength = 12;
this->name = "BlueMen";
}
/*******************************************************************************
* Function: attack()
* Description: To attack, BlueMen will throw the dice x number of times based
* on his attPoint, result will be randomly generated
* Pre-condition: BlueMen exists
* Post-condition: attack value is determined and returned
* ****************************************************************************/
int BlueMen::attack()
{
int temp, total=0;
//loop through at least once to get a randomly generated number between
//1 to 6 because BlueMen attacking style is 2d6
//add that number to total and decrement attPoint by 1
//if attPoint is less or equal to 0, exit the loop
//else repeat the loop
do
{
temp = rand()%10 + 1;
total += temp;
attPoint--;
} while (attPoint > 0);
std::cout << getName() << " attacks for " << total << std::endl;
setAttPoint(2); //reset attPoint to 2 for next attack
return total;
}
/*******************************************************************************
* Function: defense()
* Description: throw the number of dice x number of times based on BlueMen
* defending style (2d6); calculate damage receives for this round of combat;
* update strength accordingly; update defPoint according to Mob's ability
* Parameter: int
* Pre-condition: BlueMen exists
* Post-condition: defending value is determined and returned
* ****************************************************************************/
int BlueMen::defense(int att)
{
int temp=0, total=0, damage=0;
int initial = getDefPoint();
while (defPoint >0)
{
temp = rand()%6 + 1;
total += temp;
defPoint--;
}
setDefPoint(initial);
std::cout << getName() << " defends for " << total << " + " << getArmor()
<< " points armor" << std::endl;
total += getArmor();
//if BlueMen will survive this round of combat
if (total < att)
{
//calculate damege
damage = att - total;
//if damage is greater than strength, set strength to 0, set alive to false
if (this->strength-damage <= 0)
{
setStrength(0);
setAlive(false);
}
//else, update strength accordingly
else
setStrength(this->strength - damage);
//check if BlueMen receives 4 points of damage, to take Mob's ability into
//account
if (getStrength() <=8)
{
if (getDefPoint() == 3)
setDefPoint(this->defPoint - 1);
}
if (getStrength() <=4)
{
if (getDefPoint() == 2)
setDefPoint(this->defPoint - 1);
}
}
else
damage = 0;
std::cout << getName() << " receives " << damage << " points of damage." << std::endl;
std::cout << getName() << " current strength points: " << getStrength() << std::endl;
return damage;
}
| [
"noreply@github.com"
] | chermaine.noreply@github.com |
34dc206a9d755558a34a3ab82c6dc95d7df4668e | 3ff1fe3888e34cd3576d91319bf0f08ca955940f | /sms/include/tencentcloud/sms/v20210111/model/DescribePhoneNumberInfoRequest.h | 968aad2fb3f586ce65677d1c02893532c1a5c649 | [
"Apache-2.0"
] | permissive | TencentCloud/tencentcloud-sdk-cpp | 9f5df8220eaaf72f7eaee07b2ede94f89313651f | 42a76b812b81d1b52ec6a217fafc8faa135e06ca | refs/heads/master | 2023-08-30T03:22:45.269556 | 2023-08-30T00:45:39 | 2023-08-30T00:45:39 | 188,991,963 | 55 | 37 | Apache-2.0 | 2023-08-17T03:13:20 | 2019-05-28T08:56:08 | C++ | UTF-8 | C++ | false | false | 3,638 | h | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef TENCENTCLOUD_SMS_V20210111_MODEL_DESCRIBEPHONENUMBERINFOREQUEST_H_
#define TENCENTCLOUD_SMS_V20210111_MODEL_DESCRIBEPHONENUMBERINFOREQUEST_H_
#include <string>
#include <vector>
#include <map>
#include <tencentcloud/core/AbstractModel.h>
namespace TencentCloud
{
namespace Sms
{
namespace V20210111
{
namespace Model
{
/**
* DescribePhoneNumberInfo请求参数结构体
*/
class DescribePhoneNumberInfoRequest : public AbstractModel
{
public:
DescribePhoneNumberInfoRequest();
~DescribePhoneNumberInfoRequest() = default;
std::string ToJsonString() const;
/**
* 获取查询手机号码,采用 E.164 标准,格式为+[国家或地区码][手机号],单次请求最多支持200个手机号。
例如:+8613711112222, 其中前面有一个+号 ,86为国家码,13711112222为手机号。
* @return PhoneNumberSet 查询手机号码,采用 E.164 标准,格式为+[国家或地区码][手机号],单次请求最多支持200个手机号。
例如:+8613711112222, 其中前面有一个+号 ,86为国家码,13711112222为手机号。
*
*/
std::vector<std::string> GetPhoneNumberSet() const;
/**
* 设置查询手机号码,采用 E.164 标准,格式为+[国家或地区码][手机号],单次请求最多支持200个手机号。
例如:+8613711112222, 其中前面有一个+号 ,86为国家码,13711112222为手机号。
* @param _phoneNumberSet 查询手机号码,采用 E.164 标准,格式为+[国家或地区码][手机号],单次请求最多支持200个手机号。
例如:+8613711112222, 其中前面有一个+号 ,86为国家码,13711112222为手机号。
*
*/
void SetPhoneNumberSet(const std::vector<std::string>& _phoneNumberSet);
/**
* 判断参数 PhoneNumberSet 是否已赋值
* @return PhoneNumberSet 是否已赋值
*
*/
bool PhoneNumberSetHasBeenSet() const;
private:
/**
* 查询手机号码,采用 E.164 标准,格式为+[国家或地区码][手机号],单次请求最多支持200个手机号。
例如:+8613711112222, 其中前面有一个+号 ,86为国家码,13711112222为手机号。
*/
std::vector<std::string> m_phoneNumberSet;
bool m_phoneNumberSetHasBeenSet;
};
}
}
}
}
#endif // !TENCENTCLOUD_SMS_V20210111_MODEL_DESCRIBEPHONENUMBERINFOREQUEST_H_
| [
"tencentcloudapi@tencent.com"
] | tencentcloudapi@tencent.com |
92611ddf2c2ed7e0c228df008cf0612b2f9dfc35 | 111cb64da7a6b40fa80238e2c6e30615caf8a0b0 | /Virtual-ParkingManagementSystem/Linearway Parking/Linear way parking.cpp | 89fe35a26b590d96959e64b4fe46f90e1e6fefc3 | [] | no_license | chavasaiteja/My-Academic-Projects | 1f80188a27b9d7f9e6e25bbab3e3a44072e6c403 | ef5bc96c4bf85fdbbf410311db24467d8558cd56 | refs/heads/master | 2021-07-12T08:24:14.244077 | 2017-10-18T04:09:17 | 2017-10-18T04:09:17 | 105,848,419 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,611 | cpp | #include<iostream>
using namespace std;
#include<stdlib.h>
#include<strings.h>
struct node
{
//char id[10];//we can use it as floor number and car number
string id;
node *floor;//link for other nodes one by one.
node *slots;//For Edge link.
};
void ParkingBuilding();
void AddVehicle();
void Display();
void RemoveVehicle();
struct node *first,*newnode,*plinker,*elinker,*tempry;
int n,i,x=0,j,nov;
string a;
string b;
int main()
{
int ch;
while (1)
{ system("cls");
cout<<"\n1. Make Parking Building\n2. Parking of Vehicle\n3. Unparking of Vehicle";
cout<<"\n4. Display of Parking Lots\n5. Exit\n";
cout<<"Enter your choice:";
cin>>ch;
switch (ch)
{
case 1:
ParkingBuilding();
system("pause");
break;
case 2:
AddVehicle();
system("pause");
break;
case 3:
RemoveVehicle();
system("pause");
break;
case 4:
system("cls");
Display();
system("pause");
break;
case 5:
exit(0);
default:
cout<<"Soory!You have entered wrong option!!\n";
break;
}
}
return 0;
}
void ParkingBuilding()
{
cout<<"How many floors are there? : ";
cin>>n;
cout<<"Enter all the floor numbers:\n";
for(i=1;i<=n;i++)
{
if(x==0)//Creating first node or root for total building
{
newnode = new node;
cin>>newnode->id;
first=newnode;//always used to reffered to root floor
plinker=newnode;//used to create links for one after other nodes by links
newnode->floor=NULL;
newnode->slots=NULL;
x++;//Next nodes
}
else
{
//-------------------------//
newnode = new node;
cin>>newnode->id;
newnode->floor=NULL;
newnode->slots=NULL;
//------------------------//
plinker->floor=newnode;
plinker = newnode;
}
}
}
void AddVehicle()
{
cout<<"Pls give max possible vehicles can be parked:\n";
cin>>nov;//max possible no. of vehicles
cout<<"\nEnter the vehicle corresponding to floor . Enter a b, where a = floor number and b = vehicle number\n";
cout<<"\nNote:Enter 0 0 if over\n";
for(j=1;j<=nov;j++)
{
cin>>a>>b;
/*if(strcmp(a,"break") == 0)
{
break;
} */
plinker = first;
/*%*/while(plinker != NULL && plinker->id != a)//This while loop will take Plinker to perticular required floor
{
//cout<<"OK";
plinker=plinker->floor;
}
if(plinker == NULL)
{
cout<<"Sorry! No floor available in the building \n";
break;
}
//-------------------------------------------------------------------------//
elinker = plinker;
while(elinker->slots != NULL)//This will take edge link to last
{
elinker = elinker->slots;
}
newnode = new node;
newnode->id=b;
elinker->slots = newnode;
newnode->floor=NULL;
newnode->slots=NULL;
}
}
void RemoveVehicle()
{
cout<<"\nEnter the vehicle to be unparked corresponding to floor . Enter a b, where a = floor number and b = vehicle number to be removed\n";
cin>>a>>b;
/*if(strcmp(a,"break") == 0)
{
break;
} */
plinker = first;
/*%*/while(plinker != NULL && plinker->id != a)//This while loop will take Plinker to perticular required floor
{
// cout<<"OK";
plinker=plinker->floor;
}
if(plinker == NULL)
{
cout<<"Sorry! No floor available in the building \n";
}
//-------------------------------------------------------------------------//
elinker = plinker;
while(elinker->id != b )//This will take edge link to last
{
tempry = elinker;
elinker = elinker->slots;
}
free(elinker);
tempry->floor=NULL;
tempry->slots=NULL;
/* newnode = new node;
newnode->id=b;
elinker->slots = newnode;
newnode->floor=NULL;
newnode->slots=NULL; */
}
void Display()
{
cout<<"\nVehicles parking position display in ParkingBuilding is : \n\n";
plinker = first;
while(plinker != NULL)
{
cout<<plinker->id<<" ---->"<<"\t";
elinker = plinker->slots;
while(elinker != NULL)
{
cout<<elinker->id<<" -->"<<"\t";
elinker = elinker->slots;
}
cout<<"||||\n";
cout<<"\n";
plinker = plinker->floor;
}
}
| [
"noreply@github.com"
] | chavasaiteja.noreply@github.com |
6d7ee10ff81eebf19deabd7f7852e10e066e8905 | 1c1b2d570c48ff4b7a44534587599cb92ad52aae | /src/rpcmining.cpp | 7742bf93d127276e85f276a5dc6fee95af7a17df | [
"MIT"
] | permissive | likecoin-dev/DubaiCoin | 50b54fe64e35cfc43666739c6425d2c995a8d582 | ad30c991c13fe9b83cff371ba205b02722cd33f2 | refs/heads/master | 2021-07-15T00:18:03.575394 | 2016-09-28T07:55:37 | 2016-09-28T07:55:37 | 107,713,367 | 0 | 0 | null | 2017-10-20T18:35:03 | 2017-10-20T18:35:02 | null | UTF-8 | C++ | false | false | 19,206 | cpp | // Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "main.h"
#include "db.h"
#include "txdb.h"
#include "init.h"
#include "miner.h"
#include "bitcoinrpc.h"
using namespace json_spirit;
using namespace std;
Value getsubsidy(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getsubsidy [nTarget]\n"
"Returns proof-of-work subsidy value for the specified value of target.");
return (uint64_t)GetProofOfWorkReward(0);
}
Value getmininginfo(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getmininginfo\n"
"Returns an object containing mining-related information.");
uint64_t nMinWeight = 0, nMaxWeight = 0, nWeight = 0;
pwalletMain->GetStakeWeight(*pwalletMain, nMinWeight, nMaxWeight, nWeight);
Object obj, diff, weight;
obj.push_back(Pair("Blocks", (int)nBestHeight));
obj.push_back(Pair("Current Block Size",(uint64_t)nLastBlockSize));
obj.push_back(Pair("Current Block Tx",(uint64_t)nLastBlockTx));
diff.push_back(Pair("Proof of Work", GetDifficulty()));
diff.push_back(Pair("Proof of Stake", GetDifficulty(GetLastBlockIndex(pindexBest, true))));
diff.push_back(Pair("Search Interval", (int)nLastCoinStakeSearchInterval));
obj.push_back(Pair("Difficulty", diff));
obj.push_back(Pair("Block Value", (uint64_t)GetProofOfWorkReward(0)));
obj.push_back(Pair("Net MH/s", GetPoWMHashPS()));
obj.push_back(Pair("Net Stake Weight", GetPoSKernelPS()));
obj.push_back(Pair("Errors", GetWarnings("statusbar")));
obj.push_back(Pair("Pooled Tx", (uint64_t)mempool.size()));
weight.push_back(Pair("Minimum", (uint64_t)nMinWeight));
weight.push_back(Pair("Maximum", (uint64_t)nMaxWeight));
weight.push_back(Pair("Combined", (uint64_t)nWeight));
obj.push_back(Pair("Stake Weight", weight));
obj.push_back(Pair("Stake Interest", (uint64_t)COIN_YEAR_REWARD));
obj.push_back(Pair("Testnet", fTestNet));
return obj;
}
Value getstakinginfo(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getstakinginfo\n"
"Returns an object containing staking-related information.");
uint64_t nMinWeight = 0, nMaxWeight = 0, nWeight = 0;
pwalletMain->GetStakeWeight(*pwalletMain, nMinWeight, nMaxWeight, nWeight);
uint64_t nNetworkWeight = GetPoSKernelPS();
bool staking = nLastCoinStakeSearchInterval && nWeight;
int nExpectedTime = staking ? (nTargetSpacing * nNetworkWeight / nWeight) : -1;
Object obj;
obj.push_back(Pair("Enabled", GetBoolArg("-staking", true)));
obj.push_back(Pair("Staking", staking));
obj.push_back(Pair("Errors", GetWarnings("statusbar")));
obj.push_back(Pair("Current Block Size", (uint64_t)nLastBlockSize));
obj.push_back(Pair("Current Block Tx", (uint64_t)nLastBlockTx));
obj.push_back(Pair("Pooled Tx", (uint64_t)mempool.size()));
obj.push_back(Pair("Difficulty", GetDifficulty(GetLastBlockIndex(pindexBest, true))));
obj.push_back(Pair("Search Interval", (int)nLastCoinStakeSearchInterval));
obj.push_back(Pair("Weight", (uint64_t)nWeight));
obj.push_back(Pair("Net Stake Weight", (uint64_t)nNetworkWeight));
obj.push_back(Pair("Expected Time", nExpectedTime));
return obj;
}
Value getworkex(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"getworkex [data, coinbase]\n"
"If [data, coinbase] is not specified, returns extended work data.\n"
);
if (vNodes.empty())
throw JSONRPCError(-9, "DubaiCoin is not connected!");
if (IsInitialBlockDownload())
throw JSONRPCError(-10, "DubaiCoin is downloading blocks...");
if (pindexBest->nHeight >= LAST_POW_BLOCK)
throw JSONRPCError(RPC_MISC_ERROR, "No more PoW blocks");
typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
static mapNewBlock_t mapNewBlock;
static vector<CBlock*> vNewBlock;
static CReserveKey reservekey(pwalletMain);
if (params.size() == 0)
{
// Update block
static unsigned int nTransactionsUpdatedLast;
static CBlockIndex* pindexPrev;
static int64_t nStart;
static CBlock* pblock;
if (pindexPrev != pindexBest ||
(nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
{
if (pindexPrev != pindexBest)
{
// Deallocate old blocks since they're obsolete now
mapNewBlock.clear();
BOOST_FOREACH(CBlock* pblock, vNewBlock)
delete pblock;
vNewBlock.clear();
}
nTransactionsUpdatedLast = nTransactionsUpdated;
pindexPrev = pindexBest;
nStart = GetTime();
// Create new block
pblock = CreateNewBlock(pwalletMain);
if (!pblock)
throw JSONRPCError(-7, "Out of memory");
vNewBlock.push_back(pblock);
}
// Update nTime
pblock->nTime = max(pindexPrev->GetPastTimeLimit()+1, GetAdjustedTime());
pblock->nNonce = 0;
// Update nExtraNonce
static unsigned int nExtraNonce = 0;
IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
// Save
mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
// Prebuild hash buffers
char pmidstate[32];
char pdata[128];
char phash1[64];
FormatHashBuffers(pblock, pmidstate, pdata, phash1);
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
CTransaction coinbaseTx = pblock->vtx[0];
std::vector<uint256> merkle = pblock->GetMerkleBranch(0);
Object result;
result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
ssTx << coinbaseTx;
result.push_back(Pair("coinbase", HexStr(ssTx.begin(), ssTx.end())));
Array merkle_arr;
BOOST_FOREACH(uint256 merkleh, merkle) {
merkle_arr.push_back(HexStr(BEGIN(merkleh), END(merkleh)));
}
result.push_back(Pair("merkle", merkle_arr));
return result;
}
else
{
// Parse parameters
vector<unsigned char> vchData = ParseHex(params[0].get_str());
vector<unsigned char> coinbase;
if(params.size() == 2)
coinbase = ParseHex(params[1].get_str());
if (vchData.size() != 128)
throw JSONRPCError(-8, "Invalid parameter");
CBlock* pdata = (CBlock*)&vchData[0];
// Byte reverse
for (int i = 0; i < 128/4; i++)
((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
// Get saved block
if (!mapNewBlock.count(pdata->hashMerkleRoot))
return false;
CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
pblock->nTime = pdata->nTime;
pblock->nNonce = pdata->nNonce;
if(coinbase.size() == 0)
pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
else
CDataStream(coinbase, SER_NETWORK, PROTOCOL_VERSION) >> pblock->vtx[0]; // FIXME - HACK!
pblock->hashMerkleRoot = pblock->BuildMerkleTree();
return CheckWork(pblock, *pwalletMain, reservekey);
}
}
Value getwork(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getwork [data]\n"
"If [data] is not specified, returns formatted hash data to work on:\n"
" \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated
" \"data\" : block data\n"
" \"hash1\" : formatted hash buffer for second hash (DEPRECATED)\n" // deprecated
" \"target\" : little endian hash target\n"
"If [data] is specified, tries to solve the block and returns true if it was successful.");
if (vNodes.empty())
throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "DubaiCoin is not connected!");
if (IsInitialBlockDownload())
throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "DubaiCoin is downloading blocks...");
if (pindexBest->nHeight >= LAST_POW_BLOCK)
throw JSONRPCError(RPC_MISC_ERROR, "No more PoW blocks");
typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
static mapNewBlock_t mapNewBlock; // FIXME: thread safety
static vector<CBlock*> vNewBlock;
static CReserveKey reservekey(pwalletMain);
if (params.size() == 0)
{
// Update block
static unsigned int nTransactionsUpdatedLast;
static CBlockIndex* pindexPrev;
static int64_t nStart;
static CBlock* pblock;
if (pindexPrev != pindexBest ||
(nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
{
if (pindexPrev != pindexBest)
{
// Deallocate old blocks since they're obsolete now
mapNewBlock.clear();
BOOST_FOREACH(CBlock* pblock, vNewBlock)
delete pblock;
vNewBlock.clear();
}
// Clear pindexPrev so future getworks make a new block, despite any failures from here on
pindexPrev = NULL;
// Store the pindexBest used before CreateNewBlock, to avoid races
nTransactionsUpdatedLast = nTransactionsUpdated;
CBlockIndex* pindexPrevNew = pindexBest;
nStart = GetTime();
// Create new block
pblock = CreateNewBlock(pwalletMain);
if (!pblock)
throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
vNewBlock.push_back(pblock);
// Need to update only after we know CreateNewBlock succeeded
pindexPrev = pindexPrevNew;
}
// Update nTime
pblock->UpdateTime(pindexPrev);
pblock->nNonce = 0;
// Update nExtraNonce
static unsigned int nExtraNonce = 0;
IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
// Save
mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
// Pre-build hash buffers
char pmidstate[32];
char pdata[128];
char phash1[64];
FormatHashBuffers(pblock, pmidstate, pdata, phash1);
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
Object result;
result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated
result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1)))); // deprecated
result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
return result;
}
else
{
// Parse parameters
vector<unsigned char> vchData = ParseHex(params[0].get_str());
if (vchData.size() != 128)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
CBlock* pdata = (CBlock*)&vchData[0];
// Byte reverse
for (int i = 0; i < 128/4; i++)
((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
// Get saved block
if (!mapNewBlock.count(pdata->hashMerkleRoot))
return false;
CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
pblock->nTime = pdata->nTime;
pblock->nNonce = pdata->nNonce;
pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
pblock->hashMerkleRoot = pblock->BuildMerkleTree();
return CheckWork(pblock, *pwalletMain, reservekey);
}
}
Value getblocktemplate(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getblocktemplate [params]\n"
"Returns data needed to construct a block to work on:\n"
" \"version\" : block version\n"
" \"previousblockhash\" : hash of current highest block\n"
" \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n"
" \"coinbaseaux\" : data that should be included in coinbase\n"
" \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n"
" \"target\" : hash target\n"
" \"mintime\" : minimum timestamp appropriate for next block\n"
" \"curtime\" : current timestamp\n"
" \"mutable\" : list of ways the block template may be changed\n"
" \"noncerange\" : range of valid nonces\n"
" \"sigoplimit\" : limit of sigops in blocks\n"
" \"sizelimit\" : limit of block size\n"
" \"bits\" : compressed target of next block\n"
" \"height\" : height of the next block\n"
"See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
std::string strMode = "template";
if (params.size() > 0)
{
const Object& oparam = params[0].get_obj();
const Value& modeval = find_value(oparam, "mode");
if (modeval.type() == str_type)
strMode = modeval.get_str();
else if (modeval.type() == null_type)
{
/* Do nothing */
}
else
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
}
if (strMode != "template")
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
if (vNodes.empty())
throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "DubaiCoin is not connected!");
if (IsInitialBlockDownload())
throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "DubaiCoin is downloading blocks...");
if (pindexBest->nHeight >= LAST_POW_BLOCK)
throw JSONRPCError(RPC_MISC_ERROR, "No more PoW blocks");
static CReserveKey reservekey(pwalletMain);
// Update block
static unsigned int nTransactionsUpdatedLast;
static CBlockIndex* pindexPrev;
static int64_t nStart;
static CBlock* pblock;
if (pindexPrev != pindexBest ||
(nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 5))
{
// Clear pindexPrev so future calls make a new block, despite any failures from here on
pindexPrev = NULL;
// Store the pindexBest used before CreateNewBlock, to avoid races
nTransactionsUpdatedLast = nTransactionsUpdated;
CBlockIndex* pindexPrevNew = pindexBest;
nStart = GetTime();
// Create new block
if(pblock)
{
delete pblock;
pblock = NULL;
}
pblock = CreateNewBlock(pwalletMain);
if (!pblock)
throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
// Need to update only after we know CreateNewBlock succeeded
pindexPrev = pindexPrevNew;
}
// Update nTime
pblock->UpdateTime(pindexPrev);
pblock->nNonce = 0;
Array transactions;
map<uint256, int64_t> setTxIndex;
int i = 0;
CTxDB txdb("r");
BOOST_FOREACH (CTransaction& tx, pblock->vtx)
{
uint256 txHash = tx.GetHash();
setTxIndex[txHash] = i++;
if (tx.IsCoinBase() || tx.IsCoinStake())
continue;
Object entry;
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
ssTx << tx;
entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end())));
entry.push_back(Pair("hash", txHash.GetHex()));
MapPrevTx mapInputs;
map<uint256, CTxIndex> mapUnused;
bool fInvalid = false;
if (tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
{
entry.push_back(Pair("fee", (int64_t)(tx.GetValueIn(mapInputs) - tx.GetValueOut())));
Array deps;
BOOST_FOREACH (MapPrevTx::value_type& inp, mapInputs)
{
if (setTxIndex.count(inp.first))
deps.push_back(setTxIndex[inp.first]);
}
entry.push_back(Pair("depends", deps));
int64_t nSigOps = tx.GetLegacySigOpCount();
nSigOps += tx.GetP2SHSigOpCount(mapInputs);
entry.push_back(Pair("sigops", nSigOps));
}
transactions.push_back(entry);
}
Object aux;
aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
static Array aMutable;
if (aMutable.empty())
{
aMutable.push_back("time");
aMutable.push_back("transactions");
aMutable.push_back("prevblock");
}
Object result;
result.push_back(Pair("version", pblock->nVersion));
result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
result.push_back(Pair("transactions", transactions));
result.push_back(Pair("coinbaseaux", aux));
result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue));
result.push_back(Pair("target", hashTarget.GetHex()));
result.push_back(Pair("mintime", (int64_t)pindexPrev->GetPastTimeLimit()+1));
result.push_back(Pair("mutable", aMutable));
result.push_back(Pair("noncerange", "00000000ffffffff"));
result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS));
result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE));
result.push_back(Pair("curtime", (int64_t)pblock->nTime));
result.push_back(Pair("bits", HexBits(pblock->nBits)));
result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
return result;
}
Value submitblock(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"submitblock <hex data> [optional-params-obj]\n"
"[optional-params-obj] parameter is currently ignored.\n"
"Attempts to submit new block to network.\n"
"See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
vector<unsigned char> blockData(ParseHex(params[0].get_str()));
CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
CBlock block;
try {
ssBlock >> block;
}
catch (std::exception &e) {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
}
bool fAccepted = ProcessBlock(NULL, &block);
if (!fAccepted)
return "rejected";
return Value::null;
}
| [
"DubaiCoinDev@gmail.com"
] | DubaiCoinDev@gmail.com |
af379c8811bb63e0ef52bd6cea1b248e0586dbc4 | 5376fcdff458e85c49299274185b724ae2438b69 | /src/agora_edu_sdk/base/main/core/interop/agora_utils_c.cpp | d3ebbf55bab6f987763c4378c3e2f673a29862f5 | [] | no_license | pengdu/AgoraDualTeacher | aabf9aae7a1a42a1f64ecfeae56fbcf61bed8319 | 4da68749f638a843053a57d199450c798dd3f286 | refs/heads/master | 2023-07-31T14:25:52.797376 | 2021-09-22T09:51:49 | 2021-09-22T09:51:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,776 | cpp | //
// Agora C SDK
//
// Created by Tommy Miao in 2020.5
// Copyright (c) 2020 Agora.io. All rights reserved.
//
#include "agora_utils_c.h"
#include "base/AgoraBase.h"
#include "base/agora_base.h"
namespace agora {
namespace interop {
/**
* Video Frame
*/
void copy_video_frame_from_c(agora::media::base::VideoFrame* cpp_frame, const video_frame& frame) {
if (!cpp_frame) {
return;
}
cpp_frame->type = static_cast<agora::media::base::VIDEO_PIXEL_FORMAT>(frame.type);
cpp_frame->width = frame.width;
cpp_frame->height = frame.height;
cpp_frame->yStride = frame.y_stride;
cpp_frame->uStride = frame.u_stride;
cpp_frame->vStride = frame.v_stride;
cpp_frame->yBuffer = frame.y_buffer;
cpp_frame->uBuffer = frame.u_buffer;
cpp_frame->vBuffer = frame.v_buffer;
cpp_frame->rotation = frame.rotation;
cpp_frame->renderTimeMs = frame.render_time_ms;
cpp_frame->avsync_type = frame.avsync_type;
}
void copy_video_frame(video_frame* frame, const agora::media::base::VideoFrame& cpp_frame) {
if (!frame) {
return;
}
frame->type = cpp_frame.type;
frame->width = cpp_frame.width;
frame->height = cpp_frame.height;
frame->y_stride = cpp_frame.yStride;
frame->u_stride = cpp_frame.uStride;
frame->v_stride = cpp_frame.vStride;
frame->y_buffer = cpp_frame.yBuffer;
frame->u_buffer = cpp_frame.uBuffer;
frame->v_buffer = cpp_frame.vBuffer;
frame->rotation = cpp_frame.rotation;
frame->render_time_ms = cpp_frame.renderTimeMs;
frame->avsync_type = cpp_frame.avsync_type;
}
/**
* Audio PCM Frame
*/
void copy_audio_pcm_frame_from_c(agora::media::base::AudioPcmFrame* cpp_frame,
const audio_pcm_frame& frame) {
if (!cpp_frame) {
return;
}
cpp_frame->capture_timestamp = frame.capture_timestamp;
cpp_frame->samples_per_channel_ = frame.samples_per_channel;
cpp_frame->sample_rate_hz_ = frame.sample_rate_hz;
cpp_frame->num_channels_ = frame.num_channels;
cpp_frame->bytes_per_sample = frame.bytes_per_sample;
for (size_t i = 0; i < agora::media::base::AudioPcmFrame::kMaxDataSizeSamples; ++i) {
cpp_frame->data_[i] = frame.data[i];
}
}
void copy_audio_pcm_frame(audio_pcm_frame* frame,
const agora::media::base::AudioPcmFrame& cpp_frame) {
if (!frame) {
return;
}
frame->capture_timestamp = cpp_frame.capture_timestamp;
frame->samples_per_channel = cpp_frame.samples_per_channel_;
frame->sample_rate_hz = cpp_frame.sample_rate_hz_;
frame->num_channels = cpp_frame.num_channels_;
frame->bytes_per_sample = cpp_frame.bytes_per_sample;
for (size_t i = 0; i < agora::media::base::AudioPcmFrame::kMaxDataSizeSamples; ++i) {
frame->data[i] = cpp_frame.data_[i];
}
}
} // namespace interop
} // namespace agora
| [
"wangqixin@agora.io"
] | wangqixin@agora.io |
63addad6b99223c704c40b0221142aef57fd5ebf | 09ddd2df75bce4df9e413d3c8fdfddb7c69032b4 | /include/CSS/CSSImportRule.h | 14422cbab0e6698310f86de05133a8bf149c8bb8 | [] | no_license | sigurdle/FirstProject2 | be22e4824da8cd2cb5047762478050a04a4ac63b | dee78c62a1b95e55fcdf3bf2a9bc79c69705bf94 | refs/heads/master | 2021-01-16T18:45:41.042140 | 2020-08-18T16:57:13 | 2020-08-18T16:57:13 | 3,554,336 | 6 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 1,125 | h | #ifndef Web_CSSImportRule_h
#define Web_CSSImportRule_h
//#include "resource.h" // main symbols
#include "CSSRule.h"
namespace System
{
namespace Web
{
interface CSSImportRuleListener
{
virtual void OnStyleRuleChanged(CSSImportRule* pRule) = 0;
};
class XMLEXT CSSImportRule :
public CSSRule
{
public:
CTOR CSSImportRule();
~CSSImportRule();
// int FinalConstruct();
// void FinalRelease();
/*
CSSImportRuleListener* m_pListener;
CComObject<CLCSSStyleDeclaration>* m_declaration;
CArray<CSSSelector*,CSSSelector*> m_selectorList; // The parsed selectorText list
bool m_bCSSTextUpdated;
void UpdateCSSText();
void ParseCSSText();
*/
void LoadHref(StringIn href);
#if 0
virtual void OnStyleDeclChanged(CLCSSStyleDeclaration* pStyleDecl)
{
m_bCSSTextUpdated = false;
// FireOnChanged(type, targetObject, dispID); // TODO remove
}
#endif
MediaList* get_media();
String get_href() const;
CSSStyleSheet* get_styleSheet();
CSSType get_type() const;
void set_cssText(StringIn newVal);
public:
CSSStyleSheet* m_styleSheet;
String m_href;
};
} // Web
}
#endif // Web_CSSImportRule_h
| [
"sigurd.lerstad@gmail.com"
] | sigurd.lerstad@gmail.com |
1525e7a9c126b20de80a233ce70a23613bcb40f7 | 1dad3557a9f9fd3666f0b34622804dc9a63fe0b4 | /type convert claass to classs.cpp | a280b963864e9cb113e0e274842867868767da28 | [] | no_license | sarthikbabuta/Cpp-Programs | 7b064ea372dd195c10dfe8887e8deca97359fcf3 | a28ad7f1e1f6434bac7736973c328792268ccf5b | refs/heads/master | 2021-01-23T20:07:17.237971 | 2017-09-08T11:00:07 | 2017-09-08T11:00:07 | 102,852,253 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 515 | cpp | #include<iostream>
using namespace std;
class rectangle;
class square
{
int side;
public:
square(int s)
{
side=s;
}
int getside()
{
return side;
}
};
class rectangle
{
int len,breadth;
public:
rectangle(int l,int b)
{
len=l;
breadth=b;
}
rectangle(square s)
{
len=breadth=s.getside();
}
void showdata()
{
cout<<"length="<<len<<"\tbreadth="<<breadth<<"\n";
}
};
int main()
{
rectangle r(10,20);
square s(50);
r.showdata();
r=s;
r.showdata();
return 0;
}
| [
"babuta.1997sarthik@gmail.com"
] | babuta.1997sarthik@gmail.com |
740c061bd4a2f1a337a4d6c5f7c1702ba2e4a576 | 5d13e694bb360848c709ac0197fa7d81019acf98 | /cvHistCalc/main.cpp | 2728dc0045266287fb85600b20421c34e9c9eaad | [] | no_license | Toshik1/SUAI_1441_Labs | be4278f3b87a1098d107089fc101fc37f7ca974f | 46170b5ac6b3781f79d9bb30c58cc30b3be5c403 | refs/heads/master | 2020-06-05T00:03:49.212723 | 2019-06-17T01:29:27 | 2019-06-17T01:29:27 | 192,244,419 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,889 | cpp | #include <iostream>
#include <opencv4/opencv2/highgui/highgui.hpp>
#include <opencv4/opencv2/imgproc/imgproc.hpp>
#include <QApplication>
#include <QWidget>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QLabel>
#include <QSlider>
#include <QtCore>
using std::cout;
using std::cin;
using std::endl;
using namespace cv;
Mat image = imread("/home/toshiki/files/картинки/PNG for LS/kek.png");
QImage img = MatToQimage(image);
inline QImage MatToQimage(const Mat &input){
QImage image(input.data,
input.cols, input.rows,
static_cast<int>(input.step),
QImage::Format_RGB888);
return image.rgbSwapped();
}
void histDisplay(Mat image, const char* name){
int hist[256];
memset(hist, 0, 256*sizeof(*hist));
for(int y = 0; y < image.rows; y++)
for(int x = 0; x < image.cols; x++)
hist[(int)image.at<uchar>(y,x)]++;
int hist_w = 256; int hist_h = 100;
int bin_w = cvRound((double) hist_w/256);
Mat histImage(hist_h, hist_w, CV_8UC1, Scalar(255, 255, 255));
int max = hist[0];
for(int i = 1; i < 256; i++)
if(max < hist[i])
max = hist[i];
for(int i = 0; i < 256; i++)
hist[i] = ((double)hist[i]/max)*histImage.rows;
for(int i = 0; i < 256; i++){
line(histImage, Point(bin_w*(i), hist_h),
Point(bin_w*(i), hist_h - hist[i]),
Scalar(0,0,0));
}
namedWindow(name, CV_WINDOW_AUTOSIZE);
imshow(name, histImage);
}
QImage brightness(Mat input, int ratio){
Mat new_image = Mat::zeros(input.size(), input.type());
for( int y = 0; y < input.rows; y++ )
for( int x = 0; x < input.cols; x++ )
for( int c = 0; c < 3; c++ )
new_image.at<Vec3b>(y,x)[c] = saturate_cast<uchar>( 1*( input.at<Vec3b>(y,x)[c] ) + ratio );
QImage image = MatToQimage(new_image);
return image;
}
void on_Slider_valueChanged(int arg1){
int ratio = arg1*2.55;
plbl2->setPixmap(QPixmap::fromImage(brightness(image, ratio).scaled(img.width()/2, img.height()/2, Qt::KeepAspectRatio)));
}
int main(int argc, char *argv[]){
//Mat image = imread("/home/toshiki/files/картинки/PNG for LS/kek.png");
/*Mat new_image = Mat::zeros( image.size(), image.type() );
for( int y = 0; y < image.rows; y++ )
for( int x = 0; x < image.cols; x++ )
for( int c = 0; c < 3; c++ )
new_image.at<Vec3b>(y,x)[c] = saturate_cast<uchar>( 1*( image.at<Vec3b>(y,x)[c] ) + 20 );*/
/*std::vector<Mat>(rgb_planes);
split(image, rgb_planes);
histDisplay(rgb_planes[0], "red_Original");
namedWindow("Original Image");
imshow("Original Image", image);
histDisplay(image, "Original Histogram");
split(new_image, rgb_planes);
namedWindow("Equilized Image");
imshow("Equilized Image",new_image);
histDisplay(rgb_planes[0], "Equilized Histogram");
waitKey();*/
QApplication app(argc, argv);
QWidget wgt;
QWidget wgt1;
QHBoxLayout* phbx = new QHBoxLayout;
QLabel* plbl = new QLabel;
QLabel* plbl2 = new QLabel;
QSlider* slide = new QSlider;
slide->setMinimum(-100);
slide->setMaximum(100);
slide->setValue(0);
QObject::connect(slide,SIGNAL(valueChanged(int)),wgt,SLOT(on_Slider_valueChanged(int arg1)));
phbx->setMargin(0);
phbx->setSpacing(0);
//QImage img = MatToQimage(image);
plbl->setPixmap(QPixmap::fromImage(img.scaled(img.width()/2, img.height()/2, Qt::KeepAspectRatio)));
phbx->addWidget(plbl);
wgt.setLayout(phbx);
plbl2->setPixmap(QPixmap::fromImage(brightness(image, 20).scaled(img.width()/2, img.height()/2, Qt::KeepAspectRatio)));
phbx->addWidget(plbl2);
wgt.setLayout(phbx);
phbx->addWidget(slide);
wgt.setLayout(phbx);
wgt.show();
return app.exec();
}
| [
"khe7376@gmail.com"
] | khe7376@gmail.com |
02418e71ffd369a9a83c4d7a3a14b1069d9e3e41 | 480a41478674cc968f5a836db7841e69bc82ab44 | /surfgradDemo/main.cpp | b26af8c0fa87c0a6ce64a4b200a5a1d80aefdff5 | [
"MIT"
] | permissive | ElonGame/surfgrad-bump-standalone-demo | f5884a8832a4d7e8f94419e59bc6a1d27252ad50 | 82f5f9979cf1f295ee73747db0bcdd906c99c752 | refs/heads/master | 2022-12-31T08:51:19.834182 | 2020-10-14T15:35:20 | 2020-10-14T15:35:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 53,298 | cpp | // This sample was made by Morten S. Mikkelsen
// It illustrates how to do compositing of bump maps in complex scenarios using the surface gradient based framework.
#define SHOW_DEMO_SCENE
#include "DXUT.h"
#include "DXUTcamera.h"
#include "DXUTgui.h"
//#include "DXUTsettingsDlg.h"
#include "SDKmisc.h"
//#include "SDKMesh.h"
#include <d3d11_2.h>
#include "strsafe.h"
#include <stdlib.h>
#include <math.h>
#include "scenegraph.h"
#ifdef SHOW_DEMO_SCENE
#include "shadows.h"
#include "canvas.h"
#endif
#include "debug_volume_base.h"
#define RECOMPILE_SCRBOUND_CS_SHADER
#define DISABLE_QUAT
#include <geommath/geommath.h>
#include "shader.h"
#include "shaderpipeline.h"
#include "std_cbuffer.h"
#include "shaderutils.h"
#include "texture_rt.h"
#include "buffer.h"
#include <wchar.h>
CDXUTDialogResourceManager g_DialogResourceManager;
CDXUTTextHelper * g_pTxtHelper = NULL;
CFirstPersonCamera g_Camera;
CShader scrbound_shader;
CShader volumelist_coarse_shader;
CShader volumelist_exact_shader;
static CShader debug_vol_vert_shader, debug_vol_pix_shader;
static CShaderPipeline debug_volume_shader_pipeline;
#ifndef SHOW_DEMO_SCENE
static CShader vert_shader, pix_shader;
static CShader vert_shader_basic;
static ID3D11InputLayout * g_pVertexLayout = NULL;
static ID3D11InputLayout * g_pVertexSimpleLayout = NULL;
CShaderPipeline shader_dpthfill_pipeline;
CShaderPipeline shader_pipeline;
ID3D11Buffer * g_pMeshInstanceCB = NULL;
#define MODEL_NAME "ground2_reduced.fil"
#define MODEL_PATH ".\\"
#define MODEL_PATH_W WIDEN(MODEL_PATH)
#include "mesh_fil.h"
#endif
ID3D11Buffer * g_pGlobalsCB = NULL;
CBufferObject g_VolumeDataBuffer;
CBufferObject g_ScrSpaceAABounds;
ID3D11Buffer * g_pVolumeClipInfo = NULL;
CBufferObject g_volumeListBuffer;
CBufferObject g_OrientedBounds;
#define WIDEN2(x) L ## x
#define WIDEN(x) WIDEN2(x)
#ifndef SHOW_DEMO_SCENE
#define MAX_LEN 64
#define NR_TEXTURES 1
const WCHAR tex_names[NR_TEXTURES][MAX_LEN] = {L"normals.png"};
const char stex_names[NR_TEXTURES][MAX_LEN] = {"g_norm_tex"};
static ID3D11ShaderResourceView * g_pTexturesHandler[NR_TEXTURES];
#else
#include "meshimport/meshdraw.h"
#endif
#ifndef M_PI
#define M_PI 3.1415926535897932384626433832795
#endif
bool CALLBACK ModifyDeviceSettings( DXUTDeviceSettings* pDeviceSettings, void* pUserContext );
void CALLBACK OnFrameMove( double fTime, float fElapsedTime, void* pUserContext );
bool CALLBACK IsD3D11DeviceAcceptable( const CD3D11EnumAdapterInfo *AdapterInfo, UINT Output, const CD3D11EnumDeviceInfo *DeviceInfo, DXGI_FORMAT BackBufferFormat, bool bWindowed, void* pUserContext );
HRESULT CALLBACK OnD3D11CreateDevice( ID3D11Device* pd3dDevice, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext );
void CALLBACK OnD3D11DestroyDevice( void* pUserContext );
void CALLBACK OnKeyboard( UINT nChar, bool bKeyDown, bool bAltDown, void* pUserContext );
HRESULT CALLBACK OnD3D11ResizedSwapChain( ID3D11Device* pd3dDevice, IDXGISwapChain* pSwapChain, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext );
void CALLBACK OnD3D11ReleasingSwapChain( void* pUserContext );
LRESULT CALLBACK MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, bool* pbNoFurtherProcessing, void* pUserContext );
void myFrustum(float * pMat, const float fLeft, const float fRight, const float fBottom, const float fTop, const float fNear, const float fFar);
#ifndef SHOW_DEMO_SCENE
CMeshFil g_cMesh;
#endif
static int g_iCullMethod = 1;
#ifdef SHOW_DEMO_SCENE
static int g_iVisualMode = 1;
#else
static int g_iVisualMode = 0;
#endif
static int g_iMenuVisib = 1;
static int g_iDecalBlendingMethod = 0; // additive, masked, decal dir
static bool g_bUseSecondaryUVsetOnPirate = true;
static int g_iBumpFromHeightMapMethod = 0;
static bool g_bEnableDecalMipMapping = true;
static bool g_bEnableDecals = true;
static bool g_bShowNormalsWS = false;
static bool g_bIndirectSpecular = true;
static bool g_bShowDebugVolumes = false;
static bool g_bEnableShadows = true;
#include "volume_definitions.h"
#include "VolumeTiling.h"
int g_iSqrtNrVolumes = 0;
int g_iNrVolumes = MAX_NR_VOLUMES_PER_CAMERA;
SFiniteVolumeData g_sLgtData[MAX_NR_VOLUMES_PER_CAMERA];
SFiniteVolumeBound g_sLgtColiData[MAX_NR_VOLUMES_PER_CAMERA];
CVolumeTiler g_cVolumeTiler;
static float frnd() { return (float) (((double) (rand() % (RAND_MAX+1))) / RAND_MAX); }
CTextureObject g_tex_depth;
#ifdef SHOW_DEMO_SCENE
CShadowMap g_shadowMap;
CCanvas g_canvas;
#endif
void InitApp()
{
g_Camera.SetRotateButtons( true, false, false );
g_Camera.SetEnablePositionMovement( true );
#ifdef SHOW_DEMO_SCENE
const float scale = 0.04f;
#else
const float scale = 1.0f; // 0.1f
#endif
g_Camera.SetScalers( 0.2f*0.005f, 3*100.0f * scale );
DirectX::XMVECTOR vEyePt, vEyeTo;
Vec3 cam_pos = 75.68f*Normalize(Vec3(16,0,40)); // normal
vEyePt = DirectX::XMVectorSet(cam_pos.x, cam_pos.y, -cam_pos.z, 1.0f);
//vEyeTo = DirectX::XMVectorSet(0.0f, 2.0f, 0.0f, 1.0f);
vEyeTo = DirectX::XMVectorSet(10.0f, 2.0f, 0.0f, 1.0f);
// surfgrad demo
#ifdef SHOW_DEMO_SCENE
const float g_O = 2*2.59f;
const float g_S = -1.0f; // convert unity scene to right hand frame.
vEyeTo = DirectX::XMVectorSet(g_S*3.39f+g_O, 1.28f+0.3, -0.003f+1.5, 1.0f);
vEyePt = DirectX::XMVectorSet(g_S*3.39f+g_O-10, 1.28f+2.5, -0.003f, 1.0f);
#endif
g_Camera.SetViewParams( vEyePt, vEyeTo );
g_iSqrtNrVolumes = (int) sqrt((double) g_iNrVolumes);
assert((g_iSqrtNrVolumes*g_iSqrtNrVolumes)<=g_iNrVolumes);
g_iNrVolumes = g_iSqrtNrVolumes*g_iSqrtNrVolumes;
}
void RenderText()
{
g_pTxtHelper->Begin();
g_pTxtHelper->SetInsertionPos( 2, 0 );
g_pTxtHelper->SetForegroundColor(DirectX::XMFLOAT4(1.0f, 1.0f, 0.0f, 1.0f));
g_pTxtHelper->DrawTextLine( DXUTGetFrameStats(true) );
if(g_iMenuVisib!=0)
{
#ifndef SHOW_DEMO_SCENE
g_pTxtHelper->DrawTextLine(L"This scene is forward lit by 1024 lights of different shapes. High performance is achieved using FPTL.\n");
#else
g_pTxtHelper->DrawTextLine(L"This scene illustrates advanced bump map compositing using the surface gradient based framework.\n");
#endif
g_pTxtHelper->DrawTextLine(L"Rotate the camera by using the mouse while pressing and holding the left mouse button.\n");
g_pTxtHelper->DrawTextLine(L"Move the camera by using the arrow keys or: w, a, s, d\n");
g_pTxtHelper->DrawTextLine(L"Hide menu using the x key.\n");
#ifdef SHOW_DEMO_SCENE
// U
if(g_bUseSecondaryUVsetOnPirate)
g_pTxtHelper->DrawTextLine(L"Secondary UV set on the pirate On (toggle using u)\n");
else g_pTxtHelper->DrawTextLine(L"Secondary UV set on the pirate Off (toggle using u)\n");
// H
if(g_iBumpFromHeightMapMethod==2)
g_pTxtHelper->DrawTextLine(L"Bump from Height - 1 tap (toggle using h)\n");
else if(g_iBumpFromHeightMapMethod==1)
g_pTxtHelper->DrawTextLine(L"Bump from Height - 3 taps (toggle using h)\n");
else
g_pTxtHelper->DrawTextLine(L"Bump from Height - HQ upscale (toggle using h)\n");
// B
if(g_iDecalBlendingMethod==2)
g_pTxtHelper->DrawTextLine(L"Decals blending - todays approach uses decal direction (toggle using b)\n");
else if(g_iDecalBlendingMethod==1)
g_pTxtHelper->DrawTextLine(L"Decals blending - surfgrad masked (toggle using b)\n");
else
g_pTxtHelper->DrawTextLine(L"Decal blending - surfgrad additive (toggle using b)\n");
// M
if(g_bEnableDecalMipMapping)
g_pTxtHelper->DrawTextLine(L"Decals mip mapping enabled (toggle using m)\n");
else g_pTxtHelper->DrawTextLine(L"Decals mip mapping disabled (toggle using m)\n");
// P
if(g_bEnableDecals)
g_pTxtHelper->DrawTextLine(L"Projected Decals enabled (toggle using p)\n");
else g_pTxtHelper->DrawTextLine(L"Projected Decals disabled (toggle using p)\n");
// N
if(g_bShowNormalsWS)
g_pTxtHelper->DrawTextLine(L"Show Normals in world space enabled (toggle using n)\n");
else g_pTxtHelper->DrawTextLine(L"Show Normals in world space disabled (toggle using n)\n");
// R
if(g_bIndirectSpecular)
g_pTxtHelper->DrawTextLine(L"Indirect Specular Reflection enabled (toggle using r)\n");
else g_pTxtHelper->DrawTextLine(L"Indirect Specular Reflection disabled (toggle using r)\n");
// V
if(g_bShowDebugVolumes)
g_pTxtHelper->DrawTextLine(L"Show decal volumes in wireframe enabled (toggle using v)\n");
else g_pTxtHelper->DrawTextLine(L"Show decal volumes in wireframe disabled (toggle using v)\n");
// I
if(g_bEnableShadows)
g_pTxtHelper->DrawTextLine(L"Shadows enabled (toggle using i)\n");
else g_pTxtHelper->DrawTextLine(L"Shadows disabled (toggle using i)\n");
#endif
#ifdef SHOW_DEMO_SCENE
#else
if (g_iCullMethod == 0)
g_pTxtHelper->DrawTextLine(L"Fine pruning disabled (toggle using m)\n");
else
g_pTxtHelper->DrawTextLine(L"Fine pruning enabled (toggle using m)\n");
#endif
// O
if (g_iVisualMode == 0)
g_pTxtHelper->DrawTextLine(L"Show Decal Overlaps enabled (toggle using o)\n");
else
g_pTxtHelper->DrawTextLine(L"Show Decal Overlaps disabled (toggle using o)\n");
}
g_pTxtHelper->End();
}
float Lerp(const float fA, const float fB, const float fT) { return fA*(1-fT) + fB*fT; }
// full fov from left to right
void InitVolumeEntry(SFiniteVolumeData &lgtData, SFiniteVolumeBound &lgtColiData, const Mat44 &mat, const Vec3 vSize, const float range, const float fov, unsigned int uFlag)
{
Mat33 rot;
for(int c=0; c<3; c++)
{
const Vec4 col = GetColumn(mat, c);
SetColumn(&rot, c, Vec3(col.x, col.y, col.z));
}
const Vec4 lastCol = GetColumn(mat, 3);
const Vec3 vCen = Vec3(lastCol.x, lastCol.y, lastCol.z);
float fFar = range;
float fNear = 0.80*range;
lgtData.vLpos = vCen;
lgtData.fInvRange = -1/(fFar-fNear);
lgtData.fNearRadiusOverRange_LP0 = fFar/(fFar-fNear);
lgtData.fSphRadiusSq = fFar*fFar;
float fFov = fov; // full fov from left to right
float fSeg = Lerp(2*range, 3*range, frnd());
lgtData.fSegLength = (uFlag==WEDGE_VOLUME || uFlag==CAPSULE_VOLUME) ? fSeg : 0.0f;
lgtData.uVolumeType = uFlag;
Vec3 vX = GetColumn(rot, 0);
Vec3 vY = GetColumn(rot, 1);
Vec3 vZ = GetColumn(rot, 2);
// default coli settings
lgtColiData.vBoxAxisX = vX;
lgtColiData.vBoxAxisY = vY;
lgtColiData.vBoxAxisZ = vZ;
lgtColiData.vScaleXZ = Vec2(1.0f, 1.0f);
lgtData.vAxisX = vX;
lgtData.vAxisY = vY;
lgtData.vAxisZ = vZ;
// build colision info for each volume type
if(uFlag==CAPSULE_VOLUME)
{
lgtColiData.fRadius = range + 0.5*fSeg;
lgtColiData.vCen = vCen + (0.5*fSeg)*lgtColiData.vBoxAxisX;
lgtColiData.vBoxAxisX *= (range+0.5*fSeg); lgtColiData.vBoxAxisY *= range; lgtColiData.vBoxAxisZ *= range;
lgtData.vCol = Vec3(1.0, 0.1, 1.0);
}
else if(uFlag==SPHERE_VOLUME)
{
lgtColiData.vBoxAxisX *= range; lgtColiData.vBoxAxisY *= range; lgtColiData.vBoxAxisZ *= range;
lgtColiData.fRadius = range;
lgtColiData.vCen = vCen;
lgtData.vCol = Vec3(1,1,1);
}
else if(uFlag==SPOT_CIRCULAR_VOLUME || uFlag==WEDGE_VOLUME)
{
if(uFlag==SPOT_CIRCULAR_VOLUME)
lgtData.vCol = Vec3(0*0.7,0.6,1);
else
lgtData.vCol = Vec3(1,0.6,0*0.7);
float fQ = uFlag==WEDGE_VOLUME ? 0.1 : 1;
//Vec3 vDir = Normalize( Vec3(fQ*0.5*(2*frnd()-1), -1, fQ*0.5*(2*frnd()-1)) );
lgtData.fPenumbra = cosf(fFov*0.5);
lgtData.fInvUmbraDelta = 1/( lgtData.fPenumbra - cosf(0.02*(fFov*0.5)) );
Vec3 vDir = -vY;
//Vec3 vY = lgtColiData.vBoxAxisY;
//Vec3 vTmpAxis = (fabsf(vY.x)<=fabsf(vY.y) && fabsf(vY.x)<=fabsf(vY.z)) ? Vec3(1,0,0) : ( fabsf(vY.y)<=fabsf(vY.z) ? Vec3(0,1,0) : Vec3(0,0,1) );
//Vec3 vX = Normalize( Cross(vY,vTmpAxis ) );
//lgtColiData.vBoxAxisZ = Cross(vX, vY);
//lgtColiData.vBoxAxisX = vX;
// this is silly but nevertheless where this is passed in engine (note the coliData is setup with vBoxAxisY==-vDir).
// apply nonuniform scale to OBB of spot volume
bool bSqueeze = true;//uFlag==SPOT_CIRCULAR_VOLUME && fFov<0.7*(M_PI*0.5f);
float fS = bSqueeze ? tan(0.5*fFov) : sin(0.5*fFov);
lgtColiData.vCen += (vCen + ((0.5f*range)*vDir) + ((0.5f*lgtData.fSegLength)*vX));
lgtColiData.vBoxAxisX *= (fS*range + 0.5*lgtData.fSegLength);
lgtColiData.vBoxAxisY *= (0.5f*range);
lgtColiData.vBoxAxisZ *= (fS*range);
float fAltDx = sin(0.5*fFov);
float fAltDy = cos(0.5*fFov);
fAltDy = fAltDy-0.5;
if(fAltDy<0) fAltDy=-fAltDy;
fAltDx *= range; fAltDy *= range;
fAltDx += (0.5f*lgtData.fSegLength);
float fAltDist = sqrt(fAltDy*fAltDy+fAltDx*fAltDx);
lgtColiData.fRadius = fAltDist>(0.5*range) ? fAltDist : (0.5*range);
if(bSqueeze)
lgtColiData.vScaleXZ = Vec2(0.01f, 0.01f);
}
else if(uFlag==BOX_VOLUME)
{
//Mat33 rot; LoadRotation(&rot, 2*M_PI*frnd(), 2*M_PI*frnd(), 2*M_PI*frnd());
float fSx = vSize.x;//5*2*(10*frnd()+4);
float fSy = vSize.y;//5*2*(10*frnd()+4);
float fSz = vSize.z;//5*2*(10*frnd()+4);
//float fSx2 = 0.1f*fSx;
//float fSy2 = 0.1f*fSy;
//float fSz2 = 0.1f*fSz;
float fSx2 = 0.85f*fSx;
float fSy2 = 0.85f*fSy;
float fSz2 = 0.85f*fSz;
lgtColiData.vBoxAxisX = fSx*lgtData.vAxisX;
lgtColiData.vBoxAxisY = fSy*lgtData.vAxisY;
lgtColiData.vBoxAxisZ = fSz*lgtData.vAxisZ;
lgtColiData.vCen = vCen;
lgtColiData.fRadius = sqrtf(fSx*fSx+fSy*fSy+fSz*fSz);
lgtData.vCol = Vec3(0.1,1,0.16);
lgtData.fSphRadiusSq = lgtColiData.fRadius*lgtColiData.fRadius;
lgtData.vBoxInnerDist = Vec3(fSx2, fSy2, fSz2);
lgtData.vBoxInvRange = Vec3( 1/(fSx-fSx2), 1/(fSy-fSy2), 1/(fSz-fSz2) );
}
}
#ifdef SHOW_DEMO_SCENE
void BuildVolumesBuffer()
{
static bool bBufferMade = false;
const float g_O = 2*2.59f;
const float g_S = -1.0f; // convert unity scene to right hand frame.
if(!bBufferMade)
{
bBufferMade = true;
int iNrLgts = 0;
const float deg2rad = M_PI/180.0f;
// full fov from left to right
float totfov = 70.0f*deg2rad;
// insert spot decal
{
SFiniteVolumeData &lgtData = g_sLgtData[iNrLgts];
SFiniteVolumeBound &lgtColiData = g_sLgtColiData[iNrLgts];
float totfov = 60.0f*deg2rad;
const float range = 8.0f;
Mat44 mat; LoadIdentity(&mat);
LoadRotation(&mat, 55.0f*deg2rad, (180+105.0f)*deg2rad, 0.0f*deg2rad);
SetColumn(&mat, 3, Vec3(g_S*3.39f+g_O-4, 1.28f+2.0f, -0.003f-2*0-1));
InitVolumeEntry(g_sLgtData[iNrLgts], lgtColiData, mat, Vec3(0.0f, 0.0f, 0.0f), range, totfov, SPOT_CIRCULAR_VOLUME);
//InitVolumeEntry(g_sLgtData[iNrLgts], lgtColiData, mat, Vec3(0.0f, 0.0f, 0.0f), range, totfov, WEDGE_VOLUME);
++iNrLgts;
}
// insert sphere decal
{
SFiniteVolumeData &lgtData = g_sLgtData[iNrLgts];
SFiniteVolumeBound &lgtColiData = g_sLgtColiData[iNrLgts];
const float range = 1.6f;
Mat44 mat; LoadIdentity(&mat);
//LoadRotation(&mat, -30.0f*deg2rad, (180+105.0f)*deg2rad, 0.0f*deg2rad);
#if 1
SetColumn(&mat, 3, Vec3(g_S*3.39f+g_O-2-0.7, 1.28f+0.5+0.2, -0.003f-2*0-0.3));
InitVolumeEntry(g_sLgtData[iNrLgts], lgtColiData, mat, Vec3(0.0f, 0.0f, 0.0f), range, totfov, SPHERE_VOLUME);
#else
SetColumn(&mat, 3, Vec3(g_S*3.39f+g_O-2-0.7-7, 1.28f+0.5+0.2, -0.003f-2*0-0.3));
InitVolumeEntry(g_sLgtData[iNrLgts], lgtColiData, mat, Vec3(0.0f, 0.0f, 0.0f), 0.3*range, totfov, CAPSULE_VOLUME);
#endif
++iNrLgts;
}
// insert box decal
{
SFiniteVolumeData &lgtData = g_sLgtData[iNrLgts];
SFiniteVolumeBound &lgtColiData = g_sLgtColiData[iNrLgts];
const Vec3 vSize = Vec3(0.5*1.2f,0.5*1.2f,1.7);
const float range = Length(vSize);
Mat44 mat; LoadIdentity(&mat);
LoadRotation(&mat, -30.0f*deg2rad, (180+105.0f)*deg2rad, 0.0f*deg2rad);
SetColumn(&mat, 3, Vec3(g_S*3.39f+g_O-1, 1.28f, -0.003f-2-1));
//const Vec4 nose = -GetColumn(mat, 2);
InitVolumeEntry(g_sLgtData[iNrLgts], lgtColiData, mat, vSize, range, totfov, BOX_VOLUME);
++iNrLgts;
}
g_cVolumeTiler.InitTiler();
g_iNrVolumes = iNrLgts;
}
}
#else
void BuildVolumesBuffer()
{
static bool bBufferMade = false;
if(!bBufferMade)
{
bBufferMade = true;
// build volume lists
int iNrLgts = 0;
int iRealCounter = 0;
while(iNrLgts<g_iNrVolumes)
{
// 5 volume types define in
unsigned int uFlag = rand()%MAX_TYPES;
const int iX = iNrLgts % g_iSqrtNrVolumes;
const int iZ = iNrLgts / g_iSqrtNrVolumes;
const float fX = 4000*(2*((iX+0.5f)/g_iSqrtNrVolumes)-1);
const float fZ = 4000*(2*((iZ+0.5f)/g_iSqrtNrVolumes)-1);
const float fY = g_cMesh.QueryTopY(fX, fZ)+12*5 + (uFlag==WEDGE_VOLUME || uFlag==CAPSULE_VOLUME ? 2*50 : 0);
const Vec3 vCen = Vec3(fX, fY, fZ);
const float fT = frnd();
const float fRad = (uFlag==SPOT_CIRCULAR_VOLUME ? 3.0 : 2.0)*(100*fT + 80*(1-fT)+1);
{
SFiniteVolumeData &lgtData = g_sLgtData[iNrLgts];
SFiniteVolumeBound &lgtColiData = g_sLgtColiData[iNrLgts];
float fFar = fRad;
float fNear = 0.80*fRad;
lgtData.vLpos = vCen;
lgtData.fInvRange = -1/(fFar-fNear);
lgtData.fNearRadiusOverRange_LP0 = fFar/(fFar-fNear);
lgtData.fSphRadiusSq = fFar*fFar;
float fFov = 1.0*frnd()+0.2; // full fov from left to right
float fSeg = Lerp(fRad, 0.5*fRad, frnd());
lgtData.fSegLength = (uFlag==WEDGE_VOLUME || uFlag==CAPSULE_VOLUME) ? fSeg : 0.0f;
lgtData.uVolumeType = uFlag;
lgtData.vAxisX = Vec3(1,0,0);
lgtData.vAxisY = Vec3(0,1,0);
lgtData.vAxisZ = Vec3(0,0,1);
// default coli settings
lgtColiData.vBoxAxisX = Vec3(1,0,0);
lgtColiData.vBoxAxisY = Vec3(0,1,0);
lgtColiData.vBoxAxisZ = Vec3(0,0,1);
lgtColiData.vScaleXZ = Vec2(1.0f, 1.0f);
// build colision info for each volume type
if(uFlag==CAPSULE_VOLUME)
{
//lgtData.vLdir = lgtColiData.vBoxAxisX;
lgtColiData.fRadius = fRad + 0.5*fSeg;
lgtColiData.vCen = vCen + (0.5*fSeg)*lgtColiData.vBoxAxisX;
lgtColiData.vBoxAxisX *= (fRad+0.5*fSeg); lgtColiData.vBoxAxisY *= fRad; lgtColiData.vBoxAxisZ *= fRad;
lgtData.vCol = Vec3(1.0, 0.1, 1.0);
}
else if(uFlag==SPHERE_VOLUME)
{
lgtColiData.vBoxAxisX *= fRad; lgtColiData.vBoxAxisY *= fRad; lgtColiData.vBoxAxisZ *= fRad;
lgtColiData.fRadius = fRad;
lgtColiData.vCen = vCen;
lgtData.vCol = Vec3(1,1,1);
}
else if(uFlag==SPOT_CIRCULAR_VOLUME || uFlag==WEDGE_VOLUME)
{
if(uFlag==SPOT_CIRCULAR_VOLUME)
lgtData.vCol = Vec3(0*0.7,0.6,1);
else
lgtData.vCol = Vec3(1,0.6,0*0.7);
fFov *= 2;
float fQ = uFlag==WEDGE_VOLUME ? 0.1 : 1;
Vec3 vDir = Normalize( Vec3(fQ*0.5*(2*frnd()-1), -1, fQ*0.5*(2*frnd()-1)) );
//lgtData.vBoxAxisX = vDir; // Spot Dir
lgtData.fPenumbra = cosf(fFov*0.5);
lgtData.fInvUmbraDelta = 1/( lgtData.fPenumbra - cosf(0.02*(fFov*0.5)) );
lgtColiData.vBoxAxisY = -vDir;
Vec3 vY = lgtColiData.vBoxAxisY;
Vec3 vTmpAxis = (fabsf(vY.x)<=fabsf(vY.y) && fabsf(vY.x)<=fabsf(vY.z)) ? Vec3(1,0,0) : ( fabsf(vY.y)<=fabsf(vY.z) ? Vec3(0,1,0) : Vec3(0,0,1) );
Vec3 vX = Normalize( Cross(vY,vTmpAxis ) );
lgtColiData.vBoxAxisZ = Cross(vX, vY);
lgtColiData.vBoxAxisX = vX;
// this is silly but nevertheless where this is passed in engine (note the coliData is setup with vBoxAxisY==-vDir).
lgtData.vAxisX = vX;
lgtData.vAxisY = vY;
lgtData.vAxisZ = Cross(vX, vY);
// apply nonuniform scale to OBB of spot volume
bool bSqueeze = true;//uFlag==SPOT_CIRCULAR_VOLUME && fFov<0.7*(M_PI*0.5f);
float fS = bSqueeze ? tan(0.5*fFov) : sin(0.5*fFov);
lgtColiData.vCen += (vCen + ((0.5f*fRad)*vDir) + ((0.5f*lgtData.fSegLength)*vX));
lgtColiData.vBoxAxisX *= (fS*fRad + 0.5*lgtData.fSegLength);
lgtColiData.vBoxAxisY *= (0.5f*fRad);
lgtColiData.vBoxAxisZ *= (fS*fRad);
float fAltDx = sin(0.5*fFov);
float fAltDy = cos(0.5*fFov);
fAltDy = fAltDy-0.5;
if(fAltDy<0) fAltDy=-fAltDy;
fAltDx *= fRad; fAltDy *= fRad;
fAltDx += (0.5f*lgtData.fSegLength);
float fAltDist = sqrt(fAltDy*fAltDy+fAltDx*fAltDx);
lgtColiData.fRadius = fAltDist>(0.5*fRad) ? fAltDist : (0.5*fRad);
if(bSqueeze)
lgtColiData.vScaleXZ = Vec2(0.01f, 0.01f);
}
else if(uFlag==BOX_VOLUME)
{
Mat33 rot; LoadRotation(&rot, 2*M_PI*frnd(), 2*M_PI*frnd(), 2*M_PI*frnd());
float fSx = 5*2*(10*frnd()+4);
float fSy = 5*2*(10*frnd()+4);
float fSz = 5*2*(10*frnd()+4);
float fSx2 = 0.1f*fSx;
float fSy2 = 0.1f*fSy;
float fSz2 = 0.1f*fSz;
lgtData.vAxisX = GetColumn(rot, 0);
lgtData.vAxisY = GetColumn(rot, 1);
lgtData.vAxisZ = GetColumn(rot, 2);
lgtColiData.vBoxAxisX = fSx*lgtData.vAxisX;
lgtColiData.vBoxAxisY = fSy*lgtData.vAxisY;
lgtColiData.vBoxAxisZ = fSz*lgtData.vAxisZ;
lgtColiData.vCen = vCen;
lgtColiData.fRadius = sqrtf(fSx*fSx+fSy*fSy+fSz*fSz);
lgtData.vCol = Vec3(0.1,1,0.16);
lgtData.fSphRadiusSq = lgtColiData.fRadius*lgtColiData.fRadius;
lgtData.vBoxInnerDist = Vec3(fSx2, fSy2, fSz2);
lgtData.vBoxInvRange = Vec3( 1/(fSx-fSx2), 1/(fSy-fSy2), 1/(fSz-fSz2) );
}
++iNrLgts;
}
}
g_cVolumeTiler.InitTiler();
}
}
#endif
void RenderDebugVolumes(ID3D11DeviceContext* pd3dImmediateContext)
{
if(g_iNrVolumes>0)
{
CShaderPipeline &pipe = debug_volume_shader_pipeline;
pipe.PrepPipelineForRendering(pd3dImmediateContext);
// set streams and layout
pd3dImmediateContext->IASetVertexBuffers( 0, 0, NULL, NULL, NULL );
pd3dImmediateContext->IASetIndexBuffer( NULL, DXGI_FORMAT_UNKNOWN, 0 );
pd3dImmediateContext->IASetInputLayout( NULL );
// Set primitive topology
pd3dImmediateContext->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_LINELIST );
pd3dImmediateContext->DrawInstanced( 2*MAX_NR_SEGMENTS_ON_ANY_VOLUME, g_iNrVolumes, 0, 0);
//pd3dImmediateContext->Draw( 2*12, 0);
pipe.FlushResources(pd3dImmediateContext);
}
}
void render_surface(ID3D11DeviceContext* pd3dImmediateContext, bool bSimpleLayout)
{
#ifdef SHOW_DEMO_SCENE
RenderSceneGraph(pd3dImmediateContext, bSimpleLayout, g_bEnableDecals, g_bEnableDecalMipMapping, false);
#else
CShaderPipeline &shader_pipe = bSimpleLayout ? shader_dpthfill_pipeline : shader_pipeline;
shader_pipe.PrepPipelineForRendering(pd3dImmediateContext);
// set streams and layout
UINT stride = sizeof(SFilVert), offset = 0;
pd3dImmediateContext->IASetVertexBuffers( 0, 1, g_cMesh.GetVertexBuffer(), &stride, &offset );
pd3dImmediateContext->IASetIndexBuffer( g_cMesh.GetIndexBuffer(), DXGI_FORMAT_R32_UINT, 0 );
pd3dImmediateContext->IASetInputLayout( bSimpleLayout ? g_pVertexSimpleLayout : g_pVertexLayout );
// Set primitive topology
pd3dImmediateContext->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST );
pd3dImmediateContext->DrawIndexed( 3*g_cMesh.GetNrTriangles(), 0, 0 );
shader_pipe.FlushResources(pd3dImmediateContext);
#endif
if(!bSimpleLayout && g_bShowDebugVolumes) RenderDebugVolumes(pd3dImmediateContext);
}
Mat44 g_m44Proj, g_m44InvProj, g_mViewToScr, g_mScrToView;
Vec3 XMVToVec3(const DirectX::XMVECTOR vec)
{
return Vec3(DirectX::XMVectorGetX(vec), DirectX::XMVectorGetY(vec), DirectX::XMVectorGetZ(vec));
}
Vec4 XMVToVec4(const DirectX::XMVECTOR vec)
{
return Vec4(DirectX::XMVectorGetX(vec), DirectX::XMVectorGetY(vec), DirectX::XMVectorGetZ(vec), DirectX::XMVectorGetW(vec));
}
Mat44 ToMat44(const DirectX::XMMATRIX &dxmat)
{
Mat44 res;
for (int c = 0; c < 4; c++)
SetColumn(&res, c, XMVToVec4(dxmat.r[c]));
return res;
}
void CALLBACK OnD3D11FrameRender( ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3dImmediateContext,
double fTime, float fElapsedTime, void* pUserContext )
{
HRESULT hr;
//const float fTimeDiff = DXUTGetElapsedTime();
// clear screen
ID3D11RenderTargetView* pRTV = DXUTGetD3D11RenderTargetView();
ID3D11DepthStencilView* pDSV = g_tex_depth.GetDSV();//DXUTGetD3D11DepthStencilView();
//DXUTGetD3D11DepthStencil();
Vec3 vToPoint = XMVToVec3(g_Camera.GetLookAtPt());
Vec3 cam_pos = XMVToVec3(g_Camera.GetEyePt());
Mat44 world_to_view = ToMat44(g_Camera.GetViewMatrix() ); // get world to view projection
Mat44 mZflip; LoadIdentity(&mZflip);
SetColumn(&mZflip, 2, Vec4(0,0,-1,0));
#ifndef LEFT_HAND_COORDINATES
world_to_view = mZflip * world_to_view * mZflip;
#else
world_to_view = world_to_view * mZflip;
#endif
Mat44 m44LocalToWorld; LoadIdentity(&m44LocalToWorld);
Mat44 m44LocalToView = world_to_view * m44LocalToWorld;
Mat44 Trans = g_m44Proj * world_to_view;
// fill constant buffers
D3D11_MAPPED_SUBRESOURCE MappedSubResource;
#ifndef SHOW_DEMO_SCENE
V( pd3dImmediateContext->Map( g_pMeshInstanceCB, 0, D3D11_MAP_WRITE_DISCARD, 0, &MappedSubResource ) );
((cbMeshInstance *)MappedSubResource.pData)->g_mLocToWorld = Transpose(m44LocalToWorld);
((cbMeshInstance *)MappedSubResource.pData)->g_mWorldToLocal = Transpose(~m44LocalToWorld);
pd3dImmediateContext->Unmap( g_pMeshInstanceCB, 0 );
#endif
// prefill shadow map
#ifdef SHOW_DEMO_SCENE
if(g_bEnableShadows) g_shadowMap.RenderShadowMap(pd3dImmediateContext, g_pGlobalsCB, GetSunDir());
#endif
// fill constant buffers
const Mat44 view_to_world = ~world_to_view;
V( pd3dImmediateContext->Map( g_pGlobalsCB, 0, D3D11_MAP_WRITE_DISCARD, 0, &MappedSubResource ) );
((cbGlobals *)MappedSubResource.pData)->g_mWorldToView = Transpose(world_to_view);
((cbGlobals *)MappedSubResource.pData)->g_mViewToWorld = Transpose(view_to_world);
((cbGlobals *)MappedSubResource.pData)->g_mScrToView = Transpose(g_mScrToView);
((cbGlobals *)MappedSubResource.pData)->g_mProj = Transpose(g_m44Proj);
((cbGlobals *)MappedSubResource.pData)->g_mViewProjection = Transpose(Trans);
((cbGlobals *)MappedSubResource.pData)->g_vCamPos = view_to_world * Vec3(0,0,0);
((cbGlobals *)MappedSubResource.pData)->g_iWidth = DXUTGetDXGIBackBufferSurfaceDesc()->Width;
((cbGlobals *)MappedSubResource.pData)->g_iHeight = DXUTGetDXGIBackBufferSurfaceDesc()->Height;
((cbGlobals *)MappedSubResource.pData)->g_iMode = g_iVisualMode;
((cbGlobals *)MappedSubResource.pData)->g_iDecalBlendingMethod = g_iDecalBlendingMethod;
((cbGlobals *)MappedSubResource.pData)->g_bShowNormalsWS = g_bShowNormalsWS;
((cbGlobals *)MappedSubResource.pData)->g_bIndirectSpecular = g_bIndirectSpecular;
((cbGlobals *)MappedSubResource.pData)->g_vSunDir = GetSunDir();
((cbGlobals *)MappedSubResource.pData)->g_bEnableShadows = g_bEnableShadows;
((cbGlobals *)MappedSubResource.pData)->g_iBumpFromHeightMapMethod = g_iBumpFromHeightMapMethod;
((cbGlobals *)MappedSubResource.pData)->g_bUseSecondaryUVsetOnPirate = g_bUseSecondaryUVsetOnPirate;
pd3dImmediateContext->Unmap( g_pGlobalsCB, 0 );
V( pd3dImmediateContext->Map( g_pVolumeClipInfo, 0, D3D11_MAP_WRITE_DISCARD, 0, &MappedSubResource ) );
((cbBoundsInfo *) MappedSubResource.pData)->g_mProjection = Transpose(g_m44Proj);
((cbBoundsInfo *) MappedSubResource.pData)->g_mInvProjection = Transpose(g_m44InvProj);
((cbBoundsInfo *) MappedSubResource.pData)->g_mScrProjection = Transpose(g_mViewToScr);
((cbBoundsInfo *) MappedSubResource.pData)->g_mInvScrProjection = Transpose(g_mScrToView);
((cbBoundsInfo *) MappedSubResource.pData)->g_iNrVisibVolumes = g_iNrVolumes;
((cbBoundsInfo *) MappedSubResource.pData)->g_vStuff = Vec3(0,0,0);
pd3dImmediateContext->Unmap( g_pVolumeClipInfo, 0 );
// build volume list
g_cVolumeTiler.InitFrame(world_to_view, g_m44Proj);
for(int l=0; l<g_iNrVolumes; l++)
{
g_cVolumeTiler.AddVolume(g_sLgtData[l], g_sLgtColiData[l]);
}
g_cVolumeTiler.CompileVolumeList();
// transfer volume bounds
V( pd3dImmediateContext->Map( g_OrientedBounds.GetStagedBuffer(), 0, D3D11_MAP_WRITE, 0, &MappedSubResource ) );
for(int l=0; l<g_iNrVolumes; l++)
{
((SFiniteVolumeBound *) MappedSubResource.pData)[l] = g_cVolumeTiler.GetOrderedBoundsList()[l];
}
pd3dImmediateContext->Unmap( g_OrientedBounds.GetStagedBuffer(), 0 );
V( pd3dImmediateContext->Map( g_VolumeDataBuffer.GetStagedBuffer(), 0, D3D11_MAP_WRITE, 0, &MappedSubResource ) );
for(int l=0; l<g_iNrVolumes; l++)
{
((SFiniteVolumeData *) MappedSubResource.pData)[l] = g_cVolumeTiler.GetVolumesDataList()[l];
if(g_iVisualMode==0) ((SFiniteVolumeData *) MappedSubResource.pData)[l].vCol = Vec3(1,1,1);
}
pd3dImmediateContext->Unmap( g_VolumeDataBuffer.GetStagedBuffer(), 0 );
pd3dImmediateContext->CopyResource(g_VolumeDataBuffer.GetBuffer(), g_VolumeDataBuffer.GetStagedBuffer());
// Convert OBBs of volumes into screen space AABBs (incl. depth)
const int nrGroups = (g_iNrVolumes*8 + 63)/64;
ID3D11UnorderedAccessView* g_ppNullUAV[] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
ID3D11Buffer * pDatas[] = {g_pVolumeClipInfo};
pd3dImmediateContext->CSSetConstantBuffers(0, 1, pDatas); //
pd3dImmediateContext->CopyResource(g_OrientedBounds.GetBuffer(), g_OrientedBounds.GetStagedBuffer());
ID3D11ShaderResourceView * pSRVbounds[] = {g_OrientedBounds.GetSRV()};
pd3dImmediateContext->CSSetShaderResources(0, 1, pSRVbounds);
ID3D11UnorderedAccessView * ppAABB_UAV[] = { g_ScrSpaceAABounds.GetUAV() };
pd3dImmediateContext->CSSetUnorderedAccessViews(0, 1, ppAABB_UAV, 0);
ID3D11ComputeShader * pShaderCS = (ID3D11ComputeShader *) scrbound_shader.GetDeviceChild();
pd3dImmediateContext->CSSetShader( pShaderCS, NULL, 0 );
pd3dImmediateContext->Dispatch(nrGroups, 1, 1);
pd3dImmediateContext->CSSetUnorderedAccessViews(0, 1, g_ppNullUAV, 0);
ID3D11ShaderResourceView * pNullSRV_bound[] = {NULL};
pd3dImmediateContext->CSSetShaderResources(0, 1, pNullSRV_bound);
// debugging code...
/*
pd3dImmediateContext->CopyResource(g_pScrSpaceAABounds_staged, g_pScrSpaceAABounds);
V( pd3dImmediateContext->Map( g_pScrSpaceAABounds_staged, 0, D3D11_MAP_READ, 0, &MappedSubResource ) );
const Vec3 * pData0 = ((Vec3 *) MappedSubResource.pData);
const Vec3 * pData1 = g_cVolumeTiler.GetScrBoundsList();
pd3dImmediateContext->Unmap( g_pScrSpaceAABounds_staged, 0 );*/
// prefill depth
const bool bRenderFront = true;
float ClearColor[4] = { 0.03f, 0.05f, 0.1f, 0.0f };
DXUTSetupD3D11Views(pd3dImmediateContext);
pd3dImmediateContext->OMSetRenderTargets( 0, NULL, pDSV );
pd3dImmediateContext->ClearDepthStencilView( pDSV, D3D11_CLEAR_DEPTH, 1.0f, 0 );
pd3dImmediateContext->RSSetState( GetDefaultRasterSolidCullBack() );
pd3dImmediateContext->OMSetDepthStencilState( GetDefaultDepthStencilState(), 0 );
render_surface(pd3dImmediateContext, true);
// resolve shadow map
#ifdef SHOW_DEMO_SCENE
if(g_bEnableShadows) g_shadowMap.ResolveToScreen(pd3dImmediateContext, g_tex_depth.GetReadOnlyDSV(), g_pGlobalsCB);
#endif
// restore depth state
pd3dImmediateContext->OMSetDepthStencilState( GetDefaultDepthStencilState_NoDepthWrite(), 0 );
// switch to back-buffer
pd3dImmediateContext->OMSetRenderTargets( 1, &pRTV, g_tex_depth.GetReadOnlyDSV() );
pd3dImmediateContext->ClearRenderTargetView( pRTV, ClearColor );
const int iNrTilesX = (DXUTGetDXGIBackBufferSurfaceDesc()->Width+15)/16;
const int iNrTilesY = (DXUTGetDXGIBackBufferSurfaceDesc()->Height+15)/16;
ID3D11ShaderResourceView * pNullSRV[] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
// build a volume list per 16x16 tile
ID3D11UnorderedAccessView * ppVolumeList_UAV[] = { g_volumeListBuffer.GetUAV() };
ID3D11ShaderResourceView * pSRV[] = {g_tex_depth.GetSRV(), g_ScrSpaceAABounds.GetSRV(), g_VolumeDataBuffer.GetSRV(), g_OrientedBounds.GetSRV()};
pShaderCS = (ID3D11ComputeShader *) (g_iCullMethod==0 ? volumelist_coarse_shader.GetDeviceChild() : volumelist_exact_shader.GetDeviceChild());
pd3dImmediateContext->CSSetUnorderedAccessViews(0, 1, ppVolumeList_UAV, 0);
pd3dImmediateContext->CSSetShaderResources(0, 4, pSRV);
pd3dImmediateContext->CSSetShader( pShaderCS, NULL, 0 );
pd3dImmediateContext->Dispatch(iNrTilesX, iNrTilesY, 1);
pd3dImmediateContext->CSSetUnorderedAccessViews(0, 1, g_ppNullUAV, 0);
pd3dImmediateContext->CSSetShaderResources(0, 4, pNullSRV);
// debugging code...
/*
pd3dImmediateContext->CopyResource(g_pVolumeListBuffer_staged, g_pVolumeListBuffer);
V( pd3dImmediateContext->Map( g_pVolumeListBuffer_staged, 0, D3D11_MAP_READ, 0, &MappedSubResource ) );
const unsigned int * pData2 = ((const unsigned int *) MappedSubResource.pData);
pd3dImmediateContext->Unmap( g_pVolumeListBuffer_staged, 0 );
*/
#ifdef SHOW_DEMO_SCENE
//
g_canvas.DrawCanvas(pd3dImmediateContext, g_pGlobalsCB);
// restore depth state
pd3dImmediateContext->OMSetDepthStencilState( GetDefaultDepthStencilState_NoDepthWrite(), 0 );
#endif
// Do tiled forward rendering
render_surface(pd3dImmediateContext, false);
// fire off menu text
RenderText();
}
int WINAPI wWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow )
{
// Enable run-time memory check for debug builds.
#if defined(DEBUG) | defined(_DEBUG)
_CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
#endif
// Set DXUT callbacks
DXUTSetCallbackDeviceChanging( ModifyDeviceSettings );
DXUTSetCallbackMsgProc( MsgProc );
DXUTSetCallbackFrameMove( OnFrameMove );
DXUTSetCallbackD3D11DeviceAcceptable( IsD3D11DeviceAcceptable );
DXUTSetCallbackD3D11DeviceCreated( OnD3D11CreateDevice );
DXUTSetCallbackD3D11SwapChainResized( OnD3D11ResizedSwapChain );
DXUTSetCallbackD3D11FrameRender( OnD3D11FrameRender );
DXUTSetCallbackD3D11SwapChainReleasing( OnD3D11ReleasingSwapChain );
DXUTSetCallbackD3D11DeviceDestroyed( OnD3D11DestroyDevice );
DXUTSetCallbackKeyboard( OnKeyboard );
InitApp();
DXUTInit( true, true );
DXUTSetCursorSettings( true, true ); // Show the cursor and clip it when in full screen
DXUTCreateWindow( L"Surface Gradient Based Bump Mapping Demo." );
int dimX = 1280, dimY = 960;
DXUTCreateDevice( D3D_FEATURE_LEVEL_11_0, true, dimX, dimY);
//DXUTCreateDevice( D3D_FEATURE_LEVEL_11_0, true, 1024, 768);
DXUTMainLoop(); // Enter into the DXUT render loop
return DXUTGetExitCode();
}
//--------------------------------------------------------------------------------------
// Create any D3D11 resources that depend on the back buffer
//--------------------------------------------------------------------------------------
HRESULT CALLBACK OnD3D11ResizedSwapChain( ID3D11Device* pd3dDevice, IDXGISwapChain* pSwapChain,
const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext )
{
HRESULT hr;
// Setup the camera's projection parameters
int w = pBackBufferSurfaceDesc->Width;
int h = pBackBufferSurfaceDesc->Height;
#ifdef SHOW_DEMO_SCENE
const float scale = 0.01f;
#else
const float scale = 1.0f; // 0.1f
#endif
//const float fFov = 30;
const float fNear = 10 * scale;
const float fFar = 10000 * scale;
//const float fNear = 45;//275;
//const float fFar = 65;//500;
//const float fHalfWidthAtMinusNear = fNear * tanf((fFov*((float) M_PI))/360);
//const float fHalfHeightAtMinusNear = fHalfWidthAtMinusNear * (((float) 3)/4.0);
const float fFov = 2*23;
const float fHalfHeightAtMinusNear = fNear * tanf((fFov*((float) M_PI))/360);
const float fHalfWidthAtMinusNear = fHalfHeightAtMinusNear * (((float) w)/h);
const float fS = 1.0;// 1280.0f / 960.0f;
myFrustum(g_m44Proj.m_fMat, -fS*fHalfWidthAtMinusNear, fS*fHalfWidthAtMinusNear, -fHalfHeightAtMinusNear, fHalfHeightAtMinusNear, fNear, fFar);
{
float fAspectRatio = fS;
g_Camera.SetProjParams( (fFov*M_PI)/360, fAspectRatio, fNear, fFar );
}
Mat44 mToScr;
SetRow(&mToScr, 0, Vec4(0.5*w, 0, 0, 0.5*w));
SetRow(&mToScr, 1, Vec4(0, -0.5*h, 0, 0.5*h));
SetRow(&mToScr, 2, Vec4(0, 0, 1, 0));
SetRow(&mToScr, 3, Vec4(0, 0, 0, 1));
g_mViewToScr = mToScr * g_m44Proj;
g_mScrToView = ~g_mViewToScr;
g_m44InvProj = ~g_m44Proj;
// Set GUI size and locations
/*g_HUD.SetLocation( pBackBufferSurfaceDesc->Width - 170, 0 );
g_HUD.SetSize( 170, 170 );
g_SampleUI.SetLocation( pBackBufferSurfaceDesc->Width - 245, pBackBufferSurfaceDesc->Height - 520 );
g_SampleUI.SetSize( 245, 520 );*/
// create render targets
const bool bEnableReadBySampling = true;
const bool bEnableWriteTo = true;
const bool bAllocateMipMaps = false;
const bool bAllowStandardMipMapGeneration = false;
const void * pInitData = NULL;
g_tex_depth.CleanUp();
g_tex_depth.CreateTexture(pd3dDevice,w,h, DXGI_FORMAT_R24G8_TYPELESS, bAllocateMipMaps, false, NULL,
bEnableReadBySampling, DXGI_FORMAT_R24_UNORM_X8_TYPELESS, bEnableWriteTo, DXGI_FORMAT_D24_UNORM_S8_UINT,
true);
////////////////////////////////////////////////
g_volumeListBuffer.CleanUp();
const int nrTiles = ((w+15)/16)*((h+15)/16);
g_volumeListBuffer.CreateBuffer(pd3dDevice, NR_USHORTS_PER_TILE*sizeof( unsigned short ) * nrTiles, 0, NULL, CBufferObject::DefaultBuf, true, true, CBufferObject::StagingCpuReadOnly);
g_volumeListBuffer.AddTypedSRV(pd3dDevice, DXGI_FORMAT_R16_UINT);
g_volumeListBuffer.AddTypedUAV(pd3dDevice, DXGI_FORMAT_R16_UINT);
#ifndef SHOW_DEMO_SCENE
shader_pipeline.RegisterResourceView("g_vVolumeList", g_volumeListBuffer.GetSRV());
#endif
#ifdef SHOW_DEMO_SCENE
g_shadowMap.OnResize(pd3dDevice, g_tex_depth.GetSRV());
PassVolumeIndicesPerTileBuffer(g_volumeListBuffer.GetSRV(), g_shadowMap.GetShadowResolveSRV());
#endif
////////////////////////////////////////////////
V_RETURN( g_DialogResourceManager.OnD3D11ResizedSwapChain( pd3dDevice, pBackBufferSurfaceDesc ) );
//V_RETURN( g_D3DSettingsDlg.OnD3D11ResizedSwapChain( pd3dDevice, pBackBufferSurfaceDesc ) );
return S_OK;
}
//--------------------------------------------------------------------------------------
// Release D3D11 resources created in OnD3D11ResizedSwapChain
//--------------------------------------------------------------------------------------
void CALLBACK OnD3D11ReleasingSwapChain( void* pUserContext )
{
g_DialogResourceManager.OnD3D11ReleasingSwapChain();
}
//--------------------------------------------------------------------------------------
// Handle key presses
//--------------------------------------------------------------------------------------
LRESULT CALLBACK MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, bool* pbNoFurtherProcessing,
void* pUserContext )
{
#if 0
switch( uMsg )
{
case WM_KEYDOWN: // Prevent the camera class to use some prefefined keys that we're already using
{
switch( (UINT)wParam )
{
case VK_CONTROL:
case VK_LEFT:
{
g_fL0ay -= 0.05f;
return 0;
}
break;
case VK_RIGHT:
{
g_fL0ay += 0.05f;
return 0;
}
case VK_UP:
{
g_fL0ax += 0.05f;
if(g_fL0ax>(M_PI/2.5)) g_fL0ax=(M_PI/2.5);
return 0;
}
break;
case VK_DOWN:
{
g_fL0ax -= 0.05f;
if(g_fL0ax<-(M_PI/2.5)) g_fL0ax=-(M_PI/2.5);
return 0;
}
break;
case 'F':
{
int iTing;
iTing = 0;
}
default:
;
}
}
break;
}
#endif
// Pass all remaining windows messages to camera so it can respond to user input
g_Camera.HandleMessages( hWnd, uMsg, wParam, lParam );
return 0;
}
void CALLBACK OnKeyboard( UINT nChar, bool bKeyDown, bool bAltDown, void* pUserContext )
{
if(bKeyDown)
{
if(nChar=='M')
{
#ifndef SHOW_DEMO_SCENE
g_iCullMethod = 1-g_iCullMethod;
#else
g_bEnableDecalMipMapping = !g_bEnableDecalMipMapping;
#endif
}
if(nChar=='O')
{
g_iVisualMode = 1-g_iVisualMode;
}
if (nChar == 'X')
{
g_iMenuVisib = 1 - g_iMenuVisib;
}
if (nChar == 'B')
{
g_iDecalBlendingMethod = g_iDecalBlendingMethod+1;
if(g_iDecalBlendingMethod>=3) g_iDecalBlendingMethod -= 3;
}
if (nChar == 'H')
{
g_iBumpFromHeightMapMethod = g_iBumpFromHeightMapMethod+1;
if(g_iBumpFromHeightMapMethod>=3) g_iBumpFromHeightMapMethod -= 3;
}
if (nChar == 'P')
{
g_bEnableDecals = !g_bEnableDecals;
}
if (nChar == 'N')
{
g_bShowNormalsWS = !g_bShowNormalsWS;
}
if (nChar == 'R')
{
g_bIndirectSpecular = !g_bIndirectSpecular;
}
if (nChar == 'V')
{
g_bShowDebugVolumes = !g_bShowDebugVolumes;
}
if (nChar == 'I')
{
g_bEnableShadows = !g_bEnableShadows;
}
if (nChar == 'U')
{
g_bUseSecondaryUVsetOnPirate = !g_bUseSecondaryUVsetOnPirate;
}
}
}
//--------------------------------------------------------------------------------------
// Called right before creating a D3D9 or D3D10 device, allowing the app to modify the device settings as needed
//--------------------------------------------------------------------------------------
bool CALLBACK ModifyDeviceSettings( DXUTDeviceSettings* pDeviceSettings, void* pUserContext )
{
// For the first device created if its a REF device, optionally display a warning dialog box
static bool s_bFirstTime = true;
if( s_bFirstTime )
{
s_bFirstTime = false;
pDeviceSettings->d3d11.AutoCreateDepthStencil = false;
/*
s_bFirstTime = false;
if( ( DXUT_D3D11_DEVICE == pDeviceSettings->ver &&
pDeviceSettings->d3d11.DriverType == D3D_DRIVER_TYPE_REFERENCE ) )
{
DXUTDisplaySwitchingToREFWarning( pDeviceSettings->ver );
}
// Enable 4xMSAA by default
DXGI_SAMPLE_DESC MSAA4xSampleDesc = { 4, 0 };
pDeviceSettings->d3d11.sd.SampleDesc = MSAA4xSampleDesc;*/
}
return true;
}
//--------------------------------------------------------------------------------------
// Handle updates to the scene
//--------------------------------------------------------------------------------------
void CALLBACK OnFrameMove( double fTime, float fElapsedTime, void* pUserContext )
{
// Update the camera's position based on user input
g_Camera.FrameMove( fElapsedTime );
}
//--------------------------------------------------------------------------------------
// Reject any D3D11 devices that aren't acceptable by returning false
//--------------------------------------------------------------------------------------
bool CALLBACK IsD3D11DeviceAcceptable( const CD3D11EnumAdapterInfo *AdapterInfo, UINT Output, const CD3D11EnumDeviceInfo *DeviceInfo,
DXGI_FORMAT BackBufferFormat, bool bWindowed, void* pUserContext )
{
return true;
}
//--------------------------------------------------------------------------------------
// Create any D3D11 resources that aren't dependant on the back buffer
//--------------------------------------------------------------------------------------
HRESULT CALLBACK OnD3D11CreateDevice( ID3D11Device* pd3dDevice, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc,
void* pUserContext )
{
HRESULT hr;
// Get device context
ID3D11DeviceContext* pd3dImmediateContext = DXUTGetD3D11DeviceContext();
// create text helper
V_RETURN( g_DialogResourceManager.OnD3D11CreateDevice(pd3dDevice, pd3dImmediateContext) );
g_pTxtHelper = new CDXUTTextHelper( pd3dDevice, pd3dImmediateContext, &g_DialogResourceManager, 15 );
InitUtils(pd3dDevice);
// set compiler flag
DWORD dwShaderFlags = D3D10_SHADER_ENABLE_STRICTNESS;
#if defined( DEBUG ) || defined( _DEBUG )
// Set the D3D10_SHADER_DEBUG flag to embed debug information in the shaders.
// Setting this flag improves the shader debugging experience, but still allows
// the shaders to be optimized and to run exactly the way they will run in
// the release configuration of this program.
dwShaderFlags |= D3D10_SHADER_DEBUG;
#endif
//dwShaderFlags |= D3DCOMPILE_OPTIMIZATION_LEVEL0;
// create constant buffers
D3D11_BUFFER_DESC bd;
#ifndef SHOW_DEMO_SCENE
memset(&bd, 0, sizeof(bd));
bd.Usage = D3D11_USAGE_DYNAMIC;
bd.ByteWidth = (sizeof( cbMeshInstance )+0xf)&(~0xf);
bd.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
bd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
bd.MiscFlags = 0;
V_RETURN( pd3dDevice->CreateBuffer( &bd, NULL, &g_pMeshInstanceCB ) );
#endif
memset(&bd, 0, sizeof(bd));
bd.Usage = D3D11_USAGE_DYNAMIC;
bd.ByteWidth = (sizeof( cbGlobals )+0xf)&(~0xf);
bd.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
bd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
bd.MiscFlags = 0;
V_RETURN( pd3dDevice->CreateBuffer( &bd, NULL, &g_pGlobalsCB ) );
CONST D3D10_SHADER_MACRO* pDefines = NULL;
// compile per tile volume list generation compute shader (with and without fine pruning)
CONST D3D10_SHADER_MACRO sDefineExact[] = {{"FINE_PRUNING_ENABLED", NULL}, {NULL, NULL}};
volumelist_exact_shader.CompileShaderFunction(pd3dDevice, L"volumelist_cs.hlsl", sDefineExact, "main", "cs_5_0", dwShaderFlags );
volumelist_coarse_shader.CompileShaderFunction(pd3dDevice, L"volumelist_cs.hlsl", pDefines, "main", "cs_5_0", dwShaderFlags );
// compile compute shader for screen-space AABB generation
#ifdef RECOMPILE_SCRBOUND_CS_SHADER
scrbound_shader.CompileShaderFunction(pd3dDevice, L"scrbound_cs.hlsl", pDefines, "main", "cs_5_0", dwShaderFlags );
FILE * fptr_out = fopen("scrbound_cs.bsh", "wb");
fwrite(scrbound_shader.GetBufferPointer(), 1, scrbound_shader.GetBufferSize(), fptr_out);
fclose(fptr_out);
#else
scrbound_shader.CreateComputeShaderFromBinary(pd3dDevice, "scrbound_cs.bsh");
#endif
#ifndef SHOW_DEMO_SCENE
// compile tiled forward lighting shader
vert_shader.CompileShaderFunction(pd3dDevice, L"shader_lighting_old_fptl_demo.hlsl", pDefines, "RenderSceneVS", "vs_5_0", dwShaderFlags );
pix_shader.CompileShaderFunction(pd3dDevice, L"shader_lighting_old_fptl_demo.hlsl", pDefines, "RenderScenePS", "ps_5_0", dwShaderFlags );
// prepare shader pipeline
shader_pipeline.SetVertexShader(&vert_shader);
shader_pipeline.SetPixelShader(&pix_shader);
// register constant buffers
shader_pipeline.RegisterConstBuffer("cbMeshInstance", g_pMeshInstanceCB);
shader_pipeline.RegisterConstBuffer("cbGlobals", g_pGlobalsCB);
// register samplers
shader_pipeline.RegisterSampler("g_samWrap", GetDefaultSamplerWrap() );
shader_pipeline.RegisterSampler("g_samClamp", GetDefaultSamplerClamp() );
shader_pipeline.RegisterSampler("g_samShadow", GetDefaultShadowSampler() );
// depth only pre-pass
vert_shader_basic.CompileShaderFunction(pd3dDevice, L"shader_basic.hlsl", pDefines, "RenderSceneVS", "vs_5_0", dwShaderFlags );
shader_dpthfill_pipeline.SetVertexShader(&vert_shader_basic);
shader_dpthfill_pipeline.RegisterConstBuffer("cbMeshInstance", g_pMeshInstanceCB);
shader_dpthfill_pipeline.RegisterConstBuffer("cbGlobals", g_pGlobalsCB);
#endif
{
debug_vol_vert_shader.CompileShaderFunction(pd3dDevice, L"shader_debug_volumes.hlsl", pDefines, "RenderDebugVolumeVS", "vs_5_0", dwShaderFlags );
debug_vol_pix_shader.CompileShaderFunction(pd3dDevice, L"shader_debug_volumes.hlsl", pDefines, "YellowPS", "ps_5_0", dwShaderFlags );
// prepare shader pipeline
debug_volume_shader_pipeline.SetVertexShader(&debug_vol_vert_shader);
debug_volume_shader_pipeline.SetPixelShader(&debug_vol_pix_shader);
// register constant buffers
debug_volume_shader_pipeline.RegisterConstBuffer("cbGlobals", g_pGlobalsCB);
// register samplers
debug_volume_shader_pipeline.RegisterSampler("g_samWrap", GetDefaultSamplerWrap() );
debug_volume_shader_pipeline.RegisterSampler("g_samClamp", GetDefaultSamplerClamp() );
debug_volume_shader_pipeline.RegisterSampler("g_samShadow", GetDefaultShadowSampler() );
}
#ifndef SHOW_DEMO_SCENE
// create all textures
WCHAR dest_str[256];
for(int t=0; t<NR_TEXTURES; t++)
{
wcscpy(dest_str, MODEL_PATH_W);
wcscat(dest_str, tex_names[t]);
V_RETURN(DXUTCreateShaderResourceViewFromFile(pd3dDevice, dest_str, &g_pTexturesHandler[t]));
shader_pipeline.RegisterResourceView(stex_names[t], g_pTexturesHandler[t]);
if(t==1) shader_dpthfill_pipeline.RegisterResourceView(stex_names[t], g_pTexturesHandler[t]);
}
#endif
#ifndef SHOW_DEMO_SCENE
g_cMesh.ReadMeshFil(pd3dDevice, MODEL_PATH MODEL_NAME, 4000.0f, true, true);
#endif
bd.ByteWidth = (sizeof( cbBoundsInfo )+0xf)&(~0xf);
V_RETURN( pd3dDevice->CreateBuffer( &bd, NULL, &g_pVolumeClipInfo ) );
D3D11_SHADER_RESOURCE_VIEW_DESC srvbuffer_desc;
// attribute data for volumes such as attenuation, color, etc.
g_VolumeDataBuffer.CreateBuffer(pd3dDevice, sizeof( SFiniteVolumeData ) * MAX_NR_VOLUMES_PER_CAMERA, sizeof( SFiniteVolumeData ), NULL, CBufferObject::StructuredBuf, true, false, CBufferObject::StagingCpuWriteOnly);
g_VolumeDataBuffer.AddStructuredSRV(pd3dDevice);
#ifndef SHOW_DEMO_SCENE
shader_pipeline.RegisterResourceView("g_vVolumeData", g_VolumeDataBuffer.GetSRV());
#endif
debug_volume_shader_pipeline.RegisterResourceView("g_vVolumeData", g_VolumeDataBuffer.GetSRV());
// buffer for GPU generated screen-space AABB per volume
g_ScrSpaceAABounds.CreateBuffer(pd3dDevice, 2 * sizeof(Vec3) * MAX_NR_VOLUMES_PER_CAMERA, sizeof(Vec3), NULL, CBufferObject::StructuredBuf, true, true, CBufferObject::StagingCpuReadOnly);
g_ScrSpaceAABounds.AddStructuredSRV(pd3dDevice);
g_ScrSpaceAABounds.AddStructuredUAV(pd3dDevice);
// a nonuniformly scaled OBB per volume
g_OrientedBounds.CreateBuffer(pd3dDevice, sizeof(SFiniteVolumeBound) * MAX_NR_VOLUMES_PER_CAMERA, sizeof(SFiniteVolumeBound), NULL, CBufferObject::StructuredBuf, true, false, CBufferObject::StagingCpuWriteOnly);
g_OrientedBounds.AddStructuredSRV(pd3dDevice);
InitializeSceneGraph(pd3dDevice, pd3dImmediateContext, g_pGlobalsCB, g_VolumeDataBuffer.GetSRV());
BuildVolumesBuffer();
// create vertex decleration
#ifndef SHOW_DEMO_SCENE
const D3D11_INPUT_ELEMENT_DESC vertexlayout[] =
{
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, ATTR_OFFS(SFilVert, pos), D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, ATTR_OFFS(SFilVert, s), D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "TEXCOORD", 1, DXGI_FORMAT_R32G32_FLOAT, 0, ATTR_OFFS(SFilVert, s2), D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, ATTR_OFFS(SFilVert, norm), D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "TEXCOORD", 2, DXGI_FORMAT_R32G32B32A32_FLOAT,0, ATTR_OFFS(SFilVert, tang), D3D11_INPUT_PER_VERTEX_DATA, 0 },
};
V_RETURN( pd3dDevice->CreateInputLayout( vertexlayout, ARRAYSIZE( vertexlayout ),
vert_shader.GetBufferPointer(), vert_shader.GetBufferSize(),
&g_pVertexLayout ) );
const D3D11_INPUT_ELEMENT_DESC simplevertexlayout[] =
{
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, ATTR_OFFS(SFilVert, pos), D3D11_INPUT_PER_VERTEX_DATA, 0 },
};
V_RETURN( pd3dDevice->CreateInputLayout( simplevertexlayout, ARRAYSIZE( simplevertexlayout ),
vert_shader_basic.GetBufferPointer(), vert_shader_basic.GetBufferSize(),
&g_pVertexSimpleLayout ) );
#endif
#ifdef SHOW_DEMO_SCENE
g_shadowMap.InitShadowMap(pd3dDevice, g_pGlobalsCB, 4096, 4096);
g_canvas.InitCanvas(pd3dDevice, g_pGlobalsCB);
#endif
return S_OK;
}
//--------------------------------------------------------------------------------------
// Release D3D11 resources created in OnD3D11CreateDevice
//--------------------------------------------------------------------------------------
void CALLBACK OnD3D11DestroyDevice( void* pUserContext )
{
g_DialogResourceManager.OnD3D11DestroyDevice();
SAFE_DELETE( g_pTxtHelper );
g_tex_depth.CleanUp();
g_VolumeDataBuffer.CleanUp();
g_ScrSpaceAABounds.CleanUp();
g_OrientedBounds.CleanUp();
g_volumeListBuffer.CleanUp();
#ifndef SHOW_DEMO_SCENE
SAFE_RELEASE( g_pMeshInstanceCB );
#endif
SAFE_RELEASE( g_pGlobalsCB );
SAFE_RELEASE( g_pVolumeClipInfo );
#ifndef SHOW_DEMO_SCENE
for(int t=0; t<NR_TEXTURES; t++)
SAFE_RELEASE( g_pTexturesHandler[t] );
#endif
ReleaseSceneGraph();
#ifndef SHOW_DEMO_SCENE
g_cMesh.CleanUp();
#endif
#ifndef SHOW_DEMO_SCENE
vert_shader.CleanUp();
pix_shader.CleanUp();
vert_shader_basic.CleanUp();
#endif
debug_vol_vert_shader.CleanUp();
debug_vol_pix_shader.CleanUp();
scrbound_shader.CleanUp();
volumelist_coarse_shader.CleanUp();
volumelist_exact_shader.CleanUp();
#ifndef SHOW_DEMO_SCENE
SAFE_RELEASE( g_pVertexLayout );
SAFE_RELEASE( g_pVertexSimpleLayout );
#endif
#ifdef SHOW_DEMO_SCENE
g_shadowMap.CleanUp();
g_canvas.CleanUp();
#endif
DeinitUtils();
}
// [0;1] but right hand coordinate system
void myFrustum(float * pMat, const float fLeft, const float fRight, const float fBottom, const float fTop, const float fNear, const float fFar)
{
// first column
pMat[0*4 + 0] = (2 * fNear) / (fRight - fLeft); pMat[0*4 + 1] = 0; pMat[0*4 + 2] = 0; pMat[0*4 + 3] = 0;
// second column
pMat[1*4 + 0] = 0; pMat[1*4 + 1] = (2 * fNear) / (fTop - fBottom); pMat[1*4 + 2] = 0; pMat[1*4 + 3] = 0;
// fourth column
pMat[3*4 + 0] = 0; pMat[3*4 + 1] = 0; pMat[3*4 + 2] = -(fFar * fNear) / (fFar - fNear); pMat[3*4 + 3] = 0;
// third column
pMat[2*4 + 0] = (fRight + fLeft) / (fRight - fLeft);
pMat[2*4 + 1] = (fTop + fBottom) / (fTop - fBottom);
pMat[2*4 + 2] = -fFar / (fFar - fNear);
pMat[2*4 + 3] = -1;
#ifdef LEFT_HAND_COORDINATES
for(int r=0; r<4; r++) pMat[2*4 + r] = -pMat[2*4 + r];
#endif
} | [
"mikkelsen7@gmail.com"
] | mikkelsen7@gmail.com |
a8f40d5d6e0f167e9927bea0aabd1fb1205ca8ee | 807c79f8056f385523c8a7d76def36fcb254e2e8 | /DirectoryDiffUi/stdafx.h | eaba641c443b108e813d2e6d29a81376ae8de0e7 | [] | no_license | yang123vc/DirectoryDiffUI | c2956ebfa6c21bd07e8e5401a95172149ef20779 | af6b7a442a1f2e7481915090029380bf211aa810 | refs/heads/master | 2020-05-07T05:43:40.674758 | 2017-01-03T03:31:04 | 2017-01-03T03:31:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,226 | h | #ifndef STDAFX_H
#define STDAFX_H
#define _CRT_SECURE_NO_WARNINGS
#define BOOST_FILESYSTEM_NO_DEPRECATE
#include <stdio.h>
#include <tchar.h>
/*
*
* general includes
*
*/
#include <iostream>
#include <string>
#include <memory>
// make hash_path::get_hash_digest member function thread safe.
#include <mutex>
#include <algorithm>
#include <vector>
#include <utility>
#include <iterator>
#include <time.h> // for runtime http://www.cplusplus.com/forum/beginner/14666/#msg71908
#include <iostream> // for std::cout
#include <utility> // for std::pair
#include <algorithm> // for std::for_each
/*
* windows headers
*/
#include <conio.h> // used for delayed exit http://www.cplusplus.com/forum/general/16335/#msg81524
/*
*
*Boost includes
*
*/
#include <boost/filesystem.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/thread/thread.hpp> // for sleeping at exit
#include <boost/function.hpp> // for comparison hash_path overloads
/*
*
*OpenSsl includes
*
*/
#include <openssl/sha.h>
/*
*
* Qt includes
*
*/
#include <QObject>
#include <QString>
#include <QList>
#include "hash_path.h"
#include "gc_file_system.h"
#endif // STDAFX_H
| [
"graham.crowell@gmail.com"
] | graham.crowell@gmail.com |
ff489d9c9014c42db1f33d4d83bfc736d6dc9556 | 7be1543c55866ab1628dcf4070e79b44fc747e9b | /cs240/lab-5-Goldenr9/BSTree.cpp | 60f9be21ffdca5c29ef7f08d0e140ca938cdf9ea | [] | no_license | rorourk2/CS240 | bc6c07a443960e16a6464972f704285930d9c3f8 | 5845eea9ad7387539555b4b62117417758de80d7 | refs/heads/main | 2023-03-26T19:14:09.212257 | 2021-03-24T19:29:19 | 2021-03-24T19:29:19 | 351,199,534 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,183 | cpp | #include "BSTree.h"
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <fstream>
BSTree::BSTree(){
this->root=NULL;
}
bool BSTree::empty(){
if(root==NULL){
return true;
}
return false;
}
bool BSTree::insert(int t){
if(root==NULL){
root= new Node(t);
return true;
}else{
return insertNode(t,root);
}
}
bool BSTree::insertNode(int t,Node *n){
if(t<n->data){
if(n->left==NULL){
n->left=new Node(t);
n->left->parent=n;
return true;
}else{
return insertNode(t,n->left);
}
}else if(t>n->data){
if(n->right==NULL){
n->right=new Node(t);
n->right->parent=n;
return true;
}else{
return insertNode(t,n->right);
}
}
return false;
}
bool BSTree::find(int t){
if(root==NULL){
return false;
}else{
return findNode(t,root);
}
}
bool BSTree::findNode(int t,Node *n){
if(t<n->data){
if(n->left==NULL){
return false;
}else{
return findNode(t,n->left);
}
}else if(t>n->data){
if(n->right==NULL){
return false;
}else{
return findNode(t,n->right);
}
}else{
return true;
}
}
BSTree::~BSTree(){
if(root!=NULL){
deleteNode(root);
}
}
void BSTree::deleteNode(Node *n){
if(n->left!=NULL){
deleteNode(n->left);
}
if(n->right!=NULL){
deleteNode(n->right);
}
delete n;
}
BSTree::BSTree(const BSTree &old_tree){
Node *o= old_tree.root;
if(o==NULL){
this->root=NULL;
}else{
this->root=makeTree(this->root,o);
}
}
BSTree::Node *BSTree::makeTree(Node *n,Node *o){
n=new Node(o->data);
if(o->left!=NULL){
Node *l=makeTree(n->left,o->left);
n->left=l;
n->left->parent=n;
}
if(o->right!=NULL){
Node *r=makeTree(n->right,o->right);
n->right=r;
n->right->parent=n;
}
return n;
}
void BSTree::sortedArray(std::vector<int> &list){
if(this->root!=NULL){
sortedArrayHelper(list,this->root);
}
}
void BSTree::sortedArrayHelper(std::vector<int> &list, Node *n){
if(n != NULL){
sortedArrayHelper(list,n->left);
list.push_back(n->data);
sortedArrayHelper(list,n->right);
}
return;
}
bool BSTree::remove(int num){
//std::cout<<"8"<<std::endl;
Node *del=read(num);
//std::cout<<"9"<<std::endl;
if(del==NULL){
return false;
}
//std::cout<<"10"<<std::endl;
if(del->left==NULL && del->right==NULL){
if(del==this->root){
delete del;
this->root=NULL;
}else{
removeLeaf(del);
}
return true;
}else if(del->left==NULL || del->right==NULL){
if(del==this->root && del->left==NULL){
this->root=del->right;
delete del;
}else if(del==this->root && del->right==NULL){
this->root=del->left;
delete del;
}else{
shortCircuit(del);
}
return true;
}else{
promotion(del);
return true;
}
return false;
}
void BSTree::removeLeaf(Node *del){
if(del->parent->left==del){
del->parent->left=NULL;
}else{
del->parent->right=NULL;
}
delete del;
}
void BSTree::shortCircuit(Node *del){
if(del->parent->left==del){
if(del->left!=NULL){
del->parent->left=del->left;
del->left->parent=del->parent;
}else{
del->parent->left=del->right;
del->right->parent=del->parent;
}
}else{
if(del->left!=NULL){
del->parent->right=del->left;
del->left->parent=del->parent;
}else{
del->parent->right=del->right;
del->right->parent=del->parent;
}
}
delete del;
}
void BSTree::promotion(Node *del){
Node *promote = getMinMax(del->right);
del->data=promote->data;
if(promote->left==NULL && promote->right==NULL){
removeLeaf(promote);
}else{
shortCircuit(promote);
}
}
BSTree::Node *BSTree::getMinMax(Node *n){
if(n->left==NULL){
return n;
}else{
return getMinMax(n->left);
}
}
BSTree::Node *BSTree::read(int t){
if(root==NULL){
return NULL;
}else{
return readNode(t,root);
}
}
BSTree::Node *BSTree::readNode(int t,Node *n){
if(t<n->data){
if(n->left==NULL){
return NULL;
}else{
return readNode(t,n->left);
}
}else if(t>n->data){
if(n->right==NULL){
return NULL;
}else{
return readNode(t,n->right);
}
}else{
return n;
}
} | [
"noreply@github.com"
] | rorourk2.noreply@github.com |
21fe282b9b3fc4701c7e4851720cc69571dbd85b | f331d26357d58e47c2faf51033a3d92fc641a044 | /include/Being/Player.h | f5a6b518275ee8f38a3ff1a5d791d105f9d376ab | [] | no_license | AnnaPeyl98/roguelike | eddc360ae686d6db8589306d1a7f08222db7b28f | cc5ea83db034a46cdab5f9e0d61d57fe6c9fbc1b | refs/heads/master | 2021-05-18T00:09:34.665928 | 2019-08-14T08:33:20 | 2019-08-14T08:33:20 | 251,016,986 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 980 | h | //
// Created by anna on 25.06.19.
//
#ifndef MYGAME_PLAYER_H
#define MYGAME_PLAYER_H
#include "../Controls.h"
#include "../Map.h"
#include "../statemashine/IState.h"
#include "../statemashine/StateSteps.h"
class Player {
int x_;
int y_;
int money_;
int steps_;
int health_;
int countSteps_ = 0;
int countKeys_ = 0;
public:
void SetX(int x);
void SetY(int y);
void SetMoney(int money);
void SetSteps(int steps);
void SetHealth(int health);
int GetX();
int GetY();
int GetMoney();
int GetSteps();
int GetHealth();
void SetOneStep(int countStep);
int GetCountStep();
Player(int x, int money, int steps, int health, int y);
void Update();
int GetKeys();
void SetKey(int);
Player& operator=(const Player& player) {
x_ = player.x_;
y_ = player.y_;
money_ = player.money_;
health_ = player.health_;
steps_ = player.steps_;
countSteps_ = player.countSteps_;
return *this;
}
};
#endif // MYGAME_PLAYER_H
| [
"annapeyl@gmail.com"
] | annapeyl@gmail.com |
d55abe0475310f6679729ac84cf7435a89743751 | e7eb3448b955b08545452d4758b05dab497d32cd | /src/ktx_c_binding.cpp | 8fd080b57df839229ff6c5589492e72cc82dedc1 | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] | permissive | kyapp69/KTX-Software-Unity | fa983a03d28c0851e8cd0d8b8fb18350603f37cf | a4ca93596017e3fb1a3f4671bfccaf7f2fb3dd54 | refs/heads/main | 2023-06-15T18:27:00.045106 | 2021-07-16T20:54:16 | 2021-07-16T20:54:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,095 | cpp | // Copyright (c) 2020 Andreas Atteneder, All Rights Reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#if defined(_WIN32)
#if !defined(KTX_UNITY_API)
#define KTX_UNITY_API __declspec(dllimport)
#endif
#elif defined(__ANDROID__)
#define KTX_UNITY_API __attribute__((visibility("default")))
#else
#define KTX_UNITY_API
#endif
#include <stdint.h>
#include <string.h>
#include <ktx.h>
#include <basisu_c_binding.h>
#ifdef __cplusplus
extern "C" {
#endif
KTX_UNITY_API ktxTexture* ktx_load_ktx( const uint8_t * data, uint32_t length, KTX_error_code* out_status ) {
KTX_error_code result;
ktxTexture* newTex = 0;
result = ktxTexture_CreateFromMemory(
(const ktx_uint8_t*) data,
(ktx_size_t) length,
KTX_TEXTURE_CREATE_LOAD_IMAGE_DATA_BIT,
&newTex
);
*out_status = result;
return newTex;
}
KTX_UNITY_API class_id ktx_get_classId ( ktxTexture* ktx ) {
return ktx->classId;
}
KTX_UNITY_API ktx_bool_t ktx_get_isArray ( ktxTexture* ktx ) {
return ktx->isArray;
}
KTX_UNITY_API ktx_bool_t ktx_get_isCubemap ( ktxTexture* ktx ) {
return ktx->isCubemap;
}
KTX_UNITY_API ktx_bool_t ktx_get_isCompressed ( ktxTexture* ktx ) {
return ktx->isCompressed;
}
KTX_UNITY_API ktx_uint32_t ktx_get_baseWidth ( ktxTexture* ktx ) {
return ktx->baseWidth;
}
KTX_UNITY_API ktx_uint32_t ktx_get_baseHeight ( ktxTexture* ktx ) {
return ktx->baseHeight;
}
KTX_UNITY_API ktx_uint32_t ktx_get_numDimensions ( ktxTexture* ktx ) {
return ktx->numDimensions;
}
KTX_UNITY_API ktx_uint32_t ktx_get_numLevels ( ktxTexture* ktx ) {
return ktx->numLevels;
}
KTX_UNITY_API ktx_uint32_t ktx_get_numLayers ( ktxTexture* ktx ) {
return ktx->numLayers;
}
KTX_UNITY_API ktx_uint32_t ktx_get_numFaces ( ktxTexture* ktx ) {
return ktx->numFaces;
}
KTX_UNITY_API ktx_uint32_t ktx_get_vkFormat ( ktxTexture* ktx ) {
if (ktx->classId != ktxTexture2_c) {
return 0; // VK_FORMAT_UNDEFINED
}
return ((ktxTexture2*)ktx)->vkFormat;
}
KTX_UNITY_API ktxSupercmpScheme ktx_get_supercompressionScheme ( ktxTexture* ktx ) {
if (ktx->classId != ktxTexture2_c) {
return KTX_SS_NONE;
}
return ((ktxTexture2 *)ktx)->supercompressionScheme;
}
KTX_UNITY_API ktx_uint32_t ktx_get_orientation ( ktxTexture* ktx ) {
ktx_uint32_t orientation = 0;
if(ktx->orientation.x == KTX_ORIENT_X_LEFT) {
orientation |= 0x1;
}
if(ktx->orientation.y == KTX_ORIENT_Y_UP) {
orientation |= 0x2;
}
if(ktx->orientation.z == KTX_ORIENT_Z_IN) {
orientation |= 0x4;
}
return orientation;
}
ktx_uint32_t ktx_transcode (ktxTexture2* ktx, ktx_transcode_fmt_e fmt, ktx_transcode_flags transcodeFlags) {
return ktxTexture2_TranscodeBasis(ktx, fmt, transcodeFlags);
}
KTX_UNITY_API void ktx_get_data(
ktxTexture* ktx,
const uint8_t ** data,
uint32_t* length
)
{
*data = ktx->pData;
*length = (uint32_t) ktx->dataSize;
}
/**
* @~English
* @brief Copies the texture's data into a destination buffer in reverted
* level order (resulting in biggest to smallest)
*
* @param[in] ktx pointer to the ktxTexture object of interest.
* @param[in] ktx pointer to the destination buffer.
* @param[in] dst_length length of the destination buffer.
*
* @return KTX_SUCCESS on success, other KTX_* enum values on error.
*/
KTX_UNITY_API KTX_error_code ktx_copy_data_levels_reverted(
ktxTexture* ktx,
uint8_t * dst,
uint32_t dst_length
)
{
size_t dst_offset = 0;
KTX_error_code result;
if(ktx->dataSize>dst_length) return KTX_FILE_OVERFLOW;
for (ktx_uint32_t level = 0; level < ktx->numLevels; level++)
{
size_t offset;
result = ktxTexture_GetImageOffset(
ktx,
level,
0, //layer
0, //faceSlice
&offset
);
if(result!=KTX_SUCCESS) return result;
ktx_size_t level_size = ktxTexture_GetImageSize(ktxTexture(ktx),level);
if(dst_offset+level_size > dst_length) {
return KTX_FILE_OVERFLOW;
}
memcpy((void*)(dst+dst_offset), ktx->pData+offset, level_size);
dst_offset += level_size;
}
return result;
}
KTX_UNITY_API void ktx_unload_ktx( ktxTexture* ktx ) {
ktxTexture_Destroy(ktx);
}
void _basisu_dummy() {
// Referencing just one function of KTX-Software's basisu C binding
// ensures its symbols are included when linking (e.g. Android)
basis_file* x = ktx_basisu_create_basis();
}
#ifdef __cplusplus
}
#endif
| [
"andreas.atteneder@gmail.com"
] | andreas.atteneder@gmail.com |
87897963e25cd2bc38da31a3886d45c44493c478 | c5a09c77fd5307c934f09d27a554b967dd56a96b | /src/FMTstarViz/path_planning_info.h | 305365285df5226e4481f76c4906298713f8cb1a | [] | no_license | dqyi11/fmt | 13cee8ab54ff92234f62e106bae1527f21c23640 | 24e08417a2e9a8537f4899ec1cee2dd5216accd7 | refs/heads/master | 2021-01-17T22:14:08.231451 | 2016-07-18T20:15:50 | 2016-07-18T20:15:50 | 63,626,890 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,285 | h | #ifndef PATHPLANNINGINFO_H_
#define PATHPLANNINGINFO_H_
#include <libxml/tree.h>
#include <QString>
#include <QPoint>
#include <list>
#include <vector>
#include <QDebug>
#include <math.h>
#include "fmt_star.h"
class PathPlanningInfo {
public:
PathPlanningInfo();
bool get_obstacle_info( int** pp_obstacle_info );
bool get_cost_distribution( double** pp_cost_distribution );
bool get_pix_info( QString filename, double** pp_pix_info );
bool get_pix_info( QString filename, int** pp_pix_info );
void init_func_param();
void dump_cost_distribution( QString filename );
bool save_to_file( QString filename );
bool load_from_file( QString filename );
void read( xmlNodePtr root );
void write( xmlDocPtr doc, xmlNodePtr root ) const;
void load_path( Path* path );
bool export_path( QString filename );
static double calc_dist( POS2D pos_a, POS2D pos_b, double** pp_distribution, void* tree ) {
double dist = 0.0;
if (pos_a == pos_b) {
return dist;
}
double delta_x = fabs(pos_a[0]-pos_b[0]);
double delta_y = fabs(pos_a[1]-pos_b[1]);
dist = sqrt(delta_x*delta_x+delta_y*delta_y);
if(dist < 0.0) {
qWarning() << "Dist negative " << dist ;
}
return dist;
}
static double calc_cost( POS2D pos_a, POS2D pos_b, double** pp_distribution, void* tree ) {
double cost = 0.0;
FMTstar* rrts = (FMTstar*)tree;
if ( pos_a == pos_b ) {
return cost;
}
if( pp_distribution == NULL ) {
return cost;
}
float x1 = pos_a[0];
float y1 = pos_a[1];
float x2 = pos_b[0];
float y2 = pos_b[1];
const bool steep = (fabs(y2 - y1) > fabs(x2 - x1));
if (steep) {
std::swap(x1, y1);
std::swap(x2, y2);
}
if (x1 > x2) {
std::swap(x1, x2);
std::swap(y1, y2);
}
const float dx = x2 - x1;
const float dy = fabs(y2 - y1);
float error = dx / 2.0f;
const int ystep = (y1 < y2) ? 1 : -1;
int y = (int)y1;
const int maxX = (int)x2;
for(int x=(int)x1; x<maxX; x++) {
if(steep) {
if (y>=0 && y<rrts->get_sampling_width() && x>=0 && x<rrts->get_sampling_height()) {
cost += pp_distribution[y][x];
}
}
else {
if (x>=0 && x<rrts->get_sampling_width() && y>=0 && y<rrts->get_sampling_height()) {
cost += pp_distribution[x][y];
}
}
error -= dy;
if(error < 0) {
y += ystep;
error += dx;
}
}
return cost;
}
/* Member variables */
QString m_info_filename;
QString m_map_filename;
QString m_map_fullpath;
int m_map_width;
int m_map_height;
QPoint m_start;
QPoint m_goal;
QString m_paths_output;
bool m_min_dist_enabled;
QString m_objective_file;
COST_FUNC_PTR mp_func;
double** mCostDistribution;
int m_max_iteration_num;
double m_segment_length;
Path* mp_found_path;
};
#endif // PATHPLANNINGINFO_H_
| [
"daqing.yi@byu.edu"
] | daqing.yi@byu.edu |
b74dc9fc77fb2ab07a02286f587b60c2b91afb11 | a66fcf097bd760475b253f35097b85e687a97e19 | /LTFRAME_SRC/Source/WebKit2/WebProcess/Notifications/WebNotificationManager.cpp | 0c865292d020a7aec593779d5bc664d07115fb9d | [] | no_license | AtaLuZiK/ltframe | fca6c5b3a9dd256818220535cc762233eac49652 | f0906ab8f97557a44184d9c79cdc022c26a500db | refs/heads/master | 2023-08-17T14:44:10.479147 | 2019-12-08T08:13:26 | 2019-12-08T08:13:26 | 45,810,387 | 0 | 0 | null | 2015-11-09T02:33:47 | 2015-11-09T02:33:44 | C++ | UTF-8 | C++ | false | false | 6,260 | cpp | /*
* Copyright (C) 2011 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "WebNotificationManager.h"
#include "WebPage.h"
#include "WebProcess.h"
#if ENABLE(NOTIFICATIONS)
#include "WebNotification.h"
#include "WebNotificationManagerProxyMessages.h"
#include "WebPageProxyMessages.h"
#include <WebCore/Notification.h>
#include <WebCore/Page.h>
#include <WebCore/ScriptExecutionContext.h>
#include <WebCore/SecurityOrigin.h>
#include <WebCore/Settings.h>
#endif
using namespace WebCore;
namespace WebKit {
#if ENABLE(NOTIFICATIONS)
static uint64_t generateNotificationID()
{
static uint64_t uniqueNotificationID = 1;
return uniqueNotificationID++;
}
#endif
WebNotificationManager::WebNotificationManager(WebProcess* process)
: m_process(process)
{
}
WebNotificationManager::~WebNotificationManager()
{
}
void WebNotificationManager::didReceiveMessage(CoreIPC::Connection* connection, CoreIPC::MessageID messageID, CoreIPC::ArgumentDecoder* arguments)
{
didReceiveWebNotificationManagerMessage(connection, messageID, arguments);
}
void WebNotificationManager::initialize(const HashMap<String, bool>& permissions)
{
#if ENABLE(NOTIFICATIONS)
m_permissionsMap = permissions;
#endif
}
void WebNotificationManager::didUpdateNotificationDecision(const String& originString, bool allowed)
{
#if ENABLE(NOTIFICATIONS)
m_permissionsMap.set(originString, allowed);
#endif
}
void WebNotificationManager::didRemoveNotificationDecisions(const Vector<String>& originStrings)
{
#if ENABLE(NOTIFICATIONS)
size_t count = originStrings.size();
for (size_t i = 0; i < count; ++i)
m_permissionsMap.remove(originStrings[i]);
#endif
}
NotificationPresenter::Permission WebNotificationManager::policyForOrigin(WebCore::SecurityOrigin *origin) const
{
#if ENABLE(NOTIFICATIONS)
if (!origin)
return NotificationPresenter::PermissionNotAllowed;
HashMap<String, bool>::const_iterator it = m_permissionsMap.find(origin->toString());
if (it != m_permissionsMap.end())
return it->second ? NotificationPresenter::PermissionAllowed : NotificationPresenter::PermissionDenied;
#endif
return NotificationPresenter::PermissionNotAllowed;
}
bool WebNotificationManager::show(Notification* notification, WebPage* page)
{
#if ENABLE(NOTIFICATIONS)
if (!notification || !page->corePage()->settings()->notificationsEnabled())
return true;
uint64_t notificationID = generateNotificationID();
m_notificationMap.set(notification, notificationID);
m_notificationIDMap.set(notificationID, notification);
m_process->connection()->send(Messages::WebPageProxy::ShowNotification(notification->contents().title, notification->contents().body, notification->scriptExecutionContext()->securityOrigin()->toString(), notificationID), page->pageID());
#endif
return true;
}
void WebNotificationManager::cancel(Notification* notification, WebPage* page)
{
#if ENABLE(NOTIFICATIONS)
if (!notification || !page->corePage()->settings()->notificationsEnabled())
return;
uint64_t notificationID = m_notificationMap.get(notification);
if (!notificationID)
return;
m_process->connection()->send(Messages::WebNotificationManagerProxy::Cancel(notificationID), page->pageID());
#endif
}
void WebNotificationManager::didDestroyNotification(Notification* notification, WebPage* page)
{
#if ENABLE(NOTIFICATIONS)
uint64_t notificationID = m_notificationMap.take(notification);
if (!notificationID)
return;
m_notificationIDMap.take(notificationID);
m_process->connection()->send(Messages::WebNotificationManagerProxy::DidDestroyNotification(notificationID), page->pageID());
#endif
}
void WebNotificationManager::didShowNotification(uint64_t notificationID)
{
#if ENABLE(NOTIFICATIONS)
if (!isNotificationIDValid(notificationID))
return;
RefPtr<Notification> notification = m_notificationIDMap.get(notificationID);
if (!notification)
return;
notification->dispatchShowEvent();
#endif
}
void WebNotificationManager::didClickNotification(uint64_t notificationID)
{
#if ENABLE(NOTIFICATIONS)
if (!isNotificationIDValid(notificationID))
return;
RefPtr<Notification> notification = m_notificationIDMap.get(notificationID);
if (!notification)
return;
notification->dispatchClickEvent();
#endif
}
void WebNotificationManager::didCloseNotifications(const Vector<uint64_t>& notificationIDs)
{
#if ENABLE(NOTIFICATIONS)
size_t count = notificationIDs.size();
for (size_t i = 0; i < count; ++i) {
uint64_t notificationID = notificationIDs[i];
if (!isNotificationIDValid(notificationID))
continue;
RefPtr<Notification> notification = m_notificationIDMap.get(notificationID);
if (!notification)
continue;
notification->dispatchCloseEvent();
}
#endif
}
} // namespace WebKit
| [
"ltplayer@yeah.net"
] | ltplayer@yeah.net |
acfadd7ba431c772aaedd223b8933342de2ff10d | 4bff5107afcb116caf88180531444d2ad5354f92 | /MyGame/MyGame/Scene/GameScene/Cource.cpp | 0f7243b9499125f95183ab1dbd8bbda8e9d8729c | [] | no_license | teramoti/- | d45350bd9fe5603538169812adb538808b1eb604 | 09b5ff422913908b13f2df33677c09975ef95ce0 | refs/heads/master | 2020-05-23T19:40:15.087896 | 2019-09-04T05:07:04 | 2019-09-04T05:07:04 | 186,917,644 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,219 | cpp | //#include "../../../pch.h"
#include "Cource.h"
#include "../../Collison/DebugBox.h"
Cource::Cource()
{
}
Cource::~Cource()
{
m_model.reset();
}
void Cource::Initilize()
{
m_directX11.Get().GetEffect()->SetDirectory(L"Resources\\Model");
CreateResource();
m_inBox.c=(DirectX::SimpleMath::Vector3(1000/2,0,0));
m_inBox.r=(DirectX::SimpleMath::Vector3(360 ,50,360));
m_translation = DirectX::SimpleMath::Vector3(0, -1, 0);
}
void Cource::Update()
{
Object3D::Update();
}
void Cource::Render(DirectX::SimpleMath::Matrix view, DirectX::SimpleMath::Matrix proj)
{
DirectX::SimpleMath::Matrix world;
world = DirectX::SimpleMath::Matrix::CreateScale(m_inBox.r)*DirectX::SimpleMath::Matrix::CreateTranslation(m_inBox.c);
m_model->Draw(m_directX11.GetContext().Get(), *m_directX11.Get().GetStates(), m_world, view,proj);
DebugBox* playerdebugbox = new DebugBox(m_directX.GetDevice().Get(), m_inBox.c, m_inBox.r);
playerdebugbox->Draw(m_directX.GetContext().Get(), *m_directX.Get().GetStates(), world, view, proj);
}
void Cource::CreateResource()
{
m_model = DirectX::Model::CreateFromCMO(m_directX11.GetDevice().Get(), L"Resources\\Model\\MyGameCource_01.cmo", *m_directX11.Get().GetEffect());
}
| [
"teramoti0315@icloud.com"
] | teramoti0315@icloud.com |
e7b417f0aaab1a1617540424c0450ab6559238d6 | 23868e4637c39cc16b019246f0649a8d8a60e306 | /Array Template Implementation/Currency.cpp | f9a5faf583765943cea408d90b74cf5c7599dc8b | [] | no_license | srdea93/Data-Structures-in-CPP | caa4aaf29e2eb25465b30fc44f752cd93f032029 | e9e6922c28e4efad0d17a6f068f854ed0f47983c | refs/heads/master | 2021-02-04T08:52:34.834617 | 2020-02-28T01:24:43 | 2020-02-28T01:24:43 | 243,645,920 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,174 | cpp | #include "Currency.h"
#include <string>
//explicit constructor
Currency::Currency() {};
Currency::Currency(std::string note, int whole, int fraction, std::string coin) :
m_note(note), m_whole(whole), m_fraction(fraction), m_coin(coin) {}
//Getters for all member variables
std::string Currency::getNote() {
return this->m_note;
}
int Currency::getWhole() {
return this->m_whole;
}
int Currency::getFraction() {
return this->m_fraction;
}
std::string Currency::getCoin() {
return this->m_coin;
}
//Setters for only integer member variables
void Currency::setWhole(int whole) {
this->m_whole = whole;
}
void Currency::setFraction(int fraction) {
this->m_fraction = fraction;
}
//overloaded operators implemented in Currency because
//each derived class constructor is creating a polymorphic Currency class
//Add operator with built in check for if currency is of the same type
void Currency::operator+(Currency ¤cy) {
//cout error if two currencies not of the same type are added
if (this->m_note != currency.m_note) {
std::cout << "Can only add currencies of the same type!" << std::endl;
}
//add together currencies, if m_fractions go above 100, roll over the amount of times into whole
else {
this->m_fraction += currency.m_fraction;
this->m_whole += currency.m_whole;
if (this->m_fraction > 99) {
this->m_whole += (this->m_fraction / 100);
this->m_fraction = (this->m_fraction % 100);
}
}
}
//Subtract operator
void Currency::operator-(Currency ¤cy) {
if (this->m_note != currency.m_note) {
std::cout << "Can only subtract currencies of the same type!" << std::endl;
}
else {
this->m_fraction -= currency.m_fraction;
this->m_whole -= currency.m_whole;
if (this->m_fraction < 0) {
this->m_whole -= 1;
this->m_fraction = abs(this->m_fraction % 100);
}
}
}
//Greater than compare operator
bool Currency::operator>(Currency ¤cy) {
if (this->m_note != currency.m_note) {
std::cout << "Can only compare currencies of the same type!" << std::endl;
}
else {
//first compare the wholes to see if LH is > RH
if (this->m_whole > currency.m_whole) {
return true;
}
//if wholes are ==, compare fractions
else if (this->m_whole == currency.m_whole) {
if (this->m_fraction > currency.m_fraction) {
return true;
}
else {
return false;
}
}
else {
return false;
}
}
return false;
}
//Less than compare operator
bool Currency::operator<(Currency ¤cy) {
if (this->m_note != currency.m_note) {
std::cout << "Can only compare currencies of the same type!" << std::endl;
}
else {
if (this->m_whole < currency.m_whole) {
return true;
}
else if (this->m_whole == currency.m_whole) {
if (this->m_fraction < currency.m_fraction) {
return true;
}
else {
return false;
}
}
else {
return false;
}
}
return false;
}
//input/output operator overloads
//input, take in any reference to a currency object
std::istream& operator>>(std::istream &in, Currency ¤cy) {
if (!in) {
return in;
}
std::string note, coin;
std::string whole, fraction;
// char comma;
//eat white space before the dollar type
std::cin >> std::ws;
std::getline(in, note, ',');
std::getline(in, whole, ',');
std::getline(in, fraction, ',');
//eat white space before the coin type
std::cin >> std::ws;
std::getline(in, coin);
currency.m_note = note;
currency.m_whole = std::stoi(whole);
currency.m_fraction = std::stoi(fraction);
currency.m_coin = coin;
return in;
}
//output should write out the values of any currency
//left hand is the ostream object and the right is a reference to the currency being put into the stream
std::ostream& operator<<(std::ostream &out, Currency ¤cy) {
out << currency.getNote() << ", " << currency.getWhole() << ", "
<< currency.getFraction() << ", " << currency.getCoin();
return out;
}
//virtual destructor
Currency::~Currency() {};
//polymorphic constructors for different monetary types
Dollar::Dollar() : Currency("Dollar", 0, 0, "cent") {};
Dollar::Dollar(std::string note, int whole, int fraction, std::string coin) :
Currency("Dollar", whole, fraction, "cent") {}
Dollar::~Dollar() {
// std::cout << "Dollar Destroyed" << std::endl;
}
Euro::Euro() : Currency("Euro", 0, 0, "cent") {};
Euro::Euro(std::string note, int whole, int fraction, std::string coin) :
Currency("Euro", whole, fraction, "cent") {}
Euro::~Euro() {
std::cout << "Euro Destroyed" << std::endl;
}
Yen::Yen() : Currency("Yen", 0, 0, "sen") {};
Yen::Yen(std::string note, int whole, int fraction, std::string coin) :
Currency("Yen", whole, fraction, "sen") {}
Yen::~Yen() {
std::cout << "Yen Destroyed" << std::endl;
}
Rupee::Rupee() : Currency("Rupee", 0, 0, "paise") {}
Rupee::Rupee(std::string note, int whole, int fraction, std::string coin) :
Currency("Rupee", whole, fraction, "paise") {}
Rupee::~Rupee() {
std::cout << "Rupee Destroyed" << std::endl;
}
Yuan::Yuan() : Currency("Yuan", 0, 0, "fen") {}
Yuan::Yuan(std::string note, int whole, int fraction, std::string coin) :
Currency("Yuan", whole, fraction, "fen") {}
Yuan::~Yuan() {
std::cout << "Yuan Destroyed" << std::endl;
}
| [
"noreply@github.com"
] | srdea93.noreply@github.com |
b25faaef9e067f2c6c79a63323056fc2ee8de3e4 | 8a90c18515990d948067db3812c723a9c7ca35bd | /C++ - Print the string character by character using pointer.cpp | 31b79a23cfa4f5bd9b65614c1da8bea99d898141 | [] | no_license | lohitakshsingla0/Programming-Questions-C-and-Cpp | 7c24116eeea21c5126a9b5e9d5e2ffc3e25fc11f | 7b9ddd898ea08e30298345108575f70bf8785cbb | refs/heads/master | 2021-01-23T02:22:47.966395 | 2017-10-04T18:30:18 | 2017-10-04T18:30:18 | 102,441,092 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 180 | cpp | #include <iostream>
using namespace std;
int main()
{
char name[]="lohitaksh singla";
char *ptr=name;
while(*ptr!=NULL){
cout<<*ptr;
ptr++;
}
cout<<endl;
return 0;
}
| [
"lohitakshsingla0@gmail.com"
] | lohitakshsingla0@gmail.com |
6b8720589bccec250c7ee606cab983e4a428c885 | 6b2a8dd202fdce77c971c412717e305e1caaac51 | /solutions_5644738749267968_0/C++/tchrikch/D.cpp | 121658e5c1d96ddc8314a4bdb9d5e7e2f7b0fae3 | [] | no_license | alexandraback/datacollection | 0bc67a9ace00abbc843f4912562f3a064992e0e9 | 076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf | refs/heads/master | 2021-01-24T18:27:24.417992 | 2017-05-23T09:23:38 | 2017-05-23T09:23:38 | 84,313,442 | 2 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 1,113 | cpp | #include<iostream>
#include<vector>
#include<algorithm>
#include <iomanip>
#include<set>
#include<string>
#include<sstream>
#define REP(i,n) for(int i=0;i<n;++i)
#define FOR(i,j,k) for(int i=j;i<k;++i)
#define REPD(i,n) for(int i=n;i>-1;--i)
#define ALL(v) v.begin(),v.end()
#define ll long long
#define PB push_back
using namespace std;
int main()
{
int ts;cin>>ts;
REP(tn,ts)
{
int n; cin>>n;
vector<double> a(n,.0);
vector<double> b(n,.0);
REP(i,n) cin>>a[i];
REP(i,n) cin>>b[i];
sort(ALL(a));
sort(ALL(b));
int r1 =0 , r2 = 0;
//fair game
int b1 = 0 , b2 = b.size()-1;
REPD(i,a.size()-1)
{
if(a[i]>b[b2]) { ++r2; ++b1; }
else { --b2; }
}
b1 = 0 , b2 = b.size()-1;
REP(i,a.size())
{
if(a[i]>b[b1]) { ++r1; ++b1; }
}
//unfair game
cout<<"Case #"<<(tn+1)<<": "<<r1<<" "<<r2<<endl;
}
return 0;
}
| [
"eewestman@gmail.com"
] | eewestman@gmail.com |
aa8e435d3fedf00713e0079d35831af2ed9d1efc | 572871ee2bbcdf9c1a5f6999300307c57d2b31ae | /general/func/src/A2Cal1ToCal2.cpp | eb825d95e951cdd7bc446eb6428e286f1a32316c | [] | no_license | hmenjo/RHICf-library | 9bd3ed12726e989962e1b882e871a6ad59756ca5 | c95cb94a2cc2fbe281b2d85bbf02296da2329eac | refs/heads/develop | 2022-05-15T00:45:30.783099 | 2022-04-19T01:57:01 | 2022-04-19T01:57:01 | 203,476,841 | 0 | 0 | null | 2021-04-28T06:30:37 | 2019-08-21T00:45:21 | Shell | UTF-8 | C++ | false | false | 7,290 | cpp | #ifndef __A2CAL1TOCAL2_CPP__
#define __A2CAL1TOCAL2_CPP__
#include "A2Cal1ToCal2.h"
//----------------------------------------------------------------------
// This class is for convertion of the data type from
// A2Cal1 to A2Cal2. In this convertion, the adc value
// of A2Cal2::cal are calcurated from "high range" adc value of
// each channnel, if the "low range" adc value is over the
// threshold (default 3700). if you want to use this adc
// calculation in the convertion, you should set
// use_adcrange parameter to 0 by UseADCRange().
// easy way:
// UseADCRange(true);
// (Pedestal subtraction)
// Convert(cal1,cal2,pede);
// In this way, the low range adc values of "cal1+pede"
// are used as the discrimination parameters for the adc
// calculations. The pede argument don't affect without this
// adc calculation.
//
// exact way:
// UseADCRange(false);
// CalculateADC(cal1);
// (Pedestal subtraction)
// Convert(cal1,cal2);
// if you don't mind the pedestal fluctuation of adc
// this way give more exact result of adc calculation.
// +++ Logs ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// ?? ???. 08: First edited by H.MENJO
// 15 Oct. 08: Added use_adcrange parameter and
// CalculateADC(A2Cal1* cal1) by H.MENJO
// 31 Jan. 10: Added ClassDef and ClassImp to make a manual automanitically by H.MENJO.
// 23 Nov. 10: Modified Convert() and InverseConvert for A2Cal2M
//----------------------------------------------------------------------
#if !defined(__CINT__)
ClassImp(A2Cal1ToCal2);
#endif
#include <iostream>
#include <iomanip>
#include <math.h>
#include <cstring>
using namespace std;
#include "A2Cal2M.h"
const double A2Cal1ToCal2::DEFAULT_THRESHOLD = 3700.;
const char* A2Cal1ToCal2::DEFAULT_ADCRANGE_FILE = "./config/adcrange.dat";
const int A2Cal1ToCal2::ADC_OVERRANGE;
const int A2Cal1ToCal2::SCIFI_OVERRANGE;
// ******* A2Cal1ToCal2::Init ****************************
int A2Cal1ToCal2::Init(){
Initialize();
adcrange.ReadFile((char*)DEFAULT_ADCRANGE_FILE);
return OK;
}
// ******* A2Cal1ToCal2::Initialize **********************
int A2Cal1ToCal2::Initialize(){
defult_pede.clear();
use_adcrange = true;
SetADCRangeThreshold(DEFAULT_THRESHOLD);
return OK;
}
// ******* A2Cal1ToCal2::ReadADCRangeTable ***************
int A2Cal1ToCal2::ReadADCRangeTable(char* file){
adcrange.ReadFile(file);
return OK;
}
// ******* A2Cal1ToCal2::SetADCRangeThreshold ************
int A2Cal1ToCal2::SetADCRangeThreshold(double th){
threshold = th;
adcrange.SetThresold(threshold);
return OK;
}
// ******* A2Cal1ToCal2::Convert *************************
int A2Cal1ToCal2::Convert(A2Cal1* cal1, A2Cal2* cal2, A2Cal1* pede){
if(pede==0){
pede = &defult_pede;
}
// for event informations
cal2->run = cal1->run;
cal2->number = cal1->number;
cal2->gnumber = cal1->gnumber;
cal2->time[0] = cal1->time[0];
cal2->time[1] = cal1->time[1];
// +++++ for Calorimeters +++++
double lowrange=0.;
for(int it=0;it<2;it++){
for(int il=0;il<16;il++){
lowrange = cal1->cal[it][il][0]+pede->cal[it][il][0];
if(use_adcrange==true){
if(lowrange < threshold){
cal2->cal[it][il] = cal1->cal[it][il][0];
}
else{
cal2->cal[it][il]
= adcrange.GetParameter(2+it,il,1)*cal1->cal[it][il][1];
}
}
else{
cal2->cal[it][il] = cal1->cal[it][il][0];
}
}
}
// +++++ for flags +++++
for(int i=0;i<3;i++){ cal2->flag[i] = cal1->flag[i]; }
// +++++ for silicon +++++
for(int il=0;il<4;il++){
for(int ixy=0;ixy<2;ixy++){
for(int istrip=0;istrip<384;istrip++){
for(int isample=0;isample<3;isample++){
cal2->silicon[il][ixy][istrip][isample]
= cal1->silicon[il][ixy][istrip][isample];
}
}
}
}
// ++++++++++++++++++++++++++++++++++++++++++++++
// +++++ IF cal2 is "A2Cal2M" +++++
// ++++++++++++++++++++++++++++++++++++++++++++++
if(strcmp(cal2->ClassName(),"A2Cal2M")==0){
A2Cal2M* cal2m = (A2Cal2M*) cal2;
// for TDC
for(int ich=0;ich<12;ich++){
for(int ihit=0;ihit<16;ihit++){
cal2m->tdc0[ich][ihit] = cal1->tdc0[ich][ihit];
cal2m->tdc0flag[ich][ihit] = cal1->tdc0flag[ich][ihit];
}
}
// for Scaler
for(int i=0;i<16;i++){ cal2m->scl0[i] = cal1->scl0[i];}
// for Counter
for(int i=0;i<35;i++){ cal2m->counter[i] = cal1->counter[i];}
// for FIFO Counter
for(int ich=0;ich<2;ich++){
for(int ib=0;ib<4;ib++){
cal2m->fifocounter[ich][ib]=cal1->fifocounter[ich][ib];
}
}
}
return OK;
}
// ******* A2Cal1ToCal2::InverseConvert ******************
int A2Cal1ToCal2::InverseConvert(A2Cal2* cal2, A2Cal1* cal1, A2Cal1* pede){
if(pede==0){
pede = &defult_pede;
}
// initalize cal1
cal1->clear();
// for event informations
cal1->run = cal2->run;
cal1->number = cal2->number;
cal1->gnumber = cal2->gnumber;
cal1->time[0] = cal2->time[0];
cal1->time[1] = cal2->time[1];
// +++++ for Calorimeters +++++
for(int it=0;it<2;it++){
for(int il=0;il<16;il++){
cal1->cal[it][il][0] = cal2->cal[it][il];
cal1->cal[it][il][1]
= cal2->cal[it][il]/adcrange.GetParameter(it,il,1);
if(use_adcrange==true){
if(cal1->cal[it][il][0]+pede->cal[it][il][0]>threshold){
cal1->cal[it][il][0] = 8000.-pede->cal[it][il][0];
}
if(cal1->cal[it][il][1]+pede->cal[it][il][1]>threshold){
cal1->cal[it][il][1] = 8000.-pede->cal[it][il][1];
}
}
}
}
// +++++ for flags +++++
for(int i=0;i<3;i++){ cal1->flag[i] = cal2->flag[i]; }
// +++++ for silicon +++++
for(int il=0;il<4;il++){
for(int ixy=0;ixy<2;ixy++){
for(int istrip=0;istrip<384;istrip++){
for(int isample=0;isample<3;isample++){
cal1->silicon[il][ixy][istrip][isample]
= cal2->silicon[il][ixy][istrip][isample];
}
}
}
}
// ++++++++++++++++++++++++++++++++++++++++++++++
// +++++ IF cal2 is "A2Cal2M" +++++
// ++++++++++++++++++++++++++++++++++++++++++++++
if(strcmp(cal2->ClassName(),"A2Cal2M")==0){
A2Cal2M* cal2m = (A2Cal2M*) cal2;
// for TDC
for(int ich=0;ich<12;ich++){
for(int ihit=0;ihit<16;ihit++){
cal1->tdc0[ich][ihit] = cal2m->tdc0[ich][ihit];
cal1->tdc0flag[ich][ihit] = cal2m->tdc0flag[ich][ihit];
}
}
// for Scaler
for(int i=0;i<16;i++){ cal1->scl0[i] = cal2m->scl0[i];}
// for Counter
for(int i=0;i<35;i++){ cal1->counter[i] = cal2m->counter[i];}
// for FIFO Counter
for(int ich=0;ich<2;ich++){
for(int ib=0;ib<4;ib++){
cal1->fifocounter[ich][ib] = cal2m->fifocounter[ich][ib];
}
}
}
return OK;
}
int A2Cal1ToCal2::CalculateADC(A2Cal1* cal1){
int iadc=0;
for(int it=0;it<2;it++){
if(it==0) iadc=2;
if(it==1) iadc=3;
for(int il=0;il<16;il++){
if( cal1->cal[it][il][0] > threshold){
cal1->cal[it][il][0]
= adcrange.Get(iadc,il,
cal1->cal[it][il][0],
cal1->cal[it][il][1]);
}
}
}
return OK;
}
int A2Cal1ToCal2::CheckADCOverRange(A2Cal1* cal1){
int nch=0;
for(int it=0;it<2;it++){
for(int il=0;il<16;il++){
if(cal1->cal[it][il][1] > 4096){nch++;}
}
}
return nch;
}
#endif
| [
"hiroaki.menjo@cern.ch"
] | hiroaki.menjo@cern.ch |
9c166924ab6ff1858103118e13898c3ffe52c678 | 772c4d7923e1dede09c108968faddf7840c6690a | /ZekeGame/ZekeGame/Engine/physics/CapsuleCollider.cpp | cee9db7d74e22234a5705e965e7d0904ea989695 | [] | no_license | ZekeZR1/Planet-search-game | 53e915b00c01b6a6fa8bbb14ffab8fd3866420e8 | 505f655a283980a841718e9d0a888d6b92a1cc03 | refs/heads/master | 2022-01-10T20:10:20.329434 | 2019-04-30T07:33:18 | 2019-04-30T07:33:18 | 139,558,202 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 192 | cpp | /*!
* @brief カプセルコライダー。
*/
#include "stdafx.h"
#include "CapsuleCollider.h"
/*!
* @brief デストラクタ。
*/
CapsuleCollider::~CapsuleCollider()
{
delete shape;
}
| [
"hnta3574@gmail.com"
] | hnta3574@gmail.com |
0db631ef12e660bc5db939b33990c264984c24c8 | fc55598fc4258961a869196257d8c3ecd706725a | /a61.cpp | 3bd6b10d9a5667735a273f969ad9573906f8085b | [] | no_license | ishsum/cpp-oops | 03836bfa1579776b9dabf84ec1c05ee5f7a3ef4f | 78be30e469151ebb17dba0067353d8aa5edcedf4 | refs/heads/master | 2020-03-24T04:51:31.547045 | 2018-07-26T16:55:40 | 2018-07-26T16:55:40 | 142,466,972 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 597 | cpp | #include<iostream>
using namespace std;
class figure
{
public:
float radius, height,vol;
virtual void volume()=0;
};
//STUDENT COD HERE
class cone:public figure{
protected:
int R,H;
public:
void input()
{
cin>>R>>H;
}
void volume()
{
float v1;
v1=(3.14*R*R*H)/3;
cout<<v1;
}
};
class cylinder:public figure
{
protected:
int r,h;
public:
void input()
{
cin>>r>>h;
}
void volume()
{
float v;
v=3.14*r*r*h;
cout<<v;
}
};
int main() {
cone ob1;
ob1.input();
ob1.volume();
cylinder ob2;
ob2.input();
ob2.volume();
return 0;
}
| [
"ishanigupta19@gmail.com"
] | ishanigupta19@gmail.com |
ff4336e2bae623608262bcab798d3e8f8c41188f | 29ec15f1afc259dbb73da68c1d97c2ed6ba1fa37 | /FaceTrackServer/src/testApp.h | e9279fc7a757ca923f5b202830c7032f3b1f17e7 | [] | no_license | umhr/FaceTrackServerCPPtoClientAS | 3ca254a16e7545aa4825b29054bca2f3db1dcc6f | 50b6efe61de73612a388fb635fe8deb85928aa81 | refs/heads/master | 2020-06-07T02:54:59.034093 | 2012-11-01T12:48:42 | 2012-11-01T12:48:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 840 | h | #pragma once
#include "ofMain.h"
#include "ofxCvHaarFinder.h"
#include "ofxNetwork.h"
class testApp : public ofBaseApp{
private:
ofVideoGrabber camera;
ofImage image;
ofxCvHaarFinder finder;
int msec;
public:
void setup();
void netWorksetup();
void update();
void netWorkupdate(string senndData);
void draw();
void keyPressed (int key);
void keyReleased(int key);
void mouseMoved(int x, int y );
void mouseDragged(int x, int y, int button);
void mousePressed(int x, int y, int button);
void mouseReleased(int x, int y, int button);
void windowResized(int w, int h);
void dragEvent(ofDragInfo dragInfo);
void gotMessage(ofMessage msg);
ofImage img;
// NetWork
ofxTCPServer TCP;
ofTrueTypeFont mono;
ofTrueTypeFont monosm;
vector <string> storeText;
};
| [
"com@umehara.net"
] | com@umehara.net |
f035ec2116600041245b6a469980a3e8234b6ec3 | f1a257f1233eea91eb2e219efd382ceec5709c71 | /console/console.cpp | 5161303ecb1dc3dd9fc145681be7cc092566268a | [
"MIT"
] | permissive | Elexir-Stefan/ray-usermode | 1c37dbf978d36a463b08f12cd4577cd3d6e19d8f | 9a1c7d773496493482cf2e711fe1808b537db63a | refs/heads/main | 2023-02-15T18:18:17.984239 | 2021-01-12T12:02:14 | 2021-01-12T12:02:14 | 328,964,351 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,644 | cpp | #include <raykernel.h>
#include <exception>
#include <keyboard/keyboard.h>
#include <video/VideoStream.h>
#include <video/KernelVideo.h>
#include "Command.h"
using namespace Kernel;
using namespace std;
using namespace Keyboard;
using namespace Kernel::IPC;
const UINT32 CmdBufferSize = 32;
void InsertString(std::list<String>& list)
{
// Only isert, when last position is not empty
if ((list.empty()) || (strlen(list.back())) > 0)
{
String newString = new char[256];
memset(newString, 0, 256);
list.push_back(newString);
}
}
void DisplayString(String s)
{
KernelVideo::WriteUnformattedString("\r> ");
KernelVideo::WriteUnformattedString("\r>");
KernelVideo::WriteUnformattedString(s);
}
std::list<String>::iterator DeleteUnused(std::list<String>::iterator it, std::list<String>& list)
{
if (strlen(*it) == 0)
{
delete *it;
return list.erase(it);
} else {
return it;
}
}
void GetUserInput()
{
KeyEvent keyEvent = KeyEvent();
std::list<String> commandBuffer;
InsertString(commandBuffer);
std::list<String>::iterator it = commandBuffer.begin();
UINT32 strPos = 0;
while(true)
{
KeyState keyState = keyEvent.GetKey();
if (keyState.ContainsKey)
{
Key key = keyState.KeyOnly;
// Arrow keys?
if (key.isUpArrow || key.isDownArrow)
{
if ((key.isUpArrow) && (*it != commandBuffer.front()))
{
// there is an element before this, go back one element
//it = DeleteUnused(it, commandBuffer);
it--;
}
if ((key.isDownArrow) && (*it != commandBuffer.back()))
{
// there is an element after this, advance one element
//it = DeleteUnused(it, commandBuffer);
it++;
}
strPos = strlen(*it);
DisplayString(*it);
}
else if (key.IsReturn)
{
// accept string
if (strlen(*it) > 0)
{
kout << VideoStream::endl;
Command::ExecuteCommand(*it);
InsertString(commandBuffer);
strPos = 0;
it = commandBuffer.end();
it--;
}
kout << VideoStream::endl;
DisplayString(*it);
}
else if (key.IsBackspace)
{
if (strPos > 0)
{
(*it)[--strPos] = 0;
DisplayString(*it);
}
}
else if (key.IsCharacter)
{
// add the character to the string
(*it)[strPos++] = key.RawCharacter;
DisplayString(*it);
}
// else do nothing ...
}
}
}
int UserProgramEntry(const char *arguments)
{
// Register our connection
Communication::Register("Console", "Basic shell application");
kout << "NURNware Console" << VideoStream::endl;
kout << ">_";
GetUserInput();
return 0;
}
| [
"stefan@elexir.eu"
] | stefan@elexir.eu |
e1d059b8f7bb1cc0d179fa6e17431f07c131d3bb | 0f764a7dd57533e0685e2d907ceff67e2bd65af3 | /dlls/hl2_dll/npc_manhack.cpp | da7865079d067850ecf590a787fc9b5cbe8f02bb | [
"MIT"
] | permissive | sswires/ham-and-jam | 86754d5a48a9745f86763e7150a2091e2d71f556 | 25121bf6302d81e68207706ae5c313c0c84ffc78 | refs/heads/master | 2020-05-17T16:21:23.920987 | 2015-01-06T13:01:09 | 2015-01-06T13:01:09 | 28,862,333 | 3 | 2 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 93,830 | cpp | //========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#include "cbase.h"
#include "soundenvelope.h"
#include "npc_manhack.h"
#include "ai_default.h"
#include "ai_node.h"
#include "ai_navigator.h"
#include "ai_pathfinder.h"
#include "ai_moveprobe.h"
#include "ai_memory.h"
#include "ai_squad.h"
#include "ai_route.h"
#include "explode.h"
#include "basegrenade_shared.h"
#include "ndebugoverlay.h"
#include "decals.h"
#include "gib.h"
#include "game.h"
#include "ai_interactions.h"
#include "IEffects.h"
#include "vstdlib/random.h"
#include "engine/IEngineSound.h"
#include "movevars_shared.h"
#include "npcevent.h"
#include "props.h"
#include "te_effect_dispatch.h"
#include "ai_squadslot.h"
#include "world.h"
#include "smoke_trail.h"
#include "func_break.h"
#include "physics_impact_damage.h"
#include "weapon_physcannon.h"
#include "physics_prop_ragdoll.h"
#include "soundent.h"
#include "ammodef.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
// When the engine is running and the manhack is operating under power
// we don't let gravity affect him.
#define MANHACK_GRAVITY 0.000
#define MANHACK_GIB_COUNT 5
#define MANHACK_INGORE_WATER_DIST 384
// Sound stuff
#define MANHACK_PITCH_DIST1 512
#define MANHACK_MIN_PITCH1 (100)
#define MANHACK_MAX_PITCH1 (160)
#define MANHACK_WATER_PITCH1 (85)
#define MANHACK_VOLUME1 0.55
#define MANHACK_PITCH_DIST2 400
#define MANHACK_MIN_PITCH2 (85)
#define MANHACK_MAX_PITCH2 (190)
#define MANHACK_WATER_PITCH2 (90)
#define MANHACK_NOISEMOD_HIDE 5000
#define MANHACK_BODYGROUP_BLADE 1
#define MANHACK_BODYGROUP_BLUR 2
#define MANHACK_BODYGROUP_OFF 0
#define MANHACK_BODYGROUP_ON 1
// ANIMATION EVENTS
#define MANHACK_AE_START_ENGINE 50
#define MANHACK_AE_DONE_UNPACKING 51
#define MANHACK_AE_OPEN_BLADE 52
//#define MANHACK_GLOW_SPRITE "sprites/laserdot.vmt"
#define MANHACK_GLOW_SPRITE "sprites/glow1.vmt"
#define MANHACK_CHARGE_MIN_DIST 200
ConVar sk_manhack_health( "sk_manhack_health","0");
ConVar sk_manhack_melee_dmg( "sk_manhack_melee_dmg","0");
ConVar sk_manhack_v2( "sk_manhack_v2","1");
extern void SpawnBlood(Vector vecSpot, const Vector &vAttackDir, int bloodColor, float flDamage);
extern float GetFloorZ(const Vector &origin);
//-----------------------------------------------------------------------------
// Private activities.
//-----------------------------------------------------------------------------
Activity ACT_MANHACK_UNPACK;
//-----------------------------------------------------------------------------
// Manhack Conditions
//-----------------------------------------------------------------------------
enum ManhackConditions
{
COND_MANHACK_START_ATTACK = LAST_SHARED_CONDITION, // We are able to do a bombing run on the current enemy.
};
//-----------------------------------------------------------------------------
// Manhack schedules.
//-----------------------------------------------------------------------------
enum ManhackSchedules
{
SCHED_MANHACK_ATTACK_HOVER = LAST_SHARED_SCHEDULE,
SCHED_MANHACK_DEPLOY,
SCHED_MANHACK_REGROUP,
SCHED_MANHACK_SWARM_IDLE,
SCHED_MANHACK_SWARM,
SCHED_MANHACK_SWARM_FAILURE,
};
//-----------------------------------------------------------------------------
// Manhack tasks.
//-----------------------------------------------------------------------------
enum ManhackTasks
{
TASK_MANHACK_HOVER = LAST_SHARED_TASK,
TASK_MANHACK_UNPACK,
TASK_MANHACK_FIND_SQUAD_CENTER,
TASK_MANHACK_FIND_SQUAD_MEMBER,
TASK_MANHACK_MOVEAT_SAVEPOSITION,
};
BEGIN_DATADESC( CNPC_Manhack )
DEFINE_FIELD( m_vForceVelocity, FIELD_VECTOR),
DEFINE_FIELD( m_vTargetBanking, FIELD_VECTOR),
DEFINE_FIELD( m_vForceMoveTarget, FIELD_POSITION_VECTOR),
DEFINE_FIELD( m_fForceMoveTime, FIELD_TIME),
DEFINE_FIELD( m_vSwarmMoveTarget, FIELD_POSITION_VECTOR),
DEFINE_FIELD( m_fSwarmMoveTime, FIELD_TIME),
DEFINE_FIELD( m_fEnginePowerScale, FIELD_FLOAT),
DEFINE_FIELD( m_flNextEngineSoundTime, FIELD_TIME),
DEFINE_FIELD( m_flEngineStallTime, FIELD_TIME),
DEFINE_FIELD( m_flNextBurstTime, FIELD_TIME ),
DEFINE_FIELD( m_flWaterSuspendTime, FIELD_TIME),
DEFINE_FIELD( m_nLastSpinSound, FIELD_INTEGER ),
// Death
DEFINE_FIELD( m_fSparkTime, FIELD_TIME),
DEFINE_FIELD( m_fSmokeTime, FIELD_TIME),
DEFINE_FIELD( m_bDirtyPitch, FIELD_BOOLEAN ),
DEFINE_FIELD( m_bGib, FIELD_BOOLEAN),
DEFINE_FIELD( m_bHeld, FIELD_BOOLEAN),
DEFINE_FIELD( m_bHackedByAlyx, FIELD_BOOLEAN),
DEFINE_FIELD( m_vecLoiterPosition, FIELD_POSITION_VECTOR),
DEFINE_FIELD( m_fTimeNextLoiterPulse, FIELD_TIME),
DEFINE_FIELD( m_flBumpSuppressTime, FIELD_TIME ),
DEFINE_FIELD( m_bBladesActive, FIELD_BOOLEAN),
DEFINE_FIELD( m_flBladeSpeed, FIELD_FLOAT),
DEFINE_FIELD( m_hSmokeTrail, FIELD_EHANDLE),
// DEFINE_FIELD( m_pLightGlow, FIELD_CLASSPTR ),
// DEFINE_FIELD( m_pEyeGlow, FIELD_CLASSPTR ),
DEFINE_FIELD( m_iPanel1, FIELD_INTEGER ),
DEFINE_FIELD( m_iPanel2, FIELD_INTEGER ),
DEFINE_FIELD( m_iPanel3, FIELD_INTEGER ),
DEFINE_FIELD( m_iPanel4, FIELD_INTEGER ),
DEFINE_FIELD( m_nLastWaterLevel, FIELD_INTEGER ),
DEFINE_FIELD( m_bDoSwarmBehavior, FIELD_BOOLEAN ),
DEFINE_FIELD( m_nEnginePitch1, FIELD_INTEGER ),
DEFINE_FIELD( m_flEnginePitch1Time, FIELD_TIME ),
DEFINE_FIELD( m_nEnginePitch2, FIELD_INTEGER ),
DEFINE_FIELD( m_flEnginePitch2Time, FIELD_TIME ),
// Physics Influence
DEFINE_FIELD( m_hPhysicsAttacker, FIELD_EHANDLE ),
DEFINE_FIELD( m_flLastPhysicsInfluenceTime, FIELD_TIME ),
DEFINE_FIELD( m_flBurstDuration, FIELD_FLOAT ),
DEFINE_FIELD( m_vecBurstDirection, FIELD_VECTOR ),
DEFINE_FIELD( m_bShowingHostile, FIELD_BOOLEAN ),
// Function Pointers
DEFINE_INPUTFUNC( FIELD_VOID, "DisableSwarm", InputDisableSwarm ),
DEFINE_INPUTFUNC( FIELD_VOID, "Unpack", InputUnpack ),
DEFINE_ENTITYFUNC( CrashTouch ),
DEFINE_BASENPCINTERACTABLE_DATADESC(),
END_DATADESC()
LINK_ENTITY_TO_CLASS( npc_manhack, CNPC_Manhack );
IMPLEMENT_SERVERCLASS_ST(CNPC_Manhack, DT_NPC_Manhack)
SendPropIntWithMinusOneFlag (SENDINFO(m_nEnginePitch1), 8 ),
SendPropFloat(SENDINFO(m_flEnginePitch1Time), 0, SPROP_NOSCALE),
SendPropIntWithMinusOneFlag(SENDINFO(m_nEnginePitch2), 8 )
END_SEND_TABLE()
//------------------------------------------------------------------------------
// Purpose :
// Input :
// Output :
//------------------------------------------------------------------------------
CNPC_Manhack::CNPC_Manhack()
{
#ifdef _DEBUG
m_vForceMoveTarget.Init();
m_vSwarmMoveTarget.Init();
m_vTargetBanking.Init();
m_vForceVelocity.Init();
#endif
m_bDirtyPitch = true;
m_nLastWaterLevel = 0;
m_nEnginePitch1 = -1;
m_nEnginePitch2 = -1;
m_flEnginePitch1Time = 0;
m_flEnginePitch1Time = 0;
m_bDoSwarmBehavior = true;
m_flBumpSuppressTime = 0;
}
//------------------------------------------------------------------------------
// Purpose:
//------------------------------------------------------------------------------
CNPC_Manhack::~CNPC_Manhack()
{
}
//-----------------------------------------------------------------------------
// Purpose: Indicates this NPC's place in the relationship table.
//-----------------------------------------------------------------------------
Class_T CNPC_Manhack::Classify(void)
{
return (m_bHeld||m_bHackedByAlyx) ? CLASS_PLAYER_ALLY : CLASS_MANHACK;
}
//-----------------------------------------------------------------------------
// Purpose: Turns the manhack into a physics corpse when dying.
//-----------------------------------------------------------------------------
void CNPC_Manhack::Event_Dying(void)
{
DestroySmokeTrail();
SetHullSizeNormal();
BaseClass::Event_Dying();
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CNPC_Manhack::GatherConditions()
{
BaseClass::GatherConditions();
if( IsLoitering() && GetEnemy() )
{
StopLoitering();
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Input :
// Output :
//-----------------------------------------------------------------------------
void CNPC_Manhack::PrescheduleThink( void )
{
BaseClass::PrescheduleThink();
UpdatePanels();
if( m_flWaterSuspendTime > gpGlobals->curtime )
{
// Stuck in water!
// Reduce engine power so that the manhack lifts out of the water slowly.
m_fEnginePowerScale = 0.75;
}
// ----------------------------------------
// Am I in water?
// ----------------------------------------
if ( GetWaterLevel() > 0 )
{
if( m_nLastWaterLevel == 0 )
{
Splash( WorldSpaceCenter() );
}
if( IsAlive() )
{
// If I've been out of water for 2 seconds or more, I'm eligible to be stuck in water again.
if( gpGlobals->curtime - m_flWaterSuspendTime > 2.0 )
{
m_flWaterSuspendTime = gpGlobals->curtime + 1.0;
}
}
}
else
{
if( m_nLastWaterLevel != 0 )
{
Splash( WorldSpaceCenter() );
}
}
m_nLastWaterLevel = GetWaterLevel();
}
//-----------------------------------------------------------------------------
// Purpose:
// Input :
// Output :
//-----------------------------------------------------------------------------
void CNPC_Manhack::TraceAttack( const CTakeDamageInfo &info, const Vector &vecDir, trace_t *ptr )
{
g_vecAttackDir = vecDir;
if ( info.GetDamageType() & DMG_BULLET)
{
g_pEffects->Ricochet(ptr->endpos,ptr->plane.normal);
}
if ( info.GetDamageType() & DMG_CLUB )
{
// Clubbed!
// UTIL_Smoke(GetAbsOrigin(), random->RandomInt(10, 15), 10);
g_pEffects->Sparks( ptr->endpos, 1, 1, &ptr->plane.normal );
}
BaseClass::TraceAttack( info, vecDir, ptr );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNPC_Manhack::DeathSound( const CTakeDamageInfo &info )
{
StopSound("NPC_Manhack.Stunned");
CPASAttenuationFilter filter2( this, "NPC_Manhack.Die" );
EmitSound( filter2, entindex(), "NPC_Manhack.Die" );
}
//-----------------------------------------------------------------------------
// Purpose:
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CNPC_Manhack::ShouldGib( const CTakeDamageInfo &info )
{
return ( m_bGib );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input :
// Output :
//-----------------------------------------------------------------------------
void CNPC_Manhack::Event_Killed( const CTakeDamageInfo &info )
{
// turn off the blur!
SetBodygroup( MANHACK_BODYGROUP_BLUR, MANHACK_BODYGROUP_OFF );
// Sparks
for (int i = 0; i < 3; i++)
{
Vector sparkPos = GetAbsOrigin();
sparkPos.x += random->RandomFloat(-12,12);
sparkPos.y += random->RandomFloat(-12,12);
sparkPos.z += random->RandomFloat(-12,12);
g_pEffects->Sparks( sparkPos, 2 );
}
// Light
CBroadcastRecipientFilter filter;
te->DynamicLight( filter, 0.0, &GetAbsOrigin(), 255, 180, 100, 0, 100, 0.1, 0 );
if ( m_nEnginePitch1 < 0 )
{
// Probably this manhack was killed immediately after spawning. Turn the sound
// on right now so that we can pitch it up for the crash!
SoundInit();
}
// Always gib when clubbed or blasted or crushed, or just randomly
if ( ( info.GetDamageType() & (DMG_CLUB|DMG_CRUSH|DMG_BLAST) ) || ( random->RandomInt( 0, 1 ) ) )
{
m_bGib = true;
}
else
{
m_bGib = false;
//FIXME: These don't stay with the ragdolls currently -- jdw
// Long fadeout on the sprites!!
KillSprites( 0.0f );
}
BaseClass::Event_Killed( info );
}
void CNPC_Manhack::HitPhysicsObject( CBaseEntity *pOther )
{
IPhysicsObject *pOtherPhysics = pOther->VPhysicsGetObject();
Vector pos, posOther;
// Put the force on the line between the manhack origin and hit object origin
VPhysicsGetObject()->GetPosition( &pos, NULL );
pOtherPhysics->GetPosition( &posOther, NULL );
Vector dir = posOther - pos;
VectorNormalize(dir);
// size/2 is approx radius
pos += dir * WorldAlignSize().x * 0.5;
Vector cross;
// UNDONE: Use actual manhack up vector so the fake blade is
// in the right plane?
// Get a vector in the x/y plane in the direction of blade spin (clockwise)
CrossProduct( dir, Vector(0,0,1), cross );
VectorNormalize( cross );
// force is a 30kg object going 100 in/s
pOtherPhysics->ApplyForceOffset( cross * 30 * 100, pos );
}
//-----------------------------------------------------------------------------
// Take damage from being thrown by a physcannon
//-----------------------------------------------------------------------------
#define MANHACK_SMASH_SPEED 500.0 // How fast a manhack must slam into something to take full damage
void CNPC_Manhack::TakeDamageFromPhyscannon( CBasePlayer *pPlayer )
{
CTakeDamageInfo info;
info.SetDamageType( DMG_GENERIC );
info.SetInflictor( this );
info.SetAttacker( pPlayer );
info.SetDamagePosition( GetAbsOrigin() );
info.SetDamageForce( Vector( 1.0, 1.0, 1.0 ) );
// Convert velocity into damage.
Vector vel;
VPhysicsGetObject()->GetVelocity( &vel, NULL );
float flSpeed = vel.Length();
float flFactor = flSpeed / MANHACK_SMASH_SPEED;
// Clamp. Don't inflict negative damage or massive damage!
flFactor = clamp( flFactor, 0.0f, 2.0f );
float flDamage = m_iMaxHealth * flFactor;
#if 0
Msg("Doing %f damage for %f speed!\n", flDamage, flSpeed );
#endif
info.SetDamage( flDamage );
TakeDamage( info );
}
//-----------------------------------------------------------------------------
// Take damage from a vehicle; it's like a really big crowbar
//-----------------------------------------------------------------------------
void CNPC_Manhack::TakeDamageFromVehicle( int index, gamevcollisionevent_t *pEvent )
{
// Use the vehicle velocity to determine the damage
int otherIndex = !index;
CBaseEntity *pOther = pEvent->pEntities[otherIndex];
float flSpeed = pEvent->preVelocity[ otherIndex ].Length();
flSpeed = clamp( flSpeed, 300.0f, 600.0f );
float flDamage = SimpleSplineRemapVal( flSpeed, 300.0f, 600.0f, 0.0f, 1.0f );
if ( flDamage == 0.0f )
return;
flDamage *= 20.0f;
Vector damagePos;
pEvent->pInternalData->GetContactPoint( damagePos );
Vector damageForce = 2.0f * pEvent->postVelocity[index] * pEvent->pObjects[index]->GetMass();
if ( damageForce == vec3_origin )
{
// This can happen if this entity is a func_breakable, and can't move.
// Use the velocity of the entity that hit us instead.
damageForce = 2.0f * pEvent->postVelocity[!index] * pEvent->pObjects[!index]->GetMass();
}
Assert( damageForce != vec3_origin );
CTakeDamageInfo dmgInfo( pOther, pOther, damageForce, damagePos, flDamage, DMG_CRUSH );
TakeDamage( dmgInfo );
}
//-----------------------------------------------------------------------------
// Take damage from combine ball
//-----------------------------------------------------------------------------
void CNPC_Manhack::TakeDamageFromPhysicsImpact( int index, gamevcollisionevent_t *pEvent )
{
CBaseEntity *pHitEntity = pEvent->pEntities[!index];
// NOTE: Bypass the normal impact energy scale here.
//float flDamageScale = PlayerHasMegaPhysCannon() ? 10.0f : 1.0f;
float flDamageScale = 1.0f;
int damageType = 0;
float damage = CalculateDefaultPhysicsDamage( index, pEvent, flDamageScale, true, damageType );
if ( damage == 0 )
return;
Vector damagePos;
pEvent->pInternalData->GetContactPoint( damagePos );
Vector damageForce = pEvent->postVelocity[index] * pEvent->pObjects[index]->GetMass();
if ( damageForce == vec3_origin )
{
// This can happen if this entity is motion disabled, and can't move.
// Use the velocity of the entity that hit us instead.
damageForce = pEvent->postVelocity[!index] * pEvent->pObjects[!index]->GetMass();
}
// FIXME: this doesn't pass in who is responsible if some other entity "caused" this collision
PhysCallbackDamage( this, CTakeDamageInfo( pHitEntity, pHitEntity, damageForce, damagePos, damage, damageType ), *pEvent, index );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
#define MANHACK_SMASH_TIME 0.35 // How long after being thrown from a physcannon that a manhack is eligible to die from impact
void CNPC_Manhack::VPhysicsCollision( int index, gamevcollisionevent_t *pEvent )
{
BaseClass::VPhysicsCollision( index, pEvent );
// Take no impact damage while being carried.
if ( IsHeldByPhyscannon() )
return;
// Wake us up
if ( m_spawnflags & SF_MANHACK_PACKED_UP )
{
SetCondition( COND_LIGHT_DAMAGE );
}
int otherIndex = !index;
CBaseEntity *pHitEntity = pEvent->pEntities[otherIndex];
CBasePlayer *pPlayer = HasPhysicsAttacker( MANHACK_SMASH_TIME );
if( pPlayer )
{
if (!pHitEntity)
{
TakeDamageFromPhyscannon( pPlayer );
StopBurst( true );
return;
}
// Don't take damage from NPCs or server ragdolls killed by the manhack
CRagdollProp *pRagdollProp = dynamic_cast<CRagdollProp*>(pHitEntity);
if (!pHitEntity->IsNPC() && (!pRagdollProp || pRagdollProp->GetKiller() != this))
{
TakeDamageFromPhyscannon( pPlayer );
StopBurst( true );
return;
}
}
if ( pHitEntity )
{
// It can take physics damage if it rams into a vehicle
if ( pHitEntity->GetServerVehicle() )
{
TakeDamageFromVehicle( index, pEvent );
}
else if ( pHitEntity->HasPhysicsAttacker( 0.5f ) )
{
// It also can take physics damage from things thrown by the player.
TakeDamageFromPhysicsImpact( index, pEvent );
}
else if ( FClassnameIs( pHitEntity, "prop_combine_ball" ) )
{
// It also can take physics damage from a combine ball.
TakeDamageFromPhysicsImpact( index, pEvent );
}
else if ( m_iHealth <= 0 )
{
TakeDamageFromPhysicsImpact( index, pEvent );
}
StopBurst( true );
}
}
void CNPC_Manhack::VPhysicsShadowCollision( int index, gamevcollisionevent_t *pEvent )
{
int otherIndex = !index;
CBaseEntity *pOther = pEvent->pEntities[otherIndex];
if ( pOther->GetMoveType() == MOVETYPE_VPHYSICS )
{
HitPhysicsObject( pOther );
}
BaseClass::VPhysicsShadowCollision( index, pEvent );
}
//-----------------------------------------------------------------------------
// Purpose: Manhack is out of control! (dying) Just explode as soon as you touch anything!
// Input :
// Output :
//-----------------------------------------------------------------------------
void CNPC_Manhack::CrashTouch( CBaseEntity *pOther )
{
CTakeDamageInfo info( GetWorldEntity(), GetWorldEntity(), 25, DMG_CRUSH );
CorpseGib( info );
}
//-----------------------------------------------------------------------------
// Create smoke trail!
//-----------------------------------------------------------------------------
void CNPC_Manhack::CreateSmokeTrail()
{
if ( HasSpawnFlags( SF_MANHACK_NO_DAMAGE_EFFECTS ) )
return;
if ( m_hSmokeTrail != NULL )
return;
SmokeTrail *pSmokeTrail = SmokeTrail::CreateSmokeTrail();
if( !pSmokeTrail )
return;
pSmokeTrail->m_SpawnRate = 20;
pSmokeTrail->m_ParticleLifetime = 0.5f;
pSmokeTrail->m_StartSize = 8;
pSmokeTrail->m_EndSize = 32;
pSmokeTrail->m_SpawnRadius = 5;
pSmokeTrail->m_MinSpeed = 15;
pSmokeTrail->m_MaxSpeed = 25;
pSmokeTrail->m_StartColor.Init( 0.4f, 0.4f, 0.4f );
pSmokeTrail->m_EndColor.Init( 0, 0, 0 );
pSmokeTrail->SetLifetime(-1);
pSmokeTrail->FollowEntity(this);
m_hSmokeTrail = pSmokeTrail;
}
void CNPC_Manhack::DestroySmokeTrail()
{
if ( m_hSmokeTrail.Get() )
{
UTIL_Remove( m_hSmokeTrail );
m_hSmokeTrail = NULL;
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Input :
// Output :
//-----------------------------------------------------------------------------
int CNPC_Manhack::OnTakeDamage_Alive( const CTakeDamageInfo &info )
{
// Hafta make a copy of info cause we might need to scale damage.(sjb)
CTakeDamageInfo tdInfo = info;
if( tdInfo.GetAmmoType() == GetAmmoDef()->Index("SniperRound") )
{
// Unfortunately, this is the easiest way to stop the sniper killing manhacks in one shot.
tdInfo.SetDamage( m_iMaxHealth>>1 );
}
if (info.GetDamageType() & DMG_PHYSGUN )
{
m_flBladeSpeed = 20.0;
// respond to physics
// FIXME: shouldn't this happen in a base class? Anyway to prevent it from happening twice?
VPhysicsTakeDamage( info );
// reduce damage to nothing
tdInfo.SetDamage( 1.0 );
StopBurst( true );
}
else if ( info.GetDamageType() & DMG_AIRBOAT )
{
// Airboat gun kills me instantly.
tdInfo.SetDamage( GetHealth() );
}
else if (info.GetDamageType() & DMG_CLUB)
{
// Being hit by a club means a couple of things:
//
// -I'm going to be knocked away from the person that clubbed me.
// if fudging this vector a little bit could help me slam into a physics object,
// then make that adjustment. This is a simple heuristic. The manhack will be
// directed towards the physics object that is closest to g_vecAttackDir
//
// -Take 150% damage from club attacks. This makes crowbar duels take two hits.
tdInfo.ScaleDamage( 1.50 );
#define MANHACK_PHYS_SEARCH_SIZE 64
#define MANHACK_PHYSICS_SEARCH_RADIUS 128
CBaseEntity *pList[ MANHACK_PHYS_SEARCH_SIZE ];
Vector attackDir = info.GetDamageForce();
VectorNormalize( attackDir );
Vector testCenter = GetAbsOrigin() + ( attackDir * MANHACK_PHYSICS_SEARCH_RADIUS );
Vector vecDelta( MANHACK_PHYSICS_SEARCH_RADIUS, MANHACK_PHYSICS_SEARCH_RADIUS, MANHACK_PHYSICS_SEARCH_RADIUS );
int count = UTIL_EntitiesInBox( pList, MANHACK_PHYS_SEARCH_SIZE, testCenter - vecDelta, testCenter + vecDelta, 0 );
Vector vecBestDir = g_vecAttackDir;
float flBestDot = 0.90;
IPhysicsObject *pPhysObj;
int i;
for( i = 0 ; i < count ; i++ )
{
pPhysObj = pList[ i ]->VPhysicsGetObject();
if( !pPhysObj || pPhysObj->GetMass() > 200 )
{
// Not physics.
continue;
}
Vector center = pList[ i ]->WorldSpaceCenter();
Vector vecDirToObject;
VectorSubtract( center, WorldSpaceCenter(), vecDirToObject );
VectorNormalize( vecDirToObject );
float flDot;
flDot = DotProduct( g_vecAttackDir, vecDirToObject );
if( flDot > flBestDot )
{
flBestDot = flDot;
vecBestDir = vecDirToObject;
}
}
tdInfo.SetDamageForce( vecBestDir * info.GetDamage() * 200 );
// FIXME: shouldn't this happen in a base class? Anyway to prevent it from happening twice?
VPhysicsTakeDamage( tdInfo );
// Force us away (no more residual speed hits!)
m_vForceVelocity = vecBestDir * info.GetDamage() * 0.5f;
m_flBladeSpeed = 10.0;
EmitSound( "NPC_Manhack.Bat" );
// tdInfo.SetDamage( 1.0 );
m_flEngineStallTime = gpGlobals->curtime + 0.5f;
StopBurst( true );
}
else
{
m_flBladeSpeed = 20.0;
Vector vecDamageDir = tdInfo.GetDamageForce();
VectorNormalize( vecDamageDir );
m_flEngineStallTime = gpGlobals->curtime + 0.25f;
m_vForceVelocity = vecDamageDir * info.GetDamage() * 20.0f;
tdInfo.SetDamageForce( tdInfo.GetDamageForce() * 20 );
VPhysicsTakeDamage( info );
}
int nRetVal = BaseClass::OnTakeDamage_Alive( tdInfo );
if ( nRetVal )
{
if ( m_iHealth > 0 )
{
if ( info.GetDamageType() & DMG_CLUB )
{
SetEyeState( MANHACK_EYE_STATE_STUNNED );
}
if ( m_iHealth <= ( m_iMaxHealth / 2 ) )
{
CreateSmokeTrail();
}
}
else
{
DestroySmokeTrail();
}
}
return nRetVal;
}
//------------------------------------------------------------------------------
// Purpose:
//------------------------------------------------------------------------------
bool CNPC_Manhack::CorpseGib( const CTakeDamageInfo &info )
{
Vector vecGibVelocity;
AngularImpulse vecGibAVelocity;
if( info.GetDamageType() & DMG_CLUB )
{
// If clubbed to death, break apart before the attacker's eyes!
vecGibVelocity = g_vecAttackDir * -150;
vecGibAVelocity.x = random->RandomFloat( -2000, 2000 );
vecGibAVelocity.y = random->RandomFloat( -2000, 2000 );
vecGibAVelocity.z = random->RandomFloat( -2000, 2000 );
}
else
{
// Shower the pieces with my velocity.
vecGibVelocity = GetCurrentVelocity();
vecGibAVelocity.x = random->RandomFloat( -500, 500 );
vecGibAVelocity.y = random->RandomFloat( -500, 500 );
vecGibAVelocity.z = random->RandomFloat( -500, 500 );
}
PropBreakableCreateAll( GetModelIndex(), NULL, GetAbsOrigin(), GetAbsAngles(), vecGibVelocity, vecGibAVelocity, 1.0, 60, COLLISION_GROUP_DEBRIS );
RemoveDeferred();
KillSprites( 0.0f );
return true;
}
//-----------------------------------------------------------------------------
// Purpose: Explode the manhack if it's damaged while crashing
// Input :
// Output :
//-----------------------------------------------------------------------------
int CNPC_Manhack::OnTakeDamage_Dying( const CTakeDamageInfo &info )
{
// Ignore damage for the first 1 second of crashing behavior.
// If we don't do this, manhacks always just explode under
// sustained fire.
VPhysicsTakeDamage( info );
return 0;
}
//-----------------------------------------------------------------------------
// Turn on the engine sound if we're gagged!
//-----------------------------------------------------------------------------
void CNPC_Manhack::OnStateChange( NPC_STATE OldState, NPC_STATE NewState )
{
if( m_vNoiseMod.z == MANHACK_NOISEMOD_HIDE && !(m_spawnflags & SF_NPC_WAIT_FOR_SCRIPT) && !(m_spawnflags & SF_MANHACK_PACKED_UP) )
{
// This manhack should get a normal noisemod now.
float flNoiseMod = random->RandomFloat( 1.7, 2.3 );
// Just bob up and down.
SetNoiseMod( 0, 0, flNoiseMod );
}
if( NewState != NPC_STATE_IDLE && (m_spawnflags & SF_NPC_GAG) && (m_nEnginePitch1 < 0) )
{
m_spawnflags &= ~SF_NPC_GAG;
SoundInit();
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : Type -
//-----------------------------------------------------------------------------
void CNPC_Manhack::HandleAnimEvent( animevent_t *pEvent )
{
Vector vecNewVelocity;
switch( pEvent->event )
{
case MANHACK_AE_START_ENGINE:
StartEye();
StartEngine( true );
m_spawnflags &= ~SF_MANHACK_PACKED_UP;
// No bursts until fully unpacked!
m_flNextBurstTime = gpGlobals->curtime + FLT_MAX;
break;
case MANHACK_AE_DONE_UNPACKING:
m_flNextBurstTime = gpGlobals->curtime + 2.0;
break;
case MANHACK_AE_OPEN_BLADE:
m_bBladesActive = true;
break;
default:
BaseClass::HandleAnimEvent( pEvent );
break;
}
}
//-----------------------------------------------------------------------------
// Purpose: Returns whether or not the given activity would translate to flying.
//-----------------------------------------------------------------------------
bool CNPC_Manhack::IsFlyingActivity( Activity baseAct )
{
return ((baseAct == ACT_FLY || baseAct == ACT_IDLE || baseAct == ACT_RUN || baseAct == ACT_WALK) && m_bBladesActive);
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : Type -
//-----------------------------------------------------------------------------
Activity CNPC_Manhack::NPC_TranslateActivity( Activity baseAct )
{
if (IsFlyingActivity( baseAct ))
{
return (Activity)ACT_FLY;
}
return BaseClass::NPC_TranslateActivity( baseAct );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : Type -
//-----------------------------------------------------------------------------
int CNPC_Manhack::TranslateSchedule( int scheduleType )
{
// Fail-safe for deployment if packed up and interrupted
if ( m_spawnflags & SF_MANHACK_PACKED_UP )
{
if ( scheduleType != SCHED_WAIT_FOR_SCRIPT )
return SCHED_MANHACK_DEPLOY;
}
switch ( scheduleType )
{
case SCHED_MELEE_ATTACK1:
{
return SCHED_MANHACK_ATTACK_HOVER;
break;
}
case SCHED_BACK_AWAY_FROM_ENEMY:
{
return SCHED_MANHACK_REGROUP;
break;
}
case SCHED_CHASE_ENEMY:
{
// If we're waiting for our next attack opportunity, just swarm
if ( m_flNextBurstTime > gpGlobals->curtime )
{
return SCHED_MANHACK_SWARM;
}
if ( !m_bDoSwarmBehavior || OccupyStrategySlotRange( SQUAD_SLOT_ATTACK1, SQUAD_SLOT_ATTACK2 ) )
{
return SCHED_CHASE_ENEMY;
}
else
{
return SCHED_MANHACK_SWARM;
}
}
case SCHED_COMBAT_FACE:
{
// Don't care about facing enemy, handled automatically
return TranslateSchedule( SCHED_CHASE_ENEMY );
break;
}
case SCHED_WAKE_ANGRY:
{
if( m_spawnflags & SF_MANHACK_PACKED_UP )
{
return SCHED_MANHACK_DEPLOY;
}
else
{
return TranslateSchedule( SCHED_CHASE_ENEMY );
}
break;
}
case SCHED_IDLE_STAND:
case SCHED_ALERT_STAND:
case SCHED_ALERT_FACE:
{
if ( m_pSquad && m_bDoSwarmBehavior )
{
return SCHED_MANHACK_SWARM_IDLE;
}
else
{
return BaseClass::TranslateSchedule(scheduleType);
}
}
case SCHED_CHASE_ENEMY_FAILED:
{
// Relentless bastard! Doesn't fail (fail not valid anyway)
return TranslateSchedule( SCHED_CHASE_ENEMY );
break;
}
}
return BaseClass::TranslateSchedule(scheduleType);
}
#define MAX_LOITER_DIST_SQR 144 // (12 inches sqr)
void CNPC_Manhack::Loiter()
{
//NDebugOverlay::Line( GetAbsOrigin(), m_vecLoiterPosition, 255, 255, 255, false, 0.1 );
// Friendly manhack is loitering.
if( !m_bHeld )
{
float distSqr = m_vecLoiterPosition.DistToSqr(GetAbsOrigin());
if( distSqr > MAX_LOITER_DIST_SQR )
{
Vector vecDir = m_vecLoiterPosition - GetAbsOrigin();
VectorNormalize( vecDir );
// Move back to our loiter position.
if( gpGlobals->curtime > m_fTimeNextLoiterPulse )
{
// Apply a pulse of force if allowed right now.
if( distSqr > MAX_LOITER_DIST_SQR * 4.0f )
{
//Msg("Big Pulse\n");
m_vForceVelocity = vecDir * 12.0f;
}
else
{
//Msg("Small Pulse\n");
m_vForceVelocity = vecDir * 6.0f;
}
m_fTimeNextLoiterPulse = gpGlobals->curtime + 1.0f;
}
else
{
m_vForceVelocity = vec3_origin;
}
}
else
{
// Counteract velocity to slow down.
Vector velocity = GetCurrentVelocity();
m_vForceVelocity = velocity * -0.5;
}
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNPC_Manhack::MaintainGroundHeight( void )
{
float zSpeed = GetCurrentVelocity().z;
if ( zSpeed > 32.0f )
return;
const float minGroundHeight = 52.0f;
trace_t tr;
AI_TraceHull( GetAbsOrigin(),
GetAbsOrigin() - Vector( 0, 0, minGroundHeight ),
GetHullMins(),
GetHullMaxs(),
(MASK_NPCSOLID_BRUSHONLY),
this,
COLLISION_GROUP_NONE,
&tr );
if ( tr.fraction != 1.0f )
{
float speedAdj = max( 16, (-zSpeed*0.5f) );
m_vForceVelocity += Vector(0,0,1) * ( speedAdj * ( 1.0f - tr.fraction ) );
}
}
//-----------------------------------------------------------------------------
// Purpose: Handles movement towards the last move target.
// Input : flInterval -
//-----------------------------------------------------------------------------
bool CNPC_Manhack::OverrideMove( float flInterval )
{
SpinBlades( flInterval );
// Don't execute any move code if packed up.
if( HasSpawnFlags(SF_MANHACK_PACKED_UP|SF_MANHACK_CARRIED) )
return true;
if( IsLoitering() )
{
Loiter();
}
else
{
MaintainGroundHeight();
}
// So cops, etc. will try to avoid them
if ( !HasSpawnFlags( SF_MANHACK_NO_DANGER_SOUNDS ) && !m_bHeld )
{
CSoundEnt::InsertSound( SOUND_DANGER, GetAbsOrigin(), 75, flInterval, this );
}
// -----------------------------------------------------------------
// If I'm being forced to move somewhere
// ------------------------------------------------------------------
if (m_fForceMoveTime > gpGlobals->curtime)
{
MoveToTarget(flInterval, m_vForceMoveTarget);
}
// -----------------------------------------------------------------
// If I have a route, keep it updated and move toward target
// ------------------------------------------------------------------
else if (GetNavigator()->IsGoalActive())
{
bool bReducible = GetNavigator()->GetPath()->GetCurWaypoint()->IsReducible();
const float strictTolerance = 64.0;
//NDebugOverlay::Line( GetAbsOrigin(), GetAbsOrigin() + Vector(0, 0, 10 ), 255, 0, 0, true, 0.1);
if ( ProgressFlyPath( flInterval, GetEnemy(), MoveCollisionMask(), bReducible, strictTolerance ) == AINPP_COMPLETE )
return true;
}
// -----------------------------------------------------------------
// If I'm supposed to swarm somewhere, try to go there
// ------------------------------------------------------------------
else if (m_fSwarmMoveTime > gpGlobals->curtime)
{
MoveToTarget(flInterval, m_vSwarmMoveTarget);
}
// -----------------------------------------------------------------
// If I don't have anything better to do, just decelerate
// -------------------------------------------------------------- ----
else
{
float myDecay = 9.5;
Decelerate( flInterval, myDecay );
m_vTargetBanking = vec3_origin;
// -------------------------------------
// If I have an enemy turn to face him
// -------------------------------------
if (GetEnemy())
{
TurnHeadToTarget(flInterval, GetEnemy()->EyePosition() );
}
}
if ( m_iHealth <= 0 )
{
// Crashing!!
MoveExecute_Dead(flInterval);
}
else
{
// Alive!
MoveExecute_Alive(flInterval);
}
return true;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input :
// Output :
//-----------------------------------------------------------------------------
void CNPC_Manhack::TurnHeadRandomly(float flInterval )
{
float desYaw = random->RandomFloat(0,360);
float iRate = 0.8;
// Make frame rate independent
float timeToUse = flInterval;
while (timeToUse > 0)
{
m_fHeadYaw = (iRate * m_fHeadYaw) + (1-iRate)*desYaw;
timeToUse =- 0.1;
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Input :
// Output :
//-----------------------------------------------------------------------------
void CNPC_Manhack::MoveToTarget(float flInterval, const Vector &vMoveTarget)
{
if (flInterval <= 0)
{
return;
}
// -----------------------------------------
// Don't steer if engine's have stalled
// -----------------------------------------
if ( gpGlobals->curtime < m_flEngineStallTime || m_iHealth <= 0 )
return;
if ( GetEnemy() != NULL )
{
TurnHeadToTarget( flInterval, GetEnemy()->EyePosition() );
}
else
{
TurnHeadToTarget( flInterval, vMoveTarget );
}
// -------------------------------------
// Move towards our target
// -------------------------------------
float myAccel;
float myZAccel = 300.0f;
float myDecay = 0.3f;
Vector targetDir;
float flDist;
// If we're bursting, just head straight
if ( m_flBurstDuration > gpGlobals->curtime )
{
float zDist = 500;
// Steer towards our enemy if we're able to
if ( GetEnemy() != NULL )
{
Vector steerDir = ( GetEnemy()->EyePosition() - GetAbsOrigin() );
zDist = fabs( steerDir.z );
VectorNormalize( steerDir );
float useTime = flInterval;
while ( useTime > 0.0f )
{
m_vecBurstDirection += ( steerDir * 4.0f );
useTime -= 0.1f;
}
m_vecBurstDirection.z = steerDir.z;
VectorNormalize( m_vecBurstDirection );
}
// Debug visualizations
/*
NDebugOverlay::Line( GetAbsOrigin(), GetAbsOrigin() + ( targetDir * 64.0f ), 255, 0, 0, true, 2.1f );
NDebugOverlay::Line( GetAbsOrigin(), GetAbsOrigin() + ( steerDir * 64.0f ), 0, 255, 0, true, 2.1f );
NDebugOverlay::Line( GetAbsOrigin(), GetAbsOrigin() + ( m_vecBurstDirection * 64.0f ), 0, 0, 255, true, 2.1f );
NDebugOverlay::Cross3D( GetAbsOrigin() , -Vector(8,8,8), Vector(8,8,8), 255, 0, 0, true, 2.1f );
*/
targetDir = m_vecBurstDirection;
flDist = FLT_MAX;
myDecay = 0.3f;
#ifdef _XBOX
myAccel = 500;
#else
myAccel = 400;
#endif // _XBOX
myZAccel = min( 500, zDist / flInterval );
}
else
{
Vector vecCurrentDir = GetCurrentVelocity();
VectorNormalize( vecCurrentDir );
targetDir = vMoveTarget - GetAbsOrigin();
flDist = VectorNormalize( targetDir );
float flDot = DotProduct( targetDir, vecCurrentDir );
// Otherwise we should steer towards our goal
if( flDot > 0.25 )
{
// If my target is in front of me, my flight model is a bit more accurate.
myAccel = 300;
}
else
{
// Have a harder time correcting my course if I'm currently flying away from my target.
myAccel = 200;
}
}
// Clamp lateral acceleration
if ( myAccel > ( flDist / flInterval ) )
{
myAccel = flDist / flInterval;
}
/*
// Boost vertical movement
if ( targetDir.z > 0 )
{
// Z acceleration is faster when we thrust upwards.
// This is to help keep manhacks out of water.
myZAccel *= 5.0;
}
*/
// Clamp vertical movement
if ( myZAccel > flDist / flInterval )
{
myZAccel = flDist / flInterval;
}
// Scale by our engine force
myAccel *= m_fEnginePowerScale;
myZAccel *= m_fEnginePowerScale;
MoveInDirection( flInterval, targetDir, myAccel, myZAccel, myDecay );
// calc relative banking targets
Vector forward, right;
GetVectors( &forward, &right, NULL );
m_vTargetBanking.x = 40 * DotProduct( forward, targetDir );
m_vTargetBanking.z = 40 * DotProduct( right, targetDir );
m_vTargetBanking.y = 0.0;
}
//-----------------------------------------------------------------------------
// Purpose: Ignore water if I'm close to my enemy
// Input :
// Output :
//-----------------------------------------------------------------------------
int CNPC_Manhack::MoveCollisionMask(void)
{
return MASK_NPCSOLID;
}
//-----------------------------------------------------------------------------
// Purpose: Make a splash effect
// Input :
// Output :
//-----------------------------------------------------------------------------
void CNPC_Manhack::Splash( const Vector &vecSplashPos )
{
CEffectData data;
data.m_fFlags = 0;
data.m_vOrigin = vecSplashPos;
data.m_vNormal = Vector( 0, 0, 1 );
data.m_flScale = 8.0f;
int contents = GetWaterType();
// Verify we have valid contents
if ( !( contents & (CONTENTS_SLIME|CONTENTS_WATER)))
{
// We're leaving the water so we have to reverify what it was
trace_t tr;
UTIL_TraceLine( GetAbsOrigin(), GetAbsOrigin() - Vector( 0, 0, 256 ), (CONTENTS_WATER|CONTENTS_SLIME), this, COLLISION_GROUP_NONE, &tr );
// Re-validate this
if ( !(tr.contents&(CONTENTS_WATER|CONTENTS_SLIME)) )
{
//NOTENOTE: We called a splash but we don't seem to be near water?
Assert( 0 );
return;
}
contents = tr.contents;
}
// Mark us if we're in slime
if ( contents & CONTENTS_SLIME )
{
data.m_fFlags |= FX_WATER_IN_SLIME;
}
DispatchEffect( "watersplash", data );
}
//-----------------------------------------------------------------------------
// Computes the slice bounce velocity
//-----------------------------------------------------------------------------
void CNPC_Manhack::ComputeSliceBounceVelocity( CBaseEntity *pHitEntity, trace_t &tr )
{
if( pHitEntity->IsAlive() && FClassnameIs( pHitEntity, "func_breakable_surf" ) )
{
// We want to see if the manhack hits a breakable pane of glass. To keep from checking
// The classname of the HitEntity on each impact, we only do this check if we hit
// something that's alive. Anyway, prevent the manhack bouncing off the pane of glass,
// since this impact will shatter the glass and let the manhack through.
return;
}
Vector vecDir;
// If the manhack isn't bouncing away from whatever he sliced, force it.
VectorSubtract( WorldSpaceCenter(), pHitEntity->WorldSpaceCenter(), vecDir );
VectorNormalize( vecDir );
vecDir *= 200;
vecDir[2] = 0.0f;
// Knock it away from us
if ( VPhysicsGetObject() != NULL )
{
VPhysicsGetObject()->ApplyForceOffset( vecDir * 4, GetAbsOrigin() );
}
// Also set our velocity
SetCurrentVelocity( vecDir );
}
//-----------------------------------------------------------------------------
// Is the manhack being held?
//-----------------------------------------------------------------------------
bool CNPC_Manhack::IsHeldByPhyscannon( )
{
return VPhysicsGetObject() && (VPhysicsGetObject()->GetGameFlags() & FVPHYSICS_PLAYER_HELD);
}
//-----------------------------------------------------------------------------
// Purpose: We've touched something that we can hurt. Slice it!
// Input :
// Output :
//-----------------------------------------------------------------------------
void CNPC_Manhack::Slice( CBaseEntity *pHitEntity, float flInterval, trace_t &tr )
{
// Don't hurt the player if I'm in water
if( GetWaterLevel() > 0 && pHitEntity->IsPlayer() )
return;
// Can't slice players holding it with the phys cannon
if ( IsHeldByPhyscannon() )
{
if ( pHitEntity && (pHitEntity == HasPhysicsAttacker( FLT_MAX )) )
return;
}
if ( pHitEntity->m_takedamage == DAMAGE_NO )
return;
// Damage must be scaled by flInterval so framerate independent
float flDamage = sk_manhack_melee_dmg.GetFloat() * flInterval;
if ( pHitEntity->IsPlayer() )
{
flDamage *= 2.0f;
}
// Held manhacks do more damage
if ( IsHeldByPhyscannon() )
{
// Deal 100 damage/sec
flDamage = 100.0f * flInterval;
}
else if ( pHitEntity->IsNPC() && HasPhysicsAttacker( MANHACK_SMASH_TIME ) )
{
// NOTE: The else here is essential.
// The physics attacker *will* be set even when the manhack is held
flDamage = pHitEntity->GetHealth();
}
else if ( dynamic_cast<CBaseProp*>(pHitEntity) || dynamic_cast<CBreakable*>(pHitEntity) )
{
// If we hit a prop, we want it to break immediately
flDamage = pHitEntity->GetHealth();
}
else if ( pHitEntity->IsNPC() && IRelationType( pHitEntity ) == D_HT && FClassnameIs( pHitEntity, "npc_combine_s" ) )
{
flDamage *= 6.0f;
}
if (flDamage < 1.0f)
{
flDamage = 1.0f;
}
CTakeDamageInfo info( this, this, flDamage, DMG_SLASH );
// check for actual "ownership" of damage
CBasePlayer *pPlayer = HasPhysicsAttacker( MANHACK_SMASH_TIME );
if (pPlayer)
{
info.SetAttacker( pPlayer );
}
Vector dir = (tr.endpos - tr.startpos);
if ( dir == vec3_origin )
{
dir = tr.m_pEnt->GetAbsOrigin() - GetAbsOrigin();
}
CalculateMeleeDamageForce( &info, dir, tr.endpos );
pHitEntity->TakeDamage( info );
// Spawn some extra blood where we hit
if ( pHitEntity->BloodColor() == DONT_BLEED )
{
CEffectData data;
Vector velocity = GetCurrentVelocity();
data.m_vOrigin = tr.endpos;
data.m_vAngles = GetAbsAngles();
VectorNormalize( velocity );
data.m_vNormal = ( tr.plane.normal + velocity ) * 0.5;;
DispatchEffect( "ManhackSparks", data );
EmitSound( "NPC_Manhack.Grind" );
//TODO: What we really want to do is get a material reference and emit the proper sprayage! - jdw
}
else
{
SpawnBlood(tr.endpos, g_vecAttackDir, pHitEntity->BloodColor(), 6 );
EmitSound( "NPC_Manhack.Slice" );
}
// Pop back a little bit after hitting the player
ComputeSliceBounceVelocity( pHitEntity, tr );
// Save off when we last hit something
m_flLastDamageTime = gpGlobals->curtime;
// Reset our state and give the player time to react
StopBurst( true );
}
//-----------------------------------------------------------------------------
// Purpose: We've touched something solid. Just bump it.
// Input :
// Output :
//-----------------------------------------------------------------------------
void CNPC_Manhack::Bump( CBaseEntity *pHitEntity, float flInterval, trace_t &tr )
{
if ( !VPhysicsGetObject() )
return;
// Surpressing this behavior
if ( m_flBumpSuppressTime > gpGlobals->curtime )
return;
if ( pHitEntity->GetMoveType() == MOVETYPE_VPHYSICS && pHitEntity->Classify()!=CLASS_MANHACK )
{
HitPhysicsObject( pHitEntity );
}
// We've hit something so deflect our velocity based on the surface
// norm of what we've hit
if (flInterval > 0)
{
float moveLen = ( (GetCurrentVelocity() * flInterval) * (1.0 - tr.fraction) ).Length();
Vector moveVec = moveLen*tr.plane.normal/flInterval;
// If I'm totally dead, don't bounce me up
if (m_iHealth <=0 && moveVec.z > 0)
{
moveVec.z = 0;
}
// If I'm right over the ground don't push down
if (moveVec.z < 0)
{
float floorZ = GetFloorZ(GetAbsOrigin());
if (abs(GetAbsOrigin().z - floorZ) < 36)
{
moveVec.z = 0;
}
}
Vector myUp;
VPhysicsGetObject()->LocalToWorldVector( &myUp, Vector( 0.0, 0.0, 1.0 ) );
// plane must be something that could hit the blades
if (fabs( DotProduct( myUp, tr.plane.normal ) ) < 0.25 )
{
CEffectData data;
Vector velocity = GetCurrentVelocity();
data.m_vOrigin = tr.endpos;
data.m_vAngles = GetAbsAngles();
VectorNormalize( velocity );
data.m_vNormal = ( tr.plane.normal + velocity ) * 0.5;;
DispatchEffect( "ManhackSparks", data );
CBroadcastRecipientFilter filter;
te->DynamicLight( filter, 0.0, &GetAbsOrigin(), 255, 180, 100, 0, 50, 0.3, 150 );
// add some spin, but only if we're not already going fast..
Vector vecVelocity;
AngularImpulse vecAngVelocity;
VPhysicsGetObject()->GetVelocity( &vecVelocity, &vecAngVelocity );
float flDot = DotProduct( myUp, vecAngVelocity );
if ( fabs(flDot) < 100 )
{
//AngularImpulse torque = myUp * (1000 - flDot * 10);
AngularImpulse torque = myUp * (1000 - flDot * 2);
VPhysicsGetObject()->ApplyTorqueCenter( torque );
}
if (!(m_spawnflags & SF_NPC_GAG))
{
EmitSound( "NPC_Manhack.Grind" );
}
// For decals and sparks we must trace a line in the direction of the surface norm
// that we hit.
trace_t decalTrace;
AI_TraceLine( GetAbsOrigin(), GetAbsOrigin() - (tr.plane.normal * 24),MASK_SOLID, this, COLLISION_GROUP_NONE, &decalTrace );
if ( decalTrace.fraction != 1.0 )
{
// Leave decal only if colliding horizontally
if ((DotProduct(Vector(0,0,1),decalTrace.plane.normal)<0.5) && (DotProduct(Vector(0,0,-1),decalTrace.plane.normal)<0.5))
{
UTIL_DecalTrace( &decalTrace, "ManhackCut" );
}
}
}
// See if we will not have a valid surface
if ( tr.allsolid || tr.startsolid )
{
// Build a fake reflection back along our current velocity because we can't know how to reflect off
// a non-existant surface! -- jdw
Vector vecRandomDir = RandomVector( -1.0f, 1.0f );
SetCurrentVelocity( vecRandomDir * 50.0f );
m_flBumpSuppressTime = gpGlobals->curtime + 0.5f;
}
else
{
// This is a valid hit and we can deflect properly
VectorNormalize( moveVec );
float hitAngle = -DotProduct( tr.plane.normal, -moveVec );
Vector vReflection = 2.0 * tr.plane.normal * hitAngle + -moveVec;
float flSpeed = GetCurrentVelocity().Length();
SetCurrentVelocity( GetCurrentVelocity() + vReflection * flSpeed * 0.5f );
}
}
// -------------------------------------------------------------
// If I'm on a path check LOS to my next node, and fail on path
// if I don't have LOS. Note this is the only place I do this,
// so the manhack has to collide before failing on a path
// -------------------------------------------------------------
if (GetNavigator()->IsGoalActive() && !(GetNavigator()->GetPath()->CurWaypointFlags() & bits_WP_TO_PATHCORNER) )
{
AIMoveTrace_t moveTrace;
GetMoveProbe()->MoveLimit( NAV_GROUND, GetAbsOrigin(), GetNavigator()->GetCurWaypointPos(),
MoveCollisionMask(), GetEnemy(), &moveTrace );
if (IsMoveBlocked( moveTrace ) &&
!moveTrace.pObstruction->ClassMatches( GetClassname() ))
{
TaskFail(FAIL_NO_ROUTE);
GetNavigator()->ClearGoal();
return;
}
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Input :
// Output :
//-----------------------------------------------------------------------------
void CNPC_Manhack::CheckCollisions(float flInterval)
{
// Trace forward to see if I hit anything. But trace forward along the
// owner's view direction if you're being carried.
Vector vecTraceDir, vecCheckPos;
VPhysicsGetObject()->GetVelocity( &vecTraceDir, NULL );
vecTraceDir *= flInterval;
if ( IsHeldByPhyscannon() )
{
CBasePlayer *pCarrier = HasPhysicsAttacker( FLT_MAX );
if ( pCarrier )
{
if ( pCarrier->CollisionProp()->CalcDistanceFromPoint( WorldSpaceCenter() ) < 30 )
{
AngleVectors( pCarrier->EyeAngles(), &vecTraceDir, NULL, NULL );
vecTraceDir *= 40.0f;
}
}
}
VectorAdd( GetAbsOrigin(), vecTraceDir, vecCheckPos );
trace_t tr;
CBaseEntity* pHitEntity = NULL;
AI_TraceHull( GetAbsOrigin(),
vecCheckPos,
GetHullMins(),
GetHullMaxs(),
MoveCollisionMask(),
this,
COLLISION_GROUP_NONE,
&tr );
if ( (tr.fraction != 1.0 || tr.startsolid) && tr.m_pEnt)
{
PhysicsMarkEntitiesAsTouching( tr.m_pEnt, tr );
pHitEntity = tr.m_pEnt;
if( m_bHeld && tr.m_pEnt->MyNPCPointer() && tr.m_pEnt->MyNPCPointer()->IsPlayerAlly() )
{
// Don't slice Alyx when she approaches to hack. We need a better solution for this!!
//Msg("Ignoring!\n");
return;
}
if ( pHitEntity != NULL &&
pHitEntity->m_takedamage == DAMAGE_YES &&
pHitEntity->Classify() != CLASS_MANHACK &&
gpGlobals->curtime > m_flWaterSuspendTime )
{
// Slice this thing
Slice( pHitEntity, flInterval, tr );
m_flBladeSpeed = 20.0;
}
else
{
// Just bump into this thing.
Bump( pHitEntity, flInterval, tr );
m_flBladeSpeed = 20.0;
}
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Input :
// Output :
//-----------------------------------------------------------------------------
#define tempTIME_STEP = 0.5;
void CNPC_Manhack::PlayFlySound(void)
{
float flEnemyDist;
if( GetEnemy() )
{
flEnemyDist = (GetAbsOrigin() - GetEnemy()->GetAbsOrigin()).Length();
}
else
{
flEnemyDist = FLT_MAX;
}
if( m_spawnflags & SF_NPC_GAG )
{
// Quiet!
return;
}
if( m_flWaterSuspendTime > gpGlobals->curtime )
{
// Just went in water. Slow the motor!!
if( m_bDirtyPitch )
{
m_nEnginePitch1 = MANHACK_WATER_PITCH1;
m_flEnginePitch1Time = gpGlobals->curtime + 0.5f;
m_nEnginePitch2 = MANHACK_WATER_PITCH2;
m_flEnginePitch2Time = gpGlobals->curtime + 0.5f;
m_bDirtyPitch = false;
}
}
// Spin sound based on distance from enemy (unless we're crashing)
else if (GetEnemy() && IsAlive() )
{
if( flEnemyDist < MANHACK_PITCH_DIST1 )
{
// recalculate pitch.
int iPitch1, iPitch2;
float flDistFactor;
flDistFactor = min( 1.0, 1 - flEnemyDist / MANHACK_PITCH_DIST1 );
iPitch1 = MANHACK_MIN_PITCH1 + ( ( MANHACK_MAX_PITCH1 - MANHACK_MIN_PITCH1 ) * flDistFactor);
// NOTE: MANHACK_PITCH_DIST2 must be < MANHACK_PITCH_DIST1
flDistFactor = min( 1.0, 1 - flEnemyDist / MANHACK_PITCH_DIST2 );
iPitch2 = MANHACK_MIN_PITCH2 + ( ( MANHACK_MAX_PITCH2 - MANHACK_MIN_PITCH2 ) * flDistFactor);
m_nEnginePitch1 = iPitch1;
m_flEnginePitch1Time = gpGlobals->curtime + 0.1f;
m_nEnginePitch2 = iPitch2;
m_flEnginePitch2Time = gpGlobals->curtime + 0.1f;
m_bDirtyPitch = true;
}
else if( m_bDirtyPitch )
{
m_nEnginePitch1 = MANHACK_MIN_PITCH1;
m_flEnginePitch1Time = gpGlobals->curtime + 0.1f;
m_nEnginePitch2 = MANHACK_MIN_PITCH2;
m_flEnginePitch2Time = gpGlobals->curtime + 0.2f;
m_bDirtyPitch = false;
}
}
// If no enemy just play low sound
else if( IsAlive() && m_bDirtyPitch )
{
m_nEnginePitch1 = MANHACK_MIN_PITCH1;
m_flEnginePitch1Time = gpGlobals->curtime + 0.1f;
m_nEnginePitch2 = MANHACK_MIN_PITCH2;
m_flEnginePitch2Time = gpGlobals->curtime + 0.2f;
m_bDirtyPitch = false;
}
// Play special engine every once in a while
if (gpGlobals->curtime > m_flNextEngineSoundTime && flEnemyDist < 48)
{
m_flNextEngineSoundTime = gpGlobals->curtime + random->RandomFloat( 3.0, 10.0 );
EmitSound( "NPC_Manhack.EngineNoise" );
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Input :
// Output :
//-----------------------------------------------------------------------------
void CNPC_Manhack::MoveExecute_Alive(float flInterval)
{
PhysicsCheckWaterTransition();
Vector vCurrentVelocity = GetCurrentVelocity();
// FIXME: move this
VPhysicsGetObject()->Wake();
if( m_fEnginePowerScale < GetMaxEnginePower() && gpGlobals->curtime > m_flWaterSuspendTime )
{
// Power is low, and we're no longer stuck in water, so bring power up.
m_fEnginePowerScale += 0.05;
}
// ----------------------------------------------------------------------------------------
// Add time-coherent noise to the current velocity so that it never looks bolted in place.
// ----------------------------------------------------------------------------------------
float noiseScale = 7.0f;
if ( (CBaseEntity*)GetEnemy() )
{
float flDist = (GetAbsOrigin() - GetEnemy()->GetAbsOrigin()).Length2D();
if( flDist < MANHACK_CHARGE_MIN_DIST )
{
// Less noise up close.
noiseScale = 2.0;
}
if ( IsInEffectiveTargetZone( GetEnemy() ) && flDist < MANHACK_CHARGE_MIN_DIST && gpGlobals->curtime > m_flNextBurstTime )
{
Vector vecCurrentDir = GetCurrentVelocity();
VectorNormalize( vecCurrentDir );
Vector vecToEnemy = ( GetEnemy()->EyePosition() - WorldSpaceCenter() );
VectorNormalize( vecToEnemy );
float flDot = DotProduct( vecCurrentDir, vecToEnemy );
if ( flDot > 0.75 )
{
Vector offsetDir = ( vecToEnemy - vecCurrentDir );
VectorNormalize( offsetDir );
Vector offsetSpeed = GetCurrentVelocity() * flDot;
//FIXME: This code sucks -- jdw
offsetDir.z = 0.0f;
m_vForceVelocity += ( offsetDir * ( offsetSpeed.Length2D() * 0.25f ) );
// Commit to the attack- no steering for about a second
StartBurst( vecToEnemy );
SetEyeState( MANHACK_EYE_STATE_CHARGE );
}
}
if ( gpGlobals->curtime > m_flBurstDuration )
{
ShowHostile( false );
}
}
// ----------------------------------------------------------------------------------------
// Add in any forced velocity
// ----------------------------------------------------------------------------------------
SetCurrentVelocity( vCurrentVelocity + m_vForceVelocity );
m_vForceVelocity = vec3_origin;
if( !m_bHackedByAlyx || GetEnemy() )
{
// If hacked and no enemy, don't drift!
AddNoiseToVelocity( noiseScale );
}
LimitSpeed( 200, ManhackMaxSpeed() );
if( m_flWaterSuspendTime > gpGlobals->curtime )
{
if( UTIL_PointContents( GetAbsOrigin() ) & (CONTENTS_WATER|CONTENTS_SLIME) )
{
// Ooops, we're submerged somehow. Move upwards until our origin is out of the water.
m_vCurrentVelocity.z = 20.0;
}
else
{
// Skimming the surface. Forbid any movement on Z
m_vCurrentVelocity.z = 0.0;
}
}
else if( GetWaterLevel() > 0 )
{
// Allow the manhack to lift off, but not to go deeper.
m_vCurrentVelocity.z = max( m_vCurrentVelocity.z, 0 );
}
CheckCollisions(flInterval);
// Blend out desired velocity when launched by the physcannon
if ( HasPhysicsAttacker( MANHACK_SMASH_TIME ) && (!IsHeldByPhyscannon()) && VPhysicsGetObject() )
{
Vector vecCurrentVelocity;
VPhysicsGetObject()->GetVelocity( &vecCurrentVelocity, NULL );
float flLerpFactor = (gpGlobals->curtime - m_flLastPhysicsInfluenceTime) / MANHACK_SMASH_TIME;
flLerpFactor = clamp( flLerpFactor, 0.0f, 1.0f );
flLerpFactor = SimpleSplineRemapVal( flLerpFactor, 0.0f, 1.0f, 0.0f, 1.0f );
VectorLerp( vecCurrentVelocity, m_vCurrentVelocity, flLerpFactor, m_vCurrentVelocity );
}
QAngle angles = GetLocalAngles();
// ------------------------------------------
// Stalling
// ------------------------------------------
if (gpGlobals->curtime < m_flEngineStallTime)
{
/*
// If I'm stalled add random noise
angles.x += -20+(random->RandomInt(-10,10));
angles.z += -20+(random->RandomInt(0,40));
TurnHeadRandomly(flInterval);
*/
}
else
{
// Make frame rate independent
float iRate = 0.5;
float timeToUse = flInterval;
while (timeToUse > 0)
{
m_vCurrentBanking.x = (iRate * m_vCurrentBanking.x) + (1 - iRate)*(m_vTargetBanking.x);
m_vCurrentBanking.z = (iRate * m_vCurrentBanking.z) + (1 - iRate)*(m_vTargetBanking.z);
timeToUse =- 0.1;
}
angles.x = m_vCurrentBanking.x;
angles.z = m_vCurrentBanking.z;
angles.y = 0;
#if 0
// Using our steering if we're not otherwise affecting our panels
if ( m_flEngineStallTime < gpGlobals->curtime && m_flBurstDuration < gpGlobals->curtime )
{
Vector delta( 10 * AngleDiff( m_vTargetBanking.x, m_vCurrentBanking.x ), -10 * AngleDiff( m_vTargetBanking.z, m_vCurrentBanking.z ), 0 );
//Vector delta( 3 * AngleNormalize( m_vCurrentBanking.x ), -4 * AngleNormalize( m_vCurrentBanking.z ), 0 );
VectorYawRotate( delta, -m_fHeadYaw, delta );
// DevMsg("%.0f %.0f\n", delta.x, delta.y );
SetPoseParameter( m_iPanel1, -delta.x - delta.y * 2);
SetPoseParameter( m_iPanel2, -delta.x + delta.y * 2);
SetPoseParameter( m_iPanel3, delta.x + delta.y * 2);
SetPoseParameter( m_iPanel4, delta.x - delta.y * 2);
//SetPoseParameter( m_iPanel1, -delta.x );
//SetPoseParameter( m_iPanel2, -delta.x );
//SetPoseParameter( m_iPanel3, delta.x );
//SetPoseParameter( m_iPanel4, delta.x );
}
#endif
}
// SetLocalAngles( angles );
if( m_lifeState != LIFE_DEAD )
{
PlayFlySound();
// SpinBlades( flInterval );
// WalkMove( GetCurrentVelocity() * flInterval, MASK_NPCSOLID );
}
// NDebugOverlay::Line( GetAbsOrigin(), GetAbsOrigin() + Vector(0, 0, -10 ), 0, 255, 0, true, 0.1);
}
//-----------------------------------------------------------------------------
// Purpose:
// Input :
// Output :
//-----------------------------------------------------------------------------
void CNPC_Manhack::SpinBlades(float flInterval)
{
if (!m_bBladesActive)
{
SetBodygroup( MANHACK_BODYGROUP_BLADE, MANHACK_BODYGROUP_OFF );
SetBodygroup( MANHACK_BODYGROUP_BLUR, MANHACK_BODYGROUP_OFF );
m_flBladeSpeed = 0.0;
m_flPlaybackRate = 1.0;
return;
}
if ( IsFlyingActivity( GetActivity() ) )
{
// Blades may only ramp up while the engine is running
if ( m_flEngineStallTime < gpGlobals->curtime )
{
if (m_flBladeSpeed < 10)
{
m_flBladeSpeed = m_flBladeSpeed * 2 + 1;
}
else
{
// accelerate engine
m_flBladeSpeed = m_flBladeSpeed + 80 * flInterval;
}
}
if (m_flBladeSpeed > 100)
{
m_flBladeSpeed = 100;
}
// blend through blades, blades+blur, blur
if (m_flBladeSpeed < 20)
{
SetBodygroup( MANHACK_BODYGROUP_BLADE, MANHACK_BODYGROUP_ON );
SetBodygroup( MANHACK_BODYGROUP_BLUR, MANHACK_BODYGROUP_OFF );
}
else if (m_flBladeSpeed < 40)
{
SetBodygroup( MANHACK_BODYGROUP_BLADE, MANHACK_BODYGROUP_ON );
SetBodygroup( MANHACK_BODYGROUP_BLUR, MANHACK_BODYGROUP_ON );
}
else
{
SetBodygroup( MANHACK_BODYGROUP_BLADE, MANHACK_BODYGROUP_OFF );
SetBodygroup( MANHACK_BODYGROUP_BLUR, MANHACK_BODYGROUP_ON );
}
m_flPlaybackRate = m_flBladeSpeed / 100.0;
}
else
{
m_flBladeSpeed = 0.0;
}
}
//-----------------------------------------------------------------------------
// Purpose: Smokes and sparks, exploding periodically. Eventually it goes away.
//-----------------------------------------------------------------------------
void CNPC_Manhack::MoveExecute_Dead(float flInterval)
{
if( GetWaterLevel() > 0 )
{
// No movement if sinking in water.
return;
}
// Periodically emit smoke.
if (gpGlobals->curtime > m_fSmokeTime && GetWaterLevel() == 0)
{
// UTIL_Smoke(GetAbsOrigin(), random->RandomInt(10, 15), 10);
m_fSmokeTime = gpGlobals->curtime + random->RandomFloat( 0.1, 0.3);
}
// Periodically emit sparks.
if (gpGlobals->curtime > m_fSparkTime)
{
g_pEffects->Sparks( GetAbsOrigin() );
m_fSparkTime = gpGlobals->curtime + random->RandomFloat(0.1, 0.3);
}
Vector newVelocity = GetCurrentVelocity();
// accelerate faster and faster when dying
newVelocity = newVelocity + (newVelocity * 1.5 * flInterval );
// Lose lift
newVelocity.z -= 0.02*flInterval*(sv_gravity.GetFloat());
// ----------------------------------------------------------------------------------------
// Add in any forced velocity
// ----------------------------------------------------------------------------------------
newVelocity += m_vForceVelocity;
SetCurrentVelocity( newVelocity );
m_vForceVelocity = vec3_origin;
// Lots of noise!! Out of control!
AddNoiseToVelocity( 5.0 );
// ----------------------
// Limit overall speed
// ----------------------
LimitSpeed( -1, MANHACK_MAX_SPEED * 2.0 );
QAngle angles = GetLocalAngles();
// ------------------------------------------
// If I'm dying, add random banking noise
// ------------------------------------------
angles.x += -20+(random->RandomInt(0,40));
angles.z += -20+(random->RandomInt(0,40));
CheckCollisions(flInterval);
PlayFlySound();
// SetLocalAngles( angles );
WalkMove( GetCurrentVelocity() * flInterval,MASK_NPCSOLID );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNPC_Manhack::Precache(void)
{
//
// Model.
//
PrecacheModel("models/manhack.mdl");
PrecacheModel( MANHACK_GLOW_SPRITE );
PropBreakablePrecacheAll( MAKE_STRING("models/manhack.mdl") );
PrecacheScriptSound( "NPC_Manhack.Die" );
PrecacheScriptSound( "NPC_Manhack.Bat" );
PrecacheScriptSound( "NPC_Manhack.Grind" );
PrecacheScriptSound( "NPC_Manhack.Slice" );
PrecacheScriptSound( "NPC_Manhack.EngineNoise" );
PrecacheScriptSound( "NPC_Manhack.Unpack" );
PrecacheScriptSound( "NPC_Manhack.ChargeAnnounce" );
PrecacheScriptSound( "NPC_Manhack.ChargeEnd" );
PrecacheScriptSound( "NPC_Manhack.Stunned" );
// Sounds used on Client:
PrecacheScriptSound( "NPC_Manhack.EngineSound1" );
PrecacheScriptSound( "NPC_Manhack.EngineSound2" );
PrecacheScriptSound( "NPC_Manhack.BladeSound" );
BaseClass::Precache();
}
//-----------------------------------------------------------------------------
// Purpose:
// Input :
// Output :
//-----------------------------------------------------------------------------
void CNPC_Manhack::GatherEnemyConditions( CBaseEntity *pEnemy )
{
// The Manhack "regroups" when its in attack range but to
// far above or below its enemy. Set the start attack
// condition if we are far enough away from the enemy
// or at the correct height
// Don't bother with Z if the enemy is in a vehicle
float fl2DDist = 60.0f;
float flZDist = 12.0f;
if ( GetEnemy()->IsPlayer() && assert_cast< CBasePlayer * >(GetEnemy())->IsInAVehicle() )
{
flZDist = 24.0f;
}
if ((GetAbsOrigin() - pEnemy->GetAbsOrigin()).Length2D() > fl2DDist)
{
SetCondition(COND_MANHACK_START_ATTACK);
}
else
{
float targetZ = pEnemy->EyePosition().z;
if (fabs(GetAbsOrigin().z - targetZ) < flZDist)
{
SetCondition(COND_MANHACK_START_ATTACK);
}
}
BaseClass::GatherEnemyConditions(pEnemy);
}
//-----------------------------------------------------------------------------
// Purpose: For innate melee attack
// Input :
// Output :
//-----------------------------------------------------------------------------
int CNPC_Manhack::MeleeAttack1Conditions( float flDot, float flDist )
{
if ( GetEnemy() == NULL )
return COND_NONE;
//TODO: We could also decide if we want to back up here
if ( m_flNextBurstTime > gpGlobals->curtime )
return COND_NONE;
float flMaxDist = 45;
float flMinDist = 24;
bool bEnemyInVehicle = GetEnemy()->IsPlayer() && assert_cast< CBasePlayer * >(GetEnemy())->IsInAVehicle();
if ( GetEnemy()->IsPlayer() && assert_cast< CBasePlayer * >(GetEnemy())->IsInAVehicle() )
{
flMinDist = 0;
flMaxDist = 200.0f;
}
if (flDist > flMaxDist)
{
return COND_TOO_FAR_TO_ATTACK;
}
if (flDist < flMinDist)
{
return COND_TOO_CLOSE_TO_ATTACK;
}
// Check our current velocity and speed, if it's too far off, we need to settle
// Don't bother with Z if the enemy is in a vehicle
if ( bEnemyInVehicle )
{
return COND_CAN_MELEE_ATTACK1;
}
// Assume the this check is in regards to my current enemy
// for the Manhacks spetial condition
float deltaZ = GetAbsOrigin().z - GetEnemy()->EyePosition().z;
if ( (deltaZ > 12.0f) || (deltaZ < -24.0f) )
{
return COND_TOO_CLOSE_TO_ATTACK;
}
return COND_CAN_MELEE_ATTACK1;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *pTask -
//-----------------------------------------------------------------------------
void CNPC_Manhack::RunTask( const Task_t *pTask )
{
switch ( pTask->iTask )
{
// Override this task so we go for the enemy at eye level
case TASK_MANHACK_HOVER:
{
break;
}
// If my enemy has moved significantly, update my path
case TASK_WAIT_FOR_MOVEMENT:
{
CBaseEntity *pEnemy = GetEnemy();
if (pEnemy &&
(GetCurSchedule()->GetId() == SCHED_CHASE_ENEMY) &&
GetNavigator()->IsGoalActive() )
{
Vector vecEnemyPosition;
vecEnemyPosition = pEnemy->EyePosition();
if ( GetNavigator()->GetGoalPos().DistToSqr(vecEnemyPosition) > 40 * 40 )
{
GetNavigator()->UpdateGoalPos( vecEnemyPosition );
}
}
BaseClass::RunTask(pTask);
break;
}
case TASK_MANHACK_MOVEAT_SAVEPOSITION:
{
// do the movement thingy
// NDebugOverlay::Line( GetAbsOrigin(), m_vSavePosition, 0, 255, 0, true, 0.1);
Vector dir = (m_vSavePosition - GetAbsOrigin());
float dist = VectorNormalize( dir );
float t = m_fSwarmMoveTime - gpGlobals->curtime;
if (t < 0.1)
{
if (dist > 256)
{
TaskFail( FAIL_NO_ROUTE );
}
else
{
TaskComplete();
}
}
else if (dist < 64)
{
m_vSwarmMoveTarget = GetAbsOrigin() - Vector( -dir.y, dir.x, 0 ) * 4;
}
else
{
m_vSwarmMoveTarget = GetAbsOrigin() + dir * 10;
}
break;
}
default:
{
BaseClass::RunTask(pTask);
}
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNPC_Manhack::Spawn(void)
{
Precache();
#ifdef _XBOX
// Always fade the corpse
AddSpawnFlags( SF_NPC_FADE_CORPSE );
#endif // _XBOX
SetModel( "models/manhack.mdl" );
SetHullType(HULL_TINY_CENTERED);
SetHullSizeNormal();
SetSolid( SOLID_BBOX );
AddSolidFlags( FSOLID_NOT_STANDABLE );
if ( HasSpawnFlags( SF_MANHACK_CARRIED ) )
{
AddSolidFlags( FSOLID_NOT_SOLID );
SetMoveType( MOVETYPE_NONE );
}
else
{
SetMoveType( MOVETYPE_VPHYSICS );
}
m_iHealth = sk_manhack_health.GetFloat();
SetViewOffset( Vector(0, 0, 10) ); // Position of the eyes relative to NPC's origin.
m_flFieldOfView = VIEW_FIELD_FULL;
m_NPCState = NPC_STATE_NONE;
if ( m_spawnflags & SF_MANHACK_USE_AIR_NODES)
{
SetNavType(NAV_FLY);
}
else
{
SetNavType(NAV_GROUND);
}
AddEFlags( EFL_NO_DISSOLVE | EFL_NO_MEGAPHYSCANNON_RAGDOLL );
AddEffects( EF_NOSHADOW );
SetBloodColor( DONT_BLEED );
SetCurrentVelocity( vec3_origin );
m_vForceVelocity.Init();
m_vCurrentBanking.Init();
m_vTargetBanking.Init();
m_flNextBurstTime = gpGlobals->curtime;
CapabilitiesAdd( bits_CAP_INNATE_MELEE_ATTACK1 | bits_CAP_MOVE_FLY | bits_CAP_SQUAD );
m_flNextEngineSoundTime = gpGlobals->curtime;
m_flWaterSuspendTime = gpGlobals->curtime;
m_flEngineStallTime = gpGlobals->curtime;
m_fForceMoveTime = gpGlobals->curtime;
m_vForceMoveTarget = vec3_origin;
m_fSwarmMoveTime = gpGlobals->curtime;
m_vSwarmMoveTarget = vec3_origin;
m_nLastSpinSound = -1;
m_fSmokeTime = 0;
m_fSparkTime = 0;
// Set the noise mod to huge numbers right now, in case this manhack starts out waiting for a script
// for instance, we don't want him to bob whilst he's waiting for a script. This allows designers
// to 'hide' manhacks in small places. (sjb)
SetNoiseMod( MANHACK_NOISEMOD_HIDE, MANHACK_NOISEMOD_HIDE, MANHACK_NOISEMOD_HIDE );
// Start out with full power!
m_fEnginePowerScale = GetMaxEnginePower();
// find panels
m_iPanel1 = LookupPoseParameter( "Panel1" );
m_iPanel2 = LookupPoseParameter( "Panel2" );
m_iPanel3 = LookupPoseParameter( "Panel3" );
m_iPanel4 = LookupPoseParameter( "Panel4" );
m_fHeadYaw = 0;
NPCInit();
// Manhacks are designed to slam into things, so don't take much damage from it!
SetImpactEnergyScale( 0.001 );
// Manhacks get 30 seconds worth of free knowledge.
GetEnemies()->SetFreeKnowledgeDuration( 30.0 );
// don't be an NPC, we want to collide with debris stuff
SetCollisionGroup( COLLISION_GROUP_NONE );
m_bHeld = false;
m_bHackedByAlyx = false;
StopLoitering();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNPC_Manhack::StartEye( void )
{
//Create our Eye sprite
if ( m_pEyeGlow == NULL )
{
m_pEyeGlow = CSprite::SpriteCreate( MANHACK_GLOW_SPRITE, GetLocalOrigin(), false );
m_pEyeGlow->SetAttachment( this, LookupAttachment( "Eye" ) );
if( m_bHackedByAlyx )
{
m_pEyeGlow->SetTransparency( kRenderTransAdd, 0, 255, 0, 128, kRenderFxNoDissipation );
m_pEyeGlow->SetColor( 0, 255, 0 );
}
else
{
m_pEyeGlow->SetTransparency( kRenderTransAdd, 255, 0, 0, 128, kRenderFxNoDissipation );
m_pEyeGlow->SetColor( 255, 0, 0 );
}
m_pEyeGlow->SetBrightness( 164, 0.1f );
m_pEyeGlow->SetScale( 0.25f, 0.1f );
m_pEyeGlow->SetAsTemporary();
}
//Create our light sprite
if ( m_pLightGlow == NULL )
{
m_pLightGlow = CSprite::SpriteCreate( MANHACK_GLOW_SPRITE, GetLocalOrigin(), false );
m_pLightGlow->SetAttachment( this, LookupAttachment( "Light" ) );
if( m_bHackedByAlyx )
{
m_pLightGlow->SetTransparency( kRenderTransAdd, 0, 255, 0, 128, kRenderFxNoDissipation );
m_pLightGlow->SetColor( 0, 255, 0 );
}
else
{
m_pLightGlow->SetTransparency( kRenderTransAdd, 255, 0, 0, 128, kRenderFxNoDissipation );
m_pLightGlow->SetColor( 255, 0, 0 );
}
m_pLightGlow->SetBrightness( 164, 0.1f );
m_pLightGlow->SetScale( 0.25f, 0.1f );
m_pLightGlow->SetAsTemporary();
}
}
//-----------------------------------------------------------------------------
void CNPC_Manhack::Activate()
{
BaseClass::Activate();
if ( IsAlive() )
{
StartEye();
}
}
//-----------------------------------------------------------------------------
// Purpose: Get the engine sound started. Unless we're not supposed to have it on yet!
//-----------------------------------------------------------------------------
void CNPC_Manhack::PostNPCInit( void )
{
// SetAbsVelocity( vec3_origin );
m_bBladesActive = (m_spawnflags & (SF_MANHACK_PACKED_UP|SF_MANHACK_CARRIED)) ? false : true;
BladesInit();
}
void CNPC_Manhack::BladesInit()
{
if( !m_bBladesActive )
{
// manhack is packed up, so has no power of its own.
// don't start the engine sounds.
// make us fall a little slower than we should, for visual's sake
SetGravity( UTIL_ScaleForGravity( 400 ) );
SetActivity( ACT_IDLE );
}
else
{
bool engineSound = (m_spawnflags & SF_NPC_GAG) ? false : true;
StartEngine( engineSound );
SetActivity( ACT_FLY );
}
}
//-----------------------------------------------------------------------------
// Crank up the engine!
//-----------------------------------------------------------------------------
void CNPC_Manhack::StartEngine( bool fStartSound )
{
if( fStartSound )
{
SoundInit();
}
// Make the blade appear.
SetBodygroup( 1, 1 );
// Pop up a little if falling fast!
Vector vecVelocity;
GetVelocity( &vecVelocity, NULL );
if( ( m_spawnflags & SF_MANHACK_PACKED_UP ) && vecVelocity.z < 0 )
{
// DevMsg(" POP UP \n" );
// ApplyAbsVelocityImpulse( Vector(0,0,-vecVelocity.z*0.75) );
}
// Under powered flight now.
// SetMoveType( MOVETYPE_STEP );
// SetGravity( MANHACK_GRAVITY );
AddFlag( FL_FLY );
}
//-----------------------------------------------------------------------------
// Purpose: Start the manhack's engine sound.
//-----------------------------------------------------------------------------
void CNPC_Manhack::SoundInit( void )
{
m_nEnginePitch1 = MANHACK_MIN_PITCH1;
m_flEnginePitch1Time = gpGlobals->curtime;
m_nEnginePitch2 = MANHACK_MIN_PITCH2;
m_flEnginePitch2Time = gpGlobals->curtime;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNPC_Manhack::StopLoopingSounds(void)
{
BaseClass::StopLoopingSounds();
m_nEnginePitch1 = -1;
m_flEnginePitch1Time = gpGlobals->curtime;
m_nEnginePitch2 = -1;
m_flEnginePitch2Time = gpGlobals->curtime;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : pTask -
//-----------------------------------------------------------------------------
void CNPC_Manhack::StartTask( const Task_t *pTask )
{
switch (pTask->iTask)
{
case TASK_MANHACK_UNPACK:
{
// Just play a sound for now.
EmitSound( "NPC_Manhack.Unpack" );
TaskComplete();
}
break;
case TASK_MANHACK_HOVER:
break;
case TASK_MOVE_TO_TARGET_RANGE:
case TASK_GET_PATH_TO_GOAL:
case TASK_GET_PATH_TO_ENEMY_LKP:
case TASK_GET_PATH_TO_PLAYER:
{
BaseClass::StartTask( pTask );
/*
// FIXME: why were these tasks considered bad?
_asm
{
int 3;
int 5;
}
*/
}
break;
case TASK_FACE_IDEAL:
{
// this shouldn't ever happen, but if it does, don't choke
TaskComplete();
}
break;
case TASK_GET_PATH_TO_ENEMY:
{
if (IsUnreachable(GetEnemy()))
{
TaskFail(FAIL_NO_ROUTE);
return;
}
CBaseEntity *pEnemy = GetEnemy();
if ( pEnemy == NULL )
{
TaskFail(FAIL_NO_ENEMY);
return;
}
if ( GetNavigator()->SetGoal( GOALTYPE_ENEMY ) )
{
TaskComplete();
}
else
{
// no way to get there =(
DevWarning( 2, "GetPathToEnemy failed!!\n" );
RememberUnreachable(GetEnemy());
TaskFail(FAIL_NO_ROUTE);
}
break;
}
break;
case TASK_GET_PATH_TO_TARGET:
// DevMsg("TARGET\n");
BaseClass::StartTask( pTask );
break;
case TASK_MANHACK_FIND_SQUAD_CENTER:
{
if (!m_pSquad)
{
m_vSavePosition = GetAbsOrigin();
TaskComplete();
break;
}
// calc center of squad
int count = 0;
m_vSavePosition = Vector( 0, 0, 0 );
// give attacking members more influence
AISquadIter_t iter;
for (CAI_BaseNPC *pSquadMember = m_pSquad->GetFirstMember( &iter ); pSquadMember; pSquadMember = m_pSquad->GetNextMember( &iter ) )
{
if (pSquadMember->HasStrategySlotRange( SQUAD_SLOT_ATTACK1, SQUAD_SLOT_ATTACK2 ))
{
m_vSavePosition += pSquadMember->GetAbsOrigin() * 10;
count += 10;
}
else
{
m_vSavePosition += pSquadMember->GetAbsOrigin();
count++;
}
}
// pull towards enemy
if (GetEnemy() != NULL)
{
m_vSavePosition += GetEnemyLKP() * 4;
count += 4;
}
Assert( count != 0 );
m_vSavePosition = m_vSavePosition * (1.0 / count);
TaskComplete();
}
break;
case TASK_MANHACK_FIND_SQUAD_MEMBER:
{
if (m_pSquad)
{
CAI_BaseNPC *pSquadMember = m_pSquad->GetAnyMember();
m_vSavePosition = pSquadMember->GetAbsOrigin();
// find attacking members
AISquadIter_t iter;
for (pSquadMember = m_pSquad->GetFirstMember( &iter ); pSquadMember; pSquadMember = m_pSquad->GetNextMember( &iter ) )
{
// are they attacking?
if (pSquadMember->HasStrategySlotRange( SQUAD_SLOT_ATTACK1, SQUAD_SLOT_ATTACK2 ))
{
m_vSavePosition = pSquadMember->GetAbsOrigin();
break;
}
// do they have a goal?
if (pSquadMember->GetNavigator()->IsGoalActive())
{
m_vSavePosition = pSquadMember->GetAbsOrigin();
break;
}
}
}
else
{
m_vSavePosition = GetAbsOrigin();
}
TaskComplete();
}
break;
case TASK_MANHACK_MOVEAT_SAVEPOSITION:
{
trace_t tr;
AI_TraceLine( GetAbsOrigin(), m_vSavePosition, MASK_NPCWORLDSTATIC, this, COLLISION_GROUP_NONE, &tr );
if (tr.DidHitWorld())
{
TaskFail( FAIL_NO_ROUTE );
}
else
{
m_fSwarmMoveTime = gpGlobals->curtime + RandomFloat( pTask->flTaskData * 0.8, pTask->flTaskData * 1.2 );
}
}
break;
default:
BaseClass::StartTask(pTask);
break;
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNPC_Manhack::UpdateOnRemove( void )
{
DestroySmokeTrail();
KillSprites( 0.0 );
BaseClass::UpdateOnRemove();
}
//-----------------------------------------------------------------------------
// Purpose: This is a generic function (to be implemented by sub-classes) to
// handle specific interactions between different types of characters
// (For example the barnacle grabbing an NPC)
// Input : Constant for the type of interaction
// Output : true - if sub-class has a response for the interaction
// false - if sub-class has no response
//-----------------------------------------------------------------------------
bool CNPC_Manhack::HandleInteraction(int interactionType, void* data, CBaseCombatCharacter* sourceEnt)
{
if (interactionType == g_interactionVortigauntClaw)
{
// Freeze so vortigaunt and hit me easier
m_vForceMoveTarget.x = ((Vector *)data)->x;
m_vForceMoveTarget.y = ((Vector *)data)->y;
m_vForceMoveTarget.z = ((Vector *)data)->z;
m_fForceMoveTime = gpGlobals->curtime + 2.0;
return false;
}
return false;
}
//-----------------------------------------------------------------------------
// Purpose:
// Output : float
//-----------------------------------------------------------------------------
float CNPC_Manhack::ManhackMaxSpeed( void )
{
if( m_flWaterSuspendTime > gpGlobals->curtime )
{
// Slower in water!
return MANHACK_MAX_SPEED * 0.1;
}
if ( HasPhysicsAttacker( MANHACK_SMASH_TIME ) )
{
return MANHACK_NPC_BURST_SPEED;
}
return MANHACK_MAX_SPEED;
}
//-----------------------------------------------------------------------------
// Purpose:
// Output :
//-----------------------------------------------------------------------------
void CNPC_Manhack::ClampMotorForces( Vector &linear, AngularImpulse &angular )
{
float scale = m_flBladeSpeed / 100.0;
// Msg("%.0f %.0f %.0f\n", linear.x, linear.y, linear.z );
float fscale = 3000 * scale;
if ( m_flEngineStallTime > gpGlobals->curtime )
{
linear.x = 0.0f;
linear.y = 0.0f;
linear.z = clamp( linear.z, -fscale, fscale < 1200 ? 1200 : fscale );
}
else
{
// limit reaction forces
linear.x = clamp( linear.x, -fscale, fscale );
linear.y = clamp( linear.y, -fscale, fscale );
linear.z = clamp( linear.z, -fscale, fscale < 1200 ? 1200 : fscale );
}
angular.x *= scale;
angular.y *= scale;
angular.z *= scale;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNPC_Manhack::KillSprites( float flDelay )
{
if( m_pEyeGlow )
{
m_pEyeGlow->FadeAndDie( flDelay );
m_pEyeGlow = NULL;
}
if( m_pLightGlow )
{
m_pLightGlow->FadeAndDie( flDelay );
m_pLightGlow = NULL;
}
// Re-enable for light trails
/*
if ( m_hLightTrail )
{
m_hLightTrail->FadeAndDie( flDelay );
m_hLightTrail = NULL;
}
*/
}
//-----------------------------------------------------------------------------
// Purpose: Tests whether we're above the target's feet but also below their top
// Input : *pTarget - who we're testing against
//-----------------------------------------------------------------------------
bool CNPC_Manhack::IsInEffectiveTargetZone( CBaseEntity *pTarget )
{
Vector vecMaxPos, vecMinPos;
float ourHeight = WorldSpaceCenter().z;
// If the enemy is in a vehicle, we need to get those bounds
if ( pTarget && pTarget->IsPlayer() && assert_cast< CBasePlayer * >(pTarget)->IsInAVehicle() )
{
CBaseEntity *pVehicle = assert_cast< CBasePlayer * >(pTarget)->GetVehicleEntity();
pVehicle->CollisionProp()->NormalizedToWorldSpace( Vector(0.0f,0.0f,1.0f), &vecMaxPos );
pVehicle->CollisionProp()->NormalizedToWorldSpace( Vector(0.0f,0.0f,0.0f), &vecMinPos );
if ( ourHeight > vecMinPos.z && ourHeight < vecMaxPos.z )
return true;
return false;
}
// Get the enemies top and bottom point
pTarget->CollisionProp()->NormalizedToWorldSpace( Vector(0.0f,0.0f,1.0f), &vecMaxPos );
#ifdef _XBOX
pTarget->CollisionProp()->NormalizedToWorldSpace( Vector(0.0f,0.0f,0.5f), &vecMinPos ); // Only half the body is valid
#else
pTarget->CollisionProp()->NormalizedToWorldSpace( Vector(0.0f,0.0f,0.0f), &vecMinPos );
#endif // _XBOX
// See if we're within that range
if ( ourHeight > vecMinPos.z && ourHeight < vecMaxPos.z )
return true;
return false;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *pEnemy -
// &chasePosition -
// &tolerance -
//-----------------------------------------------------------------------------
void CNPC_Manhack::TranslateNavGoal( CBaseEntity *pEnemy, Vector &chasePosition )
{
if ( pEnemy && pEnemy->IsPlayer() && assert_cast< CBasePlayer * >(pEnemy)->IsInAVehicle() )
{
Vector vecNewPos;
CBaseEntity *pVehicle = assert_cast< CBasePlayer * >(pEnemy)->GetVehicleEntity();
pVehicle->CollisionProp()->NormalizedToWorldSpace( Vector(0.5,0.5,0.5f), &vecNewPos );
chasePosition.z = vecNewPos.z;
}
else
{
Vector vecTarget;
pEnemy->CollisionProp()->NormalizedToCollisionSpace( Vector(0,0,0.75f), &vecTarget );
chasePosition.z += vecTarget.z;
}
}
float CNPC_Manhack::GetDefaultNavGoalTolerance()
{
return GetHullWidth();
}
//-----------------------------------------------------------------------------
// Purpose: Input that disables the manhack's swarm behavior
//-----------------------------------------------------------------------------
void CNPC_Manhack::InputDisableSwarm( inputdata_t &inputdata )
{
m_bDoSwarmBehavior = false;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : &inputdata -
//-----------------------------------------------------------------------------
void CNPC_Manhack::InputUnpack( inputdata_t &inputdata )
{
if ( HasSpawnFlags( SF_MANHACK_PACKED_UP ) == false )
return;
SetCondition( COND_LIGHT_DAMAGE );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *pPhysGunUser -
// reason -
//-----------------------------------------------------------------------------
void CNPC_Manhack::OnPhysGunPickup( CBasePlayer *pPhysGunUser, PhysGunPickup_t reason )
{
m_hPhysicsAttacker = pPhysGunUser;
m_flLastPhysicsInfluenceTime = gpGlobals->curtime;
if ( reason == PUNTED_BY_CANNON )
{
StopLoitering();
m_bHeld = false;
// There's about to be a massive change in velocity.
// Think immediately so we can do our slice traces, etc.
SetNextThink( gpGlobals->curtime + 0.01f );
// Stall our engine for awhile
m_flEngineStallTime = gpGlobals->curtime + 2.0f;
SetEyeState( MANHACK_EYE_STATE_STUNNED );
}
else
{
// Suppress collisions between the manhack and the player; we're currently bumping
// almost certainly because it's not purely a physics object.
SetOwnerEntity( pPhysGunUser );
m_bHeld = true;
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *pPhysGunUser -
// Reason -
//-----------------------------------------------------------------------------
void CNPC_Manhack::OnPhysGunDrop( CBasePlayer *pPhysGunUser, PhysGunDrop_t Reason )
{
// Stop suppressing collisions between the manhack and the player
SetOwnerEntity( NULL );
m_bHeld = false;
if ( Reason == LAUNCHED_BY_CANNON )
{
m_hPhysicsAttacker = pPhysGunUser;
m_flLastPhysicsInfluenceTime = gpGlobals->curtime;
// There's about to be a massive change in velocity.
// Think immediately so we can do our slice traces, etc.
SetNextThink( gpGlobals->curtime + 0.01f );
// Stall our engine for awhile
m_flEngineStallTime = gpGlobals->curtime + 2.0f;
SetEyeState( MANHACK_EYE_STATE_STUNNED );
}
else
{
if( m_bHackedByAlyx && !GetEnemy() )
{
// If a hacked manhack is released in peaceable conditions,
// just loiter, don't zip off.
StartLoitering( GetAbsOrigin() );
}
m_hPhysicsAttacker = NULL;
m_flLastPhysicsInfluenceTime = 0;
}
}
void CNPC_Manhack::StartLoitering( const Vector &vecLoiterPosition )
{
//Msg("Start Loitering\n");
m_vTargetBanking = vec3_origin;
m_vecLoiterPosition = GetAbsOrigin();
m_vForceVelocity = vec3_origin;
SetCurrentVelocity( vec3_origin );
}
CBasePlayer *CNPC_Manhack::HasPhysicsAttacker( float dt )
{
// If the player is holding me now, or I've been recently thrown
// then return a pointer to that player
if ( IsHeldByPhyscannon() || (gpGlobals->curtime - dt <= m_flLastPhysicsInfluenceTime) )
{
return m_hPhysicsAttacker;
}
return NULL;
}
//-----------------------------------------------------------------------------
// Manhacks that have been hacked by Alyx get more engine power (fly faster)
//-----------------------------------------------------------------------------
float CNPC_Manhack::GetMaxEnginePower()
{
if( m_bHackedByAlyx )
{
return 2.0f;
}
return 1.0f;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNPC_Manhack::UpdatePanels( void )
{
if ( m_flEngineStallTime > gpGlobals->curtime )
{
SetPoseParameter( m_iPanel1, random->RandomFloat( 0.0f, 90.0f ) );
SetPoseParameter( m_iPanel2, random->RandomFloat( 0.0f, 90.0f ) );
SetPoseParameter( m_iPanel3, random->RandomFloat( 0.0f, 90.0f ) );
SetPoseParameter( m_iPanel4, random->RandomFloat( 0.0f, 90.0f ) );
return;
}
float panelPosition = GetPoseParameter( m_iPanel1 );
if ( m_bShowingHostile )
{
panelPosition = 90.0f;//UTIL_Approach( 90.0f, panelPosition, 90.0f );
}
else
{
panelPosition = UTIL_Approach( 0.0f, panelPosition, 25.0f );
}
//FIXME: If we're going to have all these be equal, there's no need for 4 poses..
SetPoseParameter( m_iPanel1, panelPosition );
SetPoseParameter( m_iPanel2, panelPosition );
SetPoseParameter( m_iPanel3, panelPosition );
SetPoseParameter( m_iPanel4, panelPosition );
//TODO: Make these waver randomly?
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : hostile -
//-----------------------------------------------------------------------------
void CNPC_Manhack::ShowHostile( bool hostile /*= true*/)
{
if ( m_bShowingHostile == hostile )
return;
//TODO: Open the manhack panels or close them, depending on the state
m_bShowingHostile = hostile;
if ( hostile )
{
EmitSound( "NPC_Manhack.ChargeAnnounce" );
}
else
{
EmitSound( "NPC_Manhack.ChargeEnd" );
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNPC_Manhack::StartBurst( const Vector &vecDirection )
{
if ( m_flBurstDuration > gpGlobals->curtime )
return;
ShowHostile();
// Don't burst attack again for a couple seconds
m_flNextBurstTime = gpGlobals->curtime + 2.0;
m_flBurstDuration = gpGlobals->curtime + 1.0;
// Save off where we were going towards and for how long
m_vecBurstDirection = vecDirection;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNPC_Manhack::StopBurst( bool bInterruptSchedule /*= false*/ )
{
if ( m_flBurstDuration < gpGlobals->curtime )
return;
ShowHostile( false );
// Stop our burst timers
m_flNextBurstTime = gpGlobals->curtime + 2.0f; //FIXME: Skill level based
m_flBurstDuration = gpGlobals->curtime - 0.1f;
if ( bInterruptSchedule )
{
// We need to rethink our current schedule
ClearSchedule();
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNPC_Manhack::SetEyeState( int state )
{
// Make sure we're active
StartEye();
switch( state )
{
case MANHACK_EYE_STATE_STUNNED:
{
if ( m_pEyeGlow )
{
//Toggle our state
m_pEyeGlow->SetColor( 255, 128, 0 );
m_pEyeGlow->SetScale( 0.15f, 0.1f );
m_pEyeGlow->SetBrightness( 164, 0.1f );
m_pEyeGlow->m_nRenderFX = kRenderFxStrobeFast;
}
if ( m_pLightGlow )
{
m_pLightGlow->SetColor( 255, 128, 0 );
m_pLightGlow->SetScale( 0.15f, 0.1f );
m_pLightGlow->SetBrightness( 164, 0.1f );
m_pLightGlow->m_nRenderFX = kRenderFxStrobeFast;
}
EmitSound("NPC_Manhack.Stunned");
break;
}
case MANHACK_EYE_STATE_CHARGE:
{
if ( m_pEyeGlow )
{
//Toggle our state
if( m_bHackedByAlyx )
{
m_pEyeGlow->SetColor( 0, 255, 0 );
}
else
{
m_pEyeGlow->SetColor( 255, 0, 0 );
}
m_pEyeGlow->SetScale( 0.25f, 0.5f );
m_pEyeGlow->SetBrightness( 164, 0.1f );
m_pEyeGlow->m_nRenderFX = kRenderFxNone;
}
if ( m_pLightGlow )
{
if( m_bHackedByAlyx )
{
m_pLightGlow->SetColor( 0, 255, 0 );
}
else
{
m_pLightGlow->SetColor( 255, 0, 0 );
}
m_pLightGlow->SetScale( 0.25f, 0.5f );
m_pLightGlow->SetBrightness( 164, 0.1f );
m_pLightGlow->m_nRenderFX = kRenderFxNone;
}
break;
}
default:
if ( m_pEyeGlow )
m_pEyeGlow->m_nRenderFX = kRenderFxNone;
break;
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CNPC_Manhack::CreateVPhysics( void )
{
if ( HasSpawnFlags( SF_MANHACK_CARRIED ) )
return false;
return BaseClass::CreateVPhysics();
}
//-----------------------------------------------------------------------------
//
// Schedules
//
//-----------------------------------------------------------------------------
AI_BEGIN_CUSTOM_NPC( npc_manhack, CNPC_Manhack )
DECLARE_TASK( TASK_MANHACK_HOVER );
DECLARE_TASK( TASK_MANHACK_UNPACK );
DECLARE_TASK( TASK_MANHACK_FIND_SQUAD_CENTER );
DECLARE_TASK( TASK_MANHACK_FIND_SQUAD_MEMBER );
DECLARE_TASK( TASK_MANHACK_MOVEAT_SAVEPOSITION );
DECLARE_CONDITION( COND_MANHACK_START_ATTACK );
DECLARE_ACTIVITY( ACT_MANHACK_UNPACK );
//=========================================================
// > SCHED_MANHACK_ATTACK_HOVER
//=========================================================
DEFINE_SCHEDULE
(
SCHED_MANHACK_ATTACK_HOVER,
" Tasks"
" TASK_SET_ACTIVITY ACTIVITY:ACT_FLY"
" TASK_MANHACK_HOVER 0"
" "
" Interrupts"
" COND_TOO_FAR_TO_ATTACK"
" COND_TOO_CLOSE_TO_ATTACK"
" COND_NEW_ENEMY"
" COND_ENEMY_DEAD"
" COND_LIGHT_DAMAGE"
" COND_HEAVY_DAMAGE"
" COND_ENEMY_OCCLUDED"
);
//=========================================================
// > SCHED_MANHACK_ATTACK_HOVER
//=========================================================
DEFINE_SCHEDULE
(
SCHED_MANHACK_DEPLOY,
" Tasks"
" TASK_PLAY_SEQUENCE ACTIVITY:ACT_MANHACK_UNPACK"
" TASK_SET_ACTIVITY ACTIVITY:ACT_FLY"
" "
// " Interrupts"
);
//=========================================================
// > SCHED_MANHACK_REGROUP
//=========================================================
DEFINE_SCHEDULE
(
SCHED_MANHACK_REGROUP,
" Tasks"
" TASK_STOP_MOVING 0"
" TASK_SET_TOLERANCE_DISTANCE 24"
" TASK_STORE_ENEMY_POSITION_IN_SAVEPOSITION 0"
" TASK_FIND_BACKAWAY_FROM_SAVEPOSITION 0"
" TASK_RUN_PATH 0"
" TASK_WAIT_FOR_MOVEMENT 0"
" "
" Interrupts"
" COND_MANHACK_START_ATTACK"
" COND_NEW_ENEMY"
" COND_CAN_MELEE_ATTACK1"
);
//=========================================================
// > SCHED_MANHACK_SWARN
//=========================================================
DEFINE_SCHEDULE
(
SCHED_MANHACK_SWARM_IDLE,
" Tasks"
" TASK_STOP_MOVING 0"
" TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_MANHACK_SWARM_FAILURE"
" TASK_MANHACK_FIND_SQUAD_CENTER 0"
" TASK_MANHACK_MOVEAT_SAVEPOSITION 5"
" "
" Interrupts"
" COND_NEW_ENEMY"
" COND_SEE_ENEMY"
" COND_SEE_FEAR"
" COND_LIGHT_DAMAGE"
" COND_HEAVY_DAMAGE"
" COND_SMELL"
" COND_PROVOKED"
" COND_GIVE_WAY"
" COND_HEAR_PLAYER"
" COND_HEAR_DANGER"
" COND_HEAR_COMBAT"
" COND_HEAR_BULLET_IMPACT"
);
DEFINE_SCHEDULE
(
SCHED_MANHACK_SWARM,
" Tasks"
" TASK_STOP_MOVING 0"
" TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_MANHACK_SWARM_FAILURE"
" TASK_MANHACK_FIND_SQUAD_CENTER 0"
" TASK_MANHACK_MOVEAT_SAVEPOSITION 1"
" "
" Interrupts"
" COND_NEW_ENEMY"
" COND_CAN_MELEE_ATTACK1"
" COND_LIGHT_DAMAGE"
" COND_HEAVY_DAMAGE"
);
DEFINE_SCHEDULE
(
SCHED_MANHACK_SWARM_FAILURE,
" Tasks"
" TASK_STOP_MOVING 0"
" TASK_WAIT 2"
" TASK_WAIT_RANDOM 2"
" TASK_MANHACK_FIND_SQUAD_MEMBER 0"
" TASK_GET_PATH_TO_SAVEPOSITION 0"
" TASK_WAIT_FOR_MOVEMENT 0"
" "
" Interrupts"
" COND_SEE_ENEMY"
" COND_NEW_ENEMY"
);
AI_END_CUSTOM_NPC()
| [
"steve@swires.me"
] | steve@swires.me |
757ac51f28c3eee86ea67c7fc8196a0d5fa3132a | 9f314c14556a1d2ede69c08ff75d9c3e730adc4f | /oink/Test/template_func6_recursive1.cc | af9f4df8f046f2594bcee0668fe1efb33090c936 | [
"LicenseRef-scancode-other-permissive",
"LicenseRef-scancode-public-domain"
] | permissive | zhouzhenghui/oink-stack | c1077394f6a64c8aec2f3b4d4a322ada3993bc74 | 12901ab95b3ea60360906b63f6602f060ac3de1f | refs/heads/master | 2020-04-13T07:32:05.388961 | 2016-10-21T00:47:35 | 2016-10-21T00:47:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 461 | cc | // test if recursion works
template<class T> T f(T x, T y) {
if (1) { // cqual doesn't see this is determinted at compile time
return x; // bad
} else {
return f(y, 0);
}
}
int main() {
int $tainted a;
// launder the $tainted off of the type so function template
// argument inference doesn't go an infer the return type to be an
// int $tainted
int a2 = a;
int $untainted b;
b = f(3, a2);
}
| [
"daniel.wilkerson@gmail.com"
] | daniel.wilkerson@gmail.com |
929d17f12e659b7a0d951714a5662948a86e69d0 | 63086f69a6a99cbbd668990e7491d6fa31df68e9 | /src/navigation.h | 61deef197e99007826bf69f0162aab11b113cd70 | [] | no_license | changruijuan/avoidoptflow | 37c5fe0d1c47ff767141f7386cf10ce0b48a82e1 | 0c40d1ba269b2b328c883b9be97a1678ffe7b4f3 | refs/heads/master | 2021-01-20T18:08:03.685703 | 2016-07-10T02:35:39 | 2016-07-10T02:35:39 | 61,549,523 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 3,590 | h | /*
* FILE navigation.h
* AUTHOR Sarah
* DATE 2015/08/15 10:42
* TODO: ????????????
*/
#pragma once
#include "stdafx.h"
#include <cv.h>
#include "optutil.h"
#include "opticalflow.h"
using namespace cv;
using namespace std;
#ifndef optflow_NAVIGATION_
#define optflow_NAVIGATION_
//封装 LK/HS/BM
typedef float (*ImgFunType)(IplImage* imgprev, IplImage* imgcurr, CvMat* velx, CvMat* vely);
//封装 SF/FB
typedef Mat (*MatFunType)(Mat frameprev, Mat framecurr, Mat flow);
//封装 PyrLK
typedef float (*ImgFeatureFunType)(IplImage* imgprev, IplImage* imgcurr,CvPoint2D32f* cornersprev,CvPoint2D32f* cornerscurr,CvRect rect, char* status_check);
typedef float (*ImgFeatAllFunType)(IplImage* imgprev, IplImage* imgcurr,CvPoint2D32f* cornersprev,CvPoint2D32f* cornerscurr, char* status_check);
/*
* Method: imgFeatureBalance
* Description: 计算光流,利用光流进行导???
* 被video.h调用, 调用common.h & opt*util.h
* Returns: int.
* ImgFeatureFunType funtype: Required = true. PyrLK方法.
* IplImage * imgprev: Required = true. 第一帧图???
* IplImage * imgcurr: Required = true. 第二帧图???
* IplImage * imgdst: Required = true. 目的图像,在该图像上画光流,输出导航数据???
*/
float imgFeatureStrategic(ImgFeatureFunType funtype,IplImage* imgprev, IplImage* imgcurr, IplImage* imgdst, Mat &color, int strategic = 1);
float imgFeatAllStrategic(ImgFeatAllFunType funtype,IplImage* imgprev, IplImage* imgcurr, IplImage* imgdst, int strategic = 1);
/*
* Method: imgStrategic
* Description: 计算光流,利用光流进行导??? 参数类型为IplImage.
* 被video.h调用, 调用common.h & opt*util.h & motioncolor.h
* Returns: int. ?????????停止4
* ImgFunType funtype: Required = true. LK(Lucaskanade)/HS(HornSchunck)/BM(BlockMatch) 光流计算方法.
* IplImage * imgprev: Required = true. 第一帧图像,原始图像.
* IplImage * imgcurr: Required = true. 第二帧图像,原始图像.
* IplImage * imgdst: Required = true. 目的图像,在该图像上画光流,输出导航数据???
* Mat & color: Required = true. 存放光流转化为颜色的图像.
* int strategic: Required = false. 默认???(左右光流平衡). 在video.h中imgVideo函数中有详细说明.
*/
float imgStrategic(ImgFunType funtype, IplImage* imgprev_1, IplImage* imgcurr_1, IplImage* imgprev, IplImage* imgdst, Mat &color, Mat &gray, int strategic = 1);
/*
* Method: matStrategic
* Description: 计算光流,利用光流进行导??? 参数类型为cv::Mat.
* 被video.h调用, 调用common.h & opt*util.h & motioncolor.h
* Returns: int. ?????????停止4
* MatFunType funtype: Required = SF(SimpleFlow)/FB(FarneBack) 光流计算方法
* Mat frameprev: Required = true. 第一帧图???原始图像没有缩小也没有灰度化处理.
* Mat framecurr: Required = true. 第二帧图???
* Mat framedst: Required = true. 目的图像,在该图像上画光流,输出导航数据???
* Mat & color: Required = true. 存放光流转化为颜色的图像.
* int strategic: Required = false. 默认???(左右光流平衡). 在video.h中imgVideo函数中有详细说明.
* bool issf: Required = false. 默认false,调用FB。但如果调用SF方法,issf必须传??true.
*/
float matStrategic(MatFunType funtype, Mat frameprev_1, Mat framecurr_1, Mat &frameprev, Mat &framedst,Mat &color, Mat &gray, int strategic = 1, bool issf = false);
#endif /* optflow_NAVIGATION_ */
| [
"413676710@qq.com"
] | 413676710@qq.com |
72fbaa3389c0c4352618b533971f452beac04c0d | 4a54dd5a93bbb3f603a2875d5e6dcb3020fb52f2 | /custom/client-rfexe/src/network/Protocol.h | b5659012de9230bec50cd039804dad9ab9a603b5 | [] | no_license | Torashi1069/xenophase | 400ebed356cff6bfb735f9c03f10994aaad79f5e | c7bf89281c95a3c5cf909a14d0568eb940ad7449 | refs/heads/master | 2023-02-02T19:15:08.013577 | 2020-08-17T00:41:43 | 2020-08-17T00:41:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,345 | h | #pragma once
#include "Packet.hpp"
#include "packet/COPY.h"
#include "ProtocolID.h" // enum PROTOID
#include <map>
// Basic packet layout (fixed-length).
struct PACKET
{
/* this+0 */ short PacketType;
/* this+2 */ BYTE Data[];
};
// Basic packet layout (variable-length).
struct PACKETV
{
/* this+0 */ short PacketType;
/* this+2 */ unsigned short PacketLength;
/* this+4 */ BYTE Data[];
};
/// Packet adapter function prototype.
typedef Packet* (AdapterFunc)(short PacketType, Packet* p);
struct PacketInfo
{
short PacketType; // protocol-specific type
PROTOID ProtoID; // universal type
unsigned short Len; // length (total/minimal)
bool isVariable; // type (fixed/variable)
AdapterFunc* ToProto; // input -> proto
AdapterFunc* FromProto; // proto -> output
};
class Protocol
{
public:
Protocol(const char* name);
void Init();
// Info on specific packets.
const PacketInfo* GetInfo(short PacketType) const;
// Info on initial raw packet sent.
const PacketInfo* GetFirstRawPacketInfo() const;
void SetFirstRawPacketInfo(short PacketType);
// Packet adapter operations.
Packet* ToProto(Packet* p) const;
Packet* FromProto(Packet* p) const;
protected:
// Packet registration.
void Register(short PacketType, PROTOID ProtoID, unsigned short Len, bool isVariable, AdapterFunc* ToProto, AdapterFunc* FromProto);
// Instance-specific initialization callback.
virtual void InitInstance();
private:
std::map<short,PacketInfo> m_map; // packet info storage
std::multimap<PROTOID,PacketInfo*> m_proto; // reverse lookup
const PacketInfo* m_rawpacket; // first raw packet info
const char* m_name; // for debugging purposes
bool m_initialized; // only initialize once
};
/// Forward declared template for individual protocol instances.
namespace {
class ProtocolImpl : public Protocol
{
public:
ProtocolImpl(const char* name) : Protocol(name) { };
virtual void InitInstance();
};
}; // namespace
// Convenient macros for packet registration
#define REG0(P) { Register(0, P, 0, false, NULL, NULL); }
#define REGN_2(id,len) { Register(id, PROTOID_COPY, len, false, &PACKET_COPY::ToProto, &PACKET_COPY::FromProto); }
#define REGV_2(id,len) { Register(id, PROTOID_COPY, len, true, &PACKET_COPY::ToProto, &PACKET_COPY::FromProto); }
#define REGN_3(id,len,H) { Register(id, PROTOID_COPY, len, false, &PACKET_COPY::ToProto, &PACKET_COPY::FromProto); }
#define REGV_3(id,len,H) { Register(id, PROTOID_COPY, len, true, &PACKET_COPY::ToProto, &PACKET_COPY::FromProto); }
#define REGN_5(id,len,H,P,T) { Register(id, P, len, false, &T::ToProto, &T::FromProto); C_ASSERT(len == sizeof(T)); }
#define REGV_5(id,len,H,P,T) { Register(id, P, len, true, &T::ToProto, &T::FromProto); C_ASSERT(len == -1 || len == sizeof(T)); }
// Nasty hack wrapper to do macro overloading.
#define N_ARGS_IMPL(_1, _2, _3, _4, _5, _N, ...) _N
#define N_ARGS_GLUE(args) N_ARGS_IMPL args
#define N_ARGS(...) N_ARGS_GLUE((__VA_ARGS__, 5, 4, 3, 2, 1, 0))
#define CHOOSER2(F,N) F##N
#define CHOOSER1(F,N) CHOOSER2(F,N)
#define CHOOSER(F,N) CHOOSER1(F,N)
#define REG_GLUE(x, y) x y
#define REGN(...) REG_GLUE(CHOOSER(REGN_,N_ARGS(__VA_ARGS__)), (__VA_ARGS__))
#define REGV(...) REG_GLUE(CHOOSER(REGV_,N_ARGS(__VA_ARGS__)), (__VA_ARGS__))
//
| [
"50342848+Kokotewa@users.noreply.github.com"
] | 50342848+Kokotewa@users.noreply.github.com |
ca77e5c458389fb3f3a7d39ab905dccc579708fe | 3ae384742655a63bc6437eea66e611c738ad0389 | /teamsyncd/teamsyncd.cpp | cde14dcbd9bcbb9a917f9fda2873476f1e9ac130 | [
"Apache-2.0"
] | permissive | eladraz/sonic-swss | 18cd04b98f45bfa4a736b1c31dc0696cdb6d6eb3 | d744c2cb9193690bfdd0650162504617cee14317 | refs/heads/master | 2020-12-31T07:19:37.857079 | 2016-03-01T08:47:16 | 2016-03-16T08:47:08 | 53,520,084 | 0 | 0 | null | 2016-03-09T18:10:28 | 2016-03-09T18:10:28 | null | UTF-8 | C++ | false | false | 1,100 | cpp | #include <iostream>
#include <team.h>
#include "common/logger.h"
#include "common/select.h"
#include "common/netdispatcher.h"
#include "common/netlink.h"
#include "teamsyncd/teamsync.h"
using namespace std;
using namespace swss;
int main(int argc, char **argv)
{
DBConnector db(APPL_DB, "localhost", 6379, 0);
Select s;
TeamSync sync(&db, &s);
NetDispatcher::getInstance().registerMessageHandler(RTM_NEWLINK, &sync);
NetDispatcher::getInstance().registerMessageHandler(RTM_DELLINK, &sync);
while (1)
{
try
{
NetLink netlink;
netlink.registerGroup(RTNLGRP_LINK);
cout << "Listens to teamd events..." << endl;
netlink.dumpRequest(RTM_GETLINK);
s.addSelectable(&netlink);
while (true)
{
Selectable *temps;
int tempfd;
s.select(&temps, &tempfd);
}
}
catch (...)
{
cout << "Exception had been thrown in deamon" << endl;
return 0;
}
}
return 1;
}
| [
"e@eladraz.com"
] | e@eladraz.com |
d2048775d26990ffcb40cd04b3a6d8abac458fe2 | e2e1e2c27f9a9c13e7492fca93080ea093af7ae5 | /CGRA251/Ass4/work/src/scene/ray.hpp | 526fc66a981020720b48eeaa304370ec1671d229 | [] | no_license | David-B-91/uni | 30ebd03ab065ef96b5cc5033bcac1cbb7a46cab9 | 341c1d5b85f30bdfdfd977627f16aa862a48e923 | refs/heads/master | 2022-03-21T17:01:18.540959 | 2019-11-21T06:33:05 | 2019-11-21T06:33:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 244 | hpp |
#pragma once
// glm
#include <glm/glm.hpp>
// Simple ray class with origin and direction
class Ray {
public:
glm::vec3 origin;
glm::vec3 direction;
Ray() { }
Ray(const glm::vec3 &o, const glm::vec3 &d) : origin(o), direction(d) { }
};
| [
"43230632+ImaDaveDave@users.noreply.github.com"
] | 43230632+ImaDaveDave@users.noreply.github.com |
4ccac36150f7bbad8f398f706aa3ad6118dd2347 | d387c3750d6ee7481df3b30a621a1f1f67a097f2 | /codeforces/797/C.cpp | b3fe69afb676a93976e87b46d0b47c85e4c3eb55 | [] | no_license | sahilkhan03/CF-Solutions | 54b7c4858d0c810ea47768f975f4503bd83fff8b | 67e9e9581d547229b44bee271b4844423fff3a29 | refs/heads/master | 2023-04-22T01:37:43.022110 | 2021-04-19T13:34:00 | 2021-05-10T05:00:23 | 333,403,802 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,699 | cpp | /* ___ |\ /| ____ ____ ____ ____
| | /\ / \ | | | \ / | /\ | \ | \ | | \
|_____| /__\ \____ |_____| | \/ | /__\ |____/ |____/ |__ |____/
| | / \ \ | | | | / \ | | | | \
| | / \ \____/ | | | | / \ | | |____ | \
*/
#include<bits/stdc++.h>
using namespace std;
#define isko_lga_dala_to_life_jhinga_la_la ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define lb lower_bound
#define ub upper_bound
#define pf push_front
#define pb push_back
#define ll long long
#define pi pair<int,int>
#define pl pair<long long,long long>
#define pld pair<long double,long double>
#define endl '\n'
#define loop(i,n) for(ll i=0;i<n;i++)
#define mod ((ll)(1e9+7))
#define in(x) scanf("%lld",&x)
#define in2(x,y) scanf("%lld %lld",&x,&y)
#define in3(x,y,z) scanf("%lld %lld %lld",&x,&y,&z)
#define inv(v) for(auto&i:v) in(i)
#define vl vector<ll>
#define ml unordered_map<ll,ll>
#define vpl vector<pair<ll,ll>>
#define INF 0x3f3f3f3f
template<typename T, typename TT>
ostream& operator<<(ostream &os, const pair<T, TT> &t) { return os<<t.first<<" "<<t.second; }
template<typename T>
ostream& operator<<(ostream& os, const vector<T> &t) { for(auto& i: t) os<<i<<" "; return os; }
int main() {
string s;
cin>>s;
ll n = s.size();
ll c[n+1];
c[n]='z';
for(ll i=n-1;i>=0;i--) c[i] = min(c[i+1],(ll)(s[i]));
stack<ll> t;
loop(i,n) {
t.push(s[i]);
while (!t.empty() and t.top()<=c[i+1])
{
cout<<char(t.top());
t.pop();
}
}
return 0;
} | [
"sahilkhan0307.sk@gmail.com"
] | sahilkhan0307.sk@gmail.com |
094dd51d4ca98bc1da9767101d85a27d024ef3ab | 4456e1aeaec66c11e45c2c134a9201aa2d7613dd | /random-reduction/reduction.cpp | 29c7ca1b5fdcd63c04d2e1d3d3621ac686c6755d | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | Harry-Chen/parallel-computing-assignments | 090f51fc62c63aed4765b25196159d3fe45e80b5 | 821db333f61860536475d69da368caf30763cb7b | refs/heads/master | 2023-03-28T08:22:24.907987 | 2021-04-04T12:08:35 | 2021-04-04T12:08:35 | 354,534,173 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,607 | cpp | #include <algorithm>
#include <cmath>
#include <fstream>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#define epsilon 1.e-8
using namespace std;
int main(int argc, char *argv[]) {
int M, N;
string T, P, Db;
M = atoi(argv[1]);
N = atoi(argv[2]);
double elapsedTime, elapsedTime2;
timeval start, end, end2;
if (argc > 3) {
T = argv[3];
if (argc > 4) {
P = argv[4];
if (argc > 5) {
Db = argv[5];
}
}
}
// cout<<T<<P<<endl;
double **U_t;
double alpha, beta, gamma, **Alphas, **Betas, **Gammas;
int acum = 0;
int temp1, temp2;
U_t = new double *[M];
Alphas = new double *[M];
Betas = new double *[M];
Gammas = new double *[M];
for (int i = 0; i < M; i++) {
U_t[i] = new double[N];
Alphas[i] = new double[M];
Betas[i] = new double[M];
Gammas[i] = new double[M];
}
// Read from file matrix, if not available, app quit
// Already transposed
ifstream matrixfile("matrix");
if (!(matrixfile.is_open())) {
cout << "Error: file not found" << endl;
return 0;
}
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
matrixfile >> U_t[i][j];
}
}
matrixfile.close();
/* Reductions */
gettimeofday(&start, NULL);
double conv;
for (int i = 0; i < M; i++) { // convergence
for (int j = 0; j < M; j++) {
alpha = 0.0;
beta = 0.0;
gamma = 0.0;
for (int k = 0; k < N; k++) {
alpha = alpha + (U_t[i][k] * U_t[i][k]);
beta = beta + (U_t[j][k] * U_t[j][k]);
gamma = gamma + (U_t[i][k] * U_t[j][k]);
}
Alphas[i][j] = alpha;
Betas[i][j] = beta;
Gammas[i][j] = gamma;
}
}
gettimeofday(&end, NULL);
// fix final result
// Output time and iterations
if (T == "-t" || P == "-t") {
elapsedTime = (end.tv_sec - start.tv_sec) * 1000.0;
elapsedTime += (end.tv_usec - start.tv_usec) / 1000.0;
cout << "Time: " << elapsedTime << " ms." << endl << endl;
}
// Output the matrixes for debug
if (T == "-p" || P == "-p") {
cout << "Alphas" << endl << endl;
for (int i = 0; i < M; i++) {
for (int j = 0; j < M; j++) {
cout << Alphas[i][j] << " ";
}
cout << endl;
}
cout << endl << "Betas" << endl << endl;
for (int i = 0; i < M; i++) {
for (int j = 0; j < M; j++) {
cout << Betas[i][j] << " ";
}
cout << endl;
}
cout << endl << "Gammas" << endl << endl;
for (int i = 0; i < M; i++) {
for (int j = 0; j < M; j++) {
cout << Gammas[i][j] << " ";
}
cout << endl;
}
}
// Generate files for debug purpouse
if (Db == "-d" || T == "-d" || P == "-d") {
ofstream Af;
// file for Matrix A
Af.open("Alphas.mat");
/* Af<<"# Created from debug\n# name: A\n# type: matrix\n# rows:
* "<<M<<"\n# columns: "<<N<<"\n";*/
Af << M << " " << N;
for (int i = 0; i < M; i++) {
for (int j = 0; j < M; j++) {
Af << " " << Alphas[i][j];
}
Af << "\n";
}
Af.close();
ofstream Uf;
// File for Matrix U
Uf.open("Betas.mat");
/* Uf<<"# Created from debug\n# name: Ugpu\n# type: matrix\n# rows:
* "<<M<<"\n# columns: "<<N<<"\n";*/
for (int i = 0; i < M; i++) {
for (int j = 0; j < M; j++) {
Uf << " " << Betas[i][j];
}
Uf << "\n";
}
Uf.close();
ofstream Vf;
// File for Matrix V
Vf.open("Gammas.mat");
/* Vf<<"# Created from debug\n# name: Vgpu\n# type: matrix\n# rows:
* "<<M<<"\n# columns: "<<N<<"\n";*/
for (int i = 0; i < M; i++) {
for (int j = 0; j < M; j++) {
Vf << " " << Gammas[i][j];
}
Vf << "\n";
}
Vf.close();
ofstream Sf;
}
for (int i = 0; i < M; i++) {
delete[] Alphas[i];
delete[] U_t[i];
delete[] Betas[i];
delete[] Gammas[i];
}
delete[] Alphas;
delete[] Betas;
delete[] Gammas;
delete[] U_t;
return 0;
}
| [
"i@harrychen.xyz"
] | i@harrychen.xyz |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.