blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
264
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
85
| license_type
stringclasses 2
values | repo_name
stringlengths 5
140
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 905
values | visit_date
timestamp[us]date 2015-08-09 11:21:18
2023-09-06 10:45:07
| revision_date
timestamp[us]date 1997-09-14 05:04:47
2023-09-17 19:19:19
| committer_date
timestamp[us]date 1997-09-14 05:04:47
2023-09-06 06:22:19
| github_id
int64 3.89k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us]date 2012-06-07 00:51:45
2023-09-14 21:58:39
⌀ | gha_created_at
timestamp[us]date 2008-03-27 23:40:48
2023-08-21 23:17:38
⌀ | gha_language
stringclasses 141
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 3
10.4M
| extension
stringclasses 115
values | content
stringlengths 3
10.4M
| authors
sequencelengths 1
1
| author_id
stringlengths 0
158
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0ee9a08d8024d0d9c13bec8c62b60209b87d73f8 | 6f460a74aec561106fe1e31d24501b8713686239 | /problems/2720.cpp | 8a9b103497f557e46089ff66ed56af12260d9461 | [] | no_license | JVelezMed/caribbean-online-judge-solutions | 0d7a4423e5c340944aedca8134f3d9732fb71980 | 43929a7c90f26f0a1e254797dc1ed8f1f728417c | refs/heads/master | 2020-06-14T20:14:57.216235 | 2019-07-03T19:36:22 | 2019-07-03T19:36:22 | 195,113,656 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,860 | cpp | #include <iostream>
#include <cstdio>
#include <cstring>
#include <math.h>
using namespace std;
int i,j,pos = 1;
int primes[168];
bool sieve[1001]; //determines which numbers are composite
//Modified Erathostenes Sieve
void build_sieve(int upperBound){
int limit = (int)sqrt(upperBound);
primes[0] = 2; //the first prime is 2
//true = composite, false = possible prime
for(i = 3; i <= upperBound; i+=2) sieve[i] = false; //all odd numbers are possible primes
for(i = 4; i <= upperBound; i+=2) sieve[i] = true; //all even numbers are composite
//All odds found
for(i = 3; i <= upperBound; i+=2) {
if(!sieve[i]){
//printf("%d\n", i);
primes[pos++] = i;
if(i <= limit) for(j = i*i; j <= upperBound; j+=i) sieve[j] = true;
}
}
//printf("%d", pos);
}
bool canBeExpressedAsPrimeSum(int number);
int main(void){
build_sieve(1000);
int array[1001];
for (int i = 0; i < 168; ++i) {
//printf("%d\n", primes[i]);
}
int count = 0;
int next = 0;
for (int i = 2; i <= 997;) {
if(canBeExpressedAsPrimeSum(primes[next++])) {
++count;
}
while(i < primes[next] && i <= 1000) {
//printf("%d %d\n",i, count);
array[i++] = count;
}
}
int N, leastNumOfPrimes;;
scanf("%d %d",&N, &leastNumOfPrimes);
printf("%s\n", leastNumOfPrimes <= array[N] ? "YES" : "NO");
return 0;
}
bool canBeExpressedAsPrimeSum(int number) {
for (int i = 0; i <= 166 && primes[i] + primes[i+1] + 1 <= number; ++i) {
//printf(" %d\n", primes[i]);
if(primes[i] + primes[i+1] + 1 == number) {
//printf("%d = %d + %d + 1\n", number, primes[i], primes[i+1]);
return true;
}
}
return false;
} | [
"[email protected]"
] | |
729f1dbd4cd9b6e71c0f154c59bd50a773ec2240 | e110e0f375b325ff13c0fd3fe23c0b7299dd44c3 | /serial/tool.cpp | 966ee577ef4a41160f4eb5a16821f6250227f98f | [] | no_license | fatemedbghi/mobile-price-classification | 659baca9d230ca2e1c50816771ef97a9be3aadcd | 223903fc8074b9d7a3ef19805d6d705b90de2bea | refs/heads/master | 2023-02-12T22:09:52.606861 | 2020-12-13T20:15:43 | 2020-12-13T20:15:43 | 331,942,176 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,425 | cpp | #include "tool.h"
using namespace std;
vector<string> files(char* path)
{
struct dirent *de;
DIR *dr = opendir(path);
if (dr == NULL)
{
printf("Could not open current directory\n");
exit(1);
}
string str_path(path);
vector <string> dir(2, "");
while ((de = readdir(dr)) != NULL)
{
string str(de->d_name);
string temp = str_path + str;
if (str.compare("..") != 0 && str.compare(".") != 0)
{
if (str.compare("weights.csv") == 0)
dir[1] = temp;
else
dir[0] = temp;
}
}
closedir(dr);
return dir;
}
vector<vector<float>> store_weight(string file_name)
{
vector<vector<float>> weight;
fstream fin;
fin.open(file_name, ios::in);
string line, word;
int i = 0;
while (fin.good()){
getline(fin, line);
vector<float> temp;
stringstream l(line);
string token;
if (!line.empty())
{
while(getline(l, token, ',') && i!=0)
temp.push_back(stof(token));
if (i!=0) weight.push_back(temp);
i++;
}
}
return weight;
}
vector<vector<float>> store_train_data(string file_name)
{
vector<vector<float>> train_data;
fstream fin;
fin.open(file_name, ios::in);
string line, word;
int i = 0;
while (fin.good()){
getline(fin, line);
vector<float> temp;
stringstream l(line);
string token;
if (!line.empty())
{
while(getline(l, token, ',') && i!=0)
{
temp.push_back(stof(token));
}
if (i!=0) train_data.push_back(temp);
i++;
}
}
return train_data;
}
vector<vector<float>> normalize_data(vector<vector<float>> train)
{
int i;
for (i = 0; i < 20; i++)
{
if (i!=1 && i!=3 && i!=5 && i!=17 && i!=18 && i!=19)
{
vector<float> temp;
for(int j=0; j<train.size();j++)
{
temp.push_back(train[j][i]);
}
float min = *min_element(temp.begin(), temp.end());
float max = *max_element(temp.begin(), temp.end());
for(int j=0; j<train.size();j++)
{
train[j][i] = (train[j][i] - min)/(max - min);
}
}
}
return train;
}
vector<int> predict_price(vector<vector<float>> weights, vector<vector<float>> normalized_train)
{
vector<int> predicion;
for (int i=0; i< normalized_train.size(); i++)
{
vector<float>temp;
for (int j=0; j<weights.size(); j++)
{
float price = 0;
for (int k=0; k<weights[0].size()-1; k++)
price += weights[j][k]*normalized_train[i][k];
price += weights[j][weights[0].size()-1];
temp.push_back(price);
}
int p = max_element(temp.begin(),temp.end()) - temp.begin();
predicion.push_back(p);
temp.clear();
}
return predicion;
}
float calc_accuracy(vector<vector<float>> train_data, vector<int> prediction)
{
float acc = 0;
for (int i=0; i<prediction.size(); i++)
{
if (prediction[i] == train_data[i][20])
acc++;
}
return (acc*100/prediction.size());
} | [
"[email protected]"
] | |
e052cfe8c2b761332ba8fceef0140364ffff159c | 6ec4087fb56ba7b33aada9b58a9aef80eb2de786 | /gamesdk/src/soap/serversRoutine.cpp | 2232c2e64ee59e7b6577cb10531d643f68761ef2 | [] | no_license | wangscript007/xg-sdk | 660d46fb8b66bb24676ea751630a5b2e461f74e3 | e027f2382ea71c59d8d87552cd005fb3a589537c | refs/heads/master | 2022-11-12T17:09:27.794713 | 2020-06-03T00:36:11 | 2020-06-03T00:36:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,406 | cpp | /*
* This file was auto-generated by the Axis C++ Web Service Generator (WSDL2Ws)
* This file contains functions to manipulate complex type serversRoutine
*/
#include "serversRoutine.hpp"
#include <axis/AxisWrapperAPI.hpp>
/*
* This static method serialize a serversRoutine type of object
*/
int Axis_Serialize_serversRoutine(serversRoutine* param, IWrapperSoapSerializer* pSZ, bool bArray = false)
{
if (bArray)
{
pSZ->serialize("<", Axis_TypeName_serversRoutine, ">", NULL);
}
else
{
const AxisChar* sPrefix = pSZ->getNamespacePrefix(Axis_URI_serversRoutine);
pSZ->serialize("<", Axis_TypeName_serversRoutine, " xsi:type=\"", sPrefix, ":",
Axis_TypeName_serversRoutine, "\" xmlns:", sPrefix, "=\"",
Axis_URI_serversRoutine, "\">", NULL);
}
pSZ->serializeAsElement("id", (void*)&(param->id), XSD_LONG);
pSZ->serializeAsElement("name", (void*)&(param->name), XSD_STRING);
pSZ->serialize("</", Axis_TypeName_serversRoutine, ">", NULL);
return AXIS_SUCCESS;
}
/*
* This static method deserialize a serversRoutine type of object
*/
int Axis_DeSerialize_serversRoutine(serversRoutine* param, IWrapperSoapDeSerializer* pIWSDZ)
{
param->id = pIWSDZ->getElementAsLong("id",0);
param->name = pIWSDZ->getElementAsString("name",0);
return pIWSDZ->getStatus();
}
void* Axis_Create_serversRoutine(serversRoutine* pObj, bool bArray = false, int nSize=0)
{
if (bArray && (nSize > 0))
{
if (pObj)
{
serversRoutine* pNew = new serversRoutine[nSize];
memcpy(pNew, pObj, sizeof(serversRoutine)*nSize/2);
memset(pObj, 0, sizeof(serversRoutine)*nSize/2);
delete [] pObj;
return pNew;
}
else
{
return new serversRoutine[nSize];
}
}
else
return new serversRoutine;
}
/*
* This static method delete a serversRoutine type of object
*/
void Axis_Delete_serversRoutine(serversRoutine* param, bool bArray = false, int nSize=0)
{
if (bArray)
{
delete [] param;
}
else
{
delete param;
}
}
/*
* This static method gives the size of serversRoutine type of object
*/
int Axis_GetSize_serversRoutine()
{
return sizeof(serversRoutine);
}
serversRoutine::serversRoutine()
{
/*do not allocate memory to any pointer members here
because deserializer will allocate memory anyway. */
memset( &id, 0, sizeof( xsd__long));
memset( &name, 0, sizeof( xsd__string));
}
serversRoutine::~serversRoutine()
{
/*delete any pointer and array members here*/
}
| [
"[email protected]"
] | |
daa649fa62d936d191676862cf947b83a5f532ad | 43ef1f7464e4dbaacb116176698c6c09daef3558 | /과제제출/API/Chese/Chese/Player.cpp | 782d19b8dab807e95116e482c74c9717da5ab68b | [] | no_license | Sicarim/UmDoYun | ab17b61c0679fb9cffb48863b152b1425c288745 | ec7f29025ee1b6d649a1a6fc97913c42081095eb | refs/heads/master | 2023-04-29T11:18:55.521613 | 2021-05-11T07:43:07 | 2021-05-11T07:43:07 | 207,284,540 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 8,846 | cpp | #include "Player.h"
#include "GameManager.h"
#include "BitMapManager.h"
//생성자
Player::Player()
{
m_Unit = NULL;
m_SelectRect = {0};
rcRect = {0};
Selecting = false;
tmp_Num = 0;
Current_Unit = 0;
}
//플레이어 구분을 위한 정보
void Player::set_Player_Num(int _num)
{
Player_Num = _num;
}
//플레이어 구분을 위한 정보
int Player::get_Player_Num()
{
return Player_Num;
}
//Unit's Make
void Player::Make_Unit(HWND hWnd, int _posy1, int _posy2)
{
int Unit_Count = 1;
/*
기준점 75, 75(맵 가장 첫번째 칸
가로 간격: 101
세로 간격: 101
*/
//Make Pawn
for (int i = 0; i < 8; i++)
{
m_Unit = Generate_Class(CLASS_PAWN);
m_Unit->Unit_Behavior(hWnd, i, _posy1, Player_Num);
m_vPawn.push_back(m_Unit);
}
//Make Knight
for (int i = 0; i < 2; i++)
{
m_Unit = Generate_Class(CLASS_KNIGHT);
m_Unit->Unit_Behavior(hWnd, Unit_Count, _posy2, Player_Num);
m_vKnight.push_back(m_Unit);
Unit_Count += 5;
}
Unit_Count = 0;
//Make Rook
for (int i = 0; i < 2; i++)
{
m_Unit = Generate_Class(CLASS_ROOK);
m_Unit->Unit_Behavior(hWnd, Unit_Count, _posy2, Player_Num);
m_vRook.push_back(m_Unit);
Unit_Count += 7;
}
Unit_Count = 2;
//MakeBishop
for (int i = 0; i < 2; i++)
{
m_Unit = Generate_Class(CLASS_BISHOP);
m_Unit->Unit_Behavior(hWnd, Unit_Count, _posy2, Player_Num);
m_vBishop.push_back(m_Unit);
Unit_Count += 3;
}
//Make King
m_Unit = Generate_Class(CLASS_KING);
m_Unit->Unit_Behavior(hWnd, 3, _posy2, Player_Num);
m_vKing.push_back(m_Unit);
//Make Queen
m_Unit = Generate_Class(CLASS_QUEEN);
m_Unit->Unit_Behavior(hWnd, 4, _posy2, Player_Num);
m_vQueen.push_back(m_Unit);
}
///unit all Draw(제일 처음)
void Player::Unit_DrawInit(HWND hWnd)
{
//Pawn
Draw_Update(hWnd, m_vPawn, Player_Num);
//Knight
Draw_Update(hWnd, m_vKnight, Player_Num);
//Rook
Draw_Update(hWnd, m_vRook, Player_Num);
//Bishop
Draw_Update(hWnd, m_vBishop, Player_Num);
//King
Draw_Update(hWnd, m_vKing, Player_Num);
//Queen
Draw_Update(hWnd, m_vQueen, Player_Num);
if (Player_Num == PLAYER_ONE)
{
GameManager::get_Instence()->insert_WhiteUnit(m_vBishop, m_vKing, m_vKnight, m_vPawn, m_vQueen, m_vRook);
}
else
{
GameManager::get_Instence()->insert_BlackUnit(m_vBishop, m_vKing, m_vKnight, m_vPawn, m_vQueen, m_vRook);
}
}
//Click
void Player::Click(HWND hWnd, int _ptx, int _pty)
{
int tmp_ptx = floor(GameManager::get_Instence()->get_UnitXY(_ptx));
int tmp_pty = floor(GameManager::get_Instence()->get_UnitXY(_pty));
int Box_ptx = GameManager::get_Instence()->get_DrawXY(tmp_ptx);
int Box_pty = GameManager::get_Instence()->get_DrawXY(tmp_pty);
int tmp_UnitPosX = 0;
int tmp_UnitPosY = 0;
BitMapManager::get_Instence()->Select_Draw(hWnd, Box_ptx, Box_pty);
m_SelectRect = { Box_ptx, Box_pty, Box_ptx + 101, Box_pty + 101};
Delete_unitVector();
//충돌 처리
//Pawn
Hit_Update(hWnd, m_vPawn, tmp_ptx, tmp_pty);
//Rook
Hit_Update(hWnd, m_vRook, tmp_ptx, tmp_pty);
//Knight
Hit_Update(hWnd, m_vKnight, tmp_ptx, tmp_pty);
//Bishop
Hit_Update(hWnd, m_vBishop, tmp_ptx, tmp_pty);
//King
Hit_Update(hWnd, m_vKing, tmp_ptx, tmp_pty);
//Queen
Hit_Update(hWnd, m_vQueen, tmp_ptx, tmp_pty);
Player_reInit();
}
//유닛을 움직이기 위해 클릭
bool Player::Move_Click(HWND hWnd, int _ptx, int _pty)
{
bool tmp_bo = true;
int tmp_ptx = floor(GameManager::get_Instence()->get_UnitXY(_ptx));
int tmp_pty = floor(GameManager::get_Instence()->get_UnitXY(_pty));
int Box_ptx = GameManager::get_Instence()->get_DrawXY(tmp_ptx);
int Box_pty = GameManager::get_Instence()->get_DrawXY(tmp_pty);
m_SelectRect = { Box_ptx, Box_pty, Box_ptx + 101, Box_pty + 101 };
tmp_vRect = tmp_vUnit[tmp_Num]->get_vblend();
for (int i = 0; i < tmp_vRect.size(); i++)
{
//블랜드(유닛이 갈수 있는곳)을 클릭했을때
if (IntersectRect(&rcRect, &m_SelectRect, &tmp_vRect[i]))
{
//자신이 있던 위치를 빈공간으로 만든다.
int tmp_posx = tmp_vUnit[tmp_Num]->get_PosX();
int tmp_posy = tmp_vUnit[tmp_Num]->get_PosY();
GameManager::get_Instence()->set_UnitPos(tmp_posx, tmp_posy, CLASS_END);
//
if (GameManager::get_Instence()->get_UnitPos(tmp_ptx, tmp_pty) != CLASS_END)
{
tmp_bo = GameManager::get_Instence()->inspection_Unit(tmp_ptx, tmp_pty, Player_Num);
}
if (tmp_bo)
{
tmp_vUnit[tmp_Num]->Move_Unit(hWnd, tmp_ptx, tmp_pty);
Player_reInit();
Selecting = false;
return true;
}
}
}
Selecting = false;
return false;
}
//충돌 처리
void Player::Hit_Update(HWND hWnd, vector<UnitFactory*> _vunit, int _posx, int _posy)
{
for (int i = 0; i < _vunit.size(); i++)
{
tmp_UnitRect = _vunit[i]->get_Rect();
if (IntersectRect(&rcRect, &m_SelectRect, &tmp_UnitRect))
{
_vunit[i]->Clicked_Unit(hWnd, _posx, _posy);
tmp_vUnit = _vunit;
tmp_Num = i;
Current_Unit = _vunit[i]->get_Class();
Selecting = true;
}
}
}
//벡터 삭제하기
void Player::Delete_unitVector()
{
UnitFactory* tmp_unit;
if (GameManager::get_Instence()->get_isDelete())
{
tmp_unit = GameManager::get_Instence()->Delete_Unit();
tmp_unit->get_Class();
if (tmp_unit->get_Class() == CLASS_PAWN)
{
for (int i = 0; m_vPawn.size(); i++)
{
if (m_vPawn[i] == tmp_unit)
{
m_vPawn.erase(m_vPawn.begin() + i);
GameManager::get_Instence()->set_isDelete(false);
break;
}
}
}
if (tmp_unit->get_Class() == CLASS_QUEEN)
{
for (int i = 0; m_vQueen.size(); i++)
{
if (m_vQueen[i] == tmp_unit)
{
m_vQueen.erase(m_vQueen.begin() + i);
GameManager::get_Instence()->set_isDelete(false);
break;
}
}
}
if (tmp_unit->get_Class() == CLASS_ROOK)
{
for (int i = 0; m_vRook.size(); i++)
{
if (m_vRook[i] == tmp_unit)
{
m_vRook.erase(m_vRook.begin() + i);
GameManager::get_Instence()->set_isDelete(false);
return;
}
}
}
if (tmp_unit->get_Class() == CLASS_KNIGHT)
{
for (int i = 0; m_vKnight.size(); i++)
{
if (m_vKnight[i] == tmp_unit)
{
m_vKnight.erase(m_vKnight.begin() + i);
GameManager::get_Instence()->set_isDelete(false);
return;
}
}
}
if (tmp_unit->get_Class() == CLASS_BISHOP)
{
for (int i = 0; m_vBishop.size(); i++)
{
if (m_vBishop[i] == tmp_unit)
{
m_vBishop.erase(m_vBishop.begin() + i);
GameManager::get_Instence()->set_isDelete(false);
return;
}
}
}
}
}
//유닛 그리기
void Player::Draw_Update(HWND hWnd, vector<UnitFactory*> _vunit, int _num)
{
for (int i = 0; i < _vunit.size(); i++)
{
_vunit[i]->Unit_Draw(hWnd, _num);
}
}
//취소하기
bool Player::CancelUpdate(int _ptx, int _pty)
{
RECT tmp_Rect;
RECT tmp_SelectRect;
int tmp_ptx = floor(GameManager::get_Instence()->get_UnitXY(_ptx));
int tmp_pty = floor(GameManager::get_Instence()->get_UnitXY(_pty));
int Box_ptx = GameManager::get_Instence()->get_DrawXY(tmp_ptx);
int Box_pty = GameManager::get_Instence()->get_DrawXY(tmp_pty);
tmp_SelectRect = { Box_ptx, Box_pty, Box_ptx + 101, Box_pty + 101 };
Selecting = false;
for (int i = 0; i < m_vPawn.size(); i++)
{
tmp_Rect = m_vPawn[i]->get_Rect();
if (IntersectRect(&rcRect, &tmp_SelectRect, &tmp_Rect))
{
return false;
}
}
return true;
}
void Player::Player_reInit()
{
if (GameManager::get_Instence()->get_isChange() && GameManager::get_Instence()->get_changePlayer() == Player_Num)
{
tmp_Unit = GameManager::get_Instence()->isChange_Unit();
if (tmp_Unit->get_Class() == CLASS_BISHOP)
{
m_vBishop.push_back(tmp_Unit);
}
else if (tmp_Unit->get_Class() == CLASS_KNIGHT)
{
m_vKnight.push_back(tmp_Unit);
}
else if (tmp_Unit->get_Class() == CLASS_QUEEN)
{
m_vQueen.push_back(tmp_Unit);
}
else if (tmp_Unit->get_Class() == CLASS_ROOK)
{
m_vRook.push_back(tmp_Unit);
}
}
if (Player_Num == PLAYER_ONE)
{
GameManager::get_Instence()->insert_WhiteUnit(m_vBishop, m_vKing, m_vKnight, m_vPawn, m_vQueen, m_vRook);
}
else
{
GameManager::get_Instence()->insert_BlackUnit(m_vBishop, m_vKing, m_vKnight, m_vPawn, m_vQueen, m_vRook);
}
}
//유닛 직업 생성
UnitFactory* Player::Generate_Class(UNIT_CLASS _class)
{
switch (_class)
{
case CLASS_PAWN:
return new Pawn;
case CLASS_KING:
return new King;
case CLASS_QUEEN:
return new Queen;
case CLASS_ROOK:
return new Rook;
case CLASS_KNIGHT:
return new Knight;
case CLASS_BISHOP:
return new Bishop;
}
}
//이동하기 위해 유닛을 선택했는지 알려준다.
bool Player::get_Selecting()
{
return Selecting;
}
//데이터 삭제
void Player::Player_Release()
{
m_vPawn.clear();
m_vKnight.clear();
m_vRook.clear();
m_vBishop.clear();
m_vKing.clear();
m_vQueen.clear();
tmp_vUnit.clear();
tmp_vUnit.clear();
tmp_vRect.clear();
}
//소멸자
Player::~Player()
{
Player_Release();
} | [
"[email protected]"
] | |
5e76efb3e696fc35d9377779858759da037787f9 | 8f3ef878f138146a9df34440103d45607afeb48e | /Qt/GraphicsView/engine/ScaleEdgeWidget.h | ed2d28b8839c5cf42dd6102b9cb58d19cec2303e | [] | no_license | afester/CodeSamples | aa67a8d6f5c451dc92131a8722f301d026f5a894 | 10a2675f77e779d793d63e973672548aa263597b | refs/heads/main | 2023-01-05T06:45:52.130668 | 2022-12-23T21:36:36 | 2022-12-23T21:36:36 | 8,028,224 | 10 | 11 | null | 2022-10-02T18:53:29 | 2013-02-05T11:57:35 | Java | UTF-8 | C++ | false | false | 630 | h | /**
* This work is licensed under the Creative Commons Attribution 3.0 Unported
* License. To view a copy of this license, visit
* http://creativecommons.org/licenses/by/3.0/ or send a letter to Creative
* Commons, 444 Castro Street, Suite 900, Mountain View, California, 94041, USA.
*/
#include <QWidget>
#ifdef ENGINE_LIBRARY
class Q_DECL_EXPORT ScaleEdgeWidget : public QWidget {
#else
class Q_DECL_IMPORT ScaleEdgeWidget : public QWidget {
#endif
QString unit;
public:
ScaleEdgeWidget(QWidget* parent);
void setUnit(const QString& theUnit);
protected:
void paintEvent ( QPaintEvent * event );
};
| [
"[email protected]"
] | |
e8060273bd8977d9aaa6bd883435a01a38933cea | a5671cbd258b71109fa4b414afde10fc992c585e | /include/algorithms/ising/metropolis.h | 3dd7458ee26e6c3c4d2089cb55869a105f91fe5c | [
"MIT"
] | permissive | TiarnaNaTuaithe/ising-graph | ba2cca93d0dab1c0a49b10d292a8f3f558437413 | 792c51f7330d77a692b71d1b0bd68b628bd23b6f | refs/heads/master | 2020-03-26T01:59:16.883120 | 2018-09-01T12:24:15 | 2018-09-01T12:33:08 | 144,391,453 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,697 | h | #pragma once
/**
@file
@brief This file contains a Metropolis algorithm implementation for the Ising
model
*/
#include <stdexcept>
#include <vector>
#include "../../mersenne.h"
namespace isinggraph::ising {
//! A Metropolis algorithm policy for the Ising model
class Metropolis {
public:
using site_type_t = int;
//! Performs a metropolis update for each node
/*!
Sweeps the entire graph and performs a Metropolis update of each node
@param values The vector of node values
@param beta The inverse temperature parameter of the system
@param get_neighbours A callback to get a vector of the neighbours of a node
*/
template <typename F>
void sweep(std::vector<site_type_t>& values, double const& beta,
F&& get_neighbours);
private:
std::uniform_real_distribution<double> random_double_{
0.0, 1.0}; //! < Generates random doubles in [0,1)
};
template <typename F>
void Metropolis::sweep(std::vector<site_type_t>& values, double const& beta,
F&& get_neighbours) {
auto energy_difference = [&](int node) -> int {
int mismatched_neighbours = 0;
auto const& neighbours = get_neighbours(node);
for (auto const& n : neighbours) {
mismatched_neighbours += static_cast<int>(values[n] != values[node]);
}
// The following is derived from the Ising Hamiltonian.
return 2 * (neighbours.size() - 2 * mismatched_neighbours);
};
for (auto i = 0u; i < values.size(); ++i) {
auto const delta_e = energy_difference(i);
if (delta_e < 0 ||
exp(-1 * beta * delta_e) > random_double_(random::mersenne_twister())) {
values[i] *= -1;
}
}
}
} // namespace isinggraph::ising
| [
"[email protected]"
] | |
0822781940aa7d490c6131394802af3249b86b05 | 8403738e873da6add2b5d32beb8105fe8d2e66cb | /C++ Primer plus/5_circulate-and-rel_exp/test/77.cpp | b3e1c62f56b8c47e6fefbb2004f653f159786e0f | [] | no_license | autyinjing/Cpp-learning | 415a9e9130c1d864b28b749e8a27935936a08234 | fea63fed9c124c6a4218c61ce455554a8d6f29e4 | refs/heads/master | 2021-01-19T01:52:59.513207 | 2017-04-21T10:18:22 | 2017-04-21T10:18:22 | 38,310,895 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,058 | cpp | /*
* =====================================================================================
*
* Filename: 77.cpp
*
* Description:
*
* Version: 1.0
* Created: 2014年08月26日 11时03分47秒
* Revision: none
* Compiler: gcc
*
* Author: Aut(yinjing), [email protected]
* Company: Class 1201 of Information and Computing Science
*
* =====================================================================================
*/
#include <iostream>
#include <string>
using namespace std;
struct Car
{
string name;
int year;
};
int main( int argc, char *argv[] )
{
int num;
cout << "How many cars? ";
(cin >> num).get();
Car * car = new Car [num];
for ( int i = 0; i < num; ++i )
{
cout << "name" << i+1 << ": ";
getline(cin, car[i].name);
cout << "year: ";
(cin >> car[i].year).get();
}
for ( int i = 0; i < num; ++i )
{
cout << "car" << i+1 << endl;
cout << "name: " << car[i].name << endl;
cout << "year: " << car[i].year << endl;
}
return 0;
}
| [
"[email protected]"
] | |
954ad20c9cf045e04047afc96c3ee04885f7b1d2 | d4446dd5e3590110225ecff0d273c5effe2e5e76 | /solutions/dieSimulator.cpp | 567c1d3cc40d5cfa1cc7c0166726e19c91171885 | [] | no_license | realmelan/leetcode | 7f41dd4cadfe8e55cfbbee8d00c3a2683b74411b | e8d147908dac7e357a22af31921459ee9ed3c5dc | refs/heads/master | 2021-08-19T09:18:20.781322 | 2021-05-05T20:25:56 | 2021-05-05T20:25:56 | 120,499,148 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,127 | cpp | //
// dieSimulator.cpp
// leetcode
//
// Created by Song Ding on 9/14/20.
// Copyright © 2020 Song Ding. All rights reserved.
//
#include "common.h"
using namespace std;
namespace dieSimulator {
/*
// TODO: copy problem statement here
1223. Dice Roll Simulation
Medium
373
120
Add to List
Share
A die simulator generates a random number from 1 to 6 for each roll. You introduced a constraint to the generator such that it cannot roll the number i more than rollMax[i] (1-indexed) consecutive times.
Given an array of integers rollMax and an integer n, return the number of distinct sequences that can be obtained with exact n rolls.
Two sequences are considered different if at least one element differs from each other. Since the answer may be too large, return it modulo 10^9 + 7.
Example 1:
Input: n = 2, rollMax = [1,1,2,2,2,3]
Output: 34
Explanation: There will be 2 rolls of die, if there are no constraints on the die, there are 6 * 6 = 36 possible combinations. In this case, looking at rollMax array, the numbers 1 and 2 appear at most once consecutively, therefore sequences (1,1) and (2,2) cannot occur, so the final answer is 36-2 = 34.
Example 2:
Input: n = 2, rollMax = [1,1,1,1,1,1]
Output: 30
Example 3:
Input: n = 3, rollMax = [1,1,1,2,2,3]
Output: 181
Constraints:
1 <= n <= 5000
rollMax.length == 6
1 <= rollMax[i] <= 15
*/
class Solution {
public:
// TODO: copy function signature here
// https://leetcode.com/problems/dice-roll-simulation/discuss/403756/Java-Share-my-DP-solution
int dieSimulator(int n, vector<int>& rollMax) {
constexpr int M = 1000000007;
// dp[i][j] = # of sequnces of length i and last number is j
// then dp[i][j] = dp[i-1][0..5] - dp[i-rollMax[j]-1][0..5-j]
vector<vector<long>> dp(n+1, vector<long>(7, 0));
for (int i = 0; i < 6; ++i) {
dp[1][i] = 1;
}
dp[1][6] = 6;
for (int i = 2; i <= n; ++i) {
long sum = 0;
for (int j = 0; j < 6; ++j) {
dp[i][j] = dp[i-1][6];
if (i >= rollMax[j]+1) {
dp[i][j] -= (i > rollMax[j]+1) ? (dp[i-rollMax[j]-1][6]+M-dp[i-rollMax[j]-1][j])%M : 1;
dp[i][j] = (dp[i][j]+M)%M;
}
sum += dp[i][j];
sum %= M;
}
dp[i][6] = sum;
}
return dp[n][6];
}
private:
};
}
/*
int main() {
// TODO: define parameter type here
struct param {
int n;
vector<int> rollMax;
};
// TODO: prepare parameters here
vector<struct param> params {
{2,{1,1,2,2,2,3}},
{2,{1,1,1,1,1,1}},
{3,{1,1,1,2,2,3}},
};
// TODO: provide expected results here
vector<int> answers {
34,
30,
181,
};
for (auto& dp : params) {
cout << endl;
clock_t tstart = clock();
auto res = dieSimulator::Solution().dieSimulator(dp.n, dp.rollMax);
cout << res << endl;
cout << clock() - tstart << endl;
}
return 0;
}
//*/
| [
"[email protected]"
] | |
5f1ea18763cc9a0e0a2f7eb66fd587440fda83bf | b16f8738fc7d410b03914768ca1e654315c1fa48 | /src/data_structures/DoublyLinkedListNode.h | 7e81accb50199ba1d6f0b24777516d9e1537166e | [] | no_license | TobiasForner/GraphRepartition | bf435e4a4a267ff81d1e8204d3439d3590e7e8d5 | 910e53ba16581f5a754c2cec99cee9bab9ebec00 | refs/heads/master | 2023-01-04T20:52:23.364446 | 2020-10-26T16:05:11 | 2020-10-26T16:05:11 | 307,096,205 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,337 | h | //
// Created by tobias on 23.10.19.
//
#ifndef DBGTTHESIS_DOUBLYLINKEDLISTNODE_H
#define DBGTTHESIS_DOUBLYLINKEDLISTNODE_H
#include <memory>
//#include "spdlog/spdlog.h"
template<class T>
class DoublyLinkedListNode {
private:
DoublyLinkedListNode *pre;
DoublyLinkedListNode *next;
T data;
public:
/**
* Constructor
* @param data data to be stored in this DoublyLinkedListNode
*/
explicit DoublyLinkedListNode(const T data) : pre(nullptr), next(nullptr), data(data) {
}
/**
* Constructor
* @param data data to be stored in this DoublyLinkedListNode
* @param pre predecessor in the list
* @param next next node in the list
*/
DoublyLinkedListNode(const T data, DoublyLinkedListNode *pre, DoublyLinkedListNode *next) : pre(pre),
next(next), data(data) {
}
/**
* Destructor
*/
~DoublyLinkedListNode() {
//spdlog::debug("Deleting DoublyLinkedListNode.");
pre = nullptr;
next = nullptr;
}
/**
* returns predecessor
* @return pointer to predecessor
*/
inline DoublyLinkedListNode *getPre() const {
return pre;
}
/**
* returns pointer to next node
* @return pointer to next node
*/
inline DoublyLinkedListNode *getNext() const {
return next;
}
/**
* returns reference to data contained in this node
* @return reference to data contained in this node
*/
inline T &getData() {
return data;
}
/**
* returns whether the node has a next element
* @return true if the node has a next element, false otherwise
*/
bool hasNext() const {
return next != nullptr;
}
/**
* sets the next node
* @param newNext new next node
*/
void setNext(DoublyLinkedListNode *newNext) {
next = newNext;
}
/**
* sets the predecessor
* @param newPre new predecessor
*/
void setPre(DoublyLinkedListNode *newPre) {
pre = newPre;
}
/**
* operator for use with iterator-based for loops
* @return
*/
DoublyLinkedListNode<T> *operator++() {
return next;
}
};
#endif //DBGTTHESIS_DOUBLYLINKEDLISTNODE_H
| [
"[email protected]"
] | |
b42937b24f32db82fe4da3ff05a75d52f33b61fe | b630c4df9613d0dd731840110873d58064d5c934 | /TSP/ChildView.h | adce064ac3547cd938940b9c951c72587391fc61 | [] | no_license | ikvm/Genetic-Algorithms-Library | d1aed7ccde3e7b99e9c80d7710b25318afac96f6 | e9253a82fd04cca4f678f05afa67badee7ebb85d | refs/heads/master | 2020-04-10T10:11:53.509918 | 2013-05-27T19:35:02 | 2013-05-27T19:35:02 | 10,326,206 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,364 | h |
/*
*
* website: N/A
* contact: [email protected]
*
*/
#pragma once
#include "TspAlgorithm.h"
// CChildView window
class CChildView : public CWnd,
GaObserver
{
DEFINE_SYNC_CLASS
// Construction
public:
CChildView();
// Attributes
public:
// Notifies the observer that new statistical information is available
virtual void GACALL StatisticUpdate(const GaStatistics& statistics,
const GaAlgorithm& algorithm);
// Notifies observer that new best chromosome has found
virtual void GACALL NewBestChromosome(const GaChromosome& newChromosome,
const GaAlgorithm& algorithm);
// Notifies observer that state of evolution (problem sloving) has changed.
virtual void GACALL EvolutionStateChanged(GaAlgorithmState newState,
const GaAlgorithm& algorithm) { }
private:
GaCriticalSection _algControlSect;
vector<const TspCity*> _bestChromosome;
int _generation;
float _fitness;
// Operations
public:
// Overrides
protected:
virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
// Implementation
public:
virtual ~CChildView();
// Generated message map functions
protected:
afx_msg void OnPaint();
DECLARE_MESSAGE_MAP()
public:
afx_msg void OnLButtonDown(UINT nFlags, CPoint point);
afx_msg void OnStart();
afx_msg void OnPause();
afx_msg void OnStop();
};
| [
"[email protected]"
] | |
823e8611665d74359bae558adfd22ce17ea08ed3 | 562d2183cecd232559eb89d7f733bf1fe967768c | /Source/libClang/Source/lib/Target/Mips/MipsISelLowering.cpp | f66e75c59bc6a5ed0460e7f9ff9c246f6bf0fc58 | [
"NCSA"
] | permissive | orcun-gokbulut/ze-externals-sources | f1fd970ed6161b8f7ac19d1991f44a720c0125e9 | 500a237d6e0ff6308db1e2e513ad9871ac4cda65 | refs/heads/master | 2023-09-01T19:44:32.292637 | 2021-10-13T14:26:53 | 2021-10-13T14:26:53 | 416,611,297 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 149,641 | cpp | //===-- MipsISelLowering.cpp - Mips DAG Lowering Implementation -----------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the interfaces that Mips uses to lower LLVM code into a
// selection DAG.
//
//===----------------------------------------------------------------------===//
#include "MipsISelLowering.h"
#include "InstPrinter/MipsInstPrinter.h"
#include "MCTargetDesc/MipsBaseInfo.h"
#include "MipsMachineFunction.h"
#include "MipsSubtarget.h"
#include "MipsTargetMachine.h"
#include "MipsTargetObjectFile.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/CodeGen/CallingConvLower.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/SelectionDAGISel.h"
#include "llvm/CodeGen/ValueTypes.h"
#include "llvm/IR/CallingConv.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include <cctype>
using namespace llvm;
#define DEBUG_TYPE "mips-lower"
STATISTIC(NumTailCalls, "Number of tail calls");
static cl::opt<bool>
LargeGOT("mxgot", cl::Hidden,
cl::desc("MIPS: Enable GOT larger than 64k."), cl::init(false));
static cl::opt<bool>
NoZeroDivCheck("mno-check-zero-division", cl::Hidden,
cl::desc("MIPS: Don't trap on integer division by zero."),
cl::init(false));
cl::opt<bool>
EnableMipsFastISel("mips-fast-isel", cl::Hidden,
cl::desc("Allow mips-fast-isel to be used"),
cl::init(false));
static const MCPhysReg O32IntRegs[4] = {
Mips::A0, Mips::A1, Mips::A2, Mips::A3
};
static const MCPhysReg Mips64IntRegs[8] = {
Mips::A0_64, Mips::A1_64, Mips::A2_64, Mips::A3_64,
Mips::T0_64, Mips::T1_64, Mips::T2_64, Mips::T3_64
};
static const MCPhysReg Mips64DPRegs[8] = {
Mips::D12_64, Mips::D13_64, Mips::D14_64, Mips::D15_64,
Mips::D16_64, Mips::D17_64, Mips::D18_64, Mips::D19_64
};
// If I is a shifted mask, set the size (Size) and the first bit of the
// mask (Pos), and return true.
// For example, if I is 0x003ff800, (Pos, Size) = (11, 11).
static bool isShiftedMask(uint64_t I, uint64_t &Pos, uint64_t &Size) {
if (!isShiftedMask_64(I))
return false;
Size = CountPopulation_64(I);
Pos = countTrailingZeros(I);
return true;
}
SDValue MipsTargetLowering::getGlobalReg(SelectionDAG &DAG, EVT Ty) const {
MipsFunctionInfo *FI = DAG.getMachineFunction().getInfo<MipsFunctionInfo>();
return DAG.getRegister(FI->getGlobalBaseReg(), Ty);
}
SDValue MipsTargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
SelectionDAG &DAG,
unsigned Flag) const {
return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty, 0, Flag);
}
SDValue MipsTargetLowering::getTargetNode(ExternalSymbolSDNode *N, EVT Ty,
SelectionDAG &DAG,
unsigned Flag) const {
return DAG.getTargetExternalSymbol(N->getSymbol(), Ty, Flag);
}
SDValue MipsTargetLowering::getTargetNode(BlockAddressSDNode *N, EVT Ty,
SelectionDAG &DAG,
unsigned Flag) const {
return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
}
SDValue MipsTargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
SelectionDAG &DAG,
unsigned Flag) const {
return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
}
SDValue MipsTargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
SelectionDAG &DAG,
unsigned Flag) const {
return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
N->getOffset(), Flag);
}
const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
switch (Opcode) {
case MipsISD::JmpLink: return "MipsISD::JmpLink";
case MipsISD::TailCall: return "MipsISD::TailCall";
case MipsISD::Hi: return "MipsISD::Hi";
case MipsISD::Lo: return "MipsISD::Lo";
case MipsISD::GPRel: return "MipsISD::GPRel";
case MipsISD::ThreadPointer: return "MipsISD::ThreadPointer";
case MipsISD::Ret: return "MipsISD::Ret";
case MipsISD::EH_RETURN: return "MipsISD::EH_RETURN";
case MipsISD::FPBrcond: return "MipsISD::FPBrcond";
case MipsISD::FPCmp: return "MipsISD::FPCmp";
case MipsISD::CMovFP_T: return "MipsISD::CMovFP_T";
case MipsISD::CMovFP_F: return "MipsISD::CMovFP_F";
case MipsISD::TruncIntFP: return "MipsISD::TruncIntFP";
case MipsISD::MFHI: return "MipsISD::MFHI";
case MipsISD::MFLO: return "MipsISD::MFLO";
case MipsISD::MTLOHI: return "MipsISD::MTLOHI";
case MipsISD::Mult: return "MipsISD::Mult";
case MipsISD::Multu: return "MipsISD::Multu";
case MipsISD::MAdd: return "MipsISD::MAdd";
case MipsISD::MAddu: return "MipsISD::MAddu";
case MipsISD::MSub: return "MipsISD::MSub";
case MipsISD::MSubu: return "MipsISD::MSubu";
case MipsISD::DivRem: return "MipsISD::DivRem";
case MipsISD::DivRemU: return "MipsISD::DivRemU";
case MipsISD::DivRem16: return "MipsISD::DivRem16";
case MipsISD::DivRemU16: return "MipsISD::DivRemU16";
case MipsISD::BuildPairF64: return "MipsISD::BuildPairF64";
case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
case MipsISD::Wrapper: return "MipsISD::Wrapper";
case MipsISD::Sync: return "MipsISD::Sync";
case MipsISD::Ext: return "MipsISD::Ext";
case MipsISD::Ins: return "MipsISD::Ins";
case MipsISD::LWL: return "MipsISD::LWL";
case MipsISD::LWR: return "MipsISD::LWR";
case MipsISD::SWL: return "MipsISD::SWL";
case MipsISD::SWR: return "MipsISD::SWR";
case MipsISD::LDL: return "MipsISD::LDL";
case MipsISD::LDR: return "MipsISD::LDR";
case MipsISD::SDL: return "MipsISD::SDL";
case MipsISD::SDR: return "MipsISD::SDR";
case MipsISD::EXTP: return "MipsISD::EXTP";
case MipsISD::EXTPDP: return "MipsISD::EXTPDP";
case MipsISD::EXTR_S_H: return "MipsISD::EXTR_S_H";
case MipsISD::EXTR_W: return "MipsISD::EXTR_W";
case MipsISD::EXTR_R_W: return "MipsISD::EXTR_R_W";
case MipsISD::EXTR_RS_W: return "MipsISD::EXTR_RS_W";
case MipsISD::SHILO: return "MipsISD::SHILO";
case MipsISD::MTHLIP: return "MipsISD::MTHLIP";
case MipsISD::MULT: return "MipsISD::MULT";
case MipsISD::MULTU: return "MipsISD::MULTU";
case MipsISD::MADD_DSP: return "MipsISD::MADD_DSP";
case MipsISD::MADDU_DSP: return "MipsISD::MADDU_DSP";
case MipsISD::MSUB_DSP: return "MipsISD::MSUB_DSP";
case MipsISD::MSUBU_DSP: return "MipsISD::MSUBU_DSP";
case MipsISD::SHLL_DSP: return "MipsISD::SHLL_DSP";
case MipsISD::SHRA_DSP: return "MipsISD::SHRA_DSP";
case MipsISD::SHRL_DSP: return "MipsISD::SHRL_DSP";
case MipsISD::SETCC_DSP: return "MipsISD::SETCC_DSP";
case MipsISD::SELECT_CC_DSP: return "MipsISD::SELECT_CC_DSP";
case MipsISD::VALL_ZERO: return "MipsISD::VALL_ZERO";
case MipsISD::VANY_ZERO: return "MipsISD::VANY_ZERO";
case MipsISD::VALL_NONZERO: return "MipsISD::VALL_NONZERO";
case MipsISD::VANY_NONZERO: return "MipsISD::VANY_NONZERO";
case MipsISD::VCEQ: return "MipsISD::VCEQ";
case MipsISD::VCLE_S: return "MipsISD::VCLE_S";
case MipsISD::VCLE_U: return "MipsISD::VCLE_U";
case MipsISD::VCLT_S: return "MipsISD::VCLT_S";
case MipsISD::VCLT_U: return "MipsISD::VCLT_U";
case MipsISD::VSMAX: return "MipsISD::VSMAX";
case MipsISD::VSMIN: return "MipsISD::VSMIN";
case MipsISD::VUMAX: return "MipsISD::VUMAX";
case MipsISD::VUMIN: return "MipsISD::VUMIN";
case MipsISD::VEXTRACT_SEXT_ELT: return "MipsISD::VEXTRACT_SEXT_ELT";
case MipsISD::VEXTRACT_ZEXT_ELT: return "MipsISD::VEXTRACT_ZEXT_ELT";
case MipsISD::VNOR: return "MipsISD::VNOR";
case MipsISD::VSHF: return "MipsISD::VSHF";
case MipsISD::SHF: return "MipsISD::SHF";
case MipsISD::ILVEV: return "MipsISD::ILVEV";
case MipsISD::ILVOD: return "MipsISD::ILVOD";
case MipsISD::ILVL: return "MipsISD::ILVL";
case MipsISD::ILVR: return "MipsISD::ILVR";
case MipsISD::PCKEV: return "MipsISD::PCKEV";
case MipsISD::PCKOD: return "MipsISD::PCKOD";
case MipsISD::INSVE: return "MipsISD::INSVE";
default: return nullptr;
}
}
MipsTargetLowering::MipsTargetLowering(MipsTargetMachine &TM,
const MipsSubtarget &STI)
: TargetLowering(TM, new MipsTargetObjectFile()), Subtarget(STI) {
// Mips does not have i1 type, so use i32 for
// setcc operations results (slt, sgt, ...).
setBooleanContents(ZeroOrOneBooleanContent);
setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
// The cmp.cond.fmt instruction in MIPS32r6/MIPS64r6 uses 0 and -1 like MSA
// does. Integer booleans still use 0 and 1.
if (Subtarget.hasMips32r6())
setBooleanContents(ZeroOrOneBooleanContent,
ZeroOrNegativeOneBooleanContent);
// Load extented operations for i1 types must be promoted
setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
// MIPS doesn't have extending float->double load/store
setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
setTruncStoreAction(MVT::f64, MVT::f32, Expand);
// Used by legalize types to correctly generate the setcc result.
// Without this, every float setcc comes with a AND/OR with the result,
// we don't want this, since the fpcmp result goes to a flag register,
// which is used implicitly by brcond and select operations.
AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
// Mips Custom Operations
setOperationAction(ISD::BR_JT, MVT::Other, Custom);
setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
setOperationAction(ISD::JumpTable, MVT::i32, Custom);
setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
setOperationAction(ISD::SELECT, MVT::f32, Custom);
setOperationAction(ISD::SELECT, MVT::f64, Custom);
setOperationAction(ISD::SELECT, MVT::i32, Custom);
setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
setOperationAction(ISD::SETCC, MVT::f32, Custom);
setOperationAction(ISD::SETCC, MVT::f64, Custom);
setOperationAction(ISD::BRCOND, MVT::Other, Custom);
setOperationAction(ISD::VASTART, MVT::Other, Custom);
setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
if (Subtarget.isGP64bit()) {
setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
setOperationAction(ISD::JumpTable, MVT::i64, Custom);
setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
setOperationAction(ISD::SELECT, MVT::i64, Custom);
setOperationAction(ISD::LOAD, MVT::i64, Custom);
setOperationAction(ISD::STORE, MVT::i64, Custom);
setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
}
if (!Subtarget.isGP64bit()) {
setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
}
setOperationAction(ISD::ADD, MVT::i32, Custom);
if (Subtarget.isGP64bit())
setOperationAction(ISD::ADD, MVT::i64, Custom);
setOperationAction(ISD::SDIV, MVT::i32, Expand);
setOperationAction(ISD::SREM, MVT::i32, Expand);
setOperationAction(ISD::UDIV, MVT::i32, Expand);
setOperationAction(ISD::UREM, MVT::i32, Expand);
setOperationAction(ISD::SDIV, MVT::i64, Expand);
setOperationAction(ISD::SREM, MVT::i64, Expand);
setOperationAction(ISD::UDIV, MVT::i64, Expand);
setOperationAction(ISD::UREM, MVT::i64, Expand);
// Operations not directly supported by Mips.
setOperationAction(ISD::BR_CC, MVT::f32, Expand);
setOperationAction(ISD::BR_CC, MVT::f64, Expand);
setOperationAction(ISD::BR_CC, MVT::i32, Expand);
setOperationAction(ISD::BR_CC, MVT::i64, Expand);
setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
if (Subtarget.hasCnMips()) {
setOperationAction(ISD::CTPOP, MVT::i32, Legal);
setOperationAction(ISD::CTPOP, MVT::i64, Legal);
} else {
setOperationAction(ISD::CTPOP, MVT::i32, Expand);
setOperationAction(ISD::CTPOP, MVT::i64, Expand);
}
setOperationAction(ISD::CTTZ, MVT::i32, Expand);
setOperationAction(ISD::CTTZ, MVT::i64, Expand);
setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
setOperationAction(ISD::ROTL, MVT::i32, Expand);
setOperationAction(ISD::ROTL, MVT::i64, Expand);
setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
if (!Subtarget.hasMips32r2())
setOperationAction(ISD::ROTR, MVT::i32, Expand);
if (!Subtarget.hasMips64r2())
setOperationAction(ISD::ROTR, MVT::i64, Expand);
setOperationAction(ISD::FSIN, MVT::f32, Expand);
setOperationAction(ISD::FSIN, MVT::f64, Expand);
setOperationAction(ISD::FCOS, MVT::f32, Expand);
setOperationAction(ISD::FCOS, MVT::f64, Expand);
setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
setOperationAction(ISD::FPOWI, MVT::f32, Expand);
setOperationAction(ISD::FPOW, MVT::f32, Expand);
setOperationAction(ISD::FPOW, MVT::f64, Expand);
setOperationAction(ISD::FLOG, MVT::f32, Expand);
setOperationAction(ISD::FLOG2, MVT::f32, Expand);
setOperationAction(ISD::FLOG10, MVT::f32, Expand);
setOperationAction(ISD::FEXP, MVT::f32, Expand);
setOperationAction(ISD::FMA, MVT::f32, Expand);
setOperationAction(ISD::FMA, MVT::f64, Expand);
setOperationAction(ISD::FREM, MVT::f32, Expand);
setOperationAction(ISD::FREM, MVT::f64, Expand);
setOperationAction(ISD::EH_RETURN, MVT::Other, Custom);
setOperationAction(ISD::VAARG, MVT::Other, Expand);
setOperationAction(ISD::VACOPY, MVT::Other, Expand);
setOperationAction(ISD::VAEND, MVT::Other, Expand);
// Use the default for now
setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
setInsertFencesForAtomic(true);
if (!Subtarget.hasMips32r2()) {
setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
}
// MIPS16 lacks MIPS32's clz and clo instructions.
if (!Subtarget.hasMips32() || Subtarget.inMips16Mode())
setOperationAction(ISD::CTLZ, MVT::i32, Expand);
if (!Subtarget.hasMips64())
setOperationAction(ISD::CTLZ, MVT::i64, Expand);
if (!Subtarget.hasMips32r2())
setOperationAction(ISD::BSWAP, MVT::i32, Expand);
if (!Subtarget.hasMips64r2())
setOperationAction(ISD::BSWAP, MVT::i64, Expand);
if (Subtarget.isGP64bit()) {
setLoadExtAction(ISD::SEXTLOAD, MVT::i32, Custom);
setLoadExtAction(ISD::ZEXTLOAD, MVT::i32, Custom);
setLoadExtAction(ISD::EXTLOAD, MVT::i32, Custom);
setTruncStoreAction(MVT::i64, MVT::i32, Custom);
}
setOperationAction(ISD::TRAP, MVT::Other, Legal);
setTargetDAGCombine(ISD::SDIVREM);
setTargetDAGCombine(ISD::UDIVREM);
setTargetDAGCombine(ISD::SELECT);
setTargetDAGCombine(ISD::AND);
setTargetDAGCombine(ISD::OR);
setTargetDAGCombine(ISD::ADD);
setMinFunctionAlignment(Subtarget.isGP64bit() ? 3 : 2);
setStackPointerRegisterToSaveRestore(Subtarget.isABI_N64() ? Mips::SP_64
: Mips::SP);
setExceptionPointerRegister(Subtarget.isABI_N64() ? Mips::A0_64 : Mips::A0);
setExceptionSelectorRegister(Subtarget.isABI_N64() ? Mips::A1_64 : Mips::A1);
MaxStoresPerMemcpy = 16;
isMicroMips = Subtarget.inMicroMipsMode();
}
const MipsTargetLowering *MipsTargetLowering::create(MipsTargetMachine &TM,
const MipsSubtarget &STI) {
if (STI.inMips16Mode())
return llvm::createMips16TargetLowering(TM, STI);
return llvm::createMipsSETargetLowering(TM, STI);
}
// Create a fast isel object.
FastISel *
MipsTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
const TargetLibraryInfo *libInfo) const {
if (!EnableMipsFastISel)
return TargetLowering::createFastISel(funcInfo, libInfo);
return Mips::createFastISel(funcInfo, libInfo);
}
EVT MipsTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
if (!VT.isVector())
return MVT::i32;
return VT.changeVectorElementTypeToInteger();
}
static SDValue performDivRemCombine(SDNode *N, SelectionDAG &DAG,
TargetLowering::DAGCombinerInfo &DCI,
const MipsSubtarget &Subtarget) {
if (DCI.isBeforeLegalizeOps())
return SDValue();
EVT Ty = N->getValueType(0);
unsigned LO = (Ty == MVT::i32) ? Mips::LO0 : Mips::LO0_64;
unsigned HI = (Ty == MVT::i32) ? Mips::HI0 : Mips::HI0_64;
unsigned Opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem16 :
MipsISD::DivRemU16;
SDLoc DL(N);
SDValue DivRem = DAG.getNode(Opc, DL, MVT::Glue,
N->getOperand(0), N->getOperand(1));
SDValue InChain = DAG.getEntryNode();
SDValue InGlue = DivRem;
// insert MFLO
if (N->hasAnyUseOfValue(0)) {
SDValue CopyFromLo = DAG.getCopyFromReg(InChain, DL, LO, Ty,
InGlue);
DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
InChain = CopyFromLo.getValue(1);
InGlue = CopyFromLo.getValue(2);
}
// insert MFHI
if (N->hasAnyUseOfValue(1)) {
SDValue CopyFromHi = DAG.getCopyFromReg(InChain, DL,
HI, Ty, InGlue);
DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
}
return SDValue();
}
static Mips::CondCode condCodeToFCC(ISD::CondCode CC) {
switch (CC) {
default: llvm_unreachable("Unknown fp condition code!");
case ISD::SETEQ:
case ISD::SETOEQ: return Mips::FCOND_OEQ;
case ISD::SETUNE: return Mips::FCOND_UNE;
case ISD::SETLT:
case ISD::SETOLT: return Mips::FCOND_OLT;
case ISD::SETGT:
case ISD::SETOGT: return Mips::FCOND_OGT;
case ISD::SETLE:
case ISD::SETOLE: return Mips::FCOND_OLE;
case ISD::SETGE:
case ISD::SETOGE: return Mips::FCOND_OGE;
case ISD::SETULT: return Mips::FCOND_ULT;
case ISD::SETULE: return Mips::FCOND_ULE;
case ISD::SETUGT: return Mips::FCOND_UGT;
case ISD::SETUGE: return Mips::FCOND_UGE;
case ISD::SETUO: return Mips::FCOND_UN;
case ISD::SETO: return Mips::FCOND_OR;
case ISD::SETNE:
case ISD::SETONE: return Mips::FCOND_ONE;
case ISD::SETUEQ: return Mips::FCOND_UEQ;
}
}
/// This function returns true if the floating point conditional branches and
/// conditional moves which use condition code CC should be inverted.
static bool invertFPCondCodeUser(Mips::CondCode CC) {
if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
return false;
assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
"Illegal Condition Code");
return true;
}
// Creates and returns an FPCmp node from a setcc node.
// Returns Op if setcc is not a floating point comparison.
static SDValue createFPCmp(SelectionDAG &DAG, const SDValue &Op) {
// must be a SETCC node
if (Op.getOpcode() != ISD::SETCC)
return Op;
SDValue LHS = Op.getOperand(0);
if (!LHS.getValueType().isFloatingPoint())
return Op;
SDValue RHS = Op.getOperand(1);
SDLoc DL(Op);
// Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
// node if necessary.
ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
return DAG.getNode(MipsISD::FPCmp, DL, MVT::Glue, LHS, RHS,
DAG.getConstant(condCodeToFCC(CC), MVT::i32));
}
// Creates and returns a CMovFPT/F node.
static SDValue createCMovFP(SelectionDAG &DAG, SDValue Cond, SDValue True,
SDValue False, SDLoc DL) {
ConstantSDNode *CC = cast<ConstantSDNode>(Cond.getOperand(2));
bool invert = invertFPCondCodeUser((Mips::CondCode)CC->getSExtValue());
SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
True.getValueType(), True, FCC0, False, Cond);
}
static SDValue performSELECTCombine(SDNode *N, SelectionDAG &DAG,
TargetLowering::DAGCombinerInfo &DCI,
const MipsSubtarget &Subtarget) {
if (DCI.isBeforeLegalizeOps())
return SDValue();
SDValue SetCC = N->getOperand(0);
if ((SetCC.getOpcode() != ISD::SETCC) ||
!SetCC.getOperand(0).getValueType().isInteger())
return SDValue();
SDValue False = N->getOperand(2);
EVT FalseTy = False.getValueType();
if (!FalseTy.isInteger())
return SDValue();
ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(False);
// If the RHS (False) is 0, we swap the order of the operands
// of ISD::SELECT (obviously also inverting the condition) so that we can
// take advantage of conditional moves using the $0 register.
// Example:
// return (a != 0) ? x : 0;
// load $reg, x
// movz $reg, $0, a
if (!FalseC)
return SDValue();
const SDLoc DL(N);
if (!FalseC->getZExtValue()) {
ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
SDValue True = N->getOperand(1);
SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
}
// If both operands are integer constants there's a possibility that we
// can do some interesting optimizations.
SDValue True = N->getOperand(1);
ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(True);
if (!TrueC || !True.getValueType().isInteger())
return SDValue();
// We'll also ignore MVT::i64 operands as this optimizations proves
// to be ineffective because of the required sign extensions as the result
// of a SETCC operator is always MVT::i32 for non-vector types.
if (True.getValueType() == MVT::i64)
return SDValue();
int64_t Diff = TrueC->getSExtValue() - FalseC->getSExtValue();
// 1) (a < x) ? y : y-1
// slti $reg1, a, x
// addiu $reg2, $reg1, y-1
if (Diff == 1)
return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, False);
// 2) (a < x) ? y-1 : y
// slti $reg1, a, x
// xor $reg1, $reg1, 1
// addiu $reg2, $reg1, y-1
if (Diff == -1) {
ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, True);
}
// Couldn't optimize.
return SDValue();
}
static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG,
TargetLowering::DAGCombinerInfo &DCI,
const MipsSubtarget &Subtarget) {
// Pattern match EXT.
// $dst = and ((sra or srl) $src , pos), (2**size - 1)
// => ext $dst, $src, size, pos
if (DCI.isBeforeLegalizeOps() || !Subtarget.hasExtractInsert())
return SDValue();
SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
unsigned ShiftRightOpc = ShiftRight.getOpcode();
// Op's first operand must be a shift right.
if (ShiftRightOpc != ISD::SRA && ShiftRightOpc != ISD::SRL)
return SDValue();
// The second operand of the shift must be an immediate.
ConstantSDNode *CN;
if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
return SDValue();
uint64_t Pos = CN->getZExtValue();
uint64_t SMPos, SMSize;
// Op's second operand must be a shifted mask.
if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
!isShiftedMask(CN->getZExtValue(), SMPos, SMSize))
return SDValue();
// Return if the shifted mask does not start at bit 0 or the sum of its size
// and Pos exceeds the word's size.
EVT ValTy = N->getValueType(0);
if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
return SDValue();
return DAG.getNode(MipsISD::Ext, SDLoc(N), ValTy,
ShiftRight.getOperand(0), DAG.getConstant(Pos, MVT::i32),
DAG.getConstant(SMSize, MVT::i32));
}
static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
TargetLowering::DAGCombinerInfo &DCI,
const MipsSubtarget &Subtarget) {
// Pattern match INS.
// $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
// where mask1 = (2**size - 1) << pos, mask0 = ~mask1
// => ins $dst, $src, size, pos, $src1
if (DCI.isBeforeLegalizeOps() || !Subtarget.hasExtractInsert())
return SDValue();
SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
ConstantSDNode *CN;
// See if Op's first operand matches (and $src1 , mask0).
if (And0.getOpcode() != ISD::AND)
return SDValue();
if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
!isShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
return SDValue();
// See if Op's second operand matches (and (shl $src, pos), mask1).
if (And1.getOpcode() != ISD::AND)
return SDValue();
if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
!isShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
return SDValue();
// The shift masks must have the same position and size.
if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
return SDValue();
SDValue Shl = And1.getOperand(0);
if (Shl.getOpcode() != ISD::SHL)
return SDValue();
if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
return SDValue();
unsigned Shamt = CN->getZExtValue();
// Return if the shift amount and the first bit position of mask are not the
// same.
EVT ValTy = N->getValueType(0);
if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
return SDValue();
return DAG.getNode(MipsISD::Ins, SDLoc(N), ValTy, Shl.getOperand(0),
DAG.getConstant(SMPos0, MVT::i32),
DAG.getConstant(SMSize0, MVT::i32), And0.getOperand(0));
}
static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
TargetLowering::DAGCombinerInfo &DCI,
const MipsSubtarget &Subtarget) {
// (add v0, (add v1, abs_lo(tjt))) => (add (add v0, v1), abs_lo(tjt))
if (DCI.isBeforeLegalizeOps())
return SDValue();
SDValue Add = N->getOperand(1);
if (Add.getOpcode() != ISD::ADD)
return SDValue();
SDValue Lo = Add.getOperand(1);
if ((Lo.getOpcode() != MipsISD::Lo) ||
(Lo.getOperand(0).getOpcode() != ISD::TargetJumpTable))
return SDValue();
EVT ValTy = N->getValueType(0);
SDLoc DL(N);
SDValue Add1 = DAG.getNode(ISD::ADD, DL, ValTy, N->getOperand(0),
Add.getOperand(0));
return DAG.getNode(ISD::ADD, DL, ValTy, Add1, Lo);
}
SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
const {
SelectionDAG &DAG = DCI.DAG;
unsigned Opc = N->getOpcode();
switch (Opc) {
default: break;
case ISD::SDIVREM:
case ISD::UDIVREM:
return performDivRemCombine(N, DAG, DCI, Subtarget);
case ISD::SELECT:
return performSELECTCombine(N, DAG, DCI, Subtarget);
case ISD::AND:
return performANDCombine(N, DAG, DCI, Subtarget);
case ISD::OR:
return performORCombine(N, DAG, DCI, Subtarget);
case ISD::ADD:
return performADDCombine(N, DAG, DCI, Subtarget);
}
return SDValue();
}
void
MipsTargetLowering::LowerOperationWrapper(SDNode *N,
SmallVectorImpl<SDValue> &Results,
SelectionDAG &DAG) const {
SDValue Res = LowerOperation(SDValue(N, 0), DAG);
for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
Results.push_back(Res.getValue(I));
}
void
MipsTargetLowering::ReplaceNodeResults(SDNode *N,
SmallVectorImpl<SDValue> &Results,
SelectionDAG &DAG) const {
return LowerOperationWrapper(N, Results, DAG);
}
SDValue MipsTargetLowering::
LowerOperation(SDValue Op, SelectionDAG &DAG) const
{
switch (Op.getOpcode())
{
case ISD::BR_JT: return lowerBR_JT(Op, DAG);
case ISD::BRCOND: return lowerBRCOND(Op, DAG);
case ISD::ConstantPool: return lowerConstantPool(Op, DAG);
case ISD::GlobalAddress: return lowerGlobalAddress(Op, DAG);
case ISD::BlockAddress: return lowerBlockAddress(Op, DAG);
case ISD::GlobalTLSAddress: return lowerGlobalTLSAddress(Op, DAG);
case ISD::JumpTable: return lowerJumpTable(Op, DAG);
case ISD::SELECT: return lowerSELECT(Op, DAG);
case ISD::SELECT_CC: return lowerSELECT_CC(Op, DAG);
case ISD::SETCC: return lowerSETCC(Op, DAG);
case ISD::VASTART: return lowerVASTART(Op, DAG);
case ISD::FCOPYSIGN: return lowerFCOPYSIGN(Op, DAG);
case ISD::FRAMEADDR: return lowerFRAMEADDR(Op, DAG);
case ISD::RETURNADDR: return lowerRETURNADDR(Op, DAG);
case ISD::EH_RETURN: return lowerEH_RETURN(Op, DAG);
case ISD::ATOMIC_FENCE: return lowerATOMIC_FENCE(Op, DAG);
case ISD::SHL_PARTS: return lowerShiftLeftParts(Op, DAG);
case ISD::SRA_PARTS: return lowerShiftRightParts(Op, DAG, true);
case ISD::SRL_PARTS: return lowerShiftRightParts(Op, DAG, false);
case ISD::LOAD: return lowerLOAD(Op, DAG);
case ISD::STORE: return lowerSTORE(Op, DAG);
case ISD::ADD: return lowerADD(Op, DAG);
case ISD::FP_TO_SINT: return lowerFP_TO_SINT(Op, DAG);
}
return SDValue();
}
//===----------------------------------------------------------------------===//
// Lower helper functions
//===----------------------------------------------------------------------===//
// addLiveIn - This helper function adds the specified physical register to the
// MachineFunction as a live in value. It also creates a corresponding
// virtual register for it.
static unsigned
addLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
{
unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
MF.getRegInfo().addLiveIn(PReg, VReg);
return VReg;
}
static MachineBasicBlock *insertDivByZeroTrap(MachineInstr *MI,
MachineBasicBlock &MBB,
const TargetInstrInfo &TII,
bool Is64Bit) {
if (NoZeroDivCheck)
return &MBB;
// Insert instruction "teq $divisor_reg, $zero, 7".
MachineBasicBlock::iterator I(MI);
MachineInstrBuilder MIB;
MachineOperand &Divisor = MI->getOperand(2);
MIB = BuildMI(MBB, std::next(I), MI->getDebugLoc(), TII.get(Mips::TEQ))
.addReg(Divisor.getReg(), getKillRegState(Divisor.isKill()))
.addReg(Mips::ZERO).addImm(7);
// Use the 32-bit sub-register if this is a 64-bit division.
if (Is64Bit)
MIB->getOperand(0).setSubReg(Mips::sub_32);
// Clear Divisor's kill flag.
Divisor.setIsKill(false);
// We would normally delete the original instruction here but in this case
// we only needed to inject an additional instruction rather than replace it.
return &MBB;
}
MachineBasicBlock *
MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
MachineBasicBlock *BB) const {
switch (MI->getOpcode()) {
default:
llvm_unreachable("Unexpected instr type to insert");
case Mips::ATOMIC_LOAD_ADD_I8:
return emitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
case Mips::ATOMIC_LOAD_ADD_I16:
return emitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
case Mips::ATOMIC_LOAD_ADD_I32:
return emitAtomicBinary(MI, BB, 4, Mips::ADDu);
case Mips::ATOMIC_LOAD_ADD_I64:
return emitAtomicBinary(MI, BB, 8, Mips::DADDu);
case Mips::ATOMIC_LOAD_AND_I8:
return emitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
case Mips::ATOMIC_LOAD_AND_I16:
return emitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
case Mips::ATOMIC_LOAD_AND_I32:
return emitAtomicBinary(MI, BB, 4, Mips::AND);
case Mips::ATOMIC_LOAD_AND_I64:
return emitAtomicBinary(MI, BB, 8, Mips::AND64);
case Mips::ATOMIC_LOAD_OR_I8:
return emitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
case Mips::ATOMIC_LOAD_OR_I16:
return emitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
case Mips::ATOMIC_LOAD_OR_I32:
return emitAtomicBinary(MI, BB, 4, Mips::OR);
case Mips::ATOMIC_LOAD_OR_I64:
return emitAtomicBinary(MI, BB, 8, Mips::OR64);
case Mips::ATOMIC_LOAD_XOR_I8:
return emitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
case Mips::ATOMIC_LOAD_XOR_I16:
return emitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
case Mips::ATOMIC_LOAD_XOR_I32:
return emitAtomicBinary(MI, BB, 4, Mips::XOR);
case Mips::ATOMIC_LOAD_XOR_I64:
return emitAtomicBinary(MI, BB, 8, Mips::XOR64);
case Mips::ATOMIC_LOAD_NAND_I8:
return emitAtomicBinaryPartword(MI, BB, 1, 0, true);
case Mips::ATOMIC_LOAD_NAND_I16:
return emitAtomicBinaryPartword(MI, BB, 2, 0, true);
case Mips::ATOMIC_LOAD_NAND_I32:
return emitAtomicBinary(MI, BB, 4, 0, true);
case Mips::ATOMIC_LOAD_NAND_I64:
return emitAtomicBinary(MI, BB, 8, 0, true);
case Mips::ATOMIC_LOAD_SUB_I8:
return emitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
case Mips::ATOMIC_LOAD_SUB_I16:
return emitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
case Mips::ATOMIC_LOAD_SUB_I32:
return emitAtomicBinary(MI, BB, 4, Mips::SUBu);
case Mips::ATOMIC_LOAD_SUB_I64:
return emitAtomicBinary(MI, BB, 8, Mips::DSUBu);
case Mips::ATOMIC_SWAP_I8:
return emitAtomicBinaryPartword(MI, BB, 1, 0);
case Mips::ATOMIC_SWAP_I16:
return emitAtomicBinaryPartword(MI, BB, 2, 0);
case Mips::ATOMIC_SWAP_I32:
return emitAtomicBinary(MI, BB, 4, 0);
case Mips::ATOMIC_SWAP_I64:
return emitAtomicBinary(MI, BB, 8, 0);
case Mips::ATOMIC_CMP_SWAP_I8:
return emitAtomicCmpSwapPartword(MI, BB, 1);
case Mips::ATOMIC_CMP_SWAP_I16:
return emitAtomicCmpSwapPartword(MI, BB, 2);
case Mips::ATOMIC_CMP_SWAP_I32:
return emitAtomicCmpSwap(MI, BB, 4);
case Mips::ATOMIC_CMP_SWAP_I64:
return emitAtomicCmpSwap(MI, BB, 8);
case Mips::PseudoSDIV:
case Mips::PseudoUDIV:
case Mips::DIV:
case Mips::DIVU:
case Mips::MOD:
case Mips::MODU:
return insertDivByZeroTrap(MI, *BB, *getTargetMachine().getInstrInfo(),
false);
case Mips::PseudoDSDIV:
case Mips::PseudoDUDIV:
case Mips::DDIV:
case Mips::DDIVU:
case Mips::DMOD:
case Mips::DMODU:
return insertDivByZeroTrap(MI, *BB, *getTargetMachine().getInstrInfo(),
true);
case Mips::SEL_D:
return emitSEL_D(MI, BB);
}
}
// This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
// Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
MachineBasicBlock *
MipsTargetLowering::emitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
unsigned Size, unsigned BinOpcode,
bool Nand) const {
assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
MachineFunction *MF = BB->getParent();
MachineRegisterInfo &RegInfo = MF->getRegInfo();
const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
DebugLoc DL = MI->getDebugLoc();
unsigned LL, SC, AND, NOR, ZERO, BEQ;
if (Size == 4) {
if (isMicroMips) {
LL = Mips::LL_MM;
SC = Mips::SC_MM;
} else {
LL = Subtarget.hasMips32r6() ? Mips::LL_R6 : Mips::LL;
SC = Subtarget.hasMips32r6() ? Mips::SC_R6 : Mips::SC;
}
AND = Mips::AND;
NOR = Mips::NOR;
ZERO = Mips::ZERO;
BEQ = Mips::BEQ;
} else {
LL = Subtarget.hasMips64r6() ? Mips::LLD_R6 : Mips::LLD;
SC = Subtarget.hasMips64r6() ? Mips::SCD_R6 : Mips::SCD;
AND = Mips::AND64;
NOR = Mips::NOR64;
ZERO = Mips::ZERO_64;
BEQ = Mips::BEQ64;
}
unsigned OldVal = MI->getOperand(0).getReg();
unsigned Ptr = MI->getOperand(1).getReg();
unsigned Incr = MI->getOperand(2).getReg();
unsigned StoreVal = RegInfo.createVirtualRegister(RC);
unsigned AndRes = RegInfo.createVirtualRegister(RC);
unsigned Success = RegInfo.createVirtualRegister(RC);
// insert new blocks after the current block
const BasicBlock *LLVM_BB = BB->getBasicBlock();
MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
MachineFunction::iterator It = BB;
++It;
MF->insert(It, loopMBB);
MF->insert(It, exitMBB);
// Transfer the remainder of BB and its successor edges to exitMBB.
exitMBB->splice(exitMBB->begin(), BB,
std::next(MachineBasicBlock::iterator(MI)), BB->end());
exitMBB->transferSuccessorsAndUpdatePHIs(BB);
// thisMBB:
// ...
// fallthrough --> loopMBB
BB->addSuccessor(loopMBB);
loopMBB->addSuccessor(loopMBB);
loopMBB->addSuccessor(exitMBB);
// loopMBB:
// ll oldval, 0(ptr)
// <binop> storeval, oldval, incr
// sc success, storeval, 0(ptr)
// beq success, $0, loopMBB
BB = loopMBB;
BuildMI(BB, DL, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
if (Nand) {
// and andres, oldval, incr
// nor storeval, $0, andres
BuildMI(BB, DL, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
BuildMI(BB, DL, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
} else if (BinOpcode) {
// <binop> storeval, oldval, incr
BuildMI(BB, DL, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
} else {
StoreVal = Incr;
}
BuildMI(BB, DL, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
BuildMI(BB, DL, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
MI->eraseFromParent(); // The instruction is gone now.
return exitMBB;
}
MachineBasicBlock *MipsTargetLowering::emitSignExtendToI32InReg(
MachineInstr *MI, MachineBasicBlock *BB, unsigned Size, unsigned DstReg,
unsigned SrcReg) const {
const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
DebugLoc DL = MI->getDebugLoc();
if (Subtarget.hasMips32r2() && Size == 1) {
BuildMI(BB, DL, TII->get(Mips::SEB), DstReg).addReg(SrcReg);
return BB;
}
if (Subtarget.hasMips32r2() && Size == 2) {
BuildMI(BB, DL, TII->get(Mips::SEH), DstReg).addReg(SrcReg);
return BB;
}
MachineFunction *MF = BB->getParent();
MachineRegisterInfo &RegInfo = MF->getRegInfo();
const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
unsigned ScrReg = RegInfo.createVirtualRegister(RC);
assert(Size < 32);
int64_t ShiftImm = 32 - (Size * 8);
BuildMI(BB, DL, TII->get(Mips::SLL), ScrReg).addReg(SrcReg).addImm(ShiftImm);
BuildMI(BB, DL, TII->get(Mips::SRA), DstReg).addReg(ScrReg).addImm(ShiftImm);
return BB;
}
MachineBasicBlock *MipsTargetLowering::emitAtomicBinaryPartword(
MachineInstr *MI, MachineBasicBlock *BB, unsigned Size, unsigned BinOpcode,
bool Nand) const {
assert((Size == 1 || Size == 2) &&
"Unsupported size for EmitAtomicBinaryPartial.");
MachineFunction *MF = BB->getParent();
MachineRegisterInfo &RegInfo = MF->getRegInfo();
const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
DebugLoc DL = MI->getDebugLoc();
unsigned Dest = MI->getOperand(0).getReg();
unsigned Ptr = MI->getOperand(1).getReg();
unsigned Incr = MI->getOperand(2).getReg();
unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
unsigned Mask = RegInfo.createVirtualRegister(RC);
unsigned Mask2 = RegInfo.createVirtualRegister(RC);
unsigned NewVal = RegInfo.createVirtualRegister(RC);
unsigned OldVal = RegInfo.createVirtualRegister(RC);
unsigned Incr2 = RegInfo.createVirtualRegister(RC);
unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
unsigned AndRes = RegInfo.createVirtualRegister(RC);
unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
unsigned StoreVal = RegInfo.createVirtualRegister(RC);
unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
unsigned SrlRes = RegInfo.createVirtualRegister(RC);
unsigned Success = RegInfo.createVirtualRegister(RC);
// insert new blocks after the current block
const BasicBlock *LLVM_BB = BB->getBasicBlock();
MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
MachineFunction::iterator It = BB;
++It;
MF->insert(It, loopMBB);
MF->insert(It, sinkMBB);
MF->insert(It, exitMBB);
// Transfer the remainder of BB and its successor edges to exitMBB.
exitMBB->splice(exitMBB->begin(), BB,
std::next(MachineBasicBlock::iterator(MI)), BB->end());
exitMBB->transferSuccessorsAndUpdatePHIs(BB);
BB->addSuccessor(loopMBB);
loopMBB->addSuccessor(loopMBB);
loopMBB->addSuccessor(sinkMBB);
sinkMBB->addSuccessor(exitMBB);
// thisMBB:
// addiu masklsb2,$0,-4 # 0xfffffffc
// and alignedaddr,ptr,masklsb2
// andi ptrlsb2,ptr,3
// sll shiftamt,ptrlsb2,3
// ori maskupper,$0,255 # 0xff
// sll mask,maskupper,shiftamt
// nor mask2,$0,mask
// sll incr2,incr,shiftamt
int64_t MaskImm = (Size == 1) ? 255 : 65535;
BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
.addReg(Mips::ZERO).addImm(-4);
BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
.addReg(Ptr).addReg(MaskLSB2);
BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
if (Subtarget.isLittle()) {
BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
} else {
unsigned Off = RegInfo.createVirtualRegister(RC);
BuildMI(BB, DL, TII->get(Mips::XORi), Off)
.addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
}
BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
.addReg(Mips::ZERO).addImm(MaskImm);
BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
.addReg(MaskUpper).addReg(ShiftAmt);
BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
BuildMI(BB, DL, TII->get(Mips::SLLV), Incr2).addReg(Incr).addReg(ShiftAmt);
// atomic.load.binop
// loopMBB:
// ll oldval,0(alignedaddr)
// binop binopres,oldval,incr2
// and newval,binopres,mask
// and maskedoldval0,oldval,mask2
// or storeval,maskedoldval0,newval
// sc success,storeval,0(alignedaddr)
// beq success,$0,loopMBB
// atomic.swap
// loopMBB:
// ll oldval,0(alignedaddr)
// and newval,incr2,mask
// and maskedoldval0,oldval,mask2
// or storeval,maskedoldval0,newval
// sc success,storeval,0(alignedaddr)
// beq success,$0,loopMBB
BB = loopMBB;
BuildMI(BB, DL, TII->get(Mips::LL), OldVal).addReg(AlignedAddr).addImm(0);
if (Nand) {
// and andres, oldval, incr2
// nor binopres, $0, andres
// and newval, binopres, mask
BuildMI(BB, DL, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
BuildMI(BB, DL, TII->get(Mips::NOR), BinOpRes)
.addReg(Mips::ZERO).addReg(AndRes);
BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
} else if (BinOpcode) {
// <binop> binopres, oldval, incr2
// and newval, binopres, mask
BuildMI(BB, DL, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
} else { // atomic.swap
// and newval, incr2, mask
BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
}
BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
.addReg(OldVal).addReg(Mask2);
BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
.addReg(MaskedOldVal0).addReg(NewVal);
BuildMI(BB, DL, TII->get(Mips::SC), Success)
.addReg(StoreVal).addReg(AlignedAddr).addImm(0);
BuildMI(BB, DL, TII->get(Mips::BEQ))
.addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
// sinkMBB:
// and maskedoldval1,oldval,mask
// srl srlres,maskedoldval1,shiftamt
// sign_extend dest,srlres
BB = sinkMBB;
BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
.addReg(OldVal).addReg(Mask);
BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
.addReg(MaskedOldVal1).addReg(ShiftAmt);
BB = emitSignExtendToI32InReg(MI, BB, Size, Dest, SrlRes);
MI->eraseFromParent(); // The instruction is gone now.
return exitMBB;
}
MachineBasicBlock * MipsTargetLowering::emitAtomicCmpSwap(MachineInstr *MI,
MachineBasicBlock *BB,
unsigned Size) const {
assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
MachineFunction *MF = BB->getParent();
MachineRegisterInfo &RegInfo = MF->getRegInfo();
const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
DebugLoc DL = MI->getDebugLoc();
unsigned LL, SC, ZERO, BNE, BEQ;
if (Size == 4) {
LL = isMicroMips ? Mips::LL_MM : Mips::LL;
SC = isMicroMips ? Mips::SC_MM : Mips::SC;
ZERO = Mips::ZERO;
BNE = Mips::BNE;
BEQ = Mips::BEQ;
} else {
LL = Mips::LLD;
SC = Mips::SCD;
ZERO = Mips::ZERO_64;
BNE = Mips::BNE64;
BEQ = Mips::BEQ64;
}
unsigned Dest = MI->getOperand(0).getReg();
unsigned Ptr = MI->getOperand(1).getReg();
unsigned OldVal = MI->getOperand(2).getReg();
unsigned NewVal = MI->getOperand(3).getReg();
unsigned Success = RegInfo.createVirtualRegister(RC);
// insert new blocks after the current block
const BasicBlock *LLVM_BB = BB->getBasicBlock();
MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
MachineFunction::iterator It = BB;
++It;
MF->insert(It, loop1MBB);
MF->insert(It, loop2MBB);
MF->insert(It, exitMBB);
// Transfer the remainder of BB and its successor edges to exitMBB.
exitMBB->splice(exitMBB->begin(), BB,
std::next(MachineBasicBlock::iterator(MI)), BB->end());
exitMBB->transferSuccessorsAndUpdatePHIs(BB);
// thisMBB:
// ...
// fallthrough --> loop1MBB
BB->addSuccessor(loop1MBB);
loop1MBB->addSuccessor(exitMBB);
loop1MBB->addSuccessor(loop2MBB);
loop2MBB->addSuccessor(loop1MBB);
loop2MBB->addSuccessor(exitMBB);
// loop1MBB:
// ll dest, 0(ptr)
// bne dest, oldval, exitMBB
BB = loop1MBB;
BuildMI(BB, DL, TII->get(LL), Dest).addReg(Ptr).addImm(0);
BuildMI(BB, DL, TII->get(BNE))
.addReg(Dest).addReg(OldVal).addMBB(exitMBB);
// loop2MBB:
// sc success, newval, 0(ptr)
// beq success, $0, loop1MBB
BB = loop2MBB;
BuildMI(BB, DL, TII->get(SC), Success)
.addReg(NewVal).addReg(Ptr).addImm(0);
BuildMI(BB, DL, TII->get(BEQ))
.addReg(Success).addReg(ZERO).addMBB(loop1MBB);
MI->eraseFromParent(); // The instruction is gone now.
return exitMBB;
}
MachineBasicBlock *
MipsTargetLowering::emitAtomicCmpSwapPartword(MachineInstr *MI,
MachineBasicBlock *BB,
unsigned Size) const {
assert((Size == 1 || Size == 2) &&
"Unsupported size for EmitAtomicCmpSwapPartial.");
MachineFunction *MF = BB->getParent();
MachineRegisterInfo &RegInfo = MF->getRegInfo();
const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
DebugLoc DL = MI->getDebugLoc();
unsigned Dest = MI->getOperand(0).getReg();
unsigned Ptr = MI->getOperand(1).getReg();
unsigned CmpVal = MI->getOperand(2).getReg();
unsigned NewVal = MI->getOperand(3).getReg();
unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
unsigned Mask = RegInfo.createVirtualRegister(RC);
unsigned Mask2 = RegInfo.createVirtualRegister(RC);
unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
unsigned OldVal = RegInfo.createVirtualRegister(RC);
unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
unsigned StoreVal = RegInfo.createVirtualRegister(RC);
unsigned SrlRes = RegInfo.createVirtualRegister(RC);
unsigned Success = RegInfo.createVirtualRegister(RC);
// insert new blocks after the current block
const BasicBlock *LLVM_BB = BB->getBasicBlock();
MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
MachineFunction::iterator It = BB;
++It;
MF->insert(It, loop1MBB);
MF->insert(It, loop2MBB);
MF->insert(It, sinkMBB);
MF->insert(It, exitMBB);
// Transfer the remainder of BB and its successor edges to exitMBB.
exitMBB->splice(exitMBB->begin(), BB,
std::next(MachineBasicBlock::iterator(MI)), BB->end());
exitMBB->transferSuccessorsAndUpdatePHIs(BB);
BB->addSuccessor(loop1MBB);
loop1MBB->addSuccessor(sinkMBB);
loop1MBB->addSuccessor(loop2MBB);
loop2MBB->addSuccessor(loop1MBB);
loop2MBB->addSuccessor(sinkMBB);
sinkMBB->addSuccessor(exitMBB);
// FIXME: computation of newval2 can be moved to loop2MBB.
// thisMBB:
// addiu masklsb2,$0,-4 # 0xfffffffc
// and alignedaddr,ptr,masklsb2
// andi ptrlsb2,ptr,3
// sll shiftamt,ptrlsb2,3
// ori maskupper,$0,255 # 0xff
// sll mask,maskupper,shiftamt
// nor mask2,$0,mask
// andi maskedcmpval,cmpval,255
// sll shiftedcmpval,maskedcmpval,shiftamt
// andi maskednewval,newval,255
// sll shiftednewval,maskednewval,shiftamt
int64_t MaskImm = (Size == 1) ? 255 : 65535;
BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
.addReg(Mips::ZERO).addImm(-4);
BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
.addReg(Ptr).addReg(MaskLSB2);
BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
if (Subtarget.isLittle()) {
BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
} else {
unsigned Off = RegInfo.createVirtualRegister(RC);
BuildMI(BB, DL, TII->get(Mips::XORi), Off)
.addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
}
BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
.addReg(Mips::ZERO).addImm(MaskImm);
BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
.addReg(MaskUpper).addReg(ShiftAmt);
BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedCmpVal)
.addReg(CmpVal).addImm(MaskImm);
BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedCmpVal)
.addReg(MaskedCmpVal).addReg(ShiftAmt);
BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedNewVal)
.addReg(NewVal).addImm(MaskImm);
BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedNewVal)
.addReg(MaskedNewVal).addReg(ShiftAmt);
// loop1MBB:
// ll oldval,0(alginedaddr)
// and maskedoldval0,oldval,mask
// bne maskedoldval0,shiftedcmpval,sinkMBB
BB = loop1MBB;
BuildMI(BB, DL, TII->get(Mips::LL), OldVal).addReg(AlignedAddr).addImm(0);
BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
.addReg(OldVal).addReg(Mask);
BuildMI(BB, DL, TII->get(Mips::BNE))
.addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
// loop2MBB:
// and maskedoldval1,oldval,mask2
// or storeval,maskedoldval1,shiftednewval
// sc success,storeval,0(alignedaddr)
// beq success,$0,loop1MBB
BB = loop2MBB;
BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
.addReg(OldVal).addReg(Mask2);
BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
.addReg(MaskedOldVal1).addReg(ShiftedNewVal);
BuildMI(BB, DL, TII->get(Mips::SC), Success)
.addReg(StoreVal).addReg(AlignedAddr).addImm(0);
BuildMI(BB, DL, TII->get(Mips::BEQ))
.addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
// sinkMBB:
// srl srlres,maskedoldval0,shiftamt
// sign_extend dest,srlres
BB = sinkMBB;
BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
.addReg(MaskedOldVal0).addReg(ShiftAmt);
BB = emitSignExtendToI32InReg(MI, BB, Size, Dest, SrlRes);
MI->eraseFromParent(); // The instruction is gone now.
return exitMBB;
}
MachineBasicBlock *MipsTargetLowering::emitSEL_D(MachineInstr *MI,
MachineBasicBlock *BB) const {
MachineFunction *MF = BB->getParent();
const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
MachineRegisterInfo &RegInfo = MF->getRegInfo();
DebugLoc DL = MI->getDebugLoc();
MachineBasicBlock::iterator II(MI);
unsigned Fc = MI->getOperand(1).getReg();
const auto &FGR64RegClass = TRI->getRegClass(Mips::FGR64RegClassID);
unsigned Fc2 = RegInfo.createVirtualRegister(FGR64RegClass);
BuildMI(*BB, II, DL, TII->get(Mips::SUBREG_TO_REG), Fc2)
.addImm(0)
.addReg(Fc)
.addImm(Mips::sub_lo);
// We don't erase the original instruction, we just replace the condition
// register with the 64-bit super-register.
MI->getOperand(1).setReg(Fc2);
return BB;
}
//===----------------------------------------------------------------------===//
// Misc Lower Operation implementation
//===----------------------------------------------------------------------===//
SDValue MipsTargetLowering::lowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
SDValue Chain = Op.getOperand(0);
SDValue Table = Op.getOperand(1);
SDValue Index = Op.getOperand(2);
SDLoc DL(Op);
EVT PTy = getPointerTy();
unsigned EntrySize =
DAG.getMachineFunction().getJumpTableInfo()->getEntrySize(*getDataLayout());
Index = DAG.getNode(ISD::MUL, DL, PTy, Index,
DAG.getConstant(EntrySize, PTy));
SDValue Addr = DAG.getNode(ISD::ADD, DL, PTy, Index, Table);
EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), EntrySize * 8);
Addr = DAG.getExtLoad(ISD::SEXTLOAD, DL, PTy, Chain, Addr,
MachinePointerInfo::getJumpTable(), MemVT, false, false,
0);
Chain = Addr.getValue(1);
if ((getTargetMachine().getRelocationModel() == Reloc::PIC_) ||
Subtarget.isABI_N64()) {
// For PIC, the sequence is:
// BRIND(load(Jumptable + index) + RelocBase)
// RelocBase can be JumpTable, GOT or some sort of global base.
Addr = DAG.getNode(ISD::ADD, DL, PTy, Addr,
getPICJumpTableRelocBase(Table, DAG));
}
return DAG.getNode(ISD::BRIND, DL, MVT::Other, Chain, Addr);
}
SDValue MipsTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
// The first operand is the chain, the second is the condition, the third is
// the block to branch to if the condition is true.
SDValue Chain = Op.getOperand(0);
SDValue Dest = Op.getOperand(2);
SDLoc DL(Op);
assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
SDValue CondRes = createFPCmp(DAG, Op.getOperand(1));
// Return if flag is not set by a floating point comparison.
if (CondRes.getOpcode() != MipsISD::FPCmp)
return Op;
SDValue CCNode = CondRes.getOperand(2);
Mips::CondCode CC =
(Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
unsigned Opc = invertFPCondCodeUser(CC) ? Mips::BRANCH_F : Mips::BRANCH_T;
SDValue BrCode = DAG.getConstant(Opc, MVT::i32);
SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
return DAG.getNode(MipsISD::FPBrcond, DL, Op.getValueType(), Chain, BrCode,
FCC0, Dest, CondRes);
}
SDValue MipsTargetLowering::
lowerSELECT(SDValue Op, SelectionDAG &DAG) const
{
assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
SDValue Cond = createFPCmp(DAG, Op.getOperand(0));
// Return if flag is not set by a floating point comparison.
if (Cond.getOpcode() != MipsISD::FPCmp)
return Op;
return createCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
SDLoc(Op));
}
SDValue MipsTargetLowering::
lowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const
{
SDLoc DL(Op);
EVT Ty = Op.getOperand(0).getValueType();
SDValue Cond = DAG.getNode(ISD::SETCC, DL,
getSetCCResultType(*DAG.getContext(), Ty),
Op.getOperand(0), Op.getOperand(1),
Op.getOperand(4));
return DAG.getNode(ISD::SELECT, DL, Op.getValueType(), Cond, Op.getOperand(2),
Op.getOperand(3));
}
SDValue MipsTargetLowering::lowerSETCC(SDValue Op, SelectionDAG &DAG) const {
assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
SDValue Cond = createFPCmp(DAG, Op);
assert(Cond.getOpcode() == MipsISD::FPCmp &&
"Floating point operand expected.");
SDValue True = DAG.getConstant(1, MVT::i32);
SDValue False = DAG.getConstant(0, MVT::i32);
return createCMovFP(DAG, Cond, True, False, SDLoc(Op));
}
SDValue MipsTargetLowering::lowerGlobalAddress(SDValue Op,
SelectionDAG &DAG) const {
// FIXME there isn't actually debug info here
SDLoc DL(Op);
EVT Ty = Op.getValueType();
GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
const GlobalValue *GV = N->getGlobal();
if (getTargetMachine().getRelocationModel() != Reloc::PIC_ &&
!Subtarget.isABI_N64()) {
const MipsTargetObjectFile &TLOF =
(const MipsTargetObjectFile&)getObjFileLowering();
// %gp_rel relocation
if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
MipsII::MO_GPREL);
SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, DL,
DAG.getVTList(MVT::i32), GA);
SDValue GPReg = DAG.getRegister(Mips::GP, MVT::i32);
return DAG.getNode(ISD::ADD, DL, MVT::i32, GPReg, GPRelNode);
}
// %hi/%lo relocation
return getAddrNonPIC(N, Ty, DAG);
}
if (GV->hasInternalLinkage() || (GV->hasLocalLinkage() && !isa<Function>(GV)))
return getAddrLocal(N, Ty, DAG,
Subtarget.isABI_N32() || Subtarget.isABI_N64());
if (LargeGOT)
return getAddrGlobalLargeGOT(N, Ty, DAG, MipsII::MO_GOT_HI16,
MipsII::MO_GOT_LO16, DAG.getEntryNode(),
MachinePointerInfo::getGOT());
return getAddrGlobal(N, Ty, DAG,
(Subtarget.isABI_N32() || Subtarget.isABI_N64())
? MipsII::MO_GOT_DISP
: MipsII::MO_GOT16,
DAG.getEntryNode(), MachinePointerInfo::getGOT());
}
SDValue MipsTargetLowering::lowerBlockAddress(SDValue Op,
SelectionDAG &DAG) const {
BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
EVT Ty = Op.getValueType();
if (getTargetMachine().getRelocationModel() != Reloc::PIC_ &&
!Subtarget.isABI_N64())
return getAddrNonPIC(N, Ty, DAG);
return getAddrLocal(N, Ty, DAG,
Subtarget.isABI_N32() || Subtarget.isABI_N64());
}
SDValue MipsTargetLowering::
lowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
{
// If the relocation model is PIC, use the General Dynamic TLS Model or
// Local Dynamic TLS model, otherwise use the Initial Exec or
// Local Exec TLS Model.
GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
SDLoc DL(GA);
const GlobalValue *GV = GA->getGlobal();
EVT PtrVT = getPointerTy();
TLSModel::Model model = getTargetMachine().getTLSModel(GV);
if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
// General Dynamic and Local Dynamic TLS Model.
unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
: MipsII::MO_TLSGD;
SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, Flag);
SDValue Argument = DAG.getNode(MipsISD::Wrapper, DL, PtrVT,
getGlobalReg(DAG, PtrVT), TGA);
unsigned PtrSize = PtrVT.getSizeInBits();
IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
ArgListTy Args;
ArgListEntry Entry;
Entry.Node = Argument;
Entry.Ty = PtrTy;
Args.push_back(Entry);
TargetLowering::CallLoweringInfo CLI(DAG);
CLI.setDebugLoc(DL).setChain(DAG.getEntryNode())
.setCallee(CallingConv::C, PtrTy, TlsGetAddr, std::move(Args), 0);
std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
SDValue Ret = CallResult.first;
if (model != TLSModel::LocalDynamic)
return Ret;
SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
MipsII::MO_DTPREL_HI);
SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
MipsII::MO_DTPREL_LO);
SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Ret);
return DAG.getNode(ISD::ADD, DL, PtrVT, Add, Lo);
}
SDValue Offset;
if (model == TLSModel::InitialExec) {
// Initial Exec TLS Model
SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
MipsII::MO_GOTTPREL);
TGA = DAG.getNode(MipsISD::Wrapper, DL, PtrVT, getGlobalReg(DAG, PtrVT),
TGA);
Offset = DAG.getLoad(PtrVT, DL,
DAG.getEntryNode(), TGA, MachinePointerInfo(),
false, false, false, 0);
} else {
// Local Exec TLS Model
assert(model == TLSModel::LocalExec);
SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
MipsII::MO_TPREL_HI);
SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
MipsII::MO_TPREL_LO);
SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
}
SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, DL, PtrVT);
return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadPointer, Offset);
}
SDValue MipsTargetLowering::
lowerJumpTable(SDValue Op, SelectionDAG &DAG) const
{
JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
EVT Ty = Op.getValueType();
if (getTargetMachine().getRelocationModel() != Reloc::PIC_ &&
!Subtarget.isABI_N64())
return getAddrNonPIC(N, Ty, DAG);
return getAddrLocal(N, Ty, DAG,
Subtarget.isABI_N32() || Subtarget.isABI_N64());
}
SDValue MipsTargetLowering::
lowerConstantPool(SDValue Op, SelectionDAG &DAG) const
{
// gp_rel relocation
// FIXME: we should reference the constant pool using small data sections,
// but the asm printer currently doesn't support this feature without
// hacking it. This feature should come soon so we can uncomment the
// stuff below.
//if (IsInSmallSection(C->getType())) {
// SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
// SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
// ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
EVT Ty = Op.getValueType();
if (getTargetMachine().getRelocationModel() != Reloc::PIC_ &&
!Subtarget.isABI_N64())
return getAddrNonPIC(N, Ty, DAG);
return getAddrLocal(N, Ty, DAG,
Subtarget.isABI_N32() || Subtarget.isABI_N64());
}
SDValue MipsTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
MachineFunction &MF = DAG.getMachineFunction();
MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
SDLoc DL(Op);
SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
getPointerTy());
// vastart just stores the address of the VarArgsFrameIndex slot into the
// memory location argument.
const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
MachinePointerInfo(SV), false, false, 0);
}
static SDValue lowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG,
bool HasExtractInsert) {
EVT TyX = Op.getOperand(0).getValueType();
EVT TyY = Op.getOperand(1).getValueType();
SDValue Const1 = DAG.getConstant(1, MVT::i32);
SDValue Const31 = DAG.getConstant(31, MVT::i32);
SDLoc DL(Op);
SDValue Res;
// If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
// to i32.
SDValue X = (TyX == MVT::f32) ?
DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
Const1);
SDValue Y = (TyY == MVT::f32) ?
DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
Const1);
if (HasExtractInsert) {
// ext E, Y, 31, 1 ; extract bit31 of Y
// ins X, E, 31, 1 ; insert extracted bit at bit31 of X
SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
} else {
// sll SllX, X, 1
// srl SrlX, SllX, 1
// srl SrlY, Y, 31
// sll SllY, SrlX, 31
// or Or, SrlX, SllY
SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
}
if (TyX == MVT::f32)
return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
Op.getOperand(0), DAG.getConstant(0, MVT::i32));
return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
}
static SDValue lowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG,
bool HasExtractInsert) {
unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
SDValue Const1 = DAG.getConstant(1, MVT::i32);
SDLoc DL(Op);
// Bitcast to integer nodes.
SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
if (HasExtractInsert) {
// ext E, Y, width(Y) - 1, 1 ; extract bit width(Y)-1 of Y
// ins X, E, width(X) - 1, 1 ; insert extracted bit at bit width(X)-1 of X
SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
DAG.getConstant(WidthY - 1, MVT::i32), Const1);
if (WidthX > WidthY)
E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
else if (WidthY > WidthX)
E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
DAG.getConstant(WidthX - 1, MVT::i32), Const1, X);
return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
}
// (d)sll SllX, X, 1
// (d)srl SrlX, SllX, 1
// (d)srl SrlY, Y, width(Y)-1
// (d)sll SllY, SrlX, width(Y)-1
// or Or, SrlX, SllY
SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
DAG.getConstant(WidthY - 1, MVT::i32));
if (WidthX > WidthY)
SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
else if (WidthY > WidthX)
SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
DAG.getConstant(WidthX - 1, MVT::i32));
SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
}
SDValue
MipsTargetLowering::lowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
if (Subtarget.isGP64bit())
return lowerFCOPYSIGN64(Op, DAG, Subtarget.hasExtractInsert());
return lowerFCOPYSIGN32(Op, DAG, Subtarget.hasExtractInsert());
}
SDValue MipsTargetLowering::
lowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
// check the depth
assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
"Frame address can only be determined for current frame.");
MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
MFI->setFrameAddressIsTaken(true);
EVT VT = Op.getValueType();
SDLoc DL(Op);
SDValue FrameAddr =
DAG.getCopyFromReg(DAG.getEntryNode(), DL,
Subtarget.isABI_N64() ? Mips::FP_64 : Mips::FP, VT);
return FrameAddr;
}
SDValue MipsTargetLowering::lowerRETURNADDR(SDValue Op,
SelectionDAG &DAG) const {
if (verifyReturnAddressArgumentIsConstant(Op, DAG))
return SDValue();
// check the depth
assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
"Return address can be determined only for current frame.");
MachineFunction &MF = DAG.getMachineFunction();
MachineFrameInfo *MFI = MF.getFrameInfo();
MVT VT = Op.getSimpleValueType();
unsigned RA = Subtarget.isABI_N64() ? Mips::RA_64 : Mips::RA;
MFI->setReturnAddressIsTaken(true);
// Return RA, which contains the return address. Mark it an implicit live-in.
unsigned Reg = MF.addLiveIn(RA, getRegClassFor(VT));
return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), Reg, VT);
}
// An EH_RETURN is the result of lowering llvm.eh.return which in turn is
// generated from __builtin_eh_return (offset, handler)
// The effect of this is to adjust the stack pointer by "offset"
// and then branch to "handler".
SDValue MipsTargetLowering::lowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
const {
MachineFunction &MF = DAG.getMachineFunction();
MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
MipsFI->setCallsEhReturn();
SDValue Chain = Op.getOperand(0);
SDValue Offset = Op.getOperand(1);
SDValue Handler = Op.getOperand(2);
SDLoc DL(Op);
EVT Ty = Subtarget.isABI_N64() ? MVT::i64 : MVT::i32;
// Store stack offset in V1, store jump target in V0. Glue CopyToReg and
// EH_RETURN nodes, so that instructions are emitted back-to-back.
unsigned OffsetReg = Subtarget.isABI_N64() ? Mips::V1_64 : Mips::V1;
unsigned AddrReg = Subtarget.isABI_N64() ? Mips::V0_64 : Mips::V0;
Chain = DAG.getCopyToReg(Chain, DL, OffsetReg, Offset, SDValue());
Chain = DAG.getCopyToReg(Chain, DL, AddrReg, Handler, Chain.getValue(1));
return DAG.getNode(MipsISD::EH_RETURN, DL, MVT::Other, Chain,
DAG.getRegister(OffsetReg, Ty),
DAG.getRegister(AddrReg, getPointerTy()),
Chain.getValue(1));
}
SDValue MipsTargetLowering::lowerATOMIC_FENCE(SDValue Op,
SelectionDAG &DAG) const {
// FIXME: Need pseudo-fence for 'singlethread' fences
// FIXME: Set SType for weaker fences where supported/appropriate.
unsigned SType = 0;
SDLoc DL(Op);
return DAG.getNode(MipsISD::Sync, DL, MVT::Other, Op.getOperand(0),
DAG.getConstant(SType, MVT::i32));
}
SDValue MipsTargetLowering::lowerShiftLeftParts(SDValue Op,
SelectionDAG &DAG) const {
SDLoc DL(Op);
SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
SDValue Shamt = Op.getOperand(2);
// if shamt < 32:
// lo = (shl lo, shamt)
// hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt))
// else:
// lo = 0
// hi = (shl lo, shamt[4:0])
SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
DAG.getConstant(-1, MVT::i32));
SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo,
DAG.getConstant(1, MVT::i32));
SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, ShiftRight1Lo,
Not);
SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi, Shamt);
SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, MVT::i32, Lo, Shamt);
SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
DAG.getConstant(0x20, MVT::i32));
Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
DAG.getConstant(0, MVT::i32), ShiftLeftLo);
Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftLeftLo, Or);
SDValue Ops[2] = {Lo, Hi};
return DAG.getMergeValues(Ops, DL);
}
SDValue MipsTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
bool IsSRA) const {
SDLoc DL(Op);
SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
SDValue Shamt = Op.getOperand(2);
// if shamt < 32:
// lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt))
// if isSRA:
// hi = (sra hi, shamt)
// else:
// hi = (srl hi, shamt)
// else:
// if isSRA:
// lo = (sra hi, shamt[4:0])
// hi = (sra hi, 31)
// else:
// lo = (srl hi, shamt[4:0])
// hi = 0
SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
DAG.getConstant(-1, MVT::i32));
SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi,
DAG.getConstant(1, MVT::i32));
SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, ShiftLeft1Hi, Not);
SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo, Shamt);
SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, DL, MVT::i32,
Hi, Shamt);
SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
DAG.getConstant(0x20, MVT::i32));
SDValue Shift31 = DAG.getNode(ISD::SRA, DL, MVT::i32, Hi,
DAG.getConstant(31, MVT::i32));
Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftRightHi, Or);
Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
IsSRA ? Shift31 : DAG.getConstant(0, MVT::i32),
ShiftRightHi);
SDValue Ops[2] = {Lo, Hi};
return DAG.getMergeValues(Ops, DL);
}
static SDValue createLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD,
SDValue Chain, SDValue Src, unsigned Offset) {
SDValue Ptr = LD->getBasePtr();
EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
EVT BasePtrVT = Ptr.getValueType();
SDLoc DL(LD);
SDVTList VTList = DAG.getVTList(VT, MVT::Other);
if (Offset)
Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
DAG.getConstant(Offset, BasePtrVT));
SDValue Ops[] = { Chain, Ptr, Src };
return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
LD->getMemOperand());
}
// Expand an unaligned 32 or 64-bit integer load node.
SDValue MipsTargetLowering::lowerLOAD(SDValue Op, SelectionDAG &DAG) const {
LoadSDNode *LD = cast<LoadSDNode>(Op);
EVT MemVT = LD->getMemoryVT();
if (Subtarget.systemSupportsUnalignedAccess())
return Op;
// Return if load is aligned or if MemVT is neither i32 nor i64.
if ((LD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
((MemVT != MVT::i32) && (MemVT != MVT::i64)))
return SDValue();
bool IsLittle = Subtarget.isLittle();
EVT VT = Op.getValueType();
ISD::LoadExtType ExtType = LD->getExtensionType();
SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
assert((VT == MVT::i32) || (VT == MVT::i64));
// Expand
// (set dst, (i64 (load baseptr)))
// to
// (set tmp, (ldl (add baseptr, 7), undef))
// (set dst, (ldr baseptr, tmp))
if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
SDValue LDL = createLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
IsLittle ? 7 : 0);
return createLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
IsLittle ? 0 : 7);
}
SDValue LWL = createLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
IsLittle ? 3 : 0);
SDValue LWR = createLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
IsLittle ? 0 : 3);
// Expand
// (set dst, (i32 (load baseptr))) or
// (set dst, (i64 (sextload baseptr))) or
// (set dst, (i64 (extload baseptr)))
// to
// (set tmp, (lwl (add baseptr, 3), undef))
// (set dst, (lwr baseptr, tmp))
if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
(ExtType == ISD::EXTLOAD))
return LWR;
assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD));
// Expand
// (set dst, (i64 (zextload baseptr)))
// to
// (set tmp0, (lwl (add baseptr, 3), undef))
// (set tmp1, (lwr baseptr, tmp0))
// (set tmp2, (shl tmp1, 32))
// (set dst, (srl tmp2, 32))
SDLoc DL(LD);
SDValue Const32 = DAG.getConstant(32, MVT::i32);
SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
SDValue Ops[] = { SRL, LWR.getValue(1) };
return DAG.getMergeValues(Ops, DL);
}
static SDValue createStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD,
SDValue Chain, unsigned Offset) {
SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
SDLoc DL(SD);
SDVTList VTList = DAG.getVTList(MVT::Other);
if (Offset)
Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
DAG.getConstant(Offset, BasePtrVT));
SDValue Ops[] = { Chain, Value, Ptr };
return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
SD->getMemOperand());
}
// Expand an unaligned 32 or 64-bit integer store node.
static SDValue lowerUnalignedIntStore(StoreSDNode *SD, SelectionDAG &DAG,
bool IsLittle) {
SDValue Value = SD->getValue(), Chain = SD->getChain();
EVT VT = Value.getValueType();
// Expand
// (store val, baseptr) or
// (truncstore val, baseptr)
// to
// (swl val, (add baseptr, 3))
// (swr val, baseptr)
if ((VT == MVT::i32) || SD->isTruncatingStore()) {
SDValue SWL = createStoreLR(MipsISD::SWL, DAG, SD, Chain,
IsLittle ? 3 : 0);
return createStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
}
assert(VT == MVT::i64);
// Expand
// (store val, baseptr)
// to
// (sdl val, (add baseptr, 7))
// (sdr val, baseptr)
SDValue SDL = createStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
return createStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
}
// Lower (store (fp_to_sint $fp) $ptr) to (store (TruncIntFP $fp), $ptr).
static SDValue lowerFP_TO_SINT_STORE(StoreSDNode *SD, SelectionDAG &DAG) {
SDValue Val = SD->getValue();
if (Val.getOpcode() != ISD::FP_TO_SINT)
return SDValue();
EVT FPTy = EVT::getFloatingPointVT(Val.getValueSizeInBits());
SDValue Tr = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Val), FPTy,
Val.getOperand(0));
return DAG.getStore(SD->getChain(), SDLoc(SD), Tr, SD->getBasePtr(),
SD->getPointerInfo(), SD->isVolatile(),
SD->isNonTemporal(), SD->getAlignment());
}
SDValue MipsTargetLowering::lowerSTORE(SDValue Op, SelectionDAG &DAG) const {
StoreSDNode *SD = cast<StoreSDNode>(Op);
EVT MemVT = SD->getMemoryVT();
// Lower unaligned integer stores.
if (!Subtarget.systemSupportsUnalignedAccess() &&
(SD->getAlignment() < MemVT.getSizeInBits() / 8) &&
((MemVT == MVT::i32) || (MemVT == MVT::i64)))
return lowerUnalignedIntStore(SD, DAG, Subtarget.isLittle());
return lowerFP_TO_SINT_STORE(SD, DAG);
}
SDValue MipsTargetLowering::lowerADD(SDValue Op, SelectionDAG &DAG) const {
if (Op->getOperand(0).getOpcode() != ISD::FRAMEADDR
|| cast<ConstantSDNode>
(Op->getOperand(0).getOperand(0))->getZExtValue() != 0
|| Op->getOperand(1).getOpcode() != ISD::FRAME_TO_ARGS_OFFSET)
return SDValue();
// The pattern
// (add (frameaddr 0), (frame_to_args_offset))
// results from lowering llvm.eh.dwarf.cfa intrinsic. Transform it to
// (add FrameObject, 0)
// where FrameObject is a fixed StackObject with offset 0 which points to
// the old stack pointer.
MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
EVT ValTy = Op->getValueType(0);
int FI = MFI->CreateFixedObject(Op.getValueSizeInBits() / 8, 0, false);
SDValue InArgsAddr = DAG.getFrameIndex(FI, ValTy);
return DAG.getNode(ISD::ADD, SDLoc(Op), ValTy, InArgsAddr,
DAG.getConstant(0, ValTy));
}
SDValue MipsTargetLowering::lowerFP_TO_SINT(SDValue Op,
SelectionDAG &DAG) const {
EVT FPTy = EVT::getFloatingPointVT(Op.getValueSizeInBits());
SDValue Trunc = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Op), FPTy,
Op.getOperand(0));
return DAG.getNode(ISD::BITCAST, SDLoc(Op), Op.getValueType(), Trunc);
}
//===----------------------------------------------------------------------===//
// Calling Convention Implementation
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
// TODO: Implement a generic logic using tblgen that can support this.
// Mips O32 ABI rules:
// ---
// i32 - Passed in A0, A1, A2, A3 and stack
// f32 - Only passed in f32 registers if no int reg has been used yet to hold
// an argument. Otherwise, passed in A1, A2, A3 and stack.
// f64 - Only passed in two aliased f32 registers if no int reg has been used
// yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
// not used, it must be shadowed. If only A3 is avaiable, shadow it and
// go to stack.
//
// For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
//===----------------------------------------------------------------------===//
static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT,
CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
CCState &State, const MCPhysReg *F64Regs) {
static const unsigned IntRegsSize = 4, FloatRegsSize = 2;
static const MCPhysReg IntRegs[] = { Mips::A0, Mips::A1, Mips::A2, Mips::A3 };
static const MCPhysReg F32Regs[] = { Mips::F12, Mips::F14 };
// Do not process byval args here.
if (ArgFlags.isByVal())
return true;
// Promote i8 and i16
if (LocVT == MVT::i8 || LocVT == MVT::i16) {
LocVT = MVT::i32;
if (ArgFlags.isSExt())
LocInfo = CCValAssign::SExt;
else if (ArgFlags.isZExt())
LocInfo = CCValAssign::ZExt;
else
LocInfo = CCValAssign::AExt;
}
unsigned Reg;
// f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
// is true: function is vararg, argument is 3rd or higher, there is previous
// argument which is not f32 or f64.
bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
|| State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
unsigned OrigAlign = ArgFlags.getOrigAlign();
bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
Reg = State.AllocateReg(IntRegs, IntRegsSize);
// If this is the first part of an i64 arg,
// the allocated register must be either A0 or A2.
if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
Reg = State.AllocateReg(IntRegs, IntRegsSize);
LocVT = MVT::i32;
} else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
// Allocate int register and shadow next int register. If first
// available register is Mips::A1 or Mips::A3, shadow it too.
Reg = State.AllocateReg(IntRegs, IntRegsSize);
if (Reg == Mips::A1 || Reg == Mips::A3)
Reg = State.AllocateReg(IntRegs, IntRegsSize);
State.AllocateReg(IntRegs, IntRegsSize);
LocVT = MVT::i32;
} else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
// we are guaranteed to find an available float register
if (ValVT == MVT::f32) {
Reg = State.AllocateReg(F32Regs, FloatRegsSize);
// Shadow int register
State.AllocateReg(IntRegs, IntRegsSize);
} else {
Reg = State.AllocateReg(F64Regs, FloatRegsSize);
// Shadow int registers
unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
State.AllocateReg(IntRegs, IntRegsSize);
State.AllocateReg(IntRegs, IntRegsSize);
}
} else
llvm_unreachable("Cannot handle this ValVT.");
if (!Reg) {
unsigned Offset = State.AllocateStack(ValVT.getSizeInBits() >> 3,
OrigAlign);
State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
} else
State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
return false;
}
static bool CC_MipsO32_FP32(unsigned ValNo, MVT ValVT,
MVT LocVT, CCValAssign::LocInfo LocInfo,
ISD::ArgFlagsTy ArgFlags, CCState &State) {
static const MCPhysReg F64Regs[] = { Mips::D6, Mips::D7 };
return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
}
static bool CC_MipsO32_FP64(unsigned ValNo, MVT ValVT,
MVT LocVT, CCValAssign::LocInfo LocInfo,
ISD::ArgFlagsTy ArgFlags, CCState &State) {
static const MCPhysReg F64Regs[] = { Mips::D12_64, Mips::D14_64 };
return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
}
#include "MipsGenCallingConv.inc"
//===----------------------------------------------------------------------===//
// Call Calling Convention Implementation
//===----------------------------------------------------------------------===//
// Return next O32 integer argument register.
static unsigned getNextIntArgReg(unsigned Reg) {
assert((Reg == Mips::A0) || (Reg == Mips::A2));
return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
}
SDValue
MipsTargetLowering::passArgOnStack(SDValue StackPtr, unsigned Offset,
SDValue Chain, SDValue Arg, SDLoc DL,
bool IsTailCall, SelectionDAG &DAG) const {
if (!IsTailCall) {
SDValue PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr,
DAG.getIntPtrConstant(Offset));
return DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo(), false,
false, 0);
}
MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
int FI = MFI->CreateFixedObject(Arg.getValueSizeInBits() / 8, Offset, false);
SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
return DAG.getStore(Chain, DL, Arg, FIN, MachinePointerInfo(),
/*isVolatile=*/ true, false, 0);
}
void MipsTargetLowering::
getOpndList(SmallVectorImpl<SDValue> &Ops,
std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
bool IsPICCall, bool GlobalOrExternal, bool InternalLinkage,
CallLoweringInfo &CLI, SDValue Callee, SDValue Chain) const {
// Insert node "GP copy globalreg" before call to function.
//
// R_MIPS_CALL* operators (emitted when non-internal functions are called
// in PIC mode) allow symbols to be resolved via lazy binding.
// The lazy binding stub requires GP to point to the GOT.
if (IsPICCall && !InternalLinkage) {
unsigned GPReg = Subtarget.isABI_N64() ? Mips::GP_64 : Mips::GP;
EVT Ty = Subtarget.isABI_N64() ? MVT::i64 : MVT::i32;
RegsToPass.push_back(std::make_pair(GPReg, getGlobalReg(CLI.DAG, Ty)));
}
// Build a sequence of copy-to-reg nodes chained together with token
// chain and flag operands which copy the outgoing args into registers.
// The InFlag in necessary since all emitted instructions must be
// stuck together.
SDValue InFlag;
for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
Chain = CLI.DAG.getCopyToReg(Chain, CLI.DL, RegsToPass[i].first,
RegsToPass[i].second, InFlag);
InFlag = Chain.getValue(1);
}
// Add argument registers to the end of the list so that they are
// known live into the call.
for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
Ops.push_back(CLI.DAG.getRegister(RegsToPass[i].first,
RegsToPass[i].second.getValueType()));
// Add a register mask operand representing the call-preserved registers.
const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
const uint32_t *Mask = TRI->getCallPreservedMask(CLI.CallConv);
assert(Mask && "Missing call preserved mask for calling convention");
if (Subtarget.inMips16HardFloat()) {
if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(CLI.Callee)) {
llvm::StringRef Sym = G->getGlobal()->getName();
Function *F = G->getGlobal()->getParent()->getFunction(Sym);
if (F && F->hasFnAttribute("__Mips16RetHelper")) {
Mask = MipsRegisterInfo::getMips16RetHelperMask();
}
}
}
Ops.push_back(CLI.DAG.getRegisterMask(Mask));
if (InFlag.getNode())
Ops.push_back(InFlag);
}
/// LowerCall - functions arguments are copied from virtual regs to
/// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
SDValue
MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
SmallVectorImpl<SDValue> &InVals) const {
SelectionDAG &DAG = CLI.DAG;
SDLoc DL = CLI.DL;
SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
SDValue Chain = CLI.Chain;
SDValue Callee = CLI.Callee;
bool &IsTailCall = CLI.IsTailCall;
CallingConv::ID CallConv = CLI.CallConv;
bool IsVarArg = CLI.IsVarArg;
MachineFunction &MF = DAG.getMachineFunction();
MachineFrameInfo *MFI = MF.getFrameInfo();
const TargetFrameLowering *TFL = MF.getTarget().getFrameLowering();
MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
// Analyze operands of the call, assigning locations to each operand.
SmallVector<CCValAssign, 16> ArgLocs;
CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
getTargetMachine(), ArgLocs, *DAG.getContext());
MipsCC::SpecialCallingConvType SpecialCallingConv =
getSpecialCallingConv(Callee);
MipsCC MipsCCInfo(CallConv, Subtarget.isABI_O32(), Subtarget.isFP64bit(),
CCInfo, SpecialCallingConv);
MipsCCInfo.analyzeCallOperands(Outs, IsVarArg,
Subtarget.abiUsesSoftFloat(),
Callee.getNode(), CLI.getArgs());
// Get a count of how many bytes are to be pushed on the stack.
unsigned NextStackOffset = CCInfo.getNextStackOffset();
// Check if it's really possible to do a tail call.
if (IsTailCall)
IsTailCall =
isEligibleForTailCallOptimization(MipsCCInfo, NextStackOffset,
*MF.getInfo<MipsFunctionInfo>());
if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
report_fatal_error("failed to perform tail call elimination on a call "
"site marked musttail");
if (IsTailCall)
++NumTailCalls;
// Chain is the output chain of the last Load/Store or CopyToReg node.
// ByValChain is the output chain of the last Memcpy node created for copying
// byval arguments to the stack.
unsigned StackAlignment = TFL->getStackAlignment();
NextStackOffset = RoundUpToAlignment(NextStackOffset, StackAlignment);
SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
if (!IsTailCall)
Chain = DAG.getCALLSEQ_START(Chain, NextStackOffsetVal, DL);
SDValue StackPtr = DAG.getCopyFromReg(
Chain, DL, Subtarget.isABI_N64() ? Mips::SP_64 : Mips::SP,
getPointerTy());
// With EABI is it possible to have 16 args on registers.
std::deque< std::pair<unsigned, SDValue> > RegsToPass;
SmallVector<SDValue, 8> MemOpChains;
MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
// Walk the register/memloc assignments, inserting copies/loads.
for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
SDValue Arg = OutVals[i];
CCValAssign &VA = ArgLocs[i];
MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
ISD::ArgFlagsTy Flags = Outs[i].Flags;
// ByVal Arg.
if (Flags.isByVal()) {
assert(Flags.getByValSize() &&
"ByVal args of size 0 should have been ignored by front-end.");
assert(ByValArg != MipsCCInfo.byval_end());
assert(!IsTailCall &&
"Do not tail-call optimize if there is a byval argument.");
passByValArg(Chain, DL, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg,
MipsCCInfo, *ByValArg, Flags, Subtarget.isLittle());
++ByValArg;
continue;
}
// Promote the value if needed.
switch (VA.getLocInfo()) {
default: llvm_unreachable("Unknown loc info!");
case CCValAssign::Full:
if (VA.isRegLoc()) {
if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
(ValVT == MVT::f64 && LocVT == MVT::i64) ||
(ValVT == MVT::i64 && LocVT == MVT::f64))
Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
Arg, DAG.getConstant(0, MVT::i32));
SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
Arg, DAG.getConstant(1, MVT::i32));
if (!Subtarget.isLittle())
std::swap(Lo, Hi);
unsigned LocRegLo = VA.getLocReg();
unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
continue;
}
}
break;
case CCValAssign::SExt:
Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, LocVT, Arg);
break;
case CCValAssign::ZExt:
Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, LocVT, Arg);
break;
case CCValAssign::AExt:
Arg = DAG.getNode(ISD::ANY_EXTEND, DL, LocVT, Arg);
break;
}
// Arguments that can be passed on register must be kept at
// RegsToPass vector
if (VA.isRegLoc()) {
RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
continue;
}
// Register can't get to this point...
assert(VA.isMemLoc());
// emit ISD::STORE whichs stores the
// parameter value to a stack Location
MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(),
Chain, Arg, DL, IsTailCall, DAG));
}
// Transform all store nodes into one single node because all store
// nodes are independent of each other.
if (!MemOpChains.empty())
Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
// If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
// direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
// node so that legalize doesn't hack it.
bool IsPICCall =
(Subtarget.isABI_N64() || IsPIC); // true if calls are translated to
// jalr $25
bool GlobalOrExternal = false, InternalLinkage = false;
SDValue CalleeLo;
EVT Ty = Callee.getValueType();
if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
if (IsPICCall) {
const GlobalValue *Val = G->getGlobal();
InternalLinkage = Val->hasInternalLinkage();
if (InternalLinkage)
Callee = getAddrLocal(G, Ty, DAG,
Subtarget.isABI_N32() || Subtarget.isABI_N64());
else if (LargeGOT)
Callee = getAddrGlobalLargeGOT(G, Ty, DAG, MipsII::MO_CALL_HI16,
MipsII::MO_CALL_LO16, Chain,
FuncInfo->callPtrInfo(Val));
else
Callee = getAddrGlobal(G, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
FuncInfo->callPtrInfo(Val));
} else
Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, getPointerTy(), 0,
MipsII::MO_NO_FLAG);
GlobalOrExternal = true;
}
else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
const char *Sym = S->getSymbol();
if (!Subtarget.isABI_N64() && !IsPIC) // !N64 && static
Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(),
MipsII::MO_NO_FLAG);
else if (LargeGOT)
Callee = getAddrGlobalLargeGOT(S, Ty, DAG, MipsII::MO_CALL_HI16,
MipsII::MO_CALL_LO16, Chain,
FuncInfo->callPtrInfo(Sym));
else // N64 || PIC
Callee = getAddrGlobal(S, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
FuncInfo->callPtrInfo(Sym));
GlobalOrExternal = true;
}
SmallVector<SDValue, 8> Ops(1, Chain);
SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
getOpndList(Ops, RegsToPass, IsPICCall, GlobalOrExternal, InternalLinkage,
CLI, Callee, Chain);
if (IsTailCall)
return DAG.getNode(MipsISD::TailCall, DL, MVT::Other, Ops);
Chain = DAG.getNode(MipsISD::JmpLink, DL, NodeTys, Ops);
SDValue InFlag = Chain.getValue(1);
// Create the CALLSEQ_END node.
Chain = DAG.getCALLSEQ_END(Chain, NextStackOffsetVal,
DAG.getIntPtrConstant(0, true), InFlag, DL);
InFlag = Chain.getValue(1);
// Handle result values, copying them out of physregs into vregs that we
// return.
return LowerCallResult(Chain, InFlag, CallConv, IsVarArg,
Ins, DL, DAG, InVals, CLI.Callee.getNode(), CLI.RetTy);
}
/// LowerCallResult - Lower the result values of a call into the
/// appropriate copies out of appropriate physical registers.
SDValue
MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
CallingConv::ID CallConv, bool IsVarArg,
const SmallVectorImpl<ISD::InputArg> &Ins,
SDLoc DL, SelectionDAG &DAG,
SmallVectorImpl<SDValue> &InVals,
const SDNode *CallNode,
const Type *RetTy) const {
// Assign locations to each value returned by this call.
SmallVector<CCValAssign, 16> RVLocs;
CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
getTargetMachine(), RVLocs, *DAG.getContext());
MipsCC MipsCCInfo(CallConv, Subtarget.isABI_O32(), Subtarget.isFP64bit(),
CCInfo);
MipsCCInfo.analyzeCallResult(Ins, Subtarget.abiUsesSoftFloat(),
CallNode, RetTy);
// Copy all of the result registers out of their specified physreg.
for (unsigned i = 0; i != RVLocs.size(); ++i) {
SDValue Val = DAG.getCopyFromReg(Chain, DL, RVLocs[i].getLocReg(),
RVLocs[i].getLocVT(), InFlag);
Chain = Val.getValue(1);
InFlag = Val.getValue(2);
if (RVLocs[i].getValVT() != RVLocs[i].getLocVT())
Val = DAG.getNode(ISD::BITCAST, DL, RVLocs[i].getValVT(), Val);
InVals.push_back(Val);
}
return Chain;
}
//===----------------------------------------------------------------------===//
// Formal Arguments Calling Convention Implementation
//===----------------------------------------------------------------------===//
/// LowerFormalArguments - transform physical registers into virtual registers
/// and generate load operations for arguments places on the stack.
SDValue
MipsTargetLowering::LowerFormalArguments(SDValue Chain,
CallingConv::ID CallConv,
bool IsVarArg,
const SmallVectorImpl<ISD::InputArg> &Ins,
SDLoc DL, SelectionDAG &DAG,
SmallVectorImpl<SDValue> &InVals)
const {
MachineFunction &MF = DAG.getMachineFunction();
MachineFrameInfo *MFI = MF.getFrameInfo();
MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
MipsFI->setVarArgsFrameIndex(0);
// Used with vargs to acumulate store chains.
std::vector<SDValue> OutChains;
// Assign locations to all of the incoming arguments.
SmallVector<CCValAssign, 16> ArgLocs;
CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
getTargetMachine(), ArgLocs, *DAG.getContext());
MipsCC MipsCCInfo(CallConv, Subtarget.isABI_O32(), Subtarget.isFP64bit(),
CCInfo);
Function::const_arg_iterator FuncArg =
DAG.getMachineFunction().getFunction()->arg_begin();
bool UseSoftFloat = Subtarget.abiUsesSoftFloat();
MipsCCInfo.analyzeFormalArguments(Ins, UseSoftFloat, FuncArg);
MipsFI->setFormalArgInfo(CCInfo.getNextStackOffset(),
MipsCCInfo.hasByValArg());
unsigned CurArgIdx = 0;
MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
CCValAssign &VA = ArgLocs[i];
std::advance(FuncArg, Ins[i].OrigArgIndex - CurArgIdx);
CurArgIdx = Ins[i].OrigArgIndex;
EVT ValVT = VA.getValVT();
ISD::ArgFlagsTy Flags = Ins[i].Flags;
bool IsRegLoc = VA.isRegLoc();
if (Flags.isByVal()) {
assert(Flags.getByValSize() &&
"ByVal args of size 0 should have been ignored by front-end.");
assert(ByValArg != MipsCCInfo.byval_end());
copyByValRegs(Chain, DL, OutChains, DAG, Flags, InVals, &*FuncArg,
MipsCCInfo, *ByValArg);
++ByValArg;
continue;
}
// Arguments stored on registers
if (IsRegLoc) {
MVT RegVT = VA.getLocVT();
unsigned ArgReg = VA.getLocReg();
const TargetRegisterClass *RC = getRegClassFor(RegVT);
// Transform the arguments stored on
// physical registers into virtual ones
unsigned Reg = addLiveIn(DAG.getMachineFunction(), ArgReg, RC);
SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
// If this is an 8 or 16-bit value, it has been passed promoted
// to 32 bits. Insert an assert[sz]ext to capture this, then
// truncate to the right size.
if (VA.getLocInfo() != CCValAssign::Full) {
unsigned Opcode = 0;
if (VA.getLocInfo() == CCValAssign::SExt)
Opcode = ISD::AssertSext;
else if (VA.getLocInfo() == CCValAssign::ZExt)
Opcode = ISD::AssertZext;
if (Opcode)
ArgValue = DAG.getNode(Opcode, DL, RegVT, ArgValue,
DAG.getValueType(ValVT));
ArgValue = DAG.getNode(ISD::TRUNCATE, DL, ValVT, ArgValue);
}
// Handle floating point arguments passed in integer registers and
// long double arguments passed in floating point registers.
if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
(RegVT == MVT::i64 && ValVT == MVT::f64) ||
(RegVT == MVT::f64 && ValVT == MVT::i64))
ArgValue = DAG.getNode(ISD::BITCAST, DL, ValVT, ArgValue);
else if (Subtarget.isABI_O32() && RegVT == MVT::i32 &&
ValVT == MVT::f64) {
unsigned Reg2 = addLiveIn(DAG.getMachineFunction(),
getNextIntArgReg(ArgReg), RC);
SDValue ArgValue2 = DAG.getCopyFromReg(Chain, DL, Reg2, RegVT);
if (!Subtarget.isLittle())
std::swap(ArgValue, ArgValue2);
ArgValue = DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64,
ArgValue, ArgValue2);
}
InVals.push_back(ArgValue);
} else { // VA.isRegLoc()
// sanity check
assert(VA.isMemLoc());
// The stack pointer offset is relative to the caller stack frame.
int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
VA.getLocMemOffset(), true);
// Create load nodes to retrieve arguments from the stack
SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
SDValue Load = DAG.getLoad(ValVT, DL, Chain, FIN,
MachinePointerInfo::getFixedStack(FI),
false, false, false, 0);
InVals.push_back(Load);
OutChains.push_back(Load.getValue(1));
}
}
for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
// The mips ABIs for returning structs by value requires that we copy
// the sret argument into $v0 for the return. Save the argument into
// a virtual register so that we can access it from the return points.
if (Ins[i].Flags.isSRet()) {
unsigned Reg = MipsFI->getSRetReturnReg();
if (!Reg) {
Reg = MF.getRegInfo().createVirtualRegister(
getRegClassFor(Subtarget.isABI_N64() ? MVT::i64 : MVT::i32));
MipsFI->setSRetReturnReg(Reg);
}
SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[i]);
Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
break;
}
}
if (IsVarArg)
writeVarArgRegs(OutChains, MipsCCInfo, Chain, DL, DAG);
// All stores are grouped in one node to allow the matching between
// the size of Ins and InVals. This only happens when on varg functions
if (!OutChains.empty()) {
OutChains.push_back(Chain);
Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
}
return Chain;
}
//===----------------------------------------------------------------------===//
// Return Value Calling Convention Implementation
//===----------------------------------------------------------------------===//
bool
MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
MachineFunction &MF, bool IsVarArg,
const SmallVectorImpl<ISD::OutputArg> &Outs,
LLVMContext &Context) const {
SmallVector<CCValAssign, 16> RVLocs;
CCState CCInfo(CallConv, IsVarArg, MF, getTargetMachine(),
RVLocs, Context);
return CCInfo.CheckReturn(Outs, RetCC_Mips);
}
SDValue
MipsTargetLowering::LowerReturn(SDValue Chain,
CallingConv::ID CallConv, bool IsVarArg,
const SmallVectorImpl<ISD::OutputArg> &Outs,
const SmallVectorImpl<SDValue> &OutVals,
SDLoc DL, SelectionDAG &DAG) const {
// CCValAssign - represent the assignment of
// the return value to a location
SmallVector<CCValAssign, 16> RVLocs;
MachineFunction &MF = DAG.getMachineFunction();
// CCState - Info about the registers and stack slot.
CCState CCInfo(CallConv, IsVarArg, MF, getTargetMachine(), RVLocs,
*DAG.getContext());
MipsCC MipsCCInfo(CallConv, Subtarget.isABI_O32(), Subtarget.isFP64bit(),
CCInfo);
// Analyze return values.
MipsCCInfo.analyzeReturn(Outs, Subtarget.abiUsesSoftFloat(),
MF.getFunction()->getReturnType());
SDValue Flag;
SmallVector<SDValue, 4> RetOps(1, Chain);
// Copy the result values into the output registers.
for (unsigned i = 0; i != RVLocs.size(); ++i) {
SDValue Val = OutVals[i];
CCValAssign &VA = RVLocs[i];
assert(VA.isRegLoc() && "Can only return in registers!");
if (RVLocs[i].getValVT() != RVLocs[i].getLocVT())
Val = DAG.getNode(ISD::BITCAST, DL, RVLocs[i].getLocVT(), Val);
Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Flag);
// Guarantee that all emitted copies are stuck together with flags.
Flag = Chain.getValue(1);
RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
}
// The mips ABIs for returning structs by value requires that we copy
// the sret argument into $v0 for the return. We saved the argument into
// a virtual register in the entry block, so now we copy the value out
// and into $v0.
if (MF.getFunction()->hasStructRetAttr()) {
MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
unsigned Reg = MipsFI->getSRetReturnReg();
if (!Reg)
llvm_unreachable("sret virtual register not created in the entry block");
SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
unsigned V0 = Subtarget.isABI_N64() ? Mips::V0_64 : Mips::V0;
Chain = DAG.getCopyToReg(Chain, DL, V0, Val, Flag);
Flag = Chain.getValue(1);
RetOps.push_back(DAG.getRegister(V0, getPointerTy()));
}
RetOps[0] = Chain; // Update chain.
// Add the flag if we have it.
if (Flag.getNode())
RetOps.push_back(Flag);
// Return on Mips is always a "jr $ra"
return DAG.getNode(MipsISD::Ret, DL, MVT::Other, RetOps);
}
//===----------------------------------------------------------------------===//
// Mips Inline Assembly Support
//===----------------------------------------------------------------------===//
/// getConstraintType - Given a constraint letter, return the type of
/// constraint it is for this target.
MipsTargetLowering::ConstraintType MipsTargetLowering::
getConstraintType(const std::string &Constraint) const
{
// Mips specific constraints
// GCC config/mips/constraints.md
//
// 'd' : An address register. Equivalent to r
// unless generating MIPS16 code.
// 'y' : Equivalent to r; retained for
// backwards compatibility.
// 'c' : A register suitable for use in an indirect
// jump. This will always be $25 for -mabicalls.
// 'l' : The lo register. 1 word storage.
// 'x' : The hilo register pair. Double word storage.
if (Constraint.size() == 1) {
switch (Constraint[0]) {
default : break;
case 'd':
case 'y':
case 'f':
case 'c':
case 'l':
case 'x':
return C_RegisterClass;
case 'R':
return C_Memory;
}
}
return TargetLowering::getConstraintType(Constraint);
}
/// Examine constraint type and operand type and determine a weight value.
/// This object must already have been set up with the operand type
/// and the current alternative constraint selected.
TargetLowering::ConstraintWeight
MipsTargetLowering::getSingleConstraintMatchWeight(
AsmOperandInfo &info, const char *constraint) const {
ConstraintWeight weight = CW_Invalid;
Value *CallOperandVal = info.CallOperandVal;
// If we don't have a value, we can't do a match,
// but allow it at the lowest weight.
if (!CallOperandVal)
return CW_Default;
Type *type = CallOperandVal->getType();
// Look at the constraint type.
switch (*constraint) {
default:
weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
break;
case 'd':
case 'y':
if (type->isIntegerTy())
weight = CW_Register;
break;
case 'f': // FPU or MSA register
if (Subtarget.hasMSA() && type->isVectorTy() &&
cast<VectorType>(type)->getBitWidth() == 128)
weight = CW_Register;
else if (type->isFloatTy())
weight = CW_Register;
break;
case 'c': // $25 for indirect jumps
case 'l': // lo register
case 'x': // hilo register pair
if (type->isIntegerTy())
weight = CW_SpecificReg;
break;
case 'I': // signed 16 bit immediate
case 'J': // integer zero
case 'K': // unsigned 16 bit immediate
case 'L': // signed 32 bit immediate where lower 16 bits are 0
case 'N': // immediate in the range of -65535 to -1 (inclusive)
case 'O': // signed 15 bit immediate (+- 16383)
case 'P': // immediate in the range of 65535 to 1 (inclusive)
if (isa<ConstantInt>(CallOperandVal))
weight = CW_Constant;
break;
case 'R':
weight = CW_Memory;
break;
}
return weight;
}
/// This is a helper function to parse a physical register string and split it
/// into non-numeric and numeric parts (Prefix and Reg). The first boolean flag
/// that is returned indicates whether parsing was successful. The second flag
/// is true if the numeric part exists.
static std::pair<bool, bool>
parsePhysicalReg(const StringRef &C, std::string &Prefix,
unsigned long long &Reg) {
if (C.front() != '{' || C.back() != '}')
return std::make_pair(false, false);
// Search for the first numeric character.
StringRef::const_iterator I, B = C.begin() + 1, E = C.end() - 1;
I = std::find_if(B, E, std::ptr_fun(isdigit));
Prefix.assign(B, I - B);
// The second flag is set to false if no numeric characters were found.
if (I == E)
return std::make_pair(true, false);
// Parse the numeric characters.
return std::make_pair(!getAsUnsignedInteger(StringRef(I, E - I), 10, Reg),
true);
}
std::pair<unsigned, const TargetRegisterClass *> MipsTargetLowering::
parseRegForInlineAsmConstraint(const StringRef &C, MVT VT) const {
const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
const TargetRegisterClass *RC;
std::string Prefix;
unsigned long long Reg;
std::pair<bool, bool> R = parsePhysicalReg(C, Prefix, Reg);
if (!R.first)
return std::make_pair(0U, nullptr);
if ((Prefix == "hi" || Prefix == "lo")) { // Parse hi/lo.
// No numeric characters follow "hi" or "lo".
if (R.second)
return std::make_pair(0U, nullptr);
RC = TRI->getRegClass(Prefix == "hi" ?
Mips::HI32RegClassID : Mips::LO32RegClassID);
return std::make_pair(*(RC->begin()), RC);
} else if (Prefix.compare(0, 4, "$msa") == 0) {
// Parse $msa(ir|csr|access|save|modify|request|map|unmap)
// No numeric characters follow the name.
if (R.second)
return std::make_pair(0U, nullptr);
Reg = StringSwitch<unsigned long long>(Prefix)
.Case("$msair", Mips::MSAIR)
.Case("$msacsr", Mips::MSACSR)
.Case("$msaaccess", Mips::MSAAccess)
.Case("$msasave", Mips::MSASave)
.Case("$msamodify", Mips::MSAModify)
.Case("$msarequest", Mips::MSARequest)
.Case("$msamap", Mips::MSAMap)
.Case("$msaunmap", Mips::MSAUnmap)
.Default(0);
if (!Reg)
return std::make_pair(0U, nullptr);
RC = TRI->getRegClass(Mips::MSACtrlRegClassID);
return std::make_pair(Reg, RC);
}
if (!R.second)
return std::make_pair(0U, nullptr);
if (Prefix == "$f") { // Parse $f0-$f31.
// If the size of FP registers is 64-bit or Reg is an even number, select
// the 64-bit register class. Otherwise, select the 32-bit register class.
if (VT == MVT::Other)
VT = (Subtarget.isFP64bit() || !(Reg % 2)) ? MVT::f64 : MVT::f32;
RC = getRegClassFor(VT);
if (RC == &Mips::AFGR64RegClass) {
assert(Reg % 2 == 0);
Reg >>= 1;
}
} else if (Prefix == "$fcc") // Parse $fcc0-$fcc7.
RC = TRI->getRegClass(Mips::FCCRegClassID);
else if (Prefix == "$w") { // Parse $w0-$w31.
RC = getRegClassFor((VT == MVT::Other) ? MVT::v16i8 : VT);
} else { // Parse $0-$31.
assert(Prefix == "$");
RC = getRegClassFor((VT == MVT::Other) ? MVT::i32 : VT);
}
assert(Reg < RC->getNumRegs());
return std::make_pair(*(RC->begin() + Reg), RC);
}
/// Given a register class constraint, like 'r', if this corresponds directly
/// to an LLVM register class, return a register of 0 and the register class
/// pointer.
std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
getRegForInlineAsmConstraint(const std::string &Constraint, MVT VT) const
{
if (Constraint.size() == 1) {
switch (Constraint[0]) {
case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
case 'y': // Same as 'r'. Exists for compatibility.
case 'r':
if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
if (Subtarget.inMips16Mode())
return std::make_pair(0U, &Mips::CPU16RegsRegClass);
return std::make_pair(0U, &Mips::GPR32RegClass);
}
if (VT == MVT::i64 && !Subtarget.isGP64bit())
return std::make_pair(0U, &Mips::GPR32RegClass);
if (VT == MVT::i64 && Subtarget.isGP64bit())
return std::make_pair(0U, &Mips::GPR64RegClass);
// This will generate an error message
return std::make_pair(0U, nullptr);
case 'f': // FPU or MSA register
if (VT == MVT::v16i8)
return std::make_pair(0U, &Mips::MSA128BRegClass);
else if (VT == MVT::v8i16 || VT == MVT::v8f16)
return std::make_pair(0U, &Mips::MSA128HRegClass);
else if (VT == MVT::v4i32 || VT == MVT::v4f32)
return std::make_pair(0U, &Mips::MSA128WRegClass);
else if (VT == MVT::v2i64 || VT == MVT::v2f64)
return std::make_pair(0U, &Mips::MSA128DRegClass);
else if (VT == MVT::f32)
return std::make_pair(0U, &Mips::FGR32RegClass);
else if ((VT == MVT::f64) && (!Subtarget.isSingleFloat())) {
if (Subtarget.isFP64bit())
return std::make_pair(0U, &Mips::FGR64RegClass);
return std::make_pair(0U, &Mips::AFGR64RegClass);
}
break;
case 'c': // register suitable for indirect jump
if (VT == MVT::i32)
return std::make_pair((unsigned)Mips::T9, &Mips::GPR32RegClass);
assert(VT == MVT::i64 && "Unexpected type.");
return std::make_pair((unsigned)Mips::T9_64, &Mips::GPR64RegClass);
case 'l': // register suitable for indirect jump
if (VT == MVT::i32)
return std::make_pair((unsigned)Mips::LO0, &Mips::LO32RegClass);
return std::make_pair((unsigned)Mips::LO0_64, &Mips::LO64RegClass);
case 'x': // register suitable for indirect jump
// Fixme: Not triggering the use of both hi and low
// This will generate an error message
return std::make_pair(0U, nullptr);
}
}
std::pair<unsigned, const TargetRegisterClass *> R;
R = parseRegForInlineAsmConstraint(Constraint, VT);
if (R.second)
return R;
return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
}
/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
/// vector. If it is invalid, don't add anything to Ops.
void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
std::string &Constraint,
std::vector<SDValue>&Ops,
SelectionDAG &DAG) const {
SDValue Result;
// Only support length 1 constraints for now.
if (Constraint.length() > 1) return;
char ConstraintLetter = Constraint[0];
switch (ConstraintLetter) {
default: break; // This will fall through to the generic implementation
case 'I': // Signed 16 bit constant
// If this fails, the parent routine will give an error
if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
EVT Type = Op.getValueType();
int64_t Val = C->getSExtValue();
if (isInt<16>(Val)) {
Result = DAG.getTargetConstant(Val, Type);
break;
}
}
return;
case 'J': // integer zero
if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
EVT Type = Op.getValueType();
int64_t Val = C->getZExtValue();
if (Val == 0) {
Result = DAG.getTargetConstant(0, Type);
break;
}
}
return;
case 'K': // unsigned 16 bit immediate
if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
EVT Type = Op.getValueType();
uint64_t Val = (uint64_t)C->getZExtValue();
if (isUInt<16>(Val)) {
Result = DAG.getTargetConstant(Val, Type);
break;
}
}
return;
case 'L': // signed 32 bit immediate where lower 16 bits are 0
if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
EVT Type = Op.getValueType();
int64_t Val = C->getSExtValue();
if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
Result = DAG.getTargetConstant(Val, Type);
break;
}
}
return;
case 'N': // immediate in the range of -65535 to -1 (inclusive)
if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
EVT Type = Op.getValueType();
int64_t Val = C->getSExtValue();
if ((Val >= -65535) && (Val <= -1)) {
Result = DAG.getTargetConstant(Val, Type);
break;
}
}
return;
case 'O': // signed 15 bit immediate
if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
EVT Type = Op.getValueType();
int64_t Val = C->getSExtValue();
if ((isInt<15>(Val))) {
Result = DAG.getTargetConstant(Val, Type);
break;
}
}
return;
case 'P': // immediate in the range of 1 to 65535 (inclusive)
if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
EVT Type = Op.getValueType();
int64_t Val = C->getSExtValue();
if ((Val <= 65535) && (Val >= 1)) {
Result = DAG.getTargetConstant(Val, Type);
break;
}
}
return;
}
if (Result.getNode()) {
Ops.push_back(Result);
return;
}
TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
}
bool MipsTargetLowering::isLegalAddressingMode(const AddrMode &AM,
Type *Ty) const {
// No global is ever allowed as a base.
if (AM.BaseGV)
return false;
switch (AM.Scale) {
case 0: // "r+i" or just "i", depending on HasBaseReg.
break;
case 1:
if (!AM.HasBaseReg) // allow "r+i".
break;
return false; // disallow "r+r" or "r+r+i".
default:
return false;
}
return true;
}
bool
MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
// The Mips target isn't yet aware of offsets.
return false;
}
EVT MipsTargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
unsigned SrcAlign,
bool IsMemset, bool ZeroMemset,
bool MemcpyStrSrc,
MachineFunction &MF) const {
if (Subtarget.hasMips64())
return MVT::i64;
return MVT::i32;
}
bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
if (VT != MVT::f32 && VT != MVT::f64)
return false;
if (Imm.isNegZero())
return false;
return Imm.isZero();
}
unsigned MipsTargetLowering::getJumpTableEncoding() const {
if (Subtarget.isABI_N64())
return MachineJumpTableInfo::EK_GPRel64BlockAddress;
return TargetLowering::getJumpTableEncoding();
}
/// This function returns true if CallSym is a long double emulation routine.
static bool isF128SoftLibCall(const char *CallSym) {
const char *const LibCalls[] =
{"__addtf3", "__divtf3", "__eqtf2", "__extenddftf2", "__extendsftf2",
"__fixtfdi", "__fixtfsi", "__fixtfti", "__fixunstfdi", "__fixunstfsi",
"__fixunstfti", "__floatditf", "__floatsitf", "__floattitf",
"__floatunditf", "__floatunsitf", "__floatuntitf", "__getf2", "__gttf2",
"__letf2", "__lttf2", "__multf3", "__netf2", "__powitf2", "__subtf3",
"__trunctfdf2", "__trunctfsf2", "__unordtf2",
"ceill", "copysignl", "cosl", "exp2l", "expl", "floorl", "fmal", "fmodl",
"log10l", "log2l", "logl", "nearbyintl", "powl", "rintl", "sinl", "sqrtl",
"truncl"};
const char *const *End = LibCalls + array_lengthof(LibCalls);
// Check that LibCalls is sorted alphabetically.
MipsTargetLowering::LTStr Comp;
#ifndef NDEBUG
for (const char *const *I = LibCalls; I < End - 1; ++I)
assert(Comp(*I, *(I + 1)));
#endif
return std::binary_search(LibCalls, End, CallSym, Comp);
}
/// This function returns true if Ty is fp128 or i128 which was originally a
/// fp128.
static bool originalTypeIsF128(const Type *Ty, const SDNode *CallNode) {
if (Ty->isFP128Ty())
return true;
const ExternalSymbolSDNode *ES =
dyn_cast_or_null<const ExternalSymbolSDNode>(CallNode);
// If the Ty is i128 and the function being called is a long double emulation
// routine, then the original type is f128.
return (ES && Ty->isIntegerTy(128) && isF128SoftLibCall(ES->getSymbol()));
}
MipsTargetLowering::MipsCC::SpecialCallingConvType
MipsTargetLowering::getSpecialCallingConv(SDValue Callee) const {
MipsCC::SpecialCallingConvType SpecialCallingConv =
MipsCC::NoSpecialCallingConv;
if (Subtarget.inMips16HardFloat()) {
if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
llvm::StringRef Sym = G->getGlobal()->getName();
Function *F = G->getGlobal()->getParent()->getFunction(Sym);
if (F && F->hasFnAttribute("__Mips16RetHelper")) {
SpecialCallingConv = MipsCC::Mips16RetHelperConv;
}
}
}
return SpecialCallingConv;
}
MipsTargetLowering::MipsCC::MipsCC(
CallingConv::ID CC, bool IsO32_, bool IsFP64_, CCState &Info,
MipsCC::SpecialCallingConvType SpecialCallingConv_)
: CCInfo(Info), CallConv(CC), IsO32(IsO32_), IsFP64(IsFP64_),
SpecialCallingConv(SpecialCallingConv_){
// Pre-allocate reserved argument area.
CCInfo.AllocateStack(reservedArgArea(), 1);
}
void MipsTargetLowering::MipsCC::
analyzeCallOperands(const SmallVectorImpl<ISD::OutputArg> &Args,
bool IsVarArg, bool IsSoftFloat, const SDNode *CallNode,
std::vector<ArgListEntry> &FuncArgs) {
assert((CallConv != CallingConv::Fast || !IsVarArg) &&
"CallingConv::Fast shouldn't be used for vararg functions.");
unsigned NumOpnds = Args.size();
llvm::CCAssignFn *FixedFn = fixedArgFn(), *VarFn = varArgFn();
for (unsigned I = 0; I != NumOpnds; ++I) {
MVT ArgVT = Args[I].VT;
ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
bool R;
if (ArgFlags.isByVal()) {
handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
continue;
}
if (IsVarArg && !Args[I].IsFixed)
R = VarFn(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
else {
MVT RegVT = getRegVT(ArgVT, FuncArgs[Args[I].OrigArgIndex].Ty, CallNode,
IsSoftFloat);
R = FixedFn(I, ArgVT, RegVT, CCValAssign::Full, ArgFlags, CCInfo);
}
if (R) {
#ifndef NDEBUG
dbgs() << "Call operand #" << I << " has unhandled type "
<< EVT(ArgVT).getEVTString();
#endif
llvm_unreachable(nullptr);
}
}
}
void MipsTargetLowering::MipsCC::
analyzeFormalArguments(const SmallVectorImpl<ISD::InputArg> &Args,
bool IsSoftFloat, Function::const_arg_iterator FuncArg) {
unsigned NumArgs = Args.size();
llvm::CCAssignFn *FixedFn = fixedArgFn();
unsigned CurArgIdx = 0;
for (unsigned I = 0; I != NumArgs; ++I) {
MVT ArgVT = Args[I].VT;
ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
std::advance(FuncArg, Args[I].OrigArgIndex - CurArgIdx);
CurArgIdx = Args[I].OrigArgIndex;
if (ArgFlags.isByVal()) {
handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
continue;
}
MVT RegVT = getRegVT(ArgVT, FuncArg->getType(), nullptr, IsSoftFloat);
if (!FixedFn(I, ArgVT, RegVT, CCValAssign::Full, ArgFlags, CCInfo))
continue;
#ifndef NDEBUG
dbgs() << "Formal Arg #" << I << " has unhandled type "
<< EVT(ArgVT).getEVTString();
#endif
llvm_unreachable(nullptr);
}
}
template<typename Ty>
void MipsTargetLowering::MipsCC::
analyzeReturn(const SmallVectorImpl<Ty> &RetVals, bool IsSoftFloat,
const SDNode *CallNode, const Type *RetTy) const {
CCAssignFn *Fn;
if (IsSoftFloat && originalTypeIsF128(RetTy, CallNode))
Fn = RetCC_F128Soft;
else
Fn = RetCC_Mips;
for (unsigned I = 0, E = RetVals.size(); I < E; ++I) {
MVT VT = RetVals[I].VT;
ISD::ArgFlagsTy Flags = RetVals[I].Flags;
MVT RegVT = this->getRegVT(VT, RetTy, CallNode, IsSoftFloat);
if (Fn(I, VT, RegVT, CCValAssign::Full, Flags, this->CCInfo)) {
#ifndef NDEBUG
dbgs() << "Call result #" << I << " has unhandled type "
<< EVT(VT).getEVTString() << '\n';
#endif
llvm_unreachable(nullptr);
}
}
}
void MipsTargetLowering::MipsCC::
analyzeCallResult(const SmallVectorImpl<ISD::InputArg> &Ins, bool IsSoftFloat,
const SDNode *CallNode, const Type *RetTy) const {
analyzeReturn(Ins, IsSoftFloat, CallNode, RetTy);
}
void MipsTargetLowering::MipsCC::
analyzeReturn(const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsSoftFloat,
const Type *RetTy) const {
analyzeReturn(Outs, IsSoftFloat, nullptr, RetTy);
}
void MipsTargetLowering::MipsCC::handleByValArg(unsigned ValNo, MVT ValVT,
MVT LocVT,
CCValAssign::LocInfo LocInfo,
ISD::ArgFlagsTy ArgFlags) {
assert(ArgFlags.getByValSize() && "Byval argument's size shouldn't be 0.");
struct ByValArgInfo ByVal;
unsigned RegSize = regSize();
unsigned ByValSize = RoundUpToAlignment(ArgFlags.getByValSize(), RegSize);
unsigned Align = std::min(std::max(ArgFlags.getByValAlign(), RegSize),
RegSize * 2);
if (useRegsForByval())
allocateRegs(ByVal, ByValSize, Align);
// Allocate space on caller's stack.
ByVal.Address = CCInfo.AllocateStack(ByValSize - RegSize * ByVal.NumRegs,
Align);
CCInfo.addLoc(CCValAssign::getMem(ValNo, ValVT, ByVal.Address, LocVT,
LocInfo));
ByValArgs.push_back(ByVal);
}
unsigned MipsTargetLowering::MipsCC::numIntArgRegs() const {
return IsO32 ? array_lengthof(O32IntRegs) : array_lengthof(Mips64IntRegs);
}
unsigned MipsTargetLowering::MipsCC::reservedArgArea() const {
return (IsO32 && (CallConv != CallingConv::Fast)) ? 16 : 0;
}
const MCPhysReg *MipsTargetLowering::MipsCC::intArgRegs() const {
return IsO32 ? O32IntRegs : Mips64IntRegs;
}
llvm::CCAssignFn *MipsTargetLowering::MipsCC::fixedArgFn() const {
if (CallConv == CallingConv::Fast)
return CC_Mips_FastCC;
if (SpecialCallingConv == Mips16RetHelperConv)
return CC_Mips16RetHelper;
return IsO32 ? (IsFP64 ? CC_MipsO32_FP64 : CC_MipsO32_FP32) : CC_MipsN;
}
llvm::CCAssignFn *MipsTargetLowering::MipsCC::varArgFn() const {
return IsO32 ? (IsFP64 ? CC_MipsO32_FP64 : CC_MipsO32_FP32) : CC_MipsN_VarArg;
}
const MCPhysReg *MipsTargetLowering::MipsCC::shadowRegs() const {
return IsO32 ? O32IntRegs : Mips64DPRegs;
}
void MipsTargetLowering::MipsCC::allocateRegs(ByValArgInfo &ByVal,
unsigned ByValSize,
unsigned Align) {
unsigned RegSize = regSize(), NumIntArgRegs = numIntArgRegs();
const MCPhysReg *IntArgRegs = intArgRegs(), *ShadowRegs = shadowRegs();
assert(!(ByValSize % RegSize) && !(Align % RegSize) &&
"Byval argument's size and alignment should be a multiple of"
"RegSize.");
ByVal.FirstIdx = CCInfo.getFirstUnallocated(IntArgRegs, NumIntArgRegs);
// If Align > RegSize, the first arg register must be even.
if ((Align > RegSize) && (ByVal.FirstIdx % 2)) {
CCInfo.AllocateReg(IntArgRegs[ByVal.FirstIdx], ShadowRegs[ByVal.FirstIdx]);
++ByVal.FirstIdx;
}
// Mark the registers allocated.
for (unsigned I = ByVal.FirstIdx; ByValSize && (I < NumIntArgRegs);
ByValSize -= RegSize, ++I, ++ByVal.NumRegs)
CCInfo.AllocateReg(IntArgRegs[I], ShadowRegs[I]);
}
MVT MipsTargetLowering::MipsCC::getRegVT(MVT VT, const Type *OrigTy,
const SDNode *CallNode,
bool IsSoftFloat) const {
if (IsSoftFloat || IsO32)
return VT;
// Check if the original type was fp128.
if (originalTypeIsF128(OrigTy, CallNode)) {
assert(VT == MVT::i64);
return MVT::f64;
}
return VT;
}
void MipsTargetLowering::
copyByValRegs(SDValue Chain, SDLoc DL, std::vector<SDValue> &OutChains,
SelectionDAG &DAG, const ISD::ArgFlagsTy &Flags,
SmallVectorImpl<SDValue> &InVals, const Argument *FuncArg,
const MipsCC &CC, const ByValArgInfo &ByVal) const {
MachineFunction &MF = DAG.getMachineFunction();
MachineFrameInfo *MFI = MF.getFrameInfo();
unsigned RegAreaSize = ByVal.NumRegs * CC.regSize();
unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize);
int FrameObjOffset;
if (RegAreaSize)
FrameObjOffset = (int)CC.reservedArgArea() -
(int)((CC.numIntArgRegs() - ByVal.FirstIdx) * CC.regSize());
else
FrameObjOffset = ByVal.Address;
// Create frame object.
EVT PtrTy = getPointerTy();
int FI = MFI->CreateFixedObject(FrameObjSize, FrameObjOffset, true);
SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
InVals.push_back(FIN);
if (!ByVal.NumRegs)
return;
// Copy arg registers.
MVT RegTy = MVT::getIntegerVT(CC.regSize() * 8);
const TargetRegisterClass *RC = getRegClassFor(RegTy);
for (unsigned I = 0; I < ByVal.NumRegs; ++I) {
unsigned ArgReg = CC.intArgRegs()[ByVal.FirstIdx + I];
unsigned VReg = addLiveIn(MF, ArgReg, RC);
unsigned Offset = I * CC.regSize();
SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN,
DAG.getConstant(Offset, PtrTy));
SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy),
StorePtr, MachinePointerInfo(FuncArg, Offset),
false, false, 0);
OutChains.push_back(Store);
}
}
// Copy byVal arg to registers and stack.
void MipsTargetLowering::
passByValArg(SDValue Chain, SDLoc DL,
std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
SmallVectorImpl<SDValue> &MemOpChains, SDValue StackPtr,
MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
const MipsCC &CC, const ByValArgInfo &ByVal,
const ISD::ArgFlagsTy &Flags, bool isLittle) const {
unsigned ByValSizeInBytes = Flags.getByValSize();
unsigned OffsetInBytes = 0; // From beginning of struct
unsigned RegSizeInBytes = CC.regSize();
unsigned Alignment = std::min(Flags.getByValAlign(), RegSizeInBytes);
EVT PtrTy = getPointerTy(), RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
if (ByVal.NumRegs) {
const MCPhysReg *ArgRegs = CC.intArgRegs();
bool LeftoverBytes = (ByVal.NumRegs * RegSizeInBytes > ByValSizeInBytes);
unsigned I = 0;
// Copy words to registers.
for (; I < ByVal.NumRegs - LeftoverBytes;
++I, OffsetInBytes += RegSizeInBytes) {
SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
DAG.getConstant(OffsetInBytes, PtrTy));
SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr,
MachinePointerInfo(), false, false, false,
Alignment);
MemOpChains.push_back(LoadVal.getValue(1));
unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
RegsToPass.push_back(std::make_pair(ArgReg, LoadVal));
}
// Return if the struct has been fully copied.
if (ByValSizeInBytes == OffsetInBytes)
return;
// Copy the remainder of the byval argument with sub-word loads and shifts.
if (LeftoverBytes) {
assert((ByValSizeInBytes > OffsetInBytes) &&
(ByValSizeInBytes < OffsetInBytes + RegSizeInBytes) &&
"Size of the remainder should be smaller than RegSizeInBytes.");
SDValue Val;
for (unsigned LoadSizeInBytes = RegSizeInBytes / 2, TotalBytesLoaded = 0;
OffsetInBytes < ByValSizeInBytes; LoadSizeInBytes /= 2) {
unsigned RemainingSizeInBytes = ByValSizeInBytes - OffsetInBytes;
if (RemainingSizeInBytes < LoadSizeInBytes)
continue;
// Load subword.
SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
DAG.getConstant(OffsetInBytes, PtrTy));
SDValue LoadVal = DAG.getExtLoad(
ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr, MachinePointerInfo(),
MVT::getIntegerVT(LoadSizeInBytes * 8), false, false, Alignment);
MemOpChains.push_back(LoadVal.getValue(1));
// Shift the loaded value.
unsigned Shamt;
if (isLittle)
Shamt = TotalBytesLoaded * 8;
else
Shamt = (RegSizeInBytes - (TotalBytesLoaded + LoadSizeInBytes)) * 8;
SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal,
DAG.getConstant(Shamt, MVT::i32));
if (Val.getNode())
Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift);
else
Val = Shift;
OffsetInBytes += LoadSizeInBytes;
TotalBytesLoaded += LoadSizeInBytes;
Alignment = std::min(Alignment, LoadSizeInBytes);
}
unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
RegsToPass.push_back(std::make_pair(ArgReg, Val));
return;
}
}
// Copy remainder of byval arg to it with memcpy.
unsigned MemCpySize = ByValSizeInBytes - OffsetInBytes;
SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
DAG.getConstant(OffsetInBytes, PtrTy));
SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr,
DAG.getIntPtrConstant(ByVal.Address));
Chain = DAG.getMemcpy(Chain, DL, Dst, Src, DAG.getConstant(MemCpySize, PtrTy),
Alignment, /*isVolatile=*/false, /*AlwaysInline=*/false,
MachinePointerInfo(), MachinePointerInfo());
MemOpChains.push_back(Chain);
}
void MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains,
const MipsCC &CC, SDValue Chain,
SDLoc DL, SelectionDAG &DAG) const {
unsigned NumRegs = CC.numIntArgRegs();
const MCPhysReg *ArgRegs = CC.intArgRegs();
const CCState &CCInfo = CC.getCCInfo();
unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs, NumRegs);
unsigned RegSize = CC.regSize();
MVT RegTy = MVT::getIntegerVT(RegSize * 8);
const TargetRegisterClass *RC = getRegClassFor(RegTy);
MachineFunction &MF = DAG.getMachineFunction();
MachineFrameInfo *MFI = MF.getFrameInfo();
MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
// Offset of the first variable argument from stack pointer.
int VaArgOffset;
if (NumRegs == Idx)
VaArgOffset = RoundUpToAlignment(CCInfo.getNextStackOffset(), RegSize);
else
VaArgOffset = (int)CC.reservedArgArea() - (int)(RegSize * (NumRegs - Idx));
// Record the frame index of the first variable argument
// which is a value necessary to VASTART.
int FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
MipsFI->setVarArgsFrameIndex(FI);
// Copy the integer registers that have not been used for argument passing
// to the argument register save area. For O32, the save area is allocated
// in the caller's stack frame, while for N32/64, it is allocated in the
// callee's stack frame.
for (unsigned I = Idx; I < NumRegs; ++I, VaArgOffset += RegSize) {
unsigned Reg = addLiveIn(MF, ArgRegs[I], RC);
SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy);
FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy());
SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
MachinePointerInfo(), false, false, 0);
cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue(
(Value *)nullptr);
OutChains.push_back(Store);
}
}
| [
"[email protected]"
] | |
8403cd42ec09242712619aca4c1537dd1b8656b9 | e34b485dfa63c27351a87d979ff71382201f408f | /codeforces/677a.cpp | 0df3c27038ed9c5bd54fc9684431f27ee8a1b6a5 | [] | no_license | gabrielrussoc/competitive-programming | 223146586e181fdc93822d8462d56fd899d25567 | cd51b9af8daf5bab199b77d9642f7cd01bcaa8e3 | refs/heads/master | 2022-11-30T11:55:12.801388 | 2022-11-15T18:12:55 | 2022-11-15T18:12:55 | 44,883,370 | 10 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 537 | cpp | #include <bits/stdc++.h>
#define mp make_pair
#define pb push_back
#define ff first
#define ss second
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
const double eps = 1e-9;
const int inf = INT_MAX;
//////////////0123456789
const int N = 10004;
const int modn = 1000000007;
int main() {
int n, h, a;
int ans = 0;
scanf("%d %d",&n, &h);
for(int i = 0; i < n; i++) {
scanf("%d",&a);
if(a > h) ans += 2;
else ans++;
}
printf("%d\n",ans);
}
| [
"[email protected]"
] | |
1fa385b547d88693d5f9f7952b5f3e62855c7897 | 9e6aee01fc26354a4383d3523f7431333825a33f | /week_03_templates/variable_pointer_intro.cpp | 01ac8f38dc12968ae3683d638fc021661e1d2777 | [] | no_license | SuperArtisMickens/CUNY2xAdvising | a3e430e6df1184a1fbb83361c17f64ff23ceff35 | 145481cbdee4281303fba9101532ad2fb9477795 | refs/heads/main | 2023-03-02T03:36:06.128309 | 2021-02-02T23:05:15 | 2021-02-02T23:05:15 | 325,645,075 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 352 | cpp | #include <iostream>
using namespace std;
double sum(double a[], int size)
{
double total = 0;
for (int i = 0; i < size; i++)
{
total = total + a[i];
}
return total;
}
//const double pi = 3.1415;
//double initialPrice = 10.95;
int main ()
{
//cout << pi << endl;
cout<<"Thank you GOD !!\n";
return 0;
} | [
"[email protected]"
] | |
bbd9d4609dc03334abefc34ce0fc8d6f0b3858f5 | 976004c9f4426106d7ca59db25755d4d574b8025 | /algorithms/hilbert_maps/orgn/feats/hm_orgn_feat_triangle.h | ef3024ff394cf57b6038520942ab17ae5e608fef | [] | no_license | peterzxli/cvpp | 18a90c23baaaa07a32b2aafdb25d6ae78a1768c0 | 3b73cfce99dc4b5908cd6cb7898ce5ef1e336dce | refs/heads/master | 2022-12-05T07:23:20.488638 | 2020-08-11T20:08:10 | 2020-08-11T20:08:10 | 286,062,971 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 763 | h | #ifndef HM_ORGN_FEATURE_TRIANGLE_H
#define HM_ORGN_FEATURE_TRIANGLE_H
#include "./hm_orgn_feat_base.h"
namespace cvpp
{
class HMfeatTriangle : public HMfeatBase
{
protected:
public:
double gamma;
public:
HMfeatTriangle( const Matd& lim ,
const double& gam = 1.0 ,
const double& rad = 2.0 ,
const double& res = 0.5 )
{
limits = lim , gamma = gam , radius = rad , resolution = res ;
dims = ( ( limits.r(1) - limits.r(0) ) / resolution ).floor();
ndims = ( dims + 1.0 ).prod();
}
double kernel( const Matd& mat1 , const Matd& mat2 ) const
{
return std::max( 0.0 , gamma - ( mat1.eig() - mat2.eig() ).norm() ) / gamma ;
}
};
}
#endif
| [
"[email protected]"
] | |
18cdcd158750e4a7c20739a503c9ad03d8f55e9c | e94333047bd3c6bf673ff775f80f65082042afb1 | /remoteCam_simple/server.cpp | d4e6fe8b2f1ba5c0e1540d90ec2a4c41888e4cef | [] | no_license | JThanat/realtime-obstacle-avoidance | acee732070a474f490b6e44f40315b29a437bc00 | 35c63a4bfe1600626892cf14bb98f07e19fa38b3 | refs/heads/master | 2021-09-12T12:49:54.595182 | 2018-04-16T21:00:18 | 2018-04-16T21:00:18 | 107,529,340 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 19,455 | cpp | #include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "camera/camera.h"
#include "socklib/socklib.h"
#include "socketHelper.h"
extern "C" {
#include "liblz4/lz4.h"
}
#include <thread>
#include <mutex>
#include <stdint.h>
#include "remoteCam.h"
#include "shader.h"
// GLEW
#define GLEW_STATIC
#include <GL/glew.h>
// GLFW
#include <GLFW/glfw3.h>
#ifndef WIN32
#define KNRM "\x1B[0m"
#define KRED "\x1B[31m"
#define KGRN "\x1B[32m"
#define KYEL "\x1B[33m"
#define KBLU "\x1B[34m"
#define KMAG "\x1B[35m"
#define KCYN "\x1B[36m"
#define KWHT "\x1B[37m"
#else
#define KNRM ""
#define KRED ""
#define KGRN ""
#define KYEL ""
#define KBLU ""
#define KMAG ""
#define KCYN ""
#define KWHT ""
#endif
//evil globals!
int32_t newSetting=0;
int32_t settingNum = SETTING_NONE;
int32_t started =0;
int32_t previewCam=-1;
typedef struct s_recvCallArgs{
int32_t mode;
int32_t number;
int32_t resolution;
int32_t exposure;
int32_t gain;
int32_t grr;
int32_t* camList;
std::mutex* camListLock;
int32_t multiexposure;
int32_t triggerDelay;
int32_t highPrecisionMode;
} recvCallArgs;
typedef struct s_startThreadParams{
int mode;
} startThreadParams;
void errorAndExit(const char* errmsg){
fprintf(stderr, "%s\n", errmsg);
fflush(stderr);
exit(0);
}
/*
* //not used
int64_t calculateSharpness(uint16_t* imgBuff, int width, int height){
int i,j;
int64_t ret =0;
//sampling border and bound checking
int leftborder = width*4/10;
leftborder = leftborder<1?1:leftborder;
int rightborder = width*6/10;
rightborder = rightborder>width-1?width-1:rightborder;
int topborder = height*4/10;
topborder = topborder<1?1:topborder;
int bottomborder = height*6/10;;
bottomborder = bottomborder>height-1?height-1:bottomborder;
for(i=1;i<height;i++)
for(j=1;j<width;j++){
int self = imgBuff[j+i*width];
int left = imgBuff[j-1+i*width];
int up = imgBuff[j+(i-1)*width];
int xdiff = self-left;
int ydiff = self-up;
ret += xdiff*xdiff + ydiff*ydiff;
}
ret = ret/(rightborder-leftborder)/(bottomborder-topborder);
return ret;
}
*/
void loadImage(GLuint* textureRef, void* image, int width, int height){
glGenTextures(1, textureRef);
glBindTexture(GL_TEXTURE_2D, textureRef[0]); // All upcoming GL_TEXTURE_2D operations now have effect on our texture object
// Set our texture parameters
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); // Set texture wrapping to GL_REPEAT
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
// Set texture filtering
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
// Load, create texture and generate mipmaps
glTexImage2D(GL_TEXTURE_2D, 0, GL_R16, width, height, 0, GL_RED, GL_UNSIGNED_SHORT, (uint16_t*)image);
glBindTexture(GL_TEXTURE_2D, 0); // Unbind texture when done, so we won't accidentily mess up our texture.
glFlush();
return;
}
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode)
{
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
glfwSetWindowShouldClose(window, GL_TRUE);
//preview settings
if(newSetting==1) return;//send old setting first, ignore new setting
//to do, add camera exit setting
if (key == GLFW_KEY_INSERT && action == GLFW_PRESS){
settingNum = EXPOSURE_INC; newSetting = 1;
}
if (key == GLFW_KEY_DELETE && action == GLFW_PRESS){
settingNum = EXPOSURE_DEC; newSetting = 1;
}
if (key == GLFW_KEY_HOME && action == GLFW_PRESS){
settingNum = GAIN_INC; newSetting = 1;
}
if (key == GLFW_KEY_END && action == GLFW_PRESS){
settingNum = GAIN_DEC; newSetting = 1;
}
if (key == GLFW_KEY_MINUS && action == GLFW_PRESS){
settingNum = ZOOM_OUT; newSetting = 1;
}
if (key == GLFW_KEY_EQUAL && action == GLFW_PRESS){
settingNum = ZOOM_IN; newSetting = 1;
}
if (key == GLFW_KEY_0 && action == GLFW_PRESS){
settingNum = ZOOM_DEF; newSetting = 1;
}
}
void start_function(startThreadParams* p1){
if(p1->mode == 0){
fprintf(stderr, "enter preview camera id:");
fflush(stderr);
fscanf(stdin, "%d", &previewCam);
}
fprintf(stderr, "press enter to start\n"); fflush(stderr);
char dummyBuff[10];
fgets(dummyBuff, 10, stdin); //temporary fix for fgets, fscanf thingies...
fgets(dummyBuff, 10, stdin);
fprintf(stderr, "starting!!!\n"); fflush(stderr);
started=1;
return;
}
int32_t connectedCamList[MAX_CAM] = {0};
void DisplayCameraList() {
int count = 0;
for(int i=0;i< MAX_CAM ;i++) {
if (connectedCamList[i] == 0)
fprintf(stderr, KRED "%3d" KNRM, i);
else {
count++;
fprintf(stderr, KGRN "%3d" KNRM, i);
}
}
printf("\nTotal Camera Connected %d\n", count);
}
void DisplayCameraList(int32_t* readyCam) {
int count = 0;
int finCount = 0;
for(int i=0;i< MAX_CAM ;i++) {
switch(readyCam[i]){
//case 0:fprintf(stderr, KRED"%3d"KNRM, i); break;
case 1:fprintf(stderr, KRED "%3d" KNRM, i); break;
case 2:count++; fprintf(stderr, KGRN "%3d" KNRM, i); break;
case 3:finCount++; fprintf(stderr, KBLU "%3d" KNRM, i); break;
}
}
printf("\nTotal Camera ready %d\n", count);
}
void recvCall(int comm_socket, recvCallArgs* args1){
int32_t mode = args1->mode;
int32_t number = args1->number;
int32_t resolution = args1->resolution;
int32_t exposure = args1->exposure;
int32_t gain = args1->gain;
int32_t grr = args1->grr;
int32_t* camList = args1->camList;
std::mutex* camListLock = args1->camListLock;
int32_t multiexposure = args1->multiexposure;
int32_t triggerDelay = args1->triggerDelay;
int32_t highPrecisionMode = args1->highPrecisionMode;
//if started reject camera
// fprintf(stderr, "Receiving something\n");
if(started){
//wait a bit to prevent retry flood
#ifdef WIN32
Sleep(1000);
#else
usleep(1000000);
#endif
sockclose(comm_socket);
return;
}
//recieve id
int32_t id = 0;
int32_t sendSize = sizeof(id);
if(HEADER_ID!=recvHeader(comm_socket)){
fprintf(stderr, "Does not recieve camera ID, exiting\n"); fflush(stderr);
exit(0);
}
recvBytes(comm_socket, (char*)&id, sendSize);
//wait until can start and write camList
fprintf(stderr, KGRN "Cam ID:%d connected.\n" KNRM, id);
connectedCamList[id] = 1;
DisplayCameraList();
while(!started){
#ifdef WIN32
Sleep(250);
#else
usleep(250000);
#endif
}
camListLock->lock();
//critical section
/*
//poor implementation T_T
int u;
for(u=0;u<MAX_CAM;u++){
if(camList[u]==id){
fprintf(stderr, "duplicate camera ID, camera rejected\n"); fflush(stderr);
return;
}
if(camList[u]==-1){
camList[u] = id;
break;
}
}
if(u==MAX_CAM){
fprintf(stderr, "Too many cameras connecting\n"); fflush(stderr);
}
*/
if(camList[id]==1){
fprintf(stderr, "duplicate camera ID, camera rejected\n"); fflush(stderr);
return;
}
//fprintf(stderr, KGRN"Cam ID:%d connected.\n"KNRM, id);
camList[id] = 1;
//DisplayCameraList(camList);
//////////////////
camListLock->unlock();
if(mode==0){
if(id!=previewCam)
return;
}
char fileName[20];
sprintf(fileName, "%d.raw", id);
FILE* f1;
if(mode){
//force binary mode on windows
f1 = (FILE*)fopen(fileName, "wb");
}
//////////////////////////////////
int width;
int height;
switch(resolution){
case 0: width = 4896; height = 3684; break;
case 1: width = 2432; height = 1842; break;
case 2: width = 1216; height = 920; break;
default : width = 4896 ; height = 3684;
}
//send capture info
captureInfo cInfo;
cInfo.mode = mode;
cInfo.number = number;
cInfo.resolution = resolution;
cInfo.exposure = exposure;
cInfo.gain = gain;
cInfo.grr = grr;
cInfo.multiexposure = multiexposure;
cInfo.triggerDelay = triggerDelay;
cInfo.highPrecisionMode = highPrecisionMode;
sendSize = (int) sizeof(captureInfo);
//send capture info header
sendHeader(comm_socket, HEADER_CAPINFO);
// send capture info
sendBytes(comm_socket, (char*)&cInfo, sendSize);
if(recvHeader(comm_socket)!=HEADER_CAMERA_READY){
fprintf(stderr, "wrong header recieved, exiting\n");
fflush(stderr);
exit(0);
}else{
fprintf(stderr, "camera:%d ready\n", id); fflush(stderr);
camListLock->lock();
camList[id]=2;
DisplayCameraList(camList);
camListLock->unlock();
}
//mainloop
switch(mode){
case 0:{
//openGL setup
//to do, change hardcoded window size
int window_width = 1440;
int window_height = 1080;
// Init GLFW
glfwInit();
// Set all the required options for GLFW
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
// Create a GLFWwindow object that we can use for GLFW's functions
GLFWwindow* window = glfwCreateWindow(window_width, window_height, "Debayer", nullptr, nullptr);
glfwMakeContextCurrent(window);
// Set the required callback functions
glfwSetKeyCallback(window, key_callback);
// Set this to true so GLEW knows to use a modern approach to retrieving function pointers and extensions
glewExperimental = GL_TRUE;
// Initialize GLEW to setup the OpenGL Function pointers
glewInit();
// Define the viewport dimensions
glViewport(0, 0, window_width, window_height);
// Build and compile our shader program
Shader ourShader("shader.vert", "shader.frag");
// Set up vertex data (and buffer(s)) and attribute pointers
GLfloat vertices[] = {
// Positions // Colors // Texture Coords
1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, // Top Right
1.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, // Bottom Right
-1.0f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, // Bottom Left
-1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f // Top Left
};
GLuint indices[] = { // Note that we start from 0!
0, 1, 3, // First Triangle
1, 2, 3 // Second Triangle
};
GLuint VBO, VAO, EBO;
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
glGenBuffers(1, &EBO);
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
// Position attribute
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)0);
glEnableVertexAttribArray(0);
// Color attribute
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
glEnableVertexAttribArray(1);
// TexCoord attribute
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(6 * sizeof(GLfloat)));
glEnableVertexAttribArray(2);
glBindVertexArray(0); // Unbind VAO
// Load and create a texture
GLuint texture1;
//print message for preview mode
fprintf(stderr, "Preview mode\nPress INSERT, DELETE to increase or decrease exposure\nPress HOME, END to increase or decrease gain\nPress Esc to exit\n"); fflush(stderr);
//init buffers for image
sendSize = (int) width*height*sizeof(uint16_t);
uint16_t* imgBuff = (uint16_t*)malloc(sendSize);
memset(imgBuff, 0x00, sendSize);
float scale = 1.0f;
while(!glfwWindowShouldClose(window)){
// Check if any events have been activiated (key pressed, mouse moved etc.) and call corresponding response functions
glfwPollEvents();
int32_t header;
//send setting change
if(newSetting){
if(settingNum<6 || settingNum>8){
sendHeader(comm_socket, HEADER_PREVIEW_SETTING);
sendBytes(comm_socket, (char*)&settingNum, sizeof(settingNum));
newSetting = 0;
settingNum = SETTING_NONE;
}else{
switch(settingNum){
case(ZOOM_IN): scale-=0.1; break;
case(ZOOM_OUT): scale+=0.1; break;
case(ZOOM_DEF): scale=1; break;
}
newSetting=0;
}
}
//read for setting value return
header = recvHeader(comm_socket);
switch(header){
case HEADER_SETTING_RETURN:
//recvHeader(comm_socket);
//report settings
char* setting_str;
int32_t settingType;
int32_t settingValue;
recvBytes(comm_socket, (char*)&settingType, sizeof(settingType));
recvBytes(comm_socket, (char*)&settingValue, sizeof(settingValue));
switch(settingType){
char* setting_str;
case EXPOSURE_SETTING: fprintf(stderr, "exposure:"); break;
case GAIN_SETTING: fprintf(stderr, "gain:"); break;
default : fprintf(stderr, "invalid setting type reported, exiting\n"); fflush(stderr); exit(0);
}
fprintf(stderr, "%d\n", settingValue); fflush(stderr);
continue;
case HEADER_CAPSTREAM:
break;
default:
fprintf(stderr, "header:%x\n", header);
fprintf(stderr, "invalid header, exiting\n"); fflush(stderr);
exit(0);
}
//recieve the image
recvBytes(comm_socket, (char*)imgBuff, sendSize);
//draw to screen
loadImage(&texture1, imgBuff, width, height);
// Render
// Clear the colorbuffer
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
// Activate shader
ourShader.Use();
glUniform1i(glGetUniformLocation(ourShader.Program, "texImageWidth"), width);
glUniform1i(glGetUniformLocation(ourShader.Program, "texImageHeight"), height);
glUniform1f(glGetUniformLocation(ourShader.Program, "scale"), scale);
// Bind Textures using texture units
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture1);
glUniform1i(glGetUniformLocation(ourShader.Program, "ourTexture1"), 0);
// Draw container
glBindVertexArray(VAO);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
glBindVertexArray(0);
glfwSwapInterval(1);
// Swap the screen buffers
glfwSwapBuffers(window);
glDeleteTextures(1, &texture1);
//////////////////////////
//calculate sharpness
//int64_t s = calculateSharpness(imgBuff, width, height);
//fprintf(stderr, "sharpness:%ld\n", s); fflush(stderr);
}
// properly terminate openGL
// Properly de-allocate all resources once they've outlived their purpose
glDeleteVertexArrays(1, &VAO);
glDeleteBuffers(1, &VBO);
glDeleteBuffers(1, &EBO);
// Terminate GLFW, clearing any resources allocated by GLFW.
glfwTerminate();
//////////////////
free(imgBuff);
} break;
}
camListLock->lock();
camList[id]=3;
DisplayCameraList(camList);
camListLock->unlock();
fprintf(stderr, "id:%d done\n", id); fflush(stderr);
if(mode)fclose(f1);
sockclose(comm_socket);
}
int main(int argc, const char ** argv){
int32_t capmode=1;
int32_t resolution=0;
int32_t number=1;
int32_t exposure = 10;
int32_t gain = 1;
int32_t grr = 0;
int32_t multiexposure =1;
int32_t triggerDelay=0;
int32_t highPrecisionMode=0;
int useconfig=0;
char *configFile = "serverConfig.txt";
if (argc > 0) {
useconfig = 1;
configFile = argv[1];
FILE* serverCfg = fopen(configFile, "rb");
if (serverCfg == NULL) {
fprintf(stderr, "File %s does not exist\n", configFile);
useconfig = 0;
} else
fclose(serverCfg);
} else {
fprintf(stderr, "use ConfigFile? 0 or 1:");
fscanf(stdin, "%d", &useconfig);
}
if(!useconfig){
fprintf(stderr, "enter mode: 0=preview 1=raw 2=compressed:");
fscanf(stdin, "%d", &capmode);
fprintf(stderr, "enter resolution: 0=full 1= 2:1 binning 2= 4:1 binning :");
fscanf(stdin, "%d", &resolution);
if(capmode!=0){
fprintf(stderr, "enter number of frames:");
fscanf(stdin, "%d", &number);
}else{
number=1;
}
fprintf(stderr, "grr(0 or 1):");
fscanf(stdin, "%d", &grr);
fprintf(stderr, "enter exposure(1-1000):");
fscanf(stdin, "%d", &exposure);
fprintf(stderr, "enter gain(0-4):");
fscanf(stdin, "%d", &gain);
fprintf(stderr, "enter number of exposures per image(1-63):");
fscanf(stdin, "%d", &multiexposure);
if(capmode!=0){
fprintf(stderr, "High precision mode? (0=No 1=Yes 2=Yes with x^2 sum):");
fscanf(stdin, "%d", &highPrecisionMode);
}
/*
if(grr){
fprintf(stderr, "triggerDelay(0-255):");
fscanf(stdin, "%d", &triggerDelay);
}
*/
}else{
FILE* serverCfg = fopen(configFile, "rb");
if(serverCfg == NULL){
fprintf(stderr, "cannot open serverConfig.txt, exiting\n"); fflush(stderr);
exit(0);
}
char cfgArgs[20];
while(fscanf(serverCfg, "%s", cfgArgs)!=EOF){
if(strncmp("mode", cfgArgs, 4)==0){
int t1;
fscanf(serverCfg, "%d", &t1);
if(t1<0||t1>3){
errorAndExit("wrong mode in config file");
}
capmode=t1;
continue;
}
if(strncmp("resolution", cfgArgs, 10)==0){
int t1;
fscanf(serverCfg, "%d", &t1);
if(t1<0||t1>2){
errorAndExit("wrong resolution in config file");
}
resolution=t1;
continue;
}
if(strncmp("number", cfgArgs, 6)==0){
int t1;
fscanf(serverCfg, "%d", &t1);
if(t1<0){
errorAndExit("wrong number in config file");
}
number=t1;
continue;
}
if(strncmp("exposure", cfgArgs, 8)==0){
int t1;
fscanf(serverCfg, "%d", &t1);
if(t1<1||t1>1000){
errorAndExit("wrong exposure in config file");
}
exposure=t1;
continue;
}
if(strncmp("gain", cfgArgs, 4)==0){
int t1;
fscanf(serverCfg, "%d", &t1);
if(t1<0||t1>4){
errorAndExit("wrong gain in config file");
}
gain=t1;
continue;
}
if(strncmp("grr", cfgArgs, 3)==0){
int t1;
fscanf(serverCfg, "%d", &t1);
if(t1<0||t1>1){
errorAndExit("wrong grr in config file");
}
grr=t1;
continue;
}
if(strncmp("multi", cfgArgs, 4)==0){
int t1;
fscanf(serverCfg, "%d", &t1);
if(t1<0){
errorAndExit("wrong multi in config file");
}
multiexposure=t1;
continue;
}
if(strncmp("32bit", cfgArgs, 5)==0){
int t1;
fscanf(serverCfg, "%d", &t1);
if(t1<0){
errorAndExit("wrong 32-bit setting in config file");
}
highPrecisionMode=t1;
continue;
}
}
fclose(serverCfg);
}
//print settings
fprintf(stderr, "mode:%d\n", capmode);
fprintf(stderr, "resolution:%d\n", resolution);
fprintf(stderr, "number:%d\n", number);
fprintf(stderr, "exposure:%d\n", exposure);
fprintf(stderr, "gain:%d\n", gain);
fprintf(stderr, "grr:%d\n", grr);
fprintf(stderr, "multi:%d\n", multiexposure);
fprintf(stderr, "32-bit:%d\n", highPrecisionMode);
fflush(stderr);
int32_t camList[MAX_CAM];
int g;
for(g=0; g<MAX_CAM; g++)
camList[g] = -1;
std::mutex camListLock;
recvCallArgs args1;
args1.mode = capmode;
args1.number = number;
args1.resolution = resolution;
args1.exposure = exposure;
args1.gain = gain;
args1.grr = grr;
args1.camList = camList;
args1.camListLock = &camListLock;
args1.multiexposure = multiexposure;
args1.triggerDelay = triggerDelay;
args1.highPrecisionMode = highPrecisionMode;
//create thread to recieve start command
startThreadParams startParams;
startParams.mode = capmode;
std::thread start_thread(start_function, &startParams);
int comm_port = COMM_PORT;
int comm_socket = sockopen(NULL, comm_port);
PF_SOCKETHANDLER h1 = (PF_SOCKETHANDLER)(comm_socket, (void*)recvCall);
socklisten(comm_socket, &args1, h1);
return 0;
}
| [
"[email protected]"
] | |
43e10df811479334cc5cb17d941a8a619f7a8064 | f502eb33118039d349a2c3fa8581e511c429cfe7 | /SpoutSDK/Example/ofSpoutExample/src/ofApp.cpp | dfde2550e70ce666947a3ec1d31177be9704aeab | [
"BSD-3-Clause",
"BSD-2-Clause"
] | permissive | geometrybase/Spout2 | 781774ef3c209703ad74a3975669ed553ca86851 | 851deec62ef8f1e7b90c0df1448387e0d2841de1 | refs/heads/master | 2022-04-11T08:23:45.242754 | 2019-11-27T00:35:08 | 2019-11-27T00:35:08 | 257,859,364 | 2 | 0 | null | 2020-04-22T09:52:02 | 2020-04-22T09:52:01 | null | UTF-8 | C++ | false | false | 5,408 | cpp | /*
Spout OpenFrameworks Sender example - ofApp.cpp
Visual Studio using the Spout SDK
Search for SPOUT for additions to a typical Openframeworks application
Copyright (C) 2016 Lynn Jarvis.
=========================================================================
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 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
=========================================================================
*/
#include "ofApp.h"
//--------------------------------------------------------------
void ofApp::setup(){
ofBackground(10, 100, 140);
ofEnableNormalizedTexCoords(); // explicitly normalize tex coords for ofBox
// ====== SPOUT =====
spoutsender = new SpoutSender; // Create a Spout sender object
bInitialized = false; // Spout sender initialization
strcpy(sendername, "OF Spout Sender"); // Set the sender name
ofSetWindowTitle(sendername); // show it on the title bar
// Create an OpenGL texture for data transfers
sendertexture = 0; // make sure the ID is zero for the first time
InitGLtexture(sendertexture, ofGetWidth(), ofGetHeight());
// Set the window icon from resources
SetClassLong(GetActiveWindow(), GCL_HICON, (LONG)LoadIconA(GetModuleHandle(NULL), MAKEINTRESOURCEA(IDI_ICON1)));
// ===================
// 3D drawing setup for a sender
glEnable(GL_DEPTH_TEST); // enable depth comparisons and update the depth buffer
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); // Really Nice Perspective Calculations
ofDisableArbTex(); // needed for textures to work
myTextureImage.loadImage("SpoutBox1.png"); // Load a texture image for the demo
rotX = 0;
rotY = 0;
} // end setup
//--------------------------------------------------------------
void ofApp::update() {
}
//--------------------------------------------------------------
void ofApp::draw() {
char str[256];
ofSetColor(255);
// ====== SPOUT =====
// A render window must be available for Spout initialization and might not be
// available in "update" so do it now when there is definitely a render window.
if(!bInitialized) {
// Create the sender
bInitialized = spoutsender->CreateSender(sendername, ofGetWidth(), ofGetHeight());
}
// ===================
// - - - - - - - - - - - - - - - - - - - - - - - - -
// Draw 3D graphics demo - this could be anything
ofPushMatrix();
ofTranslate((float)ofGetWidth()/2.0, (float)ofGetHeight()/2.0, 0);
ofRotateY(rotX); // rotate - must be float
ofRotateX(rotY);
myTextureImage.getTextureReference().bind(); // bind our texture
ofDrawBox(0.4*(float)ofGetHeight()); // Draw the graphic
myTextureImage.getTextureReference().unbind(); // bind our texture
ofPopMatrix();
rotX+=0.5;
rotY+=0.5;
// ====== SPOUT =====
if(bInitialized) {
if(ofGetWidth() > 0 && ofGetHeight() > 0) { // protect against user minimize
// Grab the screen into the local spout texture
glBindTexture(GL_TEXTURE_2D, sendertexture);
glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, ofGetWidth(), ofGetHeight());
glBindTexture(GL_TEXTURE_2D, 0);
// Send the texture out for all receivers to use
spoutsender->SendTexture(sendertexture, GL_TEXTURE_2D, ofGetWidth(), ofGetHeight());
// Show what it is sending
ofSetColor(255);
sprintf(str, "Sending as : [%s]", sendername);
ofDrawBitmapString(str, 20, 20);
// Show fps
sprintf(str, "fps: %3.3d", (int)ofGetFrameRate());
ofDrawBitmapString(str, ofGetWidth()-120, 20);
}
}
// ===================
}
//--------------------------------------------------------------
void ofApp::exit() {
// ====== SPOUT =====
spoutsender->ReleaseSender(); // Release the sender
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h)
{
// ====== SPOUT =====
// Update the sender texture to receive the new dimensions
// Change of width and height is handled within the SendTexture function
if(w > 0 && h > 0) // protect against user minimize
InitGLtexture(sendertexture, w, h);
}
// ====== SPOUT =====
bool ofApp::InitGLtexture(GLuint &texID, unsigned int width, unsigned int height)
{
if(texID != 0) glDeleteTextures(1, &texID);
glGenTextures(1, &texID);
glBindTexture(GL_TEXTURE_2D, texID);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glBindTexture(GL_TEXTURE_2D, 0);
return true;
}
| [
"[email protected]"
] | |
f0563a939cf9de410ffff884e522d1ad39d7bc02 | 40921b6ce9ec3e8808800e638218d9d246d6ec8a | /src/gl/objects/TextureAtlas.h | fbeeaf1a6e7d66377bf0209a330833d5be6e59ed | [
"MIT"
] | permissive | miha53cevic/simpleVoxelEngine | 92a2368145391b4f9e83b5c008234e96fee8b321 | ad7f799ab5a8d5126c45888efd31d1d0998dd9ca | refs/heads/master | 2022-11-28T10:11:27.587356 | 2020-08-06T22:53:06 | 2020-08-06T22:53:06 | 231,860,817 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 412 | h | #pragma once
#include <glm/glm.hpp>
#include "Texture.h"
namespace gl
{
struct TextureAtlas
{
TextureAtlas(const std::string path, int image_size, int individualTexture_size);
std::vector<GLfloat> getTextureCoords(const glm::ivec2& coords);
Texture texture;
const GLfloat TEX_PER_ROW;
const GLfloat INDV_TEX_SIZE;
const GLfloat PIXEL_SIZE;
};
};
| [
"[email protected]"
] | |
51a5a240e6aa8c6cdee48caa1879b03d43ec9f25 | 4b924c20f005de2fefceba567ac14002a32a12c3 | /es5.52/src/PrimitiveList.cpp | 3ef71c3ef50469e492f459e5776fe6038a6a2c54 | [] | no_license | jgarte/sicp-exercises | a72df5454cd989178ff246651474b38a9d79095a | 423ae2a1b462078f91e3530b3082f1c1402253a4 | refs/heads/master | 2021-10-26T15:05:56.573869 | 2019-04-13T10:20:30 | 2019-04-13T10:20:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 272 | cpp | #include "primitive_list.h"
#include "cons.h"
#include "integer.h"
#include <iostream>
using namespace std;
Value* PrimitiveList::apply(List* arguments)
{
return arguments;
}
string PrimitiveList::to_string() const
{
return string("PrimitiveProcedure:list");
}
| [
"[email protected]"
] | |
69c98cb48492e30af4dee92934f64d21a3c8cb8d | fa11b6efee3cf9d8a310baa3cca1c5d022223fa5 | /SpaceInvaders/EInvaderGroup.h | f0432af186217ff2df69e06b4fa3fb83093a8a5b | [] | no_license | afromogli/spaceinvaders | 1665456b544fcaf0bd894d6904d839665053066d | 43b1c7f15bb2f60ac459753b81acc88300196f78 | refs/heads/master | 2021-05-07T00:31:56.051227 | 2018-01-04T19:13:51 | 2018-01-04T19:13:51 | 110,152,626 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,407 | h | #pragma once
#include <memory>
#include "Entity.h"
#include "EInvader.h"
#include "EInvaderRocket.h"
using namespace Common;
namespace SpaceInvaders
{
class EInvaderGroup : public Entity
{
friend class EntityFactory;
public:
void update(const float& deltaTime) override;
void draw(Graphics& graphics) override;
/**
* @brief Tries to find the first invader that collides with the specified rocket. Does a bottom (and up) first search for possible collision.
* @param rocket The rocket
* @return Returns either the colliding invader or a nullptr
*/
EInvader* tryFindCollidingInvader(const ECannonRocket& rocket) const;
EInvader& getClosestAliveInvaderAtPosition(const int column, const int row);
/**
* @brief Will reset the invader group, if the gameover flag is false then the velocity will not be reset.
* @param isGameOver Whether reset is caused by game over state or not.
*/
void reset(const bool isGameOver);
static float getDrawingCooldown(const int column, const int row);
/**
* @brief Returns the first alive invader starting from the bottom row and upwards.
* @return First alive invader starting from the bottom row and upwards.
*/
EInvader* getFirstAliveInvaderFromTheBottom() const;
bool areAllInvadersDead() const;
void increaseInvaderVelocity();
private:
explicit EInvaderGroup(const shared_ptr<Texture> spriteSheet, const Vector2f upperLeftStartPos);
bool isAnimationFrameChangeNeeded(const float& deltaTime);
const EInvader* getFirstAliveInvaderFromTheLeft() const;
const EInvader* getFirstAliveInvaderFromTheRight() const;
bool isChangeDirectionNeeded(const float& deltaTime);
shared_ptr<EInvader> getInvader(const int column, const int row) const;
static EntityType getInvaderType(int row);
static Vector2f centerOffset(const EntityType type, Vector2f posOffset);
Vector2f getInvaderStartPosition(const EntityType type, const int row, const int column) const;
shared_ptr<EInvader> m_invaders[GameConfig::InvaderRows* GameConfig::InvaderColumns];
const shared_ptr<Texture> m_spriteSheet;
float m_timeLeftInAnimationFrame;
const Vector2f m_upperLeftStartPos;
static constexpr float ChangeDirectionCooldownLength = 2000.f; // millisecs
float m_changeDirectionCooldown;
float m_currentInvaderVelocity;
};
} | [
"[email protected]"
] | |
5d45a1ec509047670b72165832cd5aaf748bab84 | 8366d408980003a6838b7ad6714ef49adecf9a23 | /include/elemental/blas-like/level3/Trr2k.hpp | c9db1146ca97a7a040238bf199c6d6f57d2ad370 | [] | no_license | npezolano/Elemental | c55db9d03b31ccb3595a9a1aa51945794f796625 | bce40b061ee82df2cf6e253c2b3c0f3557cad01d | refs/heads/master | 2021-01-18T11:58:01.231871 | 2013-01-22T19:49:07 | 2013-01-22T19:49:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,789 | hpp | /*
Copyright (c) 2009-2013, Jack Poulson
All rights reserved.
This file is part of Elemental and is under the BSD 2-Clause License,
which can be found in the LICENSE file in the root directory, or at
http://opensource.org/licenses/BSD-2-Clause
*/
#include "./Trr2k/Local.hpp"
#include "./Trr2k/NNNN.hpp"
#include "./Trr2k/NNNT.hpp"
#include "./Trr2k/NNTN.hpp"
#include "./Trr2k/NNTT.hpp"
#include "./Trr2k/NTNN.hpp"
#include "./Trr2k/NTNT.hpp"
#include "./Trr2k/NTTN.hpp"
#include "./Trr2k/NTTT.hpp"
#include "./Trr2k/TNNN.hpp"
#include "./Trr2k/TNNT.hpp"
#include "./Trr2k/TNTN.hpp"
#include "./Trr2k/TNTT.hpp"
#include "./Trr2k/TTNN.hpp"
#include "./Trr2k/TTNT.hpp"
#include "./Trr2k/TTTN.hpp"
#include "./Trr2k/TTTT.hpp"
namespace elem {
// This will be enabled as soon as the underlying routines are written
/*
template<typename T>
inline void
Trr2k
( UpperOrLower uplo,
Orientation orientationOfA, Orientation orientationOfB,
Orientation orientationOfC, Orientation orientationOfD,
T alpha, const Matrix<T>& A, const Matrix<T>& B,
const Matrix<T>& C, const Matrix<T>& D,
T beta, Matrix<T>& E )
{
#ifndef RELEASE
PushCallStack("Trr2k");
#endif
const bool normalA = orientationOfA == NORMAL;
const bool normalB = orientationOfB == NORMAL;
const bool normalC = orientationOfC == NORMAL;
const bool normalD = orientationOfD == NORMAL;
int subcase = 8*normalA + 4*normalB + 2*normalC + normalD;
switch( subcase )
{
case 0:
internal::Trr2kNNNN( uplo, alpha, A, B, C, D, beta, E );
break;
case 1:
internal::Trr2kNNNT
( uplo, orientationOfD, alpha, A, B, C, D, beta, E );
break;
case 2:
internal::Trr2kNNTN
( uplo, orientationOfC, alpha, A, B, C, D, beta, E );
break;
case 3:
internal::Trr2kNNTT
( uplo, orientationOfC, orientationOfD, alpha, A, B, C, D, beta, E );
break;
case 4:
internal::Trr2kNTNN
( uplo, orientationOfB, alpha, A, B, C, D, beta, E );
break;
case 5:
internal::Trr2kNTNT
( uplo, orientationOfB, orientationOfD, alpha, A, B, C, D, beta, E );
break;
case 6:
internal::Trr2kNTTN
( uplo, orientationOfB, orientationOfC, alpha, A, B, C, D, beta, E );
break;
case 7:
internal::Trr2kNTTT
( uplo, orientationOfB, orientationOfC, orientationOfD,
alpha, A, B, C, D, beta, E );
break;
case 8:
internal::Trr2kTNNN
( uplo, orientationOfA, alpha, A, B, C, D, beta, E );
break;
case 9:
internal::Trr2kTNNT
( uplo, orientationOfA, orientationOfD, alpha, A, B, C, D, beta, E );
break;
case 10:
internal::Trr2kTNTN
( uplo, orientationOfA, orientationOfC, alpha, A, B, C, D, beta, E );
break;
case 11:
internal::Trr2kTNTT
( uplo, orientationOfA, orientationOfC, orientationOfD,
alpha, A, B, C, D, beta, E );
break;
case 12:
internal::Trr2kTTNN
( uplo, orientationOfA, orientationOfB, alpha, A, B, C, D, beta, E );
break;
case 13:
internal::Trr2kTTNT
( uplo, orientationOfA, orientationOfB, orientationOfD,
alpha, A, B, C, D, beta, E );
break;
case 14:
internal::Trr2kTTTN
( uplo, orientationOfA, orientationOfB, orientationOfC,
alpha, A, B, C, D, beta, E );
break;
case 15:
internal::Trr2kTTTN
( uplo, orientationOfA, orientationOfB, orientationOfC, orientationOfD,
alpha, A, B, C, D, beta, E );
break;
default:
throw std::logic_error("Impossible subcase");
}
#ifndef RELEASE
PopCallStack();
#endif
}
*/
template<typename T>
inline void
Trr2k
( UpperOrLower uplo,
Orientation orientationOfA, Orientation orientationOfB,
Orientation orientationOfC, Orientation orientationOfD,
T alpha, const DistMatrix<T>& A, const DistMatrix<T>& B,
const DistMatrix<T>& C, const DistMatrix<T>& D,
T beta, DistMatrix<T>& E )
{
#ifndef RELEASE
PushCallStack("Trr2k");
#endif
const bool normalA = orientationOfA == NORMAL;
const bool normalB = orientationOfB == NORMAL;
const bool normalC = orientationOfC == NORMAL;
const bool normalD = orientationOfD == NORMAL;
int subcase = 8*normalA + 4*normalB + 2*normalC + normalD;
switch( subcase )
{
case 0:
internal::Trr2kNNNN( uplo, alpha, A, B, C, D, beta, E );
break;
case 1:
internal::Trr2kNNNT
( uplo, orientationOfD, alpha, A, B, C, D, beta, E );
break;
case 2:
internal::Trr2kNNTN
( uplo, orientationOfC, alpha, A, B, C, D, beta, E );
break;
case 3:
internal::Trr2kNNTT
( uplo, orientationOfC, orientationOfD, alpha, A, B, C, D, beta, E );
break;
case 4:
internal::Trr2kNTNN
( uplo, orientationOfB, alpha, A, B, C, D, beta, E );
break;
case 5:
internal::Trr2kNTNT
( uplo, orientationOfB, orientationOfD, alpha, A, B, C, D, beta, E );
break;
case 6:
internal::Trr2kNTTN
( uplo, orientationOfB, orientationOfC, alpha, A, B, C, D, beta, E );
break;
case 7:
internal::Trr2kNTTT
( uplo, orientationOfB, orientationOfC, orientationOfD,
alpha, A, B, C, D, beta, E );
break;
case 8:
internal::Trr2kTNNN
( uplo, orientationOfA, alpha, A, B, C, D, beta, E );
break;
case 9:
internal::Trr2kTNNT
( uplo, orientationOfA, orientationOfD, alpha, A, B, C, D, beta, E );
break;
case 10:
internal::Trr2kTNTN
( uplo, orientationOfA, orientationOfC, alpha, A, B, C, D, beta, E );
break;
case 11:
internal::Trr2kTNTT
( uplo, orientationOfA, orientationOfC, orientationOfD,
alpha, A, B, C, D, beta, E );
break;
case 12:
internal::Trr2kTTNN
( uplo, orientationOfA, orientationOfB, alpha, A, B, C, D, beta, E );
break;
case 13:
internal::Trr2kTTNT
( uplo, orientationOfA, orientationOfB, orientationOfD,
alpha, A, B, C, D, beta, E );
break;
case 14:
internal::Trr2kTTTN
( uplo, orientationOfA, orientationOfB, orientationOfC,
alpha, A, B, C, D, beta, E );
break;
case 15:
internal::Trr2kTTTN
( uplo, orientationOfA, orientationOfB, orientationOfC, orientationOfD,
alpha, A, B, C, D, beta, E );
break;
default:
throw std::logic_error("Impossible subcase");
}
#ifndef RELEASE
PopCallStack();
#endif
}
} // namespace elem
| [
"[email protected]"
] | |
93fbe697874c77e857d2e2b6d4515e2bb394eebd | 90d49d65583146cb13a382afac69ff693da0f132 | /G_color.cpp | 0574cb8eeb9052fa3655a05144494df1ebad42b5 | [] | no_license | srkprasad1995/files | 82768b538a9e180cc4908bff6174743a0f93a1c8 | 00983aa8439eec6158ab17d0bcbd29bf2a3239c3 | refs/heads/master | 2021-01-15T19:45:10.585486 | 2015-03-22T10:25:43 | 2015-03-22T10:25:43 | 32,670,902 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 456 | cpp | #include<iostream>
#include<string>
using namespace std;
int n,a[100][100];
int x[100];
int main()
{
cin >> n;
for( int i=1 ; i <= n ; i++)
for( int j= 1 ; i <= n ;i++)
cin >> a[i][j];
print_ham( 1 );
return 0;
}
void print_ham(int k)
{
while(1);
{
next_value(k);
if(x[k] == 0)
{
cout << "invalid input" << endl;
return ;
}
if( k ==n )
print_sol();
print_ham(k+1);
}
return ;
}
void next_value( int k )
{
while(
| [
"[email protected]"
] | |
b3a7cadc117b18bc78239b73a3a9b358dc71dfa3 | c079c287f7bbdc77e824bcd9855df2b45e74da58 | /include/kernel/globe/LineSymbolElement3D.h | 62b018d48b797ddc936f333837177efd794a8bc5 | [] | no_license | lawiest/GuangGuProject | b0ec76284c284b9e7b584b7cb8c9a503d3e5894d | 77f4db8436456b4bb9d9f1d7d35e5244f28ec99d | refs/heads/master | 2020-11-28T18:35:22.492303 | 2019-12-25T01:40:10 | 2019-12-25T01:40:10 | 229,892,801 | 12 | 10 | null | null | null | null | GB18030 | C++ | false | false | 1,082 | h | #pragma once
#include "Element.h"
#include <canvas.h>
#include <GsReference.h>
GLOBE_NS
enum Mode
{
LINES,
LINE_STRIP,
LINE_LOOP,
POLYGON
};
class GS_API LineSymbolElement3D : public Element
{
public:
LineSymbolElement3D(Mode model);
virtual~LineSymbolElement3D();
void AddPoint(double x, double y, double z);
const std::vector<KERNEL_NAME::GsRawPoint3D> getPoints();
//颜色,r[0-255],g[0-255],b[0-255],a[0-255]
void setColor(int r, int g, int b, int a = 255.0);
KERNEL_NAME::GsColor getColor();
//设置线宽
void setLineWidth(int nSize);
int getLineWidth();
/*
gsAxle:旋转轴,一般情况下只需要z轴旋转(即GsRawPoint3D(0.0, 0.0, 1.0))
dbDegree:旋转角度(角度制,如45度)
*/
void Rotate(GsRawPoint3D gsAxle, double dbDegree);
void Finish();
private:
KERNEL_NAME::GsRawPoint3D m_origin;
GsReferencePtr m_ptrVertex;
GsReferencePtr m_ptrDrawArray;
GsReferencePtr m_ptrLinesGeom;
GsReferencePtr m_ptrColors;
int m_nSize;
std::vector<KERNEL_NAME::GsRawPoint3D> m_points;
};
GS_SMARTER_PTR(LineSymbolElement3D);
GLOBE_ENDNS | [
"[email protected]"
] | |
3da831d6c4932676c2a89ac6fd0b7b4c509f43b5 | d51e54dccbb594a056005cb50a9dbad472ddb034 | /Volume_15/Number_4/Olsson2011/utils/SimpleShader.h | 9d47ced74760f7c386ae1449e2f7f5fcbe2c2372 | [
"MIT"
] | permissive | skn123/jgt-code | 4aa8d39d6354a1ede9b141e5e7131e403465f4f7 | 1c80455c8aafe61955f61372380d983ce7453e6d | refs/heads/master | 2023-08-30T22:54:09.412136 | 2023-08-28T20:54:09 | 2023-08-28T20:54:09 | 217,573,703 | 0 | 0 | MIT | 2023-08-29T02:29:29 | 2019-10-25T16:27:56 | MATLAB | UTF-8 | C++ | false | false | 4,313 | h | /****************************************************************************/
/* Copyright (c) 2011, Ola Olsson
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/****************************************************************************/
#ifndef _SimpleShader_h_
#define _SimpleShader_h_
#include <linmath/float3.h>
#include <linmath/float4x4.h>
#include <linmath/float3x3.h>
#include <linmath/int2.h>
#include <GL/glew.h>
#include <GL/glut.h>
#include <map>
#include <string>
namespace chag
{
/**
* Very simple glsl shader class, supports vertex and fragment shaders and a handful of operations.
* The most un-basic feature is that it supports setting #defines, which are supplied in a context
* that is passed to the compilation.
*/
class SimpleShader
{
public:
class Context;
/**
* Constructs and compiles a shader, the context provides preprocessor definitions.
*/
SimpleShader(const char *vertexShaderFileName, const char *fragmentShaderFileName, const Context &context);
/**
* link the shader, must be done after constructor to complete the shader creation.
* But, should not be done before attribute- and fragment data locations are bound,
* (bindAttribLocation & bindFragDataLocation).
*/
bool link();
/**
* Must be used between ctor and link.
*/
void bindAttribLocation(GLint index, GLchar* name);
/**
* Must be used between ctor and link.
*/
void bindFragDataLocation(GLuint location, const char *name);
/**
* Looks up the index of uniform buffer of the given name in the shader,
* and binds it to the given buffer index.
*/
bool setUniformBufferSlot(const char *blockName, GLuint slotIndex);
/**
* Binds the texture(2D/2D_MULTISAMPLE) to the given texture stage
* AND sets the corresponding uniform to the texture stage.
* Must be called inside a begin/end pair.
*/
bool setTexture2D(const char *varName, GLuint textureId, GLuint textureStage);
bool setTexture2DMS(const char *varName, GLuint textureId, GLuint textureStage);
bool setTextureBuffer(const char *varName, GLuint textureId, GLuint textureStage);
/**
* Set uniforms, overloaded for some types.
* Must be called inside a begin/end pair.
*/
bool setUniform(const char *varName, GLint v);
bool setUniform(const char *varName, GLfloat v0, GLfloat v1);
bool setUniform(const char *varName, const float3 &v);
bool setUniform(const char *varName, const float4x4 &value);
/**
* Before rendering geometry using the shader, call begin(), when done call end().
*/
void begin();
void end();
/**
* Used to manage preprocessor definitions, is sent to the compile of a shader.
*/
class Context
{
public:
Context() { };
/**
* Set value of preproc def, is created if needed otherwise updated.
* Also updates char buffer.
*/
void setPreprocDef(const char *name, int value);
void setPreprocDef(const char *name, bool value);
void updatePreprocDefBuffer();
char m_shaderPreprocDefBuffer[4096];
typedef std::map<std::string, std::string> StringMap;
StringMap m_shaderPreprocDefs;
};
protected:
GLuint m_shaderProgram;
bool m_linked;
bool m_begun;
bool m_compiled;
};
}; // namespace chag
#endif // _SimpleShader_h_
| [
"[email protected]"
] | |
41d1b9ad6afb83efcb584151be0c0cccc1278478 | bd6e36612cd2e00f4e523af0adeccf0c5796185e | /src/core/myReadLine.cc | d2ec42ac593b31301e1fa1ef7dce7c9d3b659d4d | [] | no_license | robert-strandh/clasp | 9efc8787501c0c5aa2480e82bb72b2a270bc889a | 1e00c7212d6f9297f7c0b9b20b312e76e206cac2 | refs/heads/master | 2021-01-21T20:07:39.855235 | 2015-03-27T20:23:46 | 2015-03-27T20:23:46 | 33,315,546 | 1 | 0 | null | 2015-04-02T15:13:04 | 2015-04-02T15:13:04 | null | UTF-8 | C++ | false | false | 1,825 | cc | /*
File: myReadLine.cc
*/
/*
Copyright (c) 2014, Christian E. Schafmeister
CLASP is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
See directory 'clasp/licenses' for full details.
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/* -^- */
#include <clasp/core/foundation.h>
#include <clasp/core/object.h>
#include <clasp/core/lisp.h>
#include <clasp/core/myReadLine.h>
#ifdef READLINE
extern "C" char *readline( const char* prompt);
extern "C" void add_history(char* line);
#endif
namespace core
{
string myReadLine(const string& prompt)
{_G();
string res;
#ifdef READLINE
char* line_read;
/* Get a line from the user. */
// lisp->print(BF("%s")%prompt);
stringstream ss;
ss << std::endl << prompt;
line_read = ::readline(ss.str().c_str()); // prompt.c_str());
if ( line_read != NULL )
{
if (*line_read) ::add_history(line_read);
res = line_read;
free(line_read);
}
#else
if ( prompt != "" )
{
_lisp->print(BF("%s ") % prompt );
}
getline(cin,res);
#endif
return res;
}
};
| [
"[email protected]"
] | |
82c3c2731791d6f97cb1bba1a31ddb0218ffa772 | 2a7e77565c33e6b5d92ce6702b4a5fd96f80d7d0 | /fuzzedpackages/fastglm/src/glm.h | 1ff6e5f1e4ab4238528294fc418d80703ab788a1 | [] | no_license | akhikolla/testpackages | 62ccaeed866e2194652b65e7360987b3b20df7e7 | 01259c3543febc89955ea5b79f3a08d3afe57e95 | refs/heads/master | 2023-02-18T03:50:28.288006 | 2021-01-18T13:23:32 | 2021-01-18T13:23:32 | 329,981,898 | 7 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 18,790 | h | #ifndef GLM_H
#define GLM_H
#include "glm_base.h"
using Eigen::ArrayXd;
using Eigen::FullPivHouseholderQR;
using Eigen::ColPivHouseholderQR;
using Eigen::ComputeThinU;
using Eigen::ComputeThinV;
using Eigen::HouseholderQR;
using Eigen::JacobiSVD;
using Eigen::BDCSVD;
using Eigen::LDLT;
using Eigen::LLT;
using Eigen::Lower;
using Eigen::Map;
using Eigen::MatrixXd;
using Eigen::SelfAdjointEigenSolver;
using Eigen::SelfAdjointView;
using Eigen::TriangularView;
using Eigen::VectorXd;
using Eigen::Upper;
using Eigen::EigenBase;
class glm: public GlmBase<Eigen::VectorXd, Eigen::MatrixXd> //Eigen::SparseVector<double>
{
protected:
typedef double Double;
typedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> Matrix;
typedef Eigen::Matrix<double, Eigen::Dynamic, 1> Vector;
typedef Eigen::Map<const Matrix> MapMat;
typedef Eigen::Map<const Vector> MapVec;
typedef const Eigen::Ref<const Matrix> ConstGenericMatrix;
typedef const Eigen::Ref<const Vector> ConstGenericVector;
typedef Eigen::SparseMatrix<double> SpMat;
typedef Eigen::SparseVector<double> SparseVector;
typedef MatrixXd::Index Index;
typedef MatrixXd::Scalar Scalar;
typedef MatrixXd::RealScalar RealScalar;
typedef ColPivHouseholderQR<MatrixXd>::PermutationType Permutation;
typedef Permutation::IndicesType Indices;
const Map<MatrixXd> X;
const Map<VectorXd> Y;
const Map<VectorXd> weights;
const Map<VectorXd> offset;
Function variance_fun;
Function mu_eta_fun;
Function linkinv;
Function dev_resids_fun;
Function valideta;
Function validmu;
double tol;
int maxit;
int type;
int rank;
FullPivHouseholderQR<MatrixXd> FPQR;
ColPivHouseholderQR<MatrixXd> PQR;
BDCSVD<MatrixXd> bSVD;
HouseholderQR<MatrixXd> QR;
LLT<MatrixXd> Ch;
LDLT<MatrixXd> ChD;
JacobiSVD<MatrixXd> UDV;
SelfAdjointEigenSolver<MatrixXd> eig;
Permutation Pmat;
MatrixXd Rinv;
VectorXd effects;
RealScalar threshold() const
{
//return m_usePrescribedThreshold ? m_prescribedThreshold
//: numeric_limits<double>::epsilon() * nvars;
return numeric_limits<double>::epsilon() * nvars;
}
// from RcppEigen
inline ArrayXd Dplus(const ArrayXd& d)
{
ArrayXd di(d.size());
double comp(d.maxCoeff() * threshold());
for (int j = 0; j < d.size(); ++j) di[j] = (d[j] < comp) ? 0. : 1./d[j];
rank = (di != 0.).count();
return di;
}
MatrixXd XtWX() const
{
return MatrixXd(nvars, nvars).setZero().selfadjointView<Lower>().
rankUpdate( (w.asDiagonal() * X).adjoint());
}
virtual void update_mu_eta()
{
NumericVector mu_eta_nv = mu_eta_fun(eta);
std::copy(mu_eta_nv.begin(), mu_eta_nv.end(), mu_eta.data());
}
virtual void update_var_mu()
{
NumericVector var_mu_nv = variance_fun(mu);
std::copy(var_mu_nv.begin(), var_mu_nv.end(), var_mu.data());
}
virtual void update_mu()
{
// mu <- linkinv(eta <- eta + offset)
NumericVector mu_nv = linkinv(eta);
std::copy(mu_nv.begin(), mu_nv.end(), mu.data());
}
virtual void update_eta()
{
// eta <- drop(x %*% start)
if (type == 0)
{
//VectorXd effects(PQR.householderQ().adjoint() * y);
if (rank == nvars)
{
eta = X * beta + offset;
} else
{
//eta = PQR.householderQ() * effects + offset;
eta = X * beta + offset;
}
} else if (type == 1)
{
eta = X * beta + offset;
} else if (type == 2)
{
eta = X * beta + offset;
} else if (type == 3)
{
eta = X * beta + offset;
} else if (type == 4)
{
if (rank == nvars)
{
eta = X * beta + offset;
} else
{
//std::cout << FPQR.matrixQ().cols() << " " << effects.size() << std::endl;
//eta = FPQR.matrixQ() * effects + offset;
eta = X * beta + offset;
}
} else
{
eta = X * beta + offset;
}
}
virtual void update_z()
{
// z <- (eta - offset)[good] + (y - mu)[good]/mu.eta.val[good]
z = (eta - offset).array() + (Y - mu).array() / mu_eta.array();
}
virtual void update_w()
{
// w <- sqrt((weights[good] * mu.eta.val[good]^2)/variance(mu)[good])
w = (weights.array() * mu_eta.array().square() / var_mu.array()).array().sqrt();
}
virtual void update_dev_resids()
{
devold = dev;
NumericVector dev_resids = dev_resids_fun(Y, mu, weights);
dev = sum(dev_resids);
}
virtual void update_dev_resids_dont_update_old()
{
NumericVector dev_resids = dev_resids_fun(Y, mu, weights);
dev = sum(dev_resids);
}
virtual void step_halve()
{
// take half step
beta = 0.5 * (beta.array() + beta_prev.array());
update_eta();
update_mu();
}
virtual void run_step_halving(int &iterr)
{
// check for infinite deviance
if (std::isinf(dev))
{
int itrr = 0;
while(std::isinf(dev))
{
++itrr;
if (itrr > maxit)
{
break;
}
//std::cout << "half step (infinite)!" << itrr << std::endl;
step_halve();
// update deviance
update_dev_resids_dont_update_old();
}
}
// check for boundary violations
if (!(valideta(eta) && validmu(mu)))
{
int itrr = 0;
while(!(valideta(eta) && validmu(mu)))
{
++itrr;
if (itrr > maxit)
{
break;
}
//std::cout << "half step (boundary)!" << itrr << std::endl;
step_halve();
}
update_dev_resids_dont_update_old();
}
// check for increasing deviance
//std::abs(deviance - deviance_prev) / (0.1 + std::abs(deviance)) < tol_irls
if ((dev - devold) / (0.1 + std::abs(dev)) >= tol && iterr > 0)
{
int itrr = 0;
//std::cout << "dev:" << deviance << "dev prev:" << deviance_prev << std::endl;
while((dev - devold) / (0.1 + std::abs(dev)) >= -tol)
{
++itrr;
if (itrr > maxit)
{
break;
}
//std::cout << "half step (increasing dev)!" << itrr << std::endl;
step_halve();
update_dev_resids_dont_update_old();
}
}
}
// much of solve_wls() comes directly
// from the source code of the RcppEigen package
virtual void solve_wls(int iter)
{
//lm ans(do_lm(X, Y, w, type));
//wls ans(ColPivQR(X, z, w));
//enum {ColPivQR_t = 0, QR_t, LLT_t, LDLT_t, SVD_t, SymmEigen_t, GESDD_t};
beta_prev = beta;
if (type == 0)
{
PQR.compute(w.asDiagonal() * X); // decompose the model matrix
Pmat = (PQR.colsPermutation());
rank = PQR.rank();
if (rank == nvars)
{ // full rank case
beta = PQR.solve( (z.array() * w.array()).matrix() );
// m_fitted = X * m_coef;
//m_se = Pmat * PQR.matrixQR().topRows(m_p).
//triangularView<Upper>().solve(MatrixXd::Identity(nvars, nvars)).rowwise().norm();
} else
{
Rinv = (PQR.matrixQR().topLeftCorner(rank, rank).
triangularView<Upper>().
solve(MatrixXd::Identity(rank, rank)));
effects = PQR.householderQ().adjoint() * (z.array() * w.array()).matrix();
beta.head(rank) = Rinv * effects.head(rank);
beta = Pmat * beta;
// create fitted values from effects
// (can't use X*m_coef if X is rank-deficient)
effects.tail(nobs - rank).setZero();
//m_fitted = PQR.householderQ() * effects;
//m_se.head(m_r) = Rinv.rowwise().norm();
//m_se = Pmat * m_se;
}
} else if (type == 1)
{
QR.compute(w.asDiagonal() * X);
beta = QR.solve((z.array() * w.array()).matrix());
//m_fitted = X * m_coef;
//m_se = QR.matrixQR().topRows(m_p).
//triangularView<Upper>().solve(I_p()).rowwise().norm();
} else if (type == 2)
{
Ch.compute(XtWX().selfadjointView<Lower>());
beta = Ch.solve((w.asDiagonal() * X).adjoint() * (z.array() * w.array()).matrix());
//m_fitted = X * m_coef;
//m_se = Ch.matrixL().solve(I_p()).colwise().norm();
} else if (type == 3)
{
ChD.compute(XtWX().selfadjointView<Lower>());
Dplus(ChD.vectorD()); // to set the rank
//FIXME: Check on the permutation in the LDLT and incorporate it in
//the coefficients and the standard error computation.
// m_coef = Ch.matrixL().adjoint().
// solve(Dplus(D) * Ch.matrixL().solve(X.adjoint() * y));
beta = ChD.solve((w.asDiagonal() * X).adjoint() * (z.array() * w.array()).matrix());
//m_fitted = X * m_coef;
//m_se = Ch.solve(I_p()).diagonal().array().sqrt();
} else if (type == 4)
{
FPQR.compute(w.asDiagonal() * X); // decompose the model matrix
Pmat = (FPQR.colsPermutation());
rank = FPQR.rank();
if (rank == nvars)
{ // full rank case
beta = FPQR.solve( (z.array() * w.array()).matrix() );
// m_fitted = X * m_coef;
//m_se = Pmat * PQR.matrixQR().topRows(m_p).
//triangularView<Upper>().solve(MatrixXd::Identity(nvars, nvars)).rowwise().norm();
} else
{
Rinv = (FPQR.matrixQR().topLeftCorner(rank, rank).
triangularView<Upper>().
solve(MatrixXd::Identity(rank, rank)));
effects = FPQR.matrixQ().adjoint() * (z.array() * w.array()).matrix();
//std::cout << effects.transpose() << std::endl;
beta.head(rank) = Rinv * effects.head(rank);
beta = Pmat * beta;
// create fitted values from effects
// (can't use X*m_coef if X is rank-deficient)
effects.tail(nobs - rank).setZero();
//m_fitted = PQR.householderQ() * effects;
//m_se.head(m_r) = Rinv.rowwise().norm();
//m_se = Pmat * m_se;
}
} else if (type == 5)
{
bSVD.compute(w.asDiagonal() * X, ComputeThinU | ComputeThinV);
rank = bSVD.rank();
// if (rank == nvars)
// { // full rank case
// beta = bSVD.solve((z.array() * w.array()).matrix());
// } else
// {
//
// }
beta = bSVD.solve((z.array() * w.array()).matrix());
//FIXME: Check on the permutation in the LDLT and incorporate it in
//the coefficients and the standard error computation.
// m_coef = Ch.matrixL().adjoint().
// solve(Dplus(D) * Ch.matrixL().solve(X.adjoint() * y));
//m_fitted = X * m_coef;
//m_se = Ch.solve(I_p()).diagonal().array().sqrt();
}
// } else if (type == 4)
// {
// // UDV.compute((w.asDiagonal() * X).jacobiSvd(ComputeThinU|ComputeThinV));
// // MatrixXd VDi(UDV.matrixV() *
// // Dplus(UDV.singularValues().array()).matrix().asDiagonal());
// // beta = VDi * UDV.matrixU().adjoint() * (z.array() * w.array()).matrix();
// // //m_fitted = X * m_coef;
// // //m_se = VDi.rowwise().norm();
// // } else if (type == 5)
// // {
// eig.compute(XtWX().selfadjointView<Lower>());
// MatrixXd VDi(eig.eigenvectors() *
// Dplus(eig.eigenvalues().array()).sqrt().matrix().asDiagonal());
// beta = VDi * VDi.adjoint() * X.adjoint() * (z.array() * w.array()).matrix();
// //m_fitted = X * m_coef;
// //m_se = VDi.rowwise().norm();
// }
}
virtual void save_se()
{
if (type == 0)
{
if (rank == nvars)
{ // full rank case
se = Pmat * PQR.matrixQR().topRows(nvars).
triangularView<Upper>().solve(MatrixXd::Identity(nvars, nvars)).rowwise().norm();
return;
} else
{
// create fitted values from effects
// (can't use X*m_coef if X is rank-deficient)
se.head(rank) = Rinv.rowwise().norm();
se = Pmat * se;
}
} else if (type == 1)
{
se = QR.matrixQR().topRows(nvars).
triangularView<Upper>().solve(MatrixXd::Identity(nvars, nvars)).rowwise().norm();
} else if (type == 2)
{
se = Ch.matrixL().solve(MatrixXd::Identity(nvars, nvars)).colwise().norm();
} else if (type == 3)
{
se = ChD.solve(MatrixXd::Identity(nvars, nvars)).diagonal().array().sqrt();
} else if (type == 4)
{
if (rank == nvars)
{ // full rank case
se = Pmat * FPQR.matrixQR().topRows(nvars).
triangularView<Upper>().solve(MatrixXd::Identity(nvars, nvars)).rowwise().norm();
return;
} else
{
// create fitted values from effects
// (can't use X*m_coef if X is rank-deficient)
se.head(rank) = Rinv.rowwise().norm();
se = Pmat * se;
}
} else if (type == 5)
{
Rinv = (bSVD.solve(MatrixXd::Identity(nvars, nvars)));
se = Rinv.rowwise().norm();
}
}
public:
glm(const Map<MatrixXd> &X_,
const Map<VectorXd> &Y_,
const Map<VectorXd> &weights_,
const Map<VectorXd> &offset_,
Function &variance_fun_,
Function &mu_eta_fun_,
Function &linkinv_,
Function &dev_resids_fun_,
Function &valideta_,
Function &validmu_,
double tol_ = 1e-6,
int maxit_ = 100,
int type_ = 1) :
GlmBase<Eigen::VectorXd, Eigen::MatrixXd>(X_.rows(), X_.cols(),
tol_, maxit_),
X(X_),
Y(Y_),
weights(weights_),
offset(offset_),
//X(X_.data(), X_.rows(), X_.cols()),
//Y(Y_.data(), Y_.size()),
variance_fun(variance_fun_),
mu_eta_fun(mu_eta_fun_),
linkinv(linkinv_),
dev_resids_fun(dev_resids_fun_),
valideta(valideta_),
validmu(validmu_),
tol(tol_),
maxit(maxit_),
type(type_)
{}
// must set params to starting vals
void init_parms(const Map<VectorXd> & start_,
const Map<VectorXd> & mu_,
const Map<VectorXd> & eta_)
{
beta = start_;
eta = eta_;
mu = mu_;
//eta.array() += offset.array();
//update_var_mu();
//update_mu_eta();
//update_mu();
update_dev_resids();
//update_z();
//update_w();
rank = nvars;
}
virtual VectorXd get_beta()
{
if (type == 0 || type == 4)
{
if (rank != nvars)
{
//beta.head(rank) = Rinv * effects.head(rank);
//beta = Pmat * beta;
}
}
return beta;
}
virtual VectorXd get_weights() { return weights; }
virtual int get_rank() { return rank; }
};
#endif // GLM_H
| [
"[email protected]"
] | |
4c1cffaf776bc1803568d7287f70fd90ba5a8ca9 | 0774780f62592d40cb1697a4ef03563cb5458fbd | /LeetCode/Copy List with Random Pointer.cpp | d123550300e96a3f00cfe3ca502dd75d454f486b | [] | no_license | Divyanshnigam/Codechef | 24d1419c858ad4ed2924d092f22e6d14f2507f59 | 83fe7aab7265770c7697ae3e8c417041e40053d0 | refs/heads/main | 2023-04-22T05:03:36.300007 | 2021-05-08T12:45:09 | 2021-05-08T12:45:09 | 309,600,002 | 0 | 1 | null | 2020-11-03T10:59:26 | 2020-11-03T06:56:09 | C++ | UTF-8 | C++ | false | false | 1,468 | cpp | /*
// https://leetcode.com/problems/copy-list-with-random-pointer/
// Definition for a Node.
class Node {
public:
int val;
Node* next;
Node* random;
Node(int _val) {
val = _val;
next = NULL;
random = NULL;
}
};
*/
class Solution {
public:
Node* copyRandomList(Node* head)
{
// s1: create a copy and make in between
Node* itr=head;
Node* front=head;
while(itr!=NULL)
{
front=itr->next;
Node* copy= new Node(itr->val);
itr->next=copy;
copy->next=front;
itr=front;
}
// s2: Assign the random pointers for copy nodes
itr=head;
while(itr!=NULL)
{
if(itr->random != NULL)
{
itr->next->random = itr->random->next;
}
itr=itr->next->next;
}
//s3: Restore the random list and extract the copy list
itr = head;
Node* pseudoHead = new Node(0);
Node* copy = pseudoHead;
while(itr!=NULL)
{
front=itr->next->next;
// extract the copy
copy->next = itr->next;
//restore the original list
itr->next=front;
copy=copy->next;
itr= front;
}
return pseudoHead->next;
}
};
| [
"[email protected]"
] | |
736009fdc2aa269b764ffdf5e3d98eac12781805 | 4497c10f3b01b7ff259f3eb45d0c094c81337db6 | /Retargeting/Shifmap/ShiftMapComputer.h | 2158e3e7e502e65b4c7e3a679edaeca618a18be7 | [] | no_license | liuguoyou/retarget-toolkit | ebda70ad13ab03a003b52bddce0313f0feb4b0d6 | d2d94653b66ea3d4fa4861e1bd8313b93cf4877a | refs/heads/master | 2020-12-28T21:39:38.350998 | 2010-12-23T16:16:59 | 2010-12-23T16:16:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 762 | h | #pragma once
#include "Label.h"
#include "GCoptimization.h"
#include "EnergyFunction.h"
#include <cv.h>
/********************************************************
Implementation of Shift-map algorithm (Peleg ICCV2009)
A width x height image will have width x height number of labels
Label index is assigned from left to right, then top to bottom
e.g: 4x4 image
1 2 3 4
5 6 7 8
9 10 11 12
********************************************************/
class ShiftMapComputer
{
public:
ShiftMapComputer(void);
~ShiftMapComputer(void);
IplImage* GetImage(IplImage* input,IplImage* saliency, int width, int height);
private:
void GetRetargetImage(GCoptimizationGridGraph * gc, IplImage* input, IplImage* output);
};
| [
"kidphys@aeedd7dc-6096-11de-8dc1-e798e446b60a"
] | kidphys@aeedd7dc-6096-11de-8dc1-e798e446b60a |
db4a0b5ecb03967a638f2f88927084198acd7bbd | 6ed471f36e5188f77dc61cca24daa41496a6d4a0 | /SDK/WeapGun_LaserBeam_functions.cpp | d93f2bdb9e2b847a45bc906eaaca72c86708ac89 | [] | no_license | zH4x-SDK/zARKSotF-SDK | 77bfaf9b4b9b6a41951ee18db88f826dd720c367 | 714730f4bb79c07d065181caf360d168761223f6 | refs/heads/main | 2023-07-16T22:33:15.140456 | 2021-08-27T13:40:06 | 2021-08-27T13:40:06 | 400,521,086 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,409 | cpp |
#include "../SDK.h"
// Name: ARKSotF, Version: 178.8.0
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
namespace SDK
{
//---------------------------------------------------------------------------
// Functions
//---------------------------------------------------------------------------
// Function WeapGun_LaserBeam.WeapGun_LaserBeam_C.UserConstructionScript
// (Final)
void AWeapGun_LaserBeam_C::UserConstructionScript()
{
static auto fn = UObject::FindObject<UFunction>("Function WeapGun_LaserBeam.WeapGun_LaserBeam_C.UserConstructionScript");
AWeapGun_LaserBeam_C_UserConstructionScript_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function WeapGun_LaserBeam.WeapGun_LaserBeam_C.ExecuteUbergraph_WeapGun_LaserBeam
// (Final)
// Parameters:
// int EntryPoint (Parm, ZeroConstructor, IsPlainOldData)
void AWeapGun_LaserBeam_C::ExecuteUbergraph_WeapGun_LaserBeam(int EntryPoint)
{
static auto fn = UObject::FindObject<UFunction>("Function WeapGun_LaserBeam.WeapGun_LaserBeam_C.ExecuteUbergraph_WeapGun_LaserBeam");
AWeapGun_LaserBeam_C_ExecuteUbergraph_WeapGun_LaserBeam_Params params;
params.EntryPoint = EntryPoint;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"[email protected]"
] | |
d8a80777754b8b7bc1d0d35f90291095056ed46d | 10eea57e61f7f9c32a26306136c390152ce51437 | /main.cpp | ad1b728ef377bb601dc863b62ffe86cc26e4b139 | [] | no_license | jiayangl/LogicZelda | 803096ce2bce53c8ff3b1cf668df467d527715b6 | 0284681fdcc5741c4010edd18e3856182b18b894 | refs/heads/master | 2021-10-11T05:48:15.246610 | 2017-04-17T04:29:11 | 2017-04-17T04:29:11 | 86,641,176 | 0 | 0 | null | 2020-02-17T07:30:02 | 2017-03-30T00:21:11 | C++ | UTF-8 | C++ | false | false | 4,784 | cpp | #include <iostream>
#include "player.h"
#include "map.h"
#include "menu.h"
#include <string>
#include <vector>
#include "include/Room.h"
#include "monster.h"
#include <unistd.h> // for sleep()
using namespace std;
void animation(string ani){
cout << ani << std::flush;
for (int x = 0; x < 0; x++ ) {
sleep(1);
cout << "\b\\" << flush;
sleep(1);
cout << "\b|" << flush;
sleep(1);
cout << "\b/" << flush;
sleep(1);
cout << "\b-" << flush;
}
}
void startUp()
{
animation("Starting Up...");
cout << endl;
animation("Looking for the Map...");
cout << endl;
animation("Finding Rooms...");
cout << endl;
animation("Understanding Monsters...");
cout << endl;
animation ("Getting Question...");
cout << endl;
cout<<"Done..." << endl;
cout << "Team-22 Presents:"<<endl;
for(int x = 0; x < 20; x ++)
cout<<endl;
}
int main()
{
startUp();
map map;
map.MakeMap();
player player;
string playerName = "";
menu menu;
cout << "What is your name?: ";
cin >> playerName;
cin.clear();
cin.ignore(10000, '\n'); /* Clears out the input incase the user includes multiple words seperated by spaces. */
player.setName(playerName);
cout << endl;
map.MakePlayerMap();
map.UpdatePlayerMap();
map.PlayerMapPrint();
map.PrintMap();
Room room;
cout << "Room Value : " << map.getRoomValue() << endl;
room.setUpRoomInt(map.getRoomValue());
room.printRoom();
string input = "";
/*Game Loop*/
while(1)
{
cout << "Input: ";
cin >> input;
cout << endl;
cin.ignore(10000, '\n');
bool check = true;
/* Various Player Input */
//Compare returns 0 therefore we need ! to make it true.
if(!input.compare("HELP"))
{
menu.openmenu();
check = false;
}
if(!input.compare("QUIT"))
{
menu.exitGame(player);
check = false;
}
if(player.getHealth() <=0)
{
menu.playerDeath(player);
}
if(!input.compare("SCORE"))
{
cout << "Score: " << player.getScores() << endl;
check = false;
}
if(!input.compare("MAP")){
map.UpdatePlayerMap2();
map.PlayerMapPrint();
check = false;
}
if(!input.compare("HEALTH")){
cout << "Your current health is " << player.getHealth() << " Out of 10!" << endl;
check = false;
}
if(!input.compare("STUCK")){
cout << "welp, sorry, but you got stuck and starved to death :)" << endl;
menu.playerDeath(player);
check = false;
}
/* Movement */
if(!input.compare("w"))
{
int res = room.move('w');
if(res > 1)
{
if(map.moveUp())
{
room.setUpRoomInt(map.getRoomValue());
room.upRoom();
map.UpdatePlayerMap2();
}
}
check = false;
}
if(!input.compare("a"))
{
int res = room.move('a');
if(res > 1)
{
if(map.moveLeft())
{
room.setUpRoomInt(map.getRoomValue());
room.leftRoom();
map.UpdatePlayerMap2();
}
}
check = false;
}
if(!input.compare("s"))
{
int res = room.move('s');
if(res > 1)
{
if(map.moveDown())
{
room.setUpRoomInt(map.getRoomValue());
room.downRoom();
map.UpdatePlayerMap2();
}
}
check = false;
}
if(!input.compare("d"))
{
int res = room.move('d');
if(res > 1)
{
if(map.moveRight())
{
room.setUpRoomInt(map.getRoomValue());
room.rightRoom();
map.UpdatePlayerMap2();
}
}
check = false;
}
if (check){
cout << "unaccaptable input!" << endl;
}
/* Monster Encounter */
if(room.getMonVal() >= 1 && room.getMonVal() <= 16)
{
monster monster(room.getMonVal());
bool defeat = false;
while(!defeat)
{
if (monster.askQuestion())
{
cout << "Good Job! You have defeated the Monster!" << endl;
defeat = true;
} else
{
cout << "\n\n\n\nWrong answer. Looks like you take some damage. Try again." << endl;
player.changeHealth(-1);
if(player.getHealth() <= 0)
menu.playerDeath(player);
}
if(defeat && room.getMonVal() == 16)
{
player.changeScore(42);
menu.winGame(player);
}
if(defeat)
{
room.killMon();
player.changeScore(1);
}
}
}
/* Print out the Room at the end of each iteration. */
room.printRoom();
}
} | [
"[email protected]"
] | |
1483be042be8edfe1fae2d9efe2eb6f979baa21c | a9d43905377e59faa570df7adc7368d34696a361 | /v1/binary_tree/diameter_of_binary_tree.cpp | a28ca92d260934f9fb2497b889641dd9ebbe3930 | [] | no_license | sukantomondal/cplusplus | 4026ca2cb6553e0da3ac7789d2f87dc698d4dac7 | a67972317e9babdd66ba67eda13656be2a229d62 | refs/heads/master | 2021-06-20T07:05:25.607113 | 2021-01-05T03:00:24 | 2021-01-05T03:00:24 | 160,621,518 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,607 | cpp | /*Author : Sukanto Mondal */
/*
The diameter of a tree (sometimes called the width) is the number of nodes on the longest path between two end nodes. The diagram below shows two trees each with diameter nine, the leaves that form the ends of a longest path are shaded (note that there is more than one path in each tree of length nine, but no path longer than nine nodes). */
#include<iostream>
using namespace std;
struct Node{
int data;
Node *left, *right;
};
int height(Node * root){
if(root == NULL)
return 0;
return 1 + max(height(root->left),height(root->right));
}
int diameter(Node * root){
if(root==NULL)
return 0;
int lheight = height(root->left);
int rheight = height(root->right);
int ldiameter = diameter(root->left);
int rdiameter = diameter(root->right);
return max(lheight+rheight+1, max(ldiameter,rdiameter));
}
Node * new_node(int data){
Node * temp = new Node();
temp->data = data;
temp->left = NULL;
temp->right = NULL;
return temp;
}
int main(){
Node * root = new_node(1);
root->left = new_node(2);
root->right = new_node(3);
root->left->left = new_node(4);
root->left->right = new_node(5);
root->left->right->left = new_node(6);
root->left->right->right = new_node(7);
root->right->right = new_node(8);
root->right->right->right = new_node(9);
root->right->right->right->left = new_node(10);
root->right->right->right->right = new_node(11);
root->right->right->right->left->right = new_node(12);
cout << "The height of the tree is " << height(root) << "\n";
cout << "The diameter of the tree is " << diameter(root) << "\n";
return 0;
}
| [
"[email protected]"
] | |
82b96d9574607c389d7cfb5ed43b1a5cef2b1e78 | 86e3367acf81c30825670ad6b16056056e60cf48 | /ls/Player/Equip/Shield.cpp | 251f896e8d67708e2c356cddaeb3d8edac430259 | [
"BSD-3-Clause"
] | permissive | sorcery-p5/Asteraiser | 0bb3e4a2e620f68764ee4e346e99440d1e7818b8 | f27da9e3e262772686245f7e83b800e41c909f0f | refs/heads/master | 2020-03-19T06:25:38.820721 | 2020-02-12T14:15:05 | 2020-02-12T14:15:05 | 136,018,491 | 6 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 11,184 | cpp | #include "stdafx.h"
#include "Shield.h"
#include "../Player.h"
#include "../PlayerData.h"
#include "World/World.h"
#include "Config/Config.h"
#include "SpriteFrame/SpriteFrame.h"
#include "Effect/Effect.h"
#include "Item/ItemManager.h"
#include "Score/ScoreManager.h"
#include "Indicate/Indicate.h"
#include "Indicate/IndicateManager.h"
namespace
{
const float SHIELD_MAX = 100.0f;
const int SECTOR_MAX = 3;
const Label INDICATE_SHIELD = "Shield";
const Label INDICATE_RING_SHIELD = "RingShield";
const Label INDICATE_BONE_GAUGE = "Gauge";
const Label INDICATE_BONE_RECOVERY = "Recovery";
const Label INDICATE_BONE_DEADLY = "Deadly";
const Label INDICATE_BONE_NUM = "Num";
const Label INDICATE_BONE_MARKER = "Marker";
pstr INDICATE_BONE_MARKER_FMT = "Marker%d";
const Label INDICATE_ANIME_DEADLY = "Deadly";
const Label INDICATE_ANIME_WAIT = "Wait";
const Color COLOR_INDICATE_DEADLY = Color( 255,0,0 );
};
///////////////////////////////////////////////////////////////////////////////
//
// シールド
//
///////////////////////////////////////////////////////////////////////////////
Shield::Shield( void )
{
m_pParent = NULL;
m_pParam = NULL;
m_State = STATE_NORMAL;
m_Shield = SHIELD_MAX;
m_Sector = SECTOR_MAX;
m_Recovery = 0.0f;
m_InvincibleCount = 0;
m_NoMoveCount = 0;
m_BreakCount = 0;
m_BreakNum = 0;
m_SerialDamageCount = 0;
}
Shield::~Shield()
{
EffectDelete( m_pEffect );
}
//******************************************************************************
// 初期化
//******************************************************************************
void Shield::Init( Player* pParent, const SHIELD_PARAM* pParam )
{
_ASSERT( pParent && pParam );
m_pParent = pParent;
m_pParam = pParam;
m_State = STATE_NORMAL;
m_Shield = SHIELD_MAX;
m_Sector = SECTOR_MAX;
m_Recovery = 0.0f;
m_InvincibleCount = 0;
m_NoMoveCount = 0;
m_BreakCount = 0;
m_BreakNum = 0;
m_SerialDamageCount = 0;
// インジケート
m_pParent->GetWorld()->GetIndicateManager()->AddIndicate( INDICATE_RING_SHIELD, m_pParent->GetData()->GetIndicateData( INDICATE_RING_SHIELD ) );
}
//******************************************************************************
// リセット
//******************************************************************************
void Shield::Reset( void )
{
m_State = STATE_NORMAL;
m_Shield = SHIELD_MAX;
m_Sector = SECTOR_MAX;
m_Recovery = 0.0f;
m_InvincibleCount = 0;
m_NoMoveCount = 0;
m_BreakCount = 0;
m_BreakNum = 0;
}
//******************************************************************************
// 更新
//******************************************************************************
void Shield::Update( void )
{
// エフェクトの位置
if( m_pEffect ) m_pEffect->SetMatrix( m_pParent->GetMatrix() );
DecreaseZero( m_InvincibleCount, 1 );
DecreaseZero( m_NoMoveCount, 1 );
DecreaseZero( m_SerialDamageCount, 1 );
switch( m_State )
{
case STATE_NORMAL: _UpdateNormal(); break;
case STATE_BREAK: _UpdateBreak(); break;
};
// インジケートの更新
_UpdateIndicate();
}
//******************************************************************************
// ダメージ
//******************************************************************************
void Shield::Damage( float Damage )
{
// 減算
if( !GetConfig()->GetDebugInfo().bPlayerNodamage )
{
DecreaseZero( m_Shield, Damage );
}
// スコア通知
m_pParent->GetWorld()->GetScoreManager()->OnEvent( SCORE_EVENT_DAMAGE );
m_pParent->GetWorld()->GetScoreManager()->StopTimeValue( SCORE_TIME_VALUE_NO_DAMAGE );
// ブレイク
if( m_Shield <= 0.0f )
{
_Break();
}
// 通常ダメージ
else
{
m_InvincibleCount = m_pParam->DamageInvincible;
m_NoMoveCount = m_pParam->DamageNoMove;
// エフェクト発生
EffectDelete( m_pEffect );
m_pEffect = m_pParent->CreateEffect( m_pParam->HitEffectName, m_pParent->GetMatrix() );
// 連続ダメージ判定
if( m_SerialDamageCount > 0 )
{
m_pParent->GetWorld()->GetScoreManager()->OnEvent( SCORE_EVENT_SERIAL_DAMAGE );
}
m_SerialDamageCount = m_pParam->SerialDamageTime;
}
}
//******************************************************************************
// 自然回復
//******************************************************************************
float Shield::Regenerate( float Energy )
{
// シールド回復
if( !IsDeadly() && m_Shield < SHIELD_MAX )
{
Increase( m_Shield, SHIELD_MAX, Energy * m_pParam->NormalRegen );
DecreaseZero( Energy, m_pParam->UseRegenEnergy );
}
// 耐久回復
else if( m_Shield >= SHIELD_MAX && m_Sector < SECTOR_MAX )
{
Increase( m_Recovery, SHIELD_MAX, (Energy * m_pParam->NormalRecovery) - (m_BreakNum * m_pParam->BreakNumDecayRate) );
DecreaseZero( Energy, m_pParam->UseRegenEnergy );
// 回復更新
_UpdateRecovery();
}
return Energy;
}
//******************************************************************************
// アイテム取得
//******************************************************************************
float Shield::OnGetItem( float Energy )
{
// シールド回復
if( !IsDeadly() && m_Shield < SHIELD_MAX )
{
Increase( m_Shield, SHIELD_MAX, Energy * m_pParam->ItemRegen );
DecreaseZero( Energy, m_pParam->UseRegenEnergy );
}
// 耐久回復
else if( ( m_Shield == SHIELD_MAX || IsDeadly() ) && m_Sector < SECTOR_MAX )
{
Increase( m_Recovery, SHIELD_MAX, Energy * m_pParam->ItemRecovery );
DecreaseZero( Energy, m_pParam->UseRegenEnergy );
// 回復更新
_UpdateRecovery();
}
return Energy;
}
//******************************************************************************
// ブレイク状態からの復帰
//******************************************************************************
void Shield::CancelBreak( void )
{
m_BreakCount = 0;
// アイテム自動回収
m_pParent->GetWorld()->GetItemManager()->ForceCollect();
_Normal();
}
//******************************************************************************
// 復活
//******************************************************************************
void Shield::OnRevive( void )
{
// アイテム自動回収
m_pParent->GetWorld()->GetItemManager()->ForceCollect();
// 復活無敵
m_InvincibleCount = m_pParam->ReviveInvincible;
}
//------------------------------------------------------------------------------
// 通常状態
//------------------------------------------------------------------------------
void Shield::_UpdateNormal( void )
{
}
//------------------------------------------------------------------------------
// 破損状態
//------------------------------------------------------------------------------
void Shield::_UpdateBreak( void )
{
DecreaseZero( m_BreakCount, 1 );
if( m_BreakCount <= 0 )
{
CancelBreak();
}
}
//------------------------------------------------------------------------------
// セクター回復の更新
//------------------------------------------------------------------------------
void Shield::_UpdateRecovery( void )
{
if( m_Recovery >= SHIELD_MAX )
{
// 瀕死状態から回復
if( IsDeadly() )
{
m_Shield = SHIELD_MAX;
}
m_Recovery = 0.0f;
Increase( m_Sector, SECTOR_MAX, 1 );
// アイテム自動回収
m_pParent->GetWorld()->GetItemManager()->AutoCollect();
// 回復エフェクト
EffectDelete( m_pEffect );
m_pEffect = m_pParent->CreateEffect( m_pParam->RecoveryEffectName, m_pParent->GetMatrix() );
}
}
//------------------------------------------------------------------------------
// インジケートの更新
//------------------------------------------------------------------------------
void Shield::_UpdateIndicate( void )
{
// インジケート
Indicate* pIndicate = m_pParent->GetWorld()->GetIndicateManager()->GetIndicate( INDICATE_SHIELD );
if( pIndicate )
{
pIndicate->SetGauge( INDICATE_BONE_GAUGE, _GetShieldRate(), 1.0f );
pIndicate->SetGauge( INDICATE_BONE_RECOVERY, _GetRecoveryRate(), 1.0f );
pIndicate->SetText( INDICATE_BONE_NUM, "%1d", m_Sector );
pIndicate->SetColor( INDICATE_BONE_NUM, IsDeadly()? COLOR_INDICATE_DEADLY : Color::White() );
pIndicate->SetBoneVisible( INDICATE_BONE_DEADLY,IsDeadly() );
}
// リング
Indicate* pRingIndicate = m_pParent->GetWorld()->GetIndicateManager()->GetIndicate( INDICATE_RING_SHIELD );
if( pRingIndicate )
{
pRingIndicate->SetMatrix( m_pParent->GetMatrix() );
// 色
Color Col = IsDeadly()? COLOR_INDICATE_DEADLY : Color::White();
pRingIndicate->SetColor( Col * m_pParent->GetBodyAlpha() );
// ゲージ
pRingIndicate->SetAngle( INDICATE_BONE_GAUGE, _GetShieldRate() );
pRingIndicate->SetAngle( INDICATE_BONE_RECOVERY, _GetRecoveryRate() );
// 残量
for( int i = 0; i < SECTOR_MAX; i++ )
{
String256 Bone;
Bone.Format( INDICATE_BONE_MARKER_FMT, i );
pRingIndicate->SetBoneVisible( Label(Bone.c_str()), i < m_Sector || IsDeadly() );
}
// アニメ
if( pRingIndicate->IsOpen() &&
!pRingIndicate->IsAnimeEnable() &&
m_pParent->IsIndicateEnable() )
{
if( IsDeadly() )
{
pRingIndicate->ChangeAnime( INDICATE_ANIME_DEADLY, 0 );
}
else
{
pRingIndicate->ChangeAnime( INDICATE_ANIME_WAIT, 5 );
}
}
if( m_pParent->IsIndicateEnable() )
{
pRingIndicate->Open();
}
else
{
pRingIndicate->Close( false );
}
}
}
//------------------------------------------------------------------------------
// 通常状態へ
//------------------------------------------------------------------------------
void Shield::_Normal( void )
{
m_State = STATE_NORMAL;
}
//------------------------------------------------------------------------------
// 破損状態へ
//------------------------------------------------------------------------------
void Shield::_Break( void )
{
m_State = STATE_BREAK;
m_BreakCount = m_pParam->BreakTime;
m_InvincibleCount = m_pParam->BreakInvincible;
m_NoMoveCount = 0;
m_SerialDamageCount = 0;
// セクター減損
if( !GetConfig()->GetDebugInfo().bShieldInfinite )
{
DecreaseZero( m_Sector, 1 );
Increase( m_BreakNum, m_pParam->BreakNumMax, 1 );
}
m_Shield = IsDeadly()? 0.0f : SHIELD_MAX;
// エフェクト発生
EffectDelete( m_pEffect );
m_pEffect = m_pParent->CreateEffect( m_pParam->BreakEffectName, m_pParent->GetMatrix() );
// アイテム発生
m_pParent->GetWorld()->GetItemManager()->AppearItem( m_pParam->BreakItemNum, m_pParent->GetPos(), m_pParam->ItemSpeed );
// スコア通知
m_pParent->GetWorld()->GetScoreManager()->OnEvent( SCORE_EVENT_BREAK );
}
//------------------------------------------------------------------------------
// シールドの残量割合を得る
//------------------------------------------------------------------------------
float Shield::_GetShieldRate( void ) const
{
return m_Shield / SHIELD_MAX;
}
//------------------------------------------------------------------------------
// シールド回復の残量割合を得る
//------------------------------------------------------------------------------
float Shield::_GetRecoveryRate( void ) const
{
return m_Recovery / SHIELD_MAX;
} | [
"[email protected]"
] | |
a56628bd449d92ffa9084db6cb58837de1430b5c | 1e2f712865132a9ebb1c485db825e055ff7de293 | /texture.cpp | bc6f0b8c27b04f24380088748dbb403482f1f4fa | [] | no_license | jto-daA/Old-Demo-Game-Engine-circa-2001- | 1decde4ae6159880184016f4abc97d851e6fa61d | edb02d16e09c87e444c40b2590f596d91afdd8d7 | refs/heads/master | 2021-01-25T06:06:18.514689 | 2016-06-21T23:59:26 | 2016-06-21T23:59:26 | 33,963,377 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,872 | cpp | /***********************************************
* $author: javery
* $date : 26 Nov 01
* $descp : texture management struct/routines.
* $path : C:\Program Files\Microsoft Visual Studio\MyProjects\KaosDemoEngine\texture.h
* $ver : 0.0.0
***********************************************/
#include <stdio.h>
#include <windows.h>
#include <gl/gl.h>
#include <gl/glu.h>
#include <gl/glaux.h>
#include "texture.h"
static k_word textureCount=0;
static void R_Tx_InitTexture( GLenum mmFilter , GLenum mxFilter , k_word textureRef )
{
glBindTexture( GL_TEXTURE_2D , textureRef );
glTexParameteri( GL_TEXTURE_2D , GL_TEXTURE_MIN_FILTER , mmFilter );
glTexParameteri( GL_TEXTURE_2D , GL_TEXTURE_MAG_FILTER , mxFilter );
}
k_word R_Tx_LoadTexture( char* sFileName )
{
AUX_RGBImageRec* texImage;
FILE* pTexFile = fopen( sFileName , "rb" );
if( pTexFile == NULL )
{
MessageBox( NULL , "Unable to load specified texture file","R_Tx_LoadTexture fault", MB_OK | MB_ICONEXCLAMATION );
PostQuitMessage( 0 );
return 0xFFFF;
}
else
{
texImage = auxDIBImageLoad( sFileName );
}
R_Tx_InitTexture( GL_LINEAR , GL_LINEAR , textureCount );
gluBuild2DMipmaps( GL_TEXTURE_2D,
3,
texImage->sizeX,
texImage->sizeY,
GL_RGB,
GL_UNSIGNED_BYTE,
texImage->data );
textureCount++;
return textureCount-1;
}
void R_Tx_UseTexture( k_word texIndex )
{
glBindTexture( GL_TEXTURE_2D , texIndex );
}
//
// Builds a texture from the passed byte buffer
//
k_word R_Tx_BuildTexture( k_word xDimen , k_word yDimen , k_byte depth , void* byteBuffer )
{
R_Tx_InitTexture( GL_LINEAR , GL_LINEAR , textureCount );
glTexImage2D( GL_TEXTURE_2D ,
0 ,
3 ,
xDimen,
yDimen,
0,
GL_COLOR_INDEX,
GL_BYTE,
byteBuffer );
textureCount++;
return textureCount-1;
} | [
"[email protected]"
] | |
8aaea15b508ca807c75b1be1f4b8ecdcee329de0 | 8b682b91b3d06afc403de23bf2c93c9ceacbeab7 | /pol-core/pol/miscmsg.cpp | 0cc103c6bb558a131ea96c99a85bcebdf97f25bb | [] | no_license | jagarop/POL_099b | 1803f3e369c2c1500f601f736059fe2908da3711 | 6a5df8893b6f38ff57a42412420813f3a3b83227 | refs/heads/master | 2021-07-16T16:33:19.905934 | 2015-01-08T01:44:03 | 2015-01-08T01:44:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 17,338 | cpp | /*
History
=======
2005/11/25 MuadDib: Added PKTBI_BF::TYPE_SESPAM: to do away with spam.
2005/11/23 MuadDib: Altered handle_mode_set for 0x72 Packet. Nows reads
from combat.cfg for warmode_wait object. Sends the
0x77 Packet and returns 0 when out of timer.
2005/12/09 MuadDib: Added TYPE_CLIENT_LANGUAGE for setting member uclang.
2006/05/24 Shinigami: Added PKTBI_BF::TYPE_CHARACTER_RACE_CHANGER to support Elfs
2006/05/30 Shinigami: Changed params of character_race_changer_handler()
2009/07/23 MuadDib: updates for new Enum::Packet IDs
2009/08/14 Turley: Added PKTBI_BF::TYPE_SCREEN_SIZE & TYPE_CLOSED_STATUS_GUMP (anti spam)
2009/09/03 MuadDib: Relocation of account related cpp/h
2009/09/03 MuadDib: Relocation of multi related cpp/h
2009/09/06 Turley: Changed Version checks to bitfield client->ClientType
Added 0xE1 packet (UO3D clienttype packet)
2009/11/19 Turley: ssopt.core_sends_season & .core_handled_tags - Tomi
2009/12/03 Turley: toggle gargoyle flying support
Notes
=======
*/
/* MISCMSG.CPP: Miscellaneous message handlers. Handlers shouldn't stay here long,
only until they find a better home - but this is better than putting them in POL.CPP. */
#include "multi/customhouses.h"
#include "multi/multi.h"
#include "mobile/charactr.h"
#include "accounts/account.h"
#include "network/client.h"
#include "network/msghandl.h"
#include "fnsearch.h"
#include "cmbtcfg.h"
#include "pktboth.h"
#include "pktin.h"
#include "spells.h"
#include "tooltips.h"
#include "globals/uvars.h"
#include "ufunc.h"
#include "uoscrobj.h"
#include "sockio.h"
#include "scrstore.h"
#include "polcfg.h"
#include "../clib/clib.h"
#include "../clib/endian.h"
#include "../clib/fdump.h"
#include "../clib/logfacility.h"
#include "../clib/strutil.h"
#include "../clib/stlutil.h"
#include "../clib/unicode.h"
#include "../plib/systemstate.h"
#include <cstddef>
namespace Pol {
namespace Module {
void character_race_changer_handler( Network::Client* client, Core::PKTBI_BF* msg );
}
namespace Core {
using namespace Network;
void handle_unknown_packet( Client* client );
void party_cmd_handler( Client* client, PKTBI_BF* msg );
void OnGuildButton( Client* client );
void OnQuestButton( Client* client );
void OnChatButton( Client* client );
void handle_bulletin_boards( Client* client, PKTBI_71* /*msg*/ )
{
handle_unknown_packet( client );
}
void handle_mode_set( Client *client, PKTBI_72 *msg )
{
if ( client->chr->warmode_wait > read_gameclock() )
{
send_move( client, client->chr );
return;
}
else
{
client->chr->warmode_wait = read_gameclock() + settingsManager.combat_config.warmode_delay;
}
bool msg_warmode = msg->warmode ? true : false;
// FIXME: Should reply with 0x77 packet!? (so says various docs!) [TJ]
transmit( client, msg, sizeof *msg );
client->chr->set_warmode( msg_warmode );
}
void handle_rename_char( Client* client, PKTIN_75* msg )
{
Mobile::Character* chr = find_character( cfBEu32( msg->serial ) );
if ( chr != NULL )
{
if ( client->chr->can_rename( chr ) )
{
msg->name[sizeof msg->name - 1] = '\0';
// check for legal characters
for ( char* p = msg->name; *p; p++ )
{
// only allow: a-z, A-Z & spaces
if ( *p != ' ' && !isalpha( *p ) )
{
fmt::Writer tmp;
tmp.Format( "Client#{} (account {}) attempted an invalid rename (packet 0x{:X}):\n{}\n" )
<< client->instance_
<< ( ( client->acct != NULL ) ? client->acct->name() : "unknown" )
<< (int)msg->msgtype << msg->name;
Clib::fdump( tmp, msg->name, static_cast<int>( strlen( msg->name ) ) );
POLLOG_INFO << tmp.c_str();
*p = '\0';
send_sysmessage( client, "Invalid name!" );
return; //dave 12/26 if invalid name, do not apply to chr!
}
}
chr->setname( msg->name );
}
else
{
send_sysmessage( client, "I can't rename that." );
}
}
else
{
send_sysmessage( client, "I can't find that." );
}
}
void handle_msg_B5( Client* client, PKTIN_B5* /*msg*/ )
{
OnChatButton( client );
}
void handle_char_profile_request( Client* client, PKTBI_B8_IN* msg )
{
ref_ptr<Bscript::EScriptProgram> prog = find_script( "misc/charprofile",
true,
Plib::systemstate.config.cache_interactive_scripts );
if ( prog.get() != NULL )
{
Mobile::Character* mobile;
if ( msg->mode == msg->MODE_REQUEST )
{
mobile = system_find_mobile( cfBEu32( msg->profile_request.serial ) );
if (mobile == nullptr)
return;
client->chr->start_script( prog.get( ), false, new Module::ECharacterRefObjImp( mobile ), new Bscript::BLong( msg->mode ), new Bscript::BLong( 0 ) );
}
else if ( msg->mode == msg->MODE_UPDATE )
{
mobile = system_find_mobile( cfBEu32( msg->profile_update.serial ) );
if (mobile == nullptr)
return;
u16 * themsg = msg->profile_update.wtext;
int intextlen = ( cfBEu16( msg->msglen ) - 12 ) / sizeof( msg->profile_update.wtext[0] );
int i = 0;
u16 wtextbuf[SPEECH_MAX_LEN];
u32 wtextbuflen;
// Preprocess the text into a sanity-checked, printable form in textbuf
if ( intextlen < 0 )
intextlen = 0;
if ( intextlen > SPEECH_MAX_LEN )
intextlen = SPEECH_MAX_LEN;
wtextbuflen = 0;
for ( i = 0; i < intextlen; i++ )
{
u16 wc = cfBEu16( themsg[i] );
if ( wc == 0 ) break; // quit early on embedded nulls
if ( wc == L'~' ) continue; // skip unprintable tildes.
wtextbuf[wtextbuflen++] = ctBEu16( wc );
}
Bscript::ObjArray* arr;
if ( Clib::convertUCtoArray( wtextbuf, arr, wtextbuflen, true ) ) // convert back with ctBEu16()
client->chr->start_script( prog.get( ), false, new Module::ECharacterRefObjImp( mobile ), new Bscript::BLong( msg->mode ), arr );
}
}
}
void handle_msg_BB( Client* client, PKTBI_BB* /*msg*/ )
{
handle_unknown_packet( client );
}
void handle_client_version( Client* client, PKTBI_BD* msg )
{
u16 len = cfBEu16( msg->msglen ) - 3;
if ( len < 100 )
{
int c = 0;
char ch;
std::string ver2 = "";
while ( c < len )
{
ch = msg->version[c];
if ( ch == 0 ) break; // seems to be null-terminated
ver2 += ch;
++c;
}
client->setversion( ver2 );
VersionDetailStruct vers_det;
client->itemizeclientversion( ver2, vers_det );
client->setversiondetail( vers_det );
if ( client->compareVersion( CLIENT_VER_70331 ) )
client->setClientType( CLIENTTYPE_70331 );
else if ( client->compareVersion( CLIENT_VER_70300 ) )
client->setClientType( CLIENTTYPE_70300 );
else if ( client->compareVersion( CLIENT_VER_70130 ) )
client->setClientType( CLIENTTYPE_70130 );
else if ( client->compareVersion( CLIENT_VER_7090 ) )
client->setClientType( CLIENTTYPE_7090 );
else if ( client->compareVersion( CLIENT_VER_7000 ) )
client->setClientType( CLIENTTYPE_7000 );
else if ( client->compareVersion( CLIENT_VER_60142 ) )
client->setClientType( CLIENTTYPE_60142 );
else if ( client->compareVersion( CLIENT_VER_6017 ) ) //Grid-loc support
client->setClientType( CLIENTTYPE_6017 );
else if ( client->compareVersion( CLIENT_VER_5020 ) )
client->setClientType( CLIENTTYPE_5020 );
else if ( client->compareVersion( CLIENT_VER_5000 ) )
client->setClientType( CLIENTTYPE_5000 );
else if ( client->compareVersion( CLIENT_VER_4070 ) )
client->setClientType( CLIENTTYPE_4070 );
else if ( client->compareVersion( CLIENT_VER_4000 ) )
client->setClientType( CLIENTTYPE_4000 );
if ( settingsManager.ssopt.core_sends_season )
send_season_info( client ); // Scott 10/11/2007 added for login fixes and handling 1.x clients.
// Season info needs to check client version to keep from crashing 1.x
// version not set until shortly after login complete.
//send_feature_enable(client); //dave commented out 8/21/03, unexpected problems with people sending B9 via script with this too.
if ( ( client->UOExpansionFlag & AOS ) )
{
send_object_cache( client, dynamic_cast<const UObject*>( client->chr ) );
}
}
else
{
POLLOG_INFO << "Suspect string length in PKTBI_BD packet: " << len << "\n";
}
}
void ext_stats_in( Client* client, PKTBI_BF* msg )
{
if ( settingsManager.ssopt.core_handled_locks )
{
const Mobile::Attribute *attrib = NULL;
switch ( msg->extstatin.stat )
{
case PKTBI_BF_1A::STAT_STR:
attrib = gamestate.pAttrStrength;
break;
case PKTBI_BF_1A::STAT_DEX:
attrib = gamestate.pAttrDexterity;
break;
case PKTBI_BF_1A::STAT_INT:
attrib = gamestate.pAttrIntelligence;
break;
default: // sent an illegal stat. Should report to console?
return;
}
if ( attrib == NULL ) // there's no attribute for this (?)
return;
u8 state = msg->extstatin.mode;
if ( state > 2 ) // FIXME hard-coded value
return;
client->chr->attribute( attrib->attrid ).lock( state );
}
}
void handle_msg_BF( Client* client, PKTBI_BF* msg )
{
UObject* obj = NULL;
Multi::UMulti* multi = NULL;
Multi::UHouse* house = NULL;
switch ( cfBEu16( msg->subcmd ) )
{
case PKTBI_BF::TYPE_CLIENT_LANGUAGE:
client->chr->uclang = Clib::strlower( msg->client_lang );
break;
case PKTBI_BF::TYPE_REQ_FULL_CUSTOM_HOUSE:
if ( ( client->UOExpansionFlag & AOS ) == 0 )
return;
multi = system_find_multi( cfBEu32( msg->reqfullcustomhouse.house_serial ) );
if ( multi != NULL )
{
house = multi->as_house();
if ( house != NULL )
{
if ( client->UOExpansionFlag & AOS )
{
send_object_cache( client, (UObject*)( house ) );
}
//consider sending working design to certain players, to assist building, or GM help
CustomHousesSendFull( house, client, Multi::HOUSE_DESIGN_CURRENT );
}
}
break;
case PKTBI_BF::TYPE_OBJECT_CACHE:
if ( ( client->UOExpansionFlag & AOS ) == 0 )
return;
obj = system_find_object( cfBEu32( msg->objectcache.serial ) );
if ( obj != NULL )
{
SendAOSTooltip( client, obj );
}
break;
case PKTBI_BF::TYPE_SESPAM:
return;
break;
case PKTBI_BF::TYPE_SPELL_SELECT:
do_cast( client, cfBEu16( msg->spellselect.selected_spell ) );
break;
case PKTBI_BF::TYPE_CHARACTER_RACE_CHANGER:
Module::character_race_changer_handler( client, msg );
break;
case PKTBI_BF::TYPE_PARTY_SYSTEM:
party_cmd_handler( client, msg );
break;
case PKTBI_BF::TYPE_EXTENDED_STATS_IN:
ext_stats_in( client, msg );
break;
case PKTBI_BF::TYPE_CLOSED_STATUS_GUMP:
return;
break;
case PKTBI_BF::TYPE_SCREEN_SIZE:
return;
break;
case PKTBI_BF::TYPE_TOGGLE_FLYING:
if ( client->chr->race == RACE_GARGOYLE )
{
// FIXME: add checks if its possible to stand with new movemode
client->chr->movemode = (MOVEMODE)( client->chr->movemode ^ MOVEMODE_FLY );
send_move_mobile_to_nearby_cansee( client->chr );
send_goxyz( client, client->chr );
}
break;
case PKTBI_BF::TYPE_CLIENTTYPE:
client->UOExpansionFlagClient = ctBEu32( msg->clienttype.clientflag );
break;
default:
handle_unknown_packet( client );
}
}
void handle_unknown_C4( Client* client, PKTOUT_C4* /*msg*/ )
{
handle_unknown_packet( client );
}
void handle_update_range_change( Client* client, PKTBI_C8* /*msg*/ )
{
handle_unknown_packet( client );
}
void handle_allnames( Client *client, PKTBI_98_IN *msg )
{
u32 serial = cfBEu32( msg->serial );
Mobile::Character *the_mob = find_character( serial );
if ( the_mob != NULL )
{
if ( !client->chr->is_visible_to_me( the_mob ) )
{
return;
}
if ( pol_distance( client->chr->x, client->chr->y, the_mob->x, the_mob->y ) > 20 )
{
return;
}
PktHelper::PacketOut<PktOut_98> msgOut;
msgOut->WriteFlipped<u16>( 37u ); // static length
msgOut->Write<u32>( the_mob->serial_ext );
msgOut->Write( the_mob->name().c_str(), 30, false );
msgOut.Send( client );
}
else
{
return;
}
}
void handle_se_object_list( Client* client, PKTBI_D6_IN* msgin )
{
UObject* obj = NULL;
int length = cfBEu16( msgin->msglen ) - 3;
if ( length < 0 || ( length % 4 ) != 0 )
return;
int count = length / 4;
for ( int i = 0; i < count; ++i )
{
obj = system_find_object( cfBEu32( msgin->serials[i].serial ) );
if ( obj != NULL )
SendAOSTooltip( client, obj );
}
}
void handle_ef_seed( Client *client, PKTIN_EF *msg )
{
VersionDetailStruct detail;
detail.major = cfBEu32( msg->ver_Major );
detail.minor = cfBEu32( msg->ver_Minor );
detail.rev = cfBEu32( msg->ver_Revision );
detail.patch = cfBEu32( msg->ver_Patch );
client->setversiondetail( detail );
if ( client->compareVersion( CLIENT_VER_70331 ) )
client->setClientType( CLIENTTYPE_70331 );
else if ( client->compareVersion( CLIENT_VER_70300 ) )
client->setClientType( CLIENTTYPE_70300 );
else if ( client->compareVersion( CLIENT_VER_70130 ) )
client->setClientType( CLIENTTYPE_70130 );
else if ( client->compareVersion( CLIENT_VER_7090 ) )
client->setClientType( CLIENTTYPE_7090 );
else if ( client->compareVersion( CLIENT_VER_7000 ) )
client->setClientType( CLIENTTYPE_7000 );
else if ( client->compareVersion( CLIENT_VER_60142 ) )
client->setClientType( CLIENTTYPE_60142 );
else if ( client->compareVersion( CLIENT_VER_6017 ) ) //Grid-loc support
client->setClientType( CLIENTTYPE_6017 );
else if ( client->compareVersion( CLIENT_VER_5020 ) )
client->setClientType( CLIENTTYPE_5020 );
else if ( client->compareVersion( CLIENT_VER_5000 ) )
client->setClientType( CLIENTTYPE_5000 );
else if ( client->compareVersion( CLIENT_VER_4070 ) )
client->setClientType( CLIENTTYPE_4070 );
else if ( client->compareVersion( CLIENT_VER_4000 ) )
client->setClientType( CLIENTTYPE_4000 );
// detail->patch is since 5.0.7 always numeric, so no need to make it complicated
OSTRINGSTREAM os;
os << detail.major << "." << detail.minor << "." << detail.rev << "." << detail.patch;
client->setversion( OSTRINGSTREAM_STR( os ) );
}
void handle_e1_clienttype( Client *client, PKTIN_E1 *msg )
{
switch ( cfBEu32( msg->clienttype ) )
{
case PKTIN_E1::CLIENTTYPE_KR:
client->setClientType( CLIENTTYPE_UOKR );
break;
case PKTIN_E1::CLIENTTYPE_SA:
client->setClientType( CLIENTTYPE_UOSA );
break;
default:
INFO_PRINT << "Unknown client type send with packet 0xE1 : 0x" << fmt::hexu(static_cast<unsigned long>( cfBEu32( msg->clienttype ) ) ) << "\n";
break;
}
}
void handle_aos_commands( Client *client, PKTBI_D7* msg )
{
//should check if serial is valid? client->chr->serial == msg->serial?
switch ( cfBEu16( msg->subcmd ) )
{
case PKTBI_D7::CUSTOM_HOUSE_BACKUP:
Multi::CustomHousesBackup( msg );
break;
case PKTBI_D7::CUSTOM_HOUSE_RESTORE:
Multi::CustomHousesRestore( msg );
break;
case PKTBI_D7::CUSTOM_HOUSE_COMMIT:
Multi::CustomHousesCommit( msg );
break;
case PKTBI_D7::CUSTOM_HOUSE_ERASE:
Multi::CustomHousesErase( msg );
break;
case PKTBI_D7::CUSTOM_HOUSE_ADD:
Multi::CustomHousesAdd( msg );
break;
case PKTBI_D7::CUSTOM_HOUSE_QUIT:
Multi::CustomHousesQuit( msg );
break;
case PKTBI_D7::CUSTOM_HOUSE_ADD_MULTI:
Multi::CustomHousesAddMulti( msg );
break;
case PKTBI_D7::CUSTOM_HOUSE_SYNCH:
Multi::CustomHousesSynch( msg );
break;
case PKTBI_D7::CUSTOM_HOUSE_CLEAR:
Multi::CustomHousesClear( msg );
break;
case PKTBI_D7::CUSTOM_HOUSE_SELECT_FLOOR:
Multi::CustomHousesSelectFloor( msg );
break;
case PKTBI_D7::CUSTOM_HOUSE_REVERT:
Multi::CustomHousesRevert( msg );
break;
case PKTBI_D7::CUSTOM_HOUSE_SELECT_ROOF:
Multi::CustomHousesRoofSelect( msg );
break;
case PKTBI_D7::CUSTOM_HOUSE_DELETE_ROOF:
Multi::CustomHousesRoofRemove( msg );
break;
case PKTBI_D7::GUILD_BUTTON:
OnGuildButton( client );
break;
case PKTBI_D7::QUEST_BUTTON:
OnQuestButton( client );
break;
//missing combat book abilities
default:
handle_unknown_packet( client );
}
}
void OnGuildButton( Client* client )
{
ref_ptr<Bscript::EScriptProgram> prog = find_script( "misc/guildbutton",
true,
Plib::systemstate.config.cache_interactive_scripts );
if ( prog.get() != NULL )
{
client->chr->start_script( prog.get(), false );
}
}
void OnQuestButton( Client* client )
{
ref_ptr<Bscript::EScriptProgram> prog = find_script( "misc/questbutton",
true,
Plib::systemstate.config.cache_interactive_scripts );
if ( prog.get() != NULL )
{
client->chr->start_script( prog.get(), false );
}
}
void OnChatButton( Client* client )
{
ref_ptr<Bscript::EScriptProgram> prog = find_script( "misc/chatbutton",
true,
Plib::systemstate.config.cache_interactive_scripts );
if ( prog.get() != NULL )
{
client->chr->start_script( prog.get(), false );
}
}
}
} | [
"[email protected]"
] | |
4cf51eb6b3414269e2d390439dfe9fb854c03f76 | f878ac2dafe9b34248e7d1d66f563dbf1cc32a3e | /Win32Application.cpp | 1b2ed7d6f3384131401588bb53319370b394f847 | [] | no_license | AlinMedianu/D3D12HelloProject | 4450bd1bb1a89768c611a8dd7bb8f4d3c179ee46 | 55bd494ed79260a3f5287de29f8cc98a2905375a | refs/heads/main | 2023-08-16T08:26:22.850122 | 2021-09-28T08:08:37 | 2021-09-28T08:08:37 | 411,024,851 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,030 | cpp | //*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
#include "stdafx.h"
#include "Win32Application.h"
HWND Win32Application::m_hwnd = nullptr;
int Win32Application::Run(DXSample* pSample, HINSTANCE hInstance, int nCmdShow)
{
// Parse the command line parameters
int argc;
LPWSTR* argv = CommandLineToArgvW(GetCommandLineW(), &argc);
pSample->ParseCommandLineArgs(argv, argc);
LocalFree(argv);
// Initialize the window class.
WNDCLASSEX windowClass = { 0 };
windowClass.cbSize = sizeof(WNDCLASSEX);
windowClass.style = CS_HREDRAW | CS_VREDRAW;
windowClass.lpfnWndProc = WindowProc;
windowClass.hInstance = hInstance;
windowClass.hCursor = LoadCursor(NULL, IDC_ARROW);
windowClass.lpszClassName = L"DXSampleClass";
RegisterClassEx(&windowClass);
RECT windowRect = { 0, 0, static_cast<LONG>(pSample->GetWidth()), static_cast<LONG>(pSample->GetHeight()) };
AdjustWindowRect(&windowRect, WS_OVERLAPPEDWINDOW, FALSE);
// Create the window and store a handle to it.
m_hwnd = CreateWindow(
windowClass.lpszClassName,
pSample->GetTitle(),
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT,
CW_USEDEFAULT,
windowRect.right - windowRect.left,
windowRect.bottom - windowRect.top,
nullptr, // We have no parent window.
nullptr, // We aren't using menus.
hInstance,
pSample);
// Initialize the sample. OnInit is defined in each child-implementation of DXSample.
pSample->OnInit();
ShowWindow(m_hwnd, nCmdShow);
// Main sample loop.
MSG msg = {};
while (msg.message != WM_QUIT)
{
// Process any messages in the queue.
if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
pSample->OnDestroy();
// Return this part of the WM_QUIT message to Windows.
return static_cast<char>(msg.wParam);
}
// Main message handler for the sample.
LRESULT CALLBACK Win32Application::WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
DXSample* pSample = reinterpret_cast<DXSample*>(GetWindowLongPtr(hWnd, GWLP_USERDATA));
switch (message)
{
case WM_CREATE:
{
// Save the DXSample* passed in to CreateWindow.
LPCREATESTRUCT pCreateStruct = reinterpret_cast<LPCREATESTRUCT>(lParam);
SetWindowLongPtr(hWnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(pCreateStruct->lpCreateParams));
}
return 0;
case WM_KEYDOWN:
if (pSample)
{
pSample->OnKeyDown(static_cast<UINT8>(wParam));
}
return 0;
case WM_KEYUP:
if (pSample)
{
pSample->OnKeyUp(static_cast<UINT8>(wParam));
}
return 0;
case WM_LBUTTONDOWN:
case WM_MBUTTONDOWN:
case WM_RBUTTONDOWN:
pSample->OnMouseDown(wParam, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
return 0;
case WM_LBUTTONUP:
case WM_MBUTTONUP:
case WM_RBUTTONUP:
pSample->OnMouseUp(wParam, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
return 0;
case WM_MOUSEMOVE:
pSample->OnMouseMove(wParam, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
return 0;
case WM_PAINT:
if (pSample)
{
pSample->OnUpdate();
pSample->OnRender();
}
return 0;
case WM_DESTROY:
PostQuitMessage(0);
return 0;
}
// Handle any messages the switch statement didn't.
return DefWindowProc(hWnd, message, wParam, lParam);
}
| [
"[email protected]"
] | |
82b2232b9a0c18944c74525efd84828d23e18bc8 | 5fcacbc63db76625cc60ffc9d6ed58a91f134ea4 | /vxl/vxl-1.13.0/contrib/brl/bseg/boxm/opt/Templates/boxm_scene+boct_tree+short.boxm_rt_sample+float---.cxx | 618990625f717ca7bc62d4eac7714ebaa52fdb8f | [] | no_license | EasonZhu/rcc | c809956eb13fb732d1b2c8035db177991e3530aa | d230b542fa97da22271b200e3be7441b56786091 | refs/heads/master | 2021-01-15T20:28:26.541784 | 2013-05-14T07:18:12 | 2013-05-14T07:18:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 181 | cxx | #include <boxm/boxm_scene.txx>
#include <boct/boct_tree.h>
#include <boxm/opt/boxm_rt_sample.h>
typedef boct_tree<short,boxm_rt_sample<float> > tree;
BOXM_SCENE_INSTANTIATE(tree);
| [
"[email protected]"
] | |
a6119c6283d39969cd50e514d9f71619651dd5cf | c0b0d03afcefe3c259742acfd024db4f63df5a32 | /CAGE/Graphics/UI/Layout.hpp | 8832630c7aad40cfb9f7d949812d28ac649fe503 | [
"MIT"
] | permissive | Mr-1337/CAGE | 49971227f31286d35e2804764880af788dfe7c98 | c45f31e2963e7e364eef0cddee7c8a1e20ec851d | refs/heads/master | 2022-03-09T12:00:56.191992 | 2022-02-20T04:52:56 | 2022-02-20T04:52:56 | 191,666,331 | 0 | 1 | MIT | 2021-06-05T17:38:34 | 2019-06-13T01:07:46 | C | UTF-8 | C++ | false | false | 580 | hpp | #pragma once
#include <GLM/glm/glm.hpp>
#include <string>
namespace cage
{
namespace ui
{
class LayoutGroup;
/*
* Represents a layout configuration for a LayoutGroup. It will automatically position elements in a LayoutGroup and it will resize the LayoutGroup to fit all child elements
*/
class Layout
{
public:
virtual ~Layout() {};
void SetContainer(LayoutGroup* container)
{
m_container = container;
}
virtual void Update() = 0;
virtual std::string GetName() = 0;
protected:
LayoutGroup* m_container;
private:
};
}
} | [
"[email protected]"
] | |
8bd2a35b6d75ff838516b3445812a1074ac47779 | 49d8f4d9372d60d29e69ddafbd42188bd9f2b614 | /src_db/filestore/LongRange.cpp | 32292e305cf5fb75cb914bac44e6b853a23e1431 | [
"MIT"
] | permissive | greg2git/codablecash | 9af29969f1392c56141fdc2f07c8025375b66b4d | fe8099ef9ffa498b5b64636a2c0a06af465c2ecf | refs/heads/master | 2021-02-07T05:12:47.697990 | 2020-02-23T07:37:53 | 2020-02-23T07:37:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,991 | cpp | /*
* LongRange.cpp
*
* Created on: 2018/05/18
* Author: iizuka
*/
#include "filestore/LongRange.h"
#include "debug/debugMacros.h"
#include "base_io/ByteBuffer.h"
namespace alinous {
LongRange::LongRange(const LongRange* base) noexcept {
this->min = base->min;
this->max = base->max;
}
LongRange::LongRange(uint64_t min, uint64_t max) noexcept {
this->min = min;
this->max = max;
}
LongRange::~LongRange() {
}
uint64_t LongRange::width() noexcept {
return this->max - this->min + 1;
}
bool LongRange::hasNext(uint64_t value) const noexcept {
return this->max > value;
}
uint64_t LongRange::getMin() const noexcept {
return this->min;
}
void LongRange::setMin(uint64_t min) noexcept {
this->min = min;
assert(this->min <= this->max);
}
uint64_t LongRange::getMax() const noexcept {
return this->max;
}
void LongRange::setMax(uint64_t max) noexcept {
this->max = max;
assert(this->min <= this->max);
}
int LongRange::compare(uint64_t value) const noexcept {
if(min <= value && value <= max){
return 0;
}
if(min > value){
return 1;
}
return -1;
}
bool LongRange::removeLow(uint64_t value) noexcept {
assert(this->min <= value);
//if(this->min == this->max && this->min){
// return true;
//}
this->min = value + 1;
return !(this->min <= this->max);
}
bool LongRange::removeHigh(uint64_t value) noexcept {
assert(this->max >= value);
//if(this->min == this->max && this->min){
// return true;
//}
this->max = value - 1;
return !(this->min <= this->max);
}
int LongRange::binarySize() noexcept {
return 8 + 8;
}
void LongRange::toBinary(ByteBuffer* buff) noexcept{
buff->putLong(this->min);
buff->putLong(this->max);
}
LongRange* LongRange::fromBinary(ByteBuffer* buff) noexcept {
uint64_t min = buff->getLong();
uint64_t max = buff->getLong();
return new LongRange(min, max);
}
bool LongRange::equals(LongRange* other) noexcept {
return this->min == other->min && this->max == other->max;
}
} /* namespace alinous */
| [
"[email protected]"
] | |
128d19f89694c89c9108c7caca5d297de1096fe4 | 0230f15c43f6abf35c1967a8fc1c0de3ef7e1a38 | /semana3/atividade/cliente.cpp | c6e0a55d74a446657a785c05ddda19b857370324 | [
"MIT"
] | permissive | luisrodrigoads/objetosDistribuidos | 1f70be1ac388063ff2966d9573e051d7d5e9ec5d | a00b9c91c0c7f7f21dab6450d2fe756925cdda2d | refs/heads/main | 2023-07-17T10:39:24.930626 | 2021-08-30T19:35:13 | 2021-08-30T19:35:13 | 252,364,824 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 2,244 | cpp | #include <windows.h>
#include <winsock.h>
#include <stdio.h>
#include <string.h>
#define REMOTE_SERVER_PORT 2018
#define MSG_LENGTH 4096
#define SERVIDOR "127.0.0.1"
FILE *fileSendTo, *fileReceiveFrom;
int main() {
int sd, msgReceiveFromServer, msgSendToServer, serverLength;
struct sockaddr_in clientAddress;
struct sockaddr_in remoteServerAddress;
WSADATA wsaData;
LPHOSTENT lpHostEntry;
char msg[MSG_LENGTH];
WSAStartup(MAKEWORD(2,1),&wsaData); // inicia o winsock
lpHostEntry = gethostbyname(SERVIDOR);
/*
Inicia socket...
padrão -> (familia protocolo, tipo, protocolo)
AF_INET -> familia ipv4
SOCK_DGRAM -> comunicação udp
*/
sd = socket(AF_INET,SOCK_DGRAM,0);
if(sd < 0) {
printf("Nao foi possivel criar o socket com o servidor %s:\n",SERVIDOR);
exit(1);
}
/* bind (associação do socket a uma porta) */
clientAddress.sin_family = AF_INET;
clientAddress.sin_addr.s_addr = htonl(INADDR_ANY);
clientAddress.sin_port = htons(0);
remoteServerAddress.sin_family = AF_INET;
remoteServerAddress.sin_addr = *((LPIN_ADDR)*lpHostEntry->h_addr_list);
remoteServerAddress.sin_port = htons(REMOTE_SERVER_PORT);
if((fileSendTo = fopen("Arquivo.txt","r+")) == NULL){
printf("Erro ao abrir Arquivo.txt!");
}else{
fileReceiveFrom = fopen("ArquivoRetorno.txt","w+");
while(!feof(fileSendTo)){
fgets(msg, MSG_LENGTH, fileSendTo);
msgSendToServer = sendto(sd, msg, strlen(msg) + 1, 0, (LPSOCKADDR) &remoteServerAddress, sizeof(struct sockaddr));
if(msgSendToServer < 0){
printf("Erro ao enviar a mensagem\n");
closesocket(sd);
exit(1);
}
printf("Mensagem enviada do cliente para o servidor ->\n %s\n", msg);
memset(msg, 0, strlen(msg));
serverLength = sizeof(remoteServerAddress);
msgReceiveFromServer = recvfrom(sd, msg, MSG_LENGTH, 0, (struct sockaddr *) &remoteServerAddress, &serverLength);
if(msgReceiveFromServer < 0){
printf("Erro ao receber dados\n");
continue;
}
printf("Mensagem recebida do servidor ->\n %s\n",msg);
fprintf(fileReceiveFrom, "%s", msg);
memset(msg, 0, strlen(msg));
}
fclose(fileSendTo);
fclose(fileReceiveFrom);
}
system("pause");
closesocket(sd);
return 1;
}
| [
"[email protected]"
] | |
46893073bb2adc4a3ffb3b30cd8715c7828d449e | 18cd709cad01d13f06051e22a53111b4318a1ce2 | /src/qt/sendcoinsdialog.cpp | defb919654e1e9bda26bdf3c9eaed966ba9865eb | [
"MIT"
] | permissive | NodeHost/NODECore | 8e0ba2794e6bd23af4e5c2126335c25a9c6e27ac | 527a1eee6f1a9992f0d3f1cb9ffecf67e0211b43 | refs/heads/master | 2020-04-02T09:04:44.575856 | 2019-02-07T05:02:29 | 2019-02-07T05:02:29 | 154,274,665 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 38,806 | cpp | // Copyright (c) 2011-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The PIVX developers
// Copyright (c) 2018-2019 The NodeHost developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "sendcoinsdialog.h"
#include "ui_sendcoinsdialog.h"
#include "addresstablemodel.h"
#include "askpassphrasedialog.h"
#include "bitcoinunits.h"
#include "clientmodel.h"
#include "coincontroldialog.h"
#include "guiutil.h"
#include "optionsmodel.h"
#include "sendcoinsentry.h"
#include "walletmodel.h"
#include "base58.h"
#include "coincontrol.h"
#include "ui_interface.h"
#include "utilmoneystr.h"
#include "wallet.h"
#include <QMessageBox>
#include <QScrollBar>
#include <QSettings>
#include <QTextDocument>
SendCoinsDialog::SendCoinsDialog(QWidget* parent) : QDialog(parent, Qt::WindowSystemMenuHint | Qt::WindowTitleHint | Qt::WindowCloseButtonHint),
ui(new Ui::SendCoinsDialog),
clientModel(0),
model(0),
fNewRecipientAllowed(true),
fFeeMinimized(true)
{
ui->setupUi(this);
#ifdef Q_OS_MAC // Icons on push buttons are very uncommon on Mac
ui->addButton->setIcon(QIcon());
ui->clearButton->setIcon(QIcon());
ui->sendButton->setIcon(QIcon());
#endif
GUIUtil::setupAddressWidget(ui->lineEditCoinControlChange, this);
addEntry();
connect(ui->addButton, SIGNAL(clicked()), this, SLOT(addEntry()));
connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear()));
// Coin Control
connect(ui->pushButtonCoinControl, SIGNAL(clicked()), this, SLOT(coinControlButtonClicked()));
connect(ui->checkBoxCoinControlChange, SIGNAL(stateChanged(int)), this, SLOT(coinControlChangeChecked(int)));
connect(ui->lineEditCoinControlChange, SIGNAL(textEdited(const QString&)), this, SLOT(coinControlChangeEdited(const QString&)));
// UTXO Splitter
connect(ui->splitBlockCheckBox, SIGNAL(stateChanged(int)), this, SLOT(splitBlockChecked(int)));
connect(ui->splitBlockLineEdit, SIGNAL(textChanged(const QString&)), this, SLOT(splitBlockLineEditChanged(const QString&)));
// NodeHost specific
QSettings settings;
if (!settings.contains("bUseSwiftTX"))
settings.setValue("bUseSwiftTX", false);
bool useSwiftTX = settings.value("bUseSwiftTX").toBool();
if (fLiteMode) {
ui->checkSwiftTX->setVisible(false);
CoinControlDialog::coinControl->useSwiftTX = false;
} else {
ui->checkSwiftTX->setChecked(useSwiftTX);
CoinControlDialog::coinControl->useSwiftTX = useSwiftTX;
}
connect(ui->checkSwiftTX, SIGNAL(stateChanged(int)), this, SLOT(updateSwiftTX()));
// Coin Control: clipboard actions
QAction* clipboardQuantityAction = new QAction(tr("Copy quantity"), this);
QAction* clipboardAmountAction = new QAction(tr("Copy amount"), this);
QAction* clipboardFeeAction = new QAction(tr("Copy fee"), this);
QAction* clipboardAfterFeeAction = new QAction(tr("Copy after fee"), this);
QAction* clipboardBytesAction = new QAction(tr("Copy bytes"), this);
QAction* clipboardPriorityAction = new QAction(tr("Copy priority"), this);
QAction* clipboardLowOutputAction = new QAction(tr("Copy dust"), this);
QAction* clipboardChangeAction = new QAction(tr("Copy change"), this);
connect(clipboardQuantityAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardQuantity()));
connect(clipboardAmountAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardAmount()));
connect(clipboardFeeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardFee()));
connect(clipboardAfterFeeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardAfterFee()));
connect(clipboardBytesAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardBytes()));
connect(clipboardPriorityAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardPriority()));
connect(clipboardLowOutputAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardLowOutput()));
connect(clipboardChangeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardChange()));
ui->labelCoinControlQuantity->addAction(clipboardQuantityAction);
ui->labelCoinControlAmount->addAction(clipboardAmountAction);
ui->labelCoinControlFee->addAction(clipboardFeeAction);
ui->labelCoinControlAfterFee->addAction(clipboardAfterFeeAction);
ui->labelCoinControlBytes->addAction(clipboardBytesAction);
ui->labelCoinControlPriority->addAction(clipboardPriorityAction);
ui->labelCoinControlLowOutput->addAction(clipboardLowOutputAction);
ui->labelCoinControlChange->addAction(clipboardChangeAction);
// init transaction fee section
if (!settings.contains("fFeeSectionMinimized"))
settings.setValue("fFeeSectionMinimized", true);
if (!settings.contains("nFeeRadio") && settings.contains("nTransactionFee") && settings.value("nTransactionFee").toLongLong() > 0) // compatibility
settings.setValue("nFeeRadio", 1); // custom
if (!settings.contains("nFeeRadio"))
settings.setValue("nFeeRadio", 0); // recommended
if (!settings.contains("nCustomFeeRadio") && settings.contains("nTransactionFee") && settings.value("nTransactionFee").toLongLong() > 0) // compatibility
settings.setValue("nCustomFeeRadio", 1); // total at least
if (!settings.contains("nCustomFeeRadio"))
settings.setValue("nCustomFeeRadio", 0); // per kilobyte
if (!settings.contains("nSmartFeeSliderPosition"))
settings.setValue("nSmartFeeSliderPosition", 0);
if (!settings.contains("nTransactionFee"))
settings.setValue("nTransactionFee", (qint64)DEFAULT_TRANSACTION_FEE);
if (!settings.contains("fPayOnlyMinFee"))
settings.setValue("fPayOnlyMinFee", false);
if (!settings.contains("fSendFreeTransactions"))
settings.setValue("fSendFreeTransactions", false);
ui->groupFee->setId(ui->radioSmartFee, 0);
ui->groupFee->setId(ui->radioCustomFee, 1);
ui->groupFee->button((int)std::max(0, std::min(1, settings.value("nFeeRadio").toInt())))->setChecked(true);
ui->groupCustomFee->setId(ui->radioCustomPerKilobyte, 0);
ui->groupCustomFee->setId(ui->radioCustomAtLeast, 1);
ui->groupCustomFee->button((int)std::max(0, std::min(1, settings.value("nCustomFeeRadio").toInt())))->setChecked(true);
ui->sliderSmartFee->setValue(settings.value("nSmartFeeSliderPosition").toInt());
ui->customFee->setValue(settings.value("nTransactionFee").toLongLong());
ui->checkBoxMinimumFee->setChecked(settings.value("fPayOnlyMinFee").toBool());
ui->checkBoxFreeTx->setChecked(settings.value("fSendFreeTransactions").toBool());
minimizeFeeSection(settings.value("fFeeSectionMinimized").toBool());
// If SwiftTX activated hide button 'Choose'. Show otherwise.
ui->buttonChooseFee->setVisible(!useSwiftTX);
}
void SendCoinsDialog::setClientModel(ClientModel* clientModel)
{
this->clientModel = clientModel;
if (clientModel) {
connect(clientModel, SIGNAL(numBlocksChanged(int)), this, SLOT(updateSmartFeeLabel()));
}
}
void SendCoinsDialog::setModel(WalletModel* model)
{
this->model = model;
if (model && model->getOptionsModel()) {
for (int i = 0; i < ui->entries->count(); ++i) {
SendCoinsEntry* entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
if (entry) {
entry->setModel(model);
}
}
setBalance(model->getBalance(), model->getUnconfirmedBalance(), model->getImmatureBalance(),
model->getWatchBalance(), model->getWatchUnconfirmedBalance(), model->getWatchImmatureBalance());
connect(model, SIGNAL(balanceChanged(CAmount, CAmount, CAmount, CAmount, CAmount, CAmount)), this,
SLOT(setBalance(CAmount, CAmount, CAmount, CAmount, CAmount, CAmount)));
connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
updateDisplayUnit();
// Coin Control
connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(coinControlUpdateLabels()));
connect(model->getOptionsModel(), SIGNAL(coinControlFeaturesChanged(bool)), this, SLOT(coinControlFeatureChanged(bool)));
ui->frameCoinControl->setVisible(model->getOptionsModel()->getCoinControlFeatures());
coinControlUpdateLabels();
// fee section
connect(ui->sliderSmartFee, SIGNAL(valueChanged(int)), this, SLOT(updateSmartFeeLabel()));
connect(ui->sliderSmartFee, SIGNAL(valueChanged(int)), this, SLOT(updateGlobalFeeVariables()));
connect(ui->sliderSmartFee, SIGNAL(valueChanged(int)), this, SLOT(coinControlUpdateLabels()));
connect(ui->groupFee, SIGNAL(buttonClicked(int)), this, SLOT(updateFeeSectionControls()));
connect(ui->groupFee, SIGNAL(buttonClicked(int)), this, SLOT(updateGlobalFeeVariables()));
connect(ui->groupFee, SIGNAL(buttonClicked(int)), this, SLOT(coinControlUpdateLabels()));
connect(ui->groupCustomFee, SIGNAL(buttonClicked(int)), this, SLOT(updateGlobalFeeVariables()));
connect(ui->groupCustomFee, SIGNAL(buttonClicked(int)), this, SLOT(coinControlUpdateLabels()));
connect(ui->customFee, SIGNAL(valueChanged()), this, SLOT(updateGlobalFeeVariables()));
connect(ui->customFee, SIGNAL(valueChanged()), this, SLOT(coinControlUpdateLabels()));
connect(ui->checkBoxMinimumFee, SIGNAL(stateChanged(int)), this, SLOT(setMinimumFee()));
connect(ui->checkBoxMinimumFee, SIGNAL(stateChanged(int)), this, SLOT(updateFeeSectionControls()));
connect(ui->checkBoxMinimumFee, SIGNAL(stateChanged(int)), this, SLOT(updateGlobalFeeVariables()));
connect(ui->checkBoxMinimumFee, SIGNAL(stateChanged(int)), this, SLOT(coinControlUpdateLabels()));
connect(ui->checkBoxFreeTx, SIGNAL(stateChanged(int)), this, SLOT(updateGlobalFeeVariables()));
connect(ui->checkBoxFreeTx, SIGNAL(stateChanged(int)), this, SLOT(coinControlUpdateLabels()));
ui->customFee->setSingleStep(CWallet::minTxFee.GetFeePerK());
updateFeeSectionControls();
updateMinFeeLabel();
updateSmartFeeLabel();
updateGlobalFeeVariables();
}
}
SendCoinsDialog::~SendCoinsDialog()
{
QSettings settings;
settings.setValue("fFeeSectionMinimized", fFeeMinimized);
settings.setValue("nFeeRadio", ui->groupFee->checkedId());
settings.setValue("nCustomFeeRadio", ui->groupCustomFee->checkedId());
settings.setValue("nSmartFeeSliderPosition", ui->sliderSmartFee->value());
settings.setValue("nTransactionFee", (qint64)ui->customFee->value());
settings.setValue("fPayOnlyMinFee", ui->checkBoxMinimumFee->isChecked());
settings.setValue("fSendFreeTransactions", ui->checkBoxFreeTx->isChecked());
delete ui;
}
void SendCoinsDialog::on_sendButton_clicked()
{
if (!model || !model->getOptionsModel())
return;
QList<SendCoinsRecipient> recipients;
bool valid = true;
for (int i = 0; i < ui->entries->count(); ++i) {
SendCoinsEntry* entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
//UTXO splitter - address should be our own
CBitcoinAddress address = entry->getValue().address.toStdString();
if (!model->isMine(address) && ui->splitBlockCheckBox->checkState() == Qt::Checked) {
CoinControlDialog::coinControl->fSplitBlock = false;
ui->splitBlockCheckBox->setCheckState(Qt::Unchecked);
QMessageBox::warning(this, tr("Send Coins"),
tr("The split block tool does not work when sending to outside addresses. Try again."),
QMessageBox::Ok, QMessageBox::Ok);
return;
}
if (entry) {
if (entry->validate()) {
recipients.append(entry->getValue());
} else {
valid = false;
}
}
}
if (!valid || recipients.isEmpty()) {
return;
}
//set split block in model
CoinControlDialog::coinControl->fSplitBlock = ui->splitBlockCheckBox->checkState() == Qt::Checked;
if (ui->entries->count() > 1 && ui->splitBlockCheckBox->checkState() == Qt::Checked) {
CoinControlDialog::coinControl->fSplitBlock = false;
ui->splitBlockCheckBox->setCheckState(Qt::Unchecked);
QMessageBox::warning(this, tr("Send Coins"),
tr("The split block tool does not work with multiple addresses. Try again."),
QMessageBox::Ok, QMessageBox::Ok);
return;
}
if (CoinControlDialog::coinControl->fSplitBlock)
CoinControlDialog::coinControl->nSplitBlock = int(ui->splitBlockLineEdit->text().toInt());
QString strFunds = "";
QString strFee = "";
recipients[0].inputType = ALL_COINS;
if (ui->checkSwiftTX->isChecked()) {
recipients[0].useSwiftTX = true;
strFunds += " ";
strFunds += tr("using SwiftTX");
} else {
recipients[0].useSwiftTX = false;
}
// Format confirmation message
QStringList formatted;
foreach (const SendCoinsRecipient& rcp, recipients) {
// generate bold amount string
QString amount = "<b>" + BitcoinUnits::formatHtmlWithUnit(model->getOptionsModel()->getDisplayUnit(), rcp.amount);
amount.append("</b> ").append(strFunds);
// generate monospace address string
QString address = "<span style='font-family: monospace;'>" + rcp.address;
address.append("</span>");
QString recipientElement;
if (!rcp.paymentRequest.IsInitialized()) // normal payment
{
if (rcp.label.length() > 0) // label with address
{
recipientElement = tr("%1 to %2").arg(amount, GUIUtil::HtmlEscape(rcp.label));
recipientElement.append(QString(" (%1)").arg(address));
} else // just address
{
recipientElement = tr("%1 to %2").arg(amount, address);
}
} else if (!rcp.authenticatedMerchant.isEmpty()) // secure payment request
{
recipientElement = tr("%1 to %2").arg(amount, GUIUtil::HtmlEscape(rcp.authenticatedMerchant));
} else // insecure payment request
{
recipientElement = tr("%1 to %2").arg(amount, address);
}
if (CoinControlDialog::coinControl->fSplitBlock) {
recipientElement.append(tr(" split into %1 outputs using the UTXO splitter.").arg(CoinControlDialog::coinControl->nSplitBlock));
}
formatted.append(recipientElement);
}
fNewRecipientAllowed = false;
// request unlock only if was locked or unlocked for staking:
// this way we let users unlock by walletpassphrase or by menu
// and make many transactions while unlocking through this dialog
// will call relock
WalletModel::EncryptionStatus encStatus = model->getEncryptionStatus();
if (encStatus == model->Locked || encStatus == model->UnlockedForStakingOnly) {
WalletModel::UnlockContext ctx(model->requestUnlock(AskPassphraseDialog::Context::Send_NODE, true));
if (!ctx.isValid()) {
// Unlock wallet was cancelled
fNewRecipientAllowed = true;
return;
}
send(recipients, strFee, formatted);
return;
}
// already unlocked or not encrypted at all
send(recipients, strFee, formatted);
}
void SendCoinsDialog::send(QList<SendCoinsRecipient> recipients, QString strFee, QStringList formatted)
{
// prepare transaction for getting txFee earlier
WalletModelTransaction currentTransaction(recipients);
WalletModel::SendCoinsReturn prepareStatus;
if (model->getOptionsModel()->getCoinControlFeatures()) // coin control enabled
prepareStatus = model->prepareTransaction(currentTransaction, CoinControlDialog::coinControl);
else
prepareStatus = model->prepareTransaction(currentTransaction);
// process prepareStatus and on error generate message shown to user
processSendCoinsReturn(prepareStatus,
BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), currentTransaction.getTransactionFee()), true);
if (prepareStatus.status != WalletModel::OK) {
fNewRecipientAllowed = true;
return;
}
CAmount txFee = currentTransaction.getTransactionFee();
QString questionString = tr("Are you sure you want to send?");
questionString.append("<br /><br />%1");
if (txFee > 0) {
// append fee string if a fee is required
questionString.append("<hr /><span style='color:red;'>");
questionString.append(BitcoinUnits::formatHtmlWithUnit(model->getOptionsModel()->getDisplayUnit(), txFee));
questionString.append("</span> ");
questionString.append(tr("are added as transaction fee"));
questionString.append(" ");
questionString.append(strFee);
// append transaction size
questionString.append(" (" + QString::number((double)currentTransaction.getTransactionSize() / 1000) + " kB)");
}
// add total amount in all subdivision units
questionString.append("<hr />");
CAmount totalAmount = currentTransaction.getTotalTransactionAmount() + txFee;
QStringList alternativeUnits;
foreach (BitcoinUnits::Unit u, BitcoinUnits::availableUnits()) {
if (u != model->getOptionsModel()->getDisplayUnit())
alternativeUnits.append(BitcoinUnits::formatHtmlWithUnit(u, totalAmount));
}
// Show total amount + all alternative units
questionString.append(tr("Total Amount = <b>%1</b><br />= %2")
.arg(BitcoinUnits::formatHtmlWithUnit(model->getOptionsModel()->getDisplayUnit(), totalAmount))
.arg(alternativeUnits.join("<br />= ")));
// Limit number of displayed entries
int messageEntries = formatted.size();
int displayedEntries = 0;
for (int i = 0; i < formatted.size(); i++) {
if (i >= MAX_SEND_POPUP_ENTRIES) {
formatted.removeLast();
i--;
} else {
displayedEntries = i + 1;
}
}
questionString.append("<hr />");
questionString.append(tr("<b>(%1 of %2 entries displayed)</b>").arg(displayedEntries).arg(messageEntries));
// Display message box
QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm send coins"),
questionString.arg(formatted.join("<br />")),
QMessageBox::Yes | QMessageBox::Cancel,
QMessageBox::Cancel);
if (retval != QMessageBox::Yes) {
fNewRecipientAllowed = true;
return;
}
// now send the prepared transaction
WalletModel::SendCoinsReturn sendStatus = model->sendCoins(currentTransaction);
// process sendStatus and on error generate message shown to user
processSendCoinsReturn(sendStatus);
if (sendStatus.status == WalletModel::OK) {
accept();
CoinControlDialog::coinControl->UnSelectAll();
coinControlUpdateLabels();
}
fNewRecipientAllowed = true;
}
void SendCoinsDialog::clear()
{
// Remove entries until only one left
while (ui->entries->count()) {
ui->entries->takeAt(0)->widget()->deleteLater();
}
addEntry();
updateTabsAndLabels();
}
void SendCoinsDialog::reject()
{
clear();
}
void SendCoinsDialog::accept()
{
clear();
}
SendCoinsEntry* SendCoinsDialog::addEntry()
{
SendCoinsEntry* entry = new SendCoinsEntry(this);
entry->setModel(model);
ui->entries->addWidget(entry);
connect(entry, SIGNAL(removeEntry(SendCoinsEntry*)), this, SLOT(removeEntry(SendCoinsEntry*)));
connect(entry, SIGNAL(payAmountChanged()), this, SLOT(coinControlUpdateLabels()));
updateTabsAndLabels();
// Focus the field, so that entry can start immediately
entry->clear();
entry->setFocus();
ui->scrollAreaWidgetContents->resize(ui->scrollAreaWidgetContents->sizeHint());
qApp->processEvents();
QScrollBar* bar = ui->scrollArea->verticalScrollBar();
if (bar)
bar->setSliderPosition(bar->maximum());
return entry;
}
void SendCoinsDialog::updateTabsAndLabels()
{
setupTabChain(0);
coinControlUpdateLabels();
}
void SendCoinsDialog::removeEntry(SendCoinsEntry* entry)
{
entry->hide();
// If the last entry is about to be removed add an empty one
if (ui->entries->count() == 1)
addEntry();
entry->deleteLater();
updateTabsAndLabels();
}
QWidget* SendCoinsDialog::setupTabChain(QWidget* prev)
{
for (int i = 0; i < ui->entries->count(); ++i) {
SendCoinsEntry* entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
if (entry) {
prev = entry->setupTabChain(prev);
}
}
QWidget::setTabOrder(prev, ui->sendButton);
QWidget::setTabOrder(ui->sendButton, ui->clearButton);
QWidget::setTabOrder(ui->clearButton, ui->addButton);
return ui->addButton;
}
void SendCoinsDialog::setAddress(const QString& address)
{
SendCoinsEntry* entry = 0;
// Replace the first entry if it is still unused
if (ui->entries->count() == 1) {
SendCoinsEntry* first = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(0)->widget());
if (first->isClear()) {
entry = first;
}
}
if (!entry) {
entry = addEntry();
}
entry->setAddress(address);
}
void SendCoinsDialog::pasteEntry(const SendCoinsRecipient& rv)
{
if (!fNewRecipientAllowed)
return;
SendCoinsEntry* entry = 0;
// Replace the first entry if it is still unused
if (ui->entries->count() == 1) {
SendCoinsEntry* first = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(0)->widget());
if (first->isClear()) {
entry = first;
}
}
if (!entry) {
entry = addEntry();
}
entry->setValue(rv);
updateTabsAndLabels();
}
bool SendCoinsDialog::handlePaymentRequest(const SendCoinsRecipient& rv)
{
// Just paste the entry, all pre-checks
// are done in paymentserver.cpp.
pasteEntry(rv);
return true;
}
void SendCoinsDialog::setBalance(const CAmount& balance, const CAmount& unconfirmedBalance, const CAmount& immatureBalance, const CAmount& watchBalance, const CAmount& watchUnconfirmedBalance, const CAmount& watchImmatureBalance)
{
Q_UNUSED(unconfirmedBalance);
Q_UNUSED(immatureBalance);
Q_UNUSED(watchBalance);
Q_UNUSED(watchUnconfirmedBalance);
Q_UNUSED(watchImmatureBalance);
if (model && model->getOptionsModel()) {
uint64_t bal = 0;
bal = balance;
ui->labelBalance->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), bal));
}
}
void SendCoinsDialog::updateDisplayUnit()
{
TRY_LOCK(cs_main, lockMain);
if (!lockMain) return;
setBalance(model->getBalance(), model->getUnconfirmedBalance(), model->getImmatureBalance(),
model->getWatchBalance(), model->getWatchUnconfirmedBalance(), model->getWatchImmatureBalance());
coinControlUpdateLabels();
ui->customFee->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
updateMinFeeLabel();
updateSmartFeeLabel();
}
void SendCoinsDialog::updateSwiftTX()
{
bool useSwiftTX = ui->checkSwiftTX->isChecked();
QSettings settings;
settings.setValue("bUseSwiftTX", useSwiftTX);
CoinControlDialog::coinControl->useSwiftTX = useSwiftTX;
// If SwiftTX activated
if (useSwiftTX) {
// minimize the Fee Section (if open)
minimizeFeeSection(true);
// set the slider to the max
ui->sliderSmartFee->setValue(24);
}
// If SwiftTX activated hide button 'Choose'. Show otherwise.
ui->buttonChooseFee->setVisible(!useSwiftTX);
// Update labels and controls
updateFeeSectionControls();
updateSmartFeeLabel();
coinControlUpdateLabels();
}
void SendCoinsDialog::processSendCoinsReturn(const WalletModel::SendCoinsReturn& sendCoinsReturn, const QString& msgArg, bool fPrepare)
{
bool fAskForUnlock = false;
QPair<QString, CClientUIInterface::MessageBoxFlags> msgParams;
// Default to a warning message, override if error message is needed
msgParams.second = CClientUIInterface::MSG_WARNING;
// This comment is specific to SendCoinsDialog usage of WalletModel::SendCoinsReturn.
// WalletModel::TransactionCommitFailed is used only in WalletModel::sendCoins()
// all others are used only in WalletModel::prepareTransaction()
switch (sendCoinsReturn.status) {
case WalletModel::InvalidAddress:
msgParams.first = tr("The recipient address is not valid, please recheck.");
break;
case WalletModel::InvalidAmount:
msgParams.first = tr("The amount to pay must be larger than 0.");
break;
case WalletModel::AmountExceedsBalance:
msgParams.first = tr("The amount exceeds your balance.");
break;
case WalletModel::AmountWithFeeExceedsBalance:
msgParams.first = tr("The total exceeds your balance when the %1 transaction fee is included.").arg(msgArg);
break;
case WalletModel::DuplicateAddress:
msgParams.first = tr("Duplicate address found, can only send to each address once per send operation.");
break;
case WalletModel::TransactionCreationFailed:
msgParams.first = tr("Transaction creation failed!");
msgParams.second = CClientUIInterface::MSG_ERROR;
break;
case WalletModel::TransactionCommitFailed:
msgParams.first = tr("The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.");
msgParams.second = CClientUIInterface::MSG_ERROR;
break;
case WalletModel::StakingOnlyUnlocked:
// Unlock is only need when the coins are send
if(!fPrepare)
fAskForUnlock = true;
else
msgParams.first = tr("Error: The wallet was unlocked only to staking coins.");
break;
case WalletModel::InsaneFee:
msgParams.first = tr("A fee %1 times higher than %2 per kB is considered an insanely high fee.").arg(10000).arg(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), ::minRelayTxFee.GetFeePerK()));
break;
// included to prevent a compiler warning.
case WalletModel::OK:
default:
return;
}
// Unlock wallet if it wasn't fully unlocked already
if(fAskForUnlock) {
model->requestUnlock(AskPassphraseDialog::Context::Unlock_Full, false);
if(model->getEncryptionStatus () != WalletModel::Unlocked) {
msgParams.first = tr("Error: The wallet was unlocked only to staking coins. Unlock canceled.");
}
else {
// Wallet unlocked
return;
}
}
emit message(tr("Send Coins"), msgParams.first, msgParams.second);
}
void SendCoinsDialog::minimizeFeeSection(bool fMinimize)
{
ui->labelFeeMinimized->setVisible(fMinimize);
ui->buttonChooseFee->setVisible(fMinimize);
ui->buttonMinimizeFee->setVisible(!fMinimize);
ui->frameFeeSelection->setVisible(!fMinimize);
ui->horizontalLayoutSmartFee->setContentsMargins(0, (fMinimize ? 0 : 6), 0, 0);
fFeeMinimized = fMinimize;
}
void SendCoinsDialog::on_buttonChooseFee_clicked()
{
minimizeFeeSection(false);
}
void SendCoinsDialog::on_buttonMinimizeFee_clicked()
{
updateFeeMinimizedLabel();
minimizeFeeSection(true);
}
void SendCoinsDialog::setMinimumFee()
{
ui->radioCustomPerKilobyte->setChecked(true);
ui->customFee->setValue(CWallet::minTxFee.GetFeePerK());
}
void SendCoinsDialog::updateFeeSectionControls()
{
ui->sliderSmartFee->setEnabled(ui->radioSmartFee->isChecked() && !ui->checkSwiftTX->isChecked());
ui->labelSmartFee->setEnabled(ui->radioSmartFee->isChecked());
ui->labelSmartFee2->setEnabled(ui->radioSmartFee->isChecked());
ui->labelSmartFee3->setEnabled(ui->radioSmartFee->isChecked());
ui->labelFeeEstimation->setEnabled(ui->radioSmartFee->isChecked());
ui->labelSmartFeeNormal->setEnabled(ui->radioSmartFee->isChecked());
ui->labelSmartFeeFast->setEnabled(ui->radioSmartFee->isChecked());
ui->checkBoxMinimumFee->setEnabled(ui->radioCustomFee->isChecked());
ui->labelMinFeeWarning->setEnabled(ui->radioCustomFee->isChecked());
ui->radioCustomPerKilobyte->setEnabled(ui->radioCustomFee->isChecked() && !ui->checkBoxMinimumFee->isChecked());
ui->radioCustomAtLeast->setEnabled(ui->radioCustomFee->isChecked() && !ui->checkBoxMinimumFee->isChecked());
ui->customFee->setEnabled(ui->radioCustomFee->isChecked() && !ui->checkBoxMinimumFee->isChecked());
}
void SendCoinsDialog::updateGlobalFeeVariables()
{
if (ui->radioSmartFee->isChecked()) {
nTxConfirmTarget = (int)25 - (int)std::max(0, std::min(24, ui->sliderSmartFee->value()));
payTxFee = CFeeRate(0);
} else {
nTxConfirmTarget = 25;
payTxFee = CFeeRate(ui->customFee->value());
fPayAtLeastCustomFee = ui->radioCustomAtLeast->isChecked();
}
fSendFreeTransactions = ui->checkBoxFreeTx->isChecked();
}
void SendCoinsDialog::updateFeeMinimizedLabel()
{
if (!model || !model->getOptionsModel())
return;
if (ui->checkSwiftTX->isChecked()) {
ui->labelFeeMinimized->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), 1000000));
} else if (ui->radioSmartFee->isChecked())
ui->labelFeeMinimized->setText(ui->labelSmartFee->text());
else {
ui->labelFeeMinimized->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), ui->customFee->value()) +
((ui->radioCustomPerKilobyte->isChecked()) ? "/kB" : ""));
}
}
void SendCoinsDialog::updateMinFeeLabel()
{
if (model && model->getOptionsModel())
ui->checkBoxMinimumFee->setText(tr("Pay only the minimum fee of %1").arg(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), CWallet::minTxFee.GetFeePerK()) + "/kB"));
}
void SendCoinsDialog::updateSmartFeeLabel()
{
if (!model || !model->getOptionsModel())
return;
int nBlocksToConfirm = (int)25 - (int)std::max(0, std::min(24, ui->sliderSmartFee->value()));
CFeeRate feeRate = mempool.estimateFee(nBlocksToConfirm);
// if SwiftTX checked, display it in the label
if (ui->checkSwiftTX->isChecked())
{
ui->labelFeeEstimation->setText(tr("Estimated to get 6 confirmations near instantly with <b>SwiftTX</b>!"));
ui->labelSmartFee2->hide();
} else if (feeRate <= CFeeRate(0)) // not enough data => minfee
{
ui->labelSmartFee->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), CWallet::minTxFee.GetFeePerK()) + "/kB");
ui->labelSmartFee2->show(); // (Smart fee not initialized yet. This usually takes a few blocks...)
ui->labelFeeEstimation->setText("");
} else {
ui->labelSmartFee->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), feeRate.GetFeePerK()) + "/kB");
ui->labelSmartFee2->hide();
ui->labelFeeEstimation->setText(tr("Estimated to begin confirmation within %n block(s).", "", nBlocksToConfirm));
}
updateFeeMinimizedLabel();
}
// UTXO splitter
void SendCoinsDialog::splitBlockChecked(int state)
{
if (model) {
CoinControlDialog::coinControl->fSplitBlock = (state == Qt::Checked);
fSplitBlock = (state == Qt::Checked);
ui->splitBlockLineEdit->setEnabled((state == Qt::Checked));
ui->labelBlockSizeText->setEnabled((state == Qt::Checked));
ui->labelBlockSize->setEnabled((state == Qt::Checked));
coinControlUpdateLabels();
}
}
//UTXO splitter
void SendCoinsDialog::splitBlockLineEditChanged(const QString& text)
{
//grab the amount in Coin Control AFter Fee field
QString qAfterFee = ui->labelCoinControlAfterFee->text().left(ui->labelCoinControlAfterFee->text().indexOf(" ")).replace("~", "").simplified().replace(" ", "");
//convert to CAmount
CAmount nAfterFee;
ParseMoney(qAfterFee.toStdString().c_str(), nAfterFee);
//if greater than 0 then divide after fee by the amount of blocks
CAmount nSize = nAfterFee;
int nBlocks = text.toInt();
if (nAfterFee && nBlocks)
nSize = nAfterFee / nBlocks;
//assign to split block dummy, which is used to recalculate the fee amount more outputs
CoinControlDialog::nSplitBlockDummy = nBlocks;
//update labels
ui->labelBlockSize->setText(QString::fromStdString(FormatMoney(nSize)));
coinControlUpdateLabels();
}
// Coin Control: copy label "Quantity" to clipboard
void SendCoinsDialog::coinControlClipboardQuantity()
{
GUIUtil::setClipboard(ui->labelCoinControlQuantity->text());
}
// Coin Control: copy label "Amount" to clipboard
void SendCoinsDialog::coinControlClipboardAmount()
{
GUIUtil::setClipboard(ui->labelCoinControlAmount->text().left(ui->labelCoinControlAmount->text().indexOf(" ")));
}
// Coin Control: copy label "Fee" to clipboard
void SendCoinsDialog::coinControlClipboardFee()
{
GUIUtil::setClipboard(ui->labelCoinControlFee->text().left(ui->labelCoinControlFee->text().indexOf(" ")).replace("~", ""));
}
// Coin Control: copy label "After fee" to clipboard
void SendCoinsDialog::coinControlClipboardAfterFee()
{
GUIUtil::setClipboard(ui->labelCoinControlAfterFee->text().left(ui->labelCoinControlAfterFee->text().indexOf(" ")).replace("~", ""));
}
// Coin Control: copy label "Bytes" to clipboard
void SendCoinsDialog::coinControlClipboardBytes()
{
GUIUtil::setClipboard(ui->labelCoinControlBytes->text().replace("~", ""));
}
// Coin Control: copy label "Priority" to clipboard
void SendCoinsDialog::coinControlClipboardPriority()
{
GUIUtil::setClipboard(ui->labelCoinControlPriority->text());
}
// Coin Control: copy label "Dust" to clipboard
void SendCoinsDialog::coinControlClipboardLowOutput()
{
GUIUtil::setClipboard(ui->labelCoinControlLowOutput->text());
}
// Coin Control: copy label "Change" to clipboard
void SendCoinsDialog::coinControlClipboardChange()
{
GUIUtil::setClipboard(ui->labelCoinControlChange->text().left(ui->labelCoinControlChange->text().indexOf(" ")).replace("~", ""));
}
// Coin Control: settings menu - coin control enabled/disabled by user
void SendCoinsDialog::coinControlFeatureChanged(bool checked)
{
ui->frameCoinControl->setVisible(checked);
if (!checked && model) // coin control features disabled
CoinControlDialog::coinControl->SetNull();
if (checked)
coinControlUpdateLabels();
}
// Coin Control: button inputs -> show actual coin control dialog
void SendCoinsDialog::coinControlButtonClicked()
{
CoinControlDialog dlg;
dlg.setModel(model);
dlg.exec();
coinControlUpdateLabels();
}
// Coin Control: checkbox custom change address
void SendCoinsDialog::coinControlChangeChecked(int state)
{
if (state == Qt::Unchecked) {
CoinControlDialog::coinControl->destChange = CNoDestination();
ui->labelCoinControlChangeLabel->clear();
} else
// use this to re-validate an already entered address
coinControlChangeEdited(ui->lineEditCoinControlChange->text());
ui->lineEditCoinControlChange->setEnabled((state == Qt::Checked));
}
// Coin Control: custom change address changed
void SendCoinsDialog::coinControlChangeEdited(const QString& text)
{
if (model && model->getAddressTableModel()) {
// Default to no change address until verified
CoinControlDialog::coinControl->destChange = CNoDestination();
ui->labelCoinControlChangeLabel->setStyleSheet("QLabel{color:red;}");
CBitcoinAddress addr = CBitcoinAddress(text.toStdString());
if (text.isEmpty()) // Nothing entered
{
ui->labelCoinControlChangeLabel->setText("");
} else if (!addr.IsValid()) // Invalid address
{
ui->labelCoinControlChangeLabel->setText(tr("Warning: Invalid NODE address"));
} else // Valid address
{
CPubKey pubkey;
CKeyID keyid;
addr.GetKeyID(keyid);
if (!model->getPubKey(keyid, pubkey)) // Unknown change address
{
ui->labelCoinControlChangeLabel->setText(tr("Warning: Unknown change address"));
} else // Known change address
{
ui->labelCoinControlChangeLabel->setStyleSheet("QLabel{color:black;}");
// Query label
QString associatedLabel = model->getAddressTableModel()->labelForAddress(text);
if (!associatedLabel.isEmpty())
ui->labelCoinControlChangeLabel->setText(associatedLabel);
else
ui->labelCoinControlChangeLabel->setText(tr("(no label)"));
CoinControlDialog::coinControl->destChange = addr.Get();
}
}
}
}
// Coin Control: update labels
void SendCoinsDialog::coinControlUpdateLabels()
{
if (!model || !model->getOptionsModel() || !model->getOptionsModel()->getCoinControlFeatures())
return;
// set pay amounts
CoinControlDialog::payAmounts.clear();
for (int i = 0; i < ui->entries->count(); ++i) {
SendCoinsEntry* entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
if (entry)
CoinControlDialog::payAmounts.append(entry->getValue().amount);
}
if (CoinControlDialog::coinControl->HasSelected()) {
// actual coin control calculation
CoinControlDialog::updateLabels(model, this);
// show coin control stats
ui->labelCoinControlAutomaticallySelected->hide();
ui->widgetCoinControl->show();
} else {
// hide coin control stats
ui->labelCoinControlAutomaticallySelected->show();
ui->widgetCoinControl->hide();
ui->labelCoinControlInsuffFunds->hide();
}
}
| [
"[email protected]"
] | |
1c28d2034462a4d989447c31f4316c33a68425ce | 3011f9e4204f2988c983b8815187f56a6bf58ebd | /src/ys_library/ysport/src/ysthread.cpp | e4abbf5cb47286944c1fb97b5714b8925407cde3 | [] | no_license | hvantil/AR-BoardGames | 9e80a0f2bb24f8bc06902785d104178a214d0d63 | 71b9620df66d80c583191b8c8e8b925a6df5ddc3 | refs/heads/master | 2020-03-17T01:36:47.674272 | 2018-05-13T18:11:16 | 2018-05-13T18:11:16 | 133,160,216 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,983 | cpp | /* ////////////////////////////////////////////////////////////
File Name: ysthread.cpp
Copyright (c) 2017 Soji Yamakawa. All rights reserved.
http://www.ysflight.com
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//////////////////////////////////////////////////////////// */
#include <ysclass.h>
#include "ysthread.h"
#ifdef __APPLE__
#include <sys/types.h>
#include <sys/sysctl.h>
#include <errno.h>
#endif
YsMutex::YsMutex()
{
#ifndef _WIN32
pthread_mutex_init(&mutex,NULL);
#endif
}
YsMutex::~YsMutex()
{
#ifndef _WIN32
pthread_mutex_destroy(&mutex);
#endif
}
void YsMutex::Lock(void)
{
#ifdef _WIN32
mutex.lock();
#else
pthread_mutex_lock(&mutex);
#endif
}
void YsMutex::Unlock(void)
{
#ifdef _WIN32
mutex.unlock();
#else
pthread_mutex_unlock(&mutex);
#endif
}
YSRESULT YsMutex::LockNoWait(void)
{
#ifdef _WIN32
if(true==mutex.try_lock())
{
return YSOK;
}
#else
if(0==pthread_mutex_trylock(&mutex))
{
return YSOK;
}
#endif
return YSERR;
}
////////////////////////////////////////////////////////////
unsigned int YsThreadController::GetNumCPU(void)
{
#ifdef _WIN32
return std::thread::hardware_concurrency();
#elif defined(__APPLE__)
unsigned int nCpu;
size_t nCpuSize=sizeof(nCpu);
int mib[2]={CTL_HW,HW_NCPU};
int res=sysctl(mib,2,&nCpu,&nCpuSize,NULL,0);
if(0==res)
{
return nCpu;
}
else if(ENOMEM==errno)
{
unsigned long int nCpu;
size_t nCpuSize=sizeof(nCpu); // Try long int then.
if(0==sysctl(mib,2,&nCpu,&nCpuSize,NULL,0))
{
return (unsigned int)nCpu;
}
}
return 1; // This OS didn't tell me.
#else
return sysconf(_SC_NPROCESSORS_ONLN);
#endif
}
#ifndef _WIN32
static void *YsPthreadLaunch(void *info)
{
YsTask *task=(YsTask *)info;
task->StartLocal();
pthread_exit(NULL);
return NULL;
}
#endif
YSRESULT YsThreadController::RunParallel(int nTask,YsTask *const task[])
{
if(0>=nTask)
{
return YSOK;
}
else if(1==nTask)
{
task[0]->StartLocal();
return YSOK;
}
else
{
#ifdef _WIN32
// Ironically VS2012 seems to support std::thread library better.
YsArray <std::thread,16> threadArray;
threadArray.Resize(nTask-1);
for(int i=0; i<nTask-1; ++i)
{
threadArray[i]=std::thread(YsTask::Start,task[i]);
}
task[nTask-1]->StartLocal();
for(int i=0; i<nTask-1; ++i)
{
threadArray[i].join();
}
#else
YsArray <pthread_t,16> hThread(nTask-1,NULL);
for(int i=0; i<nTask-1; i++)
{
pthread_create(&hThread[i],NULL,YsPthreadLaunch,(void *)task[i]);
}
task[nTask-1]->StartLocal();
for(int i=0; i<nTask; i++)
{
pthread_join(hThread[i],NULL);
}
#endif
}
return YSOK;
}
| [
"[email protected]"
] | |
215f515ad8d8154f77c1eb1aadf8f0a799466927 | aab7eafab5efae62cb06c3a2b6c26fe08eea0137 | /TMVA/kfoldandubdt/kfoldold/diffvs/CombiTriggerNoSSVertexMomAssyVectorized/src/workingversion07122015/ukfoldnew.cc | 9627bcf4832132cf9317dac41b7242fb458c8b56 | [] | no_license | Sally27/B23MuNu_backup | 397737f58722d40e2a1007649d508834c1acf501 | bad208492559f5820ed8c1899320136406b78037 | refs/heads/master | 2020-04-09T18:12:43.308589 | 2018-12-09T14:16:25 | 2018-12-09T14:16:25 | 160,504,958 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,988 | cc | #include "uKFolder2.hpp"
#include <boost/algorithm/string.hpp>
#include <boost/assign.hpp>
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <boost/program_options.hpp>
namespace po = boost::program_options;
struct Args {
std::string sig;
std::string bkg;
std::string sigtree;
std::string bkgtree;
std::string conf;
std::string runname;
std::string bdt;
std::string weight;
std::string name;
std::vector<std::string> variables;
std::vector<std::string> options;
int kfolds;
bool run;
bool all;
};
bool opts(int argc, char *argv[], Args &args) {
bool pass = true;
po::options_description desc("BDT stuff for inflaton studies");
desc.add_options()
("help,h", "produce help method")
("sig,s", po::value<std::string>(&args.sig),
"Signal file name")
("bkg,b", po::value<std::string>(&args.bkg),
"Background file name")
("sig-tree", po::value<std::string>(&args.sigtree)
->default_value("DecayTree"), "Tree name")
("bkg-tree", po::value<std::string>(&args.bkgtree)
->default_value("DecayTree"), "Tree name")
("all", po::bool_switch(&args.all), "Output all KFold values during run")
("weight,w", po::value<std::string>(&args.weight), "Weight variable")
("kfolds,k", po::value<int>(&args.kfolds)
->default_value(10), "kFolds")
("run,r", po::value<std::string>(&args.runname)
->default_value(""), "File name for running")
("bdt", po::value<std::string>(&args.bdt), "BDT name")
("name", po::value<std::string>(&args.name)->default_value(""), "Name")
("var,v", po::value<std::vector<std::string> >(&args.variables), "Add variable")
("opt,o", po::value<std::vector<std::string> >(&args.options), "Add option")
;
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
if (vm.count("help")) {
std::cout << desc << std::endl;
return false;
}
if (!args.runname.size()) {
args.run = false;
} else {
args.run = true;
}
if ((!vm.count("sig") || !vm.count("bkg")) && !args.run) {
oierror << "Please give signal, background and config files";
pass = false;
}
return pass;
}
int main(int argc, char *argv[]) {
Args args;
if (!opts(argc, argv, args)) {
oierror << "Options parser exited with an error";
return 1;
}
uKFolder2 kf(args.sig, args.bkg);
kf.setBranches(boost::assign::list_of
// kf.addTrainingVars(boost::assign::list_of
("Bplus_P")
("KFold")
("mu1_P")
("mu2_P")
("mu3_P")
("Bplus_PT")
("mu1_PT")
("mu2_PT")
("mu3_PT")
("mu1_MINIP")
("mu2_MINIP")
("mu3_MINIP")
("mu1_ghost")
("mu2_ghost")
("mu3_ghost")
("mu1_TRACK_CHI2")
("mu2_TRACK_CHI2")
("mu3_TRACK_CHI2")
("mu1_MINIPCHI2")
("mu2_MINIPCHI2")
("mu3_MINIPCHI2")
("Bplus_pmu_ISOLATION_BDT1_weights")
("Bplus_Corrected_Mass")
("Bplus_ENDVERTEX_CHI2")
("Bplus_TAU")
("Bplus_DIRA_OWNPV")
("mu1_Xmu_SV_CHI2")
// ("sqrt(((Bplus_X_travelled)*(Bplus_X_travelled))+((Bplus_Y_travelled)*(Bplus_Y_travelled))+((Bplus_Z_travelled)*(Bplus_Z_travelled)))")
("Bplus_FD_CHI2")
);
kf.addSpectatorVars(boost::assign::list_of
("Bplus_Corrected_Mass")
// ("KFold")
);
//if (args.weight.length()) {
//kf.addSpectatorVar(args.weight);
//}
kf.setNFolds(args.kfolds);
kf.addTrainingVars(args.variables);
kf.setOutFile("tmva/" + args.bdt);
kf.addTrainingOpt("misidvsmcsignotreversed", "UBDT_Num=100:!H:!V:NTrees=200:nEventsMin=100:MaxDepth=3:BoostType=AdaBoost:AdaBoostBeta=1.0:PruneMethod=NoPruning:SeparationType=GiniIndex:nCuts=200:uBoostFlag=1");
//kf.addTraining
//for (unsigned i=0; i<args.options.size(); ++i) {
// std::string name = args.bdt + "_" + args.options.at(i);
// boost::replace_all(name, ":", "_");
// boost::replace_all(name, "=", "");
// boost::replace_all(name, "-", "");
// if (args.options.size() == 1 && args.name.length()) {
// kf.addTrainingOpt(args.name, args.options.at(i));
// } else if (args.name.length()) {
// kf.addTrainingOpt(args.name + scph::ntos(i), args.options.at(i));
// } else {
// kf.addTrainingOpt(name, args.options.at(i));
// }
// }
if (!args.run) {
//kf.addBkgCut("B0_MM>5380 && B0_MM<5800 && x_TAU>-2.2e-4 && muplus_ProbNNmu>0.3 && muminus_ProbNNmu>0.3");
//kf.addSigCut("x_TAU>-2.2e-4 && muplus_ProbNNmu>0.3 && muminus_ProbNNmu>0.3");
// kf.addBkgCut("B0_MM>5380 && B0_MM<5800 && x_TAU>-2.2e-4");
// kf.addSigCut("x_TAU>-2.2e-4");
kf.setWeightExpression(args.weight);
kf.train();
}
if (args.run && !args.bdt.length()) {
oiinfo << "Run : " << args.runname;
kf.run(args.runname, "", args.all);
}
if (args.run && args.bdt.length()) {
oiinfo << "Run : " << args.runname;
oiinfo << "BDT : " << args.bdt;
kf.run(args.runname, args.bdt, args.all);
}
return 0;
}
| [
"[email protected]"
] | |
b7653b30c739c52665efe31f6bbb53584bad56e1 | 217c8c7e72f6845193fa0d416cb8c5a8f1756f8b | /auto_recognition/src/kinect2depth.cpp | b839b0cafb9d2f1222a544a9d84d962959fe5a55 | [
"MIT"
] | permissive | Gongkaka/deep_learning | ddd9f5a062deb028bd33964519c27195717148aa | 89e3d440478cd49f54115f34a6a8fb5e5dd29da8 | refs/heads/master | 2020-03-22T02:48:23.994551 | 2017-09-26T17:48:44 | 2017-09-26T17:48:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,148 | cpp | /// kinect2depth
/// Zhiang Chen, Wyatt Newman Aug 2016
/// Receive the pointcloud data from "kinect2/qhd/points", and then project the points in the box filter to a depth image.
/// Publish the depth image to "depth_image" with 10hz.
/*
* The MIT License (MIT)
* Copyright (c) 2016 Zhiang Chen, Wyatt Newman
*/
#include <ros/ros.h>
#include <stdlib.h>
#include <math.h>
#include <sensor_msgs/PointCloud2.h>
#include <sensor_msgs/Image.h>
#include <pcl_ros/point_cloud.h>
#include <pcl/conversions.h>
#include <pcl/point_types.h>
#include <pcl/point_cloud.h>
#include <pcl/common/common_headers.h>
#include <pcl-1.7/pcl/point_cloud.h>
#include <pcl-1.7/pcl/PCLHeader.h>
#include <pcl/filters/passthrough.h>
#include <pcl/filters/voxel_grid.h>
#include <pcl_utils/pcl_utils.h>
#include <iostream>
#include <fstream>
#include <image_transport/image_transport.h>
#include <cv_bridge/cv_bridge.h>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
using namespace std;
//#define DISPLAY
sensor_msgs::Image project(pcl::PointCloud<pcl::PointXYZRGB>::Ptr box_ptr, int npts_cloud);
void box_filter(pcl::PointCloud<pcl::PointXYZRGB>::Ptr inputCloud, Eigen::Vector3f pt_min, Eigen::Vector3f pt_max, vector<int> &indices);
/********* Hyperparameters **********/
// Plane Paramters
#define A 0.00081042
#define B 0.503923
#define C 0.863748
#define D -0.800717
#define cX -0.14675
#define cY 0.109414
#define cZ 0.863329
// Box Filter Parameters
#define bnX -0.06
#define bnY -0.11
#define bnZ -0.015
#define bmX 0.115
#define bmY 0.08
#define bmZ 0.1
// Projection Parameters
#define mDis 0.92 // darkest, float!
#define nDis 0.77 // brightest, float!
#define Nv 120
#define Nu 120
#define focal_len 200.0 //220.0 may be good? float!
/*************************************/
// 500x250x250
pcl::PointCloud<pcl::PointXYZRGB>::Ptr g_kinect_ptr(new pcl::PointCloud<pcl::PointXYZRGB>);
bool g_got_data = false;
void kinectCallback(const sensor_msgs::PointCloud2ConstPtr &cloud)
{
g_got_data = true;
pcl::fromROSMsg(*cloud, *g_kinect_ptr);
}
int main(int argc, char** argv)
{
ros::init(argc, argv, "kinect2depth"); //node name
ros::NodeHandle nh;
PclUtils pclUtils(&nh);
// subscribers
ros::Subscriber sub = nh.subscribe("kinect2/qhd/points", 1, kinectCallback);
// publishers
ros::Publisher pub_depth_image = nh.advertise<sensor_msgs::Image> ("/depth_image",1);
ros::Publisher pub_kinect = nh.advertise<sensor_msgs::PointCloud2> ("/kinect", 1);
ros::Publisher pub_tf_kinect = nh.advertise<sensor_msgs::PointCloud2> ("/tf_kinect", 1);
ros::Publisher pub_tf_box = nh.advertise<sensor_msgs::PointCloud2> ("/tf_box", 1);
ros::Publisher pub_box = nh.advertise<sensor_msgs::PointCloud2> ("/box", 1);
// pcl pointcloud
pcl::PointCloud<pcl::PointXYZRGB>::Ptr kinect_ptr(new pcl::PointCloud<pcl::PointXYZRGB>); // pointer to the pointcloud wrt kinect coords
pcl::PointCloud<pcl::PointXYZRGB>::Ptr tf_kinect_ptr(new pcl::PointCloud<pcl::PointXYZRGB>); // pointer to the pointcloud wrt plate coords
pcl::PointCloud<pcl::PointXYZRGB>::Ptr tf_box_ptr(new pcl::PointCloud<pcl::PointXYZRGB>); // pointer to the interesting points (in the box) wrt plate coords
pcl::PointCloud<pcl::PointXYZRGB>::Ptr box_ptr(new pcl::PointCloud<pcl::PointXYZRGB>); // pointer to the interesting points (in the box) wrt camera coords
// pointer to downsampled pointcloud
pcl::PointCloud<pcl::PointXYZRGB>::Ptr tf_ds_ptr(new pcl::PointCloud<pcl::PointXYZRGB>);
pcl::PointCloud<pcl::PointXYZRGB>::Ptr tf_ds_box_ptr(new pcl::PointCloud<pcl::PointXYZRGB>);
// sensor msg pointcloud
sensor_msgs::PointCloud2 ros_kinect, ros_box, ros_tf_kinect, ros_tf_box, ros_tf_ds, ros_tf_ds_box;
// sensor msg depth image
sensor_msgs::Image depth_image;
// The transform from camera to plane is hard-coded.
Eigen::Affine3f A_plane_wrt_camera;
Eigen::Vector4f plane_parameters;
Eigen::Vector3f plane_centroid3f;
plane_parameters<<A, B, C, D;
plane_centroid3f<<cX, cY, cZ;
A_plane_wrt_camera = pclUtils.make_affine_from_plane_params(plane_parameters,plane_centroid3f);
// Image projection variables
Eigen::Vector3f cloud_pt;
double x,y,z;
double v,vc,u,uc;
int i,j;
uc = Nu/2.0;
vc = Nv/2.0;
uchar gray_level;
double r;
int npts_cloud;
cv::Mat image(Nu,Nv,CV_8U,cv::Scalar(0));
// wait for kinect data
ROS_INFO("Initialized!");
while(!g_got_data)
{
ros::spinOnce();
ros::Duration(1.0).sleep();
}
ROS_INFO("Got Kinect Data!");
// get and publish depth image
vector<int> indices; // indices of interesting pixels
// parameters for box filter wrt plane coords
Eigen::Vector3f box_pt_min,box_pt_max;
box_pt_min<<bnX,bnY,bnZ;
box_pt_max<<bmX,bmY,bmZ;
while(ros::ok())
{
kinect_ptr = g_kinect_ptr;
// transform to plane coords
pcl::transformPointCloud(*kinect_ptr, *tf_kinect_ptr, A_plane_wrt_camera.inverse());
// box filter
box_filter(tf_kinect_ptr, box_pt_min, box_pt_max, indices);
pcl::copyPointCloud(*tf_kinect_ptr, indices, *tf_box_ptr);
pcl::copyPointCloud(*kinect_ptr, indices, *box_ptr);
// get depth image
int npts_cloud = indices.size();
depth_image = project(box_ptr, npts_cloud);
// publish depth image
pub_depth_image.publish(depth_image);
// refresh data
g_got_data = false;
while(!g_got_data && ros::ok())
{
ros::spinOnce();
ros::Duration(0.1).sleep();
}
#ifdef DISPLAY
pcl::toROSMsg(*tf_kinect_ptr, ros_tf_kinect);
pcl::toROSMsg(*kinect_ptr, ros_kinect);
pcl::toROSMsg(*tf_box_ptr, ros_tf_box);
pcl::toROSMsg(*box_ptr, ros_box);
ros_kinect.header.frame_id = "camera";
ros_tf_kinect.header.frame_id = "plane";
ros_tf_box.header.frame_id = "plane";
ros_box.header.frame_id = "camera";
pub_kinect.publish(ros_kinect);
pub_tf_kinect.publish(ros_tf_kinect);
pub_tf_box.publish(ros_tf_box);
pub_box.publish(ros_box);
#endif
}
return 0;
}
sensor_msgs::Image project(pcl::PointCloud<pcl::PointXYZRGB>::Ptr box_ptr, int npts_cloud)
{
Eigen::Vector3f cloud_pt;
double x,y,z;
double v,vc,u,uc;
int i,j;
uc = Nu/2.0;
vc = Nv/2.0;
uchar gray_level;
double r;
cv::Mat image(Nu,Nv,CV_8U,cv::Scalar(0));
sensor_msgs::Image depth_image;
// project to a depth image
for (int ipt = 0;ipt<npts_cloud;ipt++) // i-th point
{
cloud_pt = box_ptr->points[ipt].getVector3fMap();
z = cloud_pt[2];
y = cloud_pt[1];
x = cloud_pt[0];
if ((z==z)&&(x==x)&&(y==y))
{
u = uc + focal_len*x/z;
i = round(u);
v = vc + focal_len*y/z;
j = round(v);
if ((i>=0)&&(i<Nu)&&(j>=0)&&(j<Nv))
{
// convert z to an intensity:
r = sqrt(z*z+y*y+x*x);
if (r>mDis) gray_level=0;
else if (r<nDis) gray_level=0;
else
{
gray_level = (uchar) (255*(mDis-r)/(mDis-nDis));
}
image.at<uchar>(j,i)= gray_level;
}
}
}
// convert opencv image to ros image
cv_bridge::CvImage cvi;
cvi.header.stamp = ros::Time::now();
cvi.header.frame_id = "camera";
cvi.encoding = "mono8";
cvi.image = image;
cvi.toImageMsg(depth_image);
return depth_image;
}
void box_filter(pcl::PointCloud<pcl::PointXYZRGB>::Ptr inputCloud, Eigen::Vector3f pt_min, Eigen::Vector3f pt_max,
vector<int> &indices) {
int npts = inputCloud->points.size();
Eigen::Vector3f pt;
indices.clear();
for (int i = 0; i < npts; ++i) {
pt = inputCloud->points[i].getVector3fMap();
//cout<<"pt: "<<pt.transpose()<<endl;
//check if in the box:
if ((pt[0]>pt_min[0])&&(pt[0]<pt_max[0])&&(pt[1]>pt_min[1])&&(pt[1]<pt_max[1])&&(pt[2]>pt_min[2])&&(pt[2]<pt_max[2])) {
//passed box-crop test; include this point
indices.push_back(i);
}
}
int n_extracted = indices.size();
cout << " number of points within box = " << n_extracted << endl;
}
| [
"[email protected]"
] | |
c93e9c2d05b8c6fb1f4abbb3b8e8597c18830b20 | 55b5034281a1e750632fd23974e33a9daea09de9 | /3rdparty/opencv-git/modules/core/include/opencv2/core/cuda.hpp | 4ae4301665e577725d60530e27ac58b78502439f | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | joshjo/planecalib | f5fbca3a0f9899f5097c7025847c939f41ae4789 | 1d7cffac5cab39c7fbfb67e8e3a4b42340ef5e13 | refs/heads/master | 2020-04-16T08:08:28.523107 | 2019-02-18T11:19:08 | 2019-02-18T11:19:08 | 165,413,146 | 0 | 0 | NOASSERTION | 2019-01-12T17:02:34 | 2019-01-12T17:02:34 | null | UTF-8 | C++ | false | false | 22,768 | hpp | /*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Copyright (C) 2013, OpenCV Foundation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of the copyright holders may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/
#ifndef __OPENCV_CORE_CUDA_HPP__
#define __OPENCV_CORE_CUDA_HPP__
#ifndef __cplusplus
# error cuda.hpp header must be compiled as C++
#endif
#include "opencv2/core.hpp"
#include "opencv2/core/cuda_types.hpp"
namespace cv { namespace cuda {
//////////////////////////////// GpuMat ///////////////////////////////
// Smart pointer for GPU memory with reference counting.
// Its interface is mostly similar with cv::Mat.
class CV_EXPORTS GpuMat
{
public:
class CV_EXPORTS Allocator
{
public:
virtual ~Allocator() {}
// allocator must fill data, step and refcount fields
virtual bool allocate(GpuMat* mat, int rows, int cols, size_t elemSize) = 0;
virtual void free(GpuMat* mat) = 0;
};
//! default allocator
static Allocator* defaultAllocator();
static void setDefaultAllocator(Allocator* allocator);
//! default constructor
explicit GpuMat(Allocator* allocator = defaultAllocator());
//! constructs GpuMat of the specified size and type
GpuMat(int rows, int cols, int type, Allocator* allocator = defaultAllocator());
GpuMat(Size size, int type, Allocator* allocator = defaultAllocator());
//! constucts GpuMat and fills it with the specified value _s
GpuMat(int rows, int cols, int type, Scalar s, Allocator* allocator = defaultAllocator());
GpuMat(Size size, int type, Scalar s, Allocator* allocator = defaultAllocator());
//! copy constructor
GpuMat(const GpuMat& m);
//! constructor for GpuMat headers pointing to user-allocated data
GpuMat(int rows, int cols, int type, void* data, size_t step = Mat::AUTO_STEP);
GpuMat(Size size, int type, void* data, size_t step = Mat::AUTO_STEP);
//! creates a GpuMat header for a part of the bigger matrix
GpuMat(const GpuMat& m, Range rowRange, Range colRange);
GpuMat(const GpuMat& m, Rect roi);
//! builds GpuMat from host memory (Blocking call)
explicit GpuMat(InputArray arr, Allocator* allocator = defaultAllocator());
//! destructor - calls release()
~GpuMat();
//! assignment operators
GpuMat& operator =(const GpuMat& m);
//! allocates new GpuMat data unless the GpuMat already has specified size and type
void create(int rows, int cols, int type);
void create(Size size, int type);
//! decreases reference counter, deallocate the data when reference counter reaches 0
void release();
//! swaps with other smart pointer
void swap(GpuMat& mat);
//! pefroms upload data to GpuMat (Blocking call)
void upload(InputArray arr);
//! pefroms upload data to GpuMat (Non-Blocking call)
void upload(InputArray arr, Stream& stream);
//! pefroms download data from device to host memory (Blocking call)
void download(OutputArray dst) const;
//! pefroms download data from device to host memory (Non-Blocking call)
void download(OutputArray dst, Stream& stream) const;
//! returns deep copy of the GpuMat, i.e. the data is copied
GpuMat clone() const;
//! copies the GpuMat content to device memory (Blocking call)
void copyTo(OutputArray dst) const;
//! copies the GpuMat content to device memory (Non-Blocking call)
void copyTo(OutputArray dst, Stream& stream) const;
//! copies those GpuMat elements to "m" that are marked with non-zero mask elements (Blocking call)
void copyTo(OutputArray dst, InputArray mask) const;
//! copies those GpuMat elements to "m" that are marked with non-zero mask elements (Non-Blocking call)
void copyTo(OutputArray dst, InputArray mask, Stream& stream) const;
//! sets some of the GpuMat elements to s (Blocking call)
GpuMat& setTo(Scalar s);
//! sets some of the GpuMat elements to s (Non-Blocking call)
GpuMat& setTo(Scalar s, Stream& stream);
//! sets some of the GpuMat elements to s, according to the mask (Blocking call)
GpuMat& setTo(Scalar s, InputArray mask);
//! sets some of the GpuMat elements to s, according to the mask (Non-Blocking call)
GpuMat& setTo(Scalar s, InputArray mask, Stream& stream);
//! converts GpuMat to another datatype (Blocking call)
void convertTo(OutputArray dst, int rtype) const;
//! converts GpuMat to another datatype (Non-Blocking call)
void convertTo(OutputArray dst, int rtype, Stream& stream) const;
//! converts GpuMat to another datatype with scaling (Blocking call)
void convertTo(OutputArray dst, int rtype, double alpha, double beta = 0.0) const;
//! converts GpuMat to another datatype with scaling (Non-Blocking call)
void convertTo(OutputArray dst, int rtype, double alpha, Stream& stream) const;
//! converts GpuMat to another datatype with scaling (Non-Blocking call)
void convertTo(OutputArray dst, int rtype, double alpha, double beta, Stream& stream) const;
void assignTo(GpuMat& m, int type=-1) const;
//! returns pointer to y-th row
uchar* ptr(int y = 0);
const uchar* ptr(int y = 0) const;
//! template version of the above method
template<typename _Tp> _Tp* ptr(int y = 0);
template<typename _Tp> const _Tp* ptr(int y = 0) const;
template <typename _Tp> operator PtrStepSz<_Tp>() const;
template <typename _Tp> operator PtrStep<_Tp>() const;
//! returns a new GpuMat header for the specified row
GpuMat row(int y) const;
//! returns a new GpuMat header for the specified column
GpuMat col(int x) const;
//! ... for the specified row span
GpuMat rowRange(int startrow, int endrow) const;
GpuMat rowRange(Range r) const;
//! ... for the specified column span
GpuMat colRange(int startcol, int endcol) const;
GpuMat colRange(Range r) const;
//! extracts a rectangular sub-GpuMat (this is a generalized form of row, rowRange etc.)
GpuMat operator ()(Range rowRange, Range colRange) const;
GpuMat operator ()(Rect roi) const;
//! creates alternative GpuMat header for the same data, with different
//! number of channels and/or different number of rows
GpuMat reshape(int cn, int rows = 0) const;
//! locates GpuMat header within a parent GpuMat
void locateROI(Size& wholeSize, Point& ofs) const;
//! moves/resizes the current GpuMat ROI inside the parent GpuMat
GpuMat& adjustROI(int dtop, int dbottom, int dleft, int dright);
//! returns true iff the GpuMat data is continuous
//! (i.e. when there are no gaps between successive rows)
bool isContinuous() const;
//! returns element size in bytes
size_t elemSize() const;
//! returns the size of element channel in bytes
size_t elemSize1() const;
//! returns element type
int type() const;
//! returns element type
int depth() const;
//! returns number of channels
int channels() const;
//! returns step/elemSize1()
size_t step1() const;
//! returns GpuMat size : width == number of columns, height == number of rows
Size size() const;
//! returns true if GpuMat data is NULL
bool empty() const;
/*! includes several bit-fields:
- the magic signature
- continuity flag
- depth
- number of channels
*/
int flags;
//! the number of rows and columns
int rows, cols;
//! a distance between successive rows in bytes; includes the gap if any
size_t step;
//! pointer to the data
uchar* data;
//! pointer to the reference counter;
//! when GpuMat points to user-allocated data, the pointer is NULL
int* refcount;
//! helper fields used in locateROI and adjustROI
uchar* datastart;
const uchar* dataend;
//! allocator
Allocator* allocator;
};
//! creates continuous matrix
CV_EXPORTS void createContinuous(int rows, int cols, int type, OutputArray arr);
//! ensures that size of the given matrix is not less than (rows, cols) size
//! and matrix type is match specified one too
CV_EXPORTS void ensureSizeIsEnough(int rows, int cols, int type, OutputArray arr);
CV_EXPORTS GpuMat allocMatFromBuf(int rows, int cols, int type, GpuMat& mat);
//! BufferPool management (must be called before Stream creation)
CV_EXPORTS void setBufferPoolUsage(bool on);
CV_EXPORTS void setBufferPoolConfig(int deviceId, size_t stackSize, int stackCount);
//////////////////////////////// CudaMem ////////////////////////////////
// CudaMem is limited cv::Mat with page locked memory allocation.
// Page locked memory is only needed for async and faster coping to GPU.
// It is convertable to cv::Mat header without reference counting
// so you can use it with other opencv functions.
class CV_EXPORTS CudaMem
{
public:
enum AllocType { PAGE_LOCKED = 1, SHARED = 2, WRITE_COMBINED = 4 };
explicit CudaMem(AllocType alloc_type = PAGE_LOCKED);
CudaMem(const CudaMem& m);
CudaMem(int rows, int cols, int type, AllocType alloc_type = PAGE_LOCKED);
CudaMem(Size size, int type, AllocType alloc_type = PAGE_LOCKED);
//! creates from host memory with coping data
explicit CudaMem(InputArray arr, AllocType alloc_type = PAGE_LOCKED);
~CudaMem();
CudaMem& operator =(const CudaMem& m);
//! swaps with other smart pointer
void swap(CudaMem& b);
//! returns deep copy of the matrix, i.e. the data is copied
CudaMem clone() const;
//! allocates new matrix data unless the matrix already has specified size and type.
void create(int rows, int cols, int type);
void create(Size size, int type);
//! creates alternative CudaMem header for the same data, with different
//! number of channels and/or different number of rows
CudaMem reshape(int cn, int rows = 0) const;
//! decrements reference counter and released memory if needed.
void release();
//! returns matrix header with disabled reference counting for CudaMem data.
Mat createMatHeader() const;
//! maps host memory into device address space and returns GpuMat header for it. Throws exception if not supported by hardware.
GpuMat createGpuMatHeader() const;
// Please see cv::Mat for descriptions
bool isContinuous() const;
size_t elemSize() const;
size_t elemSize1() const;
int type() const;
int depth() const;
int channels() const;
size_t step1() const;
Size size() const;
bool empty() const;
// Please see cv::Mat for descriptions
int flags;
int rows, cols;
size_t step;
uchar* data;
int* refcount;
uchar* datastart;
const uchar* dataend;
AllocType alloc_type;
};
//! page-locks the matrix m memory and maps it for the device(s)
CV_EXPORTS void registerPageLocked(Mat& m);
//! unmaps the memory of matrix m, and makes it pageable again
CV_EXPORTS void unregisterPageLocked(Mat& m);
///////////////////////////////// Stream //////////////////////////////////
// Encapculates Cuda Stream. Provides interface for async coping.
// Passed to each function that supports async kernel execution.
// Reference counting is enabled.
class CV_EXPORTS Stream
{
typedef void (Stream::*bool_type)() const;
void this_type_does_not_support_comparisons() const {}
public:
typedef void (*StreamCallback)(int status, void* userData);
//! creates a new asynchronous stream
Stream();
//! queries an asynchronous stream for completion status
bool queryIfComplete() const;
//! waits for stream tasks to complete
void waitForCompletion();
//! makes a compute stream wait on an event
void waitEvent(const Event& event);
//! adds a callback to be called on the host after all currently enqueued items in the stream have completed
void enqueueHostCallback(StreamCallback callback, void* userData);
//! return Stream object for default CUDA stream
static Stream& Null();
//! returns true if stream object is not default (!= 0)
operator bool_type() const;
class Impl;
private:
Ptr<Impl> impl_;
Stream(const Ptr<Impl>& impl);
friend struct StreamAccessor;
friend class BufferPool;
};
class CV_EXPORTS Event
{
public:
enum CreateFlags
{
DEFAULT = 0x00, /**< Default event flag */
BLOCKING_SYNC = 0x01, /**< Event uses blocking synchronization */
DISABLE_TIMING = 0x02, /**< Event will not record timing data */
INTERPROCESS = 0x04 /**< Event is suitable for interprocess use. DisableTiming must be set */
};
explicit Event(CreateFlags flags = DEFAULT);
//! records an event
void record(Stream& stream = Stream::Null());
//! queries an event's status
bool queryIfComplete() const;
//! waits for an event to complete
void waitForCompletion();
//! computes the elapsed time between events
static float elapsedTime(const Event& start, const Event& end);
class Impl;
private:
Ptr<Impl> impl_;
friend struct EventAccessor;
};
//////////////////////////////// Initialization & Info ////////////////////////
//! this is the only function that do not throw exceptions if the library is compiled without CUDA
CV_EXPORTS int getCudaEnabledDeviceCount();
//! set device to be used for GPU executions for the calling host thread
CV_EXPORTS void setDevice(int device);
//! returns which device is currently being used for the calling host thread
CV_EXPORTS int getDevice();
//! explicitly destroys and cleans up all resources associated with the current device in the current process
//! any subsequent API call to this device will reinitialize the device
CV_EXPORTS void resetDevice();
enum FeatureSet
{
FEATURE_SET_COMPUTE_10 = 10,
FEATURE_SET_COMPUTE_11 = 11,
FEATURE_SET_COMPUTE_12 = 12,
FEATURE_SET_COMPUTE_13 = 13,
FEATURE_SET_COMPUTE_20 = 20,
FEATURE_SET_COMPUTE_21 = 21,
FEATURE_SET_COMPUTE_30 = 30,
FEATURE_SET_COMPUTE_35 = 35,
GLOBAL_ATOMICS = FEATURE_SET_COMPUTE_11,
SHARED_ATOMICS = FEATURE_SET_COMPUTE_12,
NATIVE_DOUBLE = FEATURE_SET_COMPUTE_13,
WARP_SHUFFLE_FUNCTIONS = FEATURE_SET_COMPUTE_30,
DYNAMIC_PARALLELISM = FEATURE_SET_COMPUTE_35
};
//! checks whether current device supports the given feature
CV_EXPORTS bool deviceSupports(FeatureSet feature_set);
//! information about what GPU archs this OpenCV CUDA module was compiled for
class CV_EXPORTS TargetArchs
{
public:
static bool builtWith(FeatureSet feature_set);
static bool has(int major, int minor);
static bool hasPtx(int major, int minor);
static bool hasBin(int major, int minor);
static bool hasEqualOrLessPtx(int major, int minor);
static bool hasEqualOrGreater(int major, int minor);
static bool hasEqualOrGreaterPtx(int major, int minor);
static bool hasEqualOrGreaterBin(int major, int minor);
};
//! information about the given GPU.
class CV_EXPORTS DeviceInfo
{
public:
//! creates DeviceInfo object for the current GPU
DeviceInfo();
//! creates DeviceInfo object for the given GPU
DeviceInfo(int device_id);
//! device number.
int deviceID() const;
//! ASCII string identifying device
const char* name() const;
//! global memory available on device in bytes
size_t totalGlobalMem() const;
//! shared memory available per block in bytes
size_t sharedMemPerBlock() const;
//! 32-bit registers available per block
int regsPerBlock() const;
//! warp size in threads
int warpSize() const;
//! maximum pitch in bytes allowed by memory copies
size_t memPitch() const;
//! maximum number of threads per block
int maxThreadsPerBlock() const;
//! maximum size of each dimension of a block
Vec3i maxThreadsDim() const;
//! maximum size of each dimension of a grid
Vec3i maxGridSize() const;
//! clock frequency in kilohertz
int clockRate() const;
//! constant memory available on device in bytes
size_t totalConstMem() const;
//! major compute capability
int majorVersion() const;
//! minor compute capability
int minorVersion() const;
//! alignment requirement for textures
size_t textureAlignment() const;
//! pitch alignment requirement for texture references bound to pitched memory
size_t texturePitchAlignment() const;
//! number of multiprocessors on device
int multiProcessorCount() const;
//! specified whether there is a run time limit on kernels
bool kernelExecTimeoutEnabled() const;
//! device is integrated as opposed to discrete
bool integrated() const;
//! device can map host memory with cudaHostAlloc/cudaHostGetDevicePointer
bool canMapHostMemory() const;
enum ComputeMode
{
ComputeModeDefault, /**< default compute mode (Multiple threads can use ::cudaSetDevice() with this device) */
ComputeModeExclusive, /**< compute-exclusive-thread mode (Only one thread in one process will be able to use ::cudaSetDevice() with this device) */
ComputeModeProhibited, /**< compute-prohibited mode (No threads can use ::cudaSetDevice() with this device) */
ComputeModeExclusiveProcess /**< compute-exclusive-process mode (Many threads in one process will be able to use ::cudaSetDevice() with this device) */
};
//! compute mode
ComputeMode computeMode() const;
//! maximum 1D texture size
int maxTexture1D() const;
//! maximum 1D mipmapped texture size
int maxTexture1DMipmap() const;
//! maximum size for 1D textures bound to linear memory
int maxTexture1DLinear() const;
//! maximum 2D texture dimensions
Vec2i maxTexture2D() const;
//! maximum 2D mipmapped texture dimensions
Vec2i maxTexture2DMipmap() const;
//! maximum dimensions (width, height, pitch) for 2D textures bound to pitched memory
Vec3i maxTexture2DLinear() const;
//! maximum 2D texture dimensions if texture gather operations have to be performed
Vec2i maxTexture2DGather() const;
//! maximum 3D texture dimensions
Vec3i maxTexture3D() const;
//! maximum Cubemap texture dimensions
int maxTextureCubemap() const;
//! maximum 1D layered texture dimensions
Vec2i maxTexture1DLayered() const;
//! maximum 2D layered texture dimensions
Vec3i maxTexture2DLayered() const;
//! maximum Cubemap layered texture dimensions
Vec2i maxTextureCubemapLayered() const;
//! maximum 1D surface size
int maxSurface1D() const;
//! maximum 2D surface dimensions
Vec2i maxSurface2D() const;
//! maximum 3D surface dimensions
Vec3i maxSurface3D() const;
//! maximum 1D layered surface dimensions
Vec2i maxSurface1DLayered() const;
//! maximum 2D layered surface dimensions
Vec3i maxSurface2DLayered() const;
//! maximum Cubemap surface dimensions
int maxSurfaceCubemap() const;
//! maximum Cubemap layered surface dimensions
Vec2i maxSurfaceCubemapLayered() const;
//! alignment requirements for surfaces
size_t surfaceAlignment() const;
//! device can possibly execute multiple kernels concurrently
bool concurrentKernels() const;
//! device has ECC support enabled
bool ECCEnabled() const;
//! PCI bus ID of the device
int pciBusID() const;
//! PCI device ID of the device
int pciDeviceID() const;
//! PCI domain ID of the device
int pciDomainID() const;
//! true if device is a Tesla device using TCC driver, false otherwise
bool tccDriver() const;
//! number of asynchronous engines
int asyncEngineCount() const;
//! device shares a unified address space with the host
bool unifiedAddressing() const;
//! peak memory clock frequency in kilohertz
int memoryClockRate() const;
//! global memory bus width in bits
int memoryBusWidth() const;
//! size of L2 cache in bytes
int l2CacheSize() const;
//! maximum resident threads per multiprocessor
int maxThreadsPerMultiProcessor() const;
//! gets free and total device memory
void queryMemory(size_t& totalMemory, size_t& freeMemory) const;
size_t freeMemory() const;
size_t totalMemory() const;
//! checks whether device supports the given feature
bool supports(FeatureSet feature_set) const;
//! checks whether the CUDA module can be run on the given device
bool isCompatible() const;
private:
int device_id_;
};
CV_EXPORTS void printCudaDeviceInfo(int device);
CV_EXPORTS void printShortCudaDeviceInfo(int device);
}} // namespace cv { namespace cuda {
#include "opencv2/core/cuda.inl.hpp"
#endif /* __OPENCV_CORE_CUDA_HPP__ */
| [
"[email protected]"
] | |
eb0903ce0a7cef421014696dc391adc0ede10331 | 3f880336b2f2dd2c947c204824fa2971a9ef14f3 | /Content/Assets/support/plugins/unreal/7.3/latest/win/4.24/MegascansPlugin/Source/MegascansPlugin/Private/Utilities/AssetData.cpp | 9aaade5abc09a80f77d2e164fb328ccca0ffa5ab | [] | no_license | SUTT0142/HorrorGame | df4510fcab55b3bf2f2af682306a7a8741451b9f | a4289a72f582634ad9cd1d37100962b57eab030c | refs/heads/master | 2023-09-05T19:04:15.660567 | 2021-11-10T00:47:16 | 2021-11-10T00:47:16 | 415,548,285 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,739 | cpp | // Copyright Epic Games, Inc. All Rights Reserved.
#include "AssetData.h"
#include "Utilities/MiscUtils.h"
#include "UI/MSSettings.h"
#include "EditorAssetLibrary.h"
#include "Utilities/MTSReader.h"
TSharedPtr<FAssetImportParams> FAssetImportParams::ImportParamsInst;
TSharedPtr<FAssetImportParams> FAssetImportParams::Get()
{
if (!ImportParamsInst.IsValid())
{
ImportParamsInst = MakeShareable(new FAssetImportParams);
}
return ImportParamsInst;
}
TSharedPtr<ImportParams3DAsset> FAssetImportParams::Get3DAssetsParams(TSharedPtr<FAssetTypeData> AssetImportData)
{
TSharedPtr<ImportParams3DAsset> AssetParams = MakeShareable(new ImportParams3DAsset);
TSharedPtr<Asset3DParams> Asset3DParameters = MakeShareable(new Asset3DParams);
int8 Count = 0;
do {
const UMaterialAssetSettings* MatAssetPathsSettings = GetDefault<UMaterialAssetSettings>();
TSharedPtr<SurfaceParams> MaterialParams = MakeShareable(new SurfaceParams);
AssetParams->BaseParams = GetAssetImportParams(AssetImportData);
Asset3DParameters->SubType = Get3DSubtype(AssetImportData);
Asset3DParameters->MeshDestination = AssetParams->BaseParams->AssetDestination;
Asset3DParameters->Asset3DMaterialType = GetS3DMasterMaterialType(AssetImportData, Count);
//TODO : create mapping of material with texture sets
if (Asset3DParameters->Asset3DMaterialType != ES3DMasterMaterialType::CUSTOM) {
MaterialParams->MasterMaterialName = MasterMaterialType[Asset3DParameters->Asset3DMaterialType];
MaterialParams->MasterMaterialPath = GetMasterMaterial(MaterialParams->MasterMaterialName);
}
else
{
MaterialParams->MasterMaterialName = TEXT("Custom");
MaterialParams->MasterMaterialPath = MatAssetPathsSettings->MasterMaterial3d;
}
MaterialParams->MaterialInstanceDestination = AssetParams->BaseParams->AssetDestination;
if (AssetImportData->AssetMetaInfo->bIsMTS) {
MaterialParams->MaterialInstanceName = AssetImportData->MaterialList[Count]->MaterialName + TEXT("_inst");
}
else {
MaterialParams->MaterialInstanceName = AssetParams->BaseParams->AssetName + TEXT("_inst");
}
MaterialParams->TexturesDestination = AssetParams->BaseParams->AssetDestination;
MaterialParams->bContainsPackedMaps = (AssetImportData->PackedTextures.Num() > 0) ? true : false;
Asset3DParameters->MaterialParams.Add(MaterialParams);
Count++;
} while (Count < AssetImportData->MaterialList.Num());//&& !AssetImportData->AssetMetaInfo->bIsUdim);//FMTSHandler::Get()->MTSJson.materials.Num());
AssetParams->ParamsAssetType = Asset3DParameters;
return AssetParams;
}
ES3DMasterMaterialType FAssetImportParams::GetS3DMasterMaterialType(TSharedPtr<FAssetTypeData> AssetImportData, int8 Count)
{
const UMegascansSettings* MegascansSettings = GetDefault<UMegascansSettings>();
const UMaterialAssetSettings* MatAssetPathsSettings = GetDefault<UMaterialAssetSettings>();
if (AssetImportData->AssetMetaInfo->Type == TEXT("3d") && MatAssetPathsSettings->MasterMaterial3d != "None" && MatAssetPathsSettings->MasterMaterial3d != "")
{
if (UEditorAssetLibrary::DoesAssetExist(MatAssetPathsSettings->MasterMaterial3d))
{
return ES3DMasterMaterialType::CUSTOM;
}
}
if (AssetImportData->AssetMetaInfo->Type == TEXT("surface") && MatAssetPathsSettings->MasterMaterialSurface != "None" && MatAssetPathsSettings->MasterMaterialSurface != "")
{
if (UEditorAssetLibrary::DoesAssetExist(MatAssetPathsSettings->MasterMaterialSurface))
{
return ES3DMasterMaterialType::CUSTOM;
}
}
if (AssetImportData->AssetMetaInfo->bIsModularWindow) {
if (AssetImportData->MaterialList[Count]->OpacityType == "Transparent") {
return ES3DMasterMaterialType::MODULAR_WINDOWS;
}
}
if (AssetImportData->PackedTextures.Num() > 0) {
if (AssetImportData->AssetMetaInfo->bIsUdim) {
return ES3DMasterMaterialType::CHANNEL_PACK_UDIM;
}
else {
return ES3DMasterMaterialType::CHANNEL_PACK;
}
}
if (MegascansSettings->bEnableDisplacement) {
return ES3DMasterMaterialType::NORMAL_DISPLACEMENT;
}
// FAssetTextureData type in auto
for (auto& TextureComponent : AssetImportData->TextureComponents)
{
if (TextureComponent->Type == TEXT("fuzz")) {
return ES3DMasterMaterialType::NORMAL_FUZZ;
}
}
if (AssetImportData->AssetMetaInfo->bIsUdim) {
return ES3DMasterMaterialType::UDIM;
}
return ES3DMasterMaterialType::NORMAL;
}
E3DPlantBillboardMaterial FAssetImportParams::GetBillboardMaterialType(TSharedPtr<FAssetTypeData> AssetImportData)
{
// Type of master material for billboards
return (AssetImportData->AssetMetaInfo->bUseBillboardMaterial) ? E3DPlantBillboardMaterial::CAMERA_FACING : E3DPlantBillboardMaterial::NORMAL_BILLBOARD;
}
TSharedPtr<ImportParamsSurfaceAsset> FAssetImportParams::GetSurfaceParams(TSharedPtr<FAssetTypeData> AssetImportData)
{
int8 Count = 0;
TSharedPtr< ImportParamsSurfaceAsset> AssetParams = MakeShareable(new ImportParamsSurfaceAsset);
AssetParams->BaseParams = GetAssetImportParams(AssetImportData);
const UMaterialAssetSettings* MatAssetPathsSettings = GetDefault<UMaterialAssetSettings>();
TSharedPtr<SurfaceParams> SurfaceParameters = MakeShareable( new SurfaceParams);
SurfaceParameters->SSubType = GetSurfaceSubtype(AssetImportData);
SurfaceParameters->MasterMaterialPath = TEXT("");
SurfaceParameters->MasterMaterialName = (SurfaceParameters->SSubType != ESurfaceSubType::SURFACE) ? SurfaceSubTypeMaterials[SurfaceParameters->SSubType] :MasterMaterialType[GetS3DMasterMaterialType(AssetImportData, Count)];
if (SurfaceParameters->MasterMaterialName == TEXT("Custom"))
{
SurfaceParameters->MasterMaterialPath = MatAssetPathsSettings->MasterMaterialSurface;
}
else {
SurfaceParameters->MasterMaterialPath = GetMasterMaterial(SurfaceParameters->MasterMaterialName);
}
SurfaceParameters->MaterialInstanceDestination = AssetParams->BaseParams->AssetDestination;
SurfaceParameters->MaterialInstanceName = AssetParams->BaseParams->AssetName + TEXT("_inst");
SurfaceParameters->TexturesDestination = AssetParams->BaseParams->AssetDestination;
SurfaceParameters->bContainsPackedMaps = (AssetImportData->PackedTextures.Num() > 0) ? true : false;
AssetParams->ParamsAssetType = SurfaceParameters;
return AssetParams;
}
TSharedPtr<ImportParams3DPlantAsset> FAssetImportParams::Get3DPlantParams(TSharedPtr<FAssetTypeData> AssetImportData)
{
TSharedPtr<ImportParams3DPlantAsset> AssetParams = MakeShareable(new ImportParams3DPlantAsset);
AssetParams->BaseParams = GetAssetImportParams(AssetImportData);
AssetParams->ParamsAssetType = MakeShareable(new Asset3DPlantParams);
const UMaterialAssetSettings* MatAssetPathsSettings = GetDefault<UMaterialAssetSettings>();
AssetParams->ParamsAssetType->FoliageDestination = FPaths::Combine(AssetParams->BaseParams->AssetDestination, TEXT("Foliage"));
AssetParams->ParamsAssetType->MeshDestination = AssetParams->BaseParams->AssetDestination;
//Plants main master material parameters
TSharedPtr < SurfaceParams> MasterMaterialParams = MakeShareable( new SurfaceParams);
MasterMaterialParams->MaterialInstanceDestination = AssetParams->BaseParams->AssetDestination;
MasterMaterialParams->MaterialInstanceName = AssetParams->BaseParams->AssetName + TEXT("_inst");
MasterMaterialParams->TexturesDestination = AssetParams->BaseParams->AssetDestination;
MasterMaterialParams->MasterMaterialName = PlantsMasterMaterial;
MasterMaterialParams->MasterMaterialPath = GetMasterMaterial(MasterMaterialParams->MasterMaterialName);
if (MatAssetPathsSettings->MasterMaterialPlant != "None" && MatAssetPathsSettings->MasterMaterialPlant != "")
{
if (UEditorAssetLibrary::DoesAssetExist(MatAssetPathsSettings->MasterMaterialPlant))
{
MasterMaterialParams->MasterMaterialName = TEXT("Custom");
MasterMaterialParams->MasterMaterialPath = MatAssetPathsSettings->MasterMaterialPlant;
}
}
//MasterMaterialParams->bContainsPackedMaps = (AssetImportData->PackedTextures.Num() > 0) ? true : false;
//MasterMaterialParams->SSubType = ESurfaceSubType::SURFACE;
AssetParams->ParamsAssetType->PlantsMasterMaterial = MasterMaterialParams;
//Plants billboard master material parameters
TSharedPtr < SurfaceParams> BillboardMasterParams = MakeShareable( new SurfaceParams) ;
BillboardMasterParams->MasterMaterialName = BillboardMaterials[GetBillboardMaterialType(AssetImportData)];
BillboardMasterParams->MaterialInstanceDestination = FPaths::Combine(AssetParams->BaseParams->AssetDestination, TEXT("Billboard"));
BillboardMasterParams->MaterialInstanceName = AssetParams->BaseParams->AssetName + TEXT("_Billboard_inst");
BillboardMasterParams->TexturesDestination = BillboardMasterParams->MaterialInstanceDestination;
BillboardMasterParams->MasterMaterialPath = GetMasterMaterial(BillboardMasterParams->MasterMaterialName);
AssetParams->ParamsAssetType->BillboardMasterMaterial = BillboardMasterParams;
return AssetParams;
}
TSharedPtr<AssetImportParams> FAssetImportParams::GetAssetImportParams(TSharedPtr<FAssetTypeData> AssetImportData)
{
TSharedPtr<AssetImportParams> AssetImportparameters = MakeShareable(new AssetImportParams);
FString AssetType = AssetImportData->AssetMetaInfo->Type;
FString RootDestination = GetRootDestination(AssetImportData->AssetMetaInfo->ExportPath);
FString AssetTypePath = GetAssetTypePath(RootDestination, AssetImportData->AssetMetaInfo->Type);
FString AssetNameOverride = AssetImportData->AssetMetaInfo->FolderNamingConvention;
if (AssetNameOverride == TEXT(""))
{
AssetNameOverride = AssetImportData->AssetMetaInfo->Name;
}
AssetImportparameters->AssetName = GetUniqueAssetName(AssetTypePath, RemoveReservedKeywords(NormalizeString(AssetNameOverride)));
AssetImportparameters->AssetDestination = FPaths::Combine(AssetTypePath, AssetImportparameters->AssetName);
return AssetImportparameters;
}
TSharedPtr<ImportParamsSurfaceAsset> FAssetImportParams::GetAtlasBrushParams(TSharedPtr<FAssetTypeData> AssetImportData)
{
TSharedPtr< ImportParamsSurfaceAsset> AssetParams = MakeShareable(new ImportParamsSurfaceAsset);
AssetParams->BaseParams = GetAssetImportParams(AssetImportData);
TSharedPtr<SurfaceParams> SurfaceParameters = MakeShareable(new SurfaceParams);
SurfaceParameters->MasterMaterialName = (AssetImportData->AssetMetaInfo->Type == TEXT("atlas")) ? AtlasSubTypeMaterials[GetAtlasSubtype(AssetImportData)] : BrushMasterMaterial;
SurfaceParameters->MasterMaterialPath = GetMasterMaterial(SurfaceParameters->MasterMaterialName);
SurfaceParameters->MaterialInstanceDestination = AssetParams->BaseParams->AssetDestination;
SurfaceParameters->MaterialInstanceName = AssetParams->BaseParams->AssetName + TEXT("_inst");
SurfaceParameters->TexturesDestination = AssetParams->BaseParams->AssetDestination;
SurfaceParameters->bContainsPackedMaps = false;
AssetParams->ParamsAssetType = SurfaceParameters;
return AssetParams;
}
FString FAssetImportParams::GetAssetTypePath(const FString& RootDestination, const FString& AssetType)
{
TMap<FString, FString> TypeNames = {
{TEXT("3d"),TEXT("3D_Assets")},
{TEXT("3dplant"),TEXT("3D_Plants")},
{TEXT("surface"),TEXT("Surfaces")},
{TEXT("atlas"),TEXT("Atlases")},
{TEXT("brush"),TEXT("Brushes")},
{TEXT("3datlas"),TEXT("3D_Atlases")}
};
return FPaths::Combine(RootDestination, TypeNames[AssetType]);
}
EAtlasSubType FAssetImportParams::GetAtlasSubtype(TSharedPtr<FAssetTypeData> AssetImportData)
{
auto& TagsList = AssetImportData->AssetMetaInfo->Tags;
return (!TagsList.Contains(TEXT("decal"))) ? EAtlasSubType::ATLAS: EAtlasSubType::DECAL;
}
ESurfaceSubType FAssetImportParams::GetSurfaceSubtype(TSharedPtr<FAssetTypeData> AssetImportData)
{
auto& TagsList = AssetImportData->AssetMetaInfo->Tags;
return (TagsList.Contains(TEXT("metal"))) ? ESurfaceSubType::METAL : (TagsList.Contains(TEXT("surface imperfection"))) ? ESurfaceSubType::IMPERFECTION : (TagsList.Contains(TEXT("tileable displacement"))) ? ESurfaceSubType::DISPLACEMENT : ESurfaceSubType::SURFACE;
}
EAsset3DSubtype FAssetImportParams::Get3DSubtype(TSharedPtr<FAssetTypeData> AssetImportData)
{
return (AssetImportData->AssetMetaInfo->Categories.Contains(TEXT("scatter")) || AssetImportData->AssetMetaInfo->Tags.Contains(TEXT("scatter")) || AssetImportData->AssetMetaInfo->Categories.Contains(TEXT("cmb_asset")) || AssetImportData->AssetMetaInfo->Tags.Contains(TEXT("cmb_asset")) || AssetImportData->AssetMetaInfo->bIsMTS) ? EAsset3DSubtype::MULTI_MESH : EAsset3DSubtype::NORMAL_3D;
}
FString FAssetImportParams::GetMasterMaterial(const FString& SelectedMaterial)
{
ManageMaterialVersion(SelectedMaterial);
CopyPresetTextures();
FString MaterialPath = GetMaterial(SelectedMaterial);
return (MaterialPath == TEXT("")) ? TEXT("") : MaterialPath;
}
| [
"[email protected]"
] | |
6d660896116c2963d57b0850ed5b6b1b59c68234 | 3cf9e141cc8fee9d490224741297d3eca3f5feff | /C++ Benchmark Programs/Benchmark Files 1/classtester/autogen-sources/source-15326.cpp | bed45a28d4818f5e72284a4791d111d0e777b216 | [] | no_license | TeamVault/tauCFI | e0ac60b8106fc1bb9874adc515fc01672b775123 | e677d8cc7acd0b1dd0ac0212ff8362fcd4178c10 | refs/heads/master | 2023-05-30T20:57:13.450360 | 2021-06-14T09:10:24 | 2021-06-14T09:10:24 | 154,563,655 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,823 | cpp | struct c0;
void __attribute__ ((noinline)) tester0(c0* p);
struct c0
{
bool active0;
c0() : active0(true) {}
virtual ~c0()
{
tester0(this);
active0 = false;
}
virtual void f0(){}
};
void __attribute__ ((noinline)) tester0(c0* p)
{
p->f0();
}
struct c1;
void __attribute__ ((noinline)) tester1(c1* p);
struct c1 : virtual c0
{
bool active1;
c1() : active1(true) {}
virtual ~c1()
{
tester1(this);
c0 *p0_0 = (c0*)(c1*)(this);
tester0(p0_0);
active1 = false;
}
virtual void f1(){}
};
void __attribute__ ((noinline)) tester1(c1* p)
{
p->f1();
if (p->active0)
p->f0();
}
struct c2;
void __attribute__ ((noinline)) tester2(c2* p);
struct c2 : virtual c0
{
bool active2;
c2() : active2(true) {}
virtual ~c2()
{
tester2(this);
c0 *p0_0 = (c0*)(c2*)(this);
tester0(p0_0);
active2 = false;
}
virtual void f2(){}
};
void __attribute__ ((noinline)) tester2(c2* p)
{
p->f2();
if (p->active0)
p->f0();
}
struct c3;
void __attribute__ ((noinline)) tester3(c3* p);
struct c3 : virtual c1
{
bool active3;
c3() : active3(true) {}
virtual ~c3()
{
tester3(this);
c0 *p0_0 = (c0*)(c1*)(c3*)(this);
tester0(p0_0);
c1 *p1_0 = (c1*)(c3*)(this);
tester1(p1_0);
active3 = false;
}
virtual void f3(){}
};
void __attribute__ ((noinline)) tester3(c3* p)
{
p->f3();
if (p->active0)
p->f0();
if (p->active1)
p->f1();
}
struct c4;
void __attribute__ ((noinline)) tester4(c4* p);
struct c4 : virtual c1, virtual c3
{
bool active4;
c4() : active4(true) {}
virtual ~c4()
{
tester4(this);
c0 *p0_0 = (c0*)(c1*)(c4*)(this);
tester0(p0_0);
c0 *p0_1 = (c0*)(c1*)(c3*)(c4*)(this);
tester0(p0_1);
c1 *p1_0 = (c1*)(c4*)(this);
tester1(p1_0);
c1 *p1_1 = (c1*)(c3*)(c4*)(this);
tester1(p1_1);
c3 *p3_0 = (c3*)(c4*)(this);
tester3(p3_0);
active4 = false;
}
virtual void f4(){}
};
void __attribute__ ((noinline)) tester4(c4* p)
{
p->f4();
if (p->active0)
p->f0();
if (p->active1)
p->f1();
if (p->active3)
p->f3();
}
int __attribute__ ((noinline)) inc(int v) {return ++v;}
int main()
{
c0* ptrs0[25];
ptrs0[0] = (c0*)(new c0());
ptrs0[1] = (c0*)(c1*)(new c1());
ptrs0[2] = (c0*)(c2*)(new c2());
ptrs0[3] = (c0*)(c1*)(c3*)(new c3());
ptrs0[4] = (c0*)(c1*)(c4*)(new c4());
ptrs0[5] = (c0*)(c1*)(c3*)(c4*)(new c4());
for (int i=0;i<6;i=inc(i))
{
tester0(ptrs0[i]);
delete ptrs0[i];
}
c1* ptrs1[25];
ptrs1[0] = (c1*)(new c1());
ptrs1[1] = (c1*)(c3*)(new c3());
ptrs1[2] = (c1*)(c4*)(new c4());
ptrs1[3] = (c1*)(c3*)(c4*)(new c4());
for (int i=0;i<4;i=inc(i))
{
tester1(ptrs1[i]);
delete ptrs1[i];
}
c2* ptrs2[25];
ptrs2[0] = (c2*)(new c2());
for (int i=0;i<1;i=inc(i))
{
tester2(ptrs2[i]);
delete ptrs2[i];
}
c3* ptrs3[25];
ptrs3[0] = (c3*)(new c3());
ptrs3[1] = (c3*)(c4*)(new c4());
for (int i=0;i<2;i=inc(i))
{
tester3(ptrs3[i]);
delete ptrs3[i];
}
c4* ptrs4[25];
ptrs4[0] = (c4*)(new c4());
for (int i=0;i<1;i=inc(i))
{
tester4(ptrs4[i]);
delete ptrs4[i];
}
return 0;
}
| [
"[email protected]"
] | |
22e5b6431cad519b7f382c13c729abed197392f1 | 0b8fd5b8fc96e444f4765becb8524962d7fec51e | /main.cpp | d25ecb2aa934f40011df62b4a23268c627e8ed58 | [] | no_license | ArcoMul/hangine | ea8bb8434b6d71cb1598f95cb11d0f77f6582c67 | 592a148956b0f6386f71a32d5d42607cffc8ea3a | refs/heads/master | 2020-06-08T18:17:05.179949 | 2012-12-30T15:55:18 | 2012-12-30T15:55:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,290 | cpp | //Include OpenGL header files, so that we can use OpenGL
/*#include <iostream>
#include <stdlib.h> //Needed for "exit" function
#ifdef __APPLE__
#include <OpenGL/OpenGL.h>
#include <GLUT/glut.h>
#else
#include <glut.h>
#endif
#include "point.h"
#include "Vector3.h"
#include "Terrain.h"
using namespace std;
/*!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
* FIELDS
*!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/
/*
//Called when a key is pressed
void handleKeypress(unsigned char key, //The key that was pressed
int x, int y) { //The current mouse coordinates
switch (key) {
case 27: //Escape key
exit(0); //Exit the program
}
}
//Initializes 3D rendering
void Initialize() {
glEnable(GL_DEPTH_TEST);
glEnable(GL_COLOR_MATERIAL);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glEnable(GL_NORMALIZE);
glShadeModel(GL_SMOOTH);
}
//Called when the window is resized
void handleResize(int w, int h) {
//Tell OpenGL how to convert from coordinates to pixel values
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION); //Switch to setting the camera perspective
//Set the camera perspective
glLoadIdentity(); //Reset the camera
gluPerspective(45.0, //The camera angle
(double)w / (double)h, //The width-to-height ratio
1.0, //The near z clipping coordinate. If something is closer than 1 it won't be drawed
200.0); //The far z clipping coordinate. If something is further than 200 it won't be drawed
}
//Draws the 3D scene
void Draw() {
//Clear information from last draw
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(0.0f, 0.0f, -10.0f);
glRotatef(30.0f, 1.0f, 0.0f, 0.0f);
glRotatef(-60, 0.0f, 1.0f, 0.0f);
GLfloat ambientColor[] = {0.4f, 0.4f, 0.4f, 1.0f};
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, ambientColor);
GLfloat lightColor0[] = {0.6f, 0.6f, 0.6f, 1.0f};
GLfloat lightPos0[] = {-0.5f, 0.8f, 0.1f, 0.0f};
glLightfv(GL_LIGHT0, GL_DIFFUSE, lightColor0);
glLightfv(GL_LIGHT0, GL_POSITION, lightPos0);
float scale = 5.0f / max(128- 1, 128 - 1);
glScalef(scale, scale, scale);
glTranslatef(-(float)(128 - 1) / 2,
0.0f,
-(float)(128 - 1) / 2);
//_terrain->Draw();
glutSwapBuffers();
}
void Update(int value)
{
glutPostRedisplay();
glutTimerFunc(25, Update, 0);
}
/*!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
* START of the engine
*!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
void main(int argc, char** argv) {
//Initialize GLUT. Don't put code before this, otherwise the programm wil start slower
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(1280, 720); //Set the window size
//Create the window
glutCreateWindow("Hangine - editor");
Initialize(); //Initialize rendering
//Set handler functions for drawing, keypresses, and window resizes
glutDisplayFunc(Draw);
glutKeyboardFunc(handleKeypress);
glutReshapeFunc(handleResize);
glutTimerFunc(25, Update, 0);
glutMainLoop(); //Start the main loop. glutMainLoop doesn't return.
}
*/
| [
"[email protected]"
] | |
8de88ef2931589245841f492c2664a5ee49882cf | 955a639f380272dae0aad59659343ed035bea4f7 | /SLabCoreLib/Simulator/FS/FSBySpringStructuralIntrinsicsMTVectorizedSimulator.h | 44661b3eb9f963744f4e765161479b0a84322b66 | [
"CC-BY-4.0"
] | permissive | GabrieleGiuseppini/SpringLab | 29607cfd96b8056a4cad5dd177cac34f13e1d1f7 | da44ed79f660057cedcd7b7ec7876d4d17070278 | refs/heads/master | 2023-07-28T04:22:14.031259 | 2023-07-19T14:45:34 | 2023-07-19T14:45:34 | 264,458,602 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,429 | h | /***************************************************************************************
* Original Author: Gabriele Giuseppini
* Created: 2023-04-15
* Copyright: Gabriele Giuseppini (https://github.com/GabrieleGiuseppini)
***************************************************************************************/
#pragma once
#include "FSBySpringStructuralIntrinsicsSimulator.h"
#include "Buffer.h"
#include "Simulator/Common/ISimulator.h"
#include "Vectors.h"
#include <memory>
#include <string>
#include <vector>
/*
* Simulator implementing the same spring relaxation algorithm
* as in the "By Spring" - "Structural Intrinsics" simulator,
* but with multiple threads *and* with vectorized integration.
*/
class FSBySpringStructuralIntrinsicsMTVectorizedSimulator : public FSBySpringStructuralIntrinsicsSimulator
{
public:
static std::string GetSimulatorName()
{
return "FS 14 - By Spring - Structural Instrinsics - MT - Vectorized";
}
using layout_optimizer = FSBySpringStructuralIntrinsicsLayoutOptimizer;
public:
FSBySpringStructuralIntrinsicsMTVectorizedSimulator(
Object const & object,
SimulationParameters const & simulationParameters,
ThreadManager const & threadManager);
private:
virtual void CreateState(
Object const & object,
SimulationParameters const & simulationParameters,
ThreadManager const & threadManager) override;
void ApplySpringsForces(
Object const & object,
ThreadManager & threadManager) override;
void IntegrateAndResetSpringForces(
Object & object,
SimulationParameters const & simulationParameters) override;
void IntegrateAndResetSpringForces_1(
Object & object,
SimulationParameters const & simulationParameters);
void IntegrateAndResetSpringForces_2(
Object & object,
SimulationParameters const & simulationParameters);
void IntegrateAndResetSpringForces_4(
Object & object,
SimulationParameters const & simulationParameters);
void IntegrateAndResetSpringForces_N(
Object & object,
SimulationParameters const & simulationParameters);
private:
std::vector<typename ThreadPool::Task> mSpringRelaxationTasks;
std::vector<Buffer<vec2f>> mPointSpringForceBuffers;
std::vector<float * restrict> mPointSpringForceBuffersVectorized;
};
| [
"[email protected]"
] | |
73bd481624d3a050d63eb2366e0e2f3c9e24994e | f398bfcd9f31f7552b957506e50df2771f0d11b7 | /20190126/SmartPointer/shared_ptr.cc | c696a65206267626b118cee283b91e5d2afdbc97 | [] | no_license | bigfei123/learngit | 886e0ebe8ea908b3596b58b6491a57e9e7877696 | 9345fd85f4005ac96646cb5f9db4c5d2e308755a | refs/heads/master | 2020-04-15T16:06:42.075706 | 2019-04-18T11:24:43 | 2019-04-18T11:24:43 | 164,820,516 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,134 | cc | ///
/// @file shared_ptr.cc
/// @author [email protected])
/// @date 2019-02-01 17:47:50
///
#include <iostream>
#include <memory>
#include <vector>
using std::cout;
using std::endl;
using std::vector;
using std::shared_ptr;
class Point
{
public:
Point(int ix = 0, int iy = 0)
: _ix(ix)
, _iy(iy)
{ cout << "Point(int,int)" << endl;}
void display() const
{
cout << "(" << _ix
<< "," << _iy
<< ")" << endl;
}
~Point()
{ cout << "~Point()" << endl; }
private:
int _ix;
int _iy;
};
int main()
{
shared_ptr<int> up(new int(10));
cout << "*up = " << *up << endl;
cout << "up's get() = " << up.get() << endl;
cout << "up's use_count = " << up.use_count() << endl;
cout << ">>>up2" << endl;
shared_ptr<int> up2(up); //共享所有权的指针
//进行复制或者赋值时,将引用计数+1
//当up2被销毁时,引用计数-1
cout << "*up = " << *up << endl;
cout << "up's get() = " << up.get() << endl;
cout << "up's use_count = " << up.use_count() << endl;
cout << "*up2 = " << *up2 << endl;
cout << "up2's get() = " << up2.get() << endl;
cout << "up2's use_count = " << up2.use_count() << endl;
cout << ">>>up3" << endl;
shared_ptr<int> up3(new int(1));
up3 = up;
cout << "*up = " << *up << endl;
cout << "up's get() = " << up.get() << endl;
cout << "up's use_count = " << up.use_count() << endl;
cout << "*up3 = " << *up3 << endl;
cout << "up3's get() = " << up3.get() << endl;
cout << "up3's use_count = " << up3.use_count() << endl;
cout << ">>>up4" << endl;
shared_ptr<int> up4(std::move(up));//通过移动语义转移资源的所有权
//具有移动语义
cout << "*up4= " << *up4<< endl;
cout << "up4's get() = " << up4.get() << endl;
cout << "up4's use_count = " << up4.use_count() << endl;
cout << "*up3 = " << *up3 << endl;
cout << "up3's get() = " << up3.get() << endl;
cout << "up3's use_count = " << up3.use_count() << endl;
shared_ptr<Point> sp(new Point(3, 4));
sp->display();
vector<shared_ptr<Point>> points;
points.push_back(shared_ptr<Point>(new Point(1, 2)));
points.push_back(sp);
return 0;
}
| [
"[email protected]"
] | |
9db2995e42c2e9d8ccbd7d64c7b2c96c9525a375 | 5f919f448d074caa4cb932fab8f829f8b480b873 | /src/txmempool.h | e2a207c1dde7925952f6967de92bc332d6889504 | [
"MIT"
] | permissive | swatchie-1/hilux | 9849440fe25548d0f97f0cb5d88f4deff1140204 | 8d8e9f93144829b65868d051fcc08f7e28610daa | refs/heads/master | 2021-07-19T20:46:43.779686 | 2020-03-03T21:16:29 | 2020-03-03T21:16:29 | 141,552,658 | 7 | 10 | MIT | 2020-04-22T21:53:24 | 2018-07-19T09:02:00 | C++ | UTF-8 | C++ | false | false | 28,014 | h | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef HILUX_TXMEMPOOL_H
#define HILUX_TXMEMPOOL_H
#include <list>
#include <set>
#include "addressindex.h"
#include "spentindex.h"
#include "amount.h"
#include "coins.h"
#include "primitives/transaction.h"
#include "sync.h"
#undef foreach
#include "boost/multi_index_container.hpp"
#include "boost/multi_index/ordered_index.hpp"
class CAutoFile;
class CBlockIndex;
inline double AllowFreeThreshold()
{
return COIN * 144 / 250;
}
inline bool AllowFree(double dPriority)
{
// Large (in bytes) low-priority (new, small-coin) transactions
// need a fee.
return dPriority > AllowFreeThreshold();
}
/** Fake height value used in Coin to signify they are only in the memory pool (since 0.8) */
static const uint32_t MEMPOOL_HEIGHT = 0x7FFFFFFF;
struct LockPoints
{
// Will be set to the blockchain height and median time past
// values that would be necessary to satisfy all relative locktime
// constraints (BIP68) of this tx given our view of block chain history
int height;
int64_t time;
// As long as the current chain descends from the highest height block
// containing one of the inputs used in the calculation, then the cached
// values are still valid even after a reorg.
CBlockIndex* maxInputBlock;
LockPoints() : height(0), time(0), maxInputBlock(NULL) { }
};
class CTxMemPool;
/** \class CTxMemPoolEntry
*
* CTxMemPoolEntry stores data about the correponding transaction, as well
* as data about all in-mempool transactions that depend on the transaction
* ("descendant" transactions).
*
* When a new entry is added to the mempool, we update the descendant state
* (nCountWithDescendants, nSizeWithDescendants, and nModFeesWithDescendants) for
* all ancestors of the newly added transaction.
*
* If updating the descendant state is skipped, we can mark the entry as
* "dirty", and set nSizeWithDescendants/nModFeesWithDescendants to equal nTxSize/
* nFee+feeDelta. (This can potentially happen during a reorg, where we limit the
* amount of work we're willing to do to avoid consuming too much CPU.)
*
*/
class CTxMemPoolEntry
{
private:
CTransaction tx;
CAmount nFee; //! Cached to avoid expensive parent-transaction lookups
size_t nTxSize; //! ... and avoid recomputing tx size
size_t nModSize; //! ... and modified size for priority
size_t nUsageSize; //! ... and total memory usage
int64_t nTime; //! Local time when entering the mempool
double entryPriority; //! Priority when entering the mempool
unsigned int entryHeight; //! Chain height when entering the mempool
bool hadNoDependencies; //! Not dependent on any other txs when it entered the mempool
CAmount inChainInputValue; //! Sum of all txin values that are already in blockchain
bool spendsCoinbase; //! keep track of transactions that spend a coinbase
unsigned int sigOpCount; //! Legacy sig ops plus P2SH sig op count
int64_t feeDelta; //! Used for determining the priority of the transaction for mining in a block
LockPoints lockPoints; //! Track the height and time at which tx was final
// Information about descendants of this transaction that are in the
// mempool; if we remove this transaction we must remove all of these
// descendants as well. if nCountWithDescendants is 0, treat this entry as
// dirty, and nSizeWithDescendants and nModFeesWithDescendants will not be
// correct.
uint64_t nCountWithDescendants; //! number of descendant transactions
uint64_t nSizeWithDescendants; //! ... and size
CAmount nModFeesWithDescendants; //! ... and total fees (all including us)
public:
CTxMemPoolEntry(const CTransaction& _tx, const CAmount& _nFee,
int64_t _nTime, double _entryPriority, unsigned int _entryHeight,
bool poolHasNoInputsOf, CAmount _inChainInputValue, bool spendsCoinbase,
unsigned int nSigOps, LockPoints lp);
CTxMemPoolEntry(const CTxMemPoolEntry& other);
const CTransaction& GetTx() const { return this->tx; }
/**
* Fast calculation of lower bound of current priority as update
* from entry priority. Only inputs that were originally in-chain will age.
*/
double GetPriority(unsigned int currentHeight) const;
const CAmount& GetFee() const { return nFee; }
size_t GetTxSize() const { return nTxSize; }
int64_t GetTime() const { return nTime; }
unsigned int GetHeight() const { return entryHeight; }
bool WasClearAtEntry() const { return hadNoDependencies; }
unsigned int GetSigOpCount() const { return sigOpCount; }
int64_t GetModifiedFee() const { return nFee + feeDelta; }
size_t DynamicMemoryUsage() const { return nUsageSize; }
const LockPoints& GetLockPoints() const { return lockPoints; }
// Adjusts the descendant state, if this entry is not dirty.
void UpdateState(int64_t modifySize, CAmount modifyFee, int64_t modifyCount);
// Updates the fee delta used for mining priority score, and the
// modified fees with descendants.
void UpdateFeeDelta(int64_t feeDelta);
// Update the LockPoints after a reorg
void UpdateLockPoints(const LockPoints& lp);
/** We can set the entry to be dirty if doing the full calculation of in-
* mempool descendants will be too expensive, which can potentially happen
* when re-adding transactions from a block back to the mempool.
*/
void SetDirty();
bool IsDirty() const { return nCountWithDescendants == 0; }
uint64_t GetCountWithDescendants() const { return nCountWithDescendants; }
uint64_t GetSizeWithDescendants() const { return nSizeWithDescendants; }
CAmount GetModFeesWithDescendants() const { return nModFeesWithDescendants; }
bool GetSpendsCoinbase() const { return spendsCoinbase; }
};
// Helpers for modifying CTxMemPool::mapTx, which is a boost multi_index.
struct update_descendant_state
{
update_descendant_state(int64_t _modifySize, CAmount _modifyFee, int64_t _modifyCount) :
modifySize(_modifySize), modifyFee(_modifyFee), modifyCount(_modifyCount)
{}
void operator() (CTxMemPoolEntry &e)
{ e.UpdateState(modifySize, modifyFee, modifyCount); }
private:
int64_t modifySize;
CAmount modifyFee;
int64_t modifyCount;
};
struct set_dirty
{
void operator() (CTxMemPoolEntry &e)
{ e.SetDirty(); }
};
struct update_fee_delta
{
update_fee_delta(int64_t _feeDelta) : feeDelta(_feeDelta) { }
void operator() (CTxMemPoolEntry &e) { e.UpdateFeeDelta(feeDelta); }
private:
int64_t feeDelta;
};
struct update_lock_points
{
update_lock_points(const LockPoints& _lp) : lp(_lp) { }
void operator() (CTxMemPoolEntry &e) { e.UpdateLockPoints(lp); }
private:
const LockPoints& lp;
};
// extracts a TxMemPoolEntry's transaction hash
struct mempoolentry_txid
{
typedef uint256 result_type;
result_type operator() (const CTxMemPoolEntry &entry) const
{
return entry.GetTx().GetHash();
}
};
/** \class CompareTxMemPoolEntryByDescendantScore
*
* Sort an entry by max(score/size of entry's tx, score/size with all descendants).
*/
class CompareTxMemPoolEntryByDescendantScore
{
public:
bool operator()(const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) const
{
bool fUseADescendants = UseDescendantScore(a);
bool fUseBDescendants = UseDescendantScore(b);
double aModFee = fUseADescendants ? a.GetModFeesWithDescendants() : a.GetModifiedFee();
double aSize = fUseADescendants ? a.GetSizeWithDescendants() : a.GetTxSize();
double bModFee = fUseBDescendants ? b.GetModFeesWithDescendants() : b.GetModifiedFee();
double bSize = fUseBDescendants ? b.GetSizeWithDescendants() : b.GetTxSize();
// Avoid division by rewriting (a/b > c/d) as (a*d > c*b).
double f1 = aModFee * bSize;
double f2 = aSize * bModFee;
if (f1 == f2) {
return a.GetTime() >= b.GetTime();
}
return f1 < f2;
}
// Calculate which score to use for an entry (avoiding division).
bool UseDescendantScore(const CTxMemPoolEntry &a) const
{
double f1 = (double)a.GetModifiedFee() * a.GetSizeWithDescendants();
double f2 = (double)a.GetModFeesWithDescendants() * a.GetTxSize();
return f2 > f1;
}
};
/** \class CompareTxMemPoolEntryByScore
*
* Sort by score of entry ((fee+delta)/size) in descending order
*/
class CompareTxMemPoolEntryByScore
{
public:
bool operator()(const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) const
{
double f1 = (double)a.GetModifiedFee() * b.GetTxSize();
double f2 = (double)b.GetModifiedFee() * a.GetTxSize();
if (f1 == f2) {
return b.GetTx().GetHash() < a.GetTx().GetHash();
}
return f1 > f2;
}
};
class CompareTxMemPoolEntryByEntryTime
{
public:
bool operator()(const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) const
{
return a.GetTime() < b.GetTime();
}
};
class CBlockPolicyEstimator;
/** An inpoint - a combination of a transaction and an index n into its vin */
class CInPoint
{
public:
const CTransaction* ptx;
uint32_t n;
CInPoint() { SetNull(); }
CInPoint(const CTransaction* ptxIn, uint32_t nIn) { ptx = ptxIn; n = nIn; }
void SetNull() { ptx = NULL; n = (uint32_t) -1; }
bool IsNull() const { return (ptx == NULL && n == (uint32_t) -1); }
size_t DynamicMemoryUsage() const { return 0; }
};
class SaltedTxidHasher
{
private:
/** Salt */
const uint64_t k0, k1;
public:
SaltedTxidHasher();
size_t operator()(const uint256& txid) const {
return SipHashUint256(k0, k1, txid);
}
};
/**
* CTxMemPool stores valid-according-to-the-current-best-chain
* transactions that may be included in the next block.
*
* Transactions are added when they are seen on the network
* (or created by the local node), but not all transactions seen
* are added to the pool: if a new transaction double-spends
* an input of a transaction in the pool, it is dropped,
* as are non-standard transactions.
*
* CTxMemPool::mapTx, and CTxMemPoolEntry bookkeeping:
*
* mapTx is a boost::multi_index that sorts the mempool on 4 criteria:
* - transaction hash
* - feerate [we use max(feerate of tx, feerate of tx with all descendants)]
* - time in mempool
* - mining score (feerate modified by any fee deltas from PrioritiseTransaction)
*
* Note: the term "descendant" refers to in-mempool transactions that depend on
* this one, while "ancestor" refers to in-mempool transactions that a given
* transaction depends on.
*
* In order for the feerate sort to remain correct, we must update transactions
* in the mempool when new descendants arrive. To facilitate this, we track
* the set of in-mempool direct parents and direct children in mapLinks. Within
* each CTxMemPoolEntry, we track the size and fees of all descendants.
*
* Usually when a new transaction is added to the mempool, it has no in-mempool
* children (because any such children would be an orphan). So in
* addUnchecked(), we:
* - update a new entry's setMemPoolParents to include all in-mempool parents
* - update the new entry's direct parents to include the new tx as a child
* - update all ancestors of the transaction to include the new tx's size/fee
*
* When a transaction is removed from the mempool, we must:
* - update all in-mempool parents to not track the tx in setMemPoolChildren
* - update all ancestors to not include the tx's size/fees in descendant state
* - update all in-mempool children to not include it as a parent
*
* These happen in UpdateForRemoveFromMempool(). (Note that when removing a
* transaction along with its descendants, we must calculate that set of
* transactions to be removed before doing the removal, or else the mempool can
* be in an inconsistent state where it's impossible to walk the ancestors of
* a transaction.)
*
* In the event of a reorg, the assumption that a newly added tx has no
* in-mempool children is false. In particular, the mempool is in an
* inconsistent state while new transactions are being added, because there may
* be descendant transactions of a tx coming from a disconnected block that are
* unreachable from just looking at transactions in the mempool (the linking
* transactions may also be in the disconnected block, waiting to be added).
* Because of this, there's not much benefit in trying to search for in-mempool
* children in addUnchecked(). Instead, in the special case of transactions
* being added from a disconnected block, we require the caller to clean up the
* state, to account for in-mempool, out-of-block descendants for all the
* in-block transactions by calling UpdateTransactionsFromBlock(). Note that
* until this is called, the mempool state is not consistent, and in particular
* mapLinks may not be correct (and therefore functions like
* CalculateMemPoolAncestors() and CalculateDescendants() that rely
* on them to walk the mempool are not generally safe to use).
*
* Computational limits:
*
* Updating all in-mempool ancestors of a newly added transaction can be slow,
* if no bound exists on how many in-mempool ancestors there may be.
* CalculateMemPoolAncestors() takes configurable limits that are designed to
* prevent these calculations from being too CPU intensive.
*
* Adding transactions from a disconnected block can be very time consuming,
* because we don't have a way to limit the number of in-mempool descendants.
* To bound CPU processing, we limit the amount of work we're willing to do
* to properly update the descendant information for a tx being added from
* a disconnected block. If we would exceed the limit, then we instead mark
* the entry as "dirty", and set the feerate for sorting purposes to be equal
* the feerate of the transaction without any descendants.
*
*/
class CTxMemPool
{
private:
uint32_t nCheckFrequency; //! Value n means that n times in 2^32 we check.
unsigned int nTransactionsUpdated;
CBlockPolicyEstimator* minerPolicyEstimator;
uint64_t totalTxSize; //! sum of all mempool tx' byte sizes
uint64_t cachedInnerUsage; //! sum of dynamic memory usage of all the map elements (NOT the maps themselves)
CFeeRate minReasonableRelayFee;
mutable int64_t lastRollingFeeUpdate;
mutable bool blockSinceLastRollingFeeBump;
mutable double rollingMinimumFeeRate; //! minimum fee to get into the pool, decreases exponentially
void trackPackageRemoved(const CFeeRate& rate);
public:
static const int ROLLING_FEE_HALFLIFE = 60 * 60 * 12; // public only for testing
typedef boost::multi_index_container<
CTxMemPoolEntry,
boost::multi_index::indexed_by<
// sorted by txid
boost::multi_index::ordered_unique<mempoolentry_txid>,
// sorted by fee rate
boost::multi_index::ordered_non_unique<
boost::multi_index::identity<CTxMemPoolEntry>,
CompareTxMemPoolEntryByDescendantScore
>,
// sorted by entry time
boost::multi_index::ordered_non_unique<
boost::multi_index::identity<CTxMemPoolEntry>,
CompareTxMemPoolEntryByEntryTime
>,
// sorted by score (for mining prioritization)
boost::multi_index::ordered_unique<
boost::multi_index::identity<CTxMemPoolEntry>,
CompareTxMemPoolEntryByScore
>
>
> indexed_transaction_set;
mutable CCriticalSection cs;
indexed_transaction_set mapTx;
typedef indexed_transaction_set::nth_index<0>::type::iterator txiter;
struct CompareIteratorByHash {
bool operator()(const txiter &a, const txiter &b) const {
return a->GetTx().GetHash() < b->GetTx().GetHash();
}
};
typedef std::set<txiter, CompareIteratorByHash> setEntries;
const setEntries & GetMemPoolParents(txiter entry) const;
const setEntries & GetMemPoolChildren(txiter entry) const;
private:
typedef std::map<txiter, setEntries, CompareIteratorByHash> cacheMap;
struct TxLinks {
setEntries parents;
setEntries children;
};
typedef std::map<txiter, TxLinks, CompareIteratorByHash> txlinksMap;
txlinksMap mapLinks;
typedef std::map<CMempoolAddressDeltaKey, CMempoolAddressDelta, CMempoolAddressDeltaKeyCompare> addressDeltaMap;
addressDeltaMap mapAddress;
typedef std::map<uint256, std::vector<CMempoolAddressDeltaKey> > addressDeltaMapInserted;
addressDeltaMapInserted mapAddressInserted;
typedef std::map<CSpentIndexKey, CSpentIndexValue, CSpentIndexKeyCompare> mapSpentIndex;
mapSpentIndex mapSpent;
typedef std::map<uint256, std::vector<CSpentIndexKey> > mapSpentIndexInserted;
mapSpentIndexInserted mapSpentInserted;
void UpdateParent(txiter entry, txiter parent, bool add);
void UpdateChild(txiter entry, txiter child, bool add);
public:
std::map<COutPoint, CInPoint> mapNextTx;
std::map<uint256, std::pair<double, CAmount> > mapDeltas;
/** Create a new CTxMemPool.
* minReasonableRelayFee should be a feerate which is, roughly, somewhere
* around what it "costs" to relay a transaction around the network and
* below which we would reasonably say a transaction has 0-effective-fee.
*/
CTxMemPool(const CFeeRate& _minReasonableRelayFee);
~CTxMemPool();
/**
* If sanity-checking is turned on, check makes sure the pool is
* consistent (does not contain two transactions that spend the same inputs,
* all inputs are in the mapNextTx array). If sanity-checking is turned off,
* check does nothing.
*/
void check(const CCoinsViewCache *pcoins) const;
void setSanityCheck(double dFrequency = 1.0) { nCheckFrequency = dFrequency * 4294967295.0; }
// addUnchecked must updated state for all ancestors of a given transaction,
// to track size/count of descendant transactions. First version of
// addUnchecked can be used to have it call CalculateMemPoolAncestors(), and
// then invoke the second version.
bool addUnchecked(const uint256& hash, const CTxMemPoolEntry &entry, bool fCurrentEstimate = true);
bool addUnchecked(const uint256& hash, const CTxMemPoolEntry &entry, setEntries &setAncestors, bool fCurrentEstimate = true);
void addAddressIndex(const CTxMemPoolEntry &entry, const CCoinsViewCache &view);
bool getAddressIndex(std::vector<std::pair<uint160, int> > &addresses,
std::vector<std::pair<CMempoolAddressDeltaKey, CMempoolAddressDelta> > &results);
bool removeAddressIndex(const uint256 txhash);
void addSpentIndex(const CTxMemPoolEntry &entry, const CCoinsViewCache &view);
bool getSpentIndex(CSpentIndexKey &key, CSpentIndexValue &value);
bool removeSpentIndex(const uint256 txhash);
void remove(const CTransaction &tx, std::list<CTransaction>& removed, bool fRecursive = false);
void removeForReorg(const CCoinsViewCache *pcoins, unsigned int nMemPoolHeight, int flags);
void removeConflicts(const CTransaction &tx, std::list<CTransaction>& removed);
void removeForBlock(const std::vector<CTransaction>& vtx, unsigned int nBlockHeight,
std::list<CTransaction>& conflicts, bool fCurrentEstimate = true);
void clear();
void _clear(); //lock free
void queryHashes(std::vector<uint256>& vtxid);
bool isSpent(const COutPoint& outpoint);
unsigned int GetTransactionsUpdated() const;
void AddTransactionsUpdated(unsigned int n);
/**
* Check that none of this transactions inputs are in the mempool, and thus
* the tx is not dependent on other mempool transactions to be included in a block.
*/
bool HasNoInputsOf(const CTransaction& tx) const;
/** Affect CreateNewBlock prioritisation of transactions */
void PrioritiseTransaction(const uint256 hash, const std::string strHash, double dPriorityDelta, const CAmount& nFeeDelta);
void ApplyDeltas(const uint256 hash, double &dPriorityDelta, CAmount &nFeeDelta) const;
void ClearPrioritisation(const uint256 hash);
public:
/** Remove a set of transactions from the mempool.
* If a transaction is in this set, then all in-mempool descendants must
* also be in the set.*/
void RemoveStaged(setEntries &stage);
/** When adding transactions from a disconnected block back to the mempool,
* new mempool entries may have children in the mempool (which is generally
* not the case when otherwise adding transactions).
* UpdateTransactionsFromBlock() will find child transactions and update the
* descendant state for each transaction in hashesToUpdate (excluding any
* child transactions present in hashesToUpdate, which are already accounted
* for). Note: hashesToUpdate should be the set of transactions from the
* disconnected block that have been accepted back into the mempool.
*/
void UpdateTransactionsFromBlock(const std::vector<uint256> &hashesToUpdate);
/** Try to calculate all in-mempool ancestors of entry.
* (these are all calculated including the tx itself)
* limitAncestorCount = max number of ancestors
* limitAncestorSize = max size of ancestors
* limitDescendantCount = max number of descendants any ancestor can have
* limitDescendantSize = max size of descendants any ancestor can have
* errString = populated with error reason if any limits are hit
* fSearchForParents = whether to search a tx's vin for in-mempool parents, or
* look up parents from mapLinks. Must be true for entries not in the mempool
*/
bool CalculateMemPoolAncestors(const CTxMemPoolEntry &entry, setEntries &setAncestors, uint64_t limitAncestorCount, uint64_t limitAncestorSize, uint64_t limitDescendantCount, uint64_t limitDescendantSize, std::string &errString, bool fSearchForParents = true);
/** Populate setDescendants with all in-mempool descendants of hash.
* Assumes that setDescendants includes all in-mempool descendants of anything
* already in it. */
void CalculateDescendants(txiter it, setEntries &setDescendants);
/** The minimum fee to get into the mempool, which may itself not be enough
* for larger-sized transactions.
* The minReasonableRelayFee constructor arg is used to bound the time it
* takes the fee rate to go back down all the way to 0. When the feerate
* would otherwise be half of this, it is set to 0 instead.
*/
CFeeRate GetMinFee(size_t sizelimit) const;
void UpdateMinFee(const CFeeRate& _minReasonableRelayFee);
/** Remove transactions from the mempool until its dynamic size is <= sizelimit.
* pvNoSpendsRemaining, if set, will be populated with the list of outpoints
* which are not in mempool which no longer have any spends in this mempool.
*/
void TrimToSize(size_t sizelimit, std::vector<COutPoint>* pvNoSpendsRemaining=NULL);
/** Expire all transaction (and their dependencies) in the mempool older than time. Return the number of removed transactions. */
int Expire(int64_t time);
unsigned long size()
{
LOCK(cs);
return mapTx.size();
}
uint64_t GetTotalTxSize()
{
LOCK(cs);
return totalTxSize;
}
bool exists(uint256 hash) const
{
LOCK(cs);
return (mapTx.count(hash) != 0);
}
bool exists(const COutPoint& outpoint) const
{
LOCK(cs);
auto it = mapTx.find(outpoint.hash);
return (it != mapTx.end() && outpoint.n < it->GetTx().vout.size());
}
bool lookup(uint256 hash, CTransaction& result) const;
/** Estimate fee rate needed to get into the next nBlocks
* If no answer can be given at nBlocks, return an estimate
* at the lowest number of blocks where one can be given
*/
CFeeRate estimateSmartFee(int nBlocks, int *answerFoundAtBlocks = NULL) const;
/** Estimate fee rate needed to get into the next nBlocks */
CFeeRate estimateFee(int nBlocks) const;
/** Estimate priority needed to get into the next nBlocks
* If no answer can be given at nBlocks, return an estimate
* at the lowest number of blocks where one can be given
*/
double estimateSmartPriority(int nBlocks, int *answerFoundAtBlocks = NULL) const;
/** Estimate priority needed to get into the next nBlocks */
double estimatePriority(int nBlocks) const;
/** Write/Read estimates to disk */
bool WriteFeeEstimates(CAutoFile& fileout) const;
bool ReadFeeEstimates(CAutoFile& filein);
size_t DynamicMemoryUsage() const;
private:
/** UpdateForDescendants is used by UpdateTransactionsFromBlock to update
* the descendants for a single transaction that has been added to the
* mempool but may have child transactions in the mempool, eg during a
* chain reorg. setExclude is the set of descendant transactions in the
* mempool that must not be accounted for (because any descendants in
* setExclude were added to the mempool after the transaction being
* updated and hence their state is already reflected in the parent
* state).
*
* If updating an entry requires looking at more than maxDescendantsToVisit
* transactions, outside of the ones in setExclude, then give up.
*
* cachedDescendants will be updated with the descendants of the transaction
* being updated, so that future invocations don't need to walk the
* same transaction again, if encountered in another transaction chain.
*/
bool UpdateForDescendants(txiter updateIt,
int maxDescendantsToVisit,
cacheMap &cachedDescendants,
const std::set<uint256> &setExclude);
/** Update ancestors of hash to add/remove it as a descendant transaction. */
void UpdateAncestorsOf(bool add, txiter hash, setEntries &setAncestors);
/** For each transaction being removed, update ancestors and any direct children. */
void UpdateForRemoveFromMempool(const setEntries &entriesToRemove);
/** Sever link between specified transaction and direct children. */
void UpdateChildrenForRemoval(txiter entry);
/** Before calling removeUnchecked for a given transaction,
* UpdateForRemoveFromMempool must be called on the entire (dependent) set
* of transactions being removed at the same time. We use each
* CTxMemPoolEntry's setMemPoolParents in order to walk ancestors of a
* given transaction that is removed, so we can't remove intermediate
* transactions in a chain before we've updated all the state for the
* removal.
*/
void removeUnchecked(txiter entry);
};
/**
* CCoinsView that brings transactions from a memorypool into view.
* It does not check for spendings by memory pool transactions.
*/
class CCoinsViewMemPool : public CCoinsViewBacked
{
protected:
CTxMemPool &mempool;
public:
CCoinsViewMemPool(CCoinsView *baseIn, CTxMemPool &mempoolIn);
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override;
};
// We want to sort transactions by coin age priority
typedef std::pair<double, CTxMemPool::txiter> TxCoinAgePriority;
struct TxCoinAgePriorityCompare
{
bool operator()(const TxCoinAgePriority& a, const TxCoinAgePriority& b)
{
if (a.first == b.first)
return CompareTxMemPoolEntryByScore()(*(b.second), *(a.second)); //Reverse order to make sort less than
return a.first < b.first;
}
};
#endif // HILUX_TXMEMPOOL_H
| [
"[email protected]"
] | |
fd5a243775645c62a2d6257dc977852cbe82a209 | f6da17de6f247d5063154ebe6d12650dd93d7ca1 | /src/include/ge/state/state.hpp | c9ba25370ba1ebb504c50c2cfebe4fc6f0fb8fa9 | [] | no_license | HerbGlitch/current_testing_platformer | 07010dd1f27759ad2a9832a2011f3c1f5ed48c3f | 0b3e1995e4eac2d8659187feb2fcc0c1e4f567ae | refs/heads/master | 2023-05-30T13:42:57.788849 | 2021-06-18T05:50:55 | 2021-06-18T05:50:55 | 370,524,838 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 325 | hpp | #ifndef STATE_HPP
#define STATE_HPP
namespace ge {
struct Data;
class State {
public:
State(Data *data): data(data){}
virtual ~State(){};
virtual void update(){};
virtual void render(){};
protected:
Data *data;
};
}
#endif // !STATE_HPP
#include "handler.hpp" | [
"[email protected]"
] | |
44ff2a6374505ed0deba21f487cd02f1c12ce58f | 6b2a8dd202fdce77c971c412717e305e1caaac51 | /solutions_1482494_1/C++/Karinsu/GCJ_1A_Q2.cpp | f5cf0f2fdbab8a752af9645e19b2ba81d4ec1191 | [] | 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,377 | cpp | #include <stdio.h>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int n;
struct LV
{
int a, b, isa;
LV(){a=b=isa=0;}
LV(int a, int b): a(a), b(b){isa=0;}
};
vector<LV> L;
int star;
int cmp1(LV left, LV right)
{
return left.b < right.b;
}
int cmp2(LV left, LV right)
{
if (left.a != right.a)
return left.a < right.a;
return left.b > right.b;
}
int sol()
{
int i;
int ans = 0;
star = 0;
sort(L.begin(), L.end(), cmp1);
while (!L.empty())
{
while (!L.empty() && star >= L[0].b)
{
if (L[0].isa) star++;
else star += 2;
L.erase(L.begin());
ans++;
}
if (L.empty())
return ans;
//sort(L.begin(), L.end(), cmp2);
for (i = L.size() - 1; i >= 0; i--)
{
if ((!L.empty()) && star >= L[i].a && (!L[i].isa))
{
star++;
L[i].isa = 1;
ans++;
break;
}
}
if (i < 0)
return 0;
}
return ans;
}
int main()
{
int t, ctr;
int i, tmp1, tmp2;
freopen("B-large.in","r",stdin);
freopen("1A_Q2_large.out","w+",stdout);
scanf("%d", &t);
for (ctr = 1; ctr <= t; ctr++)
{
scanf("%d", &n);
L.clear();
for (i = 0; i < n; i++)
{
scanf("%d%d", &tmp1, &tmp2);
L.push_back(LV(tmp1, tmp2));
}
printf("Case #%d: ", ctr);
if ((i = sol()) > 0)
printf("%d\n", i);
else puts("Too Bad");
}
} | [
"[email protected]"
] | |
057d72c79902fefa3af1dfb302c143fcbce9a124 | 1169f126efd05bb97479c6cde94e77cd5b7967f1 | /include/SocketException.h | 2844ffd77a69b1ae72739e9213509871ae1f6774 | [] | no_license | xjrueda/fixprime | 2fd78116aafe2a03f7802258d73387288c1dd0a5 | 48e3f15c14bd43eef5ef843d2c6eff20c27ad2ac | refs/heads/master | 2020-05-28T14:14:54.352364 | 2015-12-22T19:42:08 | 2015-12-22T19:42:08 | 38,892,485 | 8 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 278 | h |
#ifndef SocketException_class
#define SocketException_class
#include <string>
class SocketException
{
public:
SocketException ( std::string s ) : m_s ( s ) {};
~SocketException (){};
std::string description() { return m_s; }
private:
std::string m_s;
};
#endif | [
"[email protected]"
] | |
bda5bc4ae8f0865d333083e372205b01236f3ccc | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/git/gumtree/git_patch_hunk_3576.cpp | e2dccc34aff80fc713179a887bab33dc708ec57a | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 526 | cpp |
/**
* Saves state->msg in the state directory's "final-commit" file.
*/
static void write_commit_msg(const struct am_state *state)
{
- int fd;
const char *filename = am_path(state, "final-commit");
-
- fd = xopen(filename, O_WRONLY | O_CREAT, 0666);
- if (write_in_full(fd, state->msg, state->msg_len) < 0)
- die_errno(_("could not write to %s"), filename);
- close(fd);
+ write_file_buf(filename, state->msg, state->msg_len);
}
/**
* Loads state from disk.
*/
static void am_load(struct am_state *state)
| [
"[email protected]"
] | |
df13d38bf6627af62755f4573658be70049fcf2b | 6d258d9abc888d6c4640b77afa23355f9bafb5a0 | /xerces-c/StdInParse/StdInParse.cpp | e430a71ad6a4eeea17134757b95c935ac5af4629 | [] | no_license | ohwada/MAC_cpp_Samples | e281130c8fd339ec327d4fad6d8cdf4e9bab4edc | 74699e40343f13464d64cf5eb3e965140a6b31a2 | refs/heads/master | 2023-02-05T00:50:47.447668 | 2023-01-28T05:09:34 | 2023-01-28T05:09:34 | 237,116,830 | 15 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 7,889 | cpp | // original : https://github.com/apache/xerces-c/tree/master/samples
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Id$
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/framework/StdInInputSource.hpp>
#include <xercesc/parsers/SAXParser.hpp>
#include "StdInParse.hpp"
#include <xercesc/util/OutOfMemoryException.hpp>
// ---------------------------------------------------------------------------
// Local data
//
// doNamespaces
// Indicates whether namespace processing should be enabled or not.
// The default is no, but -n overrides that.
//
// doSchema
// Indicates whether schema processing should be enabled or not.
// The default is no, but -s overrides that.
//
// schemaFullChecking
// Indicates whether full schema constraint checking should be enabled or not.
// The default is no, but -s overrides that.
//
// valScheme
// Indicates what validation scheme to use. It defaults to 'auto', but
// can be set via the -v= command.
// ---------------------------------------------------------------------------
static bool doNamespaces = false;
static bool doSchema = false;
static bool schemaFullChecking = false;
static SAXParser::ValSchemes valScheme = SAXParser::Val_Auto;
// ---------------------------------------------------------------------------
// Local helper methods
// ---------------------------------------------------------------------------
void usage()
{
std::cout << "\nUsage:\n"
" StdInParse [options] < <XML file>\n\n"
"This program demonstrates streaming XML data from standard\n"
"input. It then uses the SAX Parser, and prints the\n"
"number of elements, attributes, spaces and characters found\n"
"in the input, using SAX API.\n\n"
"Options:\n"
" -v=xxx Validation scheme [always | never | auto*].\n"
" -n Enable namespace processing. Defaults to off.\n"
" -s Enable schema processing. Defaults to off.\n"
" -f Enable full schema constraint checking. Defaults to off.\n"
" -? Show this help.\n\n"
" * = Default if not provided explicitly.\n"
<< std::endl;
}
// ---------------------------------------------------------------------------
// Program entry point
// ---------------------------------------------------------------------------
int main(int argC, char* argV[])
{
// Initialize the XML4C system
try
{
XMLPlatformUtils::Initialize();
}
catch (const XMLException& toCatch)
{
std::cerr << "Error during initialization! Message:\n"
<< StrX(toCatch.getMessage()) << std::endl;
return 1;
}
int parmInd;
for (parmInd = 1; parmInd < argC; parmInd++)
{
// Break out on first parm not starting with a dash
if (argV[parmInd][0] != '-')
break;
// Watch for special case help request
if (!strcmp(argV[parmInd], "-?"))
{
usage();
XMLPlatformUtils::Terminate();
return 2;
}
else if (!strncmp(argV[parmInd], "-v=", 3)
|| !strncmp(argV[parmInd], "-V=", 3))
{
const char* const parm = &argV[parmInd][3];
if (!strcmp(parm, "never"))
valScheme = SAXParser::Val_Never;
else if (!strcmp(parm, "auto"))
valScheme = SAXParser::Val_Auto;
else if (!strcmp(parm, "always"))
valScheme = SAXParser::Val_Always;
else
{
std::cerr << "Unknown -v= value: " << parm << std::endl;
XMLPlatformUtils::Terminate();
return 2;
}
}
else if (!strcmp(argV[parmInd], "-n")
|| !strcmp(argV[parmInd], "-N"))
{
doNamespaces = true;
}
else if (!strcmp(argV[parmInd], "-s")
|| !strcmp(argV[parmInd], "-S"))
{
doSchema = true;
}
else if (!strcmp(argV[parmInd], "-f")
|| !strcmp(argV[parmInd], "-F"))
{
schemaFullChecking = true;
}
else
{
std::cerr << "Unknown option '" << argV[parmInd]
<< "', ignoring it\n" << std::endl;
}
}
//
// Create a SAX parser object. Then, according to what we were told on
// the command line, set the options.
//
SAXParser* parser = new SAXParser;
parser->setValidationScheme(valScheme);
parser->setDoNamespaces(doNamespaces);
parser->setDoSchema(doSchema);
parser->setHandleMultipleImports (true);
parser->setValidationSchemaFullChecking(schemaFullChecking);
//
// Create our SAX handler object and install it on the parser, as the
// document and error handler. We are responsible for cleaning them
// up, but since its just stack based here, there's nothing special
// to do.
//
StdInParseHandlers handler;
parser->setDocumentHandler(&handler);
parser->setErrorHandler(&handler);
unsigned long duration;
int errorCount = 0;
// create a faux scope so that 'src' destructor is called before
// XMLPlatformUtils::Terminate
{
//
// Kick off the parse and catch any exceptions. Create a standard
// input input source and tell the parser to parse from that.
//
StdInInputSource src;
try
{
const unsigned long startMillis = XMLPlatformUtils::getCurrentMillis();
parser->parse(src);
const unsigned long endMillis = XMLPlatformUtils::getCurrentMillis();
duration = endMillis - startMillis;
errorCount = parser->getErrorCount();
}
catch (const OutOfMemoryException&)
{
std::cerr << "OutOfMemoryException" << std::endl;
errorCount = 2;
return 4;
}
catch (const XMLException& e)
{
std::cerr << "\nError during parsing: \n"
<< StrX(e.getMessage())
<< "\n" << std::endl;
errorCount = 1;
return 4;
}
// Print out the stats that we collected and time taken
if (!errorCount) {
std::cout << StrX(src.getSystemId()) << ": " << duration << " ms ("
<< handler.getElementCount() << " elems, "
<< handler.getAttrCount() << " attrs, "
<< handler.getSpaceCount() << " spaces, "
<< handler.getCharacterCount() << " chars)" << std::endl;
}
}
//
// Delete the parser itself. Must be done prior to calling Terminate, below.
//
delete parser;
XMLPlatformUtils::Terminate();
if (errorCount > 0)
return 4;
else
return 0;
}
| [
"[email protected]"
] | |
5e8ae54037e163a964bf8269f3bbf32938a99631 | e850b4268df0bf810ecc601d4aa1a07ed0b4d0b5 | /exercises/crypto-square/example.h | 16a5a5c6c5064a968a68718d0d3f8d4c461f56b2 | [
"MIT"
] | permissive | junming403/cpp | d2a202847f57b64865d388cd6549dfa8f39ff0f4 | ef9f95396fde8cdf405c4995500e8754a9f68d99 | refs/heads/master | 2020-05-04T10:09:33.317526 | 2019-04-08T14:55:04 | 2019-04-08T14:55:04 | 179,082,951 | 1 | 0 | MIT | 2019-04-02T13:24:07 | 2019-04-02T13:24:06 | null | UTF-8 | C++ | false | false | 456 | h | #if !defined(CRYPTO_SQUARE_H)
#define CRYPTO_SQUARE_H
#include <string>
#include <vector>
namespace crypto_square
{
class cipher
{
public:
cipher(std::string const& text);
std::string normalize_plain_text() const;
std::size_t size() const;
std::vector<std::string> plain_text_segments() const;
std::string cipher_text() const;
std::string normalized_cipher_text() const;
private:
std::string const text_;
};
}
#endif
| [
"[email protected]"
] | |
d3044d54731ce95c305b6e2b4459c0128056a8b8 | d0c44dd3da2ef8c0ff835982a437946cbf4d2940 | /cmake-build-debug/programs_tiling/function14164/function14164_schedule_33/function14164_schedule_33_wrapper.cpp | 2591ff423543f6499fc8079e3aaa86c6042de091 | [] | no_license | IsraMekki/tiramisu_code_generator | 8b3f1d63cff62ba9f5242c019058d5a3119184a3 | 5a259d8e244af452e5301126683fa4320c2047a3 | refs/heads/master | 2020-04-29T17:27:57.987172 | 2019-04-23T16:50:32 | 2019-04-23T16:50:32 | 176,297,755 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,338 | cpp | #include "Halide.h"
#include "function14164_schedule_33_wrapper.h"
#include "tiramisu/utils.h"
#include <cstdlib>
#include <iostream>
#include <time.h>
#include <fstream>
#include <chrono>
#define MAX_RAND 200
int main(int, char **){
Halide::Buffer<int32_t> buf00(128);
Halide::Buffer<int32_t> buf01(64);
Halide::Buffer<int32_t> buf02(64, 128, 64);
Halide::Buffer<int32_t> buf03(128, 64);
Halide::Buffer<int32_t> buf04(64);
Halide::Buffer<int32_t> buf05(64);
Halide::Buffer<int32_t> buf06(64, 128, 64);
Halide::Buffer<int32_t> buf0(64, 64, 128, 64);
init_buffer(buf0, (int32_t)0);
auto t1 = std::chrono::high_resolution_clock::now();
function14164_schedule_33(buf00.raw_buffer(), buf01.raw_buffer(), buf02.raw_buffer(), buf03.raw_buffer(), buf04.raw_buffer(), buf05.raw_buffer(), buf06.raw_buffer(), buf0.raw_buffer());
auto t2 = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> diff = t2 - t1;
std::ofstream exec_times_file;
exec_times_file.open("../data/programs/function14164/function14164_schedule_33/exec_times.txt", std::ios_base::app);
if (exec_times_file.is_open()){
exec_times_file << diff.count() * 1000000 << "us" <<std::endl;
exec_times_file.close();
}
return 0;
} | [
"[email protected]"
] | |
1f44f5a3af044318d0edfc5217dac90a633395f9 | 675d7cc5b56305a89ab4837b3dedcadafc57ab74 | /src/extra/textparser.cpp | c55ce8e86ee280ae4f98ce931c284ce4afcf928f | [] | no_license | xDura/SIRayTracer | 3c3df6889dc46eb4998f8a6bd47c4548c234550f | e7f6bdc6d93aa5fd6e9c37e8a166f2ddaf0a9d4c | refs/heads/master | 2021-03-22T04:15:29.956435 | 2016-06-08T21:22:47 | 2016-06-08T21:22:47 | 59,030,787 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,574 | cpp | #include "textparser.h"
//#include "includes.h"
#include <sys/stat.h>
#include <string>
#include <algorithm>
//extern HWND GLOBmainwindow;
char g_string_temporal[256];
TextParser::TextParser()
: data(NULL)
{}
TextParser::TextParser(const char *name)
: data(NULL)
{
FILE *f;
struct stat stbuffer;
stat(name,&stbuffer);
fopen_s(&f, name,"rb");
size = stbuffer.st_size;
data = new char[size];
sl = 0;
fread(data,size,1,f);
fclose(f);
}
TextParser::~TextParser()
{
if (data!=NULL)
delete data;
}
bool TextParser::create(const char *name)
{
FILE *f;
struct stat stbuffer;
stat(name,&stbuffer);
fopen_s(&f, name,"rb");
if (f == NULL)
{
char s[256];
sprintf_s(s,"The resource file %s does not exist\n",name);
//MessageBox(GLOBmainwindow,s,"SR",MB_OK);
return false;
}
size = stbuffer.st_size;
data = new char[size];
sl = 0;
fread(data,size,1,f);
fclose(f);
return true;
}
int legal(char c)
{
int res;
res = (c>32);
return res;
}
char *TextParser::getword()
{
int p0,p1,i;
p0 = sl;
if (p0 >= size)
return NULL;
while (!legal(data[p0]) && p0<size)
p0++;
if (p0 >= size)
return NULL;
p1 = p0+1;
while (legal(data[p1]))
p1++;
for (i=p0;i<p1;i++)
{
if ((data[i]<='z') && (data[i]>='a'))
data[i] += ('A'-'a');
g_string_temporal[i-p0] = data[i];
}
g_string_temporal[p1-p0] = '\0';
sl = p1;
std::string s(g_string_temporal);
std::transform(s.begin(),s.end(),s.begin(),toupper);
//strupr(g_string_temporal);
strcpy_s(g_string_temporal,s.c_str());
return g_string_temporal;
}
char *TextParser::getcommaword()
{
int p0,p1,i;
p0 = sl;
while (data[p0]!='"')
p0++;
p0++;
p1 = p0+1;
while (data[p1]!='"')
p1++;
for (i=p0;i<p1;i++)
{
//if ((data[i]<='z') && (data[i]>='a')) data[i]+=('A'-'a');
g_string_temporal[i-p0] = data[i];
}
g_string_temporal[p1-p0] = '\0';
sl = p1+1;
return g_string_temporal;
}
int TextParser::getint()
{
return( atoi(getword()) );
}
double TextParser::getfloat()
{
return( atof(getword()) );
}
void TextParser::goback()
{
int p0,p1;
p0=sl;
while (!legal(data[p0])) p0--;
p1=p0-1;
while (legal(data[p1])) p1--;
sl=p1;
}
int TextParser::countchar(char c)
{
int res;
unsigned int i;
res=0;
for (i=0;i<size;i++)
if (data[i]==c) res++;
return res;
}
void TextParser::reset()
{
sl=0;
}
void TextParser::destroy()
{
if (data!=NULL)
delete data;
}
int TextParser::countword(char *s)
{
int res;
unsigned int i;
int final;
unsigned int si;
res=0;
final=0;
i=0;
while (!final)
{
si=0;
while (toupper(data[i])==toupper(s[si]))
{
i++;
si++;
}
res+=(si==strlen(s));
i+=si;
i++;
final=(i>=size);
}
return res;
}
int TextParser::countwordfromhere(char *s)
{
int res;
unsigned int i;
int final;
unsigned int si;
res=0;
final=0;
i=sl;
while (!final)
{
si=0;
while (toupper(data[i])==toupper(s[si]))
{
i++;
si++;
}
res+=(si==strlen(s));
i+=si;
i++;
final=(i>=size);
}
return res;
}
int TextParser::eof()
{
return (sl>size);
}
void TextParser::seek(const char *token)
{
char *dummy=getword();
while (strcmp(dummy,token) && (sl<size))
dummy = getword();
}
int TextParser::CountObjs()
{
char *dummy=getword();
int objCount = 0;
while (sl < size)
{
if( strcmp(dummy, "*GEOMOBJECT") == 0 ) objCount++;
dummy = getword();
}
return objCount;
}
| [
"[email protected]"
] | |
d159adad62f0a6f93696aa26c7eefabf03510044 | e572fe7da635214a975ab8aebd4a8e8565183d60 | /remove-node-in-binary-search-tree.cpp | 357aaf35e2c7bb4f5bce4d06b685bea8bc7955b3 | [] | no_license | LloydSSS/LintCode-LeetCode | 3713dc63019fbf4af8dbb9b21c72c1d03874893f | fb55572a219f51e015672768090cbda1edcef707 | refs/heads/master | 2020-12-25T22:58:26.399559 | 2015-09-14T16:09:18 | 2015-09-14T16:09:18 | 35,087,006 | 4 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 2,237 | cpp | // http://www.lintcode.com/en/problem/remove-node-in-binary-search-tree/
// 设置一个伪根,删除节点为根节点时不用特殊处理,递归调用removeNodeHelper,当发现匹配的值时,如果左右子树有一个为空,则直接把另一个子树提升上来;否则,把右子树上移,左子树作为右子树的左子树,右子树原先的左子树放在原先左子树的右子树的最右边
#include "lc.h"
class Solution {
public:
/**
* @param root: The root of the binary search tree.
* @param value: Remove the node with given value.
* @return: The root of the binary search tree after removal.
*/
TreeNode* removeNode(TreeNode* root, int value) {
if (root == nullptr)
return root;
TreeNode *dummy_root = nullptr;
if (value == INT_MIN) {
dummy_root = new TreeNode(value+1);
dummy_root->left = root;
return removeNodeHelper(dummy_root, value)->left;
} else {
dummy_root = new TreeNode(value-1);
dummy_root->right = root;
return removeNodeHelper(dummy_root, value)->right;
}
}
TreeNode* removeNodeHelper(TreeNode* root, int value) {
if (root == nullptr)
return root;
if (value < root->val)
root->left = removeNodeHelper(root->left, value);
else if (value > root->val)
root->right = removeNodeHelper(root->right, value);
else {
TreeNode *tmp = root;
if (root->left == nullptr)
root = root->right;
else if (root->right == nullptr)
root = root->left;
else {
TreeNode *ln = root->left;
TreeNode *rn = root->right;
TreeNode *rln = root->right->left;
TreeNode *lrn = root->left;
while (lrn->right != nullptr) {
lrn = lrn->right;
}
root = rn;
root->left = ln;
lrn->right = rln;
}
delete tmp;
}
return root;
}
};
};
int main(int argc, char const *argv[]) {
Solution sol;
return 0;
}
| [
"[email protected]"
] | |
03c58ec35db207ccbc0f39c844068de4f3d5247c | 5d83739af703fb400857cecc69aadaf02e07f8d1 | /Archive2/96/b6b628ed5d88bb/main.cpp | cd91eac2cc788fdc08dd0b97f8b7cec8129215c7 | [] | no_license | WhiZTiM/coliru | 3a6c4c0bdac566d1aa1c21818118ba70479b0f40 | 2c72c048846c082f943e6c7f9fa8d94aee76979f | refs/heads/master | 2021-01-01T05:10:33.812560 | 2015-08-24T19:09:22 | 2015-08-24T19:09:22 | 56,789,706 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 165 | cpp | #include "/Archive2/51/34fac35ef02db3/main.cpp"
#include <istream>
#include <ostream>
template std::getline(std::istream&, std::string&, char);
#endif //MY_HEADER | [
"francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df"
] | francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df |
22c4889455a27c9bdf5a5de75dae22c26bcae47a | 579f6399b3f8238eee552b8a70b5940db894a3eb | /mihajlov.dmitry/A1/main.cpp | ff058ba35947c9c953699174e6c9b75f6a2bac72 | [] | no_license | a-kashirin-official/spbspu-labs-2018 | 9ac7b7abaa626d07497104f20f7ed7feb6359ecf | aac2bb38fe61c12114975f034b498a116e7075c3 | refs/heads/master | 2020-03-19T04:18:15.774227 | 2018-12-02T22:21:38 | 2018-12-02T22:21:38 | 135,814,536 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,047 | cpp | #include <iostream>
#include "rectangle.hpp"
#include "circle.hpp"
void moveObject(Shape & obj, const point_t & centerPos)
{
std::cout << "Old data: " << std::endl;
obj.getInfo();
obj.move(centerPos);
std::cout << std::endl << "New data: " << std::endl;
obj.getInfo();
std::cout << "Area of Shape: " << obj.getArea() << ";" << std::endl << std::endl;
}
void moveObject(Shape & obj, const double shiftX, const double shiftY)
{
std::cout << "Old data: " << std::endl;
obj.getInfo();
std::cout << std::endl << "New data: " << std::endl;
obj.move(shiftX, shiftY);
obj.getInfo();
std::cout << "Area of Shape: " << obj.getArea() << ";" << std::endl << std::endl;
}
int main()
{
try
{
Rectangle rectangle({100, 200}, 10, 20);
Circle circle({200, 100}, 50);
Rectangle frame(circle.getFrameRect());
moveObject(rectangle, {25, 55});
moveObject(circle, 267, 333);
frame.getInfo();
}
catch (std::invalid_argument & error)
{
std::cerr << error.what() << std::endl;
return 1;
}
return 0;
}
| [
"[email protected]"
] | |
f81e0ede48bdb2fdc9235cbd4a1d1458cb739d3e | 1ec55905d71a35dd2cf1a49121660e89db3ca611 | /ArduCopter/GCS_Mavlink.pde | 4049c42c598b793c61e6c5dfc53a0284e3fe1802 | [] | no_license | ParkerK/RFID-Copter | 6a8253136a48cd98ce4bf6fa3876b5def6d89066 | 7777784747f56b68e671d3367f81ad0829440d19 | refs/heads/master | 2020-06-05T05:50:20.187724 | 2013-02-07T03:59:36 | 2013-02-07T03:59:36 | 5,769,486 | 2 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 65,337 | pde | // -*- tab-width: 4; Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*-
// use this to prevent recursion during sensor init
static bool in_mavlink_delay;
// this costs us 51 bytes, but means that low priority
// messages don't block the CPU
static mavlink_statustext_t pending_status;
// true when we have received at least 1 MAVLink packet
static bool mavlink_active;
// check if a message will fit in the payload space available
#define CHECK_PAYLOAD_SIZE(id) if (payload_space < MAVLINK_MSG_ID_ ## id ## _LEN) return false
// prototype this for use inside the GCS class
static void gcs_send_text_fmt(const prog_char_t *fmt, ...);
/*
* !!NOTE!!
*
* the use of NOINLINE separate functions for each message type avoids
* a compiler bug in gcc that would cause it to use far more stack
* space than is needed. Without the NOINLINE we use the sum of the
* stack needed for each message type. Please be careful to follow the
* pattern below when adding any new messages
*/
static NOINLINE void send_heartbeat(mavlink_channel_t chan)
{
uint8_t base_mode = MAV_MODE_FLAG_CUSTOM_MODE_ENABLED;
uint8_t system_status = MAV_STATE_ACTIVE;
uint32_t custom_mode = control_mode;
// work out the base_mode. This value is not very useful
// for APM, but we calculate it as best we can so a generic
// MAVLink enabled ground station can work out something about
// what the MAV is up to. The actual bit values are highly
// ambiguous for most of the APM flight modes. In practice, you
// only get useful information from the custom_mode, which maps to
// the APM flight mode and has a well defined meaning in the
// ArduPlane documentation
base_mode = MAV_MODE_FLAG_STABILIZE_ENABLED;
switch (control_mode) {
case AUTO:
case RTL:
case LOITER:
case GUIDED:
case CIRCLE:
base_mode |= MAV_MODE_FLAG_GUIDED_ENABLED;
// note that MAV_MODE_FLAG_AUTO_ENABLED does not match what
// APM does in any mode, as that is defined as "system finds its own goal
// positions", which APM does not currently do
break;
}
// all modes except INITIALISING have some form of manual
// override if stick mixing is enabled
base_mode |= MAV_MODE_FLAG_MANUAL_INPUT_ENABLED;
#if HIL_MODE != HIL_MODE_DISABLED
base_mode |= MAV_MODE_FLAG_HIL_ENABLED;
#endif
// we are armed if we are not initialising
if (motors.armed()) {
base_mode |= MAV_MODE_FLAG_SAFETY_ARMED;
}
// indicate we have set a custom mode
base_mode |= MAV_MODE_FLAG_CUSTOM_MODE_ENABLED;
mavlink_msg_heartbeat_send(
chan,
MAV_TYPE_QUADROTOR,
MAV_AUTOPILOT_ARDUPILOTMEGA,
base_mode,
custom_mode,
system_status);
}
static NOINLINE void send_attitude(mavlink_channel_t chan)
{
mavlink_msg_attitude_send(
chan,
millis(),
ahrs.roll,
ahrs.pitch,
ahrs.yaw,
omega.x,
omega.y,
omega.z);
}
#if AP_LIMITS == ENABLED
static NOINLINE void send_limits_status(mavlink_channel_t chan)
{
limits_send_mavlink_status(chan);
}
#endif
static NOINLINE void send_extended_status1(mavlink_channel_t chan, uint16_t packet_drops)
{
uint32_t control_sensors_present = 0;
uint32_t control_sensors_enabled;
uint32_t control_sensors_health;
// first what sensors/controllers we have
control_sensors_present |= (1<<0); // 3D gyro present
control_sensors_present |= (1<<1); // 3D accelerometer present
if (g.compass_enabled) {
control_sensors_present |= (1<<2); // compass present
}
control_sensors_present |= (1<<3); // absolute pressure sensor present
if (g_gps != NULL && g_gps->status() == GPS::GPS_OK) {
control_sensors_present |= (1<<5); // GPS present
}
control_sensors_present |= (1<<10); // 3D angular rate control
control_sensors_present |= (1<<11); // attitude stabilisation
control_sensors_present |= (1<<12); // yaw position
control_sensors_present |= (1<<13); // altitude control
control_sensors_present |= (1<<14); // X/Y position control
control_sensors_present |= (1<<15); // motor control
// now what sensors/controllers are enabled
// first the sensors
control_sensors_enabled = control_sensors_present & 0x1FF;
// now the controllers
control_sensors_enabled = control_sensors_present & 0x1FF;
control_sensors_enabled |= (1<<10); // 3D angular rate control
control_sensors_enabled |= (1<<11); // attitude stabilisation
control_sensors_enabled |= (1<<13); // altitude control
control_sensors_enabled |= (1<<15); // motor control
switch (control_mode) {
case AUTO:
case RTL:
case LOITER:
case GUIDED:
case CIRCLE:
case POSITION:
control_sensors_enabled |= (1<<12); // yaw position
control_sensors_enabled |= (1<<14); // X/Y position control
break;
}
// at the moment all sensors/controllers are assumed healthy
control_sensors_health = control_sensors_present;
uint16_t battery_current = -1;
uint8_t battery_remaining = -1;
if (current_total1 != 0 && g.pack_capacity != 0) {
battery_remaining = (100.0 * (g.pack_capacity - current_total1) / g.pack_capacity);
}
if (current_total1 != 0) {
battery_current = current_amps1 * 100;
}
if (g.battery_monitoring == 3) {
/*setting a out-of-range value.
* It informs to external devices that
* it cannot be calculated properly just by voltage*/
battery_remaining = 150;
}
mavlink_msg_sys_status_send(
chan,
control_sensors_present,
control_sensors_enabled,
control_sensors_health,
0, // CPU Load not supported in AC yet
battery_voltage1 * 1000, // mV
battery_current, // in 10mA units
battery_remaining, // in %
0, // comm drops %,
0, // comm drops in pkts,
0, 0, 0, 0);
}
static void NOINLINE send_meminfo(mavlink_channel_t chan)
{
extern unsigned __brkval;
mavlink_msg_meminfo_send(chan, __brkval, memcheck_available_memory());
}
static void NOINLINE send_location(mavlink_channel_t chan)
{
Matrix3f rot = ahrs.get_dcm_matrix(); // neglecting angle of attack for now
mavlink_msg_global_position_int_send(
chan,
millis(),
current_loc.lat, // in 1E7 degrees
current_loc.lng, // in 1E7 degrees
g_gps->altitude * 10, // millimeters above sea level
(current_loc.alt - home.alt) * 10, // millimeters above ground
g_gps->ground_speed * rot.a.x, // X speed cm/s
g_gps->ground_speed * rot.b.x, // Y speed cm/s
g_gps->ground_speed * rot.c.x,
g_gps->ground_course); // course in 1/100 degree
}
static void NOINLINE send_nav_controller_output(mavlink_channel_t chan)
{
mavlink_msg_nav_controller_output_send(
chan,
nav_roll / 1.0e2,
nav_pitch / 1.0e2,
target_bearing / 1.0e2,
target_bearing / 1.0e2,
wp_distance / 1.0e2,
altitude_error / 1.0e2,
0,
crosstrack_error); // was 0
}
static void NOINLINE send_ahrs(mavlink_channel_t chan)
{
Vector3f omega_I = ahrs.get_gyro_drift();
mavlink_msg_ahrs_send(
chan,
omega_I.x,
omega_I.y,
omega_I.z,
1,
0,
ahrs.get_error_rp(),
ahrs.get_error_yaw());
}
#ifdef DESKTOP_BUILD
// report simulator state
static void NOINLINE send_simstate(mavlink_channel_t chan)
{
sitl.simstate_send(chan);
}
#endif
#ifndef DESKTOP_BUILD
static void NOINLINE send_hwstatus(mavlink_channel_t chan)
{
mavlink_msg_hwstatus_send(
chan,
board_voltage(),
I2c.lockup_count());
}
#endif
static void NOINLINE send_gps_raw(mavlink_channel_t chan)
{
uint8_t fix = g_gps->status();
if (fix == GPS::GPS_OK) {
fix = 3;
}
mavlink_msg_gps_raw_int_send(
chan,
g_gps->last_fix_time*(uint64_t)1000,
fix,
g_gps->latitude, // in 1E7 degrees
g_gps->longitude, // in 1E7 degrees
g_gps->altitude * 10, // in mm
g_gps->hdop,
65535,
g_gps->ground_speed, // cm/s
g_gps->ground_course, // 1/100 degrees,
g_gps->num_sats);
}
static void NOINLINE send_servo_out(mavlink_channel_t chan)
{
const uint8_t rssi = 1;
// normalized values scaled to -10000 to 10000
// This is used for HIL. Do not change without discussing with HIL maintainers
#if FRAME_CONFIG == HELI_FRAME
mavlink_msg_rc_channels_scaled_send(
chan,
millis(),
0, // port 0
g.rc_1.servo_out,
g.rc_2.servo_out,
g.rc_3.radio_out,
g.rc_4.servo_out,
0,
0,
0,
0,
rssi);
#else
#if X_PLANE == ENABLED
/* update by JLN for X-Plane HIL */
if(motors.armed() && motors.auto_armed()) {
mavlink_msg_rc_channels_scaled_send(
chan,
millis(),
0, // port 0
g.rc_1.servo_out,
g.rc_2.servo_out,
10000 * g.rc_3.norm_output(),
g.rc_4.servo_out,
10000 * g.rc_1.norm_output(),
10000 * g.rc_2.norm_output(),
10000 * g.rc_3.norm_output(),
10000 * g.rc_4.norm_output(),
rssi);
}else{
mavlink_msg_rc_channels_scaled_send(
chan,
millis(),
0, // port 0
0,
0,
-10000,
0,
10000 * g.rc_1.norm_output(),
10000 * g.rc_2.norm_output(),
10000 * g.rc_3.norm_output(),
10000 * g.rc_4.norm_output(),
rssi);
}
#else
mavlink_msg_rc_channels_scaled_send(
chan,
millis(),
0, // port 0
g.rc_1.servo_out,
g.rc_2.servo_out,
g.rc_3.radio_out,
g.rc_4.servo_out,
10000 * g.rc_1.norm_output(),
10000 * g.rc_2.norm_output(),
10000 * g.rc_3.norm_output(),
10000 * g.rc_4.norm_output(),
rssi);
#endif
#endif
}
static void NOINLINE send_radio_in(mavlink_channel_t chan)
{
const uint8_t rssi = 1;
mavlink_msg_rc_channels_raw_send(
chan,
millis(),
0, // port
g.rc_1.radio_in,
g.rc_2.radio_in,
g.rc_3.radio_in,
g.rc_4.radio_in,
g.rc_5.radio_in,
g.rc_6.radio_in,
g.rc_7.radio_in,
g.rc_8.radio_in,
rssi);
}
static void NOINLINE send_radio_out(mavlink_channel_t chan)
{
mavlink_msg_servo_output_raw_send(
chan,
micros(),
0, // port
motors.motor_out[AP_MOTORS_MOT_1],
motors.motor_out[AP_MOTORS_MOT_2],
motors.motor_out[AP_MOTORS_MOT_3],
motors.motor_out[AP_MOTORS_MOT_4],
motors.motor_out[AP_MOTORS_MOT_5],
motors.motor_out[AP_MOTORS_MOT_6],
motors.motor_out[AP_MOTORS_MOT_7],
motors.motor_out[AP_MOTORS_MOT_8]);
}
static void NOINLINE send_vfr_hud(mavlink_channel_t chan)
{
mavlink_msg_vfr_hud_send(
chan,
(float)g_gps->ground_speed / 100.0,
(float)g_gps->ground_speed / 100.0,
(ahrs.yaw_sensor / 100) % 360,
g.rc_3.servo_out/10,
current_loc.alt / 100.0,
climb_rate / 100.0);
}
static void NOINLINE send_raw_imu1(mavlink_channel_t chan)
{
Vector3f accel = imu.get_accel();
Vector3f gyro = imu.get_gyro();
mavlink_msg_raw_imu_send(
chan,
micros(),
accel.x * 1000.0 / gravity,
accel.y * 1000.0 / gravity,
accel.z * 1000.0 / gravity,
gyro.x * 1000.0,
gyro.y * 1000.0,
gyro.z * 1000.0,
compass.mag_x,
compass.mag_y,
compass.mag_z);
}
static void NOINLINE send_raw_imu2(mavlink_channel_t chan)
{
mavlink_msg_scaled_pressure_send(
chan,
millis(),
(float)barometer.get_pressure()/100.0,
(float)(barometer.get_pressure() - barometer.get_ground_pressure())/100.0,
(int)(barometer.get_temperature()*10));
}
static void NOINLINE send_raw_imu3(mavlink_channel_t chan)
{
Vector3f mag_offsets = compass.get_offsets();
mavlink_msg_sensor_offsets_send(chan,
mag_offsets.x,
mag_offsets.y,
mag_offsets.z,
compass.get_declination(),
barometer.get_raw_pressure(),
barometer.get_raw_temp(),
imu.gx(), imu.gy(), imu.gz(),
imu.ax(), imu.ay(), imu.az());
}
static void NOINLINE send_gps_status(mavlink_channel_t chan)
{
mavlink_msg_gps_status_send(
chan,
g_gps->num_sats,
NULL,
NULL,
NULL,
NULL,
NULL);
}
static void NOINLINE send_current_waypoint(mavlink_channel_t chan)
{
mavlink_msg_mission_current_send(
chan,
(uint16_t)g.command_index);
}
static void NOINLINE send_statustext(mavlink_channel_t chan)
{
mavlink_msg_statustext_send(
chan,
pending_status.severity,
pending_status.text);
}
// are we still delaying telemetry to try to avoid Xbee bricking?
static bool telemetry_delayed(mavlink_channel_t chan)
{
uint32_t tnow = millis() >> 10;
if (tnow > (uint8_t)g.telem_delay) {
return false;
}
#if USB_MUX_PIN > 0
if (chan == MAVLINK_COMM_0 && usb_connected) {
// this is an APM2 with USB telemetry
return false;
}
// we're either on the 2nd UART, or no USB cable is connected
// we need to delay telemetry
return true;
#else
if (chan == MAVLINK_COMM_0) {
// we're on the USB port
return false;
}
// don't send telemetry yet
return true;
#endif
}
// try to send a message, return false if it won't fit in the serial tx buffer
static bool mavlink_try_send_message(mavlink_channel_t chan, enum ap_message id, uint16_t packet_drops)
{
int16_t payload_space = comm_get_txspace(chan) - MAVLINK_NUM_NON_PAYLOAD_BYTES;
if (telemetry_delayed(chan)) {
return false;
}
switch(id) {
case MSG_HEARTBEAT:
CHECK_PAYLOAD_SIZE(HEARTBEAT);
send_heartbeat(chan);
return true;
case MSG_EXTENDED_STATUS1:
CHECK_PAYLOAD_SIZE(SYS_STATUS);
send_extended_status1(chan, packet_drops);
break;
case MSG_EXTENDED_STATUS2:
CHECK_PAYLOAD_SIZE(MEMINFO);
send_meminfo(chan);
break;
case MSG_ATTITUDE:
CHECK_PAYLOAD_SIZE(ATTITUDE);
send_attitude(chan);
break;
case MSG_LOCATION:
CHECK_PAYLOAD_SIZE(GLOBAL_POSITION_INT);
send_location(chan);
break;
case MSG_NAV_CONTROLLER_OUTPUT:
CHECK_PAYLOAD_SIZE(NAV_CONTROLLER_OUTPUT);
send_nav_controller_output(chan);
break;
case MSG_GPS_RAW:
CHECK_PAYLOAD_SIZE(GPS_RAW_INT);
send_gps_raw(chan);
break;
case MSG_SERVO_OUT:
CHECK_PAYLOAD_SIZE(RC_CHANNELS_SCALED);
send_servo_out(chan);
break;
case MSG_RADIO_IN:
CHECK_PAYLOAD_SIZE(RC_CHANNELS_RAW);
send_radio_in(chan);
break;
case MSG_RADIO_OUT:
CHECK_PAYLOAD_SIZE(SERVO_OUTPUT_RAW);
send_radio_out(chan);
break;
case MSG_VFR_HUD:
CHECK_PAYLOAD_SIZE(VFR_HUD);
send_vfr_hud(chan);
break;
case MSG_RAW_IMU1:
CHECK_PAYLOAD_SIZE(RAW_IMU);
send_raw_imu1(chan);
break;
case MSG_RAW_IMU2:
CHECK_PAYLOAD_SIZE(SCALED_PRESSURE);
send_raw_imu2(chan);
break;
case MSG_RAW_IMU3:
CHECK_PAYLOAD_SIZE(SENSOR_OFFSETS);
send_raw_imu3(chan);
break;
case MSG_GPS_STATUS:
CHECK_PAYLOAD_SIZE(GPS_STATUS);
send_gps_status(chan);
break;
case MSG_CURRENT_WAYPOINT:
CHECK_PAYLOAD_SIZE(MISSION_CURRENT);
send_current_waypoint(chan);
break;
case MSG_NEXT_PARAM:
CHECK_PAYLOAD_SIZE(PARAM_VALUE);
if (chan == MAVLINK_COMM_0) {
gcs0.queued_param_send();
} else if (gcs3.initialised) {
gcs3.queued_param_send();
}
break;
case MSG_NEXT_WAYPOINT:
CHECK_PAYLOAD_SIZE(MISSION_REQUEST);
if (chan == MAVLINK_COMM_0) {
gcs0.queued_waypoint_send();
} else {
gcs3.queued_waypoint_send();
}
break;
case MSG_STATUSTEXT:
CHECK_PAYLOAD_SIZE(STATUSTEXT);
send_statustext(chan);
break;
#if AP_LIMITS == ENABLED
case MSG_LIMITS_STATUS:
CHECK_PAYLOAD_SIZE(LIMITS_STATUS);
send_limits_status(chan);
break;
#endif
case MSG_AHRS:
CHECK_PAYLOAD_SIZE(AHRS);
send_ahrs(chan);
break;
case MSG_SIMSTATE:
#ifdef DESKTOP_BUILD
CHECK_PAYLOAD_SIZE(SIMSTATE);
send_simstate(chan);
#endif
break;
case MSG_HWSTATUS:
#ifndef DESKTOP_BUILD
CHECK_PAYLOAD_SIZE(HWSTATUS);
send_hwstatus(chan);
#endif
break;
case MSG_RETRY_DEFERRED:
break; // just here to prevent a warning
}
return true;
}
#define MAX_DEFERRED_MESSAGES MSG_RETRY_DEFERRED
static struct mavlink_queue {
enum ap_message deferred_messages[MAX_DEFERRED_MESSAGES];
uint8_t next_deferred_message;
uint8_t num_deferred_messages;
} mavlink_queue[2];
// send a message using mavlink
static void mavlink_send_message(mavlink_channel_t chan, enum ap_message id, uint16_t packet_drops)
{
uint8_t i, nextid;
struct mavlink_queue *q = &mavlink_queue[(uint8_t)chan];
// see if we can send the deferred messages, if any
while (q->num_deferred_messages != 0) {
if (!mavlink_try_send_message(chan,
q->deferred_messages[q->next_deferred_message],
packet_drops)) {
break;
}
q->next_deferred_message++;
if (q->next_deferred_message == MAX_DEFERRED_MESSAGES) {
q->next_deferred_message = 0;
}
q->num_deferred_messages--;
}
if (id == MSG_RETRY_DEFERRED) {
return;
}
// this message id might already be deferred
for (i=0, nextid = q->next_deferred_message; i < q->num_deferred_messages; i++) {
if (q->deferred_messages[nextid] == id) {
// its already deferred, discard
return;
}
nextid++;
if (nextid == MAX_DEFERRED_MESSAGES) {
nextid = 0;
}
}
if (q->num_deferred_messages != 0 ||
!mavlink_try_send_message(chan, id, packet_drops)) {
// can't send it now, so defer it
if (q->num_deferred_messages == MAX_DEFERRED_MESSAGES) {
// the defer buffer is full, discard
return;
}
nextid = q->next_deferred_message + q->num_deferred_messages;
if (nextid >= MAX_DEFERRED_MESSAGES) {
nextid -= MAX_DEFERRED_MESSAGES;
}
q->deferred_messages[nextid] = id;
q->num_deferred_messages++;
}
}
void mavlink_send_text(mavlink_channel_t chan, gcs_severity severity, const char *str)
{
if (telemetry_delayed(chan)) {
return;
}
if (severity == SEVERITY_LOW) {
// send via the deferred queuing system
pending_status.severity = (uint8_t)severity;
strncpy((char *)pending_status.text, str, sizeof(pending_status.text));
mavlink_send_message(chan, MSG_STATUSTEXT, 0);
} else {
// send immediately
mavlink_msg_statustext_send(
chan,
severity,
str);
}
}
const AP_Param::GroupInfo GCS_MAVLINK::var_info[] PROGMEM = {
AP_GROUPINFO("RAW_SENS", 0, GCS_MAVLINK, streamRateRawSensors, 0),
AP_GROUPINFO("EXT_STAT", 1, GCS_MAVLINK, streamRateExtendedStatus, 0),
AP_GROUPINFO("RC_CHAN", 2, GCS_MAVLINK, streamRateRCChannels, 0),
AP_GROUPINFO("RAW_CTRL", 3, GCS_MAVLINK, streamRateRawController, 0),
AP_GROUPINFO("POSITION", 4, GCS_MAVLINK, streamRatePosition, 0),
AP_GROUPINFO("EXTRA1", 5, GCS_MAVLINK, streamRateExtra1, 0),
AP_GROUPINFO("EXTRA2", 6, GCS_MAVLINK, streamRateExtra2, 0),
AP_GROUPINFO("EXTRA3", 7, GCS_MAVLINK, streamRateExtra3, 0),
AP_GROUPINFO("PARAMS", 8, GCS_MAVLINK, streamRateParams, 0),
AP_GROUPEND
};
GCS_MAVLINK::GCS_MAVLINK() :
packet_drops(0),
waypoint_send_timeout(1000), // 1 second
waypoint_receive_timeout(1000) // 1 second
{
}
void
GCS_MAVLINK::init(FastSerial * port)
{
GCS_Class::init(port);
if (port == &Serial) {
mavlink_comm_0_port = port;
chan = MAVLINK_COMM_0;
}else{
mavlink_comm_1_port = port;
chan = MAVLINK_COMM_1;
}
_queued_parameter = NULL;
}
void
GCS_MAVLINK::update(void)
{
// receive new packets
mavlink_message_t msg;
mavlink_status_t status;
status.packet_rx_drop_count = 0;
// process received bytes
while(comm_get_available(chan))
{
uint8_t c = comm_receive_ch(chan);
#if CLI_ENABLED == ENABLED
/* allow CLI to be started by hitting enter 3 times, if no
* heartbeat packets have been received */
if (mavlink_active == false) {
if (c == '\n' || c == '\r') {
crlf_count++;
} else {
crlf_count = 0;
}
if (crlf_count == 3) {
run_cli();
}
}
#endif
// Try to get a new message
if (mavlink_parse_char(chan, c, &msg, &status)) {
mavlink_active = true;
handleMessage(&msg);
}
}
// Update packet drops counter
packet_drops += status.packet_rx_drop_count;
if (!waypoint_receiving && !waypoint_sending) {
return;
}
uint32_t tnow = millis();
if (waypoint_receiving &&
waypoint_request_i <= (unsigned)g.command_total &&
tnow > waypoint_timelast_request + 500 + (stream_slowdown*20)) {
waypoint_timelast_request = tnow;
send_message(MSG_NEXT_WAYPOINT);
}
// stop waypoint sending if timeout
if (waypoint_sending && (tnow - waypoint_timelast_send) > waypoint_send_timeout) {
waypoint_sending = false;
}
// stop waypoint receiving if timeout
if (waypoint_receiving && (tnow - waypoint_timelast_receive) > waypoint_receive_timeout) {
waypoint_receiving = false;
}
}
// see if we should send a stream now. Called at 50Hz
bool GCS_MAVLINK::stream_trigger(enum streams stream_num)
{
AP_Int16 *stream_rates = &streamRateRawSensors;
uint8_t rate = (uint8_t)stream_rates[stream_num].get();
if (rate == 0) {
return false;
}
if (stream_ticks[stream_num] == 0) {
// we're triggering now, setup the next trigger point
if (rate > 50) {
rate = 50;
}
stream_ticks[stream_num] = (50 / rate) + stream_slowdown;
return true;
}
// count down at 50Hz
stream_ticks[stream_num]--;
return false;
}
void
GCS_MAVLINK::data_stream_send(void)
{
if (waypoint_receiving || waypoint_sending) {
// don't interfere with mission transfer
return;
}
if (_queued_parameter != NULL) {
if (streamRateParams.get() <= 0) {
streamRateParams.set(50);
}
if (stream_trigger(STREAM_PARAMS)) {
send_message(MSG_NEXT_PARAM);
}
// don't send anything else at the same time as parameters
return;
}
if (in_mavlink_delay) {
// don't send any other stream types while in the delay callback
return;
}
if (stream_trigger(STREAM_RAW_SENSORS)) {
send_message(MSG_RAW_IMU1);
send_message(MSG_RAW_IMU2);
send_message(MSG_RAW_IMU3);
//Serial.printf("mav1 %d\n", (int)streamRateRawSensors.get());
}
if (stream_trigger(STREAM_EXTENDED_STATUS)) {
send_message(MSG_EXTENDED_STATUS1);
send_message(MSG_EXTENDED_STATUS2);
send_message(MSG_CURRENT_WAYPOINT);
send_message(MSG_GPS_RAW); // TODO - remove this message after location message is working
send_message(MSG_NAV_CONTROLLER_OUTPUT);
send_message(MSG_LIMITS_STATUS);
if (last_gps_satellites != g_gps->num_sats) {
// this message is mostly a huge waste of bandwidth,
// except it is the only message that gives the number
// of visible satellites. So only send it when that
// changes.
send_message(MSG_GPS_STATUS);
last_gps_satellites = g_gps->num_sats;
}
}
if (stream_trigger(STREAM_POSITION)) {
// sent with GPS read
//Serial.printf("mav3 %d\n", (int)streamRatePosition.get());
}
if (stream_trigger(STREAM_RAW_CONTROLLER)) {
send_message(MSG_SERVO_OUT);
//Serial.printf("mav4 %d\n", (int)streamRateRawController.get());
}
if (stream_trigger(STREAM_RC_CHANNELS)) {
send_message(MSG_RADIO_OUT);
send_message(MSG_RADIO_IN);
//Serial.printf("mav5 %d\n", (int)streamRateRCChannels.get());
}
if (stream_trigger(STREAM_EXTRA1)) {
send_message(MSG_ATTITUDE);
send_message(MSG_SIMSTATE);
//Serial.printf("mav6 %d\n", (int)streamRateExtra1.get());
}
if (stream_trigger(STREAM_EXTRA2)) {
send_message(MSG_VFR_HUD);
//Serial.printf("mav7 %d\n", (int)streamRateExtra2.get());
}
if (stream_trigger(STREAM_EXTRA3)) {
send_message(MSG_AHRS);
send_message(MSG_HWSTATUS);
}
}
void
GCS_MAVLINK::send_message(enum ap_message id)
{
mavlink_send_message(chan,id, packet_drops);
}
void
GCS_MAVLINK::send_text(gcs_severity severity, const char *str)
{
mavlink_send_text(chan,severity,str);
}
void
GCS_MAVLINK::send_text(gcs_severity severity, const prog_char_t *str)
{
mavlink_statustext_t m;
uint8_t i;
for (i=0; i<sizeof(m.text); i++) {
m.text[i] = pgm_read_byte((const prog_char *)(str++));
}
if (i < sizeof(m.text)) m.text[i] = 0;
mavlink_send_text(chan, severity, (const char *)m.text);
}
void GCS_MAVLINK::handleMessage(mavlink_message_t* msg)
{
struct Location tell_command = {}; // command for telemetry
switch (msg->msgid) {
case MAVLINK_MSG_ID_REQUEST_DATA_STREAM: //66
{
// decode
mavlink_request_data_stream_t packet;
mavlink_msg_request_data_stream_decode(msg, &packet);
if (mavlink_check_target(packet.target_system, packet.target_component))
break;
int16_t freq = 0; // packet frequency
if (packet.start_stop == 0)
freq = 0; // stop sending
else if (packet.start_stop == 1)
freq = packet.req_message_rate; // start sending
else
break;
switch(packet.req_stream_id) {
case MAV_DATA_STREAM_ALL:
streamRateRawSensors = freq;
streamRateExtendedStatus = freq;
streamRateRCChannels = freq;
streamRateRawController = freq;
streamRatePosition = freq;
streamRateExtra1 = freq;
streamRateExtra2 = freq;
//streamRateExtra3.set_and_save(freq); // We just do set and save on the last as it takes care of the whole group.
streamRateExtra3 = freq; // Don't save!!
break;
case MAV_DATA_STREAM_RAW_SENSORS:
streamRateRawSensors = freq; // We do not set and save this one so that if HIL is shut down incorrectly
// we will not continue to broadcast raw sensor data at 50Hz.
break;
case MAV_DATA_STREAM_EXTENDED_STATUS:
//streamRateExtendedStatus.set_and_save(freq);
streamRateExtendedStatus = freq;
break;
case MAV_DATA_STREAM_RC_CHANNELS:
streamRateRCChannels = freq;
break;
case MAV_DATA_STREAM_RAW_CONTROLLER:
streamRateRawController = freq;
break;
//case MAV_DATA_STREAM_RAW_SENSOR_FUSION:
// streamRateRawSensorFusion.set_and_save(freq);
// break;
case MAV_DATA_STREAM_POSITION:
streamRatePosition = freq;
break;
case MAV_DATA_STREAM_EXTRA1:
streamRateExtra1 = freq;
break;
case MAV_DATA_STREAM_EXTRA2:
streamRateExtra2 = freq;
break;
case MAV_DATA_STREAM_EXTRA3:
streamRateExtra3 = freq;
break;
default:
break;
}
break;
}
case MAVLINK_MSG_ID_COMMAND_LONG:
{
// decode
mavlink_command_long_t packet;
mavlink_msg_command_long_decode(msg, &packet);
if (mavlink_check_target(packet.target_system, packet.target_component)) break;
uint8_t result;
// do command
send_text(SEVERITY_LOW,PSTR("command received: "));
switch(packet.command) {
case MAV_CMD_NAV_LOITER_UNLIM:
set_mode(LOITER);
result = MAV_RESULT_ACCEPTED;
break;
case MAV_CMD_NAV_RETURN_TO_LAUNCH:
set_mode(RTL);
result = MAV_RESULT_ACCEPTED;
break;
case MAV_CMD_NAV_LAND:
set_mode(LAND);
result = MAV_RESULT_ACCEPTED;
break;
case MAV_CMD_MISSION_START:
set_mode(AUTO);
result = MAV_RESULT_ACCEPTED;
break;
case MAV_CMD_PREFLIGHT_CALIBRATION:
if (packet.param1 == 1 ||
packet.param2 == 1 ||
packet.param3 == 1) {
imu.init_accel(mavlink_delay, flash_leds);
}
if (packet.param4 == 1) {
trim_radio();
}
result = MAV_RESULT_ACCEPTED;
break;
case MAV_CMD_COMPONENT_ARM_DISARM:
if (packet.target_component == MAV_COMP_ID_SYSTEM_CONTROL) {
if (packet.param1 == 1.0f) {
init_arm_motors();
result = MAV_RESULT_ACCEPTED;
} else if (packet.param1 == 0.0f) {
init_disarm_motors();
result = MAV_RESULT_ACCEPTED;
} else {
result = MAV_RESULT_UNSUPPORTED;
}
} else {
result = MAV_RESULT_UNSUPPORTED;
}
break;
default:
result = MAV_RESULT_UNSUPPORTED;
break;
}
mavlink_msg_command_ack_send(
chan,
packet.command,
result);
break;
}
case MAVLINK_MSG_ID_SET_MODE: //11
{
// decode
mavlink_set_mode_t packet;
mavlink_msg_set_mode_decode(msg, &packet);
if (!(packet.base_mode & MAV_MODE_FLAG_CUSTOM_MODE_ENABLED)) {
// we ignore base_mode as there is no sane way to map
// from that bitmap to a APM flight mode. We rely on
// custom_mode instead.
break;
}
switch (packet.custom_mode) {
case STABILIZE:
case ACRO:
case ALT_HOLD:
case AUTO:
case GUIDED:
case LOITER:
case RTL:
case CIRCLE:
case POSITION:
case LAND:
case OF_LOITER:
set_mode(packet.custom_mode);
break;
}
break;
}
/*case MAVLINK_MSG_ID_SET_NAV_MODE:
* {
* // decode
* mavlink_set_nav_mode_t packet;
* mavlink_msg_set_nav_mode_decode(msg, &packet);
* // To set some flight modes we must first receive a "set nav mode" message and then a "set mode" message
* mav_nav = packet.nav_mode;
* break;
* }
*/
case MAVLINK_MSG_ID_MISSION_REQUEST_LIST: //43
{
//send_text_P(SEVERITY_LOW,PSTR("waypoint request list"));
// decode
mavlink_mission_request_list_t packet;
mavlink_msg_mission_request_list_decode(msg, &packet);
if (mavlink_check_target(packet.target_system, packet.target_component))
break;
// Start sending waypoints
mavlink_msg_mission_count_send(
chan,msg->sysid,
msg->compid,
g.command_total); // includes home
waypoint_timelast_send = millis();
waypoint_sending = true;
waypoint_receiving = false;
waypoint_dest_sysid = msg->sysid;
waypoint_dest_compid = msg->compid;
break;
}
// XXX read a WP from EEPROM and send it to the GCS
case MAVLINK_MSG_ID_MISSION_REQUEST: // 40
{
//send_text_P(SEVERITY_LOW,PSTR("waypoint request"));
// Check if sending waypiont
//if (!waypoint_sending) break;
// 5/10/11 - We are trying out relaxing the requirement that we be in waypoint sending mode to respond to a waypoint request. DEW
// decode
mavlink_mission_request_t packet;
mavlink_msg_mission_request_decode(msg, &packet);
if (mavlink_check_target(packet.target_system, packet.target_component))
break;
// send waypoint
tell_command = get_cmd_with_index(packet.seq);
// set frame of waypoint
uint8_t frame;
if (tell_command.options & MASK_OPTIONS_RELATIVE_ALT) {
frame = MAV_FRAME_GLOBAL_RELATIVE_ALT; // reference frame
} else {
frame = MAV_FRAME_GLOBAL; // reference frame
}
float param1 = 0, param2 = 0, param3 = 0, param4 = 0;
// time that the mav should loiter in milliseconds
uint8_t current = 0; // 1 (true), 0 (false)
if (packet.seq == (uint16_t)g.command_index)
current = 1;
uint8_t autocontinue = 1; // 1 (true), 0 (false)
float x = 0, y = 0, z = 0;
if (tell_command.id < MAV_CMD_NAV_LAST) {
// command needs scaling
x = tell_command.lat/1.0e7; // local (x), global (latitude)
y = tell_command.lng/1.0e7; // local (y), global (longitude)
// ACM is processing alt inside each command. so we save and load raw values. - this is diffrent to APM
z = tell_command.alt/1.0e2; // local (z), global/relative (altitude)
}
// Switch to map APM command fields into MAVLink command fields
switch (tell_command.id) {
case MAV_CMD_NAV_LOITER_TURNS:
case MAV_CMD_CONDITION_CHANGE_ALT:
case MAV_CMD_DO_SET_HOME:
param1 = tell_command.p1;
break;
case MAV_CMD_NAV_ROI:
param1 = tell_command.p1; // MAV_ROI (aka roi mode) is held in wp's parameter but we actually do nothing with it because we only support pointing at a specific location provided by x,y and z parameters
break;
case MAV_CMD_CONDITION_YAW:
param3 = tell_command.p1;
param1 = tell_command.alt;
param2 = tell_command.lat;
param4 = tell_command.lng;
break;
case MAV_CMD_NAV_TAKEOFF:
param1 = 0;
break;
case MAV_CMD_NAV_LOITER_TIME:
param1 = tell_command.p1; // ACM loiter time is in 1 second increments
break;
case MAV_CMD_CONDITION_DELAY:
case MAV_CMD_CONDITION_DISTANCE:
param1 = tell_command.lat;
break;
case MAV_CMD_DO_JUMP:
param2 = tell_command.lat;
param1 = tell_command.p1;
break;
case MAV_CMD_DO_REPEAT_SERVO:
param4 = tell_command.lng;
case MAV_CMD_DO_REPEAT_RELAY:
case MAV_CMD_DO_CHANGE_SPEED:
param3 = tell_command.lat;
param2 = tell_command.alt;
param1 = tell_command.p1;
break;
case MAV_CMD_NAV_WAYPOINT:
param1 = tell_command.p1;
break;
case MAV_CMD_DO_SET_PARAMETER:
case MAV_CMD_DO_SET_RELAY:
case MAV_CMD_DO_SET_SERVO:
param2 = tell_command.alt;
param1 = tell_command.p1;
break;
}
mavlink_msg_mission_item_send(chan,msg->sysid,
msg->compid,
packet.seq,
frame,
tell_command.id,
current,
autocontinue,
param1,
param2,
param3,
param4,
x,
y,
z);
// update last waypoint comm stamp
waypoint_timelast_send = millis();
break;
}
case MAVLINK_MSG_ID_MISSION_ACK: //47
{
//send_text_P(SEVERITY_LOW,PSTR("waypoint ack"));
// decode
mavlink_mission_ack_t packet;
mavlink_msg_mission_ack_decode(msg, &packet);
if (mavlink_check_target(packet.target_system,packet.target_component)) break;
// turn off waypoint send
waypoint_sending = false;
break;
}
case MAVLINK_MSG_ID_PARAM_REQUEST_LIST: // 21
{
// gcs_send_text_P(SEVERITY_LOW,PSTR("param request list"));
// decode
mavlink_param_request_list_t packet;
mavlink_msg_param_request_list_decode(msg, &packet);
if (mavlink_check_target(packet.target_system,packet.target_component)) break;
// Start sending parameters - next call to ::update will kick the first one out
_queued_parameter = AP_Param::first(&_queued_parameter_token, &_queued_parameter_type);
_queued_parameter_index = 0;
_queued_parameter_count = _count_parameters();
break;
}
case MAVLINK_MSG_ID_PARAM_REQUEST_READ:
{
// decode
mavlink_param_request_read_t packet;
mavlink_msg_param_request_read_decode(msg, &packet);
if (mavlink_check_target(packet.target_system,packet.target_component)) break;
if (packet.param_index != -1) {
gcs_send_text_P(SEVERITY_LOW, PSTR("Param by index not supported"));
break;
}
enum ap_var_type p_type;
AP_Param *vp = AP_Param::find(packet.param_id, &p_type);
if (vp == NULL) {
gcs_send_text_fmt(PSTR("Unknown parameter %s"), packet.param_id);
break;
}
char param_name[ONBOARD_PARAM_NAME_LENGTH];
vp->copy_name(param_name, sizeof(param_name), true);
float value = vp->cast_to_float(p_type);
mavlink_msg_param_value_send(
chan,
param_name,
value,
mav_var_type(p_type),
-1, -1);
break;
}
case MAVLINK_MSG_ID_MISSION_CLEAR_ALL: // 45
{
//send_text_P(SEVERITY_LOW,PSTR("waypoint clear all"));
// decode
mavlink_mission_clear_all_t packet;
mavlink_msg_mission_clear_all_decode(msg, &packet);
if (mavlink_check_target(packet.target_system, packet.target_component)) break;
// clear all waypoints
uint8_t type = 0; // ok (0), error(1)
g.command_total.set_and_save(1);
// send acknowledgement 3 times to makes sure it is received
for (int16_t i=0; i<3; i++)
mavlink_msg_mission_ack_send(chan, msg->sysid, msg->compid, type);
break;
}
case MAVLINK_MSG_ID_MISSION_SET_CURRENT: // 41
{
//send_text_P(SEVERITY_LOW,PSTR("waypoint set current"));
// decode
mavlink_mission_set_current_t packet;
mavlink_msg_mission_set_current_decode(msg, &packet);
if (mavlink_check_target(packet.target_system,packet.target_component)) break;
// set current command
change_command(packet.seq);
mavlink_msg_mission_current_send(chan, g.command_index);
break;
}
case MAVLINK_MSG_ID_MISSION_COUNT: // 44
{
//send_text_P(SEVERITY_LOW,PSTR("waypoint count"));
// decode
mavlink_mission_count_t packet;
mavlink_msg_mission_count_decode(msg, &packet);
if (mavlink_check_target(packet.target_system,packet.target_component)) break;
// start waypoint receiving
if (packet.count > MAX_WAYPOINTS) {
packet.count = MAX_WAYPOINTS;
}
g.command_total.set_and_save(packet.count);
waypoint_timelast_receive = millis();
waypoint_receiving = true;
waypoint_sending = false;
waypoint_request_i = 0;
waypoint_timelast_request = 0;
break;
}
#ifdef MAVLINK_MSG_ID_SET_MAG_OFFSETS
case MAVLINK_MSG_ID_SET_MAG_OFFSETS:
{
mavlink_set_mag_offsets_t packet;
mavlink_msg_set_mag_offsets_decode(msg, &packet);
if (mavlink_check_target(packet.target_system,packet.target_component)) break;
compass.set_offsets(Vector3f(packet.mag_ofs_x, packet.mag_ofs_y, packet.mag_ofs_z));
break;
}
#endif
// XXX receive a WP from GCS and store in EEPROM
case MAVLINK_MSG_ID_MISSION_ITEM: //39
{
// decode
mavlink_mission_item_t packet;
mavlink_msg_mission_item_decode(msg, &packet);
if (mavlink_check_target(packet.target_system,packet.target_component)) break;
// defaults
tell_command.id = packet.command;
/*
* switch (packet.frame){
*
* case MAV_FRAME_MISSION:
* case MAV_FRAME_GLOBAL:
* {
* tell_command.lat = 1.0e7*packet.x; // in as DD converted to * t7
* tell_command.lng = 1.0e7*packet.y; // in as DD converted to * t7
* tell_command.alt = packet.z*1.0e2; // in as m converted to cm
* tell_command.options = 0; // absolute altitude
* break;
* }
*
* case MAV_FRAME_LOCAL: // local (relative to home position)
* {
* tell_command.lat = 1.0e7*ToDeg(packet.x/
* (radius_of_earth*cos(ToRad(home.lat/1.0e7)))) + home.lat;
* tell_command.lng = 1.0e7*ToDeg(packet.y/radius_of_earth) + home.lng;
* tell_command.alt = packet.z*1.0e2;
* tell_command.options = MASK_OPTIONS_RELATIVE_ALT;
* break;
* }
* //case MAV_FRAME_GLOBAL_RELATIVE_ALT: // absolute lat/lng, relative altitude
* default:
* {
* tell_command.lat = 1.0e7 * packet.x; // in as DD converted to * t7
* tell_command.lng = 1.0e7 * packet.y; // in as DD converted to * t7
* tell_command.alt = packet.z * 1.0e2;
* tell_command.options = MASK_OPTIONS_RELATIVE_ALT; // store altitude relative!! Always!!
* break;
* }
* }
*/
// we only are supporting Abs position, relative Alt
tell_command.lat = 1.0e7 * packet.x; // in as DD converted to * t7
tell_command.lng = 1.0e7 * packet.y; // in as DD converted to * t7
tell_command.alt = packet.z * 1.0e2;
tell_command.options = 1; // store altitude relative to home alt!! Always!!
switch (tell_command.id) { // Switch to map APM command fields into MAVLink command fields
case MAV_CMD_NAV_LOITER_TURNS:
case MAV_CMD_DO_SET_HOME:
tell_command.p1 = packet.param1;
break;
case MAV_CMD_NAV_ROI:
tell_command.p1 = packet.param1; // MAV_ROI (aka roi mode) is held in wp's parameter but we actually do nothing with it because we only support pointing at a specific location provided by x,y and z parameters
break;
case MAV_CMD_CONDITION_YAW:
tell_command.p1 = packet.param3;
tell_command.alt = packet.param1;
tell_command.lat = packet.param2;
tell_command.lng = packet.param4;
break;
case MAV_CMD_NAV_TAKEOFF:
tell_command.p1 = 0;
break;
case MAV_CMD_CONDITION_CHANGE_ALT:
tell_command.p1 = packet.param1 * 100;
break;
case MAV_CMD_NAV_LOITER_TIME:
tell_command.p1 = packet.param1; // APM loiter time is in ten second increments
break;
case MAV_CMD_CONDITION_DELAY:
case MAV_CMD_CONDITION_DISTANCE:
tell_command.lat = packet.param1;
break;
case MAV_CMD_DO_JUMP:
tell_command.lat = packet.param2;
tell_command.p1 = packet.param1;
break;
case MAV_CMD_DO_REPEAT_SERVO:
tell_command.lng = packet.param4;
case MAV_CMD_DO_REPEAT_RELAY:
case MAV_CMD_DO_CHANGE_SPEED:
tell_command.lat = packet.param3;
tell_command.alt = packet.param2;
tell_command.p1 = packet.param1;
break;
case MAV_CMD_NAV_WAYPOINT:
tell_command.p1 = packet.param1;
break;
case MAV_CMD_DO_SET_PARAMETER:
case MAV_CMD_DO_SET_RELAY:
case MAV_CMD_DO_SET_SERVO:
tell_command.alt = packet.param2;
tell_command.p1 = packet.param1;
break;
}
if(packet.current == 2) { //current = 2 is a flag to tell us this is a "guided mode" waypoint and not for the mission
guided_WP = tell_command;
// add home alt if needed
if (guided_WP.options & MASK_OPTIONS_RELATIVE_ALT) {
guided_WP.alt += home.alt;
}
set_mode(GUIDED);
// make any new wp uploaded instant (in case we are already in Guided mode)
set_next_WP(&guided_WP);
// verify we recevied the command
mavlink_msg_mission_ack_send(
chan,
msg->sysid,
msg->compid,
0);
} else if(packet.current == 3) { //current = 3 is a flag to tell us this is a alt change only
// add home alt if needed
if (tell_command.options & MASK_OPTIONS_RELATIVE_ALT) {
tell_command.alt += home.alt;
}
set_new_altitude(tell_command.alt);
// verify we recevied the command
mavlink_msg_mission_ack_send(
chan,
msg->sysid,
msg->compid,
0);
} else {
// Check if receiving waypoints (mission upload expected)
if (!waypoint_receiving) break;
//Serial.printf("req: %d, seq: %d, total: %d\n", waypoint_request_i,packet.seq, g.command_total.get());
// check if this is the requested waypoint
if (packet.seq != waypoint_request_i)
break;
if(packet.seq != 0)
set_cmd_with_index(tell_command, packet.seq);
// update waypoint receiving state machine
waypoint_timelast_receive = millis();
waypoint_timelast_request = 0;
waypoint_request_i++;
if (waypoint_request_i == (uint16_t)g.command_total) {
uint8_t type = 0; // ok (0), error(1)
mavlink_msg_mission_ack_send(
chan,
msg->sysid,
msg->compid,
type);
send_text(SEVERITY_LOW,PSTR("flight plan received"));
waypoint_receiving = false;
// XXX ignores waypoint radius for individual waypoints, can
// only set WP_RADIUS parameter
}
}
break;
}
case MAVLINK_MSG_ID_PARAM_SET: // 23
{
AP_Param *vp;
enum ap_var_type var_type;
// decode
mavlink_param_set_t packet;
mavlink_msg_param_set_decode(msg, &packet);
if (mavlink_check_target(packet.target_system, packet.target_component))
break;
// set parameter
char key[ONBOARD_PARAM_NAME_LENGTH+1];
strncpy(key, (char *)packet.param_id, ONBOARD_PARAM_NAME_LENGTH);
key[ONBOARD_PARAM_NAME_LENGTH] = 0;
// find the requested parameter
vp = AP_Param::find(key, &var_type);
if ((NULL != vp) && // exists
!isnan(packet.param_value) && // not nan
!isinf(packet.param_value)) { // not inf
// add a small amount before casting parameter values
// from float to integer to avoid truncating to the
// next lower integer value.
float rounding_addition = 0.01;
// handle variables with standard type IDs
if (var_type == AP_PARAM_FLOAT) {
((AP_Float *)vp)->set_and_save(packet.param_value);
} else if (var_type == AP_PARAM_INT32) {
#if LOGGING_ENABLED == ENABLED
Log_Write_Data(1, ((AP_Int32 *)vp)->get());
#endif
if (packet.param_value < 0) rounding_addition = -rounding_addition;
float v = packet.param_value+rounding_addition;
v = constrain(v, -2147483648.0, 2147483647.0);
((AP_Int32 *)vp)->set_and_save(v);
} else if (var_type == AP_PARAM_INT16) {
#if LOGGING_ENABLED == ENABLED
Log_Write_Data(3, (int32_t)((AP_Int16 *)vp)->get());
#endif
if (packet.param_value < 0) rounding_addition = -rounding_addition;
float v = packet.param_value+rounding_addition;
v = constrain(v, -32768, 32767);
((AP_Int16 *)vp)->set_and_save(v);
} else if (var_type == AP_PARAM_INT8) {
#if LOGGING_ENABLED == ENABLED
Log_Write_Data(4, (int32_t)((AP_Int8 *)vp)->get());
#endif
if (packet.param_value < 0) rounding_addition = -rounding_addition;
float v = packet.param_value+rounding_addition;
v = constrain(v, -128, 127);
((AP_Int8 *)vp)->set_and_save(v);
} else {
// we don't support mavlink set on this parameter
break;
}
// Report back the new value if we accepted the change
// we send the value we actually set, which could be
// different from the value sent, in case someone sent
// a fractional value to an integer type
mavlink_msg_param_value_send(
chan,
key,
vp->cast_to_float(var_type),
mav_var_type(var_type),
_count_parameters(),
-1); // XXX we don't actually know what its index is...
}
break;
} // end case
case MAVLINK_MSG_ID_RC_CHANNELS_OVERRIDE: //70
{
// allow override of RC channel values for HIL
// or for complete GCS control of switch position
// and RC PWM values.
if(msg->sysid != g.sysid_my_gcs) break; // Only accept control from our gcs
mavlink_rc_channels_override_t packet;
int16_t v[8];
mavlink_msg_rc_channels_override_decode(msg, &packet);
if (mavlink_check_target(packet.target_system,packet.target_component))
break;
v[0] = packet.chan1_raw;
v[1] = packet.chan2_raw;
v[2] = packet.chan3_raw;
v[3] = packet.chan4_raw;
v[4] = packet.chan5_raw;
v[5] = packet.chan6_raw;
v[6] = packet.chan7_raw;
v[7] = packet.chan8_raw;
APM_RC.setHIL(v);
break;
}
#if HIL_MODE != HIL_MODE_DISABLED
case MAVLINK_MSG_ID_HIL_STATE:
{
mavlink_hil_state_t packet;
mavlink_msg_hil_state_decode(msg, &packet);
float vel = sqrt((packet.vx * (float)packet.vx) + (packet.vy * (float)packet.vy));
float cog = wrap_360(ToDeg(atan2(packet.vx, packet.vy)) * 100);
// set gps hil sensor
g_gps->setHIL(packet.time_usec/1000,
packet.lat*1.0e-7, packet.lon*1.0e-7, packet.alt*1.0e-3,
vel*1.0e-2, cog*1.0e-2, 0, 10);
if (gps_base_alt == 0) {
gps_base_alt = g_gps->altitude;
}
current_loc.lng = g_gps->longitude;
current_loc.lat = g_gps->latitude;
current_loc.alt = g_gps->altitude - gps_base_alt;
if (!home_is_set) {
init_home();
}
// rad/sec
Vector3f gyros;
gyros.x = packet.rollspeed;
gyros.y = packet.pitchspeed;
gyros.z = packet.yawspeed;
// m/s/s
Vector3f accels;
accels.x = (float)packet.xacc / 1000.0;
accels.y = (float)packet.yacc / 1000.0;
accels.z = (float)packet.zacc / 1000.0;
imu.set_gyro(gyros);
imu.set_accel(accels);
// set AHRS hil sensor
ahrs.setHil(packet.roll,packet.pitch,packet.yaw,packet.rollspeed,
packet.pitchspeed,packet.yawspeed);
break;
}
#endif // HIL_MODE != HIL_MODE_DISABLED
/*
* case MAVLINK_MSG_ID_HEARTBEAT:
* {
* // We keep track of the last time we received a heartbeat from our GCS for failsafe purposes
* if(msg->sysid != g.sysid_my_gcs) break;
* rc_override_fs_timer = millis();
* break;
* }
*
* #if HIL_MODE != HIL_MODE_DISABLED
* // This is used both as a sensor and to pass the location
* // in HIL_ATTITUDE mode.
* case MAVLINK_MSG_ID_GPS_RAW:
* {
* // decode
* mavlink_gps_raw_t packet;
* mavlink_msg_gps_raw_decode(msg, &packet);
*
* // set gps hil sensor
* g_gps->setHIL(packet.usec/1000,packet.lat,packet.lon,packet.alt,
* packet.v,packet.hdg,0,0);
* break;
* }
* #endif
*/
#if HIL_MODE == HIL_MODE_SENSORS
case MAVLINK_MSG_ID_RAW_IMU: // 28
{
// decode
mavlink_raw_imu_t packet;
mavlink_msg_raw_imu_decode(msg, &packet);
// set imu hil sensors
// TODO: check scaling for temp/absPress
float temp = 70;
float absPress = 1;
// Serial.printf_P(PSTR("accel:\t%d\t%d\t%d\n"), packet.xacc, packet.yacc, packet.zacc);
// Serial.printf_P(PSTR("gyro:\t%d\t%d\t%d\n"), packet.xgyro, packet.ygyro, packet.zgyro);
// rad/sec
Vector3f gyros;
gyros.x = (float)packet.xgyro / 1000.0;
gyros.y = (float)packet.ygyro / 1000.0;
gyros.z = (float)packet.zgyro / 1000.0;
// m/s/s
Vector3f accels;
accels.x = (float)packet.xacc / 1000.0;
accels.y = (float)packet.yacc / 1000.0;
accels.z = (float)packet.zacc / 1000.0;
imu.set_gyro(gyros);
imu.set_accel(accels);
compass.setHIL(packet.xmag,packet.ymag,packet.zmag);
break;
}
case MAVLINK_MSG_ID_RAW_PRESSURE: //29
{
// decode
mavlink_raw_pressure_t packet;
mavlink_msg_raw_pressure_decode(msg, &packet);
// set pressure hil sensor
// TODO: check scaling
float temp = 70;
barometer.setHIL(temp,packet.press_diff1);
break;
}
#endif // HIL_MODE
#if CAMERA == ENABLED
case MAVLINK_MSG_ID_DIGICAM_CONFIGURE:
{
g.camera.configure_msg(msg);
break;
}
case MAVLINK_MSG_ID_DIGICAM_CONTROL:
{
g.camera.control_msg(msg);
break;
}
#endif // CAMERA == ENABLED
#if MOUNT == ENABLED
case MAVLINK_MSG_ID_MOUNT_CONFIGURE:
{
camera_mount.configure_msg(msg);
break;
}
case MAVLINK_MSG_ID_MOUNT_CONTROL:
{
camera_mount.control_msg(msg);
break;
}
case MAVLINK_MSG_ID_MOUNT_STATUS:
{
camera_mount.status_msg(msg);
break;
}
#endif // MOUNT == ENABLED
case MAVLINK_MSG_ID_RADIO:
{
mavlink_radio_t packet;
mavlink_msg_radio_decode(msg, &packet);
// use the state of the transmit buffer in the radio to
// control the stream rate, giving us adaptive software
// flow control
if (packet.txbuf < 20 && stream_slowdown < 100) {
// we are very low on space - slow down a lot
stream_slowdown += 3;
} else if (packet.txbuf < 50 && stream_slowdown < 100) {
// we are a bit low on space, slow down slightly
stream_slowdown += 1;
} else if (packet.txbuf > 95 && stream_slowdown > 10) {
// the buffer has plenty of space, speed up a lot
stream_slowdown -= 2;
} else if (packet.txbuf > 90 && stream_slowdown != 0) {
// the buffer has enough space, speed up a bit
stream_slowdown--;
}
break;
}
#ifdef AP_LIMITS
// receive an AP_Limits fence point from GCS and store in EEPROM
// receive a fence point from GCS and store in EEPROM
case MAVLINK_MSG_ID_FENCE_POINT: {
mavlink_fence_point_t packet;
mavlink_msg_fence_point_decode(msg, &packet);
if (packet.count != geofence_limit.fence_total()) {
send_text(SEVERITY_LOW,PSTR("bad fence point"));
} else {
Vector2l point;
point.x = packet.lat*1.0e7;
point.y = packet.lng*1.0e7;
geofence_limit.set_fence_point_with_index(point, packet.idx);
}
break;
}
// send a fence point to GCS
case MAVLINK_MSG_ID_FENCE_FETCH_POINT: {
mavlink_fence_fetch_point_t packet;
mavlink_msg_fence_fetch_point_decode(msg, &packet);
if (mavlink_check_target(packet.target_system, packet.target_component))
break;
if (packet.idx >= geofence_limit.fence_total()) {
send_text(SEVERITY_LOW,PSTR("bad fence point"));
} else {
Vector2l point = geofence_limit.get_fence_point_with_index(packet.idx);
mavlink_msg_fence_point_send(chan, 0, 0, packet.idx, geofence_limit.fence_total(),
point.x*1.0e-7, point.y*1.0e-7);
}
break;
}
#endif // AP_LIMITS ENABLED
} // end switch
} // end handle mavlink
uint16_t
GCS_MAVLINK::_count_parameters()
{
// if we haven't cached the parameter count yet...
if (0 == _parameter_count) {
AP_Param *vp;
AP_Param::ParamToken token;
vp = AP_Param::first(&token, NULL);
do {
_parameter_count++;
} while (NULL != (vp = AP_Param::next_scalar(&token, NULL)));
}
return _parameter_count;
}
/**
* @brief Send the next pending parameter, called from deferred message
* handling code
*/
void
GCS_MAVLINK::queued_param_send()
{
// Check to see if we are sending parameters
if (NULL == _queued_parameter) return;
AP_Param *vp;
float value;
// copy the current parameter and prepare to move to the next
vp = _queued_parameter;
// if the parameter can be cast to float, report it here and break out of the loop
value = vp->cast_to_float(_queued_parameter_type);
char param_name[ONBOARD_PARAM_NAME_LENGTH];
vp->copy_name(param_name, sizeof(param_name), true);
mavlink_msg_param_value_send(
chan,
param_name,
value,
mav_var_type(_queued_parameter_type),
_queued_parameter_count,
_queued_parameter_index);
_queued_parameter = AP_Param::next_scalar(&_queued_parameter_token, &_queued_parameter_type);
_queued_parameter_index++;
}
/**
* @brief Send the next pending waypoint, called from deferred message
* handling code
*/
void
GCS_MAVLINK::queued_waypoint_send()
{
if (waypoint_receiving &&
waypoint_request_i < (unsigned)g.command_total) {
mavlink_msg_mission_request_send(
chan,
waypoint_dest_sysid,
waypoint_dest_compid,
waypoint_request_i);
}
}
/*
* a delay() callback that processes MAVLink packets. We set this as the
* callback in long running library initialisation routines to allow
* MAVLink to process packets while waiting for the initialisation to
* complete
*/
static void mavlink_delay(unsigned long t)
{
uint32_t tstart;
static uint32_t last_1hz, last_50hz, last_5s;
if (in_mavlink_delay) {
// this should never happen, but let's not tempt fate by
// letting the stack grow too much
delay(t);
return;
}
in_mavlink_delay = true;
tstart = millis();
do {
uint32_t tnow = millis();
if (tnow - last_1hz > 1000) {
last_1hz = tnow;
gcs_send_message(MSG_HEARTBEAT);
gcs_send_message(MSG_EXTENDED_STATUS1);
}
if (tnow - last_50hz > 20) {
last_50hz = tnow;
gcs_update();
gcs_data_stream_send();
}
if (tnow - last_5s > 5000) {
last_5s = tnow;
gcs_send_text_P(SEVERITY_LOW, PSTR("Initialising APM..."));
}
delay(1);
#if USB_MUX_PIN > 0
check_usb_mux();
#endif
} while (millis() - tstart < t);
in_mavlink_delay = false;
}
/*
* send a message on both GCS links
*/
static void gcs_send_message(enum ap_message id)
{
gcs0.send_message(id);
if (gcs3.initialised) {
gcs3.send_message(id);
}
}
/*
* send data streams in the given rate range on both links
*/
static void gcs_data_stream_send(void)
{
gcs0.data_stream_send();
if (gcs3.initialised) {
gcs3.data_stream_send();
}
}
/*
* look for incoming commands on the GCS links
*/
static void gcs_update(void)
{
gcs0.update();
if (gcs3.initialised) {
gcs3.update();
}
}
static void gcs_send_text(gcs_severity severity, const char *str)
{
gcs0.send_text(severity, str);
if (gcs3.initialised) {
gcs3.send_text(severity, str);
}
}
static void gcs_send_text_P(gcs_severity severity, const prog_char_t *str)
{
gcs0.send_text(severity, str);
if (gcs3.initialised) {
gcs3.send_text(severity, str);
}
}
/*
* send a low priority formatted message to the GCS
* only one fits in the queue, so if you send more than one before the
* last one gets into the serial buffer then the old one will be lost
*/
static void gcs_send_text_fmt(const prog_char_t *fmt, ...)
{
char fmtstr[40];
va_list ap;
uint8_t i;
for (i=0; i<sizeof(fmtstr)-1; i++) {
fmtstr[i] = pgm_read_byte((const prog_char *)(fmt++));
if (fmtstr[i] == 0) break;
}
fmtstr[i] = 0;
pending_status.severity = (uint8_t)SEVERITY_LOW;
va_start(ap, fmt);
vsnprintf((char *)pending_status.text, sizeof(pending_status.text), fmtstr, ap);
va_end(ap);
mavlink_send_message(MAVLINK_COMM_0, MSG_STATUSTEXT, 0);
if (gcs3.initialised) {
mavlink_send_message(MAVLINK_COMM_1, MSG_STATUSTEXT, 0);
}
}
| [
"[email protected]"
] | |
5d9e098f5bdb22625cb478ad0fe87b7a3a535890 | 99d054f93c3dd45a80e99be05f3f64c2c568ea5d | /Online Judges/Neps Academy/LoteriaOBI2014.cpp | e93dfa4b79af724600cf0519739d73c4d19fd69d | [
"MIT"
] | permissive | AnneLivia/Competitive-Programming | 65972d72fc4a0b37589da408e52ada19889f7ba8 | f4057e4bce37a636c85875cc80e5a53eb715f4be | refs/heads/master | 2022-12-23T11:52:04.299919 | 2022-12-12T16:20:05 | 2022-12-12T16:20:05 | 117,617,504 | 74 | 21 | MIT | 2019-11-14T03:11:58 | 2018-01-16T01:58:28 | C++ | UTF-8 | C++ | false | false | 620 | cpp | #include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int>v(100, 0);
int n, cont = 0;
for (int i = 0; i < 6; i++)
{
cin >> n;
v[n] = 1;
}
for (int i = 0; i < 6; i++)
{
cin >> n;
if (v[n])
cont++;
}
switch(cont) {
case 3 : cout << "terno\n";
break;
case 4 : cout << "quadra\n";
break;
case 5 : cout << "quina\n";
break;
case 6 : cout << "sena\n";
break;
default: cout << "azar\n";
}
return 0;
}
| [
"[email protected]"
] | |
7e8da0c247ee572e7b13128743a4116aee5650b6 | e3afeab04cfed95b18affeb766bdffec6c610ab3 | /tools/sworks/SwUnibase/SwUniAttr.h | 8b257f91f826b7f734862b302e58d9328a78d9ca | [] | no_license | VB6Hobbyst7/NCL_in_VisualStudio | 2831e101163d34be5b5775c458471313cd6c035b | 998a5a4ca9eb1cfdee0b276ae9541f7d1f7e6371 | refs/heads/master | 2023-06-24T12:03:34.428725 | 2021-07-27T20:30:46 | 2021-07-27T20:30:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,846 | h | /*********************************************************************
** NAME: SwUniAttr.cpp
**
** Implementation of SolidWorks Attributes class functions.
**
** CONTAINS: CUniAttr class functions
**
** COPYRIGHT 2003 (c) NCCS. All Rights Reserved.
** MODULE NAME AND RELEASE LEVEL
** SwUniAttr.h , 24.2
** DATE AND TIME OF LAST MODIFICATION
** 08/13/14 , 14:51:00
*********************************************************************/
// UniAttr.h : Declaration of the CUniAttr
#ifndef __UNIATTR_H_
#define __UNIATTR_H_
#include "Swresource.h" // main symbols
#include <atlhost.h>
extern "C" int UIG_color_sec;
extern "C" int UIG_layer_sec;
/////////////////////////////////////////////////////////////////////////////
// CUniAttr
class CUniAttr :
public CAxDialogImpl<CUniAttr>
{
private:
int m_layers[7];
int m_colors[7];
int *m_layer_ptr;
int *m_color_ptr;
char c1str[16][20];
int m_combo[7];
int m_edit[7];
public:
CUniAttr(int *layers,int *colors)
{
int i;
//
//...Store form structure
//
m_layer_ptr = layers;
m_color_ptr = colors;
for (i=0;i<6;i++)
{
m_layers[i] = layers[i];
m_colors[i] = colors[i];
}
m_layers[6]=UIG_layer_sec;
m_colors[6]=UIG_color_sec;
//
//...Initialize variables
//
strcpy(c1str[0],"Default");
strcpy(c1str[1],"White");
strcpy(c1str[2],"Blue");
strcpy(c1str[3],"Red");
strcpy(c1str[4],"Green");
strcpy(c1str[5],"Magenta");
strcpy(c1str[6],"Yellow");
strcpy(c1str[7],"Cyan");
strcpy(c1str[8],"Brown");
strcpy(c1str[9],"Tan");
strcpy(c1str[10],"Lt Blue");
strcpy(c1str[11],"Sea Green");
strcpy(c1str[12],"Orange");
strcpy(c1str[13],"Pink");
strcpy(c1str[14],"Purple");
strcpy(c1str[15],"Grey");
m_combo[0] = IDC_UNIATTR_COMBO1;
m_combo[1] = IDC_UNIATTR_COMBO2;
m_combo[2] = IDC_UNIATTR_COMBO3;
m_combo[3] = IDC_UNIATTR_COMBO4;
m_combo[4] = IDC_UNIATTR_COMBO5;
m_combo[5] = IDC_UNIATTR_COMBO6;
m_combo[6] = IDC_UNIATTR_COMBO7;
m_edit[0] = IDC_UNIATTR_EDIT1;
m_edit[1] = IDC_UNIATTR_EDIT2;
m_edit[2] = IDC_UNIATTR_EDIT3;
m_edit[3] = IDC_UNIATTR_EDIT4;
m_edit[4] = IDC_UNIATTR_EDIT5;
m_edit[5] = IDC_UNIATTR_EDIT6;
m_edit[6] = IDC_UNIATTR_EDIT7;
}
~CUniAttr()
{
}
enum { IDD = IDD_UNIATTR };
BEGIN_MSG_MAP(CUniAttr)
MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog)
COMMAND_ID_HANDLER(IDOK, OnOK)
COMMAND_ID_HANDLER(IDCANCEL, OnCancel)
COMMAND_ID_HANDLER(IDC_UNIATTR_COMBO1, OnCombo)
COMMAND_ID_HANDLER(IDC_UNIATTR_COMBO2, OnCombo)
COMMAND_ID_HANDLER(IDC_UNIATTR_COMBO3, OnCombo)
COMMAND_ID_HANDLER(IDC_UNIATTR_COMBO4, OnCombo)
COMMAND_ID_HANDLER(IDC_UNIATTR_COMBO5, OnCombo)
COMMAND_ID_HANDLER(IDC_UNIATTR_COMBO6, OnCombo)
COMMAND_ID_HANDLER(IDC_UNIATTR_COMBO7, OnCombo)
END_MSG_MAP()
// Handler prototypes:
// LRESULT MessageHandler(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled);
// LRESULT CommandHandler(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled);
// LRESULT NotifyHandler(int idCtrl, LPNMHDR pnmh, BOOL& bHandled);
LRESULT OnInitDialog(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
int i,j;
char sbuf[20];
CWindow combo;
TCHAR bstr[20];
//
//...Initialize Form
//......Layers
//
for (i=0;i<7;i++)
{
sprintf(sbuf,"%d",m_layers[i]);
SetDlgItemText(m_edit[i],(CComBSTR)sbuf);
}
//
//......Colors
//
for (i=0;i<7;i++)
{
combo = GetDlgItem(m_combo[i]);
for (j=0;j<16;j++)
{
mbstowcs(bstr,c1str[j],strlen(c1str[j])+1);
combo.SendMessage(CB_ADDSTRING,0,(LPARAM)bstr);
}
combo.SendMessage(CB_SETCURSEL,m_colors[i],0);
}
return 1; // Let the system set the focus
}
LRESULT OnOK(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled)
{
int i,nc;
char cstr[20];
TCHAR bstr[20];
for (i=0;i<7;i++)
{
GetDlgItemText(m_edit[i],bstr,20);
nc = wcslen(bstr);
wcstombs(cstr,bstr,nc+1);
sscanf(cstr,"%d",&m_layers[i]);
if (m_layers[i] < 1 || m_layers[i] > 9999)
{
AfxMessageBox(_T("Layers must be between 1 and 9999."));
return 1;
}
}
for (i=0;i<6;i++)
{
m_layer_ptr[i] = m_layers[i];
m_color_ptr[i] = m_colors[i];
}
UIG_layer_sec = m_layers[6];
UIG_color_sec = m_colors[6];
EndDialog(wID);
return 0;
}
LRESULT OnCancel(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled)
{
EndDialog(wID);
return 0;
}
LRESULT OnCombo(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled)
{
int i,j,nc;
char cstr[20];
TCHAR bstr[20];
//
//...Get the toggle text
//
GetDlgItemText(wID,bstr,20);
nc = wcslen(bstr);
wcstombs(cstr,bstr,nc+1);
//
//...Get active form field
//
for (i=0;i<7;i++)
if (wID == m_combo[i]) break;
//
//...Save the response
//
if (i < 7)
{
for (j=0;j<16;j++)
{
if (strcmp(cstr,c1str[j]) == 0) m_colors[i] = j;
}
}
return 0;
}
};
#endif //__UNIATTR_H_
| [
"[email protected]"
] | |
dcdffdf9440c3fa9af14ae282d4fa3e987cfc461 | f47598d0bb10854a7d1c929e35c6494320081c2b | /stereo_cam_imu_driver/include/Float64Stamped.h | 2f6d04fcd579c27548faee580389c4ad146f8dac | [] | no_license | tixidi/qrcode | 50c192dd2ffc93fb0cc82372bd13aae183432b82 | b57a74455357eeb878799c393177de5247b48c21 | refs/heads/master | 2021-03-03T23:37:56.133692 | 2017-10-11T12:29:25 | 2017-10-11T12:29:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,086 | h | // Generated by gencpp from file stereo_camera/Float64Stamped.msg
// DO NOT EDIT!
#ifndef STEREO_CAMERA_MESSAGE_FLOAT64STAMPED_H
#define STEREO_CAMERA_MESSAGE_FLOAT64STAMPED_H
#include <string>
#include <vector>
#include <map>
#include <ros/types.h>
#include <ros/serialization.h>
#include <ros/builtin_message_traits.h>
#include <ros/message_operations.h>
#include <std_msgs/Header.h>
namespace stereo_camera
{
template <class ContainerAllocator>
struct Float64Stamped_
{
typedef Float64Stamped_<ContainerAllocator> Type;
Float64Stamped_()
: header()
, data(0.0) {
}
Float64Stamped_(const ContainerAllocator& _alloc)
: header(_alloc)
, data(0.0) {
(void)_alloc;
}
typedef ::std_msgs::Header_<ContainerAllocator> _header_type;
_header_type header;
typedef double _data_type;
_data_type data;
typedef boost::shared_ptr< ::stereo_camera::Float64Stamped_<ContainerAllocator> > Ptr;
typedef boost::shared_ptr< ::stereo_camera::Float64Stamped_<ContainerAllocator> const> ConstPtr;
}; // struct Float64Stamped_
typedef ::stereo_camera::Float64Stamped_<std::allocator<void> > Float64Stamped;
typedef boost::shared_ptr< ::stereo_camera::Float64Stamped > Float64StampedPtr;
typedef boost::shared_ptr< ::stereo_camera::Float64Stamped const> Float64StampedConstPtr;
// constants requiring out of line definition
template<typename ContainerAllocator>
std::ostream& operator<<(std::ostream& s, const ::stereo_camera::Float64Stamped_<ContainerAllocator> & v)
{
ros::message_operations::Printer< ::stereo_camera::Float64Stamped_<ContainerAllocator> >::stream(s, "", v);
return s;
}
} // namespace stereo_camera
namespace ros
{
namespace message_traits
{
// BOOLTRAITS {'IsFixedSize': False, 'IsMessage': True, 'HasHeader': True}
// {'stereo_camera': ['/home/maroon/imu/src/stereo_cam/msg'], 'std_msgs': ['/opt/ros/kinetic/share/std_msgs/cmake/../msg']}
// !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types']
template <class ContainerAllocator>
struct IsFixedSize< ::stereo_camera::Float64Stamped_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct IsFixedSize< ::stereo_camera::Float64Stamped_<ContainerAllocator> const>
: FalseType
{ };
template <class ContainerAllocator>
struct IsMessage< ::stereo_camera::Float64Stamped_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::stereo_camera::Float64Stamped_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct HasHeader< ::stereo_camera::Float64Stamped_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct HasHeader< ::stereo_camera::Float64Stamped_<ContainerAllocator> const>
: TrueType
{ };
template<class ContainerAllocator>
struct MD5Sum< ::stereo_camera::Float64Stamped_<ContainerAllocator> >
{
static const char* value()
{
return "e6c99c37e6f9fe98e071d524cc164e65";
}
static const char* value(const ::stereo_camera::Float64Stamped_<ContainerAllocator>&) { return value(); }
static const uint64_t static_value1 = 0xe6c99c37e6f9fe98ULL;
static const uint64_t static_value2 = 0xe071d524cc164e65ULL;
};
template<class ContainerAllocator>
struct DataType< ::stereo_camera::Float64Stamped_<ContainerAllocator> >
{
static const char* value()
{
return "stereo_camera/Float64Stamped";
}
static const char* value(const ::stereo_camera::Float64Stamped_<ContainerAllocator>&) { return value(); }
};
template<class ContainerAllocator>
struct Definition< ::stereo_camera::Float64Stamped_<ContainerAllocator> >
{
static const char* value()
{
return "std_msgs/Header header\n\
float64 data\n\
\n\
================================================================================\n\
MSG: std_msgs/Header\n\
# Standard metadata for higher-level stamped data types.\n\
# This is generally used to communicate timestamped data \n\
# in a particular coordinate frame.\n\
# \n\
# sequence ID: consecutively increasing ID \n\
uint32 seq\n\
#Two-integer timestamp that is expressed as:\n\
# * stamp.sec: seconds (stamp_secs) since epoch (in Python the variable is called 'secs')\n\
# * stamp.nsec: nanoseconds since stamp_secs (in Python the variable is called 'nsecs')\n\
# time-handling sugar is provided by the client library\n\
time stamp\n\
#Frame this data is associated with\n\
# 0: no frame\n\
# 1: global frame\n\
string frame_id\n\
";
}
static const char* value(const ::stereo_camera::Float64Stamped_<ContainerAllocator>&) { return value(); }
};
} // namespace message_traits
} // namespace ros
namespace ros
{
namespace serialization
{
template<class ContainerAllocator> struct Serializer< ::stereo_camera::Float64Stamped_<ContainerAllocator> >
{
template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m)
{
stream.next(m.header);
stream.next(m.data);
}
ROS_DECLARE_ALLINONE_SERIALIZER
}; // struct Float64Stamped_
} // namespace serialization
} // namespace ros
namespace ros
{
namespace message_operations
{
template<class ContainerAllocator>
struct Printer< ::stereo_camera::Float64Stamped_<ContainerAllocator> >
{
template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::stereo_camera::Float64Stamped_<ContainerAllocator>& v)
{
s << indent << "header: ";
s << std::endl;
Printer< ::std_msgs::Header_<ContainerAllocator> >::stream(s, indent + " ", v.header);
s << indent << "data: ";
Printer<double>::stream(s, indent + " ", v.data);
}
};
} // namespace message_operations
} // namespace ros
#endif // STEREO_CAMERA_MESSAGE_FLOAT64STAMPED_H
| [
"w_shiwe.163.com"
] | w_shiwe.163.com |
6dfcb875a341778a31e3afadb00a50d9a177a125 | 7aee591cf4c43a9ec382bb2e20ca89e769e4cae5 | /listmodel.cpp | 35f37e879218b326aa1c4b19c35c4ddaa199ee6f | [] | no_license | arcean/wlanscanner | a26407431b7f12e83301e8280cc1c71d84f83ac3 | 4acd85d64a23605a71f0c9b035a22f7dce061946 | refs/heads/master | 2021-01-21T12:36:32.721337 | 2013-01-08T18:59:19 | 2013-01-08T18:59:19 | 34,137,833 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,088 | cpp | /***************************************************************************
**
** Copyright (C) 2012 Tomasz Pieniążek
** All rights reserved.
** Contact: Tomasz Pieniążek <[email protected]>
**
** This program is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include <QDir>
#include <QFileInfoList>
#include <QDebug>
#include "listmodel.h"
ListModel::ListModel(QObject *parent)
: MAbstractItemModel(parent)
{
}
void ListModel::reload(const QList<ScanResult> &networks)
{
qDebug() << "reload";
this->newNetworks = networks;
qDebug() << "newNetworks updated";
/* if(networks.count() > 0)
qDebug() << networks.at(0).getEssid() << " " << networks.at(0).getEncryption();
for (int i = 0; i < networks.count(); i++) {
qDebug() << "dataChanged for" << i;
emit dataChanged(createIndex(i, 0), createIndex(i, 0));
}*/
}
int ListModel::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return networks.count();
}
/*
QVariant ListModel::data(const QModelIndex &index, int role) const
{
if (role == Qt::DisplayRole) {
QStringList rowData;
rowData << filesData.at(index.row());
return QVariant(rowData);
}
return QVariant();
}*/
int ListModel::groupCount() const
{
return 0;
}
int ListModel::rowCountInGroup(int group) const
{
return networks.count();
}
QString ListModel::groupTitle(int group) const
{
return "";
}
QVariant ListModel::itemData(int row, int group, int role) const
{
int flatRow = row;
Q_ASSERT(flatRow >= 0);
Q_ASSERT(flatRow < filesData.size());
if (role == Qt::DisplayRole) {
QStringList rowData;
rowData << networks.at(row).getEssid();
rowData << networks.at(row).getEncryption();
rowData << networks.at(row).getSignalLevel();
qDebug() << "ROWDATA" << rowData;
return QVariant(rowData);
}
return QVariant();
}
bool ListModel::insertRows(int row, int count, const QModelIndex &parent)
{
if (count <= 0)
return true; // Successfully added 0 rows.
QList<ScanResult> data;
for (int i = row; i < row + count; i++) {
data.insert(i, newNetworks.at(i));
}
QModelIndex realParent = parent;
beginInsertRows(realParent, row, row + count - 1, count == 1);
networks = data;
endInsertRows();
return true;
}
bool ListModel::removeRows(int row, int count, const QModelIndex &parent)
{
if (count <= 0)
return true; //Successfully removed 0 rows.
Q_ASSERT(row >= 0);
Q_ASSERT(row < networks.size());
beginRemoveRows(parent, row, row + count - 1, count == 1);
//qDeleteAll(filesData.begin() + flatRow, filesData.begin() + flatRow + count - 1);
networks.removeAt(row);
endRemoveRows();
return true;
}
| [
"[email protected]"
] | |
c4774e8039b8aa188a35bed17455797351dcc110 | 354f2e2befd4ddb968c507930651bb4bac2e934e | /Class Notes + Assignments/Box2.cpp | fc43b23e46d56d95547886a7a008ced5c3c0861d | [] | no_license | cshue1/cisc2000 | 60f02a412e8dbdbddc84733079880a343965f8f9 | b5fba110cdbccd73b1c718913f260ce8142da167 | refs/heads/master | 2021-08-11T17:30:55.130335 | 2017-11-14T00:48:19 | 2017-11-14T00:48:19 | 107,361,249 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 874 | cpp | #include <iostream>
using namespace std;
class Box
{
private:
int id;
static int count;
public:
static boid showCount()
{
cout << "Count is " << count << endl;
}
Box()
{
cout << "Constructor called for id " << id << endl;
}
Box(int i)
{
id = i;
cout << "Constructor called for id " << id << endl;
}
~Box()
{
cout << "Destructor called for id "<< id << endl;
}
};
int main()
{
Box **boxArrPtr = new Box*[5];
Box box0(0);
Box box1(1);
Box box2(2);
boxArrPtr[0] =&box0;
boxArrPtr[1] =&box1;
boxArrPtr[2] =&box2;
cout << "Done with declaration." << endl;
cout << "Deleting boxArrPtr" << endl;
delete boxArrPtr[1];
cout << endl << endl;
delete [] boxArrPtr;
cout << "Before return 0" << endl;
return 0;
}
| [
"[email protected]"
] | |
2d89876f5526c05842ca6291d865a1241379f21b | b5167d966602092144f25ee6be68efd2f592c7e9 | /Classes/SlotGameScene.h | ef05871308cd54aa4a606485939f7b4a31286f8c | [
"Unlicense"
] | permissive | alexgg-developer/cocos2d-game | 0e3277628553f2321896453ff44e287fbf55cd6c | 25ef16d7da70ed9f879ce35676fa3257071c7a54 | refs/heads/master | 2020-03-28T11:21:26.071336 | 2018-09-11T17:06:24 | 2018-09-11T17:06:24 | 148,204,773 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,099 | h | /****************************************************************************
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#ifndef _SLOTGAME_SCENE_H__
#define _SLOTGAME_SCENE_H__
#include "cocos2d.h"
#include "ui/CocosGUI.h"
#include "SlotsLayer.h"
USING_NS_CC;
class SlotGameScene : public cocos2d::Scene
{
public:
static cocos2d::Scene* createScene();
virtual bool init();
void spinButtonClick();
// implement the "static create()" method manually
CREATE_FUNC(SlotGameScene);
private:
ui::Button* m_spinButton;
SlotsLayer* m_slotsLayer;
Label* m_counterLabel;
size_t m_counter;
float m_figureWidth, m_figureHeight;
std::map<FigureType, std::vector<size_t>> m_creditTable;
std::vector<DrawNode*> m_prizeRects;
std::vector<Label*> m_prizeLabels;
void calculatePrizes();
void clearMarkPrizes();
void initCreditTable();
void initSpinners();
void markPrizes();
};
#endif //_SLOTGAME_SCENE_H__S
| [
"[email protected]"
] | |
778c230ac1fc713b4130f285ceb8f3a0bc99bc6e | ffb2519a2dff89a252dc4629479012e0a284ccc6 | /src/connectivity_tool/conn_tool.cpp | 2e0786b8241a8bd177be5f64ffcea432229fca66 | [
"BSD-3-Clause"
] | permissive | oplcoin/oplcoin | 182d29cea80fccf71a56c9ff1253eeb552d72d22 | 2c86ad35d0225e3e5b4ceb2be6c9f4bc6385e7d9 | refs/heads/master | 2022-12-10T12:56:21.183065 | 2020-08-28T20:03:50 | 2020-08-28T20:03:50 | 291,135,890 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,192 | cpp | // Copyright (c) 2014, OplCoin, The Monero Project
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other
// materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers
#include "include_base_utils.h"
#include "version.h"
using namespace epee;
#include <boost/program_options.hpp>
#include "p2p/p2p_protocol_defs.h"
#include "common/command_line.h"
#include "cryptonote_core/cryptonote_core.h"
#include "cryptonote_protocol/cryptonote_protocol_handler.h"
#include "net/levin_client.h"
#include "storages/levin_abstract_invoke2.h"
#include "cryptonote_core/cryptonote_core.h"
#include "storages/portable_storage_template_helper.h"
#include "crypto/crypto.h"
#include "storages/http_abstract_invoke.h"
#include "net/http_client.h"
namespace po = boost::program_options;
using namespace cryptonote;
using namespace nodetool;
namespace
{
const command_line::arg_descriptor<std::string, true> arg_ip = {"ip", "set ip"};
const command_line::arg_descriptor<size_t> arg_port = {"port", "set port"};
const command_line::arg_descriptor<size_t> arg_rpc_port = {"rpc_port", "set rpc port"};
const command_line::arg_descriptor<uint32_t, true> arg_timeout = {"timeout", "set timeout"};
const command_line::arg_descriptor<std::string> arg_priv_key = {"private_key", "private key to subscribe debug command", "", true};
const command_line::arg_descriptor<uint64_t> arg_peer_id = {"peer_id", "peer_id if known(if not - will be requested)", 0};
const command_line::arg_descriptor<bool> arg_generate_keys = {"generate_keys_pair", "generate private and public keys pair"};
const command_line::arg_descriptor<bool> arg_request_stat_info = {"request_stat_info", "request statistics information"};
const command_line::arg_descriptor<bool> arg_request_net_state = {"request_net_state", "request network state information (peer list, connections count)"};
const command_line::arg_descriptor<bool> arg_get_daemon_info = {"rpc_get_daemon_info", "request daemon state info vie rpc (--rpc_port option should be set ).", "", true};
}
typedef COMMAND_REQUEST_STAT_INFO_T<t_cryptonote_protocol_handler<core>::stat_info> COMMAND_REQUEST_STAT_INFO;
struct response_schema
{
std::string status;
std::string COMMAND_REQUEST_STAT_INFO_status;
std::string COMMAND_REQUEST_NETWORK_STATE_status;
enableable<COMMAND_REQUEST_STAT_INFO::response> si_rsp;
enableable<COMMAND_REQUEST_NETWORK_STATE::response> ns_rsp;
BEGIN_KV_SERIALIZE_MAP()
KV_SERIALIZE(status)
KV_SERIALIZE(COMMAND_REQUEST_STAT_INFO_status)
KV_SERIALIZE(COMMAND_REQUEST_NETWORK_STATE_status)
KV_SERIALIZE(si_rsp)
KV_SERIALIZE(ns_rsp)
END_KV_SERIALIZE_MAP()
};
std::string get_response_schema_as_json(response_schema& rs)
{
std::stringstream ss;
ss << "{" << ENDL
<< " \"status\": \"" << rs.status << "\"," << ENDL
<< " \"COMMAND_REQUEST_NETWORK_STATE_status\": \"" << rs.COMMAND_REQUEST_NETWORK_STATE_status << "\"," << ENDL
<< " \"COMMAND_REQUEST_STAT_INFO_status\": \"" << rs.COMMAND_REQUEST_STAT_INFO_status << "\"";
if(rs.si_rsp.enabled)
{
ss << "," << ENDL << " \"si_rsp\": " << epee::serialization::store_t_to_json(rs.si_rsp.v, 1);
}
if(rs.ns_rsp.enabled)
{
ss << "," << ENDL << " \"ns_rsp\": {" << ENDL
<< " \"local_time\": " << rs.ns_rsp.v.local_time << "," << ENDL
<< " \"my_id\": \"" << rs.ns_rsp.v.my_id << "\"," << ENDL
<< " \"connections_list\": [" << ENDL;
size_t i = 0;
BOOST_FOREACH(const connection_entry& ce, rs.ns_rsp.v.connections_list)
{
ss << " {\"peer_id\": \"" << ce.id << "\", \"ip\": \"" << string_tools::get_ip_string_from_int32(ce.adr.ip) << "\", \"port\": " << ce.adr.port << ", \"is_income\": "<< ce.is_income << "}";
if(rs.ns_rsp.v.connections_list.size()-1 != i)
ss << ",";
ss << ENDL;
i++;
}
ss << " ]," << ENDL;
ss << " \"local_peerlist_white\": [" << ENDL;
i = 0;
BOOST_FOREACH(const peerlist_entry& pe, rs.ns_rsp.v.local_peerlist_white)
{
ss << " {\"peer_id\": \"" << pe.id << "\", \"ip\": \"" << string_tools::get_ip_string_from_int32(pe.adr.ip) << "\", \"port\": " << pe.adr.port << ", \"last_seen\": "<< rs.ns_rsp.v.local_time - pe.last_seen << "}";
if(rs.ns_rsp.v.local_peerlist_white.size()-1 != i)
ss << ",";
ss << ENDL;
i++;
}
ss << " ]," << ENDL;
ss << " \"local_peerlist_gray\": [" << ENDL;
i = 0;
BOOST_FOREACH(const peerlist_entry& pe, rs.ns_rsp.v.local_peerlist_gray)
{
ss << " {\"peer_id\": \"" << pe.id << "\", \"ip\": \"" << string_tools::get_ip_string_from_int32(pe.adr.ip) << "\", \"port\": " << pe.adr.port << ", \"last_seen\": "<< rs.ns_rsp.v.local_time - pe.last_seen << "}";
if(rs.ns_rsp.v.local_peerlist_gray.size()-1 != i)
ss << ",";
ss << ENDL;
i++;
}
ss << " ]" << ENDL << " }" << ENDL;
}
ss << "}";
return std::move(ss.str());
}
//---------------------------------------------------------------------------------------------------------------
bool print_COMMAND_REQUEST_STAT_INFO(const COMMAND_REQUEST_STAT_INFO::response& si)
{
std::cout << " ------ COMMAND_REQUEST_STAT_INFO ------ " << ENDL;
std::cout << "Version: " << si.version << ENDL;
std::cout << "OS Version: " << si.os_version << ENDL;
std::cout << "Connections: " << si.connections_count << ENDL;
std::cout << "INC Connections: " << si.incoming_connections_count << ENDL;
std::cout << "Tx pool size: " << si.payload_info.tx_pool_size << ENDL;
std::cout << "BC height: " << si.payload_info.blockchain_height << ENDL;
std::cout << "Mining speed: " << si.payload_info.mining_speed << ENDL;
std::cout << "Alternative blocks: " << si.payload_info.alternative_blocks << ENDL;
std::cout << "Top block id: " << si.payload_info.top_block_id_str << ENDL;
return true;
}
//---------------------------------------------------------------------------------------------------------------
bool print_COMMAND_REQUEST_NETWORK_STATE(const COMMAND_REQUEST_NETWORK_STATE::response& ns)
{
std::cout << " ------ COMMAND_REQUEST_NETWORK_STATE ------ " << ENDL;
std::cout << "Peer id: " << ns.my_id << ENDL;
std::cout << "Active connections:" << ENDL;
BOOST_FOREACH(const connection_entry& ce, ns.connections_list)
{
std::cout << ce.id << "\t" << string_tools::get_ip_string_from_int32(ce.adr.ip) << ":" << ce.adr.port << (ce.is_income ? "(INC)":"(OUT)") << ENDL;
}
std::cout << "Peer list white:" << ns.my_id << ENDL;
BOOST_FOREACH(const peerlist_entry& pe, ns.local_peerlist_white)
{
std::cout << pe.id << "\t" << string_tools::get_ip_string_from_int32(pe.adr.ip) << ":" << pe.adr.port << "\t" << misc_utils::get_time_interval_string(ns.local_time - pe.last_seen) << ENDL;
}
std::cout << "Peer list gray:" << ns.my_id << ENDL;
BOOST_FOREACH(const peerlist_entry& pe, ns.local_peerlist_gray)
{
std::cout << pe.id << "\t" << string_tools::get_ip_string_from_int32(pe.adr.ip) << ":" << pe.adr.port << "\t" << misc_utils::get_time_interval_string(ns.local_time - pe.last_seen) << ENDL;
}
return true;
}
//---------------------------------------------------------------------------------------------------------------
bool handle_get_daemon_info(po::variables_map& vm)
{
if(!command_line::has_arg(vm, arg_rpc_port))
{
std::cout << "ERROR: rpc port not set" << ENDL;
return false;
}
epee::net_utils::http::http_simple_client http_client;
cryptonote::COMMAND_RPC_GET_INFO::request req = AUTO_VAL_INIT(req);
cryptonote::COMMAND_RPC_GET_INFO::response res = AUTO_VAL_INIT(res);
std::string daemon_addr = command_line::get_arg(vm, arg_ip) + ":" + std::to_string(command_line::get_arg(vm, arg_rpc_port));
bool r = net_utils::invoke_http_json_remote_command2(daemon_addr + "/getinfo", req, res, http_client, command_line::get_arg(vm, arg_timeout));
if(!r)
{
std::cout << "ERROR: failed to invoke request" << ENDL;
return false;
}
std::cout << "OK" << ENDL
<< "height: " << res.height << ENDL
<< "difficulty: " << res.difficulty << ENDL
<< "tx_count: " << res.tx_count << ENDL
<< "tx_pool_size: " << res.tx_pool_size << ENDL
<< "alt_blocks_count: " << res.alt_blocks_count << ENDL
<< "outgoing_connections_count: " << res.outgoing_connections_count << ENDL
<< "incoming_connections_count: " << res.incoming_connections_count << ENDL
<< "white_peerlist_size: " << res.white_peerlist_size << ENDL
<< "grey_peerlist_size: " << res.grey_peerlist_size << ENDL;
return true;
}
//---------------------------------------------------------------------------------------------------------------
bool handle_request_stat(po::variables_map& vm, peerid_type peer_id)
{
if(!command_line::has_arg(vm, arg_priv_key))
{
std::cout << "{" << ENDL << " \"status\": \"ERROR: " << "secret key not set \"" << ENDL << "}";
return false;
}
crypto::secret_key prvk = AUTO_VAL_INIT(prvk);
if(!string_tools::hex_to_pod(command_line::get_arg(vm, arg_priv_key) , prvk))
{
std::cout << "{" << ENDL << " \"status\": \"ERROR: " << "wrong secret key set \"" << ENDL << "}";
return false;
}
response_schema rs = AUTO_VAL_INIT(rs);
levin::levin_client_impl2 transport;
if(!transport.connect(command_line::get_arg(vm, arg_ip), static_cast<int>(command_line::get_arg(vm, arg_port)), static_cast<int>(command_line::get_arg(vm, arg_timeout))))
{
std::cout << "{" << ENDL << " \"status\": \"ERROR: " << "Failed to connect to " << command_line::get_arg(vm, arg_ip) << ":" << command_line::get_arg(vm, arg_port) << "\"" << ENDL << "}";
return false;
}else
rs.status = "OK";
if(!peer_id)
{
COMMAND_REQUEST_PEER_ID::request req = AUTO_VAL_INIT(req);
COMMAND_REQUEST_PEER_ID::response rsp = AUTO_VAL_INIT(rsp);
if(!net_utils::invoke_remote_command2(COMMAND_REQUEST_PEER_ID::ID, req, rsp, transport))
{
std::cout << "{" << ENDL << " \"status\": \"ERROR: " << "Failed to connect to " << command_line::get_arg(vm, arg_ip) << ":" << command_line::get_arg(vm, arg_port) << "\"" << ENDL << "}";
return false;
}else
{
peer_id = rsp.my_id;
}
}
nodetool::proof_of_trust pot = AUTO_VAL_INIT(pot);
pot.peer_id = peer_id;
pot.time = time(NULL);
crypto::public_key pubk = AUTO_VAL_INIT(pubk);
string_tools::hex_to_pod(P2P_STAT_TRUSTED_PUB_KEY, pubk);
crypto::hash h = tools::get_proof_of_trust_hash(pot);
crypto::generate_signature(h, pubk, prvk, pot.sign);
if(command_line::get_arg(vm, arg_request_stat_info))
{
COMMAND_REQUEST_STAT_INFO::request req = AUTO_VAL_INIT(req);
req.tr = pot;
if(!net_utils::invoke_remote_command2(COMMAND_REQUEST_STAT_INFO::ID, req, rs.si_rsp.v, transport))
{
std::stringstream ss;
ss << "ERROR: " << "Failed to invoke remote command COMMAND_REQUEST_STAT_INFO to " << command_line::get_arg(vm, arg_ip) << ":" << command_line::get_arg(vm, arg_port);
rs.COMMAND_REQUEST_STAT_INFO_status = ss.str();
}else
{
rs.si_rsp.enabled = true;
rs.COMMAND_REQUEST_STAT_INFO_status = "OK";
}
}
if(command_line::get_arg(vm, arg_request_net_state))
{
++pot.time;
h = tools::get_proof_of_trust_hash(pot);
crypto::generate_signature(h, pubk, prvk, pot.sign);
COMMAND_REQUEST_NETWORK_STATE::request req = AUTO_VAL_INIT(req);
req.tr = pot;
if(!net_utils::invoke_remote_command2(COMMAND_REQUEST_NETWORK_STATE::ID, req, rs.ns_rsp.v, transport))
{
std::stringstream ss;
ss << "ERROR: " << "Failed to invoke remote command COMMAND_REQUEST_NETWORK_STATE to " << command_line::get_arg(vm, arg_ip) << ":" << command_line::get_arg(vm, arg_port);
rs.COMMAND_REQUEST_NETWORK_STATE_status = ss.str();
}else
{
rs.ns_rsp.enabled = true;
rs.COMMAND_REQUEST_NETWORK_STATE_status = "OK";
}
}
std::cout << get_response_schema_as_json(rs);
return true;
}
//---------------------------------------------------------------------------------------------------------------
bool generate_and_print_keys()
{
crypto::public_key pk = AUTO_VAL_INIT(pk);
crypto::secret_key sk = AUTO_VAL_INIT(sk);
generate_keys(pk, sk);
std::cout << "PUBLIC KEY: " << epee::string_tools::pod_to_hex(pk) << ENDL
<< "PRIVATE KEY: " << epee::string_tools::pod_to_hex(sk);
return true;
}
int main(int argc, char* argv[])
{
string_tools::set_module_name_and_folder(argv[0]);
log_space::get_set_log_detalisation_level(true, LOG_LEVEL_0);
// Declare the supported options.
po::options_description desc_general("General options");
command_line::add_arg(desc_general, command_line::arg_help);
po::options_description desc_params("Connectivity options");
command_line::add_arg(desc_params, arg_ip);
command_line::add_arg(desc_params, arg_port);
command_line::add_arg(desc_params, arg_rpc_port);
command_line::add_arg(desc_params, arg_timeout);
command_line::add_arg(desc_params, arg_request_stat_info);
command_line::add_arg(desc_params, arg_request_net_state);
command_line::add_arg(desc_params, arg_generate_keys);
command_line::add_arg(desc_params, arg_peer_id);
command_line::add_arg(desc_params, arg_priv_key);
command_line::add_arg(desc_params, arg_get_daemon_info);
po::options_description desc_all;
desc_all.add(desc_general).add(desc_params);
po::variables_map vm;
bool r = command_line::handle_error_helper(desc_all, [&]()
{
po::store(command_line::parse_command_line(argc, argv, desc_general, true), vm);
if (command_line::get_arg(vm, command_line::arg_help))
{
std::cout << desc_all << ENDL;
return false;
}
po::store(command_line::parse_command_line(argc, argv, desc_params, false), vm);
po::notify(vm);
return true;
});
if (!r)
return 1;
if(command_line::has_arg(vm, arg_request_stat_info) || command_line::has_arg(vm, arg_request_net_state))
{
return handle_request_stat(vm, command_line::get_arg(vm, arg_peer_id)) ? 0:1;
}
if(command_line::has_arg(vm, arg_get_daemon_info))
{
return handle_get_daemon_info(vm) ? 0:1;
}
else if(command_line::has_arg(vm, arg_generate_keys))
{
return generate_and_print_keys() ? 0:1;
}
else
{
std::cerr << "Not enough arguments." << ENDL;
std::cerr << desc_all << ENDL;
}
return 1;
}
| [
"[email protected]"
] | |
21d0992aa4be8f8831ce1081655b41bd05d5d9ae | 297497957c531d81ba286bc91253fbbb78b4d8be | /third_party/libwebrtc/modules/audio_coding/audio_network_adaptor/bitrate_controller_unittest.cc | acfea33853ad05be2aec2e0c769497f40faa4223 | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | permissive | marco-c/gecko-dev-comments-removed | 7a9dd34045b07e6b22f0c636c0a836b9e639f9d3 | 61942784fb157763e65608e5a29b3729b0aa66fa | refs/heads/master | 2023-08-09T18:55:25.895853 | 2023-08-01T00:40:39 | 2023-08-01T00:40:39 | 211,297,481 | 0 | 0 | NOASSERTION | 2019-09-29T01:27:49 | 2019-09-27T10:44:24 | C++ | UTF-8 | C++ | false | false | 8,948 | cc |
#include "modules/audio_coding/audio_network_adaptor/bitrate_controller.h"
#include "rtc_base/numerics/safe_conversions.h"
#include "test/field_trial.h"
#include "test/gtest.h"
namespace webrtc {
namespace audio_network_adaptor {
namespace {
void UpdateNetworkMetrics(
BitrateController* controller,
const absl::optional<int>& target_audio_bitrate_bps,
const absl::optional<size_t>& overhead_bytes_per_packet) {
if (target_audio_bitrate_bps) {
Controller::NetworkMetrics network_metrics;
network_metrics.target_audio_bitrate_bps = target_audio_bitrate_bps;
controller->UpdateNetworkMetrics(network_metrics);
}
if (overhead_bytes_per_packet) {
Controller::NetworkMetrics network_metrics;
network_metrics.overhead_bytes_per_packet = overhead_bytes_per_packet;
controller->UpdateNetworkMetrics(network_metrics);
}
}
void CheckDecision(BitrateController* controller,
const absl::optional<int>& frame_length_ms,
int expected_bitrate_bps) {
AudioEncoderRuntimeConfig config;
config.frame_length_ms = frame_length_ms;
controller->MakeDecision(&config);
EXPECT_EQ(expected_bitrate_bps, config.bitrate_bps);
}
}
TEST(AnaBitrateControllerTest, OutputInitValueWhenTargetBitrateUnknown) {
constexpr int kInitialBitrateBps = 32000;
constexpr int kInitialFrameLengthMs = 20;
constexpr size_t kOverheadBytesPerPacket = 64;
BitrateController controller(BitrateController::Config(
kInitialBitrateBps, kInitialFrameLengthMs, 0, 0));
UpdateNetworkMetrics(&controller, absl::nullopt, kOverheadBytesPerPacket);
CheckDecision(&controller, kInitialFrameLengthMs * 2, kInitialBitrateBps);
}
TEST(AnaBitrateControllerTest, OutputInitValueWhenOverheadUnknown) {
constexpr int kInitialBitrateBps = 32000;
constexpr int kInitialFrameLengthMs = 20;
constexpr int kTargetBitrateBps = 48000;
BitrateController controller(BitrateController::Config(
kInitialBitrateBps, kInitialFrameLengthMs, 0, 0));
UpdateNetworkMetrics(&controller, kTargetBitrateBps, absl::nullopt);
CheckDecision(&controller, kInitialFrameLengthMs * 2, kInitialBitrateBps);
}
TEST(AnaBitrateControllerTest, ChangeBitrateOnTargetBitrateChanged) {
constexpr int kInitialFrameLengthMs = 20;
BitrateController controller(
BitrateController::Config(32000, kInitialFrameLengthMs, 0, 0));
constexpr int kTargetBitrateBps = 48000;
constexpr size_t kOverheadBytesPerPacket = 64;
constexpr int kBitrateBps = kTargetBitrateBps - kOverheadBytesPerPacket * 8 *
1000 /
kInitialFrameLengthMs;
UpdateNetworkMetrics(&controller, kTargetBitrateBps, kOverheadBytesPerPacket);
CheckDecision(&controller, kInitialFrameLengthMs, kBitrateBps);
}
TEST(AnaBitrateControllerTest, UpdateMultipleNetworkMetricsAtOnce) {
constexpr int kInitialFrameLengthMs = 20;
BitrateController controller(
BitrateController::Config(32000, kInitialFrameLengthMs, 0, 0));
constexpr int kTargetBitrateBps = 48000;
constexpr size_t kOverheadBytesPerPacket = 64;
constexpr int kBitrateBps = kTargetBitrateBps - kOverheadBytesPerPacket * 8 *
1000 /
kInitialFrameLengthMs;
Controller::NetworkMetrics network_metrics;
network_metrics.target_audio_bitrate_bps = kTargetBitrateBps;
network_metrics.overhead_bytes_per_packet = kOverheadBytesPerPacket;
controller.UpdateNetworkMetrics(network_metrics);
CheckDecision(&controller, kInitialFrameLengthMs, kBitrateBps);
}
TEST(AnaBitrateControllerTest, TreatUnknownFrameLengthAsFrameLengthUnchanged) {
constexpr int kInitialFrameLengthMs = 20;
BitrateController controller(
BitrateController::Config(32000, kInitialFrameLengthMs, 0, 0));
constexpr int kTargetBitrateBps = 48000;
constexpr size_t kOverheadBytesPerPacket = 64;
constexpr int kBitrateBps = kTargetBitrateBps - kOverheadBytesPerPacket * 8 *
1000 /
kInitialFrameLengthMs;
UpdateNetworkMetrics(&controller, kTargetBitrateBps, kOverheadBytesPerPacket);
CheckDecision(&controller, absl::nullopt, kBitrateBps);
}
TEST(AnaBitrateControllerTest, IncreaseBitrateOnFrameLengthIncreased) {
constexpr int kInitialFrameLengthMs = 20;
BitrateController controller(
BitrateController::Config(32000, kInitialFrameLengthMs, 0, 0));
constexpr int kTargetBitrateBps = 48000;
constexpr size_t kOverheadBytesPerPacket = 64;
constexpr int kBitrateBps = kTargetBitrateBps - kOverheadBytesPerPacket * 8 *
1000 /
kInitialFrameLengthMs;
UpdateNetworkMetrics(&controller, kTargetBitrateBps, kOverheadBytesPerPacket);
CheckDecision(&controller, absl::nullopt, kBitrateBps);
constexpr int kFrameLengthMs = 60;
constexpr size_t kPacketOverheadRateDiff =
kOverheadBytesPerPacket * 8 * 1000 / 20 -
kOverheadBytesPerPacket * 8 * 1000 / 60;
UpdateNetworkMetrics(&controller, kTargetBitrateBps, kOverheadBytesPerPacket);
CheckDecision(&controller, kFrameLengthMs,
kBitrateBps + kPacketOverheadRateDiff);
}
TEST(AnaBitrateControllerTest, DecreaseBitrateOnFrameLengthDecreased) {
constexpr int kInitialFrameLengthMs = 60;
BitrateController controller(
BitrateController::Config(32000, kInitialFrameLengthMs, 0, 0));
constexpr int kTargetBitrateBps = 48000;
constexpr size_t kOverheadBytesPerPacket = 64;
constexpr int kBitrateBps = kTargetBitrateBps - kOverheadBytesPerPacket * 8 *
1000 /
kInitialFrameLengthMs;
UpdateNetworkMetrics(&controller, kTargetBitrateBps, kOverheadBytesPerPacket);
CheckDecision(&controller, absl::nullopt, kBitrateBps);
constexpr int kFrameLengthMs = 20;
constexpr size_t kPacketOverheadRateDiff =
kOverheadBytesPerPacket * 8 * 1000 / 20 -
kOverheadBytesPerPacket * 8 * 1000 / 60;
UpdateNetworkMetrics(&controller, kTargetBitrateBps, kOverheadBytesPerPacket);
CheckDecision(&controller, kFrameLengthMs,
kBitrateBps - kPacketOverheadRateDiff);
}
TEST(AnaBitrateControllerTest, BitrateNeverBecomesNegative) {
BitrateController controller(BitrateController::Config(32000, 20, 0, 0));
constexpr size_t kOverheadBytesPerPacket = 64;
constexpr int kFrameLengthMs = 60;
constexpr int kTargetBitrateBps =
kOverheadBytesPerPacket * 8 * 1000 / kFrameLengthMs - 1;
UpdateNetworkMetrics(&controller, kTargetBitrateBps, kOverheadBytesPerPacket);
CheckDecision(&controller, kFrameLengthMs, 0);
}
TEST(AnaBitrateControllerTest, CheckBehaviorOnChangingCondition) {
BitrateController controller(BitrateController::Config(32000, 20, 0, 0));
int overall_bitrate = 34567;
size_t overhead_bytes_per_packet = 64;
int frame_length_ms = 20;
int current_bitrate = rtc::checked_cast<int>(
overall_bitrate - overhead_bytes_per_packet * 8 * 1000 / frame_length_ms);
UpdateNetworkMetrics(&controller, overall_bitrate, overhead_bytes_per_packet);
CheckDecision(&controller, frame_length_ms, current_bitrate);
overall_bitrate += 100;
current_bitrate += 100;
UpdateNetworkMetrics(&controller, overall_bitrate, overhead_bytes_per_packet);
CheckDecision(&controller, frame_length_ms, current_bitrate);
frame_length_ms = 60;
current_bitrate +=
rtc::checked_cast<int>(overhead_bytes_per_packet * 8 * 1000 / 20 -
overhead_bytes_per_packet * 8 * 1000 / 60);
UpdateNetworkMetrics(&controller, overall_bitrate, overhead_bytes_per_packet);
CheckDecision(&controller, frame_length_ms, current_bitrate);
overhead_bytes_per_packet -= 30;
current_bitrate += 30 * 8 * 1000 / frame_length_ms;
UpdateNetworkMetrics(&controller, overall_bitrate, overhead_bytes_per_packet);
CheckDecision(&controller, frame_length_ms, current_bitrate);
frame_length_ms = 20;
current_bitrate -=
rtc::checked_cast<int>(overhead_bytes_per_packet * 8 * 1000 / 20 -
overhead_bytes_per_packet * 8 * 1000 / 60);
UpdateNetworkMetrics(&controller, overall_bitrate, overhead_bytes_per_packet);
CheckDecision(&controller, frame_length_ms, current_bitrate);
overall_bitrate -= 100;
current_bitrate -= 100;
frame_length_ms = 60;
current_bitrate +=
rtc::checked_cast<int>(overhead_bytes_per_packet * 8 * 1000 / 20 -
overhead_bytes_per_packet * 8 * 1000 / 60);
UpdateNetworkMetrics(&controller, overall_bitrate, overhead_bytes_per_packet);
CheckDecision(&controller, frame_length_ms, current_bitrate);
}
}
}
| [
"[email protected]"
] | |
dce3b5ac6f04784e3c5353ea82a07ba57b781c4e | fda65b337a8a69a18937a5091bfa8eb49c0c9574 | /Mathematics/src/vectors/Vector3.h | 85a1d8daf616f62e6e18b77943a307603dfd1b46 | [] | no_license | DevJhin/simple-opengl-engine | f149f1fc114d55c0fd1e8d577bdd1d331dd8b175 | d20b6bc63a9529637f34dcf508a52f10cde5fd9e | refs/heads/main | 2023-01-08T14:19:22.886904 | 2020-11-02T08:15:51 | 2020-11-02T08:15:51 | 309,298,603 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,598 | h | #pragma once
#include <string>
#include <glm/gtx/norm.hpp>
#include <glm/vec3.hpp>
using Vector3Int = glm::uvec3;
using Vector3 = glm::vec3;
inline glm::vec3 bt2glm(const Vector3& vec)
{
return { vec.x, vec.y, vec.z };
}
namespace Vec3Math
{
const static Vector3 ZERO = Vector3(0, 0, 0);
const static Vector3 ONE = Vector3(1, 1, 1);
const static Vector3 FORWARD = Vector3(0, 0, -1);
const static Vector3 UP = Vector3(0, 1, 0);
const static Vector3 RIGHT = Vector3(1, 0, 0);
inline Vector3 normalize(const Vector3& value)
{
return glm::normalize(value);
}
inline float magnitude(const Vector3& value)
{
return glm::length(value);
}
inline float Distance(const Vector3& a, const Vector3& b)
{
return glm::distance(a, b);
}
inline float dot(const Vector3& a, const Vector3& b)
{
return glm::dot(a,b);
}
inline Vector3 cross(const Vector3& a, const Vector3& b)
{
return glm::cross(a, b);
}
inline std::string print(const Vector3& v)
{
std::string str;
str += std::to_string(v.x) + "_" + std::to_string(v.y) + "_" + std::to_string(v.z);
return str;
}
inline List<Vector3> ToList(float* arr, int size)
{
List<Vector3> list;
int vSize = size/3;
for(int i=0;i<vSize;i++)
{
int offset = i*3;
list.emplace_back(arr[offset], arr[offset+1], arr[offset+2]);
}
return list;
}
inline List<Vector3Int> ToList(int* arr, int size)
{
List<Vector3Int> list;
int vSize = size / 3;
for (int i = 0; i < vSize; i++)
{
int offset = i * 3;
list.emplace_back(arr[offset], arr[offset + 1], arr[offset + 2]);
}
return list;
}
}
| [
"[email protected]"
] | |
e849efc917aa4d37d061e0ff49c3ac571fc0d6d3 | e9ba8f7dc983a829e5face67a9602da43386a9af | /cpp/milestones/milestones.cpp | 5fc626ebfe41add185bebdf67218876d1d020b06 | [] | no_license | plilja/puzzlesg | 039effe7621673b2ecf60800f5c30624ee46e979 | 00ae63dff4538d49d36a6f2e12271f5fff7088a7 | refs/heads/master | 2021-04-15T09:03:56.647355 | 2018-11-15T18:15:53 | 2018-11-15T18:16:19 | 38,123,525 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 920 | cpp | #include <iostream>
#include <vector>
#include <set>
using namespace std;
typedef long long ll;
double EPS = 1e-9;
int main()
{
int m, n;
scanf("%d %d", &m, &n);
vector<ll> ts(m);
for (int i = 0; i < m; ++i) {
scanf("%lld", &ts[i]);
}
vector<ll> xs;
for (int i = 0; i < n; ++i) {
ll x;
scanf("%lld", &x);
xs.push_back(x);
}
set<ll> ans;
for (int i = 0; i < n - m + 1; ++i) {
double d = xs[i + 1] - xs[i];
double v = d/(ts[1] - ts[0]);
bool valid = true;
for (int j = i + 1; j < i + m && valid; ++j) {
ll dt = ts[j - i] - ts[0];
ll exp = xs[i] + dt * v + EPS;
valid = valid && exp == xs[j];
}
if (valid) {
ans.insert(d);
}
}
printf("%lu\n", ans.size());
for (auto d : ans) {
printf("%lld ", d);
}
printf("\n");
}
| [
"[email protected]"
] | |
2e42584f648a9fb0fa680f04d4bebf6b19b386b0 | 8a45863f5bc04ba397d046aa9e67e4a29e26cdd5 | /CarND-Extended-Kalman-Filter-Project/src/FusionEKF.h | 129201c233b061835135238b4ca032de5858c4b8 | [
"MIT"
] | permissive | avilash/Udacity-Self-Driving-Car-NanoDegree | 04a66ad984c6d0c43422177c4c6a9ef5b2037c00 | 99ab752a6de277aee22305975ccbd4ffb8f77815 | refs/heads/master | 2020-05-03T14:32:16.231394 | 2019-05-16T06:53:44 | 2019-05-16T06:53:44 | 178,680,291 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,012 | h | #ifndef FusionEKF_H_
#define FusionEKF_H_
#include <fstream>
#include <string>
#include <vector>
#include "Eigen/Dense"
#include "kalman_filter.h"
#include "measurement_package.h"
#include "tools.h"
class FusionEKF {
public:
/**
* Constructor.
*/
FusionEKF();
/**
* Destructor.
*/
virtual ~FusionEKF();
/**
* Run the whole flow of the Kalman Filter from here.
*/
void ProcessMeasurement(const MeasurementPackage &measurement_pack);
/**
* Kalman Filter update and prediction math lives in here.
*/
KalmanFilter ekf_;
private:
// check whether the tracking toolbox was initialized or not (first measurement)
bool is_initialized_;
// previous timestamp
long long previous_timestamp_;
// tool object used to compute Jacobian and RMSE
Tools tools;
Eigen::MatrixXd R_laser_;
Eigen::MatrixXd R_radar_;
Eigen::MatrixXd H_laser_;
Eigen::MatrixXd Hj_;
//acceleration noise components
double noise_ax;
double noise_ay;
};
#endif // FusionEKF_H_
| [
"[email protected]"
] | |
267eab35391f85daf12ac179ad6bbedcd02126d2 | 0de1dc0f0daea44f6f14b9629e4bb8052524bc9b | /src/tracking/include/tracking/Mapping.h | ded057b385e7ab075772e295d4411ce91199c8a3 | [] | no_license | edex99/direct_SLAM | c6578b39f321e749412481dba1b8f43591337904 | e7a05765702d3ca6a186180877370d3c105f1205 | refs/heads/master | 2020-03-10T08:53:51.303127 | 2018-04-12T18:48:47 | 2018-04-12T18:48:47 | 129,296,860 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 175 | h | #ifndef INCLUDES_MAPPING_H_
#define INCLUDES_MAPPING_H_
//#include "opencv2/opencv.hpp"
class Mapping {
public:
Mapping();
private:
};
#endif /* INCLUDES_MAPPING_ */ | [
"[email protected]"
] | |
e8c1f299ed23dc5b37e71a898e7f89c8bf3c0115 | d4812b46897795f6ca7424c0c26cf54b1b34ee86 | /Arduino/arduino based basic multimeter/arduino codes/DMM/New folder/DMM_/DMM_.ino | 206f24085bce6dabc1ae1beafe43dc8fc259d119 | [] | no_license | eheperson/embed | 2fcb7aa5d9e31403c8678f2d03fc21e3059a56aa | caeb56cf323524e0f01caa2b7e8fd253e0c59550 | refs/heads/master | 2023-03-31T20:11:36.600221 | 2021-04-08T12:50:08 | 2021-04-08T12:50:08 | 338,941,972 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,114 | ino | /*
Test LCD + MODE Select button
*/
#include <LiquidCrystal.h>
#include <math.h>
#include <SPI.h>
int button_pin = 2;
int back_light = 10;
int v100 = 9;
int v30 = 8;
int v10 = 7;
int curr_mode = 13;
int MODE = 0;
int brightness = 0;
int fadeAmount = 5;
int curr_value = 0;
int acc_value = 0;
float disp_res;
float supply = 4.91;
float coeff_v100 = 1.01;
float coeff_v30 = 1.011;
float coeff_v10 = 1.018;
float coeff_A_gain = 0.992174;
float coeff_A_res = 0.98315;
float opamp_offset = 0.000767;
volatile unsigned long last_millis = 0;
LiquidCrystal lcd(12, 11, 6, 5, 4, 3);
void setup() {
pinMode(button_pin, INPUT);
pinMode(back_light, OUTPUT);
pinMode(v100, OUTPUT);
pinMode(v30, OUTPUT);
pinMode(v10, OUTPUT);
pinMode(curr_mode, OUTPUT);
attachInterrupt(0, button_pressed, RISING);
analogWrite(back_light, brightness);
digitalWrite(v100, LOW);
digitalWrite(v30, LOW);
digitalWrite(v10, LOW);
digitalWrite(curr_mode, LOW);
lcd.begin(16, 2);
lcd.print("DIGITAL MULTIMER *** DIGITAL MULTIMER");
lcd.setCursor(0, 1);
lcd.print("Press \"MODE\" key to select a function");
Serial.begin(9600);
Serial.println("*******************************************************");
Serial.println("* DIGITAL MULTIMETER *");
Serial.println("* Press the \"MODE\" key to select a function *");
Serial.println("*******************************************************");
delay (1000);
delay (1000);
delay (1000);
delay (1000);
delay (1000);
}
void loop() {
digitalWrite(v100, LOW);
digitalWrite(v30, LOW);
digitalWrite(v10, LOW);
digitalWrite(curr_mode, LOW);
brightness = 0;
analogWrite(back_light, brightness);
delay(20);
if (MODE>0) {
lcd.clear();
lcd.print("MODE");
lcd.setCursor(0, 1);
switch (MODE) {
case 1:
V_100(); // Voltmeter mode with range 0-100V
break;
case 2:
V_30(); // Voltmeter mode with range 0-30V
break;
case 3:
V_10(); // Voltmeter mode with range 0-10V
break;
case 4:
A_500(); // Amperemeter mode with range 0-500mA
break;
case 5:
R_250(); // Ohmmeter mode with range 0-250KOhm
break;
case 6:
R_1000(); // Ohmmeter mode with range 0-1000R
break;
case 7:
D_LED_CONN(); //Check Vforward of diodes, LEDs and connectivity with 10uA
break;
case 8:
LED_FUNC(); // LED function check
break;
case 9:
BETA(); // NPN BETA meter - max 1000
break;
}
}
else {
for (int positionCounter = 0; positionCounter < 21; positionCounter++) {
lcd.scrollDisplayLeft();
delay(150);
}
delay (1000);
delay (1000);
for (int positionCounter = 0; positionCounter < 21; positionCounter++) {
lcd.scrollDisplayRight();
delay(150);
}
delay (1000);
delay (1000);
}
}
void button_pressed() {
long current_Time = millis();
if ((current_Time - last_millis) > 150) {
last_millis = current_Time;
if (MODE == 9) {
MODE = 1;
}
else {
MODE = MODE++;
}
}
}
void V_100() {
digitalWrite(v100, HIGH);
lcd.clear();
lcd.print("V-meter V=<100V");
Serial.println("* Voltmeter mode - Range 0 - 100 V *");
lcd.setCursor(0, 1);
voltage_meas();
}
void V_30() {
digitalWrite(v30, HIGH);
lcd.clear();
lcd.print("V-meter V=< 30V");
Serial.println("* Voltmeter mode - Range 0 - 30 V *");
lcd.setCursor(0, 1);
voltage_meas();
}
void V_10() {
digitalWrite(v10, HIGH);
lcd.clear();
lcd.print("V-meter V=< 10V");
Serial.println("* Voltmeter mode - Range 0 - 10 V *");
lcd.setCursor(0, 1);
voltage_meas();
}
void A_500() {
lcd.clear();
lcd.print("A-meter I=<500mA");
Serial.println("* Amperemeter mode - Range 0 - 500mA *");
lcd.setCursor(0, 1);
acc_value = 0;
for (int i=0; i <= 15; i++){
curr_value = analogRead(A1);
acc_value = acc_value + curr_value;
}
curr_value = int(acc_value/16);
if (curr_value == 1023) {
meas_overflow(); }
else {
disp_res = (((curr_value*supply )/1024 - 10*opamp_offset)/coeff_A_gain)/coeff_A_res*100;
lcd.print(" I = ");
lcd.print(disp_res, 1);
lcd.print(" mA");
Serial.print("* I = ");
Serial.print(disp_res, 1);
Serial.println(" mA");
delay(250);
}
}
void R_250() {
lcd.clear();
lcd.print("Ohmmeter R=<250K");
Serial.println("* Ohmmeter mode - Range 0 - 250 KOhm *");
lcd.setCursor(0, 1);
acc_value = 0;
for (int i=0; i <= 15; i++){
curr_value = analogRead(A2);
acc_value = acc_value + curr_value;
}
curr_value = int(acc_value/16);
if (curr_value >= 512) {
meas_overflow(); }
else {
disp_res = ( curr_value*supply )/1024*100;
lcd.print(" R = ");
lcd.print(disp_res, 1);
lcd.print(" KOhm");
Serial.print("* R = ");
Serial.print(disp_res, 1);
Serial.println(" KOhm");
delay(250);
}
}
void R_1000() {
digitalWrite(curr_mode, HIGH);
delay(20);
lcd.clear();
lcd.print("Ohmmeter R=<1000");
Serial.println("* Ohmmeter mode - Range 0 - 1000 Ohm *");
lcd.setCursor(0, 1);
acc_value = 0;
for (int i=0; i <= 15; i++){
curr_value = analogRead(A2);
acc_value = acc_value + curr_value;
}
curr_value = int(acc_value/16);
if (curr_value >= 512) {
meas_overflow(); }
else {
disp_res = ( curr_value*supply )/1024*400;
lcd.print(" R = ");
lcd.print(disp_res, 1);
lcd.print(" Ohm");
Serial.print("* R = ");
Serial.print(disp_res, 1);
Serial.println(" Ohm");
delay(250);
}
}
void D_LED_CONN() {
lcd.clear();
lcd.print("Vf:Dio/LED; CONN");
Serial.println("* Vforward of diode/LED ; Connectivity check - 10uA *");
lcd.setCursor(0, 1);
acc_value = 0;
for (int i=0; i <= 15; i++){
curr_value = analogRead(A2);
acc_value = acc_value + curr_value;
}
curr_value = int(acc_value/16);
if (curr_value >= 560) {
meas_overflow(); }
else if (curr_value <= 1) {
zero_res(); }
else {
disp_res = ( curr_value*supply )/1024*1000;
lcd.print(" V = ");
lcd.print(disp_res,0);
lcd.print(" mV");
delay(250);
Serial.print("* V = ");
Serial.print(disp_res, 0);
Serial.println(" mV");
}
}
void LED_FUNC() {
digitalWrite(curr_mode, HIGH);
lcd.clear();
lcd.print("LED function chk");
Serial.println("* LED functionality check *");
lcd.setCursor(0, 1);
acc_value = 0;
for (int i=0; i <= 15; i++){
curr_value = analogRead(A2);
acc_value = acc_value + curr_value;
}
curr_value = int(acc_value/16);
if (curr_value >= 560) {
LED_tst(); }
else if (curr_value <= 1) {
zero_res(); }
else {
disp_res = ( curr_value*supply )/1024*1000;
lcd.print(" V = ");
lcd.print(disp_res,0);
lcd.print(" mV");
Serial.print("* V = ");
Serial.print(disp_res, 0);
Serial.println(" mV");
delay(250);
}
}
void BETA() {
lcd.clear();
lcd.print("NPN BETA meter");
Serial.println("* NPN BJT BETA measurement *");
lcd.setCursor(0, 1);
acc_value = 0;
for (int i=0; i <= 15; i++){
curr_value = analogRead(A3);
acc_value = acc_value + curr_value;
}
curr_value = int(acc_value/16);
curr_value = 1023 - curr_value;
disp_res = ( curr_value*supply )/1024*333.33;
if (disp_res >=10){
lcd.print(" BETA = ");
lcd.print(disp_res,0);
Serial.print("* Beta = ");
Serial.print(disp_res, 0); }
else {
LED_tst(); }
delay(250);
}
void meas_overflow() {
lcd.setCursor(0, 1);
lcd.print(" OVERFLOW!!! ");
Serial.println("* OVERFLOW!!! *");
lcd.setCursor(0, 1);
for (int i=0; i <= 101; i++){
analogWrite(back_light, brightness);
brightness = brightness + fadeAmount;
if (brightness == 255) {
fadeAmount = -fadeAmount ;
}
delay(15);
}
}
void zero_res() {
lcd.setCursor(0, 1);
lcd.print("Zero resistance!");
Serial.println("* Short circuit - zero resistance *");
delay(250);
brightness = 255;
analogWrite(back_light, brightness);
delay(250);
brightness = 0;
analogWrite(back_light, brightness);
}
void voltage_meas() {
acc_value = 0;
for (int i=0; i <= 15; i++){
curr_value = analogRead(A0);
acc_value = acc_value + curr_value;
}
curr_value = int(acc_value/16);
if (curr_value == 1023) {
meas_overflow(); }
else {
switch (MODE) {
case 1:
disp_res = ( curr_value*supply*20)/1024*coeff_v100 ;
break;
case 2:
disp_res = ( curr_value*supply*6)/1024*coeff_v30;
break;
case 3:
disp_res = ( curr_value*supply*2)/1024*coeff_v10;
break; }
lcd.print(" V = ");
lcd.print(disp_res, 2);
lcd.print(" V");
Serial.print("* V = ");
Serial.print(disp_res, 2);
Serial.println(" V");
delay(250);
}
}
void LED_tst() {
lcd.setCursor(0, 1);
if (MODE == 8) {
lcd.print(" Swap the pins ");
Serial.println("* Try to swap the LED pins. White LED could not glow *"); }
else {
lcd.print("Check the NPN tr");
Serial.println("* Check if the BJT is NPN. Check the pin order *"); }
delay (500);
lcd.noDisplay();
delay (200);
lcd.display();
}
| [
"[email protected]"
] | |
07d6957db96d0e45940df341915eade761590744 | 5652779bc1b01b56939ee484a90ea33caeca3774 | /Lab 4/Lab 4/Tuple.cpp | 7b4a58278cdb8c74badd93af134dbf6d91991ea3 | [] | no_license | raull/CS236 | 3764cf731a696240a433d13fbfc47f9f5fb2764b | 9a5ed1ea3c858ab80f11faa6a703e27bc399d059 | refs/heads/master | 2021-01-21T00:47:22.697270 | 2014-04-08T20:25:37 | 2014-04-08T20:25:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 729 | cpp | /*
* Tuple.cpp
*
* Created on: Mar 15, 2014
* Author: raull
*/
#include "Tuple.h"
#include <sstream>
Tuple::Tuple() {
// TODO Auto-generated constructor stub
}
Tuple::Tuple(vector<Token> list){
elements = list;
}
Tuple::~Tuple() {
// TODO Auto-generated destructor stub
}
Token Tuple::getElementAtIndex(int index){
return elements[index];
}
string Tuple::toString() const{
stringstream result;
result << "(";
for(int i=0; i<elements.size(); i++){
if(i != elements.size() - 1)
result << elements[i].getTokensValue() << ", ";
else
result << elements[i].getTokensValue() << ")";
}
return result.str();
}
bool Tuple::operator<(const Tuple& tuple) const{
return elements < tuple.elements;
}
| [
"[email protected]"
] | |
aa16aad7660af005d976a7424e1e7bc9bd4e3981 | 0e79b11e100c78e1d0b7159cb6ae369a2942d6d0 | /gsyslib/g_matrix3x4.h | d8cb228acfcba742452c6f2acd927bae88a53fcf | [] | no_license | JlblC/dcmap | e3be11c4c9da9ac4f0be693fee3b4fb2cf8af6ec | e2cbfa43dfe04125d19b4bae34e9a552db307198 | refs/heads/master | 2021-07-04T01:47:45.249683 | 2014-06-08T17:46:32 | 2014-06-08T17:46:32 | 20,622,342 | 3 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 9,142 | h | #pragma once
#ifndef G_MATRIX3X4_H
#define G_MATRIX3X4_H
#include "g_gsys.h"
#include "g_alg.h"
#include "g_vector3.h"
#include "g_vector4.h"
#include "g_quaternion.h"
#include "g_text.h"
#include "g_base_matrix.h"
#include "g_matrix3.h"
#include "g_matrix4x3.h"
#include "g_matrix_operations.h"
namespace gsys
{
struct matrix3x4
{
enum layout
{
l_11, l_12, l_13,
l_21, l_22, l_23,
l_31, l_32, l_33,
l_41, l_42, l_43,
l_width=3,
l_height=4,
l_transpozed=0,
};
/*====================================================================================*\
types
\*====================================================================================*/
typedef gsys_real value_type;
typedef uint size_type;
GSYSDETAIL_TYPEDEF_VALUE_POINTERS
/*====================================================================================*\
Data access
\*====================================================================================*/
union
{
struct
{
value_type _11, _12, _13;
value_type _21, _22, _23;
value_type _31, _32, _33;
value_type _41, _42, _43;
};
value_type m[3][4];
value_type values[3*4];
};
size_type size()const{return 3*4;}
reference operator()(size_type x,size_type y){return m[x][y];}
reference operator[](size_type x){GSYS_ASSERT(x<size());return values[x];}
const_reference operator()(size_type x,size_type y)const{return m[x][y];}
const_reference operator[](size_type x)const{GSYS_ASSERT(x<size());return values[x];}
/*====================================================================================*\
Data Access
\*====================================================================================*/
matrix3& as_matrix3t(){return *(matrix3*)values;}
matrix3 const& as_matrix3t()const{return *(matrix3 const*)values;}
vector3& as_transpose(){return *(vector3*)&_41;}
vector3 const& as_transpose()const{return *(vector3 const*)&_41;}
/*====================================================================================*\
Initialisations
\*====================================================================================*/
matrix3x4& init(value_type f11, value_type f12, value_type f13,
value_type f21, value_type f22, value_type f23,
value_type f31, value_type f32, value_type f33,
value_type f41, value_type f42, value_type f43)
{
_11 = f11; _12 = f12; _13 = f13;
_21 = f21; _22 = f22; _23 = f23;
_31 = f31; _32 = f32; _33 = f33;
_41 = f41; _42 = f42; _43 = f43;
return *this;
}
matrix3x4& identity()
{
_11 = 1; _12 = 0; _13 = 0;
_21 = 0; _22 = 1; _23 = 0;
_31 = 0; _32 = 0; _33 = 1;
_41 = 0; _42 = 0; _43 = 0;
return *this;
}
matrix3x4& translation(value_type x,value_type y,value_type z)
{
_11 = 1; _12 = 0; _13 = 0;
_21 = 0; _22 = 1; _23 = 0;
_31 = 0; _32 = 0; _33 = 1;
_41 = x; _42 = y; _43 = z;
return *this;
}
matrix3x4& rotation(quaternion const& quat)
{
return mat34_rotation(*this,quat);
}
matrix3x4& rot_trans(quaternion const& quat,vector3 const& vt)
{
return mat34_rot_trans(*this,quat,vt);
}
matrix3x4& scale_rot_trans(vector3 const& scale,quaternion const& quat,vector3 const& vt)
{
return mat34_scale_rot_trans(*this,scale,quat,vt);
}
matrix3x4& scale_rot_trans(float scale,quaternion const& quat,vector3 const& vt)
{
return mat34_scale_rot_trans(*this,scale,quat,vt);
}
/*====================================================================================*\
Procuctions - builds objects from matrix
\*====================================================================================*/
matrix4x3& build_transpose(matrix4x3 & res)const
{
for(int i=0;i<3;i++)
for(int j=0;j<4;j++)
res.m[j][i] = m[i][j];
return res;
}
matrix3x4& build_muliplication(matrix3x4 const& mat,matrix3x4 & res)const
{
res._11 = _11*mat._11 + _12*mat._21 + _13*mat._31;
res._12 = _11*mat._12 + _12*mat._22 + _13*mat._32;
res._13 = _11*mat._13 + _12*mat._23 + _13*mat._33;
res._21 = _21*mat._11 + _22*mat._21 + _23*mat._31;
res._22 = _21*mat._12 + _22*mat._22 + _23*mat._32;
res._23 = _21*mat._13 + _22*mat._23 + _23*mat._33;
res._31 = _31*mat._11 + _32*mat._21 + _33*mat._31;
res._32 = _31*mat._12 + _32*mat._22 + _33*mat._32;
res._33 = _31*mat._13 + _32*mat._23 + _33*mat._33;
res._41 = _41*mat._11 + _42*mat._21 + _43*mat._31;
res._42 = _41*mat._12 + _42*mat._22 + _43*mat._32;
res._43 = _41*mat._13 + _42*mat._23 + _43*mat._33;
return res;
}
GSYSDETAIL_FRIEND_BINSTREAM_RAWDATA(matrix3x4)
};
GSYS_SET_TYPENAME(matrix3x4,"m34");
struct matrix3tx4
{
enum layout
{
l_11, l_21, l_31,
l_12, l_22, l_32,
l_13, l_23, l_33,
l_41, l_42, l_43,
l_width=3,
l_height=4,
l_transpozed=1,
};
/*====================================================================================*\
types
\*====================================================================================*/
typedef gsys_real value_type;
typedef uint size_type;
GSYSDETAIL_TYPEDEF_VALUE_POINTERS
/*====================================================================================*\
Data access
\*====================================================================================*/
union
{
struct
{
value_type _11, _12, _13;
value_type _21, _22, _23;
value_type _31, _32, _33;
value_type _41, _42, _43;
};
value_type m[3][4];
value_type values[3*4];
};
size_type size()const{return 3*4;}
reference operator()(size_type x,size_type y){return m[x][y];}
reference operator[](size_type x){GSYS_ASSERT(x<size());return values[x];}
const_reference operator()(size_type x,size_type y)const{return m[x][y];}
const_reference operator[](size_type x)const{GSYS_ASSERT(x<size());return values[x];}
/*====================================================================================*\
Data Access
\*====================================================================================*/
matrix3t& as_matrix3t(){return *(matrix3t*)values;}
matrix3t const& as_matrix3t()const{return *(matrix3t const*)values;}
vector3& as_transpose(){return *(vector3*)&_41;}
vector3 const& as_transpose()const{return *(vector3 const*)&_41;}
/*====================================================================================*\
Initialisations
\*====================================================================================*/
matrix3tx4& init(value_type f11, value_type f12, value_type f13,
value_type f21, value_type f22, value_type f23,
value_type f31, value_type f32, value_type f33,
value_type f41, value_type f42, value_type f43)
{
_11 = f11; _12 = f12; _13 = f13;
_21 = f21; _22 = f22; _23 = f23;
_31 = f31; _32 = f32; _33 = f33;
_41 = f41; _42 = f42; _43 = f43;
return *this;
}
matrix3tx4& identity()
{
_11 = 1; _12 = 0; _13 = 0;
_21 = 0; _22 = 1; _23 = 0;
_31 = 0; _32 = 0; _33 = 1;
_41 = 0; _42 = 0; _43 = 0;
return *this;
}
matrix3tx4& translation(value_type x,value_type y,value_type z)
{
_11 = 1; _12 = 0; _13 = 0;
_21 = 0; _22 = 1; _23 = 0;
_31 = 0; _32 = 0; _33 = 1;
_41 = x; _42 = y; _43 = z;
return *this;
}
matrix3tx4& rotation(quaternion const& quat)
{
return mat34_rotation(*this,quat);
}
matrix3tx4& rot_trans(quaternion const& quat,vector3 const& vt)
{
return mat34_rot_trans(*this,quat,vt);
}
matrix3tx4& scale_rot_trans(vector3 const& scale,quaternion const& quat,vector3 const& vt)
{
return mat34_scale_rot_trans(*this,scale,quat,vt);
}
matrix3tx4& scale_rot_trans(float scale,quaternion const& quat,vector3 const& vt)
{
return mat34_scale_rot_trans(*this,scale,quat,vt);
}
/*====================================================================================*\
Procuctions - builds objects from matrix
\*====================================================================================*/
matrix3x4& build_transpose(matrix3x4 & res)const
{
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
res.m[j][i] = m[i][j];
for(int j=0;j<3;j++)res.m[j][3] = m[j][3];
return res;
}
matrix3tx4& build_muliplication(matrix3tx4 const& mat,matrix3tx4 & res)const
{
res._11 = _11*mat._11 + _12*mat._21 + _13*mat._31;
res._12 = _11*mat._12 + _12*mat._22 + _13*mat._32;
res._13 = _11*mat._13 + _12*mat._23 + _13*mat._33;
res._21 = _21*mat._11 + _22*mat._21 + _23*mat._31;
res._22 = _21*mat._12 + _22*mat._22 + _23*mat._32;
res._23 = _21*mat._13 + _22*mat._23 + _23*mat._33;
res._31 = _31*mat._11 + _32*mat._21 + _33*mat._31;
res._32 = _31*mat._12 + _32*mat._22 + _33*mat._32;
res._33 = _31*mat._13 + _32*mat._23 + _33*mat._33;
res._41 = _41*mat._11 + _42*mat._21 + _43*mat._31;
res._42 = _41*mat._12 + _42*mat._22 + _43*mat._32;
res._43 = _41*mat._13 + _42*mat._23 + _43*mat._33;
return res;
}
GSYSDETAIL_FRIEND_BINSTREAM_RAWDATA(matrix3tx4)
};
GSYS_SET_TYPENAME(matrix3tx4,"m3t4");
}
#endif | [
"[email protected]"
] | |
0b97b5f5b6be2ea25c542905b61c22a05ad8173b | 89f9e9be88b477f9a4d511fe1e873d8163d1a066 | /Arduino/basic_analogue_read/basic_analogue_read.ino | c4166742b0134ce47ba45b602e70ab7583381fc2 | [] | no_license | KaufmanLabJILA/analysis_code | 292ac477042249eb4b75590f2851d555ffe27acc | 7b842434e477356614db63b59d9321a850ee7f2c | refs/heads/master | 2020-03-17T12:21:45.375604 | 2019-09-20T01:44:26 | 2019-09-20T01:44:26 | 133,585,070 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 574 | ino | byte rx_byte = 0;
void setup() {
// set ADC resolution to 12 bit (only on arduino due)
analogReadResolution(12);
// change voltage reference to 1.1V for more resolution on photodiodes
// which saturate at 600mV (not available on Due...)
// analogReference(EXTERNAL)
// initialize both serial ports:
Serial.begin(115200);
Serial.println("DAQ ready.");
}
void loop() {
if (Serial.available() > 0) {
rx_byte = Serial.read();
if (rx_byte = 1) {
Serial.println(micros());
Serial.println(analogRead(0));
}
rx_byte = 0;
}
}
| [
"[email protected]"
] | |
3535a445c4da6278d96a521d4d967154926ec659 | 8d75cad09837cb31ca31c7cfe136b14efe8f1b85 | /Codeforces/1281A.cpp | c741a8617448671895c44f17131df14938141bac | [
"MIT"
] | permissive | raad1masum/Competitive-Programming | 3d68e8bfd02526edd4f5dee582c2dfcc0765e57b | fbf37e61d219e84c4c3422d5efad2be2eb21820d | refs/heads/master | 2023-08-16T21:35:37.189131 | 2023-08-11T00:06:31 | 2023-08-11T00:06:31 | 251,714,264 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 440 | cpp | #include <bits/stdc++.h>
using namespace std;
int main()
{
int t;cin >> t;
string s;
while (t--)
{
cin >> s;
if (s[s.size()-1] == 'o')
{
cout << "FILIPINO" << endl;
}
else if (s[s.size()-1] == 'u')
{
cout << "JAPANESE" << endl;
}
else
{
cout << "KOREAN" << endl;
}
}
}
| [
"[email protected]"
] | |
220f8282e0c7b9b58849d5a95f10e394ea0d3baf | 8dc84558f0058d90dfc4955e905dab1b22d12c08 | /chrome/browser/media/router/presentation/browser_presentation_connection_proxy.h | 434cf0bcc9bc3b68497840c6bd8ca20cb4bd9640 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | meniossin/src | 42a95cc6c4a9c71d43d62bc4311224ca1fd61e03 | 44f73f7e76119e5ab415d4593ac66485e65d700a | refs/heads/master | 2022-12-16T20:17:03.747113 | 2020-09-03T10:43:12 | 2020-09-03T10:43:12 | 263,710,168 | 1 | 0 | BSD-3-Clause | 2020-05-13T18:20:09 | 2020-05-13T18:20:08 | null | UTF-8 | C++ | false | false | 3,644 | h | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_MEDIA_ROUTER_PRESENTATION_BROWSER_PRESENTATION_CONNECTION_PROXY_H_
#define CHROME_BROWSER_MEDIA_ROUTER_PRESENTATION_BROWSER_PRESENTATION_CONNECTION_PROXY_H_
#include <vector>
#include "chrome/browser/media/router/route_message_observer.h"
#include "chrome/common/media_router/media_route.h"
#include "content/public/browser/presentation_service_delegate.h"
#include "content/public/common/presentation_connection_message.h"
#include "mojo/public/cpp/bindings/binding.h"
namespace media_router {
class MediaRouter;
// This class represents a browser side PresentationConnection. It connects with
// PresentationConnection owned by a render frame to enable message exchange.
// Message received on this class is further routed to Media Router. State of
// browser side PresentationConnection is always 'connected'.
//
// |SetTargetConnection| sets |target_connection_| to mojo handle of
// PresentationConnection object owned a render frame, and transits state of
// |target_connection_| to 'connected'.
//
// Send message from render frame to media router:
// blink::PresentationConnection::send();
// -> (mojo call to browser side PresentationConnection)
// -> BrowserPresentationConnectionProxy::OnMessage();
// -> MediaRouter::SendRouteMessage();
//
// Instance of this class is only created for remotely rendered presentations.
// It is owned by PresentationFrame. When PresentationFrame gets destroyed or
// |route_| is closed or terminated, instance of this class will be destroyed.
class BrowserPresentationConnectionProxy
: public blink::mojom::PresentationConnection,
public RouteMessageObserver {
public:
using OnMessageCallback = base::OnceCallback<void(bool)>;
// |router|: media router instance not owned by this class;
// |route_id|: underlying media route. |target_connection_ptr_| sends message
// to media route with |route_id|;
// |receiver_connection_request|: mojo interface request to be bind with this
// object;
// |controller_connection_ptr|: mojo interface ptr of controlling frame's
// connection proxy object.
BrowserPresentationConnectionProxy(
MediaRouter* router,
const MediaRoute::Id& route_id,
blink::mojom::PresentationConnectionRequest receiver_connection_request,
blink::mojom::PresentationConnectionPtr controller_connection_ptr);
~BrowserPresentationConnectionProxy() override;
// blink::mojom::PresentationConnection implementation
void OnMessage(content::PresentationConnectionMessage message,
OnMessageCallback on_message_callback) override;
// Underlying media route is always connected. Media route class does not
// support state change.
void DidChangeState(
blink::mojom::PresentationConnectionState state) override {}
// Underlying media route is always connected. Media route class does not
// support state change.
void RequestClose() override {}
// RouteMessageObserver implementation.
void OnMessagesReceived(
const std::vector<content::PresentationConnectionMessage>& messages)
override;
private:
// |router_| not owned by this class.
MediaRouter* const router_;
const MediaRoute::Id route_id_;
mojo::Binding<blink::mojom::PresentationConnection> binding_;
blink::mojom::PresentationConnectionPtr target_connection_ptr_;
};
} // namespace media_router
#endif // CHROME_BROWSER_MEDIA_ROUTER_PRESENTATION_BROWSER_PRESENTATION_CONNECTION_PROXY_H_
| [
"[email protected]"
] | |
01b07c0ab79a9cb2bbe7c7f464638dba77818a5e | ddd2a67e8d54cc451b5941906146607b047fa6b6 | /VaccinneDistribution.cpp | 48ac1e7b4c8ffd49590fc2a5478e3012cbab01cc | [] | no_license | Kushagra-Kapoor25/DSA | cf1053d3bc5def66c78fe9c92dee41b7af9b01b3 | 314afafb6afa250e010b564a472a5a292e6824b3 | refs/heads/main | 2023-06-01T15:12:00.651700 | 2021-06-21T05:03:29 | 2021-06-21T05:03:29 | 371,939,850 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 722 | cpp | #include<bits/stdc++.h>
using namespace std;
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
int t;
cin >> t;
while (t--)
{
long n;
long d;
cin >> n >> d;
int a[n];
for (int i = 0; i < n; i++)
cin >> a[i];
long minDays = 0;
if (d == 1)
minDays = n;
else
{
int risky = 0;
for (auto x : a)
if (x <= 9 || x >= 80)
risky++;
int nonrisky = n - risky;
if (risky % d == 0)
minDays = minDays + risky / d;
else
minDays = minDays + risky / d + 1;
if (nonrisky % d == 0)
minDays = minDays + nonrisky / d;
else
minDays = minDays + nonrisky / d + 1;
}
cout << minDays << endl;
}
return 0;
} | [
"[email protected]"
] | |
cd9da34896ee9250ce48f8bb0779a676fd86f952 | 834e75748c0a4ff24155f9a680fa0603d5984e55 | /TCC8.0/lib/CommandsBttnR/CommandsBttnR.h | b0f892b500fbe5c5f8565773b1698d4f549ac99c | [] | no_license | iagolps/Undergraduate_Thesis | b07bb38878006a55b804c269c6666b2b37f8c558 | f401b5d2c8c4ac163fabd0336745f89261e2702f | refs/heads/master | 2020-07-07T21:10:40.515785 | 2019-08-21T20:18:42 | 2019-08-21T20:18:42 | 203,471,770 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,018 | h | #ifndef CommandsBttnR_h
#define CommandsBttnR_h
#include "Config.h"
class Right: public Data
{
public:
Right();
~Right();
void BttnR1();
void BttnR10();
void BttnR100();
void BttnR101();
void BttnR110();
void BttnR111();
void BttnR20();
void BttnR200();
void BttnR201();
void BttnR202();
void BttnR210();
void BttnR211();
void BttnR212();
void BttnR30();
void BttnR300();
void BttnR310();
void BttnR311();
void BttnR312();
void BttnR40();
void BttnR400();
void BttnR50();
void BttnR500();
void BttnR501();
void BttnR502();
void BttnR503();
void BttnR510();
void BttnR511();
void BttnR512();
void BttnR513();
void BttnR520();
void BttnR521();
void BttnR522();
void BttnR523();
void BttnR60();
};
// Right r;
#endif | [
"[email protected]"
] | |
ae44aced773f8b81506c6f83b8b279f42e75a002 | 4423987b3cb13ad3321479d11de9f0250575df75 | /Codeforces/Ascendants/ONE/Round600/cc.cpp | 793153a633347b450bf2fddeec028c8362ffd04c | [] | no_license | samplex63/Competitive-Programming | 5ebc3a933eed1a5921bea8e91b798c96225007bf | 546aecd109dbdedef5b9b2afaddb1fa5ff69bbde | refs/heads/master | 2022-12-04T16:51:57.648719 | 2020-08-24T13:37:47 | 2020-08-24T13:37:47 | 282,802,436 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 704 | cpp | #include <bits/stdc++.h>
using namespace std;
#define fi first
#define se second
#define sz(x) static_cast<int>((x).size())
typedef long long ll;
typedef long double ld;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
#ifdef LOCAL
freopen("in", "r", stdin);
#endif
int n, m;
cin >> n >> m;
vector<ll> vec(n), ok(n);
for(int i = 0; i < n; ++i) cin >> vec[i];
sort(vec.begin(), vec.end());
for(int i = 0; i < n; ++i) {
for(int j = i; j < i + m && j < n; ++j) {
ok[i] += vec[j];
}
}
for(auto x: ok) cerr << x << ' ';
for(int mm = 0; mm < m - 1; ++mm) {
for(int i = m; i < n; i += m) {
ok[i] += ok[i - m];
}
}
//~ for(auto x: ok) cerr << x << ' ';
return 0;
} | [
"[email protected]"
] | |
68615f691678f876fdc17b6e4ba0d18da3948499 | 9f0e62953b0125f7c69ef197d79724b652cf61d7 | /C++ProgrammingLanguage/ch3/abstract.cpp | 4ccb44339c9911c22aca26e2b23449d0487021c2 | [] | no_license | NewReStarter/Training | d3ece985cfc0dba7921d01e2b9766b09c5da37db | 2534c4010096b477bec72025a970f2504301d5ae | refs/heads/master | 2020-06-27T22:38:04.005695 | 2019-09-04T11:04:21 | 2019-09-04T11:04:21 | 97,077,237 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 407 | cpp | #include<vector>
class Shape{
public:
virtual Point center() const =0;
virtual void move(Point to) =0;
virtual void draw() const =0;
virtual void rotate(int angle) =0;
virtual ~Shape(){}
};
class Circle : public Shape{
public:
Circle(Point p, int rr):x{p},r{rr} {}
Point center() const
void move(Point to){ x = to;}
void draw() const;
void rotate(int i) {}
private:
Point x;
int r;
};
| [
"[email protected]"
] | |
3555cfeccba9c1b6c15dc97fbc74a390bdbebcfc | 3301396746390df707dec7e5922a8da691d6d382 | /Data_Processing_Project/src/genel.h | 1b4ca55b8a4a33433c87e1aaf29925b022dc9f7a | [] | no_license | yusufemrebudak/Data-Processing-Between-File-Types | f3ab9c1fd5d7d3d73a4cb528be9fe05fbfe74f8a | d837937cf81e0f18ef9b912a6222de4aa5d1dffe | refs/heads/main | 2023-05-08T06:44:29.813279 | 2021-05-22T14:20:42 | 2021-05-22T14:20:42 | 369,827,111 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 293 | h | /*
* genel.h
*
* Created on: 16 May 2020
* Author: yusuf
*/
#ifndef GENEL_H
#define GENEL_H
#include <cstring>
#include <string>
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <deque>
#include <list>
#include <cmath>
using namespace std;
#endif /* GENEL_H */
| [
"[email protected]"
] | |
163449628807ca33fb8da02dee8698b98910e01d | e6a416abdd593811ad7706b4b00b0a8727b8691b | /Remote/confirmbreachpopup.h | b239bbc85060235a183fea9562af07614d59d225 | [] | no_license | RonaldColyar/POI-RemoteDesktop | e4f8e7d0d48f134900fe5b259160005884927a02 | 3b1faf353e3149d651fd19f8a9ebd8b0dc65d453 | refs/heads/master | 2023-03-02T03:47:07.193870 | 2021-02-15T04:44:58 | 2021-02-15T04:44:58 | 328,091,911 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 402 | h | #ifndef CONFIRMBREACHPOPUP_H
#define CONFIRMBREACHPOPUP_H
#include <QDialog>
#include "main_functionality.h"
namespace Ui {
class ConfirmBreachPopup;
}
class ConfirmBreachPopup : public QDialog
{
Q_OBJECT
public:
explicit ConfirmBreachPopup(RequestManager RM,QWidget *parent = nullptr);
~ConfirmBreachPopup();
private:
Ui::ConfirmBreachPopup *ui;
};
#endif // CONFIRMBREACHPOPUP_H
| [
"[email protected]"
] | |
998dea819ed26c2ed3a52f20319eb78e3b89261d | 797d6efceac873bd9e9b5b63f5c17167e6c62384 | /src/Inverter.H | c1fe60f691013a66b0657e128fabf77a90c00190 | [] | no_license | smsolivier/euler_chebyshev | a01f074524e41c0de1728beeefb8f755b40722af | 66c67c3d570ff86f9c1c9ea7b0acfd288f2fa957 | refs/heads/master | 2020-03-16T17:24:16.240604 | 2018-05-10T05:42:21 | 2018-05-10T05:42:21 | 132,830,758 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,225 | h | #ifndef __INVERTER_H__
#define __INVERTER_H__
#include <vector>
#include "Common.H"
#include "DataObjects.H"
#include "PaperCutter.H"
using namespace std;
/// invert \f$ \nabla^2 f = \left( D^2 - \vec{k}^2 \right) \f$
class Inverter {
public:
/// singleton interface
/** allow only one static instance to exist to prevent redoing expensive factorizations **/
static Inverter& instance() {
static Inverter inv;
return inv;
}
/// destructor
~Inverter();
/// initialize inverses
/** BC=0: double neumann boundaries \\BC=1: double dirichlet \\BC=2: mixed **/
void init(array<int,DIM> N, int BC=0);
/// invert a scalar
void invert(Scalar& scalar, Vector& V);
/// invert a scalar
void invert(Scalar& scalar);
private:
/// default constructor
Inverter();
/// constructor
Inverter(array<int,DIM> N);
/// fourier frequencies
double freq(int ind, int d) const;
/// size in DIM dimensions
array<int,DIM> m_N;
/// second derivative matrix (in sparse Eigen format)
Eigen::SparseMatrix<cdouble> m_D2;
/// store all matrices
Eigen::SparseMatrix<cdouble>** m_theta;
/// pointers to PaperCutter's
PaperCutter** m_ppc;
/// store if init has been called
bool m_init;
};
#endif | [
"[email protected]"
] | |
f867bec3d501d77d104a0d7ca8c1907059a8c489 | 53c5ed79aa66a9ecb27ecc0e763b297e455d7a77 | /vq/codebook.h | da23530d3f35c3fa05472dac15fa08836236fe3c | [] | no_license | anax32/vq-hmm | 7c0bc3074b7cd6ece8bdedd031f9add6f13ece99 | 8232f15e1b3afa96b319b4424787805a3dd26888 | refs/heads/master | 2022-11-12T15:16:21.430456 | 2020-07-06T23:45:15 | 2020-07-06T23:45:15 | 277,672,179 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,526 | h | /*
* codebook lookup for a set of symbols to a set of values
*
* type parameters are:
* T : data type
* D : arity of value
*/
template<class T, unsigned char D>
class Codebook
{
private:
T *data;
const unsigned int size;
public:
Codebook (T* values, const unsigned int valueCount)
: size(valueCount)
{
data = new float[size*D];
for (unsigned int i=0; i<size*D; i++)
for (unsigned int j=0; j<D; j++)
data[i][j] = values[i][j];
}
~Codebook ()
{
delete[] data;
}
float getValueForSymbol (const unsigned char symbol) const
{
return data[symbol-firstSymbol];
}
unsigned char getSymbolForValue (const float f) const
{
for (unsigned int i=0; i<size; i++)
{
if (data[i] == f)
return symbols[i];
}
return NULL;
}
unsigned int getIndexForSymbol (unsigned char sym) const
{
for (unsigned int i=0; i<size; i++)
{
if (symbols[i] == sym)
return i;
}
return 0xFFFFFFFF;
}
unsigned int getIndexForValue (const float f) const
{
return getIndexForSymbol (getSymbolForValue (f));
}
float getData (const unsigned int index) const
{
return data[index];
}
unsigned char getSymbol (const unsigned int index) const
{
return symbols[index];
}
unsigned int getSize () const
{
return size;
}
const unsigned char* getSymbolSet () const
{
return symbols;
}
};
| [
"[email protected]"
] | |
79dbb0facdc5a5d12fb64d4d1c93fb3cd4452ac9 | 75ba0fa158ad5c33b91edf209f52a8b00ac43c33 | /algorithms/0210-Course-Schedule-II/210.cpp | b8a787edadd4168d9986aedb5037115d795757db | [] | no_license | yumengwu/LeetCode | d0765e77d794cea7c17a85a0703635672e39fb63 | 7df4fe07b67cf687358b5892dac98a993845436b | refs/heads/master | 2020-09-14T04:45:54.905988 | 2020-06-21T21:59:53 | 2020-06-21T21:59:53 | 223,021,024 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,618 | cpp | #include "../header.h"
class Solution {
public:
vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites) {
vector<int> res;
int n = prerequisites.size();
if (n == 0) {
for (int i = 0; i < numCourses; ++i) {
res.push_back(i);
}
return res;
}
unordered_map<int, int> cnt;
map<int, vector<int>> m;
unordered_set<int> has;
list<int> l;
for (int i = 0; i < numCourses; ++i) {
cnt[i] = 0;
}
for (int i = 0; i < n; ++i) {
++cnt[prerequisites[i][0]];
m[prerequisites[i][1]].push_back(prerequisites[i][0]);
}
for (int i = 0; i < numCourses; ++i) {
if (cnt[i] == 0) {
l.push_back(i);
}
}
while (l.size()) {
int first = l.front();
l.pop_front();
if (has.find(first) == has.end()) {
res.push_back(first);
has.insert(first);
}
vector<int> v = m[first];
for (int i = 0; i < v.size(); ++i) {
if (--cnt[v[i]] == 0) {
l.push_back(v[i]);
if (has.find(v[i]) == has.end()) {
res.push_back(v[i]);
has.insert(v[i]);
}
}
}
}
for (int i = 0; i < numCourses; ++i) {
if (cnt[i]) {
res.clear();
return res;
}
}
return res;
}
}; | [
"[email protected]"
] | |
0d949a33bd8962b3507ada11664d222f383e7a54 | 9a3b9d80afd88e1fa9a24303877d6e130ce22702 | /src/Providers/UNIXProviders/tests/UNIXProviders.Tests/UNIX_MPLSSegmentInXCFixture.cpp | 685dee27c9bd36fb96d132f24022c3bc44d52011 | [
"MIT"
] | permissive | brunolauze/openpegasus-providers | 3244b76d075bc66a77e4ed135893437a66dd769f | f24c56acab2c4c210a8d165bb499cd1b3a12f222 | refs/heads/master | 2020-04-17T04:27:14.970917 | 2015-01-04T22:08:09 | 2015-01-04T22:08:09 | 19,707,296 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,460 | cpp | //%LICENSE////////////////////////////////////////////////////////////////
//
// Licensed to The Open Group (TOG) under one or more contributor license
// agreements. Refer to the OpenPegasusNOTICE.txt file distributed with
// this work for additional information regarding copyright ownership.
// Each contributor licenses this file to you under the OpenPegasus Open
// Source License; you may not use this file except in compliance with the
// License.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//////////////////////////////////////////////////////////////////////////
//
//%/////////////////////////////////////////////////////////////////////////
#include "UNIX_MPLSSegmentInXCFixture.h"
#include <MPLSSegmentInXC/UNIX_MPLSSegmentInXCProvider.h>
UNIX_MPLSSegmentInXCFixture::UNIX_MPLSSegmentInXCFixture()
{
}
UNIX_MPLSSegmentInXCFixture::~UNIX_MPLSSegmentInXCFixture()
{
}
void UNIX_MPLSSegmentInXCFixture::Run()
{
CIMName className("UNIX_MPLSSegmentInXC");
CIMNamespaceName nameSpace("root/cimv2");
UNIX_MPLSSegmentInXC _p;
UNIX_MPLSSegmentInXCProvider _provider;
Uint32 propertyCount;
CIMOMHandle omHandle;
_provider.initialize(omHandle);
_p.initialize();
for(int pIndex = 0; _p.load(pIndex); pIndex++)
{
CIMInstance instance = _provider.constructInstance(className,
nameSpace,
_p);
CIMObjectPath path = instance.getPath();
cout << path.toString() << endl;
propertyCount = instance.getPropertyCount();
for(Uint32 i = 0; i < propertyCount; i++)
{
CIMProperty propertyItem = instance.getProperty(i);
if (propertyItem.getType() == CIMTYPE_REFERENCE) {
CIMValue subValue = propertyItem.getValue();
CIMInstance subInstance;
subValue.get(subInstance);
CIMObjectPath subPath = subInstance.getPath();
cout << " Name: " << propertyItem.getName().getString() << ": " << subPath.toString() << endl;
Uint32 subPropertyCount = subInstance.getPropertyCount();
for(Uint32 j = 0; j < subPropertyCount; j++)
{
CIMProperty subPropertyItem = subInstance.getProperty(j);
cout << " Name: " << subPropertyItem.getName().getString() << " - Value: " << subPropertyItem.getValue().toString() << endl;
}
}
else {
cout << " Name: " << propertyItem.getName().getString() << " - Value: " << propertyItem.getValue().toString() << endl;
}
}
cout << "------------------------------------" << endl;
cout << endl;
}
_p.finalize();
}
| [
"[email protected]"
] | |
e83c6bc8bdc335f5cc489b7c855f5607feece1d8 | febb991c955e52c7502b3f9c8c03ab360179b674 | /projects/android/KDDIDemo/jni/src/rtcengine.h | 741dcbeb9dd7f79ea10d65c908b3b19386e0a155 | [] | no_license | bobwolff68/gocastmain | b4c4630af1b3c1e9930735a95e11200fddf6b454 | 3aa167f7c8373a332ec7ed7cac0ef31a6f25f104 | refs/heads/master | 2020-04-16T00:24:48.460045 | 2012-11-20T22:34:05 | 2012-11-20T22:34:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,016 | h | #ifndef GOCASTMAIN_KDDIDEMO_RTCENGINE_H_
#define GOCASTMAIN_KDDIDEMO_RTCENGINE_H_
#include <map>
#include <string>
#include "voeinterface.h"
#include "vieinterface.h"
namespace GoCast
{
class RtcEngine
{
public:
RtcEngine();
~RtcEngine();
bool Init();
bool Deinit();
bool NewConnection(const std::string destIp,
const int destPorts[],
const int recvPorts[],
void* pRenderWin = NULL,
float zIdx = 0.0,
const bool bAddVideo = false);
bool DeleteConnection(const std::string destIp);
bool ActivateLocalRender(void* pRenderWin, float zIdx);
bool RemoveLocalRender();
private:
WebrtcVoeInterface* m_pVoeInterface;
WebrtcVieInterface* m_pVieInterface;
std::map<std::string, int> m_voiceConnections;
std::map<std::string, int> m_videoConnections;
};
}
#endif
| [
"[email protected]"
] | |
62a0a224a828fb65b11bd3814f60aca3c531bdbc | 7622359e2e4099d24bef9ae0ac83c96ca4ac8da0 | /src/srchilite/styleparser.h | 67a3cc45efc83ab236c231b932341faf2285243d | [] | no_license | lingnand/Helium | 23300a13dbef3d0a6ce31db92a1c2e4344374aa3 | d1f8fab6eb5d60e35b3287f6ea35cd1fae71f816 | refs/heads/master | 2023-04-04T10:44:03.009166 | 2021-04-16T01:48:05 | 2021-04-16T01:48:05 | 358,439,449 | 10 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 2,813 | h | /* A Bison parser, made by GNU Bison 2.5. */
/* Bison interface for Yacc-like parsers in C
Copyright (C) 1984, 1989-1990, 2000-2011 Free Software Foundation, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* As a special exception, you may create a larger work that contains
part or all of the Bison parser skeleton and distribute that work
under terms of your choice, so long as that work isn't itself a
parser generator using the skeleton or a modified version thereof
as a parser skeleton. Alternatively, if you modify or redistribute
the parser skeleton itself, you may (at your option) remove this
special exception, which will cause the skeleton and the resulting
Bison output files to be licensed under the GNU General Public
License without this special exception.
This special exception was added by the Free Software Foundation in
version 2.2 of Bison. */
/* Tokens. */
#ifndef YYTOKENTYPE
# define YYTOKENTYPE
/* Put the tokens into the symbol table, so that GDB and other debuggers
know about them. */
enum yytokentype {
BOLD = 258,
ITALICS = 259,
UNDERLINE = 260,
FIXED = 261,
NOTFIXED = 262,
NOREF = 263,
KEY = 264,
COLOR = 265,
BG_COLOR = 266,
STRINGDEF = 267,
BG_T = 268,
BODY_BG_COLOR = 269
};
#endif
/* Tokens. */
#define BOLD 258
#define ITALICS 259
#define UNDERLINE 260
#define FIXED 261
#define NOTFIXED 262
#define NOREF 263
#define KEY 264
#define COLOR 265
#define BG_COLOR 266
#define STRINGDEF 267
#define BG_T 268
#define BODY_BG_COLOR 269
#if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED
typedef union YYSTYPE
{
/* Line 2068 of yacc.c */
#line 66 "../../../lib/srchilite/styleparser.yy"
int tok ; /* command */
const std::string * string ; /* string : id, ... */
srchilite::StyleConstant flag ;
srchilite::StyleConstants *styleconstants;
srchilite::KeyList *keylist;
/* Line 2068 of yacc.c */
#line 88 "../../../lib/srchilite/styleparser.h"
} YYSTYPE;
# define YYSTYPE_IS_TRIVIAL 1
# define yystype YYSTYPE /* obsolescent; will be withdrawn */
# define YYSTYPE_IS_DECLARED 1
#endif
extern YYSTYPE stylesc_lval;
| [
"[email protected]"
] | |
5151b8d3cfed105d5fa177216434f530f85d1fa6 | bc5cbed05e2d5088adb85b220d998357974bc3a0 | /PartAllocator.cpp | 145f1e7120ea347628121baf95e64ef8e53f013a | [] | no_license | thya6769/ComputerBuilder | e10410f78bc5e0ae92534b991dc27bbbdf3c8085 | c6fcfc1dbab37cbe79dd1ccc757c4d71abe9baae | refs/heads/master | 2020-12-30T13:22:00.337430 | 2017-05-14T02:18:09 | 2017-05-14T02:18:09 | 91,209,447 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,801 | cpp | #include "PartAllocator.h"
GraphicsCardSet* PartAllocator::getGraphicsCardSet(GraphicsCard* graphicsCards, int numberOfGraphicsCards)
{
return new GraphicsCardSet(graphicsCards, numberOfGraphicsCards);
}
HardDriveSet* PartAllocator::getHardDriveSet(HardDrive** hardDrives, int numberOfHardDrives)
{
return new HardDriveSet(hardDrives, numberOfHardDrives);
}
RamSet* PartAllocator::getRamSet(Ram* ram, int numberOfRamSticks)
{
return new RamSet(ram, numberOfRamSticks);
}
// The next two methods use dynamic_cast this is a method used to cast from a
// base class down to a derived class. In doing so it check if such a cast is
// valid. If it is not it will return 0. This allows for a check to see if a
// hard drive is either a SolidStateDrive or a HardDiscDrive
HardDrive* PartAllocator::getHardDrive(HardDrive* hardDrive)
{
if (SolidStateDrive* ssDrive = dynamic_cast<SolidStateDrive*>(hardDrive))
{
return new SolidStateDrive(*ssDrive);
}
else if (HardDiscDrive* hhDrive = dynamic_cast<HardDiscDrive*>(hardDrive))
{
return new HardDiscDrive(*hhDrive);
}
return new HardDrive();
}
Part* PartAllocator::getPart(const Part &p)
{
if (const BluRayDrive* bluRayDrive = dynamic_cast<const BluRayDrive*>(&p))
{
return new BluRayDrive(*bluRayDrive);
}
if (const Case* computerCase = dynamic_cast<const Case*>(&p))
{
return new Case(*computerCase);
}
if (const CoolingFan* coolingFan = dynamic_cast<const CoolingFan*>(&p))
{
return new CoolingFan(*coolingFan);
}
if (const CPU* cpu = dynamic_cast<const CPU*>(&p))
{
return new CPU(*cpu);
}
if (const DVDDrive* dvdDrive = dynamic_cast<const DVDDrive*>(&p))
{
return new DVDDrive(*dvdDrive);
}
if (const HardDiscDrive* hdd = dynamic_cast<const HardDiscDrive*>(&p))
{
return new HardDiscDrive(*hdd);
}
if (const GraphicsCard* graphicsCard = dynamic_cast<const GraphicsCard*>(&p))
{
return new GraphicsCard(*graphicsCard);
}
if (const Motherboard* motherboard = dynamic_cast<const Motherboard*>(&p))
{
return new Motherboard(*motherboard);
}
if (const PowerSupply* psu = dynamic_cast<const PowerSupply*>(&p))
{
return new PowerSupply(*psu);
}
if (const Ram* ram = dynamic_cast<const Ram*>(&p))
{
return new Ram(*ram);
}
if (const SolidStateDrive* sdd = dynamic_cast<const SolidStateDrive*>(&p))
{
return new SolidStateDrive(*sdd);
}
if (const WaterCooling* waterCooling = dynamic_cast<const WaterCooling*>(&p))
{
return new WaterCooling(*waterCooling);
}
return 0;
}
| [
"[email protected]"
] | |
c537beb12e082d9b0d82c6e3570b35cd14b19fca | 4c10cf68de9f75dbee15f23dc612996c73c02e6c | /Ch2/build-Counter-Desktop_Qt_6_1_3_MinGW_64_bit-Debug/debug/moc_Counter.cpp | 286a63dd1860baacf419396c4b54d76d52f3591a | [] | no_license | Frollerman/QtBook | 784d6f79267744e9583999779f3f990bdd0df4c2 | c71c1884343955e9c33590a4547aa6f2daa35e18 | refs/heads/master | 2023-08-30T18:13:37.363513 | 2021-11-07T20:58:16 | 2021-11-07T20:58:16 | 408,225,187 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,906 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'Counter.h'
**
** Created by: The Qt Meta Object Compiler version 68 (Qt 6.1.3)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include <memory>
#include "../../Counter/Counter.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'Counter.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 68
#error "This file was generated using the moc from 6.1.3. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
QT_WARNING_PUSH
QT_WARNING_DISABLE_DEPRECATED
struct qt_meta_stringdata_Counter_t {
const uint offsetsAndSize[10];
char stringdata0[40];
};
#define QT_MOC_LITERAL(ofs, len) \
uint(offsetof(qt_meta_stringdata_Counter_t, stringdata0) + ofs), len
static const qt_meta_stringdata_Counter_t qt_meta_stringdata_Counter = {
{
QT_MOC_LITERAL(0, 7), // "Counter"
QT_MOC_LITERAL(8, 7), // "goodbye"
QT_MOC_LITERAL(16, 0), // ""
QT_MOC_LITERAL(17, 14), // "counterChanged"
QT_MOC_LITERAL(32, 7) // "slotInc"
},
"Counter\0goodbye\0\0counterChanged\0slotInc"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_Counter[] = {
// content:
9, // revision
0, // classname
0, 0, // classinfo
3, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
2, // signalCount
// signals: name, argc, parameters, tag, flags, initial metatype offsets
1, 0, 32, 2, 0x06, 0 /* Public */,
3, 1, 33, 2, 0x06, 1 /* Public */,
// slots: name, argc, parameters, tag, flags, initial metatype offsets
4, 0, 36, 2, 0x0a, 3 /* Public */,
// signals: parameters
QMetaType::Void,
QMetaType::Void, QMetaType::Int, 2,
// slots: parameters
QMetaType::Void,
0 // eod
};
void Counter::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
auto *_t = static_cast<Counter *>(_o);
(void)_t;
switch (_id) {
case 0: _t->goodbye(); break;
case 1: _t->counterChanged((*reinterpret_cast< int(*)>(_a[1]))); break;
case 2: _t->slotInc(); break;
default: ;
}
} else if (_c == QMetaObject::IndexOfMethod) {
int *result = reinterpret_cast<int *>(_a[0]);
{
using _t = void (Counter::*)();
if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&Counter::goodbye)) {
*result = 0;
return;
}
}
{
using _t = void (Counter::*)(int );
if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&Counter::counterChanged)) {
*result = 1;
return;
}
}
}
}
const QMetaObject Counter::staticMetaObject = { {
QMetaObject::SuperData::link<QObject::staticMetaObject>(),
qt_meta_stringdata_Counter.offsetsAndSize,
qt_meta_data_Counter,
qt_static_metacall,
nullptr,
qt_incomplete_metaTypeArray<qt_meta_stringdata_Counter_t
, QtPrivate::TypeAndForceComplete<void, std::false_type>, QtPrivate::TypeAndForceComplete<void, std::false_type>, QtPrivate::TypeAndForceComplete<int, std::false_type>
, QtPrivate::TypeAndForceComplete<void, std::false_type>
>,
nullptr
} };
const QMetaObject *Counter::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *Counter::qt_metacast(const char *_clname)
{
if (!_clname) return nullptr;
if (!strcmp(_clname, qt_meta_stringdata_Counter.stringdata0))
return static_cast<void*>(this);
return QObject::qt_metacast(_clname);
}
int Counter::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QObject::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 3)
qt_static_metacall(this, _c, _id, _a);
_id -= 3;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 3)
*reinterpret_cast<QMetaType *>(_a[0]) = QMetaType();
_id -= 3;
}
return _id;
}
// SIGNAL 0
void Counter::goodbye()
{
QMetaObject::activate(this, &staticMetaObject, 0, nullptr);
}
// SIGNAL 1
void Counter::counterChanged(int _t1)
{
void *_a[] = { nullptr, const_cast<void*>(reinterpret_cast<const void*>(std::addressof(_t1))) };
QMetaObject::activate(this, &staticMetaObject, 1, _a);
}
QT_WARNING_POP
QT_END_MOC_NAMESPACE
| [
"[email protected]"
] | |
9598dc09f790882debae5b70730b36b50355df50 | f1a35bd700e42302cbc76f1d59fc8e5f0cf3a0fd | /include/vrg3d/SynchedSystem.h | 9651347c34e8d9fb3e560c71f9a66645a1ea9e08 | [] | no_license | ribells/cove_yurt | ff31448c17377e9c8a3d876d92453c852ba7e611 | 4d5ceadc750d833b4384e8e1edde4c654c2c3b35 | refs/heads/master | 2020-12-25T17:04:17.473298 | 2016-06-23T18:48:54 | 2016-06-23T18:48:54 | 41,107,136 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,941 | h | // Copyright Regents of the University of Minnesota and Brown University, 2010. All rights are reserved.
/*
* \author Andy Foresberg (asf) and Daniel Keefe (dfk)
*
* \file SynchedSystem.h
*
*/
#ifndef SYNCHEDSYSTEM_H
#define SYNCHEDSYSTEM_H
namespace VRG3D {
/** This is a static class that reproduces some of the functionality
of G3D::System for use specifically in clustered rendering
environments. For example, when doing animation based on the
system's clock you want the time to be the same across all the
rendering nodes, so you can't use System::getLocalTime() because
it will be slightly off between the various nodes. Instead, use
SynchedSystem::getLocalTime() and the value for time will be the
same across all walls, although, it will only be as accurate as
the rate at which the time is updated from the vrg3d event server,
which will be once per frame.
*/
class SynchedSystem
{
public:
/// Programs should access the time through these methods
static double getLocalTime();
static double getAppStartTime() { return _appStartTime; }
static double getAppRunningTime(){ return getLocalTime() - _appStartTime; }
enum TimeUpdateMethod {
USE_LOCAL_SYSTEM_TIME, // used in non-cluster situations (default)
PROGRAM_UPDATES_TIME // used in clustered situations
};
/// Called by VRApp when running as a cluster client to initialize
/// the system.
static void setProgramUpdatesTime(double applicationStartTime);
/// Called by VRApp when running as a cluster client once per frame
/// when it receives a new timing event from the synchronization
/// server.
static void updateLocalTime(double t);
static TimeUpdateMethod getTimeUpdateMethod() { return _timeUpdateMethod; }
protected:
static TimeUpdateMethod _timeUpdateMethod;
static double _appStartTime;
static double _localTime;
};
} // end namespace
#endif
| [
"[email protected]"
] | |
f855d0a109ee45582258fc5e07d93feb6aab0027 | 5299fa8c8dace37e705208a0de69fa67b0b91351 | /reverse-string.cpp | ae3686b8b4afc5299c2ff41aed68c73c06d5b180 | [] | no_license | dym4xion/cplusplus-scrapbook | 0ba5617e7b4c97087cf04ab95d49bfdef1e6621a | 08403c7763bfc4ac047a6c12264fb93e463c5db6 | refs/heads/master | 2022-11-29T15:57:00.928018 | 2020-08-09T17:26:15 | 2020-08-09T17:26:15 | 284,307,642 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 463 | cpp | #include <iostream>
#include <cstring>
using namespace std;
int main(){
char str[] = "racecar";
char *start, *end;
int len;
char temp;
cout << "original: " << str << "\n";
len = strlen(str);
start = str;
end = &str[len - 1];
while (start < end){
temp = *start;
*start = *end;
*end = temp;
start++;
end--;
}
cout << "reversed: " << str << "\n";
return 0;
}
| [
"[email protected]"
] | |
02b3b894d70792a8e115d21c371adafcc73dbf92 | a7fb5d44cbd1ffee71519c1489fef1bdbc05fa68 | /HSMode.h | cd1be76e8b9c3214feeebe596d7a5b192fa5fa93 | [] | no_license | hodaig/hybridSched | d517d94906f0da9cf1fe6fdc8491baab72c57141 | 22e37603d64e85607bf933b19fbdba70dd10cf67 | refs/heads/master | 2021-01-13T08:08:52.261811 | 2016-12-01T16:24:17 | 2016-12-01T16:24:17 | 71,718,274 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,008 | h | /*
* HSMode.h
*
* Created on: Sep 14, 2016
* Author: hodai
*/
#ifndef HSMODE_H_
#define HSMODE_H_
#include "HybridSched.h"
#include "conditions/HSCondition.h"
#include "HSTransition.h"
#include <set>
//TODO typedef int (*HSCondition)(HybridSched*);
//typedef int (*HSCondition)(void);
#define HS_MAX_TASKS_IN_MODE 20
#define HS_MAX_TRANSITIONS_FROM_MODE 20
using namespace std;
/* Forward deceleration */
class HSMode;
//class HSTransition;
#if 0 //TODO
typedef struct {
HSCondition* cond;
HSMode* toMode;
set<hsVariable_t*> reset;
} HSMode_transition;
#endif
class HSMode {
private:
const char* _name; // mode name (for debugging)
//HSCondition* _dom; // mode domain
//set<HybridSched::Task*> _tasks; // tasks array
set<HSTransition*> _transitions; // transitions array
uint16_t _modeMaxTimeMicros;
bool _maxTimeValid; // true if the value of '_modeMaxTimeMicros' is valid
public:
HSMode();
HSMode(const char* name);
virtual ~HSMode();
void addTask(HybridSched::Task* task);
const set<HybridSched::Task*>* getTasks();
void addTransition(HSMode* toMode, HSCondition* cond, uint32_t cost);
void addTransition(HSMode* toMode, HSCondition* cond, const set<hsVariable_t*>* reset, uint32_t cost);
void addTransition(HSTransition* trans);
const set<HSTransition*>* getTransitions();
unsigned int getAvailableTransitions(set<HSTransition*>* retTransitionsSet);
HSTransition* getBestTransition();
void removeTransition(HSTransition* transition);
/*
* remove all the transitions from this mode to the mode 'toMode'
*/
void removeTransitions(HSMode* toMode);
/*
* return new set with all the followers modes
* -- the user should delete this set
*/
set<HSMode*>* getAllNexts();
uint16_t getMaxTimeMicros();
// TODO void removeOverflowTransitions(uint32_t max_slot_time_micros);
const char* getName();
private:
//TODO void removeTransition(unsigned int transitionIndex);
};
#endif /* HSMODE_H_ */
| [
"[email protected]"
] | |
b5dea9f17d6596ca3fa0db5329b64a7ac692b488 | 3051050dc3dee97dc60ef78d31ff500b6e93d0fb | /chrome/browser/pdf/pdf_extension_js_test.cc | 1949387229388d39857586f2cdc6bfec7721e2d1 | [
"BSD-3-Clause"
] | permissive | weblifeio/chromium | cd249e1c9418dcf0792bd68bbdcd2a6e56af0e2e | 74ac962b3a95c88614f734066ab2cc48b572359c | refs/heads/main | 2023-06-09T19:45:03.535378 | 2023-05-26T19:16:31 | 2023-05-26T19:16:31 | 177,631,387 | 0 | 0 | null | 2019-03-25T17:15:48 | 2019-03-25T17:15:47 | null | UTF-8 | C++ | false | false | 15,933 | cc | // Copyright 2023 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <string>
#include <vector>
#include "base/base_paths.h"
#include "base/path_service.h"
#include "base/strings/stringprintf.h"
#include "base/test/icu_test_util.h"
#include "build/branding_buildflags.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "chrome/browser/content_settings/host_content_settings_map_factory.h"
#include "chrome/browser/pdf/pdf_extension_test_base.h"
#include "chrome/browser/pdf/pdf_extension_test_util.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/common/webui_url_constants.h"
#include "chrome/test/base/ui_test_utils.h"
#include "chrome/test/base/web_ui_test_data_source.h"
#include "components/content_settings/core/browser/host_content_settings_map.h"
#include "components/services/screen_ai/buildflags/buildflags.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/common/content_features.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/scoped_time_zone.h"
#include "extensions/browser/guest_view/mime_handler_view/mime_handler_view_guest.h"
#include "extensions/test/result_catcher.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "pdf/buildflags.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/resource/resource_bundle.h"
#include "url/gurl.h"
class PDFExtensionJSTest : public PDFExtensionTestBase {
protected:
void SetUpOnMainThread() override {
PDFExtensionTestBase::SetUpOnMainThread();
// Load the pak file holding the resources served from chrome://webui-test.
base::FilePath pak_path;
ASSERT_TRUE(base::PathService::Get(base::DIR_ASSETS, &pak_path));
pak_path = pak_path.AppendASCII("browser_tests.pak");
ui::ResourceBundle::GetSharedInstance().AddDataPackFromPath(
pak_path, ui::kScaleFactorNone);
// Register the chrome://webui-test data source.
webui::CreateAndAddWebUITestDataSource(browser()->profile());
}
void RunTestsInJsModule(const std::string& filename,
const std::string& pdf_filename) {
RunTestsInJsModuleHelper(filename, pdf_filename, /*new_tab=*/false);
}
void RunTestsInJsModuleNewTab(const std::string& filename,
const std::string& pdf_filename) {
RunTestsInJsModuleHelper(filename, pdf_filename, /*new_tab=*/true);
}
private:
// Runs the extensions test at chrome/test/data/pdf/<filename> on the PDF file
// at chrome/test/data/pdf/<pdf_filename>, where |filename| is loaded as a JS
// module.
void RunTestsInJsModuleHelper(const std::string& filename,
const std::string& pdf_filename,
bool new_tab) {
extensions::ResultCatcher catcher;
GURL url(embedded_test_server()->GetURL("/pdf/" + pdf_filename));
// It should be good enough to just navigate to the URL. But loading up the
// BrowserPluginGuest seems to happen asynchronously as there was flakiness
// being seen due to the BrowserPluginGuest not being available yet (see
// crbug.com/498077). So instead use LoadPdf() which ensures that the PDF is
// loaded before continuing.
extensions::MimeHandlerViewGuest* guest =
new_tab ? LoadPdfInNewTabGetMimeHandlerView(url)
: LoadPdfGetMimeHandlerView(url);
ASSERT_TRUE(guest);
constexpr char kModuleLoaderTemplate[] =
R"(var s = document.createElement('script');
s.type = 'module';
s.src = 'chrome://%s/pdf/%s';
s.onerror = function(e) {
console.error('Error while loading', e.target.src);
};
document.body.appendChild(s);)";
ASSERT_TRUE(content::ExecuteScript(
guest->GetGuestMainFrame(),
base::StringPrintf(kModuleLoaderTemplate,
chrome::kChromeUIWebUITestHost, filename.c_str())));
if (!catcher.GetNextResult()) {
FAIL() << catcher.message();
}
}
};
IN_PROC_BROWSER_TEST_F(PDFExtensionJSTest, Basic) {
RunTestsInJsModule("basic_test.js", "test.pdf");
EXPECT_EQ(1, CountPDFProcesses());
}
IN_PROC_BROWSER_TEST_F(PDFExtensionJSTest, BasicPlugin) {
RunTestsInJsModule("basic_plugin_test.js", "test.pdf");
}
IN_PROC_BROWSER_TEST_F(PDFExtensionJSTest, PluginController) {
RunTestsInJsModule("plugin_controller_test.js", "test.pdf");
}
IN_PROC_BROWSER_TEST_F(PDFExtensionJSTest, Viewport) {
RunTestsInJsModule("viewport_test.js", "test.pdf");
}
IN_PROC_BROWSER_TEST_F(PDFExtensionJSTest, ViewportScroller) {
RunTestsInJsModule("viewport_scroller_test.js", "test.pdf");
}
IN_PROC_BROWSER_TEST_F(PDFExtensionJSTest, Layout3) {
RunTestsInJsModule("layout_test.js", "test-layout3.pdf");
}
IN_PROC_BROWSER_TEST_F(PDFExtensionJSTest, Layout4) {
RunTestsInJsModule("layout_test.js", "test-layout4.pdf");
}
IN_PROC_BROWSER_TEST_F(PDFExtensionJSTest, Bookmark) {
RunTestsInJsModule("bookmarks_test.js", "test-bookmarks-with-zoom.pdf");
}
IN_PROC_BROWSER_TEST_F(PDFExtensionJSTest, Navigator) {
RunTestsInJsModule("navigator_test.js", "test.pdf");
}
IN_PROC_BROWSER_TEST_F(PDFExtensionJSTest, ParamsParser) {
RunTestsInJsModule("params_parser_test.js", "test.pdf");
}
IN_PROC_BROWSER_TEST_F(PDFExtensionJSTest, ZoomManager) {
RunTestsInJsModule("zoom_manager_test.js", "test.pdf");
}
IN_PROC_BROWSER_TEST_F(PDFExtensionJSTest, GestureDetector) {
RunTestsInJsModule("gesture_detector_test.js", "test.pdf");
}
IN_PROC_BROWSER_TEST_F(PDFExtensionJSTest, SwipeDetector) {
RunTestsInJsModule("swipe_detector_test.js", "test.pdf");
}
IN_PROC_BROWSER_TEST_F(PDFExtensionJSTest, TouchHandling) {
RunTestsInJsModule("touch_handling_test.js", "test.pdf");
}
IN_PROC_BROWSER_TEST_F(PDFExtensionJSTest, Elements) {
// Although this test file does not require a PDF to be loaded, loading the
// elements without loading a PDF is difficult.
RunTestsInJsModule("material_elements_test.js", "test.pdf");
}
IN_PROC_BROWSER_TEST_F(PDFExtensionJSTest, DownloadControls) {
// Although this test file does not require a PDF to be loaded, loading the
// elements without loading a PDF is difficult.
RunTestsInJsModule("download_controls_test.js", "test.pdf");
}
IN_PROC_BROWSER_TEST_F(PDFExtensionJSTest, Title) {
RunTestsInJsModule("title_test.js", "test-title.pdf");
}
IN_PROC_BROWSER_TEST_F(PDFExtensionJSTest, WhitespaceTitle) {
RunTestsInJsModule("whitespace_title_test.js", "test-whitespace-title.pdf");
}
IN_PROC_BROWSER_TEST_F(PDFExtensionJSTest, PageChange) {
RunTestsInJsModule("page_change_test.js", "test-bookmarks.pdf");
}
IN_PROC_BROWSER_TEST_F(PDFExtensionJSTest, ScrollWithFormFieldFocusedTest) {
RunTestsInJsModule("scroll_with_form_field_focused_test.js",
"test-bookmarks.pdf");
}
IN_PROC_BROWSER_TEST_F(PDFExtensionJSTest, Metrics) {
RunTestsInJsModule("metrics_test.js", "test.pdf");
}
IN_PROC_BROWSER_TEST_F(PDFExtensionJSTest, ViewerPasswordDialog) {
RunTestsInJsModule("viewer_password_dialog_test.js", "encrypted.pdf");
}
IN_PROC_BROWSER_TEST_F(PDFExtensionJSTest, ArrayBufferAllocator) {
// Run several times to see if there are issues with unloading.
RunTestsInJsModule("beep_test.js", "array_buffer.pdf");
RunTestsInJsModule("beep_test.js", "array_buffer.pdf");
RunTestsInJsModule("beep_test.js", "array_buffer.pdf");
}
IN_PROC_BROWSER_TEST_F(PDFExtensionJSTest, ViewerToolbar) {
// Although this test file does not require a PDF to be loaded, loading the
// elements without loading a PDF is difficult.
RunTestsInJsModule("viewer_toolbar_test.js", "test.pdf");
}
IN_PROC_BROWSER_TEST_F(PDFExtensionJSTest, ViewerPdfSidenav) {
// Although this test file does not require a PDF to be loaded, loading the
// elements without loading a PDF is difficult.
RunTestsInJsModule("viewer_pdf_sidenav_test.js", "test.pdf");
}
IN_PROC_BROWSER_TEST_F(PDFExtensionJSTest, ViewerThumbnailBar) {
// Although this test file does not require a PDF to be loaded, loading the
// elements without loading a PDF is difficult.
RunTestsInJsModule("viewer_thumbnail_bar_test.js", "test.pdf");
}
IN_PROC_BROWSER_TEST_F(PDFExtensionJSTest, ViewerThumbnail) {
// Although this test file does not require a PDF to be loaded, loading the
// elements without loading a PDF is difficult.
RunTestsInJsModule("viewer_thumbnail_test.js", "test.pdf");
}
IN_PROC_BROWSER_TEST_F(PDFExtensionJSTest, Fullscreen) {
// Use a PDF document with multiple pages, to exercise navigating between
// pages.
RunTestsInJsModule("fullscreen_test.js", "test-bookmarks.pdf");
}
IN_PROC_BROWSER_TEST_F(PDFExtensionJSTest, ViewerPropertiesDialog) {
// The properties dialog formats some values based on locale.
base::test::ScopedRestoreICUDefaultLocale scoped_locale{"en_US"};
// This will apply to the new processes spawned within RunTestsInJsModule(),
// thus consistently running the test in a well known time zone.
content::ScopedTimeZone scoped_time_zone{"America/Los_Angeles"};
RunTestsInJsModule("viewer_properties_dialog_test.js", "document_info.pdf");
}
IN_PROC_BROWSER_TEST_F(PDFExtensionJSTest, PostMessageProxy) {
// Although this test file does not require a PDF to be loaded, loading the
// elements without loading a PDF is difficult.
RunTestsInJsModule("post_message_proxy_test.js", "test.pdf");
}
#if BUILDFLAG(IS_CHROMEOS_ASH)
IN_PROC_BROWSER_TEST_F(PDFExtensionJSTest, Printing) {
RunTestsInJsModule("printing_icon_test.js", "test.pdf");
}
#endif // BUILDFLAG(IS_CHROMEOS_ASH)
#if BUILDFLAG(ENABLE_INK)
// TODO(https://crbug.com/920684): Test times out under sanitizers.
#if defined(MEMORY_SANITIZER) || defined(LEAK_SANITIZER) || \
defined(ADDRESS_SANITIZER) || defined(_DEBUG)
#define MAYBE_AnnotationsFeatureEnabled DISABLED_AnnotationsFeatureEnabled
#else
#define MAYBE_AnnotationsFeatureEnabled AnnotationsFeatureEnabled
#endif
IN_PROC_BROWSER_TEST_F(PDFExtensionJSTest, MAYBE_AnnotationsFeatureEnabled) {
RunTestsInJsModule("annotations_feature_enabled_test.js", "test.pdf");
}
IN_PROC_BROWSER_TEST_F(PDFExtensionJSTest, AnnotationsToolbar) {
// Although this test file does not require a PDF to be loaded, loading the
// elements without loading a PDF is difficult.
RunTestsInJsModule("annotations_toolbar_test.js", "test.pdf");
}
IN_PROC_BROWSER_TEST_F(PDFExtensionJSTest, ViewerToolbarDropdown) {
// Although this test file does not require a PDF to be loaded, loading the
// elements without loading a PDF is difficult.
RunTestsInJsModule("viewer_toolbar_dropdown_test.js", "test.pdf");
}
#endif // BUILDFLAG(ENABLE_INK)
#if BUILDFLAG(ENABLE_SCREEN_AI_SERVICE)
IN_PROC_BROWSER_TEST_F(PDFExtensionJSTest, PdfOcrToolbar) {
// Although this test file does not require a PDF to be loaded, loading the
// elements without loading a PDF is difficult.
RunTestsInJsModule("pdf_ocr_toolbar_test.js", "test.pdf");
}
#endif // BUILDFLAG(ENABLE_SCREEN_AI_SERVICE)
class PDFExtensionContentSettingJSTest : public PDFExtensionJSTest {
protected:
// When blocking JavaScript, block the exact query from pdf/main.js while
// still allowing enough JavaScript to run in the extension for the test
// harness to complete its work.
void SetPdfJavaScript(bool enabled) {
auto* map =
HostContentSettingsMapFactory::GetForProfile(browser()->profile());
map->SetContentSettingCustomScope(
ContentSettingsPattern::Wildcard(),
ContentSettingsPattern::FromString(
"chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai"),
ContentSettingsType::JAVASCRIPT,
enabled ? CONTENT_SETTING_ALLOW : CONTENT_SETTING_BLOCK);
}
};
IN_PROC_BROWSER_TEST_F(PDFExtensionContentSettingJSTest, Beep) {
RunTestsInJsModule("beep_test.js", "test-beep.pdf");
}
IN_PROC_BROWSER_TEST_F(PDFExtensionContentSettingJSTest, NoBeep) {
SetPdfJavaScript(/*enabled=*/false);
RunTestsInJsModule("nobeep_test.js", "test-beep.pdf");
}
IN_PROC_BROWSER_TEST_F(PDFExtensionContentSettingJSTest, BeepThenNoBeep) {
content::RenderProcessHost::SetMaxRendererProcessCount(1);
RunTestsInJsModule("beep_test.js", "test-beep.pdf");
SetPdfJavaScript(/*enabled=*/false);
RunTestsInJsModuleNewTab("nobeep_test.js", "test-beep.pdf");
// Make sure there are two PDFs in the same process.
const int tab_count = browser()->tab_strip_model()->count();
EXPECT_EQ(2, tab_count);
EXPECT_EQ(1, CountPDFProcesses());
}
IN_PROC_BROWSER_TEST_F(PDFExtensionContentSettingJSTest, NoBeepThenBeep) {
content::RenderProcessHost::SetMaxRendererProcessCount(1);
SetPdfJavaScript(/*enabled=*/false);
RunTestsInJsModule("nobeep_test.js", "test-beep.pdf");
SetPdfJavaScript(/*enabled=*/true);
RunTestsInJsModuleNewTab("beep_test.js", "test-beep.pdf");
// Make sure there are two PDFs in the same process.
const int tab_count = browser()->tab_strip_model()->count();
EXPECT_EQ(2, tab_count);
EXPECT_EQ(1, CountPDFProcesses());
}
IN_PROC_BROWSER_TEST_F(PDFExtensionContentSettingJSTest, BeepCsp) {
// The script-source * directive in the mock headers file should
// allow the JavaScript to execute the beep().
RunTestsInJsModule("beep_test.js", "test-beep-csp.pdf");
}
IN_PROC_BROWSER_TEST_F(PDFExtensionContentSettingJSTest, DISABLED_NoBeepCsp) {
// The script-source none directive in the mock headers file should
// prevent the JavaScript from executing the beep().
// TODO(https://crbug.com/1032511) functionality not implemented.
RunTestsInJsModule("nobeep_test.js", "test-nobeep-csp.pdf");
}
class PDFExtensionWebUICodeCacheJSTest : public PDFExtensionJSTest {
protected:
std::vector<base::test::FeatureRef> GetEnabledFeatures() const override {
auto enabled = PDFExtensionJSTest::GetEnabledFeatures();
enabled.push_back(features::kWebUICodeCache);
return enabled;
}
};
// Regression test for https://crbug.com/1239148.
IN_PROC_BROWSER_TEST_F(PDFExtensionWebUICodeCacheJSTest, Basic) {
RunTestsInJsModule("basic_test.js", "test.pdf");
}
// Service worker tests are regression tests for
// https://crbug.com/916514.
class PDFExtensionServiceWorkerJSTest : public PDFExtensionJSTest {
public:
~PDFExtensionServiceWorkerJSTest() override = default;
protected:
// Installs the specified service worker and tests navigating to a PDF in its
// scope.
void RunServiceWorkerTest(const std::string& worker_path) {
// Install the service worker.
ASSERT_TRUE(ui_test_utils::NavigateToURL(
browser(), embedded_test_server()->GetURL(
"/service_worker/create_service_worker.html")));
EXPECT_EQ("DONE", EvalJs(GetActiveWebContents(),
"register('" + worker_path + "', '/pdf');"));
// Navigate to a PDF in the service worker's scope. It should load.
RunTestsInJsModule("basic_test.js", "test.pdf");
EXPECT_EQ(1, CountPDFProcesses());
}
};
// Test navigating to a PDF in the scope of a service worker with no fetch event
// handler.
IN_PROC_BROWSER_TEST_F(PDFExtensionServiceWorkerJSTest, NoFetchHandler) {
RunServiceWorkerTest("empty.js");
}
// Test navigating to a PDF when a service worker intercepts the request and
// then falls back to network by not calling FetchEvent.respondWith().
IN_PROC_BROWSER_TEST_F(PDFExtensionServiceWorkerJSTest, NetworkFallback) {
RunServiceWorkerTest("network_fallback_worker.js");
}
// Test navigating to a PDF when a service worker intercepts the request and
// provides a response.
IN_PROC_BROWSER_TEST_F(PDFExtensionServiceWorkerJSTest, Interception) {
RunServiceWorkerTest("respond_with_fetch_worker.js");
}
| [
"[email protected]"
] | |
b1402df21888ce09ce496447cba1f94d83d66611 | 6e5c688f4860277ef82f0da1dace4fc82dcbae7b | /DeferredRendering/Scene/SceneIndex.h | cf72a847e52dce7b3e22df0585d28909516a6ee5 | [
"MIT"
] | permissive | lambertjamesd/Krono | 78595d766128a652e2d57074e015afcf9ee933f2 | fc2418a176e93aeedf014ac5503fa892f2569047 | refs/heads/master | 2021-01-23T21:37:59.018525 | 2017-12-24T23:56:32 | 2017-12-24T23:56:32 | 21,313,403 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 488 | h | #pragma once
#include "Collide/Frustrum.h"
#include "Entity.h"
#include <functional>
namespace krono
{
class SceneIndex
{
public:
SceneIndex(void);
~SceneIndex(void);
typedef std::function<void (Entity&)> IndexHitCallback;
virtual void CollideFrustrum(const Frustrum& frustrum, IndexHitCallback hitCallback) = 0;
virtual void InsertEntity(Auto<Entity>& entity) = 0;
virtual void UpdateEntity(Entity* entity) = 0;
virtual void RemoveEntity(Entity* entity) = 0;
private:
};
} | [
"[email protected]"
] | |
10daa829d1b73399ca5099ed2950e4277b528769 | e7504a729324c7bf3743e36ed1acecafdfe8995b | /dx2-project/Naruto/Classes/ui/NFTownScene.h | e2243c1a9be4d38b62a69930fb15cf13e67053d0 | [
"Apache-2.0"
] | permissive | wish-wish/TheSilence | 5bc11f095724782ec5107b2f13140c08d336744a | a5b493f8583ca6319598b711de31382cded84f0f | refs/heads/master | 2023-04-01T12:20:57.538839 | 2021-04-12T19:26:19 | 2021-04-12T19:26:19 | 357,307,938 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 20,087 | h | #ifndef _NF_TOWN_SCENE_H_
#define _NF_TOWN_SCENE_H_
#include "../publicdef/PublicDef.h"
class CNFTownScene : public cocos2d::CCLayer ,public CMsgReceiver
{
protected:
//==============================================================================临时对应win32
bool m_bIsPressW; //win32下对应的键盘按键是否被按下(临时)
bool m_bIsPressA; //win32下对应的键盘按键是否被按下(临时)
bool m_bIsPressS; //win32下对应的键盘按键是否被按下(临时)
bool m_bIsPressD; //win32下对应的键盘按键是否被按下(临时)
bool m_bIsPressJ; //win32下对应的键盘按键是否被按下(临时)
bool m_bIsPressK; //win32下对应的键盘按键是否被按下(临时)
bool m_bIsPressL; //win32下对应的键盘按键是否被按下(临时)
bool m_bIsPressI; //win32下对应的键盘按键是否被按下(临时)
int m_nRunSpace; //连续按方向键使奔跑的时间间隔
float m_fFirectionOld; //上一次移动方向
bool m_bIsRun; //是否处于奔跑状态
//==============================================================================临时对应win32 end
bool m_bBtnListSwitchOpen; //右下方扩展按钮列表开关
bool m_bBtnListSwitchMoveOver; //右下方扩展按钮列表动画结束标识
bool m_bBtnFriendSwitchOpen; //右方好友扩展按钮列表开关
bool m_bBtnFriendSwitchMoveOver; //右方好友动画结束标识
int m_nStageID; //当前城镇ID
int m_nRoleID; //当前角色ID
int m_nCurrentSkillUpRoleID; //当前技能页角色ID(只用于技能升级页面)
int m_nCurrentSelectSkillID; //当前选中技能ID(只用于技能升级页面)
public:
//create
static cocos2d::CCScene* CreateTownScene(int nStageID,int nRoleID);
static CNFTownScene * CreateLayer(int nStageID,int nRoleID);
protected:
//init
virtual bool Init(int nStageID,int nRoleID);
//更新函数
void OnCallPerFrame(float dt);
//触摸
virtual bool ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent);
virtual void ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent);
virtual void ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent);
virtual void ccTouchCancelled(CCTouch *pTouch, CCEvent *pEvent);
//
virtual void onEnter();
virtual void onExit();
//接收函数
virtual void RecMsg(int enMsg,void* pData,int nSize);
//动作回调:连击结果结束
void OnHitResultOverCallBack();
//显示连击结果
void ShowHitResult();
//按钮回调
void OnBtnCallBack(CCObject *pObj);
//主UI界面功能按钮
void OnExUiBtnListSwitch(CCObject *pSender, TouchEventType type); //右下角按钮开关回调
void OnTouchSwichMoveOver(); //扩展按钮栏伸展动画回调
//重载[返回]
virtual void keyBackClicked(); //Android 返回键
void OnCloseGame(CCObject *pSender, TouchEventType type);
//切换功能页按钮函数
/************************************************************************/
/* 主UI扩展按钮 */
/************************************************************************/
//----------玩家信息模块相关---------//
void OnSwitchToPlayerInfoPage(CCObject *pSender, TouchEventType type); //切换到玩家信息层
void OnTouchPlayerInfoPage(CCObject *pSender, TouchEventType type); //玩家信息层触碰回调
void OnClosePlayerInfoPage(CCObject *pSender, TouchEventType type); //玩家信息关闭
void OnPlayerInfoItemBagPageViewEvent(CCObject* pSender, PageViewEventType type); //玩家信息背包道具滑动条事件回调
void OnSwitchToBagPage(CCObject *pSender, TouchEventType type); //切换到玩家背包层
void OnSwitchToPlayerAtribuePage(CCObject *pSender, TouchEventType type); //切换到玩家属性层
void OnSwitchToTitlePage(CCObject *pSender, TouchEventType type); //切换到玩家称号层
void OnEquClick(CCObject *pSender, TouchEventType type); //装备按钮回调
//----------设置页面模块相关---------//
void OnSwitchToSettingPage(CCObject *pSender, TouchEventType type); //设置页面
void OnMusicBtnClick(CCObject *pSender, TouchEventType type); //设置音乐
void OnSoundBtnClickPage(CCObject *pSender, TouchEventType type); //设置音效
void OnSwitchToChangeRoleLayerClick(CCObject *pSender, TouchEventType type); //跳转到选人界面
void OnOnSwitchToLoginLayer(CCObject *pSender, TouchEventType type); //跳转到登录界面
void OnHideOthersBtnClickPage(CCObject *pSender, TouchEventType type); //设置隐藏其他玩家
//----------技能---------//
void OnSwitchToSkill(CCObject *pSender, TouchEventType type); //切换到领奖层
//----------忍术---------//
void OnSwitchToNinjaSkill(CCObject *pSender, TouchEventType type); //切换到技能层
//----------奥义---------//
void OnSwitchToBigSkill(CCObject *pSender, TouchEventType type); //切换到奥义层
//----------任务---------//
void OnSwitchToTask(CCObject *pSender, TouchEventType type); //切换到任务层
//----------公会---------//
void OnSwitchToGuild(CCObject *pSender, TouchEventType type); //切换到公会层
//----------排行---------//
void OnSwitchToRank(CCObject *pSender, TouchEventType type); //切换到排行层
/************************************************************************/
/* 主UI按钮 */
/************************************************************************/
//----------获取奖励---------//
void OnSwitchToGetReward(CCObject *pSender, TouchEventType type); //切换到领奖层
//----------宝藏---------//
void OnSwitchToGoldReward(CCObject *pSender, TouchEventType type); //切换到宝箱层
//----------擂台---------//
void OnSwitchToPvP(CCObject *pSender, TouchEventType type); //切换到擂台层
//----------活动---------//
void OnSwitchToActive(CCObject *pSender, TouchEventType type); //切换到活动层
//----------vip大礼---------//
void OnSwitchToVip(CCObject *pSender, TouchEventType type); //切换到vip大礼层
//----------幸运抽奖---------//
void OnSwitchToDraw(CCObject *pSender, TouchEventType type); //切换到幸运抽奖层
//----------好友副本---------//
void OnSwitchToFirendFb(CCObject *pSender, TouchEventType type); //切换到好友副本层
//----------神秘商人---------//
void OnSwitchToShop(CCObject *pSender, TouchEventType type); //切换到神秘商人层
//----------幻兽竞技场---------//
void OnSwitchToPiePvP(CCObject *pSender, TouchEventType type); //切换到幻兽竞技场层
//----------邮件---------//
void OnSwitchToEmail(CCObject *pSender, TouchEventType type); //切换到邮件层
//----------小助手---------//
void OnSwitchToHelp(CCObject *pSender, TouchEventType type); //切换到小助手层
//----------对话框---------//
void OnSwitchTotalk(CCObject *pSender, TouchEventType type); //切换到对话框层
//----------技能升级---------//
void OnSwitchToSkillUp(CCObject *pSender, TouchEventType type); //切换到技能升级层
void OnChooseSkill(CCObject *pSender, TouchEventType type); //选择技能
void OnChooseRole(CCObject *pSender, TouchEventType type); //选择角色
void OnCreateChangeSkillLayer(CCObject *pSender, TouchEventType type); //弹出更换忍术奥义层
void OnRemoveSkillChangeLayer(CCObject *pSender, TouchEventType type); //移除更换忍术层
void OnChangeSkillSelect(CCObject *pSender, TouchEventType type); //选择忍术 (选择忍术页)
void OnChangeSkill(CCObject *pSender, TouchEventType type); //更换选择忍术(选择忍术页)
//----------装备改造---------//
void OnSwitchToEquUp(CCObject *pSender, TouchEventType type); //切换到装备改造层
//----------精英副本---------//
void OnSwitchToExFbPage(CCObject *pSender, TouchEventType type); //切换到精英副本层
void OnExFbPageViewEvent(CCObject* pSender, PageViewEventType type); //精英副本滑动条事件回调
void OnExFbClick(CCObject* pSender, TouchEventType type); //副本按钮响应
//----------普通副本---------//
void OnSwitchToNormalExFbPage(); //切换到普通副本层
void OnNormalFbPageViewEvent(CCObject* pSender, PageViewEventType type); //普通副本滑动条事件回调
void OnNormalFbClick(CCObject* pSender, TouchEventType type); //普通副本按钮响应
void OnNormalFbStartBattleClick(CCObject* pSender, TouchEventType type); //普通副本进入按钮响应
void OnNormalFbFastBattleClick(CCObject* pSender, TouchEventType type); //普通副本扫荡按钮响应
void OnNormalFbInfoCloseClick(CCObject* pSender, TouchEventType type); //关闭普通副本详情
//临时:进入战场按钮
void OnBtnBattleCallBack(CCObject *pSender, TouchEventType type);
/************************************************************************/
/* 好友UI按钮 */
/************************************************************************/
//----------好友按钮回调---------//
void OnBtnFriendSwitchCallBack(CCObject *pSender, TouchEventType type);
void OnBtnFriendCallBack(CCObject *pSender, TouchEventType type);
void OnBtnArroundCallBack(CCObject *pSender, TouchEventType type);
void OnBtnSearchCallBack(CCObject *pSender, TouchEventType type);
public:
//标签
enum
{
enTag3D = 100,
enTagRocker,
enTagStudioMainUiLayer, //主按钮栏层
enTagStudioCurrentChildUiLayer, //当前子功能层
enTagStudioTopUiLayer, //弹出层
enTagRole, //人物
enTagBtn = 10000,
};
};
#endif | [
"[email protected]"
] | |
4e21b4f830c36ffa36139e32ce45dcc53bd51194 | ad90fd7724d8bf72f3e8b3d967799e317769430a | /tests/tests/LayerTest/LayerTest.h | 0dd534a302d29c054a004b95f58692ada8cc60d5 | [] | no_license | geniikw/myFirst2DGame | f71865ec8eabdff35c33b2a013b3afd1711b7776 | d9050e71913000e9147fa3f889d4b6c7c35fda94 | refs/heads/master | 2021-07-09T21:09:57.886694 | 2016-12-15T16:50:51 | 2016-12-15T16:50:51 | 19,765,521 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,090 | h | #ifndef _LAYER_TEST_H_
#define _LAYER_TEST_H_
////----#include "cocos2d.h"
#include "../testBasic.h"
class LayerTest : public CCLayer
{
protected:
std::string m_strTitle;
public:
LayerTest(void);
~LayerTest(void);
virtual std::string title();
virtual void onEnter();
void restartCallback(NSObject* pSender);
void nextCallback(NSObject* pSender);
void backCallback(NSObject* pSender);
};
class LayerTest1 : public LayerTest
{
public:
virtual void onEnter();
virtual std::string title();
void registerWithTouchDispatcher();
void updateSize(CCTouch*touch);
virtual bool ccTouchBegan(CCTouch* touche, UIEvent* event);
virtual void ccTouchMoved(CCTouch* touche, UIEvent* event);
virtual void ccTouchEnded(CCTouch* touche, UIEvent* event);
};
class LayerTest2 : public LayerTest
{
public:
virtual void onEnter();
virtual std::string title();
};
class LayerTestBlend : public LayerTest
{
public:
LayerTestBlend();
void newBlend(ccTime dt);
virtual std::string title();
};
class LayerTestScene : public TestScene
{
public:
virtual void runThisTest();
};
#endif
| [
"[email protected]"
] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.