blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
986 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
145 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
122 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
ce29dfbeeef624a99c4b38ff95278bedcd5ea0ff
27e1b6da5115572e9f433f85c82cb1ef47ce7eb5
/pengo/Crate.h
0a2d1c99fc8b63ed0eaf464b2647bfdd921fba02
[]
no_license
leonardok/zombengo
802eed08b16c4bb2ff1534933a03bd0782dbdaa9
c6becfa3927e37abc12db222a072b2aa563a07fb
refs/heads/master
2021-01-21T12:47:42.887115
2016-03-28T02:32:37
2016-03-28T02:32:37
19,363,060
0
0
null
null
null
null
UTF-8
C++
false
false
190
h
#ifndef CRATE_H #define CRATE_H #include "Entity.h" class Crate : public Entity { public: Crate(); virtual ~Crate(); protected: private: }; #endif // CRATE_H
[ "leokorndorfer@gmail.com" ]
leokorndorfer@gmail.com
0f200ab1536f5f2d2b1ef8b117c88331ecfecad1
c715bfde6dd7771ab127cfe197d735b3cb1bee2e
/Sources/GBuffer.cpp
e223cd21d89d97173557afbb655f4ddc9749d09a
[ "MIT" ]
permissive
jjqcat/capstone-2021-6
4cf7f629a8702026a5266e616ea2f54f8fb4b8aa
bb1a4fbcc15b532fcae13f921139de3fe9f9d477
refs/heads/master
2023-05-04T23:39:34.417384
2021-05-26T11:41:02
2021-05-26T11:41:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,756
cpp
#include "GBuffer.h" GBuffer::GBuffer(unsigned int width, unsigned int height) : m_width(width), m_height(height), m_gBuffer(0), m_pos(0), m_normal(0), m_albedo(0), m_metallicRoughness(0), m_emissiveAO(0), m_depth(0) { } bool GBuffer::Init() { glGenFramebuffers(1, &m_gBuffer); glBindFramebuffer(GL_FRAMEBUFFER, m_gBuffer); glGenTextures(1, &m_pos); glBindTexture(GL_TEXTURE_2D, m_pos); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB32F, m_width, m_height, 0, GL_RGB, GL_FLOAT, nullptr); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_pos, 0); glGenTextures(1, &m_normal); glBindTexture(GL_TEXTURE_2D, m_normal); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB32F, m_width, m_height, 0, GL_RGB, GL_FLOAT, nullptr); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, m_normal, 0); glGenTextures(1, &m_albedo); glBindTexture(GL_TEXTURE_2D, m_albedo); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, m_width, m_height, 0, GL_RGB, GL_FLOAT, nullptr); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2, GL_TEXTURE_2D, m_albedo, 0); glGenTextures(1, &m_metallicRoughness); glBindTexture(GL_TEXTURE_2D, m_metallicRoughness); glTexImage2D(GL_TEXTURE_2D, 0, GL_RG, m_width, m_height, 0, GL_RG, GL_FLOAT, nullptr); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT3, GL_TEXTURE_2D, m_metallicRoughness, 0); glGenTextures(1, &m_emissiveAO); glBindTexture(GL_TEXTURE_2D, m_emissiveAO); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, m_width, m_height, 0, GL_RGBA, GL_FLOAT, nullptr); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT4, GL_TEXTURE_2D, m_emissiveAO, 0); glGenRenderbuffers(1, &m_depth); glBindRenderbuffer(GL_RENDERBUFFER, m_depth); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, m_width, m_height); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, m_depth); return true; } void GBuffer::BindFrameBuffer() { glBindFramebuffer(GL_FRAMEBUFFER, m_gBuffer); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); unsigned int attachments[5] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2, GL_COLOR_ATTACHMENT3, GL_COLOR_ATTACHMENT4 }; glDrawBuffers(5, attachments); } void GBuffer::UnbindFrameBuffer() { glBindFramebuffer(GL_FRAMEBUFFER, 0); } void GBuffer::BindTextures() { glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, m_pos); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, m_normal); glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D, m_albedo); glActiveTexture(GL_TEXTURE3); glBindTexture(GL_TEXTURE_2D, m_metallicRoughness); glActiveTexture(GL_TEXTURE4); glBindTexture(GL_TEXTURE_2D, m_emissiveAO); } void GBuffer::UnbindTextures() { glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, 0); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, 0); glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D, 0); glActiveTexture(GL_TEXTURE3); glBindTexture(GL_TEXTURE_2D, 0); glActiveTexture(GL_TEXTURE4); glBindTexture(GL_TEXTURE_2D, 0); }
[ "noreply@github.com" ]
jjqcat.noreply@github.com
91e34a8367a463b71404b66d6fee4b79cd5a0249
6a1e5a6149056c0a8103d6a35961c716803a382e
/udphandler.cpp
5ba699d6c128e1113ccce9c8242244b550b195c5
[]
no_license
zbot473/LocalSend
9496d77b69e2fe467b10590ef57ffd8fd3b2b574
c29a0f2e1d93a8da9842d6afb02a4bc75d556999
refs/heads/main
2023-01-22T20:19:27.221432
2020-11-23T00:04:54
2020-11-23T00:04:54
315,156,996
1
0
null
null
null
null
UTF-8
C++
false
false
2,474
cpp
#include "udphandler.h" #include <QUdpSocket> #include <QNetworkDatagram> #include <QTimer> #include <QObject> #include <QString> #include <QTextCodec> #include <functional> #include <QNetworkInterface> const int UDP_PORT = 4947; UDPHandler::UDPHandler(bool mobile, QString name, quint16 port){ this->mobile = mobile; this->name = name; tcpServerPort = port; udp = new QUdpSocket(this); udp->bind(QHostAddress::AnyIPv4, UDP_PORT); connect(udp, &QUdpSocket::readyRead, this, &UDPHandler::onMessage); const QHostAddress &localhost = QHostAddress(QHostAddress::LocalHost); for (const QHostAddress &address: QNetworkInterface::allAddresses()) { if (address.protocol() == QAbstractSocket::IPv4Protocol && address != localhost) localIP = address; } discover(); QTimer *timer = new QTimer(this); connect(timer, &QTimer::timeout, this, &UDPHandler::discover); timer->start(5000); } void UDPHandler::onMessage(){ while (udp->hasPendingDatagrams()) { QNetworkDatagram datagram = udp->receiveDatagram(); if (datagram.senderAddress() == localIP) return; QString text = QString::fromUtf8(datagram.data()); if (text == "offline") { emit offline(datagram.senderAddress()); } else { QStringList list = text.split("\t"); if (list.size() == 3) { bool mobile = list[0] == "m"; QString name = list[1]; quint16 port = list[2].toUShort(); deviceInfo newDevice { datagram.senderAddress(), name, mobile, port }; emit discovered(newDevice); } } } } void UDPHandler::discover(){ QString deviceType(mobile ? "m" : "d"); QByteArray message = (deviceType + "\t" + name + "\t" + QString::number(tcpServerPort)).toUtf8(); QNetworkDatagram datagram(message, QHostAddress(QHostAddress::Broadcast), UDP_PORT); udp->writeDatagram(datagram); udp->flush(); } UDPHandler::~UDPHandler(){ QByteArray message = QByteArray("offline"); QNetworkDatagram datagram(message, QHostAddress(QHostAddress::Broadcast), UDP_PORT); udp->writeDatagram(datagram); delete udp; } bool deviceInfo::operator==(const deviceInfo other) { return ip == other.ip && name == other.name && mobile == other.mobile; }
[ "zbot473@gmail.com" ]
zbot473@gmail.com
bd0c05d9bd4f731ad9fb0f79586a7668d860715c
298674d1d63579da8a9d84ba86c97cdcb5a95c66
/int_stack/main.cpp
711e16381ade55eca5420dc40c39411e2789098b
[]
no_license
hsolis11/CPPNotes
ad8d16db876f243873c3482fb6f60e4f5d3811ee
af732a93e2e0288181096bb637ad32ac6db1fc9a
refs/heads/main
2023-07-01T15:07:10.864771
2021-07-30T02:55:12
2021-07-30T02:55:12
387,316,390
0
0
null
null
null
null
UTF-8
C++
false
false
2,267
cpp
/************************************** * Name: Hector Solis * Coding 03 * Purpose: Introduction to a simple ADT(abstract data type) * and understand the function and purpose of ADTs. **************************************/ #include "main.h" int main(int argc, char** argv) { srand(time(NULL)); Stack stack; int peek; cout << "verify stack is empty" << endl; if(stack.isEmpty()){ cout << "Stack is empty" << endl; } else { cout << "Stack is not empty" << endl; } cout << "attempt to peek at empty stack" << endl; try { peek = stack.peek(); cout << "peek element is " << peek << endl; } catch (int e) { cout << "error: Stack Underflow" << endl; } cout << endl; cout << "Fill up stack with random integers range from -100 to 100" << endl; for(int i=1; i < 11; i++){ int random_int = (rand() % 201) - 100; if(stack.push(random_int)){ cout << "Element " << random_int << " Inserted" << endl; cout << "current peek element " << stack.peek() << endl; } else { cout << "error: Stack Overflow" << endl; } } cout << endl; cout << "verify stack is now filled" << endl; if(stack.isEmpty()){ cout << "Stack is empty" << endl; } else { cout << "Stack is not empty" << endl; } cout << endl; cout << "attempt to push 5 additional elements and peek value " << stack.peek() << " should remain unchanged" << endl; for(int i=11; i < 16; i++){ int random_int = (rand() % 201) - 100; cout << "attempting to push element " << random_int << endl; if(!stack.push(random_int)){ cout << "error: Stack Overflow" << endl; }; cout << "peek element is " << stack.peek() << endl; } cout << endl; cout << "attempt to pop up to 15 elements until underflows" << endl; for(int i=1; i < 16; i++){ try { peek = stack.peek(); cout << "current top element " << peek << " to be removed" << endl; cout << stack.pop() << " has been removed" << endl; } catch (int e) { cout << "error: Stack Underflow" << endl; } } return 0; }
[ "hsolis11@outlook.com" ]
hsolis11@outlook.com
0e19a89badab0e8cef305ec1f031f484f37799af
e983bb2f433521dff631e200f82a9787bbefc2dc
/ARCHIVED/CSCE1030/Lab12/Lab12D.cpp
39cbf3a8f8dcdd9e8e408f23ae443ade79f2fc87
[]
no_license
axelyates/unt_csce
051a5242d11d42e249f6f2e67939b72b7cc52453
67b09ae7f3b39d33c5c7c6dadce14748c9a6316d
refs/heads/master
2020-03-19T21:32:44.295888
2018-06-11T15:04:54
2018-06-11T15:04:54
136,942,264
2
0
null
null
null
null
UTF-8
C++
false
false
1,595
cpp
/*Name: Axel Yates Email: axelyates@unt.edu Date: 11/29/15 Instructor: Dr. Thompson Description: This program creates a struct containing variables necessary to calculate users interest based on input.*/ #include <iostream> #include <cmath> using namespace std; struct Loan{ //creating Loan struct with necessary variables in it. int ID; float amount; float rate; int term; }; float payment(Loan loan1); /* Function: payment Parameters: a type named Loan representing a struct declared earlier in function Return: a float representing the users monthly payment Description: This function computes the users monthly payment based on input. */ int main() { Loan loan1; //delcaring necessary variables float monthly_payment; cout << "Enter the ID of this loan: "; //asking user for input to be used in payment function cin >> loan1.ID; cout << "Enter the amount of this loan: "; cin >> loan1.amount; cout << "Enter the annual interest rate of this loan in % (e.g., 5.4): "; cin >> loan1.rate; cout << "Enter the term (number of months, length of loan): "; cin >> loan1.term; monthly_payment = payment(loan1); //passing variables to function cout << "The monthly payment for loan " << loan1.ID << " is: " << monthly_payment << endl; //displaying users loan ID and monthly payment return 0; } float payment(Loan loan1) { loan1.rate = (loan1.rate / 1200); //to convert % yearly rate to monthly fraction return loan1.amount*loan1.rate*(pow((loan1.rate+1), loan1.term)/(pow((loan1.rate+1), loan1.term) - 1)); //calculating users monthly payment }
[ "axelyates@gmail.com" ]
axelyates@gmail.com
747ba94185b80cf8ea651c4cd682e5a1a9f7228c
be7af0cc1c1696931df0cdd25007f5f7d62fe616
/Galaga2.0/Galaga2.0/player.cpp
71bb83b968cbf56b1407064a5f6ae61461ace5de
[]
no_license
minhoolee/id-Tech-Files
c053dc6e4061b57ca9a4c8c5fd65376f45f48bcb
54da95f5a10d6cae973fcebd6a7c00a9b056ba38
refs/heads/master
2021-01-20T16:28:32.885522
2015-07-28T16:25:48
2015-07-28T16:25:48
38,888,532
0
0
null
null
null
null
UTF-8
C++
false
false
2,441
cpp
#include "player.hpp" #include "galagaGame.hpp" Player::Player() : GameObject() {} Player::Player(sf::Vector2f position, GalagaGame *game) : GameObject(position, game) { enabled = true; this->sprite.setTexture(game->mainTexture); this->playerTextureRect = sf::IntRect(15, 52, 20, 20); this->sprite.setTextureRect(playerTextureRect); this->sprite.setScale(3, 3); this->sprite.setOrigin(12.5, 12.5); } void Player::update(sf::Time timeElapsed) { // Image starts pointed left, so rotate it 90 degrees clockwise this->sprite.setRotation(90); // Set different color so that players are obviuos if (game->MULTI_PLAYER) game->player2.sprite.setColor(sf::Color(255, 255, 150)); sf::Vector2f playerMovement(0, 0); if (this->isPlayerMovingUp) playerMovement.y -= PLAYER_SPEED; if (this->isPlayerMovingDown) playerMovement.y += PLAYER_SPEED; if (this->isPlayerMovingLeft) playerMovement.x -= PLAYER_SPEED; if (this->isPlayerMovingRight) playerMovement.x += PLAYER_SPEED; /* // Disable if outside of walls if ( (this->sprite.getPosition().x > 32) && (this->sprite.getPosition().x < game->GAME_WIDTH - 32) ) { if ( (this->sprite.getPosition().y > 32) && (this->sprite.getPosition().y < game->GAME_HEIGHT - 32) ) { //TODO : FIGURE THIS OUT } } */ this->sprite.move(playerMovement * timeElapsed.asSeconds()); if ((this->isPlayerFiring) && (this->shotTimer.getElapsedTime().asSeconds() > 0.25)) { fire(); this->shotTimer.restart(); } } void Player::fire() { game->playerBullets[game->currentBullet].sprite.setPosition(sf::Vector2f(sprite.getPosition().x, sprite.getPosition().y - 32 - 20)); game->playerBullets[game->currentBullet].enabled = true; game->playerBullets[game->currentBullet].velocity = sf::Vector2f(0, BULLET_SPEED); // If bullet not set, set a couple values on it if (game->playerBullets[game->currentBullet].game == NULL) { game->playerBullets[game->currentBullet].game = game; game->playerBullets[game->currentBullet].sprite.setTexture(game->mainTexture); // 0th index because all bullet textures are same } // Check if game is multiplayer and if the bullet was shot by player2 (hack method) //if ( (game->MULTI_PLAYER) && (sprite.getPosition() == game->player2.sprite.getPosition()) ) //game->playerBullets[game->currentBullet].sprite.setColor(sf::Color(255, 255, 150)); game->currentBullet++; if (game->currentBullet == 50) { game->currentBullet = 0; } }
[ "minhoo2000@gmail.com" ]
minhoo2000@gmail.com
7c150106d13a76c588149a95847f5b501e37a606
579e5b34d5bb8f8a633512165c7da6ecc5bb6a4c
/Core/Context.hpp
c7a5ec4939130023762d53d535952d050cc6ee01
[ "MIT" ]
permissive
WeyrSDev/SpaceY
d836777eba7b2f14c8a97475cddac160add956f9
b2ce9be0df85acb534c60ee36678d02801c677b9
refs/heads/master
2021-06-20T08:53:48.615460
2017-07-15T19:12:23
2017-07-15T19:12:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,144
hpp
/* Conrad 'Condzi' Kubacki 2017 https://github.com/condzi */ #pragma once #include <Core/Settings.hpp> namespace sf { class RenderWindow; } namespace con { // Forward declaration. class EntityManager; struct ResourceHolder; class Game; class EntityFactory; class StateStack; class Messenger; /* =============================================================================== Created by: Condzi Special structure that gives you access to core objects: window, entityManager, resourceCache, settings, entityFactory, stateStack and game. Most of them requires to include it's file (e.g resourceCache requires to use include <Core/resourceManaging/ResourceHolder.hpp>). =============================================================================== */ struct Context final { sf::RenderWindow* window = nullptr; EntityManager* entityManager = nullptr; ResourceHolder* resourceCache = nullptr; Settings<SETTINGS_ENGINE>* settingsEngine = nullptr; Settings<SETTINGS_GAME>* settingsGame = nullptr; EntityFactory* entityFactory = nullptr; StateStack* stateStack = nullptr; Messenger* messenger = nullptr; Game* game = nullptr; }; }
[ "Condzi@users.noreply.github.com" ]
Condzi@users.noreply.github.com
a45fb17a1d98e671a9a7ac22c7da580ac8a37dcf
601b73264af6a846824b5f6a5cb9abb764e9728a
/src/body_utility.h
a2e641b92267cd0e4af7e6e492d7239dd08bb5f5
[ "MIT" ]
permissive
rjsanx/nbody-simulation
436918df10fbb0d440189a781fb2efa1b28167c8
ec3d7dd4e6626e1c34154faddd6774840ea645c7
refs/heads/master
2022-04-09T16:52:14.664668
2020-03-15T23:28:42
2020-03-15T23:28:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,155
h
#ifndef body_utility_h #define body_utility_h #include "body.h" #include "ofMain.h" #include <math.h> #include <stdio.h> /* Class for a body interaction functions in the simulation. This includes distance, velocity interaction, conservation of momentum, collision handling, and collision detection. */ class BodyUtility { public: /* Will return the magnitude of the distance between the two given bodies (a) and (b) in the 3D space. */ static double Distance(Body a, Body b); /* This function will find the impact of the gravitational acceleration on the velocity on the first body (a) from the second body (b). Specifically, it uses the force equation: F = m1 m2 G / |r|^3 * r, where we can cancel the masses from F=ma to find that a = m2 G / |r|^3 * r. Multiply this acceleration with the given time step (time_step) to find and return the change in velocity on the first body (a). */ static Vector VelocityInteraction(Body a, Body b, double time_step); /* To conserve momentum between two bodies, use the given masses (m1) and (m2) as well as corresponding velocity vectors in 3D space (v1) and (v2) and use the equation ((m1 v1) + (m2 v2)) / (m1 + m2) to calculate the velocity in the corresponding component for the combined body. */ static double ConserveMomentum(double m1, double m2, double v1, double v2); /* Will handle collision between two bodies by combining the two given bodies (a) and (b) together. This is done by calculating each component of velocity (x, y, z) for the final body using the conservation of momentum and adding the mass. For the visual simulation, the radius of the larger body is used for the new body. */ static Body Collision(Body a, Body b); /* Detection if the two given bodies (a) and (b) are in the same position. This is calculated by determining if the planets are 'touching' by adding the radii with each other and finding if it is larger than the distance between the two bodies. */ static bool SamePosition(Body a, Body b); }; #endif /* body_utility_hpp */
[ "aggarwal.neeraj141@gmail.com" ]
aggarwal.neeraj141@gmail.com
cc5a31354d31549b75da882958755742591205f4
b5c50f867bdd587d726d49d53b3b032ac0e0f67f
/storyTeller/Classes/Scene/Game.hpp
e99e21d6bbc7e68523e80b60215c92b647f44f89
[ "MIT" ]
permissive
tonosamagaeru/Project-StoryTeller-
b810dfad154ecdc22fb92ab8ef8b2146b02750ea
828b086b1e32234ba93ca6843a48a484839e0087
refs/heads/master
2021-01-16T22:28:26.186521
2016-09-03T09:32:34
2016-09-03T09:32:34
56,220,028
0
0
null
2016-06-30T05:49:22
2016-04-14T08:23:42
C++
UTF-8
C++
false
false
156
hpp
// // Game.hpp // storyTeller // // Created by vantan on 2016/06/29. // // #ifndef Game_hpp #define Game_hpp #include <stdio.h> #endif /* Game_hpp */
[ "noritomodayo@gmail.com" ]
noritomodayo@gmail.com
f3d729a2d8819f3a3027aa4a55f80838f21fd5a9
84db845cc485c91e6dbc44e4944a85d27518c9a8
/2018/KMP_DP/b.cpp
f46284ab450dc8de5e77f11561b9fc9e0585f582
[]
no_license
sunyinkai/ACM_ICPC
c13398c6963f0267db282e71d11baaf7ff619c71
8e54240df29b4a722efd27b5866384ba84f859a4
refs/heads/master
2021-07-07T07:39:36.553203
2020-07-26T06:50:54
2020-07-26T06:50:54
158,057,635
2
0
null
null
null
null
UTF-8
C++
false
false
1,148
cpp
#include<cstdio> #include<cstring> const int MAXN=1007,MAXM=12; double dp[MAXN][MAXM]; //dp[i][j]:在第i个操作后已经匹配目标字符串的位置的个数 double p[MAXN]; char s[MAXM]; int next[MAXM]; int N,M,C; void getNext(){ int i=0,j=next[0]=-1; while(i<M){ while(j!=-1&&s[i]!=s[j])j=next[j]; next[++i]=++j; } //for(int i=0;i<M;++i) printf("%d\n",next[i]); } int main(){ while(~scanf("%d%d",&C,&N)&&N+C){ getchar(); memset(p,0,sizeof(p)); for(int i=0;i<C;++i){ char ch=getchar(); double p0; scanf("%lf",&p0); p[ch]=p0; getchar(); } scanf("%s",s); M=strlen(s); getNext(); //DP memset(dp,0,sizeof(dp)); dp[0][0]=100.0; for(int i=0;i<N;++i){ for(int j=0;j<M&&j<=i;++j){ for(int k='a';k<='z';++k){ if(!p[k])continue; if(s[j]==k)dp[i+1][j+1]+=dp[i][j]*p[k];//match else{ //next数组 int t=j; while(t!=-1&&s[t]!=k)t=next[t]; dp[i+1][t+1]+=p[k]*dp[i][j]; } } } //感觉前面已经组成了目标字符串的不好处理 } double ans=0.0; for(int i=0;i<=N;++i)ans+=dp[i][M]; printf("%.2f%%\n",ans); } return 0; }
[ "1091491336@qq.com" ]
1091491336@qq.com
56659f6b79598e6f4b058ba94ece828225119e19
84a55714ce7f1fa026f554ab631c9b30ad80d94d
/msvc/handle_data.cpp
e32977a4ef481ba5ee7389bcff79066fd1b4539e
[]
no_license
casterbn/my_program
d16499797aaf9e402394141f85b23e60dab343c2
52ff4bb3c5709a1c023d69d8697ba0810b3bf52b
refs/heads/master
2022-04-02T13:12:37.580488
2020-02-11T05:14:51
2020-02-11T05:14:51
null
0
0
null
null
null
null
GB18030
C++
false
false
15,460
cpp
#include <ctype.h> #include "handle_data.h" #include <io.h> void safe_free(void *ptr) { if (ptr != NULL) { free(ptr); ptr == NULL; } } /* * 去除字符串右端空格 */ char *strtrimr(char *pstr) { int i; i = strlen(pstr) - 1; while(isspace(pstr[i]) && (i >= 0)) { pstr[i--] = '\0'; } return pstr; } /* * 去除字符串左端空格 */ char *strtriml(char *pstr) { int i = 0, j; j = strlen(pstr) - 1; while(isspace(pstr[i]) && (i <= j)) { i++; } if(0 < i) { strcpy(pstr, &pstr[i]); } return pstr; } /* * 去除字符串空格 */ char *strtrimall(char *pstr) //p ' ' q vallue { char cmp[2048]; int j = 0; int len1 = strlen(pstr); //int len = 0; for(int i = 0;i < strlen(pstr) - 1;i++) { if(*(pstr + i) != ' ') { cmp[j++] = *(pstr + i); } } cmp[j] = '\0'; strncpy(pstr,cmp,j); int len2 = strlen(pstr); int count = len1 - len2; printf("1111 pstr = %s",pstr); //return count; #if 0 while (*pstr != ' ') { if (*pstr == '\0') { return; } pstr++; } int len1 = strlen(pstr); printf("len1 = %d\n",len1); char *p,*q; p = pstr; while(*p!=' ') p++; q = p; while(1) { while(*q == ' '||*q != '\0') q++; if(*q == '\0') { *p = *q; break; } else { *p = *q; *q = ' '; q++; p++; } } int len2 = strlen(pstr); int count = len1 - len2; printf("1111 pstr = %s",pstr); return count; #endif } /* *去除字符串两端空格 */ char *strtrim(char *pstr) { char *p; p = strtrimr(pstr); return strtriml(p); } /* *从文件的一行读出key或value,返回item指针 *line--从配置文件读出的一行 */ int get_item_from_line(char *line, ITEM *item) { char *p = strtrim(line); //char *p = line; int len = strlen(p); if(len <= 0) { return 1;//空行 } else if(p[0] == '#') { return 2; } else { char *p2 = strchr(p, '='); *p2++ = '\0'; item->key = (char *)malloc(strlen(p) + 1); item->value = (char *)malloc(strlen(p2) + 1); strcpy(item->key, p); strcpy(item->value, p2); } return 0;//查询成功 } int file_to_items(const char *file, ITEM *items, int *num) { char line[2048]; FILE *fp; fp = fopen(file, "r"); if(fp == NULL) { return 1; } int i = 0; while(fgets(line, 2047, fp)) { char *p = strtrim(line); int len = strlen(p); if(len <= 0) { continue; } else if(p[0] == '#') { continue; } else { char *p2 = strchr(p, '='); /*这里认为只有key没什么意义*/ if(p2 == NULL) { continue; } *p2++ = '\0'; items[i].key = (char *)malloc(strlen(p) + 1); items[i].value = (char *)malloc(strlen(p2) + 1); strcpy(items[i].key, p); strcpy(items[i].value, p2); i++; } } (*num) = i; fclose(fp); return 0; } FILE *read_conf_pre(const char *file) { FILE *fp =NULL ; fp = fopen(file, "r"); return fp; } int read_conf_ok(FILE *fp) { fclose(fp); fp= NULL; return 1; } long read_timer_value(const char *key, FILE *fp) { char line[2048] = { 0 }; int value = 0; if(fp == NULL) { return -1; } //fgets(line, 2047, fp); //printf("*********** = %s\n", fgets(line, 2048, fp)); if(fgets(line, 2048, fp) != NULL) { ITEM item; get_item_from_line(line, &item); //printf("item.key = %s\n",item.key); //printf("key = %s\n",key); if(strcmp(item.key, key) == 0) { //printf("match\n"); value = atoi(item.value); //printf("value = %lf\n",value); safe_free(item.key); safe_free(item.value); //break; } else { //printf("not match\n"); } } else { printf("time file end\n"); } return value; } float read_ins_value(const char *key, FILE *fp) { char line[2048]; float value = 0; int rec = -1; if(fp == NULL) { return -1; } if(fgets(line, 2047, fp) != NULL) { ITEM item; get_item_from_line(line, &item); //printf("item.key = %s\n",item.key); //printf("item.value = %s\n",item.value); //printf("key = %s\n",key); if(strcmp(item.key, key) == 0) { value = atof(item.value); safe_free(item.key); safe_free(item.value); //break; } else { printf("not match\n"); } } else { printf("gns file end\n"); } return value; } int StringToHex(char *str, unsigned char *out, unsigned int *outlen) { char *p = str; char high = 0, low = 0; int tmplen = strlen(p), cnt = 0; tmplen = strlen(p); while(cnt < (tmplen / 2)) { high = ((*p > '9') && ((*p <= 'F') || (*p <= 'f'))) ? *p - 48 - 7 : *p - 48; low = (*(++ p) > '9' && ((*p <= 'F') || (*p <= 'f'))) ? *(p) - 48 - 7 : *(p) - 48; out[cnt] = ((high & 0x0f) << 4 | (low & 0x0f)); p ++; cnt ++; } if(tmplen % 2 != 0) out[cnt] = ((*p > '9') && ((*p <= 'F') || (*p <= 'f'))) ? *p - 48 - 7 : *p - 48; if(outlen != NULL) *outlen = tmplen / 2 + tmplen % 2; return tmplen / 2 + tmplen % 2; } int first_read_rtk = 0; int read_gps_data(const char *key, FILE *fp, unsigned char** gps_data,int* len) { char line[2048]; float value = 0; char* value_trim; //int valid_len = 0; unsigned char data[2048] = {0}; int rec = 1; if(fp == NULL) { return -1; } //fgets(line, 2047, fp); if(fgets(line, 2047, fp) != NULL) { ITEM item; get_item_from_line(line, &item); //printf("item.value = %s\n",item.value); if(strcmp(item.key, key) == 0) { int j = 0; if(strcmp(item.value,"null") == 0) { return -1; } for(int i = 0;i < strlen(item.value) - 1;i++) { if(*(item.value + i) != ' ') { unsigned int out_len = 0; char cut[2]; strncpy(cut, item.value + i, 2); StringToHex(cut, data + (*len), &out_len); (*len)++; i++; //取两个字符 } } //printf("111cur_len = %d\n",*len); //printf("valid_len = %d\n",(*len)); //*gps_data = (unsigned char*)malloc((*len) * sizeof(char)); if (first_read_rtk == 0) { int offset; for (offset = 0; offset < *len - 1; offset++) { if ((data[offset] == 0xd3) && (data[offset + 1] == 0x00)) break; } //first_read_rtk = 1; if (offset < *len - 1) { (*len) -= offset; // printf("11111111111111 offset = %d\n", offset); // printf("len offset = %d\n", (*len)); *gps_data = (unsigned char*)malloc((*len) * sizeof(char)); memcpy(*gps_data, data + offset, (*len)); } else { //printf("test 1111111111111\n"); rec = -1; //本包无有效数据 } } else { memcpy(*gps_data, data, (*len)); } safe_free(item.key); safe_free(item.value); //break; } else { printf("not match\n"); } } else { printf("gps file end\n"); } return rec; } FILE *write_conf_pre(const char *file) { FILE *fp; fp = fopen(file, "w"); return fp; } int write_conf_value(const char *key, float value, FILE *fp) { char a[30] = {'\0'}; sprintf(a, "%.4f", value); fprintf(fp, "%s=%s\n", key, a); return 0; } int write_conf_ok(FILE *fp) { fclose(fp); return 1; } void file_return(FILE * fp, int last_offset) { long cur_offset = ftell(fp); fseek(fp,last_offset - cur_offset,SEEK_CUR); //退出时返回入口文件偏移处 //fseek(fp, last_offset - cur_offset - 8, SEEK_CUR); //退出时返回入口文件偏移处 windows 此处有问题 //DbgPrintf("cur_offset000000000000000000 = %ld\n",cur_offset); } #if 0 int line_read(FILE * fp, long line, int last_offset, unsigned char** gps_data, int* data_len) { (*data_len) = 0; //重新赋值为0 if (fp == NULL) return -1; char buf[4096]; int nread = 0, count = 0; //long lastseek = 0, size=0; char *pch = NULL, *pstr = NULL; memset(buf, 0, 4096); unsigned char data[2048] = { 0 }; int len = 0; static int search_count = 0; int offset = 0; while (1) { fgets(buf, 2047, fp); if (feof(fp)) { printf("FEOF!\n"); //file_return(fp,last_offset); //exit; return -1; } //if(nread >= 0) if (strstr(buf, "gps_data") == NULL) //不是gps数据行 { continue; } else { int i = 0; pstr = buf; //printf("pstr = %s\n",pstr); if (strstr(buf, "gps_data=null") == NULL) //gps数据非空 { pstr = buf; int next_len; //char* gps_null_dec = (char*)malloc(sizeof(char) * 4); //判断gps数据是否为空 handle_gps_string(fp, pstr, last_offset, gps_data, data_len); //printf("data_len = %d\n",*data_len); #if 1 for (offset = 0; offset < *data_len - 1; offset++) { if ((*(*gps_data + offset) == 0xd3) && (*(*gps_data + offset) == 0x00)) break; } //first_read_rtk = 1; if (offset < *data_len - 1) { memcpy(*gps_data, data + offset, (*data_len) - offset); //当前为完整包 *data_len -= offset; return 1; } else //也不是完整包 { #if 1 //return -1; //本包无有效数据 fgets(buf, 2047, fp); if (feof(fp)) { printf("FEOF!\n"); //file_return(fp,last_offset); //exit; return -1; } //if(nread >= 0) if (strstr(buf, "gps_data") == NULL) //不是gps数据行 { continue; } else { pstr = buf; //printf("pstr = %s\n",pstr); if (strstr(buf, "gps_data=null") == NULL) //gps数据非空 { pstr = buf; int next_len; //char* gps_null_dec = (char*)malloc(sizeof(char) * 4); //判断gps数据是否为空 handle_gps_string(fp, pstr, last_offset, gps_data, data_len); } } #endif #endif //return 1; } //else { } } } } } #endif int line_read(FILE * fp, long line, int last_offset, unsigned char** gps_data, int* data_len) { (*data_len) = 0; //重新赋值为0 if(fp == NULL) return -1; char buf[4096]; int nread = 0, count = 0 ; //long lastseek = 0, size=0; char *pch = NULL, *pstr = NULL; memset(buf, 0, 4096); unsigned char data[2048] = {0}; int len = 0; static int search_count = 0; while(1) { fgets(buf, 2047, fp); if(feof(fp)) { printf("FEOF!\n"); //file_return(fp,last_offset); //exit; return -1; } //if(nread >= 0) if(strstr(buf,"gps_data") == NULL) //不是gps数据行 { continue; } else { int i = 0; pstr = buf; //printf("pstr = %s\n",pstr); if(strstr(buf,"gps_data=null") == NULL) //gps数据非空 { pstr = buf; int next_len; //char* gps_null_dec = (char*)malloc(sizeof(char) * 4); //判断gps数据是否为空 handle_gps_string(fp,pstr,last_offset,gps_data,data_len); printf("data_len = %d\n",*data_len); return 1; } else { } } } } int line_read(FILE * fp, unsigned int line, int last_offset, unsigned char** gps_data, int* data_len) { (*data_len) = 0; //重新赋值为0 if (fp == NULL) return -1; char buf[4096]; int nread = 0, count = 0; //long lastseek = 0, size=0; char *pch = NULL, *pstr = NULL; memset(buf, 0, 4096); unsigned char data[2048] = { 0 }; int len = 0; static int search_count = 0; while (1) { fgets(buf, 2047, fp); if (feof(fp)) { printf("FEOF!\n"); //file_return(fp,last_offset); //exit; return -1; } //if(nread >= 0) if (strstr(buf, "gps_data") == NULL) //不是gps数据行 { continue; } else { int i = 0; pstr = buf; //printf("pstr = %s\n",pstr); if (strstr(buf, "gps_data=null") == NULL) //gps数据非空 { pstr = buf; int next_len; //char* gps_null_dec = (char*)malloc(sizeof(char) * 4); //判断gps数据是否为空 handle_gps_string(fp, pstr, last_offset, gps_data, data_len); printf("data_len = %d\n", *data_len); return 1; } else { } } } } void handle_gps_string(FILE * fp, char* pstr,int last_offset,unsigned char** gps_data,int* data_len) { ITEM item; unsigned char data[4096] = {0}; int len = 0; get_item_from_line(pstr, &item); if(strcmp(item.key, "gps_data") == 0) { int j = 0; if(strcmp(item.value,"null") == 0) { return ; } //printf("111item.value = %s\n",item.value); for(int i = 0;i < strlen(item.value) - 1;i++) { if(*(item.value + i) != ' ') { char cut[2]; unsigned int hex_len = 0; strncpy(cut, item.value + i, 2); //printf("cut , %d = %s\n",i,cut); StringToHex(cut, data + (*data_len), &hex_len); (*data_len)++; i++; //取两个字符 } } *gps_data = (unsigned char*)malloc((*data_len) * sizeof(char)); memcpy(*gps_data,data,(*data_len)); safe_free(item.key); safe_free(item.value); //break; } else { printf("not match\n"); } file_return(fp,last_offset); //fclose(fp); //return 1; } char file_name[30][80]; int file_count; void listFiles(const char * dir) { intptr_t handle; _finddata_t findData; handle = _findfirst(dir, &findData); // 查找目录中的第一个文件 int i; if (handle == -1) { printf("Failed to find first file!\n"); return; } do { if (findData.attrib & _A_SUBDIR && strcmp(findData.name, ".") == 0 && strcmp(findData.name, "..") == 0 ) // 是否是子目录并且不为"."或".." //printf("findData.name = %s\n", findData.name); { } else { //printf("findData.name = %s,findData.size = %d\n", findData.name, findData.size); if (strstr(findData.name, ".txt") != NULL) { memcpy(file_name[file_count++], findData.name, strlen(findData.name)); printf("find txt\n"); } } } while (_findnext(handle, &findData) == 0); // 查找目录中的下一个文件 printf("find done\n"); _findclose(handle); // 关闭搜索句柄 }
[ "41727862+geqian@users.noreply.github.com" ]
41727862+geqian@users.noreply.github.com
f558068b1ed2f1945cc12712614554e6cfdd09db
81f2c85741db2d56e962429f29a3e3ead1253f1a
/arduinoCode/Invensense_ICM30630_eMD_ArduinoZero_1/src/ArduinoEmdAdapter.cpp
2a56cdb26f75c8231f610a80722f776b0bf07034
[]
no_license
harrythespartan9/upenn_quadrotor_share
c2a17154f60d4179cc42a2073ab0ec31654b3833
cd8a50b62a1d8b09c6124a6d1a31e53df92e9e8b
refs/heads/master
2020-07-25T01:56:48.129261
2016-08-20T01:44:42
2016-08-20T01:44:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,308
cpp
/* * ________________________________________________________________________________________________________ * Copyright (c) 2015-2015 InvenSense Inc. All rights reserved. * * This software, related documentation and any modifications thereto (collectively “Software”) is subject * to InvenSense and its licensors' intellectual property rights under U.S. and international copyright * and other intellectual property rights laws. * * InvenSense and its licensors retain all intellectual property and proprietary rights in and to the Software * and any use, reproduction, disclosure or distribution of the Software without an express license agreement * from InvenSense is strictly prohibited. * * EXCEPT AS OTHERWISE PROVIDED IN A LICENSE AGREEMENT BETWEEN THE PARTIES, 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 NON-INFRINGEMENT. * EXCEPT AS OTHERWISE PROVIDED IN A LICENSE AGREEMENT BETWEEN THE PARTIES, IN NO EVENT SHALL * INVENSENSE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * OF THE SOFTWARE. * ________________________________________________________________________________________________________ */ // Warning are processed as error #pragma GCC diagnostic push #pragma GCC diagnostic warning "-Werror" #include "ArduinoEmdAdapter.h" #include "Invn/Utils/Message.h" #include "DeviceIoHal.h" #include <Arduino.h> #include <stdint.h> #include <stdio.h> #include <assert.h> #include <string.h> #define MAX_SPI_TRANSACTION INV_ARDUINO_EMD_ADAPTER_SERIF_MAX_TRANSACTION_SIZE #define READ_BIT 0x80 static int spi_clock = INV_ARDUINO_EMD_ADAPTER_SPI_CLOCK_DEFAULT; // serif instance for arduino static const inv_host_serif_t arduino_emd_serif_instance = { inv_arduino_emd_adapter_open, inv_arduino_emd_adapter_close, inv_arduino_emd_adapter_read_reg, inv_arduino_emd_adapter_write_reg, inv_arduino_emd_adapter_register_interrupt_callback, INV_ARDUINO_EMD_ADAPTER_SERIF_MAX_TRANSACTION_SIZE, INV_ARDUINO_EMD_ADAPTER_SERIF_TYPE, }; const inv_host_serif_t * inv_arduino_emd_adapter_get_instance(void) { return &arduino_emd_serif_instance; } void inv_arduino_emd_adapter_set_spi_clock(uint16_t clock) { spi_clock = clock; } int inv_arduino_emd_adapter_open(void) { return(inv_device_io_hal_init()); } int inv_arduino_emd_adapter_close(void) { return(inv_device_io_hal_close()); } int inv_arduino_emd_adapter_read_reg(uint8_t reg, uint8_t * rbuffer, uint32_t rlen) { int rc; rc = inv_device_io_hal_reg_read(reg, rbuffer, rlen); return rc; } int inv_arduino_emd_adapter_write_reg(uint8_t reg, const uint8_t * wbuffer, uint32_t wlen) { int rc; rc = inv_device_io_hal_reg_write(reg, wbuffer, wlen); return rc; } int inv_arduino_emd_adapter_register_interrupt_callback(void (*interrupt_cb)(void * context, int int_num), void * context) { int rc; rc = inv_device_io_hal_register_interrupt_callback(interrupt_cb, context); return rc; }
[ "maxw14k@gmail.com" ]
maxw14k@gmail.com
df7774264e6b5cd4691bf8dcf2f4578f0fa1afbd
c2e97b1aacb1e9a7a925b60129d7171a17d4d4d8
/libs/tbb44_20150728oss/examples/parallel_do/parallel_preorder/Matrix.h
9576512a67be7e7a7fdb929b7db786a55bc79fa6
[ "mif-exception", "GPL-1.0-or-later", "GPL-2.0-only", "Zlib" ]
permissive
Ushio/ofxExtremeGpuVideo
1500ba6fd57e9bca3400ebfc005e1338138345a0
0842679c0cba590cc13f4a401887e8e3a3a3311c
refs/heads/master
2022-05-04T17:36:10.936866
2022-04-22T05:50:17
2022-04-22T05:50:17
55,229,467
63
7
Zlib
2022-04-22T05:50:17
2016-04-01T12:06:13
C++
UTF-8
C++
false
false
2,656
h
/* Copyright 2005-2015 Intel Corporation. All Rights Reserved. This file is part of Threading Building Blocks. Threading Building Blocks is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. Threading Building Blocks 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 Threading Building Blocks; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA As a special exception, you may use this file as part of a free software library without restriction. Specifically, if other files instantiate templates or use macros or inline functions from this file, or you compile this file and link it with other files to produce an executable, this file does not by itself cause the resulting executable to be covered by the GNU General Public License. This exception does not however invalidate any other reasons why the executable file might be covered by the GNU General Public License. */ class Matrix { static const int n = 20; float array[n][n]; public: Matrix() {} Matrix( float z ) { for( int i=0; i<n; ++i ) for( int j=0; j<n; ++j ) array[i][j] = i==j ? z : 0; } friend Matrix operator-( const Matrix& x ) { Matrix result; for( int i=0; i<n; ++i ) for( int j=0; j<n; ++j ) result.array[i][j] = -x.array[i][j]; return result; } friend Matrix operator+( const Matrix& x, const Matrix& y ) { Matrix result; for( int i=0; i<n; ++i ) for( int j=0; j<n; ++j ) result.array[i][j] = x.array[i][j] + y.array[i][j]; return result; } friend Matrix operator-( const Matrix& x, const Matrix& y ) { Matrix result; for( int i=0; i<n; ++i ) for( int j=0; j<n; ++j ) result.array[i][j] = x.array[i][j] - y.array[i][j]; return result; } friend Matrix operator*( const Matrix& x, const Matrix& y ) { Matrix result(0); for( int i=0; i<n; ++i ) for( int k=0; k<n; ++k ) for( int j=0; j<n; ++j ) result.array[i][j] += x.array[i][k] * y.array[k][j]; return result; } };
[ "ushiostarfish@gmail.com" ]
ushiostarfish@gmail.com
54ac976e5d0a1a7aa4a0a7cafe9b451c6a4a44c9
cfee8d64efaf907df32e56e41801d851b656764c
/modules/gpu/src/cascadeclassifier.cpp
1f277f0cf7e07091c8075be5e826cdfd07e4f236
[]
no_license
jkammerl/opencv
edf96c61bc88ed228ecd2e5925a4434c7906da78
27c2aa3a4ed54b4dfc391f441e0e071a9253e62d
refs/heads/master
2020-11-30T16:22:08.806574
2012-08-02T12:25:30
2012-08-02T12:25:30
5,273,790
1
0
null
null
null
null
UTF-8
C++
false
false
37,353
cpp
/*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. // 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 GpuMaterials 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 bpied warranties, including, but not limited to, the bpied // 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*/ #include "precomp.hpp" #include <vector> #include <iostream> using namespace cv; using namespace cv::gpu; using namespace std; #if !defined (HAVE_CUDA) cv::gpu::CascadeClassifier_GPU::CascadeClassifier_GPU() { throw_nogpu(); } cv::gpu::CascadeClassifier_GPU::CascadeClassifier_GPU(const string&) { throw_nogpu(); } cv::gpu::CascadeClassifier_GPU::~CascadeClassifier_GPU() { throw_nogpu(); } bool cv::gpu::CascadeClassifier_GPU::empty() const { throw_nogpu(); return true; } bool cv::gpu::CascadeClassifier_GPU::load(const string&) { throw_nogpu(); return true; } Size cv::gpu::CascadeClassifier_GPU::getClassifierSize() const { throw_nogpu(); return Size();} void cv::gpu::CascadeClassifier_GPU::release() { throw_nogpu(); } int cv::gpu::CascadeClassifier_GPU::detectMultiScale( const GpuMat&, GpuMat&, double, int, Size) {throw_nogpu(); return -1;} int cv::gpu::CascadeClassifier_GPU::detectMultiScale( const GpuMat&, GpuMat&, Size, Size, double, int) {throw_nogpu(); return -1;} #else struct cv::gpu::CascadeClassifier_GPU::CascadeClassifierImpl { public: CascadeClassifierImpl(){} virtual ~CascadeClassifierImpl(){} virtual unsigned int process(const GpuMat& src, GpuMat& objects, float scaleStep, int minNeighbors, bool findLargestObject, bool visualizeInPlace, cv::Size ncvMinSize, cv::Size maxObjectSize) = 0; virtual cv::Size getClassifierCvSize() const = 0; virtual bool read(const string& classifierAsXml) = 0; }; struct cv::gpu::CascadeClassifier_GPU::HaarCascade : cv::gpu::CascadeClassifier_GPU::CascadeClassifierImpl { public: HaarCascade() : lastAllocatedFrameSize(-1, -1) { ncvSetDebugOutputHandler(NCVDebugOutputHandler); } bool read(const string& filename) { ncvSafeCall( load(filename) ); return true; } NCVStatus process(const GpuMat& src, GpuMat& objects, float scaleStep, int minNeighbors, bool findLargestObject, bool visualizeInPlace, cv::Size ncvMinSize, /*out*/unsigned int& numDetections) { calculateMemReqsAndAllocate(src.size()); NCVMemPtr src_beg; src_beg.ptr = (void*)src.ptr<Ncv8u>(); src_beg.memtype = NCVMemoryTypeDevice; NCVMemSegment src_seg; src_seg.begin = src_beg; src_seg.size = src.step * src.rows; NCVMatrixReuse<Ncv8u> d_src(src_seg, static_cast<int>(devProp.textureAlignment), src.cols, src.rows, static_cast<int>(src.step), true); ncvAssertReturn(d_src.isMemReused(), NCV_ALLOCATOR_BAD_REUSE); CV_Assert(objects.rows == 1); NCVMemPtr objects_beg; objects_beg.ptr = (void*)objects.ptr<NcvRect32u>(); objects_beg.memtype = NCVMemoryTypeDevice; NCVMemSegment objects_seg; objects_seg.begin = objects_beg; objects_seg.size = objects.step * objects.rows; NCVVectorReuse<NcvRect32u> d_rects(objects_seg, objects.cols); ncvAssertReturn(d_rects.isMemReused(), NCV_ALLOCATOR_BAD_REUSE); NcvSize32u roi; roi.width = d_src.width(); roi.height = d_src.height(); NcvSize32u winMinSize(ncvMinSize.width, ncvMinSize.height); Ncv32u flags = 0; flags |= findLargestObject? NCVPipeObjDet_FindLargestObject : 0; flags |= visualizeInPlace ? NCVPipeObjDet_VisualizeInPlace : 0; ncvStat = ncvDetectObjectsMultiScale_device( d_src, roi, d_rects, numDetections, haar, *h_haarStages, *d_haarStages, *d_haarNodes, *d_haarFeatures, winMinSize, minNeighbors, scaleStep, 1, flags, *gpuAllocator, *cpuAllocator, devProp, 0); ncvAssertReturnNcvStat(ncvStat); ncvAssertCUDAReturn(cudaStreamSynchronize(0), NCV_CUDA_ERROR); return NCV_SUCCESS; } unsigned int process(const GpuMat& image, GpuMat& objectsBuf, float scaleFactor, int minNeighbors, bool findLargestObject, bool visualizeInPlace, cv::Size minSize, cv::Size maxObjectSize) { CV_Assert( scaleFactor > 1 && image.depth() == CV_8U); const int defaultObjSearchNum = 100; if (objectsBuf.empty()) { objectsBuf.create(1, defaultObjSearchNum, DataType<Rect>::type); } cv::Size ncvMinSize = this->getClassifierCvSize(); if (ncvMinSize.width < (unsigned)minSize.width && ncvMinSize.height < (unsigned)minSize.height) { ncvMinSize.width = minSize.width; ncvMinSize.height = minSize.height; } unsigned int numDetections; ncvSafeCall(this->process(image, objectsBuf, (float)scaleFactor, minNeighbors, findLargestObject, visualizeInPlace, ncvMinSize, numDetections)); return numDetections; } cv::Size getClassifierCvSize() const { return cv::Size(haar.ClassifierSize.width, haar.ClassifierSize.height); } private: static void NCVDebugOutputHandler(const std::string &msg) { CV_Error(CV_GpuApiCallError, msg.c_str()); } NCVStatus load(const string& classifierFile) { int devId = cv::gpu::getDevice(); ncvAssertCUDAReturn(cudaGetDeviceProperties(&devProp, devId), NCV_CUDA_ERROR); // Load the classifier from file (assuming its size is about 1 mb) using a simple allocator gpuCascadeAllocator = new NCVMemNativeAllocator(NCVMemoryTypeDevice, static_cast<int>(devProp.textureAlignment)); cpuCascadeAllocator = new NCVMemNativeAllocator(NCVMemoryTypeHostPinned, static_cast<int>(devProp.textureAlignment)); ncvAssertPrintReturn(gpuCascadeAllocator->isInitialized(), "Error creating cascade GPU allocator", NCV_CUDA_ERROR); ncvAssertPrintReturn(cpuCascadeAllocator->isInitialized(), "Error creating cascade CPU allocator", NCV_CUDA_ERROR); Ncv32u haarNumStages, haarNumNodes, haarNumFeatures; ncvStat = ncvHaarGetClassifierSize(classifierFile, haarNumStages, haarNumNodes, haarNumFeatures); ncvAssertPrintReturn(ncvStat == NCV_SUCCESS, "Error reading classifier size (check the file)", NCV_FILE_ERROR); h_haarStages = new NCVVectorAlloc<HaarStage64>(*cpuCascadeAllocator, haarNumStages); h_haarNodes = new NCVVectorAlloc<HaarClassifierNode128>(*cpuCascadeAllocator, haarNumNodes); h_haarFeatures = new NCVVectorAlloc<HaarFeature64>(*cpuCascadeAllocator, haarNumFeatures); ncvAssertPrintReturn(h_haarStages->isMemAllocated(), "Error in cascade CPU allocator", NCV_CUDA_ERROR); ncvAssertPrintReturn(h_haarNodes->isMemAllocated(), "Error in cascade CPU allocator", NCV_CUDA_ERROR); ncvAssertPrintReturn(h_haarFeatures->isMemAllocated(), "Error in cascade CPU allocator", NCV_CUDA_ERROR); ncvStat = ncvHaarLoadFromFile_host(classifierFile, haar, *h_haarStages, *h_haarNodes, *h_haarFeatures); ncvAssertPrintReturn(ncvStat == NCV_SUCCESS, "Error loading classifier", NCV_FILE_ERROR); d_haarStages = new NCVVectorAlloc<HaarStage64>(*gpuCascadeAllocator, haarNumStages); d_haarNodes = new NCVVectorAlloc<HaarClassifierNode128>(*gpuCascadeAllocator, haarNumNodes); d_haarFeatures = new NCVVectorAlloc<HaarFeature64>(*gpuCascadeAllocator, haarNumFeatures); ncvAssertPrintReturn(d_haarStages->isMemAllocated(), "Error in cascade GPU allocator", NCV_CUDA_ERROR); ncvAssertPrintReturn(d_haarNodes->isMemAllocated(), "Error in cascade GPU allocator", NCV_CUDA_ERROR); ncvAssertPrintReturn(d_haarFeatures->isMemAllocated(), "Error in cascade GPU allocator", NCV_CUDA_ERROR); ncvStat = h_haarStages->copySolid(*d_haarStages, 0); ncvAssertPrintReturn(ncvStat == NCV_SUCCESS, "Error copying cascade to GPU", NCV_CUDA_ERROR); ncvStat = h_haarNodes->copySolid(*d_haarNodes, 0); ncvAssertPrintReturn(ncvStat == NCV_SUCCESS, "Error copying cascade to GPU", NCV_CUDA_ERROR); ncvStat = h_haarFeatures->copySolid(*d_haarFeatures, 0); ncvAssertPrintReturn(ncvStat == NCV_SUCCESS, "Error copying cascade to GPU", NCV_CUDA_ERROR); return NCV_SUCCESS; } NCVStatus calculateMemReqsAndAllocate(const Size& frameSize) { if (lastAllocatedFrameSize == frameSize) { return NCV_SUCCESS; } // Calculate memory requirements and create real allocators NCVMemStackAllocator gpuCounter(static_cast<int>(devProp.textureAlignment)); NCVMemStackAllocator cpuCounter(static_cast<int>(devProp.textureAlignment)); ncvAssertPrintReturn(gpuCounter.isInitialized(), "Error creating GPU memory counter", NCV_CUDA_ERROR); ncvAssertPrintReturn(cpuCounter.isInitialized(), "Error creating CPU memory counter", NCV_CUDA_ERROR); NCVMatrixAlloc<Ncv8u> d_src(gpuCounter, frameSize.width, frameSize.height); NCVMatrixAlloc<Ncv8u> h_src(cpuCounter, frameSize.width, frameSize.height); ncvAssertReturn(d_src.isMemAllocated(), NCV_ALLOCATOR_BAD_ALLOC); ncvAssertReturn(h_src.isMemAllocated(), NCV_ALLOCATOR_BAD_ALLOC); NCVVectorAlloc<NcvRect32u> d_rects(gpuCounter, 100); ncvAssertReturn(d_rects.isMemAllocated(), NCV_ALLOCATOR_BAD_ALLOC); NcvSize32u roi; roi.width = d_src.width(); roi.height = d_src.height(); Ncv32u numDetections; ncvStat = ncvDetectObjectsMultiScale_device(d_src, roi, d_rects, numDetections, haar, *h_haarStages, *d_haarStages, *d_haarNodes, *d_haarFeatures, haar.ClassifierSize, 4, 1.2f, 1, 0, gpuCounter, cpuCounter, devProp, 0); ncvAssertReturnNcvStat(ncvStat); ncvAssertCUDAReturn(cudaStreamSynchronize(0), NCV_CUDA_ERROR); gpuAllocator = new NCVMemStackAllocator(NCVMemoryTypeDevice, gpuCounter.maxSize(), static_cast<int>(devProp.textureAlignment)); cpuAllocator = new NCVMemStackAllocator(NCVMemoryTypeHostPinned, cpuCounter.maxSize(), static_cast<int>(devProp.textureAlignment)); ncvAssertPrintReturn(gpuAllocator->isInitialized(), "Error creating GPU memory allocator", NCV_CUDA_ERROR); ncvAssertPrintReturn(cpuAllocator->isInitialized(), "Error creating CPU memory allocator", NCV_CUDA_ERROR); lastAllocatedFrameSize = frameSize; return NCV_SUCCESS; } cudaDeviceProp devProp; NCVStatus ncvStat; Ptr<NCVMemNativeAllocator> gpuCascadeAllocator; Ptr<NCVMemNativeAllocator> cpuCascadeAllocator; Ptr<NCVVectorAlloc<HaarStage64> > h_haarStages; Ptr<NCVVectorAlloc<HaarClassifierNode128> > h_haarNodes; Ptr<NCVVectorAlloc<HaarFeature64> > h_haarFeatures; HaarClassifierCascadeDescriptor haar; Ptr<NCVVectorAlloc<HaarStage64> > d_haarStages; Ptr<NCVVectorAlloc<HaarClassifierNode128> > d_haarNodes; Ptr<NCVVectorAlloc<HaarFeature64> > d_haarFeatures; Size lastAllocatedFrameSize; Ptr<NCVMemStackAllocator> gpuAllocator; Ptr<NCVMemStackAllocator> cpuAllocator; virtual ~HaarCascade(){} }; cv::Size operator -(const cv::Size& a, const cv::Size& b) { return cv::Size(a.width - b.width, a.height - b.height); } cv::Size operator +(const cv::Size& a, const int& i) { return cv::Size(a.width + i, a.height + i); } cv::Size operator *(const cv::Size& a, const float& f) { return cv::Size(cvRound(a.width * f), cvRound(a.height * f)); } cv::Size operator /(const cv::Size& a, const float& f) { return cv::Size(cvRound(a.width / f), cvRound(a.height / f)); } bool operator <=(const cv::Size& a, const cv::Size& b) { return a.width <= b.width && a.height <= b.width; } struct PyrLavel { PyrLavel(int _order, float _scale, cv::Size frame, cv::Size window, cv::Size minObjectSize) { do { order = _order; scale = pow(_scale, order); sFrame = frame / scale; workArea = sFrame - window + 1; sWindow = window * scale; _order++; } while (sWindow <= minObjectSize); } bool isFeasible(cv::Size maxObj) { return workArea.width > 0 && workArea.height > 0 && sWindow <= maxObj; } PyrLavel next(float factor, cv::Size frame, cv::Size window, cv::Size minObjectSize) { return PyrLavel(order + 1, factor, frame, window, minObjectSize); } int order; float scale; cv::Size sFrame; cv::Size workArea; cv::Size sWindow; }; namespace cv { namespace gpu { namespace device { namespace lbp { void classifyPyramid(int frameW, int frameH, int windowW, int windowH, float initalScale, float factor, int total, const DevMem2Db& mstages, const int nstages, const DevMem2Di& mnodes, const DevMem2Df& mleaves, const DevMem2Di& msubsets, const DevMem2Db& mfeatures, const int subsetSize, DevMem2D_<int4> objects, unsigned int* classified, DevMem2Di integral); void connectedConmonents(DevMem2D_<int4> candidates, int ncandidates, DevMem2D_<int4> objects,int groupThreshold, float grouping_eps, unsigned int* nclasses); } }}} struct cv::gpu::CascadeClassifier_GPU::LbpCascade : cv::gpu::CascadeClassifier_GPU::CascadeClassifierImpl { public: struct Stage { int first; int ntrees; float threshold; }; LbpCascade(){} virtual ~LbpCascade(){} virtual unsigned int process(const GpuMat& image, GpuMat& objects, float scaleFactor, int groupThreshold, bool findLargestObject, bool visualizeInPlace, cv::Size minObjectSize, cv::Size maxObjectSize) { CV_Assert(scaleFactor > 1 && image.depth() == CV_8U); const int defaultObjSearchNum = 100; const float grouping_eps = 0.2f; if( !objects.empty() && objects.depth() == CV_32S) objects.reshape(4, 1); else objects.create(1 , image.cols >> 4, CV_32SC4); // used for debug // candidates.setTo(cv::Scalar::all(0)); // objects.setTo(cv::Scalar::all(0)); if (maxObjectSize == cv::Size()) maxObjectSize = image.size(); allocateBuffers(image.size()); unsigned int classified = 0; GpuMat dclassified(1, 1, CV_32S); cudaSafeCall( cudaMemcpy(dclassified.ptr(), &classified, sizeof(int), cudaMemcpyHostToDevice) ); PyrLavel level(0, 1.0f, image.size(), NxM, minObjectSize); while (level.isFeasible(maxObjectSize)) { int acc = level.sFrame.width + 1; float iniScale = level.scale; cv::Size area = level.workArea; int step = 1 + (level.scale <= 2.f); int total = 0, prev = 0; while (acc <= integralFactor * (image.cols + 1) && level.isFeasible(maxObjectSize)) { // create sutable matrix headers GpuMat src = resuzeBuffer(cv::Rect(0, 0, level.sFrame.width, level.sFrame.height)); GpuMat sint = integral(cv::Rect(prev, 0, level.sFrame.width + 1, level.sFrame.height + 1)); GpuMat buff = integralBuffer; // generate integral for scale gpu::resize(image, src, level.sFrame, 0, 0, CV_INTER_LINEAR); gpu::integralBuffered(src, sint, buff); // calculate job int totalWidth = level.workArea.width / step; total += totalWidth * (level.workArea.height / step); // go to next pyramide level level = level.next(scaleFactor, image.size(), NxM, minObjectSize); area = level.workArea; step = (1 + (level.scale <= 2.f)); prev = acc; acc += level.sFrame.width + 1; } device::lbp::classifyPyramid(image.cols, image.rows, NxM.width - 1, NxM.height - 1, iniScale, scaleFactor, total, stage_mat, stage_mat.cols / sizeof(Stage), nodes_mat, leaves_mat, subsets_mat, features_mat, subsetSize, candidates, dclassified.ptr<unsigned int>(), integral); } if (groupThreshold <= 0 || objects.empty()) return 0; cudaSafeCall( cudaMemcpy(&classified, dclassified.ptr(), sizeof(int), cudaMemcpyDeviceToHost) ); device::lbp::connectedConmonents(candidates, classified, objects, groupThreshold, grouping_eps, dclassified.ptr<unsigned int>()); cudaSafeCall( cudaMemcpy(&classified, dclassified.ptr(), sizeof(int), cudaMemcpyDeviceToHost) ); cudaSafeCall( cudaDeviceSynchronize() ); return classified; } virtual cv::Size getClassifierCvSize() const { return NxM; } bool read(const string& classifierAsXml) { FileStorage fs(classifierAsXml, FileStorage::READ); return fs.isOpened() ? read(fs.getFirstTopLevelNode()) : false; } private: void allocateBuffers(cv::Size frame) { if (frame == cv::Size()) return; if (resuzeBuffer.empty() || frame.width > resuzeBuffer.cols || frame.height > resuzeBuffer.rows) { resuzeBuffer.create(frame, CV_8UC1); integral.create(frame.height + 1, integralFactor * (frame.width + 1), CV_32SC1); NcvSize32u roiSize; roiSize.width = frame.width; roiSize.height = frame.height; cudaDeviceProp prop; cudaSafeCall( cudaGetDeviceProperties(&prop, cv::gpu::getDevice()) ); Ncv32u bufSize; ncvSafeCall( nppiStIntegralGetSize_8u32u(roiSize, &bufSize, prop) ); integralBuffer.create(1, bufSize, CV_8UC1); candidates.create(1 , frame.width >> 1, CV_32SC4); } } bool read(const FileNode &root) { const char *GPU_CC_STAGE_TYPE = "stageType"; const char *GPU_CC_FEATURE_TYPE = "featureType"; const char *GPU_CC_BOOST = "BOOST"; const char *GPU_CC_LBP = "LBP"; const char *GPU_CC_MAX_CAT_COUNT = "maxCatCount"; const char *GPU_CC_HEIGHT = "height"; const char *GPU_CC_WIDTH = "width"; const char *GPU_CC_STAGE_PARAMS = "stageParams"; const char *GPU_CC_MAX_DEPTH = "maxDepth"; const char *GPU_CC_FEATURE_PARAMS = "featureParams"; const char *GPU_CC_STAGES = "stages"; const char *GPU_CC_STAGE_THRESHOLD = "stageThreshold"; const float GPU_THRESHOLD_EPS = 1e-5f; const char *GPU_CC_WEAK_CLASSIFIERS = "weakClassifiers"; const char *GPU_CC_INTERNAL_NODES = "internalNodes"; const char *GPU_CC_LEAF_VALUES = "leafValues"; const char *GPU_CC_FEATURES = "features"; const char *GPU_CC_RECT = "rect"; std::string stageTypeStr = (string)root[GPU_CC_STAGE_TYPE]; CV_Assert(stageTypeStr == GPU_CC_BOOST); string featureTypeStr = (string)root[GPU_CC_FEATURE_TYPE]; CV_Assert(featureTypeStr == GPU_CC_LBP); NxM.width = (int)root[GPU_CC_WIDTH]; NxM.height = (int)root[GPU_CC_HEIGHT]; CV_Assert( NxM.height > 0 && NxM.width > 0 ); isStumps = ((int)(root[GPU_CC_STAGE_PARAMS][GPU_CC_MAX_DEPTH]) == 1) ? true : false; CV_Assert(isStumps); FileNode fn = root[GPU_CC_FEATURE_PARAMS]; if (fn.empty()) return false; ncategories = fn[GPU_CC_MAX_CAT_COUNT]; subsetSize = (ncategories + 31) / 32; nodeStep = 3 + ( ncategories > 0 ? subsetSize : 1 ); fn = root[GPU_CC_STAGES]; if (fn.empty()) return false; std::vector<Stage> stages; stages.reserve(fn.size()); std::vector<int> cl_trees; std::vector<int> cl_nodes; std::vector<float> cl_leaves; std::vector<int> subsets; FileNodeIterator it = fn.begin(), it_end = fn.end(); for (size_t si = 0; it != it_end; si++, ++it ) { FileNode fns = *it; Stage st; st.threshold = (float)fns[GPU_CC_STAGE_THRESHOLD] - GPU_THRESHOLD_EPS; fns = fns[GPU_CC_WEAK_CLASSIFIERS]; if (fns.empty()) return false; st.ntrees = (int)fns.size(); st.first = (int)cl_trees.size(); stages.push_back(st);// (int, int, float) cl_trees.reserve(stages[si].first + stages[si].ntrees); // weak trees FileNodeIterator it1 = fns.begin(), it1_end = fns.end(); for ( ; it1 != it1_end; ++it1 ) { FileNode fnw = *it1; FileNode internalNodes = fnw[GPU_CC_INTERNAL_NODES]; FileNode leafValues = fnw[GPU_CC_LEAF_VALUES]; if ( internalNodes.empty() || leafValues.empty() ) return false; int nodeCount = (int)internalNodes.size()/nodeStep; cl_trees.push_back(nodeCount); cl_nodes.reserve((cl_nodes.size() + nodeCount) * 3); cl_leaves.reserve(cl_leaves.size() + leafValues.size()); if( subsetSize > 0 ) subsets.reserve(subsets.size() + nodeCount * subsetSize); // nodes FileNodeIterator iIt = internalNodes.begin(), iEnd = internalNodes.end(); for( ; iIt != iEnd; ) { cl_nodes.push_back((int)*(iIt++)); cl_nodes.push_back((int)*(iIt++)); cl_nodes.push_back((int)*(iIt++)); if( subsetSize > 0 ) for( int j = 0; j < subsetSize; j++, ++iIt ) subsets.push_back((int)*iIt); } // leaves iIt = leafValues.begin(), iEnd = leafValues.end(); for( ; iIt != iEnd; ++iIt ) cl_leaves.push_back((float)*iIt); } } fn = root[GPU_CC_FEATURES]; if( fn.empty() ) return false; std::vector<uchar> features; features.reserve(fn.size() * 4); FileNodeIterator f_it = fn.begin(), f_end = fn.end(); for (; f_it != f_end; ++f_it) { FileNode rect = (*f_it)[GPU_CC_RECT]; FileNodeIterator r_it = rect.begin(); features.push_back(saturate_cast<uchar>((int)*(r_it++))); features.push_back(saturate_cast<uchar>((int)*(r_it++))); features.push_back(saturate_cast<uchar>((int)*(r_it++))); features.push_back(saturate_cast<uchar>((int)*(r_it++))); } // copy data structures on gpu stage_mat.upload(cv::Mat(1, stages.size() * sizeof(Stage), CV_8UC1, (uchar*)&(stages[0]) )); trees_mat.upload(cv::Mat(cl_trees).reshape(1,1)); nodes_mat.upload(cv::Mat(cl_nodes).reshape(1,1)); leaves_mat.upload(cv::Mat(cl_leaves).reshape(1,1)); subsets_mat.upload(cv::Mat(subsets).reshape(1,1)); features_mat.upload(cv::Mat(features).reshape(4,1)); return true; } enum stage { BOOST = 0 }; enum feature { LBP = 1, HAAR = 2 }; static const stage stageType = BOOST; static const feature featureType = LBP; cv::Size NxM; bool isStumps; int ncategories; int subsetSize; int nodeStep; // gpu representation of classifier GpuMat stage_mat; GpuMat trees_mat; GpuMat nodes_mat; GpuMat leaves_mat; GpuMat subsets_mat; GpuMat features_mat; GpuMat integral; GpuMat integralBuffer; GpuMat resuzeBuffer; GpuMat candidates; static const int integralFactor = 4; }; cv::gpu::CascadeClassifier_GPU::CascadeClassifier_GPU() : findLargestObject(false), visualizeInPlace(false), impl(0) {} cv::gpu::CascadeClassifier_GPU::CascadeClassifier_GPU(const string& filename) : findLargestObject(false), visualizeInPlace(false), impl(0) { load(filename); } cv::gpu::CascadeClassifier_GPU::~CascadeClassifier_GPU() { release(); } void cv::gpu::CascadeClassifier_GPU::release() { if (impl) { delete impl; impl = 0; } } bool cv::gpu::CascadeClassifier_GPU::empty() const { return impl == 0; } Size cv::gpu::CascadeClassifier_GPU::getClassifierSize() const { return this->empty() ? Size() : impl->getClassifierCvSize(); } int cv::gpu::CascadeClassifier_GPU::detectMultiScale( const GpuMat& image, GpuMat& objectsBuf, double scaleFactor, int minNeighbors, Size minSize) { CV_Assert( !this->empty()); return impl->process(image, objectsBuf, (float)scaleFactor, minNeighbors, findLargestObject, visualizeInPlace, minSize, cv::Size()); } int cv::gpu::CascadeClassifier_GPU::detectMultiScale(const GpuMat& image, GpuMat& objectsBuf, Size maxObjectSize, Size minSize, double scaleFactor, int minNeighbors) { CV_Assert( !this->empty()); return impl->process(image, objectsBuf, (float)scaleFactor, minNeighbors, findLargestObject, visualizeInPlace, minSize, maxObjectSize); } bool cv::gpu::CascadeClassifier_GPU::load(const string& filename) { release(); std::string fext = filename.substr(filename.find_last_of(".") + 1); std::transform(fext.begin(), fext.end(), fext.begin(), ::tolower); if (fext == "nvbin") { impl = new HaarCascade(); return impl->read(filename); } FileStorage fs(filename, FileStorage::READ); if (!fs.isOpened()) { impl = new HaarCascade(); return impl->read(filename); } const char *GPU_CC_LBP = "LBP"; string featureTypeStr = (string)fs.getFirstTopLevelNode()["featureType"]; if (featureTypeStr == GPU_CC_LBP) impl = new LbpCascade(); else impl = new HaarCascade(); impl->read(filename); return !this->empty(); } ////////////////////////////////////////////////////////////////////////////////////////////////////// struct RectConvert { Rect operator()(const NcvRect32u& nr) const { return Rect(nr.x, nr.y, nr.width, nr.height); } NcvRect32u operator()(const Rect& nr) const { NcvRect32u rect; rect.x = nr.x; rect.y = nr.y; rect.width = nr.width; rect.height = nr.height; return rect; } }; void groupRectangles(std::vector<NcvRect32u> &hypotheses, int groupThreshold, double eps, std::vector<Ncv32u> *weights) { vector<Rect> rects(hypotheses.size()); std::transform(hypotheses.begin(), hypotheses.end(), rects.begin(), RectConvert()); if (weights) { vector<int> weights_int; weights_int.assign(weights->begin(), weights->end()); cv::groupRectangles(rects, weights_int, groupThreshold, eps); } else { cv::groupRectangles(rects, groupThreshold, eps); } std::transform(rects.begin(), rects.end(), hypotheses.begin(), RectConvert()); hypotheses.resize(rects.size()); } NCVStatus loadFromXML(const std::string &filename, HaarClassifierCascadeDescriptor &haar, std::vector<HaarStage64> &haarStages, std::vector<HaarClassifierNode128> &haarClassifierNodes, std::vector<HaarFeature64> &haarFeatures) { NCVStatus ncvStat; haar.NumStages = 0; haar.NumClassifierRootNodes = 0; haar.NumClassifierTotalNodes = 0; haar.NumFeatures = 0; haar.ClassifierSize.width = 0; haar.ClassifierSize.height = 0; haar.bHasStumpsOnly = true; haar.bNeedsTiltedII = false; Ncv32u curMaxTreeDepth; std::vector<char> xmlFileCont; std::vector<HaarClassifierNode128> h_TmpClassifierNotRootNodes; haarStages.resize(0); haarClassifierNodes.resize(0); haarFeatures.resize(0); Ptr<CvHaarClassifierCascade> oldCascade = (CvHaarClassifierCascade*)cvLoad(filename.c_str(), 0, 0, 0); if (oldCascade.empty()) { return NCV_HAAR_XML_LOADING_EXCEPTION; } haar.ClassifierSize.width = oldCascade->orig_window_size.width; haar.ClassifierSize.height = oldCascade->orig_window_size.height; int stagesCound = oldCascade->count; for(int s = 0; s < stagesCound; ++s) // by stages { HaarStage64 curStage; curStage.setStartClassifierRootNodeOffset(static_cast<Ncv32u>(haarClassifierNodes.size())); curStage.setStageThreshold(oldCascade->stage_classifier[s].threshold); int treesCount = oldCascade->stage_classifier[s].count; for(int t = 0; t < treesCount; ++t) // by trees { Ncv32u nodeId = 0; CvHaarClassifier* tree = &oldCascade->stage_classifier[s].classifier[t]; int nodesCount = tree->count; for(int n = 0; n < nodesCount; ++n) //by features { CvHaarFeature* feature = &tree->haar_feature[n]; HaarClassifierNode128 curNode; curNode.setThreshold(tree->threshold[n]); NcvBool bIsLeftNodeLeaf = false; NcvBool bIsRightNodeLeaf = false; HaarClassifierNodeDescriptor32 nodeLeft; if ( tree->left[n] <= 0 ) { Ncv32f leftVal = tree->alpha[-tree->left[n]]; ncvStat = nodeLeft.create(leftVal); ncvAssertReturn(ncvStat == NCV_SUCCESS, ncvStat); bIsLeftNodeLeaf = true; } else { Ncv32u leftNodeOffset = tree->left[n]; nodeLeft.create((Ncv32u)(h_TmpClassifierNotRootNodes.size() + leftNodeOffset - 1)); haar.bHasStumpsOnly = false; } curNode.setLeftNodeDesc(nodeLeft); HaarClassifierNodeDescriptor32 nodeRight; if ( tree->right[n] <= 0 ) { Ncv32f rightVal = tree->alpha[-tree->right[n]]; ncvStat = nodeRight.create(rightVal); ncvAssertReturn(ncvStat == NCV_SUCCESS, ncvStat); bIsRightNodeLeaf = true; } else { Ncv32u rightNodeOffset = tree->right[n]; nodeRight.create((Ncv32u)(h_TmpClassifierNotRootNodes.size() + rightNodeOffset - 1)); haar.bHasStumpsOnly = false; } curNode.setRightNodeDesc(nodeRight); Ncv32u tiltedVal = feature->tilted; haar.bNeedsTiltedII = (tiltedVal != 0); Ncv32u featureId = 0; for(int l = 0; l < CV_HAAR_FEATURE_MAX; ++l) //by rects { Ncv32u rectX = feature->rect[l].r.x; Ncv32u rectY = feature->rect[l].r.y; Ncv32u rectWidth = feature->rect[l].r.width; Ncv32u rectHeight = feature->rect[l].r.height; Ncv32f rectWeight = feature->rect[l].weight; if (rectWeight == 0/* && rectX == 0 &&rectY == 0 && rectWidth == 0 && rectHeight == 0*/) break; HaarFeature64 curFeature; ncvStat = curFeature.setRect(rectX, rectY, rectWidth, rectHeight, haar.ClassifierSize.width, haar.ClassifierSize.height); curFeature.setWeight(rectWeight); ncvAssertReturn(NCV_SUCCESS == ncvStat, ncvStat); haarFeatures.push_back(curFeature); featureId++; } HaarFeatureDescriptor32 tmpFeatureDesc; ncvStat = tmpFeatureDesc.create(haar.bNeedsTiltedII, bIsLeftNodeLeaf, bIsRightNodeLeaf, featureId, static_cast<Ncv32u>(haarFeatures.size()) - featureId); ncvAssertReturn(NCV_SUCCESS == ncvStat, ncvStat); curNode.setFeatureDesc(tmpFeatureDesc); if (!nodeId) { //root node haarClassifierNodes.push_back(curNode); curMaxTreeDepth = 1; } else { //other node h_TmpClassifierNotRootNodes.push_back(curNode); curMaxTreeDepth++; } nodeId++; } } curStage.setNumClassifierRootNodes(treesCount); haarStages.push_back(curStage); } //fill in cascade stats haar.NumStages = static_cast<Ncv32u>(haarStages.size()); haar.NumClassifierRootNodes = static_cast<Ncv32u>(haarClassifierNodes.size()); haar.NumClassifierTotalNodes = static_cast<Ncv32u>(haar.NumClassifierRootNodes + h_TmpClassifierNotRootNodes.size()); haar.NumFeatures = static_cast<Ncv32u>(haarFeatures.size()); //merge root and leaf nodes in one classifiers array Ncv32u offsetRoot = static_cast<Ncv32u>(haarClassifierNodes.size()); for (Ncv32u i=0; i<haarClassifierNodes.size(); i++) { HaarFeatureDescriptor32 featureDesc = haarClassifierNodes[i].getFeatureDesc(); HaarClassifierNodeDescriptor32 nodeLeft = haarClassifierNodes[i].getLeftNodeDesc(); if (!featureDesc.isLeftNodeLeaf()) { Ncv32u newOffset = nodeLeft.getNextNodeOffset() + offsetRoot; nodeLeft.create(newOffset); } haarClassifierNodes[i].setLeftNodeDesc(nodeLeft); HaarClassifierNodeDescriptor32 nodeRight = haarClassifierNodes[i].getRightNodeDesc(); if (!featureDesc.isRightNodeLeaf()) { Ncv32u newOffset = nodeRight.getNextNodeOffset() + offsetRoot; nodeRight.create(newOffset); } haarClassifierNodes[i].setRightNodeDesc(nodeRight); } for (Ncv32u i=0; i<h_TmpClassifierNotRootNodes.size(); i++) { HaarFeatureDescriptor32 featureDesc = h_TmpClassifierNotRootNodes[i].getFeatureDesc(); HaarClassifierNodeDescriptor32 nodeLeft = h_TmpClassifierNotRootNodes[i].getLeftNodeDesc(); if (!featureDesc.isLeftNodeLeaf()) { Ncv32u newOffset = nodeLeft.getNextNodeOffset() + offsetRoot; nodeLeft.create(newOffset); } h_TmpClassifierNotRootNodes[i].setLeftNodeDesc(nodeLeft); HaarClassifierNodeDescriptor32 nodeRight = h_TmpClassifierNotRootNodes[i].getRightNodeDesc(); if (!featureDesc.isRightNodeLeaf()) { Ncv32u newOffset = nodeRight.getNextNodeOffset() + offsetRoot; nodeRight.create(newOffset); } h_TmpClassifierNotRootNodes[i].setRightNodeDesc(nodeRight); haarClassifierNodes.push_back(h_TmpClassifierNotRootNodes[i]); } return NCV_SUCCESS; } #endif /* HAVE_CUDA */
[ "marina.kolpakova@itseez.com" ]
marina.kolpakova@itseez.com
7f52776bba5e5d1102b23a63c5be0e43e96168a9
2ecd5125d4886b09a06741f9b0c41b633c4a1187
/graphviz/main.cpp
d526cbdb7b608ee6ab512c8a0268fca19def3b0b
[]
no_license
toryii/CS106L-1
96e022c0ee13d08e49b3be64d8c92eb697bb14df
a5f61ce99225bc6c392bd82e51a3053452645c45
refs/heads/master
2021-01-20T16:04:08.410303
2013-04-25T23:54:45
2013-04-25T23:54:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,389
cpp
/****************************************************** * File: main.cpp * Author: Darren Hau * ----- * This program implements a Fruchterman-Reingold force-directed layout of a graph. The program * prompts the user for a file, run time, and filter value. The filter value takes in a specified * number of delta_x and delta_y to be averaged in a final delta_avg, simulating inertia. The program * also uses random perturbations to avoid local optimizations. */ #include <iostream> #include <sstream> #include <fstream> #include <cmath> #include <ctime> #include <deque> #include "GraphVisualizer.h" #include "SimpleGraph.h" using namespace std; /* Constants */ const double PI = 3.14159265358979323; const double K_REPEL = 0.001; const double K_ATTRACT = 0.001; /* Function Prototypes */ void Welcome(); string promptUserForFile(string prompt); double promptUserForTime(string prompt); bool promptUserForLoop(string prompt); int promptUserForFilter(string prompt); string toUpperCase(string str); void loadFileToGraph(SimpleGraph & graph, ifstream & stream); void initNodePositions(SimpleGraph & graph, int numNodes); void runFruchtermanReingold(SimpleGraph & graph, double requestedTime, int filterNum); void computeRepelForces(SimpleGraph & graph, vector<double> & dx_tot, vector<double> & dy_tot, int node0, int node1); void computeAttractForces(SimpleGraph & graph, vector<double> & dx_tot, vector<double> & dy_tot, int edgeNum); void filterVelocities(vector<double> & dx_avg, vector<double> & dy_avg, vector< deque<double> > & dx_filter, vector< deque<double> > & dy_filter, vector<double> & dx_tot, vector<double> & dy_tot, int numNodes, int filterNum); /* Main */ int main() { Welcome(); ifstream infile; while (true) { string file = promptUserForFile("Enter file name: "); infile.open(file.c_str()); double requestedTime = promptUserForTime("Enter time: "); int filterNum = promptUserForFilter("Enter a filter value between 1 and 500: "); SimpleGraph graph; loadFileToGraph(graph, infile); InitGraphVisualizer(); runFruchtermanReingold(graph, requestedTime, filterNum); infile.close(); bool loop = promptUserForLoop("Would you like to display another graph?"); if (!loop) break; } return 0; } /* Function: runFruchtermanReingold * Usage: runFruchtermanReingold(graph, requestedTime, filterNum) * ----- * Lays out a graph according to the Fruchterman-Reingold force-directed algorithm. */ void runFruchtermanReingold(SimpleGraph & graph, double requestedTime, int filterNum) { time_t startTime = time(NULL); int numNodes = graph.nodes.size(); // This filter discards the oldest values and pushes in the newest value. vector< deque<double> > dx_filter(numNodes, deque<double>(filterNum)); vector< deque<double> > dy_filter(numNodes, deque<double>(filterNum)); while (true) { DrawGraph(graph); vector<double> dx_tot(numNodes); vector<double> dy_tot(numNodes); for (int i = 0; i < numNodes; i++) { // compute repellent forces for (int j = i+1; j < numNodes; j++) { computeRepelForces(graph, dx_tot, dy_tot, i, j); } } for (int i = 0; i < graph.edges.size(); i++) { // compute attractive forces computeAttractForces(graph, dx_tot, dy_tot, i); } vector<double> dx_avg(numNodes); vector<double> dy_avg(numNodes); filterVelocities(dx_avg, dy_avg, dx_filter, dy_filter, dx_tot, dy_tot, numNodes, filterNum); for (int i = 0; i < numNodes; i++) { // update node positions double randomShift = (double)(rand() % 10) / RAND_MAX; graph.nodes[i].x += dx_avg[i] + randomShift; graph.nodes[i].y += dy_avg[i] - randomShift; } double elapsedTime = difftime(time(NULL), startTime); if (elapsedTime >= requestedTime) break; } } /* Function: filterVelocities * Usage: filterVelocities(dx_avg, dy_avg, dx_filter, dy_filter, dx_tot, dy_tot, numNodes, filterNum) * ----- * Averages the past "filterNum" number of delta_x and delta_y to simulate inertia. */ void filterVelocities(vector<double> & dx_avg, vector<double> & dy_avg, vector< deque<double> > & dx_filter, vector< deque<double> > & dy_filter, vector<double> & dx_tot, vector<double> & dy_tot, int numNodes, int filterNum) { for (int i = 0; i < numNodes; i++) { // filter and average dx and dy dx_filter[i].pop_front(); dx_filter[i].push_back(dx_tot[i]); dy_filter[i].pop_front(); dy_filter[i].push_back(dy_tot[i]); } for (int i = 0; i < numNodes; i++) { for (int j = 0; j < filterNum; j++) { dx_avg[i] += (dx_filter[i])[j]; dy_avg[i] += (dy_filter[i])[j]; } dx_avg[i] = dx_avg[i]/(double)filterNum; dy_avg[i] = dy_avg[i]/(double)filterNum; } } void computeAttractForces(SimpleGraph & graph, vector<double> & dx_tot, vector<double> & dy_tot, int edgeNum) { int node0 = graph.edges[edgeNum].start; int node1 = graph.edges[edgeNum].end; Node n0 = graph.nodes[node0]; Node n1 = graph.nodes[node1]; double f_attract = K_ATTRACT*((n1.x-n0.x)*(n1.x-n0.x) + (n1.y-n0.y)*(n1.y-n0.y)); double theta = atan2(n1.y - n0.y, n1.x - n0.x); dx_tot[node0] += f_attract*cos(theta); dy_tot[node0] += f_attract*sin(theta); dx_tot[node1] -= f_attract*cos(theta); dy_tot[node1] -= f_attract*sin(theta); } void computeRepelForces(SimpleGraph & graph, vector<double> & dx_tot, vector<double> & dy_tot, int node0, int node1) { Node n0 = graph.nodes[node0]; Node n1 = graph.nodes[node1]; double f_repel = K_REPEL/sqrt((n1.x-n0.x)*(n1.x-n0.x) + (n1.y-n0.y)*(n1.y-n0.y)); double theta = atan2(n1.y - n0.y, n1.x - n0.x); dx_tot[node0] -= f_repel*cos(theta); dy_tot[node0] -= f_repel*sin(theta); dx_tot[node1] += f_repel*cos(theta); dy_tot[node1] += f_repel*sin(theta); } /* Function: loadFileToGraph * Usage: loadFileToGraph(graph, infile) * ----- * Initializes the nodes and edges in a formatted file */ void loadFileToGraph(SimpleGraph & graph, ifstream & file) { int numNodes; file >> numNodes; // read number of nodes initNodePositions(graph, numNodes); while (!file.fail()) { // read all edges Edge e; file >> e.start; file >> e.end; graph.edges.push_back(e); } } /* Function: initNodePositions * Usage: initNodePositions(graph, numNodes) * ----- * Initializes the number of nodes specified in a circle */ void initNodePositions(SimpleGraph & graph, int numNodes) { for (int k = 0; k < numNodes; k++) { Node n; n.x = cos(2*PI*k/numNodes); n.y = sin(2*PI*k/numNodes); graph.nodes.push_back(n); } } /* Function: promptUserForLoop * Usage: bool loop = promptUserForLoop("Would you like to display another graph?") * ----- * Returns true if the user types "yes" or "y", and false otherwise. */ bool promptUserForLoop(string prompt) { string response; string line; while (true) { cout << prompt; getline(cin, line); istringstream stream(line); stream >> response >> ws; if (!stream.fail() && stream.eof()) break; cout << "Please enter yes/no." << endl; if (prompt == "") prompt = "Would you like to loop?"; } return (toUpperCase(response) == "YES" || toUpperCase(response) == "Y"); } string toUpperCase(string str) { string result; for (int i = 0; i < str.size(); i++) { result += toupper(str[i]); } return result; } int promptUserForFilter(string prompt) { int requestedFilter; string line; while (true) { cout << prompt; getline(cin, line); istringstream stream(line); stream >> requestedFilter >> ws; if (!stream.fail() && stream.eof()) break; cout << "Illegal numeric format. Try again." << endl; if (prompt == "") prompt = "Enter a filter value: "; } return requestedFilter; } double promptUserForTime(string prompt) { double requestedTime; string line; while (true) { cout << prompt; getline(cin, line); istringstream stream(line); stream >> requestedTime >> ws; if (!stream.fail() && stream.eof()) break; cout << "Illegal numeric format. Try again." << endl; if (prompt == "") prompt = "Enter a number for time: "; } return requestedTime; } string promptUserForFile(string prompt) { string fileName; string line; while (true) { cout << prompt; getline(cin, line); istringstream stream(line); stream >> fileName >> ws; if (!stream.fail() && stream.eof()) break; cout << "Illegal file name. Try again." << endl; if (prompt == "") prompt = "Enter file name: "; } return fileName; } void Welcome() { cout << "Welcome to CS106L GraphViz!" << endl; cout << "This program uses a force-directed graph layout algorithm" << endl; cout << "to render sleek, snazzy pictures of various graphs." << endl; cout << endl; }
[ "haudarren@gmail.com" ]
haudarren@gmail.com
4825365c3c7c56c3173dc36ce63dab55cc1286aa
2dd50afaa6def54b13af4337383871b1fecfd422
/Source/3rdParty/bgfx/Header/bgfx/bgfx.h
0437289ab270d28bdb61a320ff6ddfb9c818ef76
[ "BSD-2-Clause", "MIT" ]
permissive
redchew-fork/Dorothy-SSR
cee73f9bba569295f8f71b614cc59d3266cc77b3
1874254224a5e83617b799795be1bfa4c8b707ac
refs/heads/master
2023-04-16T07:35:24.060383
2021-04-25T00:07:53
2021-04-25T00:07:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
131,646
h
/* * Copyright 2011-2021 Branimir Karadzic. All rights reserved. * License: https://github.com/bkaradzic/bgfx/blob/master/LICENSE */ #ifndef BGFX_H_HEADER_GUARD #define BGFX_H_HEADER_GUARD #include <stdarg.h> // va_list #include <stdint.h> // uint32_t #include <stdlib.h> // NULL #include "defines.h" /// #define BGFX_HANDLE(_name) \ struct _name { uint16_t idx; }; \ inline bool isValid(_name _handle) { return bgfx::kInvalidHandle != _handle.idx; } #define BGFX_INVALID_HANDLE { bgfx::kInvalidHandle } namespace bx { struct AllocatorI; } /// BGFX namespace bgfx { /// Fatal error enum. /// /// @attention C99 equivalent is `bgfx_fatal_t`. /// struct Fatal { enum Enum { DebugCheck, InvalidShader, UnableToInitialize, UnableToCreateTexture, DeviceLost, Count }; }; /// Renderer backend type enum. /// /// @attention C99 equivalent is `bgfx_renderer_type_t`. /// struct RendererType { /// Renderer types: enum Enum { Noop, //!< No rendering. Direct3D9, //!< Direct3D 9.0 Direct3D11, //!< Direct3D 11.0 Direct3D12, //!< Direct3D 12.0 Gnm, //!< GNM Metal, //!< Metal Nvn, //!< NVN OpenGLES, //!< OpenGL ES 2.0+ OpenGL, //!< OpenGL 2.1+ Vulkan, //!< Vulkan WebGPU, //!< WebGPU Count }; }; /// Access mode enum. /// /// @attention C99 equivalent is `bgfx_access_t`. /// struct Access { /// Access: enum Enum { Read, //!< Read Write, //!< Write ReadWrite, //!< Read and write Count }; }; /// Vertex attribute enum. /// /// @attention C99 equivalent is `bgfx_attrib_t`. /// struct Attrib { /// Corresponds to vertex shader attribute. enum Enum { Position, //!< a_position Normal, //!< a_normal Tangent, //!< a_tangent Bitangent, //!< a_bitangent Color0, //!< a_color0 Color1, //!< a_color1 Color2, //!< a_color2 Color3, //!< a_color3 Indices, //!< a_indices Weight, //!< a_weight TexCoord0, //!< a_texcoord0 TexCoord1, //!< a_texcoord1 TexCoord2, //!< a_texcoord2 TexCoord3, //!< a_texcoord3 TexCoord4, //!< a_texcoord4 TexCoord5, //!< a_texcoord5 TexCoord6, //!< a_texcoord6 TexCoord7, //!< a_texcoord7 Count }; }; /// Vertex attribute type enum. /// /// @attention C99 equivalent is `bgfx_attrib_type_t`. /// struct AttribType { /// Attribute types: enum Enum { Uint8, //!< Uint8 Uint10, //!< Uint10, availability depends on: `BGFX_CAPS_VERTEX_ATTRIB_UINT10`. Int16, //!< Int16 Half, //!< Half, availability depends on: `BGFX_CAPS_VERTEX_ATTRIB_HALF`. Float, //!< Float Count }; }; /// Texture format enum. /// /// Notation: /// /// RGBA16S /// ^ ^ ^ /// | | +-- [ ]Unorm /// | | [F]loat /// | | [S]norm /// | | [I]nt /// | | [U]int /// | +---- Number of bits per component /// +-------- Components /// /// @attention Availability depends on Caps (see: formats). /// /// @attention C99 equivalent is `bgfx_texture_format_t`. /// struct TextureFormat { /// Texture formats: enum Enum { BC1, //!< DXT1 R5G6B5A1 BC2, //!< DXT3 R5G6B5A4 BC3, //!< DXT5 R5G6B5A8 BC4, //!< LATC1/ATI1 R8 BC5, //!< LATC2/ATI2 RG8 BC6H, //!< BC6H RGB16F BC7, //!< BC7 RGB 4-7 bits per color channel, 0-8 bits alpha ETC1, //!< ETC1 RGB8 ETC2, //!< ETC2 RGB8 ETC2A, //!< ETC2 RGBA8 ETC2A1, //!< ETC2 RGB8A1 PTC12, //!< PVRTC1 RGB 2BPP PTC14, //!< PVRTC1 RGB 4BPP PTC12A, //!< PVRTC1 RGBA 2BPP PTC14A, //!< PVRTC1 RGBA 4BPP PTC22, //!< PVRTC2 RGBA 2BPP PTC24, //!< PVRTC2 RGBA 4BPP ATC, //!< ATC RGB 4BPP ATCE, //!< ATCE RGBA 8 BPP explicit alpha ATCI, //!< ATCI RGBA 8 BPP interpolated alpha ASTC4x4, //!< ASTC 4x4 8.0 BPP ASTC5x5, //!< ASTC 5x5 5.12 BPP ASTC6x6, //!< ASTC 6x6 3.56 BPP ASTC8x5, //!< ASTC 8x5 3.20 BPP ASTC8x6, //!< ASTC 8x6 2.67 BPP ASTC10x5, //!< ASTC 10x5 2.56 BPP Unknown, // Compressed formats above. R1, A8, R8, R8I, R8U, R8S, R16, R16I, R16U, R16F, R16S, R32I, R32U, R32F, RG8, RG8I, RG8U, RG8S, RG16, RG16I, RG16U, RG16F, RG16S, RG32I, RG32U, RG32F, RGB8, RGB8I, RGB8U, RGB8S, RGB9E5F, BGRA8, RGBA8, RGBA8I, RGBA8U, RGBA8S, RGBA16, RGBA16I, RGBA16U, RGBA16F, RGBA16S, RGBA32I, RGBA32U, RGBA32F, R5G6B5, RGBA4, RGB5A1, RGB10A2, RG11B10F, UnknownDepth, // Depth formats below. D16, D24, D24S8, D32, D16F, D24F, D32F, D0S8, Count }; }; /// Uniform type enum. /// /// @attention C99 equivalent is `bgfx_uniform_type_t`. /// struct UniformType { /// Uniform types: enum Enum { Sampler, //!< Sampler. End, //!< Reserved, do not use. Vec4, //!< 4 floats vector. Mat3, //!< 3x3 matrix. Mat4, //!< 4x4 matrix. Count }; }; /// Backbuffer ratio enum. /// /// @attention C99 equivalent is `bgfx_backbuffer_ratio_t`. /// struct BackbufferRatio { /// Backbuffer ratios: enum Enum { Equal, //!< Equal to backbuffer. Half, //!< One half size of backbuffer. Quarter, //!< One quarter size of backbuffer. Eighth, //!< One eighth size of backbuffer. Sixteenth, //!< One sixteenth size of backbuffer. Double, //!< Double size of backbuffer. Count }; }; /// Occlusion query result. /// /// @attention C99 equivalent is `bgfx_occlusion_query_result_t`. /// struct OcclusionQueryResult { /// Occlusion query results: enum Enum { Invisible, //!< Query failed test. Visible, //!< Query passed test. NoResult, //!< Query result is not available yet. Count }; }; /// Primitive topology. /// /// @attention C99 equivalent is `bgfx_topology_t`. /// struct Topology { /// Primitive topology: enum Enum { TriList, //!< Triangle list. TriStrip, //!< Triangle strip. LineList, //!< Line list. LineStrip, //!< Line strip. PointList, //!< Point list. Count }; }; /// Topology conversion function. /// /// @attention C99 equivalent is `bgfx_topology_convert_t`. /// struct TopologyConvert { /// Topology conversion functions: enum Enum { TriListFlipWinding, //!< Flip winding order of triangle list. TriStripFlipWinding, //!< Flip winding order of trinagle strip. TriListToLineList, //!< Convert triangle list to line list. TriStripToTriList, //!< Convert triangle strip to triangle list. LineStripToLineList, //!< Convert line strip to line list. Count }; }; /// Topology sort order. /// /// @attention C99 equivalent is `bgfx_topology_sort_t`. /// struct TopologySort { /// Topology sort order: enum Enum { DirectionFrontToBackMin, //!< DirectionFrontToBackAvg, //!< DirectionFrontToBackMax, //!< DirectionBackToFrontMin, //!< DirectionBackToFrontAvg, //!< DirectionBackToFrontMax, //!< DistanceFrontToBackMin, //!< DistanceFrontToBackAvg, //!< DistanceFrontToBackMax, //!< DistanceBackToFrontMin, //!< DistanceBackToFrontAvg, //!< DistanceBackToFrontMax, //!< Count }; }; /// View mode sets draw call sort order. /// /// @attention C99 equivalent is `bgfx_view_mode_t`. /// struct ViewMode { /// View modes: enum Enum { Default, //!< Default sort order. Sequential, //!< Sort in the same order in which submit calls were called. DepthAscending, //!< Sort draw call depth in ascending order. DepthDescending, //!< Sort draw call depth in descending order. Count }; }; static const uint16_t kInvalidHandle = UINT16_MAX; BGFX_HANDLE(DynamicIndexBufferHandle) BGFX_HANDLE(DynamicVertexBufferHandle) BGFX_HANDLE(FrameBufferHandle) BGFX_HANDLE(IndexBufferHandle) BGFX_HANDLE(IndirectBufferHandle) BGFX_HANDLE(OcclusionQueryHandle) BGFX_HANDLE(ProgramHandle) BGFX_HANDLE(ShaderHandle) BGFX_HANDLE(TextureHandle) BGFX_HANDLE(UniformHandle) BGFX_HANDLE(VertexBufferHandle) BGFX_HANDLE(VertexLayoutHandle) /// Callback interface to implement application specific behavior. /// Cached items are currently used for OpenGL and Direct3D 12 binary /// shaders. /// /// @remarks /// 'fatal' and 'trace' callbacks can be called from any thread. Other /// callbacks are called from the render thread. /// /// @attention C99 equivalent is `bgfx_callback_interface_t`. /// struct CallbackI { virtual ~CallbackI() = 0; /// This callback is called on unrecoverable errors. /// It's not safe to continue (Exluding _code `Fatal::DebugCheck`), /// inform the user and terminate the application. /// /// @param[in] _filePath File path where fatal message was generated. /// @param[in] _line Line where fatal message was generated. /// @param[in] _code Fatal error code. /// @param[in] _str More information about error. /// /// @remarks /// Not thread safe and it can be called from any thread. /// /// @attention C99 equivalent is `bgfx_callback_vtbl.fatal`. /// virtual void fatal( const char* _filePath , uint16_t _line , Fatal::Enum _code , const char* _str ) = 0; /// Print debug message. /// /// @param[in] _filePath File path where debug message was generated. /// @param[in] _line Line where debug message was generated. /// @param[in] _format `printf` style format. /// @param[in] _argList Variable arguments list initialized with /// `va_start`. /// /// @remarks /// Not thread safe and it can be called from any thread. /// /// @attention C99 equivalent is `bgfx_callback_vtbl.trace_vargs`. /// virtual void traceVargs( const char* _filePath , uint16_t _line , const char* _format , va_list _argList ) = 0; /// Profiler region begin. /// /// @param[in] _name Region name, contains dynamic string. /// @param[in] _abgr Color of profiler region. /// @param[in] _filePath File path where `profilerBegin` was called. /// @param[in] _line Line where `profilerBegin` was called. /// /// @remarks /// Not thread safe and it can be called from any thread. /// /// @attention C99 equivalent is `bgfx_callback_vtbl.profiler_begin`. /// virtual void profilerBegin( const char* _name , uint32_t _abgr , const char* _filePath , uint16_t _line ) = 0; /// Profiler region begin with string literal name. /// /// @param[in] _name Region name, contains string literal. /// @param[in] _abgr Color of profiler region. /// @param[in] _filePath File path where `profilerBeginLiteral` was called. /// @param[in] _line Line where `profilerBeginLiteral` was called. /// /// @remarks /// Not thread safe and it can be called from any thread. /// /// @attention C99 equivalent is `bgfx_callback_vtbl.profiler_begin_literal`. /// virtual void profilerBeginLiteral( const char* _name , uint32_t _abgr , const char* _filePath , uint16_t _line ) = 0; /// Profiler region end. /// /// @remarks /// Not thread safe and it can be called from any thread. /// /// @attention C99 equivalent is `bgfx_callback_vtbl.profiler_end`. /// virtual void profilerEnd() = 0; /// Returns the size of a cached item. Returns 0 if no cached item was /// found. /// /// @param[in] _id Cache id. /// @returns Number of bytes to read. /// /// @attention C99 equivalent is `bgfx_callback_vtbl.cache_read_size`. /// virtual uint32_t cacheReadSize(uint64_t _id) = 0; /// Read cached item. /// /// @param[in] _id Cache id. /// @param[in] _data Buffer where to read data. /// @param[in] _size Size of data to read. /// /// @returns True if data is read. /// /// @attention C99 equivalent is `bgfx_callback_vtbl.cache_read`. /// virtual bool cacheRead(uint64_t _id, void* _data, uint32_t _size) = 0; /// Write cached item. /// /// @param[in] _id Cache id. /// @param[in] _data Data to write. /// @param[in] _size Size of data to write. /// /// @attention C99 equivalent is `bgfx_callback_vtbl.cache_write`. /// virtual void cacheWrite(uint64_t _id, const void* _data, uint32_t _size) = 0; /// Screenshot captured. Screenshot format is always 4-byte BGRA. /// /// @param[in] _filePath File path. /// @param[in] _width Image width. /// @param[in] _height Image height. /// @param[in] _pitch Number of bytes to skip between the start of /// each horizontal line of the image. /// @param[in] _data Image data. /// @param[in] _size Image size. /// @param[in] _yflip If true, image origin is bottom left. /// /// @attention C99 equivalent is `bgfx_callback_vtbl.screen_shot`. /// virtual void screenShot( const char* _filePath , uint32_t _width , uint32_t _height , uint32_t _pitch , const void* _data , uint32_t _size , bool _yflip ) = 0; /// Called when a video capture begins. /// /// @param[in] _width Image width. /// @param[in] _height Image height. /// @param[in] _pitch Number of bytes to skip between the start of /// each horizontal line of the image. /// @param[in] _format Texture format. See: `TextureFormat::Enum`. /// @param[in] _yflip If true, image origin is bottom left. /// /// @attention C99 equivalent is `bgfx_callback_vtbl.capture_begin`. /// virtual void captureBegin( uint32_t _width , uint32_t _height , uint32_t _pitch , TextureFormat::Enum _format , bool _yflip ) = 0; /// Called when a video capture ends. /// /// @attention C99 equivalent is `bgfx_callback_vtbl.capture_end`. /// virtual void captureEnd() = 0; /// Captured frame. /// /// @param[in] _data Image data. /// @param[in] _size Image size. /// /// @attention C99 equivalent is `bgfx_callback_vtbl.capture_frame`. /// virtual void captureFrame(const void* _data, uint32_t _size) = 0; }; inline CallbackI::~CallbackI() { } /// Platform data. /// /// @attention C99 equivalent is `bgfx_platform_data_t`. /// struct PlatformData { PlatformData(); void* ndt; //!< Native display type (*nix specific). void* nwh; //!< Native window handle. If `NULL` bgfx will create headless /// context/device if renderer API supports it. void* context; //!< GL context, or D3D device. If `NULL`, bgfx will create context/device. void* backBuffer; //!< GL back-buffer, or D3D render target view. If `NULL` bgfx will /// create back-buffer color surface. void* backBufferDS; //!< Backbuffer depth/stencil. If `NULL` bgfx will create back-buffer /// depth/stencil surface. }; /// Backbuffer resolution and reset parameters. /// /// @attention C99 equivalent is `bgfx_resolution_t`. /// struct Resolution { Resolution(); TextureFormat::Enum format; //!< Backbuffer format. uint32_t width; //!< Backbuffer width. uint32_t height; //!< Backbuffer height. uint32_t reset; //!< Reset parameters. uint8_t numBackBuffers; //!< Number of back buffers. uint8_t maxFrameLatency; //!< Maximum frame latency. }; /// Initialization parameters used by `bgfx::init`. /// /// @attention C99 equivalent is `bgfx_init_t`. /// struct Init { Init(); /// Select rendering backend. When set to RendererType::Count /// a default rendering backend will be selected appropriate to the platform. /// See: `bgfx::RendererType` RendererType::Enum type; /// Vendor PCI id. If set to `BGFX_PCI_ID_NONE` it will select the first /// device. /// - `BGFX_PCI_ID_NONE` - Autoselect adapter. /// - `BGFX_PCI_ID_SOFTWARE_RASTERIZER` - Software rasterizer. /// - `BGFX_PCI_ID_AMD` - AMD adapter. /// - `BGFX_PCI_ID_INTEL` - Intel adapter. /// - `BGFX_PCI_ID_NVIDIA` - nVidia adapter. uint16_t vendorId; /// Device id. If set to 0 it will select first device, or device with /// matching id. uint16_t deviceId; bool debug; //!< Enable device for debuging. bool profile; //!< Enable device for profiling. /// Platform data. PlatformData platformData; /// Backbuffer resolution and reset parameters. See: `bgfx::Resolution`. Resolution resolution; /// Configurable runtime limits parameters. /// /// @attention C99 equivalent is `bgfx_init_limits_t`. /// struct Limits { Limits(); uint16_t maxEncoders; //!< Maximum number of encoder threads. uint32_t minResourceCbSize; //!< Minimum resource command buffer size. uint32_t transientVbSize; //!< Maximum transient vertex buffer size. uint32_t transientIbSize; //!< Maximum transient index buffer size. }; Limits limits; // Configurable runtime limits. /// Provide application specific callback interface. /// See: `bgfx::CallbackI` CallbackI* callback; /// Custom allocator. When a custom allocator is not /// specified, bgfx uses the CRT allocator. Bgfx assumes /// custom allocator is thread safe. bx::AllocatorI* allocator; }; /// Memory release callback. /// /// param[in] _ptr Pointer to allocated data. /// param[in] _userData User defined data if needed. /// /// @attention C99 equivalent is `bgfx_release_fn_t`. /// typedef void (*ReleaseFn)(void* _ptr, void* _userData); /// Memory must be obtained by calling `bgfx::alloc`, `bgfx::copy`, or `bgfx::makeRef`. /// /// @attention It is illegal to create this structure on stack and pass it to any bgfx API. /// /// @attention C99 equivalent is `bgfx_memory_t`. /// struct Memory { Memory() = delete; uint8_t* data; //!< Pointer to data. uint32_t size; //!< Data size. }; /// Renderer capabilities. /// /// @attention C99 equivalent is `bgfx_caps_t`. /// struct Caps { /// Renderer backend type. See: `bgfx::RendererType` RendererType::Enum rendererType; /// Supported functionality. /// /// @attention See BGFX_CAPS_* flags at https://bkaradzic.github.io/bgfx/bgfx.html#available-caps /// uint64_t supported; uint16_t vendorId; //!< Selected GPU vendor PCI id. uint16_t deviceId; //!< Selected GPU device id. bool homogeneousDepth; //!< True when NDC depth is in [-1, 1] range, otherwise its [0, 1]. bool originBottomLeft; //!< True when NDC origin is at bottom left. uint8_t numGPUs; //!< Number of enumerated GPUs. /// GPU info. /// /// @attention C99 equivalent is `bgfx_caps_gpu_t`. /// struct GPU { uint16_t vendorId; //!< Vendor PCI id. See `BGFX_PCI_ID_*`. uint16_t deviceId; //!< Device id. }; GPU gpu[4]; //!< Enumerated GPUs. /// Renderer runtime limits. /// /// @attention C99 equivalent is `bgfx_caps_limits_t`. /// struct Limits { uint32_t maxDrawCalls; //!< Maximum number of draw calls. uint32_t maxBlits; //!< Maximum number of blit calls. uint32_t maxTextureSize; //!< Maximum texture size. uint32_t maxTextureLayers; //!< Maximum texture layers. uint32_t maxViews; //!< Maximum number of views. uint32_t maxFrameBuffers; //!< Maximum number of frame buffer handles. uint32_t maxFBAttachments; //!< Maximum number of frame buffer attachments. uint32_t maxPrograms; //!< Maximum number of program handles. uint32_t maxShaders; //!< Maximum number of shader handles. uint32_t maxTextures; //!< Maximum number of texture handles. uint32_t maxTextureSamplers; //!< Maximum number of texture samplers. uint32_t maxComputeBindings; //!< Maximum number of compute bindings. uint32_t maxVertexLayouts; //!< Maximum number of vertex format layouts. uint32_t maxVertexStreams; //!< Maximum number of vertex streams. uint32_t maxIndexBuffers; //!< Maximum number of index buffer handles. uint32_t maxVertexBuffers; //!< Maximum number of vertex buffer handles. uint32_t maxDynamicIndexBuffers; //!< Maximum number of dynamic index buffer handles. uint32_t maxDynamicVertexBuffers; //!< Maximum number of dynamic vertex buffer handles. uint32_t maxUniforms; //!< Maximum number of uniform handles. uint32_t maxOcclusionQueries; //!< Maximum number of occlusion query handles. uint32_t maxEncoders; //!< Maximum number of encoder threads. uint32_t minResourceCbSize; //!< Minimum resource command buffer size. uint32_t transientVbSize; //!< Maximum transient vertex buffer size. uint32_t transientIbSize; //!< Maximum transient index buffer size. }; Limits limits; //!< Renderer runtime limits. /// Supported texture format capabilities flags: /// - `BGFX_CAPS_FORMAT_TEXTURE_NONE` - Texture format is not supported. /// - `BGFX_CAPS_FORMAT_TEXTURE_2D` - Texture format is supported. /// - `BGFX_CAPS_FORMAT_TEXTURE_2D_SRGB` - Texture as sRGB format is supported. /// - `BGFX_CAPS_FORMAT_TEXTURE_2D_EMULATED` - Texture format is emulated. /// - `BGFX_CAPS_FORMAT_TEXTURE_3D` - Texture format is supported. /// - `BGFX_CAPS_FORMAT_TEXTURE_3D_SRGB` - Texture as sRGB format is supported. /// - `BGFX_CAPS_FORMAT_TEXTURE_3D_EMULATED` - Texture format is emulated. /// - `BGFX_CAPS_FORMAT_TEXTURE_CUBE` - Texture format is supported. /// - `BGFX_CAPS_FORMAT_TEXTURE_CUBE_SRGB` - Texture as sRGB format is supported. /// - `BGFX_CAPS_FORMAT_TEXTURE_CUBE_EMULATED` - Texture format is emulated. /// - `BGFX_CAPS_FORMAT_TEXTURE_VERTEX` - Texture format can be used from vertex shader. /// - `BGFX_CAPS_FORMAT_TEXTURE_IMAGE_READ` - Texture format can be used as image /// and read from. /// - `BGFX_CAPS_FORMAT_TEXTURE_IMAGE_WRITE` - Texture format can be used as image /// and written to. /// - `BGFX_CAPS_FORMAT_TEXTURE_FRAMEBUFFER` - Texture format can be used as frame /// buffer. /// - `BGFX_CAPS_FORMAT_TEXTURE_FRAMEBUFFER_MSAA` - Texture format can be used as MSAA /// frame buffer. /// - `BGFX_CAPS_FORMAT_TEXTURE_MSAA` - Texture can be sampled as MSAA. /// - `BGFX_CAPS_FORMAT_TEXTURE_MIP_AUTOGEN` - Texture format supports auto-generated /// mips. uint16_t formats[TextureFormat::Count]; }; /// Transient index buffer. /// /// @attention C99 equivalent is `bgfx_transient_index_buffer_t`. /// struct TransientIndexBuffer { uint8_t* data; //!< Pointer to data. uint32_t size; //!< Data size. uint32_t startIndex; //!< First index. IndexBufferHandle handle; //!< Index buffer handle. bool isIndex16; //!< Index buffer format is 16-bits if true, otherwise it is 32-bit. }; /// Transient vertex buffer. /// /// @attention C99 equivalent is `bgfx_transient_vertex_buffer_t`. /// struct TransientVertexBuffer { uint8_t* data; //!< Pointer to data. uint32_t size; //!< Data size. uint32_t startVertex; //!< First vertex. uint16_t stride; //!< Vertex stride. VertexBufferHandle handle; //!< Vertex buffer handle. VertexLayoutHandle layoutHandle; //!< Vertex layout handle. }; /// Instance data buffer info. /// /// @attention C99 equivalent is `bgfx_instance_data_buffer_t`. /// struct InstanceDataBuffer { uint8_t* data; //!< Pointer to data. uint32_t size; //!< Data size. uint32_t offset; //!< Offset in vertex buffer. uint32_t num; //!< Number of instances. uint16_t stride; //!< Vertex buffer stride. VertexBufferHandle handle; //!< Vertex buffer object handle. }; /// Texture info. /// /// @attention C99 equivalent is `bgfx_texture_info_t`. /// struct TextureInfo { TextureFormat::Enum format; //!< Texture format. uint32_t storageSize; //!< Total amount of bytes required to store texture. uint16_t width; //!< Texture width. uint16_t height; //!< Texture height. uint16_t depth; //!< Texture depth. uint16_t numLayers; //!< Number of layers in texture array. uint8_t numMips; //!< Number of MIP maps. uint8_t bitsPerPixel; //!< Format bits per pixel. bool cubeMap; //!< Texture is cubemap. }; /// Uniform info. /// /// @attention C99 equivalent is `bgfx_uniform_info_t`. /// struct UniformInfo { char name[256]; //!< Uniform name. UniformType::Enum type; //!< Uniform type. uint16_t num; //!< Number of elements in array. }; /// Frame buffer texture attachment info. /// /// @attention C99 equivalent is `bgfx_attachment_t`. /// struct Attachment { /// Init attachment. /// /// @param[in] _handle Render target texture handle. /// @param[in] _access Access. See `Access::Enum`. /// @param[in] _layer Cubemap side or depth layer/slice to use. /// @param[in] _numLayers Number of texture layer/slice(s) in array to use. /// @param[in] _mip Mip level. /// @param[in] _resolve Resolve flags. See: `BGFX_RESOLVE_*` /// void init( TextureHandle _handle , Access::Enum _access = Access::Write , uint16_t _layer = 0 , uint16_t _numLayers = 1 , uint16_t _mip = 0 , uint8_t _resolve = BGFX_RESOLVE_AUTO_GEN_MIPS ); Access::Enum access; //!< Attachment access. See `Access::Enum`. TextureHandle handle; //!< Render target texture handle. uint16_t mip; //!< Mip level. uint16_t layer; //!< Cubemap side or depth layer/slice to use. uint16_t numLayers; //!< Number of texture layer/slice(s) in array to use. uint8_t resolve; //!< Resolve flags. See: `BGFX_RESOLVE_*` }; /// Transform data. /// /// @attention C99 equivalent is `bgfx_transform_t`. /// struct Transform { float* data; //!< Pointer to first 4x4 matrix. uint16_t num; //!< Number of matrices. }; /// typedef uint16_t ViewId; /// View stats. /// /// @attention C99 equivalent is `bgfx_view_stats_t`. /// struct ViewStats { char name[256]; //!< View name. ViewId view; //!< View id. int64_t cpuTimeBegin; //!< CPU (submit) begin time. int64_t cpuTimeEnd; //!< CPU (submit) end time. int64_t gpuTimeBegin; //!< GPU begin time. int64_t gpuTimeEnd; //!< GPU end time. }; /// Encoder stats. /// /// @attention C99 equivalent is `bgfx_encoder_stats_t`. /// struct EncoderStats { int64_t cpuTimeBegin; //!< Encoder thread CPU submit begin time. int64_t cpuTimeEnd; //!< Encoder thread CPU submit end time. }; /// Renderer statistics data. /// /// @attention C99 equivalent is `bgfx_stats_t`. /// /// @remarks All time values are high-resolution timestamps, while /// time frequencies define timestamps-per-second for that hardware. struct Stats { int64_t cpuTimeFrame; //!< CPU time between two `bgfx::frame` calls. int64_t cpuTimeBegin; //!< Render thread CPU submit begin time. int64_t cpuTimeEnd; //!< Render thread CPU submit end time. int64_t cpuTimerFreq; //!< CPU timer frequency. Timestamps-per-second int64_t gpuTimeBegin; //!< GPU frame begin time. int64_t gpuTimeEnd; //!< GPU frame end time. int64_t gpuTimerFreq; //!< GPU timer frequency. int64_t waitRender; //!< Time spent waiting for render backend thread to finish issuing //! draw commands to underlying graphics API. int64_t waitSubmit; //!< Time spent waiting for submit thread to advance to next frame. uint32_t numDraw; //!< Number of draw calls submitted. uint32_t numCompute; //!< Number of compute calls submitted. uint32_t numBlit; //!< Number of blit calls submitted. uint32_t maxGpuLatency; //!< GPU driver latency. uint16_t numDynamicIndexBuffers; //!< Number of used dynamic index buffers. uint16_t numDynamicVertexBuffers; //!< Number of used dynamic vertex buffers. uint16_t numFrameBuffers; //!< Number of used frame buffers. uint16_t numIndexBuffers; //!< Number of used index buffers. uint16_t numOcclusionQueries; //!< Number of used occlusion queries. uint16_t numPrograms; //!< Number of used programs. uint16_t numShaders; //!< Number of used shaders. uint16_t numTextures; //!< Number of used textures. uint16_t numUniforms; //!< Number of used uniforms. uint16_t numVertexBuffers; //!< Number of used vertex buffers. uint16_t numVertexLayouts; //!< Number of used vertex layouts. int64_t textureMemoryUsed; //!< Estimate of texture memory used. int64_t rtMemoryUsed; //!< Estimate of render target memory used. int32_t transientVbUsed; //!< Amount of transient vertex buffer used. int32_t transientIbUsed; //!< Amount of transient index buffer used. uint32_t numPrims[Topology::Count]; //!< Number of primitives rendered. int64_t gpuMemoryMax; //!< Maximum available GPU memory for application. int64_t gpuMemoryUsed; //!< Amount of GPU memory used by the application. uint16_t width; //!< Backbuffer width in pixels. uint16_t height; //!< Backbuffer height in pixels. uint16_t textWidth; //!< Debug text width in characters. uint16_t textHeight; //!< Debug text height in characters. uint16_t numViews; //!< Number of view stats. ViewStats* viewStats; //!< Array of View stats. uint8_t numEncoders; //!< Number of encoders used during frame. EncoderStats* encoderStats; //!< Array of encoder stats. }; /// Encoders are used for submitting draw calls from multiple threads. Only one encoder /// per thread should be used. Use `bgfx::begin()` to obtain an encoder for a thread. /// /// @attention C99 equivalent is `bgfx_encoder`. /// struct Encoder { /// Sets a debug marker. This allows you to group /// graphics calls together for easy browsing in /// graphics debugging tools. /// /// @attention C99 equivalent is `bgfx_encoder_set_marker`. /// void setMarker(const char* _marker); /// Set render states for draw primitive. /// /// @param[in] _state State flags. Default state for primitive type is /// triangles. See: `BGFX_STATE_DEFAULT`. /// - `BGFX_STATE_DEPTH_TEST_*` - Depth test function. /// - `BGFX_STATE_BLEND_*` - See remark 1 about BGFX_STATE_BLEND_FUNC. /// - `BGFX_STATE_BLEND_EQUATION_*` - See remark 2. /// - `BGFX_STATE_CULL_*` - Backface culling mode. /// - `BGFX_STATE_WRITE_*` - Enable R, G, B, A or Z write. /// - `BGFX_STATE_MSAA` - Enable hardware multisample antialiasing. /// - `BGFX_STATE_PT_[TRISTRIP/LINES/POINTS]` - Primitive type. /// /// @param[in] _rgba Sets blend factor used by `BGFX_STATE_BLEND_FACTOR` and /// `BGFX_STATE_BLEND_INV_FACTOR` blend modes. /// /// @remarks /// 1. To setup more complex states use: /// `BGFX_STATE_ALPHA_REF(_ref)`, /// `BGFX_STATE_POINT_SIZE(_size)`, /// `BGFX_STATE_BLEND_FUNC(_src, _dst)`, /// `BGFX_STATE_BLEND_FUNC_SEPARATE(_srcRGB, _dstRGB, _srcA, _dstA)`, /// `BGFX_STATE_BLEND_EQUATION(_equation)`, /// `BGFX_STATE_BLEND_EQUATION_SEPARATE(_equationRGB, _equationA)` /// 2. `BGFX_STATE_BLEND_EQUATION_ADD` is set when no other blend /// equation is specified. /// /// @attention C99 equivalent is `bgfx_encoder_set_state`. /// void setState( uint64_t _state , uint32_t _rgba = 0 ); /// Set condition for rendering. /// /// @param[in] _handle Occlusion query handle. /// @param[in] _visible Render if occlusion query is visible. /// /// @attention C99 equivalent is `bgfx_encoder_set_condition`. /// void setCondition( OcclusionQueryHandle _handle , bool _visible ); /// Set stencil test state. /// /// @param[in] _fstencil Front stencil state. /// @param[in] _bstencil Back stencil state. If back is set to `BGFX_STENCIL_NONE` /// _fstencil is applied to both front and back facing primitives. /// /// @attention C99 equivalent is `bgfx_encoder_set_stencil`. /// void setStencil( uint32_t _fstencil , uint32_t _bstencil = BGFX_STENCIL_NONE ); /// Set scissor for draw primitive. To scissor for all primitives in /// view see `bgfx::setViewScissor`. /// /// @param[in] _x Position x from the left side of the window. /// @param[in] _y Position y from the top of the window. /// @param[in] _width Width of scissor region. /// @param[in] _height Height of scissor region. /// @returns Scissor cache index. /// /// @attention C99 equivalent is `bgfx_encoder_set_scissor`. /// uint16_t setScissor( uint16_t _x , uint16_t _y , uint16_t _width , uint16_t _height ); /// Set scissor from cache for draw primitive. /// /// @param[in] _cache Index in scissor cache. /// Pass UINT16_MAX to have primitive use view scissor instead. /// /// @attention C99 equivalent is `bgfx_encoder_set_scissor_cached`. /// void setScissor(uint16_t _cache = UINT16_MAX); /// Set model matrix for draw primitive. If it is not called, model will /// be rendered with identity model matrix. /// /// @param[in] _mtx Pointer to first matrix in array. /// @param[in] _num Number of matrices in array. /// @returns Index into matrix cache in case the same model matrix has /// to be used for other draw primitive call. /// /// @attention C99 equivalent is `bgfx_encoder_set_transform`. /// uint32_t setTransform( const void* _mtx , uint16_t _num = 1 ); /// Reserve `_num` matrices in internal matrix cache. /// /// @param[in] _transform Pointer to `Transform` structure. /// @param[in] _num Number of matrices. /// @returns Index into matrix cache. /// /// @attention Pointer returned can be modifed until `bgfx::frame` is called. /// @attention C99 equivalent is `bgfx_encoder_alloc_transform`. /// uint32_t allocTransform( Transform* _transform , uint16_t _num ); /// Set model matrix from matrix cache for draw primitive. /// /// @param[in] _cache Index in matrix cache. /// @param[in] _num Number of matrices from cache. /// /// @attention C99 equivalent is `bgfx_encoder_set_transform_cached`. /// void setTransform( uint32_t _cache , uint16_t _num = 1 ); /// Set shader uniform parameter for draw primitive. /// /// @param[in] _handle Uniform. /// @param[in] _value Pointer to uniform data. /// @param[in] _num Number of elements. Passing `UINT16_MAX` will /// use the _num passed on uniform creation. /// /// @attention C99 equivalent is `bgfx_encoder_set_uniform`. /// void setUniform( UniformHandle _handle , const void* _value , uint16_t _num = 1 ); /// Set index buffer for draw primitive. /// /// @param[in] _handle Index buffer. /// /// @attention C99 equivalent is `bgfx_encoder_set_index_buffer`. /// void setIndexBuffer(IndexBufferHandle _handle); /// Set index buffer for draw primitive. /// /// @param[in] _handle Index buffer. /// @param[in] _firstIndex First index to render. /// @param[in] _numIndices Number of indices to render. /// /// @attention C99 equivalent is `bgfx_encoder_set_index_buffer`. /// void setIndexBuffer( IndexBufferHandle _handle , uint32_t _firstIndex , uint32_t _numIndices ); /// Set index buffer for draw primitive. /// /// @param[in] _handle Dynamic index buffer. /// /// @attention C99 equivalent is `bgfx_encoder_set_dynamic_index_buffer`. /// void setIndexBuffer(DynamicIndexBufferHandle _handle); /// Set index buffer for draw primitive. /// /// @param[in] _handle Dynamic index buffer. /// @param[in] _firstIndex First index to render. /// @param[in] _numIndices Number of indices to render. /// /// @attention C99 equivalent is `bgfx_encoder_set_dynamic_index_buffer`. /// void setIndexBuffer( DynamicIndexBufferHandle _handle , uint32_t _firstIndex , uint32_t _numIndices ); /// Set index buffer for draw primitive. /// /// @param[in] _tib Transient index buffer. /// /// @attention C99 equivalent is `bgfx_encoder_set_transient_index_buffer`. /// void setIndexBuffer(const TransientIndexBuffer* _tib); /// Set index buffer for draw primitive. /// /// @param[in] _tib Transient index buffer. /// @param[in] _firstIndex First index to render. /// @param[in] _numIndices Number of indices to render. /// /// @attention C99 equivalent is `bgfx_encoder_set_transient_index_buffer`. /// void setIndexBuffer( const TransientIndexBuffer* _tib , uint32_t _firstIndex , uint32_t _numIndices ); /// Set vertex buffer for draw primitive. /// /// @param[in] _stream Vertex stream. /// @param[in] _handle Vertex buffer. /// /// @attention C99 equivalent is `bgfx_encoder_set_vertex_buffer`. /// void setVertexBuffer( uint8_t _stream , VertexBufferHandle _handle ); /// Set vertex buffer for draw primitive. /// /// @param[in] _stream Vertex stream. /// @param[in] _handle Vertex buffer. /// @param[in] _startVertex First vertex to render. /// @param[in] _numVertices Number of vertices to render. /// @param[in] _layoutHandle Vertex layout for aliasing vertex buffer. If invalid handle is /// used, vertex layout used for creation of vertex buffer will be used. /// /// @attention C99 equivalent is `bgfx_encoder_set_vertex_buffer`. /// void setVertexBuffer( uint8_t _stream , VertexBufferHandle _handle , uint32_t _startVertex , uint32_t _numVertices , VertexLayoutHandle _layoutHandle = BGFX_INVALID_HANDLE ); /// Set vertex buffer for draw primitive. /// /// @param[in] _stream Vertex stream. /// @param[in] _handle Dynamic vertex buffer. /// /// @attention C99 equivalent is `bgfx_encoder_set_dynamic_vertex_buffer`. /// void setVertexBuffer( uint8_t _stream , DynamicVertexBufferHandle _handle ); /// Set vertex buffer for draw primitive. /// /// @param[in] _stream Vertex stream. /// @param[in] _handle Dynamic vertex buffer. /// @param[in] _startVertex First vertex to render. /// @param[in] _numVertices Number of vertices to render. /// @param[in] _layoutHandle Vertex layout for aliasing vertex buffer. If invalid handle is /// used, vertex layout used for creation of vertex buffer will be used. /// /// @attention C99 equivalent is `bgfx_encoder_set_dynamic_vertex_buffer`. /// void setVertexBuffer( uint8_t _stream , DynamicVertexBufferHandle _handle , uint32_t _startVertex , uint32_t _numVertices , VertexLayoutHandle _layoutHandle = BGFX_INVALID_HANDLE ); /// Set vertex buffer for draw primitive. /// /// @param[in] _stream Vertex stream. /// @param[in] _tvb Transient vertex buffer. /// /// @attention C99 equivalent is `bgfx_encoder_set_transient_vertex_buffer`. /// void setVertexBuffer( uint8_t _stream , const TransientVertexBuffer* _tvb ); /// Set vertex buffer for draw primitive. /// /// @param[in] _stream Vertex stream. /// @param[in] _tvb Transient vertex buffer. /// @param[in] _startVertex First vertex to render. /// @param[in] _numVertices Number of vertices to render. /// @param[in] _layoutHandle Vertex layout for aliasing vertex buffer. If invalid handle is /// used, vertex layout used for creation of vertex buffer will be used. /// /// @attention C99 equivalent is `bgfx_encoder_set_transient_vertex_buffer`. /// void setVertexBuffer( uint8_t _stream , const TransientVertexBuffer* _tvb , uint32_t _startVertex , uint32_t _numVertices , VertexLayoutHandle _layoutHandle = BGFX_INVALID_HANDLE ); /// Set number of vertices for auto generated vertices use in conjuction /// with gl_VertexID. /// /// @param[in] _numVertices Number of vertices. /// /// @attention Availability depends on: `BGFX_CAPS_VERTEX_ID`. /// @attention C99 equivalent is `bgfx_encoder_set_vertex_count`. /// void setVertexCount(uint32_t _numVertices); /// Set instance data buffer for draw primitive. /// /// @param[in] _idb Transient instance data buffer. /// /// @attention C99 equivalent is `bgfx_encoder_set_instance_data_buffer`. /// void setInstanceDataBuffer(const InstanceDataBuffer* _idb); /// Set instance data buffer for draw primitive. /// /// @param[in] _idb Transient instance data buffer. /// @param[in] _start First instance data. /// @param[in] _num Number of data instances. /// /// @attention C99 equivalent is `bgfx_encoder_set_instance_data_buffer`. /// void setInstanceDataBuffer( const InstanceDataBuffer* _idb , uint32_t _start , uint32_t _num ); /// Set instance data buffer for draw primitive. /// /// @param[in] _handle Vertex buffer. /// @param[in] _start First instance data. /// @param[in] _num Number of data instances. /// /// @attention C99 equivalent is `bgfx_encoder_set_instance_data_from_vertex_buffer`. /// void setInstanceDataBuffer( VertexBufferHandle _handle , uint32_t _start , uint32_t _num ); /// Set instance data buffer for draw primitive. /// /// @param[in] _handle Vertex buffer. /// @param[in] _start First instance data. /// @param[in] _num Number of data instances. /// /// @attention C99 equivalent is `bgfx_encoder_set_instance_data_from_dynamic_vertex_buffer`. /// void setInstanceDataBuffer( DynamicVertexBufferHandle _handle , uint32_t _start , uint32_t _num ); /// Set number of instances for auto generated instances use in conjuction /// with gl_InstanceID. /// /// @param[in] _numInstances Number of instances. /// /// @attention Availability depends on: `BGFX_CAPS_VERTEX_ID`. /// @attention C99 equivalent is `bgfx_encoder_set_instance_count`. /// void setInstanceCount(uint32_t _numInstances); /// Set texture stage for draw primitive. /// /// @param[in] _stage Texture unit. /// @param[in] _sampler Program sampler. /// @param[in] _handle Texture handle. /// @param[in] _flags Texture sampling mode. Default value UINT32_MAX uses /// texture sampling settings from the texture. /// - `BGFX_SAMPLER_[U/V/W]_[MIRROR/CLAMP]` - Mirror or clamp to edge wrap /// mode. /// - `BGFX_SAMPLER_[MIN/MAG/MIP]_[POINT/ANISOTROPIC]` - Point or anisotropic /// sampling. /// /// @attention C99 equivalent is `bgfx_encoder_set_texture`. /// void setTexture( uint8_t _stage , UniformHandle _sampler , TextureHandle _handle , uint32_t _flags = UINT32_MAX ); /// Submit an empty primitive for rendering. Uniforms and draw state /// will be applied but no geometry will be submitted. Useful in cases /// when no other draw/compute primitive is submitted to view, but it's /// desired to execute clear view. /// /// These empty draw calls will sort before ordinary draw calls. /// /// @param[in] _id View id. /// /// @attention C99 equivalent is `bgfx_encoder_touch`. /// void touch(ViewId _id); /// Submit primitive for rendering. /// /// @param[in] _id View id. /// @param[in] _program Program. /// @param[in] _depth Depth for sorting. /// @param[in] _flags Discard or preserve states. See `BGFX_DISCARD_*`. /// /// @attention C99 equivalent is `bgfx_encoder_submit`. /// void submit( ViewId _id , ProgramHandle _program , uint32_t _depth = 0 , uint8_t _flags = BGFX_DISCARD_ALL ); /// Submit primitive with occlusion query for rendering. /// /// @param[in] _id View id. /// @param[in] _program Program. /// @param[in] _occlusionQuery Occlusion query. /// @param[in] _depth Depth for sorting. /// @param[in] _flags Discard or preserve states. See `BGFX_DISCARD_*`. /// /// @attention C99 equivalent is `bgfx_encoder_submit_occlusion_query`. /// void submit( ViewId _id , ProgramHandle _program , OcclusionQueryHandle _occlusionQuery , uint32_t _depth = 0 , uint8_t _flags = BGFX_DISCARD_ALL ); /// Submit primitive for rendering with index and instance data info from /// indirect buffer. /// /// @param[in] _id View id. /// @param[in] _program Program. /// @param[in] _indirectHandle Indirect buffer. /// @param[in] _start First element in indirect buffer. /// @param[in] _num Number of dispatches. /// @param[in] _depth Depth for sorting. /// @param[in] _flags Discard or preserve states. See `BGFX_DISCARD_*`. /// /// @attention C99 equivalent is `bgfx_encoder_submit_indirect`. /// void submit( ViewId _id , ProgramHandle _program , IndirectBufferHandle _indirectHandle , uint16_t _start = 0 , uint16_t _num = 1 , uint32_t _depth = 0 , uint8_t _flags = BGFX_DISCARD_ALL ); /// Set compute index buffer. /// /// @param[in] _stage Compute stage. /// @param[in] _handle Index buffer handle. /// @param[in] _access Buffer access. See `Access::Enum`. /// /// @attention C99 equivalent is `bgfx_encoder_set_compute_index_buffer`. /// void setBuffer( uint8_t _stage , IndexBufferHandle _handle , Access::Enum _access ); /// Set compute vertex buffer. /// /// @param[in] _stage Compute stage. /// @param[in] _handle Vertex buffer handle. /// @param[in] _access Buffer access. See `Access::Enum`. /// /// @attention C99 equivalent is `bgfx_encoder_set_compute_vertex_buffer`. /// void setBuffer( uint8_t _stage , VertexBufferHandle _handle , Access::Enum _access ); /// Set compute dynamic index buffer. /// /// @param[in] _stage Compute stage. /// @param[in] _handle Dynamic index buffer handle. /// @param[in] _access Buffer access. See `Access::Enum`. /// /// @attention C99 equivalent is `bgfx_encoder_set_compute_dynamic_index_buffer`. /// void setBuffer( uint8_t _stage , DynamicIndexBufferHandle _handle , Access::Enum _access ); /// Set compute dynamic vertex buffer. /// /// @param[in] _stage Compute stage. /// @param[in] _handle Dynamic vertex buffer handle. /// @param[in] _access Buffer access. See `Access::Enum`. /// /// @attention C99 equivalent is `bgfx_encoder_set_compute_dynamic_vertex_buffer`. /// void setBuffer( uint8_t _stage , DynamicVertexBufferHandle _handle , Access::Enum _access ); /// Set compute indirect buffer. /// /// @param[in] _stage Compute stage. /// @param[in] _handle Indirect buffer handle. /// @param[in] _access Buffer access. See `Access::Enum`. /// /// @attention C99 equivalent is `bgfx_encoder_set_compute_indirect_buffer`. /// void setBuffer( uint8_t _stage , IndirectBufferHandle _handle , Access::Enum _access ); /// Set compute image from texture. /// /// @param[in] _stage Texture unit. /// @param[in] _handle Texture handle. /// @param[in] _mip Mip level. /// @param[in] _access Texture access. See `Access::Enum`. /// @param[in] _format Texture format. See: `TextureFormat::Enum`. /// /// @attention C99 equivalent is `bgfx_encoder_set_image`. /// void setImage( uint8_t _stage , TextureHandle _handle , uint8_t _mip , Access::Enum _access , TextureFormat::Enum _format = TextureFormat::Count ); /// Dispatch compute. /// /// @param[in] _id View id. /// @param[in] _handle Compute program. /// @param[in] _numX Number of groups X. /// @param[in] _numY Number of groups Y. /// @param[in] _numZ Number of groups Z. /// @param[in] _flags Discard or preserve states. See `BGFX_DISCARD_*`. /// /// @attention C99 equivalent is `bgfx_encoder_dispatch`. /// void dispatch( ViewId _id , ProgramHandle _handle , uint32_t _numX = 1 , uint32_t _numY = 1 , uint32_t _numZ = 1 , uint8_t _flags = BGFX_DISCARD_ALL ); /// Dispatch compute indirect. /// /// @param[in] _id View id. /// @param[in] _handle Compute program. /// @param[in] _indirectHandle Indirect buffer. /// @param[in] _start First element in indirect buffer. /// @param[in] _num Number of dispatches. /// @param[in] _flags Discard or preserve states. See `BGFX_DISCARD_*`. /// /// @attention C99 equivalent is `bgfx_encoder_dispatch_indirect`. /// void dispatch( ViewId _id , ProgramHandle _handle , IndirectBufferHandle _indirectHandle , uint16_t _start = 0 , uint16_t _num = 1 , uint8_t _flags = BGFX_DISCARD_ALL ); /// Discard all previously set state for draw or compute call. /// /// @param[in] _flags Draw/compute states to discard. /// /// @attention C99 equivalent is `bgfx_encoder_discard`. /// void discard(uint8_t _flags = BGFX_DISCARD_ALL); /// Blit texture 2D region between two 2D textures. /// /// @param[in] _id View id. /// @param[in] _dst Destination texture handle. /// @param[in] _dstX Destination texture X position. /// @param[in] _dstY Destination texture Y position. /// @param[in] _src Source texture handle. /// @param[in] _srcX Source texture X position. /// @param[in] _srcY Source texture Y position. /// @param[in] _width Width of region. /// @param[in] _height Height of region. /// /// @attention Destination texture must be created with `BGFX_TEXTURE_BLIT_DST` flag. /// @attention Availability depends on: `BGFX_CAPS_TEXTURE_BLIT`. /// @attention C99 equivalent is `bgfx_encoder_blit`. /// void blit( ViewId _id , TextureHandle _dst , uint16_t _dstX , uint16_t _dstY , TextureHandle _src , uint16_t _srcX = 0 , uint16_t _srcY = 0 , uint16_t _width = UINT16_MAX , uint16_t _height = UINT16_MAX ); /// Blit texture region between two textures. /// /// @param[in] _id View id. /// @param[in] _dst Destination texture handle. /// @param[in] _dstMip Destination texture mip level. /// @param[in] _dstX Destination texture X position. /// @param[in] _dstY Destination texture Y position. /// @param[in] _dstZ If texture is 2D this argument should be 0. If destination texture is cube /// this argument represents destination texture cube face. For 3D texture this argument /// represents destination texture Z position. /// @param[in] _src Source texture handle. /// @param[in] _srcMip Source texture mip level. /// @param[in] _srcX Source texture X position. /// @param[in] _srcY Source texture Y position. /// @param[in] _srcZ If texture is 2D this argument should be 0. If source texture is cube /// this argument represents source texture cube face. For 3D texture this argument /// represents source texture Z position. /// @param[in] _width Width of region. /// @param[in] _height Height of region. /// @param[in] _depth If texture is 3D this argument represents depth of region, otherwise it's /// unused. /// /// @attention Destination texture must be created with `BGFX_TEXTURE_BLIT_DST` flag. /// @attention Availability depends on: `BGFX_CAPS_TEXTURE_BLIT`. /// @attention C99 equivalent is `bgfx_encoder_blit`. /// void blit( ViewId _id , TextureHandle _dst , uint8_t _dstMip , uint16_t _dstX , uint16_t _dstY , uint16_t _dstZ , TextureHandle _src , uint8_t _srcMip = 0 , uint16_t _srcX = 0 , uint16_t _srcY = 0 , uint16_t _srcZ = 0 , uint16_t _width = UINT16_MAX , uint16_t _height = UINT16_MAX , uint16_t _depth = UINT16_MAX ); }; /// Vertex layout. /// /// @attention C99 equivalent is `bgfx_vertex_layout_t`. /// struct VertexLayout { VertexLayout(); /// Start VertexLayout. /// /// @attention C99 equivalent is `bgfx_vertex_layout_begin`. /// VertexLayout& begin(RendererType::Enum _renderer = RendererType::Noop); /// End VertexLayout. /// /// @attention C99 equivalent is `bgfx_vertex_layout_end`. /// void end(); /// Add attribute to VertexLayout. /// /// @param[in] _attrib Attribute semantics. See: `bgfx::Attrib` /// @param[in] _num Number of elements 1, 2, 3 or 4. /// @param[in] _type Element type. /// @param[in] _normalized When using fixed point AttribType (f.e. Uint8) /// value will be normalized for vertex shader usage. When normalized /// is set to true, AttribType::Uint8 value in range 0-255 will be /// in range 0.0-1.0 in vertex shader. /// @param[in] _asInt Packaging rule for vertexPack, vertexUnpack, and /// vertexConvert for AttribType::Uint8 and AttribType::Int16. /// Unpacking code must be implemented inside vertex shader. /// /// @remarks /// Must be called between begin/end. /// /// @attention C99 equivalent is `bgfx_vertex_layout_add`. /// VertexLayout& add( Attrib::Enum _attrib , uint8_t _num , AttribType::Enum _type , bool _normalized = false , bool _asInt = false ); /// Skip _num bytes in vertex stream. /// /// @attention C99 equivalent is `bgfx_vertex_layout_skip`. /// VertexLayout& skip(uint8_t _num); /// Decode attribute. /// /// @attention C99 equivalent is `bgfx_vertex_layout_decode`. /// void decode( Attrib::Enum _attrib , uint8_t& _num , AttribType::Enum& _type , bool& _normalized , bool& _asInt ) const; /// Returns true if VertexLayout contains attribute. /// /// @attention C99 equivalent is `bgfx_vertex_layout_has`. /// bool has(Attrib::Enum _attrib) const { return UINT16_MAX != m_attributes[_attrib]; } /// Returns relative attribute offset from the vertex. uint16_t getOffset(Attrib::Enum _attrib) const { return m_offset[_attrib]; } /// Returns vertex stride. uint16_t getStride() const { return m_stride; } /// Returns size of vertex buffer for number of vertices. uint32_t getSize(uint32_t _num) const { return _num*m_stride; } uint32_t m_hash; uint16_t m_stride; uint16_t m_offset[Attrib::Count]; uint16_t m_attributes[Attrib::Count]; }; /// Pack vertex attribute into vertex stream format. /// /// @param[in] _input Value to be packed into vertex stream. /// @param[in] _inputNormalized True if input value is already normalized. /// @param[in] _attr Attribute to pack. /// @param[in] _layout Vertex stream layout. /// @param[in] _data Destination vertex stream where data will be packed. /// @param[in] _index Vertex index that will be modified. /// /// @attention C99 equivalent is `bgfx_vertex_pack`. /// void vertexPack( const float _input[4] , bool _inputNormalized , Attrib::Enum _attr , const VertexLayout& _layout , void* _data , uint32_t _index = 0 ); /// Unpack vertex attribute from vertex stream format. /// /// @param[out] _output Result of unpacking. /// @param[in] _attr Attribute to unpack. /// @param[in] _layout Vertex stream layout. /// @param[in] _data Source vertex stream from where data will be unpacked. /// @param[in] _index Vertex index that will be unpacked. /// /// @attention C99 equivalent is `bgfx_vertex_unpack`. /// void vertexUnpack( float _output[4] , Attrib::Enum _attr , const VertexLayout& _layout , const void* _data , uint32_t _index = 0 ); /// Converts vertex stream data from one vertex stream format to another. /// /// @param[in] _destLayout Destination vertex stream layout. /// @param[in] _destData Destination vertex stream. /// @param[in] _srcLayout Source vertex stream layout. /// @param[in] _srcData Source vertex stream data. /// @param[in] _num Number of vertices to convert from source to destination. /// /// @attention C99 equivalent is `bgfx_vertex_convert`. /// void vertexConvert( const VertexLayout& _destLayout , void* _destData , const VertexLayout& _srcLayout , const void* _srcData , uint32_t _num = 1 ); /// Weld vertices. /// /// @param[in] _output Welded vertices remapping table. The size of buffer /// must be the same as number of vertices. /// @param[in] _layout Vertex stream layout. /// @param[in] _data Vertex stream. /// @param[in] _num Number of vertices in vertex stream. /// @param[in] _index32 Set to `true` if input indices are 32-bit. /// @param[in] _epsilon Error tolerance for vertex position comparison. /// @returns Number of unique vertices after vertex welding. /// /// @attention C99 equivalent is `bgfx_weld_vertices`. /// uint32_t weldVertices( void* _output , const VertexLayout& _layout , const void* _data , uint32_t _num , bool _index32 , float _epsilon = 0.001f ); /// Convert index buffer for use with different primitive topologies. /// /// @param[in] _conversion Conversion type, see `TopologyConvert::Enum`. /// @param[in] _dst Destination index buffer. If this argument is NULL /// function will return number of indices after conversion. /// @param[in] _dstSize Destination index buffer in bytes. It must be /// large enough to contain output indices. If destination size is /// insufficient index buffer will be truncated. /// @param[in] _indices Source indices. /// @param[in] _numIndices Number of input indices. /// @param[in] _index32 Set to `true` if input indices are 32-bit. /// /// @returns Number of output indices after conversion. /// /// @attention C99 equivalent is `bgfx_topology_convert`. /// uint32_t topologyConvert( TopologyConvert::Enum _conversion , void* _dst , uint32_t _dstSize , const void* _indices , uint32_t _numIndices , bool _index32 ); /// Sort indices. /// /// @param[in] _sort Sort order, see `TopologySort::Enum`. /// @param[in] _dst Destination index buffer. /// @param[in] _dstSize Destination index buffer in bytes. It must be /// large enough to contain output indices. If destination size is /// insufficient index buffer will be truncated. /// @param[in] _dir Direction (vector must be normalized). /// @param[in] _pos Position. /// @param[in] _vertices Pointer to first vertex represented as /// float x, y, z. Must contain at least number of vertices /// referencende by index buffer. /// @param[in] _stride Vertex stride. /// @param[in] _indices Source indices. /// @param[in] _numIndices Number of input indices. /// @param[in] _index32 Set to `true` if input indices are 32-bit. /// /// @attention C99 equivalent is `bgfx_topology_sort_tri_list`. /// void topologySortTriList( TopologySort::Enum _sort , void* _dst , uint32_t _dstSize , const float _dir[3] , const float _pos[3] , const void* _vertices , uint32_t _stride , const void* _indices , uint32_t _numIndices , bool _index32 ); /// Returns supported backend API renderers. /// /// @param[in] _max Maximum number of elements in _enum array. /// @param[inout] _enum Array where supported renderers will be written. /// /// @returns Number of supported renderers. /// /// @attention C99 equivalent is `bgfx_get_supported_renderers`. /// uint8_t getSupportedRenderers( uint8_t _max = 0 , RendererType::Enum* _enum = NULL ); /// Returns name of renderer. /// /// @attention C99 equivalent is `bgfx_get_renderer_name`. /// const char* getRendererName(RendererType::Enum _type); /// Initialize bgfx library. /// /// @param[in] _init Initialization parameters. See: `bgfx::Init` for more info. /// /// @returns `true` if initialization was successful. /// /// @attention C99 equivalent is `bgfx_init`. /// bool init(const Init& _init = {}); /// Shutdown bgfx library. /// /// @attention C99 equivalent is `bgfx_shutdown`. /// void shutdown(); /// Reset graphic settings and back-buffer size. /// /// @param[in] _width Back-buffer width. /// @param[in] _height Back-buffer height. /// @param[in] _flags See: `BGFX_RESET_*` for more info. /// - `BGFX_RESET_NONE` - No reset flags. /// - `BGFX_RESET_FULLSCREEN` - Not supported yet. /// - `BGFX_RESET_MSAA_X[2/4/8/16]` - Enable 2, 4, 8 or 16 x MSAA. /// - `BGFX_RESET_VSYNC` - Enable V-Sync. /// - `BGFX_RESET_MAXANISOTROPY` - Turn on/off max anisotropy. /// - `BGFX_RESET_CAPTURE` - Begin screen capture. /// - `BGFX_RESET_FLUSH_AFTER_RENDER` - Flush rendering after submitting to GPU. /// - `BGFX_RESET_FLIP_AFTER_RENDER` - This flag specifies where flip /// occurs. Default behavior is that flip occurs before rendering new /// frame. This flag only has effect when `BGFX_CONFIG_MULTITHREADED=0`. /// - `BGFX_RESET_SRGB_BACKBUFFER` - Enable sRGB backbuffer. /// @param[in] _format Texture format. See: `TextureFormat::Enum`. /// /// @attention This call doesn't actually change window size, it just /// resizes back-buffer. Windowing code has to change window size. /// /// @attention C99 equivalent is `bgfx_reset`. /// void reset( uint32_t _width , uint32_t _height , uint32_t _flags = BGFX_RESET_NONE , TextureFormat::Enum _format = TextureFormat::Count ); /// Begin submitting draw calls from thread. /// /// @param[in] _forThread Explicitly request an encoder for a worker thread. /// Encoder* begin(bool _forThread = false); /// End submitting draw calls from thread. /// void end(Encoder* _encoder); /// Advance to next frame. When using multithreaded renderer, this call /// just swaps internal buffers, kicks render thread, and returns. In /// singlethreaded renderer this call does frame rendering. /// /// @param[in] _capture Capture frame with graphics debugger. /// /// @returns Current frame number. This might be used in conjunction with /// double/multi buffering data outside the library and passing it to /// library via `bgfx::makeRef` calls. /// /// @attention C99 equivalent is `bgfx_frame`. /// uint32_t frame(bool _capture = false); /// Returns current renderer backend API type. /// /// @remarks /// Library must be initialized. /// /// @attention C99 equivalent is `bgfx_get_renderer_type`. /// RendererType::Enum getRendererType(); /// Returns renderer capabilities. /// /// @returns Pointer to static `bgfx::Caps` structure. /// /// @remarks /// Library must be initialized. /// /// @attention C99 equivalent is `bgfx_get_caps`. /// const Caps* getCaps(); /// Returns performance counters. /// /// @attention Pointer returned is valid until `bgfx::frame` is called. /// @attention C99 equivalent is `bgfx_get_stats`. /// const Stats* getStats(); /// Allocate buffer to pass to bgfx calls. Data will be freed inside bgfx. /// /// @param[in] _size Size to allocate. /// /// @attention C99 equivalent is `bgfx_alloc`. /// const Memory* alloc(uint32_t _size); /// Allocate buffer and copy data into it. Data will be freed inside bgfx. /// /// @param[in] _data Pointer to data to be copied. /// @param[in] _size Size of data to be copied. /// /// @attention C99 equivalent is `bgfx_copy`. /// const Memory* copy( const void* _data , uint32_t _size ); /// Make reference to data to pass to bgfx. Unlike `bgfx::alloc`, this call /// doesn't allocate memory for data. It just copies the _data pointer. You /// can pass `ReleaseFn` function pointer to release this memory after it's /// consumed, otherwise you must make sure _data is available for at least 2 /// `bgfx::frame` calls. `ReleaseFn` function must be able to be called /// from any thread. /// /// @param[in] _data Pointer to data. /// @param[in] _size Size of data. /// @param[in] _releaseFn Callback function to release memory after use. /// @param[in] _userData User data to be passed to callback function. /// /// @attention Data passed must be available for at least 2 `bgfx::frame` calls. /// @attention C99 equivalent are `bgfx_make_ref`, `bgfx_make_ref_release`. /// const Memory* makeRef( const void* _data , uint32_t _size , ReleaseFn _releaseFn = NULL , void* _userData = NULL ); /// Set debug flags. /// /// @param[in] _debug Available flags: /// - `BGFX_DEBUG_IFH` - Infinitely fast hardware. When this flag is set /// all rendering calls will be skipped. This is useful when profiling /// to quickly assess potential bottlenecks between CPU and GPU. /// - `BGFX_DEBUG_PROFILER` - Enable profiler. /// - `BGFX_DEBUG_STATS` - Display internal statistics. /// - `BGFX_DEBUG_TEXT` - Display debug text. /// - `BGFX_DEBUG_WIREFRAME` - Wireframe rendering. All rendering /// primitives will be rendered as lines. /// /// @attention C99 equivalent is `bgfx_set_debug`. /// void setDebug(uint32_t _debug); /// Clear internal debug text buffer. /// /// @param[in] _attr Background color. /// @param[in] _small Default 8x16 or 8x8 font. /// /// @attention C99 equivalent is `bgfx_dbg_text_clear`. /// void dbgTextClear( uint8_t _attr = 0 , bool _small = false ); /// Print into internal debug text character-buffer (VGA-compatible text mode). /// /// @param[in] _x, _y 2D position from top-left. /// @param[in] _attr Color palette. Where top 4-bits represent index of background, and bottom /// 4-bits represent foreground color from standard VGA text palette (ANSI escape codes). /// @param[in] _format `printf` style format. /// /// @attention C99 equivalent is `bgfx_dbg_text_printf`. /// void dbgTextPrintf( uint16_t _x , uint16_t _y , uint8_t _attr , const char* _format , ... ); /// Print into internal debug text character-buffer (VGA-compatible text mode). /// /// @param[in] _x, _y 2D position from top-left. /// @param[in] _attr Color palette. Where top 4-bits represent index of background, and bottom /// 4-bits represent foreground color from standard VGA text palette (ANSI escape codes). /// @param[in] _format `printf` style format. /// @param[in] _argList additional arguments for format string /// /// @attention C99 equivalent is `bgfx_dbg_text_vprintf`. /// void dbgTextPrintfVargs( uint16_t _x , uint16_t _y , uint8_t _attr , const char* _format , va_list _argList ); /// Draw image into internal debug text buffer. /// /// @param[in] _x, _y 2D position from top-left. /// @param[in] _width, _height Image width and height. /// @param[in] _data Raw image data (character/attribute raw encoding). /// @param[in] _pitch Image pitch in bytes. /// /// @attention C99 equivalent is `bgfx_dbg_text_image`. /// void dbgTextImage( uint16_t _x , uint16_t _y , uint16_t _width , uint16_t _height , const void* _data , uint16_t _pitch ); /// Create static index buffer. /// /// @param[in] _mem Index buffer data. /// @param[in] _flags Buffer creation flags. /// - `BGFX_BUFFER_NONE` - No flags. /// - `BGFX_BUFFER_COMPUTE_READ` - Buffer will be read from by compute shader. /// - `BGFX_BUFFER_COMPUTE_WRITE` - Buffer will be written into by compute shader. When buffer /// is created with `BGFX_BUFFER_COMPUTE_WRITE` flag it cannot be updated from CPU. /// - `BGFX_BUFFER_COMPUTE_READ_WRITE` - Buffer will be used for read/write by compute shader. /// - `BGFX_BUFFER_ALLOW_RESIZE` - Buffer will resize on buffer update if a different amount of /// data is passed. If this flag is not specified, and more data is passed on update, the buffer /// will be trimmed to fit the existing buffer size. This flag has effect only on dynamic /// buffers. /// - `BGFX_BUFFER_INDEX32` - Buffer is using 32-bit indices. This flag has effect only on /// index buffers. /// /// @attention C99 equivalent is `bgfx_create_index_buffer`. /// IndexBufferHandle createIndexBuffer( const Memory* _mem , uint16_t _flags = BGFX_BUFFER_NONE ); /// Set static index buffer debug name. /// /// @param[in] _handle Static index buffer handle. /// @param[in] _name Static index buffer name. /// @param[in] _len Static index buffer name length (if length is INT32_MAX, it's expected /// that _name is zero terminated string. /// /// @attention C99 equivalent is `bgfx_set_index_buffer_name`. /// void setName( IndexBufferHandle _handle , const char* _name , int32_t _len = INT32_MAX ); /// Destroy static index buffer. /// /// @param[in] _handle Static index buffer handle. /// /// @attention C99 equivalent is `bgfx_destroy_index_buffer`. /// void destroy(IndexBufferHandle _handle); /// Create vertex layout. /// /// @attention C99 equivalent is `bgfx_create_vertex_layout`. /// VertexLayoutHandle createVertexLayout(const VertexLayout& _layout); /// Destroy vertex layout. /// /// @attention C99 equivalent is `bgfx_destroy_vertex_layout`. /// void destroy(VertexLayoutHandle _handle); /// Create static vertex buffer. /// /// @param[in] _mem Vertex buffer data. /// @param[in] _layout Vertex layout. /// @param[in] _flags Buffer creation flags. /// - `BGFX_BUFFER_NONE` - No flags. /// - `BGFX_BUFFER_COMPUTE_READ` - Buffer will be read from by compute shader. /// - `BGFX_BUFFER_COMPUTE_WRITE` - Buffer will be written into by compute shader. When buffer /// is created with `BGFX_BUFFER_COMPUTE_WRITE` flag it cannot be updated from CPU. /// - `BGFX_BUFFER_COMPUTE_READ_WRITE` - Buffer will be used for read/write by compute shader. /// - `BGFX_BUFFER_ALLOW_RESIZE` - Buffer will resize on buffer update if a different amount of /// data is passed. If this flag is not specified, and more data is passed on update, the buffer /// will be trimmed to fit the existing buffer size. This flag has effect only on dynamic /// buffers. /// - `BGFX_BUFFER_INDEX32` - Buffer is using 32-bit indices. This flag has effect only on /// index buffers. /// @returns Static vertex buffer handle. /// /// @attention C99 equivalent is `bgfx_create_vertex_buffer`. /// VertexBufferHandle createVertexBuffer( const Memory* _mem , const VertexLayout& _layout , uint16_t _flags = BGFX_BUFFER_NONE ); /// Set static vertex buffer debug name. /// /// @param[in] _handle Static vertex buffer handle. /// @param[in] _name Static vertex buffer name. /// @param[in] _len Static vertex buffer name length (if length is INT32_MAX, it's expected /// that _name is zero terminated string. /// /// @attention C99 equivalent is `bgfx_set_vertex_buffer_name`. /// void setName( VertexBufferHandle _handle , const char* _name , int32_t _len = INT32_MAX ); /// Destroy static vertex buffer. /// /// @param[in] _handle Static vertex buffer handle. /// /// @attention C99 equivalent is `bgfx_destroy_vertex_buffer`. /// void destroy(VertexBufferHandle _handle); /// Create empty dynamic index buffer. /// /// @param[in] _num Number of indices. /// @param[in] _flags Buffer creation flags. /// - `BGFX_BUFFER_NONE` - No flags. /// - `BGFX_BUFFER_COMPUTE_READ` - Buffer will be read from by compute shader. /// - `BGFX_BUFFER_COMPUTE_WRITE` - Buffer will be written into by compute shader. When buffer /// is created with `BGFX_BUFFER_COMPUTE_WRITE` flag it cannot be updated from CPU. /// - `BGFX_BUFFER_COMPUTE_READ_WRITE` - Buffer will be used for read/write by compute shader. /// - `BGFX_BUFFER_ALLOW_RESIZE` - Buffer will resize on buffer update if a different amount of /// data is passed. If this flag is not specified, and more data is passed on update, the buffer /// will be trimmed to fit the existing buffer size. This flag has effect only on dynamic /// buffers. /// - `BGFX_BUFFER_INDEX32` - Buffer is using 32-bit indices. This flag has effect only on /// index buffers. /// @returns Dynamic index buffer handle. /// /// @attention C99 equivalent is `bgfx_create_dynamic_index_buffer`. /// DynamicIndexBufferHandle createDynamicIndexBuffer( uint32_t _num , uint16_t _flags = BGFX_BUFFER_NONE ); /// Create dynamic index buffer and initialized it. /// /// @param[in] _mem Index buffer data. /// @param[in] _flags Buffer creation flags. /// - `BGFX_BUFFER_NONE` - No flags. /// - `BGFX_BUFFER_COMPUTE_READ` - Buffer will be read from by compute shader. /// - `BGFX_BUFFER_COMPUTE_WRITE` - Buffer will be written into by compute shader. When buffer /// is created with `BGFX_BUFFER_COMPUTE_WRITE` flag it cannot be updated from CPU. /// - `BGFX_BUFFER_COMPUTE_READ_WRITE` - Buffer will be used for read/write by compute shader. /// - `BGFX_BUFFER_ALLOW_RESIZE` - Buffer will resize on buffer update if a different amount of /// data is passed. If this flag is not specified, and more data is passed on update, the buffer /// will be trimmed to fit the existing buffer size. This flag has effect only on dynamic /// buffers. /// - `BGFX_BUFFER_INDEX32` - Buffer is using 32-bit indices. This flag has effect only on /// index buffers. /// @returns Dynamic index buffer handle. /// /// @attention C99 equivalent is `bgfx_create_dynamic_index_buffer_mem`. /// DynamicIndexBufferHandle createDynamicIndexBuffer( const Memory* _mem , uint16_t _flags = BGFX_BUFFER_NONE ); /// Update dynamic index buffer. /// /// @param[in] _handle Dynamic index buffer handle. /// @param[in] _startIndex Start index. /// @param[in] _mem Index buffer data. /// /// @attention C99 equivalent is `bgfx_update_dynamic_index_buffer`. /// void update( DynamicIndexBufferHandle _handle , uint32_t _startIndex , const Memory* _mem ); /// Destroy dynamic index buffer. /// /// @param[in] _handle Dynamic index buffer handle. /// /// @attention C99 equivalent is `bgfx_destroy_dynamic_index_buffer`. /// void destroy(DynamicIndexBufferHandle _handle); /// Create empty dynamic vertex buffer. /// /// @param[in] _num Number of vertices. /// @param[in] _layout Vertex layout. /// @param[in] _flags Buffer creation flags. /// - `BGFX_BUFFER_NONE` - No flags. /// - `BGFX_BUFFER_COMPUTE_READ` - Buffer will be read from by compute shader. /// - `BGFX_BUFFER_COMPUTE_WRITE` - Buffer will be written into by compute shader. When buffer /// is created with `BGFX_BUFFER_COMPUTE_WRITE` flag it cannot be updated from CPU. /// - `BGFX_BUFFER_COMPUTE_READ_WRITE` - Buffer will be used for read/write by compute shader. /// - `BGFX_BUFFER_ALLOW_RESIZE` - Buffer will resize on buffer update if a different amount of /// data is passed. If this flag is not specified, and more data is passed on update, the buffer /// will be trimmed to fit the existing buffer size. This flag has effect only on dynamic /// buffers. /// - `BGFX_BUFFER_INDEX32` - Buffer is using 32-bit indices. This flag has effect only on /// index buffers. /// @returns Dynamic vertex buffer handle. /// /// @attention C99 equivalent is `bgfx_create_dynamic_vertex_buffer`. /// DynamicVertexBufferHandle createDynamicVertexBuffer( uint32_t _num , const VertexLayout& _layout , uint16_t _flags = BGFX_BUFFER_NONE ); /// Create dynamic vertex buffer and initialize it. /// /// @param[in] _mem Vertex buffer data. /// @param[in] _layout Vertex layout. /// @param[in] _flags Buffer creation flags. /// - `BGFX_BUFFER_NONE` - No flags. /// - `BGFX_BUFFER_COMPUTE_READ` - Buffer will be read from by compute shader. /// - `BGFX_BUFFER_COMPUTE_WRITE` - Buffer will be written into by compute shader. When buffer /// is created with `BGFX_BUFFER_COMPUTE_WRITE` flag it cannot be updated from CPU. /// - `BGFX_BUFFER_COMPUTE_READ_WRITE` - Buffer will be used for read/write by compute shader. /// - `BGFX_BUFFER_ALLOW_RESIZE` - Buffer will resize on buffer update if a different amount of /// data is passed. If this flag is not specified, and more data is passed on update, the buffer /// will be trimmed to fit the existing buffer size. This flag has effect only on dynamic /// buffers. /// - `BGFX_BUFFER_INDEX32` - Buffer is using 32-bit indices. This flag has effect only on /// index buffers. /// @returns Dynamic vertex buffer handle. /// /// @attention C99 equivalent is `bgfx_create_dynamic_vertex_buffer_mem`. /// DynamicVertexBufferHandle createDynamicVertexBuffer( const Memory* _mem , const VertexLayout& _layout , uint16_t _flags = BGFX_BUFFER_NONE ); /// Update dynamic vertex buffer. /// /// @param[in] _handle Dynamic vertex buffer handle. /// @param[in] _startVertex Start vertex. /// @param[in] _mem Vertex buffer data. /// /// @attention C99 equivalent is `bgfx_update_dynamic_vertex_buffer`. /// void update( DynamicVertexBufferHandle _handle , uint32_t _startVertex , const Memory* _mem ); /// Destroy dynamic vertex buffer. /// /// @param[in] _handle Dynamic vertex buffer handle. /// /// @attention C99 equivalent is `bgfx_destroy_dynamic_vertex_buffer`. /// void destroy(DynamicVertexBufferHandle _handle); /// Returns number of requested or maximum available indices. /// /// @param[in] _num Number of required indices. /// /// @attention C99 equivalent is `bgfx_get_avail_transient_index_buffer`. /// uint32_t getAvailTransientIndexBuffer(uint32_t _num); /// Returns number of requested or maximum available vertices. /// /// @param[in] _num Number of required vertices. /// @param[in] _layout Vertex layout. /// /// @attention C99 equivalent is `bgfx_get_avail_transient_vertex_buffer`. /// uint32_t getAvailTransientVertexBuffer( uint32_t _num , const VertexLayout& _layout ); /// Returns number of requested or maximum available instance buffer slots. /// /// @param[in] _num Number of required instances. /// @param[in] _stride Stride per instance. /// /// @attention C99 equivalent is `bgfx_get_avail_instance_data_buffer`. /// uint32_t getAvailInstanceDataBuffer( uint32_t _num , uint16_t _stride ); /// Allocate transient index buffer. /// /// @param[out] _tib TransientIndexBuffer structure is filled and is valid /// for the duration of frame, and it can be reused for multiple draw /// calls. /// @param[in] _num Number of indices to allocate. /// @param[in] _index32 Set to `true` if input indices will be 32-bit. /// /// @remarks /// Only 16-bit index buffer is supported. /// /// @attention C99 equivalent is `bgfx_alloc_transient_index_buffer`. /// void allocTransientIndexBuffer( TransientIndexBuffer* _tib , uint32_t _num , bool _index32 = false ); /// Allocate transient vertex buffer. /// /// @param[out] _tvb TransientVertexBuffer structure is filled and is valid /// for the duration of frame, and it can be reused for multiple draw /// calls. /// @param[in] _num Number of vertices to allocate. /// @param[in] _layout Vertex layout. /// /// @attention C99 equivalent is `bgfx_alloc_transient_vertex_buffer`. /// void allocTransientVertexBuffer( TransientVertexBuffer* _tvb , uint32_t _num , const VertexLayout& _layout ); /// Check for required space and allocate transient vertex and index /// buffers. If both space requirements are satisfied function returns /// true. /// /// @remarks /// Only 16-bit index buffer is supported. /// /// @attention C99 equivalent is `bgfx_alloc_transient_buffers`. /// bool allocTransientBuffers( TransientVertexBuffer* _tvb , const VertexLayout& _layout , uint32_t _numVertices , TransientIndexBuffer* _tib , uint32_t _numIndices ); /// Allocate instance data buffer. /// /// @param[out] _idb InstanceDataBuffer structure is filled and is valid /// for duration of frame, and it can be reused for multiple draw /// calls. /// @param[in] _num Number of instances. /// @param[in] _stride Instance stride. Must be multiple of 16. /// /// @attention C99 equivalent is `bgfx_alloc_instance_data_buffer`. /// void allocInstanceDataBuffer( InstanceDataBuffer* _idb , uint32_t _num , uint16_t _stride ); /// Create draw indirect buffer. /// /// @param[in] _num Number of indirect calls. /// @returns Indirect buffer handle. /// /// @attention C99 equivalent is `bgfx_create_indirect_buffer`. /// IndirectBufferHandle createIndirectBuffer(uint32_t _num); /// Destroy draw indirect buffer. /// /// @param[in] _handle Indirect buffer handle. /// /// @attention C99 equivalent is `bgfx_destroy_indirect_buffer`. /// void destroy(IndirectBufferHandle _handle); /// Create shader from memory buffer. /// /// @attention C99 equivalent is `bgfx_create_shader`. /// ShaderHandle createShader(const Memory* _mem); /// Returns the number of uniforms and uniform handles used inside a shader. /// /// @param[in] _handle Shader handle. /// @param[in] _uniforms UniformHandle array where data will be stored. /// @param[in] _max Maximum capacity of array. /// @returns Number of uniforms used by shader. /// /// @remarks /// Only non-predefined uniforms are returned. /// /// @attention C99 equivalent is `bgfx_get_shader_uniforms`. /// uint16_t getShaderUniforms( ShaderHandle _handle , UniformHandle* _uniforms = NULL , uint16_t _max = 0 ); /// Set shader debug name. /// /// @param[in] _handle Shader handle. /// @param[in] _name Shader name. /// @param[in] _len Shader name length (if length is INT32_MAX, it's expected /// that _name is zero terminated string. /// /// @attention C99 equivalent is `bgfx_set_shader_name`. /// void setName( ShaderHandle _handle , const char* _name , int32_t _len = INT32_MAX ); /// Destroy shader. Once a shader program is created with _handle, /// it is safe to destroy that shader. /// /// @param[in] _handle Shader handle. /// /// @attention C99 equivalent is `bgfx_destroy_shader`. /// void destroy(ShaderHandle _handle); /// Create program with vertex and fragment shaders. /// /// @param[in] _vsh Vertex shader. /// @param[in] _fsh Fragment shader. /// @param[in] _destroyShaders If true, shaders will be destroyed when /// program is destroyed. /// @returns Program handle if vertex shader output and fragment shader /// input are matching, otherwise returns invalid program handle. /// /// @attention C99 equivalent is `bgfx_create_program`. /// ProgramHandle createProgram( ShaderHandle _vsh , ShaderHandle _fsh , bool _destroyShaders = false ); /// Create program with compute shader. /// /// @param[in] _csh Compute shader. /// @param[in] _destroyShader If true, shader will be destroyed when /// program is destroyed. /// @returns Program handle. /// /// @attention C99 equivalent is `bgfx_create_compute_program`. /// ProgramHandle createProgram( ShaderHandle _csh , bool _destroyShader = false ); /// Destroy program. /// /// @param[in] _handle Program handle. /// /// @attention C99 equivalent is `bgfx_destroy_program`. /// void destroy(ProgramHandle _handle); /// Validate texture parameters. /// /// @param[in] _depth Depth dimension of volume texture. /// @param[in] _cubeMap Indicates that texture contains cubemap. /// @param[in] _numLayers Number of layers in texture array. /// @param[in] _format Texture format. See: `TextureFormat::Enum`. /// @param[in] _flags Texture flags. See `BGFX_TEXTURE_*`. /// @returns True if texture can be successfully created. /// /// @attention C99 equivalent is `bgfx_is_texture_valid`. /// bool isTextureValid( uint16_t _depth , bool _cubeMap , uint16_t _numLayers , TextureFormat::Enum _format , uint64_t _flags ); /// Validate frame buffer parameters. /// /// @param[in] _num Number of attachments. /// @param[in] _attachment Attachment texture info. See: `bgfx::Attachment`. /// /// @returns True if frame buffer can be successfully created. /// bool isFrameBufferValid( uint8_t _num , const Attachment* _attachment ); /// Calculate amount of memory required for texture. /// /// @param[out] _info Resulting texture info structure. See: `TextureInfo`. /// @param[in] _width Width. /// @param[in] _height Height. /// @param[in] _depth Depth dimension of volume texture. /// @param[in] _cubeMap Indicates that texture contains cubemap. /// @param[in] _hasMips Indicates that texture contains full mip-map chain. /// @param[in] _numLayers Number of layers in texture array. /// @param[in] _format Texture format. See: `TextureFormat::Enum`. /// /// @attention C99 equivalent is `bgfx_calc_texture_size`. /// void calcTextureSize( TextureInfo& _info , uint16_t _width , uint16_t _height , uint16_t _depth , bool _cubeMap , bool _hasMips , uint16_t _numLayers , TextureFormat::Enum _format ); /// Create texture from memory buffer. /// /// @param[in] _mem DDS, KTX or PVR texture data. /// @param[in] _flags Texture creation (see `BGFX_TEXTURE_*`.), and sampler (see `BGFX_SAMPLER_*`) /// flags. Default texture sampling mode is linear, and wrap mode is repeat. /// - `BGFX_SAMPLER_[U/V/W]_[MIRROR/CLAMP]` - Mirror or clamp to edge wrap /// mode. /// - `BGFX_SAMPLER_[MIN/MAG/MIP]_[POINT/ANISOTROPIC]` - Point or anisotropic /// sampling. /// /// @param[in] _skip Skip top level mips when parsing texture. /// @param[out] _info When non-`NULL` is specified it returns parsed texture information. /// @returns Texture handle. /// /// @attention C99 equivalent is `bgfx_create_texture`. /// TextureHandle createTexture( const Memory* _mem , uint64_t _flags = BGFX_TEXTURE_NONE|BGFX_SAMPLER_NONE , uint8_t _skip = 0 , TextureInfo* _info = NULL ); /// Create 2D texture. /// /// @param[in] _width Width. /// @param[in] _height Height. /// @param[in] _hasMips Indicates that texture contains full mip-map chain. /// @param[in] _numLayers Number of layers in texture array. Must be 1 if caps /// `BGFX_CAPS_TEXTURE_2D_ARRAY` flag is not set. /// @param[in] _format Texture format. See: `TextureFormat::Enum`. /// @param[in] _flags Texture creation (see `BGFX_TEXTURE_*`.), and sampler (see `BGFX_SAMPLER_*`) /// flags. Default texture sampling mode is linear, and wrap mode is repeat. /// - `BGFX_SAMPLER_[U/V/W]_[MIRROR/CLAMP]` - Mirror or clamp to edge wrap /// mode. /// - `BGFX_SAMPLER_[MIN/MAG/MIP]_[POINT/ANISOTROPIC]` - Point or anisotropic /// sampling. /// /// @param[in] _mem Texture data. If `_mem` is non-NULL, created texture will be immutable. If /// `_mem` is NULL content of the texture is uninitialized. When `_numLayers` is more than /// 1, expected memory layout is texture and all mips together for each array element. /// /// @attention C99 equivalent is `bgfx_create_texture_2d`. /// TextureHandle createTexture2D( uint16_t _width , uint16_t _height , bool _hasMips , uint16_t _numLayers , TextureFormat::Enum _format , uint64_t _flags = BGFX_TEXTURE_NONE|BGFX_SAMPLER_NONE , const Memory* _mem = NULL ); /// Create texture with size based on backbuffer ratio. Texture will maintain ratio /// if back buffer resolution changes. /// /// @param[in] _ratio Frame buffer size in respect to back-buffer size. See: /// `BackbufferRatio::Enum`. /// @param[in] _hasMips Indicates that texture contains full mip-map chain. /// @param[in] _numLayers Number of layers in texture array. Must be 1 if caps /// `BGFX_CAPS_TEXTURE_2D_ARRAY` flag is not set. /// @param[in] _format Texture format. See: `TextureFormat::Enum`. /// @param[in] _flags Texture creation (see `BGFX_TEXTURE_*`.), and sampler (see `BGFX_SAMPLER_*`) /// flags. Default texture sampling mode is linear, and wrap mode is repeat. /// - `BGFX_SAMPLER_[U/V/W]_[MIRROR/CLAMP]` - Mirror or clamp to edge wrap /// mode. /// - `BGFX_SAMPLER_[MIN/MAG/MIP]_[POINT/ANISOTROPIC]` - Point or anisotropic /// sampling. /// /// @attention C99 equivalent is `bgfx_create_texture_2d_scaled`. /// TextureHandle createTexture2D( BackbufferRatio::Enum _ratio , bool _hasMips , uint16_t _numLayers , TextureFormat::Enum _format , uint64_t _flags = BGFX_TEXTURE_NONE|BGFX_SAMPLER_NONE ); /// Create 3D texture. /// /// @param[in] _width Width. /// @param[in] _height Height. /// @param[in] _depth Depth. /// @param[in] _hasMips Indicates that texture contains full mip-map chain. /// @param[in] _format Texture format. See: `TextureFormat::Enum`. /// @param[in] _flags Texture creation (see `BGFX_TEXTURE_*`.), and sampler (see `BGFX_SAMPLER_*`) /// flags. Default texture sampling mode is linear, and wrap mode is repeat. /// - `BGFX_SAMPLER_[U/V/W]_[MIRROR/CLAMP]` - Mirror or clamp to edge wrap /// mode. /// - `BGFX_SAMPLER_[MIN/MAG/MIP]_[POINT/ANISOTROPIC]` - Point or anisotropic /// sampling. /// /// @param[in] _mem Texture data. If `_mem` is non-NULL, created texture will be immutable. If /// `_mem` is NULL content of the texture is uninitialized. /// /// @attention C99 equivalent is `bgfx_create_texture_3d`. /// TextureHandle createTexture3D( uint16_t _width , uint16_t _height , uint16_t _depth , bool _hasMips , TextureFormat::Enum _format , uint64_t _flags = BGFX_TEXTURE_NONE|BGFX_SAMPLER_NONE , const Memory* _mem = NULL ); /// Create Cube texture. /// /// @param[in] _size Cube side size. /// @param[in] _hasMips Indicates that texture contains full mip-map chain. /// @param[in] _numLayers Number of layers in texture array. Must be 1 if caps /// `BGFX_CAPS_TEXTURE_CUBE_ARRAY` flag is not set. /// @param[in] _format Texture format. See: `TextureFormat::Enum`. /// @param[in] _flags Texture creation (see `BGFX_TEXTURE_*`.), and sampler (see `BGFX_SAMPLER_*`) /// flags. Default texture sampling mode is linear, and wrap mode is repeat. /// - `BGFX_SAMPLER_[U/V/W]_[MIRROR/CLAMP]` - Mirror or clamp to edge wrap /// mode. /// - `BGFX_SAMPLER_[MIN/MAG/MIP]_[POINT/ANISOTROPIC]` - Point or anisotropic /// sampling. /// /// @param[in] _mem Texture data. If `_mem` is non-NULL, created texture will be immutable. If /// `_mem` is NULL content of the texture is uninitialized. When `_numLayers` is more than /// 1, expected memory layout is texture and all mips together for each array element. /// /// @attention C99 equivalent is `bgfx_create_texture_cube`. /// TextureHandle createTextureCube( uint16_t _size , bool _hasMips , uint16_t _numLayers , TextureFormat::Enum _format , uint64_t _flags = BGFX_TEXTURE_NONE|BGFX_SAMPLER_NONE , const Memory* _mem = NULL ); /// Update 2D texture. /// /// @param[in] _handle Texture handle. /// @param[in] _layer Layers in texture array. /// @param[in] _mip Mip level. /// @param[in] _x X offset in texture. /// @param[in] _y Y offset in texture. /// @param[in] _width Width of texture block. /// @param[in] _height Height of texture block. /// @param[in] _mem Texture update data. /// @param[in] _pitch Pitch of input image (bytes). When _pitch is set to /// UINT16_MAX, it will be calculated internally based on _width. /// /// @attention It's valid to update only mutable texture. See `bgfx::createTexture2D` for more info. /// /// @attention C99 equivalent is `bgfx_update_texture_2d`. /// void updateTexture2D( TextureHandle _handle , uint16_t _layer , uint8_t _mip , uint16_t _x , uint16_t _y , uint16_t _width , uint16_t _height , const Memory* _mem , uint16_t _pitch = UINT16_MAX ); /// Update 3D texture. /// /// @param[in] _handle Texture handle. /// @param[in] _mip Mip level. /// @param[in] _x X offset in texture. /// @param[in] _y Y offset in texture. /// @param[in] _z Z offset in texture. /// @param[in] _width Width of texture block. /// @param[in] _height Height of texture block. /// @param[in] _depth Depth of texture block. /// @param[in] _mem Texture update data. /// /// @attention It's valid to update only mutable texture. See `bgfx::createTexture3D` for more info. /// /// @attention C99 equivalent is `bgfx_update_texture_3d`. /// void updateTexture3D( TextureHandle _handle , uint8_t _mip , uint16_t _x , uint16_t _y , uint16_t _z , uint16_t _width , uint16_t _height , uint16_t _depth , const Memory* _mem ); /// Update Cube texture. /// /// @param[in] _handle Texture handle. /// @param[in] _layer Layers in texture array. /// @param[in] _side Cubemap side `BGFX_CUBE_MAP_<POSITIVE or NEGATIVE>_<X, Y or Z>`, /// where 0 is +X, 1 is -X, 2 is +Y, 3 is -Y, 4 is +Z, and 5 is -Z. /// /// +----------+ /// |-z 2| /// | ^ +y | /// | | | Unfolded cube: /// | +---->+x | /// +----------+----------+----------+----------+ /// |+y 1|+y 4|+y 0|+y 5| /// | ^ -x | ^ +z | ^ +x | ^ -z | /// | | | | | | | | | /// | +---->+z | +---->+x | +---->-z | +---->-x | /// +----------+----------+----------+----------+ /// |+z 3| /// | ^ -y | /// | | | /// | +---->+x | /// +----------+ /// /// @param[in] _mip Mip level. /// @param[in] _x X offset in texture. /// @param[in] _y Y offset in texture. /// @param[in] _width Width of texture block. /// @param[in] _height Height of texture block. /// @param[in] _mem Texture update data. /// @param[in] _pitch Pitch of input image (bytes). When _pitch is set to /// UINT16_MAX, it will be calculated internally based on _width. /// /// @attention It's valid to update only mutable texture. See `bgfx::createTextureCube` for more info. /// /// @attention C99 equivalent is `bgfx_update_texture_cube`. /// void updateTextureCube( TextureHandle _handle , uint16_t _layer , uint8_t _side , uint8_t _mip , uint16_t _x , uint16_t _y , uint16_t _width , uint16_t _height , const Memory* _mem , uint16_t _pitch = UINT16_MAX ); /// Read back texture content. /// /// @param[in] _handle Texture handle. /// @param[in] _data Destination buffer. /// @param[in] _mip Mip level. /// /// @returns Frame number when the result will be available. See: `bgfx::frame`. /// /// @attention Texture must be created with `BGFX_TEXTURE_READ_BACK` flag. /// @attention Availability depends on: `BGFX_CAPS_TEXTURE_READ_BACK`. /// @attention C99 equivalent is `bgfx_read_texture`. /// uint32_t readTexture( TextureHandle _handle , void* _data , uint8_t _mip = 0 ); /// Set texture debug name. /// /// @param[in] _handle Texture handle. /// @param[in] _name Texture name. /// @param[in] _len Texture name length (if length is INT32_MAX, it's expected /// that _name is zero terminated string. /// /// @attention C99 equivalent is `bgfx_set_texture_name`. /// void setName( TextureHandle _handle , const char* _name , int32_t _len = INT32_MAX ); /// Returns texture direct access pointer. /// /// @param[in] _handle Texture handle. /// /// @returns Pointer to texture memory. If returned pointer is `NULL` direct access /// is not available for this texture. If pointer is `UINTPTR_MAX` sentinel value /// it means texture is pending creation. Pointer returned can be cached and it /// will be valid until texture is destroyed. /// /// @attention Availability depends on: `BGFX_CAPS_TEXTURE_DIRECT_ACCESS`. This feature /// is available on GPUs that have unified memory architecture (UMA) support. /// /// @attention C99 equivalent is `bgfx_get_direct_access_ptr`. /// void* getDirectAccessPtr(TextureHandle _handle); /// Destroy texture. /// /// @param[in] _handle Texture handle. /// /// @attention C99 equivalent is `bgfx_destroy_texture`. /// void destroy(TextureHandle _handle); /// Create frame buffer (simple). /// /// @param[in] _width Texture width. /// @param[in] _height Texture height. /// @param[in] _format Texture format. See: `TextureFormat::Enum`. /// @param[in] _textureFlags Default texture sampling mode is linear, and wrap mode /// is repeat. /// - `BGFX_SAMPLER_[U/V/W]_[MIRROR/CLAMP]` - Mirror or clamp to edge wrap /// mode. /// - `BGFX_SAMPLER_[MIN/MAG/MIP]_[POINT/ANISOTROPIC]` - Point or anisotropic /// sampling. /// /// @returns Handle to frame buffer object. /// /// @attention C99 equivalent is `bgfx_create_frame_buffer`. /// FrameBufferHandle createFrameBuffer( uint16_t _width , uint16_t _height , TextureFormat::Enum _format , uint64_t _textureFlags = BGFX_SAMPLER_U_CLAMP|BGFX_SAMPLER_V_CLAMP ); /// Create frame buffer with size based on backbuffer ratio. Frame buffer will maintain ratio /// if back buffer resolution changes. /// /// @param[in] _ratio Frame buffer size in respect to back-buffer size. See: /// `BackbufferRatio::Enum`. /// @param[in] _format Texture format. See: `TextureFormat::Enum`. /// @param[in] _textureFlags Default texture sampling mode is linear, and wrap mode /// is repeat. /// - `BGFX_SAMPLER_[U/V/W]_[MIRROR/CLAMP]` - Mirror or clamp to edge wrap /// mode. /// - `BGFX_SAMPLER_[MIN/MAG/MIP]_[POINT/ANISOTROPIC]` - Point or anisotropic /// sampling. /// /// @returns Handle to frame buffer object. /// /// @attention C99 equivalent is `bgfx_create_frame_buffer_scaled`. /// FrameBufferHandle createFrameBuffer( BackbufferRatio::Enum _ratio , TextureFormat::Enum _format , uint64_t _textureFlags = BGFX_SAMPLER_U_CLAMP|BGFX_SAMPLER_V_CLAMP ); /// Create MRT frame buffer from texture handles (simple). /// /// @param[in] _num Number of texture attachments. /// @param[in] _handles Texture attachments. /// @param[in] _destroyTextures If true, textures will be destroyed when /// frame buffer is destroyed. /// /// @returns Handle to frame buffer object. /// /// @attention C99 equivalent is `bgfx_create_frame_buffer_from_handles`. /// FrameBufferHandle createFrameBuffer( uint8_t _num , const TextureHandle* _handles , bool _destroyTextures = false ); /// Create MRT frame buffer from texture handles with specific layer and /// mip level. /// /// @param[in] _num Number of texture attachments. /// @param[in] _attachment Attachment texture info. See: `bgfx::Attachment`. /// @param[in] _destroyTextures If true, textures will be destroyed when /// frame buffer is destroyed. /// /// @returns Handle to frame buffer object. /// /// @attention C99 equivalent is `bgfx_create_frame_buffer_from_attachment`. /// FrameBufferHandle createFrameBuffer( uint8_t _num , const Attachment* _attachment , bool _destroyTextures = false ); /// Create frame buffer for multiple window rendering. /// /// @param[in] _nwh OS' target native window handle. /// @param[in] _width Window back buffer width. /// @param[in] _height Window back buffer height. /// @param[in] _format Window back buffer color format. /// @param[in] _depthFormat Window back buffer depth format. /// /// @returns Handle to frame buffer object. /// /// @remarks /// Frame buffer cannot be used for sampling. /// /// @attention C99 equivalent is `bgfx_create_frame_buffer_from_nwh`. /// FrameBufferHandle createFrameBuffer( void* _nwh , uint16_t _width , uint16_t _height , TextureFormat::Enum _format = TextureFormat::Count , TextureFormat::Enum _depthFormat = TextureFormat::Count ); /// Set frame buffer debug name. /// /// @param[in] _handle frame buffer handle. /// @param[in] _name frame buffer name. /// @param[in] _len frame buffer name length (if length is INT32_MAX, it's expected /// that _name is zero terminated string. /// /// @attention C99 equivalent is `bgfx_set_frame_buffer_name`. /// void setName( FrameBufferHandle _handle , const char* _name , int32_t _len = INT32_MAX ); /// Obtain texture handle of frame buffer attachment. /// /// @param[in] _handle Frame buffer handle. /// @param[in] _attachment Frame buffer attachment index. /// /// @returns Returns invalid texture handle if attachment index is not /// correct, or frame buffer is created with native window handle. /// /// @attention C99 equivalent is `bgfx_get_texture`. /// TextureHandle getTexture( FrameBufferHandle _handle , uint8_t _attachment = 0 ); /// Destroy frame buffer. /// /// @param[in] _handle Frame buffer handle. /// /// @attention C99 equivalent is `bgfx_destroy_frame_buffer`. /// void destroy(FrameBufferHandle _handle); /// Create shader uniform parameter. /// /// @param[in] _name Uniform name in shader. /// @param[in] _type Type of uniform (See: `bgfx::UniformType`). /// @param[in] _num Number of elements in array. /// /// @returns Handle to uniform object. /// /// @remarks /// 1. Uniform names are unique. It's valid to call `bgfx::createUniform` /// multiple times with the same uniform name. The library will always /// return the same handle, but the handle reference count will be /// incremented. This means that the same number of `bgfx::destroyUniform` /// must be called to properly destroy the uniform. /// /// 2. Predefined uniforms (declared in `bgfx_shader.sh`): /// - `u_viewRect vec4(x, y, width, height)` - view rectangle for current /// view, in pixels. /// - `u_viewTexel vec4(1.0/width, 1.0/height, undef, undef)` - inverse /// width and height /// - `u_view mat4` - view matrix /// - `u_invView mat4` - inverted view matrix /// - `u_proj mat4` - projection matrix /// - `u_invProj mat4` - inverted projection matrix /// - `u_viewProj mat4` - concatenated view projection matrix /// - `u_invViewProj mat4` - concatenated inverted view projection matrix /// - `u_model mat4[BGFX_CONFIG_MAX_BONES]` - array of model matrices. /// - `u_modelView mat4` - concatenated model view matrix, only first /// model matrix from array is used. /// - `u_modelViewProj mat4` - concatenated model view projection matrix. /// - `u_alphaRef float` - alpha reference value for alpha test. /// /// @attention C99 equivalent is `bgfx_create_uniform`. /// UniformHandle createUniform( const char* _name , UniformType::Enum _type , uint16_t _num = 1 ); /// Retrieve uniform info. /// /// @param[in] _handle Handle to uniform object. /// @param[out] _info Uniform info. /// /// @attention C99 equivalent is `bgfx_get_uniform_info`. /// void getUniformInfo( UniformHandle _handle , UniformInfo& _info ); /// Destroy shader uniform parameter. /// /// @param[in] _handle Handle to uniform object. /// /// @attention C99 equivalent is `bgfx_destroy_uniform`. /// void destroy(UniformHandle _handle); /// Create occlusion query. /// /// @returns Handle to occlusion query object. /// /// @attention C99 equivalent is `bgfx_create_occlusion_query`. /// OcclusionQueryHandle createOcclusionQuery(); /// Retrieve occlusion query result from previous frame. /// /// @param[in] _handle Handle to occlusion query object. /// @param[out] _result Number of pixels that passed test. This argument /// can be `NULL` if result of occlusion query is not needed. /// @returns Occlusion query result. /// /// @attention C99 equivalent is `bgfx_get_result`. /// OcclusionQueryResult::Enum getResult( OcclusionQueryHandle _handle , int32_t* _result = NULL ); /// Destroy occlusion query. /// /// @param[in] _handle Handle to occlusion query object. /// /// @attention C99 equivalent is `bgfx_destroy_occlusion_query`. /// void destroy(OcclusionQueryHandle _handle); /// Set palette color value. /// /// @param[in] _index Index into palette. /// @param[in] _rgba Packed 32-bit RGBA value. /// /// @attention C99 equivalent is `bgfx_set_palette_color`. /// void setPaletteColor( uint8_t _index , uint32_t _rgba ); /// Set palette color value. /// /// @param[in] _index Index into palette. /// @param[in] _r, _g, _b, _a RGBA floating point values. /// /// @attention C99 equivalent is `bgfx_set_palette_color`. /// void setPaletteColor( uint8_t _index , float _r , float _g , float _b , float _a ); /// Set palette color value. /// /// @param[in] _index Index into palette. /// @param[in] _rgba RGBA floating point value. /// /// @attention C99 equivalent is `bgfx_set_palette_color`. /// void setPaletteColor( uint8_t _index , const float _rgba[4] ); /// Set view name. /// /// @param[in] _id View id. /// @param[in] _name View name. /// /// @remarks /// This is debug only feature. /// /// In graphics debugger view name will appear as: /// /// "nnnce <view name>" /// ^ ^^ ^ /// | |+-- eye (L/R) /// | +--- compute (C) /// +------ view id /// /// @attention C99 equivalent is `bgfx_set_view_name`. /// void setViewName( ViewId _id , const char* _name ); /// Set view rectangle. Draw primitive outside view will be clipped. /// /// @param[in] _id View id. /// @param[in] _x Position x from the left corner of the window. /// @param[in] _y Position y from the top corner of the window. /// @param[in] _width Width of view port region. /// @param[in] _height Height of view port region. /// /// @attention C99 equivalent is `bgfx_set_view_rect`. /// void setViewRect( ViewId _id , uint16_t _x , uint16_t _y , uint16_t _width , uint16_t _height ); /// Set view rectangle. Draw primitive outside view will be clipped. /// /// @param[in] _id View id. /// @param[in] _x Position x from the left corner of the window. /// @param[in] _y Position y from the top corner of the window. /// @param[in] _ratio Width and height will be set in respect to back-buffer size. See: /// `BackbufferRatio::Enum`. /// /// @attention C99 equivalent is `bgfx_set_view_rect_ratio`. /// void setViewRect( ViewId _id , uint16_t _x , uint16_t _y , BackbufferRatio::Enum _ratio ); /// Set view scissor. Draw primitive outside view will be clipped. When /// _x, _y, _width and _height are set to 0, scissor will be disabled. /// /// @param[in] _id View id. /// @param[in] _x Position x from the left corner of the window. /// @param[in] _y Position y from the top corner of the window. /// @param[in] _width Width of scissor region. /// @param[in] _height Height of scissor region. /// /// @attention C99 equivalent is `bgfx_set_view_scissor`. /// void setViewScissor( ViewId _id , uint16_t _x = 0 , uint16_t _y = 0 , uint16_t _width = 0 , uint16_t _height = 0 ); /// Set view clear flags. /// /// @param[in] _id View id. /// @param[in] _flags Clear flags. Use `BGFX_CLEAR_NONE` to remove any clear /// operation. See: `BGFX_CLEAR_*`. /// @param[in] _rgba Color clear value. /// @param[in] _depth Depth clear value. /// @param[in] _stencil Stencil clear value. /// /// @attention C99 equivalent is `bgfx_set_view_clear`. /// void setViewClear( ViewId _id , uint16_t _flags , uint32_t _rgba = 0x000000ff , float _depth = 1.0f , uint8_t _stencil = 0 ); /// Set view clear flags with different clear color for each /// frame buffer texture. Must use `bgfx::setPaletteColor` to setup clear color /// palette. /// /// @param[in] _id View id. /// @param[in] _flags Clear flags. Use `BGFX_CLEAR_NONE` to remove any clear /// operation. See: `BGFX_CLEAR_*`. /// @param[in] _depth Depth clear value. /// @param[in] _stencil Stencil clear value. /// @param[in] _0 Palette index for frame buffer attachment 0. /// @param[in] _1 Palette index for frame buffer attachment 1. /// @param[in] _2 Palette index for frame buffer attachment 2. /// @param[in] _3 Palette index for frame buffer attachment 3. /// @param[in] _4 Palette index for frame buffer attachment 4. /// @param[in] _5 Palette index for frame buffer attachment 5. /// @param[in] _6 Palette index for frame buffer attachment 6. /// @param[in] _7 Palette index for frame buffer attachment 7. /// /// @attention C99 equivalent is `bgfx_set_view_clear_mrt`. /// void setViewClear( ViewId _id , uint16_t _flags , float _depth , uint8_t _stencil , uint8_t _0 = UINT8_MAX , uint8_t _1 = UINT8_MAX , uint8_t _2 = UINT8_MAX , uint8_t _3 = UINT8_MAX , uint8_t _4 = UINT8_MAX , uint8_t _5 = UINT8_MAX , uint8_t _6 = UINT8_MAX , uint8_t _7 = UINT8_MAX ); /// Set view sorting mode. /// /// @param[in] _id View id. /// @param[in] _mode View sort mode. See `ViewMode::Enum`. /// /// @remarks /// View mode must be set prior calling `bgfx::submit` for the view. /// /// @attention C99 equivalent is `bgfx_set_view_mode`. /// void setViewMode( ViewId _id , ViewMode::Enum _mode = ViewMode::Default ); /// Set view frame buffer. /// /// @param[in] _id View id. /// @param[in] _handle Frame buffer handle. Passing `BGFX_INVALID_HANDLE` as /// frame buffer handle will draw primitives from this view into /// default back buffer. /// /// @remarks /// Not persistent after `bgfx::reset` call. /// /// @attention C99 equivalent is `bgfx_set_view_frame_buffer`. /// void setViewFrameBuffer( ViewId _id , FrameBufferHandle _handle ); /// Set view view and projection matrices, all draw primitives in this /// view will use these matrices. /// /// @param[in] _id View id. /// @param[in] _view View matrix. /// @param[in] _proj Projection matrix. /// /// @attention C99 equivalent is `bgfx_set_view_transform`. /// void setViewTransform( ViewId _id , const void* _view , const void* _proj ); /// Post submit view reordering. /// /// @param[in] _id First view id. /// @param[in] _num Number of views to remap. /// @param[in] _remap View remap id table. Passing `NULL` will reset view ids /// to default state. /// /// @attention C99 equivalent is `bgfx_set_view_order`. /// void setViewOrder( ViewId _id = 0 , uint16_t _num = UINT16_MAX , const ViewId* _remap = NULL ); /// Reset all view settings to default. /// /// @param[in] _id View id. /// /// @attention C99 equivalent is `bgfx_reset_view`. /// void resetView(ViewId _id); /// Sets debug marker. /// /// @attention C99 equivalent is `bgfx_set_marker`. /// void setMarker(const char* _marker); /// Set render states for draw primitive. /// /// @param[in] _state State flags. Default state for primitive type is /// triangles. See: `BGFX_STATE_DEFAULT`. /// - `BGFX_STATE_DEPTH_TEST_*` - Depth test function. /// - `BGFX_STATE_BLEND_*` - See remark 1 about BGFX_STATE_BLEND_FUNC. /// - `BGFX_STATE_BLEND_EQUATION_*` - See remark 2. /// - `BGFX_STATE_CULL_*` - Backface culling mode. /// - `BGFX_STATE_WRITE_*` - Enable R, G, B, A or Z write. /// - `BGFX_STATE_MSAA` - Enable MSAA. /// - `BGFX_STATE_PT_[TRISTRIP/LINES/POINTS]` - Primitive type. /// /// @param[in] _rgba Sets blend factor used by `BGFX_STATE_BLEND_FACTOR` and /// `BGFX_STATE_BLEND_INV_FACTOR` blend modes. /// /// @remarks /// 1. To setup more complex states use: /// `BGFX_STATE_ALPHA_REF(_ref)`, /// `BGFX_STATE_POINT_SIZE(_size)`, /// `BGFX_STATE_BLEND_FUNC(_src, _dst)`, /// `BGFX_STATE_BLEND_FUNC_SEPARATE(_srcRGB, _dstRGB, _srcA, _dstA)` /// `BGFX_STATE_BLEND_EQUATION(_equation)` /// `BGFX_STATE_BLEND_EQUATION_SEPARATE(_equationRGB, _equationA)` /// 2. `BGFX_STATE_BLEND_EQUATION_ADD` is set when no other blend /// equation is specified. /// /// @attention C99 equivalent is `bgfx_set_state`. /// void setState( uint64_t _state , uint32_t _rgba = 0 ); /// Set condition for rendering. /// /// @param[in] _handle Occlusion query handle. /// @param[in] _visible Render if occlusion query is visible. /// /// @attention C99 equivalent is `bgfx_set_condition`. /// void setCondition( OcclusionQueryHandle _handle , bool _visible ); /// Set stencil test state. /// /// @param[in] _fstencil Front stencil state. /// @param[in] _bstencil Back stencil state. If back is set to `BGFX_STENCIL_NONE` /// _fstencil is applied to both front and back facing primitives. /// /// @attention C99 equivalent is `bgfx_set_stencil`. /// void setStencil( uint32_t _fstencil , uint32_t _bstencil = BGFX_STENCIL_NONE ); /// Set scissor for draw primitive. For scissor for all primitives in /// view see `bgfx::setViewScissor`. /// /// @param[in] _x Position x from the left corner of the window. /// @param[in] _y Position y from the top corner of the window. /// @param[in] _width Width of scissor region. /// @param[in] _height Height of scissor region. /// @returns Scissor cache index. /// /// @attention C99 equivalent is `bgfx_set_scissor`. /// uint16_t setScissor( uint16_t _x , uint16_t _y , uint16_t _width , uint16_t _height ); /// Set scissor from cache for draw primitive. /// /// @param[in] _cache Index in scissor cache. Passing UINT16_MAX unset primitive /// scissor and primitive will use view scissor instead. /// /// @attention C99 equivalent is `bgfx_set_scissor_cached`. /// void setScissor(uint16_t _cache = UINT16_MAX); /// Set model matrix for draw primitive. If it is not called, /// the model will be rendered with an identity model matrix. /// /// @param[in] _mtx Pointer to first matrix in array. /// @param[in] _num Number of matrices in array. /// @returns index into matrix cache in case the same model matrix has /// to be used for other draw primitive call. /// /// @attention C99 equivalent is `bgfx_set_transform`. /// uint32_t setTransform( const void* _mtx , uint16_t _num = 1 ); /// Reserve `_num` matrices in internal matrix cache. /// /// @param[in] _transform Pointer to `Transform` structure. /// @param[in] _num Number of matrices. /// @returns index into matrix cache. /// /// @attention Pointer returned can be modifed until `bgfx::frame` is called. /// @attention C99 equivalent is `bgfx_alloc_transform`. /// uint32_t allocTransform( Transform* _transform , uint16_t _num ); /// Set model matrix from matrix cache for draw primitive. /// /// @param[in] _cache Index in matrix cache. /// @param[in] _num Number of matrices from cache. /// /// @attention C99 equivalent is `bgfx_set_transform_cached`. /// void setTransform( uint32_t _cache , uint16_t _num = 1 ); /// Set shader uniform parameter for draw primitive. /// /// @param[in] _handle Uniform. /// @param[in] _value Pointer to uniform data. /// @param[in] _num Number of elements. Passing `UINT16_MAX` will /// use the _num passed on uniform creation. /// /// @attention C99 equivalent is `bgfx_set_uniform`. /// void setUniform( UniformHandle _handle , const void* _value , uint16_t _num = 1 ); /// Set index buffer for draw primitive. /// /// @param[in] _handle Index buffer. /// /// @attention C99 equivalent is `bgfx_set_index_buffer`. /// void setIndexBuffer(IndexBufferHandle _handle); /// Set index buffer for draw primitive. /// /// @param[in] _handle Index buffer. /// @param[in] _firstIndex First index to render. /// @param[in] _numIndices Number of indices to render. /// /// @attention C99 equivalent is `bgfx_set_index_buffer`. /// void setIndexBuffer( IndexBufferHandle _handle , uint32_t _firstIndex , uint32_t _numIndices ); /// Set index buffer for draw primitive. /// /// @param[in] _handle Dynamic index buffer. /// /// @attention C99 equivalent is `bgfx_set_dynamic_index_buffer`. /// void setIndexBuffer(DynamicIndexBufferHandle _handle); /// Set index buffer for draw primitive. /// /// @param[in] _handle Dynamic index buffer. /// @param[in] _firstIndex First index to render. /// @param[in] _numIndices Number of indices to render. /// /// @attention C99 equivalent is `bgfx_set_dynamic_index_buffer`. /// void setIndexBuffer( DynamicIndexBufferHandle _handle , uint32_t _firstIndex , uint32_t _numIndices ); /// Set index buffer for draw primitive. /// /// @param[in] _tib Transient index buffer. /// /// @attention C99 equivalent is `bgfx_set_transient_index_buffer`. /// void setIndexBuffer(const TransientIndexBuffer* _tib); /// Set index buffer for draw primitive. /// /// @param[in] _tib Transient index buffer. /// @param[in] _firstIndex First index to render. /// @param[in] _numIndices Number of indices to render. /// /// @attention C99 equivalent is `bgfx_set_transient_index_buffer`. /// void setIndexBuffer( const TransientIndexBuffer* _tib , uint32_t _firstIndex , uint32_t _numIndices ); /// Set vertex buffer for draw primitive. /// /// @param[in] _stream Vertex stream. /// @param[in] _handle Vertex buffer. /// /// @attention C99 equivalent is `bgfx_set_vertex_buffer`. /// void setVertexBuffer( uint8_t _stream , VertexBufferHandle _handle ); /// Set vertex buffer for draw primitive. /// /// @param[in] _stream Vertex stream. /// @param[in] _handle Vertex buffer. /// @param[in] _startVertex First vertex to render. /// @param[in] _numVertices Number of vertices to render. /// @param[in] _layoutHandle Vertex layout for aliasing vertex buffer. If invalid handle is /// used, vertex layout used for creation of vertex buffer will be used. /// /// @attention C99 equivalent is `bgfx_set_vertex_buffer`. /// void setVertexBuffer( uint8_t _stream , VertexBufferHandle _handle , uint32_t _startVertex , uint32_t _numVertices , VertexLayoutHandle _layoutHandle = BGFX_INVALID_HANDLE ); /// Set vertex buffer for draw primitive. /// /// @param[in] _stream Vertex stream. /// @param[in] _handle Dynamic vertex buffer. /// /// @attention C99 equivalent is `bgfx_set_dynamic_vertex_buffer`. /// void setVertexBuffer( uint8_t _stream , DynamicVertexBufferHandle _handle ); /// Set vertex buffer for draw primitive. /// /// @param[in] _stream Vertex stream. /// @param[in] _handle Dynamic vertex buffer. /// @param[in] _startVertex First vertex to render. /// @param[in] _numVertices Number of vertices to render. /// @param[in] _layoutHandle Vertex layout for aliasing vertex buffer. If invalid handle is /// used, vertex layout used for creation of vertex buffer will be used. /// /// @attention C99 equivalent is `bgfx_set_dynamic_vertex_buffer`. /// void setVertexBuffer( uint8_t _stream , DynamicVertexBufferHandle _handle , uint32_t _startVertex , uint32_t _numVertices , VertexLayoutHandle _layoutHandle = BGFX_INVALID_HANDLE ); /// Set vertex buffer for draw primitive. /// /// @param[in] _stream Vertex stream. /// @param[in] _tvb Transient vertex buffer. /// /// @attention C99 equivalent is `bgfx_set_transient_vertex_buffer`. /// void setVertexBuffer( uint8_t _stream , const TransientVertexBuffer* _tvb ); /// Set vertex buffer for draw primitive. /// /// @param[in] _stream Vertex stream. /// @param[in] _tvb Transient vertex buffer. /// @param[in] _startVertex First vertex to render. /// @param[in] _numVertices Number of vertices to render. /// @param[in] _layoutHandle Vertex layout for aliasing vertex buffer. If invalid handle is /// used, vertex layout used for creation of vertex buffer will be used. /// /// @attention C99 equivalent is `bgfx_set_transient_vertex_buffer`. /// void setVertexBuffer( uint8_t _stream , const TransientVertexBuffer* _tvb , uint32_t _startVertex , uint32_t _numVertices , VertexLayoutHandle _layoutHandle = BGFX_INVALID_HANDLE ); /// Set number of vertices for auto generated vertices use in conjuction /// with gl_VertexID. /// /// @param[in] _numVertices Number of vertices. /// /// @attention Availability depends on: `BGFX_CAPS_VERTEX_ID`. /// @attention C99 equivalent is `bgfx_set_vertex_count`. /// void setVertexCount(uint32_t _numVertices); /// Set instance data buffer for draw primitive. /// /// @param[in] _idb Transient instance data buffer. /// /// @attention C99 equivalent is `bgfx_set_instance_data_buffer`. /// void setInstanceDataBuffer(const InstanceDataBuffer* _idb); /// Set instance data buffer for draw primitive. /// /// @param[in] _idb Transient instance data buffer. /// @param[in] _start First instance data. /// @param[in] _num Number of data instances. /// /// @attention C99 equivalent is `bgfx_set_instance_data_buffer`. /// void setInstanceDataBuffer( const InstanceDataBuffer* _idb , uint32_t _start , uint32_t _num ); /// Set instance data buffer for draw primitive. /// /// @param[in] _handle Vertex buffer. /// @param[in] _start First instance data. /// @param[in] _num Number of data instances. /// /// @attention C99 equivalent is `bgfx_set_instance_data_from_vertex_buffer`. /// void setInstanceDataBuffer( VertexBufferHandle _handle , uint32_t _start , uint32_t _num ); /// Set instance data buffer for draw primitive. /// /// @param[in] _handle Vertex buffer. /// @param[in] _start First instance data. /// @param[in] _num Number of data instances. /// /// @attention C99 equivalent is `bgfx_set_instance_data_from_dynamic_vertex_buffer`. /// void setInstanceDataBuffer( DynamicVertexBufferHandle _handle , uint32_t _start , uint32_t _num ); /// Set number of instances for auto generated instances use in conjuction /// with gl_InstanceID. /// /// @param[in] _numInstances Number of instances. /// /// @attention Availability depends on: `BGFX_CAPS_VERTEX_ID`. /// @attention C99 equivalent is `bgfx_set_instance_count`. /// void setInstanceCount(uint32_t _numInstances); /// Set texture stage for draw primitive. /// /// @param[in] _stage Texture unit. /// @param[in] _sampler Program sampler. /// @param[in] _handle Texture handle. /// @param[in] _flags Texture sampling mode. Default value UINT32_MAX uses /// texture sampling settings from the texture. /// - `BGFX_SAMPLER_[U/V/W]_[MIRROR/CLAMP]` - Mirror or clamp to edge wrap /// mode. /// - `BGFX_SAMPLER_[MIN/MAG/MIP]_[POINT/ANISOTROPIC]` - Point or anisotropic /// sampling. /// /// @attention C99 equivalent is `bgfx_set_texture`. /// void setTexture( uint8_t _stage , UniformHandle _sampler , TextureHandle _handle , uint32_t _flags = UINT32_MAX ); /// Submit an empty primitive for rendering. Uniforms and draw state /// will be applied but no geometry will be submitted. /// /// These empty draw calls will sort before ordinary draw calls. /// /// @param[in] _id View id. /// /// @attention C99 equivalent is `bgfx_touch`. /// void touch(ViewId _id); /// Submit primitive for rendering. /// /// @param[in] _id View id. /// @param[in] _program Program. /// @param[in] _depth Depth for sorting. /// @param[in] _flags Discard or preserve states. See `BGFX_DISCARD_*`. /// /// @attention C99 equivalent is `bgfx_submit`. /// void submit( ViewId _id , ProgramHandle _program , uint32_t _depth = 0 , uint8_t _flags = BGFX_DISCARD_ALL ); /// Submit primitive with occlusion query for rendering. /// /// @param[in] _id View id. /// @param[in] _program Program. /// @param[in] _occlusionQuery Occlusion query. /// @param[in] _depth Depth for sorting. /// @param[in] _flags Discard or preserve states. See `BGFX_DISCARD_*`. /// /// @attention C99 equivalent is `bgfx_submit_occlusion_query`. /// void submit( ViewId _id , ProgramHandle _program , OcclusionQueryHandle _occlusionQuery , uint32_t _depth = 0 , uint8_t _flags = BGFX_DISCARD_ALL ); /// Submit primitive for rendering with index and instance data info from /// indirect buffer. /// /// @param[in] _id View id. /// @param[in] _program Program. /// @param[in] _indirectHandle Indirect buffer. /// @param[in] _start First element in indirect buffer. /// @param[in] _num Number of dispatches. /// @param[in] _depth Depth for sorting. /// @param[in] _flags Discard or preserve states. See `BGFX_DISCARD_*`. /// /// @attention C99 equivalent is `bgfx_submit_indirect`. /// void submit( ViewId _id , ProgramHandle _program , IndirectBufferHandle _indirectHandle , uint16_t _start = 0 , uint16_t _num = 1 , uint32_t _depth = 0 , uint8_t _flags = BGFX_DISCARD_ALL ); /// Set compute index buffer. /// /// @param[in] _stage Compute stage. /// @param[in] _handle Index buffer handle. /// @param[in] _access Buffer access. See `Access::Enum`. /// /// @attention C99 equivalent is `bgfx_set_compute_index_buffer`. /// void setBuffer( uint8_t _stage , IndexBufferHandle _handle , Access::Enum _access ); /// Set compute vertex buffer. /// /// @param[in] _stage Compute stage. /// @param[in] _handle Vertex buffer handle. /// @param[in] _access Buffer access. See `Access::Enum`. /// /// @attention C99 equivalent is `bgfx_set_compute_vertex_buffer`. /// void setBuffer( uint8_t _stage , VertexBufferHandle _handle , Access::Enum _access ); /// Set compute dynamic index buffer. /// /// @param[in] _stage Compute stage. /// @param[in] _handle Dynamic index buffer handle. /// @param[in] _access Buffer access. See `Access::Enum`. /// /// @attention C99 equivalent is `bgfx_set_compute_dynamic_index_buffer`. /// void setBuffer( uint8_t _stage , DynamicIndexBufferHandle _handle , Access::Enum _access ); /// Set compute dynamic vertex buffer. /// /// @param[in] _stage Compute stage. /// @param[in] _handle Dynamic vertex buffer handle. /// @param[in] _access Buffer access. See `Access::Enum`. /// /// @attention C99 equivalent is `bgfx_set_compute_dynamic_vertex_buffer`. /// void setBuffer( uint8_t _stage , DynamicVertexBufferHandle _handle , Access::Enum _access ); /// Set compute indirect buffer. /// /// @param[in] _stage Compute stage. /// @param[in] _handle Indirect buffer handle. /// @param[in] _access Buffer access. See `Access::Enum`. /// /// @attention C99 equivalent is `bgfx_set_compute_indirect_buffer`. /// void setBuffer( uint8_t _stage , IndirectBufferHandle _handle , Access::Enum _access ); /// Set compute image from texture. /// /// @param[in] _stage Texture unit. /// @param[in] _handle Texture handle. /// @param[in] _mip Mip level. /// @param[in] _access Texture access. See `Access::Enum`. /// @param[in] _format Texture format. See: `TextureFormat::Enum`. /// /// @attention C99 equivalent is `bgfx_set_image`. /// void setImage( uint8_t _stage , TextureHandle _handle , uint8_t _mip , Access::Enum _access , TextureFormat::Enum _format = TextureFormat::Count ); /// Dispatch compute. /// /// @param[in] _id View id. /// @param[in] _handle Compute program. /// @param[in] _numX Number of groups X. /// @param[in] _numY Number of groups Y. /// @param[in] _numZ Number of groups Z. /// @param[in] _flags Discard or preserve states. See `BGFX_DISCARD_*`. /// /// @attention C99 equivalent is `bgfx_dispatch`. /// void dispatch( ViewId _id , ProgramHandle _handle , uint32_t _numX = 1 , uint32_t _numY = 1 , uint32_t _numZ = 1 , uint8_t _flags = BGFX_DISCARD_ALL ); /// Dispatch compute indirect. /// /// @param[in] _id View id. /// @param[in] _handle Compute program. /// @param[in] _indirectHandle Indirect buffer. /// @param[in] _start First element in indirect buffer. /// @param[in] _num Number of dispatches. /// @param[in] _flags Discard or preserve states. See `BGFX_DISCARD_*`. /// /// @attention C99 equivalent is `bgfx_dispatch_indirect`. /// void dispatch( ViewId _id , ProgramHandle _handle , IndirectBufferHandle _indirectHandle , uint16_t _start = 0 , uint16_t _num = 1 , uint8_t _flags = BGFX_DISCARD_ALL ); /// Discard all previously set state for draw or compute call. /// /// @param[in] _flags Draw/compute states to discard. /// /// @attention C99 equivalent is `bgfx_discard`. /// void discard(uint8_t _flags = BGFX_DISCARD_ALL); /// Blit 2D texture region between two 2D textures. /// /// @param[in] _id View id. /// @param[in] _dst Destination texture handle. /// @param[in] _dstX Destination texture X position. /// @param[in] _dstY Destination texture Y position. /// @param[in] _src Source texture handle. /// @param[in] _srcX Source texture X position. /// @param[in] _srcY Source texture Y position. /// @param[in] _width Width of region. /// @param[in] _height Height of region. /// /// @attention Destination texture must be created with `BGFX_TEXTURE_BLIT_DST` flag. /// @attention Availability depends on: `BGFX_CAPS_TEXTURE_BLIT`. /// @attention C99 equivalent is `bgfx_blit`. /// void blit( ViewId _id , TextureHandle _dst , uint16_t _dstX , uint16_t _dstY , TextureHandle _src , uint16_t _srcX = 0 , uint16_t _srcY = 0 , uint16_t _width = UINT16_MAX , uint16_t _height = UINT16_MAX ); /// Blit texture region between two textures. /// /// @param[in] _id View id. /// @param[in] _dst Destination texture handle. /// @param[in] _dstMip Destination texture mip level. /// @param[in] _dstX Destination texture X position. /// @param[in] _dstY Destination texture Y position. /// @param[in] _dstZ If texture is 2D this argument should be 0. If destination texture is cube /// this argument represents destination texture cube face. For 3D texture this argument /// represents destination texture Z position. /// @param[in] _src Source texture handle. /// @param[in] _srcMip Source texture mip level. /// @param[in] _srcX Source texture X position. /// @param[in] _srcY Source texture Y position. /// @param[in] _srcZ If texture is 2D this argument should be 0. If source texture is cube /// this argument represents source texture cube face. For 3D texture this argument /// represents source texture Z position. /// @param[in] _width Width of region. /// @param[in] _height Height of region. /// @param[in] _depth If texture is 3D this argument represents depth of region, otherwise it's /// unused. /// /// @attention Destination texture must be created with `BGFX_TEXTURE_BLIT_DST` flag. /// @attention Availability depends on: `BGFX_CAPS_TEXTURE_BLIT`. /// @attention C99 equivalent is `bgfx_blit`. /// void blit( ViewId _id , TextureHandle _dst , uint8_t _dstMip , uint16_t _dstX , uint16_t _dstY , uint16_t _dstZ , TextureHandle _src , uint8_t _srcMip = 0 , uint16_t _srcX = 0 , uint16_t _srcY = 0 , uint16_t _srcZ = 0 , uint16_t _width = UINT16_MAX , uint16_t _height = UINT16_MAX , uint16_t _depth = UINT16_MAX ); /// Request screen shot of window back buffer. /// /// @param[in] _handle Frame buffer handle. If handle is `BGFX_INVALID_HANDLE` request will be /// made for main window back buffer. /// @param[in] _filePath Will be passed to `bgfx::CallbackI::screenShot` callback. /// /// @remarks /// `bgfx::CallbackI::screenShot` must be implemented. /// /// @attention Frame buffer handle must be created with OS' target native window handle. /// @attention C99 equivalent is `bgfx_request_screen_shot`. /// void requestScreenShot( FrameBufferHandle _handle , const char* _filePath ); } // namespace bgfx #endif // BGFX_H_HEADER_GUARD
[ "dragon-fly@qq.com" ]
dragon-fly@qq.com
6729c3e0c77c149413cb4aedecd446734efcc020
57acc4825c2a9aa32009952291abf108be574d78
/pot_profiling/pot_profiling.ino
ab70a91d1490bb8fa22627cbedd78eddd12d471f
[ "MIT" ]
permissive
timburbank/earth_analog
74b221b6d5aca5261673c6abcfc5ffbc17c34eea
10760464137802a18e8b80cc51f3e73faeae5a29
refs/heads/master
2020-03-22T06:59:59.434583
2018-10-15T05:47:00
2018-10-15T05:47:00
139,671,838
0
0
null
null
null
null
UTF-8
C++
false
false
395
ino
#define POT_PIN A4 #define POT_MIN 0 #define POT_MAX 1023 long pot_val = 0; void setup() { pinMode(POT_PIN, INPUT); Serial.begin(115200); } void loop() { // put your main code here, to run repeatedly: pot_val = analogRead(POT_PIN); if (pot_val > POT_MIN && pot_val < POT_MAX) { // Serial.print(millis()); // Serial.print("\t"); Serial.println(pot_val); } delay(1); }
[ "tim@timburbank.com" ]
tim@timburbank.com
e3cdf45ff344353cb373b551f8999df85e22c58c
7a9e8b1802c3b4c5a68d27046cb198e51285bdfc
/1.cpp
cab399dfc0395919321c8489b06f2e29d21a8c07
[]
no_license
Drmicrosoft/encryption_Normal
9a23f060a9843175d67907b1f5208d41126eb34c
09311b48d5ba2ede739146a12543709d1132f734
refs/heads/master
2020-12-25T09:08:45.480614
2016-07-14T03:02:30
2016-07-14T03:02:30
63,297,341
0
0
null
null
null
null
UTF-8
C++
false
false
295
cpp
#include<iostream> using namespace std; int rev(int s) { int arr[s]; for (int i=0;i<s;i++) { int g; cin>>g; arr[i] = g; } int ind = s-1; for(ind ; ind >=0; ind--) { cout<< arr[ind] << " "; } return 0; } int main() { cout<<"enter size of arr \n"; int j; cin >>j; rev(j); }
[ "noreply@github.com" ]
Drmicrosoft.noreply@github.com
7933a53e45018a1e719f3a15e7f69d6d177440c7
556db265723b0cc30ad2917442ed6dad92fd9044
/tensorflow/compiler/xla/tests/cpu_gpu_fusion_test.cc
c884fcca25b5173c8c89947c1c56584312f3cd6a
[ "MIT", "Apache-2.0", "BSD-2-Clause" ]
permissive
graphcore/tensorflow
c1669b489be0e045b3ec856b311b3139858de196
085b20a4b6287eff8c0b792425d52422ab8cbab3
refs/heads/r2.6/sdk-release-3.2
2023-07-06T06:23:53.857743
2023-03-14T13:04:04
2023-03-14T13:48:43
162,717,602
84
17
Apache-2.0
2023-03-25T01:13:37
2018-12-21T13:30:38
C++
UTF-8
C++
false
false
41,313
cc
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <math.h> #include <algorithm> #include <memory> #include <new> #include <random> #include <utility> #define EIGEN_USE_THREADS #include "absl/memory/memory.h" #include "absl/types/span.h" #include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor" #include "tensorflow/compiler/xla/array2d.h" #include "tensorflow/compiler/xla/client/client_library.h" #include "tensorflow/compiler/xla/client/xla_builder.h" #include "tensorflow/compiler/xla/literal.h" #include "tensorflow/compiler/xla/primitive_util.h" #include "tensorflow/compiler/xla/service/hlo_computation.h" #include "tensorflow/compiler/xla/service/hlo_instruction.h" #include "tensorflow/compiler/xla/service/hlo_module.h" #include "tensorflow/compiler/xla/service/hlo_opcode.h" #include "tensorflow/compiler/xla/service/platform_util.h" #include "tensorflow/compiler/xla/shape_util.h" #include "tensorflow/compiler/xla/tests/client_library_test_base.h" #include "tensorflow/compiler/xla/tests/hlo_test_base.h" #include "tensorflow/compiler/xla/tests/literal_test_util.h" #include "tensorflow/compiler/xla/tests/test_macros.h" #include "tensorflow/compiler/xla/xla_data.pb.h" #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/platform/protobuf.h" #include "tensorflow/core/platform/test_benchmark.h" #include "tensorflow/core/platform/types.h" namespace xla { namespace { const int test_width = 2, test_height = 3; const float test_float_vals[3][test_width][test_height] = { {{-1.0, -1.0, 1.0}, {-3.0, 0.0, -1.0}}, {{-3.0, 2.0, 1.0}, {0.0, -3.0, 1.0}}, {{-3.0, 0.0, -3.0}, {-1.0, -2.0, 1.0}}}; // Test whether fusion operations are emitted with no errors and compute // accurate outputs. class CpuGpuFusionTest : public HloTestBase { protected: template <typename T, int Arity> void TestElementwise2D( HloOpcode opcode, absl::optional<ComparisonDirection> direction = absl::nullopt) { // Create a variable for comparisons since they require the direction. bool is_compare = std::is_same<T, bool>::value; Array2D<float> operand_data[Arity]; for (int i = 0; i < Arity; ++i) { new (&operand_data[i]) Array2D<float>(test_width, test_height); } Array2D<T> answer_data(test_width, test_height); for (int i = 0; i < test_width; ++i) { for (int j = 0; j < test_height; ++j) { float xs[Arity]; for (int k = 0; k < Arity; ++k) { xs[k] = test_float_vals[k][i][j]; operand_data[k](i, j) = xs[k]; } if (is_compare) { answer_data(i, j) = ComputeElementwiseAnswerCompare(*direction, xs); } else { answer_data(i, j) = ComputeElementwiseAnswerFloat(opcode, xs); } } } auto builder = HloComputation::Builder(TestName()); auto hlo_module = CreateNewVerifiedModule(); auto prim_type = primitive_util::NativeToPrimitiveType<T>(); HloInstruction* hlos[4]; for (int i = 0; i < Arity; ++i) { hlos[i + 1] = builder.AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR2FromArray2D(operand_data[i]))); } auto answer_shape = ShapeUtil::MakeShape(prim_type, {test_width, test_height}); std::unique_ptr<HloInstruction> root_hlo; switch (Arity) { case 1: root_hlo = HloInstruction::CreateUnary(answer_shape, opcode, hlos[1]); break; case 2: if (is_compare) { root_hlo = HloInstruction::CreateCompare(answer_shape, hlos[1], hlos[2], *direction); } else { root_hlo = HloInstruction::CreateBinary(answer_shape, opcode, hlos[1], hlos[2]); } break; case 3: root_hlo = HloInstruction::CreateTernary(answer_shape, opcode, hlos[1], hlos[2], hlos[3]); break; default: LOG(FATAL) << "Bad arity: " << Arity; } hlos[0] = builder.AddInstruction(std::move(root_hlo)); hlo_module->AddEntryComputation(builder.Build()) ->CreateFusionInstruction( absl::Span<HloInstruction* const>(hlos).subspan(0, Arity + 1), HloInstruction::FusionKind::kLoop); auto expected = LiteralUtil::CreateR2FromArray2D(answer_data); auto actual = ExecuteAndTransfer(std::move(hlo_module), {}); if (primitive_util::IsFloatingPointType(prim_type)) { EXPECT_TRUE(LiteralTestUtil::Near(expected, actual, ErrorSpec(1e-4))); } else { EXPECT_TRUE(LiteralTestUtil::Equal(expected, actual)); } } private: float ComputeElementwiseAnswerFloat(HloOpcode opcode, absl::Span<const float> xs); bool ComputeElementwiseAnswerCompare(ComparisonDirection direction, absl::Span<const float> xs); DebugOptions GetDebugOptionsForTest() override { DebugOptions debug_options = HloTestBase::GetDebugOptionsForTest(); debug_options.add_xla_disable_hlo_passes("layout-assignment"); return debug_options; } }; float CpuGpuFusionTest::ComputeElementwiseAnswerFloat( HloOpcode opcode, absl::Span<const float> xs) { switch (opcode) { case HloOpcode::kAdd: return xs[0] + xs[1]; case HloOpcode::kSubtract: return xs[0] - xs[1]; case HloOpcode::kMultiply: return xs[0] * xs[1]; case HloOpcode::kDivide: return xs[0] / xs[1]; case HloOpcode::kPower: return powf(xs[0], xs[1]); case HloOpcode::kMinimum: return std::min(xs[0], xs[1]); case HloOpcode::kMaximum: return std::max(xs[0], xs[1]); case HloOpcode::kClamp: return std::min(xs[2], std::max(xs[1], xs[0])); default: LOG(FATAL) << "No elementwise opcode: " << opcode; } } bool CpuGpuFusionTest::ComputeElementwiseAnswerCompare( ComparisonDirection direction, absl::Span<const float> xs) { switch (direction) { case ComparisonDirection::kEq: return xs[0] == xs[1]; case ComparisonDirection::kNe: return xs[0] != xs[1]; case ComparisonDirection::kGt: return xs[0] > xs[1]; case ComparisonDirection::kLt: return xs[0] < xs[1]; case ComparisonDirection::kGe: return xs[0] >= xs[1]; case ComparisonDirection::kLe: return xs[0] <= xs[1]; } } XLA_TEST_F(CpuGpuFusionTest, Test) { // test expression: // slice(select({{T, F, T}, {F, T, F}}, // concat(transpose({{1.0}, {2.0}, {3.0}} + // {{-1.0}, {-1.0}, {-1.0}}), // {{1.62, 2.72, 3.14}}) + // (-{{1.0, 1.0, 1.0}, {0.0, 0.0, 0.0}}), // {{0.5, 0.5, 0.5}, {0.5, 0.5, 0.5}})) = {{0.5}, {2.72}} auto builder = HloComputation::Builder(TestName()); auto hlo_module = CreateNewVerifiedModule(); auto const0 = builder.AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR2<float>({{1.0}, {2.0}, {3.0}}))); auto const1 = builder.AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR2<float>({{-1.0}, {-1.0}, {-1.0}}))); auto add2 = builder.AddInstruction(HloInstruction::CreateBinary( ShapeUtil::MakeShape(F32, {3, 1}), HloOpcode::kAdd, const0, const1)); auto reshape3 = builder.AddInstruction(HloInstruction::CreateTranspose( ShapeUtil::MakeShape(F32, {1, 3}), add2, {1, 0})); auto const4 = builder.AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR2<float>({{1.62, 2.72, 3.14}}))); auto concat5 = builder.AddInstruction(HloInstruction::CreateConcatenate( ShapeUtil::MakeShape(F32, {2, 3}), {reshape3, const4}, 0)); auto const6 = builder.AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR2<float>({{1.0, 1.0, 1.0}, {0.0, 0.0, 0.0}}))); auto negate7 = builder.AddInstruction(HloInstruction::CreateUnary( ShapeUtil::MakeShape(F32, {2, 3}), HloOpcode::kNegate, const6)); auto add8 = builder.AddInstruction(HloInstruction::CreateBinary( ShapeUtil::MakeShape(F32, {2, 3}), HloOpcode::kAdd, concat5, negate7)); auto const9 = builder.AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR2<float>({{0.5, 0.5, 0.5}, {0.5, 0.5, 0.5}}))); auto const10 = builder.AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR2<bool>( {{true, false, true}, {false, true, false}}))); auto select11 = builder.AddInstruction( HloInstruction::CreateTernary(ShapeUtil::MakeShape(F32, {2, 3}), HloOpcode::kSelect, const10, add8, const9)); auto slice12 = builder.AddInstruction(HloInstruction::CreateSlice( ShapeUtil::MakeShape(F32, {2, 1}), select11, {0, 1}, {2, 2}, {1, 1})); // CreateFusionInstruction needs the `instructions_to_fuse` argument in // reverse topological order, so the first element in `instructions_to_fuse` // must be the root. hlo_module->AddEntryComputation(builder.Build()) ->CreateFusionInstruction( {slice12, select11, const10, const9, add8, negate7, const6, concat5, const4, reshape3, add2, const1, const0}, HloInstruction::FusionKind::kLoop); EXPECT_TRUE(LiteralTestUtil::Near( LiteralUtil::CreateR2<float>({{0.5}, {2.72}}), ExecuteAndTransfer(std::move(hlo_module), {}), ErrorSpec(1e-4))); } // Test whether we emit appropriate code for parameters of fusion instructions. XLA_TEST_F(CpuGpuFusionTest, Parameter) { // Build a computation and fuse part of it so the fusion instruction has an // operand parameter. auto builder = HloComputation::Builder(TestName()); auto hlo_module = CreateNewVerifiedModule(); auto const0 = builder.AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR2<float>({{1.0, 2.0, 3.0}}))); auto copy1 = builder.AddInstruction(HloInstruction::CreateUnary( ShapeUtil::MakeShape(F32, {1, 3}), HloOpcode::kCopy, const0)); auto const2 = builder.AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR2<float>({{-2.0, -2.0, -2.0}}))); // add3 = copy1 + const2 = const0 + const2 = {1,2,3} + {-2,-2,-2} = {-1,0,+1} auto add3 = builder.AddInstruction(HloInstruction::CreateBinary( ShapeUtil::MakeShape(F32, {1, 3}), HloOpcode::kAdd, copy1, const2)); // CreateFusionInstruction needs `instructions_to_fuse` in reverse topological // order. hlo_module->AddEntryComputation(builder.Build()) ->CreateFusionInstruction(/*instructions_to_fuse=*/{add3, const2}, HloInstruction::FusionKind::kLoop); EXPECT_TRUE(LiteralTestUtil::Near( LiteralUtil::CreateR2<float>({{-1.0, 0.0, 1.0}}), ExecuteAndTransfer(std::move(hlo_module), {}), ErrorSpec(1e-4))); } XLA_TEST_F(CpuGpuFusionTest, RandomizedParallelPartition) { // Tests parallel partitioning of a fusion instruction. // Create shape with random outer dimension size to generate random parallel // partition counts for each test run. const int seed = tensorflow::testing::RandomSeed(); LOG(INFO) << "RandomizedParallelPartition seed: " << seed; std::mt19937 generator(seed); std::uniform_int_distribution<int> distribution(128, 1024); const int64 rand_dim0_size = distribution(generator); const int64 dim1_size = 1024; Shape shape = ShapeUtil::MakeShapeWithLayout(F32, {rand_dim0_size, dim1_size}, {1, 0}); // Build simple fusion computation: y = x^2 (elementwise). auto builder = HloComputation::Builder(TestName()); auto hlo_module = CreateNewVerifiedModule(); auto two = builder.AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<float>(2.0))); auto x = builder.AddInstruction(HloInstruction::CreateBroadcast(shape, two, {})); auto y = builder.AddInstruction( HloInstruction::CreateBinary(shape, HloOpcode::kMultiply, x, x)); hlo_module->AddEntryComputation(builder.Build()) ->CreateFusionInstruction(/*instructions_to_fuse=*/{y, x, two}, HloInstruction::FusionKind::kLoop); // Compute result. auto result = ExecuteAndTransfer(std::move(hlo_module), {}); // Every element of result should be y = x^2 = 4.0. for (int i = 0; i < rand_dim0_size; ++i) { for (int j = 0; j < dim1_size; ++j) { EXPECT_EQ(4.0, result.Get<float>({i, j})); } } } XLA_TEST_F(CpuGpuFusionTest, BroadcastIntoBinaryOp) { auto builder = HloComputation::Builder(TestName()); auto hlo_module = CreateNewVerifiedModule(); auto const_vector = builder.AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR1<float>({1.0, 2.0, 3.0}))); auto const_array = builder.AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR2<float>({{-1.0, -2.0, -4.0}, {10.0, 20.0, 30.0}}))); auto broadcast = builder.AddInstruction( HloInstruction::CreateBroadcast(const_array->shape(), const_vector, {1})); // add2 = broadcast(const_vector) + const_array // = broadcast({1,2,3}) + {{-1.0, -2.0, -4.0}, {10.0, 20.0, 30.0}} // = {{1, 2, 3}, {1, 2, 3}} + {{-1.0, -2.0, -4.0}, {10.0, 20.0, 30.0}} auto add2 = builder.AddInstruction( HloInstruction::CreateBinary(ShapeUtil::MakeShape(F32, {2, 3}), HloOpcode::kAdd, broadcast, const_array)); hlo_module->AddEntryComputation(builder.Build()) ->CreateFusionInstruction(/*instructions_to_fuse=*/{add2, broadcast}, HloInstruction::FusionKind::kLoop); EXPECT_TRUE(LiteralTestUtil::Near( LiteralUtil::CreateR2<float>({{0.0, 0.0, -1.0}, {11.0, 22.0, 33.0}}), ExecuteAndTransfer(std::move(hlo_module), {}), ErrorSpec(1e-4))); } XLA_TEST_F(CpuGpuFusionTest, ReshapeToScalar) { auto builder = HloComputation::Builder(TestName()); auto hlo_module = CreateNewVerifiedModule(); auto single_element_array = builder.AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR2<int32>({{5}}))); auto reshape = builder.AddInstruction(HloInstruction::CreateReshape( ShapeUtil::MakeShape(S32, {}), single_element_array)); hlo_module->AddEntryComputation(builder.Build()) ->CreateFusionInstruction(/*instructions_to_fuse=*/{reshape}, HloInstruction::FusionKind::kLoop); EXPECT_TRUE( LiteralTestUtil::Equal(LiteralUtil::CreateR0<int32>(5), ExecuteAndTransfer(std::move(hlo_module), {}))); } XLA_TEST_F(CpuGpuFusionTest, Reshape_3by2_1by2by3) { auto builder = HloComputation::Builder(TestName()); auto hlo_module = CreateNewVerifiedModule(); auto const0 = builder.AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR2<int32>({{1, 2}, {3, 4}, {5, 6}}))); auto reshape1 = builder.AddInstruction(HloInstruction::CreateReshape( ShapeUtil::MakeShape(S32, {1, 2, 3}), const0)); hlo_module->AddEntryComputation(builder.Build()) ->CreateFusionInstruction(/*instructions_to_fuse=*/{reshape1}, HloInstruction::FusionKind::kLoop); EXPECT_TRUE(LiteralTestUtil::Equal( LiteralUtil::CreateR3<int32>({{{1, 2, 3}, {4, 5, 6}}}), ExecuteAndTransfer(std::move(hlo_module), {}))); } XLA_TEST_F(CpuGpuFusionTest, Reshape_1by2by3_3by2) { auto builder = HloComputation::Builder(TestName()); auto hlo_module = CreateNewVerifiedModule(); auto const0 = builder.AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR3<int32>({{{1, 2, 3}, {4, 5, 6}}}))); auto reshape1 = builder.AddInstruction( HloInstruction::CreateReshape(ShapeUtil::MakeShape(S32, {3, 2}), const0)); hlo_module->AddEntryComputation(builder.Build()) ->CreateFusionInstruction(/*instructions_to_fuse=*/{reshape1}, HloInstruction::FusionKind::kLoop); EXPECT_TRUE(LiteralTestUtil::Equal( LiteralUtil::CreateR2<int32>({{1, 2}, {3, 4}, {5, 6}}), ExecuteAndTransfer(std::move(hlo_module), {}))); } XLA_TEST_F(CpuGpuFusionTest, Reshape_1by1by1_) { auto builder = HloComputation::Builder(TestName()); auto hlo_module = CreateNewVerifiedModule(); auto const0 = builder.AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR3<int32>({{{7}}}))); auto reshape1 = builder.AddInstruction( HloInstruction::CreateReshape(ShapeUtil::MakeShape(S32, {}), const0)); hlo_module->AddEntryComputation(builder.Build()) ->CreateFusionInstruction(/*instructions_to_fuse=*/{reshape1}, HloInstruction::FusionKind::kLoop); EXPECT_TRUE( LiteralTestUtil::Equal(LiteralUtil::CreateR0<int32>(7), ExecuteAndTransfer(std::move(hlo_module), {}))); } XLA_TEST_F(CpuGpuFusionTest, Reshape__1by1by1) { auto builder = HloComputation::Builder(TestName()); auto hlo_module = CreateNewVerifiedModule(); auto const0 = builder.AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int32>(7))); auto reshape1 = builder.AddInstruction(HloInstruction::CreateReshape( ShapeUtil::MakeShape(S32, {1, 1, 1}), const0)); hlo_module->AddEntryComputation(builder.Build()) ->CreateFusionInstruction(/*instructions_to_fuse=*/{reshape1}, HloInstruction::FusionKind::kLoop); EXPECT_TRUE( LiteralTestUtil::Equal(LiteralUtil::CreateR3<int32>({{{7}}}), ExecuteAndTransfer(std::move(hlo_module), {}))); } XLA_TEST_F(CpuGpuFusionTest, Reshape__) { auto builder = HloComputation::Builder(TestName()); auto hlo_module = CreateNewVerifiedModule(); auto const0 = builder.AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int32>(7))); auto reshape1 = builder.AddInstruction( HloInstruction::CreateReshape(ShapeUtil::MakeShape(S32, {}), const0)); hlo_module->AddEntryComputation(builder.Build()) ->CreateFusionInstruction(/*instructions_to_fuse=*/{reshape1}, HloInstruction::FusionKind::kLoop); EXPECT_TRUE( LiteralTestUtil::Equal(LiteralUtil::CreateR0<int32>(7), ExecuteAndTransfer(std::move(hlo_module), {}))); } XLA_TEST_F(CpuGpuFusionTest, Reshape_3by3_3by3) { auto builder = HloComputation::Builder(TestName()); auto hlo_module = CreateNewVerifiedModule(); auto const0 = builder.AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR2<int32>({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}))); auto reshape1 = builder.AddInstruction( HloInstruction::CreateReshape(ShapeUtil::MakeShape(S32, {3, 3}), const0)); hlo_module->AddEntryComputation(builder.Build()) ->CreateFusionInstruction(/*instructions_to_fuse=*/{reshape1}, HloInstruction::FusionKind::kLoop); EXPECT_TRUE(LiteralTestUtil::Equal( LiteralUtil::CreateR2<int32>({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}), ExecuteAndTransfer(std::move(hlo_module), {}))); } XLA_TEST_F(CpuGpuFusionTest, Transpose_2by3) { auto builder = HloComputation::Builder(TestName()); auto hlo_module = CreateNewVerifiedModule(); auto const0 = builder.AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR2<int32>({{1, 2, 3}, {4, 5, 6}}))); auto reshape1 = builder.AddInstruction(HloInstruction::CreateTranspose( ShapeUtil::MakeShape(S32, {3, 2}), const0, {1, 0})); hlo_module->AddEntryComputation(builder.Build()) ->CreateFusionInstruction(/*instructions_to_fuse=*/{reshape1}, HloInstruction::FusionKind::kLoop); EXPECT_TRUE(LiteralTestUtil::Equal( LiteralUtil::CreateR2<int32>({{1, 4}, {2, 5}, {3, 6}}), ExecuteAndTransfer(std::move(hlo_module), {}))); } XLA_TEST_F(CpuGpuFusionTest, Transpose_3by3) { auto builder = HloComputation::Builder(TestName()); auto hlo_module = CreateNewVerifiedModule(); auto const0 = builder.AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR2<int32>({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}))); auto reshape1 = builder.AddInstruction(HloInstruction::CreateTranspose( ShapeUtil::MakeShape(S32, {3, 3}), const0, {1, 0})); hlo_module->AddEntryComputation(builder.Build()) ->CreateFusionInstruction(/*instructions_to_fuse=*/{reshape1}, HloInstruction::FusionKind::kLoop); EXPECT_TRUE(LiteralTestUtil::Equal( LiteralUtil::CreateR2<int32>({{1, 4, 7}, {2, 5, 8}, {3, 6, 9}}), ExecuteAndTransfer(std::move(hlo_module), {}))); } XLA_TEST_F(CpuGpuFusionTest, Reverse) { auto builder = HloComputation::Builder(TestName()); auto hlo_module = CreateNewVerifiedModule(); auto const0 = builder.AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR1<int32>({1, 2, 3}))); auto reverse1 = builder.AddInstruction(HloInstruction::CreateReverse( ShapeUtil::MakeShape(S32, {3}), const0, {0})); hlo_module->AddEntryComputation(builder.Build()) ->CreateFusionInstruction(/*instructions_to_fuse=*/{reverse1}, HloInstruction::FusionKind::kLoop); EXPECT_TRUE( LiteralTestUtil::Equal(LiteralUtil::CreateR1<int32>({3, 2, 1}), ExecuteAndTransfer(std::move(hlo_module), {}))); } XLA_TEST_F(CpuGpuFusionTest, ReverseNegate) { auto builder = HloComputation::Builder(TestName()); auto hlo_module = CreateNewVerifiedModule(); auto const0 = builder.AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR1<int32>({1, 2, 3}))); auto reverse1 = builder.AddInstruction(HloInstruction::CreateReverse( ShapeUtil::MakeShape(S32, {3}), const0, {0})); auto negate2 = builder.AddInstruction(HloInstruction::CreateUnary( ShapeUtil::MakeShape(S32, {3}), HloOpcode::kNegate, reverse1)); hlo_module->AddEntryComputation(builder.Build()) ->CreateFusionInstruction(/*instructions_to_fuse=*/{negate2, reverse1}, HloInstruction::FusionKind::kLoop); EXPECT_TRUE( LiteralTestUtil::Equal(LiteralUtil::CreateR1<int32>({-3, -2, -1}), ExecuteAndTransfer(std::move(hlo_module), {}))); } XLA_TEST_F(CpuGpuFusionTest, BroadcastNegate) { auto builder = HloComputation::Builder(TestName()); auto hlo_module = CreateNewVerifiedModule(); auto const0 = builder.AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int32>(1))); auto broadcast1 = builder.AddInstruction(HloInstruction::CreateBroadcast( ShapeUtil::MakeShape(S32, {2}), const0, {})); auto negate2 = builder.AddInstruction(HloInstruction::CreateUnary( ShapeUtil::MakeShape(S32, {2}), HloOpcode::kNegate, broadcast1)); hlo_module->AddEntryComputation(builder.Build()) ->CreateFusionInstruction(/*instructions_to_fuse=*/{negate2, broadcast1}, HloInstruction::FusionKind::kLoop); EXPECT_TRUE( LiteralTestUtil::Equal(LiteralUtil::CreateR1<int32>({-1, -1}), ExecuteAndTransfer(std::move(hlo_module), {}))); } XLA_TEST_F(CpuGpuFusionTest, SliceNegate) { auto builder = HloComputation::Builder(TestName()); auto hlo_module = CreateNewVerifiedModule(); auto const0 = builder.AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR1<int32>({1, 2, 3, 4}))); auto slice1 = builder.AddInstruction(HloInstruction::CreateSlice( ShapeUtil::MakeShape(S32, {2}), const0, {0}, {4}, {2})); auto negate2 = builder.AddInstruction(HloInstruction::CreateUnary( ShapeUtil::MakeShape(S32, {2}), HloOpcode::kNegate, slice1)); hlo_module->AddEntryComputation(builder.Build()) ->CreateFusionInstruction(/*instructions_to_fuse=*/{negate2, slice1}, HloInstruction::FusionKind::kLoop); EXPECT_TRUE( LiteralTestUtil::Equal(LiteralUtil::CreateR1<int32>({-1, -3}), ExecuteAndTransfer(std::move(hlo_module), {}))); } XLA_TEST_F(CpuGpuFusionTest, DynamicSliceNegate) { auto builder = HloComputation::Builder(TestName()); auto hlo_module = CreateNewVerifiedModule(); auto const0 = builder.AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR1<int32>({1, 2, 3, 4}))); auto const1 = builder.AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int32>(1))); auto dynamic_slice2 = builder.AddInstruction(HloInstruction::CreateDynamicSlice( ShapeUtil::MakeShape(S32, {2}), const0, {const1}, {2})); auto negate3 = builder.AddInstruction(HloInstruction::CreateUnary( ShapeUtil::MakeShape(S32, {2}), HloOpcode::kNegate, dynamic_slice2)); hlo_module->AddEntryComputation(builder.Build()) ->CreateFusionInstruction( /*instructions_to_fuse=*/{negate3, dynamic_slice2}, HloInstruction::FusionKind::kLoop); EXPECT_TRUE( LiteralTestUtil::Equal(LiteralUtil::CreateR1<int32>({-2, -3}), ExecuteAndTransfer(std::move(hlo_module), {}))); } XLA_TEST_F(CpuGpuFusionTest, ReshapeNegate) { auto builder = HloComputation::Builder(TestName()); auto hlo_module = CreateNewVerifiedModule(); auto const0 = builder.AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR1<int32>({1, 2, 3, 4}))); auto reshape1 = builder.AddInstruction( HloInstruction::CreateReshape(ShapeUtil::MakeShape(S32, {2, 2}), const0)); auto negate2 = builder.AddInstruction(HloInstruction::CreateUnary( ShapeUtil::MakeShape(S32, {2, 2}), HloOpcode::kNegate, reshape1)); hlo_module->AddEntryComputation(builder.Build()) ->CreateFusionInstruction(/*instructions_to_fuse=*/{negate2, reshape1}, HloInstruction::FusionKind::kLoop); EXPECT_TRUE( LiteralTestUtil::Equal(LiteralUtil::CreateR2<int32>({{-1, -2}, {-3, -4}}), ExecuteAndTransfer(std::move(hlo_module), {}))); } XLA_TEST_F(CpuGpuFusionTest, TransposeNegate) { auto builder = HloComputation::Builder(TestName()); auto hlo_module = CreateNewVerifiedModule(); auto const0 = builder.AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR2<int32>({{1, 2}, {3, 4}}))); auto transpose1 = builder.AddInstruction(HloInstruction::CreateTranspose( ShapeUtil::MakeShape(S32, {2, 2}), const0, {1, 0})); auto negate2 = builder.AddInstruction(HloInstruction::CreateUnary( ShapeUtil::MakeShape(S32, {2, 2}), HloOpcode::kNegate, transpose1)); hlo_module->AddEntryComputation(builder.Build()) ->CreateFusionInstruction(/*instructions_to_fuse=*/{negate2, transpose1}, HloInstruction::FusionKind::kLoop); EXPECT_TRUE( LiteralTestUtil::Equal(LiteralUtil::CreateR2<int32>({{-1, -3}, {-2, -4}}), ExecuteAndTransfer(std::move(hlo_module), {}))); } std::unique_ptr<HloComputation> MakeReduceTestComputation() { auto builder = HloComputation::Builder("add"); auto lhs = builder.AddInstruction(HloInstruction::CreateParameter( /*parameter_number=*/0, ShapeUtil::MakeShape(S32, {}), "lhs")); auto rhs = builder.AddInstruction(HloInstruction::CreateParameter( /*parameter_number=*/1, ShapeUtil::MakeShape(S32, {}), "rhs")); builder.AddInstruction(HloInstruction::CreateBinary( ShapeUtil::MakeShape(S32, {}), HloOpcode::kAdd, lhs, rhs)); return builder.Build(); } XLA_TEST_F(CpuGpuFusionTest, DISABLED_ON_CPU(Reduce)) { auto hlo_module = CreateNewVerifiedModule(); auto builder = HloComputation::Builder(TestName()); auto const0 = builder.AddInstruction( HloInstruction::CreateIota(ShapeUtil::MakeShape(S32, {32}), 0)); auto const1 = builder.AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int32>(0))); auto reduce2 = builder.AddInstruction(HloInstruction::CreateReduce( ShapeUtil::MakeShape(S32, {}), const0, const1, {0}, hlo_module->AddEmbeddedComputation(MakeReduceTestComputation()))); hlo_module->AddEntryComputation(builder.Build()) ->CreateFusionInstruction(/*instructions_to_fuse=*/{reduce2}, HloInstruction::FusionKind::kInput); EXPECT_TRUE( LiteralTestUtil::Equal(LiteralUtil::CreateR0<int32>(496), ExecuteAndTransfer(std::move(hlo_module), {}))); } XLA_TEST_F(CpuGpuFusionTest, ReduceImplicitBroadcast) { auto hlo_module = CreateNewVerifiedModule(); auto builder = HloComputation::Builder(TestName()); auto const0 = builder.AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR1<int32>({1, 2, 4, 8}))); auto const1 = builder.AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int32>(0))); auto reduce2 = builder.AddInstruction(HloInstruction::CreateReduce( ShapeUtil::MakeShape(S32, {}), const0, const1, {0}, hlo_module->AddEmbeddedComputation(MakeReduceTestComputation()))); auto negate3 = builder.AddInstruction(HloInstruction::CreateUnary( ShapeUtil::MakeShape(S32, {}), HloOpcode::kNegate, reduce2)); hlo_module->AddEntryComputation(builder.Build()) ->CreateFusionInstruction(/*instructions_to_fuse=*/{negate3, reduce2}, HloInstruction::FusionKind::kLoop); EXPECT_TRUE( LiteralTestUtil::Equal(LiteralUtil::CreateR0<int32>(-15), ExecuteAndTransfer(std::move(hlo_module), {}))); } XLA_TEST_F(CpuGpuFusionTest, DISABLED_ON_CPU(ReduceWindow)) { auto builder = HloComputation::Builder(TestName()); auto hlo_module = CreateNewVerifiedModule(); auto const0 = builder.AddInstruction(HloInstruction::CreateConstant( LiteralUtil::CreateR2<int32>({{2, 3, 5}, {7, 11, 13}, {17, 19, 23}}))); auto const1 = builder.AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<int32>(1))); Window window; ASSERT_TRUE( tensorflow::protobuf::TextFormat::ParseFromString("dimensions:{\n" "size:2\n" "stride:1\n" "padding_low:0\n" "padding_high:0\n" "window_dilation:1\n" "base_dilation:1\n" "}\n" "dimensions:{\n" "size:2\n" "stride:1\n" "padding_low:0\n" "padding_high:0\n" "window_dilation:1\n" "base_dilation:1\n" "}\n", &window)); auto nested_builder = HloComputation::Builder("mul"); { auto x = nested_builder.AddInstruction( HloInstruction::CreateParameter(0, ShapeUtil::MakeShape(S32, {}), "x")); auto y = nested_builder.AddInstruction( HloInstruction::CreateParameter(1, ShapeUtil::MakeShape(S32, {}), "y")); nested_builder.AddInstruction(HloInstruction::CreateBinary( ShapeUtil::MakeShape(S32, {}), HloOpcode::kMultiply, x, y)); } auto nested_computation = hlo_module->AddEmbeddedComputation(nested_builder.Build()); auto reduce_window2 = builder.AddInstruction(HloInstruction::CreateReduceWindow( ShapeUtil::MakeShape(S32, {2, 2}), const0, const1, window, nested_computation)); hlo_module->AddEntryComputation(builder.Build()) ->CreateFusionInstruction(/*instructions_to_fuse=*/{reduce_window2}, HloInstruction::FusionKind::kLoop); EXPECT_TRUE(LiteralTestUtil::Equal( LiteralUtil::CreateR2<int32>({{462, 2145}, {24871, 62491}}), ExecuteAndTransfer(std::move(hlo_module), {}))); } // When a constant (or other op) which has multiple users is imported // into a fusion, it should remain shared, rather than being duplicated // within the fusion. XLA_TEST_F(CpuGpuFusionTest, SharedConstant) { auto hlo_module = CreateNewVerifiedModule(); auto builder = HloComputation::Builder(TestName()); auto const0 = builder.AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR1<int32>({0}))); auto const1 = builder.AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR1<int32>({2}))); auto add1 = builder.AddInstruction(HloInstruction::CreateBinary( ShapeUtil::MakeShape(S32, {1}), HloOpcode::kAdd, const1, const0)); auto add2 = builder.AddInstruction(HloInstruction::CreateBinary( ShapeUtil::MakeShape(S32, {1}), HloOpcode::kAdd, const1, add1)); auto add3 = builder.AddInstruction(HloInstruction::CreateBinary( ShapeUtil::MakeShape(S32, {1}), HloOpcode::kAdd, const1, add2)); auto add4 = builder.AddInstruction(HloInstruction::CreateBinary( ShapeUtil::MakeShape(S32, {1}), HloOpcode::kAdd, const1, add3)); hlo_module->AddEntryComputation(builder.Build()) ->CreateFusionInstruction({add4, add3, add2, add1, const1}, HloInstruction::FusionKind::kLoop); HloComputation* entry_comp = hlo_module->entry_computation(); // entry computation contains the constant(0) and the fusion EXPECT_EQ(entry_comp->instruction_count(), 2); // fused instruction contains the constant(2), the parameter, and 4 adds EXPECT_EQ(entry_comp->root_instruction()->fused_instruction_count(), 6); EXPECT_TRUE( LiteralTestUtil::Equal(LiteralUtil::CreateR1<int32>({8}), ExecuteAndTransfer(std::move(hlo_module), {}))); } XLA_TEST_F(CpuGpuFusionTest, Add2D) { TestElementwise2D<float, 2>(HloOpcode::kAdd); } XLA_TEST_F(CpuGpuFusionTest, Subtract2D) { TestElementwise2D<float, 2>(HloOpcode::kSubtract); } XLA_TEST_F(CpuGpuFusionTest, Multiply2D) { TestElementwise2D<float, 2>(HloOpcode::kMultiply); } XLA_TEST_F(CpuGpuFusionTest, Divide2D) { TestElementwise2D<float, 2>(HloOpcode::kDivide); } XLA_TEST_F(CpuGpuFusionTest, Power2D) { TestElementwise2D<float, 2>(HloOpcode::kPower); } XLA_TEST_F(CpuGpuFusionTest, Minimum2D) { TestElementwise2D<float, 2>(HloOpcode::kMinimum); } XLA_TEST_F(CpuGpuFusionTest, Maximum2D) { TestElementwise2D<float, 2>(HloOpcode::kMaximum); } XLA_TEST_F(CpuGpuFusionTest, Equal2D) { TestElementwise2D<bool, 2>(HloOpcode::kCompare, ComparisonDirection::kEq); } XLA_TEST_F(CpuGpuFusionTest, Inequal2D) { TestElementwise2D<bool, 2>(HloOpcode::kCompare, ComparisonDirection::kNe); } XLA_TEST_F(CpuGpuFusionTest, Greater2D) { TestElementwise2D<bool, 2>(HloOpcode::kCompare, ComparisonDirection::kGt); } XLA_TEST_F(CpuGpuFusionTest, Lesser2D) { TestElementwise2D<bool, 2>(HloOpcode::kCompare, ComparisonDirection::kLt); } XLA_TEST_F(CpuGpuFusionTest, GreaterOrEqual2D) { TestElementwise2D<bool, 2>(HloOpcode::kCompare, ComparisonDirection::kGe); } XLA_TEST_F(CpuGpuFusionTest, LesserOrEqual2D) { TestElementwise2D<bool, 2>(HloOpcode::kCompare, ComparisonDirection::kLe); } XLA_TEST_F(CpuGpuFusionTest, Clamp2D) { TestElementwise2D<float, 3>(HloOpcode::kClamp); } class FusionClientLibraryTest : public ClientLibraryTestBase {}; XLA_TEST_F(FusionClientLibraryTest, ManyLayoutTransformations) { // On the GPU backend, it's possible to have too many transposes within one // fusion, causing the kernel to run out shared memory and thus not compile. // We want to check that doesn't happen. // // To do this, we create a computation that computes // // P0 + P0*P1*P1 + P0*P2*P2 ... // // where even parameters have layout 1 and odd parameters have layout 2. // // Our goal is to tempt the backend into creating one giant multi-output // fusion for the whole computation, including the transposes. Currently // multi-output fusion only fuses fusions, so each of the terms in the sum // needs to be a fusion itself, thus the contortions above. constexpr int kNumParams = 25; XlaBuilder b("ManyLayoutTransformations"); // This test produces values that overflow int32, which is UB, so use uint32, // where overflow is OK. Array2D<uint32> arr(32, 32); arr.FillUnique(); Literal l1 = LiteralUtil::CreateR2FromArray2D(arr).Relayout( LayoutUtil::MakeLayout({0, 1})); Literal l2 = LiteralUtil::CreateR2FromArray2D(arr).Relayout( LayoutUtil::MakeLayout({1, 0})); XlaOp p0 = AddParam(l1, &b); XlaOp sum = p0; for (int i = 1; i < kNumParams; ++i) { auto pN = AddParam((i % 2 == 0 ? l1 : l2), &b); sum = sum + p0 * pN * pN; } ComputeAndCompare(&b, {}); } void BM_ParallelFusion(::testing::benchmark::State& state) { // Simple element-wise computation to benchmark parallel task partitioning. se::Platform* platform = PlatformUtil::GetDefaultPlatform().ValueOrDie(); auto executors = PlatformUtil::GetStreamExecutors(platform).ValueOrDie(); se::StreamExecutorMemoryAllocator allocator(platform, executors); const int64 intra_op_parallelism_threads = 24; xla::LocalClientOptions client_options; client_options.set_platform(platform); client_options.set_intra_op_parallelism_threads(intra_op_parallelism_threads); auto client = ClientLibrary::GetOrCreateLocalClient(client_options).ValueOrDie(); int device_ordinal = client->default_device_ordinal(); // Computation shape parameters. const int64 param0_dim0 = 1024; const int64 param0_dim1 = 1024; const int64 param1_dim0 = 1024; const int64 param1_dim1 = 1024; const int64 param2_dim0 = 1024; const int64 param2_dim1 = 1024; // Create computation. XlaBuilder builder("ParallelFusion"); Shape shape0 = ShapeUtil::MakeShape(F32, {param0_dim0, param0_dim1}); auto param0 = Parameter(&builder, 0, shape0, "param0"); Shape shape1 = ShapeUtil::MakeShape(F32, {param1_dim0, param1_dim1}); auto param1 = Parameter(&builder, 1, shape1, "param1"); Shape shape2 = ShapeUtil::MakeShape(F32, {param2_dim0, param2_dim1}); auto param2 = Parameter(&builder, 2, shape2, "param2"); auto x = Mul(param0, param1); Add(x, param2); auto computation = builder.Build().ConsumeValueOrDie(); // Transfer literals to device. auto param0_literal = LiteralUtil::CreateR2F32Linspace(1.0, 2.0, param0_dim0, param0_dim1); ScopedShapedBuffer buffer0 = client->LiteralToShapedBuffer(param0_literal, device_ordinal) .ConsumeValueOrDie(); auto param1_literal = LiteralUtil::CreateR2F32Linspace(1.0, 2.0, param1_dim0, param1_dim1); ScopedShapedBuffer buffer1 = client->LiteralToShapedBuffer(param1_literal, device_ordinal) .ConsumeValueOrDie(); auto param2_literal = LiteralUtil::CreateR2F32Linspace(1.0, 2.0, param2_dim0, param2_dim1); ScopedShapedBuffer buffer2 = client->LiteralToShapedBuffer(param2_literal, device_ordinal) .ConsumeValueOrDie(); // Build executable. auto executables = client ->Compile(computation, {&buffer0.on_host_shape(), &buffer1.on_host_shape(), &buffer2.on_host_shape()}, ExecutableBuildOptions()) .ConsumeValueOrDie(); auto executable = std::move(executables[0]); se::Stream stream(executors[device_ordinal]); stream.Init(); // Initialize thread pool. tensorflow::thread::ThreadPool pool(tensorflow::Env::Default(), "XLAEigen", intra_op_parallelism_threads); Eigen::ThreadPoolDevice device(pool.AsEigenThreadPool(), pool.NumThreads()); // Initialize ExecutableRunOptions. ExecutableRunOptions options; options.set_allocator(&allocator).set_stream(&stream); options.set_intra_op_thread_pool(&device); // Run some warm-up executions. const int kWarmups = 2; for (int i = 0; i < kWarmups; ++i) { auto result = executable->Run({&buffer0, &buffer1, &buffer2}, options); ASSERT_TRUE(result.ok()); } // Run benchmark. const int64 total_bytes = param0_dim0 * param0_dim0 + param1_dim0 * param1_dim0 + param2_dim0 * param2_dim0; for (auto s : state) { auto result = executable->Run({&buffer0, &buffer1, &buffer2}, options); ASSERT_TRUE(result.ok()); } state.SetBytesProcessed(static_cast<int64>(state.iterations()) * total_bytes * sizeof(float)); } BENCHMARK(BM_ParallelFusion)->UseRealTime(); } // namespace } // namespace xla
[ "gardener@tensorflow.org" ]
gardener@tensorflow.org
58b8eccdaae2a0188aceca68f282156769947542
9c56a1548ee24fa679b831bca5e796fa86dbb583
/codeforces/Global Round 2/C/s.cpp
59300dc3b1652330dbad1ac3e0023eef757a6f8b
[ "CC-BY-4.0", "CC-BY-3.0" ]
permissive
qilip/ACMStudy
1a006f759d52dc6afbb0cd4b6c2060a8bf5377d8
da7361b09a4519b3c721d54cd6df6ff00337fa27
refs/heads/master
2023-04-21T17:50:52.806789
2023-04-10T17:39:57
2023-04-10T17:39:57
124,194,483
4
0
null
null
null
null
UTF-8
C++
false
false
1,419
cpp
// #include <bits/stdc++.h> /* codeforces printf %Lf problem #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> */ #include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <climits> #include <iostream> #include <iomanip> #include <algorithm> #include <string> #include <vector> #include <queue> #include <stack> #include <deque> #include <utility> #include <tuple> #include <functional> #include <numeric> #include <map> #include <set> #include <list> using namespace std; typedef long long ll; int n, m; int a[510][510]; int c[510][510]; int main(void){ ios_base::sync_with_stdio(false); cin.tie(NULL); // cout.tie(NULL); // SLOW? cout<<setprecision(8)<<fixed; // code start scanf("%d %d", &n, &m); for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ scanf("%d", &a[i][j]); } } int no = 0; for(int i=0;i<n;i++){ int wcnt = 0; for(int j=0;j<m;j++){ int t; scanf("%d", &t); if(t==a[i][j]) c[i][j] = 0; else{ c[i][j] = 1; wcnt++; } } if(wcnt%2) no = 1; } for(int j=0;j<m;j++){ int hcnt = 0; for(int i=0;i<n;i++){ if(c[i][j]) hcnt++; } if(hcnt%2) no = 1; } if(no) printf("No"); else printf("Yes"); return 0; }
[ "qilip@qilip.io" ]
qilip@qilip.io
997c7eb87eb88ac0eb4f05b52bda8dd44d7caff3
2579ece8703c8596010a59740e28c6fbdd1b795a
/Bubble Sort/Source.cpp
84800bd8d92495114ac6f232eb3fbdf1c40c1eaa
[]
no_license
brockbarlow/Bubble-Sort-Assignment
67ce63552427292c83eb924638e0b09e65b20e0e
9ed0d155bce517de2b4ff1d784fc15014cde3e71
refs/heads/master
2021-01-21T21:14:25.312619
2017-05-24T17:49:14
2017-05-24T17:49:14
92,319,538
0
0
null
null
null
null
UTF-8
C++
false
false
870
cpp
//Bubble Soft (C++), 5/24/2017, Brock Barlow. //1. Implement. //2. Cost Analysis. //3a. When would this be preferred over other sorting methods? Answer: //3b. Do you know any other sorting methods? Answer(s): Heap Sort. //1. Implement: #include <iostream> #include "Header.h" //header file has bubble sort function. void main() { int testArray[] = { 45, 2, 9, 642, 1790, 17, 3, 90, 38, 35, 26, 2200, 4 }; int arraySize = sizeof(testArray) / sizeof(testArray[0]); //testArray size is 13. std::cout << "Array before bubble sort: " << std::endl; for (int i = 0; i < arraySize; i++) { std::cout << testArray[i] << " "; } bubbleSort(testArray, arraySize); std::cout << "\n" << "\n" << "Array after bubble sort: " << std::endl; for (int i = 0; i < arraySize; i++) { std::cout << testArray[i] << " "; } std::cout << "\n" << std::endl; system("pause"); }
[ "brock.barlow@students.aie.edu.au" ]
brock.barlow@students.aie.edu.au
358bda5ea1fe5ad24e23d01a36b00c61e6027c44
b4925f354c0236406d07cdab4e47667f12f58067
/club/dp/coder3.cpp
f302d35de28ddc4f0afd670feb6b2a8e388f27d5
[]
no_license
MauricioCerv10/schoolhistory
93be0e0adc57a79e5feea4665cac92d925edd9d8
7e5ef296909cc1e6daa54846e595b299e4be4e6e
refs/heads/master
2023-07-01T16:14:25.918824
2021-07-30T03:12:15
2021-07-30T03:12:15
390,902,375
0
0
null
null
null
null
UTF-8
C++
false
false
785
cpp
#include <bits/stdc++.h> using namespace std; int lis[1005]; int lds[1005]; int nums[1005]; int main(){ int t; cin>>t; while(t--){ int n; cin>>n; for(int i = 0; i<n; i++){ lis[i] = 0; lds[i] = 0;} for(int i = 0; i<n; i++) cin>>nums[i]; //LIS lis[0] = 1; for(int i = 1; i<n; i++){ lis[i] = 1; for(int j = 0; j<i ; j++) if(nums[j] < nums[i] && (lis[j] + 1) > lis[i]) lis[i] = lis[j] + 1; } //LDS lds[n-1] = 1; for(int i = n-2; i>=0; i--){ lds[i] = 1; for(int j = n-1; j>i;j--) if(nums[j] < nums[i] && lds[j] + 1 > lds[i]) lds[i] = lds[j] + 1; } int max = 1; for(int i = 0; i < n;i++){ for(int j = i+1; j<n; j++){ if(lis[i] + lds[j] > max && nums[i] > nums[j]) max = lis[i] + lds[j]; } } cout<<max<<endl; } }
[ "mauriciocervantesdelgadillo10@gmail.com" ]
mauriciocervantesdelgadillo10@gmail.com
443988cb880f7ffbb0521817dbcaa7cdc9b9c24d
6f38dd191f1a866475ccdba31b92fa0583bf6c01
/src/DynamicArray.cpp
d9eecbf09982032aa3cad8a8e84e8319b41cca0d
[]
no_license
jacintak/AdaptR
e758c455b7e92f1edb24c298990a2f0bc35b64e3
4ac906189a5579ea78dfdad0e6d62ae9d01b1f6e
refs/heads/master
2020-05-25T05:31:16.040665
2019-05-21T22:31:53
2019-05-21T22:31:53
187,650,551
0
1
null
2019-05-20T13:54:53
2019-05-20T13:54:53
null
UTF-8
C++
false
false
15,658
cpp
//***************************************************************************** // Dynamic Array . cpp // Suite of functions for the allocation and deletion of dynamic arrays, 1& 2D // Written Tom Harwood May 2010 //***************************************************************************** #include "DynamicArray.h" //***************************************************************************** //***************************************************************************** //***************************************************************************** // ***** Allocate Double 1D Array // Creates a 1D array of the specified dimension // Memory: ###### Allocates an array which must be DELETED ELSEWHERE! ####### // use FreeDouble1DArray(float**) // Arguments: // const int arg_i_n_cols number of columns // Returns: // Pointer to the double* pointing to the newly allocated 1D array //***************************************************************************** double* AllocateDouble1DArray(const int arg_i_n_cols) { double* d_new_ptr = new double[arg_i_n_cols]; return d_new_ptr; } // End func AllocateDouble1DArray //***************************************************************************** // ***** Free Double 1D Array ******** // Deletes the suuplied 1D array of the supplied TYPE // Memory: Deletes argument // Arguments: // T* arg_T_Array the array to delete // any type // Returns: none // //***************************************************************************** void FreeDouble1DArray(double* arg_d_Array) { delete [] arg_d_Array; } // end func delete double 1D array //***************************************************************************** //***************************************************************************** //***************************************************************************** // ***** Allocate Float 1D Array // Creates a 1D array of the specified dimension // Memory: ###### Allocates an array which must be DELETED ELSEWHERE! ####### // use FreeFloat1DArray(float**) // Arguments: // const int arg_i_n_cols number of columns // Returns: // Pointer to the float* pointing to the newly allocated 1D array //***************************************************************************** float* AllocateFloat1DArray(const int arg_i_n_cols) { float* f_new_ptr = new float[arg_i_n_cols]; return f_new_ptr; } // End func AllocateInt1DArray //***************************************************************************** // ***** Free INT 1D Array ******** // Deletes the suuplied 1D array of the supplied TYPE // Memory: Deletes argument // Arguments: // T* arg_T_Array the array to delete // any type // Returns: none // //***************************************************************************** void FreeFloat1DArray(float* arg_f_Array) { delete [] arg_f_Array; } // end func delete float 1D array //***************************************************************************** //***************************************************************************** //***************************************************************************** // ***** Allocate Int 1D Array // Creates a 1D array of the specified dimension // Memory: ###### Allocates an array which must be DELETED ELSEWHERE! ####### // use FreeInt1DArray(int**) // Arguments: // const int arg_i_n_cols number of columns // Returns: // Pointer to the TEMPLATE type pointing to the newly allocated 1D array //***************************************************************************** int* AllocateInt1DArray(const int arg_i_n_cols) { // Allocate memory for array int* i_new_ptr = new int[arg_i_n_cols]; return i_new_ptr; } // End func AllocateInt1DArray //***************************************************************************** // ***** Free INT 1D Array ******** // Deletes the suuplied 1D array of the supplied TYPE // Memory: Deletes argument // Arguments: // T* arg_T_Array the array to delete // any type // Returns: none // //***************************************************************************** void FreeInt1DArray(int* arg_i_Array) { // Free up array delete [] arg_i_Array; } // end func delete INT 1D array //***************************************************************************** //***************************************************************************** // ***** Allocate Long 1D Array // Creates a 1D array of the specified dimension // Memory: ###### Allocates an array which must be DELETED ELSEWHERE! ####### // use FreeInt1DArray(int**) // Arguments: // const long int arg_i_n_cols number of columns // Returns: // Pointer to the TEMPLATE type pointing to the newly allocated 1D array //***************************************************************************** long int* AllocateLong1DArray(const long int arg_i_n_cols) { // Allocate memory for array long int* i_new_ptr = new long int[arg_i_n_cols]; return i_new_ptr; } // End func AllocateLong1DArray //***************************************************************************** // ***** Free Long 1D Array ******** // Deletes the suuplied 1D array of the supplied TYPE // Memory: Deletes argument // Arguments: // T* arg_T_Array the array to delete // any type // Returns: none // //***************************************************************************** void FreeLong1DArray(long int* arg_i_Array) { // Free up array delete [] arg_i_Array; } // end func delete LONG INT 1D array //***************************************************************************** //***************************************************************************** //***************************************************************************** // ***** Allocate Short 1D Array // Creates a 1D array of the specified dimension // Memory: ###### Allocates an array which must be DELETED ELSEWHERE! ####### // use FreeShort1DArray(short**) // Arguments: // const short arg_i_n_cols number of columns // Returns: // Pointer to the TEMPLATE type pointing to the newly allocated 1D array //***************************************************************************** short* AllocateShort1DArray(const int arg_i_n_cols) { // Allocate memory for array short* s_new_ptr = new short[arg_i_n_cols]; return s_new_ptr; } // End func AllocateShort1DArray //***************************************************************************** // ***** Free SHORT 1D Array ******** // Deletes the suuplied 1D array of the supplied TYPE // Memory: Deletes argument // Arguments: // T* arg_T_Array the array to delete // any type // Returns: none // //***************************************************************************** void FreeShort1DArray(short* arg_s_Array) { // Free up array delete [] arg_s_Array; } // end func delete Short 1D array //***************************************************************************** //***************************************************************************** //***************************************************************************** // ***** Allocate Double 2D Array ******** // Creates a 2D array of the specified dimensions // Memory: ###### Allocates an array which must be DELETED ELSEWHERE! ####### // use FreeDouble2DArray(double**) // Arguments: // const int arg_i_n_rows number of rows // const int arg_i_n_cols number of columns // Returns: // Pointer to Pointer to Float pointing to the newly allocated 2D array // ..which can be referenced as result[][]. // usage example: // double** d_fish; // d_fish= AllocateDouble2DArray(10,10); // d_fish[2][5]=21.563; // FreeDouble2DArray(d_fish); //***************************************************************************** double **AllocateDouble2DArray(const int arg_i_n_rows, const int arg_i_n_cols) { int i_row; // row counter double** d_new_pptr; // Pointer to pointer for the whole 2D buffer double* d_row_ptr; // Pointer to start of each row in the array // Allocate memory for array of elements of column .. // i.e. list of pointers to first element of each row d_new_pptr = new double*[arg_i_n_rows]; // Allocate memory for array of elements of all the rows // Do this as one big block to speed things up d_row_ptr = new double [arg_i_n_rows* arg_i_n_cols]; // Now point the pointers in the right place for(i_row=0; i_row<arg_i_n_rows; i_row++) { *(d_new_pptr+i_row) = d_row_ptr; d_row_ptr += arg_i_n_cols; } return d_new_pptr; } // end func Allocate Double 2D Array //***************************************************************************** // ***** Free Double 2D Array ******** // Deletes the suuplied 2D array // Memory: Deletes argument // Arguments: // double** arg_d_Array the array to delete // Returns: none // //***************************************************************************** void FreeDouble2DArray(double** arg_d_Array) { // Free up both levels of the allocated array delete [] *arg_d_Array; delete [] arg_d_Array; } // end func delete Double 2D array //***************************************************************************** //***************************************************************************** // ***** Allocate Float 2D Array ******** // Creates a 2D array of the specified dimensions // Memory: ###### Allocates an array which must be DELETED ELSEWHERE! ####### // use FreeFloat2DArray(float**) // Arguments: // const int arg_i_n_rows number of rows // const int arg_i_n_cols number of columns // Returns: // Pointer to Pointer to Float pointing to the newly allocated 2D array // ..which can be referenced as result[][]. // usage example: // float** f_fish; // f_fish= AllocateFloat2DArray(10,10); // f_fish[2][5]=21.563; // FreeFloat2DArray(f_fish); //***************************************************************************** float **AllocateFloat2DArray( const int arg_i_n_rows, const int arg_i_n_cols) { int i_row; // row counter float** f_new_pptr; // Pointer to pointer for the whole 2D buffer float* f_row_ptr; // Pointer to start of each row in the array // Allocate memory for array of elements of column .. // i.e. list of pointers to first element of each row f_new_pptr = new float*[arg_i_n_rows]; // Allocate memory for array of elements of all the rows // Do this as one big block to speed things up f_row_ptr = new float [arg_i_n_rows* arg_i_n_cols]; // Now point the pointers in the right place for(i_row=0; i_row<arg_i_n_rows; i_row++) { *(f_new_pptr+i_row) = f_row_ptr; f_row_ptr += arg_i_n_cols; } return f_new_pptr; } // end func Allocate Float 2D Array //***************************************************************************** // ***** Free Float 2D Array ******** // Deletes the suuplied 2D array // Memory: Deletes argument // Arguments: // float** arg_f_Array the array to delete // Returns: none // //***************************************************************************** void FreeFloat2DArray(float** arg_f_Array) { // Free up both levels of the allocated array delete [] *arg_f_Array; delete [] arg_f_Array; } // end func delete Float 2D array //***************************************************************************** //***************************************************************************** // ***** Allocate Int 2D Array ******** // Creates a 2D array integers of the specified dimensions // Memory: ###### Allocates an array which must be DELETED ELSEWHERE! ####### // use FreeInt2DArray(int**) // Arguments: // const int arg_i_n_rows number of rows // const int arg_i_n_cols number of columns // Returns: // Pointer to Pointer to Int pointing to the newly allocated 2D array // ..which can be referenced as result[][]. // usage example: // int** i_fish; // i_fish= AllocateInt2DArray(60,300); // i_fish[27][35]=26.563; // FreeInt2DArray(i_fish); //***************************************************************************** int** AllocateInt2DArray( const int arg_i_n_rows, const int arg_i_n_cols) { int i_row; // row counter int** i_new_pptr; // Pointer to pointer for the whole 2D buffer int* i_row_ptr; // Pointer to start of each row in the array // Allocate memory for array of elements of column .. // i.e. list of pointers to first element of each row i_new_pptr = new int*[arg_i_n_rows]; // Allocate memory for array of elements of all the rows // Do this as one big block to speed things up i_row_ptr = new int[arg_i_n_rows*arg_i_n_cols]; // Now point the pointers in the right place for(i_row=0; i_row<arg_i_n_rows; i_row++) { *(i_new_pptr+i_row) = i_row_ptr; i_row_ptr += arg_i_n_cols; } return i_new_pptr; } // end func Allocate Int 2D Array //***************************************************************************** // ***** Free Int 2D Array ******** // Deletes the suuplied 2D array // Memory: Deletes argument // Arguments: // int** arg_i_Array the array to delete // Returns: none // //***************************************************************************** void FreeInt2DArray(int** arg_i_Array) { // Free up both levels of the allocated array delete [] *arg_i_Array; delete [] arg_i_Array; } // end func delete Int 2D array //***************************************************************************** // ***** Allocate Short 2D Array ******** // Creates a 2D array short integers of the specified dimensions // Memory: ###### Allocates an array which must be DELETED ELSEWHERE! ####### // use FreeShort2DArray(short**) // Arguments: // const short arg_i_n_rows number of rows // const short arg_i_n_cols number of columns // Returns: // Pointer to Pointer to short pointing to the newly allocated 2D array // ..which can be referenced as result[][]. // usage example: // short** s_fish; // s_fish= AllocateShort2DArray(60,300); // s_fish[27][35]=26.563; // FreeShort2DArray(s_fish); //***************************************************************************** short** AllocateShort2DArray(const int arg_i_n_rows, const int arg_i_n_cols) { int i_row; // row counter short** s_new_pptr; // Pointer to pointer for the whole 2D buffer short* s_row_ptr; // Pointer to start of each row in the array // Allocate memory for array of elements of column .. // i.e. list of pointers to first element of each row s_new_pptr = new short*[arg_i_n_rows]; // Allocate memory for array of elements of all the rows // Do this as one big block to speed things up s_row_ptr = new short[arg_i_n_rows*arg_i_n_cols]; // Now point the pointers in the right place for(i_row=0; i_row<arg_i_n_rows; i_row++) { *(s_new_pptr+i_row) = s_row_ptr; s_row_ptr += arg_i_n_cols; } return s_new_pptr; } // end func Allocate Short 2D Array //***************************************************************************** // ***** Free short 2D Array ******** // Deletes the suuplied 2D array // Memory: Deletes argument // Arguments: // short** arg_s_Array the array to delete // Returns: none // //***************************************************************************** void FreeShort2DArray(short** arg_s_Array) { // Free up both levels of the allocated array delete [] *arg_s_Array; delete [] arg_s_Array; } // end func delete short 2D array //---------------------------------------------------------------------------
[ "Karel.Mokany@csiro.au" ]
Karel.Mokany@csiro.au
f3131a696ffb16bc4c8f82f2ff3e6bbbf734e900
7d8123fc07fbb467ed09f840d2399d2a915e539d
/Siv3D/src/Siv3D/Renderer2D/IRenderer2D.hpp
98678b74e6f7c9b267627398d82557eb9c221c95
[ "MIT" ]
permissive
Fuyutsubaki/OpenSiv3D
8ab206dd675bbc66ef4d7f496f163dcf30072d17
4370f6ebe28addd39bfdd75915c5a18e3e5e9273
refs/heads/master
2020-12-25T06:24:11.141196
2019-04-06T15:24:27
2019-04-06T15:24:27
60,793,366
0
0
null
null
null
null
UTF-8
C++
false
false
4,499
hpp
//----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (c) 2008-2018 Ryo Suzuki // Copyright (c) 2016-2018 OpenSiv3D Project // // Licensed under the MIT License. // //----------------------------------------------- # pragma once # include <Siv3D/Fwd.hpp> # include <Siv3D/Array.hpp> # include <Siv3D/Optional.hpp> # include <Siv3D/Texture.hpp> # include <Siv3D/PointVector.hpp> # include <Siv3D/SamplerState.hpp> namespace s3d { class ISiv3DRenderer2D { public: static ISiv3DRenderer2D* Create(); virtual ~ISiv3DRenderer2D() = default; virtual void flush(bool clearGraphics) = 0; virtual void setBlendState(const BlendState& state) = 0; virtual BlendState getBlendState() const = 0; virtual void setRasterizerState(const RasterizerState& state) = 0; virtual RasterizerState getRasterizerState() const = 0; virtual void setSamplerState(ShaderStage stage, uint32 slot, const SamplerState& state) = 0; virtual const std::array<SamplerState, SamplerState::MaxSamplerCount>& getSamplerStates(ShaderStage stage) const = 0; virtual void setScissorRect(const Rect& rect) = 0; virtual Rect getScissorRect() const = 0; virtual void setViewport(const Optional<Rect>& viewport) = 0; virtual Optional<Rect> getViewport() const = 0; virtual void setTransformLocal(const Mat3x2& matrix) = 0; virtual void setTransformCamera(const Mat3x2& matrix) = 0; virtual void setTransformScreen(const Mat3x2& matrix) = 0; virtual const Mat3x2& getTransformLocal() const = 0; virtual const Mat3x2& getTransformCamera() const = 0; virtual const Mat3x2& getTransformScreen() const = 0; virtual float getMaxScaling() const = 0; virtual void addLine(const LineStyle& style, const Float2& begin, const Float2& end, float thickness, const Float4(&colors)[2]) = 0; virtual void addTriangle(const Float2(&pts)[3], const Float4& color) = 0; virtual void addTriangle(const Float2(&pts)[3], const Float4(&colors)[3]) = 0; virtual void addRect(const FloatRect& rect, const Float4& color) = 0; virtual void addRect(const FloatRect& rect, const Float4(&colors)[4]) = 0; virtual void addRectFrame(const FloatRect& rect, float thickness, const Float4& color) = 0; virtual void addCircle(const Float2& center, float r, const Float4& color) = 0; virtual void addCircleFrame(const Float2& center, float r, float thickness, const Float4& color) = 0; virtual void addCircleFrame(const Float2& center, float r, float thickness, const Float4& innerColor, const Float4& outerColor) = 0; virtual void addCirclePie(const Float2& center, float r, float startAngle, float angle, const Float4& color) = 0; virtual void addCircleArc(const Float2& center, float r, float startAngle, float angle, float thickness, const Float4& color) = 0; virtual void addEllipse(const Float2& center, float a, float b, const Float4& color) = 0; virtual void addEllipseFrame(const Float2& center, float a, float b, float thickness, const Float4& color) = 0; virtual void addQuad(const FloatQuad& quad, const Float4& color) = 0; virtual void addQuad(const FloatQuad& quad, const Float4(&colors)[4]) = 0; virtual void addLineString(LineStyle style, const Vec2* pts, uint32 size, const Optional<Float2>& offset, float thickness, bool inner, const Float4& color, bool isClosed) = 0; virtual void addShape2D(const Array<Float2>& vertices, const Array<uint32>& indices, const Optional<Float2>& offset, const Float4& color) = 0; virtual void addShape2DFrame(const Float2* pts, uint32 size, float thickness, const Float4& color) = 0; virtual void addShape2DTransformed(const Array<Float2>& vertices, const Array<uint32>& indices, float s, float c, const Float2& offset, const Float4& color) = 0; virtual void addTextureRegion(const Texture& texture, const FloatRect& rect, const FloatRect& uv, const Float4& color) = 0; virtual void addTextureRegion(const Texture& texture, const FloatRect& rect, const FloatRect& uv, const Float4(&colors)[4]) = 0; virtual void addTexturedCircle(const Texture& texture, const Circle& circle, const FloatRect& uv, const Float4& color) = 0; virtual void addTexturedQuad(const Texture& texture, const FloatQuad& quad, const FloatRect& uv, const Float4& color) = 0; virtual void addSprite(const Optional<Texture>& texture, const Sprite& sprite, uint32 startIndex, uint32 indexCount) = 0; virtual const Texture& getBoxShadowTexture() const = 0; }; }
[ "Reputeless@users.noreply.github.com" ]
Reputeless@users.noreply.github.com
196dcb7604b4c4b3254bc7d5bc2a3757f994d766
54f86b5ec332bc4cde6d41c78b61cfa1241cd6d5
/Experiment 10.cpp
50ac0295ec342d9c039d46e085ddc491b3df0ed9
[]
no_license
ShethDhvaniHitesh/DS-Lab-File
f371d025766076af731f4269240133dfa5ceabc1
9052b5b7293c784082dc791835d38d13b00f794a
refs/heads/master
2020-04-06T17:35:21.240165
2018-11-15T07:02:58
2018-11-15T07:02:58
157,666,023
0
0
null
null
null
null
UTF-8
C++
false
false
620
cpp
#include<iostream> using namespace std; int merge(int *A, int M, int *B, int N, int *C) { int p=0.q=0,k=0,c=0; while ( p < M && q < N) { if (A[p] < B[q]) { C[k++] = A[p++]; c++; } else { C[k++] = B[q++]; c++; } } while ( p < M) { C[k++] = A[p++]; } while ( q < N) { C[k++] = B[q++]; } return c; } int main() { int i,M,N; cin >> M >> N; int A[M],B[N],C[M+N]; int X; for(i=0;i<=M-1;i++) cin >> A[i]; for(i=0;i<=N-1;i++) cin >> B[i]; X = merge(A,M,B,N,C); for(i=0;i<=M+N-1;i++) cout << C[i] << " "; cout << endl << X; return 0; }
[ "noreply@github.com" ]
ShethDhvaniHitesh.noreply@github.com
64d899ba0d9cecf1e443d94ae07710d655d12d66
ff0ace7d298b35d3a90b8dd5ba3d9fd3aa7745ac
/android.cpp
1a9582ea3cf4bd16e7b599917b8aca486aed2a68
[]
no_license
myuaggie/cg_fkr
25880cf4f4b7dd347a62abc9f50d3ea0208b124e
8d969907fc89f24c908e1282c97b6e885a0e862e
refs/heads/master
2020-04-11T18:49:09.915081
2018-12-17T15:03:41
2018-12-17T15:03:41
162,012,618
0
0
null
null
null
null
UTF-8
C++
false
false
1,899
cpp
// // Created by myu on 2018/12/2. // #include "android.h" #include <iostream> #include <math.h> using namespace std; Android::Android(float dx, float dy, float dz) { x = dx; y = dy; z = dz; c = 3.1415926 / 180.0f; v = 2; w = 5; maxD = 10; mode = 0; angle = 0; angleHead = 0; //angleY angleLeftFoot = 0; // angleZ angleRightFoot = 0; angleLeftHand = 0; angleRightHand = 0; modeLeftFoot = -1; modeRightFoot = 1; modeLeftHand = 1; modeRightHand = -1; bias = 0; } void Android::changeDirection(float degree) { angle = degree; } void Android::swing(){ if (angleLeftFoot == maxD || angleLeftFoot == -maxD){ modeLeftFoot = 0-modeLeftFoot; } if (angleRightFoot == maxD || angleRightFoot == -maxD){ modeRightFoot = 0-modeRightFoot; } if (angleLeftHand == maxD || angleLeftHand == -maxD){ modeLeftHand = 0-modeLeftHand; } if (angleRightHand == maxD || angleRightHand == -maxD){ modeRightHand = 0-modeRightHand; } angleLeftFoot += modeLeftFoot * w; angleRightFoot += modeRightFoot * w; angleLeftHand += modeLeftHand * w; angleRightHand += modeRightHand * w; } void Android::forward() { swing(); z += v * cos(angle*c); x += v * sin(angle*c); if (x <= -380/sqrt(2)){x = -379/sqrt(2);} else if (x >= 380/sqrt(2)) {x = 379/sqrt(2);} if (z <= -380/sqrt(2)) {z = -379/sqrt(2);} else if (z >= 380/sqrt(2)) {z = 379/sqrt(2);} } void Android::setForward(){ mode = 1; } void Android::setStill() { angleLeftFoot = 0; angleRightFoot = 0; angleLeftHand = 0; angleRightHand = 0; modeLeftFoot = -1; modeRightFoot = 1; modeLeftHand = 1; modeRightHand = -1; mode = 0; } void Android::captured() { setStill(); mode = -2; if (bias != 20) { bias += 0.5; } }
[ "920369216@qq.com" ]
920369216@qq.com
2192bba6e3c4dacc78f04201c2c6613d9cefa222
545c6f6a18bcbb1221e8698e67a8fdff2c8ca673
/creature.h
6242c3ec57e4e47253cfc2a28fc664dfd10d0b88
[]
no_license
CheshireCat26/Life
12e0c1edf100257c3c4684ba9c90e2a54ae5b923
5f289cc9a553da4ede089c9c84e8a6199f8bf79e
refs/heads/master
2020-04-14T23:48:20.539111
2019-01-05T13:20:27
2019-01-05T13:20:27
164,211,858
0
0
null
null
null
null
UTF-8
C++
false
false
657
h
// // Created by nail1 on 05.01.2019. // #ifndef LIFE_CREATURE_H #define LIFE_CREATURE_H class Creature { public: Creature() : food{100}, health{100} {} int getFood() { return food; } int getHealth() { return health; } void eat(); //Существо пытается есть private: int food; int health; const static int hunger = 2; //Скорость с которой убывает food const static int eatSpeed = 3; //Скорость увеличение food const static int die = 2; //Скороть с которой убывает die const static int eatChance = 50; }; #endif //LIFE_CREATURE_H
[ "nail160306@gmail.com" ]
nail160306@gmail.com
11c494e20a46779e502f92292f2e62a9da297776
cba27af08c33150ed2fc1f40e50c3b89046497ab
/sensor.h
e867c419c5d95eb946f9843866b512c01cc3aa14
[]
no_license
ShepherdSosimple/USB-DAQ-V1.2
e5c967b1b9ad8e4bef3d32d2b43cb9031a7d6019
11a7c49dc6306a3476b09b45677d591a205b301b
refs/heads/master
2020-04-15T17:10:14.485099
2019-01-09T13:11:07
2019-01-09T13:11:07
164,863,794
0
2
null
null
null
null
UTF-8
C++
false
false
837
h
#ifndef SENSOR_H #define SENSOR_H #include <QQueue> //基类:传感器 class Sensor { public: int num; //传感器对应的采集卡端口 QQueue<float> voltages; //传感器电压值队列 float voltage; //传感器电压值 Sensor(); explicit Sensor(int n); ~Sensor(); }; //派生类:光电开关(模拟量形式) class Photoelec: public Sensor { private: const float max_v = 10.0; const float min_v = 1.0; public: bool arrive; Photoelec(); Photoelec(int n); ~Photoelec(); bool IsArrive(); }; //派生类:力传感器 class ForceSensor: public Sensor { public: ForceSensor(); ForceSensor(int n); bool processFlag;//力数据处理标志 quint64 counts; ~ForceSensor(); }; #endif // SENSOR_H
[ "noreply@github.com" ]
ShepherdSosimple.noreply@github.com
e60b4a84eca4b2f859a601d8d1319320753783cf
0b8cef02024d1fa64e858d0f17365d26a8ad8d50
/geotemporal-spray-and-wait/model/geotemporal-spray-and-wait-neighbors-table.cc
0a3eee8369bc85d4788d91471e3dbae04c942d03
[]
no_license
LuissRicardo/NS3-GeoTemporalProtocols
bf68159e7d2965767a9ea26334afcd1d89f63169
d69c49c430cf1e889fab15fcc66c315ea62d273e
refs/heads/master
2022-11-23T00:01:45.799606
2020-04-28T09:30:44
2020-04-28T09:30:44
188,138,171
1
0
null
null
null
null
UTF-8
C++
false
false
6,954
cc
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2019 Luis Ricardo Gallego Tercero <luiss_121314@hotmail.com>, * Networks and Data Science Laboratory (NDS-Lab) at the * Computing Research Center (CIC-IPN) <www.prime.cic.ipn.mx> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * 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, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Luis Ricardo Gallego Tercero <luiss_121314@hotmail.com> * * Neighbors table of the Geo-Temporal Spray And Wait protocol. */ #include "geotemporal-spray-and-wait-neighbors-table.h" #include <algorithm> #include <cstdio> #include <utility> #include <ns3/log.h> #include <ns3/packet-utils.h> NS_LOG_COMPONENT_DEFINE ("GeoTemporalSprayAndWaitNeighborsTable"); namespace ns3 { namespace geotemporal_spray_and_wait { // ============================================================================= // NeighborEntry // ============================================================================= NeighborEntry::NeighborEntry () : m_neighbor_ip (), m_expiration_time () { } NeighborEntry::NeighborEntry (const Ipv4Address& neighbor_ip, const Time& expiration_time) : m_neighbor_ip (neighbor_ip), m_expiration_time () { SetExpirationTime (expiration_time); } NeighborEntry::NeighborEntry (const NeighborEntry& copy) : m_neighbor_ip (copy.m_neighbor_ip), m_expiration_time (copy.m_expiration_time) { } void NeighborEntry::Print (std::ostream& os) const { os << ToString (); } std::string NeighborEntry::ToString () const { char buffer[15]; std::sprintf (buffer, "%.2f", m_expiration_time.ToDouble (Time::S)); std::string str = "Neighbor entry " + GeoTemporalLibrary::LibraryUtils::ToString (m_neighbor_ip) + " will expire at second " + std::string (buffer); return str; } // ============================================================================= // NeighborsTable // ============================================================================= NeighborsTable::NeighborsTable () : NeighborsTable (Seconds (15)) { NS_LOG_FUNCTION (this); } NeighborsTable::NeighborsTable (const Time& entries_expiration_time) : m_table (), m_entries_expiration_time (entries_expiration_time) { NS_LOG_FUNCTION (this); } NeighborsTable::NeighborsTable (const NeighborsTable& copy) : m_table (copy.m_table), m_entries_expiration_time (copy.m_entries_expiration_time) { NS_LOG_FUNCTION (this); } // -------------------------- // Getters & Setters // -------------------------- uint32_t NeighborsTable::Size () { NS_LOG_FUNCTION (this); Purge (); return m_table.size (); } // -------------------------- // Lookup // -------------------------- bool NeighborsTable::Find (const Ipv4Address& neighbor_ip, NeighborEntry& entry) { NS_LOG_FUNCTION (this); Purge (); ConstIterator_t entry_it = m_table.find (neighbor_ip); if (entry_it == m_table.end ()) { return false; } entry = entry_it->second; return true; } bool NeighborsTable::Find (const Ipv4Address& neighbor_ip) { NS_LOG_FUNCTION (this); NeighborEntry temp; return Find (neighbor_ip, temp); } bool NeighborsTable::Find (const NeighborEntry& neighbor_entry) { NS_LOG_FUNCTION (this); NeighborEntry temp; return Find (neighbor_entry.GetNeighborIpAddress (), temp); } // -------------------------- // Modifiers // -------------------------- bool NeighborsTable::Insert (const Ipv4Address& new_neighbor_ip) { NS_LOG_FUNCTION (this << new_neighbor_ip); Purge (); NS_LOG_DEBUG (m_table.size () << " neighbors before insertion of new neighbor " << new_neighbor_ip); if (Find (new_neighbor_ip)) { NS_LOG_DEBUG ("Neighbor " << new_neighbor_ip << " already present in table. Insertion ignored."); return false; } const NeighborEntry new_neighbor_entry (new_neighbor_ip, m_entries_expiration_time); m_table.insert (std::make_pair (new_neighbor_ip, new_neighbor_entry)); NS_LOG_DEBUG (m_table.size () << " neighbors after insertion of new neighbor: " << new_neighbor_entry); return true; } bool NeighborsTable::Remove (const Ipv4Address& neighbor_ip_to_delete) { NS_LOG_FUNCTION (this << neighbor_ip_to_delete); Purge (); NS_LOG_DEBUG ("Removing neighbor " << neighbor_ip_to_delete); return m_table.erase (neighbor_ip_to_delete) > 0u; } bool NeighborsTable::Remove (const NeighborEntry& neighbor_entry_to_delete) { NS_LOG_FUNCTION (this << neighbor_entry_to_delete); return Remove (neighbor_entry_to_delete.GetNeighborIpAddress ()); } bool NeighborsTable::RestartNeighborEntryExpirationTime (const Ipv4Address& neighbor_ip) { NS_LOG_FUNCTION (this << neighbor_ip); Iterator_t entry_it = m_table.find (neighbor_ip); if (entry_it == m_table.end ()) { NS_LOG_DEBUG ("Neighbor " << neighbor_ip << " not present in table. Operation ignored."); return false; } NS_LOG_DEBUG ("Expiration time of neighbor entry " << neighbor_ip << " restarted."); entry_it->second.SetExpirationTime (m_entries_expiration_time); return true; } void NeighborsTable::Purge () { NS_LOG_FUNCTION (this); for (ConstIterator_t entry_it = m_table.begin (); entry_it != m_table.end ();) { if (entry_it->second.GetExpirationTime () <= Seconds (0)) { NS_LOG_LOGIC ("Drops expired neighbor entry : " << entry_it->second); // m_table.erase (entry_it++); // For C++03 entry_it = m_table.erase (entry_it); // For C++11 } else { ++entry_it; } } } void NeighborsTable::Print (std::ostream& os) const { NS_LOG_FUNCTION (this); os << ToString (); } std::string NeighborsTable::ToString () const { NS_LOG_FUNCTION (this); char buffer [10]; std::sprintf (buffer, "%u", (uint32_t) m_table.size ()); std::string str = "Neighbors table with " + std::string (buffer) + " entries"; if (m_table.size () > 0) str += ":"; for (ConstIterator_t it = m_table.begin (); it != m_table.end (); ++it) { str += " " + GeoTemporalLibrary::LibraryUtils::ToString (it->second.GetNeighborIpAddress ()); } return str; } } // namespace geotemporal_spray_and_wait } // namespace ns3
[ "luiss_121314@hotmail.com" ]
luiss_121314@hotmail.com
ff9fc1ae1de15bddea8b0d26a318e370fa86acd9
3c483b666c0fbe5a28cb68261ee5c64f0aff2ea5
/B1/B1_project/ratingd.h
f93a8f04b1f09360de36dae4620bc479fa7d9098
[]
no_license
Fater20/NJUPT_SoftwareDesign
f7f6bfdc1c009065df1707628c1eaa575f1d5a39
afe6f5e5efad95b17b387566f70a3bb2d083f9c8
refs/heads/main
2023-06-05T17:28:10.494311
2021-06-21T01:08:10
2021-06-21T01:08:10
375,620,407
3
1
null
null
null
null
UTF-8
C++
false
false
265
h
#ifndef RATINGD_H #define RATINGD_H #include <QDialog> namespace Ui { class ratingd; } class ratingd : public QDialog { Q_OBJECT public: explicit ratingd(QWidget *parent = nullptr); ~ratingd(); private: Ui::ratingd *ui; }; #endif // RATINGD_H
[ "1524644382@qq.com" ]
1524644382@qq.com
ce94655eb8617860b403166754bc685819ab5af8
78d9ca77a93d213d39a3afcd94da3e44478c6759
/GaussJordan.cpp
8033c7d14eaaff193c2987649f0b516500402994
[]
no_license
parthpm/PSNA_Lab
d574e199b2e3a5669eff4b202961f09754868456
ae0337ea965188d239b830100f6e697bbbd5fcaf
refs/heads/master
2020-04-15T10:15:16.993233
2019-04-17T09:35:42
2019-04-17T09:35:42
164,588,078
3
1
null
null
null
null
UTF-8
C++
false
false
912
cpp
#include<stdio.h> int main() { int i,j,k,n; float A[20][20],c,x[10]; printf("\nEnter the size of matrix: "); scanf("%d",&n); printf("\nEnter the elements of augmented matrix row-wise:\n"); for(i=1; i<=n; i++) { for(j=1; j<=(n+1); j++) { printf(" A[%d][%d]:", i,j); scanf("%f",&A[i][j]); } } /* Now finding the elements of diagonal matrix */ for(j=1; j<=n; j++) { for(i=1; i<=n; i++) { if(i!=j) { c=A[i][j]/A[j][j]; for(k=1; k<=n+1; k++) { A[i][k]=A[i][k]-c*A[j][k]; } } } } printf("\nThe solution is:\n"); for(i=1; i<=n; i++) { x[i]=A[i][n+1]/A[i][i]; printf("\n x%d=%f\n",i,x[i]); } return(0); }
[ "noreply@github.com" ]
parthpm.noreply@github.com
f74e942d779a6669f868e811f0468f730d1762fa
a04ea7a5b5baf88fd131a2163131ce6f53f57c0d
/MultiplayerSnake/MultiplayerSnake.cpp
06eec356f338ab8c43189eb6670c4f849b111900
[]
no_license
hardcoregandhi/MultiplayerSnakeServer
d090ba72bb0d0979752a99e74014b7f6abd72f57
70db5a4078c2ae13ca5914c488558b5b63dc3c49
refs/heads/master
2021-07-17T07:53:37.867300
2017-10-20T17:58:41
2017-10-20T17:58:41
107,709,481
0
0
null
null
null
null
UTF-8
C++
false
false
4,983
cpp
// MultiplayerSnake.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <SDL.h> #include <iostream> #include <string> #include <vector> #include "SDL2net\include\SDL_net.h" #include <SDL_ttf.h> #include <sstream> const int SCREEN_WIDTH = 1000; const int SCREEN_HEIGHT = 1000; const int GRID_DIVIDER = 2; const int FPS = 60; const int SCREEN_TICKS_PER_FRAME = 1000 / FPS; const int gridHeight = 50; const int gridWidth = 50; using namespace std; struct vec2 { int x; int y; vec2() {}; vec2(int x, int y) : x(x), y(y) {}; friend inline bool operator==(const vec2 lhs, const vec2 rhs) { return(lhs.x == rhs.x && lhs.y == rhs.y); } }; enum constantDirection { UP, DOWN, LEFT, RIGHT }; enum dataType { NONE, BODY, BIP, SERVER }; int grid[gridHeight][gridWidth]; #define PORT 2000 struct packet { int id; dataType dataType = NONE; int bodylength; vec2 body[100]; }; struct handshake { string st = "hello"; int clientIp; }; struct player { TCPsocket socket; handshake hs; std::vector<vec2> playerBody; packet playerPacket; player() {}; player(TCPsocket _socket) : socket(_socket) {}; }; vec2 bipLocation; constantDirection playerDirection = UP; /** * Log an SDL error with some error message to the output stream of our choice * @param os The output stream to write the message to * @param msg The error message to write, format will be msg error: SDL_GetError() */ void logSDLError(std::ostream &os, const std::string &msg) { os << msg.c_str() << " error: " << SDL_GetError() << std::endl; } std::vector<player> otherplayers; SDL_Event e; int main(int, char**) { if (SDL_Init(SDL_INIT_EVERYTHING) != 0) { logSDLError(std::cout, "SDL_Init"); return 1; } //SERVER bool isServer = false; TCPsocket server = 0; TCPsocket client; vector<player> clients; float serverTickRate = 60; float serverTickTimer = -1; SDLNet_Init(); //CLIENT IPaddress ip; //90.253.170.185 SDLNet_ResolveHost(&ip, "127.0.0.1", PORT); server = SDLNet_TCP_Open(&ip); handshake hs; if (server) { int ret = SDLNet_TCP_Recv(server, &hs, sizeof(handshake)); cout << "handshake :" << sizeof(handshake) << endl; cout << "Received :" << ret << endl; std::cout << "Connected to " << SDLNet_TCP_GetPeerAddress(server)->host << std::endl; std::cout << hs.st << std::endl; } else { cout << "Creating Server..." << endl; char res; //cin >> res; if (1) { isServer = true; //SERVER IPaddress ip; //90.253.170.185 SDLNet_ResolveHost(&ip, NULL, PORT); server = SDLNet_TCP_Open(&ip); } } bool isGrowing = false; float movementCooldownTimer = -1; float previousTime = 0; bool quit = false; cout << "Server Created." << endl; cout << "Server Running..." << endl; while (!quit) { //system("cls"); while (SDL_PollEvent(&e)) { if (e.type == SDL_QUIT) { quit = true; } //If user presses esc if (e.key.keysym.sym == SDLK_ESCAPE) { quit = true; } } //accept new players TCPsocket client = SDLNet_TCP_Accept(server); if (client) { clients.push_back(player(client)); handshake hs; clients.back().hs.clientIp = SDLNet_TCP_GetPeerAddress(client)->host; int ret = SDLNet_TCP_Send(client, &clients.back().hs, sizeof(handshake)); cout << "Sent :" << ret << endl; cout << "New player detected : " << clients.back().hs.clientIp << endl; } packet data; if (!clients.empty()) { //recieve packets for each (player clis in clients) { int ret = SDLNet_TCP_Recv(clis.socket, &clis, sizeof(packet)); cout << "Received :" << ret << endl; if (ret != -1) { cout << "Received :" << ret << endl; cout << "Packet Received from " << clis.hs.clientIp << endl; cout << data.id << endl; cout << data.dataType << endl; cout << data.body[0].x << " " << data.body[0].y << endl; //new bip requested if (data.dataType == dataType::BIP) { cout << " Bip requested" << endl; packet updatedBip; bipLocation = vec2(rand() % 20, rand() % 20); updatedBip.dataType = SERVER; updatedBip.body[0] = bipLocation; for each (player cli in clients) { int ret = SDLNet_TCP_Send(cli.socket, &updatedBip, sizeof(packet)); cout << "Sent new bip location to:" << cli.hs.clientIp << endl; cout << "Sent :" << ret << endl; } ////updated body //if (data.dataType == dataType::BODY) //{ // cout << " Body Updated" << endl; // vector<vec2> cliBody; // for each (player var in clients) // { // if (var.hs.clientIp == data.id) // { // var.playerBody.clear(); // for each (vec2 location in data.body) // { // var.playerBody.push_back(location); // } // } // } //} } cout << "Packet Closed from " << clis.hs.clientIp << endl; } } } } //SDLNet_TCP_Close(server); SDL_Quit(); return 0; }
[ "j.dryan@hotmail.com" ]
j.dryan@hotmail.com
72d50bd1841a10d538f9000396fdbacd966cda0e
591df59d439e1d7cc630a6a5958e7a92c6bdaabc
/ui/platform/custom/FontToolBar.hpp
2d4501ff83c904c6fac35c186b7e02d277a756a2
[]
no_license
kjhgnkv/DSControl_17_09
b929ef051d7a17705bc963c1bcda96badf860463
03957e8153e3852cbf026ec37bdac340a6b23f24
refs/heads/main
2023-08-02T19:20:05.527221
2021-10-01T14:59:20
2021-10-01T14:59:20
412,485,720
0
0
null
null
null
null
UTF-8
C++
false
false
489
hpp
#pragma once #include <QFontComboBox> #include <QSpinBox> #include <QToolBar> #include "ColorButton.hpp" namespace dscontrol { class ColorButton; /*! \brief qt designer have not functionality for add widgets in QToolBar, so we create custom class witch represent this */ class FontToolBar : public QToolBar { public: explicit FontToolBar(QWidget* parent); QFontComboBox* fontBox_; QSpinBox* fontSizeSpin_; ColorButton* fontColorButton_; }; } // namespace dscontrol
[ "yingfanyz@gmail.com" ]
yingfanyz@gmail.com
1baba581997760a187fe9574ec4362904fb78c76
383cc38fd74b0194c1b9fda4517bd35f371c0ffa
/Game Engine/VFXFireShaders.h
5c25f4cf6cd5c000ff107b0c6a582dc553cc7797
[]
no_license
Petterf91/BelowZero-Game
2b7632ac5510172bbe3c397fed150a7d9d2605d5
4ce9176353952e986a29cec31ed6f58aa5569ca0
refs/heads/master
2020-05-20T08:21:36.811988
2019-05-07T20:55:06
2019-05-07T20:55:06
185,471,994
1
1
null
null
null
null
UTF-8
C++
false
false
428
h
#pragma once #include <windows.h> #include <vector> #include <string> #include <fstream> #include <GL/gl3w.h> #include "ShaderBase.h" #include "Mesh.h" #pragma comment(lib, "opengl32.lib") #pragma comment(lib, "glew32.lib") class VFXFireShaders :public ShaderBase { public: VFXFireShaders(); VFXFireShaders(int otherAssetID); ~VFXFireShaders(); void CreateShaderData(); GLuint vfxFireShaderProgram; int assetID; };
[ "petter.flood91@gmail.com" ]
petter.flood91@gmail.com
84bf79b6dfda0426dbddebf1aa44ac74fa117946
3bd90c84fdd0aaecdf7e704a6b7ab2aa2212190e
/_common/Engine/Renderer/MaterialState.h
ee7e47494e718a0393fce5a8aa2a54fa34e347ee
[]
no_license
Hengle/OPENGL_Lispsm
064cbf5a9ee290b9a63f51b2b7f974d48d30bf00
4d863b7d7d41f896e80f050c364ea79f86eee890
refs/heads/master
2021-06-08T06:15:43.323680
2016-08-31T09:02:04
2016-08-31T09:02:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
918
h
#ifndef MaterialStateH #define MaterialStateH //--------------------------------------------------------------------------- #include "RenderState.h" #include "../EngineBase/Color4.h" #include "../EngineBase/Color3.h" #include "../Mathematic/Mathematic.h" #include "TextureManager.h" //--------------------------------------------------------------------------- class MaterialState; typedef SmartPointer<MaterialState> SmpMaterialState; class MaterialState : public RenderState { private: static RenderStateID id; public: typedef Color4<Math::Real> C4; typedef Color3<Math::Real> C3; C4 ambient, diffuse, specular; Math::Real shininess; bool twoSided; std::string name; ITexture texture1; MaterialState(const std::string& vName): name(vName), ambient(C4::WHITE()), diffuse(C4::WHITE()), specular(C4::WHITE()), shininess(1), twoSided(false) { } static const SmpMaterialState DEFAULT; }; #endif
[ "xtknightMM@iCloud.com" ]
xtknightMM@iCloud.com
c585468888397654925c2f36272ae9b9c3de5fb1
ef2027a883384e78034cfe692b37f9d61927f632
/DRChanllenge/Project/source/utils/BitReader.cpp
e51cbf03247914ae99e6ebc96bd178331f4b19da
[]
no_license
Decision2016/ExperimentRepo
476d72b65bcf55789a3df1d6d49f5149ae785ddb
fa2968b09818da63f4344f309e0d87573064a90e
refs/heads/main
2023-04-21T07:49:11.691212
2021-05-17T11:42:09
2021-05-17T11:42:09
309,039,062
0
0
null
null
null
null
UTF-8
C++
false
false
1,529
cpp
// // Created by Decision on 2021/3/20. // #include "BitReader.h" BitReader::BitReader(uint8_t *_ptr, int pos) { ptr = _ptr; _position = pos; } // input bit_num, read bit from left to right uint32_t BitReader::fnReadBits(int bit_nums, bool _move) { if (bit_nums > 16) return 0; uint16_t res = 0; uint8_t _tmp; int savePos = _position; uint8_t *savePtr = ptr; int nextPosition = _position + bit_nums; for (int i = 0; i < 3; i++) { _tmp = *ptr << _position; _tmp >>= _position; if (nextPosition == -1) break; if (nextPosition >= 8) { res = (res << 8) + _tmp; _position = 0; if (*ptr == 0xFF && *(ptr + 1) == 0x00) ptr += 2; else if (*ptr == 0xFF && *(ptr + 1) != 0x00){ err = true; } else ptr++; nextPosition -= 8; } else if(nextPosition < 8){ int delta = 8 - nextPosition; res = (res << nextPosition) + (_tmp >> delta); _position = nextPosition; nextPosition = -1; } } if (!_move) { ptr = savePtr; _position = savePos; } return res; } void BitReader::debug(uint8_t *_data) { // std::cout<<"Count:"<<_position<<std::endl; std::cout<<std::hex<<(int)(ptr - _data)<<":"<<_position<<std::endl; } uint8_t* BitReader::getPtr() { return ptr; } bool BitReader::checkErr() { return err; } int BitReader::getPosition() { return _position; }
[ "787362202@qq.com" ]
787362202@qq.com
52d8739f1dd657a759fe5ddd31c020d1e19829be
34f6293a0ee5a78830ff4bcf0e96c27d9b015b7b
/loops.cpp
eabda3bcee9e4a0f01ee3e39e636d53ea9badd8b
[ "MIT" ]
permissive
Aaqib925/Cpp
22a995eccafbb9d72f0890fc44f5f06b6dab67ef
cba7b42a486dd8e5c734f0d8907c53c64d47617b
refs/heads/master
2023-03-12T05:00:32.903617
2021-02-11T09:55:51
2021-02-11T09:55:51
272,004,648
2
0
null
null
null
null
UTF-8
C++
false
false
400
cpp
#include <iostream> using namespace std; void forLoop(); int main(){ int x = 1; while (x < 5){ cout << x << endl; x += 1; } do{ // it executes first then check the condition cout << x << endl; x += 1; } while(x <= 10); forLoop(); } // using for loop void forLoop(){ for (int i = 0; i < 10; i ++){ cout << i << endl; } }
[ "muhammadaaqib925@gmail.com" ]
muhammadaaqib925@gmail.com
7c517b70b0bb3d6dd06a869e69fe274a9c1cd7e5
0688ed4fbbbd19613cc453c568af75ba59ae5144
/libraries/mojingsdk/src/main/cpp/Hook/Global/detour.cpp
936161f2d497025d752c00117081efdeac178b56
[]
no_license
playbar/testplayer
49c068e53a5b93768b4d46f4f9b8d2bb739ff7fe
b4869ed9193739ab48c067cd51b4f5084943e924
refs/heads/master
2021-05-07T03:37:09.438661
2017-11-20T03:38:59
2017-11-20T03:38:59
110,958,488
3
0
null
null
null
null
UTF-8
C++
false
false
13,439
cpp
#include <stdlib.h> #include <stdbool.h> #include <string.h> #include <dirent.h> #include <signal.h> #include <sys/mman.h> // #include <asm/ptrace.h> #include <sys/wait.h> #include <sys/ptrace.h> #include <sys/types.h> #include <unistd.h> #include "../../Base/MojingTypes.h" #include "instruction.h" #include "detour.h" #ifndef PAGE_SIZE #define PAGE_SIZE 4096 #endif #define PAGE_START(addr) (~(PAGE_SIZE - 1) & (addr)) #define SET_BIT0(addr) (addr | 1) #define CLEAR_BIT0(addr) (addr & 0xFFFFFFFE) #define TEST_BIT0(addr) (addr & 1) #define ACTION_ENABLE 0 #define ACTION_DISABLE 1 #ifdef LOG4CPLUS_IMPORT #include "../../3rdPart/log4cplus/LogInterface.h" #else #include "../../LogTraker/LogInterface.h" #endif #ifdef ENABLE_LOGGER extern MojingLogger g_APIlogger; #endif enum hook_status { REGISTERED, HOOKED, }; struct inlineHookItem { uint32_t target_addr; uint32_t new_addr; uint32_t **proto_addr; void *orig_instructions; int orig_boundaries[4]; int trampoline_boundaries[20]; int count; void *trampoline_instructions; int length; int status; int mode; }; struct inlineHookInfo { struct inlineHookItem item[1024]; int size; }; static struct inlineHookInfo info = {0}; static int getAllTids( pid_t pid, pid_t *tids ) { char dir_path[32]; DIR *dir; int i; struct dirent *entry; pid_t tid; if ( pid < 0 ) { snprintf( dir_path, sizeof( dir_path ), "/proc/self/task" ); } else { snprintf( dir_path, sizeof( dir_path ), "/proc/%d/task", pid ); } dir = opendir( dir_path ); if ( dir == NULL ) { return 0; } i = 0; while ( ( entry = readdir( dir ) ) != NULL ) { tid = atoi( entry->d_name ); if ( tid != 0 && tid != getpid() ) { tids[i++] = tid; } } closedir( dir ); return i; } static bool doProcessThreadPC( struct inlineHookItem *item, struct pt_regs *regs, int action ) { int offset; int i; switch ( action ) { case ACTION_ENABLE: offset = regs->ARM_pc - CLEAR_BIT0( item->target_addr ); for ( i = 0; i < item->count; ++i ) { if ( offset == item->orig_boundaries[i] ) { regs->ARM_pc = ( uint32_t )item->trampoline_instructions + item->trampoline_boundaries[i]; return true; } } break; case ACTION_DISABLE: offset = regs->ARM_pc - ( int )item->trampoline_instructions; for ( i = 0; i < item->count; ++i ) { if ( offset == item->trampoline_boundaries[i] ) { regs->ARM_pc = CLEAR_BIT0( item->target_addr ) + item->orig_boundaries[i]; return true; } } break; } return false; } static void processThreadPC( pid_t tid, struct inlineHookItem *item, int action ) { struct pt_regs regs; if ( ptrace( PTRACE_GETREGS, tid, NULL, &regs ) == 0 ) { if ( item == NULL ) { int pos; for ( pos = 0; pos < info.size; ++pos ) { if ( doProcessThreadPC( &info.item[pos], &regs, action ) == true ) { break; } } } else { doProcessThreadPC( item, &regs, action ); } ptrace( PTRACE_SETREGS, tid, NULL, &regs ); } } static pid_t freeze( struct inlineHookItem *item, int action ) { int count; pid_t tids[1024]; pid_t pid; pid = -1; count = getAllTids( getpid(), tids ); #ifdef _DEBUG MOJING_TRACE(g_APIlogger , "Count = " << count); #endif if ( count > 0 ) { #ifdef _DEBUG MOJING_TRACE(g_APIlogger, "fork begin ... "); #endif pid = fork(); #ifdef _DEBUG MOJING_TRACE(g_APIlogger, "fork end ... , pid = " << pid); #endif if ( pid == 0 ) { int i; for ( i = 0; i < count; ++i ) { #ifdef _DEBUG MOJING_TRACE(g_APIlogger, "loop :: " << i << " / " << count); #endif if ( ptrace( PTRACE_ATTACH, tids[i], NULL, NULL ) == 0 ) { #ifdef _DEBUG MOJING_TRACE(g_APIlogger, "waitpid :: " << tids[i]); #endif waitpid( tids[i], NULL, WUNTRACED ); #ifdef _DEBUG MOJING_TRACE(g_APIlogger, "waitpid :: Done" ); #endif processThreadPC( tids[i], item, action ); #ifdef _DEBUG MOJING_TRACE(g_APIlogger, "end of loop"); #endif } } #ifdef _DEBUG MOJING_TRACE(g_APIlogger, "raise SIGSTOP ... begin"); #endif raise( SIGSTOP ); #ifdef _DEBUG MOJING_TRACE(g_APIlogger, "raise SIGSTOP ... end"); #endif for ( i = 0; i < count; ++i ) { #ifdef _DEBUG MOJING_TRACE(g_APIlogger, "ptrace " << i << " / " << count); #endif ptrace( PTRACE_DETACH, tids[i], NULL, NULL ); } #ifdef _DEBUG MOJING_TRACE(g_APIlogger, "raise SIGKILL ... begin"); #endif raise( SIGKILL ); #ifdef _DEBUG MOJING_TRACE(g_APIlogger, "raise SIGKILL ... begin"); #endif } else if ( pid > 0 ) { #ifdef _DEBUG MOJING_TRACE(g_APIlogger, "waitpid , begin..."); #endif waitpid( pid, NULL, WUNTRACED ); #ifdef _DEBUG MOJING_TRACE(g_APIlogger, "waitpid , end"); #endif } else { #ifdef _DEBUG MOJING_WARN(g_APIlogger, "DO NOTHING"); #endif } } return pid; } static void unFreeze( pid_t pid ) { if ( pid < 0 ) { return; } kill( pid, SIGCONT ); wait( NULL ); } static bool isExecutableAddr( uint32_t addr ) { FILE *fp; char line[1024]; uint32_t start; uint32_t end; fp = fopen( "/proc/self/maps", "r" ); if ( fp == NULL ) { return false; } while ( fgets( line, sizeof( line ), fp ) ) { if ( strstr( line, "r-xp" ) ) { start = strtoul( strtok( line, "-" ), NULL, 16 ); end = strtoul( strtok( NULL, " " ), NULL, 16 ); if ( addr >= start && addr <= end ) { fclose( fp ); return true; } } } fclose( fp ); return false; } static struct inlineHookItem *findInlineHookItem( uint32_t target_addr ) { int i; for ( i = 0; i < info.size; ++i ) { if ( info.item[i].target_addr == target_addr ) { return &info.item[i]; } } return NULL; } static struct inlineHookItem *addInlineHookItem() { struct inlineHookItem *item; if ( info.size >= 1024 ) { return NULL; } item = &info.item[info.size]; ++info.size; return item; } static void deleteInlineHookItem( int pos ) { info.item[pos] = info.item[info.size - 1]; --info.size; } enum detour_status registerInlineHook( uint32_t target_addr, uint32_t new_addr, uint32_t **proto_addr ) { MOJING_FUNC_TRACE(g_APIlogger); struct inlineHookItem *item; if ( !isExecutableAddr( target_addr ) || !isExecutableAddr( new_addr ) ) { return DETOUR_ERROR_NOT_EXECUTABLE; } item = findInlineHookItem( target_addr ); if ( item != NULL ) { if ( item->status == REGISTERED ) { return DETOUR_ERROR_ALREADY_REGISTERED; } else if ( item->status == HOOKED ) { return DETOUR_ERROR_ALREADY_HOOKED; } else { return DETOUR_ERROR_UNKNOWN; } } MOJING_TRACE(g_APIlogger , "addInlineHookItem...."); item = addInlineHookItem(); MOJING_TRACE(g_APIlogger, "addInlineHookItem done , totle = " << info.size); item->target_addr = target_addr; item->new_addr = new_addr; item->proto_addr = proto_addr; item->length = TEST_BIT0( item->target_addr ) ? 12 : 8; item->orig_instructions = malloc( item->length ); memcpy( item->orig_instructions, ( void * )CLEAR_BIT0( item->target_addr ), item->length ); item->trampoline_instructions = mmap( NULL, PAGE_SIZE, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_ANONYMOUS | MAP_PRIVATE, 0, 0 ); relocateInstruction( item->target_addr, item->orig_instructions, item->length, item->trampoline_instructions, item->orig_boundaries, item->trampoline_boundaries, &item->count ); item->status = REGISTERED; return DETOUR_OK; } static void doInlineUnHook( struct inlineHookItem *item, int pos ) { mprotect( ( void * )PAGE_START( CLEAR_BIT0( item->target_addr ) ), PAGE_SIZE * 2, PROT_READ | PROT_WRITE | PROT_EXEC ); memcpy( ( void * )CLEAR_BIT0( item->target_addr ), item->orig_instructions, item->length ); mprotect( ( void * )PAGE_START( CLEAR_BIT0( item->target_addr ) ), PAGE_SIZE * 2, PROT_READ | PROT_EXEC ); munmap( item->trampoline_instructions, PAGE_SIZE ); free( item->orig_instructions ); deleteInlineHookItem( pos ); cacheflush( CLEAR_BIT0( item->target_addr ), CLEAR_BIT0( item->target_addr ) + item->length, 0 ); } enum detour_status inlineUnHook( uint32_t target_addr ) { int i; for ( i = 0; i < info.size; ++i ) { if ( info.item[i].target_addr == target_addr && info.item[i].status == HOOKED ) { pid_t pid; pid = freeze( &info.item[i], ACTION_DISABLE ); doInlineUnHook( &info.item[i], i ); unFreeze( pid ); return DETOUR_OK; } } return DETOUR_ERROR_NOT_HOOKED; } void inlineUnHookAll() { pid_t pid; int i; pid = freeze( NULL, ACTION_DISABLE ); for ( i = 0; i < info.size; ++i ) { if ( info.item[i].status == HOOKED ) { doInlineUnHook( &info.item[i], i ); --i; } } unFreeze( pid ); } static void doInlineHook( struct inlineHookItem *item ) { mprotect( ( void * )PAGE_START( CLEAR_BIT0( item->target_addr ) ), PAGE_SIZE * 2, PROT_READ | PROT_WRITE | PROT_EXEC ); if ( TEST_BIT0( item->target_addr ) ) { int i; i = 0; if ( CLEAR_BIT0( item->target_addr ) % 4 != 0 ) { ( ( uint16_t * )CLEAR_BIT0( item->target_addr ) )[i++] = 0xBF00; // NOP } ( ( uint16_t * )CLEAR_BIT0( item->target_addr ) )[i++] = 0xF8DF; ( ( uint16_t * )CLEAR_BIT0( item->target_addr ) )[i++] = 0xF000; // LDR.W PC, [PC] ( ( uint16_t * )CLEAR_BIT0( item->target_addr ) )[i++] = item->new_addr & 0xFFFF; ( ( uint16_t * )CLEAR_BIT0( item->target_addr ) )[i++] = item->new_addr >> 16; } else { ( ( uint32_t * )( item->target_addr ) )[0] = 0xe51ff004; // LDR PC, [PC, #-4] ( ( uint32_t * )( item->target_addr ) )[1] = item->new_addr; } mprotect( ( void * )PAGE_START( CLEAR_BIT0( item->target_addr ) ), PAGE_SIZE * 2, PROT_READ | PROT_EXEC ); if ( item->proto_addr != NULL ) { *( item->proto_addr ) = TEST_BIT0( item->target_addr ) ? ( uint32_t * )SET_BIT0( ( uint32_t )item->trampoline_instructions ) : ( uint32_t * )item->trampoline_instructions; //(addr & 1) //(addr | 1) // *(item->proto_addr) = ( item->target_addr & 1) ? // (uint32_t*)((uint32_t)item->trampoline_instructions | 1) : // (uint32_t*)item->trampoline_instructions; //(uint32_t *) SET_BIT0(*(uint32_t*)item->trampoline_instructions) : } item->status = HOOKED; cacheflush( CLEAR_BIT0( item->target_addr ), CLEAR_BIT0( item->target_addr ) + item->length, 0 ); } enum detour_status inlineHook( uint32_t target_addr ) { MOJING_FUNC_TRACE(g_APIlogger); int i; struct inlineHookItem *item; item = NULL; for ( i = 0; i < info.size; ++i ) { MOJING_TRACE(g_APIlogger , "Find in function " << i << " / " << info.size); if ( info.item[i].target_addr == target_addr ) { item = &info.item[i]; break; } } if ( item == NULL ) { return DETOUR_ERROR_NOT_REGISTERED; } MOJING_TRACE(g_APIlogger, "status = " << item->status); if ( item->status == REGISTERED ) { pid_t pid; //#ifdef _DEBUG // MOJING_TRACE(g_APIlogger, "freeze ..."); //#endif // pid = freeze(item, ACTION_ENABLE); //#ifdef _DEBUG // MOJING_TRACE(g_APIlogger, "doInlineHook ..."); //#endif doInlineHook( item ); //#ifdef _DEBUG // MOJING_TRACE(g_APIlogger, "unFreeze ..."); //#endif // unFreeze( pid ); return DETOUR_OK; } else if ( item->status == HOOKED ) { return DETOUR_ERROR_ALREADY_HOOKED; } else { return DETOUR_ERROR_UNKNOWN; } } void inlineHookAll() { pid_t pid; int i; #ifdef _DEBUG MOJING_TRACE(g_APIlogger, "freeze ..."); #endif pid = freeze( NULL, ACTION_ENABLE ); #ifdef _DEBUG MOJING_TRACE(g_APIlogger, "freeze ... end"); #endif // endif for ( i = 0; i < info.size; ++i ) { if ( info.item[i].status == REGISTERED ) { #ifdef _DEBUG MOJING_TRACE(g_APIlogger , "do hook " << i << " / " << info.size); #endif // endif doInlineHook( &info.item[i] ); } else { #ifdef _DEBUG MOJING_TRACE(g_APIlogger, "skip hook " << i << " / " << info.size); #endif // endif } usleep(10 * 1000); } #ifdef _DEBUG MOJING_TRACE(g_APIlogger, "unFreeze ..." ); #endif // endif unFreeze( pid ); #ifdef _DEBUG MOJING_TRACE(g_APIlogger, "unFreeze ... done"); #endif // endif }
[ "hgl868@126.com" ]
hgl868@126.com
32b7829d964f06ba80ddd4b583b560bf1a67d5d3
25e561036bc0e0c582fa4604c4ecf847144dc9c1
/Beam_Xray_N7599.cc
b2b8d5be82c514d49d9d2449dad518424aadd6de
[]
no_license
lynch829/Transport-Framework
f1e418ecb6f181783c60cd2a60a7f34cc146019f
8b7d9eb1c293251f576b64fba9746b8301ee1cb8
refs/heads/master
2021-01-21T14:13:25.058883
2016-06-29T23:48:52
2016-06-29T23:48:52
95,253,118
1
0
null
2017-06-23T20:12:47
2017-06-23T20:12:47
null
UTF-8
C++
false
false
5,670
cc
//Beam_Xray_N7599.cc - Defines an approximate spectra for a Hamamatsu N7599 xray source. // //Programming notes: // -Do not make items here "const", because they will not show up when loading. // -Avoid using macro variables here because they will be obliterated during loading. // -Wrap dynamically-loaded code with extern "C", otherwise C++ compilation will mangle function names, etc. // // From man page for dlsym/dlopen: For running some 'initialization' code prior to finishing loading: // "Instead, libraries should export routines using the __attribute__((constructor)) and __attribute__((destructor)) function attributes. See the gcc info pages for // information on these. Constructor routines are executed before dlopen() returns, and destructor routines are executed before dlclose() returns." // ---for instance, we can use this to seed a random number generator with a random seed. However, in order to pass in a specific seed (and pass that seed to the library) // we need to define an explicitly callable initialization function. In general, these libraries should have both so that we can quickly adjust behaviour if desired. // #include <iostream> #include <string> #include <vector> #include <cmath> #include "./Misc.h" #include "./MyMath.h" #include "./Constants.h" #include "./Structs.h" #ifdef __cplusplus extern "C" { #endif std::string MODULE_NAME(__FILE__); std::string FILE_TYPE("BEAM"); std::string BEAM_TYPE("XRAY"); bool VERBOSE = false; //vec3<double> position(0.0, 0.0, -14.0); //The geometric location of the beam 'spout.' #ifdef __GNUG__ __attribute__((constructor)) static void init_on_dynamic_load(void){ //Do something automatic here. if(VERBOSE) FUNCINFO("Loaded lib_beam_xray_N7599.so"); return; } __attribute__((destructor)) static void cleanup_on_dynamic_unload(void){ //Cleanup memory (if needed) automatically here. if(VERBOSE) FUNCINFO("Closed lib_beam_xray_N7599.so"); return; } #else #warning Being compiled with non-gcc compiler. Unable to use gcc-specific function declarations like 'attribute.' Proceed at your own risk! #endif void toggle_verbosity(bool in){ VERBOSE = in; return; } /* void set_position(const vec3<double> &in){ position = in; return; } vec3<double> get_position(void){ return position; } //Given three clamped [0,1], random, uniformly-distributed numbers, we return a (three-vector) unit vector pointing in the direction // which a new beam particle will have. // //For instance, for an isotropic point source, we just return a random orientation. For a sharply directed beam, we can probably // just return a constant, directed orientation. In between, we will likely have some angular distribution. // //NOTE: It would be better to start with a unit vector and rotate it twice --> no sqrt, only need two randoms. // vec3<double> get_orientation(const double &ina, const double &inb, const double &inc){ const double dtheta = 7.5/28.0; //Approximate apparent width of the detector from the point of the source. const double theta = (ina-0.5)*dtheta; const double dphi = 0.5/28.0; //Approximate apparent thickness of the CT setup at the far edge. const double phi = (inb-0.5)*dphi; return vec3<double>(sin(theta)*cos(phi), sin(phi), cos(theta)*cos(phi)); // return vec3<double>(0.0,0.0,1.0); } */ //This function returns a normalized (to f(8.4000000) = 99.9763803675478...) Hamamatsu N7599 emission spectrum. // It is used in a rejection-method scheme for a stochastic numerical inversion of the probability density function. // Do NOT use anywhere where absolute output is required - this is total-output agnostic! inline double normalized_spectral_intensity(const double &E){ if(E < 2.0000E-3) return 0.0; if(E > 15.714E-3) return 0.0; return 1.7*(1.0-0.9*pow(2.718281828459045,-0.6155722066724582*pow(1000.0*E-2.0,0.35)))*pow(1.0-0.8*pow(2.718281828459045,-0.75*(1000.0*E-1.7)),3.0)*(55.0-3500.0*E)+69.0*pow(2.718281828459045,-28.0*pow(1000.0*E-8.4,2.0))+20.0*pow(2.718281828459045,-28.0*pow(1000.0*E-9.67,2.0)); } //This function returns a random energy for a given clamped random which conforms to the Hamamatsu N7599 emission spectrum. // //It is suitable for determining the energy of photons which have been freshly created at an // undescribed source. // //Units of energy: [E] = MeV. double energy_distribution(const struct Functions &Loaded_Functions){ const double energy_min = 2.0000E-3; const double energy_max = 15.714E-3; double energy; const double ymin = 0.0; const double ymax = 100.0; //Doesn't have to be exactly max, but it DOES have to be slightly higher than max. double y; do{ energy = Loaded_Functions.PRNG_source()*(energy_max - energy_min) + energy_min; //Within [energy_min,energy_max]. y = Loaded_Functions.PRNG_source()*(ymax-ymin) + ymin; //Within [0,ymin]. }while( y > normalized_spectral_intensity( energy )); //Adjusting for a useable image quality.. //return 7.5*energy; return 2.5*energy; //Looks OK. A little higher would probably be sweet-spot, but it is a little too finicky.. return 10.0 * energy; //This essentially makes the water transparent! No noticeable perturbation during testing.. return 25.0 * energy; //Appears to INCREASE signal for water object ?? return 100.0 * energy; //FIXME ! Note: we bump this up to MeV range because it is damned impossible to see anything interesting otherwise... //ACTUAL: return energy; } #ifdef __cplusplus } #endif
[ "hdclark@ualberta.ca" ]
hdclark@ualberta.ca
e9bf62c3f752c36318429a7ea3dd2fb604c13cce
e07e3f41c9774c9684c4700a9772712bf6ac3533
/app/Temp/StagingArea/Data/il2cppOutput/AssemblyU2DCSharp_PlanarWindows_WallOrWindow346663157.h
53c404b8d8785533c00799a236c137e22d85e19b
[]
no_license
gdesmarais-gsn/inprocess-mobile-skill-client
0171a0d4aaed13dbbc9cca248aec646ec5020025
2499d8ab5149a306001995064852353c33208fc3
refs/heads/master
2020-12-03T09:22:52.530033
2017-06-27T22:08:38
2017-06-27T22:08:38
95,603,544
0
0
null
null
null
null
UTF-8
C++
false
false
1,433
h
#pragma once #include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <stdint.h> #include "mscorlib_System_Object2689449295.h" #include "UnityEngine_UnityEngine_Bounds3033363703.h" #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // PlanarWindows/WallOrWindow struct WallOrWindow_t346663157 : public Il2CppObject { public: // UnityEngine.Bounds PlanarWindows/WallOrWindow::bounds Bounds_t3033363703 ___bounds_0; // System.Boolean PlanarWindows/WallOrWindow::isWindow bool ___isWindow_1; public: inline static int32_t get_offset_of_bounds_0() { return static_cast<int32_t>(offsetof(WallOrWindow_t346663157, ___bounds_0)); } inline Bounds_t3033363703 get_bounds_0() const { return ___bounds_0; } inline Bounds_t3033363703 * get_address_of_bounds_0() { return &___bounds_0; } inline void set_bounds_0(Bounds_t3033363703 value) { ___bounds_0 = value; } inline static int32_t get_offset_of_isWindow_1() { return static_cast<int32_t>(offsetof(WallOrWindow_t346663157, ___isWindow_1)); } inline bool get_isWindow_1() const { return ___isWindow_1; } inline bool* get_address_of_isWindow_1() { return &___isWindow_1; } inline void set_isWindow_1(bool value) { ___isWindow_1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif
[ "gdesmarais@gsngames.com" ]
gdesmarais@gsngames.com
a1b88f2f5ee264c6e6c0c7d2ed090ea186ac201f
3706c9baa2beb9d5b19150d1506dedaf0a036f22
/src/FileWvIn.h
3f1f0dde291012b38e96468cd494de41cd470d02
[ "MIT" ]
permissive
Miserlou/RJModules
0e7c0bff3723d64decb13787b6e5031fd7e6740d
809ad4f0b11cf227f6fcd6b4fed66110d4348b61
refs/heads/master
2023-05-12T00:25:07.001406
2023-05-04T00:21:51
2023-05-04T00:21:51
112,019,216
105
23
MIT
2023-05-04T00:08:54
2017-11-25T16:45:46
C++
UTF-8
C++
false
false
7,632
h
#ifndef STK_FILEWVIN_H #define STK_FILEWVIN_H #include "WvIn.h" #include "FileRead.h" namespace stk { /***************************************************/ /*! \class FileWvIn \brief STK audio file input class. This class inherits from WvIn. It provides a "tick-level" interface to the FileRead class. It also provides variable-rate playback functionality. Audio file support is provided by the FileRead class. Linear interpolation is used for fractional read rates. FileWvIn supports multi-channel data. It is important to distinguish the tick() method that computes a single frame (and returns only the specified sample of a multi-channel frame) from the overloaded one that takes an StkFrames object for multi-channel and/or multi-frame data. FileWvIn will either load the entire content of an audio file into local memory or incrementally read file data from disk in chunks. This behavior is controlled by the optional constructor arguments \e chunkThreshold and \e chunkSize. File sizes greater than \e chunkThreshold (in sample frames) will be read incrementally in chunks of \e chunkSize each (also in sample frames). For file data read completely into local memory, the \e doNormalize flag can be used to normalize all values with respect to the maximum absolute value of the data. If the file data format is fixed point, the flag \e doInt2FloatScaling can be used to control whether the values are scaled with respect to the corresponding fixed-point maximum. For example, if reading 16-bit signed integers, the input values will be scaled by 1 / 32768.0. This scaling will not happen for floating-point file data formats. When the file end is reached, subsequent calls to the tick() functions return zeros and isFinished() returns \e true. See the FileRead class for a description of the supported audio file formats. by Perry R. Cook and Gary P. Scavone, 1995--2019. */ /***************************************************/ class FileWvIn : public WvIn { public: //! Default constructor. FileWvIn( unsigned long chunkThreshold = 1000000, unsigned long chunkSize = 1024 ); //! Overloaded constructor for file input. /*! An StkError will be thrown if the file is not found, its format is unknown, or a read error occurs. */ FileWvIn( std::string fileName, bool raw = false, bool doNormalize = true, unsigned long chunkThreshold = 1000000, unsigned long chunkSize = 1024, bool doInt2FloatScaling = true ); //! Class destructor. ~FileWvIn( void ); //! Open the specified file and load its data. /*! Data from a previously opened file will be overwritten by this function. An StkError will be thrown if the file is not found, its format is unknown, or a read error occurs. If the file length is less than the chunkThreshold limit and \e doNormalize is true, the file data will be normalized with respect to the maximum absolute value of the data. If the \e doInt2FloatScaling flag is true and the input data is fixed-point, a scaling will be applied with respect to the fixed-point limits. */ virtual void openFile( std::string fileName, bool raw = false, bool doNormalize = true, bool doInt2FloatScaling = true ); //! Close a file if one is open. virtual void closeFile( void ); //! Clear outputs and reset time (file) pointer to zero. virtual void reset( void ); //! Normalize data to a maximum of +-1.0. /*! This function has no effect when data is incrementally loaded from disk. */ virtual void normalize( void ); //! Normalize data to a maximum of \e +-peak. /*! This function has no effect when data is incrementally loaded from disk. */ virtual void normalize( StkFloat peak ); //! Return the file size in sample frames. virtual unsigned long getSize( void ) const { return fileSize_; }; //! Return the input file sample rate in Hz (not the data read rate). /*! WAV, SND, and AIF formatted files specify a sample rate in their headers. STK RAW files have a sample rate of 22050 Hz by definition. MAT-files are assumed to have a rate of 44100 Hz. */ virtual StkFloat getFileRate( void ) const { return data_.dataRate(); }; //! Query whether a file is open. bool isOpen( void ) { return file_.isOpen(); }; //! Query whether reading is complete. bool isFinished( void ) const { return finished_; }; //! Set the data read rate in samples. The rate can be negative. /*! If the rate value is negative, the data is read in reverse order. */ virtual void setRate( StkFloat rate ); //! Increment the read pointer by \e time samples. /*! Note that this function will not modify the interpolation flag status. */ virtual void addTime( StkFloat time ); //! Turn linear interpolation on/off. /*! Interpolation is automatically off when the read rate is an integer value. If interpolation is turned off for a fractional rate, the time index is truncated to an integer value. */ void setInterpolate( bool doInterpolate ) { interpolate_ = doInterpolate; }; //! Return the specified channel value of the last computed frame. /*! If no file is loaded, the returned value is 0.0. The \c channel argument must be less than the number of output channels, which can be determined with the channelsOut() function (the first channel is specified by 0). However, range checking is only performed if _STK_DEBUG_ is defined during compilation, in which case an out-of-range value will trigger an StkError exception. \sa lastFrame() */ StkFloat lastOut( unsigned int channel = 0 ); //! Compute a sample frame and return the specified \c channel value. /*! For multi-channel files, use the lastFrame() function to get all values from the computed frame. If no file data is loaded, the returned value is 0.0. The \c channel argument must be less than the number of channels in the file data (the first channel is specified by 0). However, range checking is only performed if _STK_DEBUG_ is defined during compilation, in which case an out-of-range value will trigger an StkError exception. */ virtual StkFloat tick( unsigned int channel = 0 ); //! Fill the StkFrames object with computed sample frames, starting at the specified channel and return the same reference. /*! The \c channel argument plus the number of input channels must be less than the number of channels in the StkFrames argument (the first channel is specified by 0). However, range checking is only performed if _STK_DEBUG_ is defined during compilation, in which case an out-of-range value will trigger an StkError exception. */ virtual StkFrames& tick( StkFrames& frames, unsigned int channel = 0 ); protected: void sampleRateChanged( StkFloat newRate, StkFloat oldRate ); FileRead file_; bool finished_; bool interpolate_; bool int2floatscaling_; bool chunking_; StkFloat time_; StkFloat rate_; unsigned long fileSize_; unsigned long chunkThreshold_; unsigned long chunkSize_; long chunkPointer_; }; inline StkFloat FileWvIn :: lastOut( unsigned int channel ) { #if defined(_STK_DEBUG_) if ( channel >= data_.channels() ) { oStream_ << "FileWvIn::lastOut(): channel argument and soundfile data are incompatible!"; handleError( StkError::FUNCTION_ARGUMENT ); } #endif if ( finished_ ) return 0.0; return lastFrame_[channel]; } } // stk namespace #endif
[ "rich@anomos.info" ]
rich@anomos.info
b81c0b650f08b35918f4fe32918edb3ffa440ce5
3a11ab191326e9876175ec1353d217ca354f36e5
/exp2.2/exp2.2/exp2.2.h
51b925e6e1c3271ba8c74f20ec4d7e354e442757
[]
no_license
ningkekeke/EXP2_2020-03-10
ffeec88ae0b6f25a40d62bd151938c0571b9c31f
6884c2538ec475ed6d9bc73d4832bbc93f6314be
refs/heads/master
2021-04-04T14:59:22.533726
2020-03-19T15:51:39
2020-03-19T15:51:39
248,466,324
0
0
null
null
null
null
GB18030
C++
false
false
509
h
// exp2.2.h : exp2.2 应用程序的主头文件 // #pragma once #ifndef __AFXWIN_H__ #error "在包含此文件之前包含“stdafx.h”以生成 PCH 文件" #endif #include "resource.h" // 主符号 // Cexp22App: // 有关此类的实现,请参阅 exp2.2.cpp // class Cexp22App : public CWinAppEx { public: Cexp22App(); // 重写 public: virtual BOOL InitInstance(); virtual int ExitInstance(); // 实现 afx_msg void OnAppAbout(); DECLARE_MESSAGE_MAP() }; extern Cexp22App theApp;
[ "2290418168@qq.com" ]
2290418168@qq.com
85ad188f34b4d3a997873820d392729a70f88728
66f8d79506550b3ab5157386e048a3f65decf85e
/tls/tls13.cc
e4240fae61aa8ea47b8e44d2b8cecefcdc5ada44
[]
no_license
zetapark/ez
057ec2752a369dff07a0192f812e1123a8c8f4dc
3965d69b5626c15f828725af90b0e11449671d6a
refs/heads/master
2022-06-20T07:25:45.418567
2020-05-04T23:41:26
2020-05-04T23:41:26
261,129,607
0
0
null
null
null
null
UTF-8
C++
false
false
22,237
cc
#include<utility> #include<nettle/curve25519.h> #include<fstream> #include"util/log.h" #include"cert_util.h" #include"ecdsa.h" #include"tls13.h" #include"pss.h" using namespace std; template class TLS13<true>; template class TLS13<false>; extern PSK PSKnCLIENT; static string init_certificate() { ifstream f("../fullchain.pem");//openssl req -x509 -days 1000 -new -key key.pem -out cert.pem vector<unsigned char> r; for(string s; (s = get_certificate_core(f)) != "";) { auto v = base64_decode(s); r.push_back(0); r.push_back(0); r.push_back(0);//fill with length mpz2bnd(v.size(), r.end() - 3, r.end()); r.insert(r.end(), v.begin(), v.end()); r.push_back(0); r.push_back(0);//extension!!! } const int REQUESTED_CONTEXT = 0; vector<uint8_t> front{CERTIFICATE, 0,0,0, REQUESTED_CONTEXT, 0,0,0}; mpz2bnd(r.size(), front.end() - 3, front.end()); mpz2bnd(r.size() + 4, front.begin() + 1, front.begin() + 4); r.insert(r.begin(), front.begin(), front.end()); return {r.begin(), r.end()}; } static string certificate13 = init_certificate(); #pragma pack(1) template<bool SV> TLS13<SV>::TLS13() { mpz2bnd(this->prv_key_, prv_, prv_ + 32); } template<bool SV> string TLS13<SV>::client_ext() { struct Ext { uint8_t extension_length[2] = {0, 0}; uint8_t supported_group[2] = {0, 10};//type uint8_t supported_group_length[2] = {0, 6};//length uint8_t support_group_list_length[2] = {0, 4}; uint8_t secp256r1[2] = {0, 23}; uint8_t x255[2] = {0, 29}; uint8_t ec_point_format[2] = {0, 11};//type uint8_t ec_point_format_length[2] = {0, 2};//length uint8_t ec_length = 1; uint8_t non_compressed = 0; uint8_t key_share[2] = {0, 51};//type uint8_t key_share_length[2] = {0, 107};//length uint8_t client_key_share_len[2] = {0, 105}; uint8_t x25519[2] = {0, 29}; uint8_t key_length2[2] = {0, 32}; uint8_t x2[32]; uint8_t secp256r1_key[2] = {0, 23}; uint8_t key_length[2] = {0, 65}; uint8_t type = 4; uint8_t x[32], y[32]; uint8_t supported_version[2] = {0, 0x2b}; uint8_t supported_version_length[2] = {0, 5}; uint8_t supported_version_list_length = 4; uint8_t supported_versions[4] = {3, 4, 3, 3};//TLS 1.3, TLS 1.2 uint8_t psk_mode[2] = {0, 0x2d}; uint8_t psk_mode_length[2] = {0, 2}; uint8_t psk_mode_llength = 1; uint8_t psk_with_ecdhe = 1; uint8_t signature_algorithm[2] = {0, 13}; uint8_t signature_algorithm_length[2] = {0, 8}; uint8_t signature_alg_len[2] = {0, 6}; uint8_t signature[6] = {8, 4, 4, 1, 4, 3};//pss rase, sha256 rsa, ecdsa sha 256 } ext; mpz2bnd(this->P_.x, ext.x, ext.x + 32); mpz2bnd(this->P_.y, ext.y, ext.y + 32); mpz2bnd(sizeof(Ext) - 2, ext.extension_length, ext.extension_length + 2); curve25519_mul_g(ext.x2, prv_); return struct2str(ext); } //template<bool SV> string //TLS13<SV>::psk_ext(vector<uint8_t> resumption_psk, vector<uint8_t> psk_id) //{//generate sesison ticket to resume handshake // int id_sz = psk_id.size(); // int psk_sz = resumption_psk.size(); // struct { // uint8_t psk[2] = {0, 41}; // uint8_t len[2]; // uint8_t all_id_len[2]; // uint8_t id_len[2]; // uint8_t id[id_sz]; // uint8_t obfuscated_age[4]; // uint8_t binder_len[2] = {0, 33}; // uint8_t binder_sz = 32; // uint8_t binder[32]; // } h; // mpz2bnd(id_sz, h.id_len, h.id_len + id_sz); // mpz2bnd(id_sz + 2, h.all_id_len, h.all_id_len + id_sz); // mpz2bnd(sizeof(h) - 4, h.len, h.len + 2); // std::copy(psk_id.cbegin(), psk_id.cend(), h.id); // return struct2str(h); //} // template<bool SV> bool TLS13<SV>::supported_group(unsigned char *p, int len) {//return true when support secp256r1, len = ext leng, p point at the start of actual ext for(int i=2; i<len; i+=2) if(*(p+i) == 0 && *(p+i+1) == 23) return true; return false; } template<bool SV> bool TLS13<SV>::point_format(unsigned char *p, int len) { for(int i=1; i<len; i++) if(*(p+i) == 0) return true; return false; } template<bool SV> bool TLS13<SV>::sub_key_share(unsigned char *p) { if(*p == 0 && *(p+1) == 23 && *(p+4) == 4) { EC_Point Q{bnd2mpz(p + 5, p + 37), bnd2mpz(p + 37, p + 69), this->secp256r1_}; premaster_secret_ = (Q * this->prv_key_).x; return true; } else if(*p == 0 && *(p+1) == 29) { uint8_t q[32]; curve25519_mul(q, prv_, p + 4); premaster_secret_ = bnd2mpz(q, q+32); this->P_.x = -1; return true; } else return false; } template<bool SV> bool TLS13<SV>::key_share(unsigned char *p, int len) { len = *p++ * 0x100 + *p++; for(unsigned char *q = p; p < q + len; p += p[2] * 0x100 + p[3] + 4) if(sub_key_share(p)) return true; return false; } template<bool SV> bool TLS13<SV>::supported_version(unsigned char *p, int len) { for(int i=1; i<len; i+=2) if(*(p+i) == 3 && *(p+i+1) == 4) return true; return false; } template<bool SV> int TLS13<SV>::psk(unsigned char *p, int len) {//should add binder check // struct { // uint8_t identities_sz[2] = {0, 21}; // uint8_t ticket_sz[2] = {0, 15}; // uint8_t ticket[15]; // uint8_t obfuscated_ticket_age[4]; // uint8_t binder_sz[2]; // uint8_t bind_sz[2]; // uint8_t binder[32]; // } h; int id_sz = *p++ * 0x100 + *p++; int selected = 0; for(unsigned char *q = p; p < q + id_sz; selected++) { int id_len = *p++ * 0x100 + *p++; vector<uint8_t> v{p, p + id_len}; p += id_len + 4;//obfuscated ticket age 4 byte if(auto a = PSKnCLIENT[v]) { psk_ = a->psk; sclient_.sp_client = a->sp_client; return selected;//need to check binder } } return -1; } template<bool SV> bool TLS13<SV>::client_ext(unsigned char *p) //buggy {//check extension and return if it is capable of negotiating with us int total_len = *p++ * 0x100 + *p++; bool check_ext[5] = {false,}; for(unsigned char *q = p; p < q + total_len;) { int type = *p++ * 0x100 + *p++; int len = *p++ * 0x100 + *p++; switch(type) { case 10: check_ext[0] = supported_group(p, len); break; case 11: check_ext[1] = point_format(p, len); break; case 43: check_ext[2] = supported_version(p, len); break; case 45: check_ext[3] = true; break; case 51: check_ext[4] = key_share(p, len); break; case 41: selected_psk_ = psk(p, len); break; } p += len; } check_ext[1] = true; for(int i=0; i<5; i++) if(check_ext[i] == false) return false; return true; } template<bool SV> string TLS13<SV>::server_ext() { struct Ext { uint8_t extension_length[2] = {0, 6}; uint8_t supported_version[2] = {0, 43}; uint8_t supported_version_length[2] = {0, 2}; uint8_t support[2] = {3, 4}; } ext; struct { uint8_t key_share[2] = {0, 51}; uint8_t key_share_length[2] = {0, 69}; uint8_t type[2] = {0, 23}; uint8_t key_length[2] = {0, 65}; uint8_t point_type = 4; uint8_t x[32], y[32]; } secp; struct { uint8_t key_share[2] = {0, 51}; uint8_t key_share_length[2] = {0, 36}; uint8_t type[2] = {0, 29}; uint8_t key_length[2] = {0, 32}; uint8_t x[32]; } x25519; struct { uint8_t selected_identity[2] = {0, 41}; uint8_t length[2] = {0, 2}; uint8_t id[2] = {0, 0}; } psk; string r; if(this->P_.x == -1) { curve25519_mul_g(x25519.x, prv_); ext.extension_length[1] += sizeof(x25519); r = struct2str(x25519); } else { ext.extension_length[1] += sizeof(secp); mpz2bnd(this->P_.x, secp.x, secp.x + 32); mpz2bnd(this->P_.y, secp.y, secp.y + 32); r = struct2str(secp); } if(selected_psk_ >= 0) { ext.extension_length[1] += sizeof(psk); psk.id[1] = selected_psk_; r += struct2str(psk); } return struct2str(ext) + r; } template<bool SV> string TLS13<SV>::encrypted_extension() { struct H { uint8_t enc_ext_type = 8; uint8_t total_len[3] = {0, 0, 10}; uint8_t ext_len[2] = {0, 8}; uint8_t supported_group[2] = {0, 10}; uint8_t len[2] = {0, 4}; uint8_t group[4] = {0, 0x1d, 0, 0x17}; } h; string r = struct2str(h); this->accumulated_handshakes_ += r; return r; } template<bool SV> void TLS13<SV>::protect_handshake() {//call after server hello hkdf_.zero_salt(); uint8_t pre[32], zeros[32] = {0,}; psk_.resize(HASH::output_size);//for empty resumption secret auto early_secret = hkdf_.extract(&psk_[0], HASH::output_size); LOGD << hexprint("early", early_secret) << endl; hkdf_.salt(&early_secret[0], early_secret.size()); auto a = hkdf_.derive_secret("derived", ""); hkdf_.salt(&a[0], a.size()); mpz2bnd(premaster_secret_, pre, pre + 32); auto handshake_secret = hkdf_.extract(pre, 32); LOGD << hexprint("handshake secret", handshake_secret) << endl; finished_key_ = set_aes(handshake_secret, "c hs traffic", "s hs traffic"); hkdf_.salt(&handshake_secret[0], handshake_secret.size()); a = hkdf_.derive_secret("derived", ""); hkdf_.salt(&a[0], a.size()); this->master_secret_ = hkdf_.extract(zeros, HASH::output_size); } template<bool SV> string TLS13<SV>::finished(string &&s) {//handle message without tls header struct H { uint8_t finished = 0x14; uint8_t length[3] = { 0, 0, 32}; } h; hkdf_.salt(finished_key_[s == "" ? SV : !SV].data(), HASH::output_size);//define use HASH sha;//this is cipher suite hash algorithm auto a = sha.hash(this->accumulated_handshakes_.begin(), this->accumulated_handshakes_.end()); a = hkdf_.hash(a.begin(), a.end()); string fin = struct2str(h) + string{a.begin(), a.end()}; this->accumulated_handshakes_ += fin; // if(SV == (s == "")) protect_data();//SV send, clietn receive if(s == "") return fin; else return s == fin ? "" : this->alert(2, 51); } template<bool SV> tuple<string, shared_ptr<MClient>> TLS13<SV>::new_session(string ip, int port, bool is13) { sclient_.sp_client = make_shared<MClient>(ip, port); sclient_.issue_time = chrono::system_clock::now(); if(!is13) sclient_.psk = this->master_secret_; vector<uint8_t> v{this->session_id_.begin(), this->session_id_.end()}; if(is13) v = ticket_id_; PSKnCLIENT.insert(v, sclient_); return {base64_encode(v), sclient_.sp_client}; } template<bool SV> string TLS13<SV>::new_session_ticket() {//return msg, base64 encrypted id, client shared pointer const int sz = 8; struct { uint8_t new_session_ticket = 4; uint8_t size[3] = {0, 0, 29}; uint8_t ticket_lifetime_in_sec[4] = {0, 0, 14, 16}; uint8_t ticket_age_add[4]; uint8_t ticket_nonce_size = sz; uint8_t ticket_nonce[sz]; uint8_t ticket_size[2] = {0, sz}; uint8_t ticket_id[sz]; uint8_t extension[2] = {0, 0}; } h; mpz2bnd(random_prime(4), h.ticket_age_add, h.ticket_age_add + 4); mpz2bnd(random_prime(sz), h.ticket_nonce, h.ticket_nonce + sz); std::copy(h.ticket_nonce, h.ticket_nonce + sz, h.ticket_id); hkdf_.salt(&resumption_master_secret_[0], resumption_master_secret_.size()); sclient_.psk = hkdf_.expand_label("resumption", {h.ticket_nonce, h.ticket_nonce + sz}, HASH::output_size); LOGD << hexprint("master", this->master_secret_) << endl; LOGD << hexprint("res master", resumption_master_secret_) << endl; LOGD << hexprint("resumption psk", sclient_.psk) << endl; ticket_id_ = vector<uint8_t>{h.ticket_id, h.ticket_id + sz}; return struct2str(h); } template<bool SV> pair<vector<uint8_t>, vector<uint8_t>> TLS13<SV>::new_session_ticket(string s) {//client will use this function to process session ticket unsigned char *p = reinterpret_cast<uint8_t*>(s.data()); int nonce_sz = p[12]; hkdf_.salt(&resumption_master_secret_[0], resumption_master_secret_.size()); LOGD << hexprint("resumption_master_secret", resumption_master_secret_) << endl; auto psk = hkdf_.expand_label("resumption", {p+13, p+13+nonce_sz}, HASH::output_size); p += 13 + nonce_sz; int ticket_sz = *p++ * 0x100 + *p++; vector<uint8_t> id{p, p+ticket_sz}; return {psk, id}; } template<bool SV> array<vector<uint8_t>, 2> TLS13<SV>::set_aes(vector<uint8_t> salt, string cl, string sv) { this->enc_seq_num_ = 0; this->dec_seq_num_ = 0; hkdf_.salt(&salt[0], salt.size()); array<vector<unsigned char>, 2> secret, finished_key; LOGD << hexprint("accum", this->accumulated_handshakes_) << endl; secret[0] = hkdf_.derive_secret(cl, this->accumulated_handshakes_); secret[1] = hkdf_.derive_secret(sv, this->accumulated_handshakes_); for(int i=0; i<2; i++) { hkdf_.salt(&secret[i][0], secret[i].size()); auto key = hkdf_.expand_label("key", "", 16); auto iv = hkdf_.expand_label("iv", "", 12); this->aes_[i].key(&key[0]); this->aes_[i].iv(&iv[0], 0, iv.size()); finished_key[i] = hkdf_.expand_label("finished", "", HASH::output_size); LOGD << hexprint("s hs traffic", secret[i]) << endl; LOGD << hexprint("key", key) << endl; LOGD << hexprint("iv", iv) << endl; } return finished_key; } template<bool SV> bool TLS13<SV>::server_ext(unsigned char *p) {//debug int total_len = *p++ * 0x100 + *p++; for(uint8_t *q = p; p < q + total_len;) { int type = *p++ * 0x100 + *p++; int length = *p++ * 0x100 + *p++; if(type == 51 && sub_key_share(p)) return true; p += length; } return false; } template<bool SV> string TLS13<SV>::client_hello(string &&s) { if constexpr(SV) {//is not returning correct ext_start unsigned char *p = (unsigned char*)&s[43];//session id length memcpy(echo_id_, p+1, *p);//copy session id p += *p + 1; int cipher_suite_len = *p++ * 0x100 + *p++; p += cipher_suite_len; p += *p + 1;//compression length int ext_start = p - (unsigned char*)&s[0]; string r = TLS<SV>::client_hello(forward<string>(s)); return s.size() > ext_start && client_ext(p) ? "" : r; } else { string hello = TLS<SV>::client_hello(); this->accumulated_handshakes_ = ""; string ext = client_ext(); int hello_size = static_cast<uint8_t>(hello[3]) * 0x100 + static_cast<uint8_t>(hello[4]) + ext.size(); mpz2bnd(hello_size, &hello[3], &hello[5]);//tls length mpz2bnd(hello_size - 4, &hello[6], &hello[9]);//handshake length return this->accumulate(hello + ext); } } template<bool SV> string TLS13<SV>::server_hello(string &&s) { if constexpr(SV) { string tmp = this->accumulated_handshakes_; string hello = TLS<SV>::server_hello(); if(!premaster_secret_) { if(auto a = PSKnCLIENT[{echo_id_, echo_id_+32}]) { sclient_.sp_client = a->sp_client; this->master_secret_ = a->psk; memcpy(&hello[44], echo_id_, 32);//echo session id } return hello; } memcpy(&hello[44], echo_id_, 32);//echo session id hello[76] = 19; hello[77] = 1;//TLS AES128 GCM SHA256 this->accumulated_handshakes_ = tmp; string ext = server_ext(); int hello_size = static_cast<uint8_t>(hello[3]) * 0x100 + static_cast<uint8_t>(hello[4]) + ext.size(); mpz2bnd(hello_size, &hello[3], &hello[5]);//tls length mpz2bnd(hello_size - 4, &hello[6], &hello[9]);//handshake length return this->accumulate(hello + ext); } else { string s2 = s; string r = TLS<SV>::server_hello(move(s2)); return s.size() > 80 && server_ext((uint8_t*)&s[79]) ? "" : r; } } template<bool SV> string TLS13<SV>::server_certificate13() { this->accumulated_handshakes_ += certificate13; return certificate13; } template<bool SV> string TLS13<SV>::certificate_verify() { SHA2 sha; auto a = sha.hash(this->accumulated_handshakes_.begin(), this->accumulated_handshakes_.end()); string t; for(int i=0; i<64; i++) t += ' '; t += "TLS 1.3, server CertificateVerify"; t += (uint8_t)0x0; t.insert(t.end(), a.begin(), a.end()); struct { uint8_t type = 0x0f; uint8_t length[3] = {0, 1, 4}; uint8_t signature[2] = {8, 4};//4 3 : ecdsa sha256, 8 4 : RSA SHA256 PSS uint8_t len[2] = {1, 0}; uint8_t sign[256]; } h; auto v = pss_encode({t.begin(), t.end()}, mpz_sizeinbase(this->rsa_.K.get_mpz_t(), 2) - 1); mpz2bnd(this->rsa_.sign(bnd2mpz(v.begin(), v.end())), h.sign, h.sign + 256); t = struct2str(h); this->accumulated_handshakes_ += t; return t; } template<bool SV> bool TLS13<SV>::is_tls13() { return premaster_secret_ != 0; } template<bool SV> optional<shared_ptr<MClient>> TLS13<SV>::handshake(function<optional<string>()> read_f, function<void(string)> write_f) {//handshake according to compromised version string s; optional<string> a; switch(1) { case 1://to use break if constexpr(SV) { if(s = this->alert(2, 0); !(a = read_f()) || (s = client_hello(move(*a))) != "") break; if(s = server_hello(); premaster_secret_) {//premaster secret is set in extension if 1.3 protect_handshake(); s += this->change_cipher_spec(); string t = encrypted_extension(); if(selected_psk_ < 0) {//not resumption t += server_certificate13(); t += certificate_verify(); } t += finished(); // string tmp = this->accumulated_handshakes_;//save after server finished s += encode(move(t), HANDSHAKE);//first condition true:read error->alert(2, 0) write_f(s); //second condition true->error message of function v if(s = this->alert(2, 49); !(a = read_f()) || (s = this->change_cipher_spec(move(*a))) != "") break; if(s = this->alert(2, 49); !(a = read_f())) break; if(s = this->alert(2, 50); !(a = decode(move(*a)))) break; set_aes(this->master_secret_, "c ap traffic", "s ap traffic"); if((s = finished(move(*a))) != "") break; hkdf_.salt(&this->master_secret_[0], this->master_secret_.size()); resumption_master_secret_ = hkdf_.derive_secret("res master", this->accumulated_handshakes_); write_f(encode(new_session_ticket(), HANDSHAKE)); } else {//1.2 if(this->master_secret_.empty()) {//no session resumption s += this->server_certificate(); s += this->server_key_exchange(); s += this->server_hello_done(); write_f(s); if(s = this->alert(2, 0); !(a = read_f()) || (s = this->client_key_exchange(move(*a))) != "") break; if(s = this->alert(2, 0); !(a = read_f()) || (s = this->change_cipher_spec(move(*a))) != "") break; if(s = this->alert(2, 0); !(a = read_f()) || (s = TLS<SV>::finished(move(*a))) != "") break; } else this->derive_from_master();//session resumption s = this->change_cipher_spec(); s += TLS<SV>::finished(); write_f(move(s));//empty s if(sclient_.sp_client) {//connected to former connection == session resump if(s = this->alert(2, 0); !(a = read_f()) || (s = this->change_cipher_spec(move(*a))) != "") break; if(s = this->alert(2, 0); !(a = read_f()) || (s = TLS<SV>::finished(move(*a))) != "") break; } } } else {//client write_f(client_hello()); if(s = this->alert(2, 0); !(a = read_f()) || (s = server_hello(move(*a))) != "") break; if(premaster_secret_) {//1.3 protect_handshake();//should prepend header? if(s = this->alert(2, 49); !(a = read_f()) || (s = this->change_cipher_spec(move(*a))) != "") break; for(int i=0; i<4; i++) { if(s = this->alert(2, 49); !(a = read_f())) break; if(s = this->alert(2, 50); !(a = decode(move(*a)))) break; else this->accumulated_handshakes_ += *a; } string tmp = this->accumulated_handshakes_; s = this->change_cipher_spec(); s += encode(finished(), HANDSHAKE); write_f(move(s)); this->accumulated_handshakes_ = tmp; set_aes(this->master_secret_, "c ap traffic", "s ap traffic"); resumption_master_secret_ = hkdf_.derive_secret("res master", this->accumulated_handshakes_); // if(a = read_f(); !a || !(a = decode(move(*a))) || // (s = new_session_ticket(*a)) != "") break; } else { if(s = this->alert(2, 0); !(a = read_f()) || (s = this->server_certificate(move(*a))) != "") break; if(s = this->alert(2, 0); !(a = read_f()) || (s = this->server_key_exchange(move(*a))) != "") break; if(s = this->alert(2, 0); !(a = read_f()) || (s = this->server_hello_done(move(*a))) != "") break; s = this->client_key_exchange(); s += this->change_cipher_spec(); s += TLS<SV>::finished(); write_f(move(s));//empty s if(s = this->alert(2, 0); !(a = read_f()) || (s = this->change_cipher_spec(move(*a))) != "") break; if(s = this->alert(2, 0); !(a = read_f()) || (s = TLS<SV>::finished(move(*a))) != "") break; } }//if constexpr }//switch if(s != "") { write_f(s);//send alert message return {}; } else return sclient_.sp_client; } struct TLS_header { uint8_t content_type = HANDSHAKE; // 0x17 for Application Data, 0x16 handshake uint8_t version[2] = {0x03, 0x03}; // 0x0303 for TLS 1.2 uint8_t length[2] = {0, 4}; //length of encrypted_data, 4 : handshake size void set_length(int k) { length[0] = k / 0x100; length[1] = k % 0x100; } int get_length() { return length[0] * 0x100 + length[1]; } }; template<bool SV> string TLS13<SV>::encode(string &&s, int type) { return premaster_secret_ ? encode13(forward<string>(s), type) : TLS<SV>::encode(forward<string>(s), type); } template<bool SV> optional<string> TLS13<SV>::decode(string &&s) { return premaster_secret_ ? decode13(forward<string>(s)) : TLS<SV>::decode(forward<string>(s)); } template<bool SV> string TLS13<SV>::encode13(string &&s, int type) { uint8_t seq[8]; TLS_header h1; h1.content_type = 23; mpz2bnd(this->enc_seq_num_++, seq, seq + 8); const size_t chunk_size = (1 << 14) - 64;//cut string into 2^14 string frag = s.substr(0, chunk_size) + string{type}; h1.set_length(frag.size() + 16); uint8_t *p = (uint8_t*)&h1; this->aes_[SV].aad(p, 5); p = (uint8_t*)frag.data(); this->aes_[SV].xor_with_iv(seq); auto tag = this->aes_[SV].encrypt(p, frag.size()); this->aes_[SV].xor_with_iv(seq); frag += string{tag.begin(), tag.end()}; string s2 = struct2str(h1) + frag; if(s.size() > chunk_size) s2 += encode(s.substr(chunk_size)); return s2; } template<bool SV> optional<string> TLS13<SV>::decode13(string &&s) { struct H { TLS_header h1; unsigned char encrypted_msg[]; } *p = (H*)s.data(); uint8_t seq[8]; if(int type = this->get_content_type(s).first; type != APPLICATION_DATA) { this->alert(this->alert(2, 10)); return {};//alert case } mpz2bnd(this->dec_seq_num_++, seq, seq + 8); int msg_len = p->h1.get_length() - 16;//tag length 16 this->aes_[!SV].aad((uint8_t*)p, 5); this->aes_[!SV].xor_with_iv(seq); auto auth = this->aes_[!SV].decrypt(p->encrypted_msg, msg_len); this->aes_[!SV].xor_with_iv(seq); if(equal(auth.begin(), auth.end(), p->encrypted_msg + msg_len)) { string r{p->encrypted_msg, p->encrypted_msg + msg_len}; while(r.back() == 0) r.pop_back(); if(r.back() == ALERT) { this->alert(this->alert(r[0], r[1])); return {}; } r.pop_back(); return r; } else { this->alert(this->alert(2, 20)); return {};//bad record mac } } #pragma pack()
[ "zezeon1@gmail.com" ]
zezeon1@gmail.com
d0652ad258a2a5413f9c0c58b215cf8a8776ec0c
364408b7128dab42a54e4b10609fc459c5ca6edc
/PlacementNewStateMachine/src/ColorState.h
3812a1a727b3cd8bf7c861cf5995d81896bea38d
[]
no_license
derLars/CPP11
7a55bae9466d6b26b5933f9276c12d32f0fe973b
fd58ad99b3dc2c780541a703628291e12e1901c4
refs/heads/master
2016-08-11T12:01:57.880210
2015-09-29T06:11:45
2015-09-29T06:11:45
43,348,435
0
0
null
null
null
null
UTF-8
C++
false
false
1,550
h
/* * ColorState.h * * Created on: Sep 15, 2015 * Author: derlars */ #ifndef SRC_COLORSTATE_H_ #define SRC_COLORSTATE_H_ #include "StateMachine.h" #include "Context.h" #include <iostream> using namespace std; class BaseStateColor : public StateMachine<BaseStateColor, Context>{ public: BaseStateColor(){ connectSignalToFunction(GREEN,this,&BaseStateColor::green); connectSignalToFunction(YELLOW,this,&BaseStateColor::yellow); connectSignalToFunction(BLUE,this,&BaseStateColor::blue); } virtual ~BaseStateColor(){} enum COLOR{GREEN,YELLOW,BLUE}; virtual void status() = 0; virtual void green() = 0; virtual void yellow() = 0; virtual void blue() = 0; }; class Yellow; class Blue; class Green : public BaseStateColor { public: Green(){context->addToHistory("Green");} virtual ~Green(){} void status(){cout << "Color is green!" << endl;} void green(){} void yellow(){changeState<Yellow>();} void blue(){changeState<Blue>();} }; class Yellow : public BaseStateColor { public: Yellow(){context->addToHistory("Yellow");} virtual ~Yellow(){} void status(){cout << "Color is yellow!" << endl;} void green(){changeState<Green>();} void yellow(){} void blue(){changeState<Blue>();} }; class Blue : public BaseStateColor { public: Blue(){context->addToHistory("Blue");} virtual ~Blue(){} void status(){cout << "Color is blue!" << endl;} void green(){changeState<Green>();} void yellow(){changeState<Yellow>();} void blue(){} }; #endif /* SRC_COLORSTATE_H_ */
[ "l.schwensen@hotmail.de" ]
l.schwensen@hotmail.de
c9538cf36de1e9cb4ec9d24b66349bf227833af7
001bdf99592315f5ffc932d70f7b15d76bbc3433
/src/qt/signverifymessagedialog.h
a1c9a805cc2d0c0dc6c4912f86ca01ebabf9565d
[ "MIT" ]
permissive
elquer/rdct-alpha
c3fecff8f78de8dbd29357c193910210cc4c8355
04b7e8fea0d8f113d4f7403cd487c3108adcafba
refs/heads/master
2020-03-26T15:05:10.844599
2018-08-16T14:16:20
2018-08-16T14:16:20
145,021,597
0
0
null
2018-08-16T17:50:13
2018-08-16T17:50:13
null
UTF-8
C++
false
false
1,367
h
// Copyright (c) 2011-2013 The Bitcoin developers // Copyright (c) 2017 The RDCT developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_QT_SIGNVERIFYMESSAGEDIALOG_H #define BITCOIN_QT_SIGNVERIFYMESSAGEDIALOG_H #include <QDialog> class WalletModel; namespace Ui { class SignVerifyMessageDialog; } class SignVerifyMessageDialog : public QDialog { Q_OBJECT public: explicit SignVerifyMessageDialog(QWidget* parent); ~SignVerifyMessageDialog(); void setModel(WalletModel* model); void setAddress_SM(const QString& address); void setAddress_VM(const QString& address); void showTab_SM(bool fShow); void showTab_VM(bool fShow); protected: bool eventFilter(QObject* object, QEvent* event); private: Ui::SignVerifyMessageDialog* ui; WalletModel* model; private slots: /* sign message */ void on_addressBookButton_SM_clicked(); void on_pasteButton_SM_clicked(); void on_signMessageButton_SM_clicked(); void on_copySignatureButton_SM_clicked(); void on_clearButton_SM_clicked(); /* verify message */ void on_addressBookButton_VM_clicked(); void on_verifyMessageButton_VM_clicked(); void on_clearButton_VM_clicked(); }; #endif // BITCOIN_QT_SIGNVERIFYMESSAGEDIALOG_H
[ "brunohass2303@gmail.com" ]
brunohass2303@gmail.com
a6e3b95cbddce917df72c847af2df695818cddda
36c0e07fba5319f186a135a41f2ecd2445656894
/tests/method/test_const_prop.cpp
8aa0980289747c40a7ad0cbda9b0bd0baf4e7970
[ "LLVM-exception", "Apache-2.0" ]
permissive
mfkiwl/systemc-compiler
5f53c3dbd52439997289b3947d863d9d8b3c90b4
96d94cac721224745cffe3daaee35c406af36e9e
refs/heads/main
2023-06-12T06:39:48.707703
2021-07-08T11:10:41
2021-07-08T11:10:41
385,031,718
1
0
NOASSERTION
2021-07-11T19:05:42
2021-07-11T19:05:42
null
UTF-8
C++
false
false
21,935
cpp
/****************************************************************************** * Copyright (c) 2020, Intel Corporation. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception. * *****************************************************************************/ #include "systemc.h" #include <sct_assert.h> using namespace sc_core; // Constant propagation general case class A : public sc_module { public: sc_in<bool> clk{"clk"}; sc_in<bool> nrst{"nrst"}; sc_in<bool> a{"a"}; sc_out<bool> b{"b"}; sc_signal<bool> c{"c"}; static const unsigned CTRL_NUM = 0; sc_signal<bool>* ctrl_interrupt_sig[CTRL_NUM]; SC_CTOR(A) : useWriteResp0(1), useWriteResp1(1) { for (int i = 0; i < 3; i++) { arr1[i] = new sc_signal<bool>("arr1"); arr2[i] = new sc_signal<bool>("arr2"); arr3[i] = new sc_signal<bool>("arr3"); } SC_METHOD(complex_if_level); sensitive << a; SC_METHOD(mstrResponseMuxProc); sensitive << a; SC_METHOD(NoReturnProc); sensitive << a; SC_METHOD(NoReturnProc2); sensitive << a; SC_METHOD(not_test); sensitive << a; SC_METHOD(intrControlProc); sensitive << a; SC_METHOD(chooseRequestProc); sensitive << a; SC_METHOD(ackProc2R2Wcache4); sensitive << a << rr_first_indx; SC_METHOD(simple_if1); sensitive << a; SC_METHOD(simple_if2); sensitive << a; SC_METHOD(if_in_func1); sensitive << a; SC_METHOD(if_in_func2); sensitive << a; SC_METHOD(if_in_func3); sensitive << a; SC_METHOD(const_param_func); sensitive << a; SC_METHOD(if_in_func5); sensitive << a; SC_METHOD(simple_switch1); sensitive << a; SC_METHOD(simple_switch2); sensitive << a; SC_METHOD(simple_switch3); sensitive << a; SC_METHOD(simple_binary1); sensitive << a; SC_METHOD(simple_binary2); sensitive << a << c; SC_METHOD(simple_binary3); sensitive << a << c; SC_METHOD(simple_cond1); sensitive << a; SC_METHOD(double_if1); sensitive << a << b; SC_METHOD(double_if2); sensitive << a << b; SC_METHOD(double_if3); sensitive << a << b; SC_METHOD(double_if4); sensitive << a << b << c; SC_METHOD(double_if5); sensitive << a << b << c; SC_METHOD(double_if6); sensitive << a << b << c; SC_METHOD(seq_if); sensitive << a << b << c; SC_METHOD(double_if_for1); sensitive << a << b << c; SC_METHOD(double_if_for2); sensitive << a << b << c; SC_METHOD(double_if_while); sensitive << a << b << c; SC_METHOD(double_if_break); sensitive << a << b << c; SC_METHOD(false_if_break); sensitive << c; SC_METHOD(multiple_calls1); sensitive << a; SC_METHOD(multiple_calls2); sensitive << a; SC_METHOD(local_array_if); sensitive << a; SC_CTHREAD(local_array, clk.pos()); async_reset_signal_is(nrst, false); SC_METHOD(return_const_in_if); sensitive << a; SC_METHOD(return_const_in_for); sensitive << a; } //---------------------------------------------------------------------- // One IF at level 2 and several IF at level 4, no IF with level 3 // Bug in real design -- fixed void complex_if_level() { int k; int m; int n; if (k) { if (m) { if (n) { if (k > n) { int aa = 0; } } else { if (true) { int bb = 1; } else { } } } sct_assert_level(1); } } //---------------------------------------------------------------------- // Bug in real design cache module sc_signal<bool>* arr1[3]; sc_signal<bool>* arr2[3]; sc_signal<bool>* arr3[3]; void mstrResponseMuxProc() { int k; int m; int n; int i = a.read(); if ( ( (*arr1[i]) && // B5 (true || !(*arr2[i]))) || // B4, B3 (*arr3[i]) ) // B2 { m = 1; // B1 } } //---------------------------------------------------------------------- // No return in some branch processes const unsigned useWriteResp0; const unsigned useWriteResp1; bool useWriteResp(unsigned portId) { switch (portId) { case 0: return useWriteResp0; case 1: return useWriteResp1; default: assert(false); return useWriteResp0; } } void NoReturnProc() { int k; int m; int n; assert (m > k); if (a.read()) { assert (m > k); assert (m > k && "message"); } } void NoReturnProc2() { useWriteResp(a.read()); } //---------------------------------------------------------------------- // Unary not and logic not void not_test() { sc_uint<3> x = 3; sc_uint<3> y = ~x; sct_assert_const(y == 4); bool b = x == y; sct_assert_const(!b); } //---------------------------------------------------------------------- // Check level after complex IF void double_if1() { int k; int m; int n; if (a.read()) { if (b.read()) { m = 1; } else { m = 2; } } else { if (b.read()) { m = 3; } else { m = 4; } } sct_assert_level(0); m = 0; } void double_if2() { int k; int m; int n; if (a.read()) { if (b.read()) { m = 1; } else { m = 2; } } sct_assert_level(0); m = 0; } void double_if3() { int k; int m; int n; if (a.read()) { if (b.read()) { m = 1; } else { m = 2; } } else { if (b.read()) { m = 3; } } sct_assert_level(0); m = 0; } void double_if4() { int k; int m; int n; if (a.read()) { if (b.read()) { m = 1; } else if (c.read()) { m = 2; } else { m = 3; } } else { if (b.read()) { m = 4; } else if (c.read()) { m = 5; } else { m = 6; } } sct_assert_level(0); m = 0; } int f() { return 5; } void double_if5() { int k; int m; int n; if (a.read()) { if (a.read()) { if (b.read()) { m = 1; } else if (c.read()) { if (true) { m = f(); } } } sct_assert_level(1); } } void double_if6() { int k; int m; int n; if (a.read()) { if (b.read()) { m = 1; // Min level } else { if (c.read()) { m = 2; } else { m = 3; } } } else { if (b.read()) { if (c.read()) { m = 4; } else { m = 5; } } else { if (c.read()) { m = 6; } else { m = 7; } } } sct_assert_level(0); } void double_if_for1() { int k; int m; int n; if (a.read()) { if (b.read()) { for (int i = 0; i < 2; i++) { } } else if (c.read()) { m = 2; } else { m = 3; } } else { if (b.read()) { m = 4; } else if (c.read()) { for (int i = 0; i < 2; i++) { if (a.read()) break; } } else { m = 6; } } sct_assert_level(0); m = 0; } void double_if_for2() { int k; int m; int n; if (a.read()) { if (b.read()) { for (int i = 0; i < 2; i++) { if (c.read()) { m = 1; } } } else if (c.read()) { m = 2; } else { m = 3; } } else { if (b.read()) { m = 4; } else if (c.read()) { for (int i = 0; i < 2; i++) { if (c.read()) { m = 1; } else { m = 2; } } } else { m = 6; if (c.read()) { m = 1; } else { m = 2; } } } sct_assert_level(0); m = 0; } void double_if_while() { int k; int m; int n; if (a.read()) { int i = 0; if (b.read()) { while (i < 2) { i++; } } else if (c.read()) { m = 2; } else { m = 3; } } else { int i = 0; while (i < 2) { if (b.read()) { m = 4; } else { int j = 1; while (j < 3) { j++; if (c.read()) break; } } i++; } if (c.read()) { for (int i = 0; i < 2; i++) { if (c.read()) { m = 1; } else { m = 2; } } } } sct_assert_level(0); m = 0; } void double_if_break() { int k; int m; int n; for (int i = 0; i < 2; i++) { if (a.read()) { m = 1; if (b.read()) { m = 2; break; } break; } } sct_assert_level(0); } void false_if_break() { for (int i = 0; i < 3; ++i) { if (false) { if (c.read()) break; } sct_assert_level(1); } } void seq_if() { int k; int m; int n; if (a.read()) { sct_assert_level(1); m = 1; } else if (b.read()) { sct_assert_level(2); m = 2; } else if (c.read()) { sct_assert_level(3); m = 3; } else { m = 4; } sct_assert_level(0); m = 0; } //---------------------------------------------------------------------- // Bug in real design -- fixed void intrControlProc() { // Zero iteration loop bool b = false; for (int i = 0; i < CTRL_NUM; i++) { b = b || *ctrl_interrupt_sig[i]; } } // Bug in real design -- fixed void chooseRequestProc() { if (false) { for (int i = 0; i < 1; i++) { if (a.read()) { break; } } } else { } } // Bug in real design -- fixed static const unsigned BLOCK_NUM = 3; static const unsigned PORT_NUM = 3; sc_signal<bool> port_req[PORT_NUM]; sc_signal<bool> port_oper[PORT_NUM]; sc_signal<sc_uint<2> > rr_first_indx; sc_signal<sc_uint<2> > port_bindx[PORT_NUM]; sc_uint<2> getNextPortIndex(unsigned iter, sc_uint<2> portIndx) { if (true) { if (iter < 1) { // High priority ports return (portIndx+1); // No wrap up allowed for them } else if (iter == 1) { return rr_first_indx.read(); } else { return ((portIndx == 0) ? 2 : ((portIndx == PORT_NUM-1) ? 0 : (portIndx+1))); } } else { return ((portIndx == PORT_NUM-1) ? 0 : (portIndx+1)); } } sc_uint<2> getFirstPortIndx() { return rr_first_indx.read(); } void ackProc2R2Wcache4() { bool readFirstAccess_flat[BLOCK_NUM]; bool readSecndAccess_flat[BLOCK_NUM]; bool writeFirstAccess_flat[BLOCK_NUM]; bool writeSecndAccess_flat[BLOCK_NUM]; for (int i = 0; i < BLOCK_NUM; i++) { readFirstAccess_flat[i] = a.read(); readSecndAccess_flat[i] = 0; writeFirstAccess_flat[i] = a.read(); writeSecndAccess_flat[i] = 0; } sc_uint<2> portIndx = getFirstPortIndx(); for (unsigned i = 1; i < PORT_NUM; i++) { portIndx = getNextPortIndex(i, portIndx); sc_uint<2> blockIndx = port_bindx[portIndx].read(); bool accessPermit = port_req[portIndx]; if (!port_oper[portIndx]) { if (!readFirstAccess_flat[blockIndx]) { readFirstAccess_flat[blockIndx] = accessPermit; } else if (!readSecndAccess_flat[blockIndx]) { readSecndAccess_flat[blockIndx] = accessPermit; } else { accessPermit = 0; } } else { if (!writeFirstAccess_flat[blockIndx]) { writeFirstAccess_flat[blockIndx] = accessPermit; } else if (!writeSecndAccess_flat[blockIndx]) { writeSecndAccess_flat[blockIndx] = accessPermit; } else { accessPermit = 0; } } sct_assert_level(1); } } //---------------------------------------------------------------------- // One IF with constant condition void simple_if1() { int i; i = 1; if (i > 0) { // termCond 1 i = 2; } sct_assert_const(i == 2); } // Two IFs with constant condition void simple_if2() { int i; i = 1; int m = i+1; if (a.read()) { if (i < 0) { // termCond 0 i = 2; } else { i = 3; } sct_assert_const(i == 3); } else { if (m > 0) { // termCond 1 i = 4; } sct_assert_const(i == 4); } } // IFs in function call void f1() { int j = 1; if (j > 0) { // termCond 1 j = 2; } } void if_in_func1() { int i = 1; if (i < 0) { // termCond 0 i = 2; } f1(); } // Constant propagation from function void f2() { int m = 3; } void if_in_func2() { f2(); } // Constant propagation to function void f3() { int m; if (m == 4) { int ll = 1; } } void if_in_func3() { int m = 4; f3(); } // Function with constant parameter by reference void f4_(unsigned& ref) { ref++; } void f4(unsigned val) { f4_(val); sct_assert_const(val == 2); } void const_param_func() { f4(1); } // Function returns constant value int f5() { return 5; } void if_in_func5() { int i = f5(); sct_assert_const (i == 5); if (i == 5) {} } // One SWITCH with constant condition void simple_switch1() { int i = 2; switch (i) { case 1: i = 2; break; case 2: i = 3; break; default: ; } sct_assert_const (i == 3); } // One SWITCH w/o constant condition void simple_switch2() { int i = a.read(); switch (i) { case 1: i = 2; break; case 2: i = 3; break; default: ; } } // One SWITCH with default true void simple_switch3() { int i = 3; switch (i) { case 1: i = 2; break; case 2: i = 3; break; default: i = 4; } sct_assert_const (i == 4); } // Two binary operators in condition void simple_binary1() { int i = 1; int m; if (a.read() && i < 0) { m = 2; } if (i > 0 || a.read()) { m = 3; } } void simple_binary2() { int i = 0; int m = -1; if (i == 0 || a.read()) { m = 0; } sct_assert_const (m == 0); if ((i == 1 || i == 2) && a.read()) { m = 1; } if ((i == 0 || i == 1) && a.read()) { m = 2; } if ((i == 1 || i == 0) && a.read()) { m = 3; } if ((i == 1 || a.read()) && c.read()) { m = 4; } if ((i == 0 || a.read()) && c.read()) { m = 5; } if ((a.read() || i == 0) && c.read()) { m = 6; } if ((a.read() || i == 1) && c.read()) { m = 7; } } void simple_binary3() { int i = 0; int m; if ((i == 0 && i == 1) && a.read()) { m = 1; } if ((i == 0 && i == 1) || a.read()) { m = 2; } if ((i == 0 && a.read()) || c.read()) { m = 3; } if ((i == 1 && a.read()) || c.read()) { m = 4; } if ((i == 0 && a.read()) && c.read()) { m = 5; } } // Conditional operator void simple_cond1() { int i = 1; int m = (i < 0) ? 1 : 2; sct_assert_const(m == 2); } void simple_var() { int k = 1; int m = a.read(); int i = m; } //--------------------------------------------------------------------------- // IF with local array void local_array_if() { if (a.read()) { bool arr[3]; } } // Local array in main loop void local_array() { wait(); while (true) { bool arr[3]; wait(); } } // ----------------------------------------------------------------------- // Multiple function calls at different levels void g() { int k = 0; } void multiple_calls1() { if (a.read()) { g(); } g(); } void multiple_calls2() { g(); if (a.read()) { g(); } } // ----------------------------------------------------------------------- // Constant returned from function int getConst() { return 2; } int getConst_(int i) { return i+1; } void return_const_in_if() { int i = a.read(); if (i < getConst()) { int ll = 1; } } void return_const_in_for() { int x = 0; int N = getConst(); sct_assert_const (N==2); for (int i = 0; i < N; ++i) { x++; } sct_assert_const (x==2); } // Function call in loop not supported void return_const_in_for2() { int x = 0; for (int i = 0; i < getConst(); ++i) { x++; } sct_assert_const (x==2); } void return_const_in_for3() { int x = 0; for (int i = getConst(); i < 4; ++i) { x++; } sct_assert_const (x==2); } void return_const_in_while() { int i = 0; while (i < getConst()) { i++; } sct_assert_const (i == 2); } void return_const_in_while2() { int i = 0; while (i < getConst_(1)) { i++; } sct_assert_const (i == 2); } void return_const_in_dowhile() { int i = 0; do { i++; } while (i < getConst()); } }; class B_top : public sc_module { sc_signal<bool> a{"a"}; sc_signal<bool> b{"b"}; sc_signal<bool> clk{"clk"}; sc_signal<bool> nrst{"nrst"}; public: A a_mod{"a_mod"}; SC_CTOR(B_top) { a_mod.clk(clk); a_mod.nrst(nrst); a_mod.a(a); a_mod.b(b); } }; int sc_main(int argc, char* argv[]) { B_top b_mod{"b_mod"}; sc_start(); return 0; }
[ "mikhail.moiseev@intel.com" ]
mikhail.moiseev@intel.com
86a4d69dded76adf5bcc9181e3c03bc4cb2610e4
c74e77aed37c97ad459a876720e4e2848bb75d60
/400-499/487/(8784912)[COMPILATION_ERROR]A[ b'Fight the Monster' ].cpp
4e5ee91cbf5634102d4a08d3a2548839e19576c9
[]
no_license
yashar-sb-sb/my-codeforces-submissions
aebecf4e906a955f066db43cb97b478d218a720e
a044fccb2e2b2411a4fbd40c3788df2487c5e747
refs/heads/master
2021-01-21T21:06:06.327357
2017-11-14T21:20:28
2017-11-14T21:28:39
98,517,002
1
1
null
null
null
null
UTF-8
C++
false
false
831
cpp
#include<iostream> #include<vector> #include<algorithm> #include<functional> #include<map> #include<cmath> #include<queue> #include<stack> #include<sstream> #include<iomanip> #include<bitset> #include<string> #include<cstdio> #include<list> using namespace std; typedef long long LL; typedef unsigned long long uLL; typedef long double ldb; typedef pair<int,int> pii; int main() { ios_base::sync_with_stdio(0); int yh,ya,yd,mh,ma,md,h,a,d,p; cin>>yh>>ya>>yd>>mh>>ma>>md>>h>>a>>d; p = a*max(0,md-ya+1); ya+=p/max(a,1); int m=1000000007; if(ma<=yd){cout<<p; return 0;} for(int i = 0; i < 201; ++i) { for(int j = 0; j < 201; ++j) { for(int k = 0; k < 201; ++k) { if(ma-yd-k==0 || (yh+i)/(ma-yd-k)+((yh+i)%(ma-yd-k)>0)>mh/(ya+j-md)+(mh%(ya+j-md)>0)){m = min(i*h+j*a+k*d,m);} } } } cout<<m+p; return 0;
[ "yashar_sb_sb@yahoo.com" ]
yashar_sb_sb@yahoo.com
f69f3a6482c11d353e2e63739b32c693b8fb07d3
dd80a584130ef1a0333429ba76c1cee0eb40df73
/external/chromium_org/tools/gn/gyp_helper.cc
fb669afd123e7f0f677af1deabb34dd6378c8c3f
[ "MIT", "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference", "GPL-2.0-only", "Apache-2.0", "LicenseRef-scancode-unknown" ]
permissive
karunmatharu/Android-4.4-Pay-by-Data
466f4e169ede13c5835424c78e8c30ce58f885c1
fcb778e92d4aad525ef7a995660580f948d40bc9
refs/heads/master
2021-03-24T13:33:01.721868
2017-02-18T17:48:49
2017-02-18T17:48:49
81,847,777
0
2
MIT
2020-03-09T00:02:12
2017-02-13T16:47:00
null
UTF-8
C++
false
false
3,290
cc
// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "tools/gn/gyp_helper.h" #include "tools/gn/err.h" #include "tools/gn/filesystem_utils.h" #include "tools/gn/settings.h" #include "tools/gn/source_file.h" #include "tools/gn/target.h" #include "tools/gn/toolchain.h" GypHelper::GypHelper() { } GypHelper::~GypHelper() { } SourceFile GypHelper::GetGypFileForTarget(const Target* target, Err* err) const { // Use the manually specified one if its there. if (!target->gyp_file().is_null()) return target->gyp_file(); // Otherwise inherit the directory name. const std::string& dir = target->label().dir().value(); size_t last_slash = dir.size() - 1; std::string dir_name; if (last_slash > 0) { size_t next_to_last_slash = dir.rfind('/', last_slash - 1); if (next_to_last_slash != std::string::npos) { dir_name = dir.substr(next_to_last_slash + 1, last_slash - next_to_last_slash - 1); } } if (dir_name.empty()) { *err = Err(Location(), "Need to specify a gyp_file value for " + target->label().GetUserVisibleName(false) + "\n" "since I can't make up one with no name."); return SourceFile(); } return SourceFile(dir + dir_name + ".gyp"); } std::string GypHelper::GetNameForTarget(const Target* target) const { if (target->settings()->is_default()) return target->label().name(); // Default toolchain has no suffix. return target->label().name() + "_" + target->settings()->toolchain_label().name(); } std::string GypHelper::GetFullRefForTarget(const Target* target) const { Err err; SourceFile gypfile = GetGypFileForTarget(target, &err); CHECK(gypfile.is_source_absolute()) << "GYP files should not be system-absolute: " << gypfile.value(); std::string ret("<(DEPTH)/"); // Trim off the leading double-slash. ret.append(&gypfile.value()[2], gypfile.value().size() - 2); ret.push_back(':'); ret.append(GetNameForTarget(target)); return ret; } std::string GypHelper::GetFileReference(const SourceFile& file) const { std::string ret; if (file.is_null()) return ret; // Use FilePath's resolver to get the system paths out (on Windows this // requires special handling). Since it's absolute, it doesn't matter what // we pass in as the source root. if (file.is_system_absolute()) return FilePathToUTF8(file.Resolve(base::FilePath())); // Source root relative, strip the "//". ret.assign("<(DEPTH)/"); ret.append(&file.value()[2], file.value().size() - 2); return ret; } std::string GypHelper::GetDirReference(const SourceDir& dir, bool include_slash) const { std::string ret; if (dir.is_null()) return ret; if (dir.is_system_absolute()) { ret = FilePathToUTF8(dir.Resolve(base::FilePath())); } else { ret.assign("<(DEPTH)/"); ret.append(&dir.value()[2], dir.value().size() - 2); } // Optionally trim the slash off the end. if (!ret.empty() && !include_slash && (ret[ret.size() - 1] == '/' || ret[ret.size() - 1] == '\\')) ret.resize(ret.size() - 1); return ret; }
[ "karun.matharu@gmail.com" ]
karun.matharu@gmail.com
ac131897f68522e3bbe6e16c4472dae00344414a
f6d8a207d9ffd21793d5a05e14339d0cd015da01
/robot.cpp
fcf5a05499e91e7ed8b90a9dafd912cecc5e7a65
[]
no_license
bluewell/ENGR101-2016
32379da66068d200eb08df13cc674ea3be0c0b45
24af846f5dc7fb4387070970876b6d45e63ead0b
refs/heads/master
2016-09-14T06:17:30.249930
2016-05-25T04:34:06
2016-05-25T04:34:06
56,122,208
0
0
null
null
null
null
UTF-8
C++
false
false
472
cpp
//Including libraries #include <stdio.h> #include <time.h> //Loading methods form E101 library extern "C" int init(int d_lev); extern "C" int Sleep(int sec, int usec); extern "C" int set_motor(int motor, int speed); extern "C" int connect_to_server(char server_addr[15], int port); extern "C" int send_to_server(char message[24]); extern "C" int receive_from_server(char message[24]); extern "C" int take_picture(); extern "C" char get_pixel(int row,int col,int colour);
[ "bluewell239@gmail.com" ]
bluewell239@gmail.com
4f9532349020d08375b07f9b561ea1ec1281ff5e
6c179452e468cf6cc633573fd497260bd3b08405
/Source/Test/main.cpp
99669f5f49163a0cdb8030148a22ff871c3c8572
[]
no_license
Chill-Language/CoreLib
4b08724194793464db65f216feb96380997f00dd
5f82b952856625eb8076b6ab73b9c6bc63ee1be0
refs/heads/master
2021-03-20T13:46:33.869010
2020-11-05T01:14:31
2020-11-05T01:14:31
247,211,196
1
0
null
null
null
null
UTF-8
C++
false
false
2,915
cpp
#include "Tree/TreeCreator.hpp" #include "Tree/TreeWalker.hpp" #include "Lexer/Lexer.hpp" #include "Lexer/SourceData.hpp" #include "Lexer/Handler.hpp" #include <iostream> #include <fstream> #include <string> using Tree = ChillParser::Tree<std::string>; // TODO ChillParser_Begin SourceData initSourceData(std::istream &input) { SourceData result; SourceOffset offset = 0; while (input) { std::string line; std::getline(input, line); result.data += line; std::cerr << "\""; for (auto c : line) { switch (c) { case '\n': std::cerr << "\\n"; break; case '\r': std::cerr << "\\r"; break; case '\t': std::cerr << "\\t"; break; case '\0': std::cerr << "\\0"; break; default: std::cerr << c; } } std::cerr << "\"" << std::endl; } return result; } ChillParser_End static ChillParser::SourceData source_data; // TODO static ChillParser::SourceOffset offset; // TODO static ChillParser::MemoryListTreeAllocator<ChillParser::TokenTree> allocator; // TODO auto test_create(const char *filename) -> ChillParser::TokenTree { if (filename == nullptr) { return ChillParser::TokenTree(ChillParser::TokenTree::NodePtr()); } std::ifstream input(filename, std::ios::binary); ChillParser::SourceData source_data; // TODO return ChillParser::Lexer::parse(input, source_data, allocator, offset, [](const ChillParser::Lexer::SubmitFunc &submit, ChillParser::SourceOffset &offset) { return new ChillParser::TriggerHandler(submit, offset); }); } auto main(int argc, const char *argv[]) -> int { // class _ : public ChillParser::TreeWalker<ChillParser::TokenTree> { public: void visitElementNode(ElementNode& node) override { std::cout << source_data.data.substr(node.data.begin, node.data.end - node.data.begin); } void visitTreeNode(TreeNode& node) override { auto btype = node.brackettype; std::pair<char, char> bracket; switch (btype) { case ChillParser::BracketType::Small: bracket = std::make_pair<char, char>('(', ')'); break; case ChillParser::BracketType::Square: bracket = std::make_pair<char, char>('[', ']'); break; case ChillParser::BracketType::Big: bracket = std::make_pair<char, char>('{', '}'); break; } std::cout << bracket.first; for (auto i = 0; i != node.count; ++i) { traverseNode(node.begin()[i]); if (i != node.count - 1) { std::cout << " "; } } std::cout << bracket.second; } } Walker; std::ifstream input(argv[1], std::ios::binary); if (argc > 1) { std::cout << argv[1] << std::endl; } while (true) { auto tree = ChillParser::Lexer::parse(input, source_data, allocator, offset, [](const ChillParser::Lexer::SubmitFunc &submit, ChillParser::SourceOffset &offset) { return new ChillParser::TriggerHandler(submit, offset); }); if (tree.root().isNull()) { break; } Walker.traverseNode(tree.root()); std::cout << "\n"; } return 0; }
[ "hanlengmowang@hotmail.com" ]
hanlengmowang@hotmail.com
4a6c58d7b1047fc7d8d1d8eada98a4ad1fd9768c
8d81f8a15efd9a4d0f11ac3fe64d822eb98bd37d
/crackCode_5/09.10.cpp
748764644e81d7efced2571500832f062eacfc2c
[]
no_license
wyxmails/MyCode
b32a14d3b3a63dd9b3049d266231728419ed60d1
641abffc65b52b6f4a279432a8c4037a3b6a900c
refs/heads/master
2020-12-25T17:24:03.304677
2016-08-28T14:05:10
2016-08-28T14:05:10
18,900,363
2
0
null
null
null
null
UTF-8
C++
false
false
1,966
cpp
/* You have a stack of n boxes, with widths wi, heights hi, and depths di, Theboxes cannot be rotated and can only be stacked on top of one another if each box in the stack is strictly larger than the box above it in width, height, and depth. Implement a method to build the tallest stack possible, where the height of a stack is the sum of the heights of each box. */ #include <iostream> #include <vector> #include <algorithm> using namespace std; struct Box{ int w,h,d; Box(){} Box(int w,int h,int d):w(w),h(h),d(d){} }; bool cmp(const Box&b1,const Box&b2){ return ((b1.w+b1.h+b1.d)>(b2.w+b2.h+b2.d)); } void printStack(int index,vector<int>&pre,vector<Box>&boxes){ while(index!=-1){ cout << boxes[index].w << " " << boxes[index].h << " " << boxes[index].d << endl; index = pre[index]; } return ; } int GetHeight(vector<Box>& boxes){ int n = boxes.size(); if(n==0) return 0; if(n==1) return boxes[0].h; sort(boxes.begin(),boxes.end(),cmp); vector<int> mark(n,0); vector<int> pre(n,-1); for(int i=0;i<n;++i){ cout << "(" << boxes[i].w << " " << boxes[i].h << " " << boxes[i].d << ")"; mark[i] = boxes[i].h; for(int j=0;j<i;++j){ if(boxes[i].w<boxes[j].w&&boxes[i].h<boxes[j].h&&boxes[i].d<boxes[j].d){ if(mark[j]+boxes[i].h>mark[i]){ mark[i] = mark[j]+boxes[i].h; pre[i] = j; } //mark[i] = max(mark[i],mark[j]+boxes[i].h); } } } cout << endl; int index=0; int Max = mark[0]; for(int i=1;i<n;++i){ if(mark[i]>Max){ index = i; Max = mark[i]; } //Max = max(Max,mark[i]); } cout << "stack: " << endl; printStack(index,pre,boxes); return Max; } int main(int argc,char*argv[]){ srand(time(NULL)); int n = rand()%10; vector<Box> boxes; for(int i=0;i<n;++i){ int w = rand()%20+1, h = rand()%20+1, d = rand()%20+1; Box b(w,h,d); boxes.push_back(b); cout << "(" << w << " " << h << " " << d << ")"; } cout << endl; cout << "result: " << GetHeight(boxes) << endl; return 0; }
[ "wyxmails@gmail.com" ]
wyxmails@gmail.com
b26b2223876f99a8495db1cce9c76b7d9359f934
a08a30f88e249ece2a1e1a9bd59d1d3d6c7e3f23
/10-27/FoxNames.cc
868527ad6f3d7bdeaba672232689493f4d892b0f
[]
no_license
abisbano/cpc-1718
8c3297264fab21241fbf583ee910e14e90b85c45
c5f08c08c5d3fd8546c9451dd1874614ee48f9fd
refs/heads/master
2018-10-08T02:49:07.730907
2018-07-16T18:00:15
2018-07-16T18:00:15
105,977,599
0
0
null
null
null
null
UTF-8
C++
false
false
2,969
cc
/* FoxNames.cc Author: Andrea Bisbano Date: 12/02/18 Problem: http://codeforces.com/problemset/problem/510/C?locale=en Solution: This algorithm creates a graph where each node represent an alphabet letter. Then is computes the input strings adding an edge (u, v) if the letter u preceeds letter v in the solution's order. Then it performs a DFS to check if the graph is acyclic and in that case its topological sort is the solution. Otherwise, if the graph has a cycle there isn't a solution. Time cost: O(N+M) where N is 26 (the letter of the alphabet) and M is the number of dependencies (1 less than the number of strings). Space cost: O(1) */ #include <iostream> #include <vector> #include <cassert> #include <algorithm> #define OFFSET 97 class node { std::vector<uint64_t> adjacent; uint64_t color; public: void addEdge(uint64_t dest) { adjacent.push_back(dest); } const std::vector<uint64_t> &getAdjacent() { return adjacent; } uint64_t getColor() { return color; } void setColor(uint64_t c) { color = c; } node() : color(0) {} }; bool visitDfs(std::string &result, std::vector<node> &G, uint64_t i) { // std::cout << "Visit " << i << "\n"; G[i].setColor(1); auto adj = G[i].getAdjacent(); for (uint64_t n : adj) { if (G[n].getColor() == 0 && visitDfs(result, G, n)) { return true; } else if (G[n].getColor() == 1) { return true; } } G[i].setColor(2); result.push_back(i+OFFSET); return false; } std::string foxNames(std::vector<node> &G, const std::vector<uint32_t> &order) { std::string result; size_t n = order.size(); for (size_t i = 0; i < n; ++i) { if (G[order[i]].getColor() == 0) { if (visitDfs(result, G, order[i])) return "Impossible"; } } for (int i = 25; i >= 0; --i) { if (G[i].getColor() == 0) { result.push_back(i+OFFSET); } } std::reverse(result.begin(), result.end()); return result; } bool addEdges(std::vector<node> &G, std::vector<uint32_t> &order, std::string &succ, std::string &pred) { size_t lenghtSucc = succ.length(); size_t lengthPred = pred.length(); size_t i = 0; while(succ[i] == pred[i]) { ++i; } if (i == lenghtSucc && lengthPred > lenghtSucc) { return true; } if (i < lengthPred && i < lenghtSucc) { G[pred[i]-OFFSET].addEdge(succ[i]-OFFSET); order.push_back(pred[i]-OFFSET); } return false; } int main() { std::ios_base::sync_with_stdio(false); std::cin.tie(NULL); size_t n; std::vector<node> graph(26); std::vector<uint32_t> order; order.reserve(26); std::string sOld; std::string sNew; std::cin >> n; assert(n >= 1 && n <= 100); std::cin >> sOld; for (size_t i = 1; i < n; ++i) { std::cin >> sNew; if (addEdges(graph, order, sNew, sOld)) { std::cout << "Impossible\n"; return 0; } sOld = sNew; } std::cout << foxNames(graph, order) << "\n"; }
[ "a.bisbano@studenti.unipi.it" ]
a.bisbano@studenti.unipi.it
f8f65525588951de2104e7b18708f5749561f311
921ddb77a9efeab57dfe664995c78311f01e8d80
/Lecture 17/RootToLeaf/AllSumPaths.cpp
1dc06d0625ed267c308c81337dbbcb4581551127
[]
no_license
kumarnitin15/Algo-DS-in-CPP
c814eb6f54e9ac7161f41d8ce0225e2e9ee10439
4eec955236d0dd02a1b2334d76427372c3072f55
refs/heads/master
2020-07-13T05:19:51.640032
2020-01-20T15:09:44
2020-01-20T15:09:44
205,001,685
13
5
null
2020-06-12T12:17:42
2019-08-28T18:51:41
C++
UTF-8
C++
false
false
458
cpp
void rootToLeafPath(Node *root, int sum, vector<Node *> &path, vector<vector<Node *>> &paths){ if(!root) return; path.push_back(root); if(!root->left && !root->right){ if(root->key == sum){ paths.push_back(path); } path.pop_back(); return; } rootToLeafPath(root->left,sum-root->key,path,paths); rootToLeafPath(root->right,sum-root->key,path,paths) path.pop_back(); }
[ "nk525888@gmail.com" ]
nk525888@gmail.com
e87eda7743eb38498837d5f230ceab3b6dae0f6b
0cf900dd34bd2f99bcd6c280a237ea3c3cd72a9b
/LightSaber/Classes/LightSaber.cpp
4353bc4305633720eb4d30b9e008cee29caf25a1
[]
no_license
colin3dmax/cocos2dx-lightsaber
ce01cf15c38142f084a81302de659ad66f886125
c24793272efc8c325862fd667a3d788517771da7
refs/heads/master
2021-01-24T20:42:05.699266
2013-06-25T11:00:52
2013-06-25T11:00:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,608
cpp
// // LightSaber.cpp // LightSaber // // Created by saiy2k on 24/06/13. // // #include "LightSaber.h" void LightSaber::createSabers() { CCParticleSystem *saber; textureSprite = CCSprite::create("swipeParticle.png"); textureSprite->retain(); for (int i = 0; i < strength; i++) { saber = CCParticleSun::create(); saber->setTexture(textureSprite->getTexture()); saber->setAutoRemoveOnFinish(true); saber->setEmissionRate(2000); saber->setLife(0.06); saber->setLifeVar(0.01); saber->setSpeed(0.0); saber->setSpeedVar(0.0); saber->setStartColor(ccc4f(0.2, 0.2, 0.9, 0.9)); saber->setEndColor(ccc4f(0.1, 0.1, 0.9, 0.5)); saber->setStartSize(16.0); saber->setStartSizeVar(2.0); saber->setEndSize(8.0); saber->setEndSizeVar(2.0); saber->setBlendAdditive(true); saber->setPosition( ccp(2020, 2020) ); saberArray->addObject(saber); this->addChild(saber); } textureSprite->release(); } void LightSaber::updateSabers(CCArray *systems, CCPoint startPoint, CCPoint endPoint) { float dist; CCPoint velocity; CCPoint delta, offset, final; CCPoint centerPoint; CCParticleSystem *saber; float ang; delta = ccpSub(endPoint, startPoint); centerPoint = ccpAdd(ccpMult(delta, 0.5), startPoint); ang = atan2f(delta.y, delta.x) * 180 / 3.14; dist = ccpDistance(startPoint, endPoint); for (int i = 0; i < systems->count(); i++) { saber = (CCParticleSystem *)systems->objectAtIndex(i); saber->setPosition( centerPoint ); saber->setPosVar( ccp(0, dist * 0.5) ); saber->setRotation(90 - ang); } } void LightSaber::removeSabers() { CCObject *obj; CCParticleSystem *particleSys; CCARRAY_FOREACH(saberArray, obj) { particleSys = (CCParticleSystem *)obj; particleSys->stopSystem(); particleSys->setAutoRemoveOnFinish(true); } } #pragma mark - #pragma mark TOUCH OVERRIDES bool LightSaber::ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent) { this->createSabers(); return true; } void LightSaber::ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent) { CCPoint point; point = pTouch->getLocation(); this->updateSabers(saberArray, point, ccpAdd(point, ccp(-40, 100))); } void LightSaber::ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent) { this->removeSabers(); } void LightSaber::ccTouchCancelled(CCTouch *pTouch, CCEvent *pEvent) { } void LightSaber::registerWithTouchDispatcher() { CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this, INT_MIN, true); } #pragma mark - #pragma mark OBJECT LIFE CYCLE bool LightSaber::init() { if ( !CCLayer::init() ) { return false; } this->setTouchEnabled(true); strength = 8; saberArray = CCArray::create(); saberArray->retain(); return true; } LightSaber::~LightSaber() { saberArray->release(); }
[ "saiy2k@gmail.com" ]
saiy2k@gmail.com
a52169a71797b9a53326e6082eecd60cc388ac70
2f1b4afd890e08e6a137b4076a879be77e78e3a6
/TE2502/src/tfile.hpp
7b8188e9dcabb7cbbb5045f789e01cdc211faa8e
[ "MIT" ]
permissive
ferthu/TE2502
8832f54380278d0bc51b9b82928032a82c47f84a
de801f886713c0b2ef3ce6aa1e41e3fd9a58483e
refs/heads/master
2020-04-17T21:22:08.247398
2019-04-11T08:11:43
2019-04-11T08:11:43
166,946,446
0
0
null
null
null
null
UTF-8
C++
false
false
577
hpp
#pragma once #include "ffile.hpp" // Loads variables from settings file and replaces variables in shader files before compiling them class TFile { public: TFile(const std::string& settings_file, const std::string& shader_dir); // Returns key as u32 uint32_t get_u32(const std::string& key); // Returns key as u64 uint64_t get_u64(const std::string& key); void compile_shaders(); private: void compile_shaders(std::string extension); std::unordered_map<std::string, uint64_t> m_map; FFile m_ffile; std::string m_shader_dir; std::string m_settings_file_path; };
[ "timmie.pettersson@gmail.com" ]
timmie.pettersson@gmail.com
4975806ff4452fe52d6216302f9292279c38b40d
8adc0f6392fa41fc7497962f84bdc8eaa1471a83
/src/deps/v8/test/cctest/test-persistent-handles.cc
b40b3eb0443df3cdc24b257c35b49623343b14b1
[ "MIT", "SunPro", "BSD-3-Clause", "bzip2-1.0.6", "Apache-2.0", "LicenseRef-scancode-openssl", "Zlib", "LicenseRef-scancode-public-domain-disclaimer", "ICU", "LicenseRef-scancode-unknown-license-reference", "Artistic-2.0", "NAIST-2003", "NTP", "CC0-1.0", "ISC", "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unicode", "BSD-2-Clause" ]
permissive
odant/conan-jscript
91d57eb46886ebda4b21683b290f726197362729
0e7433ebe9e5ebf331a47c8b2d01a510c7f53952
refs/heads/dev-14x
2023-08-25T03:00:34.085881
2021-11-01T08:12:58
2021-11-01T08:12:58
123,407,718
0
3
MIT
2023-01-07T04:16:47
2018-03-01T08:48:23
C++
UTF-8
C++
false
false
3,375
cc
// Copyright 2020 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <memory> #include "src/api/api.h" #include "src/base/platform/condition-variable.h" #include "src/base/platform/mutex.h" #include "src/base/platform/semaphore.h" #include "src/handles/handles-inl.h" #include "src/handles/local-handles-inl.h" #include "src/handles/persistent-handles.h" #include "src/heap/heap.h" #include "src/heap/local-heap.h" #include "src/heap/safepoint.h" #include "src/objects/heap-number.h" #include "test/cctest/cctest.h" #include "test/cctest/heap/heap-utils.h" namespace v8 { namespace internal { static constexpr int kNumHandles = kHandleBlockSize * 2 + kHandleBlockSize / 2; namespace { class PersistentHandlesThread final : public v8::base::Thread { public: PersistentHandlesThread(Heap* heap, std::vector<Handle<HeapNumber>> handles, std::unique_ptr<PersistentHandles> ph, Address object, base::Semaphore* sema_started, base::Semaphore* sema_gc_finished) : v8::base::Thread(base::Thread::Options("ThreadWithLocalHeap")), heap_(heap), handles_(std::move(handles)), ph_(std::move(ph)), object_(object), sema_started_(sema_started), sema_gc_finished_(sema_gc_finished) {} void Run() override { LocalHeap local_heap(heap_, std::move(ph_)); LocalHandleScope scope(&local_heap); for (int i = 0; i < kNumHandles; i++) { handles_.push_back( Handle<HeapNumber>::cast(local_heap.NewPersistentHandle(object_))); } sema_started_->Signal(); { ParkedScope scope(&local_heap); sema_gc_finished_->Wait(); } for (Handle<HeapNumber> handle : handles_) { CHECK_EQ(42.0, handle->value()); } CHECK_EQ(handles_.size(), kNumHandles * 2); CHECK(!ph_); ph_ = local_heap.DetachPersistentHandles(); } Heap* heap_; std::vector<Handle<HeapNumber>> handles_; std::unique_ptr<PersistentHandles> ph_; Address object_; base::Semaphore* sema_started_; base::Semaphore* sema_gc_finished_; }; TEST(CreatePersistentHandles) { CcTest::InitializeVM(); FLAG_local_heaps = true; Isolate* isolate = CcTest::i_isolate(); Address object = kNullAddress; std::unique_ptr<PersistentHandles> ph = isolate->NewPersistentHandles(); std::vector<Handle<HeapNumber>> handles; HandleScope handle_scope(isolate); Handle<HeapNumber> number = isolate->factory()->NewHeapNumber(42.0); object = number->ptr(); for (int i = 0; i < kNumHandles; i++) { handles.push_back(Handle<HeapNumber>::cast(ph->NewHandle(object))); } base::Semaphore sema_started(0); base::Semaphore sema_gc_finished(0); // pass persistent handles to background thread std::unique_ptr<PersistentHandlesThread> thread(new PersistentHandlesThread( isolate->heap(), std::move(handles), std::move(ph), object, &sema_started, &sema_gc_finished)); CHECK(thread->Start()); sema_started.Wait(); CcTest::CollectAllGarbage(); sema_gc_finished.Signal(); thread->Join(); // get persistent handles back to main thread ph = std::move(thread->ph_); ph->NewHandle(number->ptr()); } } // anonymous namespace } // namespace internal } // namespace v8
[ "udincev@yandex.ru" ]
udincev@yandex.ru
b03cae793c7c135eae37219fbd0af420f71882f5
32a6ac6cbec63296ba68838ad4699b995810c6cd
/compiled/cpp_stl_98/expr_1.cpp
8f281bb55c1c34d668e244bac730cc3e6250b401
[ "MIT" ]
permissive
smarek/ci_targets
a33696ddaa97daa77c0aecbdfb20c67546c729bc
c5edee7b0901fd8e7f75f85245ea4209b38e0cb3
refs/heads/master
2022-12-01T22:54:38.478115
2020-08-10T13:36:36
2020-08-19T07:12:14
286,483,420
0
0
MIT
2020-08-10T13:30:22
2020-08-10T13:30:21
null
UTF-8
C++
false
false
1,018
cpp
// This is a generated file! Please edit source .ksy file and use kaitai-struct-compiler to rebuild #include "expr_1.h" expr_1_t::expr_1_t(kaitai::kstream* p__io, kaitai::kstruct* p__parent, expr_1_t* p__root) : kaitai::kstruct(p__io) { m__parent = p__parent; m__root = this; f_len_of_1_mod = false; f_str1_len = false; try { _read(); } catch(...) { _clean_up(); throw; } } void expr_1_t::_read() { m_len_of_1 = m__io->read_u2le(); m_str1 = kaitai::kstream::bytes_to_str(m__io->read_bytes(len_of_1_mod()), std::string("ASCII")); } expr_1_t::~expr_1_t() { _clean_up(); } void expr_1_t::_clean_up() { } int32_t expr_1_t::len_of_1_mod() { if (f_len_of_1_mod) return m_len_of_1_mod; m_len_of_1_mod = (len_of_1() - 2); f_len_of_1_mod = true; return m_len_of_1_mod; } int32_t expr_1_t::str1_len() { if (f_str1_len) return m_str1_len; m_str1_len = str1().length(); f_str1_len = true; return m_str1_len; }
[ "kaitai-bot@kaitai.io" ]
kaitai-bot@kaitai.io
a19c45eb1a8a6f5d9bde84bb32c7aadf1105da3f
44341e2500d1aafe1615b0f79ce0f52c19a4d044
/RenderEngine2/Event.h
2843810f87562262b4c46acccd68c99bfff9d0f5
[]
no_license
daniel-zhang/render_demos
9a420306bdf00761e2ffac4f919fbdd6777e2f8c
73aa0958b97c9354147404d4f0c5a7754d80bf38
refs/heads/master
2020-12-24T16:06:39.923784
2016-04-02T00:17:25
2016-04-02T00:17:25
19,178,207
0
0
null
null
null
null
UTF-8
C++
false
false
397
h
#ifndef EVENT_H #define EVENT_H #include <boost/signals2.hpp> class MouseEvent { public: typedef boost::signals2::signal<void(int, int)> SIGNAL_TYPE; public: void fire(int x, int y) { return mSig(x, y); } boost::signals2::connection hook(SIGNAL_TYPE::slot_type &handler) { return mSig.connect(handler); } private: SIGNAL_TYPE mSig; }; #endif
[ "rovermills@gmail.com" ]
rovermills@gmail.com
96c623817c102179611f26fabfa4e7f90e1490ed
32bcb6a6009c648c77a0a710421689815bc18594
/Rasterizer/Rasterizer/src/Graphics/Vertex.cpp
ecf5f3303ce0fa0e354b6963c08a9284fa4f7efa
[]
no_license
qstawarz/Rasterizer
0b994890147a72c938d41a9b2a9778c635d7dab9
4b7252b9f6a463c1b0818a068f43274085ec7577
refs/heads/master
2021-04-26T22:20:01.499980
2018-03-06T12:23:27
2018-03-06T12:23:27
124,073,487
0
0
null
null
null
null
UTF-8
C++
false
false
883
cpp
#include <iostream> #include "../../includes/Graphics/Vertex.h" using namespace Graphics; Vertex::Vertex(const Vec3& p_position, const Vec3& p_normal, const Color& p_color) : m_position {p_position}, m_normal {p_normal.Normalize()}, m_color {p_color} { // std::cout << "Vertex created" << std::endl; } Vertex::~Vertex() { // std::cout << "Vertex destroyed" << std::endl; } void Vertex::SetPosition(const Vec3& p_position) { m_position = p_position; } void Vertex::SetNormal(const Vec3& p_normal) { m_normal = p_normal; } void Vertex::SetColor(const Color& p_color) { m_color = p_color; } const Vec3& Vertex::GetPosition() const { return m_position; } const Vec3& Vertex::GetNormal() const { return m_normal; } const Color& Vertex::GetColor() const { return m_color; }
[ "q.stawarz@student.isartdigital.com" ]
q.stawarz@student.isartdigital.com
7fe05222051e1cec75575bfbf8c0e87f8645bd8e
98b345594e6fa0ad9910bc0c20020827bbb62c53
/re110_1/processor24/10/p
2532200279858794b892fcb19042329a78d1e8c4
[]
no_license
carsumptive/coe-of2
e9027de48e42546ca4df1c104dcc8d04725954f2
fc3e0426696f42fbbbdce7c027df9ee8ced4ccd0
refs/heads/master
2023-04-04T06:09:23.093717
2021-04-06T06:47:14
2021-04-06T06:47:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,886
/*--------------------------------*- C++ -*----------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Version: 7 \\/ M anipulation | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volScalarField; location "10"; object p; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 2 -2 0 0 0 0]; internalField nonuniform List<scalar> 183 ( -0.29726 -0.298879 -0.300587 -0.302352 -0.304148 -0.304616 -0.305959 -0.30628 -0.307777 -0.307971 -0.309607 -0.309693 -0.30961 -0.31146 -0.311264 -0.313294 -0.312982 -0.31248 -0.314793 -0.314132 -0.313303 -0.316728 -0.315895 -0.314867 -0.317807 -0.316564 -0.315187 -0.318432 -0.316815 -0.315143 -0.31864 -0.316717 -0.318521 -0.316376 -0.320593 -0.31819 -0.315895 -0.317739 -0.315305 -0.317144 -0.314464 -0.311765 -0.316148 -0.31295 -0.30954 -0.314178 -0.310062 -0.305554 -0.305054 -0.299223 -0.293 -0.297511 -0.290431 -0.283145 -0.279541 -0.271551 -0.263677 -0.258788 -0.250638 -0.242907 -0.237181 -0.236655 -0.258253 -0.250102 -0.242372 -0.27899 -0.271003 -0.263131 -0.296937 -0.289862 -0.28258 -0.304463 -0.298633 -0.292413 -0.313581 -0.309459 -0.304947 -0.315558 -0.312348 -0.308927 -0.316566 -0.313872 -0.31974 -0.317174 -0.314728 -0.320041 -0.317636 -0.315332 -0.320155 -0.317972 -0.315823 -0.318094 -0.31617 -0.317888 -0.316273 -0.314598 -0.317264 -0.316026 -0.31465 -0.316188 -0.315362 -0.314337 -0.314265 -0.313609 -0.312782 -0.312775 -0.312467 -0.31197 -0.310957 -0.310766 -0.309113 -0.309209 -0.309131 -0.307305 -0.307508 -0.305513 -0.305842 -0.30373 -0.304206 -0.301965 -0.300233 -0.29856 -0.296978 -0.223484 -0.192628 -0.166022 -0.147096 -0.130018 -0.116487 -0.104831 -0.0951266 -0.086866 -0.0798707 -0.0738941 -0.0686658 -0.0643112 -0.0605223 -0.0574032 -0.0547868 -0.0526284 -0.0509215 -0.0496225 -0.0488764 -0.0483303 -0.217235 -0.186997 -0.161053 -0.142672 -0.126145 -0.113159 -0.10192 -0.0925894 -0.216684 -0.186456 -0.160464 -0.142067 -0.125422 -0.112338 -0.100803 -0.0913708 -0.0833004 -0.0763233 -0.0706073 -0.0656569 -0.165424 -0.146486 -0.129295 -0.115677 -0.103749 -0.0939416 -0.0855669 -0.0783434 -0.0724012 -0.0672717 -0.0629977 -0.0595157 -0.0565057 -0.0541508 -0.0521221 -0.0506718 -0.0495541 -0.0488263 -0.0483921 ) ; boundaryField { inlet { type zeroGradient; } outlet { type fixedValue; value nonuniform 0(); } cylinder { type zeroGradient; } top { type symmetryPlane; } bottom { type symmetryPlane; } defaultFaces { type empty; } procBoundary24to23 { type processor; value nonuniform List<scalar> 122 ( -0.311466 -0.311466 -0.31338 -0.315225 -0.315225 -0.31729 -0.318826 -0.318826 -0.319904 -0.319904 -0.320511 -0.320511 -0.320705 -0.320705 -0.323046 -0.322969 -0.320298 -0.320298 -0.319884 -0.319884 -0.319247 -0.319247 -0.317987 -0.317987 -0.315383 -0.310442 -0.310442 -0.304269 -0.304269 -0.295462 -0.287547 -0.287547 -0.275672 -0.267127 -0.267127 -0.253713 -0.245234 -0.245234 -0.231288 -0.230772 -0.253188 -0.244708 -0.244708 -0.275135 -0.266591 -0.266591 -0.294904 -0.286993 -0.286993 -0.303692 -0.303692 -0.314791 -0.30985 -0.30985 -0.317396 -0.317396 -0.318667 -0.318667 -0.322166 -0.319316 -0.319316 -0.322412 -0.322412 -0.322491 -0.322491 -0.322285 -0.319961 -0.319961 -0.319354 -0.319354 -0.318276 -0.318276 -0.316742 -0.31469 -0.31469 -0.312847 -0.310951 -0.310951 -0.0846437 -0.0779178 -0.0721605 -0.0671047 -0.0628974 -0.0592239 -0.0562059 -0.05367 -0.0515711 -0.0499018 -0.0486369 -0.0479204 -0.0473752 -0.210926 -0.181321 -0.156054 -0.138266 -0.122273 -0.109835 -0.0990117 -0.0846437 -0.0900474 -0.210382 -0.180788 -0.155476 -0.137668 -0.121555 -0.109004 -0.0978586 -0.0887951 -0.0810252 -0.0742898 -0.0687981 -0.0640249 -0.0615413 -0.0615413 -0.0582003 -0.0552983 -0.0530349 -0.0510686 -0.0496775 -0.048604 -0.0479002 -0.0474754 ) ; } procBoundary24to25 { type processor; value nonuniform List<scalar> 134 ( -0.295768 -0.298439 -0.299872 -0.301396 -0.302984 -0.302984 -0.304885 -0.306429 -0.308002 -0.308002 -0.309396 -0.310909 -0.310909 -0.311839 -0.311839 -0.312373 -0.31372 -0.31372 -0.313759 -0.313759 -0.313493 -0.314823 -0.314823 -0.31433 -0.31433 -0.313731 -0.313731 -0.312971 -0.312971 -0.310678 -0.308944 -0.308944 -0.305814 -0.305814 -0.300612 -0.300612 -0.295242 -0.286473 -0.286473 -0.275757 -0.275757 -0.268391 -0.255885 -0.255885 -0.248491 -0.255339 -0.247947 -0.222929 -0.275195 -0.255339 -0.267832 -0.275195 -0.28589 -0.300004 -0.28589 -0.294635 -0.300004 -0.305192 -0.311157 -0.305192 -0.308321 -0.311157 -0.312377 -0.312377 -0.313153 -0.313153 -0.313766 -0.313766 -0.31427 -0.31427 -0.31294 -0.313217 -0.313217 -0.313188 -0.313188 -0.31185 -0.31133 -0.31133 -0.310415 -0.310415 -0.30892 -0.307545 -0.307545 -0.305995 -0.304478 -0.302603 -0.302603 -0.301048 -0.299559 -0.298162 -0.295526 -0.229721 -0.198224 -0.170977 -0.151548 -0.133895 -0.119824 -0.107745 -0.0976605 -0.0890828 -0.0818164 -0.0756176 -0.0702134 -0.0657096 -0.0618037 -0.0585832 -0.0558862 -0.0536674 -0.0519213 -0.0505887 -0.0498142 -0.0492665 -0.222929 -0.19208 -0.19208 -0.170373 -0.150937 -0.133173 -0.119026 -0.106697 -0.0965088 -0.0878258 -0.0803508 -0.0741803 -0.0688694 -0.0644363 -0.0608142 -0.057696 -0.0552491 -0.0531571 -0.0516484 -0.0504877 -0.049736 -0.0492922 ) ; } } // ************************************************************************* //
[ "chaseguy15" ]
chaseguy15
53da9226e9b747a4ee05c5e5692980e733b6c792
5e3196ecf27f0a87ea50ceaba663fda24c17bd93
/Tower.cpp
5daf0502eb3a2fd451c0c3ea5cd5ff72ffc8db11
[]
no_license
heehee812/Game-tour-in-ALLEGRO
145b1d00d73925c0b63410e1c12cebddfad02818
21c676c3864187091cc11850fe547470a1a47c72
refs/heads/master
2022-09-16T23:19:57.172171
2020-05-31T09:07:00
2020-05-31T09:07:00
260,366,837
0
0
null
null
null
null
UTF-8
C++
false
false
3,230
cpp
#include "Tower.h" #include<iostream> #include<vector> Tower::Tower(int pos_x = 0, int pos_y = 0) { this->circle = new Circle(pos_x, pos_y, 70); } Tower::~Tower() { delete circle; al_destroy_bitmap(img); al_destroy_bitmap(attack_img); for(auto&& child : this->attack_set) { delete child; } this->attack_set.clear(); } void Tower::Draw() { int draw_x = circle->x - (TowerWidth[this->type]/2); int draw_y = circle->y - (TowerHeight[this->type] - (TowerWidth[this->type]/2)); al_draw_bitmap(img, draw_x, draw_y, 0); for(unsigned int i=0; i<this->attack_set.size(); i++) this->attack_set[i]->Draw(); if(isClicked) { al_draw_filled_circle(circle->x, circle->y, circle->r, al_map_rgba(196, 79, 79, 200)); al_draw_filled_circle(circle->x, circle->y, 2, al_map_rgb(0, 0, 0)); } } void Tower::SelectedTower(int mouse_x, int mouse_y, int type) { int draw_x = mouse_x - (TowerWidth[type]/2); int draw_y = mouse_y - (TowerHeight[type] - (TowerWidth[type]/2)); char filename[50]; ALLEGRO_BITMAP *bitmap; sprintf(filename, "./Tower/%s.png", TowerClass[type]); bitmap = al_load_bitmap(filename); al_draw_bitmap(bitmap, draw_x, draw_y, 0); al_draw_filled_circle(mouse_x, mouse_y, TowerRadius[type], al_map_rgba(196, 79, 79, 200)); al_draw_filled_circle(mouse_x, mouse_y, 2, al_map_rgb(0, 0, 0)); al_destroy_bitmap(bitmap); } bool Tower::DetectAttack(Monster *monster) { bool willAttack = false; Attack *attack; if(Circle::isOverlap(this->circle, monster->getCircle())) { if(attack_counter == 0) { attack = new Attack( this->circle, monster->getCircle(), this->attack_harm_point, this->attack_velocity, this->attack_img ); this->attack_set.push_back(attack); willAttack = true; } attack_counter = (attack_counter + 1) % attack_frequency; } return willAttack; } bool Tower::TriggerAttack(Monster *monster) { bool isDestroyed = false; for(unsigned int i = 0; i < this->attack_set.size(); i++) { if(Circle::isOverlap(attack_set[i]->getCircle(), monster->getCircle())) { Attack *attack = attack_set[i]; attack_set.erase(attack_set.begin()); if(monster->Subtract_HP(attack->getHarmPoint())){ isDestroyed=true; delete attack; return isDestroyed; } delete attack; /*TODO:*/ /*1. Reduce the monster HP by the harm point*/ /*2. Erase and delete the attack from attack set*/ /*3. Return true if the monster's HP is reduced to zero*/ } } return isDestroyed; } void Tower::UpdateAttack() { for(unsigned int i=0; i < this->attack_set.size(); i++) { if(!Circle::isOverlap(this->attack_set[i]->getCircle(), this->circle)) { Attack *attack = this->attack_set[i]; this->attack_set.erase(this->attack_set.begin() + i); i--; delete attack; } } }
[ "e.enyuu812@gmail.com" ]
e.enyuu812@gmail.com
2b5ee31abc318b25eeb8d4e93c9e1ad28f376782
fc74c5c7f44fbdff161b94a9bb3e2913a350a713
/Classes/Junior Year/January 2019/Project/FlowContraction v2/0.02/p
a31fc299c3447c586ac8babac2c615bfbb55ab8c
[]
no_license
cjn1012/Charlie
1158a2e1322904b28e9f523dc21048f148a14fcf
738acb4c7a8330a64619d049ae81cfefdff7b367
refs/heads/master
2021-07-17T10:53:19.810054
2020-05-03T20:40:46
2020-05-03T20:40:46
146,947,278
0
0
null
null
null
null
UTF-8
C++
false
false
9,774
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: 5.x | | \\ / A nd | Web: www.OpenFOAM.org | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ /* Windows 32 and 64 bit porting by blueCAPE: http://www.bluecape.com.pt *\ | Based on Windows porting (2.0.x v4) by Symscape: http://www.symscape.com | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volScalarField; location "0.02"; object p; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 2 -2 0 0 0 0]; internalField nonuniform List<scalar> 750 ( 0.45603963 0.45440675 0.4555517 0.45428856 0.45468421 0.45398529 0.45379337 0.45334128 0.45294807 0.45251453 0.45207014 0.45161197 0.45113954 0.4506507 0.45013973 0.44959653 0.44900445 0.44832475 0.44755453 0.44640697 0.44535684 0.44230794 0.44095325 0.43076642 0.42777543 0.45601567 0.45447072 0.45550322 0.4543227 0.45466671 0.45399535 0.45379169 0.45334403 0.45294878 0.45251558 0.452071 0.45161283 0.45114055 0.45065202 0.45014164 0.44959947 0.44900888 0.44833293 0.44756439 0.44643362 0.44537817 0.44240921 0.44101963 0.43105856 0.42795681 0.45602435 0.45449085 0.45550167 0.45433795 0.45466845 0.45400344 0.45379341 0.45334765 0.45295079 0.45251756 0.45207275 0.45161461 0.45114266 0.45065481 0.45014567 0.44960564 0.4490185 0.44834908 0.44758909 0.44648142 0.44544886 0.4425582 0.44126164 0.43138996 0.42862539 0.45604968 0.45449494 0.45551497 0.45435105 0.45467025 0.45401449 0.45379645 0.45335278 0.45295392 0.45252047 0.45207534 0.45161724 0.45114576 0.45065892 0.45015161 0.44961471 0.44903274 0.44837268 0.44762605 0.44655219 0.44555467 0.44277444 0.44163567 0.43185277 0.42970202 0.45608155 0.45450372 0.4555298 0.45437048 0.45467145 0.45402965 0.45380047 0.45335952 0.45295814 0.45252431 0.45207877 0.45162072 0.45114984 0.45066433 0.45015942 0.44962662 0.44905143 0.4484035 0.44767448 0.44664423 0.44568946 0.44305809 0.44212318 0.43248815 0.43114997 0.45611913 0.45451945 0.45554532 0.45439688 0.45467261 0.45404866 0.45380565 0.45336776 0.45296343 0.45252905 0.452083 0.45162501 0.45115487 0.45067096 0.45016898 0.44964116 0.44907423 0.44844093 0.4477335 0.44675551 0.44585191 0.44340254 0.44271089 0.43328451 0.43288933 0.45616529 0.45453671 0.455565 0.45442833 0.45467367 0.45407137 0.45381205 0.45337742 0.45296977 0.45253463 0.45208799 0.45163002 0.4511607 0.45067865 0.45018003 0.44965792 0.44910046 0.44848375 0.44780111 0.44688233 0.44603715 0.44380316 0.44338067 0.43420948 0.43499047 0.45622112 0.45455381 0.45559082 0.45446346 0.45467509 0.45409762 0.45381971 0.45338847 0.45297713 0.45254105 0.45209372 0.45163574 0.45116735 0.45068737 0.45019254 0.44967683 0.44912994 0.44853159 0.44787665 0.44702237 0.44624192 0.44425949 0.4441253 0.43525589 0.43800725 0.45627986 0.45458366 0.45561756 0.45450599 0.4546772 0.45412769 0.45382852 0.45340092 0.45298554 0.45254836 0.45210024 0.4516423 0.45117497 0.45069736 0.4502068 0.44969829 0.44916319 0.44858501 0.44796053 0.44717536 0.4464658 0.44477086 0.44496401 0.43671848 0.44239435 0.45632409 0.45466178 0.45561113 0.45457475 0.45467117 0.4541637 0.45383812 0.45341473 0.45299495 0.45255647 0.45210744 0.45164956 0.45118336 0.45070832 0.45022243 0.44972173 0.44919935 0.44864298 0.44805047 0.44734051 0.44669983 0.44535542 0.44581934 0.43899221 0.44780468 0.3993687 0.39161123 0.37006874 0.35559061 0.33828326 0.32192461 0.30539303 0.288869 0.27236692 0.25585747 0.23935037 0.22284345 0.20633645 0.18982952 0.1733226 0.15681568 0.14030876 0.12380185 0.10729493 0.090788012 0.074281097 0.05777418 0.041267267 0.024760354 0.0082534454 0.39937429 0.3915357 0.37012161 0.35555311 0.33829419 0.32191893 0.30539327 0.28886877 0.2723667 0.25585748 0.23935035 0.22284344 0.20633645 0.18982952 0.1733226 0.15681568 0.14030876 0.12380185 0.10729493 0.090788012 0.074281097 0.05777418 0.041267267 0.024760353 0.0082534448 0.39907293 0.39167614 0.37008352 0.35555335 0.33829133 0.3219156 0.30539281 0.28886823 0.27236652 0.25585742 0.23935032 0.22284343 0.20633644 0.18982952 0.1733226 0.15681568 0.14030876 0.12380185 0.10729493 0.090788012 0.074281097 0.05777418 0.041267267 0.024760352 0.0082534439 0.39854055 0.39192664 0.37000694 0.35556002 0.33828291 0.32191228 0.30539155 0.28886755 0.27236625 0.25585732 0.23935028 0.22284342 0.20633644 0.18982952 0.1733226 0.15681568 0.14030876 0.12380185 0.10729493 0.090788012 0.074281097 0.05777418 0.041267267 0.024760351 0.0082534425 0.39770599 0.39225617 0.36989767 0.35556974 0.33826935 0.3219089 0.30538949 0.28886679 0.27236593 0.2558572 0.23935023 0.2228434 0.20633643 0.18982952 0.1733226 0.15681568 0.14030876 0.12380185 0.10729493 0.090788012 0.074281097 0.05777418 0.041267267 0.02476035 0.0082534404 0.39641437 0.39266293 0.36974486 0.35558675 0.33824915 0.32190593 0.30538664 0.288866 0.27236557 0.25585704 0.23935018 0.22284338 0.20633642 0.18982951 0.1733226 0.15681568 0.14030876 0.12380185 0.10729493 0.090788012 0.074281097 0.057774179 0.041267268 0.024760348 0.0082534378 0.39478471 0.39317799 0.36955026 0.35561209 0.33822231 0.32190386 0.30538303 0.28886524 0.27236521 0.25585688 0.23935014 0.22284336 0.20633642 0.18982951 0.1733226 0.15681568 0.14030876 0.12380184 0.10729493 0.090788012 0.074281096 0.057774179 0.041267269 0.024760344 0.0082534344 0.39324347 0.39388948 0.36934866 0.35563562 0.33818989 0.32190304 0.30537864 0.28886454 0.27236485 0.2558567 0.2393501 0.22284334 0.20633641 0.18982951 0.1733226 0.15681568 0.14030876 0.12380184 0.10729493 0.090788012 0.074281096 0.057774178 0.04126727 0.024760336 0.0082534292 0.39030484 0.39474722 0.3691961 0.35564926 0.33815644 0.32190399 0.30537437 0.28886405 0.27236456 0.25585656 0.23935008 0.22284332 0.2063364 0.18982951 0.17332259 0.15681568 0.14030876 0.12380184 0.10729493 0.090788012 0.074281096 0.057774178 0.041267271 0.024760331 0.0082534256 0.38082965 0.39548318 0.36901961 0.35576454 0.33813862 0.3219095 0.30537371 0.2888642 0.27236458 0.25585655 0.23935008 0.22284332 0.20633641 0.18982951 0.17332259 0.15681568 0.14030876 0.12380184 0.10729493 0.090788012 0.074281096 0.057774178 0.041267272 0.024760348 0.0082534434 0.4563798 0.45492045 0.45547493 0.45477434 0.45463136 0.45424205 0.4538619 0.45344405 0.45301562 0.45257385 0.45212276 0.45166472 0.45120067 0.45073084 0.45025451 0.44976994 0.44927406 0.44876299 0.44823747 0.44768305 0.44717702 0.44662875 0.44738559 0.44499002 0.46064667 0.45663547 0.45508218 0.45562704 0.4549328 0.4547075 0.45433725 0.45392425 0.45349452 0.4530547 0.45260556 0.45215036 0.45169163 0.45123081 0.45076922 0.45030792 0.44984813 0.44939158 0.44894188 0.44850655 0.44809569 0.44774015 0.44748697 0.44776867 0.44625606 0.44960647 0.45692956 0.45531894 0.45580579 0.45511892 0.45481524 0.45443797 0.4540003 0.45355222 0.45309926 0.45264096 0.45218035 0.45172009 0.45126189 0.45080783 0.45036061 0.44992385 0.44950285 0.44910617 0.44874713 0.44844634 0.44823614 0.4481988 0.44851606 0.44836366 0.4509951 0.4572884 0.45562963 0.45604737 0.45533375 0.45495483 0.45454949 0.45408497 0.4536151 0.45314666 0.45267765 0.45221043 0.45174742 0.45129044 0.45084215 0.4504064 0.44998856 0.44959631 0.44924139 0.44894082 0.44871952 0.44861205 0.44869654 0.44902799 0.44928625 0.45094109 0.45773239 0.45601036 0.45633711 0.45556874 0.45511756 0.45467003 0.45417401 0.45367986 0.45319408 0.45271311 0.45223819 0.451771 0.45131337 0.45086831 0.45044021 0.45003546 0.44966326 0.44933677 0.4490744 0.44890057 0.44884706 0.44897047 0.44927989 0.44962781 0.45073399 0.45829659 0.45647115 0.45667188 0.45582056 0.45529256 0.4547939 0.4542624 0.4537425 0.45323846 0.45274477 0.45226116 0.45178847 0.45132823 0.45088331 0.45045835 0.45006011 0.44969845 0.44938695 0.44914356 0.44899089 0.44895682 0.44908139 0.44936846 0.44973448 0.45056024 0.45900889 0.45702271 0.45703832 0.456079 0.45546695 0.45491275 0.4543442 0.45379863 0.45327662 0.4527702 0.4522775 0.45179828 0.45133348 0.45088567 0.45045925 0.45006098 0.44970071 0.44939169 0.44915079 0.4489987 0.44895956 0.44906537 0.4493185 0.44966547 0.45034346 0.45999619 0.45770146 0.45742383 0.45633222 0.45562871 0.45501715 0.45441291 0.45384389 0.45330567 0.45278754 0.45228596 0.45179962 0.45132869 0.45087518 0.45044303 0.45003864 0.44967122 0.44935312 0.44910002 0.44893067 0.44886679 0.44893591 0.44914218 0.44944634 0.45005629 0.46154977 0.458463 0.45778086 0.4565349 0.45575326 0.45509274 0.45446042 0.45387356 0.45332257 0.45279469 0.45228503 0.45179126 0.45131274 0.45085076 0.45040862 0.44999183 0.44960858 0.44926996 0.4489902 0.44878595 0.44867716 0.44868977 0.44883094 0.44907193 0.44966136 0.4637943 0.45784422 0.45794629 0.45660446 0.45580593 0.4551247 0.45447822 0.4538837 0.45332655 0.45279344 0.45227898 0.45178016 0.45129589 0.45082692 0.45037602 0.44994804 0.44955029 0.44919287 0.4488889 0.44865407 0.44850689 0.44847221 0.44855194 0.44869795 0.4491566 ) ; boundaryField { inlet { type zeroGradient; } walls { type zeroGradient; } outlet { type fixedValue; value uniform 0; } centreline { type symmetryPlane; } frontAndBack { type empty; } } // ************************************************************************* //
[ "39833752+cjn1012@users.noreply.github.com" ]
39833752+cjn1012@users.noreply.github.com
81a51ba54f2e3d4d1bdac9e84950f3e5d4c9ea39
19920ea21e520da7a413d423a851e7cc43f270db
/WMS-master/WMS/build-TREKdisplay-Desktop_Qt_5_12_1_MSVC2017_32bit-Debug/debug/moc_modify_password.cpp
1eb37d941f251fb67f4b44a272f93a223a394b69
[]
no_license
519984307/wms-BASE
ab01196f15c0585ec31c6abc7cd030e7880c807d
91811aa427478b237092d68e7a78deb521497cb0
refs/heads/master
2023-03-19T21:56:36.168630
2020-10-30T07:16:47
2020-10-30T07:16:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,022
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'modify_password.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.12.1) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../../Deca/login/modify_password.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'modify_password.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.12.1. 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_modify_password_t { QByteArrayData data[5]; char stringdata0[82]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_modify_password_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_modify_password_t qt_meta_stringdata_modify_password = { { QT_MOC_LITERAL(0, 0, 15), // "modify_password" QT_MOC_LITERAL(1, 16, 23), // "on_pushButton_2_clicked" QT_MOC_LITERAL(2, 40, 0), // "" QT_MOC_LITERAL(3, 41, 18), // "displayImformation" QT_MOC_LITERAL(4, 60, 21) // "on_pushButton_clicked" }, "modify_password\0on_pushButton_2_clicked\0" "\0displayImformation\0on_pushButton_clicked" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_modify_password[] = { // content: 8, // revision 0, // classname 0, 0, // classinfo 3, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: name, argc, parameters, tag, flags 1, 0, 29, 2, 0x08 /* Private */, 3, 2, 30, 2, 0x08 /* Private */, 4, 0, 35, 2, 0x08 /* Private */, // slots: parameters QMetaType::Void, QMetaType::Void, QMetaType::QString, QMetaType::QString, 2, 2, QMetaType::Void, 0 // eod }; void modify_password::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { auto *_t = static_cast<modify_password *>(_o); Q_UNUSED(_t) switch (_id) { case 0: _t->on_pushButton_2_clicked(); break; case 1: _t->displayImformation((*reinterpret_cast< QString(*)>(_a[1])),(*reinterpret_cast< QString(*)>(_a[2]))); break; case 2: _t->on_pushButton_clicked(); break; default: ; } } } QT_INIT_METAOBJECT const QMetaObject modify_password::staticMetaObject = { { &QWidget::staticMetaObject, qt_meta_stringdata_modify_password.data, qt_meta_data_modify_password, qt_static_metacall, nullptr, nullptr } }; const QMetaObject *modify_password::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *modify_password::qt_metacast(const char *_clname) { if (!_clname) return nullptr; if (!strcmp(_clname, qt_meta_stringdata_modify_password.stringdata0)) return static_cast<void*>(this); return QWidget::qt_metacast(_clname); } int modify_password::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QWidget::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<int*>(_a[0]) = -1; _id -= 3; } return _id; } QT_WARNING_POP QT_END_MOC_NAMESPACE
[ "1335870469@qq.com" ]
1335870469@qq.com
a57117588a30ada1eb8ee556431fa7bd5e7f1c5e
a57f34a696c449c5a091edb5c57e1927a38e6064
/libdansdl/herramientas/vector_2d/vector_2d.h
5313efb6f2e1e7e88fbf0cd7e0fabcb76cbafb2b
[]
no_license
TheMarlboroMan/the-seer
4ad257473c456452f06314b3f21705f6a5dcb2b2
eaee3c4b31d568607553a888b88a2739b04cd552
refs/heads/master
2021-05-15T04:08:59.374274
2021-05-11T11:09:23
2021-05-11T11:09:23
119,861,400
1
0
null
null
null
null
UTF-8
C++
false
false
1,232
h
#ifndef VECTOR_2D_H #define VECTOR_2D_H #include <cmath> namespace DLibH { struct Vector_2d { float x; float y; Vector_2d(): x(0.f), y(0.f) {} Vector_2d(const Vector_2d& o): x(o.x), y(o.y) {} Vector_2d(float p_x, float p_y):x(p_x), y(p_y) {} Vector_2d operator+(const Vector_2d &otro); Vector_2d operator-(const Vector_2d &otro); Vector_2d operator*(const Vector_2d &otro); Vector_2d operator/(const Vector_2d &otro); Vector_2d& operator=(const Vector_2d &otro); Vector_2d& operator+=(const Vector_2d &otro); Vector_2d& operator-=(const Vector_2d &otro); Vector_2d& operator*=(const Vector_2d &otro); Vector_2d& operator/=(const Vector_2d &otro); Vector_2d& operator*(const float p_multiplicador); Vector_2d& operator/(const float p_divisor); Vector_2d& operator*=(const float p_multiplicador); Vector_2d& operator/=(const float p_divisor); void normalizar(); float longitud(); static float obtener_angulo_para_vector_unidad_radianes(const Vector_2d&); static float obtener_angulo_para_vector_unidad_grados(const Vector_2d&); static Vector_2d obtener_para_puntos(float p_xa, float p_ya, float p_xb, float p_yb); static Vector_2d vector_unidad_para_angulo(float); }; } //Fin namespace DLibH #endif
[ "marlborometal@gmail.com" ]
marlborometal@gmail.com
274c19ee00d3077f5504619c7ee861ae07389b3d
88e767888471c22af6f04480af4cc4a06d351a2d
/Payment_System/Client/mainwindow.h
9b3da06510a19fd36489f9025c93b2988270be24
[]
no_license
MykhailoMaidan/Lab_University
f8be7f1e336ccfddafde5dee5b02bb3ccf416958
cba75898b31b6198173f8a4b927e3c187892c272
refs/heads/master
2021-01-20T19:33:29.770994
2016-06-22T10:26:31
2016-06-22T10:26:31
61,702,912
0
0
null
null
null
null
UTF-8
C++
false
false
822
h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include "payment.h" #include "clientsocket.h" namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); private slots: void on_water_pushButton_clicked(); void on_gas_pushButton_clicked(); void on_power_pushButton_clicked(); void on_rubbish_pushButton_clicked(); void on__Intercom_pushButton_clicked(); void on_Internet_pushButton_clicked(); void on_elevator_pushButton_clicked(); void on_telephone_pushButton_clicked(); void on_heating_pushButton_clicked(); void on_pushButton_clicked(); private: Ui::MainWindow *ui; Payment* window; ClientSocket* socket; }; #endif // MAINWINDOW_H
[ "nikolasosvordl@gmail.com" ]
nikolasosvordl@gmail.com
e55df33b5696e3fe73893b6ab198c80aee209706
58e65f021f19b09ce435e02f07085e956ec9d3d3
/2darray/quiz.cpp
fb13db44af81c577bd75fdda39a172953014e844
[]
no_license
sagarr70/coding-blocks-launchpad
58ecafad992d5a387fe60cff791a3b4335eeb9ad
0470c30e9c63f9df6606b3a18b34e9036e1b9281
refs/heads/master
2022-12-10T13:39:33.572265
2020-09-14T06:19:21
2020-09-14T06:19:21
268,731,038
1
0
null
null
null
null
UTF-8
C++
false
false
138
cpp
#include<iostream> using namespace std; int main(){ int a[]={1,2,3}; int *p=a; cout<<a[*p++]<<" "<<(*++p)[a]; return 0; }
[ "sagar_aggarwal@outlook.com" ]
sagar_aggarwal@outlook.com
e7d237560d744ce2a0352588607bef74526c2619
d52b9a9e1838189d6b324704865ca6badec1dd79
/C/NAA42C/LANGS/PASCAL/NAAMATH.INC
1f4df3efff039639b0a3b240c0aadecba9a9be2c
[ "Unlicense" ]
permissive
htoomey/WyzAnt
c3c7ac286f7ac4ac91c803d8e7be9560b39efabc
6db59fb3d9df88cc0df6687b8090995dd7b2f434
refs/heads/main
2023-03-11T16:59:13.547143
2021-02-28T19:55:49
2021-02-28T19:55:49
337,597,520
0
0
null
null
null
null
UTF-8
C++
false
false
15,796
inc
(******************************* NAAMATH.INC ********************************** "Numerical Analysis Algorithms in Pascal" Math Procedures v4.0 ******************************************************************************) (* This include file contains many functions that are not part of the PASCAL language but are implemented in other languages. Only the functions that involve floating-point numbers (i.e. - REAL, float, double, DOUBLE PRECISION) are implemented. These functions may be cut-and-pasted from this file and placed into your programs as need, or you can include them all inside every program by leaving the line "{$I NAAMATH.INC}" inside the programs as they now stand. These functions are not in perfect alphabetical order, since some of the functions call upon others (such as POW()), making their implementation easier and more readable. WARNING: If using Turbo Pascal, do not compile with TURBOBCD.COM. (Sqrt, Sin, and similar operations are nor implemented in the BCD version.) Use TURBO.COM to compile. VARIABLES USED: COMPILERS COMPARED: I, R, X, Y : REAL; Microsoft C 5.0 N : INTEGER; Microsoft FORTRAN77 v3.3 C : COMPLEX_TYPE; Borland Turbo PASCAL 3.02A ??? ADA FUNCTIONS ANSI MSC FORTRAN Pascal Conflict with C C 77 ADA PASCAL another language ------------------------------------------------------------------------------- ABS(X) X ACOS(X) X X X AINT(X) X ANINT(X) X ARCCOS(X) ARCSIN(X) ARCTAN(X) X ASIN(X) X X X ATAN(X) X X X (X) ATAN2(X,Y) X X X CABS(C) X X CEIL(X) X X COS(X) X X X X COSH(X) X X X DIM(X) X EXP(X) X X X X FABS(X) X X FLOOR(X) X X FMOD(X,Y) X X FREXP(X,N) X X HYPOT(X,Y) X J0(X) X J1(X) X JN(N,X) X LDEXP(X,N) X X LN(X) X LOG(X) X X X (X) C, FORTRAN LOG10(X) X X X MOD(X) X X FORTRAN Function MODF(X,*N) X X NOT IMPLIMENTED NINT(X) X POW(X,Y) X X PWROFTEN(N) X ROUND(X) X SIN(X) X X X X SINH(X) X X X SQR(X) X SQRT(X) X X X X TAN(X) X X X TANH(X) X X X TRUNC(X) X Y0(X) X Y1(X) X YN(N,X) X *) (****************************************************************************** TYPE DEFINITION: Complex_type. For complex numbers. ******************************************************************************) TYPE COMPLEX_TYPE = RECORD R, I : REAL END; (****************************************************************************** FUNCTION ATAN2(y, x): Arctangent [-PI, PI]. Used in C and FORTRAN 77. ******************************************************************************) FUNCTION ATAN2(y, x : REAL) : REAL; CONST PI = 3.1415926535897932384626433832795; BEGIN IF x = 0.0 THEN (* For the asymptotes at PI/2 and -PI/2. *) BEGIN IF y >= 0.0 THEN ATAN2 := PI / 2.0 ELSE ATAN2 := -PI / 2.0 END ELSE IF x > 0.0 THEN (* For quadrants I and IV. *) ATAN2 := ARCTAN(Y/X) ELSE IF y >= 0.0 THEN (* For quadrant II. *) ATAN2 := ARCTAN(Y/X) + PI ELSE (* For quadrant III. *) ATAN2 := ARCTAN(Y/X) - PI END; (****************************************************************************** FUNCTION ACOS(x): Arccosine [0, PI]. Used in C and FORTRAN 77. ******************************************************************************) FUNCTION ACOS(x : REAL) : REAL; VAR theta, y : REAL; BEGIN IF ((x < -1.0) OR (x > 1.0)) THEN (* x must be between -1 and 1. *) naaerror('RANGE ERROR - x must be between -1 and 1 with ACOS().'); IF x = 0.0 THEN (* Special case: For theta = 90 degrees. *) ACOS := 3.1415926535897932384626433832795 / 2.0; y := SQRT(1.0 - SQR(x)); theta := ARCTAN(y / x); IF theta > 0.0 THEN (* For quadrant I. *) ACOS := theta ELSE (* For quadrant II (from quadrant IV). *) ACOS := theta + 3.1415926535897932384626433832795 END; (****************************************************************************** FUNCTION AINT(x): Truncation. Used in FORTRAN 77. ******************************************************************************) FUNCTION AINT(x : REAL) : REAL; BEGIN AINT := TRUNC(x) END; (****************************************************************************** FUNCTION ANINT(x): Nearest whole number. Used in FORTRAN 77. ******************************************************************************) FUNCTION ANINT(x : REAL) : REAL; BEGIN ANINT := ROUND(x) END; (****************************************************************************** FUNCTION ARCCOS(x): Arccosine [0, PI]. ******************************************************************************) FUNCTION ARCCOS(x : REAL) : REAL; BEGIN ARCCOS := ACOS(x) END; (****************************************************************************** FUNCTION ASIN(x): Arcsine [-PI/2, PI/2]. Used in C and FORTRAN 77. ******************************************************************************) FUNCTION ASIN(x : REAL) : REAL; VAR y : REAL; (* Think of x as y and y as x. *) BEGIN IF ((x < -1.0) OR (x > 1.0)) THEN (* x must be between -1 and 1. *) naaerror('RANGE ERROR - x must be between -1 and 1 with ASIN().'); y := SQRT(1.0 - SQR(x)); ASIN := ARCTAN(x / y) (* For quadrants I and IV. *) END; (****************************************************************************** FUNCTION ARCSIN(x): Arcsine [-PI/2, PI/2]. ******************************************************************************) FUNCTION ARCSIN(x : REAL) : REAL; BEGIN ARCSIN := ASIN(x) END; (****************************************************************************** FUNCTION ATAN(x): Arctangent [-PI/2, PI/2]. Used in C and FORTRAN 77. ******************************************************************************) FUNCTION ATAN(x : REAL) : REAL; BEGIN ATAN := ARCTAN(x) END; (****************************************************************************** FUNCTION CABS(r,i): Complex absolute value. Used in MSC and FORTRAN 77. ******************************************************************************) FUNCTION CABS(c : COMPLEX_TYPE) : REAL; BEGIN CABS := SQRT(SQR(c.r) + SQR(c.i)) END; (****************************************************************************** FUNCTION CEIL(x): Smallest integer not less than x. Used in C. ******************************************************************************) FUNCTION CEIL(x : REAL) : REAL; VAR tmp : REAL; BEGIN tmp := x - TRUNC(x); IF tmp = 0.0 THEN (* x is already an integer. *) CEIL := x ELSE IF x > 0.0 THEN (* For positive x. *) CEIL := TRUNC(x) + 1.0 ELSE (* For negative x. *) CEIL := TRUNC(x) END; (****************************************************************************** FUNCTION COSH(x): Hyperbolic Cosine. Used in C and FORTRAN 77. ******************************************************************************) FUNCTION COSH(x : REAL) : REAL; BEGIN COSH := (EXP(x) + EXP(-x)) / 2.0 END; (****************************************************************************** FUNCTION DIM(x): Positive difference. Used in FORTRAN 77. ******************************************************************************) FUNCTION DIM(x, y : REAL) : REAL; VAR tmp : REAL; BEGIN tmp := x - y; IF tmp >= 0.0 THEN DIM := tmp ELSE DIM := 0.0 END; (****************************************************************************** FUNCTION FABS(x): Absolute value of a float. Used in C. ******************************************************************************) FUNCTION FABS(x : REAL) : REAL; BEGIN FABS := ABS(x) END; (****************************************************************************** FUNCTION FLOOR(x): Largest integer not greater than x. Used in C. ******************************************************************************) FUNCTION FLOOR(x : REAL) : REAL; VAR tmp : REAL; BEGIN tmp := x - TRUNC(x); IF tmp = 0.0 THEN (* x is already an integer. *) FLOOR := x ELSE IF x > 0.0 THEN (* For positive x. *) FLOOR := TRUNC(x) ELSE (* For negative x. *) FLOOR := TRUNC(x) - 1.0 END; (****************************************************************************** FUNCTION FMOD(x, y): Floating-point remainder w/sign of x. Used in C. ******************************************************************************) FUNCTION FMOD(x, y : REAL) : REAL; VAR remainder : REAL; BEGIN IF y = 0.0 THEN (* An ambiguous case. *) FMOD := 0.0 ELSE BEGIN remainder := x / y; remainder := remainder - TRUNC(remainder); IF x >= 0.0 THEN (* For positive x. *) FMOD := ABS(remainder) ELSE (* For negative x. *) FMOD := -ABS(remainder) END END; (****************************************************************************** FUNCTION HYPOT(x,y): Hypotenuse or SQRT(SQR(x) + SQR(y)). Used in C. ******************************************************************************) FUNCTION HYPOT(x, y : REAL) : REAL; BEGIN HYPOT := SQRT(SQR(x) + SQR(y)) END; (****************************************************************************** FUNCTION J0(x): Bessel function of first kind (order 0). Used in MSC. ******************************************************************************) (* Not implemented yet. *) (****************************************************************************** FUNCTION J1(x): Bessel function of first kind (order 1). Used in MSC. ******************************************************************************) (* Not implemented yet. *) (****************************************************************************** FUNCTION JN(x): Bessel function of first kind (order n). Used in MSC. ******************************************************************************) (* Not implemented yet. *) (****************************************************************************** FUNCTION LDEXP(x, n): Computes x * 2^n. Used in C. ******************************************************************************) FUNCTION LDEXP(x : REAL; n : INTEGER) : REAL; VAR tmp, i : INTEGER; BEGIN IF n < 0 THEN (* For Negative n. *) LDEXP := 0.0 ELSE IF n = 0 THEN (* For zero n. *) LDEXP := x ELSE (* For Positive n. *) BEGIN tmp := 1; FOR i := 1 to n DO tmp := tmp * 2; LDEXP := x * tmp END END; (****************************************************************************** FUNCTION LOG10(x): Logorithm to base 10. Used in C and FORTRAN 77. ******************************************************************************) FUNCTION LOG10(x : REAL) : REAL; BEGIN LOG10 := LN(x) / LN(10.0) END; (****************************************************************************** FUNCTION MODF(x, y): Like FMOD but saves quotient too. Used in C. ******************************************************************************) (* Not implemented. Use FMOD(). *) (****************************************************************************** FUNCTION NINT(x): Nearest integer. Used in FORTRAN 77. ******************************************************************************) FUNCTION NINT(x : REAL) : REAL; BEGIN NINT := ROUND(x) END; (****************************************************************************** FUNCTION POW(x,y): Returns X^Y (X raised to the Y power). ******************************************************************************) FUNCTION POW(x, y : REAL) : REAL; BEGIN IF y = 0.0 THEN (* Anything raised to the 0 power equals 1. *) POW := 1.0 ELSE IF x = 0.0 THEN BEGIN IF (y > 0.0) THEN (* 0 raised to any positive power equals 0. *) POW := 0.0 ELSE (* Domain error since x=0 and y <= 0. *) naaerror('DOMAIN ERROR - Can not solve 0^(-y) in POW().') END ELSE IF x > 0.0 THEN (* For positive x. *) POW := EXP(y * LN(x)) ELSE (* For negative x. *) BEGIN IF (y - TRUNC(y)) <> 0.0 THEN (* ERROR - y is not an integer. *) BEGIN naaerror('ERROR - Can`t solve x^(-y) in POW(). y isn`t an integer.'); halt END ELSE IF ODD(TRUNC(y)) THEN POW := -EXP(y * LN(-x)) (* For y odd integers. *) ELSE POW := EXP(y * LN(-x)) (* For y even integers. *) END END; (****************************************************************************** FUNCTION FREXP(x, n): Creates m*2^n where m = [1/2..1]. Used in C. ******************************************************************************) (* n is never returned, but it is calculated. *) FUNCTION FREXP(x : REAL; n : INTEGER) : REAL; BEGIN IF x = 0.0 THEN BEGIN n := 0; FREXP := 0.0 END ELSE IF x < 0.0 THEN n := TRUNC(LN(-x) / LN(2.0)) ELSE n := TRUNC(LN(x) / LN(2.0)); IF x > 0.0 THEN BEGIN IF POW(2.0, (1.0 * n)) = x THEN FREXP := 1.0 ELSE BEGIN n := n + 1; FREXP := x / POW(2.0, (1.0 * n)) END END ELSE BEGIN IF (-POW(2.0, (1.0 * n)) = x) THEN FREXP := -1.0 ELSE BEGIN n := n + 1; FREXP := x / POW(2.0, (1.0 * n)) END END END; (****************************************************************************** FUNCTION SINH(x): Hyperbolic Sine. Used in C and FORTRAN 77. ******************************************************************************) FUNCTION SINH(x : REAL) : REAL; BEGIN SINH := (EXP(x) - EXP(-x)) / 2.0 END; (****************************************************************************** FUNCTION TAN(x): Tangent. Used in C, ADA, and FORTRAN 77. ******************************************************************************) FUNCTION TAN(x : REAL) : REAL; BEGIN TAN := SIN(x) / COS(x) END; (****************************************************************************** FUNCTION TANH(x): Hyperbolic Tangent. Used in C and FORTRAN 77. ******************************************************************************) FUNCTION TANH(x : REAL) : REAL; VAR tmp1, tmp2 : REAL; BEGIN tmp1 := EXP(x); tmp2 := EXP(-x); TANH := (tmp1 - tmp2) / (tmp1 + tmp2) END; (****************************************************************************** FUNCTION Y0(x): Bessel function of second kind (order 0). Used in MSC. ******************************************************************************) (* Not implemented yet. *) (* x must be positive. *) (****************************************************************************** FUNCTION Y1(x): Bessel function of second kind (order 1). Used in MSC. ******************************************************************************) (* Not implemented yet. *) (* x must be positive. *) (****************************************************************************** FUNCTION YN(x): Bessel function of second kind (order n). Used in MSC. ******************************************************************************) (* Not implemented yet. *) (* x must be positive. *) (****************************************************************************** * Written by: Harold A. Toomey, CARE-FREE SOFTWARE, 2Q 1991, v4.0 * * Copyright (C) 1991, Harold A. Toomey, All Rights Reserved. * ******************************************************************************) 
[ "noreply@github.com" ]
htoomey.noreply@github.com
cc8d79158ae1486f03c653aa52af8856031c9262
50d208d2afbffcb64545055eaf59c112dfa68bca
/Prog/src/Date.h
d09861badddb184cb6ae376f1830db26ecd0f274
[]
no_license
leonardo-faria/PROG1314
1ba36d1141a0c06cf8e1d0e65f3def8cf986b17c
f1686b38774753ad17f4b542ae0894d237afc5e2
refs/heads/master
2021-01-02T08:52:11.916347
2014-06-02T14:39:59
2014-06-02T14:39:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,529
h
#ifndef _DATE #define _DATE #include <iostream> #include <string> #include <vector> using namespace std; template<class T> int member(vector<T> v, T e); class Date { string weekDay; unsigned int hour; unsigned int minutes; static vector<string> week; public: static vector<string> getWeek(); static Date currentDate(); static void init(); Date() { } ; Date(string day, unsigned int hour, unsigned int minutes); const string& getWeekDay() const { return weekDay; } const bool operator<(const Date d) const { if (member(week, weekDay) != member(week, d.weekDay)) return member(week, weekDay) < member(week, d.weekDay); if (hour != d.hour) return hour < d.hour; return (minutes < d.minutes); } const bool operator>(const Date d) const { if (member(week, weekDay) != member(week, d.weekDay)) return member(week, weekDay) > member(week, d.weekDay); if (hour != d.hour) return hour > d.hour; return (minutes > d.minutes); } void operator=(const Date &d) { this->hour = d.hour; this->minutes = d.minutes; this->weekDay = d.weekDay; } const Date operator+(const int &d) const { string day = weekDay; // if ((hour + (d / 60)) / 24 > 0) { // for (int i = 0; i < week.size(); ++i) { // if (weekDay == week[i] && i < week.size() - 1) { // day = week[i + 1]; // break; // } // } // } return Date(day, hour + (d / 60), minutes + d % 60); } unsigned int getHour() const { return hour; } unsigned int getMinutes() const { return minutes; } }; #endif
[ "leonardofaria94@gmail.com" ]
leonardofaria94@gmail.com
7bf10b8bf11299c667a112aa47ffcfeb0fc16164
45c84e64a486a3c48bd41a78e28252acbc0cc1b0
/src/services/tracing/perfetto/test_utils.h
89e0f1b370ccf117b04a275e3471d31f36e02d9f
[ "BSD-3-Clause", "MIT" ]
permissive
stanleywxc/chromium-noupdator
47f9cccc6256b1e5b0cb22c598b7a86f5453eb42
637f32e9bf9079f31430c9aa9c64a75247993a71
refs/heads/master
2022-12-03T22:00:20.940455
2019-10-04T16:29:31
2019-10-04T16:29:31
212,851,250
1
2
MIT
2022-11-17T09:51:04
2019-10-04T15:49:33
null
UTF-8
C++
false
false
7,232
h
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef SERVICES_TRACING_PERFETTO_TEST_UTILS_H_ #define SERVICES_TRACING_PERFETTO_TEST_UTILS_H_ #include <memory> #include <string> #include <vector> #include "mojo/public/cpp/bindings/receiver.h" #include "services/tracing/perfetto/producer_host.h" #include "services/tracing/public/cpp/perfetto/perfetto_traced_process.h" #include "services/tracing/public/cpp/perfetto/producer_client.h" #include "third_party/perfetto/include/perfetto/ext/tracing/core/consumer.h" #include "third_party/perfetto/include/perfetto/tracing/core/trace_config.h" #include "third_party/perfetto/protos/perfetto/common/observable_events.pb.h" namespace base { class RunLoop; } namespace tracing { const char kPerfettoTestString[] = "d00df00d"; const size_t kLargeMessageSize = 1 * 1024 * 1024; class TestDataSource : public PerfettoTracedProcess::DataSourceBase { public: static std::unique_ptr<TestDataSource> CreateAndRegisterDataSource( const std::string& data_source_name, size_t send_packet_count); ~TestDataSource() override; void WritePacketBigly(); // DataSourceBase implementation void StartTracing( PerfettoProducer* producer, const perfetto::DataSourceConfig& data_source_config) override; void StopTracing( base::OnceClosure stop_complete_callback = base::OnceClosure()) override; void Flush(base::RepeatingClosure flush_complete_callback) override; const perfetto::DataSourceConfig& config() { return config_; } // In some tests we violate the assumption that only a single tracing session // is alive. This allows tests to explicitly ignore the DCHECK in place to // check this. void SetSystemProducerToNullptr() { producer_ = nullptr; } void set_send_packet_count(size_t count) { send_packet_count_ = count; } void set_start_tracing_callback(base::OnceClosure start_tracing_callback); private: TestDataSource(const std::string& data_source_name, size_t send_packet_count); size_t send_packet_count_; perfetto::DataSourceConfig config_; base::OnceClosure start_tracing_callback_ = base::OnceClosure(); }; class MockProducerClient : public ProducerClient { public: MockProducerClient( uint32_t num_data_sources = 0, base::OnceClosure client_enabled_callback = base::OnceClosure(), base::OnceClosure client_disabled_callback = base::OnceClosure()); ~MockProducerClient() override; void SetupDataSource(const std::string& data_source_name); void StartDataSource(uint64_t id, const perfetto::DataSourceConfig& data_source_config, StartDataSourceCallback callback) override; void StopDataSource(uint64_t id, StopDataSourceCallback callback) override; void CommitData(const perfetto::CommitDataRequest& commit, CommitDataCallback callback = {}) override; void SetAgentEnabledCallback(base::OnceClosure client_enabled_callback); void SetAgentDisabledCallback(base::OnceClosure client_disabled_callback); const std::string& all_client_commit_data_requests() const { return all_client_commit_data_requests_; } private: uint32_t num_data_sources_active_ = 0; uint32_t num_data_sources_expected_; base::OnceClosure client_enabled_callback_; base::OnceClosure client_disabled_callback_; std::string all_client_commit_data_requests_; std::unique_ptr<ProducerClient> old_producer_; }; class MockConsumer : public perfetto::Consumer { public: using PacketReceivedCallback = std::function<void(bool)>; MockConsumer(std::vector<std::string> data_source_names, perfetto::TracingService* service, PacketReceivedCallback packet_received_callback); MockConsumer(std::vector<std::string> data_source_names, perfetto::TracingService* service, PacketReceivedCallback packet_received_callback, const perfetto::TraceConfig& config); ~MockConsumer() override; void ReadBuffers(); void StopTracing(); void StartTracing(); void FreeBuffers(); size_t received_packets() const { return received_packets_; } size_t received_test_packets() const { return received_test_packets_; } // perfetto::Consumer implementation void OnConnect() override; void OnDisconnect() override; void OnTracingDisabled() override; void OnTraceData(std::vector<perfetto::TracePacket> packets, bool has_more) override; void OnDetach(bool success) override; void OnAttach(bool success, const perfetto::TraceConfig&) override; void OnTraceStats(bool success, const perfetto::TraceStats&) override; void OnObservableEvents(const perfetto::ObservableEvents&) override; void WaitForAllDataSourcesStarted(); void WaitForAllDataSourcesStopped(); private: struct DataSourceStatus { std::string name; perfetto::ObservableEvents::DataSourceInstanceStateChange:: DataSourceInstanceState state; }; void CheckForAllDataSourcesStarted(); void CheckForAllDataSourcesStopped(); std::unique_ptr<perfetto::TracingService::ConsumerEndpoint> consumer_endpoint_; size_t received_packets_ = 0; size_t received_test_packets_ = 0; PacketReceivedCallback packet_received_callback_; std::vector<DataSourceStatus> data_sources_; base::RunLoop* on_started_runloop_ = nullptr; base::RunLoop* on_stopped_runloop_ = nullptr; perfetto::TraceConfig trace_config_; }; class MockProducerHost : public ProducerHost { public: MockProducerHost( const std::string& producer_name, const std::string& data_source_name, perfetto::TracingService* service, MockProducerClient* producer_client, base::OnceClosure datasource_registered_callback = base::OnceClosure()); ~MockProducerHost() override; void RegisterDataSource( const perfetto::DataSourceDescriptor& registration_info) override; void OnConnect() override; void OnCommit(const perfetto::CommitDataRequest& commit_data_request); const std::string& all_host_commit_data_requests() const { return all_host_commit_data_requests_; } protected: const std::string producer_name_; base::OnceClosure datasource_registered_callback_; std::string all_host_commit_data_requests_; mojo::Receiver<mojom::ProducerHost> receiver_{this}; }; class MockProducer { public: MockProducer(const std::string& producer_name, const std::string& data_source_name, perfetto::TracingService* service, base::OnceClosure on_datasource_registered, base::OnceClosure on_tracing_started, size_t num_packets = 10); virtual ~MockProducer(); void WritePacketBigly(base::OnceClosure on_write_complete); MockProducerClient* producer_client() { return producer_client_.get(); } TestDataSource* data_source() { return data_source_.get(); } private: std::unique_ptr<TestDataSource> data_source_; std::unique_ptr<MockProducerClient> producer_client_; std::unique_ptr<MockProducerHost> producer_host_; }; } // namespace tracing #endif // SERVICES_TRACING_PERFETTO_TEST_UTILS_H_
[ "stanley@moon.lan" ]
stanley@moon.lan
64965cb88d93caa4225c826934513008ce5ae3ce
7396a56d1f6c61b81355fc6cb034491b97feb785
/algorithms/kernel/kmeans/kmeans_init_csr_random_distr_step1_fpt_dispatcher.cpp
7afd1504b844b823e35143749fd898f0bd782e5e
[ "Apache-2.0", "Intel" ]
permissive
francktcheng/daal
0ad1703be1e628a5e761ae41d2d9f8c0dde7c0bc
875ddcc8e055d1dd7e5ea51e7c1b39886f9c7b79
refs/heads/master
2018-10-01T06:08:39.904147
2017-09-20T22:37:02
2017-09-20T22:37:02
119,408,979
0
0
null
2018-01-29T16:29:51
2018-01-29T16:29:51
null
UTF-8
C++
false
false
2,594
cpp
/* file: kmeans_init_csr_random_distr_step1_fpt_dispatcher.cpp */ /******************************************************************************* * Copyright 2014-2017 Intel Corporation * All Rights Reserved. * * If this software was obtained under the Intel Simplified Software License, * the following terms apply: * * The source code, information and material ("Material") contained herein is * owned by Intel Corporation or its suppliers or licensors, and title to such * Material remains with Intel Corporation or its suppliers or licensors. The * Material contains proprietary information of Intel or its suppliers and * licensors. The Material is protected by worldwide copyright laws and treaty * provisions. No part of the Material may be used, copied, reproduced, * modified, published, uploaded, posted, transmitted, distributed or disclosed * in any way without Intel's prior express written permission. No license under * any patent, copyright or other intellectual property rights in the Material * is granted to or conferred upon you, either expressly, by implication, * inducement, estoppel or otherwise. Any license under such intellectual * property rights must be express and approved by Intel in writing. * * Unless otherwise agreed by Intel in writing, you may not remove or alter this * notice or any other notice embedded in Materials by Intel or Intel's * suppliers or licensors in any way. * * * If this software was obtained under the Apache License, Version 2.0 (the * "License"), the following terms apply: * * 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. *******************************************************************************/ /* //++ // Implementation of K-means initialization algorithm container for CSR // methods //-- */ #include "kmeans_init_container.h" namespace daal { namespace algorithms { namespace interface1 { __DAAL_INSTANTIATE_DISPATCH_CONTAINER(kmeans::init::DistributedContainer, distributed, step1Local, DAAL_FPTYPE, kmeans::init::randomCSR) } } // namespace daal::algorithms } // namespace daal
[ "vasily.rubtsov@intel.com" ]
vasily.rubtsov@intel.com
3b88fe4a9de41a4edbda62328e4e338c3d02751d
6fdb3a506e9482ac68bfcbfbed6a90f0eefaf7a8
/Lab 10/Queue.cpp
281603f5059d63a6e54b1ccd60773404100b8d23
[]
no_license
rlam15/CSE-30
424a4db44b1b8070aadea6efb9d9257d758353be
40d2821dace23b0d4beee0b3f035a74e128ef3ce
refs/heads/master
2020-03-12T19:49:25.026865
2018-04-26T17:18:39
2018-04-26T17:18:39
130,792,413
0
0
null
null
null
null
UTF-8
C++
false
false
318
cpp
#include "Queue.h" #include "LinkedList.h" Queue::Queue(){} Queue::~Queue(){} void Queue::enqueue(int val) { insertAtBack(val); } int Queue::dequeue() { if(isEmpty()) throw 1; int val = getFrontRef(); removeFromFront(); return val; } int& Queue::front() { if(isEmpty()) throw 0; return getFrontRef(); }
[ "randylam@Randys-MacBook-Pro-2.local" ]
randylam@Randys-MacBook-Pro-2.local
812dee549033f0bf466f0f23e42a072c0b006860
4d4822b29e666cea6b2d99d5b9d9c41916b455a9
/Example/Pods/Headers/Private/GeoFeatures/boost/range/iterator_range_core.hpp
a026bd4b86c8ec1354f11b95ca1a5f8a5d76d785
[ "BSL-1.0", "Apache-2.0" ]
permissive
eswiss/geofeatures
7346210128358cca5001a04b0e380afc9d19663b
1ffd5fdc49d859b829bdb8a9147ba6543d8d46c4
refs/heads/master
2020-04-05T19:45:33.653377
2016-01-28T20:11:44
2016-01-28T20:11:44
50,859,811
0
0
null
2016-02-01T18:12:28
2016-02-01T18:12:28
null
UTF-8
C++
false
false
68
hpp
../../../../../../../GeoFeatures/boost/range/iterator_range_core.hpp
[ "hatter24@gmail.com" ]
hatter24@gmail.com
c777e0a5d609b5e24cddbe7a6a358781579752dd
30657278fc951ba486d782a0f89ade4fed3037f9
/informatik3/dateClass/main.cpp
e3d02087d5b6b51addcdd44a0fb04d17cc4614ab
[]
no_license
mschaufe/FHGR
fe028793fb288439edc8fb4f9e5beb3a66173289
7d368b280eb65e72736ecfc0d91e9a88f8bc17bc
refs/heads/master
2023-01-24T07:22:58.875767
2020-11-26T09:01:31
2020-11-26T09:01:31
153,422,956
1
0
null
null
null
null
UTF-8
C++
false
false
583
cpp
/***************************** * Marc Schaufelberger * * FHGR * * 22. Okt 2019 * * Exercise 2.1: Date Class * ******************************/ #include <iostream> #include "date.h" int main() { Date d1; d1.setYear(2000); d1.setMonth(2); d1.setDay(1); d1.print(); std::cout << "\n"; Date d2(2000,3,3); d2.print(); std::cout << "\n"; std::cout << d1.daysSince2000() << "\n"; std::cout << d2.daysSince2000() << "\n"; std::cout << d1.daysUntil(&d2) << "\n"; std::cout << d2.daysUntil(&d1) << "\n"; return 0; }
[ "marc@schufi.ch" ]
marc@schufi.ch
7b8cd442f3c98a90ea334a1b86441155d2fcdfa1
d96607cdf79c4f3818788cfe2bef9888a49d56a8
/C++ How to Program/Chapter_16/Fig-16.2.cpp
d266cae6fd1510b7ce3cbfa4c4deb7a450a16983
[]
no_license
dasanchez/hellocpp
41646533ee826e59841b25961b5ff6dc93b3487d
3b37c21d4f864686ba0c5fe60f4939ea06d91cda
refs/heads/master
2021-06-02T08:56:46.201450
2020-09-28T03:16:20
2020-09-28T03:16:20
126,009,535
0
0
null
2018-08-12T21:02:20
2018-03-20T11:51:02
C++
UTF-8
C++
false
false
1,499
cpp
// Fig 16.2 A simple exception-handling example that checks for // divide-by-zero exceptions. #include <iostream> #include "DivideByZeroException.h" using namespace std; // perform division and throw DivideByZeroException object if // divide-by-zero exception occurs double quotient(int numerator, int denominator) { // throw DivideByZeroExceptioinn object if // divide-by-zero exception occurs if (denominator == 0) throw DivideByZeroException(); // terminate function // return division result return static_cast<double>(numerator) / denominator; } // end function quotient int main() { int number1; // user-specified numerator int number2; // user-specified denominator double result; // result of division cout << "Enter two integers (end-of-file to end): "; // enable user to enter two integers to divide while (cin >> number1 >> number2 ) { // try block contains code that might throw exception // and code that will not execute if an exception occurs try { result = quotient(number1, number2); cout << "The quotient is: " << result << endl; } // end try catch(DivideByZeroException &divideByZeroException) { cout << "Exception occurred: " << divideByZeroException.what() << endl; } // end catch cout << "\nEnter two integers (end-of-file to end): "; } // end while cout << endl; } // end main
[ "dante.a.sanchez@gmail.com" ]
dante.a.sanchez@gmail.com
1e700650c944a83ee10788a89f8b7e43eef22c4b
f7596a3deef02c201d54cbf0f6152abd729cdf7f
/src/coincontrol.h
e628dd931905678a0d173bb0855b45b63726121f
[ "MIT" ]
permissive
zeurocoin-dev/zeurocoin
47c641beea4001259cfdeb615f56a0e6afc3a1ea
f3155eaeeca8fd7362017caba39e7a41523cd9f4
refs/heads/master
2021-01-19T07:15:19.742455
2017-04-07T09:59:44
2017-04-07T09:59:44
87,531,929
0
1
null
2017-09-02T21:25:44
2017-04-07T09:56:37
C++
UTF-8
C++
false
false
1,343
h
// Copyright (c) 2011-2013 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_COINCONTROL_H #define BITCOIN_COINCONTROL_H #include "primitives/transaction.h" /** Coin Control Features. */ class CCoinControl { public: CTxDestination destChange; bool useNitroSend; bool useInstantX; CCoinControl() { SetNull(); } void SetNull() { destChange = CNoDestination(); setSelected.clear(); useInstantX = false; useNitroSend = true; } bool HasSelected() const { return (setSelected.size() > 0); } bool IsSelected(const uint256& hash, unsigned int n) const { COutPoint outpt(hash, n); return (setSelected.count(outpt) > 0); } void Select(const COutPoint& output) { setSelected.insert(output); } void UnSelect(const COutPoint& output) { setSelected.erase(output); } void UnSelectAll() { setSelected.clear(); } void ListSelected(std::vector<COutPoint>& vOutpoints) { vOutpoints.assign(setSelected.begin(), setSelected.end()); } private: std::set<COutPoint> setSelected; }; #endif // BITCOIN_COINCONTROL_H
[ "coinbitex@coinbitex.local" ]
coinbitex@coinbitex.local
40a429ae8f4d66fd14d3d6754fbc9dab3a24d17e
21f8a6f018748aa714bd63d68944d6474f011781
/coverage_wss/vrep_ros_interface/devel/include/vrep_common/simRosEraseFileResponse.h
c9e2f64ae9a0fd01f65cc09f2fc06b7920d9e94a
[]
no_license
ElliWhite/group_1_coverage
e04dd3d5374cad76b3914bf0dfca719dc934989e
565c325e4dc4188716f5233b6de05671a3d89b1c
refs/heads/master
2020-05-27T17:27:37.807828
2019-05-29T21:48:43
2019-05-29T21:48:43
188,720,706
1
1
null
null
null
null
UTF-8
C++
false
false
5,452
h
// Generated by gencpp from file vrep_common/simRosEraseFileResponse.msg // DO NOT EDIT! #ifndef VREP_COMMON_MESSAGE_SIMROSERASEFILERESPONSE_H #define VREP_COMMON_MESSAGE_SIMROSERASEFILERESPONSE_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> namespace vrep_common { template <class ContainerAllocator> struct simRosEraseFileResponse_ { typedef simRosEraseFileResponse_<ContainerAllocator> Type; simRosEraseFileResponse_() : result(0) { } simRosEraseFileResponse_(const ContainerAllocator& _alloc) : result(0) { (void)_alloc; } typedef int32_t _result_type; _result_type result; typedef boost::shared_ptr< ::vrep_common::simRosEraseFileResponse_<ContainerAllocator> > Ptr; typedef boost::shared_ptr< ::vrep_common::simRosEraseFileResponse_<ContainerAllocator> const> ConstPtr; }; // struct simRosEraseFileResponse_ typedef ::vrep_common::simRosEraseFileResponse_<std::allocator<void> > simRosEraseFileResponse; typedef boost::shared_ptr< ::vrep_common::simRosEraseFileResponse > simRosEraseFileResponsePtr; typedef boost::shared_ptr< ::vrep_common::simRosEraseFileResponse const> simRosEraseFileResponseConstPtr; // constants requiring out of line definition template<typename ContainerAllocator> std::ostream& operator<<(std::ostream& s, const ::vrep_common::simRosEraseFileResponse_<ContainerAllocator> & v) { ros::message_operations::Printer< ::vrep_common::simRosEraseFileResponse_<ContainerAllocator> >::stream(s, "", v); return s; } } // namespace vrep_common namespace ros { namespace message_traits { // BOOLTRAITS {'IsFixedSize': True, 'IsMessage': True, 'HasHeader': False} // {'sensor_msgs': ['/opt/ros/kinetic/share/sensor_msgs/cmake/../msg'], 'std_msgs': ['/opt/ros/kinetic/share/std_msgs/cmake/../msg'], 'geometry_msgs': ['/opt/ros/kinetic/share/geometry_msgs/cmake/../msg'], 'vrep_common': ['/home/elliottwhite/turtlebot2_wss/vrep_ros_interface/src/vrep_common/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< ::vrep_common::simRosEraseFileResponse_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsFixedSize< ::vrep_common::simRosEraseFileResponse_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::vrep_common::simRosEraseFileResponse_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::vrep_common::simRosEraseFileResponse_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::vrep_common::simRosEraseFileResponse_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct HasHeader< ::vrep_common::simRosEraseFileResponse_<ContainerAllocator> const> : FalseType { }; template<class ContainerAllocator> struct MD5Sum< ::vrep_common::simRosEraseFileResponse_<ContainerAllocator> > { static const char* value() { return "034a8e20d6a306665e3a5b340fab3f09"; } static const char* value(const ::vrep_common::simRosEraseFileResponse_<ContainerAllocator>&) { return value(); } static const uint64_t static_value1 = 0x034a8e20d6a30666ULL; static const uint64_t static_value2 = 0x5e3a5b340fab3f09ULL; }; template<class ContainerAllocator> struct DataType< ::vrep_common::simRosEraseFileResponse_<ContainerAllocator> > { static const char* value() { return "vrep_common/simRosEraseFileResponse"; } static const char* value(const ::vrep_common::simRosEraseFileResponse_<ContainerAllocator>&) { return value(); } }; template<class ContainerAllocator> struct Definition< ::vrep_common::simRosEraseFileResponse_<ContainerAllocator> > { static const char* value() { return "int32 result\n\ \n\ "; } static const char* value(const ::vrep_common::simRosEraseFileResponse_<ContainerAllocator>&) { return value(); } }; } // namespace message_traits } // namespace ros namespace ros { namespace serialization { template<class ContainerAllocator> struct Serializer< ::vrep_common::simRosEraseFileResponse_<ContainerAllocator> > { template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m) { stream.next(m.result); } ROS_DECLARE_ALLINONE_SERIALIZER }; // struct simRosEraseFileResponse_ } // namespace serialization } // namespace ros namespace ros { namespace message_operations { template<class ContainerAllocator> struct Printer< ::vrep_common::simRosEraseFileResponse_<ContainerAllocator> > { template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::vrep_common::simRosEraseFileResponse_<ContainerAllocator>& v) { s << indent << "result: "; Printer<int32_t>::stream(s, indent + " ", v.result); } }; } // namespace message_operations } // namespace ros #endif // VREP_COMMON_MESSAGE_SIMROSERASEFILERESPONSE_H
[ "elliott.white@students.plymouth.ac.uk" ]
elliott.white@students.plymouth.ac.uk
d1678444030a17e31fca2dda504b17db1aa62636
ed71cad7b2386a97ce07ffc158e921ce72879945
/Exercices/Qt/Calc/build-ExoQt-Desktop_Qt_5_10_0_MSVC2013_64bit-Debug/debug/moc_mainwindow.cpp
88ef7e85c86658b1ed5fb08f1e05afa6b258024e
[]
no_license
cedricbannelier/Cplusplus
2c462ef034a9a19a0f128f1d5579f26179906386
9126c5e839aecd24e9380502c55e60752db505d9
refs/heads/master
2021-05-12T19:38:40.621930
2018-02-23T15:55:59
2018-02-23T15:55:59
117,100,001
0
0
null
null
null
null
UTF-8
C++
false
false
2,629
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'mainwindow.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.10.0) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../../ExoQt/mainwindow.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'mainwindow.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.10.0. 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_MainWindow_t { QByteArrayData data[1]; char stringdata0[11]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_MainWindow_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_MainWindow_t qt_meta_stringdata_MainWindow = { { QT_MOC_LITERAL(0, 0, 10) // "MainWindow" }, "MainWindow" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_MainWindow[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 0, 0, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount 0 // eod }; void MainWindow::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { Q_UNUSED(_o); Q_UNUSED(_id); Q_UNUSED(_c); Q_UNUSED(_a); } const QMetaObject MainWindow::staticMetaObject = { { &QMainWindow::staticMetaObject, qt_meta_stringdata_MainWindow.data, qt_meta_data_MainWindow, qt_static_metacall, nullptr, nullptr} }; const QMetaObject *MainWindow::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *MainWindow::qt_metacast(const char *_clname) { if (!_clname) return nullptr; if (!strcmp(_clname, qt_meta_stringdata_MainWindow.stringdata0)) return static_cast<void*>(this); return QMainWindow::qt_metacast(_clname); } int MainWindow::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QMainWindow::qt_metacall(_c, _id, _a); return _id; } QT_WARNING_POP QT_END_MOC_NAMESPACE
[ "cedric.bannelier@gmail.com" ]
cedric.bannelier@gmail.com
ab348e4fbef421e923c0767bf565b0360952e0e9
c66205912503cf2ea773c78fc0b1d992eec3946d
/course-2/week-1/graph_operations/Graph.hh
92aeda30f5e2417136a0b0473161ea26fe87590e
[]
no_license
tanu-rana/Algorithms-Specialization-Stanford
d34a9bd7408b6a826eb098c580c7f25d421de3e4
047720c4f03bd98830b0ef8f115a98d659a3fa66
refs/heads/master
2020-07-27T14:16:58.591095
2019-12-25T14:02:12
2019-12-25T14:02:12
209,120,249
0
0
null
null
null
null
UTF-8
C++
false
false
1,466
hh
/** * This header file contains the declaration of a class representing a Graph. * The graph is represented using an adjacency list. The graph may be * directed or undirected. It can have multiple operations - traversing using * bfs and dfs, sorting vertices topologically, reversing the directed edges, * computing connected components, shortest path and strictly connected * components. */ #ifndef GRAPH_HH #define GRAPH_HH #include "Vertex.hh" using namespace std; class Graph { private: // Number of vertices. int n; // Array of all vertices in the graph. Vertex *vertices; public: // Creation/Deletion of a graph. Graph(int n); ~Graph(void); // Add an edge between tail and head. void add_edge(int tail, int head, bool is_directed = false); // Helper function for debugging. void print(void); // Traversing the graph. list<int> bfs(int source, bool set_unvisited = false); list<int> dfs(int source, bool set_unvisited = false); // Shortest path. int get_shortest_path(int src, int dest); // Find connected components. list<list<int>> find_connected_components(void); // Topological sort. list<int> topological_sort(void); // Reverse graph. Graph create_reverse_graph(void); void reverse_graph(void); // Gives SCCs. list<list<int>> compute_scc(void); // Tests. bool is_reverse_of(Graph &G); bool operator==(Graph &G); }; #endif
[ "2907.tanu@gmail.com" ]
2907.tanu@gmail.com
b7948e0d848df16986a0bbdb3097a92901ff6cfc
dcc72fc8b436e7ef95a23baee38760d1fc917c07
/src/src/data/sparse_page_source.h
5368f1a948a1e53a097217e1ab20e48850bed039
[ "Apache-2.0" ]
permissive
nalzok/tsoobgx
d5e60c074cecfc7b3b3ab640cd018dd5619f4d59
1c02904237e9aafeb13ce7a4a898273c903a09bd
refs/heads/master
2020-09-02T23:05:24.140676
2019-11-03T17:46:38
2019-11-03T17:46:38
219,327,480
0
0
null
null
null
null
UTF-8
C++
false
false
3,501
h
/*! * Copyright (c) 2014 by Contributors * \file page_csr_source.h * External memory data source, saved with sparse_batch_page binary format. * \author Tianqi Chen */ #ifndef TSOOBGX_DATA_SPARSE_PAGE_SOURCE_H_ #define TSOOBGX_DATA_SPARSE_PAGE_SOURCE_H_ #include <tsoobgx/base.h> #include <tsoobgx/data.h> #include <dmlc/threadediter.h> #include <algorithm> #include <memory> #include <string> #include <vector> #include "sparse_page_writer.h" namespace tsoobgx { namespace data { /*! * \brief External memory data source. * \code * std::unique_ptr<DataSource> source(new SimpleCSRSource(cache_prefix)); * // add data to source * DMatrix* dmat = DMatrix::Create(std::move(source)); * \encode */ class SparsePageSource : public DataSource { public: /*! * \brief Create source from cache files the cache_prefix. * \param cache_prefix The prefix of cache we want to solve. */ explicit SparsePageSource(const std::string& cache_prefix, const std::string& page_type) noexcept(false); /*! \brief destructor */ ~SparsePageSource() override; // implement Next bool Next() override; // implement BeforeFirst void BeforeFirst() override; // implement Value SparsePage& Value(); const SparsePage& Value() const override; /*! * \brief Create source by taking data from parser. * \param src source parser. * \param cache_info The cache_info of cache file location. * \param page_size Page size for external memory. */ static void CreateRowPage(dmlc::Parser<uint32_t>* src, const std::string& cache_info, const size_t page_size = DMatrix::kPageSize); /*! * \brief Create source cache by copy content from DMatrix. * \param cache_info The cache_info of cache file location. */ static void CreateRowPage(DMatrix* src, const std::string& cache_info); /*! * \brief Create source cache by copy content from DMatrix. Creates transposed column page, may be sorted or not. * \param cache_info The cache_info of cache file location. * \param sorted Whether columns should be pre-sorted */ static void CreateColumnPage(DMatrix* src, const std::string& cache_info, bool sorted); /*! * \brief Check if the cache file already exists. * \param cache_info The cache prefix of files. * \param page_type Type of the page. * \return Whether cache file already exists. */ static bool CacheExist(const std::string& cache_info, const std::string& page_type); /*! \brief magic number used to identify Page */ static const int kMagic = 0xffffab02; private: static void CreatePageFromDMatrix(DMatrix* src, const std::string& cache_info, const std::string& page_type, const size_t page_size = DMatrix::kPageSize); /*! \brief number of rows */ size_t base_rowid_; /*! \brief page currently on hold. */ SparsePage *page_; /*! \brief internal clock ptr */ size_t clock_ptr_; /*! \brief file pointer to the row blob file. */ std::vector<std::unique_ptr<dmlc::SeekStream> > files_; /*! \brief Sparse page format file. */ std::vector<std::unique_ptr<SparsePageFormat> > formats_; /*! \brief internal prefetcher. */ std::vector<std::unique_ptr<dmlc::ThreadedIter<SparsePage> > > prefetchers_; }; } // namespace data } // namespace tsoobgx #endif // TSOOBGX_DATA_SPARSE_PAGE_SOURCE_H_
[ "sunqingyao19970825@icloud.com" ]
sunqingyao19970825@icloud.com
024163709d452b04ef2247400326cc8b46b22c43
3051bd4bc0b7f3dace598880caf3364690688bc9
/plugins/MacAU/Wider/Wider.h
8bad13acca1e0299225d837ea69c816db3d2bd88
[ "MIT" ]
permissive
Atavic/airwindows
aa6802409eb9c7254e405874a267af700cb6ba0d
ac8d974fb5bfa349af37412aa5e1fe2aeea1a8f6
refs/heads/master
2020-03-28T08:38:49.668758
2018-09-09T01:07:53
2018-09-09T01:07:53
147,978,977
1
0
MIT
2018-09-09T00:02:49
2018-09-09T00:02:49
null
WINDOWS-1252
C++
false
false
5,298
h
/* * File: Wider.h * * Version: 1.0 * * Created: 5/21/07 * * Copyright: Copyright © 2007 Airwindows, All Rights Reserved * * Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Computer, Inc. ("Apple") in * consideration of your agreement to the following terms, and your use, installation, modification * or redistribution of this Apple software constitutes acceptance of these terms. If you do * not agree with these terms, please do not use, install, modify or redistribute this Apple * software. * * In consideration of your agreement to abide by the following terms, and subject to these terms, * Apple grants you a personal, non-exclusive license, under Apple's copyrights in this * original Apple software (the "Apple Software"), to use, reproduce, modify and redistribute the * Apple Software, with or without modifications, in source and/or binary forms; provided that if you * redistribute the Apple Software in its entirety and without modifications, you must retain this * notice and the following text and disclaimers in all such redistributions of the Apple Software. * Neither the name, trademarks, service marks or logos of Apple Computer, Inc. may be used to * endorse or promote products derived from the Apple Software without specific prior written * permission from Apple. Except as expressly stated in this notice, no other rights or * licenses, express or implied, are granted by Apple herein, including but not limited to any * patent rights that may be infringed by your derivative works or by other works in which the * Apple Software may be incorporated. * * The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES, EXPRESS OR * IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE * OR IN COMBINATION WITH YOUR PRODUCTS. * * IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, * REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER * UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN * IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include "AUEffectBase.h" #include "WiderVersion.h" #if AU_DEBUG_DISPATCHER #include "AUDebugDispatcher.h" #endif #ifndef __Wider_h__ #define __Wider_h__ #pragma mark ____Wider Parameters // parameters static const float kDefaultValue_ParamOne = 0.0; static const float kDefaultValue_ParamTwo = 0.0; static const float kDefaultValue_ParamThree = 1.0; //let's assume we always have a default of 0.0, for no effect static CFStringRef kParameterOneName = CFSTR("Width"); static CFStringRef kParameterTwoName = CFSTR("Center"); static CFStringRef kParameterThreeName = CFSTR("Dry/Wet"); //Alter the name if desired, but using the plugin name is a start enum { kParam_One =0, kParam_Two =1, kParam_Three =2, //Add your parameters here... kNumberOfParameters=3 }; #pragma mark ____Wider class Wider : public AUEffectBase { public: Wider(AudioUnit component); #if AU_DEBUG_DISPATCHER virtual ~Wider () { delete mDebugDispatcher; } #endif virtual ComponentResult Reset(AudioUnitScope inScope, AudioUnitElement inElement); virtual OSStatus ProcessBufferLists(AudioUnitRenderActionFlags & ioActionFlags, const AudioBufferList & inBuffer, AudioBufferList & outBuffer, UInt32 inFramesToProcess); virtual UInt32 SupportedNumChannels(const AUChannelInfo ** outInfo); virtual ComponentResult GetParameterValueStrings(AudioUnitScope inScope, AudioUnitParameterID inParameterID, CFArrayRef * outStrings); virtual ComponentResult GetParameterInfo(AudioUnitScope inScope, AudioUnitParameterID inParameterID, AudioUnitParameterInfo &outParameterInfo); virtual ComponentResult GetPropertyInfo(AudioUnitPropertyID inID, AudioUnitScope inScope, AudioUnitElement inElement, UInt32 & outDataSize, Boolean & outWritable ); virtual ComponentResult GetProperty(AudioUnitPropertyID inID, AudioUnitScope inScope, AudioUnitElement inElement, void * outData); virtual ComponentResult Initialize(); virtual bool SupportsTail () { return true; } virtual Float64 GetTailTime() {return 0.0;} virtual Float64 GetLatency() {return 0.0;} // edit these because tail time isn't 1000 samples and latency isn't 1 /*! @method Version */ virtual ComponentResult Version() { return kWiderVersion; } private: Float64 p[4099]; long double fpNShapeAL; long double fpNShapeBL; long double fpNShapeAR; long double fpNShapeBR; bool flip; int count; }; //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #endif
[ "jinx6568@sover.net" ]
jinx6568@sover.net
b59acf056593c1020f9bdf1398f6dd11a70823e4
311e0608b4005865b90eb153d961b8758ba6de28
/LAB 5/Date and Employee Friend/EmployeeDriver.cpp
30296e5b23128a12442834bfcbe34e662bde56bd
[]
no_license
JPL4494/DVC-COMSC200
e71c9c46b33bd4886932ee87c0be31e581cb8c3e
c76a7f087b353ba16fdac9a1b0ba27e972daa5f0
refs/heads/master
2020-03-19T00:25:03.075887
2018-05-30T19:23:33
2018-05-30T19:23:33
135,479,290
0
0
null
null
null
null
UTF-8
C++
false
false
1,168
cpp
/* Lab 5a, The friend Program Programmer: Joshua Long Editor used: Notepad Compiler used: CodeBlocks */ #include<iostream> using std::cout; using std::endl; #include "Date.h" #include "Date.h" #include "Employee.h" #include "Employee.h" int main() { cout << "Lab 5a, The friend Program" << endl; cout << "Programmer: Joshua Long" << endl; cout << "Editor used: Notepad" << endl; cout << "Compiler used: CodeBlocks" << endl; cout << "File: " << __FILE__ << endl; cout << "Compiled: " << __DATE__ << " at " << __TIME__ << endl << endl; cout << "Passing employee info as follows, Josh Long 4 4 1994 8 15 2011" << endl; Date b(4,4,1994); Date h(8,15,2011); Employee e("Josh","Long",b,h); cout << endl << "Expected out put Long, Josh Hired: 8/15/2011 Birthday: 4/4/1994" << endl; e.print(); cout << endl << endl; { cout << "Copying employee information from above using upon declaration copy" << endl; const Employee copy = e; cout << endl << "Expected out put Long, Josh Hired: 8/15/2011 Birthday: 4/4/1994" << endl; copy.print(); cout << endl << endl; } cout << endl; }
[ "noreply@github.com" ]
JPL4494.noreply@github.com
8d9f8aa28d1cdac9b4b2275f8c38484bcc1488b2
dc0d3fdaf06c786b915ff9661d87662bfbf1600d
/BehaviourArises/BehaviourArises/BT_Leaf.h
c2429f679160c4c20105e82c9a939e3a4cf0828e
[]
no_license
leehax/BehaviourArises
1085e687ad1fb3a830a26502c3bde4a9dba36b61
7901f3eadbc0af20abce3f2732e97d59484d3df2
refs/heads/master
2021-03-27T09:11:26.381405
2018-03-25T17:33:21
2018-03-25T17:33:21
123,574,042
0
0
null
null
null
null
UTF-8
C++
false
false
336
h
#pragma once #include "BT_Node.h" #include <string> class BT_Leaf : public BT_Node { public: BT_Leaf(std::string p_name, int p_probablity); BT_Leaf(std::shared_ptr<BlackBoard> p_BB); virtual ~BT_Leaf(); BT_State Update() override; protected: std::shared_ptr<BlackBoard> m_blackBoard; std::string m_name; int m_probability; };
[ "leevi.hakala@gmail.com" ]
leevi.hakala@gmail.com
48fd74cfab27f8d4d4addd0add2641b44944d65d
91426326744bd2093822dabc0c2c46beca174663
/TrakkerBPfinalCode/testRF/testRF.ino
3e87339feda3051caab06d11a33238ca4f20a314
[]
no_license
ronniewhyrick/Senior-Design
0eb989c715b49176405016b5391bf91f80c7ca20
0e155e6488091090e1286579e0e397210b0740a4
refs/heads/master
2020-08-10T04:40:37.752724
2019-12-10T12:35:38
2019-12-10T12:35:38
214,259,346
2
1
null
2019-10-22T13:51:57
2019-10-10T18:42:21
C++
UTF-8
C++
false
false
503
ino
#include <SoftwareSerial.h> SoftwareSerial HC12(6, 5); // HC-12 TX Pin, HC-12 RX Pin void setup() { Serial.begin(9600); // Serial port to computer HC12.begin(9600); // Serial port to HC12 } void loop() { while (HC12.available()) { // If HC-12 has data Serial.write(HC12.read()); // Send the data to Serial monitor } while (Serial.available()) { // If Serial monitor has data HC12.write(Serial.read()); // Send that data to HC-12 } }
[ "noreply@github.com" ]
ronniewhyrick.noreply@github.com
5a98dcf9011a41d4eed7113f8ab0f163c5ffc3fc
b66208cedcbca09c44f007dcd0e01e4d5f04a0b1
/frameworks/rs/rsObjectBase.h
4f29e572fba2f1f754a065a34fa87166d6f12dba
[]
no_license
hua3505/AndroidFrameworkSource
2bb848110ec93f650fa8285f7dbb5524ee78e42e
c2fb180c9dbcc657456bab9feb62c351bec7f91e
refs/heads/master
2021-08-31T17:36:52.205076
2017-12-13T09:38:34
2017-12-13T09:38:34
111,386,259
8
1
null
null
null
null
UTF-8
C++
false
false
3,923
h
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef ANDROID_RS_OBJECT_BASE_H #define ANDROID_RS_OBJECT_BASE_H #include "rsUtils.h" #include "rsDefines.h" #include "rsInternalDefines.h" namespace android { namespace renderscript { class Context; class OStream; // An element is a group of Components that occupies one cell in a structure. class ObjectBase { public: static const bool gDebugStacks = false; static const bool gDebugReferences = false; static const bool gDebugLeaks = false; static const bool gDebugLifetime = false; ObjectBase(Context *rsc); // NOLINT, implicit void incSysRef() const; bool decSysRef() const; void incUserRef() const; bool decUserRef() const; bool zeroUserRef() const; static bool checkDelete(const ObjectBase *); const char * getName() const { return mName; } void assignName(const char *s) {mName = s;} void setName(const char *); void setName(const char *, uint32_t len); Context * getContext() const {return mRSC;} virtual bool freeChildren(); static void zeroAllUserRef(Context *rsc); static void freeAllChildren(Context *rsc); static void dumpAll(Context *rsc); virtual void dumpLOGV(const char *prefix) const; virtual void serialize(Context *rsc, OStream *stream) const = 0; virtual RsA3DClassID getClassId() const = 0; static bool isValid(const Context *rsc, const ObjectBase *obj); // The async lock is taken during object creation in non-rs threads // and object deletion in the rs thread. static void asyncLock(); static void asyncUnlock(); virtual void callUpdateCacheObject(const Context *rsc, void *dstObj) const; protected: // Called inside the async lock for any object list management that is // necessary in derived classes. virtual void preDestroy() const; Context *mRSC; virtual ~ObjectBase(); private: static pthread_mutex_t gObjectInitMutex; void add() const; void remove() const; const char* mName; mutable int32_t mSysRefCount; mutable int32_t mUserRefCount; mutable const ObjectBase * mPrev; mutable const ObjectBase * mNext; class DebugHelper *mDH; }; template<class T> class ObjectBaseRef { public: ObjectBaseRef() { mRef = nullptr; } ObjectBaseRef(const ObjectBaseRef &ref) { mRef = ref.get(); if (mRef) { mRef->incSysRef(); } } ObjectBaseRef(T *ref) { // NOLINT, implicit mRef = ref; if (mRef) { ref->incSysRef(); } } ObjectBaseRef & operator= (const ObjectBaseRef &ref) { if (&ref != this) { set(ref); } return *this; } ~ObjectBaseRef() { clear(); } void set(T *ref) { if (mRef != ref) { clear(); mRef = ref; if (mRef) { ref->incSysRef(); } } } void set(const ObjectBaseRef &ref) { set(ref.mRef); } void clear() { if (mRef) { mRef->decSysRef(); } mRef = nullptr; } inline T * get() const { return mRef; } inline T * operator-> () const { return mRef; } protected: T * mRef; }; } } #endif //ANDROID_RS_OBJECT_BASE_H
[ "wolf.xu@ximalaya.com" ]
wolf.xu@ximalaya.com
12b06bc2b7cedc5333026badd6dd747055d0258b
1e381f2b974bc82cd2f0bd0cc5029cbda1baedb2
/ProjectEuler/004/problem 4.cpp
e310f926f7979efe9de3c7ed07819acdc9d8760f
[]
no_license
rajat189/Competetive_programming
7655678935d40cada5a3d39ed400ee430f0311db
709065b3527eceb3923c13091608c174ae3a5d64
refs/heads/master
2021-01-19T05:53:35.790236
2016-04-12T19:12:34
2016-04-12T19:12:34
38,609,439
1
1
null
null
null
null
UTF-8
C++
false
false
317
cpp
#include <cstdio> int ispal(int i){ int n=i,rev=0,dig; while(i>0) { dig=i%10; rev=rev*10+dig; i/=10; } return n==rev; } int main(){ int max; for(int i=100;i<1000;i++){ for(int j=100;j<1000;j++){ if(ispal(i*j)){ if(max<i*j)max=i*j; } } } printf("%d\n",max); }
[ "coolrajatsharma18@gmail.com" ]
coolrajatsharma18@gmail.com
967712889fa20199fe2798e05d9af617c0df4f00
04b1803adb6653ecb7cb827c4f4aa616afacf629
/remoting/client/display/gl_renderer.h
bd48ffbf2e0030c9576cfd6967ea0eb2fdc5b46d
[ "BSD-3-Clause" ]
permissive
Samsung/Castanets
240d9338e097b75b3f669604315b06f7cf129d64
4896f732fc747dfdcfcbac3d442f2d2d42df264a
refs/heads/castanets_76_dev
2023-08-31T09:01:04.744346
2021-07-30T04:56:25
2021-08-11T05:45:21
125,484,161
58
49
BSD-3-Clause
2022-10-16T19:31:26
2018-03-16T08:07:37
null
UTF-8
C++
false
false
5,317
h
// Copyright 2016 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 REMOTING_CLIENT_DISPLAY_GL_RENDERER_H_ #define REMOTING_CLIENT_DISPLAY_GL_RENDERER_H_ #include <vector> #include "base/callback.h" #include "base/containers/queue.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "base/optional.h" #include "base/threading/thread_checker.h" #include "remoting/client/display/gl_cursor.h" #include "remoting/client/display/gl_cursor_feedback.h" #include "remoting/client/display/gl_desktop.h" #include "remoting/proto/control.pb.h" namespace webrtc { class DesktopFrame; } // namespace webrtc namespace remoting { namespace protocol { class CursorShapeInfo; } // namespace protocol class Canvas; class GlRendererDelegate; class GlRendererTest; // Renders desktop and cursor on the OpenGL surface. Can be created on any // thread but thereafter must be used and deleted on the same thread (usually // the display thread. Or any Chromium thread with a task runner attached to // it) unless otherwise noted. // The unit of all length arguments is pixel. class GlRenderer { public: explicit GlRenderer(); ~GlRenderer(); // The delegate can be set on any hread no more than once before calling any // On* functions. void SetDelegate(base::WeakPtr<GlRendererDelegate> delegate); // Notifies the delegate with the current canvas size. Canvas size will be // (0, 0) if no desktop frame is received yet. // Caller can use this function to get the canvas size when the surface is // recreated. void RequestCanvasSize(); // TODO(yuweih): Use ViewMatrix instead of the 3x3 array. // Sets the pixel based transformation matrix related to the size of the // canvas. // 3 by 3 transformation matrix, [ m0, m1, m2, m3, m4, m5, m6, m7, m8 ]. // // | m0, m1, m2, | | x | // | m3, m4, m5, | * | y | // | m6, m7, m8 | | 1 | // // The final size of the canvas will be (m0*canvas_width, m4*canvas_height) // and the top-left corner will be (m2, m5) in pixel coordinates. void OnPixelTransformationChanged(const std::array<float, 9>& matrix); void OnCursorMoved(float x, float y); void OnCursorInputFeedback(float x, float y, float diameter); void OnCursorVisibilityChanged(bool visible); // Called when a desktop frame is received. // The size of the canvas is determined by the dimension of the desktop frame. // |done| will be queued up and called on the display thread after the actual // rendering happens. void OnFrameReceived(std::unique_ptr<webrtc::DesktopFrame> frame, const base::Closure& done); void OnCursorShapeChanged(const protocol::CursorShapeInfo& shape); // Called after the EGL/EAGL context is established and the surface is created // (or recreated). Previous desktop frame and canvas transformation will be // lost after calling this function. // Caller must call OnSurfaceDestroyed() before calling this function if the // surface is recreated. void OnSurfaceCreated(std::unique_ptr<Canvas> canvas); // Sets the size of the view. Called right after OnSurfaceCreated() or // whenever the view size is changed. void OnSurfaceChanged(int view_width, int view_height); // Called when the surface is destroyed. void OnSurfaceDestroyed(); void AddDrawable(base::WeakPtr<Drawable> drawable); // Returns the weak pointer to be used on the display thread. base::WeakPtr<GlRenderer> GetWeakPtr(); // Convenience method to create a Renderer with standard desktop components. // This function must be called on the display thread, or whatever thread that // will be used after the renderer is created. static std::unique_ptr<GlRenderer> CreateGlRendererWithDesktop(); private: friend class GlRendererTest; // Post a rendering task to the task runner of current thread. // Do nothing if render_callback_ is not set yet or an existing rendering task // in the queue will cover changes before this function is called. void RequestRender(); // Draws out everything on current OpenGL buffer and runs closures in // |pending_done_callbacks_|. // Nothing will be drawn nor the done callbacks will be run if |delegate_| is // invalid or !delegate_.CanRenderFrame(). void OnRender(); base::WeakPtr<GlRendererDelegate> delegate_; // Done callbacks from OnFrameReceived. Will all be called once rendering // takes place. base::queue<base::Closure> pending_done_callbacks_; bool render_scheduled_ = false; int canvas_width_ = 0; int canvas_height_ = 0; // Used to store the view size before the canvas is created. int view_width_ = 0; int view_height_ = 0; std::unique_ptr<Canvas> canvas_; // Used to recover the transformation matrix when the canvas is recreated. base::Optional<std::array<float, 9>> transformation_matrix_; GlCursor cursor_; GlCursorFeedback cursor_feedback_; GlDesktop desktop_; std::vector<base::WeakPtr<Drawable>> drawables_; base::ThreadChecker thread_checker_; base::WeakPtr<GlRenderer> weak_ptr_; base::WeakPtrFactory<GlRenderer> weak_factory_; DISALLOW_COPY_AND_ASSIGN(GlRenderer); }; } // namespace remoting #endif // REMOTING_CLIENT_DISPLAY_GL_RENDERER_H_
[ "sunny.nam@samsung.com" ]
sunny.nam@samsung.com
e6d38be2a884244a1f3dc844a2e4d7ed1cf5c35b
d0d2ad2ca6893e930d1c498f3626fb837ddcc600
/SP1Framework-master/SP1Framework/Companion.h
ae96e586d792be92f5ce6e54c522ed7976c2ea2c
[]
no_license
elisionJL/sp1-test
8b2cfd69428624622bd4b1303bcb0312a4b7fc03
c8337c6034a6702521378bbe2fc671b9e31ffa09
refs/heads/main
2023-07-12T10:04:37.476248
2021-08-20T06:49:27
2021-08-20T06:49:27
398,121,147
0
0
null
null
null
null
UTF-8
C++
false
false
556
h
#pragma once #include "Entity.h" #include <string> class Companion : public Entity { private: float MovePower; int companionId; int lvl; double upgradecost; int timespulled; public: Companion(); Companion(int companionId,std::string x); void setMovePower(float pwr); ~Companion(); string getMoveName(int MoveNo); double getMovePower(int MoveNo); void summonedagain(); void lvlup(); int getlvl(); double getupgradecost(); int getid(); int gettimespulled(); };
[ "noreply@github.com" ]
elisionJL.noreply@github.com
1dd42792236da1aa1f51d62ec6c63b99fa678d91
77a073d9628c9c3e627923325d6a6f6383d3ab00
/simple-joystick.ino
6a44815ab0999657d9b8d01b03f67fa949e0d1db
[ "MIT" ]
permissive
iot-crazy/simple-joystick
2d7b084d9c20de5771a8d45d76117185c247f084
bf53279a478d9da876b1360a31482bd3b1449179
refs/heads/master
2022-06-06T04:25:36.458234
2020-05-01T10:50:34
2020-05-01T10:50:34
260,421,479
0
0
null
2020-05-01T09:58:36
2020-05-01T09:26:04
null
UTF-8
C++
false
false
1,511
ino
// IoT Crazy 2020 // Simple joystick tutorial with smoothing // Which pins the joystick is connected to // These values are for the ESP 32 int JoyStick_X = 36; // x int JoyStick_Y = 39; // y int JoyStick_Z = 35; // switch - remember the pullup resistor! int prevx, prevy, prevbtn = 0; // previous states or each joystick input, default to zero int minChange = 20; // minimum amount of change that must be seen to determine that the stick has moved int numSamples = 20; // how many samples to take when reading the joystick void setup() { Serial.begin(115200); delay(10); pinMode(JoyStick_Z, INPUT); pinMode(JoyStick_X, INPUT); pinMode(JoyStick_Y, INPUT); } void loop() { int x,y,z,sum_x,sum_y = 0; // start with all values at zero // collect the required number of samples and add to a sum for(int i = 0; i<=numSamples; i++) { sum_x += analogRead(JoyStick_X); sum_y += analogRead(JoyStick_Y); } // find the mean average of the samples x = sum_x / numSamples; y = sum_y / numSamples; z = digitalRead(JoyStick_Z); // if the average of either axis is greater than the minimum required change, or the button state has changed, display the values if (abs(x - prevx) > minChange || abs(y - prevy) > minChange || z != prevbtn) { Serial.printf("Stick: %d,%d Δ: %d,%d / btn:%d \n", x, x, abs(x-prevx), abs(y-prevy), z); // save the current values as the new 'previous' value to compare on th next loop prevx = x; prevy = y; prevbtn = z; } }
[ "webmaster@iotcrazy.com" ]
webmaster@iotcrazy.com
b114dbbd37af56edb625c6afe38a53e0e7f49823
43f77fb986fbf74dd2bf16aa8db98b713c5a4b0c
/BOJ/BOJ_16434/BOJ_16434.cpp
db11b5925d3083fc56c557415681c4b76add3418
[]
no_license
wonbae/Algorithm
d5070962214ed2c18b8cd90487a06e6ea71fb491
e084e1da9b292f64fde4511b4077bcacc147fc69
refs/heads/master
2023-08-22T17:45:51.611529
2023-08-22T13:30:47
2023-08-22T13:30:47
170,489,231
0
0
null
null
null
null
UTF-8
C++
false
false
1,154
cpp
#include<bits/stdc++.h> #define fastio ios_base::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL); typedef long long ll; using namespace std; ll n, Hatk; ll curHP, maxHP, res; vector<ll> t, a, h; bool check(ll mid){ maxHP = mid; curHP = mid; ll atk = Hatk; for(int i = 0; i < n; i++){ if(t[i] == 1){ ll iter; if(h[i] % atk == 0){ iter = h[i] / atk; }else iter = h[i] / atk + 1; if((iter - 1) * a[i] >= curHP) return false; curHP -= ((iter - 1) * a[i]); }else{ atk += a[i]; curHP = min(curHP + h[i], maxHP); } } return curHP >= 1 ? true : false; } int main(){ fastio; cin>>n>>Hatk; for(int i = 0; i < n; i++){ ll ti, ai, hi; cin>>ti>>ai>>hi; t.push_back(ti); a.push_back(ai); h.push_back(hi); } ll lo = 1; ll hi = 1e18 + 4; while(lo <= hi){ ll mid = lo + ((hi - lo) / 2); if(check(mid)){ res = mid; hi = mid - 1; }else lo = mid + 1; } cout<<res<<"\n"; return 0; }
[ "k1bae2301@gmail.com" ]
k1bae2301@gmail.com
d52e995fd34561d30592d3dc6c70125c1019936f
cad91ae76d2746a6c28ddda0f33a58f9d461378f
/PyTorch/Recommendation/DLRM/dlrm/cuda_src/sparse_gather/sparse_pytorch_ops.cpp
55fa875698a150679c37a48964ac4e33afdbed04
[ "Apache-2.0", "MIT" ]
permissive
NVIDIA/DeepLearningExamples
fe677521e7e2a16e3cb0b77e358f9aab72f8c11a
a5388a45f71a949639b35cc5b990bd130d2d8164
refs/heads/master
2023-08-31T20:57:08.798455
2023-08-23T10:09:12
2023-08-23T10:09:12
131,881,622
11,838
3,124
null
2023-08-28T16:57:33
2018-05-02T17:04:05
Jupyter Notebook
UTF-8
C++
false
false
827
cpp
#include <torch/extension.h> torch::Tensor gather_gpu_fwd(torch::Tensor input, torch::Tensor weight); void gather_gpu_bwd_fuse_sgd(const torch::Tensor grad, const torch::Tensor indices, float lr, torch::Tensor weight); torch::Tensor gather_gpu_bwd(const torch::Tensor grad, const torch::Tensor indices, const int num_features); PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("gather_gpu_fwd", &gather_gpu_fwd, "Embedding gather", py::arg("indices"), py::arg("weight")); m.def("gather_gpu_bwd_fuse_sgd", &gather_gpu_bwd_fuse_sgd, "Embedding gather backward with fused plain SGD", py::arg("grad"), py::arg("indices"), py::arg("lr"), py::arg("weight")); m.def("gather_gpu_bwd", &gather_gpu_bwd, "Embedding gather backward", py::arg("grad"), py::arg("indices"), py::arg("num_features")); }
[ "41076710+nvpstr@users.noreply.github.com" ]
41076710+nvpstr@users.noreply.github.com
8d4e17fe9db635b202d99adc83d6b46fef2a59c7
24a5c5a32b8d5afe1b65233d8ff43cf85b604ebe
/tensorpipe/test/channel/cuda_basic/cuda_basic_test.cc
3729e9e83f7b3f72574f87ad63d9d7b507539f96
[ "BSD-3-Clause" ]
permissive
pytorch/tensorpipe
52cc56f1c3b4be12fcee8d7dae1b45090401cb1a
bb1473a4b38b18268e8693044afdb8635bc8351b
refs/heads/main
2023-06-12T05:10:56.398500
2022-05-13T15:10:04
2022-05-13T15:10:04
219,778,184
235
78
NOASSERTION
2022-11-23T08:06:49
2019-11-05T15:27:14
C++
UTF-8
C++
false
false
2,385
cc
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #include <numeric> #include <tensorpipe/channel/basic/factory.h> #include <tensorpipe/channel/cuda_basic/factory.h> #include <tensorpipe/test/channel/channel_test_cuda.h> namespace { class CudaBasicChannelTestHelper : public CudaChannelTestHelper { protected: std::shared_ptr<tensorpipe::channel::Context> makeContextInternal( std::string id) override { auto cpuContext = tensorpipe::channel::basic::create(); auto context = tensorpipe::channel::cuda_basic::create(std::move(cpuContext)); context->setId(std::move(id)); return context; } public: std::shared_ptr<PeerGroup> makePeerGroup() override { return std::make_shared<ProcessPeerGroup>(); } }; CudaBasicChannelTestHelper helper; class CudaBasicChannelTestSuite : public ChannelTestSuite {}; } // namespace class CannotCommunicateCpuToCpuTest : public ChannelTestCase { public: void run(ChannelTestHelper* /* unused */) override { ForkedThreadPeerGroup pg; pg.spawn( [&]() { auto cpuContext = tensorpipe::channel::basic::create(); auto ctx = tensorpipe::channel::cuda_basic::create(std::move(cpuContext)); auto deviceDescriptors = ctx->deviceDescriptors(); auto it = deviceDescriptors.find( tensorpipe::Device{tensorpipe::kCpuDeviceType, 0}); EXPECT_FALSE(it == deviceDescriptors.end()); auto descriptor = it->second; EXPECT_FALSE(ctx->canCommunicateWithRemote(descriptor, descriptor)); }, [&]() { // Do nothing. }); } }; CHANNEL_TEST(CudaBasicChannelTestSuite, CannotCommunicateCpuToCpu); INSTANTIATE_TEST_CASE_P( CudaBasic, ChannelTestSuite, ::testing::Values(&helper)); INSTANTIATE_TEST_CASE_P( CudaBasic, CudaChannelTestSuite, ::testing::Values(&helper)); INSTANTIATE_TEST_CASE_P( CudaBasic, CudaMultiGPUChannelTestSuite, ::testing::Values(&helper)); INSTANTIATE_TEST_CASE_P( CudaBasic, CudaXDTTChannelTestSuite, ::testing::Values(&helper)); INSTANTIATE_TEST_CASE_P( CudaBasic, CudaBasicChannelTestSuite, ::testing::Values(&helper));
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
b83f84c250cdf79ebb1a464bbcae2fe1c009aa01
4d6b65d04f367678563f48771bf918f5e609c86a
/plugins/consoles/guicons/s60/src/GuiCons.cpp
ce631bad5dc2482c813ccc6c67170f9af8b6b091
[]
no_license
xdsh/FShell
3bdb79d690de00efeac2d727fda9ed413d07621d
3f2cf79601f53c9435c8f957e06a4067085320c3
refs/heads/master
2020-12-28T14:22:03.942434
2020-02-05T04:42:32
2020-02-05T04:42:32
238,367,577
2
0
null
2020-02-05T04:27:58
2020-02-05T04:27:57
null
UTF-8
C++
false
false
633
cpp
// GuiCons.cpp // // Copyright (c) 2009 - 2010 Accenture. All rights reserved. // This component and the accompanying materials are made available // under the terms of the "Eclipse Public License v1.0" // which accompanies this distribution, and is available // at the URL "http://www.eclipse.org/legal/epl-v10.html". // // Initial Contributors: // Accenture - Initial contribution // #include <eikstart.h> #include "GuiConsApplication.h" LOCAL_C CApaApplication* NewApplication() { return new CGuiConsApplication; } GLDEF_C TInt E32Main() { return EikStart::RunApplication( NewApplication ); }
[ "thomas.sutcliffe@accenture.com" ]
thomas.sutcliffe@accenture.com
d36a05d900a5fdcc78c96cab6cf22f881e303f7a
14dec18b0df4c61bc82f53ec48e99728fe8bff97
/src/ray/core_worker/transport/direct_task_transport.h
fabedc903f8aea1eb962054349b20fe23c1b3b69
[ "Apache-2.0", "MIT" ]
permissive
sureshannapureddy/ray
04110c001889301f8b8c5749b05b05340ee1857b
a1744f67fe954d8408c5b84e28ecccc130157f8e
refs/heads/master
2020-09-13T04:29:24.320444
2019-11-19T07:03:46
2019-11-19T07:03:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,937
h
#ifndef RAY_CORE_WORKER_DIRECT_TASK_H #define RAY_CORE_WORKER_DIRECT_TASK_H #include "absl/base/thread_annotations.h" #include "absl/synchronization/mutex.h" #include "ray/common/id.h" #include "ray/common/ray_object.h" #include "ray/core_worker/context.h" #include "ray/core_worker/store_provider/memory_store_provider.h" #include "ray/core_worker/transport/direct_actor_transport.h" #include "ray/raylet/raylet_client.h" #include "ray/rpc/worker/core_worker_client.h" namespace ray { struct TaskState { /// The task to be run. TaskSpecification task; /// The remaining dependencies to resolve for this task. absl::flat_hash_set<ObjectID> local_dependencies; }; // This class is thread-safe. class LocalDependencyResolver { public: LocalDependencyResolver(std::shared_ptr<CoreWorkerMemoryStoreProvider> store_provider) : in_memory_store_(store_provider), num_pending_(0) {} /// Resolve all local and remote dependencies for the task, calling the specified /// callback when done. Direct call ids in the task specification will be resolved /// to concrete values and inlined. // /// Note: This method **will mutate** the given TaskSpecification. /// /// Postcondition: all direct call ids in arguments are converted to values. void ResolveDependencies(const TaskSpecification &task, std::function<void()> on_complete); /// Return the number of tasks pending dependency resolution. /// TODO(ekl) this should be exposed in worker stats. int NumPendingTasks() const { return num_pending_; } private: /// The store provider. std::shared_ptr<CoreWorkerMemoryStoreProvider> in_memory_store_; /// Number of tasks pending dependency resolution. std::atomic<int> num_pending_; /// Protects against concurrent access to internal state. absl::Mutex mu_; }; typedef std::pair<std::string, int> WorkerAddress; typedef std::function<std::shared_ptr<rpc::CoreWorkerClientInterface>(WorkerAddress)> ClientFactoryFn; typedef std::function<std::shared_ptr<WorkerLeaseInterface>(const rpc::Address &)> LeaseClientFactoryFn; // This class is thread-safe. class CoreWorkerDirectTaskSubmitter { public: CoreWorkerDirectTaskSubmitter( std::shared_ptr<WorkerLeaseInterface> lease_client, ClientFactoryFn client_factory, LeaseClientFactoryFn lease_client_factory, std::shared_ptr<CoreWorkerMemoryStoreProvider> store_provider) : local_lease_client_(lease_client), client_factory_(client_factory), lease_client_factory_(lease_client_factory), in_memory_store_(store_provider), resolver_(in_memory_store_) {} /// Schedule a task for direct submission to a worker. /// /// \param[in] task_spec The task to schedule. Status SubmitTask(TaskSpecification task_spec); private: /// Schedule more work onto an idle worker or return it back to the raylet if /// no more tasks are queued for submission. If an error was encountered /// processing the worker, we don't attempt to re-use the worker. void OnWorkerIdle(const WorkerAddress &addr, bool was_error); /// Get an existing lease client or connect a new one. If a raylet_address is /// provided, this connects to a remote raylet. Else, this connects to the /// local raylet. std::shared_ptr<WorkerLeaseInterface> GetOrConnectLeaseClient( const rpc::Address *raylet_address) EXCLUSIVE_LOCKS_REQUIRED(mu_); /// Request a new worker from the raylet if no such requests are currently in /// flight and there are tasks queued. If a raylet address is provided, then /// the worker should be requested from the raylet at that address. Else, the /// worker should be requested from the local raylet. void RequestNewWorkerIfNeeded(const TaskSpecification &resource_spec, const rpc::Address *raylet_address = nullptr) EXCLUSIVE_LOCKS_REQUIRED(mu_); /// Callback for when the raylet grants us a worker lease. The worker is returned /// to the raylet via the given lease client once the task queue is empty. /// TODO: Implement a lease term by which we need to return the worker. void HandleWorkerLeaseGranted(const WorkerAddress &addr, std::shared_ptr<WorkerLeaseInterface> lease_client); /// Push a task to a specific worker. void PushNormalTask(const WorkerAddress &addr, rpc::CoreWorkerClientInterface &client, TaskSpecification &task_spec); // Client that can be used to lease and return workers from the local raylet. std::shared_ptr<WorkerLeaseInterface> local_lease_client_; /// Cache of gRPC clients to remote raylets. absl::flat_hash_map<ClientID, std::shared_ptr<WorkerLeaseInterface>> remote_lease_clients_ GUARDED_BY(mu_); /// Factory for producing new core worker clients. ClientFactoryFn client_factory_; /// Factory for producing new clients to request leases from remote nodes. LeaseClientFactoryFn lease_client_factory_; /// The store provider. std::shared_ptr<CoreWorkerMemoryStoreProvider> in_memory_store_; /// Resolve local and remote dependencies; LocalDependencyResolver resolver_; // Protects task submission state below. absl::Mutex mu_; /// Cache of gRPC clients to other workers. absl::flat_hash_map<WorkerAddress, std::shared_ptr<rpc::CoreWorkerClientInterface>> client_cache_ GUARDED_BY(mu_); /// Map from worker address to the lease client through which it should be /// returned. absl::flat_hash_map<WorkerAddress, std::shared_ptr<WorkerLeaseInterface>> worker_to_lease_client_ GUARDED_BY(mu_); // Whether we have a request to the Raylet to acquire a new worker in flight. bool worker_request_pending_ GUARDED_BY(mu_) = false; // Tasks that are queued for execution in this submitter.. std::deque<TaskSpecification> queued_tasks_ GUARDED_BY(mu_); }; }; // namespace ray #endif // RAY_CORE_WORKER_DIRECT_TASK_H
[ "noreply@github.com" ]
sureshannapureddy.noreply@github.com
80f7ebb0e26106c02c73c03fcde9ee21f7e39680
1c458bc11ff832d7b201e1f7ee0ef1daba9f8565
/Lab02/Application.h
4a2bf1926f7bc4b4d034dcfab636e718a1b9d065
[]
no_license
yeonsssu26/data-structure
f80dc688fa7c3d463d36e104644cc6c0ab7600e3
b9aba3ca320f8503efee81c0ed993068d6daaa43
refs/heads/master
2023-02-27T10:34:02.025124
2021-02-06T00:29:19
2021-02-06T00:29:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,450
h
#ifndef _APPLICATION_H #define _APPLICATION_H #include <iostream> #include <fstream> #include <string> using namespace std; #include "SortedList.h" #define FILENAMESIZE 1024 /** * application class for item management simply. */ class Application { public: /** * default constructor. */ Application() { m_Command = 0; } /** * destructor. */ ~Application() {} /** * @brief Program driver. * @pre program is started. * @post program is finished. */ void Run(); /** * @brief Display command on screen and get a input from keyboard. * @pre none. * @post none. * @return user's command. */ int GetCommand(); /** * @brief Add new record into list. * @pre list should be initialized. * @post new record is added into the list. * @return none */ void AddContents(); /** * @brief delete the given record into list. * @pre list should be initialized. * @post the given record is deleted out the list. * @return none */ void DeleteContents(); /** * @brief replace the given record in the list. * @pre list should be initialized. * @post the given record is replaced out the list. * @return none */ void ReplaceItem(); /** * @brief search the given record sequencially in the list. * @pre list should be initialized. * @post the given record is sequencially searched in the list. * @return none */ void SearchById_SequenceSearch(); /** * @brief binary search the given record in the list. * @pre list should be initialized. * @post the given record is binary searched in the list. * @return none */ void SearchByID_BinarySearch(); /** * @brief search the given record by name in the list. * @pre list should be initialized. * @post the given name of the record is searched in the list. * @return none */ void SearchByName(); /** * @brief search the given record by name in the list. * @pre list should be initialized. * @post the given name of the record is searched in the list. * @return none */ void SearchAllItmeByName(ItemType& inData); /** * @brief Display all records in the list on screen. * @pre none. * @post none. */ void DisplayAllContents(); /** * @brief Open a file by file descriptor as an input file. * @pre a file for reading is exist. * @post open the file for reading. * @param fileName a filename to open for reading. * @return return 1 if this function works well, otherwise 0. */ int OpenInFile(char* fileName); /** * @brief Open a file by file descriptor as an output file. * @pre list should be initialized. * @post open the file for writing. * @param fileName a filename to open for writing. * @return return 1 if this function works well, otherwise 0. */ int OpenOutFile(char* fileName); /** * @brief Open a file as a read mode, read all data on the file, and set list by the data. * @pre The file is not opened. * @post list holds all records from the file. * @return return 1 if this function works well, otherwise 0. */ int ReadDataFromFile(); /** * @brief Open a file as a write mode, and write all data into the file, * @pre The file is not opened. * @post the list is stored in the output file. * @return return 1 if this function works well, otherwise 0. */ int WriteDataToFile(); private: ifstream m_InFile; ///< input file descriptor. ofstream m_OutFile; ///< output file descriptor. SortedList m_List; ///< item list. int m_Command; ///< current command number. }; #endif _APPLICATION_H
[ "monica0326@khu.ac.kr" ]
monica0326@khu.ac.kr
958dd462582a80254990bfe21c3203e075121ed1
49f88ff91aa582e1a9d5ae5a7014f5c07eab7503
/gen/services/ui/public/interfaces/video_detector.mojom-shared.cc
622701d5afc4cc334cf9db873c0eb7558dad05cb
[]
no_license
AoEiuV020/kiwibrowser-arm64
b6c719b5f35d65906ae08503ec32f6775c9bb048
ae7383776e0978b945e85e54242b4e3f7b930284
refs/heads/main
2023-06-01T21:09:33.928929
2021-06-22T15:56:53
2021-06-22T15:56:53
379,186,747
0
1
null
null
null
null
UTF-8
C++
false
false
2,646
cc
// Copyright 2016 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. #if defined(_MSC_VER) #pragma warning(push) #pragma warning(disable:4065) #endif #include "services/ui/public/interfaces/video_detector.mojom-shared.h" #include <utility> #include "base/logging.h" #include "mojo/public/cpp/bindings/lib/validate_params.h" #include "mojo/public/cpp/bindings/lib/validation_context.h" #include "mojo/public/cpp/bindings/lib/validation_errors.h" #include "mojo/public/cpp/bindings/lib/validation_util.h" namespace ui { namespace mojom { namespace internal { // static bool VideoDetector_AddObserver_Params_Data::Validate( const void* data, mojo::internal::ValidationContext* validation_context) { if (!data) return true; if (!ValidateStructHeaderAndClaimMemory(data, validation_context)) return false; // NOTE: The memory backing |object| may be smaller than |sizeof(*object)| if // the message comes from an older version. const VideoDetector_AddObserver_Params_Data* object = static_cast<const VideoDetector_AddObserver_Params_Data*>(data); static constexpr struct { uint32_t version; uint32_t num_bytes; } kVersionSizes[] = {{ 0, 16 }}; if (object->header_.version <= kVersionSizes[arraysize(kVersionSizes) - 1].version) { // Scan in reverse order to optimize for more recent versions. for (int i = arraysize(kVersionSizes) - 1; i >= 0; --i) { if (object->header_.version >= kVersionSizes[i].version) { if (object->header_.num_bytes == kVersionSizes[i].num_bytes) break; ReportValidationError( validation_context, mojo::internal::VALIDATION_ERROR_UNEXPECTED_STRUCT_HEADER); return false; } } } else if (object->header_.num_bytes < kVersionSizes[arraysize(kVersionSizes) - 1].num_bytes) { ReportValidationError( validation_context, mojo::internal::VALIDATION_ERROR_UNEXPECTED_STRUCT_HEADER); return false; } if (!mojo::internal::ValidateHandleOrInterfaceNonNullable( object->observer, 1, validation_context)) { return false; } if (!mojo::internal::ValidateHandleOrInterface(object->observer, validation_context)) { return false; } return true; } VideoDetector_AddObserver_Params_Data::VideoDetector_AddObserver_Params_Data() : header_({sizeof(*this), 0}) {} } // namespace internal } // namespace mojom } // namespace ui #if defined(_MSC_VER) #pragma warning(pop) #endif
[ "aoeiuv020@gmail.com" ]
aoeiuv020@gmail.com
1ce0781e6b61cfdf660a697a82c37493122ba901
ecc67ae0af568ed368594e571e4e5ad6693a4f73
/337a.cpp
71244e01e6825df28eafeca41b3e6c632694cd27
[]
no_license
suman9868/competitve-coding-
85f2b884407cb56831276dedec3b863cea67f6a9
e8bef6b4dc2c69111b649b4deb13bac627ee95e7
refs/heads/master
2021-01-19T05:24:30.388120
2021-01-18T18:06:24
2021-01-18T18:06:24
61,265,612
0
0
null
null
null
null
UTF-8
C++
false
false
447
cpp
#include<iostream> #include<algorithm> using namespace std; int main() { int n,m,i; cin>>n>>m; int f[1001]; for(i=0; i<m; i++) cin>>f[i]; //f.sort(); sort(f,f+m); //for(i=0; i<m; i++) // cout<<f[i]<<endl; int diff=100000; for(i=n-1; i<m; i++) { if((f[i]-f[i-n+1])<diff) diff = f[i]-f[i-n+1]; //cout<<diff<<endl; } cout<<diff;//<<endl; return 0; }
[ "noreply@github.com" ]
suman9868.noreply@github.com
e2337d42ab14be9d15749594a70965a4c120d67f
9babb8a0430005223f3383f010dfe7cbe1ff4ae9
/external/eigen/doc/snippets/tut_arithmetic_transpose_inplace.cpp
5c81c9e02df83f78784c96cec5bb0fb436db99be
[ "MIT", "GPL-3.0-only", "Minpack", "BSD-3-Clause", "Apache-2.0", "LGPL-2.1-only", "MPL-2.0", "LGPL-2.0-or-later", "LGPL-2.1-or-later" ]
permissive
mlivesu/cinolib
964f857a2d19321a968521a20e79409c1f0103f2
a6249b9be0ce6a61536bf61f8206ee6f00e3f1ac
refs/heads/master
2023-08-14T03:28:18.385368
2023-07-21T21:21:09
2023-07-21T21:21:09
100,456,759
734
88
MIT
2023-05-05T14:13:11
2017-08-16T06:41:43
C++
UTF-8
C++
false
false
174
cpp
MatrixXf a(2,3); a << 1, 2, 3, 4, 5, 6; cout << "Here is the initial matrix a:\n" << a << endl; a.transposeInPlace(); cout << "and after being transposed:\n" << a << endl;
[ "marco.livesu@ge.imati.cnr.it" ]
marco.livesu@ge.imati.cnr.it
2ab2b9c83baf3b4d837648208487c28d9cf93810
c4d3c5cb2fd5ca4e442c9cccfe1953dcf9a30d5a
/11 Sorting and Searching/Source/splitstring.cpp
2575a641337f63891a5251c576f701d07cfbebad
[]
no_license
laughtrey/cis202
36f20ea20a265bfa4352141497346c3e73e06189
8355466119fafdc6032ffa3b7b55be1c8e41f3ee
refs/heads/master
2020-04-15T07:27:49.963819
2019-09-11T09:31:56
2019-09-11T09:31:56
164,494,834
1
1
null
null
null
null
UTF-8
C++
false
false
771
cpp
/** * Provided class starter code for splitting a string of information * with a selected delimiter. */ #include "splitstring.h" #include <vector> #include <string> using namespace std; // split: receives a char delimiter; returns a vector of strings // By default ignores repeated delimiters, unless argument rep == 1. vector<string>& splitstring::split(char delim, int rep) { if (!flds.empty()) flds.clear(); // empty vector if necessary string work = data(); string buf = ""; int i = 0; while (i < work.length()) { if (work[i] != delim) buf += work[i]; else if (rep == 1) { flds.push_back(buf); buf = ""; } else if (buf.length() > 0) { flds.push_back(buf); buf = ""; } i++; } if (!buf.empty()) flds.push_back(buf); return flds; }
[ "laughtrey@gmail.com" ]
laughtrey@gmail.com
ec33bac44989a5374a2d1dcd765a31c2d676405d
ba0211d260d1d65ab18fc17c29e984479189f2f5
/src/qt/askpassphrasedialog.cpp
d5a5c935eab7cea0556cb7c23de8b3fa12eb1acd
[ "MIT" ]
permissive
tripleseventvs/tripleseven
317fb6c5a0153e8c027940b0c7fb8ae39c89c808
3f880dfc4634ee25f034d9ee53cec595fa30fb5c
refs/heads/master
2020-04-09T20:40:23.762394
2018-12-07T16:31:17
2018-12-07T16:31:17
160,580,539
0
0
null
null
null
null
UTF-8
C++
false
false
10,003
cpp
#include "askpassphrasedialog.h" #include "ui_askpassphrasedialog.h" #include "guiconstants.h" #include "walletmodel.h" #include <QMessageBox> #include <QPushButton> #include <QKeyEvent> extern bool fWalletUnlockStakingOnly; AskPassphraseDialog::AskPassphraseDialog(Mode mode, QWidget *parent) : QDialog(parent), ui(new Ui::AskPassphraseDialog), mode(mode), model(0), fCapsLock(false) { ui->setupUi(this); ui->passEdit1->setMaxLength(MAX_PASSPHRASE_SIZE); ui->passEdit2->setMaxLength(MAX_PASSPHRASE_SIZE); ui->passEdit3->setMaxLength(MAX_PASSPHRASE_SIZE); // Setup Caps Lock detection. ui->passEdit1->installEventFilter(this); ui->passEdit2->installEventFilter(this); ui->passEdit3->installEventFilter(this); switch(mode) { case Encrypt: // Ask passphrase x2 ui->passLabel1->hide(); ui->passEdit1->hide(); ui->warningLabel->setText(tr("Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.")); setWindowTitle(tr("Encrypt wallet")); break; case UnlockStaking: ui->stakingCheckBox->setChecked(true); ui->stakingCheckBox->show(); // fallthru case Unlock: // Ask passphrase ui->warningLabel->setText(tr("This operation needs your wallet passphrase to unlock the wallet.")); ui->passLabel2->hide(); ui->passEdit2->hide(); ui->passLabel3->hide(); ui->passEdit3->hide(); setWindowTitle(tr("Unlock wallet")); break; case Decrypt: // Ask passphrase ui->warningLabel->setText(tr("This operation needs your wallet passphrase to decrypt the wallet.")); ui->passLabel2->hide(); ui->passEdit2->hide(); ui->passLabel3->hide(); ui->passEdit3->hide(); setWindowTitle(tr("Decrypt wallet")); break; case ChangePass: // Ask old passphrase + new passphrase x2 setWindowTitle(tr("Change passphrase")); ui->warningLabel->setText(tr("Enter the old and new passphrase to the wallet.")); break; } textChanged(); connect(ui->passEdit1, SIGNAL(textChanged(QString)), this, SLOT(textChanged())); connect(ui->passEdit2, SIGNAL(textChanged(QString)), this, SLOT(textChanged())); connect(ui->passEdit3, SIGNAL(textChanged(QString)), this, SLOT(textChanged())); } AskPassphraseDialog::~AskPassphraseDialog() { // Attempt to overwrite text so that they do not linger around in memory ui->passEdit1->setText(QString(" ").repeated(ui->passEdit1->text().size())); ui->passEdit2->setText(QString(" ").repeated(ui->passEdit2->text().size())); ui->passEdit3->setText(QString(" ").repeated(ui->passEdit3->text().size())); delete ui; } void AskPassphraseDialog::setModel(WalletModel *model) { this->model = model; } void AskPassphraseDialog::accept() { SecureString oldpass, newpass1, newpass2; if(!model) return; oldpass.reserve(MAX_PASSPHRASE_SIZE); newpass1.reserve(MAX_PASSPHRASE_SIZE); newpass2.reserve(MAX_PASSPHRASE_SIZE); // TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string) // Alternately, find a way to make this input mlock()'d to begin with. oldpass.assign(ui->passEdit1->text().toStdString().c_str()); newpass1.assign(ui->passEdit2->text().toStdString().c_str()); newpass2.assign(ui->passEdit3->text().toStdString().c_str()); switch(mode) { case Encrypt: { if(newpass1.empty() || newpass2.empty()) { // Cannot encrypt with empty passphrase break; } QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm wallet encryption"), tr("Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR COINS</b>!") + "<br><br>" + tr("Are you sure you wish to encrypt your wallet?"), QMessageBox::Yes|QMessageBox::Cancel, QMessageBox::Cancel); if(retval == QMessageBox::Yes) { if(newpass1 == newpass2) { if(model->setWalletEncrypted(true, newpass1)) { QMessageBox::warning(this, tr("Wallet encrypted"), "<qt>" + tr("Tripleseven will close now to finish the encryption process. " "Remember that encrypting your wallet cannot fully protect " "your coins from being stolen by malware infecting your computer.") + "<br><br><b>" + tr("IMPORTANT: Any previous backups you have made of your wallet file " "should be replaced with the newly generated, encrypted wallet file. " "For security reasons, previous backups of the unencrypted wallet file " "will become useless as soon as you start using the new, encrypted wallet.") + "</b></qt>"); QApplication::quit(); } else { QMessageBox::critical(this, tr("Wallet encryption failed"), tr("Wallet encryption failed due to an internal error. Your wallet was not encrypted.")); } QDialog::accept(); // Success } else { QMessageBox::critical(this, tr("Wallet encryption failed"), tr("The supplied passphrases do not match.")); } } else { QDialog::reject(); // Cancelled } } break; case UnlockStaking: case Unlock: if(!model->setWalletLocked(false, oldpass)) { QMessageBox::critical(this, tr("Wallet unlock failed"), tr("The passphrase entered for the wallet decryption was incorrect.")); } else { fWalletUnlockStakingOnly = ui->stakingCheckBox->isChecked(); QDialog::accept(); // Success } break; case Decrypt: if(!model->setWalletEncrypted(false, oldpass)) { QMessageBox::critical(this, tr("Wallet decryption failed"), tr("The passphrase entered for the wallet decryption was incorrect.")); } else { QDialog::accept(); // Success } break; case ChangePass: if(newpass1 == newpass2) { if(model->changePassphrase(oldpass, newpass1)) { QMessageBox::information(this, tr("Wallet encrypted"), tr("Wallet passphrase was successfully changed.")); QDialog::accept(); // Success } else { QMessageBox::critical(this, tr("Wallet encryption failed"), tr("The passphrase entered for the wallet decryption was incorrect.")); } } else { QMessageBox::critical(this, tr("Wallet encryption failed"), tr("The supplied passphrases do not match.")); } break; } } void AskPassphraseDialog::textChanged() { // Validate input, set Ok button to enabled when acceptable bool acceptable = false; switch(mode) { case Encrypt: // New passphrase x2 acceptable = !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty(); break; case UnlockStaking: case Unlock: // Old passphrase x1 case Decrypt: acceptable = !ui->passEdit1->text().isEmpty(); break; case ChangePass: // Old passphrase x1, new passphrase x2 acceptable = !ui->passEdit1->text().isEmpty() && !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty(); break; } ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(acceptable); } bool AskPassphraseDialog::event(QEvent *event) { // Detect Caps Lock key press. if (event->type() == QEvent::KeyPress) { QKeyEvent *ke = static_cast<QKeyEvent *>(event); if (ke->key() == Qt::Key_CapsLock) { fCapsLock = !fCapsLock; } if (fCapsLock) { ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!")); } else { ui->capsLabel->clear(); } } return QWidget::event(event); } bool AskPassphraseDialog::eventFilter(QObject *object, QEvent *event) { /* Detect Caps Lock. * There is no good OS-independent way to check a key state in Qt, but we * can detect Caps Lock by checking for the following condition: * Shift key is down and the result is a lower case character, or * Shift key is not down and the result is an upper case character. */ if (event->type() == QEvent::KeyPress) { QKeyEvent *ke = static_cast<QKeyEvent *>(event); QString str = ke->text(); if (str.length() != 0) { const QChar *psz = str.unicode(); bool fShift = (ke->modifiers() & Qt::ShiftModifier) != 0; if ((fShift && psz->isLower()) || (!fShift && psz->isUpper())) { fCapsLock = true; ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!")); } else if (psz->isLetter()) { fCapsLock = false; ui->capsLabel->clear(); } } } return QDialog::eventFilter(object, event); }
[ "you@example.com" ]
you@example.com
ddf6c60b97658f54daad31e52af7f7ee8c1738f0
2277375bd4a554d23da334dddd091a36138f5cae
/ThirdParty/Havok/Source/Physics2012/Dynamics/Classes/Reflections/hkpSimpleShapePhantomReflection.cpp
a74cf37a3354504ee84ee159425faf1926dc9600
[]
no_license
kevinmore/Project-Nebula
9a0553ccf8bdc1b4bb5e2588fc94516d9e3532bc
f6d284d4879ae1ea1bd30c5775ef8733cfafa71d
refs/heads/master
2022-10-22T03:55:42.596618
2020-06-19T09:07:07
2020-06-19T09:07:07
25,372,691
6
5
null
null
null
null
UTF-8
C++
false
false
6,212
cpp
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Product and Trade Secret source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2013 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ //HK_REFLECTION_PARSER_EXCLUDE_FILE // Autogenerated by generateReflections.py (reflectedClasses.py) // Changes will not be lost unless: // - The workspace is re-generated using build.py // - The corresponding reflection database (reflection.db) is deleted // - The --force-output or --force-rebuild option is added to the pre-build generateReflection.py execution // Generated from 'Physics2012/Dynamics/Phantom/hkpSimpleShapePhantom.h' #include <Physics2012/Dynamics/hkpDynamics.h> #include <Common/Base/Reflection/hkClass.h> #include <Common/Base/Reflection/hkInternalClassMember.h> #include <Common/Base/Reflection/hkTypeInfo.h> #include <Common/Base/Reflection/Attributes/hkAttributes.h> #include <Physics2012/Dynamics/Phantom/hkpSimpleShapePhantom.h> #define True true #define False false // External pointer and enum types extern const hkClass hkpCollidableClass; extern const hkClass hkpSimpleShapePhantomCollisionDetailClass; // // Class hkpSimpleShapePhantom::CollisionDetail // static const hkInternalClassMember hkpSimpleShapePhantom_CollisionDetailClass_Members[] = { { "collidable", &hkpCollidableClass, HK_NULL, hkClassMember::TYPE_POINTER, hkClassMember::TYPE_STRUCT, 0, 0, HK_OFFSET_OF(hkpSimpleShapePhantom::CollisionDetail,m_collidable), HK_NULL } }; const hkClass hkpSimpleShapePhantomCollisionDetailClass( "hkpSimpleShapePhantomCollisionDetail", HK_NULL, // parent sizeof(hkpSimpleShapePhantom::CollisionDetail), HK_NULL, 0, // interfaces HK_NULL, 0, // enums reinterpret_cast<const hkClassMember*>(hkpSimpleShapePhantom_CollisionDetailClass_Members), HK_COUNT_OF(hkpSimpleShapePhantom_CollisionDetailClass_Members), HK_NULL, // defaults HK_NULL, // attributes hkClass::FLAGS_NOT_SERIALIZABLE, hkUint32(0) // version ); #ifndef HK_HKCLASS_DEFINITION_ONLY const hkClass& HK_CALL hkpSimpleShapePhantom::CollisionDetail::staticClass() { return hkpSimpleShapePhantomCollisionDetailClass; } HK_COMPILE_TIME_ASSERT2( \ sizeof(hkIsVirtual(static_cast<hkpSimpleShapePhantom::CollisionDetail*>(0))) == sizeof(hkBool::CompileTimeFalseType), \ REFLECTION_PARSER_VTABLE_DETECTION_FAILED ); static void HK_CALL cleanupLoadedObjecthkpSimpleShapePhantomCollisionDetail(void* p) { static_cast<hkpSimpleShapePhantom::CollisionDetail*>(p)->~CollisionDetail(); } extern const hkTypeInfo hkpSimpleShapePhantomCollisionDetailTypeInfo; const hkTypeInfo hkpSimpleShapePhantomCollisionDetailTypeInfo( "hkpSimpleShapePhantomCollisionDetail", "!hkpSimpleShapePhantom::CollisionDetail", HK_NULL, cleanupLoadedObjecthkpSimpleShapePhantomCollisionDetail, HK_NULL, sizeof(hkpSimpleShapePhantom::CollisionDetail) ); #endif // // Class hkpSimpleShapePhantom // extern const hkClass hkpShapePhantomClass; const hkInternalClassMember hkpSimpleShapePhantom::Members[] = { { "collisionDetails", &hkpSimpleShapePhantomCollisionDetailClass, HK_NULL, hkClassMember::TYPE_ARRAY, hkClassMember::TYPE_STRUCT, 0, 0|hkClassMember::SERIALIZE_IGNORED, HK_OFFSET_OF(hkpSimpleShapePhantom,m_collisionDetails), HK_NULL }, { "orderDirty", HK_NULL, HK_NULL, hkClassMember::TYPE_BOOL, hkClassMember::TYPE_VOID, 0, 0|hkClassMember::SERIALIZE_IGNORED, HK_OFFSET_OF(hkpSimpleShapePhantom,m_orderDirty), HK_NULL } }; extern const hkClass hkpSimpleShapePhantomClass; const hkClass hkpSimpleShapePhantomClass( "hkpSimpleShapePhantom", &hkpShapePhantomClass, // parent sizeof(::hkpSimpleShapePhantom), HK_NULL, 0, // interfaces HK_NULL, 0, // enums reinterpret_cast<const hkClassMember*>(hkpSimpleShapePhantom::Members), HK_COUNT_OF(hkpSimpleShapePhantom::Members), HK_NULL, // defaults HK_NULL, // attributes 0, // flags hkUint32(0) // version ); #ifndef HK_HKCLASS_DEFINITION_ONLY const hkClass& HK_CALL hkpSimpleShapePhantom::staticClass() { return hkpSimpleShapePhantomClass; } HK_COMPILE_TIME_ASSERT2( \ sizeof(hkIsVirtual(static_cast<hkpSimpleShapePhantom*>(0))) == sizeof(hkBool::CompileTimeTrueType), \ REFLECTION_PARSER_VTABLE_DETECTION_FAILED ); static void HK_CALL finishLoadedObjecthkpSimpleShapePhantom(void* p, int finishing = 1) { hkFinishLoadedObjectFlag f; f.m_finishing = finishing; new (p) hkpSimpleShapePhantom(f); } static void HK_CALL cleanupLoadedObjecthkpSimpleShapePhantom(void* p) { static_cast<hkpSimpleShapePhantom*>(p)->~hkpSimpleShapePhantom(); } static const void* HK_CALL getVtablehkpSimpleShapePhantom() { #if HK_LINKONCE_VTABLES==0 #if HK_HASHCODE_VTABLE_REGISTRY==1 return ((const void*)(typeid(hkpSimpleShapePhantom).hash_code())); #else return ((const void*)(typeid(hkpSimpleShapePhantom).name())); #endif #else union { HK_ALIGN16(void* ptr); char buf[sizeof(hkpSimpleShapePhantom)]; } u; hkFinishLoadedObjectFlag f; new (u.buf) hkpSimpleShapePhantom(f); return u.ptr; #endif } extern const hkTypeInfo hkpSimpleShapePhantomTypeInfo; const hkTypeInfo hkpSimpleShapePhantomTypeInfo( "hkpSimpleShapePhantom", "!hkpSimpleShapePhantom", finishLoadedObjecthkpSimpleShapePhantom, cleanupLoadedObjecthkpSimpleShapePhantom, getVtablehkpSimpleShapePhantom(), sizeof(hkpSimpleShapePhantom) ); #endif /* * Havok SDK - Base file, BUILD(#20130912) * * Confidential Information of Havok. (C) Copyright 1999-2013 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available from salesteam@havok.com. * */
[ "dingfengyu@gmail.com" ]
dingfengyu@gmail.com